pdf转图片的工具类
1、需要引入的包
-
- <dependency>
- <groupId>org.apache.pdfboxgroupId>
- <artifactId>pdfboxartifactId>
- <version>2.0.4version>
- dependency>
2、工具类
- public static void main(String[] args) {
- String path="D://test/21.pdf";
- String outpath="D://filesdata/21.png";
- pdfToImage(path,outpath);
- }
-
- public static List
pdfToImage(String path, String outpath) { - int DPI = 130;
- try {
- Path pdfPath = Paths.get(path);
- byte[] bytes = Files.readAllBytes(pdfPath);
- PDDocument doc = PDDocument.load(bytes);
- int pageCount = doc.getNumberOfPages();
- /* log.info("PDF转图片流,总页数:{}", pageCount);*/
- PDFRenderer pdfRenderer = new PDFRenderer(doc);
- // 不知道图片的宽和高,所以先定义个null
- BufferedImage pdfImage = null;
- // pdf有多少页
- int y = 0;
- List
list = new ArrayList<>(pageCount); - // 所有页高度综合
- int totalHeight = 0;
- if (pageCount > 0) {
- for (int i = 0; i < pageCount; i++) {
- // 每页pdf内容
- BufferedImage bim = pdfRenderer.renderImageWithDPI(i, DPI, ImageType.RGB);
- totalHeight += bim.getHeight();
- list.add(bim);
- }
- }
- System.out.println(list.size());
- List
picList = new ArrayList<>(); - int i = 1;
- for (BufferedImage bim : list) {
- // 如果是第一页需要初始化 BufferedImage
- if (bim != null) {
- String out = outpath + i + ".png";
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ImageIO.write(bim, "png", baos);
- baos.flush();
- byte[] imageInByte = baos.toByteArray();
- File file = new File(out);
- //打开输入流
- FileImageOutputStream imageOutput = new FileImageOutputStream(file);
- //将byte写入硬盘
- imageOutput.write(imageInByte, 0, imageInByte.length);
- imageOutput.flush();
- imageOutput.close();
- picList.add(out);
- i++;
- }
- }
- doc.close();
- return picList;
- } catch (Exception e) {
- return null;
- }
- }