HTML to PDF via PHP : Convert HTML to PDF with PHP

You can convert HTML files to PDF format using PHP. In the tutorial below, we will show you how you can easily do this.

Try HTML2PDF Rocket for FREE

and start converting HTML to PDF instantly!

Code Examples to Convert HTML to PDF with PHP

    • Example #1 - How to use PHP to convert an HTML string to a PDF and save to disk

    • // Set parameters
      $apikey = 'YOUR-API-KEY';
      $value = 'Test PDF conversionThis is the body'; // can aso be a url, starting with http..
      
      // Convert the HTML string to a PDF using those parameters.  Note if you have a very long HTML string use POST rather than get.  See example #5
      $result = file_get_contents("https://api.html2pdfrocket.com/pdf?apikey=" . urlencode($apikey) . "&value=" . urlencode($value));
      
      // Save to root folder in website
      file_put_contents('mypdf-1.pdf', $result);
      
    • Example #2 - How to convert a PHP webpage to a PDF and stream it to a user as an attachment with PHP

    • Example also shows how you can download the file as an attachment, or show it inline in the web browser.

    • // Set parameters
      $apikey = 'YOUR-API-KEY';
      $value = 'Test PDF conversionThis is the body'; // can aso be a url, starting with http..
      
      // Convert the HTML string to a PDF using those parameters.  Note if you have a very long HTML string use POST rather than get.  See example #5
      $result = file_get_contents("https://api.html2pdfrocket.com/pdf?apikey=" . urlencode($apikey) . "&value=" . urlencode($value));
      
      // Output headers so that the file is downloaded rather than displayed
      // Remember that header() must be called before any actual output is sent
      header('Content-Description: File Transfer');
      header('Content-Type: application/pdf');
      header('Expires: 0');
      header('Cache-Control: must-revalidate');
      header('Pragma: public');
      header('Content-Length: ' . strlen($result));
      
      // Make the file a downloadable attachment - comment this out to show it directly inside the 
      // web browser.  Note that you can give the file any name you want, e.g. alias-name.pdf below:
      header('Content-Disposition: attachment; filename=' . 'alias-name.pdf' );
      
      // Stream PDF to user
      echo $result;
      
    • Example #3 - How convert an webpage to an image thumbnail using PHP

    • You can also convert an HTML string to a PDF by supplying the HTML directly. It can be as complex as you like and may include image references and stylesheeet information -- just make sure it is valid HTML

    •                                          
      // Set parameters
      $apikey = 'YOUR-API-KEY';
      $value = 'http://www.google.com'; // can aso be an HTML string
       
      // Convert the HTML string to a PDF using those parameters.  Note if you have a very long HTML string in $value use POST rather than get.  See example #5
      $result = file_get_contents("https://api.html2pdfrocket.com/pdf?apikey=" . urlencode($apikey) . "&value=" . urlencode($value) . "&OutputFormat=jpg");
      
      // Save to website folder - you can then stream to the user as a thumb or full size image
      file_put_contents('my_image.jpg', $result);
      
    • Example #4 - How to add a standard header or footer when converting HTML to PDF using PHP

    • Be sure to urlencode any extra parameters you send to the API, especially if they have funny HTML characters in them.

    •                                     
      // Set parameters
      $apikey = 'YOUR-API-KEY';
      $value = 'http://www.google.com'; // can aso be an HTML string
      
      // Note that by default all page margins are set to zero - so to make space in the bottom for the footer we set the bottom margin to a higher value
      $result = file_get_contents("https://api.html2pdfrocket.com/pdf?apikey=" . urlencode($apikey) . "&value=" . urlencode($value) . "&MarginBottom=30&FooterUrl=" . urlencode("https://html2pdfrocket.com/Examples/footer.htm"));
      
      // Output headers so that the file is downloaded rather than displayed
      // Remember that header() must be called before any actual output is sent
      // Make the file a downloadable attachment - comment this out to show it directly inside
      header('Content-Description: File Transfer');
      header('Content-Type: application/pdf');
      header('Content-Disposition: attachment; filename=' . 'alias-name.pdf' );
      header('Expires: 0');
      header('Cache-Control: must-revalidate');
      header('Pragma: public');
      header('Content-Length: ' . strlen($result));
      
      echo $result;
      
    • Example #5 - Using POST rather than GET when calling the API to convert HTML to PDF's

    • For long strings PHP may have a limitation with GET but you can POST the parameters instead using this syntax

    •                                     
      // Set parameters
      $apikey = 'YOUR-API-KEY';
      $value = 'HTML to PDF conversionA very long HTML body here..'; // can aso be a url, starting with http..
                                                 
      $postdata = http_build_query(
          array(
              'apikey' => $apikey,
              'value' => $value,
              'MarginBottom' => '30',
              'MarginTop' => '20'
          )
      );
      
      $opts = array('http' =>
          array(
              'method'  => 'POST',
              'header'  => 'Content-type: application/x-www-form-urlencoded',
              'content' => $postdata
          )
      );
      
      $context  = stream_context_create($opts);
      
      // Convert the HTML string to a PDF using those parameters
      $result = file_get_contents('https://api.html2pdfrocket.com/pdf', false, $context);
      
      // Save to root folder in website
      file_put_contents('mypdf-1.pdf', $result);
      
    • Example #6 - PDF Custom HTML Headers and Footers

    • Instead of using the Footer and Header Left/Right parameters which allow basic text, you can have a full HTML based header or footer by including a URL or a string to an HTML snippet in the HeaderUrl/HeaderHtml or FooterUrl/FooterHtml parameters. You can use page numbering, fonts, colours and images to lay out the header as you see fit here is an example of a standard HTML header. As by default page margins are set to 0 to allow full access to the page, make sure you specify are margin parameter large enough to allow the header or footer to fit. Make sure your header/footer code starts with <!DOCTYPE html> and include the <html> and <body> tags

    •                                     
      // Set parameters
      $apikey = 'YOUR-API-KEY';
      $value = 'http://www.w3.org/TR/html5/'; 
      
      // Make sure your margins are large enough to allow the header to fit                                           
      $postdata = http_build_query(
          array(
              'apikey' => $apikey,
              'value' => $value,
              'MarginBottom' => '30',
              'MarginTop' => '10',
              'HeaderUrl' => 'https://html2pdfrocket.com/examples/basicheader.html'
          )
      );
      
      $opts = array('http' =>
          array(
              'method'  => 'POST',
              'header'  => 'Content-type: application/x-www-form-urlencoded',
              'content' => $postdata
          )
      );
      
      $context  = stream_context_create($opts);
      
      // Convert the HTML string to a PDF using those parameters
      $result = file_get_contents('https://api.html2pdfrocket.com/pdf', false, $context);
      
      // Save to root folder in website
      file_put_contents('mypdf-1.pdf', $result);
      

      Here is an example custom HTML header file with page numbers. Do not forget the doctype.

      
      <!DOCTYPE html>
      <html>
      <head>
          <script>
              function subst() {
                  var vars = {};
                  var x = window.location.search.substring(1).split('&');
                  for (var i in x) { var z = x[i].split('=', 2); vars[z[0]] = unescape(z[1]); }
                  var x = ['frompage', 'topage', 'page', 'webpage', 'section', 'subsection', 'subsubsection'];
                  for (var i in x) {
                      var y = document.getElementsByClassName(x[i]);
                      for (var j = 0; j < y.length; ++j) y[j].textContent = vars[x[i]];
                  }
              }
          </script>
      </head>
          <body style="border:0; margin: 0;" onload="subst()">
              <table style="border-bottom: 1px solid black; width: 100%">
                  <tr>
                      <td class="section"></td>
                      <td style="text-align:right">
                          Page <span class="page"></span> of <span class="topage"></span>
                      </td>
                  </tr>
              </table>
          </body>
      </html>
      

      This is an example which hides the header on page 1 and 3

                                          
      <!DOCTYPE html>
      <html>
      <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
          <script>
              function subst() {
                  var vars = {};
                  var x = document.location.search.substring(1).split('&');
                  for (var i in x) { var z = x[i].split('=', 2); vars[z[0]] = unescape(z[1]); }
                  var x = ['frompage', 'topage', 'page', 'webpage', 'section', 'subsection', 'subsubsection'];
                  for (var i in x) {
                      var y = document.getElementsByClassName(x[i]);
                      for (var j = 0; j < y.length; ++j) y[j].textContent = vars[x[i]];
                      if (vars['page'] == 1) { // If page is 1, set FakeHeaders display to none
                          document.getElementById("FakeHeaders").style.display = 'none';
                      }
                      if (vars['page'] == 3) { // If page is 3, set FakeHeaders display to none
                          document.getElementById("FakeHeaders").style.display = 'none';
                      }
                  }
              }
          </script>
      </head>
      <body style="border:0;margin:0;" onload="subst()">
           <table style="border-bottom: 1px solid pink; width: 100%; margin-bottom:5px;" id="FakeHeaders">
               <tr>
                   <th>Your awesome table column header 1</th>
                   <th>Column 2</th>
                   <th style="text-align:right">
                   Page <span class="page"></span>/<span class="topage"></span>
                   </th>
              </tr>
          </table>
      </body>
      </html>
      
    • Example #7 - Batch/Asynchronous Process

    • For PDF conversion taking more than 30 seconds or input/output files more than 6 Mb, you need to use the batch/asynchronous parameters.

    •                                     
      <?php
      
          function PostToWeb($postData) : string {
      
              $apiUrl = 'https://api.html2pdfrocket.com/pdf';
              $opts = array('http' =>
                  array(
                  'method' => 'POST',
                  'header' => 'Content-type: application/x-www-form-urlencoded',
                  'content' => http_build_query($postData)
                  )
              );
      
              $context = stream_context_create($opts);
              $data = file_get_contents($apiUrl, false, $context);
              return $data;
          }
      
          // Set parameters
          $apikey = 'YOUR-API-KEY';
          $sHTMLToConvert = 'https://www.google.com';
      
          //as an alternative to polling, you can pass the webhook option parameter from your website
          //where the api could post back once the pdf file is ready
          //the same JSON Result is posted back with Status=Ready and the PDFLink
          $webhook = 'https://b2b-example.customer.com/my-webhook';
      
          $postdata = array(
              'apikey' => $apikey,
              'value' => $sHTMLToConvert,
              'Batch' => true,
              'Webhook' => $webhook
          );
      
          $data = json_decode(PostToWeb($postdata), true);
          $postdata['PdfToken'] = $data["PdfToken"];
          do
          {
              //polling every 30 seconds to check if the pdf file is ready
              $data = json_decode(PostToWeb($postdata), true);
              if ($data["Status"] === "Ready")
              {
                  $result = file_get_contents($data["PdfLink"]);
                  file_put_contents('myFile.pdf',$result);
                  break;
              }
      
              sleep(30);
          }while(true)
      ?>
                                                 
      

Need another PHP example? Would you mind dropping us a quick one line note to say which example you would have liked and we'll put the most commonly used ones here.

About HTML2PDF Rocket

Html2PDF Rocket is based on an open source technology. It is a free and easy to use web service to convert html webpages into PDF files or images. HTML2PDF Rocket is trusted by over 10,500 companies worldwide.

What is an HTML to PDF API?

An HTML to PDF API is a web service that will read your webpage and dynamically generate a PDF or an image. It will convert the contents of a webpage to a PDF file. It handles fairly complex documents and layouts, including images.

Why Convert HTML to PDF?

Converting HTML to PDF is great for reporting, creating brochures, and printing invoices. Just create one HTML or PHP webpage, and use it as a source to generate downloadable PDF or viewable PDF pages. PDF is a fixed-layout document created by Adobe Systems. It is a perfect document for downloading text or HTML content in a file, with consistent layout that does not depend on the device for viewing and does not require internet connection.

Try HTML2PDF Rocket for FREE

and start converting HTML to PDF instantly!

Conversion Tip


The number #1 reason a conversion fails to come out how you expect is because it contains references to external links or images that don't exist - or you are trying to link to localhost! If there is a conversion error, please check the page using your webbrowsers 'developer' network tab to ensure there are no 404 errors.