SoFunction
Updated on 2025-03-05

JAVA PDF operation implements intercepting N pages and merging multiple PDFs

JAVA PDF Intercept N pages, generate new files, convert pictures, and merge multiple PDFs

<dependency>
    <groupId></groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>

Complete code

import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;
import .*;

public class PdfUtil {

    /**
      * Intercept the from page from page to page end of pdfFile to form a new file name
      *
      * @param pdfFile pdf file to be cut
      * @param newFile New pdf file formed after cutting
      * @param from Starting from page N
      * @param end to page N
      */
    public static void partitionPdf(String pdfFile, String newFile, int from, int end) {
        Document document = null;
        PdfCopy copy = null;
        PdfReader reader = null;
        try {
            reader = new PdfReader(pdfFile);
            int pageCount = ();
            if (from &lt; 1) {
                from = 1;
            }
            if (from &gt; pageCount) {
                from = pageCount;
            }
            if (end == 0 || end &gt; pageCount) {
                end = pageCount;
            }
            document = new Document((1));
            copy = new PdfCopy(document, new FileOutputStream(newFile));
            ();
            for (int j = from; j &lt;= end; j++) {
                ();
                PdfImportedPage page = (reader, j);
                (page);
            }
        } catch (Exception e) {
            ();
        } finally {
            if (document != null) {
                ();
            }
            if (copy != null) {
                ();
            }
            if (reader != null) {
                ();
            }
        }
    }

    /**
      * pdf to picture
      *
      * @param pdfFile PDF file
      * @param imageFile output image file
      * @param from Start Page Start from 1
      * @param end End Page Maximum is the total number of PDF pages
      * @throws Exception
      */
    public static void pdfToImage(String pdfFile, String imageFile, int from, int end) throws Exception {
        PDDocument doc = null;
        ByteArrayOutputStream os = null;
        InputStream stream = null;
        OutputStream out = null;
        try {
            //pdf path            stream = new FileInputStream(pdfFile);
            // Load and parse PDF files            doc = (stream);
            PDFRenderer pdfRenderer = new PDFRenderer(doc);
            PDPageTree pages = ();
            int pageCount = ();
            if (from &lt; 1) {
                from = 1;
            }
            if (from &gt; pageCount) {
                from = pageCount;
            }
            if (end == 0 || end &gt; pageCount) {
                end = pageCount;
            }
            for (int i = from; i &lt;= end; i++) {
                BufferedImage bim = (i - 1, 200); //PDFBOX starts from 0, and the initial value from is 1, so you need to reduce i-1 here.                os = new ByteArrayOutputStream();
                (bim, "jpg", os);
                byte[] dataList = (); 
                // Only one page is equivalent to the name passed in. When multiple pages are added, the page number is added                String imageFilePath = from == end ? saveImgFile : (".jpg", "_" + i + ".jpg");
                File file = new File(imageFilePath);
                if (!().exists()) {
                    // Create parent directory and child files if it does not exist                    ().mkdirs();
                    ();
                }
                out = new FileOutputStream(file);
                (dataList);
            }
        } catch (Exception e) {
            ();
        } finally {
            if (doc != null) {
                ();
            }
            if (os != null) {
                ();
            }
            if (stream != null) {
                ();
            }
            if (out != null) {
                ();
            }
        }
    }

    //Merge multiple PDFs into one    public static void mergePDFFiles(List&lt;String&gt; pdfFiles, String outputPdf) throws IOException {
        // Create a new PDF reader object and a new PDF write object        PdfReader reader = null;
        PdfCopy copy = null;
        Document document = new Document();
        try {
            // Create PDF reader objects and write objects            reader = new PdfReader((0));
            copy = new PdfCopy(document, new FileOutputStream(outputPdf));
            // Open the document and prepare to write content            ();

            // Copy all pages of the first PDF to the output PDF            for (int i = 1; i &lt;= (); i++) {
                PdfImportedPage page = (reader, i);
                (page);
            }

            // Output all pages of other PDFs to PDF            for (int i = 1; i &lt; (); i++) {
                reader = new PdfReader((i));
                for (int j = 1; j &lt;= (); j++) {
                    PdfImportedPage page = (reader, j);
                    (page);
                }
            }

        } catch (Exception e) {
            ();
        } finally {
            if (document != null) {
                ();
            }
            if (copy != null) {
                ();
            }
            if (reader != null) {
                ();
            }
        }
    }
}

Test class

@Test
void pdf() throws Exception {
    String pdfFile = "D:\\Desktop\\";
    String jpgFile = "D:\\Desktop\\";
    (pdfFile, jpgFile, 1, 1); 
}

@Test
 void testMerge() throws IOException {
    List<String> pdfFiles = new ArrayList<>();
    ("D:\\Projects\\");
    ("D:\\Projects\\");
    ("D:\\Projects\\");
    (pdfFiles, "D:\\Projects\\");
}

This is the article about JAVA PDF operation that implements the implementation of intercepting N pages and merging multiple PDFs. For more related JAVA PDF content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!