Java编程技巧:将图片导出成pdf文件

目录

      • 一、pom依赖
      • 二、代码
      • 三、测试链接
      • 四、结果展示

一、pom依赖

<!-- pdf插件 start -->
<dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.3</version>
</dependency>
<dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version>
</dependency>
<!-- pdf插件 end --><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.16</version>
</dependency>

二、代码

import cn.hutool.core.io.FileUtil;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.SneakyThrows;
import org.springframework.util.ResourceUtils;
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 javax.xml.bind.DatatypeConverter;
import java.io.*;@RestController
@RequestMapping("/test")
public class TestController {// 公文格式-页边距 start// 上页边距(单位:cm)private static final double TOP = 3.7;// 上页边距(单位:cm)private static final double BOTTOM = 3.5;// 上页边距(单位:cm)private static final double LEFT = 2.8;// 上页边距(单位:cm)private static final double RIGHT = 2.6;// 公文格式-页边距 end// 厘米转磅private static final double CM_2_POUND = 28.35;/*** 将base64编码图片字符串转换为pdf,然后在浏览器中下载* 模拟场景:从数据库中读取base64图片编码,然后进行下载*/@GetMapping("/base642pdf")public void base642pdf(HttpServletResponse response) {// 准备数据String base64 = "/9j/4AAQSkZJRgABAQAAAQABAAD/4gHYSUNDX1BST0ZJTEUAAQEAAAHIAAAAAAQwAABtbnRyUkdCIFhZWiAH4AABAAEAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAACRyW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AAAAAAAAAAAAAAJrJWPai8yb+VCEAJ/M3zk9Y5m+cnrIAAn8zfOT1jmb5yesgACfzN85PWOZvnJ6yAAJr5WMaq8yb+RCEAAIGO+OZT87b/AiJ5Ax3xzKfnbf4EQE815x9w2Kz/C3LYjL4GTLssdE2GCOjNae2VHorXo2Kpbc1W7KvN4PIieVNl3NhlVqXS+D1hjFwuo6brlB8jXy1lmkZFOif1JWsciSxr3OjfuxydjmqgH88KOCw2SlmqM4f0FyuMyN5mbdDpqRZKtNzNo0mgTS7oq6NbDC5sjY+k3leqsZ0juToequKp5DFuxeNZSwCYXCwtpQwvhRkjq2QSB3LLDE9WJJ27LFGqqrX7Jtyrsup7nLh/DgIMBcsZu/HRVvV0k97lbQayXpYmw142trNax6NXZYlR/IxJOkRqIXNXg/pbrp+qdQPk1DqF2PbjmZnJ1Ka24Y06Xd0TooGJE5yTOR3IiIqNb2d+4YLj7/ABHsJwqh1NpTTdDGJfr9FZo6gntzuXq2xyo6F9KJrUVN1VUkXZezt7zeZr3D8DtHYK9gsjRy2rpZtPypLWbe1RkLsLlSF8XjQWJXxJ4r1XxGNVF22VE3RdhAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhS4mrLPJY6SzG+VUc/orD2IqoiJvsiom+yIn6CaAIHU1f5Vf8AbJfrDqav8qv+2S/WJ4AgdTV/lV/2yX6w6mr/ACq/7ZL9YngCB1NX+VX/AGyX6w6mr/Kr/tkv1ieAPljUY1GIqryptuq7r6z6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/9k=";String fileName = "中国城市-导图版";// 公文格式页边距float marginLeft = Math.round(LEFT * CM_2_POUND);float marginRight = Math.round(RIGHT * CM_2_POUND);float marginTop = Math.round(TOP * CM_2_POUND);float marginBottom = Math.round(BOTTOM * CM_2_POUND);Document document = null;OutputStream os = null;try {// 设置response属性os = response.getOutputStream();response.setContentType("application/force-download");try {fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");} catch (UnsupportedEncodingException e) {e.printStackTrace();}response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".pdf");// 设置pdf页面大小document = new Document(PageSize.A4, marginLeft, marginRight, marginTop, marginBottom);document.addTitle(fileName);// 处理图片数据、居中byte[] bytes = DatatypeConverter.parseBase64Binary(base64);Image img = Image.getInstance(bytes);img.setAlignment(Image.MIDDLE);// 处理图片缩放比率float contentWidth = PageSize.A4.getWidth() - marginLeft - marginRight;float contentHeight = PageSize.A4.getHeight() - marginTop - marginBottom;float imgWidth = img.getWidth();float imgHeight = img.getHeight();float widthPercent = contentWidth / imgWidth * 100;float heightPercent = contentHeight / imgHeight * 100;img.scalePercent(widthPercent < heightPercent ? widthPercent : heightPercent);// 将图片放入pdfPdfWriter.getInstance(document, os);document.open();document.newPage();document.add(img);} catch (Exception e) {e.printStackTrace();} finally {if (document != null) {document.close();}if (os != null) {try {os.close();} catch (IOException e) {e.printStackTrace();}}}}/*** 将图片文件转换为pdf,然后在浏览器中下载* 模拟场景:从本地读取图片文件,然后在浏览器中下载*/@SneakyThrows@GetMapping("/file2pdf")public void file2pdf(HttpServletResponse response) {// 准备数据File file = ResourceUtils.getFile("classpath:中国城市-导图版.jpg");String fileName = "中国城市-导图版";// 公文格式页边距float marginLeft = Math.round(LEFT * CM_2_POUND);float marginRight = Math.round(RIGHT * CM_2_POUND);float marginTop = Math.round(TOP * CM_2_POUND);float marginBottom = Math.round(BOTTOM * CM_2_POUND);Document document = null;OutputStream os = null;try {// 设置response属性os = response.getOutputStream();response.setContentType("application/force-download");try {fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");} catch (UnsupportedEncodingException e) {e.printStackTrace();}response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".pdf");// 设置pdf页面大小document = new Document(PageSize.A4, marginLeft, marginRight, marginTop, marginBottom);document.addTitle(fileName);// 将图片输入流转换成字节数组byte[] bytes = FileUtil.readBytes(file);// 处理图片数据、居中Image img = Image.getInstance(bytes);img.setAlignment(Image.MIDDLE);// 处理图片缩放比率float contentWidth = PageSize.A4.getWidth() - marginLeft - marginRight;float contentHeight = PageSize.A4.getHeight() - marginTop - marginBottom;float imgWidth = img.getWidth();float imgHeight = img.getHeight();float widthPercent = contentWidth / imgWidth * 100;float heightPercent = contentHeight / imgHeight * 100;img.scalePercent(widthPercent < heightPercent ? widthPercent : heightPercent);// 将图片放入pdfPdfWriter.getInstance(document, os);document.open();document.newPage();document.add(img);} catch (Exception e) {e.printStackTrace();} finally {if (document != null) {document.close();}if (os != null) {try {os.close();} catch (IOException e) {e.printStackTrace();}}}}/*** 将图片输入流转换为pdf,然后在浏览器中下载* 模拟场景:从任何位置读取出图片输入流,然后在浏览器中下载*/@GetMapping("/stream2pdf")public void stream2pdf(HttpServletResponse response) throws FileNotFoundException {// 准备数据File file = ResourceUtils.getFile("classpath:中国城市-导图版.jpg");String fileName = "中国城市-导图版";// 公文格式页边距float marginLeft = Math.round(LEFT * CM_2_POUND);float marginRight = Math.round(RIGHT * CM_2_POUND);float marginTop = Math.round(TOP * CM_2_POUND);float marginBottom = Math.round(BOTTOM * CM_2_POUND);Document document = null;OutputStream os = null;try (InputStream inputStream = new FileInputStream(file)) {// 设置response属性os = response.getOutputStream();response.setContentType("application/force-download");try {fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");} catch (UnsupportedEncodingException e) {e.printStackTrace();}response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".pdf");// 设置pdf页面大小document = new Document(PageSize.A4, marginLeft, marginRight, marginTop, marginBottom);document.addTitle(fileName);// 将图片输入流转换成字节数组byte[] bytes = toByteArray(inputStream);// 处理图片数据、居中Image img = Image.getInstance(bytes);img.setAlignment(Image.MIDDLE);// 处理图片缩放比率float contentWidth = PageSize.A4.getWidth() - marginLeft - marginRight;float contentHeight = PageSize.A4.getHeight() - marginTop - marginBottom;float imgWidth = img.getWidth();float imgHeight = img.getHeight();float widthPercent = contentWidth / imgWidth * 100;float heightPercent = contentHeight / imgHeight * 100;img.scalePercent(widthPercent < heightPercent ? widthPercent : heightPercent);// 将图片放入pdfPdfWriter.getInstance(document, os);document.open();document.newPage();document.add(img);} catch (Exception e) {e.printStackTrace();} finally {if (document != null) {document.close();}if (os != null) {try {os.close();} catch (IOException e) {e.printStackTrace();}}}}/*** 将图片文件转换为pdf,然后在本地下载* 模拟场景:将图片文件或者图片流存储在本地*/@GetMapping("/img2LocalPdf")public String img2LocalPdf() throws FileNotFoundException {// 准备数据;注意:切换成你自己本地的图片File file = ResourceUtils.getFile("classpath:中国城市-导图版.jpg");String fileName = "中国城市-导图版";// 公文格式页边距float marginLeft = Math.round(LEFT * CM_2_POUND);float marginRight = Math.round(RIGHT * CM_2_POUND);float marginTop = Math.round(TOP * CM_2_POUND);float marginBottom = Math.round(BOTTOM * CM_2_POUND);// 创建临时文件File pdf = FileUtil.createTempFile(".pdf", true);Document document = null;OutputStream os = null;try (InputStream inputStream = new FileInputStream(file)) {// 设置response属性os = new FileOutputStream(pdf);// 设置pdf页面大小document = new Document(PageSize.A4, marginLeft, marginRight, marginTop, marginBottom);document.addTitle(fileName);// 将图片输入流转换成字节数组byte[] bytes = toByteArray(inputStream);// 处理图片数据、居中Image img = Image.getInstance(bytes);img.setAlignment(Image.MIDDLE);// 处理图片缩放比率float contentWidth = PageSize.A4.getWidth() - marginLeft - marginRight;float contentHeight = PageSize.A4.getHeight() - marginTop - marginBottom;float imgWidth = img.getWidth();float imgHeight = img.getHeight();float widthPercent = contentWidth / imgWidth * 100;float heightPercent = contentHeight / imgHeight * 100;img.scalePercent(widthPercent < heightPercent ? widthPercent : heightPercent);// 将图片放入pdfPdfWriter.getInstance(document, os);document.open();document.newPage();document.add(img);} catch (Exception e) {e.printStackTrace();} finally {if (document != null) {document.close();}if (os != null) {try {os.close();} catch (IOException e) {e.printStackTrace();}}}return pdf.getAbsolutePath();}// 将输入流转换成字节数组private static byte[] toByteArray(InputStream input) throws IOException {ByteArrayOutputStream output = new ByteArrayOutputStream();byte[] buffer = new byte[1024 * 4];int n = 0;while (-1 != (n = input.read(buffer))) {output.write(buffer, 0, n);}return output.toByteArray();}
}

