Skip to content

PDF Generation ​

GhostAI can generate professional PDF documents directly in chat. Ask the AI to create reports, briefings, memos, summaries, or any printable document, and it will produce a styled, downloadable PDF.

How It Works ​

Features ​

Two Generation Modes ​

ModeDescriptionBest For
Markdown-to-PDFFree-form markdown rendered to a styled documentQuick docs, notes, summaries
Template ReportsStructured report with cover page and branded layoutBriefings, reports, memos

Templates ​

Four built-in templates are available:

  • report (default) -- Full report with cover page, headers, and professional typography
  • briefing -- Executive briefing format with cover page
  • memo -- Internal memo format with cover page
  • summary -- Concise summary format with cover page

OCR Text Layer ​

When enabled (ocr_text: true), an invisible but searchable text layer is added to the PDF. This makes the document:

  • Searchable in PDF readers (Cmd+F / Ctrl+F)
  • Selectable -- text can be copied from the PDF
  • Accessible for screen readers and assistive technology

Professional Styling ​

All generated PDFs include:

  • GhostAI branded header and footer
  • Page numbers
  • Generation timestamp
  • Professional typography (headings, body text, code blocks, bullet lists)
  • Configurable page size (US Letter or A4)

Rich Markdown Rendering ​

GhostAI's PDF generation supports world-class rich markdown rendering. The LLM can use the full spectrum of markdown features and they will be faithfully rendered into the PDF with professional styling and graceful fallback if any element fails to render.

Mermaid Diagrams ​

Flowcharts, sequence diagrams, architecture diagrams, and process flows written in Mermaid syntax are rendered as high-resolution images via the mermaid.ink API and embedded directly into the PDF.

markdown
```mermaid
graph TD
    A[User Request] --> B{PII Detected?}
    B -->|Yes| C[Tokenize]
    B -->|No| D[Pass Through]
    C --> D
    D --> E[Send to LLM]
```
  • Diagrams are rendered server-side — no browser or JavaScript required
  • Rendered images are cached so repeated builds with the same diagram are fast
  • If the mermaid.ink API is unavailable, the raw Mermaid source is included as a styled code block (graceful fallback)

LaTeX Math ​

Mathematical equations, formulas, and notation are supported in both block and inline forms. Math is rendered to images using matplotlib mathtext.

Block math (centered, full-width):

markdown
$$
E = mc^2
$$

Inline math (within a paragraph):

markdown
The quadratic formula is $x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$ where $a \neq 0$.
  • Block math ($$...$$) renders as a centered image on its own line
  • Inline math ($...$) renders as a small image placed inline with surrounding text
  • If rendering fails for a given expression, the raw LaTeX source is displayed as monospace text (graceful fallback)

Styled Tables ​

Pipe-delimited markdown tables are rendered with branded, styled headers and clean alternating-row formatting.

markdown
| Feature       | Status | Notes                  |
|---------------|--------|------------------------|
| Mermaid       | ✅      | via mermaid.ink API    |
| LaTeX Math    | ✅      | via matplotlib         |
| Code Blocks   | ✅      | via Pygments           |
  • Header row is styled with GhostAI brand colors
  • Cell padding and borders are professionally formatted
  • Tables respect page width and wrap content as needed

Syntax-Highlighted Code Blocks ​

Fenced code blocks with a language identifier are rendered with full syntax highlighting powered by Pygments. (In chat, code blocks are highlighted client-side with Prism for the same visual experience.)

markdown
```python
def greet(name: str) -> str:
    return f"Hello, {name}!"
```
  • Supports all major languages (Python, JavaScript, TypeScript, SQL, Bash, Go, Rust, Java, C++, and many more)
  • Uses a professional color scheme optimized for print
  • Code blocks include a subtle background and monospace font

Image Embedding ​

Images referenced in markdown — including GhostAI-generated images — are embedded directly into the PDF.

