我使用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函數使用不同的字體,如果它是,如何?