QT结合HTML打印简单应用

10290阅读 1评论2010-12-28 zhaoliping_cu
分类:WINDOWS

最近在使用QT进行打印,感觉这种方法还算可以,如果大家有什么好方法可以推荐推荐。

测试环境:Windowx XP SP2 + QT 4.4.0
下面的方式使用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);
    }
}

// 打印HTML到PDF文件
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);
}

剩余的主要工作就是根据打印格式、数据等拼接HTML串,拼接好了直接调用以上的两个函数即可打印。一下是个简单的例子:
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);
}
上一篇:QT获取Windows系统路径
下一篇:QT修改应用程序图标

文章评论