我使用iTextSharp来加载现有的PDF并使用PdfStamper添加文本。我想完全控制文本,这意味着我希望能够控制字体(仅TrueType),字体大小和坐标。现在,我正在使用ShowTextAligned将文本添加到某些坐标,setFontAndSize设置字体和字体大小。这是我的代码添加文字:使用iTextSharp和PDFStamper在PDF中使用不同的字体
private void AddText(BaseFont font, string text, int x, int y, int size)
{
pdf.BeginText();
pdf.SetFontAndSize(font, size);
pdf.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, x, y, 0);
pdf.EndText();
}
下面的函数是用来加载TrueType字体:
public BaseFont GetFont(string font, string encoding)
{
if (!(font.EndsWith(".ttf") || font.EndsWith(".TTF")))
font += ".ttf";
BaseFont basefont;
basefont = BaseFont.CreateFont(ConfigurationManager.AppSettings["fontdir"] + font, encoding, BaseFont.NOT_EMBEDDED);
if (basefont == null)
throw new Exception("Could not load font '" + font + "' with encoding '" + encoding + "'");
return basefont;
}
下面的代码是用来加载现有的PDF:
Stream outputPdfStream = Response.OutputStream;
PdfReader pdfReader = new PdfReader(new RandomAccessFileOrArray(HttpContext.Current.Request.MapPath("PdfTemplates/" + ConfigurationManager.AppSettings["pdf_template"])), null);
PdfStamper pdfStamper = new PdfStamper(pdfReader, outputPdfStream);
pdf = pdfStamper.GetOverContent(1);
除非我尝试使用不同的字体,否则这一切都可以很好地工作。所以当用不同的字体多次调用AddText时,当openend时,PDF将显示一个通用错误。我想知道是否可以使用ShowTextAligned函数使用不同的字体,如果它是,如何?