Converting HTML to PDF is one of the most common tasks in web development. Whether you’re generating invoices, creating reports, exporting tickets, or building a document management system, you need a reliable way to turn HTML content into pixel-perfect PDF documents.
In this guide, we’ll walk through how to use the ToolCenter PDF API to convert HTML to PDF programmatically, with complete code examples in Python, Node.js, PHP, and cURL.
Why Use an API for HTML to PDF Conversion?
You might be thinking: “Can’t I just use wkhtmltopdf or Puppeteer?” You can, but here’s why an API is usually the better choice:
Self-Hosted Challenges
- Memory management — Headless browsers consume 200-500MB per instance
- Font rendering — Inconsistent across operating systems
- Scaling — Managing browser pools is complex
- Security — Running untrusted HTML in Chromium poses risks
- Maintenance — Keeping Chromium updated, handling crashes, managing timeouts
API Advantages
- Zero infrastructure — No servers to manage
- Consistent output — Same rendering every time
- Scalability — Handle 1 or 10,000 PDFs without changing your code
- Security — Sandboxed rendering environment
- Speed — Warm browser pools mean faster generation
Common Use Cases
1. Invoice Generation
E-commerce platforms and SaaS products need to generate PDF invoices from HTML templates:
<div class="invoice">
<h1>Invoice #INV-2026-001</h1>
<table>
<tr><td>API Pro Plan</td><td>$29.00</td></tr>
<tr><td>Extra Requests (5,000)</td><td>$15.00</td></tr>
<tr class="total"><td>Total</td><td>$44.00</td></tr>
</table>
</div>
2. Reports and Dashboards
Convert data-rich HTML dashboards into PDF reports for stakeholders who prefer offline documents.
3. Tickets and Boarding Passes
Generate printable tickets with barcodes, QR codes, and formatted layouts from HTML templates.
4. Contracts and Legal Documents
Create formatted legal documents from dynamic HTML templates with proper pagination and headers.
5. Receipts
Point-of-sale systems can generate PDF receipts from HTML templates with proper formatting for thermal printers or email delivery.
Getting Started with ToolCenter PDF API
Step 1: Get Your API Key
Sign up at toolcenter.dev and grab your API key from the dashboard. The free tier includes 100 requests per month — plenty for testing.
Step 2: Understand the API Endpoint
The PDF generation endpoint accepts the following parameters:
Request body:
| Parameter | Type | Required | Description |
|---|---|---|---|
url | string | Either url or html | URL to convert to PDF |
html | string | Either url or html | Raw HTML to convert |
format | string | No | Page size: A4, Letter, Legal (default: A4) |
landscape | boolean | No | Landscape orientation (default: false) |
margin_top | string | No | Top margin (e.g., “20mm”) |
margin_bottom | string | No | Bottom margin |
margin_left | string | No | Left margin |
margin_right | string | No | Right margin |
print_background | boolean | No | Include background colors/images (default: true) |
scale | number | No | Scale factor (0.1 to 2.0) |
header_html | string | No | Custom header HTML |
footer_html | string | No | Custom footer HTML |
Step 3: Make Your First Request
Let’s convert a URL to PDF using different languages.
Code Examples
cURL
# Convert a URL to PDF
curl -X POST "https://toolcenter.dev/api/v1/pdf" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://example.com",
"format": "A4",
"margin_top": "20mm",
"margin_bottom": "20mm",
"margin_left": "15mm",
"margin_right": "15mm"
}' \
--output document.pdf
echo "PDF saved as document.pdf"
# Convert raw HTML to PDF
curl -X POST "https://toolcenter.dev/api/v1/pdf" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"html": "<html><body><h1>Hello World</h1><p>This is a PDF generated from HTML.</p></body></html>",
"format": "A4",
"print_background": true
}' \
--output hello.pdf
Node.js
const ToolCenter = require('devtoolbox-sdk');
const fs = require('fs');
const client = new ToolCenter('YOUR_API_KEY');
// Convert URL to PDF
async function urlToPdf() {
const pdf = await client.pdf({
url: 'https://example.com',
format: 'A4',
marginTop: '20mm',
marginBottom: '20mm',
marginLeft: '15mm',
marginRight: '15mm',
printBackground: true
});
fs.writeFileSync('document.pdf', pdf);
console.log('PDF generated successfully!');
}
// Convert HTML template to PDF (invoice example)
async function generateInvoice(invoiceData) {
const html = `
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 40px; }
.header { display: flex; justify-content: space-between; }
table { width: 100%; border-collapse: collapse; margin-top: 30px; }
th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }
.total { font-weight: bold; font-size: 1.2em; }
</style>
</head>
<body>
<div class="header">
<h1>Invoice #${invoiceData.number}</h1>
<p>Date: ${invoiceData.date}</p>
</div>
<table>
<tr><th>Item</th><th>Amount</th></tr>
${invoiceData.items.map(item =>
`<tr><td>${item.name}</td><td>$${item.amount}</td></tr>`
).join('')}
<tr class="total">
<td>Total</td>
<td>$${invoiceData.total}</td>
</tr>
</table>
</body>
</html>
`;
const pdf = await client.pdf({ html, format: 'A4' });
fs.writeFileSync(`invoice-${invoiceData.number}.pdf`, pdf);
}
urlToPdf();
Python
from devtoolbox import ToolCenter
client = ToolCenter("YOUR_API_KEY")
# Convert URL to PDF
pdf = client.pdf(
url="https://example.com",
format="A4",
margin_top="20mm",
margin_bottom="20mm",
margin_left="15mm",
margin_right="15mm",
print_background=True
)
with open("document.pdf", "wb") as f:
f.write(pdf)
print("PDF generated successfully!")
# Convert HTML to PDF
html_content = """
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 40px; }
h1 { color: #333; }
.highlight { background: #fff3cd; padding: 15px; border-radius: 5px; }
</style>
</head>
<body>
<h1>Monthly Report - February 2026</h1>
<div class="highlight">
<p>Total API calls: 45,231</p>
<p>Success rate: 99.8%</p>
<p>Average response time: 1.2s</p>
</div>
</body>
</html>
"""
pdf = client.pdf(html=html_content, format="A4")
with open("report.pdf", "wb") as f:
f.write(pdf)
print("Report generated!")
PHP
use ToolCenter\Client;
$client = new Client('YOUR_API_KEY');
// Convert URL to PDF
$pdf = $client->pdf([
'url' => 'https://example.com',
'format' => 'A4',
'margin_top' => '20mm',
'margin_bottom' => '20mm',
'margin_left' => '15mm',
'margin_right' => '15mm',
'print_background' => true,
]);
file_put_contents('document.pdf', $pdf);
echo "PDF generated successfully!\n";
// Convert HTML to PDF with custom header/footer
$pdf = $client->pdf([
'html' => '<html><body><h1>Contract</h1><p>Terms and conditions...</p></body></html>',
'format' => 'A4',
'header_html' => '<div style="font-size:10px;text-align:center;">CONFIDENTIAL</div>',
'footer_html' => '<div style="font-size:10px;text-align:center;">Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>',
]);
file_put_contents('contract.pdf', $pdf);
Advanced Features
Custom Headers and Footers
Add professional headers and footers to your PDFs:
curl -X POST "https://toolcenter.dev/api/v1/pdf" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://example.com",
"format": "A4",
"header_html": "<div style=\"font-size:10px;width:100%;text-align:center;color:#999;\">Company Name — Confidential</div>",
"footer_html": "<div style=\"font-size:10px;width:100%;text-align:center;color:#999;\">Page <span class=\"pageNumber\"></span> of <span class=\"totalPages\"></span></div>"
}' \
--output report.pdf
Landscape Mode
Perfect for wide tables, charts, and dashboards:
const pdf = await client.pdf({
url: 'https://dashboard.example.com',
format: 'A4',
landscape: true,
printBackground: true
});
Custom Page Sizes
Use predefined sizes or specify custom dimensions:
# Letter size (US standard)
pdf = client.pdf(url="https://example.com", format="Letter")
# Legal size
pdf = client.pdf(url="https://example.com", format="Legal")
Best Practices
1. Use Print Stylesheets
Add a @media print stylesheet to your HTML for optimal PDF output:
@media print {
.no-print { display: none; }
body { font-size: 12pt; }
a { text-decoration: none; color: #000; }
.page-break { page-break-after: always; }
}
2. Handle Pagination
Use CSS page break properties for multi-page documents:
.section { page-break-inside: avoid; }
h2 { page-break-after: avoid; }
.chapter { page-break-before: always; }
3. Embed Fonts
For consistent rendering, use web fonts or embed fonts as base64:
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap');
body { font-family: 'Inter', sans-serif; }
</style>
4. Optimize Images
Ensure images are accessible via public URLs or embed them as base64 data URIs for reliable rendering.
5. Test with Print Preview
Use your browser’s print preview (Ctrl+P) to approximate how the PDF will look before making API calls.
Pricing
ToolCenter PDF API is included in all plans at no extra cost:
| Plan | Price | Monthly Requests | Features |
|---|---|---|---|
| Free | $0 | 100 | All tools included |
| Starter | $9/mo | 5,000 | Priority support |
| Pro | $29/mo | 25,000 | Bulk operations, signed URLs |
| Business | $79/mo | 100,000 | Custom webhooks, SLA |
Conclusion
Converting HTML to PDF doesn’t have to be painful. With the ToolCenter PDF API, you can generate professional PDF documents from any URL or HTML content in seconds, without managing headless browsers or dealing with rendering inconsistencies.
The API handles the complexity of PDF generation — fonts, pagination, headers, footers, and scaling — so you can focus on building your application.
Need help? Check the API documentation or reach out to our support team.