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.mzph.cn/news/152083.shtml

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

相关文章

【计算机网络笔记】DHCP协议

系列文章目录 什么是计算机网络&#xff1f; 什么是网络协议&#xff1f; 计算机网络的结构 数据交换之电路交换 数据交换之报文交换和分组交换 分组交换 vs 电路交换 计算机网络性能&#xff08;1&#xff09;——速率、带宽、延迟 计算机网络性能&#xff08;2&#xff09;…

信息机房监控系统(动环辅助监控系统)

信息机房监控系统是一个综合性的系统&#xff0c;用于对机房的所有设备及其环境进行集中监控和管理。这种系统主要针对机房的各个子系统进行监控&#xff0c;包括动力系统、环境系统、消防系统、保安系统、网络系统等。 依托电易云-智慧电力物联网&#xff0c;以下是信息机房监…

037、目标检测-算法速览

之——常用算法速览 目录 之——常用算法速览 杂谈 正文 1.区域卷积神经网络 - R-CNN 2.单发多框检测SSD&#xff0c;single shot detection 3.yolo 杂谈 快速过一下目标检测的各类算法。 正文 1.区域卷积神经网络 - R-CNN region_based CNN&#xff0c;奠基性的工作。…

AI自动写代码:GitHub copilot插件在Idea的安装和使用教程

GitHub Copilot 是微软与OpenAI共同推出的一款AI编程工具&#xff0c;基于GitHub及其他网站的源代码&#xff0c;根据上文提示为程序员自动编写下文代码&#xff0c;可以极大地提高编写代码的效率。 先看看ChatGpt是怎么回答Copilot的功能特点&#xff1a; 给大家简单提取一…

什么是缓存雪崩、击穿、穿透?

背景 数据一般是存储于数据库中&#xff0c;数据库中的数据都是存在磁盘上的&#xff0c;磁盘读写的速度相较于内存或者CPU中的寄存器来说是非常慢的了。 如果用户的请求都直接访问数据库的话&#xff0c;请求数量一上来&#xff0c;数据库很容易就崩溃了&#xff0c;所以为了…

Visio免费版!Visio国产平替软件,终于被我找到啦!

作为一个职场人士&#xff0c;我经常需要绘制各种流程图和图表&#xff0c;而Visio一直是我使用的首选工具。但是&#xff0c;随着公司的发展和工作的需要&#xff0c;我逐渐发现了Visio的优点和不足。 首先&#xff0c;让我们来看看Visio的优点。Visio是一个专业的流程图和图…

注册表单mvc 含源代码

总结 jsp给我们的ControllerServlet.java,ControllerServlet.java获取参数,信息封装给RegisterFormBean.java的对象看是否符合格式,符合格式再信息封装给UserBean对象,调用Dbutil插入方法查重.]]要创建一个user集合成功跳哪个界面,打印信息注意什么时候要加getsession失败跳哪…

VS+Qt+C++ Yolov8物体识别窗体程序onnx模型

程序示例精选 VSQtC Yolov8物体识别窗体程序onnx模型 如需安装运行环境或远程调试&#xff0c;见文章底部个人QQ名片&#xff0c;由专业技术人员远程协助&#xff01; 前言 这篇博客针对《VSQtC Yolov8物体识别窗体程序onnx模型》编写代码&#xff0c;代码整洁&#xff0c;规…

Linux远程工具专家推荐(二)

8. Apache Guacamole Apache Guacamole 是一款免费开源的无客户端远程桌面网关&#xff0c;支持 VNC、RDP 和 SSH 等标准协议。无需插件或客户端软件&#xff1b;只需使用 HTML5 Web 应用程序&#xff08;例如 Web 浏览器&#xff09;即可。 这意味着您的计算机的使用不受任何一…

【开源】基于Vue和SpringBoot的民宿预定管理系统

项目编号&#xff1a; S 058 &#xff0c;文末获取源码。 \color{red}{项目编号&#xff1a;S058&#xff0c;文末获取源码。} 项目编号&#xff1a;S058&#xff0c;文末获取源码。 目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 用例设计2.2 功能设计2.2.1 租客角色…

【监控系统】日志可视化监控体系ELK搭建

