18

My code produces pdf by rendering QGraphicsScene content onto properly initialized QPrinter. While dealing with application such text can be edited, copied into clipboard etc. How can I produce pdf from QGraphicsScene, where my text string can be also copied, or it is impossible and I need to create QTextDocument for such tasks?

QGraphicsTextItem* textItem = new QGraphicsTextItem ( text );

textItem->setPlainText ( text );
textItem->setTextInteractionFlags ( Qt::TextEditorInteraction );
textItem->setFlags( QGraphicsItem::ItemIsSelectable | textItem->flags() );

scene->addItem( textItem );

QPrinter pdfPrinter; 
pdfPrinter.setOutputFormat( QPrinter::PdfFormat );
pdfPrinter.setPaperSize( QSize(scene->width(), scene->height()), QPrinter::Point );
pdfPrinter.setFullPage(true);
pdfPrinter.setOutputFileName( path );

QPainter pdfPainter;
pdfPainter.begin( &pdfPrinter);
scene->render( &pdfPainter );
pdfPainter.end();
Mykyta Kozlov
  • 413
  • 3
  • 14
  • The [Qt spec](http://doc.qt.nokia.com/latest/qprinter.html#OutputFormat-enum) describes "searchable" text as its output. This implies that the base characters are being stored. As far as I know, whether text can be selected is more a function of the PDF *reader* than the writer. – spraff Dec 13 '11 at 10:23
  • Tried several readers including Mac OS X Preview, Adobe Acrobat X. In preview text string is selectable but clipboard gets only space symbol while copying. In Acrobat text string is not selectable at all. – Mykyta Kozlov Dec 13 '11 at 12:17
  • 1
    your code produce selectable text in PDF file. I just tried it! So I don't understand your question... – CapelliC Dec 25 '11 at 21:18
  • Unfortunately it is only selectable in mac's Preview, as i wrote before, not copyable. What pdf viewer did you use? – Mykyta Kozlov Dec 26 '11 at 10:07

1 Answers1

3

It seems that you have to use a QTextDocument and write your content as HTML. See my answer and my comments to the question: Qt4: Print a SQL table to PDF

EDIT: I did a debugging session (with Visual Studio in Windows7) and stepped into scene->render. At some step QGraphicsTextItem::paint(...) in file qgraphicsitem.cpp (line 10067 in Qt 4.8.0) gets called, where you can see that the text item is stored in a QTextDocument.

My conclusion (from the referenced question): Text is printed as text to the pdf document, which means that your inability to select or copy the text is just an artefact of your pdf viewer. If xpdf including pdftotext is available for your platform you can easily verify this.

Community
  • 1
  • 1
hmuelner
  • 8,093
  • 1
  • 28
  • 39