In the nearest future I will be developing a PDF generating service. It’s all about a simple template being filled using data coming from request.
During my research I heard about Apache PDFBox and at the moment I am testing it – looks very handy, but I have some annoying problem – when the PDF is generated it has this strange, gray borders.
I made a research and did not found the way to get rid of them.
My sample DataDTO:
@Data
public class DocumentDataDto {
private int documentNumber;
private LocalDate date;
private String creatorFirstName;
private String creatorLastName;
}
Sample controller:
@RestController
@RequiredArgsConstructor
public class PdfController {
private final PdfService pdfService;
@PostMapping(value = "/generatePdf")
public ResponseEntity<ByteArrayResource> generatePdf(@RequestBody DocumentDataDto data) {
ByteArrayResource pdf = pdfService.generatePdf(data);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=generated.pdf");
headers.add(HttpHeaders.CONTENT_TYPE, "application/pdf");
return ResponseEntity.ok()
.headers(headers)
.contentLength(pdf.contentLength())
.body(pdf);
}
}
Sample service:
@Service
public class PdfService {
public ByteArrayResource generatePdf(DocumentDataDto data) {
try {
ClassPathResource pdfResource = new ClassPathResource("templates/template1.pdf");
try (InputStream inputStream = pdfResource.getInputStream();
PDDocument document = PDDocument.load(inputStream)) {
PDAcroForm form = document.getDocumentCatalog().getAcroForm();
if (form != null) {
PDField field = form.getField("Text1");
if (field != null) {
field.setValue(String.valueOf(data.getDocumentNumber()));
}
field = form.getField("Text2");
if (field != null) {
field.setValue(String.valueOf(data.getDate()));
}
field = form.getField("Text3");
if (field != null) {
field.setValue(data.getCreatorFirstName() + " " + data.getCreatorLastName());
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
document.save(byteArrayOutputStream);
return new ByteArrayResource(byteArrayOutputStream.toByteArray());
}
}
} catch (IOException e) {
e.printStackTrace();
}
return new ByteArrayResource(new byte[0]);
}
}
*NOTE: The code above is just a sample – I am aware that there should be some exception handling instead of returning empty byte array 🙂 *
My PDF template looks simple as that:
Created using https://www.pdfescape.com
I have tried to remove the styles from AcroForm, as well as making them invisible. Unfortunately, no one of my approaches helped. The final output was always like:
I have to admit, that is my first time of creating such a service for PDF.
If you have any advices, please let me know – maybe there are more straight-forward ways to achieve the PDF file filled with pure text?
Much appreciate all help!
You need to sign in to view this answers
Leave feedback about this