下载相应的iText-5.0.2.jar并放到对应的lib目录下。在工程中创建包并创建测试类,该类包含一个inspect方法用于从一个PDF中获取文本,它接受两个参数,分别是PDF文件路径和输出流,指定要提取的PDF文件的路径和读取PDF所用的输出流,比如:PDF路径为E://text.pdf。然后调用iText提供的PdfReader类和PdfTextExtractor类,将PDF格式的文本提取出来并写入txt文件中。部分代码如下:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
public class PDF {
/** The resulting text file with info about a PDF. */
public static final String RESULT = "d:/ceshi.txt";//存放由pdf转换成txt文件的路径。
/**
* Main method.
* @param args no arguments needed
* @throws DocumentException
* @throws IOException
*/
public static void main(String[] args)
throws DocumentException, IOException {
PrintWriter writer = new PrintWriter(new FileOutputStream(RESULT));//txt文件写入流
String string = "E:/text.pdf";//pdf文件路径
inspect(writer,string); //调用读取方法
writer.close();
}
/**
* Inspect a PDF file and write the info to a txt file
* @param writer Writer to a text file
* @param filename Path to the PDF file
* @throws IOException
*/
public static void inspect(PrintWriter writer, String filename)
throws IOException {
PdfReader reader = new PdfReader(filename); //读取pdf所使用的输出流
int num = reader.getNumberOfPages();//获得页数
String content = ""; //存放读取出的文档内容
for (int i = 1; i < num; i++) {
content += PdfTextExtractor.getTextFromPage(reader, i); //读取第i页的文档内容
}
writer.write(content);//写入文件内容
writer.flush();
}
}
-------j2ee协会吧,欢迎您的到来!
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
public class PDF {
/** The resulting text file with info about a PDF. */
public static final String RESULT = "d:/ceshi.txt";//存放由pdf转换成txt文件的路径。
/**
* Main method.
* @param args no arguments needed
* @throws DocumentException
* @throws IOException
*/
public static void main(String[] args)
throws DocumentException, IOException {
PrintWriter writer = new PrintWriter(new FileOutputStream(RESULT));//txt文件写入流
String string = "E:/text.pdf";//pdf文件路径
inspect(writer,string); //调用读取方法
writer.close();
}
/**
* Inspect a PDF file and write the info to a txt file
* @param writer Writer to a text file
* @param filename Path to the PDF file
* @throws IOException
*/
public static void inspect(PrintWriter writer, String filename)
throws IOException {
PdfReader reader = new PdfReader(filename); //读取pdf所使用的输出流
int num = reader.getNumberOfPages();//获得页数
String content = ""; //存放读取出的文档内容
for (int i = 1; i < num; i++) {
content += PdfTextExtractor.getTextFromPage(reader, i); //读取第i页的文档内容
}
writer.write(content);//写入文件内容
writer.flush();
}
}
-------j2ee协会吧,欢迎您的到来!