QT 使用QPdfWriter和QPainter绘制PDF文件

发布于:2025-05-16 ⋅ 阅读:(17) ⋅ 点赞:(0)

QT如何生产pdf文件,网上有许多文章介绍,我也是看了网上的文章,看他们的代码,自己琢磨琢磨,才有了本编博客;

其他什么就不详细说了,本篇博客介绍的QPdfWriter和QPainter绘制PDF文件;对pdf这里是绘制出来的,没有什么规范的格式,都是通过xy坐标绘制出来的。

QPdfWriter类设置pdf的基础设置;QPainter类绘制文本,图片矩形等;

以下代码参考博客:Qt中使用QPdfWriter类结合QPainter类绘制并输出PDF文件-CSDN博客

自己稍微做了调整了修改!

反正得自己会QPainter绘制,否则你无法绘制pdf文件出来!!!

头文件:

#include <QPdfWriter>
#include <QDesktopServices>
#include <QtPrintSupport/QPrinter>
#include <QtPrintSupport/QtPrintSupport>

一、步骤

绘制pdf有以下步骤:

1.选择需要导出的pdf文件路径;

2.创建pdf文件;

3.创建生成pdf类,作为绘图设备;

4.绘制PDF;

5.查看绘制好的pdf。

void Widget::exportPdf()
{
    //一、选择保存pdf文件路径
    QString sPath = QFileDialog::getSaveFileName(this, tr("另存为"), "/", tr("Text Files (*.pdf)"));
    if(sPath.isEmpty())
    {
        return;
    }
    qDebug() << sPath;

    //二、创建pdf文件
    QFile pdfFile(sPath);
    pdfFile.open(QIODevice::WriteOnly);

    //三、创建生成pdf类,作为绘图设备
    QPdfWriter *pPdfWriter = new QPdfWriter(&pdfFile);
    pPdfWriter->setResolution(300);      // 将打印设备的分辨率设置为屏幕分辨率
    pPdfWriter->setPageSize(QPagedPaintDevice::A4);             // 设置纸张为A4纸
    pPdfWriter->setPageMargins(QMarginsF(30, 30, 30, 30));      // 设置页边距 顺序是:左上右下

    //四、开始绘制PDF
    //paintPdf(pPdfWriter);

    delete pPdfWriter;
    pdfFile.close();

    //通过其它PDF阅读器来打开刚刚绘制的PDF
    QDesktopServices::openUrl(QUrl::fromLocalFile(sPath));
}

二、效果展示

三、代码实现

#include "widget.h"
#include "ui_widget.h"

#include <QFileDialog>
#include <QStandardPaths>
#include <QPdfWriter>
#include <QDebug>
#include <QDesktopServices>
#include <QMessageBox>
#include <QtPrintSupport/QPrinter>
#include <QtPrintSupport/QtPrintSupport>

