1. Project dependency
To implement PDF export function, you first need to add the following dependencies to the project:
<dependencies> <!-- ThymeleafTemplate Engine --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- Flying Saucer for PDF generation --> <dependency> <groupId></groupId> <artifactId>flying-saucer-pdf</artifactId> <version>9.1.22</version> </dependency> <!-- iTextPDF ( Version,For compatibility Flying Saucer) --> <dependency> <groupId></groupId> <artifactId>itext</artifactId> <version>2.1.7</version> </dependency> </dependencies>
Note: Flying Saucer uses the old iText library, not the new one, make sure to use the correct version to avoid dependency conflicts.
2. Create Thymeleaf template
Create a new HTML template to generate invoice content, for example, write the following HTML in the resources/templates/pdf/ file:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>bill</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } h1 { text-align: center; } table { width: 100%; border-collapse: collapse; margin-top: 20px; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } .total { font-weight: bold; } .footer { margin-top: 30px; text-align: center; font-size: 12px; color: #888; } </style> </head> <body> <h1>bill</h1> <p>bill编号:<span th:text="${invoiceNumber}"></span></p> <p>Issuance date:<span th:text="${invoiceDate}"></span></p> <p>Buyer's name:<span th:text="${buyerName}"></span></p> <h2>Product details</h2> <table> <thead> <tr> <th>Product Name</th> <th>describe</th> <th>quantity</th> <th>unit price</th> <th>Subtotal</th> </tr> </thead> <tbody> <tr th:each="item : ${goodsItems}"> <td th:text="${}"></td> <td th:text="${}"></td> <td th:text="${}"></td> <td th:text="${}"></td> <td th:text="${}"></td> </tr> </tbody> </table> <p class="total">lump sum:<span th:text="${finalAmount}"></span></p> <div class="footer">Thank you for your purchase!</div> </body> </html>
3. Create PDF generation tool class
Next, createPdfUtil
Tool class, render HTML through Thymeleaf and convert HTML to PDF using Flying Saucer:
package ; import ; import ; import ; import ; import ; import ; import ; public class PdfUtil { public static byte[] generateInvoicePdf(String buyerName, String invoiceNumber, List<GoodsInvoice> goodsItems, String finalAmount) { TemplateEngine templateEngine = new TemplateEngine(); // Render HTML with Thymeleaf Context context = new Context(); ("buyerName", buyerName); ("invoiceNumber", invoiceNumber); ("goodsItems", goodsItems); ("finalAmount", finalAmount); String htmlContent = ("pdf/", context); // Convert HTML to PDF try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { ITextRenderer renderer = new ITextRenderer(); ().addFont("/path/to/your/font/", true); // Prevent Chinese garbled (htmlContent); (); (outputStream); return (); } catch (Exception e) { (); throw new BusinessException("Invoice PDF generation failed"); } } }
4. Use PDF generation function in Spring Boot
Called in Spring Boot controller, return the generated PDF to the user or send an email as an attachment:
@RestController @RequestMapping("/invoice") public class InvoiceController { @GetMapping("/generate") public ResponseEntity<byte[]> generateInvoice() { byte[] pdfBytes = ("Zhang San", "INV-12345", goodsItems, "1000.00"); HttpHeaders headers = new HttpHeaders(); (MediaType.APPLICATION_PDF); ("attachment", ""); return new ResponseEntity<>(pdfBytes, headers, ); } }
5. Common errors and solutions
1. Chinese characters garbled
- question: In the generated PDF, Chinese characters may appear garbled.
-
Solution:make sure
addFont
Quoting Chinese-supported font files (such as)。
2. Image loading failed
question: Images in HTML cannot be displayed normally in PDF.
Solution: Set the image path to an absolute path or pass
setBaseURL
Specify the resource root path:
().setBaseURL("file:/path/to/resources/");
3. The style does not take effect
- question: Flying Saucer does not support advanced CSS.
-
Solution: Use basic
table
Layout and simple CSS, do not rely on flex, CSS variables, etc.
4. Template path recognition error
- question: The template engine cannot find the specified HTML file.
-
Solution: Check the file path and template configuration to ensure that the template is placed in
resources/templates/pdf
In the directory.
5. Dependency conflict
- question: Flying Saucer uses old iText and conflicts with other dependencies.
-
Solution: Independent module management dependencies, use
maven-shade-plugin
Handle conflict classes.
6. Insufficient memory
- question: Memory overflow occurs when generating large PDFs.
- Solution: Increase JVM memory configuration, or simplify HTML structure and reduce memory usage.
Summarize
Using Spring Boot to integrate Thymeleaf and Flying Saucer to implement PDF export is an efficient way to generate invoices, reports and other documents. With the above implementation steps and FAQ solutions, I hope it can help you integrate this feature smoothly in your project.
The above is the detailed content of using SpringBoot to integrate Thymeleaf and Flying Saucer to achieve PDF export. For more information about SpringBoot implement PDF export, please pay attention to my other related articles!