@pdfik/client
v0.2.1
Published
Official TypeScript SDK for the PDFik PDF generation API
Downloads
82
Readme
@pdfik/client
Official JavaScript/TypeScript SDK for PDFik — the premium, fast, and reliable PDF generation API.
Convert HTML markup or any public URL into pixel-perfect PDF documents in seconds, powered by scalable browser rendering.
Features
- TypeScript Native: Full auto-complete and type safety for all endpoints.
- Dual Build: ES Modules (ESM) and CommonJS (CJS) support.
- Zero Runtime Dependencies: Uses native
fetch(Node 18+, browsers, Edge). - Auto Retry: Automatic exponential backoff for
5xxand429(Rate Limit) errors. - DX Affordances: Built-in polling logic (
waitForJob) and binary download helpers.
Installation
npm install @pdfik/client
# or
yarn add @pdfik/client
# or
pnpm add @pdfik/clientQuick Start
Convert public URL to PDF
import { PdfikClient } from '@pdfik/client';
// Initialize the client
const client = new PdfikClient({
apiKey: 'sk_live_...' // Get your API key from the dashboard
});
async function generatePdf() {
try {
// 1. Submit the URL to be rendered
const job = await client.urlToPdf('https://example.com', {
options: {
format: 'A4',
landscape: false,
printBackground: true,
margin: { top: '10mm', right: '10mm', bottom: '10mm', left: '10mm' }
}
});
console.log(`Job created: ${job.jobId}. Waiting for rendering...`);
// 2. Poll until the job completes
const result = await client.waitForJob(job.jobId);
console.log(`Job finished! Pages: ${result.pagesCount}`);
// 3. Download the PDF bytes
const pdfBytes = await client.downloadPdf(job.jobId);
// Save to file (Node.js example)
const fs = require('fs');
fs.writeFileSync('output.pdf', pdfBytes);
console.log('PDF saved to output.pdf');
} catch (error) {
console.error('Failed to generate PDF:', error);
}
}
generatePdf();Convert raw HTML to PDF
const job = await client.htmlToPdf('<h1>Hello World</h1><p>Sent from PDFik SDK</p>', {
options: {
format: 'Letter',
displayHeaderFooter: true,
headerTemplate: "<span style='font-size: 10px;'>My Invoice Header</span>",
footerTemplate: "<span style='font-size: 10px;'>Page <span class='pageNumber'></span></span>"
}
});Get the direct download URL
Get the direct API download URL for the generated PDF (requires the "X-API-Key" header to download):
const { downloadUrl } = await client.getFileUrl(job.jobId);
console.log(`Direct Download URL: ${downloadUrl}`);Handling Webhooks
If you specify webhookUrl in the options of urlToPdf or htmlToPdf, PDFik will send an HTTP POST request to your server when the rendering job is finished.
You should verify the authenticity of the webhook by validating the signature. We provide a static helper verifyWebhookSignature in PdfikClient for this purpose.
Example (Express / Node.js):
import express from 'express';
import { PdfikClient } from '@pdfik/client';
const app = express();
// IMPORTANT: Use raw body parser to get the exact raw bytes for verification
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
const webhookSecret = process.env.PDFIK_WEBHOOK_SECRET || 'whsec_...';
const rawBody = req.body.toString('utf8');
// Pass req.headers directly (contains X-PDFik-Signature and X-PDFik-Timestamp)
const isValid = PdfikClient.verifyWebhookSignature(rawBody, req.headers as any, webhookSecret);
if (!isValid) {
console.error('Invalid webhook signature!');
return res.status(400).send('Invalid signature');
}
const event = JSON.parse(rawBody);
console.log(`Webhook received for job: ${event.job_id}, status: ${event.status}`);
if (event.event_type === 'job.completed') {
console.log(`PDF rendered! Download URL: https://api.pdfik.net/jobs/${event.job_id}/download`);
}
res.status(200).send('OK');
});
app.listen(3000, () => console.log('Webhook server running on port 3000'));API Reference
PdfikClient
constructor(config: { apiKey: string; baseUrl?: string })Methods
urlToPdf(url, opts): Submits a job to convert a public URL to a PDF. Returns aJobCreatedResponse.htmlToPdf(html, opts): Submits a job to convert raw HTML markup to a PDF. Returns aJobCreatedResponse.getJob(jobId): Fetches the status of a specific job. Returns aJobStatusResponse.waitForJob(jobId, opts): Helper that pollsgetJobuntil the job isdoneorfailed. Throws aPdfikErrorif the job fails or times out.opts.timeoutMs(default:120000ms)opts.pollIntervalMs(default:2000ms)
getFileUrl(jobId): Returns the direct download URL for the PDF (requires the "X-API-Key" header).downloadPdf(jobId): Downloads and returns the PDF file as aUint8Array.verifyWebhookSignature(rawBody, headers, webhookSecret): (Static) Verifies the webhook HMAC-SHA256 signature using the raw request body and request headers. Returnsboolean.
License
MIT License.