#include <pdfgenerator.h>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    createPDF();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::createPDF()
{
    int y = 0;
    QString path = "/home/UOS/Desktop/3.pdf";

    PdfGenerator *pdfGenerator = new PdfGenerator;
    bool flag = pdfGenerator->setFileName(path);
    if (!flag) {
        return ;
    }

    int nPdfWidth = pdfGenerator->getPdfWidth();

    pdfGenerator->beginPage();

    QPixmap p;
    p.load(":/007.jpg");
    int pHeight = pdfGenerator->drawImage(QRectF(0, y, 150, 150), p);

    y += pHeight + 50;


    // 绘制表格
    y += 100;
    QFont f = QFont("宋体", 18, 36);
    QColor blackColor = QColor(0,0,0);

    pdfGenerator->drawRect(QRectF(0, y, nPdfWidth, 200), blackColor, 2, QColor(100, 0, 200, 50));
    pdfGenerator->drawText(QRectF(0, y, nPdfWidth, 200), "这是标题文本!", QFont("宋体", 32, 64));


    // 绘制科目
    y += 200;

    int nClassWidthFlag = nPdfWidth / (8);
    int nClassWidth = nClassWidthFlag;

    QList<QString> classList;
    classList << "语文" << "数学" << "英语" << "历史" << "政治" << "地理" << "音乐" << "体育";
    int classx = 0;
    for (int i = 0; i < classList.count(); i++) {
        pdfGenerator->drawRect(QRectF(classx, y, nClassWidth, 100), blackColor, 2);
        pdfGenerator->drawText(QRectF(classx, y, nClassWidth, 100), classList.at(i), QFont("宋体", 12, 20), QColor(200, 100, 100), Qt::AlignCenter);

        classx += nClassWidth;
        if (7 == i + 1) {
            int n = nPdfWidth - (classx + nClassWidth);
            nClassWidth += n;
        }
    }



    // 绘制个人信息
    y += 100;

    int nPersonDescriptionWidth = nClassWidthFlag * 2;

    QList<QList<QString>> descriptionList;
    QList<QString> list;
    list << "小米" << "男" << "15";
    descriptionList << list;
    list.clear();
    list << "小明" << "男" << "20";
    descriptionList << list;
    list.clear();
    list << "小红" << "女" << "21";
    descriptionList << list;
    list.clear();
    list << "姓名" << "性别" << "年龄";


    int nPersonDescriptionHeight = 120 + descriptionList.count() * 100;

    pdfGenerator->drawRect(QRect(0, y, nPersonDescriptionWidth, nPersonDescriptionHeight));
    pdfGenerator->drawText(QRect(0, y, nPersonDescriptionWidth, nPersonDescriptionHeight), "个人信息",
                           QFont("宋体", 20, 40), QColor(100, 100, 255));



    int nMessageX = nPersonDescriptionWidth;
    int nMessageWidth = nPersonDescriptionWidth;
    for (int i = 0; i < list.count(); i++) {
        pdfGenerator->drawRect(QRect(nMessageX, y, nMessageWidth, 120));
        pdfGenerator->drawText(QRect(nMessageX, y, nMessageWidth, 120), list.at(i), QFont("宋体", 18, 30), QColor(200, 50, 50));

        nMessageX += nPersonDescriptionWidth;
        if (list.count()-1 == i + 1) {
            int n = nPdfWidth - (nMessageX + nPersonDescriptionWidth);
            nMessageWidth += n;
        }
    }


    y += 120;

    int nPersonX = nPersonDescriptionWidth;
    int nPersonWidth = nPersonDescriptionWidth;
    for (int i = 0; i < descriptionList.count(); ++i) {
        QList<QString> list = descriptionList.at(i);

        for (int j = 0; j < list.count(); ++j) {
            pdfGenerator->drawRect(QRect(nPersonX, y, nPersonWidth, 100));
            pdfGenerator->drawText(QRect(nPersonX, y, nPersonWidth, 100), list.at(j), pdfGenerator->getBaseFont());

            nPersonX += nPersonDescriptionWidth;
            if (list.count()-1 == j + 1) {
                int n = nPdfWidth - (nPersonX + nPersonDescriptionWidth);
                nPersonWidth += n;
            }
        }

        y += 100;

        nPersonX = nPersonDescriptionWidth;
        nPersonWidth = nPersonDescriptionWidth;
    }




    // 绘制详细信息
    descriptionList.clear();
    list.clear();
    list << "小明" << "swim" << "擅长蛙泳" << "170cm";
    descriptionList << list;
    list.clear();
    list << "小红" << "dance" << "街舞鼻祖" << "160cm";
    descriptionList << list;
    list.clear();
    list << "小黄" << "run" << "短跑小王子" << "166cm";
    descriptionList << list;
    list.clear();
    list << "小绿" << "jump" << "跳高运动员" << "196cm";
    descriptionList << list;
    list.clear();
    list << "姓名" << "爱好" << "特点" << "身高";


    int nDetailedInformationWidth = nClassWidthFlag * 2;
    int nDetailedInformationHeight = 120 + descriptionList.count() * 100;

    pdfGenerator->drawRect(QRect(0, y, nDetailedInformationWidth, nDetailedInformationHeight));
    pdfGenerator->drawText(QRect(0, y, nDetailedInformationWidth, nDetailedInformationHeight), "详细信息",
                           QFont("宋体", 20, 40), QColor(100, 100, 255));



    int nInformationTotalWidth = nPdfWidth - nDetailedInformationWidth;
    int nInformationOneWidth = nInformationTotalWidth / descriptionList.count();

    int nDetailedX = nDetailedInformationWidth;
    int nDetailedWidth = nInformationOneWidth;
    for (int i = 0; i < list.count(); i++) {
        pdfGenerator->drawRect(QRect(nDetailedX, y, nDetailedWidth, 120));
        pdfGenerator->drawText(QRect(nDetailedX, y, nDetailedWidth, 120), list.at(i), QFont("宋体", 20, 30));

        nDetailedX += nDetailedWidth;
        if (list.count()-1 == i + 1) {
            int n = nPdfWidth - (nDetailedX + nDetailedWidth);
            nDetailedWidth += n;
        }
    }


    y += 120;
    int nInformationX = nDetailedInformationWidth;
    int nInformationWidth = nInformationOneWidth;
    for (int i = 0; i < descriptionList.count(); ++i) {
        QList<QString> list = descriptionList.at(i);

        for (int j = 0; j < list.count(); ++j) {
            pdfGenerator->drawRect(QRect(nInformationX, y, nInformationWidth, 100));
            pdfGenerator->drawText(QRect(nInformationX, y, nInformationWidth, 100), list.at(j),
                                   pdfGenerator->getBaseFont(), QColor(200,0,0));

            nInformationX += nInformationWidth;
            if (list.count()-1 == j + 1) {
                int n = nPdfWidth - (nInformationX + nInformationWidth);
                nInformationWidth += n;
            }
        }

        y += 100;
        nInformationX = nDetailedInformationWidth;
        nInformationWidth = nInformationOneWidth;
    }


    y += 50;
    pdfGenerator->drawPolygon(QRect(600, y, 800, 600));
    pdfGenerator->drawRect(QRect(600, y, 800, 600));

    // 换页
    //    if(y + 100 >= pdfGenerator->getPdfHeight()) {
    //        pdfGenerator->newPage();
    //        y = 10;
    //    }



    pdfGenerator->newPage();
    y = 0;


    /************************************************************************************************************/

    // 外部大矩形框
    pdfGenerator->drawRect(QRect(0, y, nPdfWidth, pdfGenerator->getPdfHeight()), QColor(0,0,0), 8);

    // 左上角m级
    f = pdfGenerator->getBaseFont();
    f.setBold(true);
    f.setPointSize(13);
    pdfGenerator->drawText(QRectF(10, y, 360, 100), "m级:非m", f, QColor(0,0,0), Qt::AlignLeft);


    // 页码
    int pageX = 900;
    f = pdfGenerator->getBaseFont("宋体", 12, 0);
    pdfGenerator->drawText(QRectF(pageX, y, 500, 100), "第 1 页   Page", f, QColor(0,0,0), Qt::AlignLeft);
    y += 80;
    pdfGenerator->drawText(QRectF(pageX, y, 1444, 100), "共 2 页   This report includes page", f, QColor(0,0,0), Qt::AlignLeft);


    y += 100;
    // 标题1
    f = pdfGenerator->getBaseFont("宋体", 20, 8);
    pdfGenerator->drawText(QRectF(0, y, nPdfWidth, 120), "嘻嘻嘻这是一份关于检测相关的世界的详细报告哈哈", f, QColor(0,0,0), Qt::AlignCenter);

    y += 120;
    // 标题1英语
    f = pdfGenerator->getBaseFont("Times New Roman", 11, 8);
    QString english = "abc abc He he he, this is a detailed report about the world related to testing. Ha ha. abc abc";
    pdfGenerator->drawText(QRectF(0, y, nPdfWidth, 120), english, f, QColor(0,0,0), Qt::AlignCenter);



    y += 150;
    // 标题2
    f = pdfGenerator->getBaseFont("宋体", 30, 8);
    pdfGenerator->drawText(QRectF(0, y, nPdfWidth, 130), "一二三四五六报告", f, QColor(0,0,0), Qt::AlignCenter);


    y += 160;
    // 标题2英语
    f = pdfGenerator->getBaseFont("Times New Roman", 20, 12);
    pdfGenerator->drawText(QRectF(0, y, nPdfWidth, 130), "Tihs is a Report", f, QColor(0,0,0), Qt::AlignCenter);


    y += 160;
    // 报告编号
    f = pdfGenerator->getBaseFont("宋体", 10, 0);
    pdfGenerator->drawText(QRectF(0, y, nPdfWidth, 50), "报告编号:( 2025 )报告的 第 15 号", f, QColor(0,0,0), Qt::AlignCenter);


    y += 80;
    // Report No.
    f = pdfGenerator->getBaseFont("Times New Roman", 10, 0);
    pdfGenerator->drawText(QRectF(0, y, nPdfWidth, 50), "Report No.", f, QColor(0,0,0), Qt::AlignCenter);


    int nameX = 200;    // 距离左边的距离
    int lineX = 500;    // 横线距离左边的距离
    int lineWidth = 1322;    // 横线宽度

    y += 100;
    for (int i = 0; i < 6; i++) {
        int tmpY = y + 30;
        // 你的名称
        f = pdfGenerator->getBaseFont();
        pdfGenerator->drawText(QRectF(nameX, y, 250, 60), "你的名称:", f, QColor(0,0,0), Qt::AlignLeft);
        y += 80;
        // 英文
        f = pdfGenerator->getBaseFont("Times New Roman", 10, 0);
        pdfGenerator->drawText(QRectF(nameX, y, 250, 60), "Your name", f, QColor(0,0,0), Qt::AlignLeft);
        y += 70;
        // 画横线
        f = pdfGenerator->getBaseFont();
        pdfGenerator->drawLine(QPointF(lineX, y), QPointF(lineX + lineWidth, y));
        // 画文本
        pdfGenerator->drawText(QRectF(lineX, tmpY, lineWidth, 80), "这是名字呀", f, QColor(0,0,0), Qt::AlignCenter);

        y += 30;

        // 自动换页处理
//        if(y + 200 >= pdfGenerator->getPdfHeight()) {
//            pdfGenerator->newPage();
//            y = 10;
//        }
    }

    y += 50;
    // 签发人
    f = pdfGenerator->getBaseFont();
    pdfGenerator->drawText(QRectF(nameX, y, 400, 60), "签发人:(签字)", f, QColor(0,0,0), Qt::AlignLeft);

    int dataX = 1111;
    // 发证日期
    f = pdfGenerator->getBaseFont();
    pdfGenerator->drawText(QRectF(dataX, y, 400, 60), "发证日期:", f, QColor(0,0,0), Qt::AlignLeft);


    y += 90;
    // 签发人 英文
    f = pdfGenerator->getBaseFont("Times New Roman", 10);
    pdfGenerator->drawText(QRectF(nameX, y, 400, 60), "Signature of leader", f, QColor(0,0,0), Qt::AlignLeft);

    // 发证日期 英文
    f = pdfGenerator->getBaseFont("Times New Roman", 10);
    pdfGenerator->drawText(QRectF(dataX, y, 400, 60), "lssued date", f, QColor(0,0,0), Qt::AlignLeft);


    y += 200;
    // 发证单位
    f = pdfGenerator->getBaseFont();
    pdfGenerator->drawText(QRectF(dataX, y, 600, 60), "发证单位:(盖章位置)", f, QColor(0,0,0), Qt::AlignLeft);

    y += 90;
    // 发证单位 英文
    f = pdfGenerator->getBaseFont("Times New Roman", 10);
    pdfGenerator->drawText(QRectF(dataX, y, 400, 60), "lssued by(stamp)", f, QColor(0,0,0), Qt::AlignLeft);


    y += 200;
    // 地址
    f = pdfGenerator->getBaseFont("宋体", 10);
    f.setBold(true);
    pdfGenerator->drawText(QRectF(nameX, y, 600, 66), "地址(Add):", f, QColor(0,0,0), Qt::AlignLeft);

    f = pdfGenerator->getBaseFont("宋体", 10);
    pdfGenerator->drawText(QRectF(nameX + 330, y, 800, 66), "广东省广州市天河区xx街道xx村xx号", f, QColor(0,0,0), Qt::AlignLeft);

    // 邮编
    f = pdfGenerator->getBaseFont("宋体", 10);
    f.setBold(true);
    pdfGenerator->drawText(QRectF(nameX + 1100, y, 600, 66), "邮编(Post Code):", f, QColor(0,0,0), Qt::AlignLeft);

    f = pdfGenerator->getBaseFont("宋体", 10);
    pdfGenerator->drawText(QRectF(nameX + 1550, y, 300, 66), "123456", f, QColor(0,0,0), Qt::AlignLeft);

    y += 100;
    // 电话
    f = pdfGenerator->getBaseFont("宋体", 10);
    f.setBold(true);
    pdfGenerator->drawText(QRectF(nameX, y, 600, 66), "电话(Tel):", f, QColor(0,0,0), Qt::AlignLeft);

    f = pdfGenerator->getBaseFont("宋体", 10);
    pdfGenerator->drawText(QRectF(nameX + 330, y, 800, 66), "002-123456789", f, QColor(0,0,0), Qt::AlignLeft);

    // 传真
    f = pdfGenerator->getBaseFont("宋体", 10);
    f.setBold(true);
    pdfGenerator->drawText(QRectF(nameX + 800, y, 600, 66), "传真(Fax):", f, QColor(0,0,0), Qt::AlignLeft);

    f = pdfGenerator->getBaseFont("宋体", 10);
    pdfGenerator->drawText(QRectF(nameX + 1050, y, 300, 66), "002-123456789", f, QColor(0,0,0), Qt::AlignLeft);


    y += 100;
    // 电子邮箱
    f = pdfGenerator->getBaseFont("宋体", 10);
    f.setBold(true);
    pdfGenerator->drawText(QRectF(nameX, y, 600, 66), "电子信箱(E-mail):", f, QColor(0,0,0), Qt::AlignLeft);

    f = pdfGenerator->getBaseFont("宋体", 10);
    pdfGenerator->drawText(QRectF(nameX + 400, y, 800, 66), "youxiang666@qq.com", f, QColor(0,0,0), Qt::AlignLeft);


    pdfGenerator->endPage();

    // 通过其它PDF阅读器来打开刚刚绘制的PDF
    QDesktopServices::openUrl(QUrl::fromLocalFile(path));
}

