使用 QPdfWriter 创建链接

Posted

技术标签:

【中文标题】使用 QPdfWriter 创建链接【英文标题】:Create a link with QPdfWriter 【发布时间】:2021-10-14 13:36:04 【问题描述】:

我正在使用 PySide6 库在 Python 中编写一个 GUI 应用程序,并且我想编写 PDF。我通常使用reportlab 库来编写PDF,但我看到PySide6 有一个QPdfWriter class。如果 PySide6 足够,我想避免对 reportlab 的额外依赖,但我看不到在 PDF 中创建链接的方法,无论是指向文档的一部分还是指向网站。

是否可以使用QPdfWriter 添加指向 PDF 的链接,还是仅支持绘图和文本?

这是一个示例,我创建了一个包含一些文本的 PDF,我想将文本转换为网页的链接。

from PySide6.QtGui import QPdfWriter, QPainter, QPageSize
from PySide6.QtWidgets import QApplication

app = QApplication()
pdf = QPdfWriter('example.pdf')
pdf.setPageSize(QPageSize.Letter)
painter = QPainter(pdf)
painter.drawText(painter.window().width()//2,
                 painter.window().height()//2,
                 'https://donkirkby.github.io')
painter.end()

【问题讨论】:

【参考方案1】:

一种可能的解决方案是使用 QTextDocument:

from PySide6.QtGui import QGuiApplication, QPageSize, QPdfWriter, QTextDocument

app = QGuiApplication()

html = "<a href='https://donkirkby.github.io'>https://donkirkby.github.io</a>"


pdf = QPdfWriter("example.pdf")
pdf.setPageSize(QPageSize.Letter)

document = QTextDocument()
document.setHtml(html)
document.print_(pdf)

您可以使用 QWebEnginePage,它在 Qt6 中尚不可用,因此应使用 PySide2 作为示例:

from PySide2.QtWidgets import QApplication
from PySide2.QtWebEngineWidgets import QWebEnginePage

app = QApplication()

html = """
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
        .container 
            position: absolute;
            top: 50%;
            left: 50%;
            -moz-transform: translateX(-50%) translateY(-50%);
            -webkit-transform: translateX(-50%) translateY(-50%);
            transform: translateX(-50%) translateY(-50%);
        
    </style>
  </head>
  <body>
    <div class="container">
        <a href='https://donkirkby.github.io'>https://donkirkby.github.io</a>
    </div>
  </body>
</html>
"""

page = QWebEnginePage()


def handle_load_finished():
    page.printToPdf("example.pdf")


def handle_pdf_printing_finished():
    app.quit()


page.loadFinished.connect(handle_load_finished)
page.pdfPrintingFinished.connect(handle_pdf_printing_finished)

page.setHtml(html)


app.exec_()

【讨论】:

有趣!我可以在 PDF 的同一页面上使用 QPainterQTextDocument 吗? @DonKirkby 是的,你可以这样做。

以上是关于使用 QPdfWriter 创建链接的主要内容,如果未能解决你的问题,请参考以下文章

Php fopen或fwrite使用unicode创建文本

PHP 'fwrite' 不会使用变量

linux下php fwrite无法写入文件怎么回事呀

matlab中使用fwrite将1到10写入文本文件中,再用fread读取该文本文件中的数据,怎么写程序

Linux read/write fread/fwrite两者区别

使用 fwrite 时使文件环绕