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依賴,并編寫代碼來(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實(shí)現(xiàn)簡(jiǎn)單的銀行管理系統(tǒng)
這篇文章主要介紹了基于java實(shí)現(xiàn)簡(jiǎn)單的銀行管理系統(tǒng),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01
java基于QuartzJobBean實(shí)現(xiàn)定時(shí)功能的示例代碼
QuartzJobBean是Quartz框架中的一個(gè)抽象類,用于定義和實(shí)現(xiàn)可由Quartz調(diào)度的作業(yè),本文主要介紹了java基于QuartzJobBean實(shí)現(xiàn)定時(shí)功能的示例代碼,具有一定的參考價(jià)值,感興趣可以了解一下2023-09-09
idea使用easyCode生成代碼(根據(jù)mybatis-plus模板創(chuàng)建自己的模板)
本文主要介紹了idea使用easyCode生成代碼,easyCode代碼生成器可以減少低價(jià)值搬磚,具有一定的參考價(jià)值,感興趣的可以了解一下2023-10-10
mybatis,foreach,找不到參數(shù)報(bào)錯(cuò)問(wèn)題及解決
這篇文章主要介紹了mybatis,foreach,找不到參數(shù)報(bào)錯(cuò)問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03
Spring Boot搭配MinIO和KKFileView實(shí)現(xiàn)文件存儲(chǔ)和在線預(yù)覽
在現(xiàn)代的Web應(yīng)用中,文件上傳和預(yù)覽是常見(jiàn)的需求場(chǎng)景,尤其是在內(nèi)容管理系統(tǒng)(CMS)或企業(yè)內(nèi)部應(yīng)用,本文介紹了如何使用SpringBoot、MinIO和KKFileView實(shí)現(xiàn)文件上傳和在線預(yù)覽功能,包括項(xiàng)目背景、技術(shù)選型、環(huán)境準(zhǔn)備、項(xiàng)目代碼實(shí)現(xiàn)和運(yùn)行測(cè)試等步驟2024-12-12

