Printing to PDF from WebView2

Wael Sedky 61 Reputation points
2023-04-30T23:14:05.36+00:00

I need an example of how to print from a web page to the default printer using WebView2. The example in the documentation doesn't seem complete. I also need to know what library I need to import if applicable.

PrinterSettings printSettings;
printSettings = webView21.CoreWebView2.Environment.CreatePrintSettings();
webView21.CoreWebView2.PrintAsync(printSettings);
Developer technologies Windows Forms
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2023-05-01T05:39:33.06+00:00

    @Wael Sedky, Welcome to Microsoft Q&A, you could try to use CoreWebView2.PrintToPdfAsync(String, CoreWebView2PrintSettings) Method to print pdf from webview2 control.

    Here is a code example you could refer to.

      private async void Form1_Load(object sender, EventArgs e)
            {
                await webView21.EnsureCoreWebView2Async();
                webView21.CoreWebView2.Navigate("https://www.example.com");
            }
    
            private async void button1_Click(object sender, EventArgs e)
            {
                var printSettings = webView21.CoreWebView2.Environment.CreatePrintSettings();
                printSettings.PageHeight = 297; // A4 paper size
                printSettings.PageWidth = 210;
                printSettings.MarginTop = 10;
                printSettings.MarginBottom = 10;
                printSettings.MarginLeft = 10;
                printSettings.MarginRight = 10;
        
                var pdfData = await webView21.CoreWebView2.PrintToPdfAsync("B:\\test1.pdf",printSettings);
               
            }
    
    

    Tested result:

    User's image

    Hope my code could help you.

    Best Regards,

    Jack

    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.  


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.