maven导入包
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>com.sleepycat</groupId>
<artifactId>je</artifactId>
<version>5.0.73</version>
</dependency>
<dependency>
<groupId>com.github.jai-imageio</groupId>
<artifactId>jai-imageio-jpeg2000</artifactId>
<version>1.3.0</version>
</dependency>
PdfUtil.java
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.text.PDFTextStripper;
@Slf4j
public class PdfUtil {
/**
* 通过PDFbox获取文章总页数
*
* @param filePath:文件路径
* @return
* @throws IOException
*/
public static int getNumberOfPages(String filePath) throws IOException, InterruptedException {
File file = new File(filePath);
PDDocument pdDocument = PDDocument.load(new File(filePath));
int pages = pdDocument.getNumberOfPages();
pdDocument.close();
return pages;
}
/**
* 通过PDFbox获取文章内容
*
* @param filePath
* @return
*/
public static String getContent(String filePath) throws IOException {
PDFParser pdfParser =
new PDFParser(new org.apache.pdfbox.io.RandomAccessFile(new File(filePath), "rw"));
pdfParser.parse();
PDDocument pdDocument = pdfParser.getPDDocument();
String text = new PDFTextStripper().getText(pdDocument);
pdDocument.close();
return text;
}
/**
* 通过PDFbox生成文件的缩略图
*
* @param filePath:文件路径
* @param outPath:输出图片路径
* @throws IOException
*/
public static void getPdfImage(String filePath, String outPath) throws IOException {
// 利用PdfBox生成图像
List<String> list = new ArrayList<>();
PDDocument pdDocument = PDDocument.load(new File(filePath));
PDFRenderer renderer = new PDFRenderer(pdDocument);
int pages = pdDocument.getNumberOfPages();
for (int i = 0; i < pages; i++) {
// 构造图片
File file = new File(outPath);
if (!file.exists()) {
file.mkdirs();
}
String fileName = outPath + "/" + (i + 1) + ".png";
BufferedImage image = renderer.renderImageWithDPI(i, 96); // Windows native DPI
ImageIO.write(image, "PNG", new File(fileName));
list.add(fileName);
}
// Warning: You did not close a PDF Document
pdDocument.close();
}
}
测试代码
import java.io.IOException;
/**
* */
public class PdfTest {
public static void main(String[] args) throws IOException, InterruptedException {
int numberOfPages =
PdfUtil.getNumberOfPages("D:\\workspace\\service-api\\xyd-client\\data1.pdf");
System.out.println(numberOfPages);
String content = PdfUtil.getContent("D:\\workspace\\service-api\\xyd-client\\data1.pdf");
System.out.println(content);
PdfUtil.getPdfImage(
"D:\\workspace\\service-api\\xyd-client\\data1.pdf",
"D:\\workspace\\service-api\\xyd-client\\data1.pdf.png");
}
}