2016-03-22 2 views
0

Я хотел бы получить все имена файлов вложений/вложенных файлов PDF-документа. Я давно искал, но мой код все еще не работает.Список pdf Вложения с использованием PDFBox (Java)

Что я пробовал:

File input = new File(inputfile); // Input File Path, Given as param from args[] 
pd = PDDocument.load(input); 
PDDocumentNameDictionary names = new PDDocumentNameDictionary(pd.getDocumentCatalog()); 
PDEmbeddedFilesNameTreeNode efTree = names.getEmbeddedFiles(); 
Map<String, COSObjectable> existedNames = efTree.getNames(); 

System.out.println(existedNames);//Print Embedded-Filenames to console 
pd.close(); 

Я не знаю, если это возможно даже напечатать содержание ПДЧ на консоль. Я кодирую в eclipse, который не дает мне никаких ошибок. Но когда я запускаю файл jar, я получаю всегда: NullPointerException at org.apache.pdfbox.pdmodel.PDDocument.getDocumentCatalog(PDDocument.java:778)

Любые идеи или помощь? Большое спасибо ...

+0

PDDocument.load(), вероятно, терпит неудачу и возвращает нулевое значение – user489041

+0

PDDocument.load() работает. Я знаю, потому что я делаю другие вещи с «pd» до ... Что-то со следующими тремя строками (после загрузки pd = ...) должно быть неправильным:/ – Nicola

+0

В нескольких примерах я увидел «Map existedNames = efTree.getNames(); 'но когда я изменяю это в eclipse, он дает мне ошибку:' Тип несоответствия: Невозможно преобразовать из Map в Map ' – Nicola

ответ

0

Наконец нашел решение. Для тех, кто с той же проблемой, следующий код работает для меня:

PDDocument pd; 

File input = new File(inputfile); // Input File 

pd = PDDocument.load(input); 

//Writes all embedded Filenames (from pdf document) into Logfile 
try{ 
    PDDocumentCatalog catalog = pd.getDocumentCatalog(); 
    PDDocumentNameDictionary names = catalog.getNames(); 
    PDEmbeddedFilesNameTreeNode embeddedFiles = names.getEmbeddedFiles(); 
    Map<String, COSObjectable> embeddedFileNames = embeddedFiles.getNames(); 

    //For-Each Loop is used to list all embedded files (if there is more than one)   
    for (Map.Entry<String, COSObjectable> entry : embeddedFileNames.entrySet()) 
    { 
     //You might need to configure the logger first 
     logger.info("Inputfile: " + inputfile +"Found embedded File: " + entry.getKey() + ":"); 
    } 

} 
catch (Exception e){ 
    System.out.println("Document has no attachments. "); 
} 
0

Вот ExtractEmbeddedFiles example из исходного кода загрузки:

public final class ExtractEmbeddedFiles 
{ 
    private ExtractEmbeddedFiles() 
    { 
    } 

    /** 
    * This is the main method. 
    * 
    * @param args The command line arguments. 
    * 
    * @throws IOException If there is an error parsing the document. 
    */ 
    public static void main(String[] args) throws IOException 
    { 
     if(args.length != 1) 
     { 
      usage(); 
      System.exit(1); 
     } 
     else 
     { 
      PDDocument document = null; 
      try 
      { 
       File pdfFile = new File(args[0]); 
       String filePath = pdfFile.getParent() + System.getProperty("file.separator"); 
       document = PDDocument.load(pdfFile); 
       PDDocumentNameDictionary namesDictionary = 
         new PDDocumentNameDictionary(document.getDocumentCatalog()); 
       PDEmbeddedFilesNameTreeNode efTree = namesDictionary.getEmbeddedFiles(); 
       if (efTree != null) 
       { 
        Map<String, PDComplexFileSpecification> names = efTree.getNames(); 
        if (names != null) 
        { 
         extractFiles(names, filePath); 
        } 
        else 
        { 
         List<PDNameTreeNode<PDComplexFileSpecification>> kids = efTree.getKids(); 
         for (PDNameTreeNode<PDComplexFileSpecification> node : kids) 
         { 
          names = node.getNames(); 
          extractFiles(names, filePath); 
         } 
        } 
       } 

       // extract files from annotations 
       for (PDPage page : document.getPages()) 
       { 
        for (PDAnnotation annotation : page.getAnnotations()) 
        { 
         if (annotation instanceof PDAnnotationFileAttachment) 
         { 
          PDAnnotationFileAttachment annotationFileAttachment = (PDAnnotationFileAttachment) annotation; 
          PDComplexFileSpecification fileSpec = (PDComplexFileSpecification) annotationFileAttachment.getFile(); 
          PDEmbeddedFile embeddedFile = getEmbeddedFile(fileSpec); 
          extractFile(filePath, fileSpec.getFilename(), embeddedFile); 
         } 
        } 
       } 

      } 
      finally 
      { 
       if(document != null) 
       { 
        document.close(); 
       } 
      } 
     } 
    } 

    private static void extractFiles(Map<String, PDComplexFileSpecification> names, String filePath) 
      throws IOException 
    { 
     for (Entry<String, PDComplexFileSpecification> entry : names.entrySet()) 
     { 
      String filename = entry.getKey(); 
      PDComplexFileSpecification fileSpec = entry.getValue(); 
      PDEmbeddedFile embeddedFile = getEmbeddedFile(fileSpec); 
      extractFile(filePath, filename, embeddedFile); 
     } 
    } 

    private static void extractFile(String filePath, String filename, PDEmbeddedFile embeddedFile) 
      throws IOException 
    { 
     String embeddedFilename = filePath + filename; 
     File file = new File(filePath + filename); 
     System.out.println("Writing " + embeddedFilename); 
     FileOutputStream fos = null; 
     try 
     { 
      fos = new FileOutputStream(file); 
      fos.write(embeddedFile.toByteArray()); 
     } 
     finally 
     { 
      IOUtils.closeQuietly(fos); 
     } 
    } 

    private static PDEmbeddedFile getEmbeddedFile(PDComplexFileSpecification fileSpec) 
    { 
     // search for the first available alternative of the embedded file 
     PDEmbeddedFile embeddedFile = null; 
     if (fileSpec != null) 
     { 
      embeddedFile = fileSpec.getEmbeddedFileUnicode(); 
      if (embeddedFile == null) 
      { 
       embeddedFile = fileSpec.getEmbeddedFileDos(); 
      } 
      if (embeddedFile == null) 
      { 
       embeddedFile = fileSpec.getEmbeddedFileMac(); 
      } 
      if (embeddedFile == null) 
      { 
       embeddedFile = fileSpec.getEmbeddedFileUnix(); 
      } 
      if (embeddedFile == null) 
      { 
       embeddedFile = fileSpec.getEmbeddedFile(); 
      } 
     } 
     return embeddedFile; 
    } 

    /** 
    * This will print the usage for this program. 
    */ 
    private static void usage() 
    { 
     System.err.println("Usage: java " + ExtractEmbeddedFiles.class.getName() + " <input-pdf>"); 
    } 
} 
+0

Я знаю пример кода, но это не работает для меня. Мой код также основан на этом примере. – Nicola

+0

@ Никола загрузите файл в формате pdf. Btw какая версия использует? 2.0.0? –

+0

@Nicola Если вы используете версию 1.8, убедитесь, что вы проверяете, зашифрован ли файл. Или используйте loadNonSeq() вместо load(). –