Exclude Elements, Convert a Part of the Page |
Parts of a page that make no sense on paper - menus, buttons, banners, forms - can be left out of the PDF, and a single part of a page can be converted on its own.
List the elements to exclude in HtmlElementSelectors (property HtmlExcludedRegionsOptions): "img" selects all images, "*.myclass" the elements with the CSS class myclass, "*#myid" the element with the id myid. The elements are hidden before the page is converted, and the content after them moves up to take their place, as with display: none.
PdfConverter converter = new PdfConverter(); converter.HtmlExcludedRegionsOptions.HtmlElementSelectors = new string[] { "*#menu", "*.no-pdf", "form" }; converter.SavePdfFromUrlToFile("https://www.example.com/article", "article.pdf");
The same can be done with CSS: the CustomCSS property adds styles to the page before the conversion. A print style sheet of the page works too, when UsePrintCSSMediaType is true.
RenderElementSelector converts only the element matched by a CSS selector - an article, an invoice, a table. The element is lifted out of the page and rendered on its own, at the width of the page. RenderElementId does the same for an element id; when both are set, RenderElementSelector is used. When no element matches, or the element has no visible size, the conversion fails with an error instead of converting the whole page.
PdfConverter converter = new PdfConverter(); converter.RenderElementSelector = "main article"; converter.SavePdfFromUrlToFile("https://www.example.com/article", "article-only.pdf");
ImgConverter, HtmlToPdfArea, HtmlToPdfElement and HtmlToImageElement have the same RenderElementSelector and RenderElementId properties.