Reputation: 2118
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
Upvotes: 2
Views: 4478
Reputation: 95928
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);
Upvotes: 3
Reputation: 658
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();
}
}
Upvotes: 0