如何用Java將數(shù)據(jù)庫的數(shù)據(jù)生成pdf返回給前端用戶下載
本篇文章演示了一個(gè)從數(shù)據(jù)庫中選取最近十條記錄,并將它們轉(zhuǎn)換成PDF格式供前端下載的完整后端處理流程。
注釋很詳細(xì),望周知??
所需要的工具:
iText庫 SpringBoot框架 MyBatis
Controller層(PdfDownloadController.java)
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
/**
這些Java庫用于實(shí)現(xiàn)生成PDF文件、處理HTTP請求和響應(yīng),以及操作數(shù)據(jù)集的操作。
com.itextpdf.text.Document: 用于創(chuàng)建一個(gè)PDF文檔的模型。它代表了一個(gè)PDF文檔,并提供了添加元素(如段落、表格等)到文檔中的方法。
com.itextpdf.text.Paragraph: 包含字符串、短語和其他可以逐個(gè)添加到Document對象中的PDF元素。
com.itextpdf.text.pdf.PdfWriter: iText庫的核心類,用于將Document對象(即PDF文檔)寫入到你的文件系統(tǒng)、網(wǎng)絡(luò)或內(nèi)存。它的實(shí)例化是通過調(diào)用靜態(tài)方法getInstance,并連接到一個(gè)特定的Document對象完成的。
*/
@RestController
public class PdfDownloadController {
// 假設(shè)這是用來獲取數(shù)據(jù)庫最近十條數(shù)據(jù)的服務(wù)
private final DataService dataService;
public PdfDownloadController(DataService dataService) {
this.dataService = dataService;
}
@GetMapping("/download-pdf")
public void downloadPdf(HttpServletResponse response) {
try {
// 查詢數(shù)據(jù)庫最近十條記錄
List<Data> dataList = dataService.getTopTenData();
// 創(chuàng)建PDF
ByteArrayOutputStream out = new ByteArrayOutputStream();
Document document = new Document();
PdfWriter.getInstance(document, out);
document.open();
// 將每條數(shù)據(jù)加入PDF
for (Data data : dataList) {
document.add(new Paragraph(data.toString())); // 假設(shè)toString()方法返回?cái)?shù)據(jù)的有用表示
}
document.close();
// 設(shè)置HTTP響應(yīng)頭
response.setContentType("application/pdf"); // 設(shè)置HTTP響應(yīng)的內(nèi)容類型為PDF
/**
例如你想發(fā)送其他類型的數(shù)據(jù)也可以設(shè)置:
發(fā)送HTML內(nèi)容: response.setContentType("text/html");
發(fā)送純文本: response.setContentType("text/plain");
發(fā)送JPEG圖片: response.setContentType("image/jpeg");
發(fā)送JSON數(shù)據(jù): response.setContentType("application/json");
*/
response.setHeader("Content-Disposition", "attachment; filename=\"data.pdf\""); // 設(shè)置HTTP響應(yīng)的頭信息,告訴瀏覽器這是一個(gè)附件,建議保存的文件名為"data.pdf"
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
org.apache.commons.io.IOUtils.copy(in, response.getOutputStream());
// 上面一行利用Apache Commons IO庫的IOUtils類的copy方法,
// 將PDF文件的內(nèi)容(現(xiàn)在存儲在ByteArrayInputStream 'in')復(fù)制到HTTP響應(yīng)的輸出流中
// 這使得PDF的內(nèi)容能夠被發(fā)送到請求該服務(wù)的客戶端
response.flushBuffer(); // 刷新響應(yīng)的緩沖區(qū),完成響應(yīng)的發(fā)送
} catch (Exception e) {
e.printStackTrace();
// 錯(cuò)誤處理
}
}
}
? 后半部分代碼的目的是在服務(wù)器端動(dòng)態(tài)生成一個(gè)PDF文件,并通過HTTP響應(yīng)將其發(fā)送給客戶端供下載。通過設(shè)置Content-Disposition為attachment,告訴瀏覽器這個(gè)文件應(yīng)該被當(dāng)做下載處理,而不是直接在瀏覽器中打開,filename=\"data.pdf\"則建議瀏覽器將文件保存為"data.pdf"。利用Apache Commons IO庫簡化了二進(jìn)制數(shù)據(jù)傳輸?shù)拇a編寫。最后,使用response.flushBuffer()確保所有數(shù)據(jù)都被發(fā)送給客戶端。
? 上述代碼因?yàn)槭褂玫搅薸Text庫和Apache Commons IO庫的一部分,所以需要在Maven或Gradle項(xiàng)目的pom.xml文件中添加依賴,這里展示一下Maven添加依賴項(xiàng)的過程:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
數(shù)據(jù)模型(Data.java)
首先,定義一個(gè)簡單的數(shù)據(jù)模型:
假設(shè)這里有一個(gè)Data實(shí)體類,它代表了數(shù)據(jù)庫中的表。
這個(gè)表僅包含兩個(gè)字段:ID(主鍵)和Name,大家可以自行增減字段。
public class Data {
private Integer id;
private String name;
// 構(gòu)造函數(shù)、getter和setter省略
// 大家可以用alt + ins快捷鍵快速生成
@Override
public String toString() {
return "Data{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
Mapper接口(DataMapper.java)
然后,定義MyBatis的Mapper接口:
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface DataMapper {
@Select("SELECT * FROM data_table ORDER BY id DESC LIMIT 10") // 倒序選擇10條數(shù)據(jù)
List<Data> selectTopTenData();
}
MyBatis Mapper XML文件(DataMapper.xml)
接下來是對應(yīng)的MyBatis Mapper XML配置。
大家可以這個(gè)文件與DataMapper接口放置在相同的路徑下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.DataMapper">
<select id="selectTopTenData" resultType="com.example.demo.model.Data">
SELECT * FROM data_table ORDER BY id DESC LIMIT 10
</select>
</mapper>
Service層(DataService.java)
在Service層,我們調(diào)用Mapper接口中定義的方法:
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DataService {
private final DataMapper dataMapper;
public DataService(DataMapper dataMapper) {
this.dataMapper = dataMapper;
}
public List<Data> getTopTenData() {
return dataMapper.selectTopTenData();
}
}
? 本篇文章演示了一個(gè)從數(shù)據(jù)庫中選取最近十條記錄,并將它們轉(zhuǎn)換成PDF格式供前端下載的完整后端處理流程。在現(xiàn)實(shí)的應(yīng)用中,大家需要根據(jù)自己的業(yè)務(wù)需求和實(shí)際的數(shù)據(jù)庫表結(jié)構(gòu)進(jìn)行適當(dāng)?shù)恼{(diào)整。

此圖是我應(yīng)用于<訪問記錄數(shù)據(jù)庫>的pdf導(dǎo)出效果,列舉了最新幾天的訪問次數(shù)。
總結(jié)
到此這篇關(guān)于如何用Java將數(shù)據(jù)庫的數(shù)據(jù)生成pdf返回給前端用戶下載的文章就介紹到這了,更多相關(guān)Java數(shù)據(jù)生成pdf返回給前端下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
IDEA 啟動(dòng) Tomcat 項(xiàng)目輸出亂碼的解決方法
這篇文章主要介紹了IDEA 啟動(dòng) Tomcat 項(xiàng)目輸出亂碼的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
SpringBoot生成License的實(shí)現(xiàn)示例
License指的是版權(quán)許可證,那么對于SpringBoot項(xiàng)目,如何增加License呢?本文就來介紹一下,感興趣的可以了解一下2021-06-06
Spring security如何實(shí)現(xiàn)記錄用戶登錄時(shí)間功能
這篇文章主要介紹了Spring security如何實(shí)現(xiàn)記錄用戶登錄時(shí)間功能,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03
IntelliJ IDEA運(yùn)行bat腳本,自動(dòng)taskkill端口進(jìn)程
這篇文章主要介紹了IDEA里面無法運(yùn)行bat文件的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11

