pdf-document
Create PDF documents with automatic pagination for reports, articles, contracts, and sequential content. Supports text, headings, images, dividers, and page breaks with customizable formatting and page setup.
Instructions
Create a flowing PDF document with automatic pagination.
Best for: Reports, articles, letters, contracts, and documents with sequential content.
Content flows naturally from top to bottom. Pages break automatically when content exceeds page height. Use "pageBreak" to force page breaks, "divider" for horizontal rules, and "spacer" for vertical spacing.
Supported content types:
text: Body text with optional formatting (bold, italic, color, alignment)
heading: Section headings (larger font, bold by default)
image: Inline images that flow with content
divider: Horizontal line separators
spacer: Vertical whitespace
pageBreak: Force new page
Default margins: Varies by page size (e.g., 72pt/1" for Letter, ~56pt for A4).
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| filename | No | Optional logical filename (metadata only). Storage uses UUID. Defaults to "document.pdf". | |
| title | No | Document title metadata | |
| author | No | Document author metadata | |
| font | No | Font strategy (default: auto). Built-ins: Helvetica, Times-Roman, Courier. Use a path or URL for Unicode. | |
| pageSetup | No | Page configuration including size, margins, and background color. | |
| content | Yes | Document content in flow order |
Implementation Reference
- src/mcp/tools/pdf-document.ts:91-294 (handler)Core handler function that executes the pdf-document tool: initializes PDFKit document, processes flowing content array with automatic pagination, supports text/heading/image/divider/spacer/pageBreak, manages fonts/emoji/images, stores PDF and returns metadata/URI.async function handler(args: Input, extra: StorageExtra): Promise<CallToolResult> { const { storageContext } = extra; const { storageDir, baseUrl, transport } = storageContext; const { filename = 'document.pdf', title, author, font, pageSetup, content } = args; try { // Resolve page size and margins const resolvedPageSize = resolvePageSize(pageSetup?.size as PageSizePreset | [number, number] | undefined); const sizePreset = typeof pageSetup?.size === 'string' ? (pageSetup.size as PageSizePreset) : 'LETTER'; const margins = pageSetup?.margins ?? getDefaultMargins(sizePreset); const docOptions = { info: { ...(title && { Title: title }), ...(author && { Author: author }), ...(filename && { Subject: filename }), }, size: [resolvedPageSize.width, resolvedPageSize.height] as [number, number], margins: margins, }; const doc = new PDFDocument({ ...docOptions, autoFirstPage: false }); // Buffer accumulation const chunks: Buffer[] = []; doc.on('data', (c: Buffer) => chunks.push(c)); const pdfPromise = new Promise<Buffer>((resolve, reject) => { doc.on('end', () => resolve(Buffer.concat(chunks))); doc.on('error', reject); }); // Setup fonts and emoji const contentText = JSON.stringify(content); const containsEmoji = hasEmoji(contentText); const emojiAvailable = containsEmoji ? registerEmojiFont() : false; const fonts = await setupFonts(doc, font); const { regular: regularFont, bold: boldFont } = fonts; const warnings: string[] = []; // Track page count and apply background to ALL pages consistently let actualPageCount = 0; doc.on('pageAdded', () => { actualPageCount++; if (pageSetup?.backgroundColor) { doc.rect(0, 0, resolvedPageSize.width, resolvedPageSize.height).fill(pageSetup.backgroundColor); doc.fillColor('black'); } }); // Add first page explicitly - goes through same event handler as all other pages doc.addPage(); // Validate text content for (const item of content) { if ((item.type === 'text' || item.type === 'heading') && item.text) { const fnt = item.bold ? boldFont : regularFont; const validation = validateTextForFont(item.text, fnt, undefined); if (validation.hasUnsupportedCharacters) { warnings.push(...validation.warnings); } } } // Get content width (page width minus margins) const contentWidth = doc.page.width - doc.page.margins.left - doc.page.margins.right; // Render flowing content for (const item of content) { switch (item.type) { case 'text': { const fontSize = item.fontSize ?? DEFAULT_TEXT_FONT_SIZE; const fnt = item.bold ? boldFont : regularFont; if (item.color) doc.fillColor(item.color); const options = extractTextOptions(item); options.width = item.width ?? contentWidth; renderTextWithEmoji(doc, item.text ?? '', fontSize, fnt, emojiAvailable, options); if (item.moveDown) { doc.moveDown(item.moveDown); } if (item.color) doc.fillColor('black'); break; } case 'heading': { const fontSize = item.fontSize ?? DEFAULT_HEADING_FONT_SIZE; const fnt = item.bold !== false ? boldFont : regularFont; if (item.color) doc.fillColor(item.color); const options = extractTextOptions(item); options.width = item.width ?? contentWidth; renderTextWithEmoji(doc, item.text ?? '', fontSize, fnt, emojiAvailable, options); if (item.moveDown) { doc.moveDown(item.moveDown); } if (item.color) doc.fillColor('black'); break; } case 'image': { const dimensions = resolveImageDimensions( item.imagePath, item.width ?? contentWidth, // Default to content width item.height ); // Ensure image doesn't exceed content width const imgWidth = Math.min(dimensions.width, contentWidth); const imgHeight = dimensions.height * (imgWidth / dimensions.width); // Calculate X position based on alignment let imgX = doc.x; if (item.align === 'center') { imgX = doc.page.margins.left + (contentWidth - imgWidth) / 2; } else if (item.align === 'right') { imgX = doc.page.margins.left + contentWidth - imgWidth; } doc.image(item.imagePath, imgX, doc.y, { width: imgWidth, height: imgHeight, }); doc.y += imgHeight; doc.moveDown(0.5); // Small spacing after image break; } case 'divider': { const marginTop = item.marginTop ?? 10; const marginBottom = item.marginBottom ?? 10; const thickness = item.thickness ?? 1; const color = item.color ?? '#cccccc'; doc.y += marginTop; doc .lineWidth(thickness) .moveTo(doc.page.margins.left, doc.y) .lineTo(doc.page.width - doc.page.margins.right, doc.y) .stroke(color); doc.y += thickness + marginBottom; break; } case 'spacer': { doc.y += item.height; break; } case 'pageBreak': { doc.addPage(); break; } } } doc.end(); const pdfBuffer = await pdfPromise; // Write file const { storedName } = await writeFile(pdfBuffer, filename, { storageDir }); // Generate URI const fileUri = getFileUri(storedName, transport, { storageDir, ...(baseUrl && { baseUrl }), endpoint: '/files', }); const result: PDFOutput & { margins: Margins } = { operationSummary: `Created PDF document: ${filename}`, itemsProcessed: content.length, itemsChanged: 1, completedAt: new Date().toISOString(), documentId: storedName, filename, uri: fileUri, sizeBytes: pdfBuffer.length, pageCount: actualPageCount, margins, ...(warnings.length > 0 && { warnings }), }; return { content: [ { type: 'text' as const, text: JSON.stringify(result), }, ], structuredContent: { result }, }; } catch (error) { const message = error instanceof Error ? error.message : String(error); throw new McpError(ErrorCode.InternalError, `Error creating PDF document: ${message}`, { stack: error instanceof Error ? error.stack : undefined, }); } }
- src/mcp/tools/pdf-document.ts:31-86 (schema)Zod schemas for input (filename, title, pageSetup, content[]) and output (extending pdfOutputSchema with margins, file info), part of tool config.const inputSchema = z.object({ filename: z.string().optional().describe('Optional logical filename (metadata only). Storage uses UUID. Defaults to "document.pdf".'), title: z.string().optional().describe('Document title metadata'), author: z.string().optional().describe('Document author metadata'), font: z.string().optional().describe('Font strategy (default: auto). Built-ins: Helvetica, Times-Roman, Courier. Use a path or URL for Unicode.'), pageSetup: z .object({ size: z .union([z.enum(['LETTER', 'A4', 'LEGAL']), z.tuple([z.number(), z.number()])]) .optional() .describe('Page size preset or custom [width, height] in points. LETTER: 612×792pt (8.5×11in). A4: 595×842pt (210×297mm). LEGAL: 612×1008pt (8.5×14in). Default: LETTER.'), margins: z .object({ top: z.number(), bottom: z.number(), left: z.number(), right: z.number(), }) .optional() .describe('Page margins in points. all 4 (top, bottom, left, right) are REQUIRED if provided. Defaults vary by page size (LETTER/LEGAL: 72pt, A4: ~56pt).'), backgroundColor: z.string().optional().describe('Page background color (hex like "#000000" or named color). Default: white.'), }) .optional() .describe('Page configuration including size, margins, and background color.'), content: z.array(flowingContentItemSchema).describe('Document content in flow order'), }); const config = { title: 'Create PDF Document', description: `Create a flowing PDF document with automatic pagination. Best for: Reports, articles, letters, contracts, and documents with sequential content. Content flows naturally from top to bottom. Pages break automatically when content exceeds page height. Use "pageBreak" to force page breaks, "divider" for horizontal rules, and "spacer" for vertical spacing. Supported content types: - text: Body text with optional formatting (bold, italic, color, alignment) - heading: Section headings (larger font, bold by default) - image: Inline images that flow with content - divider: Horizontal line separators - spacer: Vertical whitespace - pageBreak: Force new page Default margins: Varies by page size (e.g., 72pt/1" for Letter, ~56pt for A4).`, inputSchema, outputSchema: z.object({ result: pdfOutputSchema.extend({ margins: z.object({ top: z.number(), bottom: z.number(), left: z.number(), right: z.number(), }), }), }), } as const;
- src/mcp/tools/pdf-document.ts:296-300 (registration)ToolModule registration object defining the tool's name, config (with schemas/title/description), and handler reference. Exported as default from createTool() factory.return { name: 'pdf-document', config, handler, } satisfies ToolModule;
- src/mcp/tools/index.ts:1-1 (registration)Re-export of the pdfDocument tool factory from tools index for aggregation in mcp.toolFactories.export { default as pdfDocument } from './pdf-document.ts';
- src/setup/runtime.ts:60-62 (registration)Dynamic registration of all tools (including pdf-document) by instantiating factories from mcp.toolFactories in the default runtime setup.(() => ({ tools: Object.values(mcp.toolFactories).map((factory) => factory()), // resources: Object.values(mcp.resourceFactories).map((factory) => factory()),