Convert HTML to PDF

Increase CMS content portability by rendering it as PDFs. Rendering content in PDF format is useful for menus, flyers, confirmations and more.

This tutorial will use Silverstripe CMS as a content management system and html generator. However, any CMS and template engine may be used.

Setting up your PDF controller

  1. Start with a fresh Silverstripe CMS project or open up an existing one. Getting started with Silverstripe CMS will teach you how to set up a development environment and create a Silverstripe project.
  2. Install dompdf by running composer require dompdf/dompdf in your Silverstripe project folder.
  3. Create the following routes.yml file in your mysillverstripeapp/app/_config folder and PDFController.php in your mysillverstripeapp/app/src folder.
  4. Run dev/build and visit http://yoursite/pdf and you should see a PDF with the heading "It works!".

Creating a data model for your PDF

Create a MyDataObject.php file in your mysilverstripeapp/app/src directory with the following code. This will create a model with a title, description and an image. This can be customized to fit your needs.

Create a MyDataObjectsModelAdmin.php file in your mysilverstripeapp/app/src directory with the following code. This creates a tab in the administrator interface that is used to manage your data objects.

Creating your PDF template

Create a templates folder in mysilverstripeapp/app directory and add a MyPDF.ss template file with the following code. The template will have access to MyDataObject's variables and files in the mysilverstripeapp/public directory (images, stylesheets etc.). The template bellow includes the mypdf.css stylesheet in mysilverstripeapp/public/css

The PDF can also be styled using inline styles (which are customizable with variables pertaining to MyDataObject). Please note that all CSS syntax is not supported and may render differently compared to an html page in your browser.

Remember to replace the base href with your host.

Updating your PDF controller

Replace the content of your current PDFController.php with the code bellow. The PDFController uses an id from the url, try to load that data object and render the PDF using its data. The controller also makes sure an id is provided and an object is found.

Managing your rendered objects

  1. Run dev/build and visit http://yoursite/admin/my-data-objects/ to add new objects.
  2. Click on the link for the created data object(s).
  3. The links be automatically inserted into Silverstripe templates using the data object method PDFLink.

A code repository with the above project can be found on Github.


Vad kan vi göra för dig?

Har du en bra idé eller ett problem som du behöver hjälp att lösa?
Ta gärna kontakt med oss för att se vad vi kan göra för er, och hur vi kan hjälpa er!

Kontakta oss