如何在Java中将PdfCopy转换为字节数组

时间:2016-11-17 08:07:05

标签: java pdf itext

我尝试将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();
}

感谢。

索哈

2 个答案:

答案 0 :(得分:2)

而不是在

中使用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);

答案 1 :(得分:0)

span