DEV Community

eth shihao
eth shihao

Posted on

Print-ready PDF layout with crop marks, CSV mail merge, and two-up imposition

A four-page wedding newspaper fits on one duplex sheet. Put page 4 to the left of page 1 on the outside, and page 2 to the left of page 3 on the inside. A CSV with two guests then produces four PDF pages, in pairs ready for duplex printing.

Give the press room to trim

This job finishes at 17 × 11 in unfolded, or 8.5 × 11 in folded. The example uses 18 × 12 in stock to fit a 0.125 in bleed and crop marks around the trim. An 11 × 17 in sheet is already the finished size and needs a printer that can handle the intended margins, or a design with white space at its edges. Confirm stock, bleed, and marks with the print shop before writing the final file. Adobe printer’s marks guidance

PDF box Size in points Lower-left corner
MediaBox and CropBox 1296 × 864 (0, 0)
BleedBox 1242 × 810 (27, 27)
TrimBox 1224 × 792 (36, 36)

The trim rectangle sits in the center of the stock. Extend the background 9 pt past each outside edge. Start the crop marks 12 pt from trim so their ink lies beyond the bleed. Put the fold ticks at the center x-coordinate, outside the top and bottom bleed. The left and right backgrounds meet at the fold without extra stock between them. PDF 1.7, section 14.11.2 · Adobe booklet setup

Merge records and draw both sides

Save the example as newspaper.mts. With Node.js 24, run npm install pdf-lib@1.17.1, then node newspaper.mts for the built-in sample or node newspaper.mts guests.csv for your own data. Use the header guest_id,name,table,note. The parser handles a BOM, LF and CRLF, quoted commas, multiline quoted fields, and doubled quotes. It expects a small CSV with this fixed schema. RFC 4180 CSV conventions

import assert from "node:assert/strict";
import { readFile, writeFile } from "node:fs/promises";
import { PDFDocument, StandardFonts, rgb } from "pdf-lib";
import type { PDFFont, PDFPage } from "pdf-lib";

type Guest = { id: string; name: string; table: string; note: string };

function guestsFromCsv(csv: string): Guest[] {
  const source = csv.replace(/^\uFEFF/, "");
  const field = /(?:"((?:[^"]|"")*)"|([^",\r\n]*))(,|\r\n|\n|$)/y;
  const rows: string[][] = [];
  let row: string[] = [];
  let offset = 0;
  while (offset < source.length) {
    field.lastIndex = offset;
    const match = field.exec(source);
    if (!match) throw new Error("Invalid CSV near character " + (offset + 1));
    offset = field.lastIndex;
    row.push(match[1] === undefined ? match[2] : match[1].replace(/""/g, '"'));
    if (match[3] !== ",") {
      rows.push(row);
      row = [];
    }
  }
  if (row.length) rows.push([...row, ""]); // Trailing comma at EOF.
  const [header, ...records] = rows;
  assert.deepEqual(header, ["guest_id", "name", "table", "note"]);
  const ids = new Set<string>();
  return records.map((fields, i) => {
    if (fields.length !== 4) throw new Error("Expected four fields in record " + (i + 1));
    const [id, name, table, note] = fields.map((value) => value.trim());
    if (!id || !name || !table || ids.has(id)) {
      throw new Error("Missing required value or duplicate guest ID in record " + (i + 1));
    }
    ids.add(id);
    return { id, name, table, note };
  });
}

const pt = (inches: number) => 72 * inches;
const stockWidth = pt(18);
const stockHeight = pt(12);
const panelWidth = pt(8.5);
const trimWidth = panelWidth * 2;
const trimHeight = pt(11);
const bleed = pt(0.125);
const left = (stockWidth - trimWidth) / 2;
const bottom = (stockHeight - trimHeight) / 2;
const right = left + trimWidth;
const top = bottom + trimHeight;
const fold = left + panelWidth;
const ink = rgb(0, 0, 0);

function marks(page: PDFPage) {
  const offset = 12;
  const length = 12;
  const mark = (x1: number, y1: number, x2: number, y2: number) =>
    page.drawLine({ start: { x: x1, y: y1 }, end: { x: x2, y: y2 }, thickness: 0.35, color: ink });

  for (const [x, dx] of [[left, -1], [right, 1]]) {
    for (const [y, dy] of [[bottom, -1], [top, 1]]) {
      mark(x + dx * offset, y, x + dx * (offset + length), y);
      mark(x, y + dy * offset, x, y + dy * (offset + length));
    }
  }
  mark(fold, bottom - offset, fold, bottom - offset - length);
  mark(fold, top + offset, fold, top + offset + length);
}

