user1012506 user1012506 - 18 days ago 5
Java Question

How to convert PdfCopy to byte array in java

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

mkl mkl
Answer

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);
Comments