View all our articles

Convert an HTML document to PDF from a URL in Python with aiohttp

In this guide, we'll show you how to convert HTML documents to PDFs using PDFShift's API. This is a straightforward process that can be accomplished with just a few lines of Python code.

import aiohttp, asyncio, json, base64

# You can get an API key at
api_key = 'sk_xxxxxxxxxxxx'

params = {
    'source': '',

response = None
    auth = base64.b64encode(

    async with aiohttp.ClientSession() as session:
        async with
            headers={'Authorization': f'Basic {auth}'},
        ) as response:
            if response.status >= 400:
                raise Exception('Invalid request: {}'.format(await response.text()))

            with open('result.pdf', 'wb') as f:

            print('The PDF document was generated and saved to result.pdf')
except asyncio.TimeoutError:
    raise Exception('The request took too long to process')
except aiohttp.ClientError as e:
    raise Exception(f'An error occurred: {e}')
except Exception as e:
    # We highly recommend you to handle exceptions. Often, PDFShift will provide you with a clear explanation about what happened.
    # Moreover, in case of error, no PDF are returned !
    raise Exception(f'An error occurred: {e}')

With this Python script, you can effortlessly convert HTML documents from a URL to PDF files using PDFShift's API. Happy coding!

For further details on the source property and its usage, please refer to our dedicated documentation.

We hope this guide was helpful. If you have any questions or noticed any issues on the code above,
feel free to drop us a line.