Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to produce pdf files from QGraphicsScene with copyable text?

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();
like image 560
Mykyta Kozlov Avatar asked Dec 12 '11 13:12

Mykyta Kozlov


1 Answers

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.

like image 97
hmuelner Avatar answered Oct 31 '22 11:10

hmuelner