Exception in thread

Pessoal, estou precisando de um help no programinha abaixo, com urgência:

  1. ele abre uma tela ao usuário e pede o nome do arquivo a ser manipulado
  2. quando dou ENTER, ele exibe as informações sobre o arquivo especificado pelo usuário
  3. mais na frente um pouco, ele testa o tipo do arquivo (pdf, txt e doc)
  4. se for PDF, ele chama o método “chamaConversor” que cria uma cópia TXT para o arquivo PDF na mesma pasta de origem
  5. estava tudo ok até aqui.
  6. agora, ele não retorna mais o controle ao “ConstrutorDeTemplate2.java” e dá a seguinte msg de erro:

Exception in thread “AWT-EventQueue-O” java.lang.NoClassDefFoundError : org/fontbox/afm/FontMetric
at org.pdfbox.pdmodel.font.PDFont.getAFM (PDFont.java:334)

Não estou conseguindo descobrir exatamente onde mexer para resolver o problema. Já tentei um monte de coisas, mas não deram certo.
Qq ajuda, fico muitíssimo grato!

Marcus.

/*
 * ConstrutorDeTemplate2.java
 *
 * Created on 11 de Agosto de 2007, 14:54
 *
 * @author 
 */

package br.unifacs.dis2007.template2;

// Java core packages
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;


// Java extension packages
import javax.swing.*;

import org.pdfbox.*;


public class ConstrutorDeTemplate2 extends JFrame
   implements ActionListener {

   private JTextField enterField;
   private JTextArea outputArea;
   private BufferedWriter out;
   private String word;
   
   private PdfToText conversor = new PdfToText();

   
   // ajusta a interface do usuário
   public ConstrutorDeTemplate2()
   {
      super( "Testing class File" );

      enterField = new JTextField("Digite aqui o nome do arquivo :" );
      enterField.addActionListener( this );
      outputArea = new JTextArea();

      ScrollPane scrollPane = new ScrollPane();
      scrollPane.add( outputArea );

      Container container = getContentPane();
      container.add( enterField, BorderLayout.NORTH );
      container.add( scrollPane, BorderLayout.CENTER );

      setSize( 400, 400 );
      show();
   }

   // Exibe as informações sobre o arquivo especificado pelo usuário
   public void actionPerformed( ActionEvent actionEvent )
   {
      File name = new File( actionEvent.getActionCommand() );

      // Se o arquivo existe, envia para a saída as informações sobre ele
      if ( name.exists() ) {
         outputArea.setText(
            name.getName() + " exists\n" +
            ( name.isFile () ? 
               "is a file\n" : "is not a file\n" ) +
            ( name.isDirectory() ? 
               "is a directory\n" : "is not a directory\n" ) +
            ( name.isAbsolute() ? "is absolute path\n" : 
               "is not absolute path\n" ) +
            "Last modified: " + name.lastModified() +
            "\nLength: " + name.length () +
            "\nPath: " + name.getPath() +
            "\nAbsolute path: " + name.getAbsolutePath() +
            "\nParent: " + name.getParent() );
         
         // informação de saída se "name" é um arquivo 
         if ( name.isFile() ) {

            String nameString = String.valueOf(name.getPath());
            String nameTeste = new String(nameString);
            
            
            if (nameString.endsWith(".pdf")) 

                nameTeste = chamaConversor(nameString);

            else
            {
                if (nameString.endsWith(".doc"))
                    nameTeste = chamaConversorDoc(nameString); // chama conversor de arquivos DOC
                else 
                    if (nameString.endsWith(".txt"))
                        nameTeste = nameString;
            }

           
            // se o arquivo termina com ".txt"           
            if (nameTeste.endsWith(".txt"))
            {

           
                // acrescenta conteúdo do arquivo à área de saída

                try {
                    // Create the tokenizer to read from a file
                    FileReader rd = new FileReader(nameTeste);
                    StreamTokenizer st = new StreamTokenizer(rd); 
    
                    // Prepare the tokenizer for Java-style tokenizing rules
                    st.parseNumbers();
                    st.wordChars('_', '_');
                    st.eolIsSignificant (true);
    
                    // If whitespace is not to be discarded, make this call
                    st.ordinaryChars(0, ' ');
    
                    // These calls caused comments to be discarded 
                    st.slashSlashComments(true);
                    st.slashStarComments(true);
    
                    // Parse the file
                    int token = st.nextToken();
                    String word_ant = ""; 
                    outputArea.append( " \n" );
                    out = new BufferedWriter(new FileWriter(nameTeste, true));
        
                    while (token != StreamTokenizer.TT_EOF) {
                        token = st.nextToken();
                                        
                        if (token == StreamTokenizer.TT_EOL){
                            //out.write(word);
                            out.flush();
                            out = new BufferedWriter(new FileWriter(nameTeste, true));
                            //outputArea.append( word + "\n" );
                            // out.append ( "\n" );
                        }
            
                        switch (token) {
                            
                        case StreamTokenizer.TT_NUMBER:
                            // A number was found; the value is in nval 
                            double num = st.nval;
                            break;
                        case StreamTokenizer.TT_WORD:
                            // A word was found; the value is in sval 
                            word = st.sval;
                            //   if (word_ant.equals("a") || word_ant.equals("an") || word_ant.equals("the") || word_ant.equals("The") || word_ant.equals("An")) 
                            //   {
                            outputArea.append( word.toString() + " \n " );
                           // out.append( word + "   " );
                            //    } 
               
                            //     word_ant = word;
                            break;
                        case '"':
                            // A double-quoted string was found; sval contains the contents 
                            String dquoteVal = st.sval;
                            break;
                        case '\'':
                            // A single-quoted string was found; sval contains the contents 
                            String squoteVal = st.sval;
                            break;
                        case StreamTokenizer.TT_EOL:
                            // End of line character found
                            break; 
                        case StreamTokenizer.TT_EOF:
                            // End of file has been reached
                            break;
                        default:
                            // A regular character was found; the value is the token itself 
                            char ch = (char)st.ttype;
                            break;
                        } // fim do switch
                    } // fim do while
                
                    rd.close();
                    out.close(); 
                } // fim do try 

             
                // process file processing problems
                catch( IOException ioException ) {
                    JOptionPane.showMessageDialog( this,
                    "FILE ERROR", 
                    "FILE ERROR", JOptionPane.ERROR_MESSAGE );
                }
      
            } // fim do if da linha 92 - testa se o arquivo é do tipo texto
            
         } // fim do if da linha 78 - testa se é um arquivo 

         // output directory listing
         else if ( name.isDirectory() ) {
                String directory[] = name.list();
   
            outputArea.append( "\n\nDirectory contents:\n");
   
            for ( int i = 0; i < directory.length; i++ )
               outputArea.append( directory[ i ] + "\n" );
         } // fim do else if da linha 184 - testa se é um diretório
            
            
      } // fim do if da linha 62 - testa se o arquivo existe

      // not file or directory, output error message
      else {
         JOptionPane.showMessageDialog( this,
            actionEvent.getActionCommand() + " Does Not Exist",
            "ERROR", JOptionPane.ERROR_MESSAGE );
      }       

   }  // fim do método actionPerformed

   

   // método que chama o conversor
   
   public String chamaConversor(String arquivoPdf){
       
       String arquivoTxt = new String(arquivoPdf);
   
       arquivoTxt = arquivoPdf.replace(".pdf", ".txt"); 
   
       try {

           conversor.pdfToText(arquivoPdf,arquivoTxt);

       } 
       catch (Exception ex) {
           ex.printStackTrace();
       }
       

       return (arquivoTxt);
   }


   
   // executa a aplicação
   public static void main( String args[] )
   {
      ConstrutorDeTemplate2 application = new ConstrutorDeTemplate2();
      
      application.setDefaultCloseOperation (
         JFrame.EXIT_ON_CLOSE );
   } // fim do método main

}  // fim da classe ExtratorDeSubstantivos2 


