import { PDFDocument, StandardFonts, degrees, rgb } from 'pdf-lib';
import { loadPDF, pdfFile } from '../expansion/pdf.js';
import { text, num, choice, color, assert, json, zip, canvas, encode } from './common.js';
const MM = 72 / 25.4;
const paper = () => choice('paper', '纸张', [['a4', 'A4'], ['letter', 'Letter']]);
const paperSize = (value) => value === 'letter' ? [612, 792] : [595.276, 841.89];
const padding = () => num('margin', '页边距(mm)', 8, 0, 40);
function checked(doc) { assert(doc.getPageCount() <= 100, '输出页数超过100页。'); return doc; }
async function source(files, index = 0) { assert(files[index], '请选择PDF文件。'); return loadPDF(files[index]); }
function visible(page) {
const m = page.getMediaBox(), c = page.getCropBox(), x = Math.max(m.x, c.x), y = Math.max(m.y, c.y), right = Math.min(m.x + m.width, c.x + c.width), top = Math.min(m.y + m.height, c.y + c.height);
const angle = (page.getRotation().angle % 360 + 360) % 360; assert([0, 90, 180, 270].includes(angle) && right > x && top > y && right - x <= 20000 && top - y <= 20000, 'PDF可视区域或旋转角度无效。');
return { box: { left: x, bottom: y, right, top }, width: right - x, height: top - y, angle };
}
async function embedded(out, page) {
const d = visible(page), image = page.node.Contents() ? await out.embedPage(page, d.box) : null; return { image, angle: d.angle, width: d.angle % 180 ? d.height : d.width, height: d.angle % 180 ? d.width : d.height };
}
function place(target, e, left, bottom, width, height, opacity = 1) {
if (!e.image) return;
assert(width > 0 && height > 0, '页边距超过可用区域。'); const scale = Math.min(width / e.width, height / e.height), x = left + (width - e.width * scale) / 2, y = bottom + (height - e.height * scale) / 2;
const dx = e.angle === 180 ? e.image.width * scale : e.angle === 270 ? e.image.height * scale : 0, dy = e.angle === 90 ? e.image.width * scale : e.angle === 180 ? e.image.height * scale : 0;
target.drawPage(e.image, { x: x + dx, y: y + dy, xScale: scale, yScale: scale, rotate: degrees(-e.angle), opacity });
}
async function normalized(doc) {
const out = await PDFDocument.create(); for (const page of doc.getPages()) { const e = await embedded(out, page); place(out.addPage([e.width, e.height]), e, 0, 0, e.width, e.height); } return out;
}
export const pdf_split_all = (() => ({ fields: [], async run({ files }) {
const doc = await source(files), entries = []; for (const i of doc.getPageIndices()) { const out = await PDFDocument.create(), [page] = await out.copyPages(doc, [i]); out.addPage(page); entries.push(await pdfFile(out, `page-${String(i + 1).padStart(3, '0')}.pdf`)); }
return [await zip(entries, 'pdf-pages.zip'), json({ pages: entries.map((e) => e.name) }, 'pages.json')];
} }))();
export const pdf_booklet = (() => ({ fields: [paper(), padding(), choice('binding', '装订方向', [['left', '左侧装订'], ['right', '右侧装订']])], async run({ files, values: v }) {
const doc = await source(files), out = await PDFDocument.create(), count = doc.getPageCount(), padded = Math.ceil(count / 4) * 4, [ph, pw] = paperSize(v.paper), margin = v.margin * MM, order = [], pages = [];
for (const page of doc.getPages()) pages.push(await embedded(out, page));
for (let sheet = 0; sheet < padded / 4; sheet++) for (const side of [0, 1]) {
const numbers = side === 0 ? [padded - sheet * 2, sheet * 2 + 1] : [sheet * 2 + 2, padded - sheet * 2 - 1]; if (v.binding === 'right') numbers.reverse();
const page = out.addPage([pw, ph]); numbers.forEach((n, col) => { if (n <= count) place(page, pages[n - 1], col * pw / 2 + margin, margin, pw / 2 - margin * 2, ph - margin * 2); }); order.push({ sheet: sheet + 1, side: side ? 'back' : 'front', sourcePages: numbers.map((n) => n <= count ? n : null) });
}
return [await pdfFile(checked(out), 'booklet.pdf'), json({ inputPages: count, paddedPages: padded, order, printing: '按输出顺序双面打印、短边翻转;先用一张纸确认设备走纸方向。' }, 'booklet-order.json')];
} }))();
export const pdf_nup = (() => ({ fields: [paper(), num('columns', '每页列数', 2, 1, 4), num('rows', '每页行数', 2, 1, 4), padding()], async run({ files, values: v }) {
const doc = await source(files), out = await PDFDocument.create(), [pw, ph] = paperSize(v.paper), cw = pw / v.columns, ch = ph / v.rows, margin = v.margin * MM, order = []; assert(cw > margin * 2 && ch > margin * 2, '页边距超过单元格尺寸。');
for (let i = 0; i < doc.getPageCount(); i++) { const slot = i % (v.rows * v.columns); if (slot === 0) out.addPage([pw, ph]); const row = Math.floor(slot / v.columns), col = slot % v.columns; place(out.getPages().at(-1), await embedded(out, doc.getPage(i)), col * cw + margin, ph - (row + 1) * ch + margin, cw - margin * 2, ch - margin * 2); order.push({ sourcePage: i + 1, outputPage: out.getPageCount(), row: row + 1, column: col + 1 }); }
return [await pdfFile(checked(out), 'n-up.pdf'), json(order, 'n-up-order.json')];
} }))();
export const pdf_number = (() => ({ fields: [num('start', '起始编号', 1, 0, 9999), num('size', '字号(pt)', 12, 6, 36), num('margin', '距底边(mm)', 8, 2, 40), choice('position', '位置', [['center', '居中'], ['left', '靠左'], ['right', '靠右']])], async run({ files, values: v }) {
const doc = await normalized(await source(files)), font = await doc.embedFont(StandardFonts.Helvetica), margin = v.margin * MM;
for (const [i, page] of doc.getPages().entries()) { const value = String(v.start + i), w = font.widthOfTextAtSize(value, v.size); assert(margin + v.size < page.getHeight() && w + margin * 2 < page.getWidth(), '页码或边距超出页面。'); const x = v.position === 'left' ? margin : v.position === 'right' ? page.getWidth() - margin - w : (page.getWidth() - w) / 2; page.drawText(value, { x, y: margin, size: v.size, font, color: rgb(.12, .2, .16) }); }
return [await pdfFile(doc, 'numbered.pdf'), json({ first: v.start, last: v.start + doc.getPageCount() - 1 }, 'numbering.json')];
} }))();
export const pdf_watermark = (() => ({ fields: [text('content', '水印文字', '内部资料'), num('size', '字号(pt)', 40, 12, 100), num('opacity', '不透明度', .2, .05, 1, .05), num('angle', '逆时针角度', 30, -90, 90), color('fill', '文字颜色', '#167d68')], async run({ files, values: v }) {
assert([...v.content].length <= 40, '水印最多40字符。'); const doc = await normalized(await source(files)), probe = canvas(1, 1).getContext('2d'); probe.font = `${v.size * 2}px sans-serif`; const width = Math.ceil(probe.measureText(v.content).width + 20), height = v.size * 3; assert(width <= 4096, '水印文字过宽。'); const image = canvas(width, height), ctx = image.getContext('2d'); ctx.font = probe.font; ctx.fillStyle = v.fill; ctx.fillText(v.content, 10, v.size * 2);
const embedded = await doc.embedPng(await (await encode(image)).arrayBuffer());
for (const page of doc.getPages()) { const w = Math.min(width / 2, page.getWidth() * .8, page.getHeight() * .8), h = w * height / width, angle = v.angle * Math.PI / 180, x = page.getWidth() / 2 - w / 2 * Math.cos(angle) + h / 2 * Math.sin(angle), y = page.getHeight() / 2 - w / 2 * Math.sin(angle) - h / 2 * Math.cos(angle); page.drawImage(embedded, { x, y, width: w, height: h, opacity: v.opacity, rotate: degrees(v.angle) }); }
return [await pdfFile(doc, 'watermarked.pdf')];
} }))();
function metadata(doc) { return { title: doc.getTitle() || '', author: doc.getAuthor() || '', subject: doc.getSubject() || '', keywords: doc.getKeywords() || '', creator: doc.getCreator() || '', producer: doc.getProducer() || '', creationDate: doc.getCreationDate()?.toISOString(), modificationDate: doc.getModificationDate()?.toISOString() }; }
export const pdf_metadata = (() => ({ fields: [choice('mode', '操作', [['read', '读取属性'], ['write', '修改标题、作者与主题']]), text('title', '标题', '文档标题'), text('author', '作者', '作者'), text('subject', '主题', '文档主题')], async run({ files, values: v }) {
const doc = await source(files), before = metadata(doc); if (v.mode === 'read') return [json(before, 'metadata.json')]; doc.setTitle(v.title); doc.setAuthor(v.author); doc.setSubject(v.subject);
return [await pdfFile(doc, 'metadata.pdf'), json({ before, after: metadata(doc), scope: '修改文档信息字典,不清除XMP或隐藏内容。' }, 'metadata.json')];
} }))();
export const pdf_page_boxes = (() => ({ fields: [], async run({ files }) {
const doc = await source(files); return [json(doc.getPages().map((p, i) => ({ page: i + 1, rotation: p.getRotation().angle, mediaBox: p.getMediaBox(), cropBox: p.getCropBox(), bleedBox: p.getBleedBox(), trimBox: p.getTrimBox(), artBox: p.getArtBox(), visible: visible(p), unit: 'PDF point (1/72 inch)' })), 'page-boxes.json')];
} }))();
export const pdf_crop = (() => ({ fields: [num('left', '原坐标左边裁量(mm)', 5, 0, 100), num('right', '原坐标右边裁量(mm)', 5, 0, 100), num('top', '原坐标上边裁量(mm)', 5, 0, 100), num('bottom', '原坐标下边裁量(mm)', 5, 0, 100)], async run({ files, values: v }) {
const doc = await source(files), report = [];
for (const [i, p] of doc.getPages().entries()) { const d = visible(p), width = d.width - (v.left + v.right) * MM, height = d.height - (v.top + v.bottom) * MM; assert(width >= 10 && height >= 10, `第${i + 1}页裁量过大。`); p.setCropBox(d.box.left + v.left * MM, d.box.bottom + v.bottom * MM, width, height); report.push({ page: i + 1, before: d.box, after: p.getCropBox(), rotation: d.angle }); }
return [await pdfFile(doc, 'cropped.pdf'), json({ pages: report, note: '裁量按PDF未旋转坐标方向;只改CropBox,隐藏内容仍在文件中。' }, 'crop-report.json')];
} }))();
export const pdf_blank = (() => ({ fields: [num('width', '纸张宽度(mm)', 210, 10, 1000), num('height', '纸张高度(mm)', 297, 10, 1000), num('pages', '页数', 1, 1, 100)], async run({ values: v }) {
const doc = await PDFDocument.create(); for (let i = 0; i < v.pages; i++) doc.addPage([v.width * MM, v.height * MM]); return [await pdfFile(doc, 'blank.pdf')];
} }))();
export const pdf_interleave = (() => ({ fields: [choice('order', '每组先放', [['first', '第一份PDF'], ['second', '第二份PDF']])], async run({ files, values: v }) {
assert(files.length === 2, '请选择两份PDF。'); const docs = [await source(files), await source(files, 1)], out = await PDFDocument.create(), order = []; assert(docs[0].getPageCount() + docs[1].getPageCount() <= 100, '合并后最多100页。'); const sequence = v.order === 'first' ? [0, 1] : [1, 0];
for (let i = 0; i < Math.max(...docs.map((d) => d.getPageCount())); i++) for (const index of sequence) if (i < docs[index].getPageCount()) { const [p] = await out.copyPages(docs[index], [i]); out.addPage(p); order.push({ file: index + 1, sourcePage: i + 1, outputPage: out.getPageCount() }); }
return [await pdfFile(out, 'interleaved.pdf'), json(order, 'interleave-order.json')];
} }))();
export const pdf_overlay = (() => ({ fields: [num('opacity', '覆盖页不透明度', .5, .05, 1, .05)], async run({ files, values: v }) {
assert(files.length === 2, '请按底稿、覆盖页的顺序选择两份PDF。'); const base = await source(files), overlay = await source(files, 1), out = await PDFDocument.create(); assert(overlay.getPageCount() === 1 || overlay.getPageCount() === base.getPageCount(), '覆盖PDF须为1页或与底稿页数相同。');
for (const [i, p] of base.getPages().entries()) { const e = await embedded(out, p), page = out.addPage([e.width, e.height]); place(page, e, 0, 0, e.width, e.height); const top = await embedded(out, overlay.getPage(overlay.getPageCount() === 1 ? 0 : i)); place(page, top, 0, 0, e.width, e.height, v.opacity); }
return [await pdfFile(out, 'overlay.pdf')];
} }))();
export const pdf_poster = (() => ({ fields: [num('columns', '横向分块', 2, 1, 5), num('rows', '纵向分块', 2, 1, 5), num('overlap', '相邻块重叠(mm)', 3, 0, 30)], async run({ files, values: v }) {
const doc = await normalized(await source(files)), out = await PDFDocument.create(), report = []; assert(doc.getPageCount() * v.rows * v.columns <= 100, '分块输出最多100页。');
for (const [i, page] of doc.getPages().entries()) { const w = page.getWidth(), h = page.getHeight(), cw = w / v.columns, ch = h / v.rows, overlap = v.overlap * MM; assert(overlap < Math.min(cw, ch), '重叠宽度超过分块尺寸。');
for (let row = 0; row < v.rows; row++) for (let col = 0; col < v.columns; col++) { const left = Math.max(0, col * cw - overlap / 2), right = Math.min(w, (col + 1) * cw + overlap / 2), bottom = Math.max(0, h - (row + 1) * ch - overlap / 2), top = Math.min(h, h - row * ch + overlap / 2), target = out.addPage([right - left, top - bottom]); if (page.node.Contents()) target.drawPage(await out.embedPage(page, { left, bottom, right, top }), { x: 0, y: 0 }); report.push({ sourcePage: i + 1, outputPage: out.getPageCount(), row: row + 1, column: col + 1, crop: { left, bottom, right, top } }); }
}
return [await pdfFile(out, 'poster-tiles.pdf'), json({ pages: report, note: '输出纸张尺寸等于分块实际尺寸;按100%打印可保持原比例。' }, 'poster-tiles.json')];
} }))();