0
File newFile=new File("mergedFile.pdf");
    newFile.createNewFile();
    System.out.println(newFile.toURL());
    File oldFile1=new File("file1.pdf");
    File oldFile2=new File("file2.pdf");
    System.out.println(oldFile1.isFile());
    System.out.println(oldFile2.isFile());
    FileInputStream fin1=new FileInputStream(oldFile1);
    FileInputStream fin2=new FileInputStream(oldFile2);
    FileOutputStream fout=new FileOutputStream(newFile);
    byte[] byteData1=new byte[fin1.available()];
    fin1.read(byteData1);
    byte[] byteData2=new byte[fin2.available()];
    fin2.read(byteData2);
    int len=byteData1.length+byteData2.length;
    byte[] byteData=new byte[len];
    int j=0;
    for(int i=0;i<len;i++)
    {
        if(i<byteData1.length)
        {
            byteData[i]=byteData1[i];
        }
        else
        {
            byteData[i]=byteData2[j];
            j++;
        }
    }

    fout.write(byteData);
    fin1.close();
    fin2.close();
    fout.close();

Only the contents of file2.pdf is stored in mergedFile.pdf.What's is wrong with this way of merging the pdf?The byte contents of the file1.pdf and file2.pdf is stored in mergedFile.pdf .

  • I don't know much about PDF format internals, but I wonder if there's some kind of marker to say it's the end of the file, or some initial metadata to tell how many pages the PDF has, maybe appending the bytes won't work – Leo Jun 04 '16 at 21:50
  • Possible duplicate of [How to merge two PDF files into one in Java?](http://stackoverflow.com/questions/3585329/how-to-merge-two-pdf-files-into-one-in-java) – Roman Jun 05 '16 at 03:01
  • I have seen those answers. I just want to know that what's wrong in this approach of merging? – harishbisht29 Jun 05 '16 at 06:17
  • 1
    PDFs are not text files, they have a complex structure. You cannot just glue them together by appending their raw binary contents. You have to create a new PDF document, that will store the extracted contents of both source PDFs. – Roman Jun 05 '16 at 17:36

0 Answers0