Getting started overview

This guide provides a focused walkthrough for developers to quickly begin using the Html2PDF API. It covers the essential steps from account creation and credential retrieval to executing a first successful API request. Html2PDF offers a service for converting HTML content into PDF documents, useful for tasks such as automated report generation, invoice creation, and the conversion of web pages for print (Html2PDF documentation portal). The API is designed to be accessible via standard HTTP POST requests, with extensive customization options for the generated PDF output, including headers, footers, and page dimensions.

Before proceeding, ensure you have a basic understanding of making HTTP requests and handling API responses in your preferred programming language. Html2PDF provides documentation with code examples in PHP, Node.js, Python, and Ruby. While these SDKs simplify interaction, the underlying mechanism is a direct API call.

Quick Reference Steps

The following table summarizes the key steps to get started with Html2PDF:

Step What to Do Where
1. Sign Up Create a free Html2PDF account. Html2PDF homepage
2. Get API Keys Locate your unique API key in your account dashboard. Html2PDF dashboard > API Keys
3. Prepare Request Construct an HTTP POST request with your HTML content and API key. Your development environment
4. Send Request Execute the POST request to the Html2PDF API endpoint. Your application code
5. Process Response Handle the API response, typically a PDF file. Your application code

Create an account and get keys

To begin using Html2PDF, you must first create an account on their platform. A free tier is available, which includes up to 250 conversions per month, allowing developers to test and integrate the API without initial cost (Html2PDF pricing page).

Account Creation

  1. Navigate to the Html2PDF website.
  2. Look for a "Sign Up" or "Get Started Free" button, typically found in the header or prominent sections of the homepage.
  3. Follow the prompts to register, providing an email address and creating a password. You may need to verify your email address.

Obtaining API Keys

Upon successful registration and login, you will be directed to your Html2PDF dashboard. Your API key is a crucial credential that authenticates your requests to the Html2PDF API. It functions similarly to how other services like Stripe API keys or Google Maps API keys are used for authentication.

  1. From your dashboard, locate the section related to "API Keys", "Settings", or "Developer Settings". The exact label may vary but it will be clearly identifiable.
  2. Your unique API key will be displayed. This key is sensitive and should be kept confidential. Do not expose it in client-side code or public repositories.
  3. Copy your API key. You will need to include this key in the headers or body of every request you send to the Html2PDF API for authentication.

It is good practice to store your API key securely, for example, using environment variables in your application, rather than hardcoding it directly into your source code.

Your first request

Once you have your API key, you can make your first request to the Html2PDF API. The core functionality involves sending an HTTP POST request to the API endpoint with the HTML content you wish to convert.

API Endpoint

The primary API endpoint for HTML to PDF conversion is typically:

POST https://api.html2pdf.com/v1/convert

Refer to the Html2PDF API reference documentation for the most current endpoint details and any regional variations.

Request Structure

Your request must include your API key for authentication and the HTML content for conversion. The API generally expects a JSON payload for configuration and HTML content, or raw HTML in the request body, depending on the specific endpoint and desired options.

Example: Node.js with axios

This example demonstrates how to make a basic conversion request using Node.js and the axios HTTP client. First, ensure you have axios installed: npm install axios.


const axios = require('axios');

const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
const htmlContent = `
  <!DOCTYPE html>
  <html>
  <head>
    <title>My First PDF</title>
    <style>
      body { font-family: Arial, sans-serif; margin: 40px; }
      h1 { color: #333; }
      p { line-height: 1.6; }
    </style>
  </head>
  <body>
    <h1>Hello, Html2PDF!</h1>
    <p>This is a sample HTML document converted to PDF using the Html2PDF API. This demonstrates a basic conversion without advanced options.</p>
    <p>The API can handle more complex layouts, CSS, and JavaScript for dynamic content, allowing for rich document generation.</p>
  </body>
  </html>
`;

async function convertHtmlToPdf() {
  try {
    const response = await axios.post('https://api.html2pdf.com/v1/convert', {
      html: htmlContent,
      options: { // Optional: Customize PDF output
        format: 'A4',
        margin: {
          top: '20mm',
          right: '20mm',
          bottom: '20mm',
          left: '20mm'
        },
        printBackground: true
      }
    }, {
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      responseType: 'arraybuffer' // Important for binary file response
    });

    // Save the PDF file
    const fs = require('fs');
    fs.writeFileSync('output.pdf', response.data);
    console.log('PDF generated successfully: output.pdf');
  } catch (error) {
    if (error.response) {
      console.error('API Error:', error.response.status, error.response.data.toString());
    } else {
      console.error('Request Error:', error.message);
    }
  }
}

convertHtmlToPdf();

Example: Python with requests

This Python example uses the requests library. Install it with: pip install requests.


import requests

api_key = 'YOUR_API_KEY' # Replace with your actual API key
html_content = """
  <!DOCTYPE html>
  <html>
  <head>
    <title>Python Generated PDF</title>
    <style>
      body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 50px; background-color: #f0f0f0; }
      h1 { color: #2c3e50; text-align: center; }
      p { color: #34495e; text-align: justify; }
      .container { max-width: 800px; margin: auto; padding: 20px; background: white; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); }
    </style>
  </head>
  <body>
    <div class="container">
      <h1>Hello from Python and Html2PDF!</h1>
      <p>This document demonstrates converting a more styled HTML snippet into a PDF using the Python requests library. The API handles the rendering of CSS and HTML structure effectively.</p>
      <p>Developers can specify various PDF options within the JSON payload, such as page size, margins, and whether to include background graphics, providing granular control over the final output.</p>
    </div>
  </body>
  </html>
"""

url = 'https://api.html2pdf.com/v1/convert'
headers = {
    'Authorization': f'Bearer {api_key}',
    'Content-Type': 'application/json'
}
data = {
    'html': html_content,
    'options': {
        'format': 'Letter',
        'landscape': False,
        'displayHeaderFooter': True,
        'headerTemplate': '<div style="font-size: 10px; text-align: center; width: 100%; border-bottom: 1px solid #eee; padding-bottom: 5px;">Document Header</div>',
        'footerTemplate': '<div style="font-size: 10px; text-align: right; width: 100%; border-top: 1px solid #eee; padding-top: 5px;">Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>'
    }
}

try:
    response = requests.post(url, headers=headers, json=data, stream=True)
    response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)

    # Save the PDF file
    with open('output_python.pdf', 'wb') as f:
        for chunk in response.iter_content(chunk_size=8192):
            f.write(chunk)
    print('PDF generated successfully: output_python.pdf')

except requests.exceptions.HTTPError as errh:
    print(f"HTTP Error: {errh}")
    print(f"Response body: {errh.response.content.decode()}")
except requests.exceptions.ConnectionError as errc:
    print(f"Error Connecting: {errc}")
except requests.exceptions.Timeout as errt:
    print(f"Timeout Error: {errt}")
except requests.exceptions.RequestException as err:
    print(f"Oops: Something Else {err}")

After executing either of these code snippets, you should find a new PDF file (output.pdf or output_python.pdf) in your project directory containing the rendered HTML content.

Common next steps

Once you have successfully generated your first PDF, consider these common next steps to further integrate and optimize your use of Html2PDF:

  • Explore advanced options: Review the API reference documentation for options like custom headers and footers, page numbering, landscape orientation, specific PDF formats (e.g., A4, Letter), and print media queries. These options provide granular control over the appearance and structure of the generated PDF.
  • Integrate with your application: Connect the Html2PDF API into your existing application workflows. This might involve generating invoices after an e-commerce transaction, creating reports from database queries, or converting user-generated content for archival purposes.
  • Handle dynamic content: If your HTML content is generated dynamically (e.g., from a database or user input), ensure proper sanitization and escaping to prevent injection vulnerabilities. Test how the API handles complex JavaScript or CSS within your HTML.
  • Error handling and logging: Implement robust error handling in your application to gracefully manage API failures, network issues, or invalid requests. Log detailed error messages to assist with debugging.
  • Monitor usage and billing: Keep track of your API usage through the Html2PDF dashboard to stay within your plan limits. Upgrade your plan if your conversion volume increases beyond the free tier or your current paid subscription (Html2PDF pricing details).
  • Security best practices: Ensure your API key is stored securely and transmitted over HTTPS. Never embed API keys directly in client-side code or public repositories. Consider rotating API keys periodically as a security measure.
  • Performance optimization: For high-volume applications, consider optimizing the HTML content to reduce processing time and file size. This might involve minifying CSS/JavaScript or optimizing images.

Troubleshooting the first call

Encountering issues during your first API call is common. Here are some troubleshooting steps:

  • Check API Key: Double-check that your API key is correct and included in the Authorization header or request body as specified by the Html2PDF documentation. An incorrect or missing key will result in authentication errors (e.g., 401 Unauthorized or 403 Forbidden).
  • Verify Endpoint URL: Ensure the API endpoint URL is accurate (e.g., https://api.html2pdf.com/v1/convert). Typos or outdated URLs can lead to 404 Not Found errors.
  • Content Type Header: Confirm that your Content-Type header is set correctly, typically application/json if you're sending a JSON payload, or text/html if sending raw HTML directly. Mismatched content types can cause the API to misinterpret your request.
  • Request Body Format: Ensure your request body is correctly formatted. If sending JSON, validate that it is valid JSON and contains the expected fields (e.g., html for the HTML content and an optional options object for PDF customization).
  • Network Issues: Check your network connection. Temporary network outages or firewall restrictions can prevent your application from reaching the Html2PDF API. Tools like curl or a browser's developer console can help diagnose connectivity.
  • HTML Syntax Errors: While Html2PDF is generally robust, malformed HTML can sometimes lead to unexpected rendering or errors. Validate your HTML content for basic syntax correctness using an HTML validator if you suspect this is the issue.
  • API Error Responses: Pay close attention to the HTTP status codes and error messages returned by the API. Html2PDF will typically provide descriptive error messages in the response body for issues like invalid parameters, exceeding rate limits, or account-specific problems. For example, a 429 Too Many Requests status code indicates you've hit your rate limit, similar to how AWS APIs handle rate limiting.
  • Timeout Errors: If your request takes too long to process, you might encounter a timeout. This can happen with very large or complex HTML documents. Consider simplifying the HTML or contacting support if timeouts are persistent for reasonable content.
  • Check Html2PDF Status Page: Occasionally, the Html2PDF service itself might experience issues. Check their official status page (usually linked from their documentation or homepage) for any reported outages or maintenance.
  • Consult Documentation: Re-read the relevant sections of the Html2PDF documentation, especially the API reference and troubleshooting guides, as they often contain solutions to common problems.