PdfHelper
The PDFHelper provides APIs to work with PDF files in Magentrix. Using this class, developers can generate PDF files from HTML templates, merge and flatten PDF files, and add password protection to PDF files.
Converting HTML to PDF
Using this feature you can prepare HTML content with code or write an Active Template that can contain dynamic data from the database and convert the final output to PDF.
var htmlContent = "<html><body>Hello World!</body></html>";
var PdfHelper.ConvertHtmlToPdf(htmlContent);
Header and Footer Support
To support headers and footers, <PdfHeader> and <PdfFooter> tags can be used within your HTML template. Within these tags, {!PageNumber} & {!TotalPages} merge fields can be used to display the page number and the total number of pages.
Example HTML Template:
<html>
<head></head>
<body>
<PdfHeader>
<img src='https://www.mycompany.com/logo.png' alt='logo'/>
<div style='text-align:center'>You Company Name</div>
</PdfHeader>
<!-- PDF CONTENT GOES HERE -->
<PdfFooter>
<p style='text-align:center'>Page {!PageNumber} of {!TotalPages}</p>
<p>Company Address: …</p>
</PdfFooter>
</body>
</html>
Note*: All images references should be full path. Also note that Magentrix will not apply any CSS automatically; you need to apply your own styling.
Note*: When using adding duplicate images in merge fields, use the following format: {!Image}, {!Image}#1, ..., {!Image}#n.
Supported Methods:
| Name | Parameters: | Output |
|---|
| CombinePdfFiles | List<byte[]> files | byte[] |
| ConvertHtmlToPdf | String htmlContent,
PdfOptions options (optional parameter) | byte[] |
| ConvertHtmlToPdf | String htmlContent,
Object model,
PdfOptions options (optional parameter) | byte[] |
| ConvertHtmlToPdf | String htmlContent,
List<object> models,
PdfOptions options (optional parameter) | byte[] |
| PopulateFields | byte[] pdfFile,
Object model | byte[] |
| FlattenFile | byte[] pdfFile | byte[] |
| PasswordProtect | byte[] pdfFile,
String password | byte[] |
Example of Flattening Layers and Adding Password Protection to a PDF File:
public ActionResponse DownloadPdf()
{
var bytes = Storage.ReadFileBytes(documentId);
var flattenFileBytes = PdfHelper.FlattenFile(bytes);
var protectedFileBytes = PdfHelper.PasswordProtect(flattenFileBytes, "password");
return File(protectedFileBytes, MimeContentTypes.Pdf, "myPageFileName.pdf");
}
In order to convert HTML to PDF you have the following options:
var htmlContent = "<h1>Hi {!Firstname}</h1>";
//below shows the default values, note that this is an optional parametervar options = new PdfOptions {
IsLandscape = true,
PageSize = PdfPageSize.Letter,
MarginTop = 0.5f,
MarginLeft = 0.5f,
MarginBottom = 0.5f,
MarginRight = 0.5f;
};
var bytes = PdfHelper.ConvertHtmlToPdf(htmlContent, contact, options);