#QT# PDF文件处理
-Start:关注本公众号后,可直接联系后台获取排版美化的详细文档!
-Hints:本篇文章所编纂的资料均来自网络,特此感谢参与奉献的有关人员。
pro文件配置
QT5把所有打印的相关类,包括QPrinter、QPrintDialog都放到了Qt Print Support模块,如果你只是在.cpp文件中包含QPrinter库,在编译阶段就会报错,你需要先修改.pro文件,加上这句:QT += printsupport
H头文件增加相关的库
#include<QPrinter>
#include<QUrl>
#include<QFileDialog>
#include<QDesktopServices>
#include<QRect>
#include<QDateTime>
#include<QFile>
#include<QPainter>
#include<QPdfWriter>
#include<QDebug>
#include<QTextDocument>
#include<QPixmap>
#include<QMessageBox>
#include
#include<QTextEdit>
#include<QPrintPreviewDialog>
H头文件定义
-增加相关函数声明
voidqprinter_pdf();
voidqpdfwriter_pdf();
voidqtextdocument_pdf();
voidpicture_to_pdf();
voidtext_to_pdf();
voidhtml_to_pdf();
voidcomplex_pdf();
voidpdfDrawForm(QPainter*paint,inty,inthorzBorder,introw,intcolumn,intunitHeight,QFont&font,QStringList&list);
voidcreate_pdf();
voidPrintPreview();
voidPreview(QPrinter*printer);
-增加相关的控件
QTextEdit*textEdit;
QPrintPreviewDialog*printPreview;
CPP文件增加相关的函数定义
-基于QPrinter生成PDF文件
voidMainWindow::qprinter_pdf()
{
QStringpdfName="E://"+QDateTime::currentDateTime().toString("yyyy-MM-dd-HH-mm-ss")+".pdf";
QStringpdfPath=QFileDialog::getSaveFileName(this,"SavePdf",pdfName,"*.pdf");
if(pdfPath.isEmpty())
{
return;
}
QPrinterprinter(QPrinter::PrinterMode::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setPageSize(QPagedPaintDevice::A4);
printer.setOutputFileName(pdfPath);
printer.setOrientation(QPrinter::Landscape);
printer.setPageMargins(10,10,10,10,QPrinter::Millimeter);
QPainterpainter;
painter.begin(&printer);
//设置字体属性
QFontfont;
font.setFamily("宋体");
font.setBold(true);
font.setWeight(15);
font.setUnderline(true);
painter.setFont(font);
//设置画笔颜色
QPenpen;
pen.setColor(Qt::green);
painter.setPen(pen);
//开始绘制
painter.drawText(QRect(0,100,printer.width(),printer.height()),"111111");
painter.drawText(QRect(0,400,printer.width(),printer.height()),"222222222222222222222222");
//新一页
printer.newPage();
painter.drawText(QRect(0,0,printer.width(),printer.height()),"3333333333333333333333333");
painter.end();
//打开PDF
QDesktopServices::openUrl(QUrl(pdfPath));
}
-基于QPdfWriter生成PDF文件
voidMainWindow::qpdfwriter_pdf()
{
QStringpdfName="E://"+QDateTime::currentDateTime().toString("yyyy-MM-dd-HH-mm-ss")+".pdf";
QStringpdfPath=QFileDialog::getSaveFileName(this,"QPdfWriter方式导出PDF",pdfName,"*.pdf");
if(pdfPath.isEmpty())
{
return;
}
QFilepdfFile(pdfPath);
if(pdfFile.open(QIODevice::WriteOnly))
{
//实例化写入对象
QPdfWriter*writer=newQPdfWriter(&pdfFile);
//设置纸张属性(ps:有反馈说设置其他纸张类型,但是打印机还是A4的格式,楼主没有打印件所以没得测试有条件可以测试下)
writer->setPageSize(QPagedPaintDevice::A4);
//设置dpi好像基本都是设置300像素
writer->setResolution(300);
//设置边距
writer->setPageMargins(QMarginsF(20,20,20,20));
QPainter*painter=newQPainter(writer);
painter->setFont(QFont("宋体",13));
//开始绘制内容
intstart=10;
painter->drawText(QRect(0,start,writer->width(),100),Qt::AlignCenter,"标题");
start+=120;
// QPenpen;
// pen.setColor(Qt::gray);
painter->setPen(QPen(QBrush(QColor(0,0,0)),5));
painter->drawLine(0,start,writer->width(),start);
start+=120;
painter->drawText(QRect(0,start,writer->width(),100),Qt::AlignLeft,"标题1");
deletepainter;
painter=nullptr;
deletewriter;
writer=nullptr;
//打开
QDesktopServices::openUrl(pdfPath);
pdfFile.close();
}
}
-基于QTextdocument生成PDF文件
voidMainWindow::qtextdocument_pdf()
{
QStringpdfName="E://"+QDateTime::currentDateTime().toString("yyyy-MM-dd-HH-mm-ss")+".pdf";
QStringpdfPath=QFileDialog::getSaveFileName(this,"QPdfWriter方式导出PDF",pdfName,"*.pdf");
if(pdfPath.isEmpty())
{
return;
}
QPrinterprinter;
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setPageSize(QPagedPaintDevice::A4);
printer.setOutputFileName(pdfPath);
printer.setOrientation(QPrinter::Portrait);//默认页面方向
printer.setPageMargins(5,5,5,5,QPrinter::Millimeter);//设置边距
//绘制的内容
QStringhtml=QString("width='600'border='1'align='center'frame='border'cellspacing='0'cellpadding='3px'rules='all'>");
";html+=""; ";//表头QStringListheaders;headers<<"标题1"<<"标题2"<<"标题3"<<"标题4"<<"标题5";for(QStringti:headers){
html+=QString("%1 ").arg(ti);}
html+="qDebug()<<"html:"<<html;//单元格内容for(inti=0;i<10;i++){
html+=""; ";for(intj=0;j<headers.count();j++){
html+=QString("内容%1 ").arg(j+1);}
html+="}
html+="
qDebug()<<"html:"<<html;
QTextDocumenttextDoc;
textDoc.setHtml(html);
textDoc.print(&printer);
//
QDesktopServices::openUrl(QUrl(pdfPath));
}
-将图片保存成PDF文件
voidMainWindow::picture_to_pdf()
{
QPrinterprinter_pixmap(QPrinter::HighResolution);
printer_pixmap.setPageSize(QPrinter::A4); //设置纸张大小为A4
printer_pixmap.setOutputFormat(QPrinter::PdfFormat); //设置输出格式为pdf
printer_pixmap.setOutputFileName("E:\\test_pixmap.pdf"); //设置输出路径
QPixmappixmap;
pixmap.load("E:\\p.png"); //获取界面的图片
QPainterpainter_pixmap;
painter_pixmap.begin(&printer_pixmap);
QRectrect=painter_pixmap.viewport();
intmultiple=rect.width()/pixmap.width();
painter_pixmap.scale(multiple,multiple);//将图像(所有要画的东西)在pdf上放大multiple-1倍
painter_pixmap.drawPixmap(0,0,pixmap); //画图
painter_pixmap.end();
}
-将文本保存成PDF文件
voidMainWindow::text_to_pdf()
{
QFilepdfFile("d:\\test.pdf");//输出文件名
if(!pdfFile.open(QIODevice::WriteOnly))
{
QMessageBox::warning(this,tr("writeFile"),tr("Cannotopenfile:\n%1").arg("d:\\test.pdf"));
return;
}
QPdfWriter*pdfWriter=newQPdfWriter(&pdfFile); //实例化QPdfWriter可以设置PDF文件的一些参数
pdfWriter->setPageSize(QPagedPaintDevice::A4); //设置纸张为A4纸
pdfWriter->setResolution(QPrinter::ScreenResolution); //设置分辨率屏幕分辨率打印机分辨率高分辨率
pdfWriter->setPageMargins(QMarginsF(40,40,40,40)); //设置页边距顺序是:左上右下
QPainter*pdfPainter=newQPainter(pdfWriter); //qt绘制工具
//设置标题
QTextOptionoption(Qt::AlignCenter); //标题居中显示
option.setWrapMode(QTextOption::WordWrap); //标题自动换行
//设置标题字体需要使用QT的QFont
QFontfont;
font.setFamily("MicrosoftYaHei"); //设置字体微软雅黑、宋体之类的
font.setPointSize(22); //设置字体大小
//font.setItalic(true);//斜体
//font.setUnderline(true);//设置下划线
font.setBold(true); //加粗
pdfPainter->setFont(font);
pdfPainter->drawText(QRect(3000,0,2100,450),QString::fromLocal8Bit("标题"),option);//距离左边3000,上面0,标题字宽度2100,标题字高450(如果字显示不全,可以适当调整)
pdfWriter->newPage(); //换一页
//设置内容
option.setAlignment(Qt::AlignLeft);
font.setPointSize(14); //字体大小14
pdfPainter->setFont(font);
pdfPainter->drawText(QRect(500,20,8000,300),
QString::fromLocal8Bit("我是第一行我是第一行我是第一行我是第一行我是第一行我是第一行我是第一"));
pdfPainter->drawText(QRect(0,320,8500,300),
QString::fromLocal8Bit("我是后续我是后续我是后续我是后续我是后续我是后续我是后续我是后续我是后续"),option);
pdfPainter->drawText(QRect(0,620,8500,300),
QString::fromLocal8Bit("我是后续我是后续我是后续我是后续我是后续我是后续我是后续我是后续我是后续"),option);
deletepdfPainter;
deletepdfWriter;
pdfFile.close();
QDesktopServices::openUrl(QUrl::fromLocalFile("d:\\test.pdf"));
}
-将网页保存成PDF文件
voidMainWindow::html_to_pdf()
{
QFilepdfFile("d:\\test.pdf");//输出文件名
if(!pdfFile.open(QIODevice::WriteOnly))
{
QMessageBox::warning(this,tr("writeFile"),tr("Cannotopenfile:\n%1").arg("d:\\test.pdf"));
return;
}
QPdfWriter*pdfWriter=newQPdfWriter(&pdfFile); //实例化QPdfWriter可以设置PDF文件的一些参数
pdfWriter->setPageSize(QPagedPaintDevice::A4); //设置纸张为A4纸
pdfWriter->setResolution(QPrinter::ScreenResolution); //设置分辨率屏幕分辨率打印机分辨率高分辨率
pdfWriter->setPageMargins(QMarginsF(40,40,40,40));//设置页边距顺序是:左上右下
QTextDocumenttext_document;
QStringhtml=QString("border=\"6\">
");" ).append(QStringLiteral("薪资")).append("") .append(QStringLiteral("工号")).append("").append(QStringLiteral("姓名")).append(" ") .append(QStringLiteral("薪资")).append("101 102 103 123 124 125
text_document.setHtml(html);
text_document.print(pdfWriter);
text_document.end();
QDesktopServices::openUrl(QUrl::fromLocalFile("d:\\test.pdf"));
}
-生成复杂的PDF文件
voidMainWindow::complex_pdf()
{
//创建PDF文件
QStringfile_path=QApplication::applicationDirPath()+"/text.pdf";
QFilepdfFile(file_path);
pdfFile.open(QIODevice::WriteOnly);
QPdfWriter*pWriter=newQPdfWriter(&pdfFile);
pWriter->setPageSize(QPagedPaintDevice::A4);
pWriter->setResolution(300);
pWriter->setPageMargins(QMarginsF(30,30,30,30));
QPainter*pPainter=newQPainter(pWriter);
QFontfont[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);
qDebug()<<pPainter->viewport().width()<<""<<pPainter->viewport().height();
intnPDFWidth=pPainter->viewport().width();
intnPDFHeight=pPainter->viewport().height();
//标题
inty=10;
pPainter->setFont(font[0]);
pPainter->drawText(QRect(0,y,nPDFWidth,100),Qt::AlignCenter,QString("这是第一个PDF文档"));
//画两条横线
y+=140;
pPainter->setPen(QPen(QBrush(QColor(0,0,0)),5));
pPainter->drawLine(0,y,nPDFWidth,y);
pPainter->drawLine(0,y+18,nPDFWidth,y+18);
//添加文字
y+=60;
pPainter->setFont(font[2]);
pPainter->drawText(QRect(100,y,nPDFWidth/2,70),Qt::AlignVCenter|Qt::AlignLeft,QString("器件型号:YT-CR810"));
pPainter->setFont(font[2]);
pPainter->drawText(QRect(nPDFWidth/2+100,y,nPDFWidth/2-100,70),Qt::AlignVCenter|Qt::AlignLeft,QString("器件编号:YT-CR810"));
y+=90;
pPainter->setFont(font[2]);
pPainter->drawText(QRect(100,y,nPDFWidth/2,70),Qt::AlignVCenter|Qt::AlignLeft,QString("装车车号:YT-CR810"));
pPainter->setFont(font[2]);
pPainter->drawText(QRect(nPDFWidth/2+100,y,nPDFWidth/2-100,70),Qt::AlignVCenter|Qt::AlignLeft,QString("实验日期:YT-CR810"));
//小标题
y+=110;
pPainter->setFont(font[1]);
pPainter->drawText(QRect(0,y,nPDFWidth,80),Qt::AlignVCenter|Qt::AlignLeft,"减振器标准参数");
//画表格
y+=120;
QStringListlist;
list<<"速度"<<"压力"<<"拉力"<<"阻尼系数"<<"不对称率"<<"正允差"<<"负允差";
list<<"12.5m/s"<<"17KN"<<"15KN"<<"1.3kNs/m"<<"12%"<<"13%"<<"14%";
pdfDrawForm(pPainter,y,0,2,7,100,font[3],list);
y+=260;
pPainter->setFont(font[1]);
pPainter->drawText(QRect(0,y,nPDFWidth,80),Qt::AlignVCenter|Qt::AlignLeft,"示功图");
//插入图片
y+=100;
intimageBorder=150;
QPixmappixmap=QPixmap::grabWidget(this,this->rect());
floatx=(float)(nPDFWidth-imageBorder*2)/(float)pixmap.width();
pixmap=pixmap.scaled(nPDFWidth-imageBorder*2,x*pixmap.height(),Qt::IgnoreAspectRatio);
pPainter->drawPixmap(imageBorder,y,pixmap);
y+=pixmap.height()+90;
pPainter->setFont(font[1]);
pPainter->drawText(QRect(0,y,nPDFWidth,80),Qt::AlignVCenter|Qt::AlignLeft,"减震器测试结果");
y+=120;
list.clear();
list<<"拉伸行程"<<"0.00mm"<<"压缩行程"<<"0.00mm"<<"最大速度"<<"0.000m/s"<<"阻尼系数"<<"0.00kNs/m"
<<"最大压力"<<"0.00kN"<<"压力偏差"<<"0.00%"<<"最大拉力"<<"0.00kN"<<"拉力偏差"<<"0.00%"
<<"不对称率"<<"0.00%"<<"运动时间"<<"5S"<<"实验结果"<<"100%"<<"曲线结论"<<"100";
pdfDrawForm(pPainter,y,0,3,8,100,font[3],list);
pPainter->setFont(font[4]);
pPainter->drawText(QRect(50,nPDFHeight,nPDFWidth/3,80),Qt::AlignVCenter|Qt::AlignLeft,QString("试验员:张三"));
pPainter->drawText(QRect(nPDFWidth/3+50,nPDFHeight,nPDFWidth/3,80),Qt::AlignVCenter|Qt::AlignLeft,QString("检查员签字:"));
pPainter->drawText(QRect(nPDFWidth/3*2,nPDFHeight,nPDFWidth/3,80),Qt::AlignVCenter|Qt::AlignLeft,QString("签字日期:"));
//绘制完毕
deletepPainter;
deletepWriter;
pdfFile.close();
//通过其他PDF阅读器来打开PDF
QDesktopServices::openUrl(QUrl::fromLocalFile(file_path));
}
voidMainWindow::pdfDrawForm(QPainter*paint,inty,inthorzBorder,introw,intcolumn,intunitHeight,QFont&font,QStringList&list)
{
paint->setFont(font);
paint->setPen(QPen(QBrush(QColor(0,0,0)),2));
intWidth=paint->viewport().width()-horzBorder*2;
intunitWidth=Width/column;
for(inti=0;i<row;i++){
intx=horzBorder;
for(intj=0;j<column;j++){
paint->drawText(QRect(x,y,unitWidth,unitHeight),Qt::AlignCenter,list[i*column+j]);
paint->drawRect(QRect(x,y,unitWidth,unitHeight));
x+=unitWidth;
}
y+=unitHeight;
}
}
-创建PDF文件
voidMainWindow::create_pdf()
{
QPrinterprinter;
QFileDialogfileDialog;
QStringstr=QFileDialog::getSaveFileName(this,tr("SaveText"),"/",tr("TextFiles(*.pdf)"));
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setPageSize(QPrinter::A4);
printer.setOutputFileName(str);
textEdit->print(&printer);
}
-显示PDF文件的打印预览
voidMainWindow::PrintPreview()
{
QPrinterprinter;
QPrintPreviewDialogpreviewDialog(&printer,this);
connect(&previewDialog,SIGNAL(paintRequested(QPrinter*)),this,SLOT(Preview(QPrinter*)));
previewDialog.exec();//打印对话框显示,paintRequest触发
}
voidMainWindow::Preview(QPrinter*printer)
{
textEdit->print(printer);
}
参考资料:
QPrinter方式导出PDF
https://blog.csdn.net/Joker__123/article/details/124154190?spm=1001.2014.3001.5501
QPdfWriter方式导出PDF
https://blog.csdn.net/Joker__123/article/details/124178511?spm=1001.2014.3001.5501
QTextDocument方式导出PDF
https://blog.csdn.net/Joker__123/article/details/124199830
QT将图片、文本、网页生成PDF
https://blog.csdn.net/sunatmine/article/details/110489151
https://blog.csdn.net/xiao123456bin/article/details/114579029
https://www.pianshen.com/article/46371132328/
QT生成复杂的PDF文件
https://blog.csdn.net/yuchunhai321/article/details/120566783
QT实现打印预览及生成Pdf功能
https://martinkeith.blog.csdn.net/article/details/104061822?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.pc_relevant_default&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.pc_relevant_default&utm_relevant_index=2
公众号二维码
End:如果有兴趣了解量化交易、数据分析和互联网+的实用技术,欢迎关注本公众号