function wrapText(text: string, font: PDFFont, size: number, width: number): string[] {
  const lines: string[] = [];
  let current = "";
  for (const word of text.trim().split(/\s+/u).filter(Boolean)) {
    if (font.widthOfTextAtSize(word, size) > width) throw new Error("Word exceeds column width");
    const candidate = current ? current + " " + word : word;
    if (current && font.widthOfTextAtSize(candidate, size) > width) {
      lines.push(current);
      current = word;
    } else {
      current = candidate;
    }
  }
  if (current) lines.push(current);
  return lines;
}

const fixture = [
  "guest_id,name,table,note",
  '001,"Rivera, Sam",07,"Welcome, Sam! The toast is at 6."',
  '002,Avery Chen,04,"Look for the ""Garden"" table.',
  'The first dance is at 7."',
].join("\r\n");
const input = process.argv[2];
const guests = guestsFromCsv(input ? await readFile(input, "utf8") : fixture);
if (!guests.length) throw new Error("CSV contains no guests");
if (!input) {
  assert.equal(guests[0].name, "Rivera, Sam");
  assert.equal(guests[0].table, "07");
  assert.match(guests[1].note, /"Garden" table\.\r\nThe first dance/);
}

const doc = await PDFDocument.create();
const font = await doc.embedFont(StandardFonts.Helvetica);
const sides = [[4, 1], [2, 3]] as const;

for (const guest of guests) {
  const copy = {
    1: `Welcome to the wedding, ${guest.name}!`,
    2: `Your seat is at table ${guest.table}.`,
    3: guest.note,
    4: "Thank you for celebrating with us.",
  };
  for (const spread of sides) {
    const page = doc.addPage([stockWidth, stockHeight]);
    page.setCropBox(0, 0, stockWidth, stockHeight);
    page.setTrimBox(left, bottom, trimWidth, trimHeight);
    page.setBleedBox(left - bleed, bottom - bleed, trimWidth + 2 * bleed, trimHeight + 2 * bleed);

    spread.forEach((number, column) => {
      const x = left + column * panelWidth;
      page.drawRectangle({
        x: column === 0 ? x - bleed : x, y: bottom - bleed,
        width: panelWidth + bleed, height: trimHeight + 2 * bleed,
        color: column === 0 ? rgb(0.95, 0.97, 0.99) : rgb(0.99, 0.96, 0.90),
      });
      page.drawText("THE WEDDING EDITION", { x: x + 36, y: top - 62, font, size: 24 });

      const lines = wrapText(copy[number], font, 15, panelWidth - 72);
      if (lines.length > 8) throw new Error(`Guest ${guest.id}, page ${number}: copy overflows`);
      lines.forEach((line, i) => {
        page.drawText(line, { x: x + 36, y: top - 105 - 19 * i, font, size: 15, color: ink });
      });
      page.drawText(`${guest.id} / ${number}`, { x: x + 36, y: bottom + 36, font, size: 10 });
    });
    marks(page);
  }
}

const bytes = await doc.save();
const proof = await PDFDocument.load(bytes);
assert.equal(proof.getPageCount(), 2 * guests.length);
assert.deepEqual(proof.getPage(0).getTrimBox(), { x: 36, y: 36, width: 1224, height: 792 });
assert.deepEqual(proof.getPage(0).getBleedBox(), { x: 27, y: 27, width: 1242, height: 810 });
await writeFile("wedding-newspapers.pdf", bytes);
console.log(`${proof.getPageCount()} PDF pages for ${guests.length} duplex sheets`);
Enter fullscreen mode Exit fullscreen mode

The fixture produces 4 PDF pages for 2 duplex sheets. Quoted commas stay inside the name field, and a table value of 07 stays a string. The template wraps to measured font widths and stops the export if a row exceeds the available copy area. It collapses whitespace in the printed copy. For a guest list outside Helvetica's WinAnsi repertoire, embed a font with the needed glyphs and verify shaping if the script requires it. pdf-lib font embedding API

Fold one proof before running the batch

Print the first pair at actual size, duplex, with short-edge flip as the starting setting for this landscape file. Trim on the crop marks and fold it. Check that the cover reads upright, all four panels are in order, and the personalized text fits. Ask the shop which PDF/X preset, output profile, and image resolution it requires for the production run. These files use RGB vector shapes and standard Helvetica for the geometry and mail-merge demonstration. Adobe print production guidance

WedPaperPack is published by the team behind this article. It offers a four-page editor, a folded preview, and an 11 × 17 in duplex layout with a separate fold test for local print-shop handoff. WedPaperPack

AI disclosure. This article was generated with AI.

Top comments (0)