用户的需求真的是千奇百怪,刚做完不同页面横向纵向排版的需求,又来个需要图片转pdf的需求,提供静态函数直接使用。 经过这么些年的社会的毒打,我的原则是:用户是上帝和大爷,尽量站在用户的角度换位思考,只要是合理或者基本合理的需求,甚至说只要不是太过分,给钱就干。
接到这个需求的时候,第一时间想到的就是用QPainter绘制图片到打印机对象,之前就用QPainter绘制了200多个自定义控件,对于QPainter如何绘制,心中早有代码自动生成了,现在看到真实世界的很多东西,尤其是图形,都自动在脑海中转成了代码,比如公交车上的路线图,到某个站点自动点亮。既然QPrinter支持QPainter绘制,这两者结合就是对程序员的绘制功底要求高,熟悉了以后绘制起来还是非常顺手的,因为思路和方法完全一样。
在封装的本函数中,可以直接传入图片文件名称,需要保存的文件名,如果保存的文件名为空,则取同名文件,就拓展名格式不一样,还可以传入资源文件中的图片,可以设置如何缩放,是拉伸填充还是等比例缩放等。
体验地址:http://pan.baidu.com/s/1eeL5MTz0rifwtVLegRpkoQ 提取码:erxm 文件名:bin_dataout.zip
国内站点:https://gitee.com/feiyangqingyun
国际站点:https://github.com/feiyangqingyun
void DataOther::toPdf(const QPixmap &pixmap, const QString &fileName, int scale) { QPrinter printer(QPrinter::HighResolution); if (scale > 1) { printer.setResolution(96); } printer.setFullPage(false); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(fileName); #if (QT_VERSION >= QT_VERSION_CHECK(5,3,0)) printer.setPageSize(QPageSize(QPageSize::A4)); printer.setPageOrientation(QPageLayout::Portrait); #else printer.setPaperSize(QPrinter::A4); printer.setOrientation(QPrinter::Portrait); #endif //调整图片大小比如等比例缩放拉伸填充等 QRectF rect = printer.pageRect(QPrinter::DevicePixel); QPixmap pix = pixmap; //保存原图看下效果 #if 0 QString file = fileName; file.replace("pdf", "png"); pix.save(file, "png"); #endif if (scale == 0) { //pix = pix.scaled(rect.width(), rect.height(), Qt::KeepAspectRatio, Qt::FastTransformation); pix = pix.scaled(rect.width(), rect.height(), Qt::KeepAspectRatio, Qt::SmoothTransformation); } else if (scale == 1) { pix = pix.scaled(rect.width(), rect.height()); } QPainter painter; painter.begin(&printer); int x = 0; int y = 0; //图片宽度小于绘制区域宽度没有缩放处理过的图片 才需要按照比例自动居中绘制 if (pixmap.width() < rect.width() && scale > 1) { x = rect.center().x() - pix.width() / 2; //y = rect.center().y() - pix.height() / 2; } painter.drawPixmap(QPoint(x, y), pix); painter.end(); } void DataOther::widgetToPdf(QWidget *widget, const QString &fileName, int scale) { #if (QT_VERSION >= QT_VERSION_CHECK(5,0,0)) QPixmap pixmap = QApplication::primaryScreen()->grabWindow(widget->winId()); #else QPixmap pixmap = QPixmap::grabWindow(widget->winId()); #endif toPdf(pixmap, fileName, scale); } QString DataOther::imageToPdf(const QString &imageFile, const QString &pdfFile, int scale) { //为空则同名文件 QString fileName = pdfFile; if (fileName.isEmpty()) { fileName = imageFile; fileName.replace("." + QFileInfo(imageFile).suffix(), ".pdf"); } //资源文件则当前目录下 if (imageFile.startsWith(":/")) { fileName = qApp->applicationDirPath() + "/" + QFileInfo(imageFile).baseName() + ".pdf"; } toPdf(QPixmap(imageFile), fileName, scale); return fileName; }