2016-01-29 152 views
0

嗨,我试图用ItextSharp.dll读取各种pdf文件,其中一些尝试读取它时会引发异常。这是一个例外:“文档没有页面根目录(意思是:这是一个无效的PDF)”。我在合并示例中,在Itext网页(Merge-Example)中做了一些测试,并且这些都是成功的。那么,有人能指导我看看我做错了什么吗? 这是我的代码:ItextSharp-Exception in the reader initialization“The document has no page root”

public void MergeFiles(String[] strFiles, String strFileresult) 
    { 
     Document document = new Document(); ; 
     PdfCopy copy; 

     copy = new PdfCopy(document, new FileStream(strFileresult, FileMode.Create)); 
     document.Open(); 

     PdfReader[] reader = new PdfReader[3]; 

     for (int i = 0; i < strFiles.Count(); i++) 
     { 

      reader[i] = new PdfReader(strFiles[i]); 
      copy.AddDocument(reader[i]); 
     } 
     document.Close(); 
     for (int i = 0; i < reader.Count(); i++) 
     { 
      reader[i].Close(); 
     } 
    } 

回答

0

我不知道是什么导致你确切的问题,但一旦我们摆脱了不必要的内部阵列,并切换到using模式得到自动清理一切工作就好了。

public void MergeFiles(string[] strFiles, String strFileresult) { 
    using(var document = new Document()) { 
     using (var copy = new PdfCopy(document, new FileStream(strFileresult, FileMode.Create))) { 

      document.Open(); 

      foreach(var file in strFiles) { 
       using (var reader = new PdfReader(file)) { 
        copy.AddDocument(reader); 
       } 
      } 

      document.Close(); 
     } 
    } 
} 
+0

感谢您的回复,我尝试了您的方法,但一直在这一行中抛出相同的异常“使用(var reader = new PdfReader(file))”。 这个例外只出现在一些文件中,但奇怪的是:测试页正在处理好冲突文件。 –

+0

你可以发布问题文件供我们检查吗? –

+0

确定这是该文件。 [PDF](https://drive.google.com/folderview?id=0B76us6MtUwziNFJKUkxwczlQTkE&usp=sharing) –

相关问题