基于poi包的流式文件和版式文件操作工具

说明

该工具类是基于poi包的流式文件(如doc、excel等)和版式文件(如pdf、ofd等)的操作工具类。
因为自己在开发相关功能的时候踩过一些坑,网上也很多例子都不适用,不是jar版本不对,要么就是各个jar不兼容,要么就是某些属性过时等等问题,所以在这里整合了一下。

相关链接

使用前提

<dependency>
    <groupId>com.aspose.cells</groupId>
    <artifactId>cells-8.5.2 </artifactId>
    <scope>system</scope>
    <systemPath>${basedir}/lib/aspose-cells-8.5.2.jar</systemPath>
    <version>8.5.2</version>
</dependency>
<dependency>
    <groupId>com.aspose.words</groupId>
    <artifactId>words-15.8.0-jdk16</artifactId>
    <scope>system</scope>
    <systemPath>${basedir}/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
    <version>15.8.0</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>com.deepoove</groupId>
    <artifactId>poi-tl</artifactId>
    <version>1.8.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>

其中,cells-8.5.2需要在src同级的lib目录下添加下面的jar包:
相关jar包和配置
在这里插入图片描述
同理,words相关的jar包也是放在lib目录下。

代码

PS:因为这是实际项目需要到的功能才去编写的(针对本人遇到的问题整合的功能点),所以只记录了使用过的功能,后续会更新其他功能…

目前已经整合好的功能

  • excel转pdf
  • pdf添加水印
  • word转图片
  • 持续更新中…
import com.aspose.cells.*;
import com.aspose.words.ImageSaveOptions;
import com.aspose.words.SaveFormat;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.*;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 基于poi包的流式文件和版式文件操作工具
 */
public class PoiUtil {

    /**
     * 获取license
     * @return
     */
    public static boolean getLicense(){
        boolean result = false;
        try {
            InputStream is = PoiUtil.class.getClassLoader().getResourceAsStream("/file/license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        }catch (Exception e){
            System.out.println(e);
        }
        return result;
    }

    /**
     * excel转pdf
     * @param excelFilePath excel文件全路径
     * @param pdfFilePath pdf文件全路径
     */
    public static boolean excelToPdf(String excelFilePath, String pdfFilePath){
        if (!getLicense()){
            return false;
        }
        try {
            //创建excel工作簿
            Workbook wb = new Workbook(excelFilePath);
            //设置纸张水平居中打印
            Worksheet worksheet = wb.getWorksheets().get(0);
            PageSetup pageSetup = worksheet.getPageSetup();
            pageSetup.setCenterHorizontally(true);
            //设置保存PDF操作参数
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            //pdfSaveOptions.setOnePagePerSheet(false);//把内容放在一张PDF 页面上
            FileOutputStream fileOS = new FileOutputStream(new File(pdfFilePath));
            wb.save(fileOS, pdfSaveOptions);
            fileOS.close();
            return true;
        }catch (Exception e){
            System.out.println(e);
        }
        return false;
    }

    /**
     * pdf添加水印
     * @param pdfFilePath pdf原文件全路径
     * @param outPutFilePath 添加水印后的文件全路径
     * @param waterMark 水印
     * @return
     */
    public static boolean addWaterMarkToPdf(String pdfFilePath, String outPutFilePath, String waterMark){
        try {
            PdfReader reader = new PdfReader(pdfFilePath);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outPutFilePath));
            //这里的字体设置比较关键,这个设置是支持中文的写法
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体
            int total = reader.getNumberOfPages() + 1;
            PdfContentByte under;
            com.itextpdf.text.Rectangle pageRect = null;

            for (int i = 1; i < total; i++) {
                pageRect = stamper.getReader().getPageSizeWithRotation(i);
                int yNum = (int)(pageRect.getHeight() / (waterMark.length() * 15));
                int xNum = (int)(pageRect.getWidth() / (waterMark.length() * 15));
                int px = waterMark.length() * 25;
                //x,y为水印的坐标
                float x = 0l;
                float y = 0l;
                for (int j = 0; j < yNum; j++){
                    for (int r = 0; r < xNum; r++){

                        x = px * r;
                        y = px * j;
                        // 获得PDF最顶层
                        under = stamper.getOverContent(i);
                        under.saveState();
                        // set Transparency
                        PdfGState gs = new PdfGState();
                        // 设置透明度为0.5
                        gs.setFillOpacity(0.4f);
                        under.setGState(gs);
                        under.beginText();
                        under.setFontAndSize(base, 15);
                        under.setColorFill(BaseColor.GRAY);
                        // 水印文字成45度角倾斜
                        under.showTextAligned(Element.ALIGN_CENTER, waterMark, x, y, 45);
                        // 添加水印文字
                        under.endText();
                        under.setLineWidth(1f);
                        under.stroke();
                        under.restoreState();
                    }
                }
            }
            stamper.close();
            reader.close();
            return true;
        }catch (Exception e){
            System.out.println(e);
        }
        return false;
    }

    /**
     * word转图片
     * @param wordFile word文件的输入流
     * @param imageOutPutPath 生成图片保存在的文件目录
     * @return
     */
    public static boolean wordToImage(InputStream wordFile, String imageOutPutPath){
        if (!getLicense()){
            return false;
        }
        try {
            com.aspose.words.Document doc = new com.aspose.words.Document(wordFile);
            ImageSaveOptions options = new ImageSaveOptions(SaveFormat.JPEG);
            options.setPrettyFormat(true);
            options.setUseAntiAliasing(true);
            options.setUseHighQualityRendering(true);
            int pageCount = doc.getPageCount();

            List<BufferedImage> pageImageList = new ArrayList<BufferedImage>();
            for (int i = 0; i < pageCount; i++) {
                ByteArrayOutputStream outps = new ByteArrayOutputStream();
                options.setPageIndex(i);
                doc.save(outps, options);
                ImageInputStream imageInputStream = ImageIO.createImageInputStream(parse(outps));
                pageImageList.add(ImageIO.read(imageInputStream));
            }
            for (int i = 0; i < pageImageList.size(); i++) {
                byte[] bytes = imageToBytes(pageImageList.get(i));
                ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
                inputstreamToFile(stream, imageOutPutPath + File.separator + String.valueOf(i) + ".jpeg");
            }
            return true;
        }catch (Exception e){
            System.out.println(e);
        }
        return false;
    }

    /**
     * ByteArrayOutputStream转ByteArrayInputStream
     * @param out
     * @return
     */
    public static ByteArrayInputStream parse(OutputStream out) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            baos = (ByteArrayOutputStream) out;
            ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
            return swapStream;
        }catch (Exception e){
            System.out.println(e);
        }
        return null;
    }

    /**
     * BufferedImage转byte
     * @param bImage
     * @return
     */
    private static byte[] imageToBytes(BufferedImage bImage) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(bImage, "jpeg", out);
        } catch (IOException e) {
            //log.error(e.getMessage());
        }
        return out.toByteArray();
    }

    /**
     * inputStream转File
     * @param input 文件的输入流
     * @param fileName 文件名
     * @return file
     */
    private static File inputstreamToFile(InputStream input, String filePath){
        File file = null;
        try {
            file = new File(filePath);
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = input.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            input.close();
            return file;
        }catch (Exception e){
            System.out.println(e);
        }
        return file;
    }
}

