Qtの基礎 - PDF
ナビゲーションに移動
検索に移動
概要
Qtにおいて、PDFを作成する手順を記載する。
PDFの作成
QPdfWriterライブラリ
Qtでは、簡単にPDFを作成する機能が用意されている。
#include <QPdfWriter>
// PDFを作成
QPdfWriter pdfWriter("ファイル名");
// レイアウトオブジェクト
QPageLayout pdfLayout;
// 単位をポイントに設定
pdfLayout.setUnits(QPageLayout::Point);
// 紙サイズ、余白を設定
pdfLayout.setPageSize(QPageSize(QPageSize::A4), QMarginsF(105.0, 40.0, 40.0, 20.0));
// 縦に設定
pdfLayout.setOrientation(QPageLayout::Portrait);
// レイアウトオブジェクトをPDFに設置
pdfWriter.setPageLayout(pdfLayout);
// DPIを取得する場合は以下のようにする
double dPixToPoints = (double)pdfWriter.resolution() / 72.0;
// QPainterクラスを使用してPDFを書き込む
QPainter painter;
if(painter.begin(&pdfWriter))
{
painter.drawText(QPoint(100, 100), "何か文字");
// 改ページ
pdfWriter.newPage();
}
painter.end();
Poppler-Qt5ライブラリ
Poppler-Qt5は、QPdfWriterライブラリと比較して、より高度なPDF操作や読み込みに適している。
#include <QCoreApplication>
#include <QPainter>
#include <poppler-qt5.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// PDFファイルを読み込む
Poppler::Document *document = Poppler::Document::load("input.pdf");
if (!document || document->isLocked()) {
delete document;
return -1;
}
// 最初のページを取得
Poppler::Page *page = document->page(0);
if (page == nullptr) {
delete document;
return -1;
}
// ページを画像として描画
QImage image = page->renderToImage(72.0, 72.0);
// 画像を保存
image.save("output.png");
delete page;
delete document;
return 0;
}