java操作PDF文件,可支持分页、合并、图片转PDF等

java操作PDF,有一个很好用的工具——pdfbox。只需要引入依赖,即可使用。

<dependency>
     <groupId>org.apache.pdfbox</groupId>
     <artifactId>pdfbox-app</artifactId>
     <version>2.0.21</version>
</dependency>

利用这个工具,可以实现很多的功能,我这里示例了以下几种:

  1. 加载PDF文档
  2. 创建一个单页的PDF空文档
  3. 获取PDF文档总页数
  4. 获取pdf文档的所有分页对象
  5. 给整个PDF文件分页,形成多个pdf单页文件
  6. 合并多个单页PDF文件,输出一个合并后的PDF文档
  7. 图片转PDF
  8. 获取pdf单页分辨率

代码如下:

  /**
     * 从文件中加载pdf
     *
     * @param file 文件
     * @return
     * @throws IOException
     */
    public static PDDocument load(File file) throws IOException {
        if (!file.exists() || file.isDirectory()) {
            return null;
        }
        return PDDocument.load(file);
    }

    /**
     * 从文件流中加载pdf
     *
     * @param inputStream 文件输入流
     * @return
     * @throws IOException
     */
    public static PDDocument load(InputStream inputStream) throws IOException {
        if (inputStream == null || inputStream.available() == 0) {
            return null;
        }
        return PDDocument.load(inputStream);
    }

    /**
     * 创建一个单页的PDF空文档
     *
     * @param outputFile
     * @return
     * @throws IOException
     */
    public static PDDocument getBlankPDF(File outputFile) throws IOException {
        //首先创建pdf文档类
        PDDocument pdf = null;
        pdf = new PDDocument();
        //实例化pdf页对象
        PDPage blankPage = new PDPage();
        //插入文档类
        pdf.addPage(blankPage);
        //保存
        pdf.save(outputFile);
        return pdf;
    }

    /**
     * 获取pdf总页数
     *
     * @param pdf
     * @return
     */
    public static int pageCount(PDDocument pdf) {
        return pdf.getNumberOfPages();
    }

    /**
     * 获取pdf文档的所有分页对象
     *
     * @param pdf
     * @return 返回的list集合
     */
    public static List<PDPage> getPageList(PDDocument pdf) {
        int count = pageCount(pdf);
        List<PDPage> pages = new ArrayList<>(64);
        PDPageTree pdPages = pdf.getPages();
        for (int i = 0; i < count; i++) {
            PDPage pdPage = pdPages.get(i);
            pages.add(pdPage);
        }
        return pages;
    }


 /**
     * 给整个PDF文件分页,形成多个pdf单页文件
     *
     * @param inputStream  pdf文件流
     * @param outputParent 输出文件的父目录
     * @throws IOException
     */
    public static Integer pageSpilt(InputStream inputStream, File outputParent) throws IOException {
        if (!outputParent.exists() || !outputParent.isDirectory()) {
            throw new RuntimeException("输出文件的父目录不存在");
        }

        PDDocument pdf = load(inputStream);
        try {
            int numberOfPages = pageCount(pdf);
            for (int i = 0; i < numberOfPages; i++) {
                PDDocument document = new PDDocument();
                document.addPage(pdf.getPage(i));
                document.save(new File(outputParent, i + 1 + ".pdf"));
                close(document);
            }
            return numberOfPages;
        } finally {
            close(pdf);
            close(inputStream);
        }
    }


  /**
     * 合并多个单页PDF文件,输出一个合并后的PDF文档
     *
     * @param inputParent
     * @param outputFile
     * @param sortor
     * @throws IOException
     */
    public static void combine(File inputParent, String outputFile, FileSortor sortor) throws IOException {
        if (!inputParent.exists() || !inputParent.isDirectory()) {
            throw new RuntimeException("输入文件的父目录不存在");
        }
        if (new File(outputFile).exists()) {
            throw new RuntimeException("输出文件已存在");
        }
        File[] files = inputParent.listFiles();
        if (sortor != null) {
            sortor.sort(files);
        }
        PDFMergerUtility merger = new PDFMergerUtility();
        //输出目标路径
        merger.setDestinationFileName(outputFile);
        for (int i = 0; i < files.length; i++) {
            if (files[i].getName().toLowerCase().endsWith(".pdf")) {
                merger.addSource(files[i]);
            }
        }
        merger.mergeDocuments(null);
    }

    /**
     * 获取pdf单页分辨率
     *
     * @param page
     * @return
     */
    public static String getResolution(PDPage page) {
        PDRectangle rectangle = page.getArtBox();
        double width = Math.ceil(rectangle.getWidth());
        double height = Math.ceil(rectangle.getHeight());
        return (int) width + "*" + (int) height;
    }

    /**
     * 图片转PDF
     *
     * @param inputFile  图片路径
     * @param outputFile 生成pdf的文件路径
     * @throws IOException
     */
    public static void convertImgToPDF(String inputFile, String outputFile) throws IOException {
        if (!new File(inputFile).exists()) {
            throw new RuntimeException("输入文件不存在");
        }
        if (!outputFile.toLowerCase().endsWith(".pdf")) {
            throw new RuntimeException("只能转成pdf文件");
        }
        PDDocument document = new PDDocument();
        InputStream inputStream = new FileInputStream(inputFile);
        BufferedImage bimg = ImageIO.read(inputStream);
        float width = bimg.getWidth();
        float height = bimg.getHeight();
        PDPage page = new PDPage(new PDRectangle(width, height));
        document.addPage(page);
        PDImageXObject img = PDImageXObject.createFromFile(inputFile, document);
        PDPageContentStream contentStream = new PDPageContentStream(document, page);
        contentStream.drawImage(img, 0, 0, width, height);
        contentStream.close();
        close(inputStream);
        document.save(outputFile);
        close(document);
    }



    public static void close(InputStream inputStream) {
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void close(PDDocument pdf) {
        try {
            pdf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件排序器
     */
    public interface FileSortor {
        /**
         * 源文件组
         *
         * @param sources
         */
        void sort(File[] sources);
    }
  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 使用 Aspose 将 PDF 分页换为图片后再合并PDF 并压缩的代码示例如下: ``` import com.aspose.pdf.*; // Load the PDF document Document pdfDocument = new Document("input.pdf"); // Loop through all the pages in the PDF for (int pageNumber = 1; pageNumber <= pdfDocument.getPages().size(); pageNumber++) { // Get the current page Page pdfPage = pdfDocument.getPages().get_Item(pageNumber); // Convert the page to image BufferedImage image = pdfPage.convertToImage(); // Save the image ImageIO.write(image, "jpg", new File("page_" + pageNumber + ".jpg")); } // Create a new PDF document Document newPdfDocument = new Document(); // Loop through all the images for (int pageNumber = 1; pageNumber <= pdfDocument.getPages().size(); pageNumber++) { // Get the current image BufferedImage image = ImageIO.read(new File("page_" + pageNumber + ".jpg")); // Create a new page in the new PDF document Page newPdfPage = newPdfDocument.getPages().add(); // Add the image to the page newPdfPage.getResources().getImages().add(image); } // Save the new PDF document newPdfDocument.save("output.pdf"); // Compress the PDF document newPdfDocument.compress(); // Save the compressed PDF document newPdfDocument.save("output_compressed.pdf"); ``` 需要注意的是,上面的代码需要 Aspose.PDF for Java 库的支持,请确保在项目中导入了该库。 ### 回答2: Java pdf使用aspose分页图片后再合成pdf再压缩pdf的代码可以按照以下步骤来实现: 第一步:导入aspose-pdf依赖 首先,需要在Java项目中导入aspose-pdf的依赖。可以在项目的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.aspose</groupId> <artifactId>aspose-pdf</artifactId> <version>20.11</version> </dependency> ``` 第二步:分页图片 使用aspose-pdf提供的API,将PDF文件按页分解为多个图片。可以使用以下代码实现: ```java // 加载PDF文件 Document pdfDocument = new Document("input.pdf"); // 获取总页数 int pageCount = pdfDocument.getPages().size(); for (int pageIndex = 1; pageIndex <= pageCount; pageIndex++) { // 生成对应页码的图片文件 String imageFilePath = "page" + pageIndex + ".jpg"; ImageSaveOptions options = new ImageSaveOptions(SaveFormat.JPEG); options.setPageCount(1); options.setPageIndex(pageIndex); pdfDocument.save(imageFilePath, options); } ``` 第三步:合成PDF 将上一步生成的多个图片文件合成为一个PDF文件。可以使用以下代码实现: ```java // 创建新的PDF文档 Document newPdfDocument = new Document(); // 添加每个图片文件作为一个页码 for (int pageIndex = 1; pageIndex <= pageCount; pageIndex++) { String imageFilePath = "page" + pageIndex + ".jpg"; Page pdfPage = newPdfDocument.getPages().add(); pdfPage.getPageInfo().setMargin(new MarginInfo(0, 0, 0, 0)); Image image = new Image(); image.setFile(imageFilePath); pdfPage.getParagraphs().add(image); } // 保存合成的PDF文件 newPdfDocument.save("output.pdf"); ``` 第四步:压缩PDF 在合成的PDF文件中,可能存在一些冗余信息,可以通过压缩来减小文件大小。可以使用以下代码实现: ```java Document pdfDocument = new Document("output.pdf"); pdfDocument.setOptimizeSize(true); pdfDocument.optimize(); // 保存压缩后的PDF文件 pdfDocument.save("compressed.pdf"); ``` 通过以上的代码,可以实现Java pdf使用aspose分页图片后再合成pdf再压缩pdf的功能。简单说就是先将PDF文件分解为多个图片,然后将这些图片合成为一个新的PDF文件,最后再对新的PDF文件进行压缩,减小文件大小。 ### 回答3: 使用Aspose来实现Java PDF分页图片、合成PDF以及压缩PDF的代码。 ```java import com.aspose.pdf.Document; import com.aspose.pdf.ImagePlacementAbsorber; import com.aspose.pdf.ImagePlacementPropertiesCollection; import com.aspose.pdf.Page; import com.aspose.pdf.Rectangle; import com.aspose.pdf.devices.Resolution; import com.aspose.pdf.devices.TiffDevice; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; public class PdfUtil { // 分页图片 public static List<String> convertPdfToImage(String pdfFilePath, String imageFolder) { List<String> imagePaths = new ArrayList<>(); try { Document document = new Document(pdfFilePath); int pageCount = document.getPages().size(); for (int i = 1; i <= pageCount; i++) { Page page = document.getPages().get_Item(i); String imagePath = imageFolder + File.separator + "page_" + i + ".tiff"; FileOutputStream imageStream = new FileOutputStream(imagePath); Resolution resolution = new Resolution(300); TiffDevice tiffDevice = new TiffDevice(resolution); tiffDevice.process(page, imageStream); imageStream.close(); imagePaths.add(imagePath); } } catch (Exception ex) { ex.printStackTrace(); } return imagePaths; } // 合成PDF public static void mergeImagesToPdf(List<String> imagePaths, String mergedPdfPath) { try { Document mergedPdf = new Document(); for (String imagePath : imagePaths) { Page page = mergedPdf.getPages().add(); page.getPageInfo().setMargin(new Rectangle(0, 0, 0, 0)); ImagePlacementAbsorber absorber = new ImagePlacementAbsorber(); page.accept(absorber); ImagePlacementPropertiesCollection properties = absorber.getImagePlacementProperties(); page.getResources().getImages().add(imagePath); properties.get_Item(properties.size()).setRectangle(new Rectangle(page.getPageInfo().getWidth(), page.getPageInfo().getHeight())); } mergedPdf.save(mergedPdfPath); } catch (Exception ex) { ex.printStackTrace(); } } // 压缩PDF public static void compressPdf(String pdfFilePath, String compressedPdfPath) { try { Document document = new Document(pdfFilePath); document.optimizeSize(); document.save(compressedPdfPath); } catch (Exception ex) { ex.printStackTrace(); } } public static void main(String[] args) { String pdfFilePath = "input.pdf"; String imageFolder = "images"; String mergedPdfPath = "merged.pdf"; String compressedPdfPath = "compressed.pdf"; // 分页图片 List<String> imagePaths = convertPdfToImage(pdfFilePath, imageFolder); // 合成PDF mergeImagesToPdf(imagePaths, mergedPdfPath); // 压缩PDF compressPdf(mergedPdfPath, compressedPdfPath); } } ``` 这段代码利用Aspose库来实现了对PDF文件进行分页图片、合成PDF以及压缩PDF的功能。具体实现过程为先将PDF文件的每一页换为图片(TIFF 格式),然后将这些图片合成为一个新的PDF文件,最后对新生成的PDF进行压缩。在代码中使用了Aspose.PDF的Document类来处理PDF文件,TiffDevice类将PDF中的每一页换为TIFF格式的图片,ImagePlacementAbsorber和ImagePlacementPropertiesCollection类用于合成PDF文件,而compressPdf方法则是利用optimizeSize方法对PDF文件进行压缩。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值