Qt中如何讓圖片、文本、HTML或者其餘形式的內容生成pdf呢?主要利用QPrinter來實現,QPrinter不止能夠操做打印機來打印紙張文件,而且能夠將文件保存至磁盤,存儲爲pdf格式的文件。html
圖片生成pdf
代碼以下:
QPrinter printer_pixmap(QPrinter::HighResolution);
printer_pixmap.setPageSize(QPrinter::A4); //設置紙張大小爲A4
printer_pixmap.setOutputFormat(QPrinter::PdfFormat); //設置輸出格式爲pdf
printer_pixmap.setOutputFileName("E:\\test_pixmap.pdf"); //設置輸出路徑
QPixmap pixmap = QPixmap::grabWidget(main_widget, main_widget->rect()); //獲取界面的圖片
QPainter painter_pixmap;
painter_pixmap.begin(&printer_pixmap);
QRect rect = painter_pixmap.viewport();
int multiple = rect.width()/pixmap.width();
painter_pixmap.scale(multiple, multiple); //將圖像(全部要畫的東西)在pdf上放大multiple-1倍
painter_pixmap.drawPixmap(0, 0, pixmap); //畫圖
painter_pixmap.end();
文本生成pdf
代碼以下:
QPrinter printer_text;
printer_text.setOutputFormat(QPrinter::PdfFormat);
printer_text.setOutputFileName("E:\\test_text.pdf");
QPainter painter_text;
painter_text.begin(&printer_text);
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);
painter_text.drawText(point, message);
message.clear();
}
//printer_text.newPage(); //生成新的一頁,可繼續插入
painter_text.end();
QStringList title;
title.push_back(QStringLiteral("名稱"));
title.push_back(QStringLiteral("修改日期"));
title.push_back(QStringLiteral("類型"));
title.push_back(QStringLiteral("大小"));
QPrinter printer_html;
printer_html.setPageSize(QPrinter::A4);
printer_html.setOutputFormat(QPrinter::PdfFormat);
printer_html.setOutputFileName("E:\\test_html.pdf");
QTextDocument text_document;
text_document.setHtml(html);
text_document.print(&printer_html);
text_document.end();
注:
技術在於交流、溝通,轉載請註明出處並保持做品的完整性。