Skip to main content
Recipe number 24

Cookbook · Chapter 10 · Output & integration

Print-ready PDF: bleed, crop marks and PDF/X

An exhibition leaflet with 3 mm of bleed and crop marks, exported as PDF/X-4 on FOGRA51 with print masters and a clean preflight.

On this page
Output
Canvas · PDF
Postext
Tested with Postext 1.65.0
Needs ≥ 1.25.0 · postext-pdf ≥ 1.25.0
Licence
Updated 10 Oct 2026
Code MIT · Text CC BY 4.0
  • Spanish sample: no English edition yet
  • Trim 170 × 227 mm
  • 1 column
  • Karla 9.6/13.6
  • Space Grotesk
  • Space Mono
  • 4 pages
  • Level
  • Postext 1.57.1
  • Laid out in 51 ms
  • 274 lines of code

In short

A leaflet for a map exhibition, ready to send to a print shop. It shows how to add extra room past the page edge and cutting marks, and save a PDF in the colours printing presses use.

What you'll build

The room sheet for Cartografías imaginarias, an invented exhibition of maps of imaginary places, as it goes to the printer, in Spanish on both editions of this page. Each 170 × 227 mm page sits on a sheet 22 mm larger that carries the bleed and the crop marks. On the cover an orange route crosses an archipelago in stepped greens and runs off the trim into the bleed. Inside, four rooms in ragged Karla open under waypoint kickers and an orange tab carries the folio off the fore-edge; the back cover sets a floor plan above a band of relief. The pen exports the press file, a PDF/X-4 separated for FOGRA51 (the PSO Coated v3 condition of the 150 g coated stock) with its fonts, bookmarks and page labels, and a greyscale proof, and runs the preflight on the layout before it offers them. In the press file the maps and the plan come from print masters in hand-picked inks, and the type, the tab and the waypoint rings use the same inks through a palette authored in CMYK.

This recipe answers

  • How do I make a print-ready PDF with bleed, crop marks, bookmarks, page labels and a colour space?
  • How do I export a real PDF in the browser with the fonts embedded?
  • How do I add a watermark, a background tint or a decorative image on every page?

The short answer

script.js · lines 46–76in full code
const BLEED = 3; // mm of artwork past the trim: the cover, the tab and the back band reach it
// Hook-up: config().page.cutLines. A mark starts markOffset outside the trim (3 mm by default)
// and never inside the bleed, and runs 5 mm (markLength). Each page grows by doc.trimOffset
// a side, bleed + offset + mark: 11 mm here.
const cutLines = { enabled: true, bleed: mm(BLEED) };

// Hook-up: config().print. PDF/X-4 for the press on FOGRA51 (PSO Coated v3, the leaflet's
// 150 g coated matte): every colour separated through the profile (the authored ones as
// written), 100 % K text overprinting, the output intent, TrimBox and BleedBox on each page.
// The 7.5 pt bold labels in forest hold in four inks on coated stock: the small-text check
// starts at 7 pt instead of 9.
const PRINT = { standard: 'pdfx4', outputProfile: 'fogra51', preflight: { smallTextSize: pt(7) } };
// Where the profiles are fetched from: postext.dev serves postext's icc/ folder at /icc/ (any
// copy of it works, and so does the npm CDN's postext/icc/).
const PROFILES = 'https://postext.dev/icc/';

// `masters` holds print-master bytes by fileId (section 2 writes them). The proof is an
// ordinary greyscale PDF: no PDF/X, which would force CMYK.
function pressPdf(doc, kind, masters) {
  const press = kind === 'press';
  return renderToPdf(doc, {
    fontProvider: fontsourceProvider, // Fontsource's files; TrueType faces are subset
    // The press file takes config().print, its profile fetched from PROFILES
    // (outputProfile: the .icc bytes, to hand it over yourself).
    profileBaseUrl: PROFILES,
    ...(press ? {} : { print: { standard: 'none' }, colorSpace: 'grayscale' }),
    // renderToPdf asks for a drawing's master (svg.pdfFileId) first, then for its SVG. The
    // proof answers the SVG only, which its grey conversion can reach; a master stays in CMYK.
    resourceBytes: (fileId) => (press && masters.get(fileId)) || imageBytes(fileId),
  }); // bookmarks (from the headings) and /PageLabels (from the folios) come by default
}

