我已經得到了一些代碼爲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