Published on 2nd Mar 2018 in PHP
When we develop a web application, it is often required to export html content or html table content in PDF files. Generally a developer is needed to change the HTML file to PDF document as per client requirement. It is also a very lengthy task to send HTML content to someone so, we must try to convert it into the document format. In this tutorial, we will see how to convert HTML to PDF document.
If you want to share an HTML webpage content then must change it to PDF format because PDF file is easy to share. You can convert HTML and XLS file to PDF easily with DocRaptop library. API integration is very easy, we just need to download its library and include on webpage.
DocRaptor is a useful PHP library to convert HTML and XLS file to PDF.
First download its zip file from website then include autoload.php on webpage
Then write some snippet to change Html to pdf. We write html content in setDocumentContent() method to convert into PDF. Making a PDF file to complete webpage is also very easy using DocRaptor library, we should have to pass webpage URL to setDocumentUrl() method. It allows you keep PDF name as you want. We write file name setName() method to generate DOC with given name.
You can also use url to download a file , replace setDocumentContent() method with setDocumentUrl() and pass your file url in it.
setDocumentType() method is used to mention in which format(pdf,xls or xlsx) you want to convert HTML content.
So, we have seen all method require to convert document into desired format.
Write snippet to generate PDF file from simple HTML code. Let’s us see.
<?php set_time_limit(0); require "docraptor-php-1.3.0/autoload.php"; $configuration = DocRaptorConfiguration::getDefaultConfiguration(); $configuration->setUsername("YOUR_API_KEY_HERE"); # this key works for test documents $docraptor = new DocRaptorDocApi(); $doc = new DocRaptorDoc(); $doc->setTest(true); $doc->setDocumentContent("<html><body>Hello World</body></html>"); $doc->setName("docraptor-php.pdf"); $doc->setDocumentType("pdf"); $create_response = $docraptor->createDoc($doc); /*download file*/ header('Content-Description: File Transfer'); header('Content-Type: application/pdf'); header('Content-Disposition: attachment; filename=example.pdf'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . strlen($create_response)); ob_clean(); flush(); echo($create_response); //you can also use readfile in place of echo ?>
This example download a pdf file with hello world content containg watermark.You can buy docraptor premium plan to get watermark free download. If you have any query regarding this article, feel free to comment.