[英]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.