Java merge PDF files

   When processing PDF documents, we can by way of merger to merge any of several different PDF file, so that we facilitate the storage and management of documents. For example, when doing graduate design, cover and text papers are often two PDF documents, however, turned over to electronic files when needed combined. The following describes specific PDF merging method by Java code.

maven dependence

 

    <!-- https://mvnrepository.com/artifact/com.lowagie/itext -->
    <dependency>
        <groupId>com.lowagie</groupId>
        <artifactId>itext</artifactId>
        <version>4.2.2</version>
    </dependency>

Java code

 

package com.wiener.lou.TestWebApp.Controller;

import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;

public class MergeFile {
    public static void main(String[] args) {
        String[] files = {  "e:\\1.pdf", "e:\\2.pdf" , "e:\\3.pdf"};
        String savepath = "e:\\temp\\tempNew.pdf";
        Boolean bool = mergePdfFiles(files, savepath);
        System.out.println (BOOL); 
    } 

    / * 
     * merge pdf file 
     * @param files to be merged array of files (such as absolute path { "E: \\ 1.pdf", "E: \\ 2.pdf", 
     * "e: \\ 3.pdf"}) , the combined order of the order in the array, as in the combined 2.pdf 1.pdf. 
     * @Param newfile file absolute path to the newly created merger, such as E: \\ \\ tempNew.pdf the TEMP, 
     * @return boolean Returns true if successful merger; otherwise, it returns false 
     * 
     * / 

    public  static  boolean mergePdfFiles (String [] Files , String newfile) {
         Boolean retValue = to false ; 
        the Document Document = null ;
         the try { 
            Document = new new the Document ( new new . PdfReader (Files [0]) getPageSize (. 1));
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));
            document.open();
            for (int i = 0; i < files.length; i++) {
                PdfReader reader = new PdfReader(files[i]);
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
            }
            retValue = true;
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            System.out.println("执行结束");
            document.close();
        }
        return retValue;
    }
}

Reference

    https://www.cnblogs.com/pocketbook/p/6427579.html

 

Guess you like

Origin www.cnblogs.com/east7/p/11915415.html