Getting Started with the HTML to PDF Converter |
The converter is in the ExpertPdf.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. See ImgConverter class.
The option objects of the converter: PdfDocumentOptions (page size, orientation, margins, compression, header and footer switches), PdfHeaderOptions, PdfFooterOptions, PdfSecurityOptions, PdfDocumentInfo, PdfViewerPreferences.
PdfConverter pdfConverter = new PdfConverter(); pdfConverter.LicenseKey = "your license key"; pdfConverter.RenderingEngine = RenderingEngine.Chromium; // 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(); pdfConverter.RenderingEngine = RenderingEngine.Chromium; 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 ASP.NET Web Forms, write the bytes to the response:
byte[] pdfBytes = new PdfConverter().GetPdfBytesFromUrl("https://www.example.com/report"); Response.Clear(); Response.ContentType = "application/pdf"; Response.AddHeader("Content-Disposition", "attachment; filename=report.pdf"); Response.BinaryWrite(pdfBytes); Response.End();
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.