我已经得到了一些代码为itextsharp合并2个pdf文件。在某处找到它。合并工作正常,但似乎源文件完成后仍在使用。我想要做的是删除我已经合并的第一个文件,它通过fileupload上传,并且只保留合并的文件。这绝对是执行合并的代码,导致文件保持打开状态。我试图删除服务器上的文件,它告诉我有一些像IIShelper打开的文件。通过几小时的工作,我缩小到了这个东西。为什么它保持文件在使用中?itextsharp不关闭文件
public static void MergeFiles(string destinationFile, string[] sourceFiles)
{
int f = 0;
// we create a reader for a certain document
PdfReader reader = new PdfReader(sourceFiles[f]);
// we retrieve the total number of pages
int n = reader.NumberOfPages;
// step 1: creation of a document-object
Document document = new Document(reader.GetPageSizeWithRotation(1));
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
// step 3: we open the document
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
if(reader.IsEncrypted() == false)
{
// step 4: we add content
while (f < sourceFiles.Length)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(reader.GetPageSizeWithRotation(i));
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
f++;
if (f < sourceFiles.Length)
{
reader = new PdfReader(sourceFiles[f]);
// we retrieve the total number of pages
n = reader.NumberOfPages;
}
}
}
else
{
//is encrypted
}
// step 5: we close the document
document.Close();
reader.Close();
reader.Dispose();
}
在此先感谢
我看到了逻辑,但我似乎无法弄清楚如何去做。我已经试过在所有地方添加reader.close语句无济于事。有时也会引发其他问题。你能否让我知道如何恰当地关闭读者? – user3100712