四、源码分享

pdfgenerator.h

#ifndef PDF_GENERATOR_H
#define PDF_GENERATOR_H

#include <QObject>
#include <QPdfWriter>
#include <QPainter>
#include <QFont>
#include <QImage>
#include <QPageSize>
#include <QFile>

class PdfGenerator : public QObject {
    Q_OBJECT
public:
    explicit PdfGenerator(const QString &fileName, QPagedPaintDevice::PageSize size = QPagedPaintDevice::PageSize::A4, QObject *parent = nullptr);
    explicit PdfGenerator(QObject *parent = nullptr);

    ~PdfGenerator();

    qreal getPdfWidth();
    qreal getPdfHeight();


    /**
     * @brief getBaseFont   获得基本的字体
     * @param family
     * @param pointSize
     * @param weight
     * @return
     */
    QFont getBaseFont(const QString &family = "宋体", int pointSize = 12, int weight = -1);

    /**
     * @brief setMargins    设置pdf边距,分别是 左-上-右-下
     * @param left
     * @param top
     * @param right
     * @param bottom
     */
    void setMargins(qreal left, qreal top, qreal right, qreal bottom);

    /**
     * @brief setResolution     设置分辨率,一般为300
     * @param dpi
     */
    void setResolution(int dpi = 300);

