Generate PDF
A product catalogue report built from the product table with OpenPDF: title, grouped tables with a header
row that repeats on every page, zebra rows, optional barcode images and a total. Change the options - the PDF updates.
How it works
- Read data with Spring Data JPA:
productRepository.findAllByOrderByCategoryAscNameAsc(). PdfKit.render(setup, title, body)createsnew Document(pageSize, margins), attachesPdfWriterto aByteArrayOutputStream, opens the document and calls your code.- Add content:
Paragraphfor text,PdfPTable+PdfPCellfor tables,Image.getInstance(pngBytes)for barcodes. - The bytes go back to the browser as
application/pdf- nothing is written to disk.
byte[] pdf = pdfKit.render(setup, "Product Catalogue", (doc, writer) -> {
doc.add(new Paragraph("Product Catalogue", Fonts.bold(20)));
PdfPTable t = new PdfPTable(new float[]{14, 40, 12, 15, 13});
t.setWidthPercentage(100);
t.setHeaderRows(1); // header repeats on every page
t.addCell(head("SKU", Element.ALIGN_LEFT));
...
for (Product p : products) { t.addCell(body(p.getSku(), Element.ALIGN_LEFT, shade)); ... }
doc.add(t);
});
SELECT category, COUNT(*) AS products, SUM(unit_price * stock) AS stock_value
FROM product GROUP BY category ORDER BY category;
Files: service/CatalogueReportService.java, print/PdfKit.java, print/PdfParts.java.