0

I have generated a PDF using PyQt5 which is working perfectly fine. Am just looking to have a border spacing, unable to do that using layouts. Below is the code,

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",
    )

Result is,

enter image description here

Expected result is as below having spaces in the beginning and end of the content. Basically i need to have a padding on left, right, top and bottom

enter image description here

Any suggestion will be appreciated

Jim Macaulay
  • 4,709
  • 4
  • 28
  • 53

1 Answers1

0

You can try to load a custom CSS style sheet in PyQt and apply this CSS file to the HTML content, resulting in the desired padding effect on elements.

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",
)

style css file

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

style.css file is located in the same directory as your Python script.

Also check this answer. It load css using javascript.

DarekD
  • 54
  • 7