2017-05-08 44 views
0

使用spring和pdfbox apache庫我已經在控制器中編輯了PDF,但也不知道如何將此pdf保存到類路徑中,以便可以將保存的PDF轉換爲字節並將其傳遞給服務。在classpath中保存已編輯的pdf並使用spring框架轉換爲字節

任何幫助表示讚賞。謝謝。

我控制器下面的代碼:

@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(); 
} 
+0

您也可以直接保存到OutputStream中。 –

+0

它現在工作。謝謝蒂爾曼:) –

+0

很高興聽到這一點。請刪除問題或自己回答(這是允許的)。我不確定哪些提示是有幫助的。 –

回答

1

這爲我工作。

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
document.save(byteArrayOutputStream); 
document.close(); 
InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); 
相關問題