*************************************************************

/*
 * PdfToText.java
 *
 * Created on 11 de Agosto de 2007, 10:57
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

//package br.unifacs.dis2007.template2;

/**
 *
 * @author www
 */

package br.unifacs.dis2007.template2;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL ;

import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.pdmodel.encryption.AccessPermission;
import org.pdfbox.pdmodel.encryption.StandardDecryptionMaterial;
import org.pdfbox.util.PDFText2HTML;
import org.pdfbox.pdmodel.font.PDFont.* ;
import org.pdfbox.util.PDFTextStripper;
import org.pdfbox.util.*;
import org.pdfbox.pdmodel.*;

 

public class PdfToText
{


   public void pdfToText( String pdfFile, String textFile) throws Exception
   {
           Writer output = null;
           PDDocument document = null;

           try
           {
               try
               {
                   //basically try to load it from a url first and if the URL
                   //is not recognized then try to load it from the file system. 
                   URL url = new URL( pdfFile );
                   document = PDDocument.load( url );
                   String fileName = url.getFile();
                   if( textFile == null && fileName.length () >4 )
                   {
                       File outputFile =
                           new File( fileName.substring( 0,fileName.length() -4 ) + ".txt" );
                       textFile = outputFile.getName();

                   }
               }
               catch( MalformedURLException e )
               {
                   document = PDDocument.load( pdfFile );
                   if( textFile == null && pdfFile.length() >4 )
                   {
                       textFile = pdfFile.substring( 0,pdfFile.length() -4 ) + ".txt";
  
  
                   }
               }
                  //use default encoding 
                 output = new OutputStreamWriter( new FileOutputStream( textFile ) );


               PDFTextStripper stripper = null;
               stripper = new PDFTextStripper();
               stripper.writeText( document, output );
           }
           finally
           {
               if( output != null )
               {
                   output.close();
               }
               if( document != null )
               {
                   document.close();
               } 
           }//finally
       }//end funcao


}

Está faltando um .jar no seu projeto(Classpath) , inclui o :

PDFBox-0.7.3/external/FontBox-0.1.0-dev.jar

Se continuar dando java.lang.NoClassDefFoundError, procure nos .jar dentro do diretório do PDFBox, senão procura no Goooooooogle …

Eu estou usando o NetBeans IDE 5.5.
Adicionei todas as bibliotecas abaixo ao meu projeto a partir do diretório c:\Program Files\netbeans-5.5\PDFBox-0.7.3\external:

  • FontBox-0.1.0-dev.jar
  • ant.jar
  • bcmail-jdk14-132.jar
  • junit.jar
  • bcprov-jdk14-132.jar
  • lucene-core-2.0.0.jar
  • checkstyle-all-4.2.jar
  • lucene-demos-2.0.0.jar

e PDFBox-0.7.3.jar do c:\Program Files\netbeans-5.5\PDFBox-0.7.3\lib.

Não achei mais nenhum arquivo jar na pasta PDFBox-0.7.3.

Todas estas bibliotecas estão na Aba “Compile-time Libraries” na Project Properties. Eu deveria adicioná-las também na Aba “Run-time Libraries”?

Mais uma vez obrigado pela atenção.