下面的方式使用HTML进行排版,然后打印HTML
// 打印HTML到打印机
void printhtmltoPrinter(QWidget * parent, const QString & html)
{
QPrinter printer;
QPrintDialog printDialog(&printer, parent);
if (printDialog.exec()) {
QTextDocument textDocument;
textDocument.setHtml(html);
textDocument.print(&printer);
}
}
void QMyPrintDialog::printhtmltoPdf(const QString & html)
{
/*
* QT: windows system path
* QDesktopServices::storageLocation(QDesktopServices::DesktopLocation)
* QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation)
* QDesktopServices::storageLocation(QDesktopServices::HomeLocation)
* QDesktopServices::storageLocation(QDesktopServices::ApplicationsLocation)
* QDesktopServices::storageLocation(QDesktopServices::TempLocation)
*/
QString filename = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
filename += "\\default.pdf";
filename = QFileDialog::getSaveFileName(this, "Save File", filename, "Adobe PDF Files (*.pdf)");
if (filename.trimmed() == "") {
return;
}
QPrinter printer;
printer.setPageSize(QPrinter::A4);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(filename);
QTextDocument textDocument;
textDocument.setHtml(html);
textDocument.print(&printer);
}
void printData(QWidget * parent)
{
QStringList entries;
entries.push_back("ZhanSan:I am zhanSan");
entries.push_back("LiSi:I am LiSi");
entries.push_back("WangWu:I am WangWu");
QString html;
html += "This is a DEMO
";
html += "";
foreach (QString entry, entries) {
QStringList fields = entry.split(":");
QString title = Qt::escape(fields[0]);
QString body = Qt::escape(fields[1]);
html += "\n" "" "" + title + "\n " + body + "\n | |
\n
\n"; }
printhtmltoPrinter(parent, html);
}