Node.js Integration
Learn how to generate PDFs from your Node.js application using the native fetch API or any HTTP client.
Why use PixelToPdf with Node.js?
PixelToPdf provides a simple REST API that integrates seamlessly with Node.js applications. Whether you're building invoices, reports, or any document generation feature, you can convert HTML or URLs to pixel-perfect PDFs with just a few lines of code.
Prerequisites
- Node.js 18+ for native fetch support, or any version with the
node-fetchpackage installed - A PixelToPdf API key from your dashboard (free tier available)
Basic Example
The simplest way to generate a PDF is to convert an existing URL. This example fetches a webpage and saves it as a PDF file. The API key is read from an environment variable for security.
import fs from 'fs';
const response = await fetch('https://api.pixeltopdf.com/convert/pdf', {
method: 'POST',
headers: {
'X-API-Key': process.env.PIXELTOPDF_API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({
source: 'https://example.com',
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const buffer = await response.arrayBuffer();
fs.writeFileSync('output.pdf', Buffer.from(buffer));
console.log('PDF saved to output.pdf');How it works: The source parameter accepts any public URL. PixelToPdf renders the page in a headless browser and returns the PDF as binary data. We use arrayBuffer() to handle the binary response and save it to disk.
Convert HTML String
For dynamic content like invoices or reports, you can pass raw HTML directly. This gives you full control over the PDF content and styling. You can include inline CSS or link to external stylesheets.
import fs from 'fs';
const html = `
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 40px; }
h1 { color: #333; }
</style>
</head>
<body>
<h1>Hello, PixelToPdf!</h1>
<p>This PDF was generated from HTML.</p>
</body>
</html>
`;
const response = await fetch('https://api.pixeltopdf.com/convert/pdf', {
method: 'POST',
headers: {
'X-API-Key': process.env.PIXELTOPDF_API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({
source: html,
format: 'A4',
margin: { top: '20mm', bottom: '20mm', left: '20mm', right: '20mm' },
}),
});
const buffer = await response.arrayBuffer();
fs.writeFileSync('output.pdf', Buffer.from(buffer));Tip: The format option sets the page size (A4, Letter, Legal, etc.) and margin controls the spacing around the content. All margin values support units like mm, cm, in, or px.
With Express.js
In a web application, you typically want to generate PDFs on-demand and stream them directly to the user's browser. This example shows how to create an Express endpoint that generates and downloads an invoice PDF.
import express from 'express';
const app = express();
app.get('/invoice/:id', async (req, res) => {
const response = await fetch('https://api.pixeltopdf.com/convert/pdf', {
method: 'POST',
headers: {
'X-API-Key': process.env.PIXELTOPDF_API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({
source: `https://yourapp.com/invoice/${req.params.id}/html`,
}),
});
if (!response.ok) {
return res.status(500).send('PDF generation failed');
}
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', `attachment; filename="invoice-${req.params.id}.pdf"`);
const buffer = await response.arrayBuffer();
res.send(Buffer.from(buffer));
});
app.listen(3000);How it works: When a user visits /invoice/123, the server calls PixelToPdf to convert your invoice HTML page to PDF, then streams it to the browser with the correct headers for download. The Content-Disposition header tells the browser to download the file instead of displaying it.
Error Handling
Production applications should handle API errors gracefully. This reusable function wraps the API call and throws descriptive errors for common failure cases like invalid credentials, exhausted credits, or rate limiting.
async function generatePdf(source) {
const response = await fetch('https://api.pixeltopdf.com/convert/pdf', {
method: 'POST',
headers: {
'X-API-Key': process.env.PIXELTOPDF_API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({ source }),
});
if (!response.ok) {
const error = await response.json().catch(() => ({}));
switch (response.status) {
case 401:
throw new Error('Invalid API key');
case 402:
throw new Error('No credits remaining');
case 429:
throw new Error('Rate limit exceeded');
default:
throw new Error(error.message || 'PDF generation failed');
}
}
return Buffer.from(await response.arrayBuffer());
}Important: Always check the response status before processing. The API returns JSON error details for non-200 responses. Handle 429 errors by implementing exponential backoff or queuing requests.
Next steps
You've learned the basics! Explore headers, footers, custom CSS injection, and more in our API documentation.