2

Can we use PuppeteerSharp with Razor View. I want to send the HTML from Razor View inside AspNetCore app and get the output as PDF. Any references or code samples would be helpful

code_blue
  • 523
  • 2
  • 9
  • 19

2 Answers2

2

You can inject the HTML using SetContentAsync and then call PdfAsync

await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
    Headless = false,
}))
using (var page = await browser.NewPageAsync())
{
    await page.SetContentAsync("Hello World");
    await page.PdfAsync("test.pdf");
}
hardkoded
  • 18,915
  • 3
  • 52
  • 64
  • Thanks..If the page has reference to external JS or CSS files how can I load them or tell Puppeteer to load them. – code_blue Apr 05 '19 at 12:34
  • Yes, but you have to be sure that a browser can access that resource. It can't be a relative url. – hardkoded Apr 05 '19 at 13:03
0

According to github you can generate PDF file like this

await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
    Headless = false
});
var page = await browser.NewPageAsync();
await page.GoToAsync("http://localhost/your/page");
Stream pdfStream = await page.PdfStreamAsync();
Alexander
  • 9,104
  • 1
  • 17
  • 41