How to generate pdf with an added post request?

21 Views Asked by At

I have an old but working application that can generate a pdf from an url. I'm trying to modify it to be able to send a post request.

The package PuppeteerSharp has been upgraded to version 14.1.0 on it. The relevant code is the following:

await new BrowserFetcher().DownloadAsync(); 
var browser = await Puppeteer.LaunchAsync(new LaunchOptions 
{ 
    Headless = true, 
    IgnoreHTTPSErrors = true 
}); 

var page = await browser.NewPageAsync(); 
try 
{ 
    await page.GoToAsync(url, new NavigationOptions 
    { 
        WaitUntil = new[] { 
            WaitUntilNavigation.Networkidle2 
        } 
    }); 
    await page.PdfAsync(Path.Combine(pdfDirPath, filename), new PdfOptions 
    { 
        Format = PaperFormat.A4, 
        PrintBackground = true 
    }); 
} 
catch (Exception e) 
{ 
    errorMsg.Add($"Error generating pdf: {e.Message}"); 
} 
await browser.CloseAsync();

I supposed it's coming from this example.

The web server delivering the pdf file has customization options that can be set with a post request. Based on this issue I modified the above code to add the post request (added part between the stars):

await new BrowserFetcher().DownloadAsync(); 
var browser = await Puppeteer.LaunchAsync(new LaunchOptions 
{ 
    Headless = true, 
    IgnoreHTTPSErrors = true 
}); 

var page = await browser.NewPageAsync(); 
try 
{
    // *****************************
    await page.SetRequestInterceptionAsync(true);
    page.Request += async (sender, e) =>
    {
        var data = new Payload()
        {
            Url = url,
            Method = System.Net.Http.HttpMethod.Post,
            PostData = "test"
        };
        await e.Request.ContinueAsync(data);
    };
    // ***************************
    await page.GoToAsync(url, new NavigationOptions 
    { 
        WaitUntil = new[] { 
            WaitUntilNavigation.Networkidle2 
        } 
    }); 
    await page.PdfAsync(Path.Combine(pdfDirPath, filename), new PdfOptions 
    { 
        Format = PaperFormat.A4, 
        PrintBackground = true 
    }); 
} 
catch (Exception e) 
{ 
    errorMsg.Add($"Error generating pdf: {e.Message}"); 
} 
await browser.CloseAsync();

Now when I'm using this code I get a blank pdf file with just the text "Cannot POST /" in it and have no idea what to do.

1

There are 1 best solutions below

0
Fred On

Seems like the web server doesn't accept post request. My bad.