1. 程式人生 > >如何抽取word,excel,pdf

如何抽取word,excel,pdf


public class PdfExtractor {
public PdfExtractor() {
}
public static void main(String args[]) throws Exception
{
FileInputStream in = new FileInputStream ("c://a.doc");
WordExtractor extractor = new WordExtractor();
String str = extractor.extractText(in);
System.out.println("the result length is"+str.length());
System.out.println("the result is"+str);
}
}

3。pdfbox-用來抽取pdf檔案

但是pdfbox對中文支援還不好,先下載pdfbox:http://www.matrix.org.cn/down_view.asp?id=12
下面是一個如何使用pdfbox抽取pdf檔案的例子:
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.pdfparser.PDFParser;
import java.io.*;
import org.pdfbox.util.PDFTextStripper;
import java.util.Date;

public class PdfExtracter{

public PdfExtracter(){
}
public String GetTextFromPdf(String filename) throws Exception
{
String temp=null;
PDDocument pdfdocument=null;
FileInputStream is=new FileInputStream(filename);
PDFParser parser = new PDFParser( is );
parser.parse();
pdfdocument = parser.getPDDocument();
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter( out );
PDFTextStripper stripper = new PDFTextStripper();
stripper.writeText(pdfdocument.getDocument(), writer );
writer.close();
byte[] contents = out.toByteArray();

String ts=new String(contents);
System.out.println("the string length is"+contents.length+"/n");
return ts;
}
public static void main(String args[])
{
PdfExtracter pf=new PdfExtracter();
PDDocument pdfDocument = null;

try{
String ts=pf.GetTextFromPdf("c://a.pdf");
System.out.println(ts);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

4.抽取支援中文的pdf檔案-xpdf

xpdf是一個開源專案,我們可以呼叫他的本地方法來實現抽取中文pdf檔案。
下載xpdf函式包:http://www.matrix.org.cn/down_view.asp?id=15
同時需要下載支援中文的補丁包:http://www.matrix.org.cn/down_view.asp?id=16
按照readme放好中文的patch,就可以開始寫呼叫本地方法的java程式了
下面是一個如何呼叫的例子:
import java.io.*;

public class PdfWin {
public PdfWin() {
}
public static void main(String args[]) throws Exception
{
String PATH_TO_XPDF="C://Program Files//xpdf//pdftotext.exe";
String filename="c://a.pdf";
String[] cmd = new String[] { PATH_TO_XPDF, "-enc", "UTF-8", "-q", filename, "-"};
Process p = Runtime.getRuntime().exec(cmd);
BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
InputStreamReader reader = new InputStreamReader(bis, "UTF-8");
StringWriter out = new StringWriter();
char [] buf = new char[10000];
int len;
while((len = reader.read(buf))>= 0) {
//out.write(buf, 0, len);
System.out.println("the length is"+len);
}
reader.close();
String ts=new String(buf);
System.out.println("the str is"+ts);
}
}