SpringBoot生成PDF的五種實(shí)現(xiàn)方法總結(jié)
在Spring Boot應(yīng)用程序中生成PDF文件,可以通過(guò)以下幾種方式實(shí)現(xiàn):
一、使用PDFBox庫(kù)
PDFBox是一個(gè)開(kāi)源的Java庫(kù),用于處理PDF文檔。它支持創(chuàng)建、讀取和修改PDF文件。在Spring Boot應(yīng)用程序中,可以通過(guò)PDFBox庫(kù)來(lái)生成PDF文件。具體實(shí)現(xiàn)包括創(chuàng)建一個(gè)PDDocument對(duì)象,添加頁(yè)面,設(shè)置頁(yè)面內(nèi)容流,設(shè)置字體和大小,顯示文本,最后保存并關(guān)閉文檔。
1、添加依賴
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>
2、使用PDFBox API來(lái)創(chuàng)建讀取編輯PDF文件
以下是一個(gè)簡(jiǎn)單的例子,展示如何使用PDFBox創(chuàng)建一個(gè)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)建一個(gè)PDF文檔
PDDocument document = new PDDocument();
// 創(chuàng)建一頁(yè)
PDPage page = new PDPage();
document.addPage(page);
// 創(chuàng)建一個(gè)內(nèi)容流
PDPageContentStream contentStream = new PDPageContentStream(document, page);
// 設(shè)置字體
contentStream.setFont(PDType1Font.HELVETICA_BOLD);
// 將文本添加到PDF頁(yè)面
contentStream.drawString("PDFBox! This is a PDF document.");
// 關(guān)閉內(nèi)容流
contentStream.close();
// 保存文檔
document.save("PDFBox.pdf");
// 關(guān)閉文檔
document.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}二、使用ReportLab庫(kù)
ReportLab是一個(gè)開(kāi)源的PDF生成庫(kù),支持多種編程語(yǔ)言,包括Java和Python。在Spring Boot應(yīng)用程序中,可以通過(guò)集成ReportLab庫(kù)來(lái)實(shí)現(xiàn)PDF的生成。這需要在項(xiàng)目的pom.xml文件中添加ReportLab依賴。
1、添加依賴
<dependency>
<groupId>com.reportlab</groupId>
<artifactId>reportlab</artifactId>
<version>4.5.3</version>
</dependency>
2、創(chuàng)建一個(gè)服務(wù)來(lái)生成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、在一個(gè)控制器中調(diào)用服務(wù)生成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庫(kù)
iText是一個(gè)流行的PDF處理庫(kù),支持創(chuàng)建、編輯和提取PDF文件的內(nèi)容。在Spring Boot中,可以通過(guò)集成iText庫(kù)來(lái)生成PDF文件。這需要在pom.xml文件中添加iText依賴,并編寫(xiě)代碼來(lái)生成PDF文件,例如創(chuàng)建一個(gè)Document對(duì)象,添加內(nèi)容,然后保存為PDF文件。
1、添加依賴
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.9</version>
</dependency>
2、創(chuàng)建一個(gè)服務(wù)來(lái)生成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)建一個(gè)控制器來(lái)調(diào)用服務(wù)生成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";
}
}
}四、使用動(dòng)態(tài)HTML轉(zhuǎn)換
先創(chuàng)建一個(gè)動(dòng)態(tài)HTML文件,然后使用HTML轉(zhuǎn)PDF的工具或庫(kù)將其轉(zhuǎn)換為PDF。這種方法適用于需要從HTML內(nèi)容生成PDF的情況。可以在Spring Boot應(yīng)用程序中實(shí)現(xiàn)這種轉(zhuǎn)換,例如通過(guò)將HTML內(nèi)容保存為文件,然后使用外部工具或庫(kù)將其轉(zhuǎn)換為PDF。
在Spring Boot中,可以使用OpenPDF庫(kù)(一個(gè)開(kāi)源的iText分支)來(lái)動(dòng)態(tài)生成PDF文件。
1、添加依賴
<dependency>
<groupId>com.openhtmltopdf</groupId>
<artifactId>openhtmltopdf-core</artifactId>
<version>1.0.10</version>
</dependency>
2、創(chuàng)建一個(gè)服務(wù)來(lái)生成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)建一個(gè)控制器來(lái)提供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ù)模板動(dòng)態(tài)生成
這種方法適用于需要根據(jù)特定模板生成PDF的情況。通過(guò)集成itextpdf庫(kù),可以根據(jù)合同模板動(dòng)態(tài)生成包含合同標(biāo)簽、合同方以及簽約時(shí)間等信息的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)建一個(gè) PDF 文檔并添加一些內(nèi)容:
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、調(diào)用createPdf方法
在你的 Spring Boot 應(yīng)用中,你可以在任何需要的地方調(diào)用 createPdf 方法來(lái)創(chuàng)建 PDF 文檔。
到此這篇關(guān)于SpringBoot生成PDF實(shí)現(xiàn)方法總結(jié)的文章就介紹到這了,更多相關(guān)SpringBoot生成PDF內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java通過(guò)snmp協(xié)議獲取物理設(shè)備信息
這篇文章主要介紹了java通過(guò)snmp協(xié)議獲取物理設(shè)備信息,snmp中文含義是簡(jiǎn)單網(wǎng)絡(luò)管理協(xié)議,可用完成對(duì)計(jì)算機(jī)、路由器和其他網(wǎng)絡(luò)設(shè)備的遠(yuǎn)程管理和監(jiān)視,本文我們是通過(guò)java程序來(lái)獲取,需要的朋友可以參考下2023-07-07
SpringBoot如何導(dǎo)出Jar包并測(cè)試(使用IDEA)
這篇文章主要介紹了SpringBoot如何導(dǎo)出Jar包并測(cè)試(使用IDEA),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07
Spring JdbcTemplate實(shí)現(xiàn)添加與查詢方法詳解
JdbcTemplate是Spring框架自帶的對(duì)JDBC操作的封裝,目的是提供統(tǒng)一的模板方法使對(duì)數(shù)據(jù)庫(kù)的操作更加方便、友好,效率也不錯(cuò),這篇文章主要介紹了Spring?JdbcTemplate執(zhí)行數(shù)據(jù)庫(kù)操作,需要的朋友可以參考下2022-11-11
SpringBoot實(shí)現(xiàn)項(xiàng)目文件上傳的方法詳解
這篇文章主要為大家詳細(xì)介紹了SpringBoot中實(shí)現(xiàn)項(xiàng)目文件上傳的相關(guān)資料,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的小伙伴可以了解一下2022-11-11
Java導(dǎo)出網(wǎng)頁(yè)表格Excel過(guò)程詳解
這篇文章主要介紹了Java導(dǎo)出網(wǎng)頁(yè)表格Excel過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
MyBatis通用Mapper實(shí)現(xiàn)原理及相關(guān)內(nèi)容
今天小編就為大家分享一篇關(guān)于MyBatis通用Mapper實(shí)現(xiàn)原理及相關(guān)內(nèi)容,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-12-12
hibernate-validator如何使用校驗(yàn)框架
高效、合理的使用hibernate-validator校驗(yàn)框架可以提高程序的可讀性,以及減少不必要的代碼邏輯,本文主要介紹了hibernate-validator如何使用校驗(yàn)框架,感興趣的可以了解一下2022-04-04

