如何从 QGraphicsScene 生成带有可复制文本的 pdf 文件?
我的代码通过将 QGraphicsScene 内容渲染到正确初始化的 QPrinter 上来生成 pdf。 在处理应用程序时,可以编辑此类文本,将其复制到剪贴板等。如何从 QGraphicsScene 生成 pdf,其中也可以复制我的文本字符串,或者这是不可能的,我需要为此类任务创建 QTextDocument?
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();
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看来您必须使用 QTextDocument 并将内容编写为 HTML。请参阅我的回答和我对问题的评论:Qt4:将 SQL 表打印为 PDF
编辑:我进行了一次调试会话(在 Windows7 中使用 Visual Studio)并进入场景 -> 渲染。在文件 qgraphicsitem.cpp 中的某个步骤 QGraphicsTextItem::paint(...) (Qt 4.8.0 中的第 10067 行)被调用,您可以在其中看到文本项存储在 QTextDocument 中。
我的结论(来自所引用的问题):文本作为文本打印到 pdf 文档中,这意味着您无法选择或复制文本只是 pdf 查看器的产物。如果包含 pdftotext 的 xpdf 适用于您的平台,您可以轻松验证这一点。
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.