Does WebWidget's printToPdf work on Mac?

Hi. I would like to know if this script to create a pdfReport with a webwidget works on Mac (it does work on Windows):

#get/create directories/paths
import os

desktopPath = os.path.join(os.path.expanduser("~"), "Desktop")
reportFolderPath = os.path.join(desktopPath, "ReportFolder")

if not os.path.exists(reportFolderPath):

reportPath = os.path.join(
    reportFolderPath, "PDFReport.pdf"

import tempfile
tempFolderPath = tempfile.mkdtemp()

pdfReportPicturePath = os.path.join(
    tempFolderPath, "pdfReportPicture.png"

#load CT
import SampleData
sampleDataLogic = SampleData.SampleDataLogic()
ct = sampleDataLogic.downloadCTChest()

#take report picture
import ScreenCapture

redSliceNode = slicer.mrmlScene.GetNodeByID("vtkMRMLSliceNodeRed")

screenCaptureLogic = ScreenCapture.ScreenCaptureLogic()
view = screenCaptureLogic.viewFromNode(redSliceNode)
screenCaptureLogic.captureImageFromView(view, pdfReportPicturePath)

#create html code
_html = f"""
        <h1>Test PDF Report</h1>
        <img src="{pdfReportPicturePath}" alt="" border=3 width=300></img>

#create html file
htmlPath = os.path.join(tempFolderPath, "pdfReport.html")
file = qt.QFile(htmlPath) | qt.QIODevice.Text)

#page layout for the pdf
pageLayout = qt.QPageLayout(
    qt.QMarginsF(15, 15, 0, 15),

#create webwidget, load html page, print pdf and open it
webWidget = slicer.qSlicerWebWidget()

def onWebWidgetLoadFinished(result):
    webWidget.printToPdf(reportPath, pageLayout)

def onWebWidgetPDFPrintingFinished(filePath, result):
    from shutil import rmtree
    rmtree(tempFolderPath, ignore_errors=True)
    # Open in PDF viewer
    print("Starting '" + reportPath + "' ...")
    # slash/backlash replacements because of active directory
    import subprocess
    subprocess.Popen([reportPath], shell=True)

webWidget.setUrl(htmlPath.replace("\\", "/"))

If it doesn’t work on Mac, do you know any workaround to make it work?


With today’s nightly it runs but the webWidget and the pdf are blank.

Changing the last line to this works:

webWidget.url = "file://" + htmlPath.replace("\\", "/")
1 Like

Thanks @pieper.

Is there any function I can call to check in what OS Slicer is running on?

Is there any function I can call to check in what OS Slicer is running on?

You don’t need to do anything different based on the os - the file:// should also work on windows.

In my PC it doesn’t work with that change. Here is the result.

What is the return of this function on mac?

Looks like file:/// is the right thing - it works on mac and should also work on windows.

But if you really need it:

1 Like

There is no need to implement such low-level logic. You can simply use the QUrl class to get URL from local file path:

>>> qt.QUrl.fromLocalFile(r"c:\tmp").toString()
1 Like