C++ 如何将QTextBrowser的多个实例打印到一个PDF文件中?

C++ 如何将QTextBrowser的多个实例打印到一个PDF文件中?,c++,qt,pdf,qtextbrowser,C++,Qt,Pdf,Qtextbrowser,我正在开发的QT应用程序附带了一个教程。每个章节都是一个独立的HTML文件,每个文件可以跨越多个页面。现在我想把它们打印成一个单独的PDF文件(带有页码) 我天真的做法是这样的,但这是错误的: #include <QApplication> #include <QPrinter> #include <QTextBrowser> #include <QUrl> int main(int argc, char *argv[]) { QApplic

我正在开发的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...
}
#包括
#包括
#包括
#包括
int main(int argc,char*argv[])
{
QApplication应用程序(argc、argv);
打印机;
打印机.setOutputFormat(QPrinter::PdfFormat);
打印机.setOutputFileName(“/tmp/test.pdf”);
QTextBrowser*tp=新的QTextBrowser();
tp->setSource(QUrl(“qrc:///help/tutorial_item_1.html"));
tp->打印和打印机;
tp->setSource(QUrl(“qrc:///help/tutorial_item_2.html"));
tp->打印和打印机;
tp->setSource(QUrl(“qrc:///help/tutorial_item_3.html"));
tp->打印和打印机;
//等等。。。
}
但是,这将在每次调用
print()
时重新启动打印机,从一个新的PDF文件开始,覆盖旧的PDF文件


使用QT将所有HTML打印成一个PDF文件的简单解决方案是什么?

您可以通过在链接到设备的对象上呈现内容来实现这一点

//前面的示例代码~>
打印机;
打印机.setOutputFormat(QPrinter::PdfFormat);
打印机.setOutputFileName(“C:\\test.pdf”);
打印机。设置整页(真);
打印机。设置页面大小(QPrinter::A4);
qtextb;
油漆工;
画师。开始(打印和打印);
QRect rect=printer.pageRect();
tb.resize(rect.width(),rect.height());
{
QFile文件(“C:\\test1.html”);
if(file.open(QIODevice::ReadOnly)){
QTextStream ts(文件(&F);
tb.setHtml(ts.readAll());
file.close();
tb.渲染和绘制,QPoint(0,0));
}
}
if(printer.newPage()==false)
qDebug()基于您的“天真方法”,我可以通过在父级
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);

  // ...

您可以将两个文本浏览器的内容联合起来,一步打印出来。每次打印后,请尝试使用
printer.newPage()
,谢谢您的建议。但是,在我的例子中,它没有帮助,
tb.render()
不处理多页HTML内容。
  // ...
  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);

  // ...