Why PDF.co API

Convert HTML to PDF
PDF.co API helps you convert your HTML to PDF files in seconds. Here HTML can be either your website URL or any physical HTML file. Newly generated PDF files are of high quality and ready for printing and archiving. The API can generate PDF from HTML in Python, JavaScript, C#, C++, cURL, PHP, and any programming language you need. Full documentation of PDF.co API is here.

PDF.co API runs on the secure and certified Amazon AWS infrastructure. All data transfers are encrypted by SSL/TLS encryption. See the security page for details. The on-prem version can run on any hosting provider and cloud storage of your choice.

Battle-tested by thousands of production users. Our engines are tested in production by thousands of enterprise users.


Credits-based system

For every page/image processed credits are reduced on your account. You can purchase credits with one-time payments or subscribe for monthly credits. Separate methods like uploading, background job also consume credits. (cloud version only) You can check how many credits are left using credits property in output or and remaining credits property to check how many credits are left. For details please explore your API logs.

Asynchronous mode

It is supported so you can process large files and documents with hundreds of pages in the cloud.

On-Prem API Server and On-Prem SDK are available

Enterprise users may obtain ByteScout API Server for use on their own server (Windows Server). The On-Prem version is available here.


HTML to PDF API Sample & Demo

This sample and demo below aim to give you the technical detail on how you can convert your website URL to a PDF file using PDF.co API. So, let’s get started.

So for the demo, I am going to use a Wikipedia page.

And then we’ll use the below code snippet which is written in different programming languages which simply converts the above page content into a PDF file using our PDF.co API. The source web page and the final output will look something like this.

HTML To PDF API Input And Output

Now before we look into the code, let me walk you through the PDF.co API endpoint documentation which we are going to use in our demo application.


URL: https://api.pdf.co/v1/pdf/convert/from/url
Method: POST


Key Value Description
x-api-key {{x-api-key}} Required. API key for PDF.co. Get yours at https://pdf.co/

 Now after setting the above endpoint and headers, we need to pass/set the following parameters:

Parameter Description
Url* Link to input HTML file or website page to be converted.
margins (optional) set to css style margins like 10px, 5mm, 5in for all sides or “5px 5px 5px 5px”
paperSize (optional) Can be Letter, A4, A5, A6 or custom size in pixels, mm or inches with width and height separated by space like this: “200 300”, “200px 300px”, “200mm 300mm”, “20cm 30cm”
orientation (optional) set to Portrait or Landscape. Portrait by default.
true by default. Set to false to disable printing of background.
header (optional) Set to HTML for the header to be applied on every page at the header.
Set an HTML for the footer to be applied on every page at the bottom.

Now it’s time to write some code.

Javascript (Node.js) Code Snippet

var https = require("https");
var path = require("path");
var fs = require("fs");

// The authentication key (API Key).
const API_KEY = "***********************************";

// URL of web page to convert to PDF document.
const SourceUrl = "https://en.wikipedia.org/wiki/Style_sheet_(web_development)";
// Destination PDF file name
const DestinationFile = "./result.pdf";

