qt生成pdf(用图片qgrabwidget抓取图片生成PDF;用文字生成pdf)

来源:互联网 发布:java转json忽略字段 编辑:程序博客网 时间:2024/05/16 08:17

1.用图片生成PDF:

 QPrinter printerPixmap(QPrinter::HighResolution);        printerPixmap.setPageSize(QPrinter::A4);  //设置纸张大小为A4        printerPixmap.setOutputFormat(QPrinter::PdfFormat);  //设置输出格式为pdf        QString currentDateTime =QDateTime::currentDateTime().toString("_yyyyMMddhhmm");        QString pdfPath=QDir::currentPath()+"/outPDF/"+sourceDir.dirName()+currentDateTime+".pdf";        printerPixmap.setOutputFileName(pdfPath);        QPixmap pixmap = QPixmap::grabWidget(report);  //获取界面的图片        QPainter painterPixmap;        painterPixmap.begin(&printerPixmap);        QRect rect = painterPixmap.viewport();        int multiple = rect.width() / pixmap.width();        painterPixmap.scale(multiple, multiple); //将图像(所有要画的东西)在pdf上放大multiple-1倍        painterPixmap.drawPixmap(0, 0, pixmap);  //画图        painterPixmap.end();

report是自定义类的对象。

2.用文字生成PDF

 QPrinter printerText;      printerText.setOutputFormat(QPrinter::PdfFormat);      printerText.setOutputFileName("E:\\test_text.pdf");      QPainter painterText;      painterText.begin(&printerText);      QDateTime current_date_time = QDateTime::currentDateTime();      QString current_date = current_date_time.toString("yyyy-MM-dd hh:mm:ss ddd");      QPoint point(10, 10);      for (int i = 1; i <= 5; i++)      {          QString message = QString("%1          %2          %3").arg(QString::number(i)).arg(current_date).arg(QStringLiteral("北京"));          int y = point.y();          point.setY(y + 20);          painterText.drawText(point, message);          message.clear();      }      //printer_text.newPage();  //生成新的一页,可继续插入      painterText.end();  
原创粉丝点击