【问题标题】:Create a link with QPdfWriter使用 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()

【问题讨论】:

    标签: python pdf-generation pyside6


    【解决方案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 是的,你可以这样做。
    猜你喜欢
    • 2019-11-07
    • 2018-09-19
    • 1970-01-01
    • 2011-10-28
    • 2019-01-10
    • 2015-06-09
    • 1970-01-01
    • 2019-04-18
    • 2017-07-04
    相关资源
    最近更新 更多