[英]How to print multiple instances of QTextBrowser into one PDF file?
我正在研究的QT應用程序附帶了一個教程。 每章都是一個獨立的HTML文件,每個文件可以跨多個頁面。 現在我想將它們打印成一個PDF文件(帶頁碼)。
我天真的做法就是這樣,但這是錯誤的:
#include <QApplication>
#include <QPrinter>
#include <QTextBrowser>
#include <QUrl>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QPrinter printer;
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName("/tmp/test.pdf");
QTextBrowser *tp = new QTextBrowser();
tp->setSource(QUrl("qrc:///help/tutorial_item_1.html"));
tp->print(&printer);
tp->setSource(QUrl("qrc:///help/tutorial_item_2.html"));
tp->print(&printer);
tp->setSource(QUrl("qrc:///help/tutorial_item_3.html"));
tp->print(&printer);
// etc...
}
但是,這將在每次print()
調用時重新啟動打印機,從新的PDF文件開始,覆蓋舊的PDF文件。
使用QT將所有HTML打印成一個PDF文件的簡單解決方案是什么?
您可以通過在鏈接到QPrinter設備的QPainter對象上呈現內容來實現此目的
// Sample code ahead ~>
QPrinter printer;
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName("C:\\test.pdf");
printer.setFullPage(true);
printer.setPageSize(QPrinter::A4);
QTextBrowser tb;
QPainter painter;
painter.begin(&printer);
QRect rect = printer.pageRect();
tb.resize(rect.width(), rect.height());
{
QFile file("C:\\test1.html");
if(file.open(QIODevice::ReadOnly)) {
QTextStream ts(&file);
tb.setHtml(ts.readAll());
file.close();
tb.render(&painter, QPoint(0,0));
}
}
if(printer.newPage() == false)
qDebug() << "ERROR";
{
QFile file("C:\\test2.html");
if(file.open(QIODevice::ReadOnly)) {
QTextStream ts(&file);
tb.setHtml(ts.readAll());
file.close();
tb.render(&painter, QPoint(0,0));
}
}
painter.end();
開發你的“天真的方法”,我可以通過將幾個頁面附加到父QTextEdit
來打印連接的html文件。 它可能也可以使用第二個QTextBrowser
。
// ...
QTextBrowser *tp = new QTextBrowser();
QTextEdit te;
tp->setSource(QUrl("qrc:///help/tutorial_item_1.html"));
te.append(tp->toHtml());
tp->setSource(QUrl("qrc:///help/tutorial_item_2.html"));
te.append(tp->toHtml());
te.print(&printer);
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.