Python中的PyQt5 PDF边框间距

7gyucuyw  于 2023-06-04  发布在  Python
关注(0)|答案(1)|浏览(155)

我已经使用PyQt5生成了一个PDF,它工作得非常好。我只是希望有一个边界间距,无法做到这一点使用布局。下面是代码

from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets

    def printhtmltopdf(html_in, pdf_filename):
        app = QtWidgets.QApplication([])
        page = QtWebEngineWidgets.QWebEnginePage()

        def handle_pdfPrintingFinished(*args):
            print("finished: ", args)
            app.quit()

        def handle_loadFinished(finished):
            page.printToPdf(pdf_filename)

        page.pdfPrintingFinished.connect(handle_pdfPrintingFinished)
        page.loadFinished.connect(handle_loadFinished)

        page.setZoomFactor(1)
        page.setHtml(html_in)

        app.exec()

    printhtmltopdf(
        result,    # raw html variable
        "file.pdf",
    )

结果是,

预期结果如下,内容开头和结尾处有空格。基本上我需要有一个填充左,右,顶部和底部

任何建议将不胜感激

t2a7ltrp

t2a7ltrp1#

您可以尝试在PyQt中加载自定义CSS样式表,并将此CSS文件应用于HTML内容,从而在元素上产生所需的填充效果。

from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets

def printhtmltopdf(html_in, pdf_filename):
    app = QtWidgets.QApplication([])
    page = QtWebEngineWidgets.QWebEnginePage()

    def handle_pdfPrintingFinished(*args):
        print("finished: ", args)
        app.quit()

    def handle_loadFinished(finished):
        page.printToPdf(pdf_filename)

# added function
    def add_border_spacing():
        # Load a custom CSS style sheet with border spacing
        with open("style.css", "r") as file:
            css_content = file.read()
        page.setHtml(html_in, QtCore.QUrl().fromLocalFile(QtCore.QFileInfo("style.css").absoluteFilePath()))
        page.profile().scripts().insert(QtWebEngineWidgets.QWebEngineScript.DocumentCreation, css_content)

    page.pdfPrintingFinished.connect(handle_pdfPrintingFinished)
    page.loadFinished.connect(handle_loadFinished)

    page.setZoomFactor(1)

    add_border_spacing() # apply function

    app.exec()

printhtmltopdf(
    result, 
    "file.pdf",
)

样式CSS文件

border-spacing: 10px;
    padding: 20px;

style.css文件与Python脚本位于同一目录中。
也检查this答案。它使用javascript加载css。

相关问题