当前位置:   article > 正文

java操作PDF:转换、合成、切分_pdfmergerutility

pdfmergerutility

将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);

引入依赖

  1. <!-- apache PDF转图片-->
  2. <dependency>
  3. <groupId>org.apache.pdfbox</groupId>
  4. <artifactId>pdfbox</artifactId>
  5. <version>2.0.24</version>
  6. </dependency>
  7. <!-- itext 图片合成PDF-->
  8. <dependency>
  9. <groupId>com.itextpdf</groupId>
  10. <artifactId>itextpdf</artifactId>
  11. <version>5.5.13.2</version>
  12. </dependency>

代码(如下4个java类放在一起直接使用即可)

PDFUtils.java

  1. import com.itextpdf.text.Document;
  2. import com.itextpdf.text.DocumentException;
  3. import com.itextpdf.text.Image;
  4. import com.itextpdf.text.pdf.*;
  5. import org.apache.pdfbox.io.MemoryUsageSetting;
  6. import org.apache.pdfbox.multipdf.PDFMergerUtility;
  7. import org.apache.pdfbox.multipdf.Splitter;
  8. import org.apache.pdfbox.pdmodel.PDDocument;
  9. import org.apache.pdfbox.pdmodel.PDPage;
  10. import org.apache.pdfbox.pdmodel.PDResources;
  11. import org.apache.pdfbox.pdmodel.common.PDRectangle;
  12. import org.apache.pdfbox.rendering.ImageType;
  13. import org.apache.pdfbox.rendering.PDFRenderer;
  14. import javax.imageio.ImageIO;
  15. import java.awt.image.BufferedImage;
  16. import java.io.File;
  17. import java.io.FileOutputStream;
  18. import java.io.FilenameFilter;
  19. import java.io.IOException;
  20. import java.util.ArrayList;
  21. import java.util.List;
  22. /**
  23. * pdf工具类
  24. */
  25. public class PDFUtils {
  26. /**
  27. * PDF分解图片文件
  28. *
  29. * @param pdfPath pdf文件路径
  30. */
  31. public static void cutPNG(String pdfPath) throws IOException {
  32. File pdf = new File(pdfPath);
  33. cutPNG(pdfPath, pdf.getParent() + File.separator + pdf.getName() + "_pngs");
  34. }
  35. /**
  36. * PDF分解图片文件
  37. *
  38. * @param pdfPath pdf文件路径
  39. * @param outPath 输出文件夹路径
  40. */
  41. public static void cutPNG(String pdfPath, String outPath) throws IOException {
  42. File outDir = new File(outPath);
  43. if (!outDir.exists()) outDir.mkdirs();
  44. cutPNG(new File(pdfPath), outDir);
  45. }
  46. /**
  47. * PDF分解图片文件
  48. *
  49. * @param pdf pdf文件
  50. * @param outDir 输出文件夹
  51. */
  52. public static void cutPNG(File pdf, File outDir) throws IOException {
  53. LogUtils.info("PDF分解图片工作开始");
  54. List<BufferedImage> list = getImgList(pdf);
  55. LogUtils.info(pdf.getName() + " 一共发现了 " + list.size() + " 页");
  56. FileUtils.cleanDir(outDir);
  57. for (int i = 0; i < list.size(); i++) {
  58. IMGUtils.saveImageToFile(list.get(i), outDir.getAbsolutePath() + File.separator + (i + 1) + ".png");
  59. LogUtils.info("已保存图片:" + (i + 1) + ".png");
  60. }
  61. LogUtils.info("PDF分解图片工作结束,一共分解出" + list.size() + "个图片文件,保存至:" + outDir.getAbsolutePath());
  62. }
  63. /**
  64. * 将pdf文件转换成一张图片
  65. *
  66. * @param pdfPath pdf文件路径
  67. */
  68. public static void transition_ONE_PNG(String pdfPath) throws IOException {
  69. transition_ONE_PNG(new File(pdfPath));
  70. }
  71. /**
  72. * 将pdf文件转换成一张图片
  73. *
  74. * @param pdf pdf文件
  75. */
  76. public static void transition_ONE_PNG(File pdf) throws IOException {
  77. LogUtils.info("PDF转换长图工作开始");
  78. List<BufferedImage> list = getImgList(pdf);
  79. LogUtils.info(pdf.getName() + " 一共发现了 " + list.size() + " 页");
  80. BufferedImage image = list.get(0);
  81. for (int i = 1; i < list.size(); i++) {
  82. image = IMGUtils.verticalJoinTwoImage(image, list.get(i));
  83. }
  84. byte[] data = IMGUtils.getBytes(image);
  85. String imgPath = pdf.getParent() + File.separator + pdf.getName().replaceAll("\\.", "_") + ".png";
  86. FileUtils.saveDataToFile(imgPath, data);
  87. LogUtils.info("PDF转换长图工作结束,合成尺寸:" + image.getWidth() + "x" + image.getHeight() + ",合成文件大小:" + data.length / 1024 + "KB,保存至:" + imgPath);
  88. }
  89. /**
  90. * 将PDF文档拆分成图像列表
  91. *
  92. * @param pdf PDF文件
  93. */
  94. private static List<BufferedImage> getImgList(File pdf) throws IOException {
  95. PDDocument pdfDoc = PDDocument.load(pdf);
  96. List<BufferedImage> imgList = new ArrayList<>();
  97. PDFRenderer pdfRenderer = new PDFRenderer(pdfDoc);
  98. int numPages = pdfDoc.getNumberOfPages();
  99. for (int i = 0; i < numPages; i++) {
  100. BufferedImage image = pdfRenderer.renderImageWithDPI(i, 300, ImageType.RGB);
  101. imgList.add(image);
  102. }
  103. pdfDoc.close();
  104. return imgList;
  105. }
  106. /**
  107. * 图片合成PDF
  108. *
  109. * @param pngsDirPath 图片文件夹路径
  110. */
  111. public static void merge_PNG(String pngsDirPath) throws Exception {
  112. File pngsDir = new File(pngsDirPath);
  113. merge_PNG(pngsDir, pngsDir.getName() + ".pdf");
  114. }
  115. /**
  116. * 图片合成pdf
  117. *
  118. * @param pngsDir 图片文件夹
  119. * @param pdfName 合成pdf名称
  120. */
  121. private static void merge_PNG(File pngsDir, String pdfName) throws Exception {
  122. File pdf = new File(pngsDir.getParent() + File.separator + pdfName);
  123. if (!pdf.exists()) pdf.createNewFile();
  124. File[] pngList = pngsDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".png"));
  125. LogUtils.info("在" + pngsDir.getAbsolutePath() + ",一共发现" + pngList.length + "个PNG文件");
  126. Document document = new Document();
  127. FileOutputStream fo = new FileOutputStream(pdf);
  128. PdfWriter writer = PdfWriter.getInstance(document, fo);
  129. document.open();
  130. for (File f : pngList) {
  131. document.newPage();
  132. byte[] bytes = FileUtils.getFileBytes(f);
  133. Image image = Image.getInstance(bytes);
  134. float heigth = image.getHeight();
  135. float width = image.getWidth();
  136. int percent = getPercent2(heigth, width);
  137. image.setAlignment(Image.MIDDLE);
  138. image.scalePercent(percent + 3);// 表示是原来图像的比例;
  139. document.add(image);
  140. System.out.println("正在合成" + f.getName());
  141. }
  142. document.close();
  143. writer.close();
  144. System.out.println("PDF文件生成地址:" + pdf.getAbsolutePath());
  145. }
  146. private static int getPercent2(float h, float w) {
  147. int p = 0;
  148. float p2 = 0.0f;
  149. p2 = 530 / w * 100;
  150. p = Math.round(p2);
  151. return p;
  152. }
  153. /**
  154. * 多PDF合成
  155. *
  156. * @param pngsDirPath pdf所在文件夹路径
  157. */
  158. public static void merge_PDF(String pngsDirPath) throws IOException {
  159. File pngsDir = new File(pngsDirPath);
  160. merge_PDF(pngsDir, pngsDir.getName() + "_合并.pdf");
  161. }
  162. /**
  163. * 多PDF合成
  164. *
  165. * @param pngsDir pdf所在文件夹
  166. * @param pdfName 合成pdf文件名
  167. */
  168. private static void merge_PDF(File pngsDir, String pdfName) throws IOException {
  169. File[] pdfList = pngsDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".pdf"));
  170. LogUtils.info("在" + pngsDir.getAbsolutePath() + ",一共发现" + pdfList.length + "个PDF文件");
  171. PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
  172. pdfMergerUtility.setDestinationFileName(pngsDir.getParent() + File.separator + pdfName);
  173. for (File f : pdfList) {
  174. pdfMergerUtility.addSource(f);
  175. }
  176. pdfMergerUtility.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
  177. }
  178. public static void getPartPDF(String pdfPath, int from, int end) throws Exception {
  179. pdfPath = pdfPath.trim();
  180. Document document = null;
  181. PdfCopy copy = null;
  182. PdfReader reader = new PdfReader(pdfPath);
  183. int n = reader.getNumberOfPages();
  184. if (end == 0) {
  185. end = n;
  186. }
  187. document = new Document(reader.getPageSize(1));
  188. copy = new PdfCopy(document, new FileOutputStream(pdfPath.substring(0, pdfPath.length() - 4) + "_" + from + "_" + end + ".pdf"));
  189. document.open();
  190. for (int j = from; j <= end; j++) {
  191. document.newPage();
  192. PdfImportedPage page = copy.getImportedPage(reader, j);
  193. copy.addPage(page);
  194. }
  195. document.close();
  196. }
  197. }

