0

Using spring and pdfbox apache library I have edited the PDF in controller, but nor sure how I can save this pdf to classpath so that I can convert the saved pdf to bytes and pass it on to a service.

Any help is appreciated. Thank you.

My controller code below:

 @RequestMapping("/individual/load/editablePDF.do")
public void getFile(HttpServletRequest request,HttpServletResponse response) throws IOException {
    Resource resource = new ClassPathResource("EditableFile.pdf");
    InputStream resourceInputStream = resource.getInputStream();
    PDDocument pdfDoc = PDDocument.load(resourceInputStream);
    PDDocumentCatalog docCatalog = pdfDoc.getDocumentCatalog();
    PDAcroForm acroForm = docCatalog.getAcroForm();
    List<PDField> fieldList = acroForm.getFields();
    String[] fieldArray = new String[fieldList.size()];
    int i = 0;
    for (PDField sField : fieldList) {
        fieldArray[i] = sField.getFullyQualifiedName();
        i++;
    }
    for (String f : fieldArray) {
        PDField field = acroForm.getField(f);

        System.out.println("f is: " + f);
        if (f.contains("company name")) {
            String value = "Discovery";
            field.setValue(value);
            System.out.println("printed: " + value + " to: " + f);
        }

    }
    try {
        pdfDoc.save("D:\\workspace\\TestSamples\\src\\Editable_ Discovery wellness days application form 2017-SAVED.pdf");//Not sure how to achieve this?
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    pdfDoc.close();
}

1 Answers1

1

This worked for me.

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
document.save(byteArrayOutputStream);
document.close();
InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());