C# 关闭物体后,不得进行处理
我需要拆分一个pdf,我使用以下代码:C# 关闭物体后,不得进行处理,c#,pdf,itext,C#,Pdf,Itext,我需要拆分一个pdf,我使用以下代码: using iTextSharp.text; using iTextSharp.text.pdf; private static void PDF_ExtractPages(string pdfFilePath, string outputPath) { int pageNameSuffix = 0; // Intialize a new PdfReader instance with the c
using iTextSharp.text;
using iTextSharp.text.pdf;
private static void PDF_ExtractPages(string pdfFilePath, string outputPath)
{
int pageNameSuffix = 0;
// Intialize a new PdfReader instance with the contents of the source Pdf file:
//PdfReader reader = new PdfReader(pdfFilePath);
using (PdfReader reader = new PdfReader(pdfFilePath))
{
FileInfo file = new FileInfo(pdfFilePath);
string pdfFileName = file.Name.Substring(0, file.Name.LastIndexOf(".")) + "-";
for (int pageNumber = 1; pageNumber <= reader.NumberOfPages; pageNumber++)
{
pageNameSuffix++;
string newPdfFileName = string.Format(pdfFileName + "{0}", pageNameSuffix);
Document document = new Document();
PdfCopy copy = new PdfCopy(document, new FileStream(outputPath + "\\" + newPdfFileName + ".pdf", FileMode.Create));
document.Open();
copy.AddPage(copy.GetImportedPage(reader, pageNumber));
document.Close();
copy.Close();
}
}
}
PdfReader reader = new PdfReader(pdfFilePath);
如果我删除了使用此代码的选项:
using iTextSharp.text;
using iTextSharp.text.pdf;
private static void PDF_ExtractPages(string pdfFilePath, string outputPath)
{
int pageNameSuffix = 0;
// Intialize a new PdfReader instance with the contents of the source Pdf file:
//PdfReader reader = new PdfReader(pdfFilePath);
using (PdfReader reader = new PdfReader(pdfFilePath))
{
FileInfo file = new FileInfo(pdfFilePath);
string pdfFileName = file.Name.Substring(0, file.Name.LastIndexOf(".")) + "-";
for (int pageNumber = 1; pageNumber <= reader.NumberOfPages; pageNumber++)
{
pageNameSuffix++;
string newPdfFileName = string.Format(pdfFileName + "{0}", pageNameSuffix);
Document document = new Document();
PdfCopy copy = new PdfCopy(document, new FileStream(outputPath + "\\" + newPdfFileName + ".pdf", FileMode.Create));
document.Open();
copy.AddPage(copy.GetImportedPage(reader, pageNumber));
document.Close();
copy.Close();
}
}
}
PdfReader reader = new PdfReader(pdfFilePath);
代码可以工作,但不能处理reader对象,当我尝试打开PDF时,会收到这样的消息:“此文档已被其他用户打开”
有没有办法处理PdfReader和所有内部代码
谢谢 这就是为什么它没有实现
IDisposable
您可以使用try catch
块,这是一种等效的方法
PdfReader reader = null;
try
{
reader = new PdfReader(pdfFilePath);
// Some code here
}
catch (Exception)
{
// Take some action.
}
finally
{
reader.Dispose();
}
谢谢,但读者不包含dispose方法。出于这个原因,我发布了这个问题。@Marco999谢谢,我怀疑发生这种情况是因为我从nuget软件包ItextSharp.LGPLV2.Core(1.7.1)获得了我的版本,这是ItextSharp For.net Core的非官方端口。你能建议一些解决方法吗?如果你没有使用该端口的任何具体要求,我建议你使用iTextSharp。iTextSharp最新的稳定版本5.5.13.2是EOL,已被iText 7取代(具有“隐藏”定价,但它也有一个免费的开源版本,带有AGPL许可证),但未来将添加安全修复程序。非常感谢您的建议。