Search code examples
c#htmlpdfpuppeteerpuppeteer-sharp

Puppeteer pdf always render html in 1024px width how to change that


I am using Puppeteer Sharp for HTML to pdf. The issue is using media type print cause HTML to render at a width of 1024px, but I want to change that.

private async System.Threading.Tasks.Task<MemoryStream> GeneratePuppeteerPDF(string html)
{
    var workStream = new MemoryStream();
    using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions()
    {
        Headless = true,
        Timeout = 10000,
        ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
    }))
    {
        using (var page = await browser.NewPageAsync())
        {
            await page.SetContentAsync(html);
            var pdfOptions = new PdfOptions()
            {
                DisplayHeaderFooter = false,
                Landscape = false,
                PrintBackground = true,
                Format = PaperFormat.A4,
                MarginOptions = new MarginOptions()
                {
                    Top = "1cm",
                    Bottom = "1cm",
                    Left = "1cm",
                    Right = "1cm"
                }
            };
            await page.EmulateMediaTypeAsync(MediaType.Print);
            var st = await page.PdfStreamAsync(pdfOptions);
            st.CopyTo(workStream);
        }
    }
    return workStream;
}

How can I control the render width of HTML without using Media Type Screen

Even using Width in PdfOptions won't work; please help. I didn't yet find any solution on stackOverflow or anyplace.


Solution

  • The issue is solved. I am using Bootstrap 4, which had media print in the CSS.

    @media print {
     @page {
       size: a3;
     }
     body {
       min-width: 992px !important;
     }
     .container {
       min-width: 992px !important;
     }
    }
    

    I overwrited the above by

    @media print {
      @page {
        size: auto;
      }
    
      body {
        min-width: 100% !important;
      }
    
      .container {
        min-width: 100% !important;
      }
     }
    

    And now it's working if you set the div that holds the content to 600px, it will render in 600px width. You get what you see in the browser.