Chinaunix首页 | 论坛 | 博客
  • 博客访问: 132950
  • 博文数量: 22
  • 博客积分: 698
  • 博客等级: 上士
  • 技术积分: 265
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-17 09:53
文章分类
文章存档

2012年(2)

2011年(15)

2010年(5)

我的朋友

分类: WINDOWS

2010-12-28 17:37:12

最近在使用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);
}
阅读(10158) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2011-01-01 19:47:18

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com