【问题标题】:Qt output pdf is emptyQt输出pdf为空
【发布时间】:2015-02-24 17:00:54
【问题描述】:

我使用了我在 Qt pdf 打印上能找到的最简单的代码,它运行良好,没有任何错误。但是,当我尝试打开生成的 pdf 时,它抱怨 pdf 为空且无法打开。我不知道代码的哪个方面是错误的或可能已过时?我虽然可能是权限问题,但正在创建 pdf 文件。下面是使用的代码:

更新完整代码

 #include <QCoreApplication>
 #include <QPrinter>
 #include <QTextDocument> 

int main(int argc, char *argv[])
{
 QCoreApplication a(argc, argv);

 QTextDocument doc;
 doc.setHtml( "<p>A QTextDocument can be used to present formatted text "
              "in a nice way.</p>"
              "<p align=center>It can be <b>formatted</b> "
              "<font size=+2>in</font> <i>different</i> ways.</p>"
              "<p>The text can be really long and contain many "
              "paragraphs. It is properly wrapped and such...</p>" );
  QPrinter printer;
  printer.setOutputFileName("../out.pdf");
  printer.setOutputFormat(QPrinter::PdfFormat);
  doc.print(&printer);
  printer.newPage();

 return 0;

}

【问题讨论】:

  • I could find on Qt pdf printing, and it works fine without any errors. However when I attempt to open the produced pdf it complains that the pdf is empty -> 这很矛盾。另外,this 示例对您有用吗?
  • 另外,您的示例是错误的,因为它在打印之前没有创建 QCoreApplication 实例。

标签: c++ qt pdf qtgui qprinter


【解决方案1】:

当您尝试使用 GUI 控件(例如 QTextDocument)实例化 core 应用程序时,您的应用程序会崩溃。这段代码对我来说很好用:

main.cpp

#include <QGuiApplication>
#include <QPrinter>
#include <QTextDocument> 

int main(int argc, char **argv)
{
    QGuiApplication a(argc, argv);

    QTextDocument doc;
    doc.setHtml( "<p>A QTextDocument can be used to present formatted text "
            "in a nice way.</p>"
            "<p align=center>It can be <b>formatted</b> "
            "<font size=+2>in</font> <i>different</i> ways.</p>"
            "<p>The text can be really long and contain many "
            "paragraphs. It is properly wrapped and such...</p>" );
    QPrinter printer;
    printer.setOutputFileName("out.pdf");
    printer.setOutputFormat(QPrinter::PdfFormat);
    doc.print(&printer);
    printer.newPage();

    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT += printsupport
SOURCES += main.cpp

构建并运行

qmake && ./main && ./main && okular out.pdf

【讨论】:

  • 哦,我明白了,现在很有意义。非常感谢,就像一个魅力:)
  • @user1477957:不用担心。顺便说一句,以防万一:如果您没有意识到,网站上还有一个投票功能。您的历史记录中似乎有 19 个问题和零票。
猜你喜欢
  • 2013-12-22
  • 1970-01-01
  • 2018-12-30
  • 1970-01-01
  • 1970-01-01
  • 2013-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多