【发布时间】:2015-11-23 10:45:24
【问题描述】:
我正在使用 iTextSharp 从模板生成一个 pdf 文件,并填充此代码部分中的每个字段:
PdfReader pdfReader = new PdfReader(templatePath);
try
{
using (FileStream newFileStream = new FileStream(newFilePath, FileMode.Create))
{
using (PdfStamper stamper = new PdfStamper(pdfReader, newFileStream))
{
// fill each field
AcroFields pdfFormFields = stamper.AcroFields;
foreach (KeyValuePair<string, string> entry in content)
{
if (!String.IsNullOrEmpty(entry.Value))
pdfFormFields.SetField(entry.Key, entry.Value);
}
//The below will make sure the fields are not editable in
//the output PDF.
stamper.FormFlattening = true;
stamper.Close();
}
}
}
finally
{
pdfReader.Close();
}
一切正常,文件看起来不错,但是当我尝试重新打开文件以将其与我在唯一文档中生成的其他文件合并时,我收到此错误:
2015-11-23 09:46:54,651||ERROR|UrbeWeb|System.IO.IOException: The process cannot access the file 'D:\Sviluppo\communitygov\MaxiAnagrafeImmobiliare\MaxiAnagrafeImmobiliare\cache\IMU\E124\admin\Stampe\Provvedimento_00223850306_2015_11_23_094654.pdf' because it is being used by another process.
此时出现错误
foreach (Documento item in docs)
{
string fileName = item.FilePath;
pdfReader = new PdfReader(fileName); // IOException
// some other operations ...
}
编辑:按照建议使用进程监视器,我可以看到没有像我预期的那样关闭 CloseFile 操作。这可能是问题的根源吗?
我已经坚持了好几个小时了,真的非常感谢任何帮助。
【问题讨论】:
-
您是否尝试过使用源代码进行调试(它们可用)?用 FileMon 查看文件句柄?
-
您是否打开了任何 PDF 文件,例如Adobe阅读器?某些应用程序会在打开文件时锁定文件以进行编辑。
-
另一个小点:你关闭了
stamper和pdfReader,但你没有关闭newFileStream。using无论如何都应该处理掉它,所以它可能没有任何区别...... -
@LNyarla,
PdfStamper可以绑定到Stream的任何子类,所以mkl 的意思是使用MemoryStream而不是FileStream,只需将PDF 作为字节数组获取在MemoryStream上使用ToArray()。此外,您会看到Close()经常被调用,但正如您所指出的并且 mkl 响应它是不需要的。这只是“如果您打开某些东西就应该关闭它”心态的产物(我总是这样做),但您可以跳过它。
标签: c# itextsharp