HTML to PDF Converter Element |
The HtmlToPdfElement graphic element renders a web page or an HTML string into a page or a template of a PDF document, with the Chromium engine. It lets you choose the position and the size of the content rendered from HTML, and add many HTML to PDF conversions to the same document.
When the rendered content spans several pages, the AddElementResult object returned after the element is added to a page or template tells the index of the last page and the rectangle the content occupies on it, and RenderedPagesRectangles gives the rectangle drawn on each page.
The HtmlToPdfElement offers many constructors that call the following two constructors with default values for converting a URL or an HTML string to PDF:
public HtmlToPdfElement(float x, float y, float width, float height, string urlToConvert, int htmlViewerWidth, int htmlViewerHeight); public HtmlToPdfElement(float x, float y, float width, float height, string htmlStringToConvert, string htmlStringBaseURL, int htmlViewerWidth, int htmlViewerHeight);
The first constructor creates a URL to PDF element at the specified x and y coordinates with the specified width and height. The width and height in pixels of the browser window the page is laid out in are given by the htmlViewerWidth and htmlViewerHeight parameters.
x - The x position in points where the rendered content is placed.
y - The y position in points where the rendered content is placed.
width - The destination width in points for the rendered content. If the width is negative, the destination width is the width available in the page or template.
height - The destination height in points for the rendered content. If the height is negative, the height is determined automatically so all the content is rendered.
urlToConvert - The URL to convert to PDF.
htmlViewerWidth - The browser window width in pixels. The default value is 1024 pixels. The effect of this parameter is the same as viewing the HTML page in a browser window with the specified width. Content wider than the window is cut at its right edge, unless FitWideContent is set.
htmlViewerHeight - The browser window height in pixels. A negative value, the default, lets the height be determined from the content. With ClipHtmlView set, a positive height is a fixed window height and the content below it is left out of the PDF.
The second constructor creates an HTML string to PDF element at the specified x and y coordinates with the specified width and height.
htmlStringToConvert - The HTML string converted to PDF.
htmlStringBaseURL - The full URL of the page the string was taken from, used to resolve the images and CSS files referenced by a relative URL in the HTML string. When it is an http or https URL, the string is loaded as the page at that URL, so its scripts, fonts and cookies work as they do for that page. When this parameter is null, no base URL is used.
Below is a sample code that adds a web page and, after it, an HTML string to a PDF page with HtmlToPdfElement objects:
using (Document document = new Document()) { PdfPage page = document.AddPage(); // a web page rendered at the top left corner of the page, with the width of the // page and the height it needs; the content continues on new pages when it is // longer than a page HtmlToPdfElement webPage = new HtmlToPdfElement(0, 0, "https://www.example.com/article"); AddElementResult result = page.AddElement(webPage); // an HTML string after it, with a base URL for its relative images and style // sheets HtmlToPdfElement note = new HtmlToPdfElement(0, result.EndPageBounds.Bottom + 20, "<p style='color:gray'>Printed from <img src='logo.png' height='16'>" + " example.com</p>", "https://www.example.com/"); document.Pages[result.EndPageIndex].AddElement(note); document.Save("article.pdf"); }
AddElementAsync starts the render of an HTML element at once and places it after the elements added before it, so several HTML elements added that way render at the same time.
An HtmlToPdfElement continues on the next pages when its content does not fit in the room left on the page - when it has no height of its own, or a height taller than that room - wherever it starts on the page, and its last page is drawn only down to where the content ends. A height taller than the room left stops the element once that much height is drawn. AddElement returns the page and the rectangle where the element ended, to place the next element right below it. This is ManagedContentTrimming (default true); set it to false to draw only what fits in the room left on the page. ManagedContentTrimmingMode chooses how the end of the content is found (Ink, the default, or Marker). A fixed window height (ClipHtmlView with an HtmlViewerHeight) keeps the element on one page.
The element continues on the page that follows when the document already has one, and adds a page otherwise. An added page has the size, orientation, margins and rotation of the page it continues. In a document loaded from an existing PDF file, the element is drawn only on the page it is added to.
MaxConversionTime limits the time the conversion of the element may take once its page is loaded (default 60 seconds); a page that never finishes fails with a timeout error when the element is added. RenderOnTimeout converts what is loaded at the navigation timeout instead of failing.
using (Document document = new Document()) { PdfPage page = document.AddPage(); PdfFont font = document.AddFont(new Font("Arial", 14)); page.AddElement(new TextElement(0, 0, "Monthly report", font)); // starts 300 points down the first page and continues on the next pages HtmlToPdfElement html = new HtmlToPdfElement(0, 300, "https://www.example.com/report"); AddElementResult result = page.AddElement(html); // a text right below the end of the HTML content PdfPage endPage = document.Pages[result.EndPageIndex]; endPage.AddElement(new TextElement(0, result.EndPageBounds.Bottom + 10, "End of report", font)); document.Save("report.pdf"); }
The mapped rectangles of the HTML elements mapping (see below) are on the document pages, ready for a table of contents.
The converter supports the CSS properties that control the page breaks: break-before: page, break-after: page and break-inside: avoid, and the older page-break-before: always, page-break-after: always and page-break-inside: avoid. For example, with the page-break-after: always style applied to an HTML element (image, text, etc), you instruct the converter to insert a page break right after that element is rendered. A line of text is never cut between two pages.
A very useful feature when creating PDF reports is keep together, done with the page-break-inside: avoid style. It instructs the converter to avoid breaking the content of a group of HTML elements you want to keep together on the same page - a table, a table row, a div element, an image.
Below is an example of using the page-break-inside: avoid style. The table contains a large number of rows, each row containing an image on the left and a text on the right, and a row must not span two pages.
<table> <tr style="page-break-inside: avoid"> <td> <img width="100" height="100" src="img1.jpg"> </td> <td> My text 1 </td> </tr> <tr style="page-break-inside: avoid"> <td> <img width="100" height="100" src="img2.jpg"> </td> <td> My text 2 </td> </tr> </table>
The converter converts the HTTP links of the HTML document into links in the PDF document. This works on links containing text, images or any other content the HTML code allows, and it is the default behavior of the converter. To get no active links in the generated PDF document, set the LiveUrlsEnabled property to False.
The element is rendered by Chromium, the engine of the Chrome browser, with HTML5, CSS3, web fonts and JavaScript. RenderingEngine has the single value Chromium. The engine is deployed by the native engine package of the platform (or a platform package such as ExpertPdf.Anywhere.Linux) in a folder beside the application; CefEnginePath points to the engine folder when it is somewhere else. The engine runs inside the application by default (ChromiumEngineHostMode); ForceOutOfProcess runs one element in an engine process of its own.
ScriptsEnabled lets the JavaScript of the HTML run (true by default), and ConversionDelay waits for the scripts a number of seconds after the page is loaded. A page that draws with WebGL needs WebGlEnabled set to true.
When the web server asks for a user name and a password (HTTP authentication, for example Basic authentication), set them in the AuthenticationOptions property of the HtmlToPdfElement object. A site that signs its users in with a login form is handled with LoginOptions, and cookies and HTTP headers are sent with HttpCookies and HttpHeaders (see Server Authentication).
Below you can find sample code for setting the user name and password for authentication when converting HTML to PDF using an HtmlToPdfElement object:
The converter can create bookmarks in the generated PDF document for the HTML elements you select. The bookmarks are controlled by the PdfBookmarkOptions property and are created when a list of CSS selectors is set in the HtmlElementSelectors property: "h1" selects all the h1 elements, ".myclass" the elements with the CSS class myclass and "#myid" the element with the id myid.
For example, to create bookmarks for the H1 and H2 elements, and only for the H2 elements with the CSS class bookmark, use the following line of code:
htmlToPdfElement.PdfBookmarkOptions.HtmlElementSelectors =
new string[] { "h1", "h2.bookmark" };With HierarchicalBookmarks set, the bookmarks are nested by the position of their selector in the list (the first selector gives the top level), and MaxTitleLength limits the length of a bookmark title.
The converter converts the HTML links with anchors found in the HTML document to internal links in the PDF. This feature can be used to create a table of contents in the generated PDF document.
An HTML link with an anchor consists of two HTML elements: a link defined by an <a href="#target">Internal Link</a> tag and the target of the link, an element with the id target or an <a name="target">Link Target</a> tag. The converter generates an internal link in the PDF from "Internal Link" to "Link Target".
The generation of internal links can be disabled with htmlToPdfElement.InternalLinksEnabled = false;.
An internal link is recognized when it refers to the converted document. When the links of a page name that page by another URL than the one converted - for example a site whose start page is served for its root address and links to itself by its file name - pass the URL the links use in the internalLinksDocUrl parameter of the HtmlToPdfElement constructors. When converting an HTML string to PDF, pass the baseUrl and, when needed, the internalLinksDocUrl parameters.
The Document compresses images with the JPEG compression algorithm to reduce the size of the PDF document: the images added with an image element, and all the images of a document loaded from an existing PDF when it is saved. The JPEG compression reduces the quality of the images; when the JPEG compression level is increased, the quality of the images in the PDF decreases. An image element keeps transparent images and very small images lossless.
The JpegCompressionLevel property sets the level used for JPEG compression on a scale from 0 to 100. When the compression level is 0 the compression is the lowest and the image quality is the best. The default JPEG compression level is 10, which offers a good balance between the quality of the images and the size of the PDF document.
For the best image quality, disable the JPEG compression of the images by setting JpegCompressionEnabled to False. ImagesMaxResolution resamples images that have more pixels than their size on the page needs.
The converter can tell the position in the generated PDF document of any HTML element. Knowing the position in the PDF document of an element from the HTML document allows you to create bookmarks for elements from the HTML document, create internal links between HTML elements, place texts or images over the HTML elements, or place a digital signature over a certain element.
This feature is accessed with the HtmlElementsMappingOptions property of the HtmlToPdfElement object. Its HtmlElementSelectors property takes the CSS selectors of the HTML elements whose position you want: "h1" selects all the h1 elements, ".myclass" the elements with the CSS class myclass and "#myid" the element with the id myid. Set it before the element is added to a page.
The HTML elements mapping is returned in the HtmlElementsMappingResult property, a collection of HtmlElementMapping objects. Each one gives the PDF page index and the rectangle inside that page for each page where the element was rendered, and the element id, tag name, CSS class name, text and outer HTML code.
In the code sample below, all the H1 and IMG elements and the elements with the ids MyID1 and MyID2 are highlighted with a red rectangle in the generated PDF:
// the HTML elements for which you want to retrieve the position htmlToPdfElement.HtmlElementsMappingOptions.HtmlElementSelectors = new string[] { "img", "h1", "#MyID1", "#MyID2" }; // add the element to a PDF page page.AddElement(htmlToPdfElement); // iterate over the HTML elements mappings and draw a red rectangle around the // element in PDF HtmlElementMappingsCollection mappings = htmlToPdfElement.HtmlElementsMappingOptions.HtmlElementsMappingResult; foreach (HtmlElementMapping elementMapping in mappings) { // an HTML element can span several PDF pages foreach (HtmlElementPdfRectangle pdfRectangle in elementMapping.PdfRectangles) { // the PDF page and the rectangle where the HTML element was rendered PdfPage elementPdfPage = document.Pages[pdfRectangle.PageIndex]; RectangleF elementPdfRectangle = pdfRectangle.Rectangle; RectangleElement elementHighlightRectangle = new RectangleElement( elementPdfRectangle.X, elementPdfRectangle.Y, elementPdfRectangle.Width, elementPdfRectangle.Height); elementHighlightRectangle.ForeColor = Color.Red; elementPdfPage.AddElement(elementHighlightRectangle); } }