Document Automation Made Simple

How to convert HTML + CSS to PDF using PHP?

It can be a real struggle when trying to convert an HTML file or a web page to a PDF document using PHP. Many developers worldwide choose to leave the complex logic for a 3rd party service specializing in this field to keep the project clean and easy to maintain. Using our ConvertAPI PHP library the conversion can be done in just a couple lines of code.

Kostas, Developer

HTML to PDF conversion may seem like a straightforward task, but it can be challenging to implement and maintain, thereby complicating your project. Thus, many nowadays solutions come from third-party, rigid, and robust service providers. We are going to use a simple API call to take care of the conversion.

Let's begin by installing a ConvertAPI PHP Client:

composer require convertapi/convertapi-php

Note: if you don't want to use Composer, please follow the manual installation guide.

Once you have the library installed, simply run this code snippet:

ConvertApi::setApiCredentials('api_token');
$result = ConvertApi::convert('pdf', [
        'File' => '/path/to/my_file.html',
    ], 'html'
);
$result->saveFiles('/path/to/result/dir');

That's it, just replace your API Token and path to your file, and it should work straight away.

If you want a more advanced conversion with control over whether to run javascript on the web page, remove cookie warning popups, ads, etc please refer to the complete guide including an interactive demo. You will also find an auto-generated snippet at the bottom of the page!

However, this particular conversion accepts only an HTML file, and all of the CSS and JavaScript should be inlined in the document. If you want to convert a web page that is hosted and accessible online by passing a web page URL instead of an HTML file, please refer to the WEB to PDF guide.

Happy coding!


Related converters

Ready to Streamline Your File Conversions?