如何从PdfDocument中提取byte []数组

时间:2019-03-25 14:19:37

标签: java arrays pdf inputstream itext7

经过大量研究,我仍然找不到从PdfDocument对象提取byte[]的方法。我该如何实现?

我尝试了FileInputStream,但实际上我没有PdfDocument的“物理路径”,因为我是通过编程方式创建的。而且,我对byte[]不太熟悉。

有人可以帮我吗?

    PdfDocument pdfDocumentWithoutSplit = getPdfUtils().generatePdfDocumentByMedia(shippingLabel);

        for (int i = 1; i < pdfDocumentWithoutSplit.getNumberOfPages() + 1; i++) {
            final ByteArrayOutputStream pdfByteArray = new ByteArrayOutputStream();
            final PdfDocument pdfDocument = new PdfDocument(new PdfWriter(pdfByteArray));

            pdfDocument.movePage(pdfDocumentWithoutSplit.getPage(i), i);
            pdfByteArray.close();
             //now here I need to get the bytes of each pdfDocument somehow

        }

欢呼

2 个答案:

答案 0 :(得分:0)

PDF中的所有内容都应作为字符串处理。首先,您需要搜索物理路径(您可以使用正则表达式或类似的字符串处理功能,根据生成方式和使用的语言来搜索路径)。然后使用PDF阅读器(因为它不是纯文本文档)在PDF中搜索看起来像字节数组的字符串。最后,您需要通过提取内部数据并使用拆分或数组生成方法将字符串转换为数组。祝你好运。

答案 1 :(得分:0)

        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final PdfDocument pdfDocument = new PdfDocument(new PdfWriter(baos ));
        pdfDocument.movePage(pdfDocumentWithoutSplit.getPage(i), i);
        pdfDocument.close();
        // should close the PdfWriter, and hence the ByteArrayOutputStream
        baos .close();
        byte[] bytes = baos .toByteArray();

关闭操作会刷新内存中的所有缓冲数据,并填充ByteArrayOutputStream。

相关问题