How to convert html into PDF by Python in Single page

  Kiến thức lập trình

how can i convert html to single page pdf and set pdf page width to 8cm and height equals to html height?

i write this example code but it set A4 page!

import os
import sys
from PyQt5 import QtWidgets
from PyQt5.QtCore import QUrl, QMarginsF
from PyQt5.QtGui import QPageLayout, QPageSize
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    loader = QWebEngineView()
    loader.setZoomFactor(1)
    layout = QPageLayout()
    layout.setPageSize(QPageSize(QPageSize.A4Extra))
    layout.setOrientation(QPageLayout.Portrait)
    layout.setMargins(QMarginsF(15, 15, 15, 15))

    pdf_name = os.environ.get('pdf_name')
    html_name = os.environ.get('html_name')

    file_path = os.path.abspath(os.path.join(os.getcwd(), "tool/files/" + html_name))


    def emit_pdf(finished):
        file_path1 = os.path.abspath(os.path.join(os.getcwd(), "tool/files/temp", pdf_name))
        loader.page().printToPdf(file_path1, pageLayout=layout)


    loader.load(QUrl.fromLocalFile(file_path))
    loader.page().pdfPrintingFinished.connect(lambda *args: QApplication.exit())
    loader.loadFinished.connect(emit_pdf)
    sys.exit(app.exec())

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT