Diagram - Print

Prepare isolated print sheets, choose fit or actual-scale pagination, and request browser print from a user action.

#Usage

This component accepts a valid initial model and page ID. It renders a read-only canvas and rooted print transport. Import DiagramPrint and its output types from the optional export entry.

<script setup lang="ts">
import { shallowRef } from 'vue';
import { Diagram, type DiagramModel } from '@primeui/vue-diagram';
import { DiagramPrint } from '@primeui/vue-diagram/export';

const props = defineProps<{ model: DiagramModel; pageId: string }>();
const printer = shallowRef<InstanceType<typeof DiagramPrint> | null>(null);
</script>

<template>
    <Diagram.Root :value="props.model" :page-id="pageId" :editing-options="{ readOnly: true }">
        <Diagram.Viewport label="Print source" auto-fit style="height: 28rem" />
        <DiagramPrint ref="printer" :value="props.model" :options="{ pageIds: [pageId] }" :print-options="{ mode: 'fit' }">
            <button type="button" @click="printer?.prepare()">Prepare print</button>
            <button type="button" :disabled="printer?.state !== 'ready'" @click="printer?.print()">Print</button>
            <button type="button" @click="printer?.cancel()">Cancel and close</button>
        </DiagramPrint>
    </Diagram.Root>
</template>

For an editable canvas, put the print controls in a child beneath Diagram.Root and read its current model through useDiagramContext(). Pass that model ref to the transport so accepted edits participate. Keep custom node definitions mounted when capturing them. Follow First Diagram for model and application setup.

Prepare first, then open browser print from a separate user action. A ready result confirms preparation; closure and print events do not confirm a physical print or saved file. An explicit source chooses a viewport. Without it, a rooted transport selects the unique directly owned viewport; a transport outside the root uses detached export.

Source-backed preparation inherits mounted Vue content and the capture limits. It does not stage offscreen Vue components. Set options.colorScheme to 'light' or 'dark', or omit it to follow the source. Rooted output panels use baseOptions.colorScheme. Application branches keep their captured values; use CSS tokens for colors that should follow the output mode.

An omitted background uses the export canvas. Source-backed portable theme overrides fail, including {}. Missing resources, unavailable content and stale source revisions fail preparation. A change to source, theme or options invalidates prepared output and releases its resources.

The examples below deliberately create detached output. They use body-only rectangle adapters and native centered captions instead of capturing the preview canvas. Browser print and Save as PDF remain browser functions; Diagram has no direct PDF-file export API.

Prepare first, then request the browser dialog from a separate user action. Closure and print events do not confirm that the user printed or saved a file.

This skeleton assumes an initialized store with page page. Use First Diagram for model creation, style imports and store disposal.

An absent options.background uses the export canvas after theme selection. An explicit background replaces that backdrop without changing content paints. A source-backed portable theme object, including {}, fails with render-unsupported-theme. Missing fonts or image bytes, fallback fonts, failed decode, unavailable content, and stale sources fail preparation. Source, theme, or options changes invalidate prepared print output and release owned resources.

The lower-level print planners also retain their detached scene contracts. Preparation is separate from requesting browser print UI. The browser controls the final destination, paper settings and user cancellation. Save as PDF is browser functionality; Diagram has no programmatic PDF API in V1.

The examples below intentionally use detached scenes without source. They supply a body-only rectangle adapter to match their empty node-content templates; native captions are exported separately. Their captions use layout: 'centered-inside' so the canvas and exported scene center text within each shape. A label's authored position alone does not center its text; see Labels.

#Fit one source page to a sheet

Loading Demo...

Choose paper, orientation and margins, then Prepare sheet. Once ready, Open browser print calls the print request directly from a click. Check the browser's final paper, margins, scale and destination. Cancel and close aborts local preparation and releases the isolated document; it does not revoke a physical job already submitted by the user.

DiagramPrint accepts a model snapshot through value, optional source, export options, and printOptions. It builds the scene, paginates it, decodes resources and prepares an isolated print iframe. prepare() returns a result and emits prepared; print() requests UI only when current state is ready; cancel() releases its abort owner, listeners and prepared document. Changed model/options/settings or component destruction also cancel the current owner.

state is idle, preparing, ready, requested, rendering, closed or error. The requested event marks the attempt to request UI; rendering follows the browser's beforeprint; closed follows releasing the prepared document. Neither an event nor return from print() proves a physical print or a user save. Use error and result diagnostics for preparation/request failure.

Detached connector outlines default to 2 output CSS pixels and retain that width at page-fit scale. DiagramPrint.options.connectorStrokeScaling uses the export policy, default 'viewport'. Set 'world' to scale outlines with the graph. Detached calls use options.styles[connectorId].strokeWidth for a numeric width override. Source-backed calls acquire rendered widths and reject styles. Browser print and Save as PDF use the selected source or detached scene. Detached calls do not capture live editor CSS. See Connector widths in saved output.

#Actual scale and tiled physical sheets

Loading Demo...

The second example uses the public functions directly, selecting a fixed 1,200 × 800 world-unit page. mode: 'actual' paginates it at 1 or 2 CSS pixels per world unit. Sheets are ordered by source page, then row and column in row-major order. Try the one-sheet limit to see rejection without a prepared document. Repeated preparation or settings changes close the previous handle.

The API enum is 'fit' | 'actual'. “Tiled sheets” describes actual-mode output; 'tiled' is not an option value. Actual print scale is independent of raster pixels, devicePixelRatio and scene export scale. Fit chooses a scale to put each selected source page on one physical sheet. An explicit scale is valid only in actual mode; supplying it in fit mode rejects.

