将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);
引入依赖
org.apache.pdfbox pdfbox 2.0.24 com.itextpdf itextpdf 5.5.13.2
代码(如下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;public class PDFUtils { public static void cutPNG(String pdfPath) throws IOException { File pdf = new File(pdfPath); cutPNG(pdfPath, pdf.getParent() + File.separator + pdf.getName() + "_pngs"); } 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); } public static void cutPNG(File pdf, File outDir) throws IOException { LogUtils.info("PDF分解图片工作开始"); List 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()); } public static void transition_ONE_PNG(String pdfPath) throws IOException { transition_ONE_PNG(new File(pdfPath)); } public static void transition_ONE_PNG(File pdf) throws IOException { LogUtils.info("PDF转换长图工作开始"); List 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); } private static List getImgList(File pdf) throws IOException { PDDocument pdfDoc = PDDocument.load(pdf); List 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; } public static void merge_PNG(String pngsDirPath) throws Exception { File pngsDir = new File(pngsDirPath); merge_PNG(pngsDir, pngsDir.getName() + ".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; } public static void merge_PDF(String pngsDirPath) throws IOException { File pngsDir = new File(pngsDirPath); merge_PDF(pngsDir, pngsDir.getName() + "_合并.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 { public static byte[] getBytes(BufferedImage image){ return getBytes(image,"png"); } 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(); } public static BufferedImage getImage(String filePath){ try { return ImageIO.read(new FileInputStream(filePath)); } catch (IOException e) { e.printStackTrace(); } return null; } public static BufferedImage getImage(byte[] data){ try { return ImageIO.read(new ByteArrayInputStream(data)); } catch (IOException e) { e.printStackTrace(); } return null; } 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; } 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); }}
来源地址:https://blog.csdn.net/qq_43319748/article/details/132133397