In this post we’ll see a Java program to merge PDFs using PDFBox library.
To know more about Apache PDFBox library and PDF examples in Java using PDFBox check this post- Generating PDF in Java Using PDFBox Tutorial
Merging PDFs using PDFBox
- To merge PDFs, PDFBox library provides PDFMergerUtility class which takes a list of pdf documents and merge them, saving the result in a new document.
- Add the PDF files that are to be merged using addSource() method of the PDFMergerUtility class.
- Add the destination PDF file name using the setDestinationFileName() method of the PDFMergerUtility class.
Following Java program shows how two PDF documents can be merged using PDFBox.
import java.io.IOException; import java.util.Arrays; import java.util.List; import org.apache.pdfbox.io.MemoryUsageSetting; import org.apache.pdfbox.multipdf.PDFMergerUtility; public class PDFMerger { public static final String MERGED_PDF = "F://knpcode//result//PDFBox//Merged.pdf"; public static void main(String[] args) { // Source PDFs as a list List<String> fileList = Arrays.asList("F://knpcode//PDF1.pdf", "F://knpcode//PDF2.pdf"); PDFMergerUtility pdfMerger = new PDFMergerUtility(); pdfMerger.setDestinationFileName(MERGED_PDF); try { // iterate list and add files to PDFMergerUtility for(String filePath : fileList) { pdfMerger.addSource(filePath); } // Merge documents pdfMerger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly()); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Related Posts
- Merging PDFs in Java Using iText
- Merging PDFs in Java Using OpenPDF
- Generating PDF in Java Using OpenPDF Tutorial
- Generating PDF in Java Using iText Tutorial
- Password Protected PDF Using PDFBox in Java
- Java PDFBox Example – Read Text And Extract Image From PDF
- Merge Sort Java Program
- How to Read Input From Console in Java
That’s all for the topic Merging PDFs in Java Using PDFBox. If something is missing or you have something to share about the topic please write a comment.
You may also like
This is not working on linux.