2

I try to merge 2 PDF files into one PDF. I did it with PdfCopy.addPage(...) now I have good PdfCopy and I want to get it as byte array.

How can I do it? This is my code:

public void mergePDF(ActionEvent actionEvent)  throws DocumentException, FileNotFoundException, IOException {

    String[] files = { "C:\\first.pdf","C:\sescond"};
    Document document = new Document();
    PdfCopy copy = new PdfCopy(document, new FileOutputStream("C:\\temp\\myMergedFile.pdf"));
    document.open();
    PdfReader reader;
    int n;
    for (int i = 0; i < files.length; i++) {
        reader = new PdfReader(files[i]);
        n = reader.getNumberOfPages();
        for (int page = 0; page < n; ) {
            copy.addPage(copy.getImportedPage(reader, ++page));
        }
        copy.freeReader(reader);
        reader.close();
    }    
    document.close();
}

Thanks.

soha

1
  • You are not saying which library you have used. Please add a tag and or upadet your question with this Commented Nov 17, 2016 at 8:46

2 Answers 2

3

Instead of using a FileOutputStream in

PdfCopy copy = new PdfCopy(document, new FileOutputStream("C:\\temp\\myMergedFile.pdf"));

simply use a ByteArrayOutputStream:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfCopy copy = new PdfCopy(document, baos);

After closing the document you can retrieve the byte array:

document.close();
byte[] documentBytes = baos.toByteArray();

If you want to have the document both as byte array and as file, simply add

Files.write(new File("PATH_AND_NAME_OF_FILE.pdf").toPath(), documentBytes);
Sign up to request clarification or add additional context in comments.

Comments

0
 public static void main( String[] args )
   {
    FileInputStream fileInputStream=null;

    File file = new File("C:\\testing.txt");

    byte[] bFile = new byte[(int) file.length()];

    try {
        //convert file into array of bytes
    fileInputStream = new FileInputStream(file);
    fileInputStream.read(bFile);
    fileInputStream.close();

    for (int i = 0; i < bFile.length; i++) {
        System.out.print((char)bFile[i]);
        }

    System.out.println("Done");
    }catch(Exception e){
        e.printStackTrace();
    }
   }

2 Comments

Nice, but I don't want use path of the PDF, I have use with convert.
Unless you are bound to a very old Java version, you might want to make this a one-liner using java.nio.file.Files.readAllBytes(Path).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.