Generate a PDF from a Container
Last updated
Last updated
The recommended way to generate a PDF document with Appfarm Create is by using the Generate Document action node. Sometimes though, for example when you'd like to include charts, it may not be possible to create the required PDF using Generate Document.
In this case, you could design your document in a View and then make use of the browser's built-in print functionality to print the page as a PDF. You can even trigger the browser's print dialog to open using the Open Print Dialog action node.
A third option, detailed in this guide, is to use the Run Code action node to generate a PDF based on the contents of a Container. This method relies on the external JavaScript library html2pdf to convert the Container to an image and then generate a PDF which is automatically downloaded.
Important
This setup uses an external JavaScript library provided by a third-party that you use at your own risk. Appfarm does not provide support for third-party libraries and will not be responsible for any issues, conflicts, errors, or damages that may occur as a result of their use.
Example
A working example is available in our Showroom.
In a new or existing View:
Add a new Container that will hold the contents of the document.
In the Container's component properties, enter an Element ID. For example, report
. Don't use spaces.
In the Container's style properties, enter an explicit Width in pixels.
Fill the Container with your desired UI components and configure them just as you normally would when building a View.
Add a new Button, outside of the Container, that will be used to trigger the PDF generation.
Head to https://ekoopmans.github.io/html2pdf.js/ to find the CDN URL for the latest version of the html2pdf JavaScript library.
Then, under Environments, for each environment in which you'd like to generate PDFs, add a new custom header tag. Use the following values:
Property | Value |
---|---|
Description |
|
Tag Type |
|
Script URL | The CDN URL of the script. For example: |
The above properties are enough to use the library in your app. You might want to consider adding custom attributes such as integrity
with the hash provided on the library's website.
Click the On Click event handler of the Button created in step 1 to open the Select Action dialog.
Click Create New Action.
Enter a name for the action.
Add a Run Code action node.
Click Code and paste in the code below. Make sure to change the Element ID to match the one you entered in step 1 and configure any other options. This code sets the following basic options, but more options are available:
A 10mm margin on all sides
A filename for the generated PDF.
The width of the Container configured in step 1.
Click OK.
Now you can preview your app and click the button to generate a PDF.