前言:

  纯代码画pdf格式

        <!-- iText PDF -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.2</version>
</dependency>
<!-- pdf 字体需要 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>

示例代码:

生成PDF文件(无表格版)

  Controller

@PostMapping("exportPDF")
public void registrationNoticeExport(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
//防止日志记录获取session异常
request.getSession(); HashMap<String, String> dataMap = new HashMap<>(); dataMap.put("year","2023");
dataMap.put("sort","12");
dataMap.put("inspectionCompany","这是第一行的标题");
dataMap.put("planName","这是第二行的标题xxxxxxxxx");
dataMap.put("qymc","这是发文公司/人");
dataMap.put("kdmc","内容测试");
dataMap.put("attachmentNameStr","attachmentNameStr测试");
dataMap.put("date","日期测试");
dataMap.put("inspectionTeamLeaderInfo","落款测试"); //导出pdf
PdfUtil.setResponseContentType(response, "文件名称测试" );
PdfUtil.downloadPdf(dataMap,response); }

  Util

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.draw.LineSeparator; import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map; public class PdfUtil { public static void setResponseContentType(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
response.setContentType("application/pdf");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8") + ".pdf");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
} public static void downloadPdf(Map<String,String> dataMap, HttpServletResponse response){
// 定义全局的字体静态变量
Font titlefont;
Font headfont;
Font keyfont = null;
Font textfont = null;
Font content = null;
Font space = null;
Font space1 = null;
Font space2 = null;
Font space3 = null;
// 最大宽度
try {
// 不同字体(这里定义为同一种字体:包含不同字号、不同style)
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
titlefont = new Font(bfChinese, 16, Font.BOLD);
headfont = new Font(bfChinese, 14, Font.BOLD);
keyfont = new Font(bfChinese, 22, Font.BOLD);
textfont = new Font(bfChinese, 15, Font.NORMAL);
content = new Font(bfChinese, 16, Font.NORMAL);
space = new Font(bfChinese, 5, Font.NORMAL);
space1 = new Font(bfChinese, 20, Font.NORMAL);
space2 = new Font(bfChinese, 20, Font.NORMAL);
space3 = new Font(bfChinese, 3, Font.NORMAL); } catch (Exception e) {
e.printStackTrace();
}
BaseFont bf;
Font font = null;
try {
//可以引用自己想要的字体
bf = BaseFont.createFont("D:\\cbd-marketSurvey-service\\src\\main\\resources\\templates\\simsun.ttc,1",
BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//创建字体
// bf = BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H",
// BaseFont.NOT_EMBEDDED);
//使用字体并给出颜色
font = new Font(bf,36,Font.BOLD, BaseColor.RED);
} catch (Exception e) {
e.printStackTrace();
}
Document document = new Document(new Rectangle(com.itextpdf.text.PageSize.A4)); try {
com.itextpdf.text.pdf.PdfWriter.getInstance(document, response.getOutputStream());
//打开PDF文件
document.open();
//设置内容
Paragraph paragraph = new Paragraph("标题内容测试", font);
//居中设置
paragraph.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph); //页眉横线
document.add(new Paragraph("\n", space2));
LineSeparator line = new LineSeparator(3f, 100, BaseColor.RED, Element.ALIGN_CENTER, 0f);
document.add(line);
document.add(new Paragraph("\n", space3));
LineSeparator lineStart = new LineSeparator(1f, 100, BaseColor.RED, Element.ALIGN_CENTER, 0f);
document.add(lineStart); document.add(new Paragraph("\n", space));
String text = "标注测试〔" + dataMap.get("year") + "〕" + dataMap.get("sort") + "号";
Paragraph paragraph0 = new Paragraph(text, content);
paragraph0.setAlignment(Element.ALIGN_RIGHT);
document.add(paragraph0); document.add(new Paragraph("\n"));
Paragraph paragraph1 = new Paragraph(dataMap.get("inspectionCompany"), keyfont);
paragraph1.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph1); document.add(new Paragraph("\n", space));
String concent = dataMap.get("planName");
Paragraph paragraph2 = new Paragraph(concent, keyfont);
paragraph2.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph2); document.add(new Paragraph("\n"));
Paragraph paragraph3 = new Paragraph(dataMap.get("qymc") + ":", content);
paragraph3.setAlignment(Element.ALIGN_LEFT);
document.add(paragraph3); document.add(new Paragraph("\n", space));
String concent1 = " 现将" + dataMap.get("kdmc")
+ "这是一段内容测试:知识密集型行业往往有着这样的特点,一方面对于从业者有着高度专业化的知识要求,需要具备高度专业化的背景和经验,准入门槛较高;同时,知识密集型行业往往也是文档密集型行业,文档的厚度和复杂性较高,让行业的数字化转型与应用创新面临更大挑战。。";
Paragraph paragraph4 = new Paragraph(concent1, content);
//设置首行缩进
paragraph4.setIndentationRight(2);
document.add(paragraph4); document.add(new Paragraph("\n", space));
Paragraph paragraph5 = new Paragraph(" 特此通知。", content);
//右缩进2格
paragraph5.setIndentationRight(2);
document.add(paragraph5); document.add(new Paragraph("\n", space1));
document.add(new Paragraph("\n", space1));
//附件
Paragraph paragraph6 = new Paragraph(" 附件:", content);
//右缩进2格
paragraph6.setIndentationRight(2);
document.add(paragraph6); document.add(new Paragraph("\n", space));
Paragraph paragraph7 = new Paragraph(" "+dataMap.get("attachmentNameStr"), content);
document.add(paragraph7); document.add(new Paragraph("\n", space1));
document.add(new Paragraph("\n", space1));
document.add(new Paragraph("\n", space1)); //日期
Paragraph paragraph8 = new Paragraph(dataMap.get("date"), content);
//向右
paragraph8.setAlignment(Element.ALIGN_RIGHT);
document.add(paragraph8); document.add(new Paragraph("\n", space1));
//落款
Paragraph paragraph9 = new Paragraph(dataMap.get("inspectionTeamLeaderInfo"), content);
paragraph9.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph9); //页尾横线
document.add(new Paragraph("\n", space2));
document.add(new Paragraph("\n", space2));
LineSeparator lineEnd = new LineSeparator(3f, 100, BaseColor.RED, Element.ALIGN_CENTER, 0f);
document.add(lineEnd);
document.add(new Paragraph("\n", space3));
LineSeparator lineEnd1 = new LineSeparator(1f, 100, BaseColor.RED, Element.ALIGN_CENTER, 0f);
document.add(lineEnd1); //关闭文档
document.close(); } catch (Exception e) {
e.printStackTrace();
//log.error("导出pdf失败:{}", e);
} }
}

  效果图

 生成PDF文件(表格版)

  Controller

    @PostMapping("/download")
