java-PDF转图片

1、maven工程添加依赖

<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>


<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.21</version>
</dependency>


<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/fontbox -->
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>fontbox</artifactId>
    <version>2.0.20</version>
</dependency>

注:如果测试需要jar包,https://mvnrepository.com/artifact/org.apache.pdfbox/fontbox/2.0.20 搜索下载。

2、代码

package com.hysoft;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

public class pdfUtil {
	public static void main(String[] args) {
		pdf2Image("D:\\Desktop\\pdftest\\2020年.pdf", "D:\\Desktop\\pdftest\\", 200);
	}
	
	//PDF转图片的方法    for那里看看是几张图片。 几页。根据页数进行转

	/***
	 * PDF文件转PNG图片,全部页数
	 *
	 * @param PdfFilePath     pdf完整路径
         * @param dstImagFolder   图片生成路径
	 * @param dpi             dpi越大转换后越清晰,相对转换速度越慢
	 * @return
	 */
	public static String pdf2Image(String PdfFilePath, String dstImgFolder, int dpi) {
		System.out.println("开始转换");
		File file = new File(PdfFilePath);
		PDDocument pdDocument;
		try {
			String imgPDFPath = file.getParent();
			int dot = file.getName().lastIndexOf('.');
			String imagePDFName = file.getName().substring(0, dot); // 获取图片文件名
			String imgFolderPath = dstImgFolder;

			pdDocument = PDDocument.load(file);
			int pageNum = pdDocument.getNumberOfPages();
			PDFRenderer renderer = new PDFRenderer(pdDocument);
			/* dpi越大转换后越清晰,相对转换速度越慢 */
			StringBuffer imgFilePath = null;
			for (int i = 0; i < pageNum; i++) {
				String imgFilePathPrefix = imgFolderPath + File.separator + imagePDFName + i;
				imgFilePath = new StringBuffer();
				imgFilePath.append(imgFilePathPrefix);
				imgFilePath.append(".png");
				File dstFile = new File(imgFilePath.toString());
				BufferedImage image = renderer.renderImageWithDPI(i, dpi);
				ImageIO.write(image, "png", dstFile);
			}
			System.out.println("PDF文档转PNG图片成功!");
			return imgFilePath.toString();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

da297368860

你的鼓励是优质内容产出的最大动

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值