后续有新的功能开发,也会更新在这里,需要的伙伴可以收藏起来喔!
更新记录:

  • 2022-09-05:第一次发布该文章,增加了excel转pdfpdf添加水印word转图片
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
注:下文中的 *** 代表文件名中的组件名称。 # 含: 中文-英文对照文档:【***-javadoc-API文档-中文(简体)-英语-对照版.zip】 jar下载地址:【***.jar下载地址(官方地址+国内镜像地址).txt】 Maven依赖:【***.jar Maven依赖信息(可用于项目pom.xml).txt】 Gradle依赖:【***.jar Gradle依赖信息(可用于项目build.gradle).txt】 源代码下载地址:【***-sources.jar下载地址(官方地址+国内镜像地址).txt】 # 本文件关键字: 中文-英文对照文档,中英对照文档,java,jar,Maven,第三方jar,组件,开源组件,第三方组件,Gradle,中文API文档,手册,开发手册,使用手册,参考手册 # 使用方法: 解压 【***.jar中文文档.zip】,再解压其中的 【***-javadoc-API文档-中文(简体)版.zip】,双击 【index.html】 文件,即可用浏览器打开、进行查看。 # 特殊说明: ·本文档为人性化翻译,精心制作,请放心使用。 ·本文档为双语同时展示,一行原文、一行译文,可逐行对照,避免了原文/译文来回切换的麻烦; ·有原文可参照,不再担心翻译偏差误导; ·边学技术、边学英语。 ·只翻译了该翻译的内容,如:注释、说明、描述、用法讲解 等; ·不该翻译的内容保持原样,如:类名、方法名、名、类型、关键字、代码 等。 # 温馨提示: (1)为了防止解压后路径太长导致浏览器无法打开,推荐在解压时选择“解压到当前文件夹”(放心,自带文件夹,文件不会散落一地); (2)有时,一套Java组件会有多个jar,所以在下载前,请仔细阅读本篇描述,以确保这就是你需要的文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是哈猿啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值