# PDFBolt - Scalable and Privacy‑First PDF Generation API > PDFBolt API - generate professional PDFs from HTML, URLs, and dynamic templates using REST endpoints. Supports Node.js, Python, Java, PHP, C#, Go, Rust with Direct/Sync/Async modes, Handlebars templates, direct S3 uploads, team collaboration, GDPR compliance, and enterprise-grade privacy. This file contains all documentation content in a single document following the llmstxt.org standard. ## Introduction 🎉 Welcome to the PDFBolt API! For quick setup instructions, head over to the [Quick Start Guide](/docs/quick-start-guide). Continue reading to explore the [API Endpoints](/docs/api-endpoints), fine‑tune [Parameters](/docs/parameters), create dynamic [Templates](/docs/pdf-templates), and uncover best practices to maximize the efficiency of our powerful PDF generation API. Let's get started and transform the way you handle documents! ## Overview PDFBolt is a robust PDF generation API that converts HTML content, web pages, and dynamic templates into **high-quality PDFs**. It’s designed for scalability, security, ease of use, and reliability – making it ideal for developers and businesses who need a fast, flexible, and cost-effective way to generate PDFs from various sources. ## Purpose and Benefits * Built to make PDF generation simple and accessible, PDFBolt offers a streamlined integration process with powerful templating capabilities that separate design from data. * Like Stripe for payment processing, PDFBolt aspires to be equally developer-friendly in document generation, supporting various business sizes and needs. * Privacy is a top priority at PDFBolt, ensuring data is handled securely throughout every step of the conversion process. ## Key Features - High-quality PDF rendering with [synchronous](/docs/api-endpoints/sync) and [asynchronous](/docs/api-endpoints/async) options. - **Dynamic template functionality** with Handlebars support for reusable PDF layouts (more details in the [Templates](/docs/pdf-templates) section). - Intuitive Admin Dashboard for monitoring usage and managing account settings (more details in the [Admin Dashboard](/docs/admin-dashboard) section). - API with clear, user-friendly documentation that enables integration across multiple languages. - Cost-efficient [pricing plans](/#pricing-plans) suitable for small and large-scale requirements. 🚀 Ready to transform your workflows? Get started with PDFBolt today! --- ## Quick Start Guide Below is a **step-by-step guide** to get up and running with PDFBolt's **PDF generation API** quickly. Test with cURL or Postman, or integrate using Node.js, Python, Java, PHP, C#, Go, Rust. ### 1. Sign Up and Get Your API Key Start by [signing up](https://app.pdfbolt.com/register) for an account. Once registered, you'll find your unique API key in the Admin Dashboard under the **API Keys** section. Every new user is automatically enrolled in our **free plan**, which provides **100 document conversions per month** to explore PDFBolt’s features. For more details on managing API keys, visit the Admin Dashboard [API Keys](/docs/admin-dashboard/api-keys) section. :::tip Quick API Testing with Postman 🚀 - Use our Postman collection and start testing API requests in seconds! - For detailed instructions, check out our [Quick Start Guide for Postman](/docs/quick-start-guide/postman). **Click the button below to get started:** [](https://app.getpostman.com/run-collection/40399365-9472b2d4-c8da-4338-8774-962cc6bb9347?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D40399365-9472b2d4-c8da-4338-8774-962cc6bb9347%26entityType%3Dcollection%26workspaceId%3D3a6b1d25-d352-4c2e-8a9b-0b4fcb6d6cae#?env%5BPDFBolt%5D=W3sia2V5IjoiYmFzZV91cmwiLCJ2YWx1ZSI6Imh0dHBzOi8vYXBpLnBkZmJvbHQuY29tIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQiLCJzZXNzaW9uVmFsdWUiOiJodHRwczovL2FwaS5wZGZib2x0LmNvbSIsImNvbXBsZXRlU2Vzc2lvblZhbHVlIjoiaHR0cHM6Ly9hcGkucGRmYm9sdC5jb20iLCJzZXNzaW9uSW5kZXgiOjB9LHsia2V5IjoiQVBJX0tFWSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6InNlY3JldCIsInNlc3Npb25WYWx1ZSI6IiIsImNvbXBsZXRlU2Vzc2lvblZhbHVlIjoiIiwic2Vzc2lvbkluZGV4IjoxfSx7ImtleSI6IndlYmhvb2tfdXJsIiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoiZGVmYXVsdCIsInNlc3Npb25WYWx1ZSI6IiIsImNvbXBsZXRlU2Vzc2lvblZhbHVlIjoiIiwic2Vzc2lvbkluZGV4IjoyfSx7ImtleSI6ImN1c3RvbVMzX3VybCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQiLCJzZXNzaW9uVmFsdWUiOiIiLCJjb21wbGV0ZVNlc3Npb25WYWx1ZSI6IiIsInNlc3Npb25JbmRleCI6M31d) ::: ### 2. Set Up Authorization Securely access PDFBolt's API by including your unique `API-KEY` in the headers of your REST API requests: ```bash API-KEY: YOUR-API-KEY ``` ### 3. Make Your First Request Choose your preferred endpoint and source combination using cURL. **➡️ Endpoints:** The **Direct** endpoint provides immediate PDF generation and returns the raw PDF file in the response. **➡️ Sources:** **Convert any webpage into a PDF:** ```bash curl 'https://api.pdfbolt.com/v1/direct' \ -H 'Content-Type: application/json' \ -H 'API-KEY: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' \ -d '{ "url": "https://example.com", "format": "A4", "printBackground": true }' \ -o webpage.pdf ``` **Convert HTML content directly into a PDF:** ```bash curl 'https://api.pdfbolt.com/v1/direct' \ -H 'Content-Type: application/json' \ -H 'API-KEY: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' \ -d '{ "html": "PGh0bWw+PGJvZHk+PGgxPkhlbGxvITwvaDE+PHA+VGhpcyBpcyBhIHNhbXBsZSBQREYuPC9wPjwvYm9keT48L2h0bWw+", "margin": { "top": "30px", "left": "30px" } }' \ -o document.pdf ``` :::note Base64 Explanation The base64 encoded HTML above represents: ``` Hello!This is a sample PDF. ``` ::: **Use reusable templates for dynamic PDF generation:** ```bash curl 'https://api.pdfbolt.com/v1/direct' \ -H 'Content-Type: application/json' \ -H 'API-KEY: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' \ -d '{ "templateId": "your-template-id", "templateData": { "client_name": "John Doe", "invoice_number": "INV-001", "total_amount": "$299.99", "line_items": [ { "description": "Web Development", "unit_price": "$200.00" }, { "description": "Design Services", "unit_price": "$99.99" } ] } }' \ -o invoice.pdf ``` :::info New to templates? Create your first template in the app, then use its ID in your API calls. **[→ Learn more about Templates](/docs/pdf-templates)** ::: The **Sync** endpoint returns a JSON response with a download URL for the PDF. **➡️ Sources:** **Convert webpage and get download URL:** ```bash curl 'https://api.pdfbolt.com/v1/sync' \ -H 'Content-Type: application/json' \ -H 'API-KEY: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' \ -d '{ "url": "https://example.com", "format": "A4", "printBackground": true }' ``` **Convert HTML and get download URL:** ```bash curl 'https://api.pdfbolt.com/v1/sync' \ -H 'Content-Type: application/json' \ -H 'API-KEY: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' \ -d '{ "html": "PGh0bWw+PGJvZHk+PGgxPkhlbGxvITwvaDE+PHA+VGhpcyBpcyBhIHNhbXBsZSBQREYuPC9wPjwvYm9keT48L2h0bWw+", "margin": { "top": "30px", "left": "30px" } }' ``` **Use templates and get download URL:** ```bash curl 'https://api.pdfbolt.com/v1/sync' \ -H 'Content-Type: application/json' \ -H 'API-KEY: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' \ -d '{ "templateId": "your-template-id", "templateData": { "client_name": "John Doe", "invoice_number": "INV-001", "total_amount": "$299.99", "line_items": [ { "description": "Web Development", "unit_price": "$200.00" }, { "description": "Design Services", "unit_price": "$99.99" } ] } }' ``` The **Async** endpoint processes requests asynchronously and sends results via webhook. **➡️ Sources:** **Convert webpage with webhook notification:** ```bash curl 'https://api.pdfbolt.com/v1/async' \ -H 'Content-Type: application/json' \ -H 'API-KEY: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' \ -d '{ "url": "https://example.com", "format": "A4", "printBackground": true, "webhook": "https://your-app.com/webhook" }' ``` **Convert HTML with webhook notification:** ```bash curl 'https://api.pdfbolt.com/v1/async' \ -H 'Content-Type: application/json' \ -H 'API-KEY: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' \ -d '{ "html": "PGh0bWw+PGJvZHk+PGgxPkhlbGxvITwvaDE+PHA+VGhpcyBpcyBhIHNhbXBsZSBQREYuPC9wPjwvYm9keT48L2h0bWw+", "margin": { "top": "30px", "left": "30px" }, "webhook": "https://your-app.com/webhook" }' ``` **Use templates with webhook notification:** ```bash curl 'https://api.pdfbolt.com/v1/async' \ -H 'Content-Type: application/json' \ -H 'API-KEY: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' \ -d '{ "templateId": "your-template-id", "templateData": { "client_name": "John Doe", "invoice_number": "INV-001", "total_amount": "$299.99", "line_items": [ { "description": "Web Development", "unit_price": "$200.00" }, { "description": "Design Services", "unit_price": "$99.99" } ] }, "webhook": "https://your-app.com/webhook" }' ``` ### 4. Quick Start for Your Favorite Language and Postman Ready to get started? Choose your favorite language or tool and follow our tailored step‑by‑step guides to integrate PDFBolt with ease. --- ## Node.js # Quick Start for Node.js Both wkhtmltopdf and Puppeteer are well-supported in Node.js, though they can be complex to configure for specific needs. Our PDF generation API provides a quicker, easier way to generate PDFs from HTML, URLs, and dynamic templates. Here's how to start in Node.js. ### 1. Get Your API Key * After registering, log in to the **Admin Dashboard** and navigate to the **API Keys** section to retrieve your API key. * Ensure you keep this key secure, as it is essential for authorizing your requests to the PDFBolt API. ### 2. Make Your First Request Follow these examples below to send basic requests to the PDFBolt API and generate your PDFs effortlessly. **Choose your preferred endpoint and source combination.** **➡️ Endpoints:** The **Direct** endpoint provides immediate PDF generation and returns the raw PDF file in the response. **➡️ Sources:** **Convert any webpage into a PDF:** ```js const fs = require('fs'); async function generatePdf() { const response = await fetch('https://api.pdfbolt.com/v1/direct', { method: 'POST', headers: { 'API-KEY': 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', 'Content-Type': 'application/json' }, body: JSON.stringify({ url: 'https://example.com', format: 'A4', printBackground: true }) }); if (!response.ok) { const errorText = await response.text(); throw new Error(`HTTP ${response.status} - ${errorText}`); } const pdfBuffer = await response.arrayBuffer(); fs.writeFileSync('webpage.pdf', Buffer.from(pdfBuffer)); console.log('PDF generated successfully'); } generatePdf().catch(console.error); ``` **Convert HTML content directly into a PDF** (HTML must be base64 encoded): ```js const fs = require('fs'); async function generatePdf() { const htmlContent = 'Hello!This is a sample PDF.'; const base64Html = Buffer.from(htmlContent).toString('base64'); const response = await fetch('https://api.pdfbolt.com/v1/direct', { method: 'POST', headers: { 'Content-Type': 'application/json', 'API-KEY': 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' }, body: JSON.stringify({ html: base64Html, margin: { top: '30px', left: '30px' } }) }); if (!response.ok) { const errorText = await response.text(); throw new Error(`HTTP ${response.status} - ${errorText}`); } const pdfBuffer = await response.arrayBuffer(); fs.writeFileSync('document.pdf', Buffer.from(pdfBuffer)); console.log('PDF generated successfully'); } generatePdf().catch(console.error); ``` **Use reusable templates for dynamic PDF generation:** ```js const fs = require('fs'); async function generatePdf() { const response = await fetch('https://api.pdfbolt.com/v1/direct', { method: 'POST', headers: { 'API-KEY': 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', 'Content-Type': 'application/json' }, body: JSON.stringify({ templateId: 'your-template-id', templateData: { client_name: 'John Doe', invoice_number: 'INV-001', total_amount: '$299.99', line_items: [ { description: 'Web Development', unit_price: '$200.00' }, { description: 'Design Services', unit_price: '$99.99' } ] } }) }); if (!response.ok) { const errorText = await response.text(); throw new Error(`HTTP ${response.status} - ${errorText}`); } const pdfBuffer = await response.arrayBuffer(); fs.writeFileSync('invoice.pdf', Buffer.from(pdfBuffer)); console.log('PDF generated successfully'); } generatePdf().catch(console.error); ``` :::info New to templates? Create your first template in the app, then use its ID in your API calls. **[→ Learn more about Templates](/docs/pdf-templates)** ::: The **Sync** endpoint returns a JSON response with a download URL for the PDF. **➡️ Sources:** **Convert any webpage and get download URL:** ```js async function generatePdf() { const response = await fetch('https://api.pdfbolt.com/v1/sync', { method: 'POST', headers: { 'API-KEY': 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', 'Content-Type': 'application/json' }, body: JSON.stringify({ url: 'https://example.com', format: 'A4', printBackground: true }) }); if (!response.ok) { const errorText = await response.text(); throw new Error(`HTTP ${response.status} - ${errorText}`); } const result = await response.json(); console.log('PDF URL:', result.documentUrl); } generatePdf().catch(console.error); ``` **Convert HTML content and get download URL:** ```js async function generatePdf() { const htmlContent = 'Hello!This is a sample PDF.'; const base64Html = Buffer.from(htmlContent).toString('base64'); const response = await fetch('https://api.pdfbolt.com/v1/sync', { method: 'POST', headers: { 'Content-Type': 'application/json', 'API-KEY': 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' }, body: JSON.stringify({ html: base64Html, margin: { top: '30px', left: '30px' } }) }); if (!response.ok) { const errorText = await response.text(); throw new Error(`HTTP ${response.status} - ${errorText}`); } const result = await response.json(); console.log('PDF URL:', result.documentUrl); } generatePdf().catch(console.error); ``` **Use templates and get download URL:** ```js async function generatePdf() { const response = await fetch('https://api.pdfbolt.com/v1/sync', { method: 'POST', headers: { 'API-KEY': 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', 'Content-Type': 'application/json' }, body: JSON.stringify({ templateId: 'your-template-id', templateData: { client_name: 'John Doe', invoice_number: 'INV-001', total_amount: '$299.99', line_items: [ { description: 'Web Development', unit_price: '$200.00' }, { description: 'Design Services', unit_price: '$99.99' } ] } }) }); if (!response.ok) { const errorText = await response.text(); throw new Error(`HTTP ${response.status} - ${errorText}`); } const result = await response.json(); console.log('PDF URL:', result.documentUrl); } generatePdf().catch(console.error); ``` The **Async** endpoint processes requests asynchronously and sends results via webhook. **➡️ Sources:** **Convert webpage with webhook notification:** ```js async function generatePdf() { const response = await fetch('https://api.pdfbolt.com/v1/async', { method: 'POST', headers: { 'API-KEY': 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', 'Content-Type': 'application/json' }, body: JSON.stringify({ url: 'https://example.com', format: 'A4', printBackground: true, webhook: 'https://your-app.com/webhook' }) }); if (!response.ok) { const errorText = await response.text(); throw new Error(`HTTP ${response.status} - ${errorText}`); } const result = await response.json(); console.log('Request ID:', result.requestId); console.log('PDF will be sent to webhook when ready'); } generatePdf().catch(console.error); ``` **Convert HTML with webhook notification:** ```js async function generatePdf() { const htmlContent = 'Hello!This is a sample PDF.'; const base64Html = Buffer.from(htmlContent).toString('base64'); const response = await fetch('https://api.pdfbolt.com/v1/async', { method: 'POST', headers: { 'Content-Type': 'application/json', 'API-KEY': 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' }, body: JSON.stringify({ html: base64Html, margin: { top: '30px', left: '30px' }, webhook: 'https://your-app.com/webhook' }) }); if (!response.ok) { const errorText = await response.text(); throw new Error(`HTTP ${response.status} - ${errorText}`); } const result = await response.json(); console.log('Request ID:', result.requestId); console.log('PDF will be sent to webhook when ready'); } generatePdf().catch(console.error); ``` **Use templates with webhook notification:** ```js async function generatePdf() { const response = await fetch('https://api.pdfbolt.com/v1/async', { method: 'POST', headers: { 'API-KEY': 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', 'Content-Type': 'application/json' }, body: JSON.stringify({ templateId: 'your-template-id', templateData: { client_name: 'John Doe', invoice_number: 'INV-001', total_amount: '$299.99', line_items: [ { description: 'Web Development', unit_price: '$200.00' }, { description: 'Design Services', unit_price: '$99.99' } ] }, webhook: 'https://your-app.com/webhook' }) }); if (!response.ok) { const errorText = await response.text(); throw new Error(`HTTP ${response.status} - ${errorText}`); } const result = await response.json(); console.log('Request ID:', result.requestId); console.log('PDF will be sent to webhook when ready'); } generatePdf().catch(console.error); ``` ### 3. What's next? Continue your journey with PDFBolt by exploring its powerful features and benefits. Start by checking the available [API Endpoints](/docs/api-endpoints) and dive into the [Conversion Parameters](/docs/parameters) to customize your integration for your unique needs. --- ## Python # Quick Start for Python Python offers several libraries for PDF generation, but they can be complex to set up and configure. Our PDF generation API provides a simpler, more flexible way to generate PDFs from HTML, URLs, and dynamic templates. Here's how to start in Python. ### 1. Get Your API Key * After registering, log in to the **Admin Dashboard** and navigate to the **API Keys** section to retrieve your API key. * Ensure you keep this key secure, as it is essential for authorizing your requests to the PDFBolt API. ### 2. Make Your First Request Use these examples to make requests to the PDFBolt API and generate PDFs quickly. **Choose your preferred endpoint and source combination.** **➡️ Endpoints:** The **Direct** endpoint provides immediate PDF generation and returns the raw PDF file in the response. **➡️ Sources:** **Convert any webpage into a PDF:** ```python url = "https://api.pdfbolt.com/v1/direct" headers = { "API-KEY": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "Content-Type": "application/json" } data_json = '''{ "url": "https://example.com", "format": "A4", "printBackground": true }''' data = json.loads(data_json) try: response = requests.post(url, headers=headers, json=data) response.raise_for_status() with open('webpage.pdf', 'wb') as f: f.write(response.content) print("PDF generated successfully") except requests.exceptions.HTTPError as e: print(f"HTTP {response.status_code}") print(f"Error Message: {response.text}") except requests.exceptions.RequestException as e: print(f"Error: {e}") ``` **Convert HTML content directly into a PDF:** ```python html_content = "Hello!This is a sample PDF." base64_html = base64.b64encode(html_content.encode()).decode() url = "https://api.pdfbolt.com/v1/direct" headers = { "API-KEY": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "Content-Type": "application/json" } data_json = f'''{{ "html": "{base64_html}", "margin": {{ "top": "30px", "left": "30px" }} }}''' data = json.loads(data_json) try: response = requests.post(url, headers=headers, json=data) response.raise_for_status() with open('document.pdf', 'wb') as f: f.write(response.content) print("PDF generated successfully") except requests.exceptions.HTTPError as e: print(f"HTTP {response.status_code}") print(f"Error Message: {response.text}") except requests.exceptions.RequestException as e: print(f"Error: {e}") ``` **Use reusable templates for dynamic PDF generation:** ```python url = "https://api.pdfbolt.com/v1/direct" headers = { "API-KEY": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "Content-Type": "application/json" } data_json = '''{ "templateId": "your-template-id", "templateData": { "client_name": "John Doe", "invoice_number": "INV-001", "total_amount": "$299.99", "line_items": [ {"description": "Web Development", "unit_price": "$200.00"}, {"description": "Design Services", "unit_price": "$99.99"} ] } }''' data = json.loads(data_json) try: response = requests.post(url, headers=headers, json=data) response.raise_for_status() with open('invoice.pdf', 'wb') as f: f.write(response.content) print("PDF generated successfully") except requests.exceptions.HTTPError as e: print(f"HTTP {response.status_code}") print(f"Error Message: {response.text}") except requests.exceptions.RequestException as e: print(f"Error: {e}") ``` :::info New to templates? Create your first template in the app, then use its ID in your API calls. **[→ Learn more about Templates](/docs/pdf-templates)** ::: The **Sync** endpoint returns a JSON response with a download URL for the PDF. **➡️ Sources:** **Convert webpage and get download URL:** ```python url = "https://api.pdfbolt.com/v1/sync" headers = { "API-KEY": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "Content-Type": "application/json" } data_json = '''{ "url": "https://example.com", "format": "A4", "printBackground": true }''' data = json.loads(data_json) try: response = requests.post(url, headers=headers, json=data) response.raise_for_status() result = response.json() print(f"PDF URL: {result['documentUrl']}") except requests.exceptions.HTTPError as e: print(f"HTTP {response.status_code}") print(f"Error Message: {response.text}") except requests.exceptions.RequestException as e: print(f"Error: {e}") ``` **Convert HTML and get download URL:** ```python html_content = "Hello!This is a sample PDF." base64_html = base64.b64encode(html_content.encode()).decode() url = "https://api.pdfbolt.com/v1/sync" headers = { "API-KEY": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "Content-Type": "application/json" } data_json = f'''{{ "html": "{base64_html}", "margin": {{ "top": "30px", "left": "30px" }} }}''' data = json.loads(data_json) try: response = requests.post(url, headers=headers, json=data) response.raise_for_status() result = response.json() print(f"PDF URL: {result['documentUrl']}") except requests.exceptions.HTTPError as e: print(f"HTTP {response.status_code}") print(f"Error Message: {response.text}") except requests.exceptions.RequestException as e: print(f"Error: {e}") ``` **Use templates and get download URL:** ```python url = "https://api.pdfbolt.com/v1/sync" headers = { "API-KEY": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "Content-Type": "application/json" } data_json = '''{ "templateId": "your-template-id", "templateData": { "client_name": "John Doe", "invoice_number": "INV-001", "total_amount": "$299.99", "line_items": [ {"description": "Web Development", "unit_price": "$200.00"}, {"description": "Design Services", "unit_price": "$99.99"} ] } }''' data = json.loads(data_json) try: response = requests.post(url, headers=headers, json=data) response.raise_for_status() result = response.json() print(f"PDF URL: {result['documentUrl']}") except requests.exceptions.HTTPError as e: print(f"HTTP {response.status_code}") print(f"Error Message: {response.text}") except requests.exceptions.RequestException as e: print(f"Error: {e}") ``` The **Async** endpoint processes requests asynchronously and sends results via webhook. **➡️ Sources:** **Convert webpage with webhook notification:** ```python url = "https://api.pdfbolt.com/v1/async" headers = { "API-KEY": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "Content-Type": "application/json" } data_json = '''{ "url": "https://example.com", "format": "A4", "printBackground": true, "webhook": "https://your-app.com/webhook" }''' data = json.loads(data_json) try: response = requests.post(url, headers=headers, json=data) response.raise_for_status() result = response.json() print(f"Request ID: {result['requestId']}") print("PDF will be sent to webhook when ready") except requests.exceptions.HTTPError as e: print(f"HTTP {response.status_code}") print(f"Error Message: {response.text}") except requests.exceptions.RequestException as e: print(f"Error: {e}") ``` **Convert HTML with webhook notification:** ```python html_content = "Hello!This is a sample PDF." base64_html = base64.b64encode(html_content.encode()).decode() url = "https://api.pdfbolt.com/v1/async" headers = { "API-KEY": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "Content-Type": "application/json" } data_json = f'''{{ "html": "{base64_html}", "margin": {{ "top": "30px", "left": "30px" }}, "webhook": "https://your-app.com/webhook" }}''' data = json.loads(data_json) try: response = requests.post(url, headers=headers, json=data) response.raise_for_status() result = response.json() print(f"Request ID: {result['requestId']}") print("PDF will be sent to webhook when ready") except requests.exceptions.HTTPError as e: print(f"HTTP {response.status_code}") print(f"Error Message: {response.text}") except requests.exceptions.RequestException as e: print(f"Error: {e}") ``` **Use templates with webhook notification:** ```python url = "https://api.pdfbolt.com/v1/async" headers = { "API-KEY": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "Content-Type": "application/json" } data_json = '''{ "templateId": "your-template-id", "templateData": { "client_name": "John Doe", "invoice_number": "INV-001", "total_amount": "$299.99", "line_items": [ {"description": "Web Development", "unit_price": "$200.00"}, {"description": "Design Services", "unit_price": "$99.99"} ] }, "webhook": "https://your-app.com/webhook" }''' data = json.loads(data_json) try: response = requests.post(url, headers=headers, json=data) response.raise_for_status() result = response.json() print(f"Request ID: {result['requestId']}") print("PDF will be sent to webhook when ready") except requests.exceptions.HTTPError as e: print(f"HTTP {response.status_code}") print(f"Error Message: {response.text}") except requests.exceptions.RequestException as e: print(f"Error: {e}") ``` ### 3. What's next? Continue your journey with PDFBolt by exploring its powerful features and benefits. Start by checking the available [API Endpoints](/docs/api-endpoints) and dive into the [Conversion Parameters](/docs/parameters) to customize your integration for your unique needs. --- ## Java # Quick Start for Java Java supports wkhtmltopdf integration, but Puppeteer requires additional workarounds due to its lack of native support. PDFBolt's PDF generation API offers a faster and more reliable approach to generating PDFs from HTML, URLs, and dynamic templates. Follow these steps to get started with Java. ### 1. Get Your API Key * Your API Key is available in the **Admin Dashboard** under the **API Keys** section after registration. * Ensure you keep this key secure, as it is required for authorization requests to the PDFBolt API. ### 2. Make Your First Request Use the following examples to quickly make requests to the PDFBolt API and generate your PDF documents. **Choose your preferred endpoint and source combination.** **➡️ Endpoints:** The **Direct** endpoint provides immediate PDF generation and returns the raw PDF file in the response. **➡️ Sources:** **Convert any webpage into a PDF:** ```java public class PDFBoltIntegrationUrl { public static void main(String[] args) throws Exception { String jsonBody = """ { "url": "https://example.com", "format": "A4", "printBackground": true } """; var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder() .uri(URI.create("https://api.pdfbolt.com/v1/direct")) .header("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(jsonBody)) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() == 200) { Files.write(Paths.get("webpage.pdf"), response.body()); System.out.println("PDF generated successfully"); } else { System.err.println("HTTP " + response.statusCode()); System.err.println("Error Message: " + new String(response.body())); } } } ``` **Convert HTML content directly into a PDF:** ```java public class PDFBoltIntegrationHtml { public static void main(String[] args) throws Exception { String htmlContent = "Hello!This is a sample PDF."; String base64Html = Base64.getEncoder().encodeToString(htmlContent.getBytes()); String jsonBody = """ { "html": "%s", "margin": { "top": "30px", "left": "30px" } } """.formatted(base64Html); var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder() .uri(URI.create("https://api.pdfbolt.com/v1/direct")) .header("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(jsonBody)) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() == 200) { Files.write(Paths.get("document.pdf"), response.body()); System.out.println("PDF generated successfully"); } else { System.err.println("HTTP " + response.statusCode()); System.err.println("Error Message: " + new String(response.body())); } } } ``` **Use reusable templates for dynamic PDF generation:** ```java public class PDFBoltIntegrationTemplate { public static void main(String[] args) throws Exception { String jsonBody = """ { "templateId": "your-template-id", "templateData": { "client_name": "John Doe", "invoice_number": "INV-001", "total_amount": "$299.99", "line_items": [ { "description": "Web Development", "unit_price": "$200.00" }, { "description": "Design Services", "unit_price": "$99.99" } ] } } """; var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder() .uri(URI.create("https://api.pdfbolt.com/v1/direct")) .header("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(jsonBody)) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofByteArray()); if (response.statusCode() == 200) { Files.write(Paths.get("invoice.pdf"), response.body()); System.out.println("PDF generated successfully"); } else { System.err.println("HTTP " + response.statusCode()); System.err.println("Error Message: " + new String(response.body())); } } } ``` :::info New to templates? Create your first template in the app, then use its ID in your API calls. **[→ Learn more about Templates](/docs/pdf-templates)** ::: The **Sync** endpoint returns a JSON response with a download URL for the PDF. **➡️ Sources:** **Convert webpage and get download URL:** ```java public class PDFBoltIntegrationUrl { public static void main(String[] args) throws Exception { String jsonBody = """ { "url": "https://example.com", "format": "A4", "printBackground": true } """; var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder() .uri(URI.create("https://api.pdfbolt.com/v1/sync")) .header("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(jsonBody)) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() == 200) { String responseBody = response.body(); String documentUrl = responseBody.split("\"documentUrl\":\"")[1].split("\"")[0]; System.out.println("PDF URL: " + documentUrl); } else { System.err.println("HTTP " + response.statusCode()); System.err.println("Error Message: " + response.body()); } } } ``` **Convert HTML and get download URL:** ```java public class PDFBoltIntegrationHtml { public static void main(String[] args) throws Exception { String htmlContent = "Hello!This is a sample PDF."; String base64Html = Base64.getEncoder().encodeToString(htmlContent.getBytes()); String jsonBody = """ { "html": "%s", "margin": { "top": "30px", "left": "30px" } } """.formatted(base64Html); var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder() .uri(URI.create("https://api.pdfbolt.com/v1/sync")) .header("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(jsonBody)) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() == 200) { String responseBody = response.body(); String documentUrl = responseBody.split("\"documentUrl\":\"")[1].split("\"")[0]; System.out.println("PDF URL: " + documentUrl); } else { System.err.println("HTTP " + response.statusCode()); System.err.println("Error Message: " + response.body()); } } } ``` **Use templates and get download URL:** ```java public class PDFBoltIntegrationTemplate { public static void main(String[] args) throws Exception { String jsonBody = """ { "templateId": "your-template-id", "templateData": { "client_name": "John Doe", "invoice_number": "INV-001", "total_amount": "$299.99", "line_items": [ { "description": "Web Development", "unit_price": "$200.00" }, { "description": "Design Services", "unit_price": "$99.99" } ] } } """; var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder() .uri(URI.create("https://api.pdfbolt.com/v1/sync")) .header("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(jsonBody)) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() == 200) { String responseBody = response.body(); String documentUrl = responseBody.split("\"documentUrl\":\"")[1].split("\"")[0]; System.out.println("PDF URL: " + documentUrl); } else { System.err.println("HTTP " + response.statusCode()); System.err.println("Error Message: " + response.body()); } } } ``` The **Async** endpoint processes requests asynchronously and sends results via webhook. **➡️ Sources:** **Convert webpage with webhook notification:** ```java public class PDFBoltIntegrationUrl { public static void main(String[] args) throws Exception { String jsonBody = """ { "url": "https://example.com", "format": "A4", "printBackground": true, "webhook": "https://your-app.com/webhook" } """; var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder() .uri(URI.create("https://api.pdfbolt.com/v1/async")) .header("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(jsonBody)) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() == 200) { String responseBody = response.body(); String requestId = responseBody.split("\"requestId\":\"")[1].split("\"")[0]; System.out.println("Request ID: " + requestId); System.out.println("PDF will be sent to webhook when ready"); } else { System.err.println("HTTP " + response.statusCode()); System.err.println("Error Message: " + response.body()); } } } ``` **Convert HTML with webhook notification:** ```java public class PDFBoltIntegrationHtml { public static void main(String[] args) throws Exception { String htmlContent = "Hello!This is a sample PDF."; String base64Html = Base64.getEncoder().encodeToString(htmlContent.getBytes()); String jsonBody = """ { "html": "%s", "margin": { "top": "30px", "left": "30px" }, "webhook": "https://your-app.com/webhook" } """.formatted(base64Html); var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder() .uri(URI.create("https://api.pdfbolt.com/v1/async")) .header("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(jsonBody)) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() == 200) { String responseBody = response.body(); String requestId = responseBody.split("\"requestId\":\"")[1].split("\"")[0]; System.out.println("Request ID: " + requestId); System.out.println("PDF will be sent to webhook when ready"); } else { System.err.println("HTTP " + response.statusCode()); System.err.println("Error Message: " + response.body()); } } } ``` **Use templates with webhook notification:** ```java public class PDFBoltIntegrationTemplate { public static void main(String[] args) throws Exception { String jsonBody = """ { "templateId": "your-template-id", "templateData": { "client_name": "John Doe", "invoice_number": "INV-001", "total_amount": "$299.99", "line_items": [ { "description": "Web Development", "unit_price": "$200.00" }, { "description": "Design Services", "unit_price": "$99.99" } ] }, "webhook": "https://your-app.com/webhook" } """; var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder() .uri(URI.create("https://api.pdfbolt.com/v1/async")) .header("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(jsonBody)) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() == 200) { String responseBody = response.body(); String requestId = responseBody.split("\"requestId\":\"")[1].split("\"")[0]; System.out.println("Request ID: " + requestId); System.out.println("PDF will be sent to webhook when ready"); } else { System.err.println("HTTP " + response.statusCode()); System.err.println("Error Message: " + response.body()); } } } ``` ### 3. What's next? Unlock the full potential of PDFBolt by exploring its powerful features and customization options. Start with the [API Endpoints](/docs/api-endpoints) and delve into the [Conversion Parameters](/docs/parameters) to tailor your integration to your needs. --- ## PHP # Quick Start for PHP While wkhtmltopdf is commonly used in PHP and Puppeteer requires workarounds due to its Node.js nature, PDFBolt's PDF generation API delivers a streamlined solution for generating PDFs from HTML, URLs, and dynamic templates without needing binary installations or complex setups. ### 1. Get Your API Key * After signing up, locate your API Key in the **Admin Dashboard** under the **API Keys** section. * This key is essential for authorizing your requests to the PDFBolt API. Remember to keep it secure. ### 2. Make Your First Request Try these examples to start making requests to the PDFBolt API and create your PDFs. Choose your preferred endpoint and source combination: **➡️ Endpoints:** The **Direct** endpoint provides immediate PDF generation and returns the raw PDF file in the response. **➡️ Sources:** **Convert any webpage into a PDF:** ```php post('https://api.pdfbolt.com/v1/direct', [ 'headers' => $phpHeaders, 'json' => $phpBody ]); file_put_contents('webpage.pdf', $response->getBody()); echo "PDF generated successfully\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ?> ``` **Convert HTML content directly into a PDF:** ```php Hello!This is a sample PDF.'; $base64Html = base64_encode($htmlContent); $jsonHeaders = '{"API-KEY":"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX","Content-Type":"application/json"}'; $phpHeaders = json_decode($jsonHeaders, true); $jsonBody = '{"html":"' . $base64Html . '","margin":{"top":"30px","left":"30px"}}'; $phpBody = json_decode($jsonBody, true); try { $client = new Client(); $response = $client->post('https://api.pdfbolt.com/v1/direct', [ 'headers' => $phpHeaders, 'json' => $phpBody ]); file_put_contents('document.pdf', $response->getBody()); echo "PDF generated successfully\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ?> ``` **Use reusable templates for dynamic PDF generation:** ```php post('https://api.pdfbolt.com/v1/direct', [ 'headers' => $phpHeaders, 'json' => $phpBody ]); file_put_contents('invoice.pdf', $response->getBody()); echo "PDF generated successfully\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ?> ``` :::info New to templates? Create your first template in the app, then use its ID in your API calls. **[→ Learn more about Templates](/docs/pdf-templates)** ::: The **Sync** endpoint returns a JSON response with a download URL for the PDF. **➡️ Sources:** **Convert webpage and get download URL:** ```php post('https://api.pdfbolt.com/v1/sync', [ 'headers' => $phpHeaders, 'json' => $phpBody ]); $result = json_decode($response->getBody(), true); echo "PDF URL: " . $result['documentUrl'] . "\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ?> ``` **Convert HTML and get download URL:** ```php Hello!This is a sample PDF.'; $base64Html = base64_encode($htmlContent); $jsonHeaders = '{"API-KEY":"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX","Content-Type":"application/json"}'; $phpHeaders = json_decode($jsonHeaders, true); $jsonBody = '{"html":"' . $base64Html . '","margin":{"top":"30px","left":"30px"}}'; $phpBody = json_decode($jsonBody, true); try { $client = new Client(); $response = $client->post('https://api.pdfbolt.com/v1/sync', [ 'headers' => $phpHeaders, 'json' => $phpBody ]); $result = json_decode($response->getBody(), true); echo "PDF URL: " . $result['documentUrl'] . "\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ?> ``` **Use templates and get download URL:** ```php post('https://api.pdfbolt.com/v1/sync', [ 'headers' => $phpHeaders, 'json' => $phpBody ]); $result = json_decode($response->getBody(), true); echo "PDF URL: " . $result['documentUrl'] . "\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ?> ``` The **Async** endpoint processes requests asynchronously and sends results via webhook. **➡️ Sources:** **Convert webpage with webhook notification:** ```php post('https://api.pdfbolt.com/v1/async', [ 'headers' => $phpHeaders, 'json' => $phpBody ]); $result = json_decode($response->getBody(), true); echo "Request ID: " . $result['requestId'] . "\n"; echo "PDF will be sent to webhook when ready\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ?> ``` **Convert HTML with webhook notification:** ```php Hello!This is a sample PDF.'; $base64Html = base64_encode($htmlContent); $jsonHeaders = '{"API-KEY":"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX","Content-Type":"application/json"}'; $phpHeaders = json_decode($jsonHeaders, true); $jsonBody = '{"html":"' . $base64Html . '","margin":{"top":"30px","left":"30px"},"webhook":"https://your-app.com/webhook"}'; $phpBody = json_decode($jsonBody, true); try { $client = new Client(); $response = $client->post('https://api.pdfbolt.com/v1/async', [ 'headers' => $phpHeaders, 'json' => $phpBody ]); $result = json_decode($response->getBody(), true); echo "Request ID: " . $result['requestId'] . "\n"; echo "PDF will be sent to webhook when ready\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ?> ``` **Use templates with webhook notification:** ```php post('https://api.pdfbolt.com/v1/async', [ 'headers' => $phpHeaders, 'json' => $phpBody ]); $result = json_decode($response->getBody(), true); echo "Request ID: " . $result['requestId'] . "\n"; echo "PDF will be sent to webhook when ready\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ?> ``` ### 3. What's next? Discover how PDFBolt can enhance your workflows. Begin with the [API Endpoints](/docs/api-endpoints) and explore the [Conversion Parameters](/docs/parameters) to customize your setup and meet your specific needs. --- ## C# # Quick Start for C# C# offers several PDF generation libraries like PuppeteerSharp and DinkToPdf, but they often require learning specialized APIs and have limited HTML/CSS support. PDFBolt's PDF generation API provides a straightforward HTTP-based approach for generating PDFs from HTML, URLs, and dynamic templates using familiar .NET patterns. ### 1. Get Your API Key * After signing up, locate your API Key in the **Admin Dashboard** under the **API Keys** section. * This key is essential for authorizing your requests to the PDFBolt API. Remember to keep it secure. ### 2. Make Your First Request Use the examples below to generate PDFs with the PDFBolt API. **Choose your preferred endpoint and source combination.** **➡️ Endpoints:** The **Direct** endpoint provides immediate PDF generation and returns the raw PDF file in the response. **➡️ Sources:** **Convert any webpage into a PDF:** ```csharp using System; using System.Net.Http; using System.IO; using System.Threading.Tasks; using System.Text.Json; public class PDFBoltIntegrationUrl { public static async Task Main(string[] args) { using var client = new HttpClient(); var requestData = new { url = "https://example.com", format = "A4", printBackground = true }; var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri("https://api.pdfbolt.com/v1/direct"), Content = new StringContent( JsonSerializer.Serialize(requestData), System.Text.Encoding.UTF8, "application/json" ) }; request.Headers.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"); try { using var response = await client.SendAsync(request); if (!response.IsSuccessStatusCode) { var errorContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"HTTP {(int)response.StatusCode}"); Console.WriteLine($"Error Message: {errorContent}"); return; } var pdfBytes = await response.Content.ReadAsByteArrayAsync(); await File.WriteAllBytesAsync("webpage.pdf", pdfBytes); Console.WriteLine("PDF generated successfully"); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } } ``` **Convert HTML content directly into a PDF:** ```csharp using System; using System.Net.Http; using System.IO; using System.Threading.Tasks; using System.Text.Json; public class PDFBoltIntegrationHtml { public static async Task Main(string[] args) { using var client = new HttpClient(); string htmlContent = "Hello!This is a sample PDF."; string base64Html = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(htmlContent)); var requestData = new { html = base64Html, margin = new { top = "30px", left = "30px" } }; var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri("https://api.pdfbolt.com/v1/direct"), Content = new StringContent( JsonSerializer.Serialize(requestData), System.Text.Encoding.UTF8, "application/json" ) }; request.Headers.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"); try { using var response = await client.SendAsync(request); if (!response.IsSuccessStatusCode) { var errorContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"HTTP {(int)response.StatusCode}"); Console.WriteLine($"Error Message: {errorContent}"); return; } var pdfBytes = await response.Content.ReadAsByteArrayAsync(); await File.WriteAllBytesAsync("document.pdf", pdfBytes); Console.WriteLine("PDF generated successfully"); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } } ``` **Use reusable templates for dynamic PDF generation:** ```csharp using System; using System.Net.Http; using System.IO; using System.Threading.Tasks; using System.Text.Json; public class PDFBoltIntegrationTemplate { public static async Task Main(string[] args) { using var client = new HttpClient(); var requestData = new { templateId = "your-template-id", templateData = new { client_name = "John Doe", invoice_number = "INV-001", total_amount = "$299.99", line_items = new object[] { new { description = "Web Development", unit_price = "$200.00" }, new { description = "Design Services", unit_price = "$99.99" } } } }; var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri("https://api.pdfbolt.com/v1/direct"), Content = new StringContent( JsonSerializer.Serialize(requestData), System.Text.Encoding.UTF8, "application/json" ) }; request.Headers.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"); try { using var response = await client.SendAsync(request); if (!response.IsSuccessStatusCode) { var errorContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"HTTP {(int)response.StatusCode}"); Console.WriteLine($"Error Message: {errorContent}"); return; } var pdfBytes = await response.Content.ReadAsByteArrayAsync(); await File.WriteAllBytesAsync("invoice.pdf", pdfBytes); Console.WriteLine("PDF generated successfully"); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } } ``` :::info New to templates? Create your first template in the app, then use its ID in your API calls. **[→ Learn more about Templates](/docs/pdf-templates)** ::: The **Sync** endpoint returns a JSON response with a download URL for the PDF. **➡️ Sources:** **Convert webpage and get download URL:** ```csharp using System; using System.Net.Http; using System.Threading.Tasks; using System.Text.Json; public class PDFBoltIntegrationUrl { public static async Task Main(string[] args) { using var client = new HttpClient(); var requestData = new { url = "https://example.com", format = "A4", printBackground = true }; var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri("https://api.pdfbolt.com/v1/sync"), Content = new StringContent( JsonSerializer.Serialize(requestData), System.Text.Encoding.UTF8, "application/json" ) }; request.Headers.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"); try { using var response = await client.SendAsync(request); if (!response.IsSuccessStatusCode) { var errorContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"HTTP {(int)response.StatusCode}"); Console.WriteLine($"Error Message: {errorContent}"); return; } var responseContent = await response.Content.ReadAsStringAsync(); var result = JsonSerializer.Deserialize(responseContent); Console.WriteLine($"PDF URL: {result.GetProperty("documentUrl").GetString()}"); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } } ``` **Convert HTML and get download URL:** ```csharp using System; using System.Net.Http; using System.Threading.Tasks; using System.Text.Json; public class PDFBoltIntegrationHtml { public static async Task Main(string[] args) { using var client = new HttpClient(); string htmlContent = "Hello!This is a sample PDF."; string base64Html = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(htmlContent)); var requestData = new { html = base64Html, margin = new { top = "30px", left = "30px" } }; var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri("https://api.pdfbolt.com/v1/sync"), Content = new StringContent( JsonSerializer.Serialize(requestData), System.Text.Encoding.UTF8, "application/json" ) }; request.Headers.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"); try { using var response = await client.SendAsync(request); if (!response.IsSuccessStatusCode) { var errorContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"HTTP {(int)response.StatusCode}"); Console.WriteLine($"Error Message: {errorContent}"); return; } var responseContent = await response.Content.ReadAsStringAsync(); var result = JsonSerializer.Deserialize(responseContent); Console.WriteLine($"PDF URL: {result.GetProperty("documentUrl").GetString()}"); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } } ``` **Use templates and get download URL:** ```csharp using System; using System.Net.Http; using System.Threading.Tasks; using System.Text.Json; public class PDFBoltIntegrationTemplate { public static async Task Main(string[] args) { using var client = new HttpClient(); var requestData = new { templateId = "your-template-id", templateData = new { client_name = "John Doe", invoice_number = "INV-001", total_amount = "$299.99", line_items = new object[] { new { description = "Web Development", unit_price = "$200.00" }, new { description = "Design Services", unit_price = "$99.99" } } } }; var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri("https://api.pdfbolt.com/v1/sync"), Content = new StringContent( JsonSerializer.Serialize(requestData), System.Text.Encoding.UTF8, "application/json" ) }; request.Headers.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"); try { using var response = await client.SendAsync(request); if (!response.IsSuccessStatusCode) { var errorContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"HTTP {(int)response.StatusCode}"); Console.WriteLine($"Error Message: {errorContent}"); return; } var responseContent = await response.Content.ReadAsStringAsync(); var result = JsonSerializer.Deserialize(responseContent); Console.WriteLine($"PDF URL: {result.GetProperty("documentUrl").GetString()}"); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } } ``` The **Async** endpoint processes requests asynchronously and sends results via webhook. **➡️ Sources:** **Convert webpage with webhook notification:** ```csharp using System; using System.Net.Http; using System.Threading.Tasks; using System.Text.Json; public class PDFBoltIntegrationUrl { public static async Task Main(string[] args) { using var client = new HttpClient(); var requestData = new { url = "https://example.com", format = "A4", printBackground = true, webhook = "https://your-app.com/webhook" }; var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri("https://api.pdfbolt.com/v1/async"), Content = new StringContent( JsonSerializer.Serialize(requestData), System.Text.Encoding.UTF8, "application/json" ) }; request.Headers.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"); try { using var response = await client.SendAsync(request); if (!response.IsSuccessStatusCode) { var errorContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"HTTP {(int)response.StatusCode}"); Console.WriteLine($"Error Message: {errorContent}"); return; } var responseContent = await response.Content.ReadAsStringAsync(); var result = JsonSerializer.Deserialize(responseContent); Console.WriteLine($"Request ID: {result.GetProperty("requestId").GetString()}"); Console.WriteLine("PDF will be sent to webhook when ready"); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } } ``` **Convert HTML with webhook notification:** ```csharp using System; using System.Net.Http; using System.Threading.Tasks; using System.Text.Json; public class PDFBoltIntegrationHtml { public static async Task Main(string[] args) { using var client = new HttpClient(); string htmlContent = "Hello!This is a sample PDF."; string base64Html = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(htmlContent)); var requestData = new { html = base64Html, margin = new { top = "30px", left = "30px" }, webhook = "https://your-app.com/webhook" }; var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri("https://api.pdfbolt.com/v1/async"), Content = new StringContent( JsonSerializer.Serialize(requestData), System.Text.Encoding.UTF8, "application/json" ) }; request.Headers.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"); try { using var response = await client.SendAsync(request); if (!response.IsSuccessStatusCode) { var errorContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"HTTP {(int)response.StatusCode}"); Console.WriteLine($"Error Message: {errorContent}"); return; } var responseContent = await response.Content.ReadAsStringAsync(); var result = JsonSerializer.Deserialize(responseContent); Console.WriteLine($"Request ID: {result.GetProperty("requestId").GetString()}"); Console.WriteLine("PDF will be sent to webhook when ready"); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } } ``` **Use templates with webhook notification:** ```csharp using System; using System.Net.Http; using System.Threading.Tasks; using System.Text.Json; public class PDFBoltIntegrationTemplate { public static async Task Main(string[] args) { using var client = new HttpClient(); var requestData = new { templateId = "your-template-id", templateData = new { client_name = "John Doe", invoice_number = "INV-001", total_amount = "$299.99", line_items = new object[] { new { description = "Web Development", unit_price = "$200.00" }, new { description = "Design Services", unit_price = "$99.99" } } }, webhook = "https://your-app.com/webhook" }; var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri("https://api.pdfbolt.com/v1/async"), Content = new StringContent( JsonSerializer.Serialize(requestData), System.Text.Encoding.UTF8, "application/json" ) }; request.Headers.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"); try { using var response = await client.SendAsync(request); if (!response.IsSuccessStatusCode) { var errorContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"HTTP {(int)response.StatusCode}"); Console.WriteLine($"Error Message: {errorContent}"); return; } var responseContent = await response.Content.ReadAsStringAsync(); var result = JsonSerializer.Deserialize(responseContent); Console.WriteLine($"Request ID: {result.GetProperty("requestId").GetString()}"); Console.WriteLine("PDF will be sent to webhook when ready"); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } } ``` ### 3. What's next? Discover how PDFBolt can enhance your .NET applications. Begin with the [API Endpoints](/docs/api-endpoints) and explore the [Conversion Parameters](/docs/parameters) to customize your setup and meet your specific needs. --- ## Go # Quick Start for Go Go offers libraries for programmatic PDF creation and for browser automation, but they often require additional dependencies or complex integration. PDFBolt's PDF generation API provides an efficient solution for generating PDFs from HTML, URLs, and dynamic templates that works seamlessly with Go. ### 1. Get Your API Key * After signing up, locate your API Key in the **Admin Dashboard** under the **API Keys** section. * This key is essential for authorizing your requests to the PDFBolt API. Remember to keep it secure. ### 2. Make Your First Request Get started with these examples to send requests to the PDFBolt API and generate PDFs instantly. **Choose your preferred endpoint and source combination.** **➡️ Endpoints:** The **Direct** endpoint provides immediate PDF generation and returns the raw PDF file in the response. **➡️ Sources:** **Convert any webpage into a PDF:** ```go package main "bytes" "fmt" "io" "net/http" "os" ) func main() { jsonBody := `{ "url": "https://example.com", "format": "A4", "printBackground": true }` req, _ := http.NewRequest("POST", "https://api.pdfbolt.com/v1/direct", bytes.NewBufferString(jsonBody)) req.Header.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") req.Header.Add("Content-Type", "application/json") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Printf("HTTP %d\n", resp.StatusCode) body, _ := io.ReadAll(resp.Body) fmt.Printf("Error Message: %s\n", string(body)) return } file, _ := os.Create("webpage.pdf") defer file.Close() io.Copy(file, resp.Body) fmt.Println("PDF generated successfully") } ``` **Convert HTML content directly into a PDF:** ```go package main "bytes" "encoding/base64" "fmt" "io" "net/http" "os" ) func main() { htmlContent := "Hello!This is a sample PDF." base64Html := base64.StdEncoding.EncodeToString([]byte(htmlContent)) jsonBody := fmt.Sprintf(`{ "html": "%s", "margin": { "top": "30px", "left": "30px" } }`, base64Html) req, _ := http.NewRequest("POST", "https://api.pdfbolt.com/v1/direct", bytes.NewBufferString(jsonBody)) req.Header.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") req.Header.Add("Content-Type", "application/json") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Printf("HTTP %d\n", resp.StatusCode) body, _ := io.ReadAll(resp.Body) fmt.Printf("Error Message: %s\n", string(body)) return } file, _ := os.Create("document.pdf") defer file.Close() io.Copy(file, resp.Body) fmt.Println("PDF generated successfully") } ``` **Use reusable templates for dynamic PDF generation:** ```go package main "bytes" "fmt" "io" "net/http" "os" ) func main() { jsonBody := `{ "templateId": "your-template-id", "templateData": { "client_name": "John Doe", "invoice_number": "INV-001", "total_amount": "$299.99", "line_items": [ { "description": "Web Development", "unit_price": "$200.00" }, { "description": "Design Services", "unit_price": "$99.99" } ] } }` req, _ := http.NewRequest("POST", "https://api.pdfbolt.com/v1/direct", bytes.NewBufferString(jsonBody)) req.Header.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") req.Header.Add("Content-Type", "application/json") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Printf("HTTP %d\n", resp.StatusCode) body, _ := io.ReadAll(resp.Body) fmt.Printf("Error Message: %s\n", string(body)) return } file, _ := os.Create("invoice.pdf") defer file.Close() io.Copy(file, resp.Body) fmt.Println("PDF generated successfully") } ``` :::info New to templates? Create your first template in the app, then use its ID in your API calls. **[→ Learn more about Templates](/docs/pdf-templates)** ::: The **Sync** endpoint returns a JSON response with a download URL for the PDF. **➡️ Sources:** **Convert webpage and get download URL:** ```go package main "bytes" "encoding/json" "fmt" "io" "net/http" ) func main() { jsonBody := `{ "url": "https://example.com", "format": "A4", "printBackground": true }` req, _ := http.NewRequest("POST", "https://api.pdfbolt.com/v1/sync", bytes.NewBufferString(jsonBody)) req.Header.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") req.Header.Add("Content-Type", "application/json") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Printf("HTTP %d\n", resp.StatusCode) body, _ := io.ReadAll(resp.Body) fmt.Printf("Error Message: %s\n", string(body)) return } body, _ := io.ReadAll(resp.Body) var result map[string]interface{} json.Unmarshal(body, &result) fmt.Printf("PDF URL: %s\n", result["documentUrl"]) } ``` **Convert HTML and get download URL:** ```go package main "bytes" "encoding/base64" "encoding/json" "fmt" "io" "net/http" ) func main() { htmlContent := "Hello!This is a sample PDF." base64Html := base64.StdEncoding.EncodeToString([]byte(htmlContent)) jsonBody := fmt.Sprintf(`{ "html": "%s", "margin": { "top": "30px", "left": "30px" } }`, base64Html) req, _ := http.NewRequest("POST", "https://api.pdfbolt.com/v1/sync", bytes.NewBufferString(jsonBody)) req.Header.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") req.Header.Add("Content-Type", "application/json") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Printf("HTTP %d\n", resp.StatusCode) body, _ := io.ReadAll(resp.Body) fmt.Printf("Error Message: %s\n", string(body)) return } body, _ := io.ReadAll(resp.Body) var result map[string]interface{} json.Unmarshal(body, &result) fmt.Printf("PDF URL: %s\n", result["documentUrl"]) } ``` **Use templates and get download URL:** ```go package main "bytes" "encoding/json" "fmt" "io" "net/http" ) func main() { jsonBody := `{ "templateId": "your-template-id", "templateData": { "client_name": "John Doe", "invoice_number": "INV-001", "total_amount": "$299.99", "line_items": [ { "description": "Web Development", "unit_price": "$200.00" }, { "description": "Design Services", "unit_price": "$99.99" } ] } }` req, _ := http.NewRequest("POST", "https://api.pdfbolt.com/v1/sync", bytes.NewBufferString(jsonBody)) req.Header.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") req.Header.Add("Content-Type", "application/json") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Printf("HTTP %d\n", resp.StatusCode) body, _ := io.ReadAll(resp.Body) fmt.Printf("Error Message: %s\n", string(body)) return } body, _ := io.ReadAll(resp.Body) var result map[string]interface{} json.Unmarshal(body, &result) fmt.Printf("PDF URL: %s\n", result["documentUrl"]) } ``` The **Async** endpoint processes requests asynchronously and sends results via webhook. **➡️ Sources:** **Convert webpage with webhook notification:** ```go package main "bytes" "encoding/json" "fmt" "io" "net/http" ) func main() { jsonBody := `{ "url": "https://example.com", "format": "A4", "printBackground": true, "webhook": "https://your-app.com/webhook" }` req, _ := http.NewRequest("POST", "https://api.pdfbolt.com/v1/async", bytes.NewBufferString(jsonBody)) req.Header.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") req.Header.Add("Content-Type", "application/json") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Printf("HTTP %d\n", resp.StatusCode) body, _ := io.ReadAll(resp.Body) fmt.Printf("Error Message: %s\n", string(body)) return } body, _ := io.ReadAll(resp.Body) var result map[string]interface{} json.Unmarshal(body, &result) fmt.Printf("Request ID: %s\n", result["requestId"]) fmt.Println("PDF will be sent to webhook when ready") } ``` **Convert HTML with webhook notification:** ```go package main "bytes" "encoding/base64" "encoding/json" "fmt" "io" "net/http" ) func main() { htmlContent := "Hello!This is a sample PDF." base64Html := base64.StdEncoding.EncodeToString([]byte(htmlContent)) jsonBody := fmt.Sprintf(`{ "html": "%s", "margin": { "top": "30px", "left": "30px" }, "webhook": "https://your-app.com/webhook" }`, base64Html) req, _ := http.NewRequest("POST", "https://api.pdfbolt.com/v1/async", bytes.NewBufferString(jsonBody)) req.Header.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") req.Header.Add("Content-Type", "application/json") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Printf("HTTP %d\n", resp.StatusCode) body, _ := io.ReadAll(resp.Body) fmt.Printf("Error Message: %s\n", string(body)) return } body, _ := io.ReadAll(resp.Body) var result map[string]interface{} json.Unmarshal(body, &result) fmt.Printf("Request ID: %s\n", result["requestId"]) fmt.Println("PDF will be sent to webhook when ready") } ``` **Use templates with webhook notification:** ```go package main "bytes" "encoding/json" "fmt" "io" "net/http" ) func main() { jsonBody := `{ "templateId": "your-template-id", "templateData": { "client_name": "John Doe", "invoice_number": "INV-001", "total_amount": "$299.99", "line_items": [ { "description": "Web Development", "unit_price": "$200.00" }, { "description": "Design Services", "unit_price": "$99.99" } ] }, "webhook": "https://your-app.com/webhook" }` req, _ := http.NewRequest("POST", "https://api.pdfbolt.com/v1/async", bytes.NewBufferString(jsonBody)) req.Header.Add("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") req.Header.Add("Content-Type", "application/json") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Printf("HTTP %d\n", resp.StatusCode) body, _ := io.ReadAll(resp.Body) fmt.Printf("Error Message: %s\n", string(body)) return } body, _ := io.ReadAll(resp.Body) var result map[string]interface{} json.Unmarshal(body, &result) fmt.Printf("Request ID: %s\n", result["requestId"]) fmt.Println("PDF will be sent to webhook when ready") } ``` ### 3. What's next? Explore how PDFBolt can streamline your Go applications. Start with the [API Endpoints](/docs/api-endpoints) and dive into the [Conversion Parameters](/docs/parameters) to customize your integration for your specific requirements. --- ## Rust # Quick Start for Rust Rust has libraries for PDF generation and browser automation, but they often involve complex low-level APIs and setup requirements. PDFBolt's PDF generation API offers a streamlined HTTP-based approach for generating PDFs from HTML, URLs, and dynamic templates that integrates seamlessly with Rust's ecosystem. ### 1. Get Your API Key * After signing up, locate your API Key in the **Admin Dashboard** under the **API Keys** section. * This key is essential for authorizing your requests to the PDFBolt API. Remember to keep it secure. ### 2. Make Your First Request Configure your requests using these examples to integrate with the PDFBolt API and generate PDFs. **Choose your preferred endpoint and source combination.** **➡️ Endpoints:** The **Direct** endpoint provides immediate PDF generation and returns the raw PDF file in the response. **➡️ Sources:** **Convert any webpage into a PDF:** ```rust use reqwest::{Client, Method, header::HeaderMap}; use serde_json::json; use std::fs; pub async fn make_request() -> Result<(), Box> { let client = Client::new(); let url = "https://api.pdfbolt.com/v1/direct"; let mut headers = HeaderMap::new(); headers.insert("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX".parse().unwrap()); headers.insert("Content-Type", "application/json".parse().unwrap()); let response = client.request(Method::POST, url) .headers(headers) .json(&json!({ "url": "https://example.com", "format": "A4", "printBackground": true })) .send() .await?; if !response.status().is_success() { println!("HTTP {}", response.status().as_u16()); let error_text = response.text().await?; println!("Error Message: {}", error_text); return Ok(()); } let pdf_bytes = response.bytes().await?; fs::write("webpage.pdf", pdf_bytes)?; println!("PDF generated successfully"); Ok(()) } #[tokio::main] async fn main() -> Result<(), Box> { make_request().await?; Ok(()) } ``` **Convert HTML content directly into a PDF** (HTML must be base64 encoded): ```rust use reqwest::{Client, Method, header::HeaderMap}; use serde_json::json; use base64::{Engine as _, engine::general_purpose}; use std::fs; pub async fn make_request() -> Result<(), Box> { let client = Client::new(); let url = "https://api.pdfbolt.com/v1/direct"; let html_content = "Hello!This is a sample PDF."; let base64_html = general_purpose::STANDARD.encode(html_content.as_bytes()); let mut headers = HeaderMap::new(); headers.insert("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX".parse().unwrap()); headers.insert("Content-Type", "application/json".parse().unwrap()); let response = client.request(Method::POST, url) .headers(headers) .json(&json!({ "html": base64_html, "margin": { "top": "30px", "left": "30px" } })) .send() .await?; if !response.status().is_success() { println!("HTTP {}", response.status().as_u16()); let error_text = response.text().await?; println!("Error Message: {}", error_text); return Ok(()); } let pdf_bytes = response.bytes().await?; fs::write("document.pdf", pdf_bytes)?; println!("PDF generated successfully"); Ok(()) } #[tokio::main] async fn main() -> Result<(), Box> { make_request().await?; Ok(()) } ``` **Use reusable templates for dynamic PDF generation:** ```rust use reqwest::{Client, Method, header::HeaderMap}; use serde_json::json; use std::fs; pub async fn make_request() -> Result<(), Box> { let client = Client::new(); let url = "https://api.pdfbolt.com/v1/direct"; let mut headers = HeaderMap::new(); headers.insert("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX".parse().unwrap()); headers.insert("Content-Type", "application/json".parse().unwrap()); let response = client.request(Method::POST, url) .headers(headers) .json(&json!({ "templateId": "your-template-id", "templateData": { "client_name": "John Doe", "invoice_number": "INV-001", "total_amount": "$299.99", "line_items": [ { "description": "Web Development", "unit_price": "$200.00" }, { "description": "Design Services", "unit_price": "$99.99" } ] } })) .send() .await?; if !response.status().is_success() { println!("HTTP {}", response.status().as_u16()); let error_text = response.text().await?; println!("Error Message: {}", error_text); return Ok(()); } let pdf_bytes = response.bytes().await?; fs::write("invoice.pdf", pdf_bytes)?; println!("PDF generated successfully"); Ok(()) } #[tokio::main] async fn main() -> Result<(), Box> { make_request().await?; Ok(()) } ``` :::info New to templates? Create your first template in the app, then use its ID in your API calls. **[→ Learn more about Templates](/docs/pdf-templates)** ::: The **Sync** endpoint returns a JSON response with a download URL for the PDF. **➡️ Sources:** **Convert webpage and get download URL:** ```rust use reqwest::{Client, Method, header::HeaderMap}; use serde_json::{json, Value}; use std::error::Error; pub async fn make_request() -> Result<(), Box> { let client = Client::new(); let url = "https://api.pdfbolt.com/v1/sync"; let mut headers = HeaderMap::new(); headers.insert("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX".parse().unwrap()); headers.insert("Content-Type", "application/json".parse().unwrap()); let response = client.request(Method::POST, url) .headers(headers) .json(&json!({ "url": "https://example.com", "format": "A4", "printBackground": true })) .send() .await?; if !response.status().is_success() { println!("HTTP {}", response.status().as_u16()); let error_text = response.text().await?; println!("Error Message: {}", error_text); return Ok(()); } let result: Value = response.json().await?; println!("PDF URL: {}", result["documentUrl"].as_str().unwrap_or("")); Ok(()) } #[tokio::main] async fn main() -> Result<(), Box> { make_request().await?; Ok(()) } ``` **Convert HTML and get download URL:** ```rust use reqwest::{Client, Method, header::HeaderMap}; use serde_json::{json, Value}; use base64::{Engine as _, engine::general_purpose}; use std::error::Error; pub async fn make_request() -> Result<(), Box> { let client = Client::new(); let url = "https://api.pdfbolt.com/v1/sync"; let html_content = "Hello!This is a sample PDF."; let base64_html = general_purpose::STANDARD.encode(html_content.as_bytes()); let mut headers = HeaderMap::new(); headers.insert("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX".parse().unwrap()); headers.insert("Content-Type", "application/json".parse().unwrap()); let response = client.request(Method::POST, url) .headers(headers) .json(&json!({ "html": base64_html, "margin": { "top": "30px", "left": "30px" } })) .send() .await?; if !response.status().is_success() { println!("HTTP {}", response.status().as_u16()); let error_text = response.text().await?; println!("Error Message: {}", error_text); return Ok(()); } let result: Value = response.json().await?; println!("PDF URL: {}", result["documentUrl"].as_str().unwrap_or("")); Ok(()) } #[tokio::main] async fn main() -> Result<(), Box> { make_request().await?; Ok(()) } ``` **Use templates and get download URL:** ```rust use reqwest::{Client, Method, header::HeaderMap}; use serde_json::{json, Value}; use std::error::Error; pub async fn make_request() -> Result<(), Box> { let client = Client::new(); let url = "https://api.pdfbolt.com/v1/sync"; let mut headers = HeaderMap::new(); headers.insert("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX".parse().unwrap()); headers.insert("Content-Type", "application/json".parse().unwrap()); let response = client.request(Method::POST, url) .headers(headers) .json(&json!({ "templateId": "your-template-id", "templateData": { "client_name": "John Doe", "invoice_number": "INV-001", "total_amount": "$299.99", "line_items": [ { "description": "Web Development", "unit_price": "$200.00" }, { "description": "Design Services", "unit_price": "$99.99" } ] } })) .send() .await?; if !response.status().is_success() { println!("HTTP {}", response.status().as_u16()); let error_text = response.text().await?; println!("Error Message: {}", error_text); return Ok(()); } let result: Value = response.json().await?; println!("PDF URL: {}", result["documentUrl"].as_str().unwrap_or("")); Ok(()) } #[tokio::main] async fn main() -> Result<(), Box> { make_request().await?; Ok(()) } ``` The **Async** endpoint processes requests asynchronously and sends results via webhook. **➡️ Sources:** **Convert webpage with webhook notification:** ```rust use reqwest::{Client, Method, header::HeaderMap}; use serde_json::{json, Value}; use std::error::Error; pub async fn make_request() -> Result<(), Box> { let client = Client::new(); let url = "https://api.pdfbolt.com/v1/async"; let mut headers = HeaderMap::new(); headers.insert("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX".parse().unwrap()); headers.insert("Content-Type", "application/json".parse().unwrap()); let response = client.request(Method::POST, url) .headers(headers) .json(&json!({ "url": "https://example.com", "format": "A4", "printBackground": true, "webhook": "https://your-app.com/webhook" })) .send() .await?; if !response.status().is_success() { println!("HTTP {}", response.status().as_u16()); let error_text = response.text().await?; println!("Error Message: {}", error_text); return Ok(()); } let result: Value = response.json().await?; println!("Request ID: {}", result["requestId"].as_str().unwrap_or("")); println!("PDF will be sent to webhook when ready"); Ok(()) } #[tokio::main] async fn main() -> Result<(), Box> { make_request().await?; Ok(()) } ``` **Convert HTML with webhook notification:** ```rust use reqwest::{Client, Method, header::HeaderMap}; use serde_json::{json, Value}; use base64::{Engine as _, engine::general_purpose}; use std::error::Error; pub async fn make_request() -> Result<(), Box> { let client = Client::new(); let url = "https://api.pdfbolt.com/v1/async"; let html_content = "Hello!This is a sample PDF."; let base64_html = general_purpose::STANDARD.encode(html_content.as_bytes()); let mut headers = HeaderMap::new(); headers.insert("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX".parse().unwrap()); headers.insert("Content-Type", "application/json".parse().unwrap()); let response = client.request(Method::POST, url) .headers(headers) .json(&json!({ "html": base64_html, "margin": { "top": "30px", "left": "30px" }, "webhook": "https://your-app.com/webhook" })) .send() .await?; if !response.status().is_success() { println!("HTTP {}", response.status().as_u16()); let error_text = response.text().await?; println!("Error Message: {}", error_text); return Ok(()); } let result: Value = response.json().await?; println!("Request ID: {}", result["requestId"].as_str().unwrap_or("")); println!("PDF will be sent to webhook when ready"); Ok(()) } #[tokio::main] async fn main() -> Result<(), Box> { make_request().await?; Ok(()) } ``` **Use templates with webhook notification:** ```rust use reqwest::{Client, Method, header::HeaderMap}; use serde_json::{json, Value}; use std::error::Error; pub async fn make_request() -> Result<(), Box> { let client = Client::new(); let url = "https://api.pdfbolt.com/v1/async"; let mut headers = HeaderMap::new(); headers.insert("API-KEY", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX".parse().unwrap()); headers.insert("Content-Type", "application/json".parse().unwrap()); let response = client.request(Method::POST, url) .headers(headers) .json(&json!({ "templateId": "your-template-id", "templateData": { "client_name": "John Doe", "invoice_number": "INV-001", "total_amount": "$299.99", "line_items": [ { "description": "Web Development", "unit_price": "$200.00" }, { "description": "Design Services", "unit_price": "$99.99" } ] }, "webhook": "https://your-app.com/webhook" })) .send() .await?; if !response.status().is_success() { println!("HTTP {}", response.status().as_u16()); let error_text = response.text().await?; println!("Error Message: {}", error_text); return Ok(()); } let result: Value = response.json().await?; println!("Request ID: {}", result["requestId"].as_str().unwrap_or("")); println!("PDF will be sent to webhook when ready"); Ok(()) } #[tokio::main] async fn main() -> Result<(), Box> { make_request().await?; Ok(()) } ``` ### 3. What's next? Discover how PDFBolt can enhance your Rust applications. Start with the [API Endpoints](/docs/api-endpoints) and explore the [Conversion Parameters](/docs/parameters) to tailor your integration for your specific needs. --- ## Postman # Quick Start with Postman Tools like Postman simplify testing and interaction with the PDFBolt API, making it easy to explore its features without writing code. You can start right away by watching the **quick start video**, **using our Postman collection**, or following the **step-by-step guide** below. ## Quick Start Video ## Quick API Testing Getting started with the **PDFBolt API** has never been easier! - To simplify testing, we've prepared a **Postman collection** with all available API endpoints. - With just a single click, you can fork the collection and start experimenting directly in Postman. - Simply set your **API key** as an **environment variable**. You can find your API key in the Admin Dashboard under the API Keys section. [](https://app.getpostman.com/run-collection/40399365-9472b2d4-c8da-4338-8774-962cc6bb9347?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D40399365-9472b2d4-c8da-4338-8774-962cc6bb9347%26entityType%3Dcollection%26workspaceId%3D3a6b1d25-d352-4c2e-8a9b-0b4fcb6d6cae#?env%5BPDFBolt%5D=W3sia2V5IjoiYmFzZV91cmwiLCJ2YWx1ZSI6Imh0dHBzOi8vYXBpLnBkZmJvbHQuY29tIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQiLCJzZXNzaW9uVmFsdWUiOiJodHRwczovL2FwaS5wZGZib2x0LmNvbSIsImNvbXBsZXRlU2Vzc2lvblZhbHVlIjoiaHR0cHM6Ly9hcGkucGRmYm9sdC5jb20iLCJzZXNzaW9uSW5kZXgiOjB9LHsia2V5IjoiQVBJX0tFWSIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6InNlY3JldCIsInNlc3Npb25WYWx1ZSI6IiIsImNvbXBsZXRlU2Vzc2lvblZhbHVlIjoiIiwic2Vzc2lvbkluZGV4IjoxfSx7ImtleSI6IndlYmhvb2tfdXJsIiwidmFsdWUiOiIiLCJlbmFibGVkIjp0cnVlLCJ0eXBlIjoiZGVmYXVsdCIsInNlc3Npb25WYWx1ZSI6IiIsImNvbXBsZXRlU2Vzc2lvblZhbHVlIjoiIiwic2Vzc2lvbkluZGV4IjoyfSx7ImtleSI6ImN1c3RvbVMzX3VybCIsInZhbHVlIjoiIiwiZW5hYmxlZCI6dHJ1ZSwidHlwZSI6ImRlZmF1bHQiLCJzZXNzaW9uVmFsdWUiOiIiLCJjb21wbGV0ZVNlc3Npb25WYWx1ZSI6IiIsInNlc3Npb25JbmRleCI6M31d) ## Quick Start from Scratch ### 1. Get Your API Key * Your **API Key** can be found in the **Admin Dashboard** under the **API Keys** section after signing up. * The API Key is required to authorize your requests to the PDFBolt API. ### 2. Set Up Postman for PDFBolt #### 1. Create a New Request: - Open Postman and create a new Request. - Set the HTTP Method to `POST`. - Enter one of the following PDFBolt API endpoint URLs based on your use case: ```js https://api.pdfbolt.com/v1/direct ``` ```js https://api.pdfbolt.com/v1/sync ``` ```js https://api.pdfbolt.com/v1/async ``` #### 2. Set Up Authorization: - Go to the **Authorization** tab. - Choose **API Key** as the Auth Type. - Enter the following values: - Key: `API-KEY` - Value: Your unique API key. - Select *Header* to include the key in the request headers.
**📌 Setting Up Your API Key as an Environment Variable in Postman** Instead of manually entering your API key every time, store it as an **environment variable** in Postman for easier reuse in future requests. #### **How to set it up in Postman:** 1. Open Postman and go to **Environments**. 2. Click ➕ to create a new environment. 3. Create a new variable called `API-KEY` and set its type to *Secret*. 4. Paste your **API key** into Initial value and Current value, then save the environment. 5. In your request headers, instead of manually entering the key, use `{{API-KEY}}`. This way, Postman will automatically insert your API key, improving security and efficiency.
#### 3. Define the Request Body: - Navigate to the **Body** tab. - Select raw and set the content type to `JSON`. - Choose your preferred method to generate PDFs: **➡️ Convert any webpage into a PDF:** ```json { "url": "https://example.com", "printBackground": true, "margin": { "top": "30px", "right": "20px", "left": "20px", "bottom": "30px" } } ``` **➡️ Convert HTML content directly into a PDF** (HTML must be base64 encoded): ```json { "html": "PGh0bWw+PGJvZHk+PGgxPkhlbGxvITwvaDE+PHA+VGhpcyBpcyBhIHNhbXBsZSBQREYuPC9wPjwvYm9keT48L2h0bWw+", "format": "A4", "landscape": false } ``` :::note Base64 Encoded HTML The above base64 string represents: ```html Hello!This is a sample PDF. ``` ::: **➡️ Use reusable templates for dynamic PDF generation:** ```json { "templateId": "your-template-id", "templateData": { "customerName": "John Doe", "invoiceNumber": "INV-001", "total": "$299.99", "items": [ { "name": "Web Development", "price": "$200.00" }, { "name": "Design Services", "price": "$99.99" } ] } } ``` :::info Template workflow Create templates in the app, then test them instantly in Postman. **[→ Learn more about Templates](/docs/pdf-templates)** ::: #### 4. Send the Request - Click *Send* to execute the request. - Upon success, the response will contain a PDF. :::note If you want to use the `/async` endpoint, ensure you include the `webhook` parameter in your request. ::: ### 3. What's next? Test different [API Endpoints](/docs/api-endpoints) and experiment with [Conversion Parameters](/docs/parameters) directly in Postman. Modify the request body to customize your document generation process. :::info Why Use Postman or a Similar Tool? Here’s why they’re a great choice: - **Quick Testing:** Easily test your requests without hassle. - **Code-Free Interaction:** Generate PDFs and interact with the API without writing code. - **Effortless Configuration:** Easily set up endpoints, parameters, and authorization. - **Debugging Support:** Inspect requests and responses for effective troubleshooting and optimization. ::: --- ## Automation Platform Integrations Integrate PDFBolt with leading automation platforms to generate invoices, reports, certificates, and other documents using visual workflows. ## Integration Guides | **Platform** | **Description** | **Best For** | |--------------|---------------------------------------------------------------------------------------|----------------------------------------------------------| | **n8n** | Open-source workflow automation with extensive integrations and visual builder. | Complex workflows, self-hosted solutions, developers who want flexibility. | | **Make** | Visual automation platform for connecting apps and building multi-step scenarios. | Users needing flexible automation from simple to complex workflows. | | **Zapier** | User-friendly automation platform with a large app library and quick setup. | Non-technical users, small teams, simple mainstream app integrations. | | **Airtable** | Spreadsheet-database hybrid with built-in automation capabilities. | Database-driven documents, team collaboration. | | **Bubble** | Visual programming platform for building web applications. | Custom web apps, user-triggered documents. | | **Integrately** | One-click automation platform with pre-built workflows. | Fast setup, simple automations. | ## Why Use Automation Platforms? These integrations enable you to: - **Visual Workflow Building**: Design workflows using drag-and-drop interfaces - **Connect Multiple Services**: Trigger PDF generation from forms, databases, webhooks, schedules, and various apps. - **Minimal Setup**: Automate document creation with visual workflows and simple code snippets. - **Faster Deployment**: Launch automations in hours instead of weeks. - **Simplify maintenance**: Visual workflows are easier to update and troubleshoot ## Common Use Cases - **E-commerce**: Automatically generate invoices when orders are placed. - **Education**: Create certificates when students complete courses. - **HR & Onboarding**: Generate employee handbooks and welcome packets. - **Reporting**: Schedule automated report generation and distribution. - **Event Management**: Create tickets and badges for registered attendees. - **Sales**: Generate proposals and quotes from CRM data. --- ## n8n Integration Guide Learn how to integrate PDFBolt with n8n to automate PDF generation in your workflows. Generate professional documents from templates, HTML content, or web pages using n8n's visual workflow builder. ## Prerequisites Before starting, ensure you have: 1. **PDFBolt API Key** - [Sign up](https://app.pdfbolt.com/register) or [log in](https://app.pdfbolt.com/login) to your PDFBolt account. - Navigate to API Keys section. - Copy your API key for authentication. 2. **n8n Access** - n8n cloud account or self-hosted instance. ## Basic Setup ### Configure HTTP Request Node Use n8n's HTTP Request node to call the PDFBolt API: 1. Add an **HTTP Request** node to your workflow. 2. Configure authentication: - **Method:** `POST` - **URL:** `https://api.pdfbolt.com/v1/direct` - **Authentication:** `Generic Credential Type` - **Generic Auth Type:** `Header Auth` 3. Create authentication credential: - **Name:** `API-KEY` - **Value:** `YOUR-API-KEY` 4. Configure request body: - **Send Body:** `Enabled` - **Body Content Type:** `JSON` - **Specify Body:** `Using JSON` ### Choose Your Endpoint Select the PDFBolt endpoint based on your workflow needs: | Endpoint | Best For | Returns | |----------|----------|---------| | `/v1/direct` | Immediate PDF delivery | Raw PDF data in response | | `/v1/sync` | URL-based access | JSON with download URL | | `/v1/async` | High-volume processing | Webhook callback with results | :::info Endpoint Details See [API Endpoints](/docs/api-endpoints) for detailed specifications. ::: ### Choose Your Source Select the content source that best fits your use case: | Source | Best For | When to Use | |--------|----------|-------------| | **Templates** | Recurring documents with consistent layouts | Invoices, contracts, certificates – any document you generate repeatedly with different data | | **HTML** | Custom documents | When you need full control over a unique layout | | **URL** | Existing web pages | Archiving documentation, reports, capturing dashboards, saving public web content | :::info Source Parameters Learn more about source parameters in the [API Documentation](/docs/parameters#source-parameters). ::: ## Source 1: Templates Templates provide the most efficient way to generate consistent, branded PDFs by separating design from data. ### How It Works 1. **Create your template** in PDFBolt's Template section: - Build custom layouts with HTML, CSS, and Handlebars variables. - Or start with a ready-made template from the gallery. 2. **Publish the template** to make it available via API and get your unique `templateId`. 3. **Send API request** with only `templateId` and `templateData`. 4. **Receive your PDF** – PDFBolt merges the data with your template and returns the generated PDF. :::tip Template Setup Learn how to create and manage templates in the [Templates Documentation](/docs/admin-dashboard/templates). ::: ### Example: Invoice Generation **Real-world scenario:** Customer places an order in your e-commerce system. Automatically generate a professional invoice PDF and send it to the customer. **n8n HTTP Request Configuration:** If your workflow is triggered by a webhook, paste this expression into the **JSON body** field of the HTTP Request node: ```json {{ $json.body.toJsonString() }} ``` :::info How It Works - `$json.body` – Accesses the data received from the webhook. - `toJsonString()` – Converts the object into JSON string format. - Result: PDFBolt receives the data in the correct structure for template processing. ::: Expected example webhook payload: ```json { "templateId": "your-template-id", "templateData": { "invoice_number": "INV-2025-001", "client_name": "John Doe", "line_items": [ { "quantity": "1", "tax_rate": "10", "unit_price": "1200.00", "description": "Website Design", "total_amount": "1200.00" }, { "quantity": "2", "tax_rate": "10", "unit_price": "250.00", "description": "Logo Design Package", "total_amount": "500.00" } ], "total_amount": "1700.00" } } ``` When your data comes from previous workflow nodes (like databases, forms, or APIs), map the fields manually using n8n expressions: ```json { "templateId": "your-template-id", "templateData": { "invoice_number": "{{ $json.body.invoice_number }}", "client_name": "{{ $json.body.client_name }}", "line_items": {{ $json.body.line_items.toJsonString() }}, "total_amount": "{{ $json.body.total_amount }}" } } ``` :::tip Expression Syntax - Use `{{ $json.body.fieldName }}` to reference simple fields from the previous node. - Use `.toJsonString()` for arrays and objects to maintain proper JSON structure. - All field names must match your template's Handlebars variables. ::: ### Template Workflow Example **Complete workflow:** 1. **Webhook** – Receives order data from your system. 2. **HTTP Request (PDFBolt)** – Generates invoice PDF. 3. **Send Message** – Sends PDF to customer. :::tip Data Mapping Field names in `templateData` must exactly match Handlebars variables in your template. Mismatched names result in empty values. ::: ## Source 2: HTML Convert HTML directly into PDFs – perfect for custom documents, event programs, announcements, or guides. ### How It Works 1. Prepare HTML content in your workflow. 2. Base64 encode the HTML. 3. Send **encoded HTML to PDFBolt**. 4. Receive generated PDF. ### Example: Event Program **Real-world scenario:** Organizing a webinar or conference. Generate a PDF program with schedule, speakers, and session details that attendees can download. 1. Add a **Code** node after your event registration trigger:
**View Complete Code Example** ```javascript // Static event program HTML – same for all attendees const htmlContent = ` Tech Summit 2025 Building the Future Together November 15, 2025 | Virtual Event Event Details: Date: November 15, 2025 Time: 9:00 AM – 5:00 PM EST Platform: Zoom (link will be sent via email) Event Schedule 9:00 AM – 9:30 AM Opening Keynote: The Future of AI Speaker: Dr. Sarah Johnson, AI Research Director Exploring emerging trends in artificial intelligence and their impact on business. 9:45 AM – 10:30 AM Workshop: Building Scalable APIs Speaker: Mike Chen, Senior Engineer Hands-on session covering best practices for API design and implementation. ☕ Coffee Break (10:30 AM – 11:00 AM) 11:00 AM – 11:45 AM Panel Discussion: Cloud Architecture Panelists: Various industry experts Interactive discussion about modern cloud infrastructure and DevOps practices. 12:00 PM – 1:00 PM Networking Session Connect with other attendees and speakers in breakout rooms. 🍽️ Lunch Break (1:00 PM – 2:00 PM) 2:00 PM – 2:45 PM Case Study: Digital Transformation Success Speaker: Lisa Martinez, CTO Real-world example of successful digital transformation journey. 3:00 PM – 4:00 PM Q&A with Speakers Ask questions and get insights from all our speakers. Questions? Contact us at events@example.com `; // Encode to base64 const base64Html = Buffer.from(htmlContent).toString('base64'); return { json: { html: base64Html } }; ```
:::warning HTML Encoding HTML must be Base64 encoded before sending to PDFBolt. Use `Buffer.from(html).toString('base64')` in Code nodes. ::: 2. In the **HTTP Request** node body, configure PDF settings: ```json { "html": "{{ $json.html }}", "format": "A4", "printBackground": true, "margin": { "top": "30px", "bottom": "30px", "right": "30px", "left": "30px" } } ``` ### HTML Workflow Example **Complete workflow:** 1. **Typeform Trigger** – New registration form submitted. 2. **Code Node** – Generate event program (Base64-encoded HTML content). 3. **HTTP Request (PDFBolt)** – Generate a PDF. 4. **Gmail** – Send confirmation email with PDF program to the attendee. :::tip PDF Customization By separating PDF settings into the HTTP Request body, you can easily adjust format, margins, and other options without modifying the HTML code. See [Conversion Parameters](/docs/parameters) for all available options. ::: ## Source 3: URL Generate PDFs from any publicly accessible webpage, perfect for archiving web content, capturing dashboards, or generating reports. ### How It Works 1. Provide the target URL. 2. PDFBolt loads and renders the page. 3. Returns PDF of the rendered page. ### Example: Daily Dashboard Report **Real-world scenario:** Your team uses an analytics dashboard. Every morning, automatically capture the dashboard as PDF and share it on Slack so the team stays informed. In the **HTTP Request** node body, configure the URL and PDF settings: ```json { "url": "https://analytics.yourcompany.com/dashboard", "format": "A4", "landscape": true, "printBackground": true, "waitUntil": "networkidle", "margin": { "top": "20px", "right": "20px", "bottom": "20px", "left": "20px" } } ``` :::tip Wait for Page Load Use `waitUntil: "networkidle"` to ensure all dashboard charts and data finish loading before capturing the PDF. For pages with specific loading indicators, use `waitForSelector` instead. ::: ### URL Workflow Example **Complete workflow:** 1. **Schedule Trigger** – Every weekday at 8:00 AM. 2. **HTTP Request (PDFBolt)** – Capture dashboard as PDF. 3. **Slack** – Shares report with team. 4. **Google Drive** – Archives PDF. ## Additional Resources ### PDFBolt Documentation - [Templates Management Guide](/docs/admin-dashboard/templates) – Detailed creation and management instructions. - [Templates Docs](/docs/pdf-templates) – Templates overview, benefits, and use cases. - [API Endpoints](/docs/api-endpoints) – All available endpoints. - [Conversion Parameters](/docs/parameters) – Complete parameter reference. - [Error Handling](/docs/error-handling) – Error codes and solutions. - [Automate PDF Generation in n8n: Complete Guide](/blog/n8n-pdf-automation-guide) – Practical implementation example. ### n8n Resources - n8n Documentation - n8n Community Forum --- ## Make Integration Guide Learn how to integrate PDFBolt with Make to automate PDF generation in your scenarios. Generate professional documents from templates, HTML content, or web pages using Make's visual automation platform. ## Prerequisites Before starting, ensure you have: 1. **PDFBolt API Key** - [Sign up](https://app.pdfbolt.com/register) or [log in](https://app.pdfbolt.com/login) to your PDFBolt account. - Navigate to API Keys section. - Copy your API key for authentication. 2. **Make Account** - Make account (free or paid plan). ## Basic Setup ### Configure HTTP Module Use Make's HTTP module to call the PDFBolt API: 1. Add an **HTTP** module to your scenario (select "Make a request"). 2. Configure authentication: - **URL:** `https://api.pdfbolt.com/v1/direct` - **Method:** `POST` - **Headers:** – Name: `API-KEY` – Value: `YOUR-API-KEY` 3. Set up request body: - **Body type:** `Raw` - **Content type:** `JSON (application/json)` ### Choose Your Endpoint Select the PDFBolt endpoint based on your scenario needs: | Endpoint | Best For | Returns | |----------|----------|---------| | `/v1/direct` | Immediate PDF delivery | Raw PDF data in response | | `/v1/sync` | URL-based access | JSON with download URL | | `/v1/async` | High-volume processing | Webhook callback with results | :::info Endpoint Details See [API Endpoints](/docs/api-endpoints) for detailed specifications. ::: ### Choose Your Source Select the content source that best fits your use case: | Source | Best For | When to Use | |--------|----------|-------------| | **Templates** | Recurring documents with consistent layouts | Invoices, contracts, certificates – any document you generate repeatedly with different data | | **HTML** | Custom documents | When you need full control over a unique layout | | **URL** | Existing web pages | Archiving documentation, reports, capturing dashboards, saving public web content | :::info Source Parameters Learn more about source parameters in the [API Documentation](/docs/parameters#source-parameters). ::: ## Source 1: Templates Templates provide the most efficient way to generate consistent, branded PDFs by separating design from data. ### How It Works 1. **Create your template** in PDFBolt's Template section: - Build custom layouts with HTML, CSS, and Handlebars variables. - Or start with a ready-made template from the gallery. 2. **Publish the template** to make it available via API and get your unique `templateId`. 3. **Send API request** with only `templateId` and `templateData`. 4. **Receive your PDF** – PDFBolt returns the generated PDF. :::tip Template Setup Learn how to create your template in the [Templates Documentation](/docs/admin-dashboard/templates). ::: ### Example: Invoice Generation **Real-world scenario:** Customer places an order in your e-commerce system. Automatically generate a professional invoice PDF and send it to the customer. 1. Configure the **HTTP – PDFBolt** module: When receiving order data from a webhook trigger, configure the Request content field: ```json { "templateId": "your-template-id", "templateData": { "invoice_number": "{{1.invoice_number}}", "issue_date": "{{1.order_date}}", "client_name": "{{1.customer_name}}", "client_email": "{{1.customer_email}}", "line_items": [{{1.line_items}}], "total_amount": "{{1.total}}" } } ``` :::info How It Works - `{{1.fieldName}}` references data from module 1 (your webhook trigger). - Module numbers auto-increment based on scenario position. - All field names must match your template's Handlebars variables exactly. ::: Expected webhook payload example: ```json { "invoice_number": "INV-2025-001", "order_date": "2025-01-15", "customer_name": "John Doe", "customer_email": "john@example.com", "line_items": [ { "description": "Website Design", "quantity": 1, "unit_price": "1200.00", "total_amount": "1200.00" }, { "description": "Logo Design Package", "quantity": 2, "unit_price": "250.00", "total_amount": "500.00" } ], "total": "1700.00" } ``` :::tip Other E-commerce Integrations This same approach works with **Shopify**, **Stripe**, **WooCommerce**, **Square**, or any other e-commerce platform in Make. Simply use their respective trigger modules and map the order data to your template fields. The syntax remains the same: `{{moduleNumber.fieldName}}`. ::: ### Template Scenario Example **Complete scenario:** 1. **Webhook: Custom webhook** – Receives order data from your system. 2. **HTTP: PDFBolt** – Generates invoice PDF. 3. **Email** – Sends PDF to customer. ## Source 2: HTML Convert HTML directly into PDFs within your scenarios – perfect for event materials, policy documents, or one-time custom layouts. ### How It Works 1. Add your HTML content in the scenario. 2. Encode HTML to Base64 format. 3. Pass **encoded HTML to PDFBolt**. 4. Receive your PDF. ### Example: Event Program **Real-world scenario:** Running a conference or webinar. Create a PDF program containing the full agenda and session information that attendees can download. 1. Add a **Tools – Set variable** module after your trigger: Configure the module: - **Variable name:** `html_content` - **Variable value:** Paste your HTML
**View Complete HTML Example** ```html Tech Summit 2025 Building the Future Together November 15, 2025 | Virtual Event Event Details: Date: November 15, 2025 Time: 9:00 AM – 5:00 PM EST Platform: Zoom (link will be sent via email) Event Schedule 9:00 AM – 9:30 AM Opening Keynote: The Future of AI Speaker: Dr. Sarah Johnson, AI Research Director Exploring emerging trends in artificial intelligence and their impact on business. 9:45 AM – 10:30 AM Workshop: Building Scalable APIs Speaker: Mike Chen, Senior Engineer Hands-on session covering best practices for API design and implementation. ☕ Coffee Break (10:30 AM – 11:00 AM) 11:00 AM – 11:45 AM Panel Discussion: Cloud Architecture Panelists: Various industry experts Interactive discussion about modern cloud infrastructure and DevOps practices. 12:00 PM – 1:00 PM Networking Session Connect with other attendees and speakers in breakout rooms. 🍽️ Lunch Break (1:00 PM – 2:00 PM) 2:00 PM – 2:45 PM Case Study: Digital Transformation Success Speaker: Lisa Martinez, CTO Real-world example of successful digital transformation journey. 3:00 PM – 4:00 PM Q&A with Speakers Ask questions and get insights from all our speakers. Questions? Contact us at events@example.com ```
2. Configure the **HTTP – PDFBolt** module with Base64 encoding: Request content: ```json { "html": "{{base64(2.html_content)}}", "format": "A4", "printBackground": true, "margin": { "top": "30px", "bottom": "30px", "right": "30px", "left": "30px" } } ``` :::warning Base64 Encoding Use Make's built-in `base64()` function to encode HTML. Wrap your HTML variable with `{{base64(your_content)}}` in the request content. ::: ### HTML Scenario Example **Complete scenario:** 1. **Typeform: Watch Responses** – Registration form completed. 2. **Tools: Set Variable** – Store event program HTML layout. 3. **HTTP: PDFBolt** – Convert to PDF (Base64 encoding applied). 4. **Gmail: Send Email** – Deliver program to registered attendee. :::tip PDF Configuration Adjust PDF appearance by modifying parameters in the HTTP module Request content. Explore all options in [Conversion Parameters](/docs/parameters). ::: ## Source 3: URL Transform any public webpage into a PDF document – ideal for preserving online content, dashboards, or generating reports. ### How It Works 1. Specify the webpage URL. 2. PDFBolt fetches and renders the content. 3. Delivers a PDF of the page. ### Example: Website Change Documentation **Real-world scenario:** Monitor your company's public documentation or status page for updates. When changes are detected by your monitoring tool, automatically capture the updated page as a PDF for compliance records and team notifications. 1. Configure the **HTTP – PDFBolt** module: Request content: ```json { "url": "{{1.page_url}}", "format": "A4", "landscape": false, "printBackground": true, "waitUntil": "networkidle", "margin": { "top": "20px", "right": "20px", "bottom": "20px", "left": "20px" } } ``` :::tip Dynamic URLs Use `{{1.page_url}}` to capture the URL sent by your monitoring tool's webhook. This allows you to document any page that triggers an update alert. ::: :::info Page Loading `waitUntil: "networkidle"` waits for all network activity to complete before PDF capture – essential for dynamic content and dashboards. ::: ### URL Scenario Example **Complete scenario:** 1. **Webhooks: Custom webhook** – Triggered when page is updated. 2. **HTTP: PDFBolt** – Convert updated page to PDF. 3. **Slack: Create a Message** – Notify team with PDF attachment. 4. **Google Drive: Upload a File** – Archive snapshot for compliance. **Integration options:** Connect this webhook with page monitoring services like Visualping, ChangeTower, or custom scripts that detect website updates. ## Additional Resources ### PDFBolt Documentation - [Templates Management Guide](/docs/admin-dashboard/templates) – Detailed creation and management instructions. - [Templates Docs](/docs/pdf-templates) – Templates overview, benefits, and use cases. - [API Endpoints](/docs/api-endpoints) – All available endpoints. - [Conversion Parameters](/docs/parameters) – Complete parameter reference. - [Error Handling](/docs/error-handling) – Error codes and solutions. ### Make Resources - Make How-to guides - Make Help Center - Make Community --- ## Zapier Integration Guide Discover how to connect PDFBolt with Zapier for automated PDF creation in your workflows. Build professional documents from templates, HTML markup, or web pages through Zapier's no-code automation interface. ## Prerequisites To get started, you'll need: 1. **PDFBolt API Key** - [Sign up](https://app.pdfbolt.com/register) or [log in](https://app.pdfbolt.com/login) to your PDFBolt account. - Navigate to API Keys section. - Copy your API key for authentication. 2. **Zapier Account** - Zapier account (free or paid plan). ## Basic Setup ### Configure Webhooks by Zapier Connect to PDFBolt's API using Zapier's Webhooks action: 1. In your Zap, add an action step and search for **Webhooks by Zapier**. 2. Select **Custom Request** as your action event → Continue. 3. Set up the request parameters: - **Method:** `POST` - **URL:** `https://api.pdfbolt.com/v1/direct` - **Data Pass-Through?** `False` - **Data:** (configuration varies by content source – examples provided below) - **Unflatten:** `No` - **Headers:** - `API-KEY`: `YOUR-API-KEY` ### Choose Your Endpoint Pick the PDFBolt endpoint that matches your workflow requirements: | Endpoint | Best For | Returns | |----------|----------|---------| | `/v1/direct` | Immediate PDF delivery | Raw PDF data in response | | `/v1/sync` | URL-based access | JSON with download URL | | `/v1/async` | High-volume processing | Webhook callback with results | :::info Endpoint Details Check [API Endpoints](/docs/api-endpoints) for complete specifications. ::: ### Choose Your Source Select the content source that best fits your use case: | Source | Best For | When to Use | |--------|-----------|----------| | **Templates** | Documents with consistent structure | Certificates, receipts, invoices – anything generated multiple times with variable data | | **HTML** | Custom documents | When you need full control over a unique layout | | **URL** | Existing web pages | Archiving documentation, reports, capturing dashboards, saving public web content | :::info Source Parameters Explore source parameters in the [API Documentation](/docs/parameters#source-parameters). ::: ## Source 1: Templates Templates offer the cleanest approach for creating branded, consistent PDFs through design-data separation. ### How It Works 1. **Create your template** in PDFBolt's Template section: - Build custom layouts with HTML, CSS, and Handlebars variables. - Or start with a ready-made template from the gallery. 2. **Publish for API access** and get your `templateId`. 3. **Send API request** containing just `templateId` and `templateData`. 4. **Receive your PDF** – PDFBolt returns the generated PDF. :::tip Template Setup Learn how to create and manage templates in the [Templates Documentation](/docs/admin-dashboard/templates). ::: ### Example: Course Completion Certificate **Real-world scenario:** Student completes your online course. Automatically generate a personalized completion certificate PDF and email it to them. **Step 1:** Set up your trigger (e.g., **Google Forms** or **Teachable** for course completion). **Step 2:** In **Webhooks by Zapier** action, configure the `Data` field: ```json { "templateId": "your-certificate-template-id", "templateData": { "recipient_name": "{{1. Your Full Name}}", "course_title": "{{1. Which course}}", "completion_date": "{{1. Last Submitted Time}}", "instructor_name": "Prof. Lingua Ford", "organization_name": "International Language Center" } } ``` :::info How It Works - `{{1. Field Name}}` references data from step 1 (your trigger). To insert dynamic values, click the **+** icon, search for the field name, and select it. - Step numbers match your Zap sequence position. - Field names must exactly match your template's Handlebars variables. - Combine dynamic fields from triggers with static values as needed. ::: ### Template Zap Example **Complete Zap:** 1. **Google Forms: New Response** – Student submits completion form. 2. **Webhooks by Zapier: Custom Request** – Creates certificate PDF. 3. **Gmail: Send Email** – Delivers certificate to recipient. 4. **Google Drive: Upload File** – Stores certificate copy. :::tip Other Learning Platform Integrations Apply this pattern with **Thinkific**, **Kajabi**, **Teachable**, or similar platforms available in Zapier. Connect completion triggers to your certificate template variables. ::: ## Source 2: HTML Convert HTML directly into PDFs within your Zaps – perfect for event materials, announcements, or custom one-time documents. ### How It Works 1. Add your HTML content in a Code step. 2. Encode HTML to Base64 format. 3. Send **encoded HTML to PDFBolt**. 4. Receive your PDF. :::warning Base64 Encoding Required PDFBolt requires Base64-encoded HTML. This means you'll need **Code by Zapier** to encode your HTML before sending it to the Webhooks step. ::: ### Example: Event Program **Real-world scenario:** Organizing a webinar or conference. Generate a PDF program with schedule, speakers, and session details that attendees can download. **Step 1:** Set up **Typeform: New Entry** trigger for event registration. **Step 2:** Add **Code by Zapier** action with **Run JavaScript**.
**View Complete Code Example** ```javascript // Static event program HTML – same for all attendees const htmlContent = ` Tech Summit 2025 Building the Future Together November 15, 2025 | Virtual Event Event Details: Date: November 15, 2025 Time: 9:00 AM – 5:00 PM EST Platform: Zoom (link will be sent via email) Event Schedule 9:00 AM – 9:30 AM Opening Keynote: The Future of AI Speaker: Dr. Sarah Johnson, AI Research Director Exploring emerging trends in artificial intelligence and their impact on business. 9:45 AM – 10:30 AM Workshop: Building Scalable APIs Speaker: Mike Chen, Senior Engineer Hands-on session covering best practices for API design and implementation. ☕ Coffee Break (10:30 AM – 11:00 AM) 11:00 AM – 11:45 AM Panel Discussion: Cloud Architecture Panelists: Various industry experts Interactive discussion about modern cloud infrastructure and DevOps practices. 12:00 PM – 1:00 PM Networking Session Connect with other attendees and speakers in breakout rooms. 🍽️ Lunch Break (1:00 PM – 2:00 PM) 2:00 PM – 2:45 PM Case Study: Digital Transformation Success Speaker: Lisa Martinez, CTO Real-world example of successful digital transformation journey. 3:00 PM – 4:00 PM Q&A with Speakers Ask questions and get insights from all our speakers. Questions? Contact us at events@example.com `; // Encode to Base64 const html = Buffer.from(htmlContent).toString('base64'); output = { html }; ```
:::info Why Code by Zapier? HTML must be Base64-encoded before sending to PDFBolt. Code by Zapier handles this encoding using `Buffer.from(html).toString('base64')`. ::: **Step 3:** Add **Webhooks by Zapier: Custom Request**. Configure the `Data` field: ```json { "html": "{{2. Html}}", "format": "A4", "printBackground": true, "margin": { "top": "30px", "bottom": "30px", "right": "30px", "left": "30px" } } ``` :::info Dynamic Values - Click the **+** icon in the Data field and select `2. Html` from the Code step output. - This passes the Base64-encoded HTML to PDFBolt. ::: ### HTML Zap Example **Complete Zap:** 1. **Typeform: New Entry** – Registration form submitted. 2. **Code by Zapier: Run JavaScript** – Add and encode HTML. 3. **Webhooks by Zapier: Custom Request** – Generate PDF program. 4. **Gmail: Send Email** – Send confirmation with PDF to attendee. :::tip PDF Customization Adjust PDF formatting by modifying parameters in the Webhooks Data field. See [Conversion Parameters](/docs/parameters) for all available options like page size, orientation, and margins. ::: ## Source 3: URL Convert public web pages into PDF documents – perfect for saving online materials, dashboard snapshots, or creating report archives. ### How It Works 1. Provide the target webpage URL. 2. PDFBolt retrieves and renders the page. 3. Returns a PDF. ### Example: Daily Dashboard Report **Real-world scenario:** Your team tracks metrics on a web-based analytics dashboard. Every weekday morning, automatically capture the dashboard as PDF and share it on Slack so the team stays informed. **Step 1:** Set up **Schedule by Zapier** trigger. Configure to run **every weekday at 8:00 AM**. **Step 2:** Add **Webhooks by Zapier: Custom Request**. Configure the `Data` field: ```json { "url": "https://analytics.yourcompany.com/dashboard", "format": "A4", "landscape": true, "printBackground": true, "waitUntil": "networkidle", "margin": { "top": "20px", "right": "20px", "bottom": "20px", "left": "20px" } } ``` :::tip Dynamic URLs For pages requiring variable URLs, construct the URL in previous Zap steps. Reference it using `{{Step Number. Field Name}}` in the Data field. ::: :::info Page Loading `waitUntil: "networkidle"` ensures all dashboard charts, data, and dynamic content finish loading before PDF capture – essential for accurate snapshots. ::: ### URL Zap Example **Complete Zap:** 1. **Schedule by Zapier** – Every weekday at 8:00 AM. 2. **Webhooks by Zapier: Custom Request** – Capture dashboard as PDF. 3. **Slack: Send Channel Message** – Share report with team channel. 4. **Google Drive: Upload File** – Archive in Reports folder. ## Additional Resources ### PDFBolt Documentation - [Templates Management Guide](/docs/admin-dashboard/templates) – Detailed creation and management instructions. - [Templates Docs](/docs/pdf-templates) – Templates overview, benefits, and use cases. - [API Endpoints](/docs/api-endpoints) – Complete endpoint reference. - [Conversion Parameters](/docs/parameters) – Full parameter documentation. - [Error Handling](/docs/error-handling) – Troubleshooting and error codes. ### Zapier Resources - Zapier Guides - Zapier Help Center - Zapier Community --- ## Airtable Integration Guide Learn how to integrate PDFBolt with Airtable to automate PDF generation directly from your bases. Generate professional documents using Airtable's automation capabilities. ## Prerequisites Before starting, ensure you have: 1. **PDFBolt API Key** - [Sign up](https://app.pdfbolt.com/register) or [log in](https://app.pdfbolt.com/login) to your PDFBolt account. - Navigate to API Keys section. - Copy your API key for authentication. 2. **Airtable Account** - Active Airtable workspace. :::note Plan Requirements The **"Run a script"** automation action used in these examples requires an Airtable Team plan or higher. If you're on a Free plan, consider using Zapier or Make as a bridge to PDFBolt (see our [Zapier](/docs/integrations/zapier) or [Make](/docs/integrations/make) guides). ::: ### Choose Your Endpoint Select the PDFBolt endpoint based on your app's needs: | Endpoint | Best For | Returns | |----------|----------|---------| | `/v1/direct` | Immediate PDF delivery | Raw PDF data in response | | `/v1/sync` | URL-based access | JSON with download URL | | `/v1/async` | High-volume processing | Webhook callback with results | :::info Endpoint Details See [API Endpoints](/docs/api-endpoints) for detailed specifications. ::: ### Choose Your Source Select the content source that best fits your use case: | Source | Best For | When to Use | |--------|----------|-------------| | **Templates** | Recurring documents with consistent layouts | Certificates, invoices, receipts – any document you generate repeatedly with different data | | **HTML** | Custom documents | When you need full control over a unique layout | | **URL** | Existing web pages | Archiving documentation, capturing dashboards, saving public content | :::info Source Parameters Learn more about source parameters in the [API Documentation](/docs/parameters#source-parameters). ::: ## Source: Templates Templates provide the most efficient way to generate consistent, branded PDFs by separating design from data. ### How It Works 1. **Create your template** in PDFBolt's Template section: - Build custom layouts with HTML, CSS, and Handlebars variables. - Or start with a ready-made template from the gallery. 2. **Publish for API access** and get your `templateId`. 3. **Map Airtable fields** to template variables using a script. 4. **Receive your PDF** – PDFBolt merges record data with your template. :::tip Template Setup See [Templates Documentation](/docs/admin-dashboard/templates) for creating and managing templates. ::: ## Example: Event Ticket Generation **Real-world scenario:** You're organizing a conference. Instead of manually creating tickets, you need an automated system where someone fills out a registration form and immediately receives their ticket PDF with a QR code via email. ### Step 1: Database Setup In our example, we will use a `Registrations` table with the following sample fields: **Optional: Create an Events table** to store event information: :::info Linked Records Setup The **Event** field in the Registrations table must be a **linked record** field connecting to the Events table. This allows each registration to be associated with a specific event. See Airtable's guide on linked records for setup instructions. ::: ### Step 2: Registration Form In this example, a new record in the table will be created each time the form is submitted: - Turn your table into a public registration form by selecting the fields to display. - Share the form URL on your event website or in marketing emails. - Each submission will automatically create a new record and trigger the automation. ### Step 3: Automation Configuration Navigate to the **Automations** tab in your Airtable base and create a new automation: **Trigger Setup:** - Trigger type: **When record created** - Table: `Registrations` This fires immediately when someone submits the registration form. **Action 1: Run a script (Generate Ticket)** Click **Add action** → Select **Run a script** Before pasting the code, you must configure input variables: 1. Under **"Inputs"**, click **+ Add input variable**. 2. Configure the input: - **Name:** `recordId` - **Value:** Select `Airtable record ID` :::info About Inputs Airtable Inputs let you use values from previous automation triggers and actions. Access them in your script using `input.config()`. This passes the newly created record's ID to the script. ::: **Secure API Key Storage with Secrets:** Instead of hardcoding your API key in the script, use Airtable's **Secrets** feature: 1. Click **+ Add new secret** 2. Name: `PDFBOLT_API_KEY` 3. Value: Paste your actual API key. Then update your script to use the variable: ```javascript const apiKey = input.secret('PDFBOLT_API_KEY') ``` :::tip Secrets Airtable's **Secret** variable type lets you securely store and use sensitive information in scripts without exposing it in code. This is the recommended approach for API keys and other credentials. ::: **Script Implementation:**
**View Code** ```javascript // PDFBolt API configuration const TEMPLATE_ID = 'your-template-id'; let config = input.config(); let recordId = config.recordId; const apiKey = input.secret('PDFBOLT_API_KEY'); let tableRegistrations = base.getTable("Registrations"); let record = await tableRegistrations.selectRecordAsync(recordId); // Get event information from Events table let tableEvents = base.getTable("Events"); let linkedEvent = record.getCellValue('Event'); let eventRecord = await tableEvents.selectRecordAsync(linkedEvent[0].id); // Extract registration data const attendeeData = { attendee_name: record.getCellValueAsString('Full Name'), email: record.getCellValueAsString('Email'), company: record.getCellValueAsString('Company') || 'N/A', ticket_type: record.getCellValueAsString('Ticket Type'), qr_code: record.getCellValueAsString('QR Code'), event_name: eventRecord.getCellValueAsString('Event Name'), event_date: eventRecord.getCellValueAsString('Event Date'), event_time: eventRecord.getCellValueAsString('Event Time'), event_location: eventRecord.getCellValueAsString('Event Location'), }; // Call PDFBolt API try { const response = await fetch('https://api.pdfbolt.com/v1/sync', { method: 'POST', headers: { 'API-KEY': apiKey, 'Content-Type': 'application/json' }, body: JSON.stringify({ templateId: TEMPLATE_ID, templateData: attendeeData }) }); const result = await response.json(); if (response.ok && result.documentUrl) { await tableRegistrations.updateRecordAsync(record.id, { 'Ticket Status': {name: 'Generated'}, 'Ticket PDF': result.documentUrl }); output.set('ticketUrl', result.documentUrl); } else { throw new Error(result.message || 'Failed to generate ticket'); } } catch (error) { console.error('Error:', error.message); await tableRegistrations.updateRecordAsync(record.id, { 'Ticket Status': {name: 'Failed'} }); throw error; } ```
**Understanding the script:** 1. **Data Collection:** Fetches the newly created attendee record via `input.config()` and extracts field values. 2. **PDF Generation:** Sends data to PDFBolt API which merges it with your template. 3. **Record Update:** Stores the PDF URL back in Airtable. **Action 2: Send email** - Add another action → Select **Gmail: Send email** (or your preferred email service). Configure the step with recipients, subject, and message. - In the message, include the `ticketUrl` generated by the script so the attendee can download it. :::note Using Script Output The `ticketUrl` comes from `output.set('ticketUrl', result.documentUrl)` in the script. Select it from the **"Run a script"** step dropdown when configuring the email body. ::: ### Complete Automations Workflow :::tip Optimization Tips **High volume:** Use `/v1/async` endpoint instead of `/v1/sync` for better performance. **Long-term storage:** Use `customS3PresignedUrl` parameter to store PDFs on your S3 bucket (default URLs expire after 24h). See [S3 Bucket Upload](/docs/s3-bucket-upload). ::: ## Additional Resources ### PDFBolt Documentation - [Templates Management Guide](/docs/admin-dashboard/templates) – Create and manage templates. - [Templates Docs](/docs/pdf-templates) – Templates overview, benefits, and use cases. - [API Endpoints](/docs/api-endpoints) – Complete endpoint reference. - [Conversion Parameters](/docs/parameters) – Full parameter documentation. - [Error Handling](/docs/error-handling) – Error codes and solutions. - [S3 Bucket Upload](/docs/s3-bucket-upload) – Store PDFs permanently. ### Airtable Resources - Airtable Guides - Airtable Help Center - Airtable Community --- ## Bubble Integration Guide Learn how to integrate PDFBolt with Bubble.io to automate PDF generation in your no-code applications. Create professional documents from templates, HTML content, or web pages using Bubble's visual workflow builder and API Connector. ## Prerequisites Before starting, ensure you have: 1. **PDFBolt API Key** - [Sign up](https://app.pdfbolt.com/register) or [log in](https://app.pdfbolt.com/login) to your PDFBolt account. - Navigate to API Keys section. - Copy your API key for authentication. 2. Bubble Account - Active Bubble.io account with an app. - API Connector plugin installed. ## Basic Setup ### Install and Configure API Connector The API Connector plugin enables your Bubble app to communicate with external APIs like PDFBolt. **Step 1: Install API Connector Plugin** 1. In your Bubble editor, go to **Plugins** tab. 2. Click **Add plugins**. 3. Search for **API Connector**. 4. Click **Install** (it's free on all Bubble plans). **Step 2: Add PDFBolt API Connection** 1. Go to **Plugins** → **API Connector**. 2. Click **Add another API**. 3. Configure the API: - **API Name:** `PDFBolt` - **Authentication:** `Private key in header` - **Key name:** `API-KEY` - **Key value:** `YOUR-API-KEY` (paste your actual PDFBolt API key) ### Choose Your Endpoint Select the PDFBolt endpoint based on your app's needs: | Endpoint | Best For | Returns | |----------|----------|---------| | `/v1/direct` | Immediate PDF delivery | Raw PDF data in response | | `/v1/sync` | URL-based access | JSON with download URL | | `/v1/async` | High-volume processing | Webhook callback with results | :::info Endpoint Details See [API Endpoints](/docs/api-endpoints) for detailed specifications. ::: ### Choose Your Source Select the content source that best fits your use case: | Source | Best For | When to Use | |--------|----------|-------------| | **Templates** | Recurring documents with consistent layouts | Certificates, invoices, receipts – any document you generate repeatedly with different data | | **HTML** | Custom documents | When you need full control over a unique layout | | **URL** | Existing web pages | Archiving documentation, capturing dashboards, saving public content | :::info Source Parameters Learn more about source parameters in the [API Documentation](/docs/parameters#source-parameters). ::: ## Source: Templates Templates provide the most efficient way to generate consistent, branded PDFs by separating design from data – perfect for Bubble apps that need to generate certificates, invoices, or reports. ### How It Works 1. **Create your template** in PDFBolt's Template section: - Build custom layouts with HTML, CSS, and Handlebars variables. - Or start with a ready-made template from the gallery. 2. **Publish the template** to make it available via API and get your unique `templateId`. 3. **Call API from Bubble workflow** with `templateId` and data from your database. 4. **Receive your PDF** – Display, download, or email directly from Bubble. :::tip Template Setup Learn how to create and manage templates in the [Templates Documentation](/docs/admin-dashboard/templates). ::: ### Example: Student Certification Platform **Real-world scenario:** You're building an online learning platform in Bubble. When students complete a course, they can generate and download a personalized certificate PDF. **1. Data structure for this example:** **Courses** (Data Type) - Name (text) - Instructor (text) - Duration (text) **Enrollments** (Data Type) - Student (User) - Course (Courses) - Completion Date (date) **2. Create API Call** In API Connector, add a new call under your PDFBolt API: - **Name:** `Generate Certificate` - **Use as:** `Action` - **Data type:** `JSON` - **Request type:** `POST` - **URL:** `https://api.pdfbolt.com/v1/sync` **Body:** ```json { "templateId": "your-certificate-template-id", "templateData": { "student_name": "", "course_title": "", "completion_date": "", "instructor_name": "", "course_duration": "" } } ``` :::info Dynamic Parameters The `` syntax in Bubble's API Connector creates dynamic parameters that you'll fill with actual data in your workflows. Bubble automatically detects these and makes them available when you use the API call. ::: **3. Initialize the Call** After configuring the body: - Fill in sample values for each parameter to test: - student_name: `John Doe` - course_title: `Advanced Web Development` - completion_date: `10/04/25` - instructor_name: `Prof. Sarah Chen` - course_duration: `12 weeks` - Uncheck "Private" checkbox – this allows dynamic values in workflows. - Click **Initialize call** to test the connection. - If successful, Bubble will show the response structure. **4. Build the User Interface** Create a page showing the student's enrolled and completed courses in a Repeating Group with course details and a "Generate Certificate" button. ### Create the Workflow Click on the button "Generate Certificate" → **Start/Edit workflow**. **Step 1 – Generate PDF:** - Action: **Plugins → PDFBolt – Generate Certificate** - Fill parameters with dynamic data: - `student_name`: `Current User's Name` - `course_title`: `Parent group's Enrollment's Course's name` - `completion_date`: `Parent group's Enrollment's Completion Date:formatted as 10/04/25` - `instructor_name`: `Parent group's Enrollment's Course's instructor` - `course_duration`: `Parent group's Enrollment's Course's duration` **Step 2 – Navigate to PDF:** - Action: **Navigation → Open an external website** - Destination: `Result of step 1's documentUrl` - Open in: `New tab` :::tip Result Access Use `Result of step 1` to access API response data in subsequent workflow steps. Bubble makes all returned fields available automatically. ::: ### Template Workflow Example **What happens:** 1. Student completes course (marked in database). 2. Student clicks "Generate Certificate" button. 3. Workflow triggers → generates personalized PDF. 4. PDF opens in new tab for download. :::info Additional PDF Sources Beyond templates, PDFBolt can generate PDFs from: - **[HTML content](/docs/parameters#html)** – Custom document layouts. - **[URLs](/docs/parameters#url)** – Convert any public webpage to PDF. ::: ## Additional Resources ### PDFBolt Documentation - [Templates Management Guide](/docs/admin-dashboard/templates) – Create and manage templates. - [Templates Overview](/docs/pdf-templates) – Benefits and use cases. - [API Endpoints](/docs/api-endpoints) – Complete endpoint reference. - [Conversion Parameters](/docs/parameters) – Full parameter documentation. - [Error Handling](/docs/error-handling) – Error codes and solutions. - [S3 Bucket Upload](/docs/s3-bucket-upload) – Store PDFs permanently. ### Bubble Resources - Bubble Docs - Bubble Academy - Bubble Forum --- ## Templates This guide walks you through template concepts, provides real-world examples and common use cases, explains the complete workflow, and helps you get started with using templates. ## What are Templates? **Templates** are **reusable HTML layouts powered by templating engines** that enable you to generate dynamic PDFs by combining a predefined design with variable data. Think of templates as smart document blueprints where you design the layout once and then populate it with different data for each PDF generation. Template Overview Instead of sending complete HTML content for each PDF generation, templates use a clean separation approach: 1. **Template Definition** – Create an HTML layout with placeholders (variables) using **Handlebars** syntax: - You can either design your own template using our visual designer in the frontend app. - Or choose from our professionally designed gallery of ready-to-use templates for common document types. 2. **Data Injection** – Send only the **template ID and JSON data payload** to our API to generate personalized PDFs: - The JSON data gets automatically merged with your template. - You can integrate this from any programming language – Node.js, Python, PHP, Java, C#, Go, Rust, etc. or use simple cURL commands. :::note Data Privacy Template data is not stored – it's only used for PDF generation and immediately discarded. **Your data remains private and secure.** ::: **PDFBolt** uses Handlebars – a powerful and widely-adopted **templating engine** that extends HTML with dynamic capabilities: - **Variable Substitution** – `{{customerName}}` gets replaced with actual customer data. - **Conditional Logic** – `{{#if isPaid}}...{{/if}}` shows content based on conditions. - **Loops & Iteration** – `{{#each items}}...{{/each}}` repeats content for arrays. - **Helper Functions** – Built-in functions for formatting dates, numbers, and text. - **Nested Objects** – Access deep data structures like `{{customer.address.city}}`. :::tip Handlebars Syntax Learn more about Handlebars templating syntax in the official Handlebars documentation. ::: :::info Need Another Template Engine? We currently support Handlebars, but **if you have a specific template engine in mind**, contact us at [contact@pdfbolt.com](mailto:contact@pdfbolt.com) and we'll consider adding engines based on your needs. ::: Simple Example: Template Transformation This basic example demonstrates the core concept – see the [full invoice example](/docs/pdf-templates#complete-example-from-template-to-pdf) below. **📝 Template HTML (with Handlebars):** ```html Invoice #{{invoiceNumber}} Invoice #{{invoiceNumber}} Dear {{customer.name}}, {{#each items}} {{name}}: ${{price}} {{/each}} {{#if isPaid}} ✅ PAID {{else}} PENDING {{/if}} Total: ${{total}} ``` **📊 JSON Data Used:** ```json { "invoiceNumber": "INV-001", "customer": {"name": "John Doe"}, "items": [ {"name": "Premium Service", "price": "199.99"}, {"name": "Setup Fee", "price": "99.99"} ], "isPaid": true, "total": "299.98" } ``` **📋 Final PDF Result:** ## Key Benefits Templates transform how you generate PDFs by separating design from data, making document creation more efficient, consistent, and maintainable. Here are the key advantages of using PDFBolt's template system: Simplified API Calls - **Cleaner Code** – Send only `templateId` and `templateData` instead of complete HTML content. - **Easier debugging** – Template and data are completely separate. Consistent Design - **Version Control** – Update template design in one place, instantly applies to all future PDFs. - **Eliminates Errors** – No more formatting mistakes or inconsistent styling across documents. Faster Development - **Ready-to-Use Gallery** – Start with ready-made designs for invoices, certificates, resumes, and more. - **Visual Designer** – Build and test templates with real-time preview. - **Developer-Friendly** – Handlebars syntax familiar to most developers, ready-to-use code snippets. Flexible Data Handling - **Smart Data Binding** – Handlebars automatically handles complex data structures, arrays, and nested objects. - **Conditional Logic** – Show/hide content based on data values (`{{#if}}`, `{{#unless}}`). Team Efficiency - **Team collaboration** – Manage templates across your organization. - **Scalable Solution** – Handle growing document volume without additional infrastructure. ## Common Use Cases Whether it's automated billing or personalized certificates, templates streamline document generation across your business needs. Business Operations Invoices, Receipts, Purchase Orders, Quotes, Statements Analytics & Reporting Financial reports, KPI dashboards, Performance reviews, Executive summaries Education & Human Resources Certificates, Course completion, Employee handbooks, Offer letters, Performance evaluations Customer Communications Personalized letters, Product catalogs, Support tickets, Shipping labels Legal & Compliance Contracts, Agreements, Policy documents, Audit reports Sales & Marketing Sales proposals, Product sheets, Marketing brochures, Event materials ## How Templates Work Templates follow a simple workflow that separates design from data, making PDF generation scalable and maintainable: ### 1. Template Creation - Design your HTML layout using our visual **designer** or **choose from our gallery**. - **Add Handlebars variables** (`{{variableName}}`) for dynamic content insertion. - Include conditional logic (`{{#if}}`) and loops (`{{#each}}`) for complex document structures. - **Preview** with sample data using real-time quick HTML preview and generate real PDFs to verify the final output. - You can also **duplicate templates** for variations, **save drafts** automatically, and edit template details. [→ Learn more about template creation and management](/docs/admin-dashboard/templates) ### 2. Template Publishing - **Publish your template** to make it available via API endpoints. - Get your unique **template ID** for seamless integration. - Built-in **version control** allows you to roll back changes safely. [→ See template publishing guide](/docs/admin-dashboard/templates#step-7-publish-your-template) ### 3. PDF Generation - Access **ready-to-use code snippets** for multiple programming languages (Node.js, Python, PHP, Java, C#, Go, Rust). - Send a lightweight API request containing only your **template ID and JSON data**. - Our high-performance engine merges your data with the template automatically. [→ Explore API integration examples](/docs/quick-start-guide#4-quick-start-for-your-favorite-language-and-postman) [→ Check out API endpoints](/docs/api-endpoints) ### 4. Receive Results - Receive professional, **high-quality PDFs** ready for download, email, or storage. - Scale effortlessly to generate millions of documents without performance bottlenecks. [→ Check out PDF customization options](/docs/parameters) ## Complete Example: From Template to PDF See how templates transform complex document generation into a simple API call. This professional invoice example demonstrates the full power of PDFBolt's template system: **1. Create your HTML template with Handlebars variables and logic (or choose from our gallery):**
Example Template Code ```html Invoice - {{invoice_number}} {{#if company_logo_url}} {{/if}} {{company_name}} Invoice Invoice No: {{invoice_number}} Issue Date: {{issue_date}} {{#if due_date}} Due Date: {{due_date}} {{/if}} Billed from {{company_name}} {{#if company_address_street}} {{company_address_street}} {{/if}} {{#if company_address_line2}} {{company_address_line2}} {{/if}}{{#if company_city}} {{company_city}}{{#if company_state}}, {{company_state}}{{/if}}{{#if company_postal_code}} {{company_postal_code}}{{/if}}{{#if company_country}}, {{company_country}}{{/if}} {{/if}} {{#if company_email}} {{company_email}} {{/if}} {{#if company_phone}} {{company_phone}} {{/if}} {{#if company_tax_id}} Tax ID: {{company_tax_id}} {{/if}} Billed to {{client_name}} {{#if client_address_street}} {{client_address_street}} {{/if}} {{#if client_address_line2}} {{client_address_line2}} {{/if}}{{#if client_city}} {{client_city}}{{#if client_state}}, {{client_state}}{{/if}}{{#if client_postal_code}} {{client_postal_code}}{{/if}}{{#if client_country}}, {{client_country}}{{/if}} {{/if}} {{#if client_email}} {{client_email}} {{/if}} {{#if client_phone}} {{client_phone}} {{/if}} {{#if client_tax_id}} Tax ID: {{client_tax_id}} {{/if}} Description Quantity Price Total {{#each line_items}} {{this.description}} {{this.quantity}} {{../currency_symbol}}{{this.unit_price}} {{../currency_symbol}}{{this.total_amount}} {{/each}} Payment Information {{#if payment_info.bank_name}} Bank Name: {{payment_info.bank_name}} {{/if}} {{#if payment_info.account_number}} Account No: {{payment_info.account_number}} {{/if}} {{#if payment_info.routing_number}} Routing: {{payment_info.routing_number}} {{/if}} {{#if payment_info.payment_terms}} Terms: {{payment_info.payment_terms}} {{/if}} Subtotal {{currency_symbol}}{{subtotal_amount}} {{#if discount_amount}} Discount{{#if discount_percentage}} ({{discount_percentage}}%){{/if}} -{{currency_symbol}}{{discount_amount}} {{/if}} {{#if tax_amount}} Tax{{#if tax_percentage}} ({{tax_percentage}}%){{/if}} {{currency_symbol}}{{tax_amount}} {{/if}} Total Amount {{currency_symbol}}{{total_amount}} Thank you! ```
**2. Send your API request with template ID and data (cURL example):** ```bash curl 'https://api.pdfbolt.com/v1/direct' \ -H 'API-KEY: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' \ -H 'Content-Type: application/json' \ -d '{ "templateId": "your-template-id", "templateData": {"invoice_number":"INV-2025-014","issue_date":"June 13, 2025","due_date":"June 27, 2025","company_name":"Pink Brand Studio","company_email":"pink@example.com","company_phone":"+1 (555) 222-3344","company_address_street":"22 Rose Garden Lane","company_city":"Blushville","company_state":"CA","company_postal_code":"90210","company_country":"USA","company_tax_id":"PB-2025-001","company_logo_url":"https://img.pdfbolt.com/business-logo-template.png","client_name":"Luxe Beauty Co.","client_email":"contact@example.com","client_phone":"+1 (555) 667-8899","client_address_street":"88 Glamour Ave","client_city":"Glowtown","client_state":"NY","client_postal_code":"10001","client_country":"USA","client_tax_id":"LB-9988","line_items":[{"description":"Brand Identity Package","quantity":1,"unit_price":"600.00","total_amount":"600.00"},{"description":"Custom Instagram Templates","quantity":1,"unit_price":"200.00","total_amount":"200.00"},{"description":"Product Photography Session","quantity":1,"unit_price":"350.00","total_amount":"350.00"},{"description":"E-commerce Banner Design","quantity":2,"unit_price":"75.00","total_amount":"150.00"},{"description":"Email Newsletter Template","quantity":1,"unit_price":"120.00","total_amount":"120.00"}],"payment_info":{"bank_name":"Example Bank","account_number":"1234567890123456","routing_number":"110099001","payment_terms":"Due in 14 days"},"currency_symbol":"$","subtotal_amount":"1420.00","discount_percentage":"10","discount_amount":"142.00","tax_percentage":"20","tax_amount":"255.60","total_amount":"1533.60"} }' \ --output professional_invoice.pdf ``` **3. Receive your generated PDF:** *Professional invoice PDF with dynamic data, conditional, and branded styling.* ## Additional Resources Explore these resources for detailed implementation: --- ## API Endpoints The PDFBolt API provides flexible PDF generation options from HTML, URLs, and dynamic templates, tailored to meet diverse workflow requirements. **API Endpoints Overview:** | **Endpoint** | **Description** | **Method** | **Response** | **Parameters** | |--------------|---------------------------------------------------------------------------------------|------------|----------------------------------------------------------|---------------------------------------------------------------------------------------------------------------| | `/v1/direct` | Generates PDFs directly from URLs, HTML, or templates and returns it in the response. | `POST` | Raw PDF or Base64-encoded PDF in the HTTP response body. | [Direct Parameters](/docs/api-endpoints/direct#body-parameters) [Common Parameters](/docs/parameters/) | | `/v1/sync` | Generates PDFs from URLs, HTML, or templates and provides a downloadable URL. | `POST` | JSON containing a downloadable URL to the generated PDF. | [Sync Parameters](/docs/api-endpoints/sync#body-parameters) [Common Parameters](/docs/parameters/) | | `/v1/async` | Processes URLs, HTML, or templates and sends results via webhook. Optionally uploads directly to your S3 bucket. | `POST` | Webhook callback with processing results. | [Async Parameters](/docs/api-endpoints/async#body-parameters) [Common Parameters](/docs/parameters/) | **Explore the detailed documentation for each generation method:** --- ## Direct Conversion The direct mode offers a quick and efficient approach to PDF generation by sending a POST request with URLs, HTML content, or template ID and JSON data. The API responds immediately with the **raw PDF**, ready for **download or display**. This endpoint is ideal for workflows requiring real-time PDF generation, such as document rendering in web applications or dashboards, delivering the PDF directly in the response. ## Endpoint Details **Method**: `POST` ```js https://api.pdfbolt.com/v1/direct ``` ## Example Example for generating a PDF directly from a URL: ```json { "url": "https://example.com" } ``` The response is a raw PDF file, ready for saving or further processing. ![PDF Preview](https://img.pdfbolt.com/responsePDF.png) ## Body Parameters :::info In this section, you will find only the parameters specific to the **`/direct`** endpoint. To view the list of common parameters shared across all endpoints, please refer to the **[Conversion Parameters](/docs/parameters)** section. ::: ### isEncoded **Type:** `boolean` **Required:** No **Default Value:** `false` **Details:** The `isEncoded` parameter determines the format of the PDF data returned in the response: - When set to `true`, the response contains the PDF data encoded in Base64 format, and the content type is `text/plain`. - When set to `false` or omitted, the response contains the raw PDF binary data, and the content type is `application/pdf`. **Usage:** ```json { "url": "https://example.com", "isEncoded": true } ``` :::warning Be aware that Base64 encoding increases the size of the data by approximately 33%, which can impact data transfer times and storage requirements. ::: ## Response The format of the response depends on the value of the `isEncoded` parameter. See the details below: | Value | Response Format | Content Type | |---------|--------------------|-------------------| | `true` | Base64-encoded PDF | `text/plain` | | `false` | Raw PDF binary | `application/pdf` | --- ## Sync Conversion The sync endpoint generates a PDF and provides a **downloadable URL** once the conversion is complete. This method is ideal for workflows where real-time access is not required, but the PDF can be downloaded via URL. ## Endpoint Details **Method**: `POST` ```js https://api.pdfbolt.com/v1/sync ``` ## Example Below is an example demonstrating a request and its corresponding response: ```json { "url": "https://example.com" } ``` ```json { "requestId": "ee57bcb5-b02b-4ae7-af37-6e91549f647d", "status": "SUCCESS", "errorCode": null, "errorMessage": null, "documentUrl": "https://s3.pdfbolt.com/pdfbolt_dd3f57ef-ea17-48a9-930a-8990ee7f52a7_2024-12-30T14-26-23Z.pdf", "expiresAt": "2024-12-31T14:26:23Z", "isAsync": false, "duration": 1168, "documentSizeMb": 0.04, "isCustomS3Bucket": false } ``` ## Body Parameters :::info In this section, you will find only the parameters specific to the **`/sync`** endpoint. To view the list of common parameters shared across all endpoints, please refer to the **[Conversion Parameters](/docs/parameters)** section. ::: ### customS3PresignedUrl **Type:** `string` **Required:** No **Details:** The `customS3PresignedUrl` allows you to specify a URL for direct upload to your S3 bucket. If not provided, the document is stored in our S3 bucket for 24 hours. See [Uploading to Your S3 Bucket](/docs/s3-bucket-upload) for setup details. **Usage:** ```json { "url": "https://example.com", "customS3PresignedUrl": "https://s3-your-custom-bucket.com?token=abcdef" } ``` ## Response Parameters The table below outlines the structure of the response for a successful request. To learn more about the structure of responses for failed requests, refer to the [Error Response Format](/docs/error-handling#error-response-format). | **Parameter** | **Type** | **Description** | **Possible Values** | **Example Value** | |--------------------|---------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------|--------------------------------------------------| | `requestId` | `string` (UUID) | Unique identifier for the request. | Any valid UUID | `ee57bcb5-b02b-4ae7-af37-6e91549f647d` | | `status` | `string` (Enum) | Status of the request. | `SUCCESS` | `SUCCESS` | | `errorCode` | `string` | Error code.This field is `null` for successful requests. | `null` | `null` | | `errorMessage` | `string` | Error message.This field is `null` for successful requests. | `null` | `null` | | `documentUrl` | `string` (URL) | URL to the generated document.This will be `null` if `customS3PresignedUrl` is used, as the PDF is uploaded directly to the provided S3 bucket. | Any valid URL or `null` | `https://s3-your-custom-bucket.com/document.pdf` | | `expiresAt` | `string` (ISO 8601) | Expiration date and time of the document stored in the default PDFBolt S3 bucket.Will be `null` if `customS3PresignedUrl` is provided. | ISO 8601 datetime string in UTC or `null` | `2024-11-19T23:59:59Z` | | `isAsync` | `boolean` | Indicates if the operation is asynchronous.Will always be `false` for the `/sync` endpoint. | `false` | `false` | | `duration` | `number` | Total processing time for the request.Measured in milliseconds. | Any positive number | `1000` | | `documentSizeMb` | `number` | Size of the document in megabytes. | Any positive number | `0.55` | | `isCustomS3Bucket` | `boolean` | Indicates if the generated document was uploaded to a user-provided custom S3 bucket or PDFBolt's default storage. | `true` `false` | `false` | --- ## Async Conversion The async conversion endpoint processes your request and immediately acknowledges receipt. Once generation is complete, it sends a **callback to the specified webhook**, notifying you of the completion. This method is ideal for handling **large-scale document generation**, especially when combined with **uploading to your S3 storage**. The `webhook` parameter is mandatory in the request body. ## Endpoint Details **Method**: `POST` ```js https://api.pdfbolt.com/v1/async ``` ## Success Example ```json { "url": "https://example.com", "webhook": "https://your-example-webhook.com" } ``` ```json { "requestId": "b32bb5ce-483a-44ab-9239-52c0e3b0ff6c" } ``` ```json { "requestId": "b32bb5ce-483a-44ab-9239-52c0e3b0ff6c", "status": "SUCCESS", "errorCode": null, "errorMessage": null, "documentUrl": "https://s3.pdfbolt.com/pdfbolt_dd3f57ef-ea17-48a9-930a-8990ee7f52a7_2024-12-30T14-26-23Z.pdf", "expiresAt": "2024-12-30T21:05:38Z", "isAsync": true, "duration": 1403, "documentSizeMb": 0.04, "isCustomS3Bucket": false } ``` ## Failure Example ```json { "url": "https://example.com", "webhook": "https://your-example-webhook.com", "waitForFunction": "() => document.body.innerText.includes('Ready to Download')" } ``` ```json { "requestId": "7e075770-9c50-4018-a877-fc45c45b7850" } ``` ```json { "requestId": "7e075770-9c50-4018-a877-fc45c45b7850", "status": "FAILURE", "errorCode": "CONVERSION_TIMEOUT", "errorMessage": "Conversion process timed out. Please see https://pdfbolt.com/docs for optimization tips.", "documentUrl": null, "expiresAt": null, "isAsync": true, "duration": 32150, "documentSizeMb": null, "isCustomS3Bucket": false } ``` ## Body Parameters :::info In this section, you will find only the parameters specific to the **`/async`** endpoint. To view the list of common parameters shared across all endpoints, please refer to the **[Conversion Parameters](/docs/parameters)** section. ::: ### webhook **Type:** `string` **Required:** Yes **Details:** The `webhook` parameter specifies the URL of your application's endpoint to receive document URLs and additional details. It must be a valid, publicly accessible URL that can process incoming requests from our service. **Usage:** ```json { "url": "https://example.com", "webhook": "https://your-app.com/endpoint" } ``` ### customS3PresignedUrl **Type:** `string` **Required:** No **Details:** The `customS3PresignedUrl` allows you to specify a URL for direct upload to your S3 bucket. If not provided, the document is stored in our S3 bucket for 24 hours. See [Uploading to Your S3 Bucket](/docs/s3-bucket-upload) for setup details. **Usage:** ```json { "url": "https://example.com", "webhook": "https://your-app.com/endpoint", "customS3PresignedUrl": "https://s3-your-custom-bucket.com?token=abcdef" } ``` ### additionalWebhookHeaders **Type:** `object` **Required:** No **Details:** This parameter allows you to include up to **10 custom headers** in asynchronous webhook requests, providing additional information as needed. **Usage:** ```json { "url": "https://example.com", "webhook": "https://your-app.com/endpoint", "additionalWebhookHeaders": { "X-Custom-Header-1": "Value1", "X-Custom-Header-2": "Value2" // up to 10 headers } } ``` :::tip The `additionalWebhookHeaders` parameter can be used to: - Add additional context about the request. - Personalize webhook responses with custom headers. - Assist in debugging and tracking requests effectively. ::: ## Response Parameters | **Parameter** | **Type** | **Description** | **Possible Values** | **Example Value** | |---------------|-----------------|----------------------------------------------------------------|---------------------|----------------------------------------| | `requestId` | `string` (UUID) | Unique identifier for the request. | Any valid UUID | `ee57bcb5-b02b-4ae7-af37-6e91549f647d` | ## Webhook Request Parameters | **Parameter** | **Type** | **Description** | **Possible Values** | **Example Value** | |--------------------|---------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------| | `requestId` | `string` (UUID) | Unique identifier for the request. | Any valid UUID | `ee57bcb5-b02b-4ae7-af37-6e91549f647d` | | `status` | `string` (Enum) | Status of the request. | `SUCCESS` `FAILURE` | `SUCCESS` | | `errorCode` | `string` | Error code if the request failed.Will be `null` if status is `SUCCESS`. | Refer to `errorCode` values in the [HTTP Status Codes](/docs/error-handling/#http-status-codes) table for all possible values | `CONVERSION_TIMEOUT` | | `errorMessage` | `string` | Error message if the request failed.Will be `null` if status is `SUCCESS`. | Any string or `null` | `Conversion process timed out. Please see https://pdfbolt.com/docs for optimization tips.` | | `documentUrl` | `string` (URL) | URL to the generated document.Will be `null` if `customS3PresignedUrl` is provided.Will be `null` if status is `FAILURE`. | Any valid URL or `null` | `https://s3.pdfbolt.com/pdfbolt_dd3f57ef-ea17-48a9-930a-8990ee7f52a7_2024-12-30T14-26-23Z.pdf` | | `expiresAt` | `string` (ISO 8601) | Expiration date and time of the document.Will be `null` if `customS3PresignedUrl` is provided.Will be `null` if status is `FAILURE`. | ISO 8601 datetime string in UTC or `null` | `2024-12-31T16:45:01Z` | | `isAsync` | `boolean` | Indicates if the operation is asynchronous.Will always be `true` for the `/async` endpoint. | `true` | `true` | | `duration` | `number` | Total processing time for the request.Measured in milliseconds. | Any positive number | `1261` | | `documentSizeMb` | `number` | Size of the document in megabytes.Will be `null` if status is `FAILURE`. | Any positive number or `null` | `0.36` | | `isCustomS3Bucket` | `boolean` | Indicates if the generated document was uploaded to a user-provided custom S3 bucket or PDFBolt's default storage. | `true` `false` | `false` | --- ## Usage Monitoring This endpoint provides real-time **information about your API usage**, including details on your subscription plan, the total number of conversions, remaining conversions, and the expiration date for current limits. ## Endpoint Details **Method**: `GET` ```js https://api.pdfbolt.com/v1/usage ``` ## Example Below is an example response from the usage endpoint: ```json { "plan": "BASIC_MONTHLY", "recurring": [ { "total": 2000, "left": 999, "expiryAt": "2025-01-29T23:59:26Z", "overage": 0 } ] } ``` ## Response Parameters | **Parameter** | **Type** | **Description** | **Possible Values** | **Example Value** | |----------------------|---------------------|-------------------------------------------------------------------------------------------------------------|---------------------------------|----------------------------------------------------------------------| | `plan` | `string` | Subscription plan name. | All plan names | `DEVELOPER_MONTHLY` | | `recurring` | `array` | Details of recurring document conversion plan. | Array with objects | `[{"total": 2000, "left": 999, "expiryAt": "2025-01-29T23:59:26Z"}]` | | `recurring.total` | `number` | Total number of recurring conversions available. | Any positive integer | `2000` | | `recurring.left` | `number` | Number of remaining recurring conversions.Includes 0 if no conversions are left. | Any non-negative integer | `999` | | `recurring.expiryAt` | `string` (ISO 8601) | Expiration date and time for the recurring limit. | ISO 8601 datetime string in UTC | `2025-01-29T23:59:26Z` | | `recurring.overage` | `number` | Number of overage conversions used for recurring plans. | Any non-negative integer | `0` | --- ## Conversion Parameters Our API offers parameters for customizing PDF generation from HTML, URLs, and dynamic templates. This section details each parameter, with examples, to help you tailor the output to your needs. ## Source Parameters :::info Content Source You must provide **exactly one** of the following content sources: [`html`](/docs/parameters#html), [`url`](/docs/parameters#url), or [`templateId`](/docs/parameters#templateid) (with [`templateData`](/docs/parameters#templatedata)). These parameters are mutually exclusive – use only one per API request. ::: ### html **Type:** `string` **Required:** No **Details:** Accepts Base64-encoded HTML content, allowing you to provide the HTML directly for generating a PDF. **Usage:** ```json { "html": "PGh0bWw+Cjxib2R5Pgo8cD5UZXN0IHBhcmFncmFwaDwvcD4KPC9ib2R5Pgo8L2h0bWw+Cg==" } ``` This example generates a PDF containing the text: “Test paragraph”. :::tip Ensure your HTML content is properly encoded in **Base64** format before passing it to this parameter. You can use online tools or libraries to perform the conversion. ::: ### url **Type:** `string` **Required:** No **Details:** Accepts any valid URL. This allows specifying the webpage to be converted to a PDF. **Usage:** ```json { "url": "https://example.com" } ``` ### templateId **Type:** `string` **Required:** No **Details:** Specifies the unique identifier (UUID) of a published template to use for PDF generation. When using this parameter, [`templateData`](/docs/parameters#templatedata) must also be provided to populate the template variables. Templates allow you to separate design from data, making document generation more efficient and maintainable. **Usage:** ```json { "templateId": "c2b5f574-19bc-4e34-9049-566176e6dc48", "templateData": { "customerName": "John Doe", "invoiceNumber": "INV-001" } } ``` :::info Template Management - Templates must be created and published through the [Templates Dashboard](https://app.pdfbolt.com/templates) before they can be used via API. - Learn more about [template creation and management](/docs/admin-dashboard/templates). ::: ### templateData **Type:** `object` **Required:** No (mandatory only if `templateId` is provided) **Details:** Contains the **JSON data** that replaces placeholder variables in your template to generate the final PDF. Property names in this object must match the variable names used in your template's Handlebars syntax. For example, if your template contains `{{customerName}}`, your templateData should include a `customerName` property with the actual value. **Usage:** ```json { "templateId": "c2b5f574-19bc-4e34-9049-566176e6dc48", "templateData": { "invoiceNumber": "INV-001", "customerName": "John Doe", "items": [ { "name": "Premium Service", "price": "199.99" } ], "total": "199.99", "isPaid": true } } ``` :::note Data Privacy Template data is only used for PDF generation and is not stored, logged, or retained by PDFBolt. **Your data remains private and secure.** See our **[DPA](/data-processing-agreement)** for compliance details. ::: ## Page Parameters ### emulateMediaType **Type:** `string` **Required:** No **Default Value:** `print` **Details:** Determines the media type for rendering the PDF. **Allowed Values:** | **Value** | **Description** | |-----------|-------------------------------------------------------------| | `screen` | Generates a PDF using styles optimized for digital screens. | | `print` | Generates a PDF using styles intended for print. | **Usage:** ```json { "url": "https://example.com", "emulateMediaType": "screen" } ``` ### javaScriptEnabled **Type:** `boolean` **Required:** No **Default Value:** `true` **Details:** Determines whether JavaScript execution is enabled on the source page during PDF generation. | **Value** | **Description** | |-----------|----------------------------------------------------------------------------------------------------------------------------------------------| | `true` | Enables JavaScript execution. Dynamic content, animations, and interactive elements are rendered accurately. | | `false` | Disables JavaScript execution. Improves performance and reduces rendering time, but dynamic or interactive content may not render correctly. | **Usage:** ```json { "url": "https://example.com", "javaScriptEnabled": true } ``` ### httpCredentials **Type:** `object` **Required:** No **Details:** Enables HTTP Basic Authentication by providing a `username` and `password`, allowing access to resources protected by authentication. | **Property Name** | **Type** | **Description** | |-------------------|----------|---------------------------------------------| | `username` | `string` | The username for authentication. `required` | | `password` | `string` | The password for authentication. `required` | **Usage:** ```json { "url": "https://example.com", "httpCredentials": { "username": "john", "password": "pa55w0rd" } } ``` ### viewportSize **Type:** `object` **Required:** No **Details:** Defines the viewport dimensions for the page, specifying the `width` and `height` in pixels. Both `width` and `height` must be included in the `viewportSize` object and must be integers. | **Property Name** | **Type** | **Description** | |-------------------|----------|----------------------------------------------| | `width` | `number` | Width of the viewport in pixels. `required` | | `height` | `number` | Height of the viewport in pixels. `required` | **Usage:** ```json { "url": "https://example.com", "viewportSize": { "width": 1280, "height": 800 } } ``` :::note How viewport size works Viewport size controls how the page is rendered before PDF conversion, similar to resizing a browser window. This only **affects pages that use responsive design with CSS media queries** like `@media (max-width: 768px)`. Pages without defined responsive CSS will look the same regardless of viewport size. ::: ### isMobile **Type:** `boolean` **Required:** No **Default Value:** `false` **Details:** Enables or disables mobile device emulation, affecting how the page is rendered and interacted with. | **Value** | **Description** | |-----------|------------------------------------------------------------------------------------------| | `true` | Simulates a mobile device by respecting the meta viewport tag and enabling touch events. | | `false` | Disables mobile emulation, rendering the page as it would appear on a desktop device. | **Usage:** ```json { "url": "https://example.com", "isMobile": true } ``` :::note When to use isMobile Most sites only need [`viewportSize`](/docs/parameters#viewportsize) for mobile layout. Use `isMobile: true` only for sites that detect mobile devices with JavaScript or use touch-specific CSS. ::: ### deviceScaleFactor **Type:** `number` **Required:** No **Default Value:** `1` **Details:** Defines the level of scaling applied to the webpage during rendering. A higher scale factor enhances the resolution, making text and images appear sharper in the generated PDF. The allowed values range from `1` to `4`. **Usage:** ```json { "url": "https://example.com", "deviceScaleFactor": 2 } ``` :::note Performance impact Using a higher `deviceScaleFactor` can increase the file size and slightly prolong the processing time for generating the PDF. ::: ### extraHTTPHeaders **Type:** `object` **Required:** No **Details:** Allows you to include additional custom HTTP headers in the request. You can specify up to **10 headers**, but the order of the headers is not guaranteed. By default, these headers will be sent with every request the page initiates, including requests for images, stylesheets, scripts, and other resources. **Usage:** ```json { "url": "https://example.com", "extraHTTPHeaders": { "X-extra-header": "test1", "X-extra-header2": "test2" } } ``` :::tip Header Scope To limit headers to only the main page request and exclude sub-resources (images, CSS, JS), set [`applyExtraHTTPHeadersToAllResources`](/docs/parameters#applyextrahttpheaderstoallresources) to `false`. See details below. ::: ### applyExtraHTTPHeadersToAllResources **Type:** `boolean` **Required:** No **Default Value:** `true` **Details:** Determines whether custom HTTP headers specified in [`extraHTTPHeaders`](/docs/parameters#extrahttpheaders) should be applied to all resource requests or only to the main page request. | **Value** | **Description** | |-----------|---------------------------------------------------------------------------------------------------------------------------| | `true` | Headers are sent with every request initiated by the page, including sub-resources like images, stylesheets, and scripts. | | `false` | Headers are sent only with the main page request. | **Usage:** ```json { "url": "https://example.com", "extraHTTPHeaders": { "X-Custom-Key": "abc123xyz789" }, "applyExtraHTTPHeadersToAllResources": false } ``` :::info Usage Notes - Use this parameter only with [`extraHTTPHeaders`](/docs/parameters#extrahttpheaders). - Set to `false` if your headers are only intended for the main page request. This prevents errors when external resources (e.g., CDNs, S3) reject custom headers, which can block assets from loading and result in a blank page. ::: ### cookies **Type:** `Array` **Required:** No **Details:** Specifies a list of cookies to include in the request. Each cookie must include the `name`, `value`, and either an `url` or a combination of both `domain` and `path` to define its scope. Optional properties are available for further customization. A maximum of **10 cookies** can be added. | **Property Name** | **Type** | **Description** | |-------------------|-----------|-------------------------------------------------------------------------------------------------------| | `name` | `string` | The name of the cookie. `required` | | `value` | `string` | The value of the cookie. `required` | | `url` | `string` | Specifies the URL for which the cookie is valid. `required` if `domain` and `path` are not used | | `domain` | `string` | Specifies the domain for which the cookie is valid. `required` if `url` is not used | | `path` | `string` | The URL path that must exist in the requested URL for the cookie to be sent. `required` with `domain` | | `expires` | `number` | Expiration date of the cookie in UNIX timestamp format. `optional` | | `httpOnly` | `boolean` | Indicates if the cookie is HTTP-only. `optional` | | `secure` | `boolean` | Indicates if the cookie is secure. `optional` | **Usage:** ```json { "url": "https://example.com", "cookies": [ { "name": "sessionId", "value": "abc123", "domain": "example.com", "path": "/" }, { "name": "userPreferences", "value": "darkMode=true", "url": "https://example.com", "expires": 1739641833, "httpOnly": true, "secure": true } ] } ``` ### waitUntil **Type:** `string` **Required:** No **Default Value:** `load` **Details:** Specifies the event that defines when the page is considered fully loaded during PDF generation. Select the value that best fits your page's content and loading behavior. **Allowed Values:** | **Value** | **Description** | |--------------------|---------------------------------------------------------------------------------------------------------| | `domcontentloaded` | Completes when the `DOMContentLoaded` event fires, meaning the HTML document has been fully parsed. | | `load` | Completes when the `load` event fires, ensuring all resources such as images and scripts are loaded. | | `networkidle` | Completes when there are no active network requests for at least 500 ms, indicating the page is stable. | | `commit` | Completes as soon as a network response is received, and the document begins loading. | **Usage:** ```json { "url": "https://example.com", "waitUntil": "networkidle" } ``` ### waitForFunction **Type:** `string` **Required:** No **Details:** Waits for a specified JavaScript function to execute and return `true` within the page’s context, ensuring that certain conditions are met before continuing. **Usage:** ```json { "url": "https://example.com", "waitForFunction": "() => { return document.readyState === 'complete' && document.fonts.status === 'loaded' && Array.from(document.images).every(img => img.complete); }" } ``` :::note What this function does This example function waits until the document is fully loaded, all fonts are loaded, and all images have finished loading. This ensures your PDF captures the page after all content has properly rendered. ::: ### waitForSelector **Type:** `object` **Required:** No **Details:** Waits for a specified selector to satisfy a given state, such as appearing, disappearing, becoming visible, or hidden in the DOM. | **Property Name** | **Type** | **Description** | |-------------------|----------|------------------------------------------------------------------| | `selector` | `string` | CSS selector to target an element. `required` | | `state` | `string` | State to wait for. Must be one of the allowed values. `required` | **Allowed Values for `state`:** | **Value** | **Description** | |------------|---------------------------------------------------------------------------------------------------------------------------------------| | `attached` | Waits for the element to be present in the DOM. | | `detached` | Waits for the element to not be present in the DOM. | | `visible` | Waits for the element to have a non-empty bounding box and not have `visibility: hidden`. Elements with `display: none` are excluded. | | `hidden` | Waits for the element to be either detached from the DOM, have an empty bounding box or `visibility: hidden`. Opposite of `visible`. | **Usage:** ```json { "url": "https://example.com", "waitForSelector": { "selector": "#removable-element", "state": "hidden" } } ``` :::note Invalid selector Ensure the CSS selector exists on the target page. A non-existent selector will cause a timeout error. ::: ### timeout **Type:** `number` **Required:** No **Default Value:** `30000` **Details:** Defines the maximum time in **milliseconds** to wait for the page to load or for specific conditions to be met. Acceptable range is between `0` and `60000` (1 minute). If the timeout is exceeded, the request will fail with a timeout error. **Usage:** ```json { "url": "https://example.com", "timeout": 30000 } ``` :::warning Common Timeout Mistake Note that the timeout value must be provided in **milliseconds**, not seconds. A common mistake is entering 30 instead of 30000 for a 30-second timeout. Ensure your value is within the valid range: **0 – 60000 ms**. ::: ## Pdf Layout ### format **Type:** `string` **Required:** No **Default Value:** `Letter` **Details:** Specifies the paper format for the generated PDF. If both `format` and custom dimensions: [`width`](/docs/parameters#width) or [`height`](/docs/parameters#height) are provided, the `format` parameter takes priority. **Allowed Values:** | **Value** | **Size in Inches** | **Size in cm** | **Size in Feet** | |-----------|--------------------|-----------------|-------------------| | `Letter` | 8.5in x 11in | 21.6cm x 27.9cm | 0.666ft x 0.917ft | | `Legal` | 8.5in x 14in | 21.6cm x 35.6cm | 0.666ft x 1.167ft | | `Tabloid` | 11in x 17in | 27.9cm x 43.2cm | 0.917ft x 1.417ft | | `Ledger` | 17in x 11in | 43.2cm x 27.9cm | 1.417ft x 0.917ft | | `A0` | 33.1in x 46.8in | 84cm x 118.9cm | 2.757ft x 3.898ft | | `A1` | 23.4in x 33.1in | 59.4cm x 84cm | 1.948ft x 2.757ft | | `A2` | 16.54in x 23.4in | 42cm x 59.4cm | 1.377ft x 1.948ft | | `A3` | 11.7in x 16.54in | 29.7cm x 42cm | 0.974ft x 1.377ft | | `A4` | 8.27in x 11.7in | 21cm x 29.7cm | 0.689ft x 0.974ft | | `A5` | 5.83in x 8.27in | 14.8cm x 21cm | 0.485ft x 0.689ft | | `A6` | 4.13in x 5.83in | 10.5cm x 14.8cm | 0.344ft x 0.485ft | **Usage:** ```json { "url": "https://example.com", "format": "A4" } ``` ### landscape **Type:** `boolean` **Required:** No **Default Value:** `false` **Details:** Defines the orientation of the generated PDF. | **Value** | **Description** | |-----------|-----------------------------------------------| | `true` | Generates the PDF in landscape mode. | | `false` | Generates the PDF in portrait mode (default). | **Usage:** ```json { "url": "https://example.com", "landscape": true } ``` ### width **Type:** `string` | `number` **Required:** No **Details:** Defines the width of the page for the generated PDF. You can specify the width using different units. **Supported Units:** - `px` – pixel - `in` – inch - `cm` – centimeter - `mm` – millimeter :::info If no unit is specified, the value is interpreted as pixels. ::: **Examples:** - `"width": 100` – sets the page width to 100 pixels. - `"width": "100px"` – sets the page width to 100 pixels. - `"width": "10cm"` – sets the page width to 10 centimeters. **Usage:** ```json { "url": "https://example.com", "width": "15cm" } ``` ### height **Type:** `string` | `number` **Required:** No **Details:** Defines the height of the page for the generated PDF. For more information on supported units and examples, see [`width`](/docs/parameters#width) section. **Usage:** ```json { "url": "https://example.com", "height": "800px" } ``` ### margin **Type:** `object` **Required:** No **Details:** Specifies the page margins for the generated PDF. By default, no margins are applied. When using this parameter, at least one margin property (`top`, `right`, `left`, `bottom`) must be provided. An empty margin object is invalid and will have no effect. For more information on supported units, see [`width`](/docs/parameters#width) section. | **Property Name** | **Type** | **Description** | |-------------------|----------------------|------------------------------| | `top` | `string` \| `number` | Specifies the top margin. | | `right` | `string` \| `number` | Specifies the right margin. | | `left` | `string` \| `number` | Specifies the left margin. | | `bottom` | `string` \| `number` | Specifies the bottom margin. | **Usage:** ```json { "url": "https://example.com", "margin": { "top": "30px", "right": "20px", "left": "20px", "bottom": "30px" } } ``` ### pageRanges **Type:** `string` **Required:** No **Details:** Specifies the page ranges to include in the PDF. Accepts a comma-separated list of page ranges or individual pages, such as `1-3, 5, 8-11`. If omitted, the PDF will include all pages by default. **Usage:** ```json { "url": "https://example.com", "pageRanges": "1-7" } ``` ### preferCssPageSize **Type:** `boolean` **Required:** No **Default Value:** `false` **Details:** Specifies whether the PDF generation should prioritize the CSS `@page` size defined in the content. | **Value** | **Description** | |-----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `true` | The PDF will use the dimensions specified in the `@page` CSS rule. | | `false` | The content will scale automatically to fit the page size set by [`width`](/docs/parameters#width), [`height`](/docs/parameters#height), or [`format`](/docs/parameters#format). | **Usage:** ```json { "url": "https://example.com", "preferCssPageSize": true } ``` ### printBackground **Type:** `boolean` **Required:** No **Default Value:** `false` **Details:** Specifies whether the PDF should include background graphics like colors and images. | **Value** | **Description** | |-----------|-----------------------------------------------------------------------------------| | `true` | Background graphics (e.g., colors, images) will be included in the PDF. | | `false` | Background graphics will be excluded, producing a simpler, more minimalistic PDF. | **Usage:** ```json { "url": "https://example.com", "printBackground": true } ``` ### scale **Type:** `number` **Required:** No **Default Value:** `1` **Details:** Specifies the scaling factor for rendering the content in the generated PDF. The acceptable range for this parameter is between `0.1` and `2`. **Usage:** ```json { "url": "https://example.com", "scale": 1.5 } ``` ### displayHeaderFooter **Type:** `boolean` **Required:** No **Default Value:** `false` **Details:** Specifies whether to include a header and footer in the generated PDF. This parameter is meaningful only when used with the [`headerTemplate`](/docs/parameters#headertemplate) and/or [`footerTemplate`](/docs/parameters#footertemplate) parameters to define the content of the header and footer. | **Value** | **Description** | |-----------|--------------------------------------------------------------| | `true` | Header and footer will be displayed on each page of the PDF. | | `false` | No header or footer will be included in the PDF. | **Usage:** ```json { "url": "https://example.com", "displayHeaderFooter": true } ``` ### headerTemplate **Type:** `string` **Required:** No **Details:** Specifies the HTML template for the page header. The template must be a valid Base64-encoded HTML string with specific classes used to dynamically inject values during PDF generation. The following classes are used to inject values into them: | **Placeholder** | **Description** | |-----------------|----------------------------------------| | `date` | Formatted date. | | `title` | Document title. | | `url` | Document location. | | `pageNumber` | Current page number. | | `totalPages` | Total number of pages in the document. | **Usage:** ```json { "url": "https://example.com", "displayHeaderFooter": true, "headerTemplate": "PGRpdiBzdHlsZT0id2lkdGg6IDEwMCU7IHRleHQtYWxpZ246IGNlbnRlcjsgZm9udC1zaXplOiAxMHB4OyBjb2xvcjogZ3JheTsiPg0KICAgIDxzcGFuIGNsYXNzPSJ0aXRsZSI+PC9zcGFuPiB8IDxzcGFuIGNsYXNzPSJ1cmwiPjwvc3Bhbj4gfCA8c3BhbiBjbGFzcz0iZGF0ZSI+PC9zcGFuPg0KPC9kaXY+DQo=", "margin": { "top": "30px" } } ``` This example generates a PDF with the following header: ```html | | ``` :::info Header & Footer Templates - Ensure that your HTML templates are valid Base64-encoded strings before using them. - Please note that `