353 Generate PDF

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.

Download PDF

Other PDFs in this lab: invoices, receipts, labels, certificates, templates.

How it works
  1. Read data with Spring Data JPA: productRepository.findAllByOrderByCategoryAscNameAsc().
  2. PdfKit.render(setup, title, body) creates new Document(pageSize, margins), attaches PdfWriter to a ByteArrayOutputStream, opens the document and calls your code.
  3. Add content: Paragraph for text, PdfPTable + PdfPCell for tables, Image.getInstance(pngBytes) for barcodes.
  4. 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.