Introducing a new way to review your PRs.

Read the announcement

jgraph / drawio-desktop

Official electron build of draw.io

View on GitHub

10 documents · Updated Nov 16, 2026

docs / export-and-print-pipeline

Export and Print Pipeline

Overview

The desktop export path is orchestrated from src/…/electron.js, with the security- and format-specific pieces factored into the files owned by this doc. CLI export mode begins when parsed arguments set options.export in src/…/electron.js. The main process creates a hidden window, resolves the requested output format from --output or --format, builds expArgs, then walks each input file or directory. Directory inputs are expanded through listExportFiles in src/…/export-files.js, which filters by exportable extensions, optionally recurses into real directories, skips dotfiles, and deliberately does not follow symlinks discovered during the scan. Skipped symlinks with exportable names are reported to the caller, and the CLI logs them.

For each input, src/…/electron.js reads binary formats (.png, .pdf, .vsdx) as buffers and text formats as UTF-8. Inputs found by a directory scan are treated more leniently for .png, .pdf, and .svg: readPngXml in src/…/png-xml.js, readPdfXml in src/…/pdf-xml.js, or the local SVG reader in src/…/electron.js must find embedded diagram XML, otherwise the file is skipped as a previous export or unrelated asset. Explicitly listed files still fail if diagram data cannot be extracted. Before each file, the shared expArgs object is cleared of prior xml, csv, mermaid, xmlEncoded, and pdfEncoded fields so one input's decode mode cannot leak into the next export.

HTML export bypasses the renderer for most inputs. In src/…/electron.js, HTML output first normalizes source XML: PNG inputs are decoded with readPngXml, PDF inputs with readPdfXml, SVG inputs with the local SVG content reader, while CSV, Mermaid, layout, and normalize modes are rejected because this path cannot render them to XML. buildHtmlExport in src/…/html-export.js returns an iterator of page fragments, not one string. It constructs the data-mxgraph JSON around an empty xml placeholder, then streams the XML through repeated JSON.stringify calls bounded by MAX_XML_PART_LENGTH, preserving surrogate pairs and HTML-escaping every fragment. The writer in src/…/electron.js detects iterators and writes each fragment to the output file handle in order, avoiding the large single-string allocation tested by src/…/html-export.test.js.

Non-HTML exports use exportDiagram in src/…/electron.js. It opens a hidden offscreen BrowserWindow on export3.html, sends the prepared render arguments after load, and waits for renderer IPC. render-finished provides bounds, page count, resolved XML, and optional annotation metadata; export-error, renderer death, or invalid bounds reply with an export error. PNG/JPEG export resizes the offscreen capture to requested width or height, writes optional PNG DPI metadata, and embeds XML with writePngWithText when embedXml is enabled. That writer stores diagram data in a PNG zTXt chunk named mxGraphModel, using a zlib datastream. readPngXml reads the same tEXt/zTXt keyword, decodes URL-encoded compressed XML, and retains a raw-deflate fallback for older CLI outputs.

PDF export and native printing share the same renderer preparation. For file output, src/…/electron.js calls webContents.printToPDF, then mergePdfs loads the result with @cantoo/pdf-lib, sets the creator, embeds XML in the PDF Subject when embedXml is enabled, adds tooltip/note annotations, and saves with object streams. readPdfXml in src/…/pdf-xml.js imports both current PDFs whose URL-encoded XML Subject is stored inside PDF 1.7 object streams and older PDF 1.7 exports that attached an application/vnd.jgraph.mxfile embedded file. It also keeps the older PDF 1.4 Subject parser. Inflated object streams are bounded by MAX_INFLATED_LENGTH imported from src/…/png-xml.js; attachment streams get a three-bytes-per-character allowance because they are raw UTF-8 XML.

Native printing is the PDF-format branch where args.print is set in src/…/electron.js. Instead of printToPDF, it calls getPrintOptions from src/…/print-options.js with the renderer-provided page dimensions and passes the result to webContents.print. getPrintOptions converts draw.io page units to microns, sends the native dialog a portrait-ordered pageSize, sets landscape separately, disables margins, prints backgrounds, and keeps scaleFactor at 100 because Chromium already fits oversized rendered pages to paper. If Electron rejects settings as Invalid printer settings, the print path retries once with empty options so the native dialog can still open.

