qt5 linux 生成pdf文件,QT使用QPdfWriter生成PDF文件

1 导入以下头文件

#include

#include

#include

2 创建QPdfWriter对象

QString file_path =QApplication::applicationDirPath()+"/test.pdf";

QFile pdfFile(file_path);

pdfFile.open(QIODevice::WriteOnly);

QPdfWriter* pWriter = new QPdfWriter(&pdfFile);

//Init Page

pWriter->setPageSize(QPagedPaintDevice::A4);

pWriter->setResolution(300); //设置dpi 每个平方英寸像素为300

pWriter->setPageMargins(QMarginsF(30, 30, 30, 30));

3 创建QPainter对象

QPainter* pPainter = new QPainter(pWriter);

4 构建字体数组(可选)

//Init Font

QFont font[5]={QFont("宋体",26,60),QFont("宋体",26,61),QFont("宋体",26,QFont::Normal),QFont("宋体",26,QFont::Normal),QFont("宋体",26,QFont::Normal)};

font[0].setPixelSize(86);

font[1].setPixelSize(61);

font[2].setPixelSize(61);

font[3].setPixelSize(42);

font[4].setPixelSize(54);

5 写入标题

int y=10;

pPainter->setFont(font[0]);

pPainter->drawText(QRect(0,y, nPDFWidth, 100), Qt::AlignCenter, "title");

6 画两条直线

pPainter->setPen(QPen(QBrush(QColor(0,0,0)),5));

pPainter->drawLine(0,y,nPDFWidth,y);

pPainter->drawLine(0,y+18,nPDFWidth,y+18);

7 写下一页

pWriter->newPage(); //写下一页

8 绘制结束时

delete pPainter;

delete pWriter;

pdfFile.close();

9 将界面上的元素(如表格等)写入PDF

ui->widget->render(pPainter);

你可能感兴趣的:(qt5,linux,生成pdf文件)