SpringBoot生成PDF的五種實現(xiàn)方法總結
在Spring Boot應用程序中生成PDF文件,可以通過以下幾種方式實現(xiàn):
一、使用PDFBox庫
PDFBox是一個開源的Java庫,用于處理PDF文檔。它支持創(chuàng)建、讀取和修改PDF文件。在Spring Boot應用程序中,可以通過PDFBox庫來生成PDF文件。具體實現(xiàn)包括創(chuàng)建一個PDDocument對象,添加頁面,設置頁面內容流,設置字體和大小,顯示文本,最后保存并關閉文檔。
1、添加依賴
<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.24</version> </dependency>
2、使用PDFBox API來創(chuàng)建讀取編輯PDF文件
以下是一個簡單的例子,展示如何使用PDFBox創(chuàng)建一個PDF文件并添加一些文本:
import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.font.PDType1Font; import java.io.IOException; public class PDFBoxExample { public static void main(String[] args) { try { // 創(chuàng)建一個PDF文檔 PDDocument document = new PDDocument(); // 創(chuàng)建一頁 PDPage page = new PDPage(); document.addPage(page); // 創(chuàng)建一個內容流 PDPageContentStream contentStream = new PDPageContentStream(document, page); // 設置字體 contentStream.setFont(PDType1Font.HELVETICA_BOLD); // 將文本添加到PDF頁面 contentStream.drawString("PDFBox! This is a PDF document."); // 關閉內容流 contentStream.close(); // 保存文檔 document.save("PDFBox.pdf"); // 關閉文檔 document.close(); } catch (IOException e) { e.printStackTrace(); } } }
二、使用ReportLab庫
ReportLab是一個開源的PDF生成庫,支持多種編程語言,包括Java和Python。在Spring Boot應用程序中,可以通過集成ReportLab庫來實現(xiàn)PDF的生成。這需要在項目的pom.xml文件中添加ReportLab依賴。
1、添加依賴
<dependency> <groupId>com.reportlab</groupId> <artifactId>reportlab</artifactId> <version>4.5.3</version> </dependency>
2、創(chuàng)建一個服務來生成PDF
import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Paragraph; import com.lowagie.text.pdf.PdfWriter; import org.springframework.stereotype.Service; import java.io.FileNotFoundException; import java.io.FileOutputStream; @Service public class PdfGenerationService { public void generatePdf(String filePath) throws DocumentException, FileNotFoundException { Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(filePath)); document.open(); document.add(new Paragraph("Hello, ReportLab!")); document.close(); } }
3、在一個控制器中調用服務生成PDF
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.io.FileNotFoundException; import java.io.IOException; @RestController public class PdfController { @Autowired private PdfGenerationService pdfGenerationService; @GetMapping("/generatePdf") public String generatePdf() { try { pdfGenerationService.generatePdf("output.pdf"); return "PDF generated successfully"; } catch (FileNotFoundException | DocumentException e) { e.printStackTrace(); return "Error generating PDF"; } } }
三、使用iText庫
iText是一個流行的PDF處理庫,支持創(chuàng)建、編輯和提取PDF文件的內容。在Spring Boot中,可以通過集成iText庫來生成PDF文件。這需要在pom.xml文件中添加iText依賴,并編寫代碼來生成PDF文件,例如創(chuàng)建一個Document對象,添加內容,然后保存為PDF文件。
1、添加依賴
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itext7-core</artifactId> <version>7.1.9</version> </dependency>
2、創(chuàng)建一個服務來生成PDF
import com.itextpdf.kernel.pdf.*; import com.itextpdf.layout.*; import com.itextpdf.layout.element.Paragraph; import org.springframework.stereotype.Service; import java.io.IOException; @Service public class PdfService { public void generatePdf(String dest) throws IOException { // Initialize PDF writer PdfWriter writer = new PdfWriter(dest); // Initialize PDF document PdfDocument pdf = new PdfDocument(writer); // Initialize document Document document = new Document(pdf); // Add content document.add(new Paragraph("Hello, Spring Boot and iText7!")); // Close document document.close(); System.out.println("PDF created successfully!"); } }
3、創(chuàng)建一個控制器來調用服務生成PDF
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; @RestController public class PdfController { @Autowired private PdfService pdfService; @GetMapping("/generatePdf") public String generatePdf() { try { pdfService.generatePdf("target/test.pdf"); return "PDF generated"; } catch (IOException e) { e.printStackTrace(); return "Error generating PDF"; } } }
四、使用動態(tài)HTML轉換
先創(chuàng)建一個動態(tài)HTML文件,然后使用HTML轉PDF的工具或庫將其轉換為PDF。這種方法適用于需要從HTML內容生成PDF的情況。可以在Spring Boot應用程序中實現(xiàn)這種轉換,例如通過將HTML內容保存為文件,然后使用外部工具或庫將其轉換為PDF。
在Spring Boot中,可以使用OpenPDF庫(一個開源的iText分支)來動態(tài)生成PDF文件。
1、添加依賴
<dependency> <groupId>com.openhtmltopdf</groupId> <artifactId>openhtmltopdf-core</artifactId> <version>1.0.10</version> </dependency>
2、創(chuàng)建一個服務來生成PDF
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; @Service public class PdfService { public byte[] generatePdfFromHtml(String htmlContent) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PdfRendererBuilder builder = new PdfRendererBuilder(); builder.useFastMode(); builder.withHtmlContent(htmlContent, null); builder.toStream(outputStream); builder.run(); return outputStream.toByteArray(); } }
3、創(chuàng)建一個控制器來提供PDF文件的下載
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.io.IOException; @Controller @RequestMapping("/pdf") public class PdfController { @Autowired private PdfService pdfService; @GetMapping public ResponseEntity<byte[]> generatePdf() throws IOException { String htmlContent = "<html><body><h1>Hello, World!</h1></body></html>"; byte[] pdfBytes = pdfService.generatePdfFromHtml(htmlContent); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_PDF); headers.set("Content-Disposition", "attachment; filename=example.pdf"); return new ResponseEntity<>(pdfBytes, headers, org.springframework.http.HttpStatus.CREATED); } }
五、使用itextpdf根據(jù)模板動態(tài)生成
這種方法適用于需要根據(jù)特定模板生成PDF的情況。通過集成itextpdf庫,可以根據(jù)合同模板動態(tài)生成包含合同標簽、合同方以及簽約時間等信息的PDF文件。
1、添加依賴
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itext7-core</artifactId> <version>7.1.9</version> <type>pom</type> </dependency>
2、創(chuàng)建PDF文檔
創(chuàng)建一個 PDF 文檔并添加一些內容:
import com.itextpdf.kernel.pdf.*; import com.itextpdf.layout.*; import com.itextpdf.layout.element.Paragraph; public void createPdf(String dest) throws Exception { //Initialize PDF writer PdfWriter writer = new PdfWriter(dest); //Initialize PDF document PdfDocument pdf = new PdfDocument(writer); //Initialize document Document document = new Document(pdf); //Add paragraph to the document document.add(new Paragraph("Hello, World!")); //Close document document.close(); System.out.println("PDF Created"); }
3、調用createPdf方法
在你的 Spring Boot 應用中,你可以在任何需要的地方調用 createPdf 方法來創(chuàng)建 PDF 文檔。
到此這篇關于SpringBoot生成PDF實現(xiàn)方法總結的文章就介紹到這了,更多相關SpringBoot生成PDF內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
java基于QuartzJobBean實現(xiàn)定時功能的示例代碼
QuartzJobBean是Quartz框架中的一個抽象類,用于定義和實現(xiàn)可由Quartz調度的作業(yè),本文主要介紹了java基于QuartzJobBean實現(xiàn)定時功能的示例代碼,具有一定的參考價值,感興趣可以了解一下2023-09-09idea使用easyCode生成代碼(根據(jù)mybatis-plus模板創(chuàng)建自己的模板)
本文主要介紹了idea使用easyCode生成代碼,easyCode代碼生成器可以減少低價值搬磚,具有一定的參考價值,感興趣的可以了解一下2023-10-10mybatis,foreach,找不到參數(shù)報錯問題及解決
這篇文章主要介紹了mybatis,foreach,找不到參數(shù)報錯問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03Spring Boot搭配MinIO和KKFileView實現(xiàn)文件存儲和在線預覽
在現(xiàn)代的Web應用中,文件上傳和預覽是常見的需求場景,尤其是在內容管理系統(tǒng)(CMS)或企業(yè)內部應用,本文介紹了如何使用SpringBoot、MinIO和KKFileView實現(xiàn)文件上傳和在線預覽功能,包括項目背景、技術選型、環(huán)境準備、項目代碼實現(xiàn)和運行測試等步驟2024-12-12