1

I am updating the values of an editable PDF using PDFBox. Instead of saving, I want to return stream. I saved it, it works all fine. Now I want to return byte[] instead of saving it.

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
    }
}

I tried SerializationUtils.serialize but it fails to serialize it.

Failed to serialize object of type: class org.apache.pdfbox.pdfmodel.PDDcoumemt
2
  • What is the error you are getting?? Commented Apr 1, 2019 at 8:46
  • @CommonMan updated it Commented Apr 1, 2019 at 8:50

1 Answer 1

3

Use the overloaded save method which accepts an OutputStream and use 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
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

nice! didn't check the overloaded methods. Working all fine now. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.