Hi,
I have a problem with PDF generating. Some national characters (in this case from Polish language) are missing in the created file. For example I'm getting dem instead of dżem (so the letter ż is missing).
I checked the database and it's saved correctly. My WebAPI is also returning those names in a correct way. Characters are getting lost when creating the PDF file.
Is there a way to fix that (for example to specify the encoding)?
ShoppingListModel:
public class ShoppingListModel
{
public string Name { get; set; }
public string Unit { get; set; }
public double Amount { get; set; }
}
FileResult that is getting returned from the method responsible for generating PDF:
public record FileResult(Stream Content, string Type, string Name);
GetPdf method:
public FileResult GetPdf(List<ShoppingListModel> shoppingList)
{
var document = new PdfDocument();
var page = document.Pages.Add();
PdfCellStyle headerStyle = new()
{
TextPen = PdfPens.Black,
TextBrush = PdfBrushes.Black,
BackgroundBrush = PdfBrushes.White,
Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 10),
};
PdfLightTable table = new()
{
DataSource = shoppingList,
ColumnProportionalSizing = true,
};
table.Style.HeaderStyle = headerStyle;
table.Style.ShowHeader = true;
table.Style.CellPadding = 3f;
table.Draw(page, new PointF(10, 10));
var stream = new MemoryStream();
document.Save(stream);
stream.Position = 0;
document.Close(true);
return new FileResult(stream, "application/pdf", "shoppingList.pdf");
}
Action from my controller, responsible for returning a file to the caller:
[HttpGet("pdf")]
public async Task<IActionResult> GetShoppingListAsPdf(DateTime from, DateTime to, float peopleCount)
{
if (peopleCount == 0f)
peopleCount = 1f;
var shoppingList = await Mediator.Send(new GetShoppingListQuery(from, to, peopleCount));
var pdf = _pdfGenerator.GetPdf(shoppingList);
return File(pdf.Content, pdf.Type, pdf.Name);
}
Link to GitHub repo: https://github.com/MadTiger2409/FoodPlanner
|
//Load the TrueType font from the local *.ttf file.
FileStream fontStream = new FileStream("../../../arial.ttf", FileMode.Open, FileAccess.Read);
PdfFont font = new PdfTrueTypeFont(fontStream, 14);
//Declare and define the alternate style.
PdfCellStyle altStyle = new PdfCellStyle(font, PdfBrushes.Black, PdfPens.Green);
PdfLightTable table = new()
{
DataSource = shoppingList,
ColumnProportionalSizing = true,
};
table.Style.DefaultStyle = altStyle;
table.Style.HeaderStyle = headerStyle;
table.Style.ShowHeader = true;
table.Style.CellPadding = 3f;
table.Draw(page, new PointF(10, 10)); |
Now I have one more problem. I tried few fonts and even with Calibri Light text looks like it's bold.
I specified that it should be regular:
PdfCellStyle defaultStyle = new() |
I added a file that is being generated so you can see the result.
Attachment: shoppingList_7364448c.rar
Ok, I found what I did wrong. PdfTrueTypeFont object must be created before PdfCellStyle (not inside).