import { readFileSync, statSync, writeFileSync } from "node:fs"; import { basename, extname, join } from "node:path"; import { inflateSync } from "node:zlib"; import { defineTool, FilePath, Type } from "@toolpal/tool"; import { degrees, PDFArray, PDFDict, PDFDocument, PDFName, PDFRawStream, PDFRef, PDFStream, rgb, StandardFonts, } from "pdf-lib"; const MAX_FILE_BYTES = 50 * 1024 * 1024; const MAX_MERGE_BYTES = 100 * 1024 * 1024; const MAX_SPLIT_OUTPUTS = 50; const ACTIONS = [ "inspect", "merge", "split", "rotate", "watermark", "extract_text", "set_metadata", ] as const; function safeStem(raw: string): string { return ( raw .toLowerCase() .replace(/[^a-z0-9]+/g, "-") .replace(/^-+|-+$/g, "") .slice(0, 60) || "output" ); } function readPdfBuffer(path: string, limit = MAX_FILE_BYTES): Buffer { const { size } = statSync(path); if (size > limit) { throw new Error( `${basename(path)} is ${(size / 1048576).toFixed(1)} MB; limit is ${Math.round(limit / 1048576)} MB.`, ); } return readFileSync(path); } /** Parses 1-based page specs like "1-3, 5, 8-end" into unique 0-based page indices. */ function parsePageSpec(spec: string, totalPages: number): number[] { const indices: number[] = []; const seen = new Set(); for (const part of spec.split(",")) { const token = part.trim().toLowerCase(); if (!token) continue; const range = token.match(/^(\d+)\s*-\s*(\d+|end|last)$/); if (range) { const start = Number(range[1]); const end = range[2] === "end" || range[2] === "last" ? totalPages : Number(range[2]); if (start < 1 || end < 1 || start > totalPages || end > totalPages) { throw new Error(`Page range "${part.trim()}" is out of bounds (document has ${totalPages} pages).`); } const step = start <= end ? 1 : -1; for (let p = start; step > 0 ? p <= end : p >= end; p += step) { if (!seen.has(p - 1)) { seen.add(p - 1); indices.push(p - 1); } } continue; } if (/^\d+$/.test(token)) { const p = Number(token); if (p < 1 || p > totalPages) { throw new Error(`Page ${p} is out of bounds (document has ${totalPages} pages).`); } if (!seen.has(p - 1)) { seen.add(p - 1); indices.push(p - 1); } continue; } throw new Error(`Invalid page specification "${part.trim()}". Use e.g. "1-3, 5, 8-end".`); } if (indices.length === 0) throw new Error("Page selection matched zero pages."); return indices; } function readMetadata(doc: PDFDocument) { const created = doc.getCreationDate(); const modified = doc.getModificationDate(); const kw = doc.getKeywords(); return { ...(doc.getTitle() ? { title: doc.getTitle() } : {}), ...(doc.getAuthor() ? { author: doc.getAuthor() } : {}), ...(doc.getSubject() ? { subject: doc.getSubject() } : {}), ...(kw ? { keywords: kw } : {}), ...(doc.getCreator() ? { creator: doc.getCreator() } : {}), ...(doc.getProducer() ? { producer: doc.getProducer() } : {}), ...(created && !Number.isNaN(created.getTime()) ? { creationDate: created.toISOString() } : {}), ...(modified && !Number.isNaN(modified.getTime()) ? { modificationDate: modified.toISOString() } : {}), }; } // --- Pure-JS PDF content-stream text extraction (handles FlateDecode + literal/hex strings + TJ) --- function decodePdfStreamBytes(stream: PDFStream): Buffer { if (!(stream instanceof PDFRawStream)) return Buffer.alloc(0); const raw = Buffer.from(stream.contents); const filter = stream.dict.get(PDFName.of("Filter")); const filterNames: string[] = []; if (filter instanceof PDFName) { filterNames.push(filter.decodeText()); } else if (filter instanceof PDFArray) { for (let i = 0; i < filter.size(); i++) { const f = filter.get(i); if (f instanceof PDFName) filterNames.push(f.decodeText()); } } if (filterNames.length === 0) return raw; if (filterNames.length === 1 && filterNames[0] === "FlateDecode") { try { return inflateSync(raw, { maxOutputLength: 20 * 1024 * 1024 }); } catch { return Buffer.alloc(0); } } return Buffer.alloc(0); } function decodeLiteralString(raw: string): string { let out = ""; for (let i = 0; i < raw.length; i++) { const ch = raw[i]; if (ch !== "\\") { out += ch; continue; } const next = raw[++i]; if (next === undefined) break; if (next === "n") out += "\n"; else if (next === "r") out += "\r"; else if (next === "t") out += "\t"; else if (next === "b") out += "\b"; else if (next === "f") out += "\f"; else if (next === "\n") { // line continuation } else if (next === "\r") { if (raw[i + 1] === "\n") i++; } else if (next >= "0" && next <= "7") { let oct = next; if (raw[i + 1] >= "0" && raw[i + 1] <= "7") oct += raw[++i]; if (raw[i + 1] >= "0" && raw[i + 1] <= "7") oct += raw[++i]; out += String.fromCharCode(Number.parseInt(oct, 8)); } else { out += next; } } return out; } function decodeHexString(hex: string, cmap?: Map): string { const clean = hex.replace(/\s+/g, ""); const padded = clean.length % 2 === 1 ? `${clean}0` : clean; if (cmap && cmap.size > 0) { // Try 2-byte codes first (CID fonts), then 1-byte if (padded.length % 4 === 0) { let matched = 0; let out = ""; for (let i = 0; i < padded.length; i += 4) { const code = Number.parseInt(padded.slice(i, i + 4), 16); const mapped = cmap.get(code); if (mapped !== undefined) { out += mapped; matched++; } else { out += String.fromCharCode(code); } } if (matched > 0) return out; } let out = ""; for (let i = 0; i < padded.length; i += 2) { const code = Number.parseInt(padded.slice(i, i + 2), 16); out += cmap.get(code) ?? String.fromCharCode(code); } return out; } const bytes = Buffer.from(padded, "hex"); if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) { let out = ""; for (let i = 2; i + 1 < bytes.length; i += 2) { out += String.fromCharCode((bytes[i] << 8) | bytes[i + 1]); } return out; } return bytes.toString("latin1"); } function parseToUnicodeCMap(text: string): Map { const map = new Map(); const decodeUtf16Hex = (hex: string): string => { let out = ""; for (let i = 0; i + 3 < hex.length; i += 4) { out += String.fromCharCode(Number.parseInt(hex.slice(i, i + 4), 16)); } return out || String.fromCharCode(Number.parseInt(hex, 16)); }; for (const block of text.matchAll(/beginbfchar([\s\S]*?)endbfchar/g)) { for (const m of block[1].matchAll(/<([0-9a-fA-F]+)>\s*<([0-9a-fA-F]+)>/g)) { map.set(Number.parseInt(m[1], 16), decodeUtf16Hex(m[2])); } } for (const block of text.matchAll(/beginbfrange([\s\S]*?)endbfrange/g)) { for (const m of block[1].matchAll(/<([0-9a-fA-F]+)>\s*<([0-9a-fA-F]+)>\s*<([0-9a-fA-F]+)>/g)) { const start = Number.parseInt(m[1], 16); const end = Number.parseInt(m[2], 16); let target = Number.parseInt(m[3], 16); for (let c = start; c <= end && c - start < 512; c++, target++) { map.set(c, String.fromCharCode(target)); } } } return map; } function pageFontCMaps(doc: PDFDocument, pageNode: PDFDict): Map> { const result = new Map>(); const resources = pageNode.lookupMaybe(PDFName.of("Resources"), PDFDict); const fonts = resources?.lookupMaybe(PDFName.of("Font"), PDFDict); if (!fonts) return result; for (const [key, val] of fonts.entries()) { const fontDict = val instanceof PDFRef ? doc.context.lookup(val) : val; if (!(fontDict instanceof PDFDict)) continue; const toUnicode = fontDict.lookupMaybe(PDFName.of("ToUnicode"), PDFStream); if (!toUnicode) continue; const cmapText = decodePdfStreamBytes(toUnicode).toString("latin1"); if (cmapText) result.set(key.decodeText(), parseToUnicodeCMap(cmapText)); } return result; } function extractTextFromContent(content: string, cmaps: Map>): string { const chunks: string[] = []; let inText = false; let currentFont = ""; let i = 0; const readParen = (): string => { i++; // skip '(' let depth = 1; let buf = ""; while (i < content.length && depth > 0) { const c = content[i]; if (c === "\\") { buf += c + (content[i + 1] ?? ""); i += 2; } else if (c === "(") { depth++; buf += c; i++; } else if (c === ")") { depth--; if (depth > 0) buf += c; i++; } else { buf += c; i++; } } return decodeLiteralString(buf); }; const readHex = (): string => { i++; // skip '<' const start = i; while (i < content.length && content[i] !== ">") i++; const hex = content.slice(start, i); if (content[i] === ">") i++; return decodeHexString(hex, cmaps.get(currentFont)); }; const stack: Array> = []; while (i < content.length) { const ch = content[i]; if (/\s/.test(ch)) { i++; continue; } if (ch === "%") { while (i < content.length && content[i] !== "\n" && content[i] !== "\r") i++; continue; } if (ch === "(") { stack.push(readParen()); continue; } if (ch === "<" && content[i + 1] !== "<") { stack.push(readHex()); continue; } if (ch === "<" && content[i + 1] === "<") { i += 2; continue; } if (ch === ">" && content[i + 1] === ">") { i += 2; continue; } if (ch === "[") { i++; const arr: Array = []; while (i < content.length && content[i] !== "]") { if (/\s/.test(content[i])) { i++; } else if (content[i] === "(") { arr.push(readParen()); } else if (content[i] === "<" && content[i + 1] !== "<") { arr.push(readHex()); } else { const start = i; while (i < content.length && !/[\s\]()<>/]/.test(content[i])) i++; const num = Number(content.slice(start, i)); if (!Number.isNaN(num)) arr.push(num); } } if (content[i] === "]") i++; stack.push(arr); continue; } if (ch === "/") { i++; const start = i; while (i < content.length && !/[\s()<>[\]{}/%]/.test(content[i])) i++; stack.push(`/${content.slice(start, i)}`); continue; } const start = i; while (i < content.length && !/[\s()<>[\]{}/%]/.test(content[i])) i++; const tok = content.slice(start, i); if (/^[-+]?(?:\d+\.?\d*|\.\d+)$/.test(tok)) { stack.push(Number(tok)); continue; } if (tok === "BT") { inText = true; } else if (tok === "ET") { inText = false; if (chunks.length > 0 && !chunks[chunks.length - 1].endsWith("\n")) chunks.push("\n"); } else if (tok === "Tf" && stack.length >= 2) { const fontName = stack[stack.length - 2]; if (typeof fontName === "string" && fontName.startsWith("/")) { currentFont = fontName.slice(1); } } else if (inText && (tok === "Td" || tok === "TD" || tok === "T*")) { const ty = tok === "T*" ? -1 : Number(stack[stack.length - 1] ?? 0); if (Math.abs(ty) > 1) chunks.push("\n"); else if (chunks.length > 0 && !chunks[chunks.length - 1].endsWith(" ")) chunks.push(" "); } else if (inText && tok === "Tm" && stack.length >= 6) { if (chunks.length > 0 && !chunks[chunks.length - 1].endsWith("\n")) chunks.push("\n"); } else if (inText && (tok === "Tj" || tok === "'" || tok === '"')) { if (tok === "'" || tok === '"') chunks.push("\n"); const val = stack[stack.length - 1]; if (typeof val === "string") chunks.push(val); } else if (inText && tok === "TJ") { const arr = stack[stack.length - 1]; if (Array.isArray(arr)) { for (const item of arr) { if (typeof item === "string") chunks.push(item); else if (typeof item === "number" && item < -150) chunks.push(" "); } } } stack.length = 0; } return chunks .join("") .replace(/[ \t]+\n/g, "\n") .replace(/\n{3,}/g, "\n\n") .trim(); } function extractPageText(doc: PDFDocument, pageIndex: number): string { const page = doc.getPage(pageIndex); const cmaps = pageFontCMaps(doc, page.node); const contents = page.node.get(PDFName.of("Contents")); if (!contents) return ""; const resolved = contents instanceof PDFRef ? doc.context.lookup(contents) : contents; const streams: PDFStream[] = []; if (resolved instanceof PDFStream) { streams.push(resolved); } else if (resolved instanceof PDFArray) { for (let i = 0; i < resolved.size(); i++) { const item = resolved.lookup(i); if (item instanceof PDFStream) streams.push(item); } } const combined = streams.map((s) => decodePdfStreamBytes(s).toString("latin1")).join("\n"); return extractTextFromContent(combined, cmaps); } export default defineTool({ description: "Local offline PDF toolkit with zero network access and no API key: inspect pages and metadata, merge multiple PDFs, split or extract page ranges, rotate pages, stamp text watermarks, extract embedded text page by page, and edit or strip document metadata.", input: Type.Object({ action: Type.Union(ACTIONS.map((a) => Type.Literal(a)), { description: "Operation to perform: inspect, merge, split, rotate, watermark, extract_text, or set_metadata", }), file: Type.Optional( FilePath({ description: "Input PDF file (for inspect, split, rotate, watermark, extract_text, set_metadata)" }), ), files: Type.Optional( Type.Array(FilePath({ description: "Input PDF files to merge (in order)" }), { minItems: 2, maxItems: 50, }), ), pages: Type.Optional( Type.String({ maxLength: 200, description: '1-based page selection, e.g. "1-3, 5, 8-end" (for split, rotate, watermark, extract_text)', }), ), splitEvery: Type.Optional( Type.Integer({ minimum: 1, maximum: 500, description: "For action: split — split into separate PDFs of N pages each (max 50 output files)", }), ), degrees: Type.Optional( Type.Union([Type.Literal(90), Type.Literal(180), Type.Literal(270)], { description: "For action: rotate — clockwise rotation in degrees (90, 180, or 270)", }), ), watermark: Type.Optional( Type.String({ minLength: 1, maxLength: 120, description: "For action: watermark — text to stamp on each selected page", }), ), position: Type.Optional( Type.Union([Type.Literal("diagonal"), Type.Literal("header"), Type.Literal("footer")], { description: "For action: watermark — placement; diagonal by default", }), ), opacity: Type.Optional( Type.Number({ minimum: 0.05, maximum: 1, description: "Watermark opacity (0.05–1); default 0.2" }), ), fontSize: Type.Optional( Type.Integer({ minimum: 8, maximum: 120, description: "Watermark font size; default 48 for diagonal, 12 for header/footer" }), ), metadata: Type.Optional( Type.Object({ title: Type.Optional(Type.String({ maxLength: 300 })), author: Type.Optional(Type.String({ maxLength: 300 })), subject: Type.Optional(Type.String({ maxLength: 500 })), keywords: Type.Optional(Type.Array(Type.String({ maxLength: 80 }), { maxItems: 30 })), creator: Type.Optional(Type.String({ maxLength: 200 })), }), ), clearMetadata: Type.Optional( Type.Boolean({ description: "For action: set_metadata — wipe existing title/author/subject/keywords/creator/producer", }), ), filename: Type.Optional( Type.String({ maxLength: 80, description: "Optional output filename stem without extension" }), ), }), output: Type.Object({ action: Type.String(), pageCount: Type.Integer(), bytes: Type.Optional(Type.Integer()), file: Type.Optional(FilePath({ description: "Primary output file (.pdf or .txt)" })), files: Type.Optional(Type.Array(FilePath({ description: "Multiple output PDFs (for splitEvery)" }))), pages: Type.Optional( Type.Array( Type.Object({ page: Type.Integer(), width: Type.Number(), height: Type.Number(), rotation: Type.Integer(), }), ), ), metadata: Type.Optional( Type.Object({ title: Type.Optional(Type.String()), author: Type.Optional(Type.String()), subject: Type.Optional(Type.String()), keywords: Type.Optional(Type.String()), creator: Type.Optional(Type.String()), producer: Type.Optional(Type.String()), creationDate: Type.Optional(Type.String()), modificationDate: Type.Optional(Type.String()), }), ), text: Type.Optional(Type.String({ description: "Extracted text (for extract_text)" })), pagesText: Type.Optional( Type.Array(Type.Object({ page: Type.Integer(), text: Type.String() })), ), }), examples: [ { title: "Inspect pages and metadata", input: { action: "inspect", file: "examples/sample.pdf", }, }, { title: "Stamp a diagonal watermark", input: { action: "watermark", file: "examples/sample.pdf", watermark: "CONFIDENTIAL", position: "diagonal", }, }, ], handler: async (input, ctx) => { const { action } = input; if (action === "merge") { if (!input.files || input.files.length < 2) { throw new Error('Action "merge" requires at least 2 PDFs in "files".'); } let totalSize = 0; for (const f of input.files) { totalSize += statSync(f).size; if (totalSize > MAX_MERGE_BYTES) { throw new Error("Combined PDF size exceeds the 100 MB merge limit."); } } const merged = await PDFDocument.create(); for (const f of input.files) { const src = await PDFDocument.load(readPdfBuffer(f), { ignoreEncryption: true }); const copied = await merged.copyPages(src, src.getPageIndices()); for (const p of copied) merged.addPage(p); } const outBytes = Buffer.from(await merged.save()); const outPath = join(ctx.outputDir, `${safeStem(input.filename ?? "merged")}.pdf`); writeFileSync(outPath, outBytes); ctx.log("info", `Merged ${input.files.length} PDFs into ${merged.getPageCount()} pages`); return { action, pageCount: merged.getPageCount(), bytes: outBytes.length, file: outPath, }; } if (!input.file) { throw new Error(`Action "${action}" requires an input PDF in "file".`); } const rawBuf = readPdfBuffer(input.file); const doc = await PDFDocument.load(rawBuf, { ignoreEncryption: true }); const totalPages = doc.getPageCount(); const baseStem = safeStem(input.filename ?? basename(input.file, extname(input.file))); if (action === "inspect") { const pages = doc.getPages().map((p, idx) => { const { width, height } = p.getSize(); return { page: idx + 1, width: Math.round(width * 100) / 100, height: Math.round(height * 100) / 100, rotation: p.getRotation().angle, }; }); return { action, pageCount: totalPages, bytes: rawBuf.length, pages, metadata: readMetadata(doc), }; } if (action === "split") { if (input.splitEvery) { const chunkCount = Math.ceil(totalPages / input.splitEvery); if (chunkCount > MAX_SPLIT_OUTPUTS) { throw new Error( `Splitting ${totalPages} pages every ${input.splitEvery} page(s) would create ${chunkCount} files; max is ${MAX_SPLIT_OUTPUTS}.`, ); } const outFiles: string[] = []; for (let start = 0; start < totalPages; start += input.splitEvery) { const end = Math.min(totalPages, start + input.splitEvery); const indices = Array.from({ length: end - start }, (_, k) => start + k); const part = await PDFDocument.create(); const copied = await part.copyPages(doc, indices); for (const p of copied) part.addPage(p); const partBytes = Buffer.from(await part.save()); const partPath = join(ctx.outputDir, `${baseStem}-p${start + 1}-${end}.pdf`); writeFileSync(partPath, partBytes); outFiles.push(partPath); } ctx.log("info", `Split ${totalPages} pages into ${outFiles.length} PDF files`); return { action, pageCount: totalPages, files: outFiles }; } if (!input.pages) { throw new Error('Action "split" requires either "pages" (e.g. "1-3, 5") or "splitEvery".'); } const indices = parsePageSpec(input.pages, totalPages); const out = await PDFDocument.create(); const copied = await out.copyPages(doc, indices); for (const p of copied) out.addPage(p); const outBytes = Buffer.from(await out.save()); const outPath = join(ctx.outputDir, `${baseStem}-extract.pdf`); writeFileSync(outPath, outBytes); ctx.log("info", `Extracted ${indices.length} page(s) to ${basename(outPath)}`); return { action, pageCount: out.getPageCount(), bytes: outBytes.length, file: outPath }; } if (action === "rotate") { const deg = input.degrees ?? 90; const indices = input.pages ? parsePageSpec(input.pages, totalPages) : doc.getPageIndices(); for (const idx of indices) { const page = doc.getPage(idx); page.setRotation(degrees((page.getRotation().angle + deg) % 360)); } const outBytes = Buffer.from(await doc.save()); const outPath = join(ctx.outputDir, `${baseStem}-rotated.pdf`); writeFileSync(outPath, outBytes); ctx.log("info", `Rotated ${indices.length} page(s) by ${deg} degrees`); return { action, pageCount: totalPages, bytes: outBytes.length, file: outPath }; } if (action === "watermark") { if (!input.watermark) throw new Error('Action "watermark" requires "watermark" text.'); const position = input.position ?? "diagonal"; const opacity = input.opacity ?? 0.2; const size = input.fontSize ?? (position === "diagonal" ? 48 : 12); const font = await doc.embedFont(StandardFonts.HelveticaBold); const indices = input.pages ? parsePageSpec(input.pages, totalPages) : doc.getPageIndices(); const textWidth = font.widthOfTextAtSize(input.watermark, size); for (const idx of indices) { const page = doc.getPage(idx); const { width, height } = page.getSize(); if (position === "header") { page.drawText(input.watermark, { x: Math.max(24, (width - textWidth) / 2), y: height - 28, size, font, color: rgb(0.35, 0.35, 0.35), opacity, }); } else if (position === "footer") { page.drawText(input.watermark, { x: Math.max(24, (width - textWidth) / 2), y: 18, size, font, color: rgb(0.35, 0.35, 0.35), opacity, }); } else { const angleRad = Math.PI / 4; const x = width / 2 - (textWidth / 2) * Math.cos(angleRad); const y = height / 2 - (textWidth / 2) * Math.sin(angleRad); page.drawText(input.watermark, { x, y, size, font, color: rgb(0.45, 0.45, 0.45), opacity, rotate: degrees(45), }); } } const outBytes = Buffer.from(await doc.save()); const outPath = join(ctx.outputDir, `${baseStem}-watermarked.pdf`); writeFileSync(outPath, outBytes); ctx.log("info", `Watermarked ${indices.length} page(s)`); return { action, pageCount: totalPages, bytes: outBytes.length, file: outPath }; } if (action === "extract_text") { const indices = input.pages ? parsePageSpec(input.pages, totalPages) : doc.getPageIndices(); const pagesText = indices.map((idx) => ({ page: idx + 1, text: extractPageText(doc, idx), })); const combined = pagesText .map((p) => (pagesText.length > 1 ? `--- Page ${p.page} ---\n${p.text}` : p.text)) .join("\n\n") .trim(); const outPath = join(ctx.outputDir, `${baseStem}.txt`); writeFileSync(outPath, `${combined}\n`, "utf8"); ctx.log("info", `Extracted ${combined.length} characters from ${indices.length} page(s)`); return { action, pageCount: totalPages, bytes: Buffer.byteLength(combined, "utf8"), file: outPath, text: combined, pagesText, }; } if (action === "set_metadata") { if (input.clearMetadata) { doc.setTitle(""); doc.setAuthor(""); doc.setSubject(""); doc.setKeywords([]); doc.setCreator(""); doc.setProducer(""); } if (input.metadata?.title !== undefined) doc.setTitle(input.metadata.title); if (input.metadata?.author !== undefined) doc.setAuthor(input.metadata.author); if (input.metadata?.subject !== undefined) doc.setSubject(input.metadata.subject); if (input.metadata?.keywords !== undefined) doc.setKeywords(input.metadata.keywords); if (input.metadata?.creator !== undefined) doc.setCreator(input.metadata.creator); const outBytes = Buffer.from(await doc.save()); const outPath = join(ctx.outputDir, `${baseStem}-metadata.pdf`); writeFileSync(outPath, outBytes); ctx.log("info", `Updated metadata on ${basename(outPath)}`); return { action, pageCount: totalPages, bytes: outBytes.length, file: outPath, metadata: readMetadata(doc), }; } throw new Error(`Unsupported action "${String(action)}".`); }, });