将生成的PDF文件直接导出到浏览器而不是保存到本地,需要对HttpServletResponse
进行配置,将PDF写入到响应流中。
以下是可以将PDF导出到浏览器进行下载:
1、先导入pom依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.11</version>
</dependency>
<!-- 中文问题解决 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
2、编写PDF工具类
package com.scenic.util;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.IOException;
public class PdfFUtil {
// 最大宽度
private static int maxWidth = 720;
/**------------------------创建表格单元格的方法start----------------------------*/
/**
* 创建单元格(指定字体)
*
* @param value
* @param font
* @return
*/
public static PdfPCell createCell(String value, Font font) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 创建单元格(指定字体、设置单元格高度)
*
* @param value
* @param font
* @return 申请事由——这行使用的方法
*/
public static PdfPCell createCell(String value, Font font, float f) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPhrase(new Phrase(value, font));
cell.setFixedHeight(f); // 设置表格中的单行高度
return cell;
}
/**
* 创建单元格(指定字体、水平局左/中/右)
*
* @param value
* @param font
* @param align
* @return
*/
public static PdfPCell createCell(String value, Font font, int align) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
cell.setHorizontalAlignment(align); //水平居中
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 创建单元格(指定字体、水平局左/中/右、单元格跨x列合并)
*
* @param value
* @param font
* @param align
* @param colspan
* @return
*/
public PdfPCell createCell(String value, Font font, int align, int colspan) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
cell.setHorizontalAlignment(align); //水平居中
cell.setColspan(colspan);
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 创建单元格(指定字体、水平居..、单元格跨x列合并、设置单元格内边距)
*
* @param value
* @param font
* @param align
* @param colspan
* @param boderFlag
* @return
*/
public static PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setColspan(colspan);
cell.setPhrase(new Phrase(value, font));
cell.setPadding(3.0f);
if (!boderFlag) {
cell.setBorder(0);
cell.setPaddingTop(10.0f);
cell.setPaddingBottom(7.0f);
} else if (boderFlag) {
cell.setBorder(0);
cell.setPaddingTop(0.0f);
cell.setPaddingBottom(15.0f);
}
return cell;
}
/**
* 创建单元格(指定字体、水平..、边框宽度:0表示无边框、内边距)
*
* @param value
* @param font
* @param align
* @param borderWidth
* @param paddingSize
* @param flag
* @return
*/
public static PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setPhrase(new Phrase(value, font));
cell.setBorderWidthLeft(borderWidth[0]);
cell.setBorderWidthRight(borderWidth[1]);
cell.setBorderWidthTop(borderWidth[2]);
cell.setBorderWidthBottom(borderWidth[3]);
cell.setPaddingTop(paddingSize[0]);
cell.setPaddingBottom(paddingSize[1]);
if (flag) {
cell.setColspan(2);
}
return cell;
}
/**------------------------创建表格单元格的方法end----------------------------*/
/**--------------------------创建表格的方法start----------------------------*/
/**
* 创建默认列宽,指定列数、水平(居中、右、左)的表格
*
* @param colNumber
* @param align
* @return
*/
public PdfPTable createTable(int colNumber, int align) {
PdfPTable table = new PdfPTable(colNumber);
try {
table.setTotalWidth(maxWidth);
table.setLockedWidth(true);
table.setHorizontalAlignment(align);
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
/**
* 创建指定列宽、列数的表格
*
* @param widths
* @return
*/
public static PdfPTable createTable(float[] widths) {
PdfPTable table = new PdfPTable(widths);
try {
table.setTotalWidth(maxWidth);
table.setLockedWidth(true);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
/**
* 创建空白的表格
*
* @return
*/
public PdfPTable createBlankTable() throws IOException, DocumentException {
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font keyfont = new Font(bfChinese, 10, Font.BOLD);
PdfPTable table = new PdfPTable(1);
table.getDefaultCell().setBorder(0);
table.addCell(createCell("", keyfont));
table.setSpacingAfter(20.0f);
table.setSpacingBefore(20.0f);
return table;
}
/**--------------------------创建表格的方法end----------------------------*/
/**
* --------------------------页码方法start----------------------------
*/
public static void onEndPage(PdfWriter writer, Document document) throws IOException, DocumentException {
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tpl; // 页码模板用来固定显示数据
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
tpl = writer.getDirectContent().createTemplate(100, 100);
cb.saveState();
String text = "第" + writer.getPageNumber() + "页";
cb.beginText();
cb.setFontAndSize(bfChinese, 8);
cb.setTextMatrix(480, 35);//定位“第x页” 在具体的页面调试时候需要更改这xy的坐标
cb.showText(text);
cb.endText();
//** 创建以及固定显示总页数的位置
cb.addTemplate(tpl, 283, 10);//定位“y页” 在具体的页面调试时候需要更改这xy的坐标
cb.stroke();
cb.restoreState();
cb.closePath();
/**--------------------------页码方法end----------------------------*/
}
}
3、接着我们编写controller层进行实现代码
controller实现包
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.scenic.domain.dto.ActivityAdjust;
import com.scenic.domain.dto.ActivityDTO;
import com.scenic.domain.po.ActivityPO;
import com.scenic.domain.vo.ActivityVo;
import com.scenic.service.ActivityService;
import com.scenic.util.PdfFUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
编写业务代码进行导出PDF文件
/**
* 导出pdf格式文档
*
* @return
* @throws Exception
*/
@PostMapping("/pdf")
public void getUser(HttpServletResponse response) throws Exception {
// 自定义数据查询的方法
List<ActivityVo> list = activityService.searchActivityByConditions(new ActivityDTO());
// 获取当前时间戳
long currentTime = System.currentTimeMillis();
int total = list.size();
try {
// 1.新建Document对象,页面A4大小
Document document = new Document(PageSize.A4.rotate()); //建立一个Document对象
// 2.建立一个书写器(writer)与document对象关联
PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
// 3.打开文档
document.open();
// 设置响应头信息
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=user_" + currentTime + ".pdf");
// 静态文件路径
String img1 = "C:\\Users\\31966\\Pictures\\uwp4155700.jpeg";
// 获取静态图片资源
Image image = Image.getInstance(img1);
// 设置图片宽高
image.scaleToFit(500,300);
// 标题
Paragraph paragraph = new Paragraph("景区活动", titlefont_16);
paragraph.setAlignment(1); //设置文字居中,0靠左,1居中,2靠右
paragraph.setIndentationLeft(12); //设置左缩进
paragraph.setIndentationRight(12); //设置右缩进
paragraph.setFirstLineIndent(24); //设置首行缩进
paragraph.setLeading(20f); //设置行间距
paragraph.setSpacingBefore(5f); //设置段落上空白
paragraph.setSpacingAfter(10f); //设置段落下空白
document.add(paragraph); //标题
// 添加图片
document.add(image);
// 表格
PdfPTable table = PdfFUtil.createTable(new float[]{75, 110, 75, 140, 75,130,130});
// 新建单元格第一行
table.addCell(PdfFUtil.createCell("活动编号", textfont_10));
table.addCell(PdfFUtil.createCell("活动名称", textfont_10));
table.addCell(PdfFUtil.createCell("活动说明", textfont_10));
table.addCell(PdfFUtil.createCell("活动地址", textfont_10));
table.addCell(PdfFUtil.createCell("活动人员", textfont_10));
table.addCell(PdfFUtil.createCell("开始时间", textfont_10));
table.addCell(PdfFUtil.createCell("结束时间", textfont_10));
for (int i = 0; i < total; i++) {
table.addCell(PdfFUtil.createCell(String.valueOf(list.get(i).getId()), textfont_10));
table.addCell(PdfFUtil.createCell(list.get(i).getActivityName(), textfont_10));
table.addCell(PdfFUtil.createCell(String.valueOf(list.get(i).getActivityInstructions()), textfont_10));
table.addCell(PdfFUtil.createCell(String.valueOf(list.get(i).getActivityAddr()), textfont_10));
table.addCell(PdfFUtil.createCell(String.valueOf(list.get(i).getActivityPerson()), textfont_10));
table.addCell(PdfFUtil.createCell(converDate(list.get(i).getActivityStartTime()), textfont_10));
table.addCell(PdfFUtil.createCell(converDate(list.get(i).getActivityEndTime()), textfont_10));
}
document.add(table);
PdfFUtil.onEndPage(writer, document);
// 5.关闭文档
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 存储本地路径数据
* @param destination 本地路径
* @return
* @throws Exception
*/
@PostMapping("/pdf")
public List<User> getUser(@RequestParam("destination") String destination) throws Exception {
List<User> list=userService.selectAll();
long currentTime=System.currentTimeMillis();
int total=list.size();
try {
// 1.新建document对象
Document document = new Document(PageSize.A4.rotate()); //建立一个Document对象
// pdf文档存储的地址
String savePath=destination+"/"+"user_"+currentTime+".pdf";
// 2.建立一个书写器(writer)与document对象关联
File file = new File(savePath); //修改要生成pdf的位置路径
file.createNewFile();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// 3.打开文档
document.open();
// 标题
Paragraph paragraph = new Paragraph("用户表", titlefont_16);
paragraph.setAlignment(1); //设置文字居中,0靠左,1居中,2靠右
paragraph.setIndentationLeft(12); //设置左缩进
paragraph.setIndentationRight(12); //设置右缩进
paragraph.setFirstLineIndent(24); //设置首行缩进
paragraph.setLeading(20f); //设置行间距
paragraph.setSpacingBefore(5f); //设置段落上空白
paragraph.setSpacingAfter(10f); //设置段落下空白
document.add(paragraph); //标题
int pn = 1;
int ps = 34;
for (int j = 0; j < (total / ps) + 1; j++) {
PageUtil pageUtil1 = new PageUtil();
List<User> listPage=pageUtil1.pageUtil(list,pn,ps);
// 表格
PdfPTable table = PdfFUtil.createTable(new float[]{75, 110, 75, 140,75});
table.addCell(PdfFUtil.createCell("ID",textfont_10));
table.addCell(PdfFUtil.createCell("姓名",textfont_10));
table.addCell(PdfFUtil.createCell("年龄",textfont_10));
table.addCell(PdfFUtil.createCell("住址",textfont_10));
table.addCell(PdfFUtil.createCell("住址2",textfont_10));
for (int i = 0; i < listPage.size(); i++) {
table.addCell(PdfFUtil.createCell(String.valueOf(listPage.get(i).getId()), textfont_10));
table.addCell(PdfFUtil.createCell(listPage.get(i).getName(), textfont_10));
table.addCell(PdfFUtil.createCell(String.valueOf(listPage.get(i).getAge()), textfont_10));
table.addCell(PdfFUtil.createCell(String.valueOf(listPage.get(i).getAddr()), textfont_10));
table.addCell(PdfFUtil.createCell(String.valueOf(listPage.get(i).getAddr2()), textfont_10));
}
document.add(table);
PdfFUtil.onEndPage(writer, document);
pn++;
ps = 36;
}
// 5.关闭文档
document.close();
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 全局变量
*/
// 定义全局的字体静态变量
private static Font titlefont_16;
private static Font titlefontnormal_16;
private static Font headfont_14;
private static Font headfontnormal_14;
private static Font headfont_12;
private static Font headfontnormal_12;
private static Font keyfont_10;
private static Font textfont_10;
private static Font underlinefont_10;
// 静态代码块
static{
try{
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
titlefont_16=new Font(bfChinese,16,Font.BOLD);
headfont_14=new Font(bfChinese,14,Font.BOLD);
headfont_12=new Font(bfChinese,12,Font.BOLD);
keyfont_10=new Font(bfChinese,10,Font.BOLD);
titlefontnormal_16=new Font(bfChinese,16,Font.NORMAL);
headfontnormal_14=new Font(bfChinese,14,Font.NORMAL);
headfontnormal_12=new Font(bfChinese,12,Font.NORMAL);
textfont_10=new Font(bfChinese,10, Font.NORMAL);
underlinefont_10=new Font(bfChinese,10,Font.UNDERLINE);
}
catch (Exception e){
e.printStackTrace();
}
}
/**
* 导出excel表格
* @param response
* @throws Exception
*/
@PostMapping("/excel")
public void downloadExcel(HttpServletResponse response) throws Exception {
// 创建HSSFWorkbook对象,excel的文档对象
HSSFWorkbook workbook = new HSSFWorkbook();
// excel的表单
HSSFSheet sheet = workbook.createSheet("用户表");
// 数据库表中的数据
List<User> list=userService.selectAll();
// 设置要导出的文件名
String fileName="user"+".xls";
// 新增数据行,并且设置单元格数据
int rowNum=1;
String[] headers={"ID","姓名","年龄","住址","住址2"};
// headers 标识excel表中第一行的表头
HSSFRow row = sheet.createRow(0);
// 在excel表中添加表头
for(int i=0;i<headers.length;i++){
HSSFCell cell=row.createCell(i);
HSSFRichTextString text=new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
// 在表头中存放查询到的数据放入对应的列
for(User user:list){
HSSFRow row1=sheet.createRow(rowNum);
row1.createCell(0).setCellValue(user.getId());
row1.createCell(1).setCellValue(user.getName());
row1.createCell(2).setCellValue(user.getAge());
row1.createCell(3).setCellValue(user.getAddr());
row1.createCell(4).setCellValue(user.getAddr2());
rowNum++;
}
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
response.flushBuffer();
workbook.write(response.getOutputStream());
}
}
到这里基本就可以测试了,我使用的是postman来测试的
然后就到这里就结束了!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端