Skip to content

Instantly share code, notes, and snippets.

@conholdate-gists
Last active April 10, 2021 09:00
Show Gist options
  • Save conholdate-gists/6b7ce982069cbc65d037e262d1792d10 to your computer and use it in GitHub Desktop.
Save conholdate-gists/6b7ce982069cbc65d037e262d1792d10 to your computer and use it in GitHub Desktop.
Convert HTML to PDF and PDF to HTML using C# .NET API

This Gist contains the code snippets related to HTML to PDF conversion operations using Aspose.PDF for .NET. Further details regarding implementation can be found over following blog post

Convert HTML to PDF and PDF to HTML using C# .NET API
// Embed fonts during conversion
HtmlLoadOptions options = new HtmlLoadOptions {IsEmbedFonts = true};
// create an object to initiate the license
Aspose.Pdf.License license = new Aspose.Pdf.License();
// provide path of license file
license.SetLicense("/Downloads/Conholdate.Total.NET.lic");
// create an instance of HtmlLoadOptions class
Aspose.Pdf.HtmlLoadOptions htmlLoadOptions = new Aspose.Pdf.HtmlLoadOptions("User/Documents/");
// create Document object and provide input HTML file path
Aspose.Pdf.Document document = new Aspose.Pdf.Document("/Documents/input.html", htmlLoadOptions);
// save the resultant HTML to PDF format
document.Save("/Documents/Converted.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// Initialize the HtmlLoadOptions object
HtmlLoadOptions options = new HtmlLoadOptions();
// Set render to single page property
options.IsRenderToSinglePage = true;
// Load document source HTML content
Document pdfDocument= new Document("/Documents/HTMLToPDF.html", options);
// Save the resultant PDF file
pdfDocument.Save("/Documents/MyRenderContentToSamePage.pdf");
// Set Page size as A3 and page orientation as Landscape
HtmlLoadOptions options = new HtmlLoadOptions(url)
{
PageInfo = {Width = 842, Height = 1191, IsLandscape = true}
};
public static void ConvertHTMLtoPDFAdvanced_WebPage()
{
const string url = "https://en.wikipedia.org/wiki/Aspose_API";
// Set page size A3 and Landscape orientation;
HtmlLoadOptions options = new HtmlLoadOptions(url)
{
// Set the page dimensions
PageInfo = {Width = 842, Height = 1191, IsLandscape = true}
};
// Create an instance of Document object
Document pdfDocument= new Document(GetContentFromUrlAsStream(url), options);
// Save the resultant
pdfDocument.Save(_dataDir + "html_test.PDF");
}
private static Stream GetContentFromUrlAsStream(string url, ICredentials credentials = null)
{
using (var handler = new HttpClientHandler { Credentials = credentials })
using (var httpClient = new HttpClient(handler))
{
// fetch and return results in stream instance
return httpClient.GetStreamAsync(url).GetAwaiter().GetResult();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment