简单来说
一份地图展览的展厅导览,可以直接交给印刷厂。示例演示怎样在页边外多留一圈余量、加上裁切线,并导出印刷机用的四色PDF。
成品一览
《Cartografías imaginarias》是一个虚构的展览,展出想象之地的地图。这里做的是它交付印刷厂的展厅说明单,本页两种语言版本上都是西班牙文。每个170 × 227 mm的页面放在一张大22 mm的纸上,多出的部分承载出血和裁切线。封面上,一条橙色路线穿过层层渐变绿色的群岛,越过裁切边伸进出血区。内页中,四个展厅用齐左的Karla排,各在一个路标式眉题下开头,一个橙色标签把页码带到书口外侧;封底在一条地形色带上方放一张平面图。示例导出两份文件:印刷文件是按FOGRA51分色的PDF/X-4(FOGRA51即150 g铜版纸所用的PSO Coated v3印刷条件),带字体、书签和页面标签;另一份是灰度校样。提供这两份文件之前,示例先对版面做印前检查。印刷文件中的地图和平面图取自手工选定油墨的印刷母版,文字、标签和路标圆环则通过一套用CMYK指定的调色板,使用同样的油墨。
这道食谱解答
- 怎样制作带出血、裁切标记、书签、页码标签和色彩空间的可付印PDF?
- 怎样在浏览器中导出嵌入字体的真正PDF?
- 怎样给每一页加水印、背景底色或装饰图片?
简短回答
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
}
用料
做法
#1 · 按印版挑选屏幕颜色
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' }用postext自带的FOGRA51特性文件为每一种颜色分色。中性灰只印在黑版上,K值按明度匹配选取:#161616变成K95,书眉的#666666变成K66,100% K的文字叠印。按特性文件,森林绿会印成C90 M43 Y71 K62,橙色会印成C0 M70 Y90 K0,与母版中的路线(第5步)略有色差,所以这两种颜色连同鼠尾草绿和纸色都用CMYK指定:ColorValue.cmyk保存油墨配比,十六进制值留给屏幕,凡是链接到调色板的地方都按写下的配比印刷。纸色是C0 M0 Y0 K0:在森林绿上反白的文字不用任何油墨,所以没有哪块印版能让它错位。
#2 · 经得起裁切刀的书口标签
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')] };
标签的框挂在出血框上,比成品标签宽BLEED,所以即使裁切落在成品线外1 mm,切口处仍有橙色;页码挂在页面框,也就是成品线上,在剩下的10 mm内居中。parity决定每个元素出现在哪些页上,edge随之改变,好让元素抵达书口;pages: 'body'让标签和书眉(取自前置元数据的{title}和{subtitle})不出现在封面和封底上。封面和封底都算章首页,因为它们各以一个通栏或另起一页的标题开头。任何页眉或页脚元素都能这样重复,所以一个带parity和pages的image可以在每页放一个水印或装饰图。这些槽位画在文字上方,文字下方的底色要放在page.backgroundColor里。
#3 · 图稿到出血,文字在成品线内
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在页面每边加上出血、裁切线偏移和5 mm长的裁切线,这里合计11 mm。偏移默认是3 mm,与这里的出血相等,所以裁切线从出血边开始向外延伸;出血更宽时,裁切线仍从出血边开始,绝不进入出血区。一个锚定在出血框、设了width: 'fill'的图片元素取该框的宽度,并保持自身比例:封面地图按176 × 233 mm绘制,即成品尺寸每边加3 mm,所以它恰好到达裁切线起点所在的出血边,而文字挂在版心上,远在成品线以内。封底是一个标题样式,它的页脚取代文档的页脚:同一个生成器画出的色带锚定在出血框底部,下页边距让正文止于色带上方8 mm。
#4 · 变成书签的标题
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根据标题生成书签,所以每个展厅都是一个一级标题,接排而不分页;numberingTemplate给眉题提供{number},也给书签提供前缀。PDF中依次列出封面、从“Sala 1 Una isla en ninguna parte”到“Sala 4 La isla del tesoro”的四个展厅,以及参观信息。设计过的标题会隐藏自身文字,但仍保留它供书签和标签结构使用;如果不设fontFamily,这段隐藏文字会用Open Sans 700排,页面要为此加载这个字体,PDF也要为这几段文字单独嵌入它。页面标签遵循page.pageNumbering,这里保持默认,即从1开始的阿拉伯数字,所以PDF阅读器中的第3页就是书口标签上印着3的那一页。
#5 · 用准确油墨制作印刷母版
// 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)]));
每幅图只以路径定义一次。art区域把它们转成Canvas绘制用的SVG,这个区域则把同样的路径写进一个单页CMYK PDF,所选的配比让校样与屏幕一致:海面是C100 M45 Y80 K55,也就是调色板中的森林绿。每个资源在svg.pdfFileId中指明自己的母版;renderToPdf按这个id索取文件,简短回答里的pressPdf()用母版的字节作答,postext-pdf原样嵌入那一页,保持矢量,使用母版自己的油墨。平面图是一幅图,封面地图和封底色带是设计图片,三者都是如此。灰度校样则改用SVG,因为嵌入的母版从不转换,会保持彩色。
完整食谱
// ═══ 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
组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)
变化
#印刷厂要求5 mm出血
图稿、标签和比例尺都以BLEED定尺寸,裁切线从出血边开始,所以要5 mm出血只需改这一处,每张纸随之变为196 × 253 mm。
-const BLEED = 3; // 图稿越过成品线的毫米数:封面、书口标签和封底色带都延伸到这里
+const BLEED = 5; // 图稿越过成品线的毫米数:封面、书口标签和封底色带都延伸到这里#用SVG印图稿
没有pdfFileId时,印刷文件用各自的SVG绘制每张图,仍是矢量,同样经过特性文件:用CMYK指定的森林绿保持C100 M45 Y80 K55,岛屿的其他绿色则采用特性文件的分色,而不是手工选定的配比。
- updatedAt: 0, ...extra, svg: { fileId: `${id}.svg`, pdfFileId: `${id}.pdf`,
+ updatedAt: 0, ...extra, svg: { fileId: `${id}.svg`,常见问题
易错点
SVG插图中不要用<marker>或滤镜(会退回位图)
SVG图只有在不含<marker>、滤镜和蒙版时,才能在PDF中保持矢量;否则会退回位图,而且层层嵌套的滤镜可能让它在Chrome中变成空白。箭头用路径来画。 作为资源的图和表 →
易错点
Fontsource的文件只覆盖字母,不含符号
工具包嵌入每种字体在Fontsource的latin文件;正文用到č、ł、†时再嵌入latin-ext文件,用到α、χ时再嵌入greek文件(字体族须有该文件:Lora和Gelasio没有),屏幕和PDF都一样。→、≈、✓、★等符号不在这些文件里,会在PDF中缺失:把它们画出来、写成数学公式,或换用文件中包含它们的字体。 嵌入PDF的字体 →
- PDF/X标准总是写出CMYK,不管
colorSpace怎么设,所以灰度校样除了colorSpace: 'grayscale',还要用{ standard: 'none' }覆盖print。 - 没有输出特性文件,PDF/X渲染就会失败。
renderToPdf从profileBaseUrl(这里是postext.dev的/icc/)下载fogra51.icc;要自己提供,就把文件的字节作为outputProfile传入。 - 印前检查会标出小于9 pt、用一种以上油墨印刷的文字。森林绿的7.5 pt粗体标签印在铜版纸上,用四种油墨也能保持清晰,所以
print.preflight.smallTextSize设为7 pt;6.3 pt的版权说明如果用鼠尾草绿,会在四色色带上用三种油墨印刷,所以改为反白成纸色。 - PDF/X文件不带链接注释,因为交付印刷的文件在出血框内不能有注释;书签保留。
- 生成之后,每个按钮会变成一个“Open the PDF ↗”链接和一个下载链接,只有下载链接带文件名。
致谢
- 文本
- 原创文字, CC BY 4.0
- 字体
- Karla (SIL OFL 1.1) · Space Grotesk (SIL OFL 1.1) · Space Mono (SIL OFL 1.1)


