将文档转换为字节 [] 流 - Java

我正在使用 更新可编辑 PDF 的值。我想返回流,而不是保存。我保存了它,它工作正常。现在我想返回而不是保存它。PDFBoxbyte[]


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


湖上湖
浏览 158回答 1
1回答

萧十郎

使用接受 的重载保存方法,并使用 。OutputStreamByteArrayOutputStreampublic 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    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java