将 pdfDocument 转换为 byte[] 流 - PDFBox Java

Converting pdfDocument to byte[] stream - PDFBox Java

我正在使用 PDFBox 更新可编辑 PDF 的值。我不想保存,而是 return 流。我保存了它,一切正常。现在我想 return byte[] 而不是保存它。

public static void main(String[] args) throws IOException
{
    String formTemplate = "myFormPdf.pdf";

    try (PDDocument pdfDocument = PDDocument.load(new File(formTemplate)))
    {
        PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();

        if (acroForm != null)
        {

            PDTextField field = (PDTextField) acroForm.getField( "sampleField" );
            field.setValue("Text Entry");
        }

        pdfDocument.save("updatedPdf.pdf"); // instead of this I need STREAM
    }
}

我尝试了 SerializationUtils.serialize 但未能序列化它。

Failed to serialize object of type: class org.apache.pdfbox.pdfmodel.PDDcoumemt

使用接受 OutputStream 的重载 save 方法并使用 ByteArrayOutputStream.

public static void main(String[] args) throws IOException
{
    String formTemplate = "myFormPdf.pdf";

    try (PDDocument pdfDocument = PDDocument.load(new File(formTemplate)))
    {
        PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();

        if (acroForm != null)
        {

           PDTextField field = (PDTextField) acroForm.getField( "sampleField" );
           field.setValue("Text Entry");
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        pdfDocument.save(baos);
        byte[] pdfBytes = baos.toByteArray(); // PDF Bytes
    }
}