The Easiest Way to Convert HTML To PDF In PHP
October 17, 2017This article guides you how to use KoolReport to convert any HTML to PDF even if the HTML is embedded with Javascript and CSS.
About KoolReport
KoolReport is an intuitive and open source PHP Reporting Framework. It is born to make task of building data reports easier and faster. It supports various database connections, powerful data processing and stunning data visualization.
PDF Exporting is one of the cool packages created for KoolReport. The package is built to support KoolReport in exporting reports to PDF. However it can be used for general purpose of converting HTML to PDF. What makes this exporting solution stand out is the ability to support embedded CSS and Javascript beside pure HTML.
Hand-on
Step 1: Create two files MyPage.php and MyPage.view.php
mypage/
├── MyPage.php
├── MyPage.view.php
└── index.php
The MyPage.php contains MyPage
class which is derived from KoolReport
.
<?php
require "../koolreport/autoload.php";
class MyPage extends \koolreport\KoolReport
{
use \koolreport\export\Exportable;
}
The MyPage.view.php is put in the same folder with MyPage.php. This view file contains your content in form of HTML, CSS and Javascript that you want to export.
<html>
<head>
<title>Content that you want to convert to PDF</title>
</head>
<body>
<!-- CSS Style -->
<style>
p {font-size:20px;}
h1 {color:red}
</style>
<!-- Normal HTML content -->
<h1>Export HTML to PDF</h1>
<p>It is easy to convert HTML to PDF using KoolReport's Export package</p>
<p id="extra"></p>
<!-- Javascript embedded -->
<script type="text/javascript">
document.getElementById("extra").innerHTML = "Javascript is working";
</script>
<body>
</html>
Step 2: Export To PDF
To generate PDF file and push to browser so that users can download, you do:
<?php
// index.php
require "MyPage.php";
$mypage = new MyPage;
$mypage->export()
->pdf(array(
"format"=>"A4",
"orientation"=>"portrait"
))
->toBrowser("mypage.pdf");
Easy, is it? And if you want to save the file instead of pushing to browser, you do:
<?php
// index.php
require "MyPage.php";
$mypage = new MyPage;
$mypage->export()
->pdf(array(
"format"=>"A4",
"orientation"=>"portrait"
))
->saveAs("../my_folder/mypage.pdf");
It is all done. Super easy!
Export package
In above example, we demonstrated how to export HTML embedded with CSS and Javascript to PDF. The ability to run Javascript is very important and is the feature that you may not find in other HTML to PDF solutions. This feature allows you to include any kinds of javascript-based charts into your exported PDF. Here is an good example of exporting Javascript Google Charts to PDF.
You may get Export package separately or purchase the bundle of all our commercial packages, KoolReport Pro.
<3 koolreport team