user27033778
user27033778

Reputation:

ASP.NET Core & PdfSharpCore : cannot save a PDF document with no pages

I'm trying to convert a HTML page to PDF with PdfSharpCore.

This is my code:

public async Task<IActionResult> reporteAlta(int lote)
{
    var documento = new PdfDocument();

    string htmlContent = "<div style='height: 90%; font-family: Arial, Helvetica, sans-serif; padding: 0; margin: 0;'>";
    htmlContent += "<h1 style='text-align: start; padding-right: 0.25em; border-right: 3px solid black;'>PRUEBA</h1>";
    htmlContent += "</div>";

    Console.WriteLine(htmlContent);

    PdfGenerator.AddPdfPages(documento, htmlContent, PageSize.A4);
    byte[]? response = null;

    using(MemoryStream ms = new MemoryStream())
    {
        documento.Save(ms);  
        response = ms.ToArray();
    }

    string FileName = "reporte_folio_" + lote + ".pdf";

    return File(response,"application/pdf",FileName);
}

That one works and generates a PDF file, but this one below doesn't, it just throws this error:

An unhandled exception has occurred while executing the request. System.InvalidOperationException: Cannot save a PDF document with no pages.

at PdfSharpCore.Pdf.PdfDocument.DoSave(PdfWriter writer)
at PdfSharpCore.Pdf.PdfDocument.Save(Stream stream, Boolean closeStream)
at PdfSharpCore.Pdf.PdfDocument.Save(Stream stream)

Code:

public async Task<IActionResult> reporteAlta(int lote)
{
    var documento = new PdfDocument();

    string htmlContent = "<div style='height: 90%; font-family: Arial, Helvetica, sans-serif; padding: 0; margin: 0;'>";
    htmlContent  += "<div style='display: flex; align-items: stretch;'>";
    htmlContent += "<h1 style='text-align: start; padding-right: 0.25em; border-right: 3px solid black;'>PRUEBA</h1>";
    htmlContent += "</div>";
    htmlContent += "</div>";

    Console.WriteLine(htmlContent);

    PdfGenerator.AddPdfPages(documento, htmlContent, PageSize.A4);
    byte[]? response = null;

    using(MemoryStream ms = new MemoryStream())
    {
        documento.Save(ms);  
        response = ms.ToArray();
    }

    string FileName = "reporte_folio_" + lote + ".pdf";

    return File(response,"application/pdf",FileName);
}

I tried to downgrade to version 1.0.0 (dotnet add package Polybioz.HtmlRenderer.PdfSharp.Core --version 1.0.0) but that did not work. And yeah, I have these using:

using PdfSharpCore;
using PdfSharpCore.Pdf;
using TheArtOfDev.HtmlRenderer.PdfSharp;

Also Swagger shows the function fine, the only problem is just generate with more "info"

Upvotes: 0

Views: 153

Answers (0)

Related Questions