Code Examples

Ready-to-use code snippets for integrating PDFShot into your application.

Basic Conversion

const response = await fetch('https://convert.pdfshot.com/convert', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.PDFSHOT_API_KEY}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    html: '<h1>Hello World</h1>',
    options: {
      format: 'A4',
      margin: '1in'
    }
  })
})

const data = await response.json()

if (data.success) {
  console.log('PDF URL:', data.url)
} else {
  console.error('Error:', data.error.message)
}

Converting a URL

Render a webpage to PDF:

const response = await fetch('https://convert.pdfshot.com/convert', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.PDFSHOT_API_KEY}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    url: 'https://pdfshot.com/demo/invoice',
    options: {
      format: 'Letter',
      printBackground: true
    }
  })
})

Using Templates

Render a stored template with dynamic variables:

const response = await fetch('https://convert.pdfshot.com/convert', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.PDFSHOT_API_KEY}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    templateId: 'your-template-id',
    variables: {
      customerName: 'Acme Corp',
      invoiceNumber: 'INV-001',
      items: [
        { name: 'Widget Pro', qty: 2, price: 50.00 },
        { name: 'Service Fee', qty: 1, price: 25.00 }
      ],
      total: 125.00
    },
    options: { format: 'A4' }
  })
})

const data = await response.json()

if (data.success) {
  console.log('PDF URL:', data.url)
}

Create templates in your Dashboard. See the Templates Guide for Handlebars syntax and variable schema options.

Downloading the PDF

After getting the signed URL, download the file:

// Get the PDF
const pdfResponse = await fetch(data.url)
const pdfBuffer = await pdfResponse.arrayBuffer()

// Save to file (Node.js)
import { writeFile } from 'fs/promises'
await writeFile('output.pdf', Buffer.from(pdfBuffer))

// Or send to browser (browser/Nuxt)
const blob = new Blob([pdfBuffer], { type: 'application/pdf' })
const downloadUrl = URL.createObjectURL(blob)
window.open(downloadUrl, '_blank')

Invoice Template

A complete example generating an invoice:

const invoiceHtml = `
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: system-ui, sans-serif; padding: 40px; }
    .header { display: flex; justify-content: space-between; margin-bottom: 40px; }
    .logo { font-size: 24px; font-weight: bold; }
    .invoice-number { color: #666; }
    table { width: 100%; border-collapse: collapse; margin: 20px 0; }
    th, td { padding: 12px; text-align: left; border-bottom: 1px solid #eee; }
    th { background: #f9f9f9; }
    .total { font-size: 18px; font-weight: bold; text-align: right; }
  </style>
</head>
<body>
  <div class="header">
    <div class="logo">ACME Corp</div>
    <div class="invoice-number">Invoice #12345</div>
  </div>

  <table>
    <thead>
      <tr>
        <th>Item</th>
        <th>Quantity</th>
        <th>Price</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Widget Pro</td>
        <td>2</td>
        <td>$50.00</td>
      </tr>
      <tr>
        <td>Service Fee</td>
        <td>1</td>
        <td>$25.00</td>
      </tr>
    </tbody>
  </table>

  <div class="total">Total: $125.00</div>
</body>
</html>
`

const response = await fetch('https://convert.pdfshot.com/convert', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.PDFSHOT_API_KEY}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    html: invoiceHtml,
    options: {
      format: 'Letter',
      margin: '0.75in',
      printBackground: true
    }
  })
})

Error Handling

Always handle errors gracefully:

async function convertToPdf(html, options = {}) {
  try {
    const response = await fetch('https://convert.pdfshot.com/convert', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.PDFSHOT_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ html, options })
    })

    const data = await response.json()

    if (!data.success) {
      throw new Error(`${data.error.code}: ${data.error.message}`)
    }

    return data.url
  } catch (error) {
    console.error('PDF conversion failed:', error.message)
    throw error
  }
}

Retry with Backoff

For production systems, implement retry logic:

async function convertWithRetry(html, options = {}, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await convertToPdf(html, options)
    } catch (error) {
      if (attempt === maxRetries) throw error

      // Exponential backoff: 1s, 2s, 4s
      const delay = Math.pow(2, attempt - 1) * 1000
      await new Promise(resolve => setTimeout(resolve, delay))
    }
  }
}