NAV Navbar
javascript python php ruby java csharp go

Introduction

Welcome to the PDFShift API. This documentation contains all the details needed to use the API and how to convert documents from HTML to PDF.

You will find code samples in Shell, Javascript, Python and PHP.

Getting an API Key

In order to generate PDF without the PDFShift's watermark, you will need an API Key. You can request one by creating an account on PDFShift's website.

Once you have submitted the form, we will send you an email containing your API Key. You can also create other API Key if you want, to split your keys accross your project. This can be done via your Dashboard.

You can test and play with our API without an API Key. Simply don't provide a "Basic Auth" header and the request will be done, with the difference that a watermark will be applied to the document. Note that applying a watermark makes the generation slower, so you will have better result when using your API Key.

Authentication

Authenticate your account by including your secret key in API requests. You can manage your API keys in the Dashboard.

Authentication to the API is performed via HTTP Basic Auth. Provide your API key as the basic auth username value. The password is ignored and can be set to whatever you want (an empty string works fine).

Authorization: Basic your_api_key:

Rate limiting

Rate limiting is only forced for unauthenticated accounts with a limit of 2 requests per minutes.

As soon as you are authenticated, the restriction is lifted and you can convert as many documents as you want.

When reaching the rate limit, you will get an HTTP status code of 429.

Each request will contain three headers to let you know your usage:

# HTTP response from PDFShift's API will contain these three headers:

    X-RateLimit-Remaining: 30
    X-RateLimit-Limit: 45
    X-RateLimit-Reset: 1466368960
    
Key Explanation
X-RateLimit-Remaining Indicates the number of requests before hitting the rate limit.
X-RateLimit-Reset Indicates the number of requests you can make per minutes (always 45).
X-RateLimit-Reset Indicates when the rate limit will reset.

Errors

The PDFShift API uses the following error codes:

Error Code Meaning
400 Bad Request -- Your request is invalid. Often, it means a parameter was wrongly set.
401 Unauthorized -- No API key were found.
403 Forbidden -- The provided API key is invalid.
404 Not Found -- The page you tried to reach was not found.
405 Method Not Allowed -- The endpoint you tried to reach is not available with this HTTP method.
408 A timeout error occured when trying to convert a document.
429 Too Many Requests -- You sent too many request. Please see the Rate limiting section for more details.
500 Internal Server Error -- We had a problem with our server. Try again later.

Convert

General

This is the main endpoint of the PDFShift's API. The main idea is to pass a source document in HTML (either raw HTML or an URL) and get a PDF in return.

Many parameters are available to let you customize the resulting PDF to your needs.

HTTP Request

POST https://api.pdfshift.io/v2/convert

Parameters

Provide the parameters as a JSON object.

