英文:
the size of PDF file generate with QWebEnginePage::printToPdf is too large
问题
我正在使用QWebEnginePage::printToPdf将HTML转换为PDF,但生成的文件太大。
HTML文件只有100KB,没有图像,但PDF文件有15,000KB。
以下是代码:
QWebEnginePage *WebEnginePage = new QWebEnginePage(this);
WebEnginePage->load(QUrl("file:///test.html"));
connect(WebEnginePage, &QWebEnginePage::loadFinished, [=]()
{
WebEnginePage->printToPdf("test.pdf");
});
Qt版本为5.15.2。
如何减小PDF文件大小?
英文:
I'm using the QWebEnginePage::printToPdf to convert HTML to PDF,but the file generated is too large.
The html file is only 100KB and no image in it, but the PDF file is 15,000KB.
Here is the code:
QWebEnginePage *WebEnginePage = new QWebEnginePage(this);
WebEnginePage->load(QUrl("file:///test.html"));
connect(WebEnginePage, &QWebEnginePage::loadFinished, [=]()
{
WebEnginePage->printToPdf("test.pdf");
});
The Qt version is 5.15.2.
How do I reduce the PDF file size?
答案1
得分: 0
printToPdf
不允许您控制打印,但有一个单独的 print
方法,允许您使用自己的打印机。
QPrinter
有 setFontEmbeddingEnabled
和 setOutputFormat
方法,允许您控制输出。
类似这样的代码可能会改善您的文件大小(未经测试):
QPrinter printer(QPrinter::ScreenResolution);
printer.setOutputFilename("test.pdf");
printer.setFontEmbeddingEnabled(true);
printer.setOutputFormat(QPrinter::PdfFormat);
WebEnginePage->print(&printer, resultCallback);
注意:
- 由于某些原因,Qt 6 中删除了
QWebEnginePage::print
,所以如果您打算在将来升级,这可能不是最佳解决方案。 - 您可能需要尝试不同的输出格式,例如在 macOS 上,
QPrinter::PdfFormat
会产生光栅化的 PDF(可能与您现在得到的结果相同),但在 Windows 上,QPrinter::PdfFormat
是更好的选项。 QWebEnginePage::print
文档中还有一条说明,当发送到打印机时它会进行光栅化处理,因此最终可能会得到与您现在相同的结果。
英文:
printToPdf
doesn't allow you to control the printing however there is a separate print
method which allows you to use your own printer.
QPrinter
has setFontEmbeddingEnabled
and setOutputFormat
which allow you to control the output.
Something like this might improve your file sizes (untested):
QPrinter printer(QPrinter::ScreenResolution);
printer.setOutputFilename("test.pdf");
printer.setFontEmbeddingEnabled(true);
printer.setOutputFormat(QPrinter::PdfFormat);
WebEnginePage->print(&printer, resultCallback);
Notes:
QWebEnginePage::print
has been removed for some reason in Qt 6 so if you plan to upgrade in the future this might not be the best solution- You might need to experiment with the output format, for example for me, on macos
QPrinter::PdfFormat
results in a rasterised PDF (probably the same as you're getting now) butQPrinter::NativeFormat
produces a textual one. But on WindowsQPrinter::PdfFormat
is the better option. - There is also a note in the
QWebEnginePage::print
documentation that it rasterises when sending to the printer so it may end up with the same result as you have now anyway
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论