将PDF每一页切割成图片
PDFUtils.cutPNG("D:/tmp/1.pdf","D:/tmp/输出图片路径/");
将PDF转换成一张长图片
PDFUtils.transition_ONE_PNG("D:/tmp/1.pdf");
将多张图片合并成一个PDF文件
PDFUtils.merge_PNG("D:/tmp/测试图片/");
将多个PDF合并成一个PDF文件
PDFUtils.merge_PDF("D:/tmp/测试图片/");
取出指定PDF的起始和结束页码作为新的pdf
PDFUtils.getPartPDF("D:/tmp/1.pdf",3,5);
引入依赖
<!-- apache PDF转图片--><dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.24</version></dependency>
<!-- itext 图片合成PDF--><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.13.2</version></dependency>
代码(如下4个java类放在一起直接使用即可)
PDFUtils.java
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;/*** pdf工具类*/
public class PDFUtils {/*** PDF分解图片文件** @param pdfPath pdf文件路径*/public static void cutPNG(String pdfPath) throws IOException {File pdf = new File(pdfPath);cutPNG(pdfPath, pdf.getParent() + File.separator + pdf.getName() + "_pngs");}/*** PDF分解图片文件** @param pdfPath pdf文件路径* @param outPath 输出文件夹路径*/public static void cutPNG(String pdfPath, String outPath) throws IOException {File outDir = new File(outPath);if (!outDir.exists()) outDir.mkdirs();cutPNG(new File(pdfPath), outDir);}/*** PDF分解图片文件** @param pdf pdf文件* @param outDir 输出文件夹*/public static void cutPNG(File pdf, File outDir) throws IOException {LogUtils.info("PDF分解图片工作开始");List<BufferedImage> list = getImgList(pdf);LogUtils.info(pdf.getName() + " 一共发现了 " + list.size() + " 页");FileUtils.cleanDir(outDir);for (int i = 0; i < list.size(); i++) {IMGUtils.saveImageToFile(list.get(i), outDir.getAbsolutePath() + File.separator + (i + 1) + ".png");LogUtils.info("已保存图片:" + (i + 1) + ".png");}LogUtils.info("PDF分解图片工作结束,一共分解出" + list.size() + "个图片文件,保存至:" + outDir.getAbsolutePath());}/*** 将pdf文件转换成一张图片** @param pdfPath pdf文件路径*/public static void transition_ONE_PNG(String pdfPath) throws IOException {transition_ONE_PNG(new File(pdfPath));}/*** 将pdf文件转换成一张图片** @param pdf pdf文件*/public static void transition_ONE_PNG(File pdf) throws IOException {LogUtils.info("PDF转换长图工作开始");List<BufferedImage> list = getImgList(pdf);LogUtils.info(pdf.getName() + " 一共发现了 " + list.size() + " 页");BufferedImage image = list.get(0);for (int i = 1; i < list.size(); i++) {image = IMGUtils.verticalJoinTwoImage(image, list.get(i));}byte[] data = IMGUtils.getBytes(image);String imgPath = pdf.getParent() + File.separator + pdf.getName().replaceAll("\\.", "_") + ".png";FileUtils.saveDataToFile(imgPath, data);LogUtils.info("PDF转换长图工作结束,合成尺寸:" + image.getWidth() + "x" + image.getHeight() + ",合成文件大小:" + data.length / 1024 + "KB,保存至:" + imgPath);}/*** 将PDF文档拆分成图像列表** @param pdf PDF文件*/private static List<BufferedImage> getImgList(File pdf) throws IOException {PDDocument pdfDoc = PDDocument.load(pdf);List<BufferedImage> imgList = new ArrayList<>();PDFRenderer pdfRenderer = new PDFRenderer(pdfDoc);int numPages = pdfDoc.getNumberOfPages();for (int i = 0; i < numPages; i++) {BufferedImage image = pdfRenderer.renderImageWithDPI(i, 300, ImageType.RGB);imgList.add(image);}pdfDoc.close();return imgList;}/*** 图片合成PDF** @param pngsDirPath 图片文件夹路径*/public static void merge_PNG(String pngsDirPath) throws Exception {File pngsDir = new File(pngsDirPath);merge_PNG(pngsDir, pngsDir.getName() + ".pdf");}/*** 图片合成pdf** @param pngsDir 图片文件夹* @param pdfName 合成pdf名称*/private static void merge_PNG(File pngsDir, String pdfName) throws Exception {File pdf = new File(pngsDir.getParent() + File.separator + pdfName);if (!pdf.exists()) pdf.createNewFile();File[] pngList = pngsDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".png"));LogUtils.info("在" + pngsDir.getAbsolutePath() + ",一共发现" + pngList.length + "个PNG文件");Document document = new Document();FileOutputStream fo = new FileOutputStream(pdf);PdfWriter writer = PdfWriter.getInstance(document, fo);document.open();for (File f : pngList) {document.newPage();byte[] bytes = FileUtils.getFileBytes(f);Image image = Image.getInstance(bytes);float heigth = image.getHeight();float width = image.getWidth();int percent = getPercent2(heigth, width);image.setAlignment(Image.MIDDLE);image.scalePercent(percent + 3);// 表示是原来图像的比例;document.add(image);System.out.println("正在合成" + f.getName());}document.close();writer.close();System.out.println("PDF文件生成地址:" + pdf.getAbsolutePath());}private static int getPercent2(float h, float w) {int p = 0;float p2 = 0.0f;p2 = 530 / w * 100;p = Math.round(p2);return p;}/*** 多PDF合成** @param pngsDirPath pdf所在文件夹路径*/public static void merge_PDF(String pngsDirPath) throws IOException {File pngsDir = new File(pngsDirPath);merge_PDF(pngsDir, pngsDir.getName() + "_合并.pdf");}/*** 多PDF合成** @param pngsDir pdf所在文件夹* @param pdfName 合成pdf文件名*/private static void merge_PDF(File pngsDir, String pdfName) throws IOException {File[] pdfList = pngsDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".pdf"));LogUtils.info("在" + pngsDir.getAbsolutePath() + ",一共发现" + pdfList.length + "个PDF文件");PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();pdfMergerUtility.setDestinationFileName(pngsDir.getParent() + File.separator + pdfName);for (File f : pdfList) {pdfMergerUtility.addSource(f);}pdfMergerUtility.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());}public static void getPartPDF(String pdfPath, int from, int end) throws Exception {pdfPath = pdfPath.trim();Document document = null;PdfCopy copy = null;PdfReader reader = new PdfReader(pdfPath);int n = reader.getNumberOfPages();if (end == 0) {end = n;}document = new Document(reader.getPageSize(1));copy = new PdfCopy(document, new FileOutputStream(pdfPath.substring(0, pdfPath.length() - 4) + "_" + from + "_" + end + ".pdf"));document.open();for (int j = from; j <= end; j++) {document.newPage();PdfImportedPage page = copy.getImportedPage(reader, j);copy.addPage(page);}document.close();}}
IMGUtils.java
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;public class IMGUtils {/*** 将图像转为png文件的字节数据* @param image 目标图像* @return 返回数据*/public static byte[] getBytes(BufferedImage image){return getBytes(image,"png");}/*** 将图像转换为指定媒体文件类型的字节数据* @param image 目标图像* @param fileType 文件类型(后缀名)* @return 返回数据*/public static byte[] getBytes(BufferedImage image,String fileType){ByteArrayOutputStream outStream = new ByteArrayOutputStream();try {ImageIO.write(image,fileType,outStream);} catch (IOException e) {e.printStackTrace();}return outStream.toByteArray();}/*** 读取图像,通过文件* @param filePath 文件路径* @return BufferedImage*/public static BufferedImage getImage(String filePath){try {return ImageIO.read(new FileInputStream(filePath));} catch (IOException e) {e.printStackTrace();}return null;}/*** 读取图像,通过字节数据* @param data 字节数据* @return BufferedImage*/public static BufferedImage getImage(byte[] data){try {return ImageIO.read(new ByteArrayInputStream(data));} catch (IOException e) {e.printStackTrace();}return null;}/*** 保存图像到指定文件* @param image 图像* @param filePath 文件路径*/public static void saveImageToFile(BufferedImage image,String filePath) throws IOException {FileUtils.saveDataToFile(filePath,getBytes(image));}/*** 纵向拼接图片*/public static BufferedImage verticalJoinTwoImage(BufferedImage image1, BufferedImage image2){if(image1==null)return image2;if(image2==null)return image1;BufferedImage image=new BufferedImage(image1.getWidth(),image1.getHeight()+image2.getHeight(),image1.getType());Graphics2D g2d = image.createGraphics();g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);g2d.drawImage(image1, 0, 0, image1.getWidth(), image1.getHeight(), null);g2d.drawImage(image2, 0, image1.getHeight(), image2.getWidth(), image2.getHeight(), null);g2d.dispose();// 释放图形上下文使用的系统资源return image;}/*** 剪裁图片* @param image 对象* @param x 顶点x* @param y 顶点y* @param width 宽度* @param height 高度* @return 剪裁后的对象*/public static BufferedImage cutImage(BufferedImage image,int x,int y,int width,int height){if(image==null)return null;return image.getSubimage(x,y,width,height);}}
FileUtils.java
import java.io.*;public class FileUtils {/*** 将数据保存到指定文件路径*/public static void saveDataToFile(String filePath,byte[] data) throws IOException {File file = new File(filePath);if(!file.exists())file.createNewFile() ;FileOutputStream outStream = new FileOutputStream(file);outStream.write(data);outStream.flush();outStream.close();}/*** 读取文件数据*/public static byte[] getFileBytes(File file) throws IOException {if(!file.exists()||(file.exists()&&!file.isFile()))return null;InputStream inStream=new FileInputStream(file);ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len;while ((len = inStream.read(buffer)) != -1) {outStream.write(buffer, 0, len);}inStream.close();return outStream.toByteArray();}/*** 读取文本文件字*/public static String getFileText(String path){try {byte[] data= getFileBytes(new File(path));return new String(data);} catch (Exception e) {return "";}}/*** 清空文件夹下所有文件*/public static void cleanDir(File dir){if(dir!=null&&dir.isDirectory()){for(File file:dir.listFiles()){if(file.isFile())file.delete();if(file.isDirectory())cleanDir(file);}}}}
LogUtils.java
public class LogUtils {public static void info(String context){System.out.println(context);}public static void warn(String context){System.out.println(context);}public static void error(String context){System.out.println(context);}}