Java提取PDF文件中的数据
PDFBox
PDFBox是一个开源的Apache的开源Java库,用来支持PDF文档的开发和转换,内载了对于PDF执行的各种操作方法.Apache PDFBox 还包括几个命令行实用程序。Apache PDFBox 在 Apache License v2.0 下发布。
PDFBox的组件
组件 | 内容 |
---|
PDFBox | 这是PDFBox的主要部分。 它包含与内容提取和操作相关的类和接口 |
FontBox | 它包含与font相关的类和接口,使用这些类我们可以修改PDF文档的文本字体 |
XmpBox | 包含处理XMP元数据的类和接口 |
Preflight | 此组件用于根据PDF/A-1b标准验证PDF文件 |
Maven项目导入依赖
<dependencies>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.21</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>fontbox</artifactId>
<version>2.0.21</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>jempbox</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>xmpbox</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>preflight</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-tools</artifactId>
<version>2.0.0</version>
</dependency>
<dependencies>
读取文字型PDF文档的例子
public class ReadChar
{
private String pdfpath="";//PDF文件的路径
private String outputPath="";//以txt文件输出的路径
private File[] files=null;
public static void main(String[] args)
{
try
{
File pdfpath=new File(pdfpath);
files=pdfpath.listFiles();
for(File file:files)
{
PDDocument doc=PDDocument.load(file);
int pagenum=doc.getNumberOfPages();
FileOutputStream fos=new FileOutputStream( outputPath+"/"+file.getName().replace(".pdf","")+".txt");
Writer writer=new OutputStreamWriter(fos,"UTF-8");
PDFTextStripper stripper=new PDFTextStripper();
stripper.setSortByPosition(true);
stripper.setStartPage(0);
stripper.setEndPage(pagenum);
stripper.writeText(doc,writer);
writer.close();
doc.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
读取图片型PDF文档的例子
public class ReadImg
{
private String pdfpath="";//PDF文件的路径
private String outputPath="";//以图片文件输出的路径
private File[] files=null;
public static void main()
{
try
{
File pdfpath = new File(Init.PDFPath());
files=pdfpath.listFiles();
for(File file:files)
{
PDDocument doc=PDDocument.load(file);
BufferedOutputStream outputStream=null;
int pageCount=doc.getNumberOfPages();
PDFRenderer pdfRenderer=new PDFRenderer(doc);
for(int i=0;i<pageCount;i++)
{
String imgpath=outputPath+"/"+file.getName().replace(".pdf","");
File img_temp=new File(imgpath);
if(!img_temp.exists())
{
img_temp.mkdir();
}
imgpath=imgpath+"/"+file.getName().replace(".pdf","");
imgpath=imgpath+"_"+i+".png";
outputStream = new BufferedOutputStream(new FileOutputStream(imgpath));
BufferedImage image = pdfRenderer.renderImageWithDPI(i, 90, ImageType.RGB);
ImageIO.write(image, "png", outputStream);
outputStream.close();
System.out.println("The "+file.getName()+"'s"+i+"' has complete");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}