Reputation: 907
the QT application I'm working on comes with a tutorial. Each chapter is a stand-alone HTML file, each file can span multiple pages. Now I want to print them into one single PDF file (with page numbers).
My naive approach was this, but it's wrong:
#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...
}
However, this will restart the printer on each print()
call, starting with a new PDF file, overwriting the old one.
What is a simple solution to print all HTML into one PDF file, using QT?
Upvotes: 4
Views: 1306
Reputation: 1498
Developping on your "naive approach", I could print concatenated html files by appending several pages to a parent QTextEdit
. It would probably also work utilizing a second QTextBrowser
instead.
// ...
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);
// ...
Upvotes: 1
Reputation: 43662
You can achieve this by rendering your contents on a QPainter object linked to the QPrinter device
// 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();
Upvotes: 1