RuneStone 1.0.0
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
// A small PDF writer for the fixture document: one page for each text, in Helvetica, with a correct cross-reference table.
|
||||
|
||||
function escapeText(text) {
|
||||
return text.replace(/[\\()]/g, match => `\\${match}`);
|
||||
}
|
||||
|
||||
/** Write a PDF with one US Letter page for each entry of `texts`. Return the bytes. */
|
||||
export function writePdf(texts) {
|
||||
if (!texts.length) throw new Error("A PDF needs at least one page.");
|
||||
// Object numbers: 1 catalog, 2 page tree, 3 font, then a page and its content stream for each text.
|
||||
const pageIds = texts.map((_, index) => 4 + index * 2);
|
||||
const objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
`<< /Type /Pages /Kids [${pageIds.map(id => `${id} 0 R`).join(" ")}] /Count ${texts.length} >>`,
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
|
||||
];
|
||||
for (const [index, text] of texts.entries()) {
|
||||
const stream = `BT /F1 48 Tf 72 680 Td (${escapeText(text)}) Tj ET\nBT /F1 14 Tf 72 640 Td (RuneStone measurement fixture, page ${index + 1} of ${texts.length}) Tj ET\n`;
|
||||
objects.push(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> /Contents ${pageIds[index] + 1} 0 R >>`);
|
||||
objects.push(`<< /Length ${Buffer.byteLength(stream, "latin1")} >>\nstream\n${stream}endstream`);
|
||||
}
|
||||
let body = "%PDF-1.4\n%\xe2\xe3\xcf\xd3\n";
|
||||
const offsets = [];
|
||||
for (const [index, object] of objects.entries()) {
|
||||
offsets.push(Buffer.byteLength(body, "latin1"));
|
||||
body += `${index + 1} 0 obj\n${object}\nendobj\n`;
|
||||
}
|
||||
const xref = Buffer.byteLength(body, "latin1");
|
||||
// Each entry is exactly 20 bytes, with a space and a line feed at the end.
|
||||
body += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
|
||||
for (const offset of offsets) body += `${String(offset).padStart(10, "0")} 00000 n \n`;
|
||||
body += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
|
||||
return Buffer.from(body, "latin1");
|
||||
}
|
||||
|
||||
/** Read the cross-reference table of a PDF from `writePdf`. Return `startxref` and the offsets of the objects in use. */
|
||||
export function readPdfXref(bytes) {
|
||||
const text = bytes.toString("latin1");
|
||||
const start = Number(/startxref\n(\d+)\n%%EOF\n?$/.exec(text)?.[1]);
|
||||
if (!Number.isInteger(start) || !text.startsWith("xref\n", start)) throw new Error("The startxref offset does not point to the xref table.");
|
||||
const lines = text.slice(start).split("\n");
|
||||
const [, count] = lines[1].split(" ").map(Number);
|
||||
const entries = lines.slice(2, 2 + count).map(line => ({ line, offset: Number(line.slice(0, 10)), used: line.slice(17, 18) === "n" }));
|
||||
return { start, count, entries };
|
||||
}
|
||||
Reference in New Issue
Block a user