    /**
     * @brief newPage           新建下一页
     */
    void newPage();

    /**
     * @brief beginPage         开始绘画
     * @return      成功返回true;失败返回false
     */
    bool beginPage();

    /**
     * @brief endPage           结束会话
     * @return      成功返回true;失败返回false
     */
    bool endPage();

    /**
     * @brief setFileName       设置pdf文件名,内部会open
     * @param fileName
     * @param size
     * @return
     */
    bool setFileName(const QString &fileName, QPagedPaintDevice::PageSize size = QPagedPaintDevice::PageSize::A4);


    /**
     * @brief drawLine  绘制线段
     * @param start     起始坐标
     * @param end       结束坐标
     * @param color     线段颜色
     * @param width     线段宽度
     */
    void drawLine(const QPointF &start, const QPointF &end, const QColor &color = QColor(0,0,0), qreal width = 2);

    /**
     * @brief drawText  绘制文字
     * @param rect      绘制的位置(矩形)
     * @param text      绘制的文本
     * @param font      绘制字体
     * @param color     字体颜色
     * @param align     对齐
     */
    void drawText(const QRectF &rect, const QString &text, const QFont &font, const QColor &color = QColor(0,0,0), Qt::Alignment align = Qt::AlignCenter);

    /**
     * @brief drawImage             绘制图片
     * @param rect                  绘制的位置(矩形)
     * @param imagePath             图片路径
     */
    int drawImage(const QRectF &rect, const QString &imagePath);
    int drawImage(const QRectF &rect, const QPixmap &pixmap);
    int drawImage(const QRectF &rect, const QImage &image);