Parameter Type Default Description
source String or URL required Original document to convert to PDF. PDFShift will automatically detect if it's an URL and load it, or an HTML document and charge it.
You can also send an array of documents to convert if parallel conversions is enabled on your account. In that case, you will also need to provide the webhook parameters as this operation is asynchronous.
sandbox Boolean false Will generates documents that doesn't count in the credits. The generated document will come with a watermark.
encode Boolean false Will return the generated PDF in Base64 encoded format, instead of raw.
timeout Integer null If provided, will kill the page loading at a specified time without stopping with a TimeoutError. Value in seconds
wait_for String null Name of a function available globally. When present, PDFShift will wait for this function to return a truthy value (true, 1, a string, etc) or up to 30 seconds, then proceed to the conversion.
landscape Boolean false Will set the view in landscape mode instead of portrait
css String or URL null Will append this CSS styles to the document before saving it. Can be an URL or a String of CSS rules.
javascript String or URL null Will execute the given Javascript before saving the document. Can be an URL or a String of JS code.
disable_images Boolean false Images will not be included in the final document.
disable_javascript Boolean false Will not execute the javascript at all in the document
disable_links Boolean false The link in the document will not point anywhere.
disable_backgrounds Boolean false The final document will not have the background images.
remove_blank Boolean false Remove the last page if it is considered empty..
delay Integer 0 In milliseconds. Will wait for this duration before capturing the document. Up to 10 seconds max.
use_print Boolean false Use the print stylesheet instead of the general one.
format String A4 Format of the document. You can either use the standard values (Letter, Legal, Tabloid, Ledger, A0, A1, A2, A3, A4, A5) or a custom {width}x{height} value. For {width} and {height}, you can indicate the following units: in, cm, mm.
pages String null Pages to print. Can be one number (3), a range (1-5), a list (4,5,6) or a combination of both (1-3,6,7). If the number is higher than the real number of pages, that number will be ignored.
zoom Float 1 A value between 0 and 2. Allows you to increase the zoom in the document for specific purposes. 1 is the default zoom, lower is smaller, higher is bigger.
webhook String (URL) null An URL where we will send a POST request containing a JSON body similar to when you use the filename parameter. The JSON response will contain a URL key that points to your file, stored on Amazon S3.
margin String or Object null Empty spaces between the outer and the beginning of the content
auth Object null Object containing username and password for accessing password-protected content.
cookies Array null List of cookies you want to send along with the requests when loading the source. See the related part at the bottom of the document
http_headers Object null List of http headers that you can customize for a better end result.
header Object null Defines a custom header. See the "Header/Footer" section for more details.
footer Object null Same as header.
protection Object null Will add restrictions on the PDF document. See the #Protection part for more details
watermark Object null Add a watermark to the generated document. See the #Watermark part for more details.

Cookies

List of accepted parameters for the Cookie object.

Parameter Type Default Description
name String required Name of the cookie
value String ** required ** Value for the specified cookie
secure Boolean false If set to true, This cookie will only be available for secure (https) connections.
http_only Boolean false If set to true, this cookie will only be available to HTTP request only (no javascript).

Margin

You can define margin for the document (space between the limits of the document and the beginning of the content). You can either pass an object as defined below, or use a CSS like string, like the following:

Otherwise, you can use an object to directly target a specific margin, using the following:

Parameter Type Default Description
top Integer or String null Space between the top and the content.
right Integer or String null Space between the right and the content.
bottom Integer or String null Space between the bottom and the content.
left Integer or String null Space between the left and the content.

You can configure the aspect of your header and footer document using the following values.

Parameter Type Default Description
source String or URL null Element to add in the header/footer part of the document. You can use variables, indicated at the end of the document. PDFShift will automatically detect if it's an URL and load it, or an HTML data and charge it.
spacing Integer or String null A spacing between the header or footer and the content. For header, it's the space between the header and the beginning of the document. For the footer, it's the space between the end of the document and the bottom of the page.
start_at Integer 1 Display the header/footer starting at the given page. The number is 1-based.
IMPORTANT: You can not set different start_at value for the header and footer if they are higher than 1. For instance header.start_at = 1 and footer.start_at = 2 is possible, but header.start_at = 2 and footer.start_at = 3 is not supported.
Variable Description
{{date}} Formatted print date
{{title}} Title of the HTML document
{{url}} Page URL
{{page}} Current page
{{total}} Total number of pages

Protection

You can restrict access to your generated document using the following rules. The encryption is made in 128bits.

Parameter Type Default Description
author String null Document's author name
user_password String null A user who has the password will be able to view the document and perform operations allowed by the permission options
owner_password String null A user who has the password will have unlimited access to the PDF, including changing the passwords and permission options.
no_print Boolean false When set to true, printing will be disabled.
no_copy Boolean false When set to true, the possibility to copy any text will be disabled.
no_modify Boolean false When set to true, the possibility to modify the document will be disabled.

Watermark

You can add a watermark to your documents via three alternatives:

Each alternatives has a set of options, which is detailed here:

Via PDF