public void download(HttpServletResponse response, HttpServletRequest request) throws IOException {
// 防止日志记录获取session异常
request.getSession();
// 设置编码格式
response.setContentType("application/pdf;charset=UTF-8");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("下载的PDF名称", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".pdf");
List<String> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(String.valueOf(i));
}
PdfUtil.download(list, response);
}

  Util



    public static void download(List<String> list, HttpServletResponse response) throws IOException {
//要下载的数据查询数据部分我去掉了有需要自己根据业务取 // 定义全局的字体静态变量
Font content = null;
// 最大宽度
try {
// 不同字体(这里定义为同一种字体:包含不同字号、不同style)
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
content = new Font(bfChinese, 10, Font.NORMAL); } catch (Exception e) {
e.printStackTrace();
}
BaseFont bf;
Font font = null;
try {
//创建字体
bf = BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H",
BaseFont.NOT_EMBEDDED);
//使用字体并给出颜色
font = new Font(bf,20,Font.BOLD, BaseColor.BLACK);
} catch (Exception e) {
e.printStackTrace();
} Document document = new Document(new RectangleReadOnly(842F, 595F));
try {
PdfWriter.getInstance(document,response.getOutputStream());
//打开生成的pdf文件
document.open();
//设置内容
Paragraph paragraph = new Paragraph("主题名称",font);
paragraph.setAlignment(1);
//引用字体
document.add(paragraph); // 设置表格的列宽和列数
float[] widths = {25f,25f,25f,25f,25f,25f};
PdfPTable table = new PdfPTable(widths);
table.setSpacingBefore(20f);
// 设置表格宽度为100%
table.setWidthPercentage(100.0F);
table.setHeaderRows(1);
table.getDefaultCell().setHorizontalAlignment(1);
PdfPCell cell = null;
//第一行
cell = new PdfPCell(new Paragraph("标题",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setFixedHeight(30);
table.addCell(cell); cell = new PdfPCell(new Paragraph("内容测试",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell); cell = new PdfPCell(new Paragraph("标题",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell); cell = new PdfPCell(new Paragraph("内容测试",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell); cell = new PdfPCell(new Paragraph("标题",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell); cell = new PdfPCell(new Paragraph("内容测试",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
//第二行
cell = new PdfPCell(new Paragraph("标题",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setFixedHeight(30);
table.addCell(cell); cell = new PdfPCell(new Paragraph("内容测试",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell); cell = new PdfPCell(new Paragraph("标题",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell); cell = new PdfPCell(new Paragraph("内容测试",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell); cell = new PdfPCell(new Paragraph("标题",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell); cell = new PdfPCell(new Paragraph("内容测试",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
//第三行
cell = new PdfPCell(new Paragraph("标题",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setFixedHeight(30);
table.addCell(cell); cell = new PdfPCell(new Paragraph("内容测试",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell); cell = new PdfPCell(new Paragraph("标题",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell); cell = new PdfPCell(new Paragraph("内容测试",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell); cell = new PdfPCell(new Paragraph(" ",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell); cell = new PdfPCell(new Paragraph(" ",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell); // 设置表格的列宽和列数
float[] widths2 = {25f,25f,25f,25f,25f,25f};
PdfPTable table2 = new PdfPTable(widths2);
table2.setSpacingBefore(20f);
// 设置表格宽度为100%
table2.setWidthPercentage(100.0F);
table2.setHeaderRows(1);
table2.getDefaultCell().setHorizontalAlignment(1); //人员列表-第四行
cell = new PdfPCell(new Paragraph("标题",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setFixedHeight(20);
table2.addCell(cell); cell = new PdfPCell(new Paragraph("标题",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table2.addCell(cell); cell = new PdfPCell(new Paragraph("标题",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table2.addCell(cell); cell = new PdfPCell(new Paragraph("标题",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table2.addCell(cell); cell = new PdfPCell(new Paragraph("标题",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table2.addCell(cell); cell = new PdfPCell(new Paragraph("标题",content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table2.addCell(cell);
//人员列表数据-第五行
if(list.size() > 0){
for (String prople : list) {
PdfPCell cell1 = new PdfPCell(new Paragraph(prople, content));
PdfPCell cell2 = new PdfPCell(new Paragraph(prople, content));
PdfPCell cell3 = new PdfPCell(new Paragraph(prople, content));
PdfPCell cell4 = new PdfPCell(new Paragraph(prople, content));
PdfPCell cell5 = new PdfPCell(new Paragraph(prople, content));
PdfPCell cell6 = new PdfPCell(new Paragraph(prople, content)); //单元格对齐方式
cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell1.setFixedHeight(20);
//单元格垂直对齐方式
cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
cell2.setVerticalAlignment(Element.ALIGN_MIDDLE); cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
cell3.setVerticalAlignment(Element.ALIGN_MIDDLE); cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
cell4.setVerticalAlignment(Element.ALIGN_MIDDLE); cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
cell5.setVerticalAlignment(Element.ALIGN_MIDDLE); cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
cell6.setVerticalAlignment(Element.ALIGN_MIDDLE); table2.addCell(cell1);
table2.addCell(cell2);
table2.addCell(cell3);
table2.addCell(cell4);
table2.addCell(cell5);
table2.addCell(cell6);
}
} document.add(new Paragraph("\n"));
document.add(new Paragraph("▋ 基本信息",content));
document.add(new Paragraph("\n")); document.add(table); document.add(new Paragraph("\n"));
document.add(new Paragraph("▋ 基本信息",content));
document.add(new Paragraph("\n")); document.add(table2); //关闭文档
document.close(); } catch (DocumentException e) {
e.printStackTrace();
log.error("导出pdf失败:{}",e);
}
}

  效果图

java-导出pdf的更多相关文章

  1. JAVA导出pdf实例

    一.直接导出成PDF   Java代码 1. import java.io.FileNotFoundException; 2. import java.io.FileOutputStream; 3.  ...

  2. java导出pdf功能记录

    这几天已在做处理导出pdf文件的功能,摸索了几天总算可以了.记录下这几天遇到的问题. 1.网上基本都是基于Itext5和Itext7来处理的.我最终是在Itext5上成功了,itext7应该是模板出问 ...

  3. Java导出Pdf格式表单

    前言   作为开发人员,工作中难免会遇到复杂表单的导出,接下来介绍一种通过Java利用模板便捷导出Pdf表单的方式 模拟需求   需求:按照下面格式导出pdf格式的学生成绩单 准备工作 Excel软件 ...

  4. Java导出pdf文件数据

    提示:导出pdf文件,需要3个jar包iText-2.1.5.jar,iTextAsian.jar,iText-rtf-2.1.4.jar. public boolean outputPdfJhsy( ...

  5. java导出pdf

    //导出          public void ScoringAnnouncementdownLoad() throws MalformedURLException, IOException, D ...

  6. 一次java导出pdf的经历

    近期由于工作需要,需要将html代码导入到pdf中,经过了几种pdf的方案对比后发现IText是最简单和便捷的一种方式,于是乎采用了Itext. PDF生成 第一步:导入Maven依赖 <!-- ...

  7. java根据模板导出PDF详细教程

    原文:https://blog.csdn.net/pengyufight/article/details/75305128 题记:由于业务的需要,需要根据模板定制pdf文档,经测试根据模板导出word ...

  8. java根据模板导出pdf

    在网上看了一些Java生成pdf文件的,写的有点乱,有的不支持写入中文字体,有的不支持模板,有的只是随便把数据放里面生成文件,完全不考虑数据怎样放置的以及以后的维护性,想想还是自己总结一个完全版的导出 ...

  9. java利用itext导出pdf

    项目中有一功能是导出历史记录,可以导出pdf和excel,这里先说导出pdf.在网上查可以用那些方式导出pdf,用itext比较多广泛. 导出pdf可以使用两种方式,一是可以根据已有的pdf模板,进行 ...

  10. java根据模板文件导出pdf

    原文:https://www.cnblogs.com/wangpeng00700/p/8418594.html 在网上看了一些Java生成pdf文件的,写的有点乱,有的不支持写入中文字体,有的不支持模 ...

随机推荐

  1. c++算法:二分

    算法中,有一种比线性查找算力费得更少的一种算法思想,叫"分治",今天讲的是分治里的二分查找: 借助 (low+high)/2公式,找到搜索区域内的中间元素.图 1 中,搜索区域内中 ...

  2. 【pandas小技巧】--DataFrame的显示参数

    我们在jupyter notebook中使用pandas显示DataFrame的数据时,由于屏幕大小,或者数据量大小的原因,常常会觉得显示出来的表格不是特别符合预期. 这时,就需要调整pandas显示 ...

  3. 【io_uring】liburing 用户库源码分析

    文章目录 整体流程 `io_uring_queue_init` `io_uring_get_sqe` `io_uring_prep_#OP` `io_uring_sqe_set_data` `io_u ...

  4. ChatGPT如何生成可视化图表-示例中国近几年出生人口

    本教程收集于:AIGC从入门到精通教程汇总 ChatGPT本身不能直接生成可视化图表,但可以配合其他可视化工具或库 方法一:前端可视化开发库 Echarts(地址:Apache ECharts ) 方 ...

  5. 基于bert-base-chinese训练bert模型(最后附上整体代码)

    目录: 一.bert-base-chinese模型下载 二.数据集的介绍 三.完成类的代码 四.写训练方法 五.总源码及源码参考出处 一.bert-base-chinese模型下载 对于已经预训练好的 ...

  6. 拼多多根据ID取商品详情 API 返回值说明

    ​ item_get-根据ID取商品详情 注册开通 pinduoduo.item_get 公共参数 名称 类型 必须 描述 key String 是 调用key(必须以GET方式拼接在URL中) se ...

  7. api接口对接如何实现,php如何对接api

    API接口对接是现代软件开发中不可或缺的一部分,它允许不同的应用程序之间进行数据交换和服务调用.在PHP中,可以使用多种方式实现API接口的对接,包括基于HTTP协议的传统方法以及现代的API客户端库 ...

  8. MySQL实战实战系列 02 日志系统:一条SQL更新语句是如何执行的?

    前面我们系统了解了一个查询语句的执行流程,并介绍了执行过程中涉及的处理模块.相信你还记得,一条查询语句的执行过程一般是经过连接器.分析器.优化器.执行器等功能模块,最后到达存储引擎. 那么,一条更新语 ...

  9. centos7安装Python3.7,执行./configure时报错,configure: error: no acceptable C compiler found in $PATH

    执行./configure时报错,configure: error: no acceptable C compiler found in $PATH 在安装python3.7,配置编译路径时会遇到以下 ...

  10. Shell 文件或目录操作符(-e、-d、-f、-r、-w、-x)

    操作符 操作符 含义-e 判断对象是否存在(Exist),若存在则结果为真-d 判断对象是否为目录(Directory),是则为真-f 判断对象是否为一般文件(File),是则为真-r 判断对象是否有 ...