C++ 如何将QWebEngineView呈现到打印机?
我的目标:我希望能够使用Qt5.6.1将从qrc获取的HTML页面存储为PDF文件 限制:C++ 如何将QWebEngineView呈现到打印机?,c++,windows,qt,pdf,rendering,C++,Windows,Qt,Pdf,Rendering,我的目标:我希望能够使用Qt5.6.1将从qrc获取的HTML页面存储为PDF文件 限制: 我不能使用QWebEnginePage::print或QWebEnginePage::printToPdf方法,因为它们分别在5.8版和5.7版中添加 使用QTextDocument不是一个选项,因为我需要一个完整的HTML支持,而不仅仅是QTextDocument提供的有限子集 问题:下面的代码确实在屏幕上显示了页面,然后创建了doc.pdf,这意味着页面加载时没有错误,但当我打开创建的pdf文件时
- 我不能使用QWebEnginePage::print或QWebEnginePage::printToPdf方法,因为它们分别在5.8版和5.7版中添加
- 使用QTextDocument不是一个选项,因为我需要一个完整的HTML支持,而不仅仅是QTextDocument提供的有限子集
#include "MainWindow.h"
#include "ui_MainWindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QWebEngineView *view = new QWebEngineView(this);
setCentralWidget(view);
QFile file(":/print.htm");
QString str;
if (file.open(QFile::ReadOnly | QFile::Text))
{
str.append(file.readAll());
view->setHtml(str);
file.close();
}
connect(view, &QWebEngineView::loadFinished, this, &MainWindow::on_loadFinished);
}
void MainWindow::on_loadFinished(bool ok)
{
if (ok)
{
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setPageSize(QPageSize(QPageSize::A4));
printer.setPageOrientation(QPageLayout::Portrait);
printer.setColorMode(QPrinter::GrayScale);
printer.setOutputFileName("doc.pdf");
static_cast<QWebEngineView *>(sender())->render(&printer);
}
}
#包括“MainWindow.h”
#包括“ui_main window.h”
主窗口::主窗口(QWidget*父窗口):
QMainWindow(父级),
用户界面(新用户界面::主窗口)
{
用户界面->设置用户界面(此);
QWebEngineView*视图=新的QWebEngineView(此视图);
setCentralWidget(视图);
QFile文件(“:/print.htm”);
QString-str;
if(file.open(QFile::ReadOnly | QFile::Text))
{
str.append(file.readAll());
查看->设置HTML(str);
file.close();
}
连接(视图,&QWebEngineView::loadFinished,此,&MainWindow::on_loadFinished);
}
void main window::on_loadFinished(bool ok)
{
如果(确定)
{
QPrinter打印机(QPrinter::高分辨率);
打印机.setOutputFormat(QPrinter::PdfFormat);
打印机.setPageSize(QPageSize(QPageSize::A4));
打印机。设置页面方向(QPageLayout::纵向);
打印机.setColorMode(QPrinter::GrayScale);
打印机.setOutputFileName(“doc.pdf”);
静态_cast(sender())->渲染(&打印机);
}
}
正如我在评论中提到的,在我看来,更新是唯一/最好的解决方案,因为Qt 5.6不支持打印QWebEngineView
:
参考资料:
- :
- 如何打印QWebEngineView内容??使用QWebView,我只需要调用print方法 使用铬进行打印令人惊讶地难以实现,但我们 旨在支持打印到Qt 5.7中的PDF:
- : 看着它,我们似乎不会在Qt5.5也有它
QWebView
类(由QWebEngineView
替换)中的print
方法,如下所述:
对于Qt 5.6,以下模块不再是该版本的一部分
软件包,但用户仍可以从源代码生成它们:
- Qt网络工具包
请注意,我不推荐此替代方案,仅当您无法更新到最新的Qt版本时才使用它。在我看来,更新是唯一的解决方案:或正确。我已经这样做了,现在我使用QWebEnginePage::printToPdf方法。谢谢你的信息!