Parameter Type Default Description
source URL or Base64 encoded PDF content required You can provide the source either as an URL, or a base 64 encoded PDF content. Raw PDF content will be refused. We recommend you to send a one page PDF content because only the first page is used on each of your generated content.

Via Text

Parameter Type Default Description
text String required The text to display as watermark.
font_size Integer 16 The font size used.
font_family String Helvetica The font family used.
font_color String 000000 The color of the text.
font_opacity Integer 100 The opacity for the text.
font_bold Boolean false Set to true if you want the text bold.
font_italic Boolean false Set to true if you want the text in italic.
offset_x String center The X position. Can be either a String (left, center, right) or a number with unit (defaults to pixels. Allowed units are 'px', 'in', 'cm', 'mm', 'pt').
offset_y String middle The Y position. Can be either a string (top, middle, bottom) or a number with unit (defaults to pixels. Allowed units are 'px', 'in', 'cm', 'mm', 'pt').
rotate Integer -45 The degree for the rotated element.

Via Image

Parameter Type Default Description
image URL or Base64 encoded image content required The image to display as watermark.
offset_x String center The X position. Can be either a String (left, center, right) or a number with unit (defaults to pixels. Allowed units are 'px', 'in', 'cm', 'mm', 'pt').
offset_y String middle The Y position. Can be either a string (top, middle, bottom) or a number with unit (defaults to pixels. Allowed units are 'px', 'in', 'cm', 'mm', 'pt').
rotate Integer -45 The degree for the rotated element.

Misc

When converting a document, if successful, the HTTP response from PDFShift's API will contain the following header:

Header Description
X-Response-StatusCode The status code from your URL source, when an URL is provided. This can be useful to ensure the URL worked correctly.

Webhooks

If the webhook parameter is defined, the call to PDFShift's API will return a Queued response along with a 202 status code, like the following:

{"queued": true}

Once the processing has been done, we will send a POST request to your webhook endpoint, containing a JSON payload with the URL to your converted document, stored at Amazon S3 (for two days).

Here's a sample of the payload we will send you:

{
        "duration": 3121.766417985782,
        "filesize": 259972,
        "response": {
            "duration": 2562,
            "status-code": 200
        },
        "success": true,
        "url": "https://s3.amazonaws.com/pdfshift/d/2/2019-05/99c456250a01448686d81752a3fb5beb/15466098-8368-49e1-ac33-ff4c3941a0df.pdf"
    }
    














In case there is any error while processing your document, we will instead send you a payload containing an error key, like the following:

{
        "error": {
            "code": 400,
            "error": "The requested page took too long to load.",
            "identifier": "A74",
            "success": false
        }
    }
    

Use cases

Converting an URL

import requests

    response = requests.post(
        'https://api.pdfshift.io/v2/convert',
        auth=('your_api_key_here', ''),
        json={'source': 'https://www.example.com'},
        stream=True
    )

    response.raise_for_status()

    with open('result.pdf', 'wb') as output:
        for chunck in response.iter_content(chunck_size=1024):
            output.write(chunck)
    

The above command returns a PDF in binary format.

This endpoint the given URL to PDF.

Saving the document to Amazon S3

import requests

    response = requests.post(
        'https://api.pdfshift.io/v2/convert',
        auth=('your_api_key_here', ''),
        json={
            'source': 'https://www.example.com',
            'filename': 'result.pdf'
        }
    )

    response.raise_for_status()

    json_response = response.json()
    # The URL to the document is at json_response['url]
    

The above command returns JSON structured like this:

{
    "success": true,
    "url": "https://s3.amazonaws.com/pdfshift/d/2/2019-02/47fc3918791a4818a6bf655cfb63c96e/result.pdf",
    "filesize": 13370,
    "duration": 5
    }
    

By passing the "filename" parameter, the endpoint won't return the binary PDF, but an URL from Amazon S3 where the document will be stored for 2 days before being automatically deleted.

This can be useful if you don't want to download a large PDF to your server to then serve it to your users, but instead redirect them directly to that document.