IMGUtils.java

  1. import javax.imageio.ImageIO;
  2. import java.awt.*;
  3. import java.awt.image.BufferedImage;
  4. import java.io.ByteArrayInputStream;
  5. import java.io.ByteArrayOutputStream;
  6. import java.io.FileInputStream;
  7. import java.io.IOException;
  8. public class IMGUtils {
  9. /**
  10. * 将图像转为png文件的字节数据
  11. * @param image 目标图像
  12. * @return 返回数据
  13. */
  14. public static byte[] getBytes(BufferedImage image){
  15. return getBytes(image,"png");
  16. }
  17. /**
  18. * 将图像转换为指定媒体文件类型的字节数据
  19. * @param image 目标图像
  20. * @param fileType 文件类型(后缀名)
  21. * @return 返回数据
  22. */
  23. public static byte[] getBytes(BufferedImage image,String fileType){
  24. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  25. try {
  26. ImageIO.write(image,fileType,outStream);
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. }
  30. return outStream.toByteArray();
  31. }
  32. /**
  33. * 读取图像,通过文件
  34. * @param filePath 文件路径
  35. * @return BufferedImage
  36. */
  37. public static BufferedImage getImage(String filePath){
  38. try {
  39. return ImageIO.read(new FileInputStream(filePath));
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43. return null;
  44. }
  45. /**
  46. * 读取图像,通过字节数据
  47. * @param data 字节数据
  48. * @return BufferedImage
  49. */
  50. public static BufferedImage getImage(byte[] data){
  51. try {
  52. return ImageIO.read(new ByteArrayInputStream(data));
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. }
  56. return null;
  57. }
  58. /**
  59. * 保存图像到指定文件
  60. * @param image 图像
  61. * @param filePath 文件路径
  62. */
  63. public static void saveImageToFile(BufferedImage image,String filePath) throws IOException {
  64. FileUtils.saveDataToFile(filePath,getBytes(image));
  65. }
  66. /**
  67. * 纵向拼接图片
  68. */
  69. public static BufferedImage verticalJoinTwoImage(BufferedImage image1, BufferedImage image2){
  70. if(image1==null)return image2;
  71. if(image2==null)return image1;
  72. BufferedImage image=new BufferedImage(image1.getWidth(),image1.getHeight()+image2.getHeight(),image1.getType());
  73. Graphics2D g2d = image.createGraphics();
  74. g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  75. g2d.drawImage(image1, 0, 0, image1.getWidth(), image1.getHeight(), null);
  76. g2d.drawImage(image2, 0, image1.getHeight(), image2.getWidth(), image2.getHeight(), null);
  77. g2d.dispose();// 释放图形上下文使用的系统资源
  78. return image;
  79. }
  80. /**
  81. * 剪裁图片
  82. * @param image 对象
  83. * @param x 顶点x
  84. * @param y 顶点y
  85. * @param width 宽度
  86. * @param height 高度
  87. * @return 剪裁后的对象
  88. */
  89. public static BufferedImage cutImage(BufferedImage image,int x,int y,int width,int height){
  90. if(image==null)return null;
  91. return image.getSubimage(x,y,width,height);
  92. }
  93. }

FileUtils.java

  1. import java.io.*;
  2. public class FileUtils {
  3. /**
  4. * 将数据保存到指定文件路径
  5. */
  6. public static void saveDataToFile(String filePath,byte[] data) throws IOException {
  7. File file = new File(filePath);
  8. if(!file.exists())file.createNewFile() ;
  9. FileOutputStream outStream = new FileOutputStream(file);
  10. outStream.write(data);
  11. outStream.flush();
  12. outStream.close();
  13. }
  14. /**
  15. * 读取文件数据
  16. */
  17. public static byte[] getFileBytes(File file) throws IOException {
  18. if(!file.exists()||(file.exists()&&!file.isFile()))return null;
  19. InputStream inStream=new FileInputStream(file);
  20. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  21. byte[] buffer = new byte[1024];
  22. int len;
  23. while ((len = inStream.read(buffer)) != -1) {
  24. outStream.write(buffer, 0, len);
  25. }
  26. inStream.close();
  27. return outStream.toByteArray();
  28. }
  29. /**
  30. * 读取文本文件字
  31. */
  32. public static String getFileText(String path){
  33. try {
  34. byte[] data= getFileBytes(new File(path));
  35. return new String(data);
  36. } catch (Exception e) {
  37. return "";
  38. }
  39. }
  40. /**
  41. * 清空文件夹下所有文件
  42. */
  43. public static void cleanDir(File dir){
  44. if(dir!=null&&dir.isDirectory()){
  45. for(File file:dir.listFiles()){
  46. if(file.isFile())file.delete();
  47. if(file.isDirectory())cleanDir(file);
  48. }
  49. }
  50. }
  51. }

LogUtils.java

  1. public class LogUtils {
  2. public static void info(String context){
  3. System.out.println(context);
  4. }
  5. public static void warn(String context){
  6. System.out.println(context);
  7. }
  8. public static void error(String context){
  9. System.out.println(context);
  10. }
  11. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/530676
推荐阅读
相关标签
  

闽ICP备14008679号