Blog / Convert URL to PDF: Complete API Guide...

Convert URL to PDF: Complete API Guide

Generate professional PDFs from any URL or HTML content. Learn about pagination, headers, footers, and advanced PDF customization options.

ScreenCraft Team
| | 7 min read

TL;DR: Use a PDF API to convert any URL to PDF with a single request. Set format: "A4" for documents, add headers/footers with displayHeaderFooter, and use printBackground: true for full-color PDFs.

Why Convert URLs to PDF?

PDF generation from web content is essential for many applications: invoice generation, report creation, document archiving, contract signing, and creating downloadable versions of web pages.

In this guide, we'll cover how to convert URLs to PDF using an API, including customization options for professional-quality output.

Basic URL to PDF Conversion

The simplest way to convert a URL to PDF is with a single API call. Here's how to do it with ScreenCraft's API:

JavaScript Example

const response = await fetch('https://api.screencraft.dev/v2/pdf', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    url: 'https://example.com/invoice/123',
    format: 'A4',
    printBackground: true
  })
});

const data = await response.json();
console.log('PDF URL:', data.data.url);

Python Example

import requests

response = requests.post(
    'https://api.screencraft.dev/v2/pdf',
    headers={
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json',
    },
    json={
        'url': 'https://example.com/invoice/123',
        'format': 'A4',
        'printBackground': True
    }
)

data = response.json()
print('PDF URL:', data['data']['url'])

Paper Format Options

Choose from standard paper sizes or set custom dimensions:

Format Dimensions Use Case
Letter 8.5" x 11" US documents
A4 210mm x 297mm International standard
Legal 8.5" x 14" Legal documents
A3 297mm x 420mm Large documents
Custom Any size Special requirements
{
  "url": "https://example.com",
  "format": "A4",
  // Or use custom dimensions:
  "width": "210mm",
  "height": "297mm"
}

Adding Headers and Footers

Professional documents often need headers and footers with page numbers, dates, or company logos.

{
  "url": "https://example.com/report",
  "format": "A4",
  "displayHeaderFooter": true,
  "headerTemplate": "<div style='font-size:10px; text-align:center; width:100%;'>Company Name - Confidential</div>",
  "footerTemplate": "<div style='font-size:10px; text-align:center; width:100%;'>Page <span class='pageNumber'></span> of <span class='totalPages'></span></div>",
  "margin": {
    "top": "100px",
    "bottom": "80px",
    "left": "40px",
    "right": "40px"
  }
}

Available template variables:

  • pageNumber - Current page number
  • totalPages - Total number of pages
  • date - Current date
  • title - Document title
  • url - Source URL

Handling Multi-Page Documents

Long web pages automatically paginate. Control pagination behavior with these options:

{
  "url": "https://example.com/long-article",
  "format": "A4",
  "printBackground": true,
  "preferCSSPageSize": false,
  "scale": 1.0,
  "pageRanges": "1-5"  // Optional: only specific pages
}

Use CSS page-break-before and page-break-after on your source page to control where breaks occur.

Converting HTML Directly

Don't have a hosted URL? Send HTML content directly:

const html = `
  <!DOCTYPE html>
  <html>
  <head>
    <style>
      body { font-family: Arial, sans-serif; padding: 40px; }
      h1 { color: #333; }
      .invoice-table { width: 100%; border-collapse: collapse; }
      .invoice-table th, .invoice-table td { border: 1px solid #ddd; padding: 12px; }
    </style>
  </head>
  <body>
    <h1>Invoice #12345</h1>
    <table class="invoice-table">
      <tr><th>Item</th><th>Price</th></tr>
      <tr><td>API Access</td><td>$99/mo</td></tr>
    </table>
  </body>
  </html>
`;

const response = await fetch('https://api.screencraft.dev/v2/pdf', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    html: html,
    format: 'A4',
    printBackground: true
  })
});

Landscape Orientation

For wide tables or charts, use landscape orientation:

{
  "url": "https://example.com/dashboard",
  "format": "A4",
  "landscape": true,
  "printBackground": true
}

Best Practices for PDF Generation

  • Always set printBackground: true - Otherwise, background colors and images will be missing from the PDF.
  • Use print-specific CSS - Add @media print styles to your source page for better PDF output.
  • Set appropriate margins - Avoid content being cut off by setting adequate margins (at least 20px).
  • Wait for content to load - Use the waitFor option if your page has dynamic content.
  • Test with different paper sizes - Content may reflow differently depending on the paper format.

Error Handling

Handle common errors gracefully:

try {
  const response = await fetch('https://api.screencraft.dev/v2/pdf', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ url, format: 'A4' })
  });

  const data = await response.json();

  if (!data.success) {
    console.error('PDF generation failed:', data.error.message);
    return null;
  }

  return data.data.url;
} catch (error) {
  console.error('Request failed:', error);
  return null;
}

Conclusion

Converting URLs to PDF is straightforward with the right API. With customization options for paper size, headers, footers, and margins, you can generate professional-quality PDFs for any use case.

Get your API key and start generating PDFs in minutes. The free tier includes 100 PDF generations per month.

Ready to Try ScreenCraft?

Start capturing screenshots and generating PDFs in minutes. Free tier includes 100 screenshots/month.

Stop wrestling with Puppeteer.
Start shipping screenshots.

Join 2,000+ developers who chose the easy path.

Free forever tier • No credit card • Setup in 2 minutes