我使用ITextSharp处理PDF注释。我能够非常顺利地添加注释。 但现在我正在尝试编辑它们。看起来我的PdfReader对象实际上已更新。但由于某种原因,我无法保存它。如下面的代码段所示,我尝试使用压模获取字节数组。无论注释有多长,字节数组只比前一版本长1个字节。当我打开保存在文件系统上的PDF时,我仍然有旧的注释......
private void UpdatePDFAnnotation(string title, string body)
{
byte[] newBuffer;
using (PdfReader pdfReader = new PdfReader(dataBuffer))
{
int pageIndex = 1;
int annotIndex = 0;
PdfDictionary pageDict = pdfReader.GetPageN(pageIndex);
var annots = pageDict.GetAsArray(PdfName.ANNOTS);
if (annots != null)
{
PdfDictionary annot = annots.GetAsDict(annotIndex);
annot.Put(PdfName.T, new PdfString(title));
annot.Put(PdfName.CONTENTS, new PdfString(body));
}
// ********************************
// this line shows the new annotation is in here. Just have to save it somehow !!
var updatedBody = pdfReader.GetPageN(pageIndex).GetAsArray(PdfName.ANNOTS).GetAsDict(0).GetAsString(PdfName.CONTENTS);
Debug.Assert(newBody == updatedBody.ToString(), "Annotation body should be equal");
using (MemoryStream outStream = new MemoryStream())
{
using (PdfStamper stamp = new PdfStamper(pdfReader, outStream, '\0', true))
{
newBuffer = outStream.ToArray();
}
}
}
File.WriteAllBytes( @"Assets\Documents\AnnotedPdf.pdf", newBuffer);
}
知道我的代码有什么问题吗?
答案 0 :(得分:0)
height:0px
在关闭时完成了大部分的写作。这隐含地发生在PdfStamper
块的末尾。但是您检索该块中已有的using
内容。因此,PDF尚未写入检索到的MemoryStream
。
而是在检索byte[]
之前显式关闭PdfStamper
实例:
byte[]
或在using (PdfStamper stamp = new PdfStamper(pdfReader, outStream, '\0', true))
{
stamp.Close();
newBuffer = outStream.ToArray();
}
阻止之后检索byte[]
:
using
答案 1 :(得分:0)
private void UpdatePDFAnnotation(string title, string body)
{
using (PdfReader pdfReader = new PdfReader(dataBuffer))
{
PdfDictionary pageDict = pdfReader.GetPageN(pageIndex);
var annots = pageDict.GetAsArray(PdfName.ANNOTS);
PdfDictionary annot = annots.GetAsDict(annotIndex);
annot.Put(PdfName.T, new PdfString(title));
annot.Put(PdfName.CONTENTS, new PdfString(body));
using (MemoryStream ms = new MemoryStream())
{
PdfStamper stamp = new PdfStamper(pdfReader, ms);
stamp.Dispose();
dataBuffer = ms.ToArray();
}
}
}