从 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;
}
相关推荐
不想当程序猿_4 分钟前
【蓝桥杯每日一题】分糖果——DFS
c++·算法·蓝桥杯·深度优先
cdut_suye15 分钟前
Linux工具使用指南:从apt管理、gcc编译到makefile构建与gdb调试
java·linux·运维·服务器·c++·人工智能·python
波音彬要多做40 分钟前
41 stack类与queue类
开发语言·数据结构·c++·学习·算法
捕鲸叉40 分钟前
C++软件设计模式之外观(Facade)模式
c++·设计模式·外观模式
矛取矛求1 小时前
QT的前景与互联网岗位发展
开发语言·qt
Leventure_轩先生1 小时前
[WASAPI]从Qt MultipleMedia来看WASAPI
开发语言·qt
只做开心事2 小时前
C++之红黑树模拟实现
开发语言·c++
程序员老冯头3 小时前
第十五章 C++ 数组
开发语言·c++·算法
程序猿会指北4 小时前
【鸿蒙(HarmonyOS)性能优化指南】启动分析工具Launch Profiler
c++·性能优化·harmonyos·openharmony·arkui·启动优化·鸿蒙开发
无 证明8 小时前
new 分配空间;引用
数据结构·c++