@toolpal/markdown-to-doc
publicv2.0published 1 download this weekMIT
Converts Markdown (inline or .md/.txt file) or structured JSON/sheets locally into a formatted Word (.docx), PDF (.pdf), or Excel (.xlsx) file. Supports headings, bold/italic/code, links, lists, code blocks, blockquotes, and tables. Offline, no API key needed.
You're viewing 1.0, an older version
The latest is 2.0.
// Zero-dependency PDF 1.4 vector writer with FlateDecode streams, wrapping, tables, code blocks & footers.
import { Buffer } from "node:buffer";
import { deflateSync } from "node:zlib";
import type { MdBlock } from "./markdown.js";
export interface PdfOptions {
title?: string;
subtitle?: string;
pageSize?: "letter" | "a4";
}
// WinAnsi character transliteration for standard PDF Type1 fonts (Helvetica / Courier).
const CHAR_MAP: Record<string, string> = {
"\u2018": "'",
"\u2019": "'",
"\u201C": '"',
"\u201D": '"',
"\u2013": "-",
"\u2014": "--",
"\u2026": "...",
"\u2022": "*",
"\u2192": "->",
"\u2190": "<-",
"\u2194": "<->",
"\u2264": "<=",
"\u2265": ">=",
"\u2260": "!=",
"\u20B9": "INR ",
"\u20AC": "EUR ",
"\u00A0": " ",
"\u200B": "",
};
function toWinAnsi(text: string): string {
let out = "";
for (const ch of text) {
if (CHAR_MAP[ch] !== undefined) {
out += CHAR_MAP[ch];
} else {
const code = ch.charCodeAt(0);
if (code >= 0x20 && code <= 0x7e) out += ch;
else if (code >= 0xa0 && code <= 0xff) out += ch;
else out += "?";
}
}
return out;
}
function pdfStr(text: string): string {
const safe = toWinAnsi(text);
let escaped = "";
for (let i = 0; i < safe.length; i++) {
const ch = safe[i];
const code = safe.charCodeAt(i);
if (ch === "\\" || ch === "(" || ch === ")") escaped += `\\${ch}`;
else if (code > 0x7e) escaped += `\\${code.toString(8).padStart(3, "0")}`;
else escaped += ch;
}
return `(${escaped})`;
}
// Approximate Helvetica glyph width ratio (relative to font size) for clean wrapping.
function charWidth(ch: string, fontSize: number, mono: boolean): number {
if (mono) return fontSize * 0.6;
if ("ilI1!.,;:'|".includes(ch)) return fontSize * 0.28;
if ("fjrt()[]{}- ".includes(ch)) return fontSize * 0.34;
if ("mwMW@%".includes(ch)) return fontSize * 0.84;
if (ch >= "A" && ch <= "Z") return fontSize * 0.68;
return fontSize * 0.54;
}
function textWidth(text: string, fontSize: number, mono: boolean): number {
let w = 0;
for (const ch of text) w += charWidth(ch, fontSize, mono);
return w;
}
function wrapText(text: string, maxWidth: number, fontSize: number, mono: boolean): string[] {
const safe = toWinAnsi(text);
const out: string[] = [];
for (const rawLine of safe.split("\n")) {
if (!rawLine.trim()) {
out.push("");
continue;
}
const words = mono ? [rawLine] : rawLine.split(/\s+/);
if (mono) {
const maxChars = Math.max(10, Math.floor(maxWidth / (fontSize * 0.6)));
for (let i = 0; i < rawLine.length; i += maxChars) {
out.push(rawLine.slice(i, i + maxChars));
}
continue;
}
let line = "";
for (const word of words) {
const candidate = line ? `${line} ${word}` : word;
if (textWidth(candidate, fontSize, false) <= maxWidth || !line) {
line = candidate;
} else {
out.push(line);
line = word;
}
}
if (line) out.push(line);
}
return out.length > 0 ? out : [""];
}
export function renderPdf(
blocks: MdBlock[],
opts: PdfOptions = {},
): { buffer: Buffer; pages: number } {
const pageW = opts.pageSize === "a4" ? 595.28 : 612;
const pageH = opts.pageSize === "a4" ? 841.89 : 792;
const marginX = 54;
const marginTop = 58;
const marginBottom = 58;
const contentW = pageW - marginX * 2;
const pages: string[][] = [];
let cmds: string[] = [];
let y = pageH - marginTop;
const newPage = () => {
if (cmds.length > 0) pages.push(cmds);
cmds = [];
y = pageH - marginTop;
};
const ensureSpace = (needed: number) => {
if (y - needed < marginBottom) newPage();
};
const drawText = (
text: string,
x: number,
baselineY: number,
font: "F1" | "F2" | "F3" | "F4",
size: number,
rgb = "0.06 0.09 0.16",
) => {
cmds.push(`BT /${font} ${size} Tf ${rgb} rg 1 0 0 1 ${x.toFixed(2)} ${baselineY.toFixed(2)} Tm ${pdfStr(text)} Tj ET`);
};
const drawRect = (x: number, bottomY: number, w: number, h: number, fillRgb?: string, strokeRgb?: string) => {
cmds.push("q");
if (fillRgb) cmds.push(`${fillRgb} rg`);
if (strokeRgb) cmds.push(`0.5 w ${strokeRgb} RG`);
const op = fillRgb && strokeRgb ? "B" : fillRgb ? "f" : "S";
cmds.push(`${x.toFixed(2)} ${bottomY.toFixed(2)} ${w.toFixed(2)} ${h.toFixed(2)} re ${op}`);
cmds.push("Q");
};
const drawLine = (x1: number, y1: number, x2: number, y2: number, width = 0.75, rgb = "0.80 0.84 0.88") => {
cmds.push(`q ${width} w ${rgb} RG ${x1.toFixed(2)} ${y1.toFixed(2)} m ${x2.toFixed(2)} ${y2.toFixed(2)} l S Q`);
};
if (opts.title) {
const lines = wrapText(opts.title, contentW, 22, false);
for (const line of lines) {
ensureSpace(28);
drawText(line, marginX, y - 20, "F2", 22, "0.06 0.09 0.16");
y -= 28;
}
y -= 4;
}
if (opts.subtitle) {
const lines = wrapText(opts.subtitle, contentW, 11, false);
for (const line of lines) {
ensureSpace(16);
drawText(line, marginX, y - 11, "F1", 11, "0.39 0.45 0.55");
y -= 16;
}
y -= 10;
}
for (const b of blocks) {
switch (b.type) {
case "heading": {
const size = b.level === 1 ? 16 : b.level === 2 ? 13.5 : 11.5;
const lead = size + 6;
const lines = wrapText(b.text, contentW, size, false);
ensureSpace(lines.length * lead + 18);
y -= b.level === 1 ? 12 : 8;
for (const line of lines) {
drawText(line, marginX, y - size, "F2", size, "0.12 0.23 0.37");
y -= lead;
}
if (b.level === 1) {
drawLine(marginX, y + 2, marginX + contentW, y + 2, 0.75, "0.85 0.89 0.94");
y -= 6;
} else {
y -= 3;
}
break;
}
case "paragraph": {
const lines = wrapText(b.text, contentW, 10.5, false);
for (const line of lines) {
ensureSpace(15);
drawText(line, marginX, y - 10.5, "F1", 10.5);
y -= 15;
}
y -= 6;
break;
}
case "quote": {
const lines = wrapText(b.text, contentW - 18, 10, false);
const h = lines.length * 14.5 + 6;
ensureSpace(h + 8);
drawLine(marginX + 4, y - 2, marginX + 4, y - h + 2, 2.5, "0.58 0.64 0.72");
y -= 3;
for (const line of lines) {
drawText(line, marginX + 14, y - 10, "F3", 10, "0.28 0.33 0.41");
y -= 14.5;
}
y -= 9;
break;
}
case "code": {
const lines = wrapText(b.code || " ", contentW - 16, 9, true);
const boxH = lines.length * 13 + 12;
if (boxH < pageH - marginTop - marginBottom) {
ensureSpace(boxH + 8);
drawRect(marginX, y - boxH, contentW, boxH, "0.95 0.96 0.98", "0.85 0.89 0.94");
y -= 6;
for (const line of lines) {
drawText(line, marginX + 8, y - 9, "F4", 9, "0.06 0.09 0.16");
y -= 13;
}
y -= 12;
} else {
for (const line of lines) {
ensureSpace(14);
drawRect(marginX, y - 13, contentW, 13, "0.95 0.96 0.98");
drawText(line, marginX + 8, y - 10, "F4", 9, "0.06 0.09 0.16");
y -= 13;
}
y -= 8;
}
break;
}
case "hr": {
ensureSpace(18);
y -= 8;
drawLine(marginX, y, marginX + contentW, y, 0.75, "0.80 0.84 0.88");
y -= 10;
break;
}
case "bullets":
case "numbered": {
b.items.forEach((item, idx) => {
const prefix = b.type === "bullets" ? "•" : `${idx + 1}.`;
const lines = wrapText(item.text, contentW - 22, 10.5, false);
lines.forEach((line, li) => {
ensureSpace(15);
if (li === 0) drawText(prefix, marginX + 4, y - 10.5, "F2", 10.5);
drawText(line, marginX + 22, y - 10.5, "F1", 10.5);
y -= 15;
});
y -= 2;
});
y -= 5;
break;
}
case "table": {
const colCount = Math.max(1, b.header.length);
const colW = contentW / colCount;
const allRows = [b.header, ...b.rows];
allRows.forEach((row, ri) => {
const isHeader = ri === 0;
const font = isHeader ? "F2" : "F1";
const cellLines = row.map((cell) => wrapText(cell ?? "", colW - 10, 9.5, false));
const maxLines = Math.max(1, ...cellLines.map((l) => l.length));
const rowH = maxLines * 13 + 10;
ensureSpace(rowH + 4);
if (isHeader) {
drawRect(marginX, y - rowH, contentW, rowH, "0.94 0.96 0.98", "0.80 0.84 0.88");
} else {
drawRect(marginX, y - rowH, contentW, rowH, undefined, "0.85 0.89 0.94");
}
for (let c = 0; c < colCount; c++) {
const x = marginX + c * colW;
if (c > 0) drawLine(x, y, x, y - rowH, 0.5, "0.85 0.89 0.94");
const lines = cellLines[c] ?? [""];
lines.forEach((line, li) => {
drawText(line, x + 5, y - 5 - 9.5 - li * 13, font, 9.5);
});
}
y -= rowH;
});
y -= 10;
break;
}
}
}
if (cmds.length > 0 || pages.length === 0) pages.push(cmds);
// Add subtle page footers ("Page N of M")
const totalPages = pages.length;
pages.forEach((pageCmds, i) => {
const footer = `Page ${i + 1} of ${totalPages}`;
const w = textWidth(footer, 8.5, false);
pageCmds.push(
`BT /F1 8.5 Tf 0.55 0.60 0.68 rg 1 0 0 1 ${((pageW - w) / 2).toFixed(2)} 30.00 Tm ${pdfStr(footer)} Tj ET`,
);
});
// Assemble PDF objects:
// 1: Catalog, 2: Pages, 3..6: Standard Type1 Fonts, then pairs of (Page, ContentStream)
const objects: Buffer[] = [];
const addObj = (body: string | Buffer): number => {
objects.push(typeof body === "string" ? Buffer.from(body, "latin1") : body);
return objects.length;
};
addObj("<< /Type /Catalog /Pages 2 0 R >>");
const pagesIndex = addObj(""); // placeholder replaced after page ids are known
const f1 = addObj("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>");
const f2 = addObj("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>");
const f3 = addObj("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Oblique /Encoding /WinAnsiEncoding >>");
const f4 = addObj("<< /Type /Font /Subtype /Type1 /BaseFont /Courier /Encoding /WinAnsiEncoding >>");
const pageIds: number[] = [];
for (const pageCmds of pages) {
const stream = deflateSync(Buffer.from(pageCmds.join("\n"), "latin1"));
const contentId = addObj(
Buffer.concat([
Buffer.from(`<< /Filter /FlateDecode /Length ${stream.length} >>\nstream\n`, "latin1"),
stream,
Buffer.from("\nendstream", "latin1"),
]),
);
const pageId = addObj(
`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${pageW.toFixed(2)} ${pageH.toFixed(2)}] /Resources << /Font << /F1 ${f1} 0 R /F2 ${f2} 0 R /F3 ${f3} 0 R /F4 ${f4} 0 R >> >> /Contents ${contentId} 0 R >>`,
);
pageIds.push(pageId);
}
objects[pagesIndex - 1] = Buffer.from(
`<< /Type /Pages /Kids [${pageIds.map((id) => `${id} 0 R`).join(" ")}] /Count ${pageIds.length} >>`,
"latin1",
);
const infoId = addObj(
`<< /Producer (toolpal-markdown-to-doc)${opts.title ? ` /Title ${pdfStr(opts.title)}` : ""} >>`,
);
const chunks: Buffer[] = [Buffer.from("%PDF-1.4\n%\xFF\xFF\xFF\xFF\n", "latin1")];
const offsets: number[] = [0];
let offset = chunks[0].length;
objects.forEach((obj, idx) => {
offsets.push(offset);
const head = Buffer.from(`${idx + 1} 0 obj\n`, "latin1");
const tail = Buffer.from("\nendobj\n", "latin1");
chunks.push(head, obj, tail);
offset += head.length + obj.length + tail.length;
});
const xrefOffset = offset;
const xrefLines = [
`xref\n0 ${objects.length + 1}\n`,
"0000000000 65535 f \n",
...offsets.slice(1).map((o) => `${String(o).padStart(10, "0")} 00000 n \n`),
`trailer\n<< /Size ${objects.length + 1} /Root 1 0 R /Info ${infoId} 0 R >>\nstartxref\n${xrefOffset}\n%%EOF\n`,
];
chunks.push(Buffer.from(xrefLines.join(""), "latin1"));
return { buffer: Buffer.concat(chunks), pages: totalPages };
}