    /**
     * @brief drawRect          绘制矩形
     * @param rect              绘制的位置(矩形)
     * @param borderColor       边框的颜色
     * @param borderWidth       边框宽度
     * @param fillColor         填充的颜色,默认透明,不填充
     */
    void drawRect(const QRectF &rect, const QColor &borderColor = QColor(0,0,0), qreal borderWidth = 2, const QColor &fillColor = Qt::transparent);

    /**
     * @brief drawEllipse       绘制椭圆
     * @param rect              绘制的位置(矩形)
     * @param borderColor       边框的颜色
     * @param borderWidth       边框宽度
     * @param fillColor         填充的颜色,默认透明,不填充
     */
    void drawEllipse(const QRectF &rect, const QColor &borderColor = QColor(0,0,0), qreal borderWidth = 2, const QColor &fillColor = Qt::transparent);

    /**
     * @brief drawPolygon       画三角形,三角形在矩形区域内
     * @param rect              绘制的位置(矩形)
     * @param borderColor       边框的颜色
     * @param borderWidth       边框宽度
     * @param fillColor         填充的颜色,默认透明,不填充
     */
    void drawPolygon(const QRectF &rect, const QColor &borderColor = QColor(0,0,0), qreal borderWidth = 2, const QColor &fillColor = Qt::transparent);

