Taming Thymeleaf Pdf Download Today
private final PdfService pdfService;
try ITextRenderer renderer = new ITextRenderer(); renderer.setDocumentFromString(html); renderer.layout(); return renderer.createPDF(null); // byte array output catch (Exception e) throw new RuntimeException("PDF generation failed", e);
private final SpringTemplateEngine templateEngine;
createPDF(null) returns byte[] in newer Flying Saucer versions. Otherwise, use a ByteArrayOutputStream . 5. Controller – Download PDF import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController public class PdfController taming thymeleaf pdf download
public PdfService(SpringTemplateEngine templateEngine) this.templateEngine = templateEngine;
public byte[] generateInvoicePdf(InvoiceDto invoice) Context context = new Context(); context.setVariable("invoice", invoice);
return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=invoice_" + id + ".pdf") .contentType(MediaType.APPLICATION_PDF) .body(pdfBytes); Controller – Download PDF import org
Here’s a focused feature guide for — covering setup, templating, rendering, and streaming. 1. Core Concept Thymeleaf alone doesn’t generate PDFs. Common approach: Thymeleaf → HTML → Flying Saucer / OpenPDF → PDF
Images (use absolute path or base64):
String html = templateEngine.process("invoice", context); Common approach: Thymeleaf → HTML → Flying Saucer
<img src="file:/absolute/path/logo.png" /> (register in ITextRenderer):
public PdfController(PdfService pdfService) this.pdfService = pdfService;
@GetMapping("/invoice/id/pdf") public ResponseEntity<byte[]> downloadInvoice(@PathVariable Long id) InvoiceDto invoice = invoiceService.findById(id); // your logic byte[] pdfBytes = pdfService.generateInvoicePdf(invoice);