找回密码
 立即注册
首页 业界区 业界 写了一个java桌面版pdf转图片程序

写了一个java桌面版pdf转图片程序

荏牌 2025-10-1 17:47:33
1.引入依赖
  1.         
  2.         <dependency>
  3.             <groupId>org.apache.pdfbox</groupId>
  4.             pdfbox</artifactId>
  5.             <version>3.0.5</version>
  6.         </dependency>
  7.         
  8.         <dependency>
  9.             <groupId>org.apache.commons</groupId>
  10.             commons-lang3</artifactId>
  11.             <version>3.10</version>
  12.         </dependency>
  13.         
复制代码
 
2.程序核心代码
  1. package org.example.pdftoimage;
  2. import org.apache.pdfbox.Loader;
  3. import org.apache.pdfbox.pdmodel.PDDocument;
  4. import org.apache.pdfbox.rendering.PDFRenderer;
  5. import javax.imageio.ImageIO;
  6. import javax.swing.*;
  7. import java.awt.image.BufferedImage;
  8. import java.io.File;
  9. import java.io.IOException;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. import java.util.concurrent.*;
  13. public class PDFToImageConverter {
  14.     private JLabel progressLabel;
  15.     private JProgressBar progressBar;
  16.     /**
  17.      * 是否UI程序在调用
  18.      */
  19.     private boolean ui = false;
  20.     PDFToImageConverter() {
  21.     }
  22.     PDFToImageConverter(JLabel progressLabel, JProgressBar progressBar) {
  23.         this.progressLabel = progressLabel;
  24.         this.progressBar = progressBar;
  25.         this.ui = true;
  26.     }
  27.     /**
  28.      * 入口方法,用于处理 PDF 转换的操作
  29.      *
  30.      * @param pdfPath     输入的 PDF 文件路径
  31.      * @param outputDir   输出目录
  32.      * @param isLongImage 是否生成单张长图
  33.      * @param dpi         图像的DPI分辨率
  34.      * @throws IOException
  35.      * @throws InterruptedException
  36.      * @throws ExecutionException
  37.      */
  38.     public void convertPDFToImage(String pdfPath, String outputDir, boolean isLongImage, int dpi) throws Exception {
  39.         // 更新进度
  40.         updateProgress("转换开始", null);
  41.         // 调用 PDF 转换为图像的方法
  42.         List<BufferedImage> images = convertPdfToImages(pdfPath, dpi);
  43.         // 根据是否是长图的选项进行处理
  44.         String fileName = pdfPath.substring(pdfPath.lastIndexOf(File.separator) + 1, pdfPath.lastIndexOf("."));
  45.         processImages(images, outputDir, isLongImage, fileName);
  46.         // 更新进度
  47.         updateProgress("转换完成", null);
  48.     }
  49.     /**
  50.      * 处理 PDF 转换为图像
  51.      *
  52.      * @param images      要处理的图片列表
  53.      * @param outputDir   输出目录
  54.      * @param isLongImage 是否生成单张长图
  55.      * @param fileName    文件名
  56.      * @throws IOException
  57.      */
  58.     private void processImages(List<BufferedImage> images, String outputDir, boolean isLongImage, String fileName) throws IOException {
  59.         // 判断是否需要拼接成单张长图
  60.         if (isLongImage) {
  61.             BufferedImage longImage = createLongImage(images);
  62.             String outFileName = fileName + ".png";
  63.             saveImage(longImage, outputDir, outFileName);
  64.         } else {
  65.             // 否则保存为多张图
  66.             for (int i = 0; i < images.size(); i++) {
  67.                 String outFileName = fileName + "_" + (i + 1) + ".png";
  68.                 saveImage(images.get(i), outputDir, outFileName);
  69.             }
  70.         }
  71.     }
  72.     /**
  73.      * 将 PDF 转换为图像
  74.      *
  75.      * @param pdfPath PDF 文件路径
  76.      * @param dpi     图像的DPI分辨率
  77.      * @return 返回每页的 BufferedImage 列表
  78.      * @throws IOException          如果读取 PDF 文件时发生错误
  79.      * @throws InterruptedException 如果线程执行被中断
  80.      * @throws ExecutionException   如果任务执行失败
  81.      */
  82.     private List<BufferedImage> convertPdfToImages(String pdfPath, int dpi) throws IOException, InterruptedException, ExecutionException {
  83.         try (PDDocument document = Loader.loadPDF(new File(pdfPath))) {
  84.             PDFRenderer pdfRenderer = new PDFRenderer(document);
  85.             // 获取页面总数
  86.             int totalPages = document.getNumberOfPages();
  87.             // 设置进度条最大值为总页数
  88.             if (ui) {
  89.                 progressBar.setMaximum(totalPages);
  90.                 progressBar.setValue(0);
  91.             }
  92.             // 每页生成一张图片
  93.             List<BufferedImage> images = new ArrayList<>();
  94.             for (int pageIndex = 0; pageIndex < totalPages; pageIndex++) {
  95.                 // 渲染每一页为图片
  96.                 int page = pageIndex + 1;
  97.                 // 更新进度
  98.                 updateProgress("正在转换第" + page + "页", page);
  99.                 BufferedImage image = pdfRenderer.renderImageWithDPI(pageIndex, dpi);
  100.                 images.add(image);
  101.             }
  102.             return images;
  103.         }
  104.     }
  105.     /**
  106.      * 将多张图片拼接成单张长图
  107.      *
  108.      * @param images 要拼接的图片列表
  109.      * @return 拼接后的长图
  110.      */
  111.     private BufferedImage createLongImage(List<BufferedImage> images) {
  112.         // 更新进度
  113.         updateProgress("正在拼图", null);
  114.         // 计算拼接后的长图宽度和高度
  115.         int totalWidth = images.get(0).getWidth();
  116.         int totalHeight = images.stream().mapToInt(BufferedImage::getHeight).sum();
  117.         // 创建一张新的图像用于拼接
  118.         BufferedImage longImage = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_ARGB);
  119.         int yOffset = 0;
  120.         // 按照顺序将每一张图像拼接到新的长图中
  121.         for (BufferedImage image : images) {
  122.             longImage.getGraphics().drawImage(image, 0, yOffset, null);
  123.             yOffset += image.getHeight();  // 更新y偏移量
  124.         }
  125.         // 更新进度
  126.         updateProgress("拼图完成", null);
  127.         return longImage;
  128.     }
  129.     /**
  130.      * 保存图片到指定目录
  131.      *
  132.      * @param image       要保存的图片
  133.      * @param outputPath  输出路径
  134.      * @param outFileName 输出文件名
  135.      * @throws IOException 如果保存图片时发生错误
  136.      */
  137.     private void saveImage(BufferedImage image, String outputPath, String outFileName) throws IOException {
  138.         updateProgress("正在保存图片:" + outFileName, null);
  139.         String targetFilePath = outputPath + File.separator + outFileName;
  140.         ImageIO.write(image, "PNG", new File(targetFilePath));
  141.         updateProgress("保存图片完成:" + outFileName, null);
  142.     }
  143.     /**
  144.      * 更新进度
  145.      *
  146.      * @param text     进度提示
  147.      * @param progress 进度值
  148.      */
  149.     private void updateProgress(String text, Integer progress) {
  150.         if (ui) {
  151.             SwingUtilities.invokeLater(() -> {
  152.                 progressLabel.setText(text);
  153.                 if (progress != null) {
  154.                     progressBar.setValue(progress);
  155.                 }
  156.             });
  157.         }
  158.     }
  159.     public static void main(String[] args) throws Exception {
  160.         PDFToImageConverter converter = new PDFToImageConverter();
  161.         converter.convertPDFToImage("src\\main\\resources\\input.pdf", "output", false, 150);
  162.     }
  163. }
复制代码
 
3.运行效果
1.png

 
4.完整代码
https://github.com/hdwang123/PdfToImage
https://gitee.com/hdwang123/PdfToImage
 

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册