我需要删除pdf的所有表单字段,因此我使用iText并尝试压缩pdf。
由于遗留代码,我仅限于iText版本4.1.6.1
我的代码是:
public static byte[] RemoveAcroFields(String filename)
{
if (filename != null && File.Exists(filename))
{
byte[] pdfFile = File.ReadAllBytes(filename);
PdfReader reader = new PdfReader(pdfFile);
MemoryStream stream = new MemoryStream(pdfFile);
PdfStamper stamper = new PdfStamper(reader, stream);
stamper.FormFlattening = true;
stamper.Close();
var flattenedPdfBytes = stream.ToArray();
reader.Close();
stream.Close();
return flattenedPdfBytes;
}
else
{
return null;
}
}
这会产生此异常
bei System.IO.MemoryStream.set_Capacity(Int32 value)
bei System.IO.MemoryStream.set_Capacity(Int32 value)
bei System.IO.MemoryStream.EnsureCapacity(Int32 value)
bei System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
当我取消注释stamper.close()方法时,没有发生异常,但生成的pdf尚未展平
答案 0 :(得分:1)
以防万一有类似问题。我可以通过将PdfStamper的InputStream从MemoryStream更改为FileStream来解决它。有了这个改变,它对我有用。
public static void RemoveAcroFields(String filename)
{
if (filename != null && File.Exists(filename))
{
byte[] pdfFile = File.ReadAllBytes(filename);
PdfReader reader = new PdfReader(pdfFile);
PdfStamper stamper = new PdfStamper(reader, new FileStream(filename, FileMode.Create));
stamper.FormFlattening = true;
stamper.Close();
reader.Close();
}
}