三、测试链接

测试下载链接:
1、将base64编码图片字符串转换为pdf,然后在浏览器中下载
链接:http://127.0.0.1:8080/test/base642pdf2、将图片文件转换为pdf,然后在浏览器中下载
链接:http://127.0.0.1:8080/test/file2pdf3、将图片输入流转换为pdf,然后在浏览器中下载
链接:http://127.0.0.1:8080/test/stream2pdf4、将图片文件转换为pdf,然后在本地下载
链接:http://127.0.0.1:8080/test/img2LocalPdf

四、结果展示

在这里插入图片描述

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

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

相关文章

SpringDoc基础配置和集成OAuth2登录认证教程

本期内容 学会通过注解和Java代码的方式添加SpringDoc配置。在swagger-ui提供的页面上提供OAuth2登录认证&#xff0c;在集成Security的情况下便捷获取access_token并在请求时按照OAuth2规范携带。 为什么集成OAuth2登录认证&#xff1f; 现在大部分教程是在swagger-ui页面添…

Linux操作系统使用及C高级编程-D6-D8Linux shell脚本

利用shell命令写的脚本文件&#xff0c;后缀是.sh shell脚本是一个解释型语言&#xff0c;不需要编译&#xff0c;可直接执行 书写&#xff1a;vi test.sh #!/bin/bash&#xff1a;说明使用的是/bin目录下的bash 说明完后即可编写脚本文件 bash test.sh&#xff1a;运行文…

