I am trying to create an invoice look-alike PDF document with pure HTML and CSS code in my ASP.NET MVC web app, but whenever I try to create the PDF file, it gets created but it’s just a blank page, nothing on it…
I am using HTML Renderer as a library to help me print out the PDF document.
This is my code:
private async Task<IActionResult> GenerateInvoice(IEnumerable<InvoiceDTO> modelData)
{
try
{
var document = new PdfDocument();
var DateTimeNow = DateTime.Now;
string HtmlContent = $@"
<html>
<head>
<style>
body{{
padding: 50px;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
background-color: antiquewhite;
}}
#topContainer{{
height: 100px;
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
flex-direction: row;
background-color: aquamarine;
}}
</style>
</head>
<body>
<div id=""topContainer"">
<p>Date: {DateTimeNow} </p>
</div>
</body>
</html>";
PdfGenerator.AddPdfPages(document, HtmlContent, PageSize.A4);
byte[] response;
using (MemoryStream ms = new MemoryStream())
{
document.Save(ms);
response = ms.ToArray();
}
return File(new MemoryStream(response), "application/pdf", "test.pdf");
}
catch (Exception ex)
{
throw ex;
}
}
I have more classes and more code and I have tried it in a .html file and it all worked (of course I had to replace the double quotes and brackets with single ones).
Anyone know what I’m missing here?
2
Answers
This is because you put the html codes inside the action method. You must create a corresponding view for each action and move the html codes there.
Since you didn’t mention which package you are using in your code, so that I just searched about
PdfGenerator.AddPdfPages
and I found this reply which usingPolybioz.HtmlRenderer.PdfSharp.Core
and it worked well in my side. If I swtiched to your html content, I will get exception like below.Per my test, I found if I removed
display: flex;
in the style definition, it will work. In the mean time, I also reproduced your issue which generating a pdf file with no content(remove styles defined for body and only keeps styles defined for the div), and I noticed when it’s null, the file size would be 1kb, but if it contains content, it will be 18kb. Any way, I think this issue is due to the style we used.Here’s my codes, and I installed package
<PackageReference Include="Polybioz.HtmlRenderer.PdfSharp.Core" Version="1.0.0" />
: