Home > Blockchain >  C# - Using CefSharp Chromium Web Browser to Print To PDF and Fit to Page
C# - Using CefSharp Chromium Web Browser to Print To PDF and Fit to Page

Time:11-09

I'm using ChromiumWebBrowser to convert a local html page that might have images in it to PDF in order to print it on a kiosk printer. The dimensions of the PDF should be 80mm x 200mm. The following is the code so far:

using (var browser = new ChromiumWebBrowser(url, browserSettings))
{        
    if (zoomLevel > 0)
    {
        browser.FrameLoadStart  = (s, argsi) =>
        {
            var b = (ChromiumWebBrowser)s;
            if (argsi.Frame.IsMain)
            {
                b.SetZoomLevel(zoomLevel);
            }
        };
    }

    await browser.WaitForInitialLoadAsync();

    var contentSize = await browser.GetContentSizeAsync();

    var viewport = new Viewport
    {
        Height = contentSize.Height,
        Width = contentSize.Width,
        Scale = 1.0
    };

    var printSettings = new PdfPrintSettings();
    printSettings.PageWidth = 80000;   // 80mm
    printSettings.PageHeight = 200000; // 200mm
    printSettings.BackgroundsEnabled = true;

    await browser.PrintToPdfAsync("D:\\chromium_pdf.pdf", printSettings);
}

The html page is converted perfectly if it only contains text. Also, if it has images that fit within the specified print width and height, it converts fine. The issue occurs when large images are included in the html. This results in part of the image being cropped out from the right.

When printing to PDF manually in a normal browser, the popup that shows up has a tick box for "fit to printable area" that scales the entire page down to fit the whole image. I would like to simulate that through code.

In the PdfPrintSettings class, there is a property called ScaleFactor. When I change this from 100% to 50%, the image fits fine in the created PDF page. However, that 50% value is arbitrary and I would like to scale it based on the image.

I tried changing the viewport width and height or the browser zoom level but that does not affect the printed PDF.

I also don't want to take a screenshot of the PDF since that affects the print quality; printing text is much clearer.

How can I scale the page to fit into the PDF page using this ChromiumWebBrowser from CefSharp? Or how can I figure out what the ScaleFactor should be?

Here is a screenshot of the first and second pages of the PDF generated:

enter image description here

CodePudding user response:

PrintToPdfAsync uses the same code path as https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF

There is no specific support for fit to page. Until chromium adds support there won't be a built in option.

Possibly options to look at:

  • Add some css media print rules
  • Calculate scale based on content size.
  • Related