Silverstripe PDFs
Increase portability of Silverstripe CMS content by rendering it as PDFs. Rendering CMS content in PDF format is useful for menus, flyers, confirmations and more
Setting up your PDF controller
- Start with a fresh Silverstripe CMS project or open up an existing one. Docker and Silverstripe will teach you how to set up a development environment and create a Silverstripe project.
- Install dompdf by running composer require dompdf/dompdf in your Silverstripe project folder.
- Create the 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 the rendered data object
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.
Updating your PDF controller
Replace the content of your current PDFController.php with the code bellow. The PDFController now receive 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.