   // 想设计其他绘制接口继续往下加

private:
    QPdfWriter *m_writer = nullptr;
    QPainter *m_painter = nullptr;
    /// pdf可绘制区域
    QRect m_pageRect;
    /// pdf文件
    QFile m_pdfFile;
};

#endif  // PDF_GENERATOR_H

pdfgenerator.cpp

#include "pdfgenerator.h"
#include <QtDebug>


PdfGenerator::PdfGenerator(const QString &fileName, QPagedPaintDevice::PageSize size, QObject *parent) : QObject (parent)
{
    m_pdfFile.setFileName(fileName);
    m_writer = new QPdfWriter(&m_pdfFile);
    m_writer->setPageSize(size);                // 设置纸张
    m_writer->setResolution(300);               // 设置分辨率
    m_writer->setPageMargins(QMarginsF(20, 20, 20, 20), QPageLayout::Millimeter);   // 设置页边距
    m_pageRect = m_writer->pageLayout().paintRectPixels(m_writer->resolution());
    // 计算可绘制区域
    m_pageRect = QRect(0, 0, m_writer->width(), m_writer->height());
    if(!m_pdfFile.open(QIODevice::WriteOnly))
        return ;

}

PdfGenerator::PdfGenerator(QObject *parent) : QObject (parent)
{

}

