Java将Word/Excel转换成PDF—aspose工具

最近做了一个项目,客户需求:将Word/Excel转换成PDF。在网上找了找了很多资料,最后整理了最好用、最简单的一版,方便自己后续使用。
(测试案例下载地址:点击下载

一、word转pdf简单介绍

1、引入aspose-words-15.8.0-jdk16 jar
使用aspose需要在项目里加入一个license.xml,不然生成的pdf会有水印:

lib:存放Jar包的位置。

2、在项目resource文件夹下添加license.xml许可文件

<License>
  <Data>
    <Products>
      <Product>Aspose.Total for Java</Product>
      <Product>Aspose.Words for Java</Product>
    </Products>
    <EditionType>Enterprise</EditionType>
    <SubscriptionExpiry>20991231</SubscriptionExpiry>
    <LicenseExpiry>20991231</LicenseExpiry>
    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
  </Data>
  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>

 3、word转pdf工具类:

package xxx;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * 由于ASPOSE比较吃内存,操作大一点的文件就会堆溢出,所以请先设置好java虚拟机参数:-Xms512m -Xmx512m(参考值)<br>
 */
public class WordToPdfUtil {

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

    /**
     * 支持DOC, DOCX, OOXML, RTF, HTML, OpenDocument, PDF, EPUB, XPS, SWF等相互转换<br>
     *
     * @param wordfilePath [原始excel路径]
     * @param pdfFilePath  [输出路径]
     */
    public static Boolean wordConvertToPdf(String wordfilePath, String pdfFilePath) {
        // 验证License
        if (!getLicense()) {
            return false;
        }

        try {
            // 原始word路径
            Document doc = new Document(wordfilePath);
            // 输出路径
            File pdfFile = new File(pdfFilePath);
            FileOutputStream fileOS = new FileOutputStream(pdfFile);
            doc.save(fileOS, SaveFormat.PDF);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}

4、测试Demo:

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import xxx.WordToPdfUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 *  @author: xxxx
 *  @Date: 2020/12/24 15:10
 *  @Description: excel转pdf测试用例
 */
public class WordToPdfTest {

    public static void main(String[] args) {
        String sourcePath = "D:\\CYD\\公司领导测评操作手册20201205.docx";
        String targetPath = "D:\\test.pdf";
        // 验证License
        if (!WordToPdfUtil.getLicense()) {
            return;
        }

        long old = System.currentTimeMillis();
        if (WordToPdfUtil.wordConvertToPdf(sourcePath,targetPath)) {
            long now = System.currentTimeMillis();
            System.out.println("word转pdf成功,共耗时:" + ((now - old) / 1000.0) + "秒");
        }

    }
}

 5、consol控制台最终运行结果:


 二、Excel转PDF简单介绍

1、引入aspose-cells-8.5.2 jar

Excel转PDF同Word转PDF一样,引入相对应的jar包和license.xml许可文件 

2、在项目resource文件夹下添加license.xml许可文件(代码同word中的license.xml)

3、excel转pdf工具类:

package xxx;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import com.aspose.cells.License;
import com.aspose.cells.SaveFormat;
import com.aspose.cells.Workbook;

/**
 * 由于ASPOSE比较吃内存,操作大一点的文件就会堆溢出,所以请先设置好java虚拟机参数:-Xms512m -Xmx512m(参考值)<br>
 */
public class ExcelToPdfUtil {

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

    /**
     * 支持DOC, DOCX, OOXML, RTF, HTML, OpenDocument, PDF, EPUB, XPS, SWF等相互转换<br>
     *
     * @param excelfilePath [原始excel路径]
     * @param pdfFilePath   [输出路径]
     */

    public static Boolean excelConvertToPdf(String excelfilePath, String pdfFilePath) {
        // 验证License
        if (!getLicense()) {
            return false;
        }

        try {
            // 原始excel路径
            Workbook wb = new Workbook(excelfilePath);
            // 输出路径
            File pdfFile = new File(pdfFilePath);
            FileOutputStream fileOS = new FileOutputStream(pdfFile);
            wb.save(fileOS, SaveFormat.PDF);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}

4、测试Demo:

import com.aspose.cells.License;
import com.aspose.cells.SaveFormat;
import com.aspose.cells.Workbook;
import xxx.ExcelToPdfUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 *  @author: xxxx
 *  @Date: 2020/12/24 15:10
 *  @Description: excel转pdf测试用例
 */
public class ExcelToPdfTest {

    public static void main(String[] args) {
        String sourcePath = "D:\\test.xlsx";
        String targetPath = "D:\\test.pdf";
        // 验证License
        if (!ExcelToPdfUtil.getLicense()) {
            return;
        }

        long old = System.currentTimeMillis();
        if (ExcelToPdfUtil.excelConvertToPdf(sourcePath, targetPath)) {
            long now = System.currentTimeMillis();
            System.out.println("Excel转Pdf成功,共耗时:" + ((now - old) / 1000.0) + "秒");
        }

    }
}

后续更多方法有待更新......


三、pdf加水印

这里没有采用aspose下的pdf,不太好用,不过测试案例中有用例,感兴趣的同学可以自行下载学习。

对于pdf加水印,我采用 Spire 组件进行处理的。(具体可参考:Spire组件官方文档

1.pom文件引入Spire组件需要用到的依赖

<dependencies>

        <!--word文件转PDF以及水印-->
        <dependency>
            <groupId>e-iceblue</groupId>
            <artifactId>spire.doc.free</artifactId>
            <version>3.9.0</version>
        </dependency>
        <dependency>
            <groupId>e-iceblue</groupId>
            <artifactId>spire.pdf.free</artifactId>
            <version>3.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>

    </dependencies>

2.对pdf加水印的工具类:

package xxx.util;

import com.aspose.pdf.*;
import com.lowagie.text.pdf.PdfReader;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.*;

public class PDFWatermark {

    /**
     * @param page      要添加水印的页面
     * @param imageFile 水印图片路径
     */
    public static void AddImageWatermark(PdfPageBase page, String imageFile) {
        page.setBackgroundImage(imageFile);
        Rectangle2D rect = new Rectangle2D.Float();
        rect.setFrame(page.getClientSize().getWidth() / 2 - 100, page.getClientSize().getHeight() / 2 - 100, 200, 200);
        page.setBackgroundRegion(rect);
    }

    /**
     * @param page          要添加水印的页面
     * @param textWatermark 水印文字
     */
    public static void AddTextWatermark(PdfPageBase page, String textWatermark) {
        Dimension2D dimension2D = new Dimension();
        dimension2D.setSize(page.getCanvas().getClientSize().getWidth() / 3, page.getCanvas().getClientSize().getHeight() / 3);
        PdfTilingBrush brush = new PdfTilingBrush(dimension2D);
        brush.getGraphics().setTransparency(0.3F);
        brush.getGraphics().save();
        brush.getGraphics().translateTransform((float) brush.getSize().getWidth() / 2, (float) brush.getSize().getHeight() / 2);
        brush.getGraphics().rotateTransform(-45);
        brush.getGraphics().drawString(textWatermark, new PdfTrueTypeFont(new Font("新宋体", Font.PLAIN, 30), true), PdfBrushes.getGray(), 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
        brush.getGraphics().restore();
        brush.getGraphics().setTransparency(1);
        Rectangle2D loRect = new Rectangle2D.Float();
        loRect.setFrame(new Point2D.Float(0, 0), page.getCanvas().getClientSize());
        page.getCanvas().drawRectangle(brush, loRect);
    }

    /**
     * @param sourceFile 需要重新重命名的图片路径
     * @param targetPath 重命名的图片路径保存地址
     */
    public static void fileCopyRightWay(String sourceFile, String targetPath) {
        try {
            //读取源地址文件的字节流
            FileInputStream in = new FileInputStream(sourceFile);
            FileOutputStream out = new FileOutputStream(targetPath);
            byte[] bs = new byte[1026];
            int count = 0;
            while ((count = in.read(bs, 0, bs.length)) != -1) {
                //把读取到的字节流写入到目的地址的文件里面
                out.write(bs, 0, count);
            }
            //刷新下输出流
            out.flush();
            // 关闭输入流和输出流
            out.close();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

}

3.测试demo:

pdf加水印测试demo:

import com.lowagie.text.pdf.PdfReader;
import com.spire.pdf.PdfDocument;
import xxx.util.PDFWatermark;
import java.io.IOException;

/**
 *  @author: xxxx
 *  @Date: 2020/12/24 15:10
 *  @Description: pdf加水印
 */
public class PDFWatermarkTest {

    public static void main(String[] args) throws IOException {
        //原pdf文件路径
        String sourcePath = "D:\\test.pdf";
        //目标pdf文件路径
        String targetPath = "D:\\log\\Watermark22.pdf";
        //加载原pdf文档
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile(sourcePath);
        PdfReader reader = new PdfReader(sourcePath);
        int total = reader.getNumberOfPages();
        for (int i = 0; i < total; i++) {
            PDFWatermark.AddTextWatermark(pdf.getPages().get(i), "已审阅");
        }
        //保存
        pdf.saveToFile(targetPath);
        PDFWatermark.addWatermark(sourcePath, "hahah");
        //关闭
        pdf.close();
    }

}

 pdf加水印后,将每一页pdf拆分出来保存为图片,然后对每一张图片进行了重命名:

import com.lowagie.text.pdf.PdfReader;
import com.spire.pdf.PdfDocument;
import xxx.util.PDFWatermark;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 *  @author: xxxx
 *  @Date: 2020/12/24 15:10
 *  @Description: pdf加水印
 */
public class PDFWatermarkToPngTest {
    public static void main(String[] args) throws IOException {
        String sourcePath = "D:\\log\\Watermark22.pdf";
        String targetPath = "D:\\log\\";
        PdfDocument pdf1 = new PdfDocument();
        pdf1.loadFromFile(sourcePath);
        PdfReader reader = new PdfReader(sourcePath);
        BufferedImage image;
        int total1 = reader.getNumberOfPages();
        for(int i =0 ; i<total1;i++){
            image = pdf1.saveAsImage(i);//将每一页pdf拆分出来保存为图片
            File file = new File(String.format(targetPath+"Watermark33"+i+".png",i));
            ImageIO.write(image,"PNG",file);
            PDFWatermark.fileCopyRightWay(targetPath+"Watermark33"+i+".png",targetPath+"测试3_"+i+".png");//对图片进行重命名
        }
        pdf1.close();

    }

}

警告:仅供学习研究使用哦!!!

猜你喜欢

转载自blog.csdn.net/LOVE_Me__/article/details/111607071