使用开源库Apache PDFBox将PDF转换为图片
依赖
<dependency><groupId>org.apache.pdfbox</groupId><artifactId>fontbox</artifactId><version>2.0.4</version>
</dependency>
<dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.4</version>
</dependency>
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import javax.imageio.ImageIO;import cn.hutool.core.lang.UUID;
import com.zxzx.ssm.common.constant.SsmConstant;
import org.apache.commons.io.IOUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;/*** @author admin*/
public class PDFToImageConverter {/*** 按照页数返回图片-转成BASE64*/public static List<String> pdfToPng(File pdfFile) {List<String> list = new ArrayList<>();try (PDDocument doc = PDDocument.load(pdfFile)) {PDFRenderer renderer = new PDFRenderer(doc);int pageCount = doc.getNumberOfPages();for (int i = 0; i < pageCount; i++) {BufferedImage image = renderer.renderImageWithDPI(i, 144);File file = new File(SsmConstant.TEMP_PIC + "/" + pdfFile.getName() + "_" + (i + 1) + ".png");ImageIO.write(image, "png", file);InputStream inputStream = Files.newInputStream(file.toPath());byte[] byteArray = IOUtils.toByteArray(inputStream);String s = Base64.getEncoder().encodeToString(byteArray);list.add(s);}} catch (IOException e) {e.printStackTrace();}return list;}/*** 转换到同一张图片*/public static String pdfToPngCollect(File file) {String outPicPath = SsmConstant.TEMP_PIC + UUID.fastUUID() + ".png";try (PDDocument doc = PDDocument.load(file)) {PDFRenderer renderer = new PDFRenderer(doc);int pageCount = doc.getNumberOfPages();List<BufferedImage> imageList = new ArrayList<>();int height = 0;int weight = 0;for (int i = 0; i < pageCount; i++) {BufferedImage image = renderer.renderImageWithDPI(i, 144);height += image.getHeight();weight = Math.max(weight, image.getWidth());imageList.add(image);}BufferedImage mergedImage = new BufferedImage(weight, height, BufferedImage.TYPE_INT_RGB);Graphics2D g = mergedImage.createGraphics();int accHeight = 0;for (BufferedImage image : imageList) {g.drawImage(image, 0, accHeight, null);accHeight += image.getHeight();}g.dispose();File outputfile = new File(outPicPath);ImageIO.write(mergedImage, "jpg", outputfile);} catch (IOException e) {e.printStackTrace();}return outPicPath;}}