Add the Neutral template family, template picker and text-only logo allowances
Linea (the vendor's original format.pdf design), Monogram and Serenity are rebuilt from the Canva PDFs as one parametric family on the engine, with the user's logo in the measured slot, a home for every GST field and A4/Letter support. Adds static Montserrat, Open Sans and Poppins fonts and a generated Ms Madi outline for Serenity's vertical word. Text-only logo placeholders (Monolith, Tangerine) use a doc-derived allowance box. A Carbon TemplatePicker with committed thumbnails opens from the page setup controls.
This commit is contained in:
@@ -0,0 +1,225 @@
|
||||
// Generates src/pdf/decor/scriptWord.generated.ts: the word "invoice" as SVG outline paths (Serenity's
|
||||
// vertical title) plus a hand-built swash. Run: npm run decor:script-word
|
||||
//
|
||||
// The outlines come from Ms Madi Regular (SIL OFL 1.1), read with fontkit at build time. The font file lives in
|
||||
// scripts/decor/source/ for reproducibility only; it is never copied into public/fonts, never registered with
|
||||
// react-pdf and never embedded as a font: the PDF carries filled paths, so this is art, not text. Canva's
|
||||
// SimpleSerenityScript is not used or traced.
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import ClipperLib from "clipper-lib";
|
||||
import * as fontkit from "fontkit";
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
|
||||
const FONT = path.join(ROOT, "scripts/decor/source/MsMadi-Regular.ttf");
|
||||
const OUT = path.join(ROOT, "src/pdf/decor/scriptWord.generated.ts");
|
||||
const WORD = "invoice";
|
||||
/** Length of the word's ink along its reading direction, pt (Canva's word runs from y 780 to y 410). */
|
||||
const INK_LENGTH = 362;
|
||||
/**
|
||||
* Ms Madi's strokes are heavier than Canva's hairline script at this size. The glyph contours are merged
|
||||
* into one outline and shrunk by this much on every side (pt), which thins the strokes without a
|
||||
* paper-coloured stroke trick at render time.
|
||||
*/
|
||||
const THIN_BY = 0.95;
|
||||
/** Clipper works in integers: coordinates are multiplied by this. */
|
||||
const K = 1000;
|
||||
|
||||
const r2 = (v) => Math.round(v * 100) / 100;
|
||||
|
||||
/** Flattened outline commands of the laid-out word, in font units (y up, origin on the baseline start). */
|
||||
function wordCommands(font) {
|
||||
const run = font.layout(WORD);
|
||||
const cmds = [];
|
||||
let x = 0;
|
||||
run.glyphs.forEach((g, i) => {
|
||||
const pos = run.positions[i];
|
||||
for (const c of g.path.commands) {
|
||||
const args = [];
|
||||
for (let k = 0; k < c.args.length; k += 2) args.push(c.args[k] + x + pos.xOffset, c.args[k + 1] + pos.yOffset);
|
||||
cmds.push({ command: c.command, args });
|
||||
}
|
||||
x += pos.xAdvance;
|
||||
});
|
||||
return cmds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotates the word 90 degrees counter-clockwise so it reads bottom to top, scales it to INK_LENGTH and moves
|
||||
* its bounding box to the origin (the shrink in `thinned` then re-origins it). In page space (y down) a font point (x, yUp) lands at (-yUp, -x).
|
||||
*/
|
||||
function rotate(cmds) {
|
||||
const pts = cmds.flatMap((c) => c.args);
|
||||
const xs = pts.filter((_, i) => i % 2 === 0);
|
||||
const ys = pts.filter((_, i) => i % 2 === 1);
|
||||
const inkLen = Math.max(...xs) - Math.min(...xs);
|
||||
const s = INK_LENGTH / inkLen;
|
||||
const map = (x, y) => [-y * s, -x * s];
|
||||
const mapped = cmds.map((c) => {
|
||||
const a = [];
|
||||
for (let k = 0; k < c.args.length; k += 2) a.push(...map(c.args[k], c.args[k + 1]));
|
||||
return { command: c.command, args: a };
|
||||
});
|
||||
const mx = mapped.flatMap((c) => c.args.filter((_, i) => i % 2 === 0));
|
||||
const my = mapped.flatMap((c) => c.args.filter((_, i) => i % 2 === 1));
|
||||
const [x0, y0] = [Math.min(...mx), Math.min(...my)];
|
||||
const width = Math.max(...mx) - x0;
|
||||
const height = Math.max(...my) - y0;
|
||||
const shifted = mapped.map((c) => ({ command: c.command, args: c.args.map((v, i) => (i % 2 === 0 ? v - x0 : v - y0)) }));
|
||||
return { cmds: shifted, width, height, scale: s };
|
||||
}
|
||||
|
||||
/** Flattens the outline commands into closed polylines (pt). */
|
||||
function flatten(cmds) {
|
||||
const polys = [];
|
||||
let cur = [];
|
||||
let last = [0, 0];
|
||||
const close = () => {
|
||||
if (cur.length > 2) polys.push(cur);
|
||||
cur = [];
|
||||
};
|
||||
for (const c of cmds) {
|
||||
if (c.command === "moveTo") {
|
||||
close();
|
||||
cur = [c.args];
|
||||
last = c.args;
|
||||
} else if (c.command === "lineTo") {
|
||||
cur.push(c.args);
|
||||
last = c.args;
|
||||
} else if (c.command === "quadraticCurveTo") {
|
||||
const [cx, cy, x, y] = c.args;
|
||||
for (let i = 1; i <= 10; i++) {
|
||||
const t = i / 10;
|
||||
const u = 1 - t;
|
||||
cur.push([u * u * last[0] + 2 * u * t * cx + t * t * x, u * u * last[1] + 2 * u * t * cy + t * t * y]);
|
||||
}
|
||||
last = [x, y];
|
||||
} else if (c.command === "bezierCurveTo") {
|
||||
const [c1x, c1y, c2x, c2y, x, y] = c.args;
|
||||
for (let i = 1; i <= 14; i++) {
|
||||
const t = i / 14;
|
||||
const u = 1 - t;
|
||||
cur.push([
|
||||
u * u * u * last[0] + 3 * u * u * t * c1x + 3 * u * t * t * c2x + t * t * t * x,
|
||||
u * u * u * last[1] + 3 * u * u * t * c1y + 3 * u * t * t * c2y + t * t * t * y,
|
||||
]);
|
||||
}
|
||||
last = [x, y];
|
||||
} else if (c.command === "closePath") close();
|
||||
}
|
||||
close();
|
||||
return polys;
|
||||
}
|
||||
|
||||
/** Union of all contours, shrunk by THIN_BY, as one path. Returns { d, width, height, shiftX } with the box moved to the origin. */
|
||||
function thinned(cmds) {
|
||||
const subj = flatten(cmds).map((poly) => poly.map(([x, y]) => ({ X: Math.round(x * K), Y: Math.round(y * K) })));
|
||||
const clipper = new ClipperLib.Clipper();
|
||||
clipper.AddPaths(subj, ClipperLib.PolyType.ptSubject, true);
|
||||
const merged = new ClipperLib.Paths();
|
||||
clipper.Execute(ClipperLib.ClipType.ctUnion, merged, ClipperLib.PolyFillType.pftNonZero, ClipperLib.PolyFillType.pftNonZero);
|
||||
const offset = new ClipperLib.ClipperOffset(2, 0.05 * K);
|
||||
offset.AddPaths(merged, ClipperLib.JoinType.jtRound, ClipperLib.EndType.etClosedPolygon);
|
||||
const eroded = new ClipperLib.Paths();
|
||||
offset.Execute(eroded, -THIN_BY * K);
|
||||
const clean = ClipperLib.Clipper.CleanPolygons(eroded, 0.04 * K);
|
||||
const pts = clean.flat();
|
||||
const x0 = Math.min(...pts.map((p) => p.X)) / K;
|
||||
const y0 = Math.min(...pts.map((p) => p.Y)) / K;
|
||||
const x1 = Math.max(...pts.map((p) => p.X)) / K;
|
||||
const y1 = Math.max(...pts.map((p) => p.Y)) / K;
|
||||
const d = clean
|
||||
.filter((poly) => poly.length > 2)
|
||||
.map((poly) => `M${poly.map((p) => `${r2(p.X / K - x0)} ${r2(p.Y / K - y0)}`).join("L")}Z`)
|
||||
.join("");
|
||||
// Where the word ends (its topmost point): the swash continues from here.
|
||||
const top = pts.reduce((a, p) => (p.Y < a.Y ? p : a), pts[0]);
|
||||
return { d, width: x1 - x0, height: y1 - y0, anchorX: top.X / K - x0 };
|
||||
}
|
||||
|
||||
/** The swash spine is drawn this much wider than first designed, to match the 25 pt width of Canva's swash. */
|
||||
const SWASH_X_SCALE = 1.4;
|
||||
|
||||
const bez = (p0, p1, p2, p3, t) => {
|
||||
const u = 1 - t;
|
||||
return [0, 1].map((k) => u * u * u * p0[k] + 3 * u * u * t * p1[k] + 3 * u * t * t * p2[k] + t * t * t * p3[k]);
|
||||
};
|
||||
|
||||
/**
|
||||
* A tapered swash: a spine of cubic segments, thickened by a sine envelope into one filled outline.
|
||||
* Own drawing, in a 28 x 270 pt box; it continues upward from the end of the word like Canva's does.
|
||||
*/
|
||||
function swash() {
|
||||
const segs = [
|
||||
[[19, 270], [-2, 222], [30, 176], [13, 130]],
|
||||
[[13, 130], [-4, 86], [26, 52], [15, 14]],
|
||||
[[15, 14], [11, 2], [22, -1], [24, 7]],
|
||||
];
|
||||
const spine = [];
|
||||
segs.forEach((s, si) => {
|
||||
for (let i = si === 0 ? 0 : 1; i <= 40; i++) { const q = bez(s[0], s[1], s[2], s[3], i / 40); spine.push([q[0] * SWASH_X_SCALE, q[1]]); }
|
||||
});
|
||||
const n = spine.length;
|
||||
const left = [];
|
||||
const right = [];
|
||||
spine.forEach((p, i) => {
|
||||
const a = spine[Math.max(0, i - 1)];
|
||||
const b = spine[Math.min(n - 1, i + 1)];
|
||||
const len = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1;
|
||||
const nx = -(b[1] - a[1]) / len;
|
||||
const ny = (b[0] - a[0]) / len;
|
||||
const u = i / (n - 1);
|
||||
const half = 0.25 + 1.25 * Math.pow(Math.sin(Math.PI * Math.min(1, u * 1.15)), 0.9);
|
||||
left.push([p[0] + nx * half, p[1] + ny * half]);
|
||||
right.push([p[0] - nx * half, p[1] - ny * half]);
|
||||
});
|
||||
const all = [...left, ...right.reverse()];
|
||||
const minY = Math.min(...all.map((p) => p[1]));
|
||||
const minX = Math.min(...all.map((p) => p[0]));
|
||||
const maxX = Math.max(...all.map((p) => p[0]));
|
||||
const maxY = Math.max(...all.map((p) => p[1]));
|
||||
const pts = all.map(([x, y]) => [x - minX, y - minY]);
|
||||
// The spine starts at the bottom of the box: that point meets the end of the word.
|
||||
const anchorX = spine[0][0] - minX;
|
||||
const d = `M${pts.map((p) => p.map(r2).join(" ")).join("L")}Z`;
|
||||
return { d, width: r2(maxX - minX), height: r2(maxY - minY), anchorX: r2(anchorX) };
|
||||
}
|
||||
|
||||
const font = fontkit.create(readFileSync(FONT));
|
||||
const rotated = rotate(wordCommands(font));
|
||||
const thin = thinned(rotated.cmds);
|
||||
const word = { d: thin.d, width: thin.width, height: thin.height, anchorX: thin.anchorX };
|
||||
const sw = swash();
|
||||
const ts = `// Generated by \`npm run decor:script-word\` (scripts/decor/script-word.mjs). Do not edit by hand.
|
||||
//
|
||||
// Outline paths of the word "${WORD}" traced from Ms Madi Regular, rotated 90 degrees counter-clockwise (reads
|
||||
// bottom to top), plus a hand-drawn swash. Ms Madi is Copyright 2018 The Ms Madi Project Authors
|
||||
// (https://github.com/googlefonts/ms-madi), licensed under the SIL Open Font License 1.1 (scripts/decor/source/OFL-MsMadi.txt).
|
||||
// The font itself is not bundled or registered: only these vector outlines are drawn, as art.
|
||||
|
||||
export interface ScriptArt {
|
||||
/** SVG path data in a box of \`width\` x \`height\` pt starting at the origin (page space, y down). */
|
||||
d: string;
|
||||
width: number;
|
||||
height: number;
|
||||
/** x inside the box where the word ends (word) or the swash starts (swash): they are joined here. */
|
||||
anchorX: number;
|
||||
}
|
||||
|
||||
export const SCRIPT_WORD: ScriptArt = {
|
||||
d: ${JSON.stringify(word.d)},
|
||||
width: ${r2(word.width)},
|
||||
height: ${r2(word.height)},
|
||||
anchorX: ${r2(word.anchorX)},
|
||||
};
|
||||
|
||||
export const SCRIPT_SWASH: ScriptArt = {
|
||||
d: ${JSON.stringify(sw.d)},
|
||||
width: ${sw.width},
|
||||
height: ${sw.height},
|
||||
anchorX: ${sw.anchorX},
|
||||
};
|
||||
`;
|
||||
writeFileSync(OUT, ts);
|
||||
console.log(`scriptWord.generated.ts: word ${r2(word.width)} x ${r2(word.height)} pt swash ${sw.width} x ${sw.height} pt`);
|
||||
Binary file not shown.
@@ -0,0 +1,93 @@
|
||||
Copyright 2018 The Ms Madi Project Authors (https://github.com/googlefonts/ms-madi)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -136,7 +136,14 @@ async function main() {
|
||||
for (const id of ids) {
|
||||
const slot = slotFor(id);
|
||||
const page = await renderPage(TEMPLATE_PDF[id]);
|
||||
const L = slot.lockup;
|
||||
// The region covers the placeholder and, for a text-only one, its (larger) allowance.
|
||||
const L = slot.textOnly
|
||||
? { x: Math.min(slot.lockup.x, slot.allowance.x), y: Math.min(slot.lockup.y, slot.allowance.y), w: 0, h: 0 }
|
||||
: slot.lockup;
|
||||
if (slot.textOnly) {
|
||||
L.w = Math.max(slot.lockup.x + slot.lockup.w, slot.allowance.x + slot.allowance.w) - L.x;
|
||||
L.h = Math.max(slot.lockup.y + slot.lockup.h, slot.allowance.y + slot.allowance.h) - L.y;
|
||||
}
|
||||
const region = {
|
||||
x: Math.max(0, Math.floor(L.x - PAD)),
|
||||
y: Math.max(0, Math.floor(L.y - PAD)),
|
||||
@@ -158,7 +165,7 @@ async function main() {
|
||||
ctx.font = "bold 16px sans-serif";
|
||||
ctx.fillText("Logo placement sign-off sheet (Canva placeholder, then four test logos)", 8, 22);
|
||||
ctx.font = "12px sans-serif";
|
||||
ctx.fillText("Red outline = measured placeholder box, blue = mark box. Dashed = opt-in area (no Canva placeholder). Green = logo box as placed.", 8, 40);
|
||||
ctx.fillText("Red = measured placeholder box, blue = mark box, orange dashed = allowance of a text-only placeholder, red dashed = opt-in area (no Canva placeholder). Green = logo box as placed.", 8, 40);
|
||||
const heads = ["Canva placeholder", ...logos.map((l) => `${l.label} (${l.aspect.toFixed(2)}:1, d ${l.density.toFixed(2)})`)];
|
||||
ctx.font = "bold 11px sans-serif";
|
||||
heads.forEach((t, i) => ctx.fillText(t, LABEL_W + GUTTER + i * (cellW + GUTTER), HEAD_H - 6));
|
||||
@@ -182,6 +189,7 @@ async function main() {
|
||||
const lines = [
|
||||
slot.optIn ? "opt-in, off by default" : "Canva placeholder",
|
||||
`lockup ${f(slot.lockup)}`,
|
||||
...(slot.textOnly ? [`text-only: allowance ${f(slot.allowance)}`] : []),
|
||||
`mark ${f(slot.mark)}`,
|
||||
`density ${slot.lockupDensity.toFixed(2)} / ${slot.markDensity.toFixed(2)}`,
|
||||
`${slot.anchor}, ${slot.vAlign}${slot.darkSurface ? ", dark surface" : ""}`,
|
||||
@@ -214,6 +222,7 @@ async function main() {
|
||||
if (slot.optIn) box(ctx, slot.lockup, region, "#dd0000", true);
|
||||
else {
|
||||
box(ctx, slot.lockup, region, "#dd0000");
|
||||
if (slot.textOnly) box(ctx, slot.allowance, region, "#e08a00", true);
|
||||
if (slot.mark && slot.mark !== slot.lockup && slot.mark.w !== slot.lockup.w) box(ctx, slot.mark, region, "#0066cc");
|
||||
}
|
||||
c.restore();
|
||||
|
||||
@@ -39,6 +39,30 @@ const SEARCH_RECTS = {
|
||||
13: { id: "citrus-split", rect: { x: 325, y: 65, w: 165, h: 55 }, kind: "lockup", anchor: "left", vAlign: "middle", dark: false },
|
||||
};
|
||||
|
||||
/*
|
||||
* Allowances for text-only placeholders: the placeholder's own box (46.8 x 9 pt, 82.5 x 14.8 pt) would
|
||||
* make a real logo unreadable, so the target box comes from the template docs and keeps the text's
|
||||
* anchor edge.
|
||||
* monolith docs/templates/03-monolith.md "Mapping to Voiced fields": 'CAVEIN' becomes the vendor logo,
|
||||
* right-aligned, at most 28 pt tall so the 3-line stack keeps its 21 pt pitch (a 3:1 PNG is
|
||||
* 84 x 28); up to 160 wide, ending at the same right edge (x 560); top at the text's cap top.
|
||||
* tangerine-ledger docs/templates/11-tangerine-ledger.md "Mapping": 'Rimberio' becomes the vendor logo, maxHeight 36
|
||||
* at x 59.5, y about 62; up to 220 wide, left edge kept.
|
||||
*/
|
||||
const ALLOWANCES = {
|
||||
monolith: { w: 160, h: 28, top: 54.75, vAlign: "top" },
|
||||
"tangerine-ledger": { w: 220, h: 36, top: 62, vAlign: "middle" },
|
||||
};
|
||||
|
||||
const r2 = (v) => Math.round(v * 100) / 100;
|
||||
|
||||
/** The allowance box for a text-only slot: its width and height from the docs, anchored where the text is. */
|
||||
function allowanceBox(id, lockup, anchor) {
|
||||
const a = ALLOWANCES[id];
|
||||
const x = anchor === "right" ? lockup.x + lockup.w - a.w : lockup.x;
|
||||
return { x: r2(x), y: a.top, w: a.w, h: a.h };
|
||||
}
|
||||
|
||||
const TEMPLATE_IDS = [
|
||||
"classic", "marble", "highlighter", "monolith", "linea", "monogram", "serenity", "crimson-grid",
|
||||
"cobalt-stripe", "slate-band", "teal-swoosh", "tangerine-ledger", "purple-pop", "citrus-split",
|
||||
@@ -125,8 +149,6 @@ function firstColumnGroup(mask, w, h, box) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const r2 = (v) => Math.round(v * 100) / 100;
|
||||
|
||||
function toPt(rect, box) {
|
||||
return {
|
||||
x: r2(rect.x + box.minX / SCALE),
|
||||
@@ -172,6 +194,7 @@ async function main() {
|
||||
}
|
||||
|
||||
const rounded = (v) => Math.round(v * 1000) / 1000;
|
||||
const textOnly = spec.kind === "text";
|
||||
slots[spec.id] = {
|
||||
page: { w: PAGE.w, h: PAGE.h },
|
||||
mark: markBox,
|
||||
@@ -179,8 +202,10 @@ async function main() {
|
||||
markDensity: rounded(markDensity),
|
||||
lockupDensity: rounded(lockupDensity),
|
||||
anchor: spec.anchor,
|
||||
vAlign: spec.vAlign,
|
||||
vAlign: textOnly ? ALLOWANCES[spec.id].vAlign : spec.vAlign,
|
||||
darkSurface: spec.dark,
|
||||
textOnly,
|
||||
allowance: textOnly ? allowanceBox(spec.id, lockupBox, spec.anchor) : lockupBox,
|
||||
};
|
||||
rows.push({ n, id: spec.id, mark: markBox, lockup: lockupBox, markDensity, lockupDensity, anchor: spec.anchor, dark: spec.dark, bg });
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
// Side-by-side review of the Neutral templates: the Canva original (left) against our render (right), plus
|
||||
// the multi-page, Letter and long-text samples. Run: npm run templates:compare [-- linea monogram serenity]
|
||||
// Output: /tmp/invoice-c3/. With --numbers it also prints text baselines (Canva vs ours) for tuning.
|
||||
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { CANVA_DIR, loadCanvas, loadRenderer, rasterize, textItems } from "./lib.mjs";
|
||||
|
||||
const OUT = "/tmp/invoice-c3";
|
||||
const SCALE = 1.6;
|
||||
const PDF_NO = { marble: 1, highlighter: 2, monolith: 3, linea: 4, monogram: 5, serenity: 6 };
|
||||
const args = process.argv.slice(2);
|
||||
const numbers = args.includes("--numbers");
|
||||
const ids = args.filter((a) => !a.startsWith("--"));
|
||||
const targets = ids.length ? ids : ["linea", "monogram", "serenity"];
|
||||
|
||||
const LONG = "Unit 4, Third Floor, The Grand Heritage Business Centre, Plot 1187-B, Old Airport Road Extension, Opposite the Municipal Corporation Ward Office, Domlur Second Stage, Bengaluru Urban District, Karnataka State, India - 560071; Registered office: Level 12, Tower C, Global Technology Park, Outer Ring Road, Marathahalli, Bengaluru - 560103";
|
||||
const TOKEN = "Supercalifragilisticexpialidocious-Pneumonoultramicroscopic-1234567890";
|
||||
|
||||
async function main() {
|
||||
mkdirSync(OUT, { recursive: true });
|
||||
const { createCanvas } = await loadCanvas();
|
||||
const r = await loadRenderer();
|
||||
r.ensureSetup();
|
||||
const side = async (left, right, file) => {
|
||||
const gap = 12;
|
||||
const c = createCanvas(left.width + right.width + gap, Math.max(left.height, right.height));
|
||||
const ctx = c.getContext("2d");
|
||||
ctx.fillStyle = "#888888";
|
||||
ctx.fillRect(0, 0, c.width, c.height);
|
||||
ctx.drawImage(left, 0, 0);
|
||||
ctx.drawImage(right, left.width + gap, 0);
|
||||
writeFileSync(path.join(OUT, file), c.toBuffer("image/png"));
|
||||
};
|
||||
|
||||
for (const id of targets) {
|
||||
const no = PDF_NO[id];
|
||||
const canvaBytes = readFileSync(path.join(CANVA_DIR, `${no}.pdf`));
|
||||
const canva = await rasterize(canvaBytes, 1, SCALE);
|
||||
const rows = id === "linea" ? 7 : 5;
|
||||
const NAMES = ["Brand consultation", "Logo design", "Website design", "Social media templates", "Brand photography", "Brand guide", "Social media templates"];
|
||||
// Short one-line descriptions like the Canva sample, so positions can be compared row by row.
|
||||
const items = (hsn) => NAMES.slice(0, rows).map((description, i) => ({ id: i + 1, description, mode: "rate", rate: 100, unit: "hour", quantity: 1, amount: 0, sortOrder: i, ...(hsn ? { hsnSac: "998397" } : {}) }));
|
||||
const sample = (over = {}) => ({ name: `s-${id}`, items: items(over.registered !== false), signature: true, invoice: { poNumber: "", notes: "Payment due within 30 days.\nLate payments attract 2% monthly interest." }, ...over });
|
||||
const render = async (spec, size = "A4") => {
|
||||
const prefs = r.prefsFor(size, { templateId: id });
|
||||
return r.renderFixture(spec, prefs);
|
||||
};
|
||||
|
||||
const withLogo = await render(sample({ logo: "real" }));
|
||||
await side(canva, await rasterize(withLogo.result.bytes, 1, SCALE), `compare-${id}.png`);
|
||||
const noLogo = await render(sample({ registered: false, logo: "none" }));
|
||||
await side(canva, await rasterize(noLogo.result.bytes, 1, SCALE), `compare-${id}-nologo.png`);
|
||||
if (numbers) {
|
||||
const a = await textItems(canvaBytes);
|
||||
const b = await textItems(withLogo.result.bytes);
|
||||
console.log(`--- ${id}: Canva (${a.length}) vs ours (${b.length}); baseline y, x`);
|
||||
for (const it of a) console.log(` canva ${String(it.baseline).padStart(6)} ${String(it.x).padStart(6)} w${String(it.w).padStart(6)} s${it.size} ${it.str.slice(0, 40)}`);
|
||||
for (const it of b) console.log(` ours ${String(it.baseline).padStart(6)} ${String(it.x).padStart(6)} w${String(it.w).padStart(6)} s${it.size} ${it.str.slice(0, 40)}`);
|
||||
}
|
||||
|
||||
if (id === "linea") {
|
||||
// The opt-in logo band (off by default so Linea keeps matching format.pdf).
|
||||
const shown = await r.renderFixture(sample({ logo: "real" }), r.prefsFor("A4", { templateId: id, logo: { show: true } }));
|
||||
writeFileSync(path.join(OUT, `${id}-A4-logo-optin.png`), (await rasterize(shown.result.bytes, 1, SCALE)).toBuffer("image/png"));
|
||||
}
|
||||
for (const logo of ["square", "wide"]) {
|
||||
const x = await render(sample({ logo }));
|
||||
writeFileSync(path.join(OUT, `${id}-A4-logo-${logo}.png`), (await rasterize(x.result.bytes, 1, SCALE)).toBuffer("image/png"));
|
||||
}
|
||||
const sixty = await render({ name: "s60", items: 60, signature: true });
|
||||
for (let p = 1; p <= Math.min(2, sixty.result.pages); p++) writeFileSync(path.join(OUT, `${id}-A4-60rows-p${p}.png`), (await rasterize(sixty.result.bytes, p, SCALE)).toBuffer("image/png"));
|
||||
const letter = await render(sample({ logo: "real" }), "LETTER");
|
||||
writeFileSync(path.join(OUT, `${id}-Letter-tax.png`), (await rasterize(letter.result.bytes, 1, SCALE)).toBuffer("image/png"));
|
||||
const long = await render({
|
||||
name: "long",
|
||||
items: 4,
|
||||
signature: true,
|
||||
logo: "real",
|
||||
vendor: { vendorAddress: LONG, vendorEmail: `${TOKEN}@example-studios-india.co.in`, vendorName: TOKEN },
|
||||
invoice: { clientName: TOKEN, clientAddress: LONG, notes: `Note: ${TOKEN} ${LONG}` },
|
||||
});
|
||||
writeFileSync(path.join(OUT, `${id}-A4-longtext.png`), (await rasterize(long.result.bytes, 1, SCALE)).toBuffer("image/png"));
|
||||
console.log(`${id}: pages ${withLogo.result.pages}/${sixty.result.pages}/${letter.result.pages}/${long.result.pages}; audit issues`, [withLogo, noLogo, sixty, letter, long].map((x) => x.result.issues.length).join("/"));
|
||||
for (const x of [withLogo, noLogo, sixty, letter, long]) for (const i of x.result.issues) console.log(" ", i.severity, i.code, `p${i.page}`, i.message.slice(0, 160));
|
||||
}
|
||||
}
|
||||
|
||||
await main();
|
||||
@@ -0,0 +1,4 @@
|
||||
// Bundled by scripts/templates/lib.mjs so plain node can render templates (the PDF code is TypeScript + JSX).
|
||||
export { buildFixture, ensureSetup, FIXTURES, prefsFor, renderFixture, makeItems } from "../../src/pdf/templates/harness";
|
||||
export type { FixtureSpec } from "../../src/pdf/templates/harness";
|
||||
export { TEMPLATES } from "../../src/pdf/templates/registry";
|
||||
@@ -0,0 +1,82 @@
|
||||
// Shared by the template scripts (thumbnails, compare): bundles the TypeScript renderer for node and
|
||||
// rasterises PDFs with pdf.js + @napi-rs/canvas.
|
||||
import { build } from "esbuild";
|
||||
import { mkdirSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { ROOT } from "../logo/lib.mjs";
|
||||
|
||||
export { ROOT };
|
||||
export const CANVA_DIR = path.join(ROOT, "templates", "Modern Neutral Invoice Template");
|
||||
|
||||
/**
|
||||
* Bundles scripts/templates/entry.ts into node_modules/.cache (so bare imports such as react resolve from
|
||||
* node_modules) and imports it. Node packages stay external; only the app's own sources are bundled.
|
||||
*/
|
||||
export async function loadRenderer() {
|
||||
const dir = path.join(ROOT, "node_modules", ".cache", "voiced-templates");
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const outfile = path.join(dir, `bundle-${Date.now()}.mjs`);
|
||||
await build({
|
||||
entryPoints: [path.join(ROOT, "scripts/templates/entry.ts")],
|
||||
outfile,
|
||||
bundle: true,
|
||||
packages: "external",
|
||||
platform: "node",
|
||||
format: "esm",
|
||||
jsx: "automatic",
|
||||
logLevel: "error",
|
||||
});
|
||||
return import(pathToFileURL(outfile).href);
|
||||
}
|
||||
|
||||
export async function loadCanvas() {
|
||||
try {
|
||||
return await import("@napi-rs/canvas");
|
||||
} catch {
|
||||
console.error("@napi-rs/canvas is not installed (it is an optional dev dependency); run npm install");
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/** Rasterises page `pageNo` of PDF bytes at `scale` on a white background; returns the canvas. */
|
||||
export async function rasterize(bytes, pageNo = 1, scale = 1.6) {
|
||||
const { createCanvas } = await loadCanvas();
|
||||
const pdfjs = await import("pdfjs-dist/legacy/build/pdf.mjs");
|
||||
const task = pdfjs.getDocument({ data: new Uint8Array(bytes), useSystemFonts: false, disableFontFace: true, isEvalSupported: false, verbosity: 0 });
|
||||
const doc = await task.promise;
|
||||
try {
|
||||
const page = await doc.getPage(pageNo);
|
||||
const vp = page.getViewport({ scale });
|
||||
const canvas = createCanvas(Math.ceil(vp.width), Math.ceil(vp.height));
|
||||
const ctx = canvas.getContext("2d");
|
||||
ctx.fillStyle = "#ffffff";
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
await page.render({ canvasContext: ctx, canvas, viewport: vp }).promise;
|
||||
return canvas;
|
||||
} finally {
|
||||
await task.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
/** Text items of page 1 with baselines measured from the page top, for numeric comparison. */
|
||||
export async function textItems(bytes, pageNo = 1) {
|
||||
const pdfjs = await import("pdfjs-dist/legacy/build/pdf.mjs");
|
||||
const task = pdfjs.getDocument({ data: new Uint8Array(bytes), useSystemFonts: false, disableFontFace: true, isEvalSupported: false, verbosity: 0 });
|
||||
const doc = await task.promise;
|
||||
try {
|
||||
const page = await doc.getPage(pageNo);
|
||||
const vp = page.getViewport({ scale: 1 });
|
||||
const content = await page.getTextContent();
|
||||
return content.items
|
||||
.filter((it) => "str" in it && it.str.trim() !== "")
|
||||
.map((it) => {
|
||||
const m = vp.transform;
|
||||
const [px, py] = [it.transform[4], it.transform[5]];
|
||||
const [x, y] = [m[0] * px + m[2] * py + m[4], m[1] * px + m[3] * py + m[5]];
|
||||
return { str: it.str, x: Math.round(x * 10) / 10, baseline: Math.round(y * 10) / 10, w: Math.round(it.width * 10) / 10, size: Math.round(Math.hypot(it.transform[0], it.transform[1]) * 10) / 10 };
|
||||
});
|
||||
} finally {
|
||||
await task.destroy();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Renders every registered template with one fixed sample invoice into public/templates/<id>.png, the
|
||||
// static thumbnails of the template picker. Run: npm run thumbnails (the PNGs are committed).
|
||||
// The sample is the harness's tax invoice with The sample vendor's logo; the picker says that thumbnails use sample data.
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { ROOT, loadRenderer, rasterize } from "./templates/lib.mjs";
|
||||
|
||||
const OUT = path.join(ROOT, "public", "templates");
|
||||
const WIDTH = 420;
|
||||
const A4_WIDTH_PT = 595.28;
|
||||
|
||||
const ITEMS = [
|
||||
["Voice-over narration", 4, 1500],
|
||||
["Audio mastering", 2, 800],
|
||||
].map(([description, quantity, rate], i) => ({
|
||||
id: i + 1,
|
||||
description,
|
||||
mode: "rate",
|
||||
rate,
|
||||
unit: "hour",
|
||||
quantity,
|
||||
amount: 0,
|
||||
sortOrder: i,
|
||||
hsnSac: "998397",
|
||||
}));
|
||||
|
||||
const SAMPLE = {
|
||||
name: "thumbnail",
|
||||
items: ITEMS,
|
||||
logo: "real",
|
||||
signature: false,
|
||||
// A leaner supplier block keeps the whole design (closing block included) on the thumbnail's one page.
|
||||
vendor: { vendorEmail: "", vendorPhone: "", vendorPan: "" },
|
||||
invoice: { poNumber: "", notes: "" },
|
||||
};
|
||||
|
||||
const r = await loadRenderer();
|
||||
r.ensureSetup();
|
||||
mkdirSync(OUT, { recursive: true });
|
||||
for (const id of Object.keys(r.TEMPLATES)) {
|
||||
const rendered = await r.renderFixture(SAMPLE, r.prefsFor("A4", { templateId: id }));
|
||||
const canvas = await rasterize(rendered.result.bytes, 1, WIDTH / A4_WIDTH_PT);
|
||||
const file = path.join(OUT, `${id}.png`);
|
||||
writeFileSync(file, canvas.toBuffer("image/png"));
|
||||
console.log(`${id}: ${canvas.width} x ${canvas.height} px, ${rendered.result.pages} page(s), ${rendered.result.issues.length} audit issue(s)`);
|
||||
}
|
||||
Reference in New Issue
Block a user