【发布时间】:2015-11-09 23:22:35
【问题描述】:
我正在使用 ITextSharp 将多页 PDF 文件拆分为单页文件。我还设法使用 MemoryStream 将这些单页 PDF 添加到 zip 文件中。
现在,我需要使用 PdfStamper 为这些 PDF 添加密码保护,然后再将它们添加到 zip 文件中。但是每当我尝试这个时,就会抛出一个ObjectDisposedException - Cannot access a closed Stream.。
Ionic.Zip.ZipFile zipFile = new Ionic.Zip.ZipFile();
int cnt = 0;
try
{
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdfPath), new ASCIIEncoding().GetBytes(""));
for (cnt = 1; cnt <= reader.NumberOfPages; cnt++)
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (iTextSharp.text.Document document = new iTextSharp.text.Document())
{
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, memoryStream);
using (PdfStamper stamper = new PdfStamper(reader, memoryStream))
{
stamper.SetEncryption(
null,
Encoding.ASCII.GetBytes("password_here"),
PdfWriter.ALLOW_PRINTING,
PdfWriter.ENCRYPTION_AES_128);
}
memoryStreamForZipFile = new MemoryStream(memoryStream.ToArray());
memoryStreamForZipFile.Seek(0, SeekOrigin.Begin);
}
}
}
zipFile.Save(destinationFolder + "/" + fileName.Replace(".pdf", ".zip"));
reader.Close();
reader.Dispose();
}
catch
{
}
finally
{
GC.Collect();
}
return cnt - 1;
为了清楚起见,我删除了上面的一些代码。
如果我删除 PdfStamper“使用”块,代码就可以正常工作。我还尝试调整 PdfStamper 的位置,看看我是否在错误的地方使用它。
我没有正确使用using 块吗?或者我必须在这里修复一些代码序列?
【问题讨论】:
标签: c# pdf itextsharp memorystream