如何用Java將數據庫的數據生成pdf返回給前端用戶下載
本篇文章演示了一個從數據庫中選取最近十條記錄,并將它們轉換成PDF格式供前端下載的完整后端處理流程。
注釋很詳細,望周知??
所需要的工具:
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庫用于實現生成PDF文件、處理HTTP請求和響應,以及操作數據集的操作。
com.itextpdf.text.Document: 用于創(chuàng)建一個PDF文檔的模型。它代表了一個PDF文檔,并提供了添加元素(如段落、表格等)到文檔中的方法。
com.itextpdf.text.Paragraph: 包含字符串、短語和其他可以逐個添加到Document對象中的PDF元素。
com.itextpdf.text.pdf.PdfWriter: iText庫的核心類,用于將Document對象(即PDF文檔)寫入到你的文件系統(tǒng)、網絡或內存。它的實例化是通過調用靜態(tài)方法getInstance,并連接到一個特定的Document對象完成的。
*/
@RestController
public class PdfDownloadController {
// 假設這是用來獲取數據庫最近十條數據的服務
private final DataService dataService;
public PdfDownloadController(DataService dataService) {
this.dataService = dataService;
}
@GetMapping("/download-pdf")
public void downloadPdf(HttpServletResponse response) {
try {
// 查詢數據庫最近十條記錄
List<Data> dataList = dataService.getTopTenData();
// 創(chuàng)建PDF
ByteArrayOutputStream out = new ByteArrayOutputStream();
Document document = new Document();
PdfWriter.getInstance(document, out);
document.open();
// 將每條數據加入PDF
for (Data data : dataList) {
document.add(new Paragraph(data.toString())); // 假設toString()方法返回數據的有用表示
}
document.close();
// 設置HTTP響應頭
response.setContentType("application/pdf"); // 設置HTTP響應的內容類型為PDF
/**
例如你想發(fā)送其他類型的數據也可以設置:
發(fā)送HTML內容: response.setContentType("text/html");
發(fā)送純文本: response.setContentType("text/plain");
發(fā)送JPEG圖片: response.setContentType("image/jpeg");
發(fā)送JSON數據: response.setContentType("application/json");
*/
response.setHeader("Content-Disposition", "attachment; filename=\"data.pdf\""); // 設置HTTP響應的頭信息,告訴瀏覽器這是一個附件,建議保存的文件名為"data.pdf"
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
org.apache.commons.io.IOUtils.copy(in, response.getOutputStream());
// 上面一行利用Apache Commons IO庫的IOUtils類的copy方法,
// 將PDF文件的內容(現在存儲在ByteArrayInputStream 'in')復制到HTTP響應的輸出流中
// 這使得PDF的內容能夠被發(fā)送到請求該服務的客戶端
response.flushBuffer(); // 刷新響應的緩沖區(qū),完成響應的發(fā)送
} catch (Exception e) {
e.printStackTrace();
// 錯誤處理
}
}
}
? 后半部分代碼的目的是在服務器端動態(tài)生成一個PDF文件,并通過HTTP響應將其發(fā)送給客戶端供下載。通過設置Content-Disposition為attachment,告訴瀏覽器這個文件應該被當做下載處理,而不是直接在瀏覽器中打開,filename=\"data.pdf\"則建議瀏覽器將文件保存為"data.pdf"。利用Apache Commons IO庫簡化了二進制數據傳輸的代碼編寫。最后,使用response.flushBuffer()確保所有數據都被發(fā)送給客戶端。
? 上述代碼因為使用到了iText庫和Apache Commons IO庫的一部分,所以需要在Maven或Gradle項目的pom.xml文件中添加依賴,這里展示一下Maven添加依賴項的過程:
<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>
數據模型(Data.java)
首先,定義一個簡單的數據模型:
假設這里有一個Data實體類,它代表了數據庫中的表。
這個表僅包含兩個字段:ID(主鍵)和Name,大家可以自行增減字段。
public class Data {
private Integer id;
private String name;
// 構造函數、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條數據
List<Data> selectTopTenData();
}
MyBatis Mapper XML文件(DataMapper.xml)
接下來是對應的MyBatis Mapper XML配置。
大家可以這個文件與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層,我們調用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();
}
}
? 本篇文章演示了一個從數據庫中選取最近十條記錄,并將它們轉換成PDF格式供前端下載的完整后端處理流程。在現實的應用中,大家需要根據自己的業(yè)務需求和實際的數據庫表結構進行適當的調整。

此圖是我應用于<訪問記錄數據庫>的pdf導出效果,列舉了最新幾天的訪問次數。
總結
到此這篇關于如何用Java將數據庫的數據生成pdf返回給前端用戶下載的文章就介紹到這了,更多相關Java數據生成pdf返回給前端下載內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
IntelliJ IDEA運行bat腳本,自動taskkill端口進程
這篇文章主要介紹了IDEA里面無法運行bat文件的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11

