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

标签 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();
}

谢谢。

索哈

最佳答案

而不是在

中使用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/

相关文章:

java - 多线程 TestNG DataProvider 执行

c# - 在 C# 中使用 iTextSharp 和 asp 图像调整数据库中的图像大小

c# - Itext myImage.Alignment = Image.TEXTWRAP |图片.ALIGN_RIGHT; VB等效?

java - 使用 TLS 连接通过 SMTP 发送电子邮件会加密用户名和密码吗?

java - 如何使用有偏权重将 x 变量之间的总值 1 相除

java - 现在从数据库获取行时结果集的值

android - 创建 PDF 时出错

javascript - PDF jQuery 翻书插件

c# - 如何在 C# 中获取 itextSharp 表格单元格的高度?

java - 将整个页面提取为图像 iTextPdf