Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中使用iTextSharp合并之前,如何知道已损坏的PDF文件#_C#_Itextsharp - Fatal编程技术网

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

C# 在C中使用iTextSharp合并之前,如何知道已损坏的PDF文件#,c#,itextsharp,C#,Itextsharp,我正在使用iTextSharp合并pdf页面 但它们可能是一些损坏的pdf 我的问题是,如何以编程方式验证pdf是否已损坏?我通常检查文件头以查看它是什么类型的文件。PDF标题始终以%PDF开头 当然,文件在头之后可能会损坏,那么我不确定除了尝试打开和读取文档之外是否还有其他方法。当文件损坏时,打开或读取该文档可能会出现异常。我不确定iTextSharp是否会抛出所有类型的异常,但我认为您可以对此进行测试。由于您正在合并文件,一种方法是将代码包装在一个try…catch块中: Dictionar

我正在使用iTextSharp合并pdf页面

但它们可能是一些损坏的pdf


我的问题是,如何以编程方式验证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
    )));
  }
}
字典错误=
新字典();
document.Open();
PdfContentByte cb=writer.DirectContent;
foreach(testList中的字符串文件路径){
试一试{
PdfReader reader=新的PdfReader(文件路径);
int pages=reader.NumberOfPages;
对于(int i=0;i0){
document.NewPage();
foreach(错误中的字符串键。键){
文件。添加(新段落)(string.Format(
“文件:{0}\n异常:[{1}]:{2}”,
键,错误[key]。GetType(),错误[key]。消息
)));
}
}
其中,
testList
是要合并的PDF文档的文件路径集合

在单独的注释中,还需要考虑定义为腐败的内容。有许多PDF文档不符合PDF规范,但一些阅读器(Adobe Reader)足够聪明,可以动态修复它们