场景
需要按照表格的内容输出为PDF,当写入中文时:
string path = @"P_C_X.pdf";
FileStream pdfFS = new FileStream(path, FileMode.Create);
Document doc = new Document(iTextSharp.text.PageSize.A4.Rotate(), 3.19f, 3.19f, 5.04f, 2.54f);
PdfWriter writer = PdfWriter.GetInstance(doc, pdfFS);
doc.Open();
PdfContentByte cb = writer.DirectContent;
System.Text.Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
BaseFont font = BaseFont.CreateFont(@"C:\Windows\Fonts\simkai.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.BeginText();
cb.SetFontAndSize(font, 15);
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "加油", 88, 340, 0);
写入失败,但英文可以正常写入。
解决
改用BaseFont.IDENTITY_H:
BaseFont font = BaseFont.CreateFont(@"C:\Windows\Fonts\simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);