Bleed and crop marks on every page; a CMYK PDF that swaps in print masters

Ingredients

Type
Karla, Space Grotesk, Space Mono (SIL OFL 1.1)
Assets
None: every picture is drawn in code

Method

#1 · Pick screen colours for their plates

script.js · lines 19–42in full code
const palette = {
  ink: '#161616', // text: a neutral grey prints on the black plate alone (K95 on FOGRA51)
  muted: '#666666', // the running heads, on black alone for the same reason (K66)
  forest: '#0b3d2e', // the sea, the kickers, the back band
  signal: '#ff6626', // route, waypoints, tab
  sage: '#9fb8a8', // high ground; small type on forest
  paper: '#f4f1ea', // type on forest: reversed out, it prints no ink at all
};
// The colours authored in CMYK (%), the same builds as the print masters (section 2), so the
// type, the tab and the drawings share their inks. Without them the profile would separate
// the forest as C90 M43 Y71 K62 and the orange as C0 M70 Y90 K0, a shade off the route.
const AUTHORED = { forest: [100, 45, 80, 55], signal: [0, 60, 85, 0], sage: [40, 20, 35, 0],
  paper: [0, 0, 0, 0] };
const cmyk = ([c, m, y, k]) => ({ c, m, y, k });
const value = (id) => (AUTHORED[id]
  ? { hex: palette[id], model: 'cmyk', cmyk: cmyk(AUTHORED[id]) }
  : { hex: palette[id], model: 'hex' });
// col(id): a palette-linked colour: the hex for the screen and, where authored, its build.
const col = (id) => ({ ...value(id), paletteId: id });
const colorPalette = [
  ...Object.keys(palette).map((id) => ({ id, name: id, value: value(id) })),
  // The engine's defaults link to 'main-color': point it at the forest, so nothing prints blue.
  { id: 'main-color', name: 'forest (defaults)', value: { hex: palette.forest, model: 'hex' } },
];

print: { standard: 'pdfx4', outputProfile: 'fogra51' } in the configuration separates every colour through the FOGRA51 profile that ships with postext. Neutral greys print on the black plate alone, their K picked so the tone matches: #161616 becomes K95 and the running heads' #666666 K66, and 100 % K text overprints. The profile would print the forest as C90 M43 Y71 K62 and the orange as C0 M70 Y90 K0, a shade off the route of the masters (step 5), so those two, the sage and the paper colour are authored in CMYK: ColorValue.cmyk holds the build, the hex stays for the screen, and every palette-linked use prints the build as written. The paper colour is C0 M0 Y0 K0: type reversed out of the forest prints no ink, so no plate can shift it.

#2 · A thumb tab that survives the guillotine

script.js · lines 86–107in full code
const TAB = { w: 10, h: 24 }; // the tab as it will be trimmed, mm; its foot is level with the text
const tab = (parity) => {
  const edge = parity === 'even' ? 'bottom-left' : 'bottom-right'; // the fore-edge
  const from = (to, y) => ({ anchor: { to, edge }, offset: { y: mm(y) } });
  return [
    // The box hangs from the bleed frame and BLEED of its width is trimmed off, so a cut that
    // lands a millimetre outside the trim still leaves orange at the edge.
    { kind: 'box', id: `tab-${parity}`, style: { backgroundColor: col('signal') },
      placement: { ...from('bleed', -(FOOT + BLEED)), size: { width: mm(TAB.w + BLEED),
        height: mm(TAB.h) } } },
    // The folio hangs from the trim frame ('page'), so it centres on the part left after the cut.
    { kind: 'text', id: `folio-${parity}`, content: '{pageNumber}', ...label, align: 'center',
      fontSize: pt(11), letterSpacing: pt(0), color: col('ink'),
      placement: { ...from('page', -FOOT), size: { width: mm(TAB.w), height: mm(TAB.h) } } },
  ].map((element) => ({ ...element, parity, pages: 'body' })); // never on the covers
};
const head = (parity, content) => ({ kind: 'text', id: `head-${parity}`, content, ...label,
  color: col('muted'), parity, pages: 'body',
  placement: { anchor: { to: 'container', edge: parity === 'even' ? 'top-left' : 'top-right' },
    offset: { y: mm(11) } } });
const header = { elements: [head('even', '{title}'), head('odd', '{subtitle}')] };
const footer = { elements: [...tab('even'), ...tab('odd')] };

The tab's box hangs from the bleed frame and is BLEED wider than the finished tab, so a cut that lands a millimetre outside the trim still leaves orange at the edge; the folio hangs from the page frame, which is the trim, and centres on the 10 mm that remain. parity picks the pages each element appears on and edge changes with it to reach the fore-edge, while pages: 'body' keeps the tab and the running heads ({title} and {subtitle} from the frontmatter) off both covers, which count as openers because each starts with a heading that spans the page or breaks to a new one. Any header or footer element repeats this way, so an image with parity and pages puts a watermark or a decorative picture on every page; slots paint over the text, and a tint behind it goes in page.backgroundColor.

#3 · Artwork to the bleed, type inside the trim

script.js · lines 124–170in full code
const BAND = 44; // mm from the trim foot to the top of the back band
const onForest = { color: col('paper'), align: 'left', overflow: 'wrap' };
const art = (resourceId, edge) => ({ kind: 'image', id: resourceId, resourceId,
  placement: { anchor: { to: 'bleed', edge }, size: { width: 'fill' } } }); // height: its ratio
// The map is as tall as the sheet and the cover reserves down to its foot, so the lead
// starts on page 2. span: 'page' makes the cover an opener, so furniture set to
// pages: 'body' skips it.
const cover = { id: 'cover', numbered: false, span: 'page', advancedDesign: { enabled: true,
  slot: { elements: [ // paint order: the map first, the type on top
    art('cubierta', 'top-left'),
    { kind: 'text', id: 'kicker', content: '{attr.kicker}', ...label, color: col('sage'),
      placement: { anchor: { to: 'container', edge: 'top-left' }, offset: { y: mm(6) } } },
    { kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Space Grotesk',
      fontWeight: 700, fontSize: pt(50), lineHeight: 0.98, ...onForest,
      placement: { anchor: { to: '#kicker', edge: 'below' }, offset: { y: mm(4) },
        size: { width: mm(132) } } },
    { kind: 'text', id: 'subtitle', content: '{subtitle}', fontFamily: 'Karla', fontSize: pt(13),
      ...onForest, placement: { anchor: { to: '#title', edge: 'below' }, offset: { y: mm(5) } } },
  ] } },
  footer: { elements: [ // the cover's own foot: dates and place, over open sea
    { kind: 'text', id: 'dates', content: '{attr.fechas}', ...label, color: col('paper'),
      placement: { anchor: { to: 'container', edge: 'bottom-left' }, offset: { y: mm(-15) } } },
    { kind: 'text', id: 'place', content: '{attr.lugar}', ...label, color: col('sage'),
      placement: { anchor: { to: '#dates', edge: 'below' }, offset: { y: mm(1.6) } } },
  ] } };
