PDF Helpers
PDF Helpers
Imported from @xenterprises/fastify-xpdf/helpers. These helpers are used internally by the plugin's generation and manipulation methods but are also available for standalone use — e.g. in preprocessing pipelines, custom route handlers, or test fixtures.
Usage
import {
generatePdfFilename,
isValidPdfBuffer,
getPdfMetadata,
formatPdfOptions,
sanitizeFilename,
wrapHtmlTemplate,
parseMargin,
getPageFormat,
saveToStorage,
} from '@xenterprises/fastify-xpdf/helpers'
Functions
generatePdfFilename(baseName?)
Generate a unique PDF filename with an ISO timestamp suffix.
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
baseName | string | No | Base name without extension. Defaults to "document". |
Returns: string — e.g. "report-2024-01-15T10-30-00.pdf".
isValidPdfBuffer(buffer)
Check whether a buffer begins with the %PDF magic bytes.
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
buffer | Buffer | Yes | Buffer to inspect. |
Returns: boolean — true if the buffer starts with %PDF.
getPdfMetadata(buffer)
Extract basic metadata from a PDF buffer.
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
buffer | Buffer | Yes | Valid PDF buffer. |
Returns: { size: number } — size is the byte length of the buffer.
formatPdfOptions(options, defaults)
Merge per-call PDF options with plugin-level defaults, with per-call values taking precedence.
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
options | object | Yes | Per-call options (any subset of Puppeteer PDF options). |
defaults | object | Yes | Plugin-level default options to fall back to. |
Returns: object — Merged options object.
sanitizeFilename(filename)
Remove unsafe characters from a filename and lowercase the result.
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
filename | string | Yes | Raw filename string. |
Returns: string — Sanitized, lowercased filename safe for use in storage keys and Content-Disposition headers.
wrapHtmlTemplate(content)
Wrap an HTML fragment in a complete, styled HTML document suitable for Puppeteer rendering.
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
content | string | Yes | HTML fragment or full body content. |
Returns: string — A complete <!DOCTYPE html> document with base styles applied.
parseMargin(margin)
Convert a margin value — string shorthand or object — to the object format Puppeteer expects.
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
margin | string | { top?, right?, bottom?, left? } | Yes | Margin shorthand (e.g. "1cm") or an object with individual sides. |
Returns: { top: string; right: string; bottom: string; left: string }
getPageFormat(format?)
Resolve a named page format to its width and height in inches.
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
format | string | No | Format name: "A4", "Letter", "A3", "A5", "Tabloid", etc. Defaults to "A4". |
Returns: { width: number; height: number } — Dimensions in inches.
saveToStorage(fastify, buffer, filename, folder)
Upload a PDF buffer to xStorage (fastify.xStorage). Requires @xenterprises/fastify-xstorage to be registered on the same Fastify instance.
Parameters:
| Name | Type | Required | Description |
|---|---|---|---|
fastify | FastifyInstance | Yes | The Fastify instance with xStorage decorated. |
buffer | Buffer | Yes | PDF buffer to upload. |
filename | string | Yes | Destination filename (used as storage key base). |
folder | string | Yes | Storage folder prefix (e.g. "pdfs", "reports/2024"). |
Returns: Promise<{ key: string; url: string; size: number | null; contentType: string; bucket: string }> — The xStorage upload result.
Examples
Generate a safe filename for a report
import { generatePdfFilename, sanitizeFilename } from '@xenterprises/fastify-xpdf/helpers'
const base = sanitizeFilename('Q1 Revenue Report (Draft)')
// "q1-revenue-report-draft"
const filename = generatePdfFilename(base)
// "q1-revenue-report-draft-2024-01-15T10-30-00.pdf"
Validate a buffer before manipulating
import { isValidPdfBuffer } from '@xenterprises/fastify-xpdf/helpers'
fastify.post('/merge', async (request, reply) => {
const data = await request.file()
const buffer = await data.toBuffer()
if (!isValidPdfBuffer(buffer)) {
return reply.status(400).send({ error: 'Uploaded file is not a valid PDF' })
}
const merged = await fastify.xPDF.mergePDFs([existingBuffer, buffer])
return reply.type('application/pdf').send(merged.buffer)
})
Wrap markdown-converted HTML before rendering
import { wrapHtmlTemplate, parseMargin } from '@xenterprises/fastify-xpdf/helpers'
import { marked } from 'marked'
const html = wrapHtmlTemplate(marked(markdownContent))
const margin = parseMargin('2cm')
// { top: "2cm", right: "2cm", bottom: "2cm", left: "2cm" }
const { buffer } = await fastify.xPDF.generateFromHtml(html, { margin })
Upload a generated PDF directly to storage
import { generatePdfFilename, saveToStorage } from '@xenterprises/fastify-xpdf/helpers'
fastify.post('/invoices/:id/pdf', async (request, reply) => {
const html = await buildInvoiceHtml(request.params.id)
const { buffer } = await fastify.xPDF.generateFromHtml(html)
const filename = generatePdfFilename(`invoice-${request.params.id}`)
const result = await saveToStorage(fastify, buffer, filename, 'invoices')
return reply.send({ url: result.url, key: result.key })
})
Get page dimensions for a custom layout
import { getPageFormat, formatPdfOptions } from '@xenterprises/fastify-xpdf/helpers'
const dims = getPageFormat('A5')
// { width: 5.83, height: 8.27 }
const merged = formatPdfOptions(
{ printBackground: false },
{ format: 'A5', margin: { top: '1cm', right: '1cm', bottom: '1cm', left: '1cm' }, printBackground: true }
)
// printBackground: false wins; format and margin from defaults
See also
- generateFromHtml — HTML to PDF via Puppeteer
- mergePDFs — Merge multiple PDFs with pdf-lib
- getPageCount / getMetadata — Inspect PDF metadata
AI Context
import: "@xenterprises/fastify-xpdf/helpers"
use-when: >
When you need PDF utility functions outside of the plugin's main methods —
e.g. validating uploaded PDFs before processing, generating unique filenames,
wrapping HTML fragments before passing to generateFromHtml, or uploading
PDF buffers directly to xStorage.
functions:
- generatePdfFilename: Unique timestamped filename
- isValidPdfBuffer: Check %PDF header
- getPdfMetadata: Returns { size } from buffer
- formatPdfOptions: Merge per-call options with plugin defaults
- sanitizeFilename: Strip unsafe chars and lowercase
- wrapHtmlTemplate: Wrap HTML fragment in full styled document
- parseMargin: Convert string/object margin to Puppeteer format
- getPageFormat: Resolve format name to { width, height } in inches
- saveToStorage: Upload buffer to fastify.xStorage (requires xstorage plugin)
