从 QWebEnginePage 打印文档

QWebEnginePage 是 Qt WebEngine 模块中的一个类,它提供了用于处理网页内容的接口。如果你想要打印 QWebEnginePage 中的内容,你可以使用 QPrinterQPrintDialog 类来实现。

项目配置了 Qt WebEngine 模块,并且在你的.pro文件中包含了相应的配置:

QT += webenginewidgets

实现代码如下,参考

printme << webenginewidgets << examples - qt/qtwebengine.git - Qt WebEngine

main.cpp

cpp 复制代码
#include "printhandler.h"
#include <QApplication>
#include <QShortcut>
#include <QWebEngineView>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication app(argc, argv);

    view.setUrl(QUrl(QStringLiteral("qrc:/index.html")));
    view.resize(1024, 750);
    view.show();

    PrintHandler handler;
    handler.setPage(view.page());

    auto printPreviewShortCut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_P), &view);
    auto printShortCut = new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_P), &view);

    QObject::connect(printPreviewShortCut, &QShortcut::activated, &handler, &PrintHandler::printPreview);
    QObject::connect(printShortCut, &QShortcut::activated, &handler, &PrintHandler::print);

    return app.exec();
}

printhandler.h

cpp 复制代码
#ifndef PRINTHANDLER_H
#define PRINTHANDLER_H
#include <qapplication.h>
#include <QObject>
#include <QWebEngineView>
#include <QPrinter>
#include <QPrintPreviewDialog>
#include <QEventLoop>
#include <QPrintDialog>
#include <QWidget>
#include <QMainWindow>
#include <QPrinterInfo>
#include "CustomWebEnginePage.h"
#include <qapplication.h>
#include <qtimer.h>
class PrintHandler : public QObject
{
    Q_OBJECT
public:
    explicit PrintHandler(QString printName, QObject *parent = nullptr);

signals:

public slots:

public:
    void setPrintUrl(const QString&  url);
	void setPrintName(const QString& name);
    void printPreview();
    void printDocument(QPrinter *printer);
    void print();
private:
    //void print();
private:
	QString mPrinterName;
	CustomWebEnginePage* mPage;
	QString mUrl;
    bool mInPrintPreview;
	QTimer* waitTimer;
};

#endif // PRINTHANDLER_H

printhandler.cpp

cpp 复制代码
#include "printhandler.h"
#include <QDebug>
PrintHandler::PrintHandler(QString printName,QObject *parent) : mPrinterName(printName),QObject(parent)
{
    mInPrintPreview=false;
	mPage = new CustomWebEnginePage();
	waitTimer = new QTimer();
	waitTimer->setInterval(500);
	waitTimer->setSingleShot(true);
	connect(waitTimer, &QTimer::timeout, this, &PrintHandler::print);
	connect(mPage, &CustomWebEnginePage::loadFinished, waitTimer, static_cast<void(QTimer::*)()>(&QTimer::start));

}

void PrintHandler::setPrintUrl(const QString& url)
{
	mUrl = url;
	mPage->setUrl(url);
}

void PrintHandler::printPreview()
{
    if (!mPage)
      return;
    if (mInPrintPreview)
      return;
	mInPrintPreview = true;
    QPrinter printer;
    QPrintPreviewDialog preview(&printer, mPage->view());
    connect(&preview, &QPrintPreviewDialog::paintRequested,
          this, &PrintHandler::printDocument);
    preview.exec();
	mInPrintPreview = false;
}


void PrintHandler::printDocument(QPrinter *printer)
{
    QEventLoop loop;
    bool result;
    auto printPreview = [&](bool success) { result = success; loop.quit(); };
    mPage->print(printer, std::move(printPreview));
    loop.exec();
    if (!result) {
        QPainter painter;
        if (painter.begin(printer)) {
            QFont font = painter.font();
            font.setPixelSize(15);
            painter.setFont(font);
            painter.drawText(QPointF(10,25),QStringLiteral("Could not generate print preview."));

            painter.end();
        }
    }
}
void PrintHandler::setPrintName(const QString& name)
{
    mPrinterName = name;
}



void PrintHandler::print()
{
    QStringList printerNameList=QPrinterInfo::availablePrinterNames();
    foreach (QString printerStr, printerNameList)
    {
        if(printerStr== mPrinterName)
        {
            QPrinter printer(QPrinter::HighResolution);
			printer.setOutputFormat(QPrinter::NativeFormat);

            printer.setPrinterName(printerStr);
			//打印界面
           /* QPrintDialog dialog(&printer, mPage->view());
            if (dialog.exec() != QDialog::Accepted)
                return;*/
            printDocument(&printer);
			return;
        }
    }
      qDebug() << "not find printer";


}

对于https的url连接,会出现"你的连接不是专用连接"报警,需要跳过这个报警所以要继承QWebEnginePage做个类

CustomWebEnginePage.h

cpp 复制代码
#pragma once

#include <QWebEnginePage>

class CustomWebEnginePage : public QWebEnginePage
{
	Q_OBJECT

public:
	CustomWebEnginePage();
	~CustomWebEnginePage();
	virtual bool certificateError(const QWebEngineCertificateError &certificateError);
};

CustomWebEnginePage.cpp

cpp 复制代码
#include "CustomWebEnginePage.h"

CustomWebEnginePage::CustomWebEnginePage()
{
}

CustomWebEnginePage::~CustomWebEnginePage()
{
}


bool CustomWebEnginePage::certificateError(const QWebEngineCertificateError &certificateError)
{
	return true;
}
相关推荐
姆路40 分钟前
QT中使用图表之QChart绘制动态折线图
c++·qt
何曾参静谧42 分钟前
「QT」文件类 之 QDir 目录类
开发语言·qt
何曾参静谧44 分钟前
「QT」文件类 之 QTemporaryDir 临时目录类
开发语言·qt
秋说1 小时前
【数据结构 | C++】整型关键字的平方探测法散列
数据结构·c++·算法
huangjiazhi_4 小时前
QTcpSocket 服务端和客户端
开发语言·qt
槿花Hibiscus4 小时前
C++基础:Pimpl设计模式的实现
c++·设计模式
黑不拉几的小白兔5 小时前
PTA部分题目C++重练
开发语言·c++·算法
写bug的小屁孩5 小时前
websocket身份验证
开发语言·网络·c++·qt·websocket·网络协议·qt6.3
chordful5 小时前
Leetcode热题100-32 最长有效括号
c++·算法·leetcode·动态规划
材料苦逼不会梦到计算机白富美5 小时前
线性DP 区间DP C++
开发语言·c++·动态规划