1.ELK架构是什么 ELK是ElasticsearchLogstashKibana的简称。 Elasticsearch是一个开源的分布式搜索和分析引擎&#xff0c;可以用于全文检索、结构化检索和分析&#xff0c;它构建在Lucene搜索引擎库之上&#xff0c;是当前使用较为广泛的开源搜索引擎之一。 Logstash是一个…

Databend 开源周报第 120 期

Databend 是一款现代云数仓。专为弹性和高效设计&#xff0c;为您的大规模分析需求保驾护航。自由且开源。即刻体验云服务&#xff1a;https://app.databend.cn 。 Whats On In Databend 探索 Databend 本周新进展&#xff0c;遇到更贴近你心意的 Databend 。 使用自定义 CON…

常见Web安全

一.Web安全概述 以下是百度百科对于web安全的解释&#xff1a; Web安全&#xff0c;计算机术语&#xff0c;随着Web2.0、社交网络、微博等等一系列新型的互联网产品的诞生&#xff0c;基于Web环境的互联网应用越来越广泛&#xff0c;企业信息化的过程中各种应用都架设在Web平台…

MySQL 之多版本并发控制 MVCC

MySQL 之多版本并发控制 MVCC 1、MVCC 中的两种读取方式1.1、快照读1.2、当前读 2、MVCC实现原理之 ReadView2.1、隐藏字段2.2、ReadView2.3、读已提交和可重复读隔离级别下&#xff0c;产生 ReadView 时机的区别 3、MVCC 解决幻读4、总结 MVCC&#xff08;多版本并发控制&…

springboot引入第三方jar包放到项目目录中,添加web.xml

参考博客&#xff1a;https://www.cnblogs.com/mask-xiexie/p/16086612.html https://zhuanlan.zhihu.com/p/587605618 1、在resources目录下新建lib文件夹&#xff0c;将jar包放到lib文件夹中 2、修改pom.xml文件 <dependency><groupId>com.lanren312</grou…

网络运维与网络安全 学习笔记2023.11.18

网络运维与网络安全 学习笔记 第十九天 今日目标 冲突域和交换机工作原理、广播域和VLAN原理 VLAN配置、TRUNK原理与配置、HYBRID原理与配置 冲突域和交换机工作原理 冲突域概述 定义 网络设备发送的数据&#xff0c;产生冲突的区域&#xff08;范围&#xff09; 对象 “数…

【Java 进阶篇】Ajax 实现——JQuery 实现方式 `ajax()`

嗨&#xff0c;亲爱的读者们&#xff01;欢迎来到这篇关于使用 jQuery 中的 ajax() 方法进行 Ajax 请求的博客。在前端开发中&#xff0c;jQuery 提供了简便而强大的工具&#xff0c;其中 ajax() 方法为我们处理异步请求提供了便捷的解决方案。无需手动创建 XMLHttpRequest 对象…

利用AlphaMissense准确预测蛋白质组范围内的错义变体效应

Editor’s summary 蛋白质中单个氨基酸的变化有时影响不大&#xff0c;但通常会导致蛋白质折叠、活性或稳定性方面的问题。只有一小部分变体进行了实验研究&#xff0c;但有大量的生物序列数据适合用作机器学习方法的训练数据。程等人开发了AlphaMissense&#xff0c;这是一种…

浅析ChatGPT中涉及到的几种技术点

❤️觉得内容不错的话&#xff0c;欢迎点赞收藏加关注&#x1f60a;&#x1f60a;&#x1f60a;&#xff0c;后续会继续输入更多优质内容❤️ &#x1f449;有问题欢迎大家加关注私戳或者评论&#xff08;包括但不限于NLP算法相关&#xff0c;linux学习相关&#xff0c;读研读博…

航测三维实景:创造更加真实和精细的虚拟环境

航测三维实景&#xff1a;创造更加真实和精细的虚拟环境 航测三维实景技术是一项以航空摄影测量为基础&#xff0c;结合计算机图像处理和显示技术的高精度三维实景重建方法。它以其独特的视角和真实感十足的体验&#xff0c;已经广泛应用于城市规划、土地资源管理、自然资源调查…