Convert Web Page to PDF in C#

PDF from URL

Print to PDF in C# using WebBrowser control

Often in the Shopify kind of application, we would need to generate PDFs for customers for order details or transaction details. In C#, this can be achieved by WebBrowser control.

To print a web page from a URL into a PDF in .NET C#, you can use the following steps.

  1. Create a WebBrowser control.
  2. Set the Url property of the WebBrowser control to the URL of the web page you want to print.
  3. Add an event handler to the DocumentCompleted event of the WebBrowser control.
  4. In the event handler, call the PrintToPdf method of the WebBrowser control.
  5. Dispose of the WebBrowser control when you are finished with it.

Here is an example of how to do this in C#.

private void PrintWebPageToPdf(string url) {
// Create a WebBrowser control.
WebBrowser webBrowser = new WebBrowser();
// Set the Url property of the WebBrowser control.
webBrowser.Url = new Uri(url);
// Add an event handler to the DocumentCompleted event of the WebBrowser control.
webBrowser.DocumentCompleted += new
WebBrowserDocumentCompletedEventHandler(OnDocumentCompleted);
// Show the WebBrowser control.
webBrowser.Show();
}
private void OnDocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e) {
// Print the document to PDF.
webBrowser.PrintToPdf("output.pdf");
// Dispose of the WebBrowser control.
webBrowser.

In this example, the PrintWebPageToPdf() method takes a URL as its input parameter. The method creates a WebBrowser control, sets its Url property to the specified URL, and adds an event handler to the DocumentCompleted event of the WebBrowser control. The event handler is called when the web page has finished loading. In the event handler, the method calls the PrintToPdf method of the WebBrowser control to print the web page to a PDF file. Finally, the method disposes of the WebBrowser control when it is finished with it.


Similar Articles