// Prepare request to `Web Page to PDF` API endpoint
var queryPath = `/v1/pdf/convert/from/url`;
// JSON payload for api request
var jsonPayload = JSON.stringify({
    name: path.basename(DestinationFile), url: SourceUrl

var reqOptions = {
    host: "api.pdf.co",
    method: "POST",
    path: queryPath,
    headers: {
        "x-api-key": API_KEY,
        "Content-Type": "application/json",
        "Content-Length": Buffer.byteLength(jsonPayload, 'utf8')
// Send request
var postRequest = https.request(reqOptions, (response) => {
    response.on("data", (d) => {
        // Parse JSON response
        var data = JSON.parse(d);       
        if (data.error == false) {
            // Download PDF file
            var file = fs.createWriteStream(DestinationFile);
            https.get(data.url, (response2) => {
                .on("close", () => {
                    console.log(`Generated PDF file saved as "${DestinationFile}" file.`);
        else {
            // Service reported error
}).on("error", (e) => {
    // Request error

// Write request data

You can find this demo Javascript code on our GitHub repository.

PHP Code Snippet

// Get submitted form data
$apiKey = $_POST["apiKey"]; // The authentication key (API Key).
$sourceUrl = $_POST["sourceUrl"];

// Prepare URL for `Web Page to PDF` API call
$url = "https://api.pdf.co/v1/pdf/convert/from/url";

// Prepare requests params
$parameters = array();
$parameters["name"] = "result.pdf";
$parameters["url"] = $sourceUrl;

// Create Json payload
$data = json_encode($parameters);

// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-type: application/json"));
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

// Execute request
$result = curl_exec($curl);

if (curl_errno($curl) == 0)
    $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
     if ($status_code == 200)
        $json = json_decode($result, true);
        if ($json["error"] == false)
            // Get URL of generated PDF file
            $resultFileUrl = $json["url"];

            // Display link to the file with conversion results
            echo "<div>## Conversion Result:<a href='" . $resultFileUrl . "' target='_blank'>" . $resultFileUrl . "</a></div>";

            // Display service reported error
            echo "<p>Error: " . $json["message"] . "</p>";

        // Display request error
        echo "<p>Status code: " . $status_code . "</p>";
        echo "<p>" . $result . "</p>";

    // Display CURL error
    echo "Error: " . curl_error($curl);

// Cleanup

You can find this demo PHP code on our GitHub repository.

Python Code Snippet

import os
import requests # pip install requests

# The authentication key (API Key).
API_KEY = "**********************************************"

# Base URL for PDF.co Web API requests
BASE_URL = "https://api.pdf.co/v1"

# URL of web page to convert to PDF document.
SourceUrl = "https://en.wikipedia.org/wiki/Style_sheet_(web_development)"
# Destination PDF file name
DestinationFile = ".\\result.pdf"

def main(args = None):
    convertHTMLToPDF(SourceUrl, DestinationFile)

def convertHTMLToPDF(uploadedFileUrl, destinationFile):
    """Converts HTML to PDF using PDF.co Web API"""
    # Prepare requests params as JSON
    # See documentation: https://apidocs.pdf.co
    parameters = {}
    parameters["name"] = os.path.basename(destinationFile)
    parameters["url"] = uploadedFileUrl

    # Prepare URL for 'HTML To PDF' API request
    url = "{}/pdf/convert/from/url".format(BASE_URL)

    # Execute request and get response as JSON
    response = requests.post(url, data=parameters, headers={ "x-api-key": API_KEY })
    if (response.status_code == 200):
        json = response.json()

        if json["error"] == False:
            #  Get URL of result file
            resultFileUrl = json["url"]           
            # Download result file
            r = requests.get(resultFileUrl, stream=True)
            if (r.status_code == 200):
                with open(destinationFile, 'wb') as file:
                    for chunk in r:
                print(f"Result file saved as \"{destinationFile}\" file.")
                print(f"Request error: {response.status_code} {response.reason}")
            # Show service reported error
        print(f"Request error: {response.status_code} {response.reason}")

if __name__ == '__main__':

You can find this demo Python code on our GitHub repository.

C# Code Snippet

static void Main(string[] args)
    // Get your own by registering at https://app.pdf.co/documentation/api
    string API_KEY = "***********************************";

    // URL of web page to convert to PDF document.
    string SourceUrl = "https://en.wikipedia.org/wiki/Style_sheet_(web_development)";
    // Destination PDF file name
    string DestinationFile = @".\result.pdf";

    using (WebClient webClient = new WebClient())
             // Set API Key
             webClient.Headers.Add("x-api-key", API_KEY);

             // URL for `Web Page to PDF` API call
             string apiEndpoint = "https://api.pdf.co/v1/pdf/convert/from/url";

             // Prepare requests params as JSON
             Dictionary<string, object> requestBody = new Dictionary<string, object>();
             requestBody.Add("name", Path.GetFileName(DestinationFile));
             requestBody.Add("url", SourceUrl);

             // Convert dictionary of params to JSON
             string jsonPayload = JsonConvert.SerializeObject(requestBody);

             // Execute POST request
             var response = webClient.UploadString(apiEndpoint, "POST", jsonPayload);

             // Parse JSON response
             JObject json = JObject.Parse(response);

             if (json["error"].ToObject<bool>() == false)
                         // Get URL of generated PDF file
                         string resultFileUrl = json["url"].ToString();

                         // Download PDF file
                         webClient.DownloadFile(resultFileUrl, DestinationFile);


             // Open generated PDF file
             Console.WriteLine("Press any key...");

Now let’s see this program in action.


You can find this source code on our GitHub repository.

Please find code snippets to extract HTML to PDF in C# here.

Please find code snippets to extract HTML to PDF in Java here.

Please find code snippets to extract HTML to PDF in Python here.

Please find code snippets to extract HTML to PDF in JavaScript here.

Please find code snippets to extract HTML to PDF in PHP here.

Please find code snippets to extract HTML to PDF in VB.NET here.

Please find code snippets to extract HTML to PDF in cURL here.

Please find code snippets to extract HTML to PDF here.

Sign Up

If you are not from a programming background then also you can easily automate your PDF operations through business automation platforms such as Zapier, Integromat, and hundreds of others. PDF.co API uses lossless compression which makes your PDF compact in size. As PDF is using high-quality images and high-quality text, the lossless algorithm helps to compress high-quality text. Actually, lossless compression is a compression type that is used by PDF documents containing text. Its algorithm creates reference points for textual patterns, stores them in a catalog, and then brings them back to your file.

PDF.co API can be used by software developers from programming languages such as Javascript, Python, PHP, Java, C#, Visual Basic, ASP.NET, Powershell, CLI. We have hundreds of ready-to-copy-paste source code samples for other features also! You can explore our Hundreds of Source Code Sample Apps on Github. Stay tuned and stay updated with us to get more of these.

Related Samples: