General and Desktop
2018.09.30 20:37

표를 만들고 PDF문서로 출력하기

조회 수 6967 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
Qt Quick 1을 사용했다면 QML 기반 슬라이드에서 PDF를 작성하는 작업이 쉬웠다. QtQuick1은 QPainter를 통한 래스터 기반의 페인팅을 사용한다. QPainter를 사용하면 QPrinter로 렌더링을 리디렉션하는 것이 간단하다. QPrinter는 출력 파일 형식으로 PDF 파일을 사용할 수 있다.
 
QtQuick 2는 렌더링을 위해 OpenGL Scene Graph를 사용하므로 QPainter를 이용하여 현재 장면을 PDF로 직접 렌더링이 불가능하다.
 
단순한 표에 어떤 값들을 나열하여 출력하는 것이라면 아래와 같은 방법이 대안이 될수 있다. 어떤 데이터들을 html 코드로 표를 작성하고 PDF문서를 만드는 예제이다.
 
예제에서 필요한 모듈
*.pro
QT += sql gui printsupport
 
main.cpp
#include <QGuiApplication>
#include <QtSql>
#include <QPrinter>
#include <QTextDocument>

bool createConnection() {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(":memory:");
    if (!db.open()) {
        qDebug() << "Cannot open database";
        return false;
    }
    QSqlQuery query;
    qDebug() << "table:" << query.exec("create table person (id int primary key, "
                                         "firstname varchar(20), lastname varchar(20), num int )");
    query.exec("insert into person values(101, 'Dennis', 'Young','1')");
    query.exec("insert into person values(102, 'Christine', 'Holand','2')");
    query.exec("insert into person values(103, 'Lars junior', 'Gordon','4')");
    query.exec("insert into person values(104, 'Roberto', 'Robitaille','5')");
    query.exec("insert into person values(105, 'Maria', 'Papadopoulos','3')");
    return true;
}

void printTable(QPrinter* printer, QSqlQuery& Query) {
    QString strStream;
    QTextStream out(&strStream);

    const int columnCount = Query.record().count();

    out <<  "<html>\n"
            "<head>\n"
            "<meta Content=\"Text/html; charset=Windows-1251\">\n"
         <<  QString("<title>%1</title>\n").arg("TITLE OF TABLE")
          <<  "</head>\n"
              "<body bgcolor=#ffffff link=#5000A0>\n"
              "<table border=1 cellspacing=0 cellpadding=2>\n";

    // headers
    out << "<thead><tr bgcolor=#f0f0f0>";
    for (int column = 0; column < columnCount; column++)
        out << QString("<th>%1</th>").arg(Query.record().fieldName(column));
    out << "</tr></thead>\n";

    while (Query.next()) {
        out << "<tr>";
        for (int column = 0; column < columnCount; column++) {
            QString data = Query.value(column).toString();
            out << QString("<td bkcolor=0>%1</td>").arg((!data.isEmpty()) ? data : QString(" "));
        }
        out << "</tr>\n";
    }

    out <<  "</table>\n"
            "</body>\n"
            "</html>\n";

    QTextDocument document;
    document.setHtml(strStream);
    document.print(printer);
}

void print(const QString &name) {
    QPrinter printer(QPrinter::HighResolution);
    printer.setOrientation(QPrinter::Portrait);
    printer.setPageSize(QPrinter::A4);
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setOutputFileName(name);

    // DB Query
    QSqlQuery query;
    query.exec("SELECT * from person");

    // write
    printTable(&printer, query);
}

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    // Create DB table.
    createConnection();

    // Create PDF document file.
    print("file.pdf");

    return 1;
}

 

PDF문서는 A4사이즈로 아래 그림과 같이 프린트된다.

output.png


  1. No Image notice

    Qt프로그래밍(QtQuick) Beginner를 위한 글 읽는 순서

    Date2019.01.05 CategoryQML and Qt Quick By운영자 Views161134
    read more
  2. QtWayland와 ivi-compositor

    Date2018.12.27 CategoryMobile and Embedded Bymakersweb Views9520
    Read More
  3. Qml과 C++로 구현하는 GUI어플리케이션

    Date2018.12.25 CategoryQML and Qt Quick Bymakersweb Views20829
    Read More
  4. No Image

    싱글터치 스크린 및 임베디드 리눅스 기반에서 Qt 터치입력

    Date2018.12.24 CategoryMobile and Embedded Bymakersweb Views8692
    Read More
  5. ShaderEffect QML Type 을 이용한 그래픽효과

    Date2018.12.09 CategoryQML and Qt Quick Bymakersweb Views9243
    Read More
  6. No Image

    Qml에서 커튼효과 구현 예제 - Shader Effects

    Date2018.12.05 CategoryQML and Qt Quick By운영자 Views7003
    Read More
  7. 안드로이드 Qt 프로그래밍

    Date2018.11.30 CategoryMobile and Embedded Bymakersweb Views16406
    Read More
  8. 리눅스에서 Qt4.8기반 어플리케이션의 한글입력

    Date2018.11.29 CategoryInstallation and Deployment Bymakersweb Views10453
    Read More
  9. QML에서 동적으로 텍스트 다국어 처리

    Date2018.11.04 CategoryQML and Qt Quick Bymakersweb Views10138
    Read More
  10. Qt Installer Framework - 패키징, 설치프로그램 제작

    Date2018.10.14 CategoryInstallation and Deployment Bymakersweb Views22310
    Read More
  11. Qt 응용프로그램 배포(windows)

    Date2018.10.10 CategoryGeneral and Desktop Bymakersweb Views17589
    Read More
  12. No Image

    소스코드에서 환경변수 가져오기와 설정하기

    Date2018.10.08 CategoryGeneral and Desktop Bymakersweb Views8404
    Read More
  13. 표를 만들고 PDF문서로 출력하기

    Date2018.09.30 CategoryGeneral and Desktop Bymakersweb Views6967
    Read More
  14. Qml에서 키보드 입력 이벤트 핸들링

    Date2018.08.09 CategoryQML and Qt Quick Bymakersweb Views10892
    Read More
  15. Qml 어플리케이션 정적 빌드

    Date2018.07.27 CategoryInstallation and Deployment Bymakersweb Views8351
    Read More
  16. No Image

    Qt Bluetooth 관련 기능 확인 사항

    Date2018.07.10 CategoryInstallation and Deployment Bymakersweb Views7184
    Read More
  17. No Image

    Qml 및 C++개발시 유용한 팁

    Date2018.04.06 CategoryQML and Qt Quick Bymakersweb Views13945
    Read More
  18. No Image

    Qt Version확인 방법

    Date2018.03.29 CategoryGeneral and Desktop Bymakersweb Views10291
    Read More
  19. 초보자를 위한 첫번째 프로젝트 - QML로 만드는 Hello World

    Date2018.03.16 CategoryGeneral and Desktop Bymakersweb Views26528
    Read More
  20. Windows에서 라즈베리파이3 Qt 어플리케이션 개발 및 원격 실행

    Date2018.02.23 CategoryInstallation and Deployment Bymakersweb Views12199
    Read More
  21. Windows에서 라즈베리파이3용 Qt5.10.0 크로스컴파일

    Date2018.02.23 CategoryMobile and Embedded Bymakersweb Views19626
    Read More
Board Pagination Prev 1 ... 5 6 7 8 9 Next
/ 9