LDAP概念和原理介绍

相信对于许多的朋友来说&#xff0c;可能听说过LDAP&#xff0c;但是实际中对LDAP的了解和具体的原理可能还比较模糊&#xff0c;今天就从“什么是LDAP”、“LDAP的主要产品”、“LDAP的基本模型”、“LDAP的使用案例”四个方面来做一个介绍。 我们在开始介绍之前先来看几个问…

卷积神经网络(CNN)天气识别

文章目录 前期工作1. 设置GPU&#xff08;如果使用的是CPU可以忽略这步&#xff09;我的环境&#xff1a; 2. 导入数据3. 查看数据 二、数据预处理1. 加载数据2. 可视化数据3. 再次检查数据4. 配置数据集 三、构建CNN网络四、编译五、训练模型六、模型评估 前期工作 1. 设置GP…

【深度学习实验】网络优化与正则化(七):超参数优化方法——网格搜索、随机搜索、贝叶斯优化、动态资源分配、神经架构搜索

文章目录 一、实验介绍二、实验环境1. 配置虚拟环境2. 库版本介绍 三、优化算法0. 导入必要的库1. 随机梯度下降SGD算法a. PyTorch中的SGD优化器b. 使用SGD优化器的前馈神经网络 2.随机梯度下降的改进方法a. 学习率调整b. 梯度估计修正 3. 梯度估计修正&#xff1a;动量法Momen…