const back = { id: 'back', numbered: false, breakBefore: { enabled: true, parity: 'any' },
  advancedDesign: room('{attr.kicker}'),
  margins: { bottom: mm(BAND + 8) }, // the text stops 8 mm above the band
  footer: { elements: [
    art('banda', 'bottom-left'),
    { kind: 'text', id: 'venue', content: '{attr.lugar}', fontFamily: 'Space Grotesk',
      fontWeight: 700, fontSize: pt(20), ...onForest, // on the band, level with the text edge
      placement: { anchor: { to: '#banda', edge: 'align-top' }, offset: { x: mm(BLEED + OUTER),
        y: mm(6) } } },
    { kind: 'text', id: 'address', content: '{attr.direccion}', fontFamily: 'Karla',
      fontSize: pt(10), ...onForest,
      placement: { anchor: { to: '#venue', edge: 'below' }, offset: { y: mm(1.5) } } },
    { kind: 'text', id: 'when', content: '{attr.fechas}', ...label, color: col('sage'),
      placement: { anchor: { to: '#address', edge: 'below' }, offset: { y: mm(4) } } },
    { kind: 'text', id: 'colophon', content: '{attr.colofon}', ...label, fontWeight: 400,
      // 6.3 pt in sage would be three inks on a four-ink band: reversed to paper, it prints
      // no ink and no plate can shift it (the preflight's small-text check).
      fontSize: pt(6.3), letterSpacing: pt(0), textTransform: 'none', lineHeight: 1.4,
      color: col('paper'), overflow: 'wrap',
      placement: { anchor: { to: 'page', edge: 'bottom-left' }, offset: { x: mm(OUTER),
        y: mm(-6) }, size: { width: mm(78) } } }, // 57 monospaced characters a line
  ] } };

cutLines adds the bleed, the mark offset and the 5 mm mark to every side of the page, 11 mm here. The offset is 3 mm by default, the same as this bleed, so the marks start at the bleed edge and run outwards; with a wider bleed they would still start at its edge, never inside it. An image element anchored to the bleed with width: 'fill' takes that frame's width and keeps its own proportions: the cover map is drawn at 176 × 233 mm, the trim plus 3 mm a side, so it reaches the bleed edge where the crop marks start, while the type hangs from the text area, well inside the trim. The back cover is a heading style whose footer replaces the document's, with a band from the same generator anchored to the foot of the bleed and a bottom margin that stops the text 8 mm above it.

#4 · Headings that become bookmarks

script.js · lines 190–201in full code
  headings: {
    // A designed heading keeps its own text, hidden, for the bookmarks and the tags. Set it in
    // a face the pages already load, or the PDF embeds Open Sans for that text alone.
    fontFamily: 'Space Grotesk',
    levels: [
      // Rooms follow on: the H1's page break is off. The back cover breaks through its style,
      // and the front one fills its page. The template numbers kicker and bookmark: "Sala 1
      // Una isla en ninguna parte".
      { level: 1, numberingTemplate: 'Sala {1}', breakBefore: { enabled: false },
        marginTop: pt(LEAD), advancedDesign: room('{number} · {attr.fecha}') },
    ],
  },

renderToPdf builds the bookmarks from the headings, so each room is a level-1 heading that follows on without a page break, and numberingTemplate gives the kicker its {number} and the bookmark its prefix: the PDF lists the cover, "Sala 1 Una isla en ninguna parte" to "Sala 4 La isla del tesoro", and the practical information. A designed heading hides its own text but keeps it for the bookmarks and the tags; without fontFamily that hidden text is set in Open Sans 700, which the pages would load and the PDF embed for that text alone. The page labels follow page.pageNumbering, left at its default, decimal from 1, so page 3 in a PDF viewer is the page whose tab reads 3.

#5 · Print masters in exact inks

script.js · lines 394–426in full code
// C, M, Y, K in %, one build per colour of the drawings, matched to the screen colours on a
// proof. The palette authors forest, signal, sage and paper with these same builds, so the
// route matches the tab and the kickers match the sea.
const INKS = { forest: [100, 45, 80, 55], shallows: [100, 50, 85, 40], coast: [90, 50, 85, 20],
  lowland: [80, 40, 75, 5], upland: [50, 15, 45, 20], sage: [40, 20, 35, 0],
  summit: [10, 5, 10, 0], tint: [5, 0, 5, 5], signal: [0, 60, 85, 0], paper: [0, 0, 0, 0] };
