I've had a few projects where we had the need to generate dynamic PDF's for one purpose or the other. To meet such requirements, I've built a general purpose controller capable of making requests to Sitecore as the current user and taking the resulting HTML and running it through an HTML to PDF generator and returning the resulting PDF to the user.
All the code to get this to work is in a self-contained Helix Feature called "PDF" in Sitecore foundation. As it has minimal dependencies, it should be fairly straightforward to integrate into any helix solution.
When installed, if you want to generate a pdf of a page in sitecore, make a request to the following path:
To provide flexibility in the output, I've added support for a number of parameters that get passed to Rotativa and wkHtmlToPdf. These include:
- name - file name of the PDF to serve.
- landscape - presence of this parameter indicates the pdf should be rendered as landscape
- Size - Rotativa Enum value for page Size. A0 - A9, B0 - B10, Letter, Legal, Tabloid, Ledger, Folio, Executive, C5E, Com10E, Dle
- width - width of the page in inches
- height - height of the page in inches
- nomargin - presence of this sets the margins to 0
- passauth - the presence of this parameters ensures the webrequest passes the cookies from the requestor to make the request as the user. Use this option if you're personalizing the page for the user or dependent on the current user's session.
- dss - presence of this sets the wkhtmltopdf options to disable smart shrinking
- sl - presence of this sets the option to save the pdf locally. Currently this path is fixed to : C:\inetpub\wwwroot\rms\Website\App_Data\tempPDFs and should only be used for troubleshooting
Generate PDF of Page with Default Options:
Generate Landscape PDF with no margin:
Generate PDF as Current User and Fix and set page Type to Tabloid
Please note that the actual pdf generation is done using Rotativa, an open source library for ASP.Net that wraps wkhtmltopdf, a command line utility that does the actual pdf generation. As this is somewhat resource intensive, be aware, that I have seen this spike server CPU's if generating many pdf's at once. Make sure you understand the performance characteristics of your use case, and scale your environments accordingly. Alternatively, offload PDF requests to a dedicated instance or farm, or use a third party cloud hosted pdf generation tool.