Printer.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from PySide6.QtWidgets import QDialog
  2. from PySide6.QtPrintSupport import QPrintDialog, QPrinter
  3. from PySide6.QtGui import QPainter, QPixmap, QPageSize
  4. from PySide6.QtCore import Qt
  5. import pdfkit
  6. from module import create_filename
  7. from pdf2image import convert_from_path
  8. class Print:
  9. def __init__(self, text: str) -> None:
  10. self.printer = QPrinter()
  11. self.printer.setFullPage(True)
  12. self.printer.setPageSize(QPageSize.A4)
  13. pdf = CreatorPDF(text)
  14. image = convert_from_path(pdf.get_path_to_pdf())[0].toqimage()
  15. image = QPixmap.fromImage(image)
  16. # print(self.printer.pageRect())
  17. image = image.scaledToWidth(self.printer.width(), Qt.SmoothTransformation)
  18. dialog = QPrintDialog(self.printer)
  19. if dialog.exec() == QDialog.Accepted:
  20. self.handle_paint_request(image)
  21. def handle_paint_request(self, im):
  22. painter = QPainter(self.printer)
  23. painter.drawPixmap(0, 0, im)
  24. painter.end()
  25. class CreatorPDF():
  26. def __init__(self, text_html):
  27. self.__file_name = create_filename('pdf')
  28. # self.__file_name = 'pdf.pdf'
  29. configuration = pdfkit.configuration(
  30. wkhtmltopdf="/usr/bin/wkhtmltopdf")
  31. pdfkit.from_string(text_html, self.__file_name, configuration=configuration, css=None, options={
  32. "enable-local-file-access": ""
  33. })
  34. def get_path_to_pdf(self) -> str:
  35. return self.__file_name