如何在c#中使用iTextSharp合并之前知道损坏的PDF文件

本文关键字:损坏 文件 PDF 合并 iTextSharp | 更新日期: 2023-09-27 18:15:39

我正在使用iTextSharp合并pdf页面。

但他们可能是一些损坏的pdf。

我的问题是,如何以编程方式验证pdf是否损坏?

如何在c#中使用iTextSharp合并之前知道损坏的PDF文件

我通常检查文件的头,看看它是什么类型的文件。PDF头总是以%PDF开头。

当然文件可能会损坏后的头,然后我不确定是否有任何其他的方式,而不是只是试图打开并从文档中读取。当文件损坏时,打开或读取该文档可能会产生异常。我不确定iTextSharp抛出各种异常,但我认为你可以测试出来。

由于您正在合并文件,一种方法是将代码包装在try...catch块中:

Dictionary<string, Exception> errors = 
  new Dictionary<string, Exception>();
document.Open();
PdfContentByte cb = writer.DirectContent;
foreach (string filePath in testList) {
  try {
    PdfReader reader = new PdfReader(filePath);
    int pages = reader.NumberOfPages;
    for (int i = 0; i < pages; ) {
      document.NewPage();
      PdfImportedPage page = writer.GetImportedPage(reader, ++i);
      cb.AddTemplate(page, 0, 0);
    }
  }
// **may** be PDF spec, but not supported by iText      
  catch (iTextSharp.text.exceptions.UnsupportedPdfException ue) {
    errors.Add(filePath, ue);
  }
// invalid according to PDF spec
  catch (iTextSharp.text.exceptions.InvalidPdfException ie) {
    errors.Add(filePath, ie);
  }
  catch (Exception e) {
    errors.Add(filePath, e);
  }
}
if (errors.Keys.Count > 0) {
  document.NewPage();
  foreach (string key in errors.Keys) {
    document.Add(new Paragraph(string.Format(
      "FILE: {0}'nEXCEPTION: [{1}]: {2}",
      key, errors[key].GetType(), errors[key].Message
    )));
  }
}

其中testList是要合并的PDF文档的文件路径集合。

另一方面,您还需要考虑您定义的损坏的。市面上有许多PDF文档不符合PDF规范,但有些阅读器(Adobe Reader)足够聪明,可以即时修复它们。