c# - PdfContentByte.SetFontAndSize() 抛出 "Object reference not set to instance of object"

标签 c# pdf itext

我正在尝试添加一个文本框注释,其文本具有指定的字体和大小。代码如下:

void addTextBox(string inputPath,string outputPath)
{
    PdfReader pdfReader = new PdfReader(inputPath);
    PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(outputPath, FileMode.Create));
    PdfContentByte pcb = new PdfContentByte(pdfStamper.Writer);
    BaseFont baseFont = FontFactory.GetFont(FontFactory.HELVETICA).BaseFont;
    float fontsize = 32;
    pcb.SetFontAndSize(baseFont, fontsize);
    PdfAnnotation textbox = PdfAnnotation.CreateFreeText(pdfStamper.Writer, new iTextSharp.text.Rectangle(200, 200, 3000, 3000), "Here is a Textbox", pcb);
    pdfStamper.AddAnnotation(textbox, 1);
    pdfStamper.Close();
}

pcb.SetFontAndSize() 调用抛出异常:

Object reference not set to an instance of an object.

pcb 发生此错误时已实例化,并且 fontsize 已成功分配其数值,那么这里未分配的对象是什么?

最佳答案

PdfContentByte(pdfStamper.Writer) 替换为 pdfStamper.GetOverContent(1),问题就会消失。

关于c# - PdfContentByte.SetFontAndSize() 抛出 "Object reference not set to instance of object",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36757457/

相关文章:

pdf - 在 iTextSharp 中,如何在创建新文档时包含现有 PDF

c# - 如何在 JavaScript 中将日期时间格式化为字符串?

javascript - 如何使用 wkhtmltopdf 获取由 html 生成的 pdf 中的页码

ios - 在不显示打印界面的情况下,在 Swift 中从 HTML 生成带有图像的 PDF

java - iText - 如果特定行位于页面底部,则在下一页上设置特定行

android - iText 作为文本在 Android 上从 PDF 中提取/读取

javascript - 需要将 Azure blob 文件从一个文件夹复制到另一个文件夹并创建 zip

C# JSON 反序列化 : Type is an interface or abstract class and cannot be instantiated

c# - 通过最大化和恢复浏览器窗口调整大小的双滚动条

c# - iTextSharp : How to resize an image to fit a fix size?