登录  /  注册
首页 > Java > Java入门 > 正文

利用java实现一个图片转PDF文件工具

王林
发布: 2020-08-27 16:05:23
转载
3458人浏览过

利用java实现一个图片转PDF文件工具

出于某些需求需要将一张简单的图片转换为PDF的文件格式,因此自己动手写了一个图片转换PDF的系统,现在将该系统分享在这里,供大家参考。

(学习视频推荐:java课程

具体代码:

引入依赖:

<!--该项目以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>
<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文件">
        </form>
    </div>
</body>
<script>
    function allowFileType() {
        let file = document.getElementById("file").files[0];
        let fileName = file.name;
        console.log(fileName)
        let fileSize = file.size;
        console.log(fileSize)
        let suffix = fileName.substring(fileName.lastIndexOf("."),fileName.length);
        if(&#39;.jpg&#39; != suffix && &#39;.png&#39; != suffix) {
            alert("目前只允许传入.jpg或者.png格式的图片!");
            return false;
        }
        if(fileSize > 2*1024*1024) {
            alert("上传图片不允许超过2MB!");
            return false;
        }
        return true;
    }
</script>
</html>
登录后复制

(推荐教程:java入门教程

控制层接口

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);
    }
}
登录后复制

实现效果:

19973d4a8897fe5b21a3ca1b8019457.png

以上就是利用java实现一个图片转PDF文件工具的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:csdn网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号