Skip to content

Instantly share code, notes, and snippets.

@jcfr
Created February 7, 2022 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcfr/05c35f60d120e786b1bfc376ac2cbdd9 to your computer and use it in GitHub Desktop.
Save jcfr/05c35f60d120e786b1bfc376ac2cbdd9 to your computer and use it in GitHub Desktop.
@staticmethod
def convertHtmlToPdf(htmlFilePath, pdfFilePath):
"""
Convert HTML file to PDF.
It returns the tuple ``(success, errorString)``.
.. note::
Conversion from HTML to PDF is performed using :func:`slicer.qSlicerWebWidget.printToPdf()`
that internally leverage the corresponding API provided by the Qt class ``QWebEnginePage``.
"""
webWidget = slicer.qSlicerWebWidget()
printPdfLoop = qt.QEventLoop()
errorString = None
def loadFinished(ok):
if not ok:
nonlocal errorString
errorString = 'Failed to load URL %s' % webWidget.url
printPdfLoop.exit(slicer.util.EXIT_FAILURE)
return
layout = qt.QPageLayout(qt.QPageSize(qt.QPageSize.Letter), qt.QPageLayout.Portrait, qt.QMarginsF())
webWidget.printToPdf(pdfFilePath, layout)
def pdfPrintingFinished(filePath, success):
if not success:
nonlocal errorString
errorString = f'Failed to print {filePath}'
printPdfLoop.exit(slicer.util.EXIT_SUCCESS if success else slicer.util.EXIT_FAILURE)
webWidget.connect('loadFinished(bool)', loadFinished)
webWidget.connect('pdfPrintingFinished(QString,bool)', pdfPrintingFinished)
webWidget.setUrl(qt.QUrl.fromLocalFile(htmlFilePath).toString())
return printPdfLoop.exec() == slicer.util.EXIT_SUCCESS, errorString
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment