Getting Started with the HTML to PDF Converter |
The converter is in the ExpertPdf.Anywhere.HtmlToPdf namespace. Its main classes:
PdfConverter - converts a URL, an HTML string, an HTML file or stream to PDF: to bytes, a file, a stream, or a Document you can change before saving. See PdfConverter class.
ImgConverter - converts the same sources to images, returned as the bytes of an image file. See ImgConverter class.
The option objects of the converter: PdfDocumentOptions (page size, orientation, margins, compression, header and footer switches), PdfHeaderOptions, PdfFooterOptions, PdfSecurityOptions, PdfDocumentInfo, PdfViewerPreferences.
The HTML is rendered by Chromium, the only rendering engine of the library. Settings that apply to the whole process - whether the engine runs inside the application (the default) or in a process of its own for each conversion, and a log file - are on GlobalSettings.
PdfConverter pdfConverter = new PdfConverter(); pdfConverter.LicenseKey = "your license key"; // the page pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4; pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait; pdfConverter.PdfDocumentOptions.LeftMargin = 20; pdfConverter.PdfDocumentOptions.RightMargin = 20; pdfConverter.PdfDocumentOptions.TopMargin = 20; pdfConverter.PdfDocumentOptions.BottomMargin = 20; // a footer with the page numbers pdfConverter.PdfDocumentOptions.ShowFooter = true; pdfConverter.PdfFooterOptions.FooterText = "Quarterly report"; pdfConverter.PdfFooterOptions.ShowPageNumber = true; pdfConverter.PdfFooterOptions.PageNumberText = "Page"; // the document information pdfConverter.PdfDocumentInfo.Title = "Quarterly report"; pdfConverter.PdfDocumentInfo.AuthorName = "Example Inc."; pdfConverter.SavePdfFromUrlToFile("https://www.example.com/report", "report.pdf");
In an ASP.NET Core controller or Razor Page, return the bytes as a file:
public IActionResult DownloadReport() { PdfConverter pdfConverter = new PdfConverter(); byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl( "https://www.example.com/report"); // "inline" shows the document in the browser; File(bytes, type, name) downloads // it Response.Headers["Content-Disposition"] = "inline; filename=report.pdf"; return File(pdfBytes, "application/pdf"); }
In an ASP.NET Core application the conversion can run without blocking a request thread with the asynchronous methods, for example GetPdfBytesFromUrlAsync(String, CancellationToken) (see PdfConverter class).
To convert a page of your own application with the data of the current user, convert its HTML: render the view to a string and call GetPdfBytesFromHtmlString with the base URL of the site (see the FAQ), or pass the authentication cookie of the user with HttpCookies.