QuestPDF / QuestPDF

QuestPDF is a modern open-source .NET library for PDF document generation. Offering comprehensive layout engine powered by concise and discoverable C# Fluent API. Easily generate PDF reports, invoices, exports, etc.

Home Page:https://www.questpdf.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Generating PDF produces blank document when using async/await

marcmognol opened this issue · comments

Describe the bug
I'm trying to generate a PDF, the produced document is empty/blank.

To Reproduce

using QuestPDF.Fluent;
using QuestPDF.Infrastructure;

QuestPDF.Settings.License = LicenseType.Community;

for (int i = 0; i < 10; i++)
{
    var document = Document.Create(container =>
    {
        container.Page(async page =>
        {
            await Task.Delay(10);
            page.Content().Text(DateTime.Now.ToString());
        });
    });

    document.GeneratePdf("c:\\temp\\pdf_" + i + "doc.pdf");
}

Expected behavior
10 generated PDF with the current datetime as content.
But only one is correctly generated as shown below in the screenshot. Sometimes zero document is correctly generated.

Screenshots

image

Environment
What version of the library do you use? 2024.3.4, same behavior with old versions.
What operating system do you use? (OS type, x64 vs x86 vs arm64) x64

Additional context
If I remove async/await from the PageDescriptor, I've no issue but I need to be able to call some external API/Database to get contextual data that I can't operate outside.

Thanks for your support.

You are likely looking for this type of code:

class MyData
{
    public required int Index { get; init; }
    public required DateTime DateTime { get; init; }
    public required byte[] Image { get; init; }
}

public async Task Example()
{
    void GenerateDocumentImagePath(MyData data)
    {
        var document = Document.Create(container =>
        {
            container.Page(page =>
            {
                page.Content().Column(column =>
                {
                    column.Item().Text(data.DateTime.ToString());
                    column.Item().Image(data.Image);
                });
            });
        });

        document.GeneratePdf("c:\\temp\\pdf_" + data.Index + "doc.pdf");
    }
    
    for (int i = 0; i < 10; i++)
    {
        var data = new MyData
        {
            Index = i,
            DateTime = DateTime.Now,
            Image = await MyImageService.GetImageAsync(i)
        };
        
        GenerateDocumentImagePath(i);
    }
}

The PDF generation process is synchronous. If you need to call any external async resources, please do it before the generation and provide all necessary data through a DTO model.

Hi @MarcinZiabek

Thank you for your answer. I'll do it that way.

Marc