markdown
![Architecture Diagram](https://example.com/diagram.png)
  • Supports URLs to external images and GhostAI-generated image URLs
  • Images are downloaded and embedded at render time
  • If an image cannot be fetched, a placeholder with the alt text is shown (graceful fallback)

Blockquotes ​

Markdown blockquotes are rendered with a distinctive left border in GhostAI brand colors.

markdown
> "The best way to predict the future is to invent it."
> — Alan Kay
  • Styled with a colored left border and italicized text
  • Nested blockquotes are supported with increasing indentation

Hyperlinks in markdown are rendered as clickable links in the PDF.

markdown
See the [GhostAI documentation](https://docs.ghostai.com) for more details.
  • Links are styled with a distinct color to indicate clickability
  • Clicking a link in a PDF reader opens the URL in the default browser
  • Both inline links and reference-style links are supported

Caching and Fallback ​

Rich rendering elements (Mermaid diagrams, LaTeX math, fetched images) are cached during PDF generation to avoid redundant network calls and rendering passes. Every rich element has a graceful fallback:

ElementFallback Behavior
Mermaid diagramRaw source displayed as a code block
LaTeX mathRaw LaTeX shown as monospace text
ImagePlaceholder with alt text
Code highlightingPlain monospace code block (no color)

This ensures that PDF generation never fails due to a single rendering issue — the document is always produced.

Parallel Rendering Pipeline ​

PDF generation uses a 3-pass parallel pipeline for fast, asset-heavy documents:

  1. Pre-scan — The markdown is scanned to discover all heavy assets: Mermaid diagrams, LaTeX math blocks, image URLs, and fenced code blocks.
  2. Parallel Render — A ThreadPoolExecutor (up to 8 workers) renders all heavy operations concurrently:
    • Mermaid diagrams via the mermaid.ink API
    • LaTeX math (block and inline) via matplotlib
    • Image fetching from URLs
    • Pygments syntax highlighting for code blocks
  3. Assembly — Rendered assets are assembled into the final PDF.

Performance: Asset-heavy documents see roughly a 5× speedup. For example, a report with 6 Mermaid charts and 3 math blocks drops from ~18s to ~3–4s.

Deduplication: Assets are content-hashed; identical diagrams or math expressions used multiple times are rendered once and reused.

Caching: Pygments highlighting uses an LRU cache (128 entries) to avoid redundant highlighting for repeated code blocks.

Backward compatible: If the document has no heavy assets, the pipeline is effectively a no-op — simple documents render as before with minimal overhead.

Usage ​

Basic Document ​

Ask the AI naturally:

"Generate a PDF report on the key differences between REST and GraphQL APIs"

Template Selection ​

Specify a template:

"Create a briefing PDF on our Q4 security posture"

"Write a memo PDF about the upcoming infrastructure migration"

With OCR Text Layer ​

Request searchable text:

"Generate a PDF summary of Einstein's contributions to physics, with searchable text"

Page Size ​

Specify A4 for international format:

"Create an A4 report on GDPR compliance requirements"

API Reference ​

Tool Definition ​

The generate_pdf tool is automatically available to the LLM (no API key needed):

json
{
  "name": "generate_pdf",
  "parameters": {
    "title": "Document title (required)",
    "content": "Rich markdown content (required) -- supports mermaid diagrams, LaTeX math (block $$ and inline $), pipe-delimited tables, syntax-highlighted code blocks, image embedding, blockquotes, and clickable links",
    "template": "briefing | report | memo | summary (default: report)",
    "page_size": "letter | a4 (default: letter)",
    "ocr_text": "true | false (default: false)"
  }
}

SSE Events ​

When a PDF is generated, the backend sends a tool_result SSE event:

json
{
  "type": "tool_result",
  "tool_name": "generate_pdf",
  "tool_id": "call_abc123",
  "pdf_url": "/api/generated-pdfs/Report_Title_a1b2c3d4.pdf",
  "filename": "Report_Title_a1b2c3d4.pdf",
  "pages": 3,
  "result_preview": "PDF generated: Report_Title_a1b2c3d4.pdf"
}

Static File Serving ​

Generated PDFs are served at /api/generated-pdfs/ as static files.

PII Protection ​

PDF content goes through the same PII detection pipeline as regular chat messages:

  1. The user's prompt is sanitized before being sent to the LLM
  2. The LLM generates markdown content for the PDF
  3. The markdown content is rendered to PDF
  4. The PDF is served to the user

Since the LLM never sees raw PII, the generated PDF content is inherently privacy-protected.

Zero-Trust Secure PDF Generation ​

When the secure_pdf_mode setting is enabled (default: "full"), GhostAI implements a tokenize-through pipeline that allows PDFs to contain real PII data (e.g., employee names, financial records from business data queries) while ensuring the LLM never processes the original sensitive values.

How It Works ​

  1. Data Query Tokenization: When data_query or bi_insight tools return results containing PII (names, SSNs, account numbers, etc.), the results are run through PII detection and tokenized before being appended to the LLM conversation. The LLM only ever sees tokens like [PERSON_a1b2].

  2. PDF Detokenization: When the LLM calls generate_pdf, the server-side handler detokenizes the PDF title and content — replacing tokens with real values — before passing the content to the PDF rendering engine. This detokenization happens entirely server-side and the real PII values never transit back through the LLM.

  3. Audit Trail: Every detokenization event is logged to the audit trail, recording the session ID, entity types, tokens, and user who generated the PDF.

  4. UI Indicator: PDFs containing detokenized sensitive data display a "Contains sensitive data" badge in the download card, with a tooltip explaining that the AI model never saw the original values.

Configuration ​

The secure_pdf_mode setting controls zero-trust behavior:

ModeData Tool ResultsPDF ContentUse Case
"full" (default)Tokenized before LLM sees themDetokenized at render timeMaximum privacy — LLM never sees real PII
"detokenize_only"Sent as-is to LLMDetokenized at render timeFor environments where data tools already mask PII
"off"Sent as-is to LLMNo detokenizationCurrent behavior (no zero-trust)

This setting is configurable at the organization level by Owners/Admins via PUT /api/settings/detection and included in the GET /api/settings/detection response.

SSE Event Update ​

When a PDF contains detokenized PII, the tool_result SSE event includes contains_pii: true:

json
{
  "type": "tool_result",
  "tool_name": "generate_pdf",
  "pdf_url": "/api/generated-pdfs/Earnings_Report_a1b2c3d4.pdf",
  "filename": "Earnings_Report_a1b2c3d4.pdf",
  "pages": 5,
  "contains_pii": true,
  "result_preview": "PDF generated: Earnings_Report_a1b2c3d4.pdf"
}

Frontend Display ​

Generated PDFs appear in the chat as a styled download card:

  • Document icon (red) with filename
  • Page count displayed below the filename
  • Download button triggers browser download
  • Cards persist across page reloads (stored as markdown links in message history)

Configuration ​

Tool Toggle ​

Users can enable/disable PDF generation from the tool buttons in the chat input area. The "PDF" button appears between "Data" and "Image" in the toolbar.

Button Order ​

The tool buttons appear in this order: Search | Data | PDF | Image

Troubleshooting ​

PDF not generating ​

  • Ensure the PDF tool button is enabled (active state)
  • Try being more explicit: "Generate a PDF document about..."

PDF is empty or has no content ​

  • The LLM may have provided insufficient content. Try re-asking with more detail.

OCR text layer not working ​

  • OCR requires PyMuPDF (fitz) to be installed
  • If PyMuPDF is unavailable, the PDF is generated without the text layer (graceful degradation)

SOC 2 Type II Certified | BAA Available | HIPAA-Ready