Convert Html Code To Pdf | |
Using Select.Pdf Html to Pdf Converter for .NET any html code can be converted to pdf. Select.Pdf Library supports the latest HTML5 with CSS3 style sheets.
To convert a raw html string to pdf, HtmlToPdf class exposes the ConvertHtmlString(String) and ConvertHtmlString(String, String) methods.
The first method, that has only the htmlString parameter, can be used to convert html strings that don't have external references to javascript, css files or images. In case the html string contains references to external resources specified using relative paths, the second method needs to be used. ConvertHtmlString(String, String) contains an additional parameter: baseUrl. The baseUrl parameter allows the converter to resolve relative urls. Basically, baseUrl + relative image/css url = full absolute url. When baseUrl is an http or https url it is also the page's own address: the html is served as the response for that url, so the page's origin is the base url's site and web fonts, fetch requests, module scripts and cookies of that site work exactly as they do when the page is converted by url (a page loaded from a temporary file would make those requests cross-origin). A base element inside the html still takes precedence over the parameter.
This sample code shows how to use Select.Pdf html to pdf converter to convert an html string to pdf, also setting a few properties.
// instantiate a html to pdf converter object HtmlToPdf converter = new HtmlToPdf(); // set converter options converter.Options.PdfPageSize = pageSize; converter.Options.PdfPageOrientation = pdfOrientation; converter.Options.WebPageWidth = webPageWidth; converter.Options.WebPageHeight = webPageHeight; // create a new pdf document converting an html string PdfDocument doc = converter.ConvertHtmlString(htmlString, baseUrl); // save pdf document doc.Save("Sample.pdf"); // close pdf document doc.Close();