Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

puppeteerSharp failed to display image in pdf #2650

Open
kirticism opened this issue May 28, 2024 · 1 comment
Open

puppeteerSharp failed to display image in pdf #2650

kirticism opened this issue May 28, 2024 · 1 comment

Comments

@kirticism
Copy link

kirticism commented May 28, 2024

Hi,
I am encountering an issue while converting HTML to PDF using PuppeteerSharp. Specifically, the images are not displaying in the generated PDF. Despite following various solutions suggested on StackOverflow, the problem persists. Below is the method I am using to perform the HTML to PDF conversion. I would appreciate any guidance or solutions you could provide.

public async Task HtmlToPdf(string htmlContent, string fileName)
{
var startTime = DateTimeOffset.UtcNow;
_logger.LogInformation("Executing GeneratePdf: {fileName}...", fileName);

var launchOptions = new LaunchOptions { Headless = true };
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
using (var browser = await Puppeteer.LaunchAsync(launchOptions))
using (var page = await browser.NewPageAsync())
{
    await page.SetContentAsync(htmlContent);

    await page.AddStyleTagAsync(new AddTagOptions { Content = "body { font-size: 20px; margin: 50px; }" });
    await page.WaitForSelectorAsync("img");
    var pdfBytes = await page.PdfDataAsync(new PdfOptions { Format = PaperFormat.A4 });

    var filePath = Path.Combine(Path.GetTempPath(), fileName);
    File.WriteAllBytes(filePath, pdfBytes);

    var formFile = await CreateFormFile(filePath, fileName);

    File.Delete(filePath);

    var endTime = DateTimeOffset.UtcNow;
    var executionTime = endTime - startTime;
    _logger.LogInformation("Time taken to execute GeneratePdf: {fileName}. Time: {ExecutionTime} ms",
                           fileName, executionTime.TotalMilliseconds);

    return formFile;
}

}

@mstijak
Copy link

mstijak commented Jun 4, 2024

await page.WaitForSelectorAsync("img");

This is not enough. You should wait until the image loads too.

Perhaps this will do the trick.

await page.WaitForNetworkIdleAsync();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants