How to merge two PDF files into one in Java?












56















I want to merge many PDF files into one using PDFBox and this is what I've done:



PDDocument document = new PDDocument();
for (String pdfFile: pdfFiles) {
PDDocument part = PDDocument.load(pdfFile);
List<PDPage> list = part.getDocumentCatalog().getAllPages();
for (PDPage page: list) {
document.addPage(page);
}
part.close();
}
document.save("merged.pdf");
document.close();


Where pdfFiles is an ArrayList<String> containing all the PDF files.



When I'm running the above, I'm always getting:



org.apache.pdfbox.exceptions.COSVisitorException: Bad file descriptor


Am I doing something wrong? Is there any other way of doing it?










share|improve this question




















  • 1





    Somebody pointed out iText [java-x.blogspot.com/2006/11/merge-pdf-files-with-itext.html] and then deleted the answer. It worked and thanks for that.

    – Lipis
    Aug 27 '10 at 15:20











  • The link might help someone looking out for an answer.

    – java_learner
    Sep 27 '13 at 13:15
















56















I want to merge many PDF files into one using PDFBox and this is what I've done:



PDDocument document = new PDDocument();
for (String pdfFile: pdfFiles) {
PDDocument part = PDDocument.load(pdfFile);
List<PDPage> list = part.getDocumentCatalog().getAllPages();
for (PDPage page: list) {
document.addPage(page);
}
part.close();
}
document.save("merged.pdf");
document.close();


Where pdfFiles is an ArrayList<String> containing all the PDF files.



When I'm running the above, I'm always getting:



org.apache.pdfbox.exceptions.COSVisitorException: Bad file descriptor


Am I doing something wrong? Is there any other way of doing it?










share|improve this question




















  • 1





    Somebody pointed out iText [java-x.blogspot.com/2006/11/merge-pdf-files-with-itext.html] and then deleted the answer. It worked and thanks for that.

    – Lipis
    Aug 27 '10 at 15:20











  • The link might help someone looking out for an answer.

    – java_learner
    Sep 27 '13 at 13:15














56












56








56


18






I want to merge many PDF files into one using PDFBox and this is what I've done:



PDDocument document = new PDDocument();
for (String pdfFile: pdfFiles) {
PDDocument part = PDDocument.load(pdfFile);
List<PDPage> list = part.getDocumentCatalog().getAllPages();
for (PDPage page: list) {
document.addPage(page);
}
part.close();
}
document.save("merged.pdf");
document.close();


Where pdfFiles is an ArrayList<String> containing all the PDF files.



When I'm running the above, I'm always getting:



org.apache.pdfbox.exceptions.COSVisitorException: Bad file descriptor


Am I doing something wrong? Is there any other way of doing it?










share|improve this question
















I want to merge many PDF files into one using PDFBox and this is what I've done:



PDDocument document = new PDDocument();
for (String pdfFile: pdfFiles) {
PDDocument part = PDDocument.load(pdfFile);
List<PDPage> list = part.getDocumentCatalog().getAllPages();
for (PDPage page: list) {
document.addPage(page);
}
part.close();
}
document.save("merged.pdf");
document.close();


Where pdfFiles is an ArrayList<String> containing all the PDF files.



When I'm running the above, I'm always getting:



org.apache.pdfbox.exceptions.COSVisitorException: Bad file descriptor


Am I doing something wrong? Is there any other way of doing it?







java pdf pdfbox






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 4 '12 at 11:33







Lipis

















asked Aug 27 '10 at 14:46









LipisLipis

15.1k1578114




15.1k1578114








  • 1





    Somebody pointed out iText [java-x.blogspot.com/2006/11/merge-pdf-files-with-itext.html] and then deleted the answer. It worked and thanks for that.

    – Lipis
    Aug 27 '10 at 15:20











  • The link might help someone looking out for an answer.

    – java_learner
    Sep 27 '13 at 13:15














  • 1





    Somebody pointed out iText [java-x.blogspot.com/2006/11/merge-pdf-files-with-itext.html] and then deleted the answer. It worked and thanks for that.

    – Lipis
    Aug 27 '10 at 15:20











  • The link might help someone looking out for an answer.

    – java_learner
    Sep 27 '13 at 13:15








1




1





Somebody pointed out iText [java-x.blogspot.com/2006/11/merge-pdf-files-with-itext.html] and then deleted the answer. It worked and thanks for that.

– Lipis
Aug 27 '10 at 15:20





Somebody pointed out iText [java-x.blogspot.com/2006/11/merge-pdf-files-with-itext.html] and then deleted the answer. It worked and thanks for that.

– Lipis
Aug 27 '10 at 15:20













The link might help someone looking out for an answer.

– java_learner
Sep 27 '13 at 13:15





The link might help someone looking out for an answer.

– java_learner
Sep 27 '13 at 13:15












7 Answers
7






active

oldest

votes


















104














Why not use the PDFMergerUtility of pdfbox?



PDFMergerUtility ut = new PDFMergerUtility();
ut.addSource(...);
ut.addSource(...);
ut.addSource(...);
ut.setDestinationFileName(...);
ut.mergeDocuments();





share|improve this answer





















  • 1





    Also works, but I was using the PDFBox for creating PDF as well.

    – Lipis
    Feb 2 '11 at 17:11











  • will it allow to merge a PDF that has scanned images and PDF that was writtern ?

    – Ragesh Kr
    Mar 3 '15 at 8:07






  • 3





    @RageshKr: as far as I understand it will merge any PDF regardless of their content.

    – cherouvim
    Mar 3 '15 at 13:48






  • 1





    Is there any way to mention page-no in each page for resultant pdf ??

    – Prateek Singh
    Aug 31 '17 at 5:24











  • Can it be used if the pdf files have passwords?

    – coder
    Jun 8 '18 at 10:53



















27














A quick Google search returned this bug: "Bad file descriptor while saving a document w. imported PDFs".



It looks like you need to keep the PDFs to be merged open, until after you have saved and closed the combined PDF.






share|improve this answer





















  • 5





    Even though the post was two years old, this solved the problem. You have to keep them open!

    – Lipis
    Aug 27 '10 at 15:28



















8














This is a ready to use code, merging four pdf files with itext.jar from http://central.maven.org/maven2/com/itextpdf/itextpdf/5.5.0/itextpdf-5.5.0.jar, more on http://tutorialspointexamples.com/



import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

/**
* This class is used to merge two or more
* existing pdf file using iText jar.
*/
public class PDFMerger {

static void mergePdfFiles(List<InputStream> inputPdfList,
OutputStream outputStream) throws Exception{
//Create document and pdfReader objects.
Document document = new Document();
List<PdfReader> readers =
new ArrayList<PdfReader>();
int totalPages = 0;

//Create pdf Iterator object using inputPdfList.
Iterator<InputStream> pdfIterator =
inputPdfList.iterator();

// Create reader list for the input pdf files.
while (pdfIterator.hasNext()) {
InputStream pdf = pdfIterator.next();
PdfReader pdfReader = new PdfReader(pdf);
readers.add(pdfReader);
totalPages = totalPages + pdfReader.getNumberOfPages();
}

// Create writer for the outputStream
PdfWriter writer = PdfWriter.getInstance(document, outputStream);

//Open document.
document.open();

//Contain the pdf data.
PdfContentByte pageContentByte = writer.getDirectContent();

PdfImportedPage pdfImportedPage;
int currentPdfReaderPage = 1;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();

// Iterate and process the reader list.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
//Create page and add content.
while (currentPdfReaderPage <= pdfReader.getNumberOfPages()) {
document.newPage();
pdfImportedPage = writer.getImportedPage(
pdfReader,currentPdfReaderPage);
pageContentByte.addTemplate(pdfImportedPage, 0, 0);
currentPdfReaderPage++;
}
currentPdfReaderPage = 1;
}

//Close document and outputStream.
outputStream.flush();
document.close();
outputStream.close();

System.out.println("Pdf files merged successfully.");
}

public static void main(String args){
try {
//Prepare input pdf file list as list of input stream.
List<InputStream> inputPdfList = new ArrayList<InputStream>();
inputPdfList.add(new FileInputStream("..\pdf\pdf_1.pdf"));
inputPdfList.add(new FileInputStream("..\pdf\pdf_2.pdf"));
inputPdfList.add(new FileInputStream("..\pdf\pdf_3.pdf"));
inputPdfList.add(new FileInputStream("..\pdf\pdf_4.pdf"));


//Prepare output stream for merged pdf file.
OutputStream outputStream =
new FileOutputStream("..\pdf\MergeFile_1234.pdf");

//call method to merge pdf files.
mergePdfFiles(inputPdfList, outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
}





share|improve this answer



















  • 1





    The question clearly is tagged pdfbox. You present a solution for itext. Thus, your answer is off-topic. (That been said, your iText solution also is a bad one which iText developers usually recommend against as it drops interactive features and ignores rotation and page sizes.)

    – mkl
    Jan 9 '17 at 21:59











  • Then the title should be "How to merge two PDF files into one in Java with PdfBox"

    – Lluis Martinez
    Dec 11 '17 at 11:35






  • 1





    In addition iText comes with a nasty license.

    – Daniel Bo
    Jan 16 '18 at 15:54











  • This example is named IncorrectExample because this is not how you wou typically solve the problem of rotating pages, nor of merging documents. The correct way is NOT to use Document / PdfWriter, but to use PdfStamper, PdfCopy or PdfSmartCopy. However: in the question mentioned above, the circumstances are very particular and using this example in those circumstances is justified: developers.itextpdf.com/examples/merging-pdf-documents-itext5/…

    – victorpacheco3107
    Mar 16 '18 at 16:23



















4














package article14;

import java.io.File;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.util.PDFMergerUtility;

public class Pdf
{
public static void main(String args)
{
new Pdf().createNew();
new Pdf().combine();
}

public void combine()
{
try
{
PDFMergerUtility mergePdf = new PDFMergerUtility();
String folder ="pdf";
File _folder = new File(folder);
File filesInFolder;
filesInFolder = _folder.listFiles();
for (File string : filesInFolder)
{
mergePdf.addSource(string);
}
mergePdf.setDestinationFileName("Combined.pdf");
mergePdf.mergeDocuments();
}
catch(Exception e)
{

}
}

public void createNew()
{
PDDocument document = null;
try
{
String filename="test.pdf";
document=new PDDocument();
PDPage blankPage = new PDPage();
document.addPage( blankPage );
document.save( filename );
}
catch(Exception e)
{

}
}

}





share|improve this answer
























  • Swallowing exceptions is a bad pattern. catch(Exception e){ }

    – Lluis Martinez
    Dec 11 '17 at 11:40





















1














Multiple pdf merged method using org.apache.pdfbox:



public void mergePDFFiles(List<File> files,
String mergedFileName) {
try {
PDFMergerUtility pdfmerger = new PDFMergerUtility();
for (File file : files) {
PDDocument document = PDDocument.load(file);
pdfmerger.setDestinationFileName(mergedFileName);
pdfmerger.addSource(file);
pdfmerger.mergeDocuments(MemoryUsageSetting.setupTempFileOnly());
document.close();
}
} catch (IOException e) {
logger.error("Error to merge files. Error: " + e.getMessage());
}
}


From main program, call mergePDFFiles method using list of files and target file name.



        String mergedFileName = "Merged.pdf";
mergePDFFiles(files, mergedFileName);


After calling mergePDFFiles, load merged file



        File mergedFile = new File(mergedFileName);





share|improve this answer































    0














    If you want to combine two files where one overlays the other (example: document A is a template and document B has the text you want to put on the template), this works:



    after creating "doc", you want to write your template (templateFile) on top of that -



       PDDocument watermarkDoc = PDDocument.load(getServletContext()
    .getRealPath(templateFile));
    Overlay overlay = new Overlay();

    overlay.overlay(watermarkDoc, doc);





    share|improve this answer































      0














      Using iText (existing PDF in bytes)



          public static byte mergePDF(List<byte> pdfFilesAsByteArray) throws DocumentException, IOException {

      ByteArrayOutputStream outStream = new ByteArrayOutputStream();
      Document document = null;
      PdfCopy writer = null;

      for (byte pdfByteArray : pdfFilesAsByteArray) {

      try {
      PdfReader reader = new PdfReader(pdfByteArray);
      int numberOfPages = reader.getNumberOfPages();

      if (document == null) {
      document = new Document(reader.getPageSizeWithRotation(1));
      writer = new PdfCopy(document, outStream); // new
      document.open();
      }
      PdfImportedPage page;
      for (int i = 0; i < numberOfPages;) {
      ++i;
      page = writer.getImportedPage(reader, i);
      writer.addPage(page);
      }
      }

      catch (Exception e) {
      e.printStackTrace();
      }

      }

      document.close();
      outStream.close();
      return outStream.toByteArray();

      }





      share|improve this answer
























      • The OP quite clearly said "I want to merge many PDF files into one using PDFBox". iText is not PDFBox.

        – mkl
        May 18 '18 at 21:13











      • this works me xd

        – Alberto Acuña
        Jan 21 at 8:39











      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3585329%2fhow-to-merge-two-pdf-files-into-one-in-java%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      7 Answers
      7






      active

      oldest

      votes








      7 Answers
      7






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      104














      Why not use the PDFMergerUtility of pdfbox?



      PDFMergerUtility ut = new PDFMergerUtility();
      ut.addSource(...);
      ut.addSource(...);
      ut.addSource(...);
      ut.setDestinationFileName(...);
      ut.mergeDocuments();





      share|improve this answer





















      • 1





        Also works, but I was using the PDFBox for creating PDF as well.

        – Lipis
        Feb 2 '11 at 17:11











      • will it allow to merge a PDF that has scanned images and PDF that was writtern ?

        – Ragesh Kr
        Mar 3 '15 at 8:07






      • 3





        @RageshKr: as far as I understand it will merge any PDF regardless of their content.

        – cherouvim
        Mar 3 '15 at 13:48






      • 1





        Is there any way to mention page-no in each page for resultant pdf ??

        – Prateek Singh
        Aug 31 '17 at 5:24











      • Can it be used if the pdf files have passwords?

        – coder
        Jun 8 '18 at 10:53
















      104














      Why not use the PDFMergerUtility of pdfbox?



      PDFMergerUtility ut = new PDFMergerUtility();
      ut.addSource(...);
      ut.addSource(...);
      ut.addSource(...);
      ut.setDestinationFileName(...);
      ut.mergeDocuments();





      share|improve this answer





















      • 1





        Also works, but I was using the PDFBox for creating PDF as well.

        – Lipis
        Feb 2 '11 at 17:11











      • will it allow to merge a PDF that has scanned images and PDF that was writtern ?

        – Ragesh Kr
        Mar 3 '15 at 8:07






      • 3





        @RageshKr: as far as I understand it will merge any PDF regardless of their content.

        – cherouvim
        Mar 3 '15 at 13:48






      • 1





        Is there any way to mention page-no in each page for resultant pdf ??

        – Prateek Singh
        Aug 31 '17 at 5:24











      • Can it be used if the pdf files have passwords?

        – coder
        Jun 8 '18 at 10:53














      104












      104








      104







      Why not use the PDFMergerUtility of pdfbox?



      PDFMergerUtility ut = new PDFMergerUtility();
      ut.addSource(...);
      ut.addSource(...);
      ut.addSource(...);
      ut.setDestinationFileName(...);
      ut.mergeDocuments();





      share|improve this answer















      Why not use the PDFMergerUtility of pdfbox?



      PDFMergerUtility ut = new PDFMergerUtility();
      ut.addSource(...);
      ut.addSource(...);
      ut.addSource(...);
      ut.setDestinationFileName(...);
      ut.mergeDocuments();






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Aug 25 '16 at 7:32

























      answered Feb 2 '11 at 12:14









      cherouvimcherouvim

      26.5k1292137




      26.5k1292137








      • 1





        Also works, but I was using the PDFBox for creating PDF as well.

        – Lipis
        Feb 2 '11 at 17:11











      • will it allow to merge a PDF that has scanned images and PDF that was writtern ?

        – Ragesh Kr
        Mar 3 '15 at 8:07






      • 3





        @RageshKr: as far as I understand it will merge any PDF regardless of their content.

        – cherouvim
        Mar 3 '15 at 13:48






      • 1





        Is there any way to mention page-no in each page for resultant pdf ??

        – Prateek Singh
        Aug 31 '17 at 5:24











      • Can it be used if the pdf files have passwords?

        – coder
        Jun 8 '18 at 10:53














      • 1





        Also works, but I was using the PDFBox for creating PDF as well.

        – Lipis
        Feb 2 '11 at 17:11











      • will it allow to merge a PDF that has scanned images and PDF that was writtern ?

        – Ragesh Kr
        Mar 3 '15 at 8:07






      • 3





        @RageshKr: as far as I understand it will merge any PDF regardless of their content.

        – cherouvim
        Mar 3 '15 at 13:48






      • 1





        Is there any way to mention page-no in each page for resultant pdf ??

        – Prateek Singh
        Aug 31 '17 at 5:24











      • Can it be used if the pdf files have passwords?

        – coder
        Jun 8 '18 at 10:53








      1




      1





      Also works, but I was using the PDFBox for creating PDF as well.

      – Lipis
      Feb 2 '11 at 17:11





      Also works, but I was using the PDFBox for creating PDF as well.

      – Lipis
      Feb 2 '11 at 17:11













      will it allow to merge a PDF that has scanned images and PDF that was writtern ?

      – Ragesh Kr
      Mar 3 '15 at 8:07





      will it allow to merge a PDF that has scanned images and PDF that was writtern ?

      – Ragesh Kr
      Mar 3 '15 at 8:07




      3




      3





      @RageshKr: as far as I understand it will merge any PDF regardless of their content.

      – cherouvim
      Mar 3 '15 at 13:48





      @RageshKr: as far as I understand it will merge any PDF regardless of their content.

      – cherouvim
      Mar 3 '15 at 13:48




      1




      1





      Is there any way to mention page-no in each page for resultant pdf ??

      – Prateek Singh
      Aug 31 '17 at 5:24





      Is there any way to mention page-no in each page for resultant pdf ??

      – Prateek Singh
      Aug 31 '17 at 5:24













      Can it be used if the pdf files have passwords?

      – coder
      Jun 8 '18 at 10:53





      Can it be used if the pdf files have passwords?

      – coder
      Jun 8 '18 at 10:53













      27














      A quick Google search returned this bug: "Bad file descriptor while saving a document w. imported PDFs".



      It looks like you need to keep the PDFs to be merged open, until after you have saved and closed the combined PDF.






      share|improve this answer





















      • 5





        Even though the post was two years old, this solved the problem. You have to keep them open!

        – Lipis
        Aug 27 '10 at 15:28
















      27














      A quick Google search returned this bug: "Bad file descriptor while saving a document w. imported PDFs".



      It looks like you need to keep the PDFs to be merged open, until after you have saved and closed the combined PDF.






      share|improve this answer





















      • 5





        Even though the post was two years old, this solved the problem. You have to keep them open!

        – Lipis
        Aug 27 '10 at 15:28














      27












      27








      27







      A quick Google search returned this bug: "Bad file descriptor while saving a document w. imported PDFs".



      It looks like you need to keep the PDFs to be merged open, until after you have saved and closed the combined PDF.






      share|improve this answer















      A quick Google search returned this bug: "Bad file descriptor while saving a document w. imported PDFs".



      It looks like you need to keep the PDFs to be merged open, until after you have saved and closed the combined PDF.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Apr 7 '15 at 19:41









      Trinimon

      12.1k93356




      12.1k93356










      answered Aug 27 '10 at 15:04









      Michael Lloyd Lee mlkMichael Lloyd Lee mlk

      12.9k23375




      12.9k23375








      • 5





        Even though the post was two years old, this solved the problem. You have to keep them open!

        – Lipis
        Aug 27 '10 at 15:28














      • 5





        Even though the post was two years old, this solved the problem. You have to keep them open!

        – Lipis
        Aug 27 '10 at 15:28








      5




      5





      Even though the post was two years old, this solved the problem. You have to keep them open!

      – Lipis
      Aug 27 '10 at 15:28





      Even though the post was two years old, this solved the problem. You have to keep them open!

      – Lipis
      Aug 27 '10 at 15:28











      8














      This is a ready to use code, merging four pdf files with itext.jar from http://central.maven.org/maven2/com/itextpdf/itextpdf/5.5.0/itextpdf-5.5.0.jar, more on http://tutorialspointexamples.com/



      import com.itextpdf.text.Document;
      import com.itextpdf.text.pdf.PdfContentByte;
      import com.itextpdf.text.pdf.PdfImportedPage;
      import com.itextpdf.text.pdf.PdfReader;
      import com.itextpdf.text.pdf.PdfWriter;

      /**
      * This class is used to merge two or more
      * existing pdf file using iText jar.
      */
      public class PDFMerger {

      static void mergePdfFiles(List<InputStream> inputPdfList,
      OutputStream outputStream) throws Exception{
      //Create document and pdfReader objects.
      Document document = new Document();
      List<PdfReader> readers =
      new ArrayList<PdfReader>();
      int totalPages = 0;

      //Create pdf Iterator object using inputPdfList.
      Iterator<InputStream> pdfIterator =
      inputPdfList.iterator();

      // Create reader list for the input pdf files.
      while (pdfIterator.hasNext()) {
      InputStream pdf = pdfIterator.next();
      PdfReader pdfReader = new PdfReader(pdf);
      readers.add(pdfReader);
      totalPages = totalPages + pdfReader.getNumberOfPages();
      }

      // Create writer for the outputStream
      PdfWriter writer = PdfWriter.getInstance(document, outputStream);

      //Open document.
      document.open();

      //Contain the pdf data.
      PdfContentByte pageContentByte = writer.getDirectContent();

      PdfImportedPage pdfImportedPage;
      int currentPdfReaderPage = 1;
      Iterator<PdfReader> iteratorPDFReader = readers.iterator();

      // Iterate and process the reader list.
      while (iteratorPDFReader.hasNext()) {
      PdfReader pdfReader = iteratorPDFReader.next();
      //Create page and add content.
      while (currentPdfReaderPage <= pdfReader.getNumberOfPages()) {
      document.newPage();
      pdfImportedPage = writer.getImportedPage(
      pdfReader,currentPdfReaderPage);
      pageContentByte.addTemplate(pdfImportedPage, 0, 0);
      currentPdfReaderPage++;
      }
      currentPdfReaderPage = 1;
      }

      //Close document and outputStream.
      outputStream.flush();
      document.close();
      outputStream.close();

      System.out.println("Pdf files merged successfully.");
      }

      public static void main(String args){
      try {
      //Prepare input pdf file list as list of input stream.
      List<InputStream> inputPdfList = new ArrayList<InputStream>();
      inputPdfList.add(new FileInputStream("..\pdf\pdf_1.pdf"));
      inputPdfList.add(new FileInputStream("..\pdf\pdf_2.pdf"));
      inputPdfList.add(new FileInputStream("..\pdf\pdf_3.pdf"));
      inputPdfList.add(new FileInputStream("..\pdf\pdf_4.pdf"));


      //Prepare output stream for merged pdf file.
      OutputStream outputStream =
      new FileOutputStream("..\pdf\MergeFile_1234.pdf");

      //call method to merge pdf files.
      mergePdfFiles(inputPdfList, outputStream);
      } catch (Exception e) {
      e.printStackTrace();
      }
      }
      }





      share|improve this answer



















      • 1





        The question clearly is tagged pdfbox. You present a solution for itext. Thus, your answer is off-topic. (That been said, your iText solution also is a bad one which iText developers usually recommend against as it drops interactive features and ignores rotation and page sizes.)

        – mkl
        Jan 9 '17 at 21:59











      • Then the title should be "How to merge two PDF files into one in Java with PdfBox"

        – Lluis Martinez
        Dec 11 '17 at 11:35






      • 1





        In addition iText comes with a nasty license.

        – Daniel Bo
        Jan 16 '18 at 15:54











      • This example is named IncorrectExample because this is not how you wou typically solve the problem of rotating pages, nor of merging documents. The correct way is NOT to use Document / PdfWriter, but to use PdfStamper, PdfCopy or PdfSmartCopy. However: in the question mentioned above, the circumstances are very particular and using this example in those circumstances is justified: developers.itextpdf.com/examples/merging-pdf-documents-itext5/…

        – victorpacheco3107
        Mar 16 '18 at 16:23
















      8














      This is a ready to use code, merging four pdf files with itext.jar from http://central.maven.org/maven2/com/itextpdf/itextpdf/5.5.0/itextpdf-5.5.0.jar, more on http://tutorialspointexamples.com/



      import com.itextpdf.text.Document;
      import com.itextpdf.text.pdf.PdfContentByte;
      import com.itextpdf.text.pdf.PdfImportedPage;
      import com.itextpdf.text.pdf.PdfReader;
      import com.itextpdf.text.pdf.PdfWriter;

      /**
      * This class is used to merge two or more
      * existing pdf file using iText jar.
      */
      public class PDFMerger {

      static void mergePdfFiles(List<InputStream> inputPdfList,
      OutputStream outputStream) throws Exception{
      //Create document and pdfReader objects.
      Document document = new Document();
      List<PdfReader> readers =
      new ArrayList<PdfReader>();
      int totalPages = 0;

      //Create pdf Iterator object using inputPdfList.
      Iterator<InputStream> pdfIterator =
      inputPdfList.iterator();

      // Create reader list for the input pdf files.
      while (pdfIterator.hasNext()) {
      InputStream pdf = pdfIterator.next();
      PdfReader pdfReader = new PdfReader(pdf);
      readers.add(pdfReader);
      totalPages = totalPages + pdfReader.getNumberOfPages();
      }

      // Create writer for the outputStream
      PdfWriter writer = PdfWriter.getInstance(document, outputStream);

      //Open document.
      document.open();

      //Contain the pdf data.
      PdfContentByte pageContentByte = writer.getDirectContent();

      PdfImportedPage pdfImportedPage;
      int currentPdfReaderPage = 1;
      Iterator<PdfReader> iteratorPDFReader = readers.iterator();

      // Iterate and process the reader list.
      while (iteratorPDFReader.hasNext()) {
      PdfReader pdfReader = iteratorPDFReader.next();
      //Create page and add content.
      while (currentPdfReaderPage <= pdfReader.getNumberOfPages()) {
      document.newPage();
      pdfImportedPage = writer.getImportedPage(
      pdfReader,currentPdfReaderPage);
      pageContentByte.addTemplate(pdfImportedPage, 0, 0);
      currentPdfReaderPage++;
      }
      currentPdfReaderPage = 1;
      }

      //Close document and outputStream.
      outputStream.flush();
      document.close();
      outputStream.close();

      System.out.println("Pdf files merged successfully.");
      }

      public static void main(String args){
      try {
      //Prepare input pdf file list as list of input stream.
      List<InputStream> inputPdfList = new ArrayList<InputStream>();
      inputPdfList.add(new FileInputStream("..\pdf\pdf_1.pdf"));
      inputPdfList.add(new FileInputStream("..\pdf\pdf_2.pdf"));
      inputPdfList.add(new FileInputStream("..\pdf\pdf_3.pdf"));
      inputPdfList.add(new FileInputStream("..\pdf\pdf_4.pdf"));


      //Prepare output stream for merged pdf file.
      OutputStream outputStream =
      new FileOutputStream("..\pdf\MergeFile_1234.pdf");

      //call method to merge pdf files.
      mergePdfFiles(inputPdfList, outputStream);
      } catch (Exception e) {
      e.printStackTrace();
      }
      }
      }





      share|improve this answer



















      • 1





        The question clearly is tagged pdfbox. You present a solution for itext. Thus, your answer is off-topic. (That been said, your iText solution also is a bad one which iText developers usually recommend against as it drops interactive features and ignores rotation and page sizes.)

        – mkl
        Jan 9 '17 at 21:59











      • Then the title should be "How to merge two PDF files into one in Java with PdfBox"

        – Lluis Martinez
        Dec 11 '17 at 11:35






      • 1





        In addition iText comes with a nasty license.

        – Daniel Bo
        Jan 16 '18 at 15:54











      • This example is named IncorrectExample because this is not how you wou typically solve the problem of rotating pages, nor of merging documents. The correct way is NOT to use Document / PdfWriter, but to use PdfStamper, PdfCopy or PdfSmartCopy. However: in the question mentioned above, the circumstances are very particular and using this example in those circumstances is justified: developers.itextpdf.com/examples/merging-pdf-documents-itext5/…

        – victorpacheco3107
        Mar 16 '18 at 16:23














      8












      8








      8







      This is a ready to use code, merging four pdf files with itext.jar from http://central.maven.org/maven2/com/itextpdf/itextpdf/5.5.0/itextpdf-5.5.0.jar, more on http://tutorialspointexamples.com/



      import com.itextpdf.text.Document;
      import com.itextpdf.text.pdf.PdfContentByte;
      import com.itextpdf.text.pdf.PdfImportedPage;
      import com.itextpdf.text.pdf.PdfReader;
      import com.itextpdf.text.pdf.PdfWriter;

      /**
      * This class is used to merge two or more
      * existing pdf file using iText jar.
      */
      public class PDFMerger {

      static void mergePdfFiles(List<InputStream> inputPdfList,
      OutputStream outputStream) throws Exception{
      //Create document and pdfReader objects.
      Document document = new Document();
      List<PdfReader> readers =
      new ArrayList<PdfReader>();
      int totalPages = 0;

      //Create pdf Iterator object using inputPdfList.
      Iterator<InputStream> pdfIterator =
      inputPdfList.iterator();

      // Create reader list for the input pdf files.
      while (pdfIterator.hasNext()) {
      InputStream pdf = pdfIterator.next();
      PdfReader pdfReader = new PdfReader(pdf);
      readers.add(pdfReader);
      totalPages = totalPages + pdfReader.getNumberOfPages();
      }

      // Create writer for the outputStream
      PdfWriter writer = PdfWriter.getInstance(document, outputStream);

      //Open document.
      document.open();

      //Contain the pdf data.
      PdfContentByte pageContentByte = writer.getDirectContent();

      PdfImportedPage pdfImportedPage;
      int currentPdfReaderPage = 1;
      Iterator<PdfReader> iteratorPDFReader = readers.iterator();

      // Iterate and process the reader list.
      while (iteratorPDFReader.hasNext()) {
      PdfReader pdfReader = iteratorPDFReader.next();
      //Create page and add content.
      while (currentPdfReaderPage <= pdfReader.getNumberOfPages()) {
      document.newPage();
      pdfImportedPage = writer.getImportedPage(
      pdfReader,currentPdfReaderPage);
      pageContentByte.addTemplate(pdfImportedPage, 0, 0);
      currentPdfReaderPage++;
      }
      currentPdfReaderPage = 1;
      }

      //Close document and outputStream.
      outputStream.flush();
      document.close();
      outputStream.close();

      System.out.println("Pdf files merged successfully.");
      }

      public static void main(String args){
      try {
      //Prepare input pdf file list as list of input stream.
      List<InputStream> inputPdfList = new ArrayList<InputStream>();
      inputPdfList.add(new FileInputStream("..\pdf\pdf_1.pdf"));
      inputPdfList.add(new FileInputStream("..\pdf\pdf_2.pdf"));
      inputPdfList.add(new FileInputStream("..\pdf\pdf_3.pdf"));
      inputPdfList.add(new FileInputStream("..\pdf\pdf_4.pdf"));


      //Prepare output stream for merged pdf file.
      OutputStream outputStream =
      new FileOutputStream("..\pdf\MergeFile_1234.pdf");

      //call method to merge pdf files.
      mergePdfFiles(inputPdfList, outputStream);
      } catch (Exception e) {
      e.printStackTrace();
      }
      }
      }





      share|improve this answer













      This is a ready to use code, merging four pdf files with itext.jar from http://central.maven.org/maven2/com/itextpdf/itextpdf/5.5.0/itextpdf-5.5.0.jar, more on http://tutorialspointexamples.com/



      import com.itextpdf.text.Document;
      import com.itextpdf.text.pdf.PdfContentByte;
      import com.itextpdf.text.pdf.PdfImportedPage;
      import com.itextpdf.text.pdf.PdfReader;
      import com.itextpdf.text.pdf.PdfWriter;

      /**
      * This class is used to merge two or more
      * existing pdf file using iText jar.
      */
      public class PDFMerger {

      static void mergePdfFiles(List<InputStream> inputPdfList,
      OutputStream outputStream) throws Exception{
      //Create document and pdfReader objects.
      Document document = new Document();
      List<PdfReader> readers =
      new ArrayList<PdfReader>();
      int totalPages = 0;

      //Create pdf Iterator object using inputPdfList.
      Iterator<InputStream> pdfIterator =
      inputPdfList.iterator();

      // Create reader list for the input pdf files.
      while (pdfIterator.hasNext()) {
      InputStream pdf = pdfIterator.next();
      PdfReader pdfReader = new PdfReader(pdf);
      readers.add(pdfReader);
      totalPages = totalPages + pdfReader.getNumberOfPages();
      }

      // Create writer for the outputStream
      PdfWriter writer = PdfWriter.getInstance(document, outputStream);

      //Open document.
      document.open();

      //Contain the pdf data.
      PdfContentByte pageContentByte = writer.getDirectContent();

      PdfImportedPage pdfImportedPage;
      int currentPdfReaderPage = 1;
      Iterator<PdfReader> iteratorPDFReader = readers.iterator();

      // Iterate and process the reader list.
      while (iteratorPDFReader.hasNext()) {
      PdfReader pdfReader = iteratorPDFReader.next();
      //Create page and add content.
      while (currentPdfReaderPage <= pdfReader.getNumberOfPages()) {
      document.newPage();
      pdfImportedPage = writer.getImportedPage(
      pdfReader,currentPdfReaderPage);
      pageContentByte.addTemplate(pdfImportedPage, 0, 0);
      currentPdfReaderPage++;
      }
      currentPdfReaderPage = 1;
      }

      //Close document and outputStream.
      outputStream.flush();
      document.close();
      outputStream.close();

      System.out.println("Pdf files merged successfully.");
      }

      public static void main(String args){
      try {
      //Prepare input pdf file list as list of input stream.
      List<InputStream> inputPdfList = new ArrayList<InputStream>();
      inputPdfList.add(new FileInputStream("..\pdf\pdf_1.pdf"));
      inputPdfList.add(new FileInputStream("..\pdf\pdf_2.pdf"));
      inputPdfList.add(new FileInputStream("..\pdf\pdf_3.pdf"));
      inputPdfList.add(new FileInputStream("..\pdf\pdf_4.pdf"));


      //Prepare output stream for merged pdf file.
      OutputStream outputStream =
      new FileOutputStream("..\pdf\MergeFile_1234.pdf");

      //call method to merge pdf files.
      mergePdfFiles(inputPdfList, outputStream);
      } catch (Exception e) {
      e.printStackTrace();
      }
      }
      }






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Jan 9 '17 at 13:42









      benitobenito

      16228




      16228








      • 1





        The question clearly is tagged pdfbox. You present a solution for itext. Thus, your answer is off-topic. (That been said, your iText solution also is a bad one which iText developers usually recommend against as it drops interactive features and ignores rotation and page sizes.)

        – mkl
        Jan 9 '17 at 21:59











      • Then the title should be "How to merge two PDF files into one in Java with PdfBox"

        – Lluis Martinez
        Dec 11 '17 at 11:35






      • 1





        In addition iText comes with a nasty license.

        – Daniel Bo
        Jan 16 '18 at 15:54











      • This example is named IncorrectExample because this is not how you wou typically solve the problem of rotating pages, nor of merging documents. The correct way is NOT to use Document / PdfWriter, but to use PdfStamper, PdfCopy or PdfSmartCopy. However: in the question mentioned above, the circumstances are very particular and using this example in those circumstances is justified: developers.itextpdf.com/examples/merging-pdf-documents-itext5/…

        – victorpacheco3107
        Mar 16 '18 at 16:23














      • 1





        The question clearly is tagged pdfbox. You present a solution for itext. Thus, your answer is off-topic. (That been said, your iText solution also is a bad one which iText developers usually recommend against as it drops interactive features and ignores rotation and page sizes.)

        – mkl
        Jan 9 '17 at 21:59











      • Then the title should be "How to merge two PDF files into one in Java with PdfBox"

        – Lluis Martinez
        Dec 11 '17 at 11:35






      • 1





        In addition iText comes with a nasty license.

        – Daniel Bo
        Jan 16 '18 at 15:54











      • This example is named IncorrectExample because this is not how you wou typically solve the problem of rotating pages, nor of merging documents. The correct way is NOT to use Document / PdfWriter, but to use PdfStamper, PdfCopy or PdfSmartCopy. However: in the question mentioned above, the circumstances are very particular and using this example in those circumstances is justified: developers.itextpdf.com/examples/merging-pdf-documents-itext5/…

        – victorpacheco3107
        Mar 16 '18 at 16:23








      1




      1





      The question clearly is tagged pdfbox. You present a solution for itext. Thus, your answer is off-topic. (That been said, your iText solution also is a bad one which iText developers usually recommend against as it drops interactive features and ignores rotation and page sizes.)

      – mkl
      Jan 9 '17 at 21:59





      The question clearly is tagged pdfbox. You present a solution for itext. Thus, your answer is off-topic. (That been said, your iText solution also is a bad one which iText developers usually recommend against as it drops interactive features and ignores rotation and page sizes.)

      – mkl
      Jan 9 '17 at 21:59













      Then the title should be "How to merge two PDF files into one in Java with PdfBox"

      – Lluis Martinez
      Dec 11 '17 at 11:35





      Then the title should be "How to merge two PDF files into one in Java with PdfBox"

      – Lluis Martinez
      Dec 11 '17 at 11:35




      1




      1





      In addition iText comes with a nasty license.

      – Daniel Bo
      Jan 16 '18 at 15:54





      In addition iText comes with a nasty license.

      – Daniel Bo
      Jan 16 '18 at 15:54













      This example is named IncorrectExample because this is not how you wou typically solve the problem of rotating pages, nor of merging documents. The correct way is NOT to use Document / PdfWriter, but to use PdfStamper, PdfCopy or PdfSmartCopy. However: in the question mentioned above, the circumstances are very particular and using this example in those circumstances is justified: developers.itextpdf.com/examples/merging-pdf-documents-itext5/…

      – victorpacheco3107
      Mar 16 '18 at 16:23





      This example is named IncorrectExample because this is not how you wou typically solve the problem of rotating pages, nor of merging documents. The correct way is NOT to use Document / PdfWriter, but to use PdfStamper, PdfCopy or PdfSmartCopy. However: in the question mentioned above, the circumstances are very particular and using this example in those circumstances is justified: developers.itextpdf.com/examples/merging-pdf-documents-itext5/…

      – victorpacheco3107
      Mar 16 '18 at 16:23











      4














      package article14;

      import java.io.File;
      import org.apache.pdfbox.pdmodel.PDDocument;
      import org.apache.pdfbox.pdmodel.PDPage;
      import org.apache.pdfbox.util.PDFMergerUtility;

      public class Pdf
      {
      public static void main(String args)
      {
      new Pdf().createNew();
      new Pdf().combine();
      }

      public void combine()
      {
      try
      {
      PDFMergerUtility mergePdf = new PDFMergerUtility();
      String folder ="pdf";
      File _folder = new File(folder);
      File filesInFolder;
      filesInFolder = _folder.listFiles();
      for (File string : filesInFolder)
      {
      mergePdf.addSource(string);
      }
      mergePdf.setDestinationFileName("Combined.pdf");
      mergePdf.mergeDocuments();
      }
      catch(Exception e)
      {

      }
      }

      public void createNew()
      {
      PDDocument document = null;
      try
      {
      String filename="test.pdf";
      document=new PDDocument();
      PDPage blankPage = new PDPage();
      document.addPage( blankPage );
      document.save( filename );
      }
      catch(Exception e)
      {

      }
      }

      }





      share|improve this answer
























      • Swallowing exceptions is a bad pattern. catch(Exception e){ }

        – Lluis Martinez
        Dec 11 '17 at 11:40


















      4














      package article14;

      import java.io.File;
      import org.apache.pdfbox.pdmodel.PDDocument;
      import org.apache.pdfbox.pdmodel.PDPage;
      import org.apache.pdfbox.util.PDFMergerUtility;

      public class Pdf
      {
      public static void main(String args)
      {
      new Pdf().createNew();
      new Pdf().combine();
      }

      public void combine()
      {
      try
      {
      PDFMergerUtility mergePdf = new PDFMergerUtility();
      String folder ="pdf";
      File _folder = new File(folder);
      File filesInFolder;
      filesInFolder = _folder.listFiles();
      for (File string : filesInFolder)
      {
      mergePdf.addSource(string);
      }
      mergePdf.setDestinationFileName("Combined.pdf");
      mergePdf.mergeDocuments();
      }
      catch(Exception e)
      {

      }
      }

      public void createNew()
      {
      PDDocument document = null;
      try
      {
      String filename="test.pdf";
      document=new PDDocument();
      PDPage blankPage = new PDPage();
      document.addPage( blankPage );
      document.save( filename );
      }
      catch(Exception e)
      {

      }
      }

      }





      share|improve this answer
























      • Swallowing exceptions is a bad pattern. catch(Exception e){ }

        – Lluis Martinez
        Dec 11 '17 at 11:40
















      4












      4








      4







      package article14;

      import java.io.File;
      import org.apache.pdfbox.pdmodel.PDDocument;
      import org.apache.pdfbox.pdmodel.PDPage;
      import org.apache.pdfbox.util.PDFMergerUtility;

      public class Pdf
      {
      public static void main(String args)
      {
      new Pdf().createNew();
      new Pdf().combine();
      }

      public void combine()
      {
      try
      {
      PDFMergerUtility mergePdf = new PDFMergerUtility();
      String folder ="pdf";
      File _folder = new File(folder);
      File filesInFolder;
      filesInFolder = _folder.listFiles();
      for (File string : filesInFolder)
      {
      mergePdf.addSource(string);
      }
      mergePdf.setDestinationFileName("Combined.pdf");
      mergePdf.mergeDocuments();
      }
      catch(Exception e)
      {

      }
      }

      public void createNew()
      {
      PDDocument document = null;
      try
      {
      String filename="test.pdf";
      document=new PDDocument();
      PDPage blankPage = new PDPage();
      document.addPage( blankPage );
      document.save( filename );
      }
      catch(Exception e)
      {

      }
      }

      }





      share|improve this answer













      package article14;

      import java.io.File;
      import org.apache.pdfbox.pdmodel.PDDocument;
      import org.apache.pdfbox.pdmodel.PDPage;
      import org.apache.pdfbox.util.PDFMergerUtility;

      public class Pdf
      {
      public static void main(String args)
      {
      new Pdf().createNew();
      new Pdf().combine();
      }

      public void combine()
      {
      try
      {
      PDFMergerUtility mergePdf = new PDFMergerUtility();
      String folder ="pdf";
      File _folder = new File(folder);
      File filesInFolder;
      filesInFolder = _folder.listFiles();
      for (File string : filesInFolder)
      {
      mergePdf.addSource(string);
      }
      mergePdf.setDestinationFileName("Combined.pdf");
      mergePdf.mergeDocuments();
      }
      catch(Exception e)
      {

      }
      }

      public void createNew()
      {
      PDDocument document = null;
      try
      {
      String filename="test.pdf";
      document=new PDDocument();
      PDPage blankPage = new PDPage();
      document.addPage( blankPage );
      document.save( filename );
      }
      catch(Exception e)
      {

      }
      }

      }






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Dec 30 '13 at 7:26









      SabapathySabapathy

      72221228




      72221228













      • Swallowing exceptions is a bad pattern. catch(Exception e){ }

        – Lluis Martinez
        Dec 11 '17 at 11:40





















      • Swallowing exceptions is a bad pattern. catch(Exception e){ }

        – Lluis Martinez
        Dec 11 '17 at 11:40



















      Swallowing exceptions is a bad pattern. catch(Exception e){ }

      – Lluis Martinez
      Dec 11 '17 at 11:40







      Swallowing exceptions is a bad pattern. catch(Exception e){ }

      – Lluis Martinez
      Dec 11 '17 at 11:40













      1














      Multiple pdf merged method using org.apache.pdfbox:



      public void mergePDFFiles(List<File> files,
      String mergedFileName) {
      try {
      PDFMergerUtility pdfmerger = new PDFMergerUtility();
      for (File file : files) {
      PDDocument document = PDDocument.load(file);
      pdfmerger.setDestinationFileName(mergedFileName);
      pdfmerger.addSource(file);
      pdfmerger.mergeDocuments(MemoryUsageSetting.setupTempFileOnly());
      document.close();
      }
      } catch (IOException e) {
      logger.error("Error to merge files. Error: " + e.getMessage());
      }
      }


      From main program, call mergePDFFiles method using list of files and target file name.



              String mergedFileName = "Merged.pdf";
      mergePDFFiles(files, mergedFileName);


      After calling mergePDFFiles, load merged file



              File mergedFile = new File(mergedFileName);





      share|improve this answer




























        1














        Multiple pdf merged method using org.apache.pdfbox:



        public void mergePDFFiles(List<File> files,
        String mergedFileName) {
        try {
        PDFMergerUtility pdfmerger = new PDFMergerUtility();
        for (File file : files) {
        PDDocument document = PDDocument.load(file);
        pdfmerger.setDestinationFileName(mergedFileName);
        pdfmerger.addSource(file);
        pdfmerger.mergeDocuments(MemoryUsageSetting.setupTempFileOnly());
        document.close();
        }
        } catch (IOException e) {
        logger.error("Error to merge files. Error: " + e.getMessage());
        }
        }


        From main program, call mergePDFFiles method using list of files and target file name.



                String mergedFileName = "Merged.pdf";
        mergePDFFiles(files, mergedFileName);


        After calling mergePDFFiles, load merged file



                File mergedFile = new File(mergedFileName);





        share|improve this answer


























          1












          1








          1







          Multiple pdf merged method using org.apache.pdfbox:



          public void mergePDFFiles(List<File> files,
          String mergedFileName) {
          try {
          PDFMergerUtility pdfmerger = new PDFMergerUtility();
          for (File file : files) {
          PDDocument document = PDDocument.load(file);
          pdfmerger.setDestinationFileName(mergedFileName);
          pdfmerger.addSource(file);
          pdfmerger.mergeDocuments(MemoryUsageSetting.setupTempFileOnly());
          document.close();
          }
          } catch (IOException e) {
          logger.error("Error to merge files. Error: " + e.getMessage());
          }
          }


          From main program, call mergePDFFiles method using list of files and target file name.



                  String mergedFileName = "Merged.pdf";
          mergePDFFiles(files, mergedFileName);


          After calling mergePDFFiles, load merged file



                  File mergedFile = new File(mergedFileName);





          share|improve this answer













          Multiple pdf merged method using org.apache.pdfbox:



          public void mergePDFFiles(List<File> files,
          String mergedFileName) {
          try {
          PDFMergerUtility pdfmerger = new PDFMergerUtility();
          for (File file : files) {
          PDDocument document = PDDocument.load(file);
          pdfmerger.setDestinationFileName(mergedFileName);
          pdfmerger.addSource(file);
          pdfmerger.mergeDocuments(MemoryUsageSetting.setupTempFileOnly());
          document.close();
          }
          } catch (IOException e) {
          logger.error("Error to merge files. Error: " + e.getMessage());
          }
          }


          From main program, call mergePDFFiles method using list of files and target file name.



                  String mergedFileName = "Merged.pdf";
          mergePDFFiles(files, mergedFileName);


          After calling mergePDFFiles, load merged file



                  File mergedFile = new File(mergedFileName);






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Dec 17 '18 at 8:30









          arifngarifng

          4126




          4126























              0














              If you want to combine two files where one overlays the other (example: document A is a template and document B has the text you want to put on the template), this works:



              after creating "doc", you want to write your template (templateFile) on top of that -



                 PDDocument watermarkDoc = PDDocument.load(getServletContext()
              .getRealPath(templateFile));
              Overlay overlay = new Overlay();

              overlay.overlay(watermarkDoc, doc);





              share|improve this answer




























                0














                If you want to combine two files where one overlays the other (example: document A is a template and document B has the text you want to put on the template), this works:



                after creating "doc", you want to write your template (templateFile) on top of that -



                   PDDocument watermarkDoc = PDDocument.load(getServletContext()
                .getRealPath(templateFile));
                Overlay overlay = new Overlay();

                overlay.overlay(watermarkDoc, doc);





                share|improve this answer


























                  0












                  0








                  0







                  If you want to combine two files where one overlays the other (example: document A is a template and document B has the text you want to put on the template), this works:



                  after creating "doc", you want to write your template (templateFile) on top of that -



                     PDDocument watermarkDoc = PDDocument.load(getServletContext()
                  .getRealPath(templateFile));
                  Overlay overlay = new Overlay();

                  overlay.overlay(watermarkDoc, doc);





                  share|improve this answer













                  If you want to combine two files where one overlays the other (example: document A is a template and document B has the text you want to put on the template), this works:



                  after creating "doc", you want to write your template (templateFile) on top of that -



                     PDDocument watermarkDoc = PDDocument.load(getServletContext()
                  .getRealPath(templateFile));
                  Overlay overlay = new Overlay();

                  overlay.overlay(watermarkDoc, doc);






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Feb 19 '14 at 22:45









                  Dave WDave W

                  211




                  211























                      0














                      Using iText (existing PDF in bytes)



                          public static byte mergePDF(List<byte> pdfFilesAsByteArray) throws DocumentException, IOException {

                      ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                      Document document = null;
                      PdfCopy writer = null;

                      for (byte pdfByteArray : pdfFilesAsByteArray) {

                      try {
                      PdfReader reader = new PdfReader(pdfByteArray);
                      int numberOfPages = reader.getNumberOfPages();

                      if (document == null) {
                      document = new Document(reader.getPageSizeWithRotation(1));
                      writer = new PdfCopy(document, outStream); // new
                      document.open();
                      }
                      PdfImportedPage page;
                      for (int i = 0; i < numberOfPages;) {
                      ++i;
                      page = writer.getImportedPage(reader, i);
                      writer.addPage(page);
                      }
                      }

                      catch (Exception e) {
                      e.printStackTrace();
                      }

                      }

                      document.close();
                      outStream.close();
                      return outStream.toByteArray();

                      }





                      share|improve this answer
























                      • The OP quite clearly said "I want to merge many PDF files into one using PDFBox". iText is not PDFBox.

                        – mkl
                        May 18 '18 at 21:13











                      • this works me xd

                        – Alberto Acuña
                        Jan 21 at 8:39
















                      0














                      Using iText (existing PDF in bytes)



                          public static byte mergePDF(List<byte> pdfFilesAsByteArray) throws DocumentException, IOException {

                      ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                      Document document = null;
                      PdfCopy writer = null;

                      for (byte pdfByteArray : pdfFilesAsByteArray) {

                      try {
                      PdfReader reader = new PdfReader(pdfByteArray);
                      int numberOfPages = reader.getNumberOfPages();

                      if (document == null) {
                      document = new Document(reader.getPageSizeWithRotation(1));
                      writer = new PdfCopy(document, outStream); // new
                      document.open();
                      }
                      PdfImportedPage page;
                      for (int i = 0; i < numberOfPages;) {
                      ++i;
                      page = writer.getImportedPage(reader, i);
                      writer.addPage(page);
                      }
                      }

                      catch (Exception e) {
                      e.printStackTrace();
                      }

                      }

                      document.close();
                      outStream.close();
                      return outStream.toByteArray();

                      }





                      share|improve this answer
























                      • The OP quite clearly said "I want to merge many PDF files into one using PDFBox". iText is not PDFBox.

                        – mkl
                        May 18 '18 at 21:13











                      • this works me xd

                        – Alberto Acuña
                        Jan 21 at 8:39














                      0












                      0








                      0







                      Using iText (existing PDF in bytes)



                          public static byte mergePDF(List<byte> pdfFilesAsByteArray) throws DocumentException, IOException {

                      ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                      Document document = null;
                      PdfCopy writer = null;

                      for (byte pdfByteArray : pdfFilesAsByteArray) {

                      try {
                      PdfReader reader = new PdfReader(pdfByteArray);
                      int numberOfPages = reader.getNumberOfPages();

                      if (document == null) {
                      document = new Document(reader.getPageSizeWithRotation(1));
                      writer = new PdfCopy(document, outStream); // new
                      document.open();
                      }
                      PdfImportedPage page;
                      for (int i = 0; i < numberOfPages;) {
                      ++i;
                      page = writer.getImportedPage(reader, i);
                      writer.addPage(page);
                      }
                      }

                      catch (Exception e) {
                      e.printStackTrace();
                      }

                      }

                      document.close();
                      outStream.close();
                      return outStream.toByteArray();

                      }





                      share|improve this answer













                      Using iText (existing PDF in bytes)



                          public static byte mergePDF(List<byte> pdfFilesAsByteArray) throws DocumentException, IOException {

                      ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                      Document document = null;
                      PdfCopy writer = null;

                      for (byte pdfByteArray : pdfFilesAsByteArray) {

                      try {
                      PdfReader reader = new PdfReader(pdfByteArray);
                      int numberOfPages = reader.getNumberOfPages();

                      if (document == null) {
                      document = new Document(reader.getPageSizeWithRotation(1));
                      writer = new PdfCopy(document, outStream); // new
                      document.open();
                      }
                      PdfImportedPage page;
                      for (int i = 0; i < numberOfPages;) {
                      ++i;
                      page = writer.getImportedPage(reader, i);
                      writer.addPage(page);
                      }
                      }

                      catch (Exception e) {
                      e.printStackTrace();
                      }

                      }

                      document.close();
                      outStream.close();
                      return outStream.toByteArray();

                      }






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered May 18 '18 at 17:03









                      Ricardo Jl RufinoRicardo Jl Rufino

                      41037




                      41037













                      • The OP quite clearly said "I want to merge many PDF files into one using PDFBox". iText is not PDFBox.

                        – mkl
                        May 18 '18 at 21:13











                      • this works me xd

                        – Alberto Acuña
                        Jan 21 at 8:39



















                      • The OP quite clearly said "I want to merge many PDF files into one using PDFBox". iText is not PDFBox.

                        – mkl
                        May 18 '18 at 21:13











                      • this works me xd

                        – Alberto Acuña
                        Jan 21 at 8:39

















                      The OP quite clearly said "I want to merge many PDF files into one using PDFBox". iText is not PDFBox.

                      – mkl
                      May 18 '18 at 21:13





                      The OP quite clearly said "I want to merge many PDF files into one using PDFBox". iText is not PDFBox.

                      – mkl
                      May 18 '18 at 21:13













                      this works me xd

                      – Alberto Acuña
                      Jan 21 at 8:39





                      this works me xd

                      – Alberto Acuña
                      Jan 21 at 8:39


















                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3585329%2fhow-to-merge-two-pdf-files-into-one-in-java%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Monofisismo

                      Angular Downloading a file using contenturl with Basic Authentication

                      Olmecas