한국어
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 85969
50 콘솔에서 사용자 입력받기 file makersweb 2020.03.22 51849
49 QString 문자열 다루기 예제 운영자 2019.01.26 40168
48 Qt의 시그널 슬롯 시스템 file makersweb 2015.10.20 23601
47 초보자를 위한 첫번째 프로젝트 - QML로 만드는 Hello World file makersweb 2018.03.16 14478
46 Qt 프로그래밍의 시작 makersweb 2015.10.25 14383
45 Qt의 오픈소스 라이센스 소개 file makersweb 2019.12.15 12580
44 QtSerialPort를 사용한 시리얼(Serial)통신 [3] makersweb 2019.05.21 11916
43 Qt 응용프로그램 배포(windows) file makersweb 2018.10.10 11347
42 Qt의 스레드간 시그널 슬롯의 커넥션타입 [1] makersweb 2015.10.24 10187
41 Qt SQL을 이용한 가벼운 데이터베이스 다루기 [1] file 운영자 2019.01.23 6969
40 Qt 어플리에이션 전역에 폰트 설정 makersweb 2018.01.24 5592
39 Qt기반의 오픈소스 프로젝트들 makersweb 2019.05.15 5433
38 멀티 스레드환경, 스레드에 안전한 이벤트처리 makersweb 2016.10.27 5008
37 Qt 멀티 스레드 프로그래밍 시 유의해야 할 몇 가지 makersweb 2020.01.13 4875
36 QNetworkAccessManager를 통해 HTTP POST 하는 예제 makersweb 2019.01.17 4777
35 Qt응용프로그램 실행 시 콘솔창(터미널)같이 띄우기 file makersweb 2019.01.16 4492
34 Windows에서 Qt D-Bus를 사용하여 프로세스간 통신(IPC) file makersweb 2019.05.02 4484
33 Qt기반의 오픈소스 프로젝트들 - 2 운영자 2019.07.21 4006
32 Qt 를 사용하거나 기반으로 하는 응용프로그램 file makersweb 2021.01.30 3813
31 Qt Logging Rule, Qt 프레임워크 로그 출력 makersweb 2017.01.13 3701