한국어
Qt
 
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

번호 제목 글쓴이 날짜 조회 수
공지 Qt프로그래밍(QtQuick) Beginner를 위한 글 읽는 순서 운영자 2019.01.05 118557
» 표를 만들고 PDF문서로 출력하기 file makersweb 2018.09.30 4893
39 QML 전역 객체 (Global Object) file makersweb 2019.04.10 4890
38 Qt 스마트 포인터 (QSharedPointer, QScopedPointer, QPointer) makersweb 2022.08.18 4883
37 Qt 6의 C++ 프로퍼티 바인딩 예제 makersweb 2021.11.01 4863
36 Qt Bluetooth 관련 기능 확인 사항 makersweb 2018.07.10 4815
35 Qt로 작성된 안드로이드 APP에 Splash Screen을 추가 file makersweb 2020.03.10 4797
34 ShaderEffect QML Type을 이용한 버튼 클릭 효과 file makersweb 2020.05.22 4776
33 tslib의 ts_calibrate를 응용해서 Qt로 터치보정기능 구현 file makersweb 2019.04.06 4768
32 안드로이드 가상장치 사용 file makersweb 2019.01.13 4768
31 하드디스크 드라이브 여유 공간 계산 file makersweb 2023.01.15 4730
30 Qt 5 코드를 Qt 6로 포팅하기 위해 도움이 되는 Clazy Framework file makersweb 2021.03.01 4652
29 QML과 코루틴(Coroutines) makersweb 2020.11.03 4614
28 Qt 6에서 QList 변경사항 makersweb 2020.10.08 4612
27 QRhi 에 대해서 file makersweb 2023.12.29 4598
26 ApplicationWindow 와 메뉴바(MenuBar)구성 file makersweb 2020.01.04 4521
25 단일 인스턴스 Qt 응용 프로그램(Single-instance Application) makersweb 2022.06.23 4501
24 Embedded Linux 에서 Qt 및 Graphics Stack file 운영자 2020.05.27 4482
23 Qt MQTT 에 대해서 file makersweb 2020.06.02 4473
22 QScopedPointer 소개 및 사용법 makersweb 2019.11.29 4433
21 QML 바인딩 끊김 진단 makersweb 2020.11.08 4404