PdfGenerator::~PdfGenerator()
{
    if (m_painter) {
        if (m_painter->isActive())
        {
            m_painter->end();
        }
        delete m_painter;
    }

    if (m_writer) {
        m_writer->deleteLater();
    }
}

qreal PdfGenerator::getPdfWidth()
{
    return m_pageRect.width();
}

qreal PdfGenerator::getPdfHeight()
{
    return m_pageRect.height();
}

QFont PdfGenerator::getBaseFont(const QString &family, int pointSize, int weight)
{
    QFont f(family, pointSize, weight);

    return f;
}

void PdfGenerator::setMargins(qreal left, qreal top, qreal right, qreal bottom)
{
    m_writer->setPageMargins(QMarginsF(left, top, right, bottom), QPageLayout::Millimeter);
    m_pageRect = m_writer->pageLayout().paintRectPixels(m_writer->resolution()); // 更新绘制区域
}

void PdfGenerator::setResolution(int dpi)
{
    m_writer->setResolution(dpi);
}

void PdfGenerator::newPage()
{
    // 创建新页
    m_writer->newPage();
}

bool PdfGenerator::beginPage()
{
    bool bRet = false;
    if(nullptr == m_painter)
    {
        m_painter = new QPainter(m_writer);
    }
    //启用抗锯齿
    m_painter->setRenderHint(QPainter::Antialiasing);
    if (nullptr != m_painter)
    {
        m_painter->begin(m_writer);
        //m_painter->reset(new  QPainter(m_writer.data()));
        bRet = m_painter->isActive();
    }
    qDebug() << "beginPage bRet is " << bRet;
    return bRet;
}

bool PdfGenerator::endPage() {

    if (m_painter && m_painter->isActive())
    {
        m_painter->end();
        m_writer->deleteLater();
        m_pdfFile.close();
        return true;
    }
    m_pdfFile.close();
    return false;
}

bool PdfGenerator::setFileName(const QString &fileName, QPagedPaintDevice::PageSize size)
{
    m_pdfFile.setFileName(fileName);
    // 打开创建并以写的方式打开文件
    if(!m_pdfFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        return false;
    }

    m_writer = new QPdfWriter(&m_pdfFile);
    m_writer->setPageSize(size);                // 设置纸张
    m_writer->setResolution(300);               // 设置分辨率
    m_writer->setPageMargins(QMarginsF(20, 20, 20, 20), QPageLayout::Millimeter);   // 设置页边距

    m_pageRect = m_writer->pageLayout().paintRectPixels(m_writer->resolution());

    // 计算可绘制区域
    m_pageRect = QRect(0, 0, m_writer->width(), m_writer->height());

    return true;
}

// 绘制线段
void PdfGenerator::drawLine(const QPointF &start, const QPointF &end, const QColor &color, qreal width)
{
    if (!m_painter->isActive())
        return;

    m_painter->save();
    m_painter->setPen(QPen(color, width));
    m_painter->drawLine(start, end);
    m_painter->restore();
}

// 绘制文本(支持对齐)
void PdfGenerator::drawText(const QRectF &rect, const QString &text, const QFont &font, const QColor &color, Qt::Alignment align)
{
    if (!m_painter->isActive())
        return;

    m_painter->save();
    m_painter->setFont(font);
    m_painter->setPen(color);
    m_painter->drawText(rect, static_cast<int>(align), text);
    m_painter->restore();
}

