Installation
npm install @pdfbase/sdk
# or
yarn add @pdfbase/sdk
# or
pnpm add @pdfbase/sdk
Initialization
import PDFBase from '@pdfbase/sdk'
const pdfbase = new PDFBase({
apiKey: process.env.PDFBASE_API_KEY, // pk_live_xxx or pk_test_xxx
timeout: 30_000, // request timeout (default: 30s)
maxRetries: 3, // automatic retries on 5xx/429 (default: 3)
})
Generate a PDF
const pdf = await pdfbase.pdfs.create({
html: '<h1>Invoice #001</h1><p>Total: $500</p>',
format: 'a4',
output: 'url',
})
console.log(pdf.id) // pdf_x7Kf9m
console.log(pdf.url) // https://files.pdfbase.dev/pdf_x7Kf9m.pdf?token=sig_abc
console.log(pdf.pages) // 1
Templates
// Create a template
const template = await pdfbase.templates.create({
name: 'invoice',
html: '<h1>Invoice #{{number}}</h1>...',
schema: { number: 'string', customer: 'string', total: 'string' },
defaults: { format: 'a4', margin: '20mm' },
})
// Render with data
const pdf = await pdfbase.templates.render(template.id, {
data: { number: 'INV-001', customer: 'Acme Corp', total: '$500' },
output: 'url',
})
// List templates
const templates = await pdfbase.templates.list({ limit: 50 })
// Update
await pdfbase.templates.update(template.id, {
html: '<h1>Updated Invoice #{{number}}</h1>...',
})
Batch processing
// Create a batch
const batch = await pdfbase.batches.create({
items: invoices.map(inv => ({
template_id: 'tpl_abc123',
data: { number: inv.number, customer: inv.name, total: inv.total },
metadata: { invoice_id: inv.id },
})),
output: 'individual',
parallel: 10,
})
// Poll for completion (convenience method)
const result = await pdfbase.batches.poll(batch.id, {
interval: 2000, // poll every 2s
timeout: 300000, // give up after 5min
onProgress: (batch) => {
console.log(`${batch.completed_items}/${batch.total_items} done`)
},
})
// Or manually check status
const status = await pdfbase.batches.retrieve(batch.id)
Edit operations
// Merge PDFs
const merged = await pdfbase.pdfs.merge({
sources: [
{ pdf_id: 'pdf_cover' },
{ pdf_id: 'pdf_report' },
{ url: 'https://legal.example.com/terms.pdf' },
],
})
// Split
const parts = await pdfbase.pdfs.split({
source: { pdf_id: 'pdf_report' },
ranges: ['1-5', '6-10'],
})
// Watermark
const watermarked = await pdfbase.pdfs.watermark({
source: { pdf_id: 'pdf_contract' },
text: { content: 'DRAFT', color: '#FF000015' },
})
Extract operations
// Extract text (Phase 3)
const text = await pdfbase.extract.text({
source: { pdf_id: 'pdf_report' },
pages: '1-5',
format: 'markdown',
})
// OCR (Phase 3)
const ocr = await pdfbase.extract.ocr({
source: { pdf_id: 'pdf_scanned' },
language: 'eng',
format: 'structured',
})
// Table extraction (Phase 3)
const tables = await pdfbase.extract.tables({
source: { pdf_id: 'pdf_invoice' },
pages: '1-3',
format: 'json',
})
// AI structured extraction (Phase 3)
const invoice = await pdfbase.extract.structured({
source: { pdf_id: 'pdf_invoice' },
preset: 'invoice',
})
console.log(invoice.data.total) // 763.00
Convert operations
// Office to PDF (Phase 2)
const pdf = await pdfbase.convert.office({
source: { url: 'https://your-app.com/report.xlsx' },
landscape: true,
})
// PDF to thumbnail (Phase 2)
const thumbnail = await pdfbase.convert.thumbnail({
source: { pdf_id: 'pdf_report' },
page: 1,
})
console.log(thumbnail.url) // PNG thumbnail URL
Error handling
import PDFBase, { PDFBaseError, RateLimitError, AuthenticationError } from '@pdfbase/sdk'
try {
const pdf = await pdfbase.pdfs.create({ html: '<h1>Test</h1>' })
} catch (error) {
if (error instanceof RateLimitError) {
console.log(`Rate limited. Retry after ${error.retryAfter}s`)
} else if (error instanceof AuthenticationError) {
console.log('Invalid API key')
} else if (error instanceof PDFBaseError) {
console.log(`${error.type}: ${error.code} — ${error.message}`)
}
}
Webhook verification
import { verifyWebhookSignature } from '@pdfbase/sdk'
app.post('/webhooks/pdfbase', (req, res) => {
const isValid = verifyWebhookSignature(
req.body, // raw body string
req.headers['pdfbase-signature'], // signature header
process.env.PDFBASE_WEBHOOK_SECRET, // your webhook secret
)
if (!isValid) {
return res.status(401).send('Invalid signature')
}
const event = JSON.parse(req.body)
// Handle event...
res.status(200).send('ok')
})
TypeScript types
The SDK exports full types for every resource:import type { PDF, Template, Batch, BatchItem, WebhookEvent } from '@pdfbase/sdk'
The SDK is auto-generated from the PDFBase OpenAPI spec. It’s always in sync with the API. Don’t submit PRs to the SDK repo — update the spec and regenerate.