I have a fillable pdf in which i have a field IFSC code to be filled.
This is my code to fill the acroform
public String generatePreFilledMandateForm(PnachDownloadRequestDto request) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(Constants.DATE_FORMAT_DD_MM_YYYY);
LocalDateTime now = LocalDateTime.now();
String currentDate = dtf.format(now);
String currentDateAdded10Years = dtf.format(now.plusYears(10));
PDDocument pdfDocument = PDDocument.load(new ClassPathResource("templates/IDFCPnachForm.pdf").getInputStream());
ByteArrayOutputStream byteData = new ByteArrayOutputStream();
PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
setTextField(acroForm,"date",currentDate,true);
setTextField(acroForm,"rectangleWithBank",request.getBankName().toUpperCase(),false);
setTextField(acroForm,"rectangleBankAcNumber",request.getAccountNumber(),true);
setTextField(acroForm,"rectangleIfscMicr",request.getIfscCode(),true);
setTextField(acroForm,"rectangleAmountWords",MoneyConverterDigitToWordsUtil.convertToWord(request.getAmountInRupees().toString()),false);
setTextField(acroForm,"rectangleAmount",request.getAmountInRupees().toString() + "/-",false);
setTextField(acroForm,"rectangleReference1",request.getLoanNo(),false);
setTextField(acroForm,"rectangleMobileNo",request.getPhoneNo(),false);
setTextField(acroForm,"rectanglePrimaryNameField",request.getCustomerName(),false);
setTextField(acroForm,"fromDate",currentDate,true);
setTextField(acroForm,"toDate",currentDateAdded10Years,true);
acroForm.flatten();
pdfDocument.save(byteArrayOutputStream);
pdfDocument.close();
String base64EncodedPdf = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
return base64EncodedPdf;
} catch (Exception e) {
log.error("Exception in generatePreFilledMandateForm {}",e.getMessage());
e.printStackTrace();
}
return null;
}
private void setTextField(PDAcroForm acroForm, String fieldName, String value,boolean isCombField) throws IOException {
if (value != null) {
List<PDField> fields = acroForm.getFields();
for (PDField field : fields) {
if (field.getFullyQualifiedName().equals(fieldName)) {
if (isCombField) {
((PDTextField) field).setComb(true);
}
field.setValue(value);
}
}
}
}
But post filling and flattening. The response pdf doesn't have proper comb structure. PFB Response.
Also, I am using Apache PDFBox 2.0.29.
It was an issue with the pdf i was using. Flattening the pdf and then recreating the form fields using adobe acrobat made it work.
Also, a smaller optimisation in setTextField method(suggested by @TilmanHausherr)
private void setTextField(PDAcroForm acroForm, String fieldName, String value,boolean isCombField) throws IOException {
if (value != null) {
acroForm.getField(fieldName).setValue(value);
if(isCombField) {
((PDTextField)acroForm.getField(fieldName)).setComb(true);
}
}
}