The main functionality of the library is to convert HTML documents to PDF. But the library does much more than this. You can also convert HTML to raster images or HTML to SVG using the appropriate interfaces and you can edit, merge or split existing PDF documents.
HTML to PDF Conversion
There are two approaches to convert HTML to PDF. The first is to use the PdfConverter class. The second approach is to create a Document object and to add a HtmlToPdfElement to it. Below are described in detail both methods.
Convert HTML to PDF using the PdfConverter Class
The easiest approach is to use one of the PdfConverter class methods to convert an URL or a HTML string to a PDF document. The resulted PDF document can be:
produced in a memory buffer using the PdfConverter..::..GetPdfBytesFromUrl(String) and PdfConverter..::..GetPdfBytesFromHtmlString(String, String) methods
saved in a file on disk using the PdfConverter..::..SavePdfFromUrlToFile(String, String) and PdfConverter..::..SavePdfFromHtmlStringToFile(String, String, String) methods
saved in an output stream using the PdfConverter..::..SavePdfFromUrlToStream(String, Stream) and PdfConverter..::..SavePdfFromHtmlStringToStream(String, String, Stream) methods
Code Sample - Convert URL to PDF with PdfConverter Class
| C# | |
|---|---|
/// <summary> /// Convert the HTML code from the specified URL to a PDF document and send the /// document to the browser /// </summary> private void ConvertURLToPDF() { string urlToConvert = textBoxWebPageURL.Text.Trim(); // Create the PDF converter. Optionally the HTML viewer width can be specified as parameter // The default HTML viewer width is 1024 pixels. PdfConverter pdfConverter = new PdfConverter(); // set the license key - required pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; // set the converter options - optional pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; pdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait; // set if header and footer are shown in the PDF - optional - default is false pdfConverter.PdfDocumentOptions.ShowHeader = cbAddHeader.Checked; pdfConverter.PdfDocumentOptions.ShowFooter = cbAddFooter.Checked; // set if the HTML content is resized if necessary to fit the PDF page width - default is true pdfConverter.PdfDocumentOptions.FitWidth = cbFitWidth.Checked; // set the embedded fonts option - optional - default is false pdfConverter.PdfDocumentOptions.EmbedFonts = cbEmbedFonts.Checked; // set the live HTTP links option - optional - default is true pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = cbLiveLinks.Checked; // set if the JavaScript is enabled during conversion to a PDF - default is true pdfConverter.JavaScriptEnabled = cbClientScripts.Checked; // set if the images in PDF are compressed with JPEG to reduce the PDF document size - default is true pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = cbJpegCompression.Checked; // enable auto-generated bookmarks for a specified list of HTML selectors (e.g. H1 and H2) if (cbBookmarks.Checked) { pdfConverter.PdfBookmarkOptions.HtmlElementSelectors = new string[] { "H1", "H2" }; } // add HTML header if (cbAddHeader.Checked) AddHeader(pdfConverter); // add HTML footer if (cbAddFooter.Checked) AddFooter(pdfConverter); // optionally wait for asynchronous items pdfConverter.ConversionDelay = 2; // Performs the conversion and get the pdf document bytes that can // be saved to a file or sent as a browser response byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(urlToConvert); // send the generated PDF document to client browser // get the object representing the HTTP response to browser HttpResponse httpResponse = HttpContext.Current.Response; // add the Content-Type and Content-Disposition HTTP headers httpResponse.AddHeader("Content-Type", "application/pdf"); if (radioAttachment.Checked) httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=GettingStarted.pdf; size={0}", pdfBytes.Length.ToString())); else httpResponse.AddHeader("Content-Disposition", String.Format("inline; filename=GettingStarted.pdf; size={0}", pdfBytes.Length.ToString())); // write the PDF document bytes as attachment to HTTP response httpResponse.BinaryWrite(pdfBytes); // Note: it is important to end the response, otherwise the ASP.NET // web page will render its content to PDF document stream httpResponse.End(); } | |
Another approach is to add HTML content to a PDF document using HtmlToPdfElement objects. The initial Document to which the HTML elements are added are either new documents created using one of the class constructor or documents initialized with the result of another HTML to PDF conversion using the PdfConverter..::..GetPdfDocumentObjectFromUrl(String) and PdfConverter..::..GetPdfDocumentObjectFromHtmlString(String, String) methods.
Code Sample - Convert URL to PDF with HtmlToPdfElement Class
| C# | |
|---|---|
//create a PDF document Document document = new Document(); // set the license key document.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; //optional settings for the PDF document like margins, compression level, //security options, viewer preferences, document information, etc document.CompressionLevel = PdfCompressionLevel.Normal; document.Margins = new Margins(10, 10, 0, 0); //document.Security.CanPrint = true; //document.Security.UserPassword = ""; document.ViewerPreferences.HideToolbar = false; // set if the images are compressed in PDF with JPEG to reduce the PDF document size document.JpegCompressionEnabled = cbJpegCompression.Checked; //Add a first page to the document. The next pages will inherit the settings from this page PdfPage page = document.Pages.AddNewPage(PdfPageSize.A4, new Margins(10, 10, 0, 0), PdfPageOrientation.Portrait); // the code below can be used to create a page with default settings A4, document margins inherited, portrait orientation //PdfPage page = document.Pages.AddNewPage(); // add a font to the document that can be used for the texts elements PdfFont font = document.Fonts.Add(new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10, System.Drawing.GraphicsUnit.Point)); // add header and footer before renderng the content if (cbAddHeader.Checked) AddHtmlHeader(document); if (cbAddFooter.Checked) AddHtmlFooter(document, font); // the result of adding an element to a PDF page AddElementResult addResult; // Get the specified location and size of the rendered content // A negative value for width and height means to auto determine // The auto determined width is the available width in the PDF page // and the auto determined height is the height necessary to render all the content float xLocation = float.Parse(textBoxXLocation.Text.Trim()); float yLocation = float.Parse(textBoxYLocation.Text.Trim()); float width = float.Parse(textBoxWidth.Text.Trim()); float height = float.Parse(textBoxHeight.Text.Trim()); if (radioConvertToSelectablePDF.Checked) { // convert HTML to PDF HtmlToPdfElement htmlToPdfElement; if (radioConvertURL.Checked) { // convert a URL to PDF string urlToConvert = textBoxWebPageURL.Text.Trim(); htmlToPdfElement = new HtmlToPdfElement(xLocation, yLocation, width, height, urlToConvert); } else { // convert a HTML string to PDF string htmlStringToConvert = textBoxHTMLCode.Text; string baseURL = textBoxBaseURL.Text.Trim(); htmlToPdfElement = new HtmlToPdfElement(xLocation, yLocation, width, height, htmlStringToConvert, baseURL); } //optional settings for the HTML to PDF converter htmlToPdfElement.FitWidth = cbFitWidth.Checked; htmlToPdfElement.EmbedFonts = cbEmbedFonts.Checked; htmlToPdfElement.LiveUrlsEnabled = cbLiveLinks.Checked; htmlToPdfElement.JavaScriptEnabled = cbClientScripts.Checked; htmlToPdfElement.PdfBookmarkOptions.HtmlElementSelectors = cbBookmarks.Checked ? new string[] { "H1", "H2" } : null; // add theHTML to PDF converter element to page addResult = page.AddElement(htmlToPdfElement); } else { HtmlToImageElement htmlToImageElement; // convert HTML to image and add image to PDF document if (radioConvertURL.Checked) { // convert a URL to PDF string urlToConvert = textBoxWebPageURL.Text.Trim(); htmlToImageElement = new HtmlToImageElement(xLocation, yLocation, width, height, urlToConvert); } else { // convert a HTML string to PDF string htmlStringToConvert = textBoxHTMLCode.Text; string baseURL = textBoxBaseURL.Text.Trim(); htmlToImageElement = new HtmlToImageElement(xLocation, yLocation, width, height, htmlStringToConvert, baseURL); } //optional settings for the HTML to PDF converter htmlToImageElement.FitWidth = cbFitWidth.Checked; htmlToImageElement.LiveUrlsEnabled = cbLiveLinks.Checked; htmlToImageElement.JavaScriptEnabled = cbClientScripts.Checked; htmlToImageElement.PdfBookmarkOptions.HtmlElementSelectors = cbBookmarks.Checked ? new string[] { "H1", "H2" } : null; addResult = page.AddElement(htmlToImageElement); } if (cbAdditionalContent.Checked) { // The code below can be used add some other elements right under the conversion result // like texts or another HTML to PDF conversion // add a text element right under the HTML to PDF document PdfPage endPage = document.Pages[addResult.EndPageIndex]; TextElement nextTextElement = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Below there is another HTML to PDF Element", font); nextTextElement.ForeColor = System.Drawing.Color.Green; addResult = endPage.AddElement(nextTextElement); // add another HTML to PDF converter element right under the text element endPage = document.Pages[addResult.EndPageIndex]; HtmlToPdfElement nextHtmlToPdfElement = new HtmlToPdfElement(0, addResult.EndPageBounds.Bottom + 10, "http://www.google.com"); addResult = endPage.AddElement(nextHtmlToPdfElement); } try { // get the PDF document bytes byte[] pdfBytes = document.Save(); // send the generated PDF document to client browser // get the object representing the HTTP response to browser HttpResponse httpResponse = HttpContext.Current.Response; // add the Content-Type and Content-Disposition HTTP headers httpResponse.AddHeader("Content-Type", "application/pdf"); httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=HtmlToPdfElement.pdf; size={0}", pdfBytes.Length.ToString())); // write the PDF document bytes as attachment to HTTP response httpResponse.BinaryWrite(pdfBytes); // Note: it is important to end the response, otherwise the ASP.NET // web page will render its content to PDF document stream httpResponse.End(); } finally { // close the PDF document to release the resources document.Close(); } } | |