Output-file creation is centralized in openExportFile in src/…/export-files.js. --check uses lexists, not fs.existsSync, so dangling symlinks reserve names and trigger numbered alternatives. When the output path is derived from an input name or output directory, openExportFile refuses a symlink at the final path with an ELOOP error, using both lstat and O_NOFOLLOW where available. A user-typed --output file path is the exception: src/…/electron.js passes followLink when realFileName == options.output, so a deliberate target symlink is honored.

User-visible progress uses two mechanisms in this area. CLI export reports batch progress by console lines such as input -> output, Skipping ... (symbolic link), and Skipping ... (no diagram data) from src/…/electron.js. The reusable windowed progress component is ProgressBar in src/…/progress-bar.js: it creates a sandboxed, no-preload BrowserWindow with a data-URL progress UI, queues DOM updates until did-finish-load, exposes detail and value setters compatible with electron-progressbar, and emits progress, completed, aborted, and ready. In this codebase it is wired to updater download reporting in src/…/electron.js, not the export loop, but the same class owns the user-visible progress window behavior.

The tests under src/…/export-files.test.js, src/…/html-export.test.js, src/…/png-xml.test.js, src/…/pdf-xml.test.js, and src/…/print-options.test.js are the executable contract for this flow. They cover symlink avoidance and output opening, HTML streaming equivalence to a single JSON object, PNG/PDF embedded XML readers including malformed-file termination and inflate limits, and print option conversion for standard and custom paper sizes.

Coupling

  • If writePngWithText in src/…/electron.js changes the PNG chunk type, keyword, compression wrapper, or URL-encoding for embedded XML, update readPngXml in src/…/png-xml.js and src/…/png-xml.test.js; directory-scan filtering and HTML export from PNG inputs depend on that reader finding mxGraphModel.
  • If PDF embedding in mergePdfs in src/…/electron.js moves XML out of the URL-encoded Subject or stops saving with object streams, update readPdfXml in src/…/pdf-xml.js; current imports look for /Subject <...> inside inflated PDF 1.7 /ObjStm streams, while compatibility code still handles older attachments and PDF 1.4 subjects.
  • If CLI HTML export starts accepting CSV, Mermaid, layout, or normalize inputs in src/…/electron.js, route them through renderer resolution before calling buildHtmlExport in src/…/html-export.js; the direct HTML path only has source XML and explicitly rejects those modes today.
  • If output naming or --check behavior in src/…/electron.js changes, keep lexists and openExportFile in src/…/export-files.js aligned; dangling symlinks must count as existing names, and generated output paths must not write through a symlink unless the path was the exact user-typed --output.
  • If renderer print dimensions or page-unit assumptions change, verify getPrintOptions in src/…/print-options.js and src/…/print-options.test.js; it assumes page formats are in 1/100 inch and converts to microns for Electron's webContents.print paper matching.
  • If ProgressBar in src/…/progress-bar.js is reused for export progress, account for its lifecycle semantics: it is not closable by default, emits aborted on window close unless value >= 100, and does not auto-close on completion, so callers must close it after the operation finishes.

Risks

  • src/…/export-files.js protects generated exports from symlink writes for [GHSA-2w35-fgjm-2vvh]. If callers bypass listExportFiles, lexists, or openExportFile, a directory export can follow attacker-controlled links, overwrite files outside the scanned tree, or treat a dangling symlink as an available --check name.
  • src/…/html-export.js avoids V8 fatal allocations by streaming the XML through bounded chunks. If a change concatenates the whole data-mxgraph payload or calls JSON.stringify on the entire diagram, very large diagrams can crash the Electron main process instead of returning an export error.
  • src/…/png-xml.js and src/…/pdf-xml.js are synchronous parsers used during CLI batch export. If malformed chunk/stream handling stops advancing or stops bounding inflation, a bad scanned file can hang the export loop or allocate past the process string limit; the tests run malformed cases in child processes to catch this failure mode.
  • src/…/print-options.js exists because landscape paper sent as a wide custom sheet confused native print dialogs on macOS/GTK. If page size is sent in landscape order or scaleFactor is derived from page scale again, users can see custom-paper selection or double-shrunk output in native printing.