使用iTextSharp和PDFStamper在PDF中使用不同的字体

我正在使用iTextSharp加载现有PDF并使用PdfStamper添加文本。 我希望完全控制文本,这意味着我希望能够控制字体(仅限TrueType),字体大小和坐标。 现在,我正在使用ShowTextAligned将文本添加到某些协调,并使用setFontAndSize来设置字体和字体大小。 这是我添加文字的代码:

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时,PDF将在openend时显示一般错误。 我想知道是否可以使用ShowTextAligned函数使用不同的字体,如果是,怎么样?

不是,不是。 它一次只能处理一种字体。 出于好奇,你在做什么来获得糟糕的pdf输出? 我想看看你的代码。

请看一下ColumnText。 有很多例子漂浮在“iText in Action 2nd edition”中。 书中的所有样本都可以在线获得。

谢谢你的答案马克,但我已经解决了这个问题。 我的Content-Type标题出现问题,我用它来告诉浏览器PDF的大小。 这导致浏览器在实际下载整个PDF之前停止下载。 添加新字体时,PDF大小将超过Content-Type标头中指定的大小,从而导致PDF格式错误。 它现在已经解决了,多种字体工作得很好:-)。