function pdfPage(w, h, shapes) { // w, h in mm; the content stream flips y to match the SVG
  const s = 72 / 25.4; // pt per mm
  const ink = (id, op) => `${INKS[id].map((v) => v / 100).join(' ')} ${op}`;
  const ops = (d) => d.replace(/([MLCZ])([^MLCZ]*)/g,
    (_, c, v) => `${v.trim()} ${{ M: 'm', L: 'l', C: 'c', Z: 'h' }[c]} `.trimStart());
  const body = shapes.map(({ d, fill, stroke, width, dash }) => [
    'q', fill && ink(fill, 'k'), stroke && ink(stroke, 'K'), stroke && `${width} w 1 J 1 j`,
    dash && `[${dash.join(' ')}] 0 d`, ops(d), fill ? 'f' : 'S', 'Q',
  ].filter(Boolean).join(' ')).join('\n');
  const stream = `${s} 0 0 ${-s} 0 ${h * s} cm\n${body}`;
  const objects = ['<< /Type /Catalog /Pages 2 0 R >>', '<< /Type /Pages /Kids [3 0 R] /Count 1 >>',
    `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${n(w * s)} ${n(h * s)}] /Contents 4 0 R >>`,
    `<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`];
  let pdf = '%PDF-1.4\n';
  const offsets = objects.map((object, i) => {
    const offset = pdf.length;
    pdf += `${i + 1} 0 obj\n${object}\nendobj\n`;
    return offset;
  });
  const xref = pdf.length;
  pdf += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`
    + offsets.map((o) => `${String(o).padStart(10, '0')} 00000 n \n`).join('')
    + `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
  return new TextEncoder().encode(pdf); // ASCII only, so string length = byte length
}
const masters = new Map(Object.entries(DRAWINGS) // by fileId: cubierta.pdf, banda.pdf, plano.pdf
  .map(([id, [size, shapes]]) => [`${id}.pdf`, pdfPage(...size, shapes)]));

Each drawing is defined once, as paths. The art region turns them into the SVG the canvas paints, and this region writes the same paths into a one-page CMYK PDF with builds chosen so that a proof matches the screen, which puts the sea at C100 M45 Y80 K55, the forest of the palette. Each resource names its master in svg.pdfFileId; renderToPdf asks for that id, pressPdf() in the short answer answers with the master's bytes, and postext-pdf embeds that page unchanged, as vectors in the master's own inks. That holds for the plan, a figure, and for the cover map and the back band, which are design images. The greyscale proof gets the SVGs instead, because an embedded master is never converted and would stay in colour.

The whole recipe

Sandbox
// ═══ Postext Cookbook · Nº 024 · Print-ready PDF: bleed, crop marks and CMYK ═══════════
// https://postext.dev/en/cookbook/print-ready-pdf
// Code: MIT · Text: original (CC BY 4.0) · Maps: generated in code (CC BY 4.0)
// Fonts: Karla, Space Grotesk, Space Mono (SIL OFL 1.1) · Needs postext ≥ 1.25.0
// An exhibition leaflet set up for the press: bleed and crop marks on every page, and a
// PDF/X-4 file separated for FOGRA51 that embeds its fonts and takes the maps and the floor
// plan from print masters, checked by the preflight before it is offered.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, defaultResourceTypes,
  preflightDocument, loadOutputProfile, outputTransform,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'es'; // @lang: the language of the sample document (this recipe is Spanish only)
const RECIPE = 'print-ready-pdf';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: screen colours, and for four of them the inks the press prints them in
const palette = {
  ink: '#161616', // text: a neutral grey prints on the black plate alone (K95 on FOGRA51)
  muted: '#666666', // the running heads, on black alone for the same reason (K66)
  forest: '#0b3d2e', // the sea, the kickers, the back band
  signal: '#ff6626', // route, waypoints, tab
  sage: '#9fb8a8', // high ground; small type on forest
  paper: '#f4f1ea', // type on forest: reversed out, it prints no ink at all
};
// The colours authored in CMYK (%), the same builds as the print masters (section 2), so the
// type, the tab and the drawings share their inks. Without them the profile would separate
// the forest as C90 M43 Y71 K62 and the orange as C0 M70 Y90 K0, a shade off the route.
const AUTHORED = { forest: [100, 45, 80, 55], signal: [0, 60, 85, 0], sage: [40, 20, 35, 0],
  paper: [0, 0, 0, 0] };
