pdf导出实例(itestpdf)

依赖

<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf --><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.10</version></dependency>

工具类

package org.jeecg.utils;import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.List;public class PDFUtil {/*** pdf模板导出** @param map 导出结果* @param filePath 空pdf路径,作物前端访问路径* @throws Exception*/public static void creatPdf(Map<String, Object> map, String filePath) throws Exception {try {FileOutputStream fos = new FileOutputStream(filePath);;BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 读取pdf模板路径Resource resource  = new ClassPathResource(String.valueOf(map.get("tempPath")));PdfReader reader = new PdfReader(resource.getURL());ByteArrayOutputStream bos = new ByteArrayOutputStream();PdfStamper stamper = new PdfStamper(reader, bos);stamper.setFormFlattening(true);AcroFields form = stamper.getAcroFields();// 文字类的内容处理Map<String, String> datemap = (Map<String, String>) map.get("dataMap");form.addSubstitutionFont(bf);for (String key : datemap.keySet()) {String value = datemap.get(key);form.setField(key, value);form.setFieldProperty(key,"textsize",9f,null);}// 图片类的内容处理Map<String, String> imgmap = (Map<String, String>) map.get("imgMap");for (String key : imgmap.keySet()) {String value = imgmap.get(key);String imgpath = value;int pageNo = form.getFieldPositions(key).get(0).page;Rectangle signRect = form.getFieldPositions(key).get(0).position;float x = signRect.getLeft();float y = signRect.getBottom();// 根据路径读取图片Image image = Image.getInstance(imgpath);// 获取图片页面PdfContentByte under = stamper.getOverContent(pageNo);// 图片大小自适应image.scaleToFit(signRect.getWidth(), signRect.getHeight());// 添加图片image.setAbsolutePosition(x, y);under.addImage(image);}// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑stamper.setFormFlattening(false);stamper.close();Document doc = new Document();PdfCopy copy = new PdfCopy(doc, fos);doc.open();int pageNum = reader.getNumberOfPages();for (int i = 1; i <= pageNum; i++) {PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);copy.addPage(importPage);}doc.close();fos.close();} catch (IOException e) {System.out.println(e);} catch (DocumentException e) {System.out.println(e);}}}

导出结果数据实例(仅供参考)

package com.fiftheconomic.dataCalculate.service.impl;import com.fiftheconomic.dataCalculate.domain.TjDataCalculateBase;
import com.fiftheconomic.dataCalculate.domain.TjDataCalculateDetail;
import com.fiftheconomic.dataCalculate.domain.resCompenyIndex;
import com.fiftheconomic.dataCalculate.service.IPdfService;
import org.springframework.stereotype.Service;import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;/*** @Author: 苏子龙* @Date: 2023/08/01/17:00* @Description:*/
@Service
public class PdfServiceImpl implements IPdfService {/*** 123  工业单位填报 124 批发和零售业单位填报 125 住宿和餐饮业单位填报 126 制造业,信息传输、软件和信息技术服务业,科学研究和技术服务业单位填报** @param resMap* @param list* @return*/@Overridepublic Map<String, Object> oneThree(List<resCompenyIndex> resMap, TjDataCalculateBase base, List<TjDataCalculateDetail> list) {List<List<String>> lists = new ArrayList<>();//表格 (一行数据一个list)SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");Map<String, String> map = new HashMap<>();//文本域for (int i = 0; i < resMap.size(); i++) {if (resMap.get(i).getIndexCode() != null) {if (!map.containsKey(resMap.get(i).getIndexCode())) {map.put(resMap.get(i).getIndexCode(), resMap.get(i).getIndexValue());}}}//添加tj_data_calculate_index基础信息表数据for (int j = 0; j < list.size(); j++) {System.out.println("++++++++" + j);TjDataCalculateDetail data = list.get(j);map.put("name" + j, data.getIndexName());map.put("unit" + j, data.getUnitof());map.put("value" + j, data.getIndexValue());}
//        map.put("name", "无"); //添加tj_data_calculate_index头信息
//        map.put("nameInfo", "无"); //填表人姓名
//        map.put("phoen", "无");//填表人电话
//        map.put("nameBy", "无");//单位负责人
//        map.put("USCI", base.getUSCI());//企业社会信用统一代码
//        map.put("comName", base.getComName());//单位详细名称
//        //添加日期
//        LocalDate now = LocalDate.now();
//        map.put("y", String.valueOf(now.getYear()));
//        map.put("m", String.valueOf(now.getMonthValue()));
//        map.put("d", String.valueOf(now.getDayOfMonth()));
//        map.put("time", String.valueOf(now));//填表人电话Map<String, Object> o = new HashMap<>();String s = base.getIndustryCode();if (s.equals("1")) {o.put("tempPath", "static/pdf/123.pdf");} else if (s.equals("2") || s.equals("3")) {o.put("tempPath", "static/pdf/124.pdf");} else if (s.equals("4") || s.equals("5")) {o.put("tempPath", "static/pdf/125.pdf");} else {o.put("tempPath", "static/pdf/126.pdf");}o.put("dataMap", map);o.put("imgMap", new HashMap<>());Map<String, List<List<String>>> listMap = new HashMap<>();listMap.put("table", lists);o.put("tableList", listMap);return o;}public static void main(String[] args) {LocalDate now = LocalDate.now();System.out.println(now.getYear());System.out.println(now.getMonthValue());System.out.println(now.getDayOfMonth());}}

优化工具包

  public static String creatPdf1(Map<String, Object> map ,OutputStream out,float width[]) throws Exception {BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//        // 输出流
//            String outPutPath = "E:/excel/files/pdf模板导出.pdf";
//            FileOutputStream out = new FileOutputStream(filePath);// 读取pdf模板路径Resource resource = new ClassPathResource(String.valueOf(map.get("tempPath")));PdfReader reader = new PdfReader(resource.getURL());ByteArrayOutputStream bos = new ByteArrayOutputStream();PdfStamper stamper = new PdfStamper(reader, bos);stamper.setFormFlattening(true);AcroFields form = stamper.getAcroFields();// 文字类的内容处理Map<String, String> datemap = (Map<String, String>) map.get("dataMap");form.addSubstitutionFont(bf);for (String key : datemap.keySet()) {String value = datemap.get(key);form.setField(key, value);form.setFieldProperty(key, "textsize", 9f, null);}// 图片类的内容处理Map<String, String> imgmap = (Map<String, String>) map.get("imgMap");for (String key : imgmap.keySet()) {String value = imgmap.get(key);String imgpath = value;int pageNo = form.getFieldPositions(key).get(0).page;Rectangle signRect = form.getFieldPositions(key).get(0).position;float x = signRect.getLeft();float y = signRect.getBottom();// 根据路径读取图片Image image = Image.getInstance(imgpath);// 获取图片页面PdfContentByte under = stamper.getOverContent(pageNo);// 图片大小自适应image.scaleToFit(signRect.getWidth(), signRect.getHeight());// 添加图片image.setAbsolutePosition(x, y);under.addImage(image);}// 表格类Map<String, List<List<String>>> listMap = (Map<String, List<List<String>>>) map.get("tableList");if (listMap != null) {Object[] arr = new Object[]{};if (listMap.containsKey("table1")) {List<List<String>> lists1 = listMap.get("table1");if (lists1.size() > 0) {arr = new Object[]{"table", "table1"};} else {arr = new Object[]{"table"};}}else {arr = new Object[]{"table"};arr = new Object[]{"tableInfo"};}
//            for (Object key : arr) {List<List<String>> lists = listMap.get("table");List<List<String>> listInfo = listMap.get("tableInfo");List<List<String>> listBy = listMap.get("table1");//判断if (listBy!= null && listBy.size()>0) {//遍历数据添加序号for (int i = 0; i < listBy.size(); i++) {List<String> list = listBy.get(i);
//                    List<String> list = listBy.get(0);String data = list.get(0);String on = i + 1 + "   " + data;
//                    String on = 0 + 1 + "   " + data;list.set(0, on);}int pageNo = 0;if (form.getFieldPositions("table1") == null) {pageNo = 0;} else {pageNo = form.getFieldPositions("table1").get(0).page;}PdfContentByte pcb = stamper.getOverContent(pageNo);List<AcroFields.FieldPosition> listAf = form.getFieldPositions("table1");Rectangle signRect = listAf.get(0).position;//表格位置int columnInfo = listBy.get(0).size();int rowInfo = listBy.size();PdfPTable tableInfo = new PdfPTable(columnInfo);
//                    float tatalWidth = signRect.getRight() - signRect.getLeft() - 1;tableInfo.setTotalWidth(width);tableInfo.setLockedWidth(true);tableInfo.setKeepTogether(true);tableInfo.setSplitLate(false);tableInfo.setSplitRows(true);Font FontProve = new Font(bf, 8, 0);//表格数据填写for (int k = 0; k < rowInfo; k++) {List<String> listTo = listBy.get(k);
//                                List<String> listTo = listBy.get(i);for (int j = 0; j < columnInfo; j++) {Paragraph paragraph = new Paragraph(String.valueOf(listTo.get(j)), FontProve);PdfPCell cell = new PdfPCell(paragraph);cell.setBorderWidth(1);cell.setMinimumHeight(1);if (j == 0) {cell.setVerticalAlignment(Element.ALIGN_LEFT);cell.setHorizontalAlignment(Element.ALIGN_LEFT);} else {cell.setVerticalAlignment(Element.ALIGN_CENTER);cell.setHorizontalAlignment(Element.ALIGN_CENTER);}cell.setLeading(0, (float) 1.4);cell.disableBorderSide(15);//隐藏tableInfo.addCell(cell);}}tableInfo.writeSelectedRows(0, -1, signRect.getLeft(), signRect.getTop(), pcb);
//                        }}if (listInfo!= null && listInfo.size()>0) {//遍历数据添加序号for (int i = 0; i < listInfo.size(); i++) {List<String> list = listInfo.get(i);String data = list.get(0);String on = i + 1 +"   " + data ;list.set(0,on);}int pageNo = 0;if (form.getFieldPositions("tableInfo") == null) {pageNo = 0;} else {pageNo = form.getFieldPositions("tableInfo").get(0).page;}PdfContentByte pcb = stamper.getOverContent(pageNo);List<AcroFields.FieldPosition> listAf = form.getFieldPositions("tableInfo");Rectangle signRect = listAf.get(0).position;//表格位置int columnInfo = listInfo.get(0).size();int rowInfo = listInfo.size();PdfPTable tableInfo = new PdfPTable(columnInfo);float tatalWidth = signRect.getRight() - signRect.getLeft() - 1;
//tableInfo.setTotalWidth(tatalWidth);tableInfo.setLockedWidth(true);tableInfo.setKeepTogether(true);tableInfo.setSplitLate(false);tableInfo.setSplitRows(true);Font FontProve = new Font(bf, 8, 0);//表格数据填写for (int i = 0; i < rowInfo; i++) {List<String> list = listInfo.get(i);for (int j = 0; j < columnInfo; j++) {Paragraph paragraph = new Paragraph(String.valueOf(list.get(j)), FontProve);PdfPCell cell = new PdfPCell(paragraph);cell.setBorderWidth(1);cell.setMinimumHeight(1);if (j == 0) {cell.setVerticalAlignment(Element.ALIGN_LEFT);cell.setHorizontalAlignment(Element.ALIGN_LEFT);} else {cell.setVerticalAlignment(Element.ALIGN_CENTER);cell.setHorizontalAlignment(Element.ALIGN_CENTER);}cell.setLeading(0, (float) 1.4);cell.disableBorderSide(15);//隐藏tableInfo.addCell(cell);}}System.out.println(signRect.getLeft());System.out.println(signRect.getTop());System.out.println(pcb);tableInfo.writeSelectedRows(0, -1, signRect.getLeft(), signRect.getTop(), pcb);}if (lists!= null && lists.size()>0) {//遍历数据添加序号for (int i = 0; i < lists.size(); i++) {List<String> list = lists.get(i);String data = list.get(0);String on = i + 1 +"   "+ data ;list.set(0,on);}int pageNo = 0;if (form.getFieldPositions("table") == null) {pageNo = 0;} else {pageNo = form.getFieldPositions("table").get(0).page;}PdfContentByte pcb = stamper.getOverContent(pageNo);List<AcroFields.FieldPosition> listAf = form.getFieldPositions("table");Rectangle signRect = listAf.get(0).position;//表格位置int column = lists.get(0).size();int row = lists.size();PdfPTable table = new PdfPTable(column);
//                    float tatalWidth = signRect.getRight() - signRect.getLeft() - 1;//                table.setTotalWidth(width);table.setLockedWidth(true);table.setKeepTogether(true);table.setSplitLate(false);table.setSplitRows(true);Font FontProve = new Font(bf, 8, 0);//表格数据填写for (int i = 0; i < row; i++) {List<String> list = lists.get(i);for (int j = 0; j < column; j++) {Paragraph paragraph = new Paragraph(String.valueOf(list.get(j)), FontProve);PdfPCell cell = new PdfPCell(paragraph);cell.setBorderWidth(1);cell.setMinimumHeight(1);if (j == 0) {cell.setVerticalAlignment(Element.ALIGN_LEFT);cell.setHorizontalAlignment(Element.ALIGN_LEFT);} else {cell.setVerticalAlignment(Element.ALIGN_CENTER);cell.setHorizontalAlignment(Element.ALIGN_CENTER);}cell.setLeading(0, (float) 1.4);cell.disableBorderSide(15);//隐藏table.addCell(cell);}}table.writeSelectedRows(1, -1, signRect.getLeft(), signRect.getTop(), pcb);}}// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑stamper.setFormFlattening(true);stamper.close();Document doc = new Document();PdfCopy copy = new PdfCopy(doc, out);doc.open();
//        File file = new File("ruoyi-admin/src/main/resources/static/pdf/111.pdf");
//        File file = new File("D:\\feishu\\yihe\\111.pdf");//本地路径File file = new File("E:\\item\\yihe\\ruoyi-admin\\src\\main\\resources\\static\\pdf\\111.pdf");//线上路径
//        File file = new File("D:\\feishu\\yihe\\111.pdf");PdfCopy copy1 = new PdfCopy(doc, new FileOutputStream(file));doc.open();int pageNum = reader.getNumberOfPages();for (int i = 1; i <= pageNum; i++) {PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);copy.addPage(importPage);copy1.addPage(importPage);}
//        String url = AliyunOSSUtil.upload(getMultipartFile(file));
//        System.out.println("url = " + url);doc.close();return "url";}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/115396.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Gensim概念】01/3 NLP玩转 word2vec

第一部分 词法 一、说明 Gensim是一种Python库&#xff0c;用于从文档集合中提取语义主题、建立文档相似性模型和进行向量空间建模。它提供了一系列用于处理文本数据的算法和工具&#xff0c;包括主题建模、相似性计算、文本分类、聚类等。在人工智能和自然语言处理领域&…

【React】高频面试题

1. 简述下 React 的事件代理机制&#xff1f; React使用了一种称为“事件代理”&#xff08;Event Delegation&#xff09;的机制来处理事件。事件代理是指将事件处理程序绑定到组件的父级元素上&#xff0c;然后在需要处理事件的子元素上触发事件时&#xff0c;事件将被委托给…

软件外包开发迭代管理工具

软件迭代的管理工具有助于团队有效地规划、跟踪和管理迭代开发过程&#xff0c;确保项目按时交付&#xff0c;并与团队成员之间进行协作。以下是一些常用的软件迭代管理工具&#xff0c;希望对大家有所帮助。北京木奇移动技术有限公司&#xff0c;专业的软件外包开发公司&#…

Go中的工作池:并发任务的优雅管理

一、前言 在当今的软件开发领域&#xff0c;处理大规模并发任务是一项关键挑战。Go语言以其强大的并发支持而闻名&#xff0c;而工作池是一种在Go中管理并发任务的精巧方式。本文将介绍工作池的工作原理&#xff0c;并通过代码示例演示其在实际应用中的用途。 二、内容 2.1 …

地图金字塔所在块的经纬度方位

地图金字塔所在块的经纬度方位 算法 #define LON_SPAN 360.0 // 开始经度(最左端) #define LAT_SPAN 180.0 #define GLOBAL_LEFT -180.0 // 开始纬度(最上端) #define GLOBAL_TOP 90.0 #define GLOBAL_RIGHT 180.0 #define GLOBAL_BOTTOM -90.0 // 地球的纬度跨度(180-(-180))…

不能抛开学历说人工智能研发能力

【来函照登 我也说几句】 作者&#xff1a;Deng-Xian-Sheng&#xff08;佳里敦大学人工智能研究所 类脑人工智能研究实验室副教授&#xff09; 我在网上看到某些报道&#xff0c;在谈到人工智能研发时&#xff0c;刻意强调个别研发人员学历不高&#xff0c;甚至以“中专生逆袭…

Vue基于element ui中Upload组件实现文件上传下载—附源码

1.在页面中引入Upload组件 <!--上传文件--> <el-upload class"upload-demo"ref"upload"action"#":limit"3":show-file-list"true":file-list"getFileList(scope.row.fileInfoList|| [])":on-exceed&quo…

10.23归并排序

课上 归并排序 最大时&#xff0c;就是两个都是完全倒序&#xff0c;但注意一定有一个序列先用完&#xff0c;此时剩一个序列只有一个元素&#xff0c;不用比较&#xff0c;直接加入&#xff0c;所以就是nn-1, 最小时&#xff0c;是都是完全有序&#xff0c;且一个序列中的元…

Python合并同类别且相交的矩形框

Python合并同类别且相交的矩形框 前言前提条件相关介绍实验环境Python合并同类别且相交的矩形框代码实现 前言 由于本人水平有限&#xff0c;难免出现错漏&#xff0c;敬请批评改正。更多精彩内容&#xff0c;可点击进入Python日常小操作专栏、YOLO系列专栏、自然语言处理专栏或…

大语言模型(LLM)综述(二):开发大语言模型的公开可用资源

A Survey of Large Language Models 前言3. RESOURCES OF LLMS3.1 公开可用的模型CheckPoints或 API3.2 常用语料库3.3 库资源 前言 随着人工智能和机器学习领域的迅速发展&#xff0c;语言模型已经从简单的词袋模型&#xff08;Bag-of-Words&#xff09;和N-gram模型演变为更…

.NET主流的ORM框架 2023年

1. Entity Framework Entity Framework是Microsoft开发的一款强大的ORM框架。适用于.NET开发&#xff0c;支持多种数据库&#xff0c;并提供了广泛的文档和教程。Entity Framework基于面向对象的数据模型&#xff0c;使用LINQ进行查询。它的强大功能和易用性使得它成为.NET开发…

图论04-【无权无向】-图的广度优先遍历BFS

文章目录 1. 代码仓库2. 广度优先遍历图解3.主要代码4. 完整代码 1. 代码仓库 https://github.com/Chufeng-Jiang/Graph-Theory 2. 广度优先遍历图解 3.主要代码 原点入队列原点出队列的同时&#xff0c;将与其相邻的顶点全部入队列下一个顶点出队列出队列的同时&#xff0c;将…

计算机考研自命题(2)

1、C语言-字符串交替拼接 1、用C编程&#xff0c;将两个字符串数组存储实现交替连接如aaa和bbb两个字符连接成ababab 如aaa和baba 两个字符&#xff0c;连接成 abaaaba #include<stdio.h>/* 解题思路&#xff1a;将两个字符串交替拼接&#xff0c;定义三个数组&#xff0…

基础课6——计算机视觉

1.计算机视觉的概念与原理 1.1概念 计算机视觉&#xff08;CV&#xff09;是人工智能的一个重要发展领域&#xff0c;属于计算机科学的一个分支&#xff0c;它企图让计算机能像人类一样通过视觉来获取和理解信息。计算机视觉的应用非常广泛&#xff0c;包括但不限于图像识别、…

Python学习——Day10

一、sys模块 概述&#xff1a;Python 的 sys 模块提供访问解释器使用或维护的变量&#xff0c;和与解释器进行交互的函数。通俗来讲&#xff0c;sys 模块为程序与 Python 解释器的交互&#xff0c;提供了一系列的函数和变量&#xff0c;用于操控 Python 运行时的环境 sys.arg…

图像识别在自动驾驶汽车中的多传感器融合技术

摘要&#xff1a; 介绍文章的主要观点和发现。 引言&#xff1a; 自动驾驶汽车的兴起和重要性。多传感器融合技术在自动驾驶中的关键作用。 第一部分&#xff1a;图像识别技术 图像识别的基本原理。图像传感器和摄像头在自动驾驶中的应用。深度学习和卷积神经网络&#xff…

Typora的相关配置(Typora主题、字体、快捷键、习惯)

Typora的相关配置(Typora主题、字体、快捷键、习惯) 文章目录 Typora的相关配置(Typora主题、字体、快捷键、习惯)[toc]一、主题配置二、字体配置查看字体名称是否可以被识别&#xff1a;如果未能正确识别&#xff1a; 三、习惯配置四、快捷键配置更改提供的功能的快捷键&#…

常见的测试理论面试问题

1.请解释软件生存周期是什么&#xff1f; 软件生存周期是指从软件开发到维护的过程&#xff0c;包括可行性研究、需求分析、软件设计、编码、测试、发布和维护等活动。这个过程也被称为“生命周期模型”。 2.软件测试的目的是什么&#xff1f; 软件测试的目的是发现软件中的错…

前端react入门day01-了解react和JSX基础

(创作不易&#xff0c;感谢有你&#xff0c;你的支持&#xff0c;就是我前行的最大动力&#xff0c;如果看完对你有帮助&#xff0c;请留下您的足迹&#xff09; 目录 React介绍 React是什么 React的优势 React的市场情况 开发环境搭建 使用create-react-app快速搭建…

python【多线程、单线程、异步编程】三个版本--在爬虫中的应用

并发编程在爬虫中的应用 之前的课程&#xff0c;我们已经为大家介绍了 Python 中的多线程、多进程和异步编程&#xff0c;通过这三种手段&#xff0c;我们可以实现并发或并行编程&#xff0c;这一方面可以加速代码的执行&#xff0c;另一方面也可以带来更好的用户体验。爬虫程…