|
| 1 | +"""Export to HTML after loading in a headless browser""" |
| 2 | + |
| 3 | +# Copyright (c) IPython Development Team. |
| 4 | +# Distributed under the terms of the Modified BSD License. |
| 5 | + |
| 6 | +import asyncio |
| 7 | +import concurrent.futures |
| 8 | +import os |
| 9 | +import subprocess |
| 10 | +import sys |
| 11 | +import tempfile |
| 12 | +from importlib import util as importlib_util |
| 13 | + |
| 14 | +from traitlets import Bool, List, Unicode, default |
| 15 | + |
| 16 | +from .html import HTMLExporter |
| 17 | + |
| 18 | +PLAYWRIGHT_INSTALLED = importlib_util.find_spec("playwright") is not None |
| 19 | +IS_WINDOWS = os.name == "nt" |
| 20 | + |
| 21 | +__all__ = ("WebHTMLExporter",) |
| 22 | + |
| 23 | +class WebHTMLExporter(HTMLExporter): |
| 24 | + """Writer designed to write to HTML files after rendering in a browser. |
| 25 | +
|
| 26 | + This inherits from :class:`HTMLExporter`. It creates the HTML using the |
| 27 | + template machinery, and then run playwright to load in a browser, saving |
| 28 | + the resulting page. |
| 29 | + """ |
| 30 | + |
| 31 | + export_from_notebook = "HTML via Browser" |
| 32 | + |
| 33 | + allow_chromium_download = Bool( |
| 34 | + False, |
| 35 | + help="Whether to allow downloading Chromium if no suitable version is found on the system.", |
| 36 | + ).tag(config=True) |
| 37 | + |
| 38 | + @default("file_extension") |
| 39 | + def _file_extension_default(self): |
| 40 | + return ".html" |
| 41 | + |
| 42 | + @default("template_name") |
| 43 | + def _template_name_default(self): |
| 44 | + return "webhtml" |
| 45 | + |
| 46 | + disable_sandbox = Bool( |
| 47 | + False, |
| 48 | + help=""" |
| 49 | + Disable chromium security sandbox when converting to PDF. |
| 50 | +
|
| 51 | + WARNING: This could cause arbitrary code execution in specific circumstances, |
| 52 | + where JS in your notebook can execute serverside code! Please use with |
| 53 | + caution. |
| 54 | +
|
| 55 | + ``https://github.com/puppeteer/puppeteer/blob/main@%7B2020-12-14T17:22:24Z%7D/docs/troubleshooting.md#setting-up-chrome-linux-sandbox`` |
| 56 | + has more information. |
| 57 | +
|
| 58 | + This is required for webhtml to work inside most container environments. |
| 59 | + """, |
| 60 | + ).tag(config=True) |
| 61 | + |
| 62 | + browser_args = List( |
| 63 | + Unicode(), |
| 64 | + help=""" |
| 65 | + Additional arguments to pass to the browser rendering to PDF. |
| 66 | +
|
| 67 | + These arguments will be passed directly to the browser launch method |
| 68 | + and can be used to customize browser behavior beyond the default settings. |
| 69 | + """, |
| 70 | + ).tag(config=True) |
| 71 | + |
| 72 | + def run_playwright(self, html, _postprocess = None): |
| 73 | + """Run playwright.""" |
| 74 | + |
| 75 | + async def main(temp_file): |
| 76 | + """Run main playwright script.""" |
| 77 | + |
| 78 | + try: |
| 79 | + from playwright.async_api import ( # type: ignore[import-not-found] # noqa: PLC0415, |
| 80 | + async_playwright, |
| 81 | + ) |
| 82 | + except ModuleNotFoundError as e: |
| 83 | + msg = ( |
| 84 | + "Playwright is not installed to support Web PDF conversion. " |
| 85 | + "Please install `nbconvert[webpdf]` to enable." |
| 86 | + ) |
| 87 | + raise RuntimeError(msg) from e |
| 88 | + |
| 89 | + if self.allow_chromium_download: |
| 90 | + cmd = [sys.executable, "-m", "playwright", "install", "chromium"] |
| 91 | + subprocess.check_call(cmd) # noqa: S603 |
| 92 | + |
| 93 | + playwright = await async_playwright().start() |
| 94 | + chromium = playwright.chromium |
| 95 | + |
| 96 | + args = self.browser_args |
| 97 | + if self.disable_sandbox: |
| 98 | + args.append("--no-sandbox") |
| 99 | + |
| 100 | + try: |
| 101 | + browser = await chromium.launch( |
| 102 | + handle_sigint=False, handle_sigterm=False, handle_sighup=False, args=args |
| 103 | + ) |
| 104 | + except Exception as e: |
| 105 | + msg = ( |
| 106 | + "No suitable chromium executable found on the system. " |
| 107 | + "Please use '--allow-chromium-download' to allow downloading one," |
| 108 | + "or install it using `playwright install chromium`." |
| 109 | + ) |
| 110 | + await playwright.stop() |
| 111 | + raise RuntimeError(msg) from e |
| 112 | + |
| 113 | + page = await browser.new_page() |
| 114 | + await page.emulate_media(media="print") |
| 115 | + await page.wait_for_timeout(100) |
| 116 | + await page.goto(f"file://{temp_file.name}", wait_until="networkidle") |
| 117 | + await page.wait_for_timeout(100) |
| 118 | + |
| 119 | + data = await page.content() |
| 120 | + |
| 121 | + if _postprocess: |
| 122 | + # Reuse this code for webpdf |
| 123 | + data = await _postprocess(page, browser, playwright) |
| 124 | + |
| 125 | + await browser.close() |
| 126 | + await playwright.stop() |
| 127 | + return data |
| 128 | + |
| 129 | + pool = concurrent.futures.ThreadPoolExecutor() |
| 130 | + # Create a temporary file to pass the HTML code to Chromium: |
| 131 | + # Unfortunately, tempfile on Windows does not allow for an already open |
| 132 | + # file to be opened by a separate process. So we must close it first |
| 133 | + # before calling Chromium. We also specify delete=False to ensure the |
| 134 | + # file is not deleted after closing (the default behavior). |
| 135 | + temp_file = tempfile.NamedTemporaryFile( # noqa: SIM115 |
| 136 | + suffix=".html", delete=False |
| 137 | + ) |
| 138 | + with temp_file: |
| 139 | + if isinstance(html, str): |
| 140 | + temp_file.write(html.encode("utf-8")) |
| 141 | + else: |
| 142 | + temp_file.write(html) |
| 143 | + try: |
| 144 | + html_data = pool.submit(asyncio.run, main(temp_file)).result() |
| 145 | + finally: |
| 146 | + # Ensure the file is deleted even if playwright raises an exception |
| 147 | + os.unlink(temp_file.name) |
| 148 | + return html_data |
| 149 | + |
| 150 | + def from_notebook_node(self, nb, resources=None, **kw): |
| 151 | + """Convert from a notebook node.""" |
| 152 | + html, resources = super().from_notebook_node(nb, resources=resources, **kw) |
| 153 | + |
| 154 | + self.log.info("Building HTML") |
| 155 | + html_data = self.run_playwright(html) |
| 156 | + self.log.info("HTML successfully created") |
| 157 | + |
| 158 | + return html_data, resources |
0 commit comments