java PDF文件转图片

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * @description: PDF转换为图片的工具类
 */
@Component
public class ImageUtils {

	/**
	 * 图片文件格式
	 */
	public static final String FORMAT_NAME = "png";
	/**
	 * 图片文件后缀名
	 */
	public static final String PNG_SUFFIX = ".png";
	/**
	 * 压缩文件后缀名
	 */
	public static final String ZIP_SUFFIX = ".zip";

	/**
	 * 将pdf文件转换成图片
	 * 
	 */
	public static List<String> pdfToImages(MultipartFile file) throws Exception {
		String fileName = file.getOriginalFilename();
		Document document = new Document();
		document.setByteArray(file.getBytes(), 0, file.getBytes().length, fileName);

		List<String> fileList = new ArrayList<>();
		
		for (int i = 0; i < document.getNumberOfPages(); i++) {
			BufferedImage image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN,
					Page.BOUNDARY_CROPBOX, 0F, 2.5F);
			image.flush();

			// 输出流
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			ImageIO.write(image, "png", stream);
			byte[] bytes = stream.toByteArray();// 转换成字节
			Encoder encoder = Base64.getEncoder();
			String base64 = encoder.encodeToString(bytes).trim();// 转换成base64串
			base64 = base64.replaceAll("\n", "").replaceAll("\r", "");// 删除 \r\n
			// 加上图片格式 data:image/png;base64,
			StringBuffer img = new StringBuffer("data:image/png;base64,");
			img.append(base64);
			stream.flush();
			stream.close();

			fileList.add(img.toString());
		}
		document.dispose();
		return fileList;
	}

	/**
	 * 对外的开放接口,用于将PDF文件转换为图片文件压缩包进行下载
	 *
	 * @param file
	 *            SpringMVC获取的图片文件
	 * @param response
	 * @throws Exception
	 */
	public static void pdfToImage(MultipartFile file, HttpServletResponse response) throws Exception {
		File zipFile = generateImageFile(file);
		downloadZipFile(zipFile, response);
	}


	/**
	 * 将PDF文件转换为多张图片并放入一个压缩包中
	 *
	 * @param file
	 *            SpringMVC获取的图片文件
	 * @return 图片文件压缩包
	 * @throws Exception
	 *             抛出异常
	 */
	private static File generateImageFile(MultipartFile file) throws Exception {
		String fileName = file.getOriginalFilename();
		Document document = new Document();
		document.setByteArray(file.getBytes(), 0, file.getBytes().length, fileName);

		List<File> fileList = new ArrayList<>();
		for (int i = 0; i < document.getNumberOfPages(); i++) {
			BufferedImage image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN,
					Page.BOUNDARY_CROPBOX, 0F, 2.5F);
			File imageFile = new File((i + 1) + PNG_SUFFIX);
			ImageIO.write(image, FORMAT_NAME, imageFile);
			image.flush();
			fileList.add(imageFile);
		}
		document.dispose();

		String directoryName = fileName.substring(0, fileName.lastIndexOf("."));
		File zipFile = new File(directoryName + ZIP_SUFFIX);
		ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
		zipFile(fileList, zos);
		zos.close();
		return zipFile;
	}

	/**
	 * 下载zip文件
	 *
	 * @param zipFile
	 *            zip压缩文件
	 * @param response
	 *            HttpServletResponse
	 * @throws IOException
	 *             IO异常
	 */
	private static void downloadZipFile(File zipFile, HttpServletResponse response) throws IOException {
		FileInputStream fis = new FileInputStream(zipFile);
		byte[] bytes = new byte[fis.available()];
		fis.read(bytes);
		fis.close();

		response.reset();
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Type", "application/x-msdownload");
		response.setHeader("Content-Disposition",
				"attachment; filename=" + URLEncoder.encode(zipFile.getName(), "UTF-8"));
		OutputStream out = response.getOutputStream();
		out.write(bytes);
		out.flush();
		out.close();
		zipFile.delete();
	}

	/**
	 * 压缩文件
	 *
	 * @param inputFiles
	 *            具体需要压缩的文件集合
	 * @param zos
	 *            ZipOutputStream对象
	 * @throws IOException
	 *             IO异常
	 */
	private static void zipFile(List<File> inputFiles, ZipOutputStream zos) throws IOException {
		byte[] buffer = new byte[1024];
		for (File file : inputFiles) {
			if (file.exists()) {
				if (file.isFile()) {
					BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
					zos.putNextEntry(new ZipEntry(file.getName()));
					int size = 0;
					while ((size = bis.read(buffer)) > 0) {
						zos.write(buffer, 0, size);
					}
					zos.closeEntry();
					bis.close();
					file.delete();
				} else {
					File[] files = file.listFiles();
					List<File> childrenFileList = Arrays.asList(files);
					zipFile(childrenFileList, zos);
				}
			}
		}
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java可以使用开源库Apache PDFBox来实现将PDF换为图片的功能。PDFBox是一个功能强大的Java库,可以用于处理PDF文件。 以下是使用PDFBox将PDF换为图片的基本步骤: 1. 首先,你需要在你的Java项目引入PDFBox库。你可以通过在Maven项目的pom.xml文件添加以下依赖来实现: ```xml <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.26</version> </dependency> ``` 2. 创建一个Java类,并导入所需的类: ```java import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.PDFRenderer; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; public class PDFToImageConverter { public static void main(String[] args) { String pdfFilePath = "path/to/your/pdf/file.pdf"; String outputImagePath = "path/to/save/output/image.png"; try { PDDocument document = PDDocument.load(new File(pdfFilePath)); PDFRenderer pdfRenderer = new PDFRenderer(document); // 遍历每一页并将其换为图像 for (int pageIndex = 0; pageIndex < document.getNumberOfPages(); pageIndex++) { BufferedImage image = pdfRenderer.renderImageWithDPI(pageIndex, 300); // 设置图像分辨率为300dpi ImageIO.write(image, "PNG", new File(outputImagePath)); } document.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的代码,你需要将`pdfFilePath`替换为你要换的PDF文件的路径,将`outputImagePath`替换为你要保存输出图像的路径。 3. 运行Java程序,它将读取PDF文件并将每一页换为图像。图像将保存在指定的输出路径。 这就是使用JavaPDFBox库将PDF换为图片的基本过程。你可以根据自己的需求进行进一步的定制和优化。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值