[]
DsPdf library along with DsHtml library, lets you easily render HTML content to PDF document. With a utility library like DsHtml, you can convert HTML files like invoices and reports to PDF documents and print them without worrying about disarranged layouts, styles or formats. You can also add HTML content to PDF documents.
DsHtml is based on the industry standard Chrome web browser engine working in headless mode, offering advantage of rendering HTML to PDF on any platform - Windows, Linux and macOS. It doesn’t matter whether your .NET application is built for x64, x86 or AnyCPU platform target. The browser is always working in a separate process.
The DS.Documents.Html package contains the following namespaces:
GrapeCity.Documents.Html namespace provides GcHtmlRenderer(Obsolete), GcHtmlBrowser, PdfOptions, ImageOptions, PageOptions, HtmlPage classes etc.
GrapeCity.Documents.Pdf namespace provides the GcPdfGraphicsExt and HtmltoPdfFormat classes.
GrapeCity.Documents.Drawing namespace provides GcBitmapGraphicsExt and HtmlToImageFormat class.
Refer the steps below to install DsHtml package in your project:
Open Visual Studio and create a .Net Core Console application.
Right-click Dependencies and select Manage NuGet Packages.
With the Package source set to Nuget website, search for DS.Documents.Pdf under the Browse tab and click Install.
Similarly, install DS.Documents.Html.
!type=note
Note: During installation, you’ll receive two confirmation dialogs. Click OK in the Preview Changes dialog box and click I Agree in the License Acceptance dialog box to proceed installation.
Once, the DsHtml package has been installed successfully, add the namespace in Program.cs file.
using GrapeCity.Documents.Html;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Drawing;
Apply DsPdf license to GcHtmlBrowser class of DsHtml library to convert HTML to PDF. Without proper license, the count is limited to only 5 PDF conversions. The license can be applied in one of the following ways as shown below:
To license the instance being created
var html = "<html><body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>";
var re = new GcHtmlBrowser(html);
re.ApplyGcPdfLicenseKey("key");
To license all the instances
GcHtmlBrowser.SetGcPdfLicenseKey("key");
Write the sample code.
DsHtml can render HTML webpage to PDF document. DsPdf provides the PdfOptions class and RenderToPdf method of GcHtmlBrowser class to render HTML files to PDF documents.
To render the HTML webpage to a PDF document, follow the steps below:
Specify the PDF file path for rendering HTML webpage.
Specify the HTML source (URI).
Define the PDF document settings using the PdfOptions class.
Convert the HTML webpage to PDF file using SaveAsPdf method of HtmlPage class.
// Get a temporary file where the web page will be rendered:
var tmp = Path.GetTempFileName();
// The Uri of the web page to render:
var uri = new Uri("http://www.google.com");
// Create an instance of GcHtmlBrowser that is used to render HTML:
var browserPath = BrowserFetcher.GetSystemChromePath();
using var browser = new GcHtmlBrowser(browserPath);
// Create an HtmlPage instance rendering the source Uri:
using var htmlPage = browser.NewPage(uri);
// Render the source Web page to the temporary file:
htmlPage.SaveAsPdf(tmp);
// Copy the created PDF from the temp file to target stream:
using (var ts = File.OpenRead(tmp))
ts.CopyTo(stream);
// Clean up:
File.Delete(tmp);
The snapshot of the resulting PDF document is depicted below:
!type=note
Note: In order to render an HTML page to PDF document, the fonts used on that page should be already installed on your system.
You can add an HTML page or string to a PDF document using the DrawHtml method of GcPdfGraphicsExt class.
To add an HTML formatted string to a PDF document, follow the steps below:
Create an instance of the GcPdfDocument class.
Configure PDF settings using the HtmlToPdfFormat class.
Add an HTML string to a PDF document using the DrawHtml method of GcPdfGraphicsExt class.
Save the PDF file using the Save method of the GcPdfDocument class.
// HTML code that represents the content to render:
var html = "<!DOCTYPE html>" +
"<html>" +
"<head>" +
"<style>" +
"span.bold {" +
"font-weight: bold;" +
"}" +
"p.round {" +
"font: 36px arial, sans-serif;" +
"color: DarkSlateBlue;" +
"border: 4px solid SlateBlue;" +
"border-radius: 16px;" +
"padding: 3px 5px 3px 5px;" +
"text-shadow: 3px 2px LightSkyBlue;" +
"}" +
"</style>" +
"</head>" +
"<body>" +
"<p class='round'>Hello, World, from <span class='bold'>DsHtml</span>!</p>" +
"</body>" +
"</html>";
// Create a new PDF document, add a page, get graphics to draw on:
var doc = new GcPdfDocument();
var page = doc.NewPage();
var g = page.Graphics;
try
{
// Create an instance of GcHtmlBrowser that is used to render HTML:
var browserPath = BrowserFetcher.GetSystemChromePath();
using var browser = new GcHtmlBrowser(browserPath);
// Render HTML.
var ok = g.DrawHtml(browser, html, 72, 72,
new HtmlToPdfFormat(false) { MaxPageWidth = 6.5f, MaxPageHeight = 9f },
out SizeF size);
}
catch (Exception ex)
{
throw new Exception($"Error:\n{ex.Message}");
}
// Done:
doc.Save(stream);
The resulting image is shown below:
For more information on rendering HTML to PDF using DsPdf, see DsPdf sample browser.
If your application uses obsolete GcHtmlRenderer class to convert the HTML pages or content to a pdf format, you can use following steps to quickly update to the new GcHtmlBrowser class which does not depend on a custom build of Chromium and does not require GPL or LGPL licenses.
In Solution Explorer, go to Project > Dependencies > Packages and remove any references to
GrapeCity.Documents.Html.Windows.X64
GrapeCity.Documents.Html.Linux.X64
GrapeCity.Documents.Html.Mac.X64
Check for licensing calls and if they exist, change them as follows:
GcHtmlRenderer.SetGcPdfLicenseKey(key); -> GcHtmlBrowser.SetGcPdfLicenseKey(key);
In order to create and use an instance of GcHtmlBrowser, you require the path to a Chromium based browser on the current system. For instance, in case of Chrome browser:
You can get the path to an existing instance of Chrome installed on the current system.
var path = BrowserFetcher.GetSystemChromePath();
Or, you can download and install Chrome in a location of your choice.
var tp = Path.GetTempPath();
var bf = new BrowserFetcher() { DestinationFolder = Path.Combine(tp, ".gc-chromium") };
var path = bf.GetDownloadedPath();
!type=note
Note: We recommend using Chrome browser with GcHTMLBrowser class as Edge has some differences in the implementation of some DevTools features.
Create an instance of GcHtmlBrowser. Note that RunWithNoSandbox option may be needed on some Linux systems.
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
return new GcHtmlBrowser(path, new LaunchOptions { RunWithNoSandbox = true });
else
return new GcHtmlBrowser(path)
In all calls to GcGraphics.DrawHtml() method, insert browser instance as the first parameter.
g.DrawHtml(html, ...); -> g.DrawHtml(browser, html, ...);
Look for instances of GcHtmlRenderer class which are rendering Uri such as
using var re = new GcHtmlRenderer(uri);
...
re.RenderToPdf(file, new PdfSettings() {…});
and replace it with
// Create an HtmlPage from the URI
// (DefaultBackgroundColor and WindowSize options from Pdf/Jpeg/PngSettings
// have moved to PageOptions, while some other options are now in LaunchOptions):
using var htmlPage = browser.NewPage(uri, new PageOptions() { WindowSize = pixelSize;… });
...
htmlPage.SaveAsPdf(file, new PdfOptions() {...});
!type=note
Note: Few methods and properties of JpegSettings and PngSettings classes have been moved to LaunchOptions and PageOptions classes.