0
我試圖使用下面的代碼合併文件夾中的pdf文件並輸出到一個新的文件,但顯然生成的文件似乎損壞。使用itextsharp合併文件夾內的pdf文件
public Boolean MergeForm(String destinationFile, String sourceFolder)
{
try
{
using (MemoryStream stream = new MemoryStream())
using (Document doc = new Document())
using (PdfCopy pdf = new PdfCopy(doc, stream))
{
doc.Open();
PdfReader reader = null;
PdfImportedPage page = null;
foreach (var file in Directory.GetFiles(sourceFolder))
{
reader = new PdfReader(file);
for (int i = 0; i < reader.NumberOfPages; i++)
{
page = pdf.GetImportedPage(reader, i + 1);
pdf.AddPage(page);
}
pdf.FreeReader(reader);
reader.Close();
}
using (FileStream streamX = new FileStream(destinationFile, FileMode.Create))
{
stream.WriteTo(streamX);
}
}
return true;
}
catch (Exception)
{
return false;
}
}
任何人都可以發現問題在哪裏?謝謝。
這看起來非常像最近的問題的重複[使用PdfCopy合併PDF文件(https://stackoverflow.com/questions/45951966/using-pdfcopy-to-merge-pdf-files)。爲什麼不使用AddDocument()方法而不是循環遍歷不同的頁面,並且一次只添加一個頁面?您是否正在使用最新版本的iText? –
但是,主要問題是您正在編寫文件的那一刻。當你做'stream.WriteTo(streamX)'時,'Document'實例還沒有關閉。這意味着寫入'streamX'的PDF不完整。大量的信息(如交叉引用表,字體,PDF預告片)缺失。當docClose()發生時,這些信息只能添加到'stream'中。在你的情況下,當*'stream.WriteTo(streamX)'後面的括號*中的一個被隱式地發生時。 –
@BrunoLowagie我正在使用itextsharp 5.5.12.0。 btw,如何修改代碼以使用AddDocument? 我會看看你在這裏分享的另一個線索,謝謝。 – Trowa