MrSSS16
MrSSS16

Reputation: 473

Qt output pdf is empty

I used the most simplistic code 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 and cant be opened. I have no clue as to what aspect of the code is wrong OR possibly outdated ? I though it might be a permission issue, but the pdf file is being created though. Below is the code is used:

UPDATE FULL CODE

 #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;

}

Upvotes: 1

Views: 850

Answers (1)

L&#225;szl&#243; Papp
L&#225;szl&#243; Papp

Reputation: 53165

Your application is meant to crash as you are trying to instantiate a core application with GUI control, like QTextDocument. This code works fine for me:

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

Build and Run

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

Upvotes: 3

Related Questions