[英]How to convert PdfCopy to byte array in java
我尝试将2个PDF文件合并为一个PDF。 我是用PdfCopy.addPage(...)
现在我有很好的PdfCopy,我想以字节数组的形式获取它。
我该怎么做? 这是我的代码:
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();
}
谢谢。
索哈
而不是在中使用FileOutputStream
PdfCopy copy = new PdfCopy(document, new FileOutputStream("C:\\temp\\myMergedFile.pdf"));
只需使用ByteArrayOutputStream
:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfCopy copy = new PdfCopy(document, baos);
关闭文档后,您可以检索字节数组:
document.close();
byte[] documentBytes = baos.toByteArray();
如果要同时将文档作为字节数组和文件,只需添加
Files.write(new File("PATH_AND_NAME_OF_FILE.pdf").toPath(), documentBytes);
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.