// 绘制图片(根据大小比例,来放大缩小图片)
int PdfGenerator::drawImage(const QRectF &rect, const QString &imagePath)
{
    if (!m_painter->isActive())
        return -10;

    QPixmap pixmap;
    if (!pixmap.load(imagePath)) {
        return -1;
    }

    int nPdfWidth = m_pageRect.width();
    int imageBorder = rect.width();

    float x = (float)(nPdfWidth - imageBorder * 2) / (float)pixmap.width();

    pixmap = pixmap.scaled(nPdfWidth - imageBorder * 2, x * pixmap.height(), Qt::IgnoreAspectRatio);    //根据大小比例,来放大缩小图片

    m_painter->drawPixmap(imageBorder, static_cast<int>(rect.y()), pixmap);

    return pixmap.height();
}

int PdfGenerator::drawImage(const QRectF &rect, const QPixmap &pixmap)
{
    if (!m_painter->isActive())
        return -1;

    if (pixmap.isNull())
        return -1;

    int nPdfWidth = m_pageRect.width();
    int imageBorder = rect.width();

    float x = (float)(nPdfWidth - imageBorder * 2) / (float)pixmap.width();

    QPixmap pixmapTmp = pixmap.scaled(nPdfWidth - imageBorder * 2, x * pixmap.height(), Qt::IgnoreAspectRatio);    //根据大小比例,来放大缩小图片

    m_painter->drawPixmap(imageBorder, static_cast<int>(rect.y()), pixmapTmp);

    return pixmapTmp.height();
}

int PdfGenerator::drawImage(const QRectF &rect, const QImage &image)
{
    if (!m_painter->isActive())
        return -1;

    if (image.isNull())
        return -1;

    int nPdfWidth = m_pageRect.width();
    int imageBorder = rect.width();

    float x = (float)(nPdfWidth - imageBorder * 2) / (float)image.width();

    QImage imageTmp = image.scaled(nPdfWidth - imageBorder * 2, x * image.height(), Qt::IgnoreAspectRatio);    //根据大小比例,来放大缩小图片

    m_painter->drawImage(rect, image);

    return image.height();
}

// 绘制矩形(支持填充)
void PdfGenerator::drawRect(const QRectF &rect, const QColor &borderColor, qreal borderWidth, const QColor &fillColor)
{
    if (!m_painter->isActive())
        return;

    m_painter->save();
    m_painter->setBrush(QBrush(fillColor));     // 填充
    m_painter->setPen(QPen(borderColor, borderWidth));
    m_painter->drawRect(rect);
    m_painter->restore();
}

// 绘制椭圆
void PdfGenerator::drawEllipse(const QRectF &rect, const QColor &borderColor, qreal borderWidth, const QColor &fillColor)
{
    if (!m_painter->isActive())
        return;

    m_painter->save();
    m_painter->setBrush(QBrush(fillColor));
    m_painter->setPen(QPen(borderColor, borderWidth));
    m_painter->drawEllipse(rect);
    m_painter->restore();
}

void PdfGenerator::drawPolygon(const QRectF &rect, const QColor &borderColor, qreal borderWidth, const QColor &fillColor)
{
    if (!m_painter->isActive())
        return;

    QPen pen(borderColor, borderWidth); // 底边线宽为5
    m_painter->setPen(pen);
    QBrush brush(fillColor);
    m_painter->setBrush(brush);

    QPoint points[3] = {
        QPoint(rect.x(), rect.y() + rect.height()), // 左下角点
        QPoint(rect.x() + rect.width(), rect.y() + rect.height()), // 右下角点
        QPoint((rect.width() + rect.x() + rect.x()) / 2, rect.y()) // 上顶点
    };

    m_painter->drawPolygon(points, 3);
}


网站公告

今日签到

点亮在社区的每一天
去签到