Skip to main content
Glama

Create PDF Document

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

TableJSON Schema
NameRequiredDescriptionDefault
filenameNoOptional logical filename (metadata only). Storage uses UUID. Defaults to "document.pdf".
titleNoDocument title metadata
authorNoDocument author metadata
fontNoFont strategy (default: auto). Built-ins: Helvetica, Times-Roman, Courier. Use a path or URL for Unicode.
pageSetupNoPage configuration including size, margins, and background color.
contentYesDocument content in flow order

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • 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,
        });
      }
    }
  • 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;
  • 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;
  • Re-export of the pdfDocument tool factory from tools index for aggregation in mcp.toolFactories.
    export { default as pdfDocument } from './pdf-document.ts';
  • 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()),
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It does well by explaining key behavioral traits: 'Content flows naturally from top to bottom. Pages break automatically when content exceeds page height,' describing default margins that vary by page size, and listing supported content types with their purposes. It doesn't mention error conditions, performance characteristics, or output format details, but provides substantial operational context for a creation tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured and appropriately sized. It starts with the core purpose, then provides usage guidance, explains key behaviors, lists content types, and ends with margin defaults. Most sentences earn their place, though the content type listing could be more concise. The information is front-loaded with the most important details first.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (6 parameters with nested objects) and the presence of an output schema (which means return values don't need explanation), the description provides good contextual completeness. It covers the tool's purpose, appropriate use cases, key behaviors, and content semantics. With no annotations, it could benefit from mentioning error conditions or performance limits, but it's largely complete for guiding usage.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description adds some value by explaining the purpose of content types like 'pageBreak', 'divider', and 'spacer', and mentioning default margin behavior. However, it doesn't provide significant additional semantic meaning beyond what's already in the comprehensive schema descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool creates a 'flowing PDF document with automatic pagination' and specifies it's 'best for: Reports, articles, letters, contracts, and documents with sequential content.' This distinguishes it from sibling tools like pdf-image (likely for image manipulation), pdf-layout (likely for fixed layouts), and pdf-resume (likely specialized for resumes). The description goes beyond the name/title by explaining the flowing nature and target use cases.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context about when to use this tool ('Best for: Reports, articles, letters, contracts, and documents with sequential content') and mentions the text-measure tool for precise dimensions. However, it doesn't explicitly state when NOT to use this tool versus alternatives like pdf-layout or pdf-resume, nor does it provide exclusion criteria or prerequisites for usage.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/mcp-z/mcp-pdf'

If you have feedback or need assistance with the MCP directory API, please join our Discord server