Java实现图片转换PDF文件
文章目录
- 引入依赖
- 前端页面
- 控制层接口
- PDF工具类
- 页面效果
最近因为一些事情,需要将一张简单的图片转换为PDF的文件格式,在网上找了一些工具,但是这些工具不是需要注册账号,就是需要下载软件。
而对于只是转换一张图片的情况下,这些操作显然是非常繁琐的,所以作者就直接使用Java写了一个图片转换PDF的系统,现在将该系统分享在这里。
引入依赖
<!--该项目以SpringBoot为基础搭建-->
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.4.RELEASE</version><relativePath/>
</parent><dependencies><!--SpringMVC的依赖,方便我们可以获取前端传递过来的文件信息--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--ITextPdf,操作PDF文件的工具类--><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.4.2</version></dependency>
</dependencies>
前端页面
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>图片转换Pdf</title><style>.submitButton {margin-top: 20px;margin-left: 150px;background-color: #e37e10;border-radius: 10px;border: 1px solid #ff8300;}</style>
</head>
<body><div style="text-align: center"><h1>图片转换pdf工具</h1><form action="/pdf/image/to" enctype="multipart/form-data" method="post" onsubmit="return allowFileType()"><input type="file" id="file" name="file" placeholder="请选择图片" onchange="allowFileType()" style="border: 1px solid black;"><br><input type="submit" value="一键转换pdf文件" class="submitButton"></form></div>
</body>
<script>function allowFileType() {let file = document.getElementById("file").files[0];let fileName = file.name;let fileSize = file.size;let suffix = fileName.substring(fileName.lastIndexOf("."),fileName.length).toLowerCase();if('.jpg' != suffix && '.png' != suffix) {alert("目前只允许传入.jpg或者.png格式的图片!");return false;}if(fileSize > 2*1024*1024) {alert("上传图片不允许超过2MB!");return false;}return true;}
</script>
</html>
控制层接口
package com.hrp.controller;import com.hrp.util.PdfUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;/*** @description: 用于处理Pdf相关的请求*/
@Controller
@RequestMapping("pdf")
public class PdfController {@PostMapping("image/to")public void imageToPdf(@RequestParam("file") MultipartFile file,HttpServletResponse response) throws Exception{PdfUtils.imageToPdf(file,response);}}
PDF工具类
package com.hrp.util;import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;/*** @description: pdf相关的工具类*/
@Component
public class PdfUtils {/*** 图片转换PDF的公共接口** @param file SpringMVC获取的图片文件* @param response HttpServletResponse* @throws IOException IO异常* @throws DocumentException PDF文档异常*/public static void imageToPdf(MultipartFile file, HttpServletResponse response) throws IOException, DocumentException {File pdfFile = generatePdfFile(file);downloadPdfFile(pdfFile, response);}/*** 将图片转换为PDF文件** @param file SpringMVC获取的图片文件* @return PDF文件* @throws IOException IO异常* @throws DocumentException PDF文档异常*/private static File generatePdfFile(MultipartFile file) throws IOException, DocumentException {String fileName = file.getOriginalFilename();String pdfFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf";Document doc = new Document(PageSize.A4, 20, 20, 20, 20);PdfWriter.getInstance(doc, new FileOutputStream(pdfFileName));doc.open();doc.newPage();Image image = Image.getInstance(file.getBytes());float height = image.getHeight();float width = image.getWidth();int percent = getPercent(height, width);image.setAlignment(Image.MIDDLE);image.scalePercent(percent);doc.add(image);doc.close();File pdfFile = new File(pdfFileName);return pdfFile;}/**** 用于下载PDF文件** @param pdfFile PDF文件* @param response HttpServletResponse* @throws IOException IO异常*/private static void downloadPdfFile(File pdfFile, HttpServletResponse response) throws IOException {FileInputStream fis = new FileInputStream(pdfFile);byte[] bytes = new byte[fis.available()];fis.read(bytes);fis.close();response.reset();response.setHeader("Content-Type", "application/pdf");response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(pdfFile.getName(), "UTF-8"));OutputStream out = response.getOutputStream();out.write(bytes);out.flush();out.close();}/*** 等比压缩,获取压缩百分比** @param height 图片的高度* @param weight 图片的宽度* @return 压缩百分比*/private static int getPercent(float height, float weight) {float percent = 0.0F;if (height > weight) {percent = PageSize.A4.getHeight() / height * 100;} else {percent = PageSize.A4.getWidth() / weight * 100;}return Math.round(percent);}
}
页面效果
这就是系统启动之后的页面效果,虽然页面比较简陋,但是功能却没有任何折扣,有兴趣或者有需要的同学可以自己搭建一下,试一试图片转换PDF文件的效果。
注意:作者自己测试了一下,普通图片基本是没有问题的,但是遇到一些特殊的图片可能会出现异常,毕竟只是一个比较简单的图片转换PDF系统,难以兼容所有图片。
Java实现图片转换PDF文件相关推荐
- java图片转换pdf_Java实现图片转换PDF文件的示例代码
最近因为一些事情,需要将一张简单的图片转换为PDF的文件格式,在网上找了一些工具,但是这些工具不是需要注册账号,就是需要下载软件. 而对于只是转换一张图片的情况下,这些操作显然是非常繁琐的,所以作者就 ...
- 将HTML文件转换为PDF文件(Thymeleaf模板转换,简单解决中文问题, 解决HTML带图片转换PDF文件问题)
将HTML文件转换为PDF文件 一.导入依赖 <!-- itext生成Pdf --> <dependency><groupId>com.itextpdf</g ...
- java实现图片转pdf文件
2021年新年快乐!在此祝大家代码无bug~~~ 由于我是驻场开发,前段时间问我要个证件扫描件的PDF文件,我一想,现在转换pdf文件是要花钱的啊,这是我能忍受的了的吗!!! 答案当然是不能啊,我的贫 ...
- 图片批量转换pdf文件
文章目录 1. 依赖 2. 工具类抽取 1. 依赖 <!--图片转换pdf Start--><!-- https://mvnrepository.com/artifact/com.i ...
- Python用img2pdf库批量转换图片为PDF文件
Python用img2pdf库批量转换图片为PDF文件 import os #导入os库 import time #导入时间库生成时间戳 import img2pdf #导入img2pdf库, 安装命 ...
- java使用swfTools将pdf文件转换swf文件
转载请表明出处 https://blog.csdn.net/Amor_Leo/article/details/89388851 谢谢 java使用swfTools将pdf文件转换swf文件 swfTo ...
- PDF技术(四)-Java实现Html转PDF文件
html转换为pdf的关键技术是如何处理网页中复杂的css样式.以及中文乱码处理. 各实现对比表 于Windows平台进行测试: 基于IText 基于FlyingSaucer 基于WKHtmlToPd ...
- java实现写字板对pdf文件签名
java实现写字板对pdf文件签名 思路 首先明白写字板签名完输出的是base64的图片,剩下的就是将此图片插入到pdf文件中,实现此步骤的技术很多,可以用itex5但是为了实现与其他数据一起动态插入 ...
- tensor转换为图片_为大家介绍图片转换pdf的经验总结!你找对方法了吗?
图片转换pdf怎么做?不少朋友们在学习和工作中都发现了PDF这种文件格式似乎格外的吃香,你收到的很多培训文件和在网上搜罗的一些学习文件,全部都是PDF格式,PDF格式这么吃香?甚至有人让你把图片都转成 ...
最新文章
- vmware虚拟机异常关闭处理
- 解決 IE10 浏览器无法使用 ASP.NET From 验证登录的问题
- 解析全局配置文件的时候,做了什么?
- SAP CRM Opportunity订单的文档流Document Flow的一些变体variant
- oracle对查询结果求和_Oracle 闪回技术详解
- uni-app开发:(源码级别)uni-badge样式修改(自定义插槽)
- 消息称字节跳动将推迟IPO 官方回应:尚无上市计划
- Python+KNN算法判断单词相似度小案例
- 2.13 向量化 logistic 回归
- Scorm标准学习——Scorm RTE API与数据模型
- 科学计算机统计模式中中间数据输错怎么办,科学计算器在统计功能中如何清除以前不需要的数据?...
- 「创作之秋」| 参赛成员- 获奖名单(参与奖)
- 数据结构教程(详细又简单——C语言实现)
- 上海航芯|推出基于ACX200T的V2X解决方案
- 泛微OA e-cology WorkflowCenterTreeData前台接口SQL注入漏洞复现
- 内网穿透技术有哪些(经验分享)
- UT-Exynos4412 三星ARM四核旗舰开发平台android4.0体验-13串口功能调试
- C#启动打印机打印文件
- 将Excel中的数据导入html以及将html表格数据导出Excel
- 自定义报表是这样实现的