user1012506 user1012506 - 1 year ago 161
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


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



mkl mkl
Answer Source

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:

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download