Resolved IText Empty PDF

raysefo

Well-known member
Joined
Feb 22, 2019
Messages
361
Programming Experience
10+
Hello,

I am working on a Blazor Server application. I am trying to create and download PDFs as follows. PDF opens in a new browser tab but unfortunately, it is empty. What is wrong with my code? Could you please help?

C#:
private async Task ReportPDF()
    {
        var memoryStream = new MemoryStream();

        PdfDocument pdfDocument = new PdfDocument(new PdfWriter(memoryStream));
        Document doc = new Document(pdfDocument);
        
        Table table = new Table(7).UseAllAvailableWidth();

        table.AddHeaderCell(new Cell(1, 7).Add(new Paragraph("TEST")).SetBackgroundColor(DeviceRgb.BLUE).SetBold())
            .SetTextAlignment(TextAlignment.CENTER);
    

        for (int i = 0; i < 1; i++) {
            table.AddHeaderCell(new Cell().Add(new Paragraph("ORDER ID")).SetBackgroundColor(DeviceRgb.BLUE).SetBold());
            table.AddHeaderCell(new Cell().Add(new Paragraph("Product ID")).SetBackgroundColor(DeviceRgb.BLUE).SetBold());
            table.AddHeaderCell(new Cell().Add(new Paragraph("Product Code")).SetBackgroundColor(DeviceRgb.BLUE).SetBold());
            table.AddHeaderCell(new Cell().Add(new Paragraph("Currency")).SetBackgroundColor(DeviceRgb.BLUE).SetBold());
            table.AddHeaderCell(new Cell().Add(new Paragraph("Quantity")).SetBackgroundColor(DeviceRgb.BLUE).SetBold());
            table.AddHeaderCell(new Cell().Add(new Paragraph("Unit Price")).SetBackgroundColor(DeviceRgb.BLUE).SetBold());
            table.AddHeaderCell(new Cell().Add(new Paragraph("Total Price")).SetBackgroundColor(DeviceRgb.BLUE).SetBold());
        }

        foreach (var details in orderDetails)
        {
            table.AddCell(new Cell().Add(new Paragraph(details.OrderId.ToString())));
            table.AddCell(new Cell().Add(new Paragraph(details.Id.ToString())));
            table.AddCell(new Cell().Add(new Paragraph(details.ProductCode)));
            table.AddCell(new Cell().Add(new Paragraph(details.Currency)));
            table.AddCell(new Cell().Add(new Paragraph(details.Quantity.ToString())));
            table.AddCell(new Cell().Add(new Paragraph(details.BuyUnitPrice.ToString())));
            table.AddCell(new Cell().Add(new Paragraph(details.TotalBuyPrice.ToString())));
        }

        doc.Add(table);
        memoryStream.Position = 0;
        var pdfname = $"Report-{DateTime.Now.ToString("ddMMyyyyHHmm")}.pdf";


        using var streamRef = new DotNetStreamReference(stream: memoryStream);

        await JsRuntime.InvokeVoidAsync("downloadFileFromStream", pdfname, streamRef);
        
    }
 
Notice the calls to writer.SetCloseStream(false) and document.Close()
 
Solution
Back
Top Bottom