QPrinter PDF to QByteArray
-
I'm trying to generate a pdf file and save it in a QByteArray, later to attach and send via email. I already do this with other types of files, there is the possibility of generating a pdf with QPrinter and store in a QByteArray?
-
It is unfortunate that QPrinter does not have a file output option that takes a QIODevice* instead of a file name because that would enable using QBuffer. AFAICT the only option is to write to a file, perhaps a QTemporaryFile for neatness, and then read that into a QByteArray.
@
QByteArray pdf;
QPrinter printer;
printer.setOrientation(QPrinter::Portrait);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setPaperSize(QPrinter::A4);QTemporaryFile temp;
if (temp.open()) // causes file creation
temp.close();
printer.setOutputFileName(temp.fileName());
// paint
if (temp.open()) {
pdf = temp.readAll();
}
@ -
Hi,
If you are using Qt 5, you can try "QPdfWriter":http://qt-project.org/doc/qt-5/qpdfwriter.html with a "QBuffer":http://qt-project.org/doc/qt-5/qbuffer.html
Hope it helps
-
Thanks,
-
I did a test using the idea of ChrisW67 and strangely corrupted PDF content is the object (pdf) that stores
@
QByteArray pdf;
QPrinter printer;
printer.setOrientation(QPrinter::Portrait);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setPaperSize(QPrinter::A4);QTemporaryFile temp;
if (temp.open())
temp.close();printer.setOutputFileName(temp.fileName());
if (temp.open()) {
pdf = temp.readAll();
}
@I changed the format to postscript and to my surprise it worked perfectly. Is a bug of Qt 4.8.X with PDF files?
@
QByteArray ps;
QPrinter printer;
printer.setOrientation(QPrinter::Portrait);
printer.setOutputFormat(QPrinter::PostScriptFormat);
printer.setPaperSize(QPrinter::A4);QTemporaryFile temp;
if (temp.open())
temp.close();printer.setOutputFileName(temp.fileName());
if (temp.open()) {
ps = temp.readAll();
}
@ -
Are you painting anything between lines 11 and. 13? I do not think you will even get a blank page unless you at least create a QPainter on the printer.
-
Yes, I have a class that does the painter. As to this no problem, I just did not mention this code snippet. I opened the temporary file that is created and is correct.
-
If the temporary file contains a valid PDF the byte array should contain exactly the same bytes.
If you later manipulate the byte array as if it is a C-string you will break the data at the first zero byte.
-
Hi,
I did a simple test that can be played with the code below, and content of QByteArray is not the same file. Any way around this problem? My platform is GNU/Linux and Qt 4.8.5
@
QFile file("/home/marcelo/Documents/test.pdf");
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << "file open error";
return;
}QByteArray ba_pdf = file.readAll();
qDebug() << ba_pdf;
file.close();
@The output is:
@
"%PDF-1.4
1 0 obj
<<
/Title (þÿ)
/Creator (þÿ)
/Producer (þÿ
@ -
It's possible to read pdf file to QBytearray?