【JavaEE初阶】 CSS相关属性,元素显示模式,盒模型,弹性布局,Chrome 调试工具||相关讲解

文章目录 &#x1f38b;字体属性&#x1f6a9;设置字体&#x1f6a9;字体大小&#x1f6a9;字体粗细&#x1f6a9;文字样式 &#x1f38d;文本属性&#x1f6a9;文本颜色&#x1f388;认识 RGB&#x1f388;设置文本颜色 &#x1f6a9;文本对齐&#x1f6a9;文本装饰&#x1f6…

销售团队可以借助CRM系统做什么?

销售主管都想有一支效率高、质量高的销售团队&#xff0c;无论对于初创企业还是大型企业销售团队都是企业盈利的主力部门&#xff0c;直接为企业带了业绩。如何提升销售团队水平&#xff1f;离不开CRM系统的辅助&#xff0c;CRM软件能为销售团队提供哪些支持&#xff1f;下面我…

MISRA 2012学习笔记(5)-Rules 8.10

文章目录 Rules8.10 基本类型模型(The essential type model)8.10.1 原理8.10.2 基本类型(Essential type)Rule 10.1 操作数不得具有不适当的基本类型Rule 10.2 在加减法运算中&#xff0c;不得不当使用本质为字符类型的表达式Rule 10.3 表达式的值不得赋值给具有较窄基本类型或…

系列一、介绍

一、概述 官网&#xff1a; ThreadLocal用于提供线程内的局部变量&#xff0c;不同线程之间不会互相干扰&#xff0c;这种变量在线程的生命周期内起作用&#xff0c;减少同一个线程内多个函数或者组件之间一些公共变量传递的复杂度。 大白话&#xff1a; 线程并发&#xff1a;T…

编程怎么学习视频教程,编程实例入门教程,中文编程开发语言工具下载

