Simple PHP example code to convert HTML webpages to PDF

PDF Rocket is based on open source technology and is a free and easy to use web service to convert your HTML webpages into images or PDF files.

Especially great for reporting, brochures and invoicing - create one HTML or PHP webpage and use it as both as a source to generate your downloadable PDF or for users to view directly.

The service will read your webpage and dynamically generate a PDF or an image. It will handle fairly complex documents and layouts including images, although as always the simpler the better.

    • 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("http://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("http://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("http://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("http://api.html2pdfrocket.com/pdf?apikey=" . urlencode($apikey) . "&value=" . urlencode($value) . "&MarginBottom=30&FooterUrl=" . urlencode("http://www.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('http://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' => 'http://www.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('http://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>
      

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.

Get Started

Don't waste your day reinventing the wheel, be converting in 3 minutes from now

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 exis - 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.