Accessing secured pages

import requests

    response = requests.post(
        'https://api.pdfshift.io/v2/convert',
        auth=('your_api_key_here', ''),
        json={
            'source': 'https://httpbin.org/basic-auth/user/passwd',
            'auth': {
                'username': 'user',
                'password': 'passwd'
            }
        },
        stream=True
    )

    response.raise_for_status()

    with open('result.pdf', 'wb') as output:
        for chunck in response.iter_content(chunck_size=1024):
            output.write(chunck)
    

The above command returns a PDF in binary format.

If your documents are located inside a protected area requiring a Basic Auth access, you can use the auth parameter from PDFShift's API to connect to your website. Here's an example on how to do so.

Using Cookies

import requests

    response = requests.post(
        'https://api.pdfshift.io/v2/convert',
        auth=('your_api_key_here', ''),
        json={
            'source': 'https://httpbin.org/cookies',
            'cookies': [{'name': 'session', 'value': '4cb496a8-a3eb-4a7e-a704-f993cb6a4dac'}]
        },
        stream=True
    )

    response.raise_for_status()

    with open('result.pdf', 'wb') as output:
        for chunck in response.iter_content(chunck_size=1024):
            output.write(chunck)
    

The above command returns a PDF in binary format.

On the contrary, if your endpoint requires a more advanced authentication format, like a PHP session. You can add cookies to the parameter to simulate an active session.

This can be easily done with the cookies parameter from our API.

import requests

    response = requests.post(
        'https://api.pdfshift.io/v2/convert',
        auth=('your_api_key_here', ''),
        json={
            'source': 'https://www.example.com',
            'footer': {
                'source': '<div style="font-size: 12px">Page {{ "{{page}}" }} of {{ "{{total}}" }}</div>',
                'spacing': '50px'
            }
        },
        stream=True
    )

    response.raise_for_status()

    with open('result.pdf', 'wb') as output:
        for chunck in response.iter_content(chunck_size=1024):
            output.write(chunck)
    

The above command returns a PDF in binary format.

One frequent action when converting a web document to PDF is to add header and footer. This is useful to add page number for instance, or the name of your company at the top of each pages.

This is easily done in PDFShift with the header/footer parameter.

Sending an invoice by email

from django.core.mail import EmailMultiAlternatives
    from django.shortcuts import redirect
    import requests

    document = open('invoice.html', 'r')
    document_content = document.read()
    document.close()

    response = requests.post(
        'https://api.pdfshift.io/v2/convert',
        auth=('your_api_key_here', ''),
        json={'source': document_content}
    )

    response.raise_for_status()

    text_content = None
    with open('templates/emails/invoice.txt', 'r') as f:
        text_content = f.read()

    html_content = None
    with open('templates/emails/invoice.html', 'r') as f:
        html_content = f.read()

    msg = EmailMultiAlternatives("Thank you for your purchase", text_content, 'billing@your-site.tld', ['customer@gmail.com'])
    msg.attach_alternative(html_content, "text/html")
    msg.attach('invoice.pdf', response.content, 'application/pdf')
    msg.send()

    return redirect('/thank-you')
    

The above command returns a PDF in binary format.

Here's a complete example of how PDFShift can be integrated in one of your project.

A frequent use case is to use PDFShift to convert a locally generated invoice made in HTML (displayed in the back-office of your customer), converted in PDF and then sent by email.

Credits

Credits status

Sending a GET request to the credits endpoint returns JSON structured like this:

{
    "total": 1000,
    "used": 150,
    "remaining": 850
    }
    

Simply send a GET request toward https://api.pdfshift.io/v2/credits/ to know in details your credits usage for your account.

Don't forget to set your API key as "Basic auth".

HTTP Request

GET https://api.pdfshift.io/v2/credits/

Support

If you need any help converting your HTML documents, feel free to reach out to our support team.

We are available via support@pdfshift.io and we will do our best to help you convert your documents the way you want to.