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
- 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.
- Install dompdf by running
composer require dompdf/dompdfin your Silverstripe project folder.
- Create the following routes.yml file in your mysillverstripeapp/app/_config folder and PDFController.php in your mysillverstripeapp/app/src folder.
- 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
- Run dev/build and visit http://yoursite/admin/my-data-objects/ to add new objects.
- Click on the link for the created data object(s).
- 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.