#Paper, orientation and limits

SettingDefault and contract
paperA4 { widthMm: 210, heightMm: 297 }; dimensions are before orientation. Each custom dimension must be finite 50–1,200 mm. Letter is { widthMm: 215.9, heightMm: 279.4 }.
orientationPortrait when omitted. 'landscape' swaps the supplied width and height; do not pre-swap them.
marginsMm{ top: 10, right: 10, bottom: 10, left: 10 }; each is 0–100 mm and printable width/height must remain at least 10 mm.
mode / scaleDefault 'fit'. Actual-mode scale defaults to 1, allowed 0.01–16 CSS pixels per world unit.
limits.pagesDefault/max 256 physical sheets. Lower scale or select fewer pages when pagination exceeds it.
limits.outputBytes / decodedResourceBytesDefault/max 64,000,000 serialized bytes / 64,000,000 conservative decoded-resource bytes.
limits.timeoutMsDefault/max 30,000 ms; callers may lower it.

createDiagramPrintPlan(scene, options) returns a portable DiagramPrintPlan or diagnostics without a partial plan. Its paperMm, marginsMm, printableMm, pages, outputBytes and resolved limits describe the result. Each page contains sourcePageId, sourcePageName, global index, zero-based row/column, clipped world rectangle, print scale and self-contained svg/bytes. Content on sheet boundaries is clipped, not duplicated at a different scale.

Scene selection, explicit page bounds, padding, hidden/collapsed visibility and container clipping follow Export. Select all desired source pages before planning. Default content bounds frame paint visible through clips at scene scale; page-sized output requires explicit pageBounds. Offscreen visible graph content is included. Editor chrome and active editing previews are excluded. Printing does not mutate Store/history and can operate in a read-only editor.

#Preserve content paint and explicit crops

A page's bounds records its frame and per-side whitespace. It does not imply an intentional crop. clipBounds supplies that crop. Content exports omit it; bounds: 'page' export sets it from the requested page bounds. Manually constructed scenes that need a crop must set clipBounds explicitly.

Fit can increase the world-space extent of a viewport-width outline. Print recomputes actual paint through the primitive clips at the final fit scale. For uncropped content, it expands the frame as needed to keep those outlines inside the sheet while preserving the original whitespace on each side. An explicit page crop stays fixed.

Compiled viewport-stroked primitives retain their graphics, transforms, and clips even if none of their paint reaches an ancestor clip at the scene's original scale. The final print scale determines their visible paint. Printing a scene or a JSON-cloned copy uses the same plain data and produces the same result. SVG and raster output continue to apply the explicit page and ancestor clips.

#Own detached preparation and cleanup

For direct APIs, the application follows this sequence:

  1. Capture the saved model and any approved measured/routes geometry together. Create a detached export scene with explicit theme, adapters and resource providers.
  2. Call createDiagramPrintPlan and inspect diagnostics and physical-sheet count. It can run without a browser.
  3. In a browser, await prepareDiagramPrintDocument(plan, scene, document, signal, onClosed?, onBefore?). It validates embedded images/fonts, waits for the isolated document and its fonts, and returns DiagramPreparedPrint with frame, pageCount, print() and close().
  4. Call the returned print() directly from a separate user action. Keep the handle owned until it closes. Browser UI may block, return immediately, or dispatch lifecycle events synchronously.
  5. Close the handle and abort its signal on cancellation, replacement or teardown. Treat onClosed as resource release, with print/save completion unknown.

For detached scenes, the isolated iframe contains clipped SVG sheets, explicit millimeter CSS and restricted resources. Duplicate SVG fragment IDs are scoped per sheet. Images must be approved embedded PNG resources and fonts approved WOFF2 faces; invalid/missing/undecodable resources reject. Detached HTML content needs portable export adapters. Source-backed preparation captures the selected templates and resources through the shared rendered-export pipeline. Missing matching fonts can produce fallback diagnostics; resource admission does not prove glyph coverage or identical platform shaping.

A preparation deadline bounds scene/provider work, pagination and browser resource readiness. The Vue component carries a remaining deadline through its stages. The direct example does the same with a 10-second budget. Direct callers must keep one overall deadline rather than restarting a full budget at each stage. Decoded-resource estimates are admission control, not a prediction of native browser RAM.

close() is idempotent. The browser preparation handle closes on abort or afterprint, removes its iframe and listeners, and invokes onClosed. After a print request, a 120-second cleanup timer releases an orphaned document if a blocked dialog supplies no lifecycle event. A prepared but unused direct handle still needs application cleanup. Do not use afterprint, timeout, close, or return from print() as confirmation that the user printed or saved anything.

#Browser settings and errors

Check preview, cancellation and final output with your target browser and print destination. Browser settings can override the requested layout. Keep the print action explicit and show preparation or request errors when the print context is unavailable, blocked, stale or timed out. Closing the prepared document confirms resource cleanup; it does not confirm a physical print or a saved PDF.

SVG, PNG and JPEG · BPMN XML

#Connector paint order

Source-backed print inherits the selected viewport's edgeLayer. DiagramExportOptions.edgeLayer may explicitly match that setting; a conflict fails with render-invalid-options. Detached print defaults to 'below' and accepts 'above'. Both use committed model order and omit temporary selection/drag elevation.

Changing the selected viewport's policy invalidates a prepared print plan. Prepare again before requesting browser print. Preparation and the separate user print action keep their existing lifecycle. See export for the full option contract.