如果你在工作的时候经常接触到pdf,那么很有可能碰到这些情况,比如pdf文档不能复制和粘贴,有些pdf文件的拥有者也可能为了数据不被窃取和传播,禁用了pdf文档的打印功能,这样数据就只能浏览,而不能复印分发。这些情况许多时候会为工作造成不小的麻烦,现在使用一个Java小工具就可以解决这个问题。
主要是用到apache的pdfbox工具。以后可以做成一个在线解锁PDF的网站。
源码如下:
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStreamWriter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
public class Pdf2text {
public static String getTxt(File f) throws Exception {
String ts="";
try{
String temp = "";
PDDocument pdfdocument = PDDocument.load(f);
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out);
PDFTextStripper stripper = new PDFTextStripper();
stripper.writeText(pdfdocument.getDocument(), writer);
pdfdocument.close();
out.close();
writer.close();
byte[] contents = out.toByteArray();
ts = new String(contents);
System.out.println(f.getName() + "length is:" + contents.length + "\n");
}catch(Exception e){
e.printStackTrace();
}
finally{
return ts;
}
}
public static void main(String[] args){
File file = new File("C:\\Documents and Settings\\Administrator\\桌面\\springsecurity3x.pdf");
try {
System.out.println(Pdf2text.getTxt(file));
} catch (Exception e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
}