Home > Back-end >  Priniting page as PDF with code returns a blank PDF file
Priniting page as PDF with code returns a blank PDF file

Time:06-29

I am trying to make a program that can print orders from a website form as PDF. The issue I am experiencing is when I try to use any type of html to pdf or uri to pdf parser it returns a blank page with no data at all. (I have attempted online parsers and they also return a blank page).

The page I am trying to download as pdf is https://webportal.naviaq.no/final-report?OrderId= The page should throw a bunch JavaScript errors but you can ignore these as it is caused by the lack of an OrderId.

I have tried many different solutions but this is my current solution with the IronPdf package. The strange thing is that when I do a manual print of the page in my browser I am able to print it to PDF with no issues at all.

public class WebInteraction
{
    public static void UriToPdf(Uri uri, string filename)
    {
        var Renderer = new ChromePdfRenderer();
        string path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
        if (uri != null)
        {
            Renderer.RenderingOptions.EnableJavaScript = true;
            Renderer.RenderingOptions.RenderDelay = 4000;
            using var PDF = Renderer.RenderUrlAsPdf(uri);
            PDF.SaveAs(path   $"\\{filename}.pdf");
        }
    }
}

The code should return a pdf file in your C:\Users\%username%\ folder.

CodePudding user response:

I have still not figured out why this didn't work but after switching to puppeteer with a headless chrome instance I got it to work flawlessly.

public static async void UrisToPdf(List<PdfDataDto> bundle, ProgressBar reportDownloadProgressBar, string path = "")
{
    await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);

    reportDownloadProgressBar.Maximum = bundle.Count;
    reportDownloadProgressBar.Value = 0;

    foreach (var item in bundle)
    {
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions
        {
            Headless = true,
            Timeout = 600000

        });
        var page = await browser.NewPageAsync();
        page.DefaultTimeout = 600000;
        await browser.NewPageAsync();
        await page.GoToAsync(item.ReportUri?.AbsoluteUri, WaitUntilNavigation.Networkidle0);
        await page.PdfAsync(path   $"\\{item.ExternalOrderId}.pdf");
        await browser.CloseAsync();
        reportDownloadProgressBar.Value  = 1;
    }
}
  • Related