const cmyk = ([c, m, y, k]) => ({ c, m, y, k });
const value = (id) => (AUTHORED[id]
  ? { hex: palette[id], model: 'cmyk', cmyk: cmyk(AUTHORED[id]) }
  : { hex: palette[id], model: 'hex' });
// col(id): a palette-linked colour: the hex for the screen and, where authored, its build.
const col = (id) => ({ ...value(id), paletteId: id });
const colorPalette = [
  ...Object.keys(palette).map((id) => ({ id, name: id, value: value(id) })),
  // The engine's defaults link to 'main-color': point it at the forest, so nothing prints blue.
  { id: 'main-color', name: 'forest (defaults)', value: { hex: palette.forest, model: 'hex' } },
];
// #endregion

// #region answer: bleed and crop marks on every page; a CMYK PDF that swaps in print masters
const BLEED = 3; // mm of artwork past the trim: the cover, the tab and the back band reach it
// Hook-up: config().page.cutLines. A mark starts markOffset outside the trim (3 mm by default)
// and never inside the bleed, and runs 5 mm (markLength). Each page grows by doc.trimOffset

The composed script.js runs as it is: paste it into any page’s module script, or open the recipe on CodePen. Recipe folder on GitHub ↗ (opens in a new tab)

Variations

#Ask for 5 mm of bleed

The artwork, the tab and the scale bar are sized from BLEED, and the crop marks start at the edge of the bleed, so a press that wants 5 mm needs only this change, and each sheet grows to 196 × 253 mm.

-const BLEED = 3; // mm of artwork past the trim: the cover, the tab and the back band reach it
+const BLEED = 5; // mm of artwork past the trim: the cover, the tab and the back band reach it

Without pdfFileId the press file draws each picture from its SVG, still as vectors and through the profile: the forest, authored in CMYK, keeps C100 M45 Y80 K55, while the other greens of the islands take the profile's separations instead of the hand-picked ones.

-  updatedAt: 0, ...extra, svg: { fileId: `${id}.svg`, pdfFileId: `${id}.pdf`,
+  updatedAt: 0, ...extra, svg: { fileId: `${id}.svg`,

Pitfalls

Pitfall

No <marker> or filters in SVG art (raster fallback)

An SVG figure stays vector in the PDF only without <marker>, filters and masks; otherwise it falls back to a raster, and deeply nested filters can blank it in Chrome. Draw arrowheads as paths. Figures and tables as resources →

Pitfall

Fontsource files cover letters, not symbols

The kit embeds a face's Fontsource latin file, plus its latin-ext file for č, ł, † and its greek file for α, χ (in a family that ships one: Lora and Gelasio do not), when the text sets them, on screen and in the PDF. Symbols such as →, ≈, ✓ and ★ are in none of those files and go missing in the PDF: draw them, set them as maths, or choose a face whose files hold them. Fonts embedded in the PDF →

  • A PDF/X standard always writes CMYK, whatever colorSpace says, so the greyscale proof overrides print with { standard: 'none' } beside colorSpace: 'grayscale'.
  • A PDF/X render fails without its output profile. renderToPdf fetches fogra51.icc from profileBaseUrl (postext.dev's /icc/ here); pass the file's bytes as outputProfile to serve it yourself.
  • The preflight flags text under 9 pt set in more than one ink. The 7.5 pt bold labels in forest hold in four inks on coated stock, so print.preflight.smallTextSize is 7 pt; the 6.3 pt colophon, in sage it would be three inks on a four-ink band, is reversed to paper instead.
  • A PDF/X file carries no link annotations, since a file for the press may not have them inside its bleed box; the bookmarks stay.
  • Once built, each button turns into an "Open the PDF ↗" link and a download link, and only the download links carry the file names.

Credits

Text
Original prose, CC BY 4.0
Fonts
Karla (SIL OFL 1.1) · Space Grotesk (SIL OFL 1.1) · Space Mono (SIL OFL 1.1)
SandboxPDF