Back to Nappakura
SOURCE / PINNED RELEASE

Made of little things.

Nappakura

Release
a75ca0f8b596…
Author-recorded commit
4463126213fa…
License
LICENSE
Author’s source reference
nostr://npub182jczunncwe0jn6frpqwq3e0qjws7yqqnc3auccqv9nte2dnd63scjm4rf/wss%3A%2F%2Fgit.napplet.soy%2F/n-8db03001b62

Archive hash verified: b448d77b767ae754…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/pdf.ts
import type { Mesh } from './mesh.js';
import { drawPiece, pageCount, paperSize, printIssues } from './unfold.js';
import type { Pattern } from './unfold.js';

const PT = 72 / 25.4;
const num = (n: number) => Number(n.toFixed(4)).toString();
const literal = (s: string) =>
  s.replace(/[^\x20-\x7e]/g, '?').replace(/[\\()]/g, '\\$&');

/** A small vector-only PDF 1.4 writer: millimetres → points, never fit-to-page. */
export function createPDF(mesh: Mesh, pattern: Pattern): Uint8Array {
  const issues = printIssues(mesh, pattern);
  if (issues.length) throw new Error(issues.join(' '));
  const [w, h] = paperSize(pattern.settings),
    objects: string[] = [];
  const add = (s: string) => {
    objects.push(s);
    return objects.length;
  };
  add('<< /Type /Catalog /Pages 2 0 R >>');
  add('');
  const font = add('<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>'),
    pages: number[] = [];
  for (let page = 0; page < pageCount(pattern); page++) {
    const commands = ['1 J 1 j', `${num(pattern.settings.lineWidth * PT)} w`];
    const point = (p: number[]) => `${num(p[0] * PT)} ${num((h - p[1]) * PT)}`;
    for (const piece of pattern.pieces.filter((p) => p.page === page)) {
      const drawing = drawPiece(mesh, pattern, piece);
      for (const tab of drawing.tabs)
        commands.push(
          '0.95 g',
          `${point(tab[0])} m ${tab
            .slice(1)
            .map((p) => `${point(p)} l`)
            .join(' ')} h f`,
        );
      for (const line of drawing.lines) {
        if (line.kind === 'flat') continue;
        const dash =
          line.kind === 'mountain'
            ? '[5.67 2.83]'
            : line.kind === 'valley'
              ? '[5.67 2.27 1.13 2.27]'
              : '[]';
        commands.push(
          `0.12 G ${dash} 0 d`,
          `${point(line.a)} m ${point(line.b)} l S`,
        );
      }
      for (const label of drawing.labels) {
        const c = Math.cos(label.angle),
          s = Math.sin(label.angle);
        commands.push(
          `0.28 g BT /F1 ${num(label.size * PT)} Tf ${num(c)} ${num(-s)} ${num(s)} ${num(c)} ${point(label.point)} Tm ${num(-label.text.length * label.size * 0.278 * PT)} ${num(-label.size * 0.3 * PT)} Td (${literal(label.text)}) Tj ET`,
        );
      }
    }
    commands.push(
      `0.35 g BT /F1 7 Tf 28.35 12 Td (${literal(`${mesh.name.slice(0, 44)} | ${page + 1}/${pageCount(pattern)} | Print at 100% / Actual size`)}) Tj ET`,
    );
    commands.push(
      `0.35 g BT /F1 6 Tf 28.35 23 Td (Solid: cut | Dashed: mountain | Dash-dot: valley | Glue grey tabs behind matching edge numbers.) Tj ET`,
    );
    // Reference bar is 20 mm, matching physical scale irrespective of page size.
    const bx = w - 35,
      by = h - 5;
    commands.push(
      `0.3 G [] 0 d 0.5 w ${point([bx, by])} m ${point([bx + 20, by])} l S`,
      `${point([bx, by - 1])} m ${point([bx, by + 1])} l S`,
      `${point([bx + 20, by - 1])} m ${point([bx + 20, by + 1])} l S`,
      `BT /F1 6 Tf ${point([bx + 6, by - 1.7])} Td (20 mm) Tj ET`,
    );
    const stream = commands.join('\n');
    const content = add(
      `<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`,
    );
    pages.push(
      add(
        `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${num(w * PT)} ${num(h * PT)}] /Resources << /Font << /F1 ${font} 0 R >> >> /Contents ${content} 0 R >>`,
      ),
    );
  }
  objects[1] = `<< /Type /Pages /Count ${pages.length} /Kids [${pages.map((i) => `${i} 0 R`).join(' ')}] >>`;
  let output = '%PDF-1.4\n',
    offsets = [0];
  objects.forEach((value, i) => {
    offsets.push(output.length);
    output += `${i + 1} 0 obj\n${value}\nendobj\n`;
  });
  const xref = output.length;
  output += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
  output += offsets
    .slice(1)
    .map((o) => `${String(o).padStart(10, '0')} 00000 n \n`)
    .join('');
  output += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
  return new TextEncoder().encode(output);
}