编程怎么学习视频教程&#xff0c;编程实例入门教程&#xff0c;中文编程开发语言工具下载。 给大家分享一款中文编程工具&#xff0c;零基础轻松学编程&#xff0c;不需英语基础&#xff0c;编程工具可下载。 这款工具不但可以连接部分硬件&#xff0c;而且可以开发大型的软件…

Linux本地docker一键部署traefik+内网穿透工具实现远程访问Web UI管理界面

文章目录 前言1. Docker 部署 Trfɪk2. 本地访问traefik测试3. Linux 安装cpolar4. 配置Traefik公网访问地址5. 公网远程访问Traefik6. 固定Traefik公网地址 前言 Trfɪk 是一个云原生的新型的 HTTP 反向代理、负载均衡软件&#xff0c;能轻易的部署微服务。它支持多种后端 (D…

HINSTANCE是什么?

HINSTANCE 就是 HMODULE&#xff1a;

代码随想录 Day50 单调栈 LeetCodeT503 下一个最大元素II T42接雨水

前言 前面我们说到了单调栈的第一题,下一个最大元素I,其实今天的两道题都是对他的变种,知道第一个单调栈的思想能够想清楚,其实这道题是很简单的 考虑好三个状态,大于等于小于,其实对于前面这些题目只要细心的小伙伴就会发现其实小于和等于的处理是一样的都是直接入栈,只有大于…

prometheus基本介绍 prometheus和zabbix的区别 grafana可视化工具

一、 promethues概念prometheus介绍promethues的特点prometheus的工作原理prometheus的架构 二、promethues和zabbix的区别三、prometheus安装部署prometheus下载安装prometheus启动浏览器访问查看暴露指标将Prometheus配置为systemd管理 配置node_exporter监控项node_promethe…

redis cluster搭建

k8s部署 Redis Insight k8s部署redis集群_mob6454cc6c6291的技术博客_51CTO博客 占用的内存竟然这么小&#xff0c;才200M左右 随便选个节点进去&#xff0c;看能否连接上其他节点 redis-cli -h redis-cluster-v1-0.redis-cluster.project-gulimall.svc.cluster.local 再创建个…

表内容的操作(增删查改)【MySQL】

文章目录 表的 CRUDCreate&#xff08;增加&#xff09;插入记录插入冲突则更新记录替换记录 Retrieve&#xff08;查找&#xff09;查找记录指定表达式的别名为结果去重WHERE 子句运算符条件查询区间查询模糊查询空值查询 对结果排序筛选分页结果 Update&#xff08;修改&…

【Java程序员面试专栏 算法训练篇】二叉树高频面试算法题

一轮的算法训练完成后,对相关的题目有了一个初步理解了,接下来进行专题训练,以下这些题目就是二叉树相关汇总的高频题目 遍历二叉树 遍历二叉树,分为递归和迭代两种方式,递归类似于DFS,迭代类似于BFS,【算法训练-二叉树 一】【遍历二叉树】前序遍历、中序遍历、后续遍…

解决在pycharm中使用matplotlib画图问题

第一&#xff0c;再导入包后直接绘图出现&#xff1a; AttributeError: module backend_interagg has no attribute FigureCanvas表明版本不兼容&#xff0c;我们需要加入&#xff1a;matplotlib.use(‘TkAgg’) 导入函数就变成了&#xff1a; import matplotlib matplotlib.…

clickhouse分布式之弹性扩缩容的故事

现状 社区不支持喔&#xff0c;以后也不会有了。曾经尝试过&#xff0c;难道是是太难了&#xff0c;无法实现吗&#xff1f;因为他们企业版支持了&#xff0c;可能是利益相关吧&#xff0c;谁知道呢&#xff0c;毕竟开源也要赚钱&#xff0c;谁乐意一直付出没有回报呢。 社区…

桌面运维。

Windows运行命令&#xff1a; color 01/02切换字符颜色cls 清屏ipconfig 设备的ip信息ipconfig /all 设备ip的所有信息 破解系统密码&#xff1a; 进PE系统&#xff0c;使用里面的工具破解 vmware workstation安装 网卡 网卡&#xff1a;ncpa.cpl window远程控制 mstsc …