我尝试将 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);
关于java - 如何在java中将PdfCopy转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40649633/