Java-Aspose实现上传Excel、Word转换为PDF

文章目录

前言

 一、基本流程

二、使用步骤 

引入Aspose相关jar包

配置license文件

Excel转换为PDF

定义常量(EXCEL WORD 通用)

Excel转换PDF所需方法 根据路径、输入流等等

获取license文件 (EXCEL、WORD通用)

 ExcelToPdf main方法测试

Word转换为PDF


前言

Aspose.Words 是一个用于 Java 平台的强大的文档处理库,它允许开发人员在他们的 Java 应用程序中创建、编辑、转换和呈现 Word 文档。以下是 Aspose.Words 的一些主要功能和用途:

创建和编辑 Word 文档:Aspose.Words 提供了一套丰富的 API,可以创建新的 Word 文档并对其进行编辑。您可以添加和格式化文本、插入表格、插入图片和其他图形,设置页面布局和格式等。
文档转换:Aspose.Words 允许您将 Word 文档转换为其他常见的文件格式,如 PDF、HTML、纯文本、图像等。同样,您也可以将其他格式的文档转换为 Word 格式。
模板处理:Aspose.Words 支持使用模板来创建和填充 Word 文档。您可以将模板与数据源结合使用,动态生成包含可变内容的文档,例如合同、报告和邮件。
文档操作:Aspose.Words 提供了丰富的功能来处理文档,如提取文本、插入页眉和页脚、合并和拆分文档、查找和替换文本等。
格式化和样式:您可以使用 Aspose.Words 设置字体、段落和表格的格式,应用样式和主

题,控制页眉和页脚,创建目录和索引等


 一、基本流程

本文使用 Aspose 来实现 Excel、Word转换为PDF,基本流程如下:

  • 使用Aspose.Cells包来处理Excel 文档,将 Excel 文档转换为 PDF。

fileOs = new FileOutputStream(pdfFile);

wb.save(fileOs, pdfSaveOptions);

  • 使用Aspose.Words包来处理Word 文档将 Word 文档转换为 PDF。

 Document doc = new Document(wordFile);
 doc.save(os, SaveFormat.PDF);

二、使用步骤 

  1. 引入Aspose相关jar包

  • aspose-cells-8.5.2 .jar
  • aspose-words-15.8.0.jar                                                                                                       
  •  Aspose直接引入jar包可能影响功能效果 手动下载jar包至本地并导入本地maven仓库。

<dependency>
            <groupId>com.external</groupId>
            <artifactId>aspose-words</artifactId>
            <version>15.8.0</version>
        </dependency>

     

  <dependency>
            <groupId>com.external</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>8.5.2</version>
   </dependency>

  1. 配置license文件

  • Excel相关license

<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>

  • Word相关license

        注意:license文件直接复制粘贴使用即可 放在resources文件夹下即可

<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>

  1. Excel转换为PDF

  • 定义常量(EXCEL WORD 通用)

/** EXCEL文件所在路径 自定义*/

private static final String EXCEL_PATH = "";

/** PDF文件所在路径 自定义*/

private static final String PDF_PATH ="";  
/**去除文件水印 在项目的 resources 下 */
private static final String FOP_EXL = "/config/excel-license.xml"; 

private static final String FOP_WORD = "/config/word-license.xml";

  • Excel转换PDF所需方法 根据路径、输入流等等

import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.glaway.foundation.common.util.UUIDGenerator;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author: youchao
 * @description:
 * @data: 2024/1/22 17:01
 **/
public class ExcelToPdf {   
    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     */
    public static void excel2pdf(String excelFilePath) {
        excel2pdf(excelFilePath, null, null);
    }

    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     * @param convertSheets 需要转换的sheet
     */
    public static void excel2pdf(String excelFilePath, int[] convertSheets) {
        excel2pdf(excelFilePath, null, convertSheets);
    }

    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     * @param pdfFilePath   pdf文件路径
     */
    public static void excel2pdf(String excelFilePath, String pdfFilePath) {
        excel2pdf(excelFilePath, pdfFilePath, null);
    }

    /**
     * excel 转 pdf
     *
     * @param inputStream exl流
     * @param pdfFilePath pdf文件路径
     */
    public static void excel2pdf(InputStream inputStream, String pdfFilePath) {
        excel2pdf(inputStream, pdfFilePath, null);
    }

    /**
     * excel 转 pdf
     *
     * @param inputStream   exl流
     * @param convertSheets 需要的sheet
     */
    public static InputStream excel2pdf(InputStream inputStream, int[] convertSheets) {
        return excel2pdf1(inputStream, convertSheets);
    }

    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     * @param pdfFilePath   pdf文件路径
     * @param convertSheets 需要转换的sheet
     */
    public static void excel2pdf(String excelFilePath, String pdfFilePath, int[] convertSheets) {
        FileOutputStream fileOs = null;
        try {
            pdfFilePath = pdfFilePath == null ? getPdfFilePath(excelFilePath) : pdfFilePath;
            // 验证 License
            getLicenseExl();
            Workbook wb = new Workbook(excelFilePath);
            fileOs = new FileOutputStream(pdfFilePath);

            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);
            int[] autoDrawSheets = {3};
            autoDraw(wb, autoDrawSheets);
            if (null != convertSheets) {
                printSheetPage(wb, convertSheets);
            }
            wb.save(fileOs, pdfSaveOptions);
            fileOs.flush();
            System.out.println("convert success");
        } catch (Exception e) {
            System.out.println("convert failed");
            e.printStackTrace();
        } finally {
            try {
                assert fileOs != null;
                fileOs.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * excel 转 pdf
     *
     * @param inputStream   exl流
     * @param pdfFilePath   pdf文件路径
     * @param convertSheets 需要转换的sheet
     */
    public static void excel2pdf(InputStream inputStream, String pdfFilePath, int[] convertSheets) {
        FileOutputStream fileOs = null;
        try {
            // 验证 License
            getLicenseExl();
            Workbook wb = new Workbook(inputStream);// 原始excel路径
            File pdfFile = new File(pdfFilePath);// 输出路径
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            //把excel所有内容放在一张PDF 页面上;
            pdfSaveOptions.setOnePagePerSheet(false);
            //把excel所有表头放在一张pdf上
            pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
            fileOs = new FileOutputStream(pdfFile);
            wb.save(fileOs, pdfSaveOptions);
            fileOs.flush();
        } catch (Exception e) {
            System.out.println("convert failed");
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                assert fileOs != null;
                fileOs.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            System.out.println("exl转pdf结束");
        }
    }

    /**
     * @param wb   设置打印的sheet自动拉伸比例
     * @param page 自动拉伸的页的sheet数组
     */
    public static void autoDraw(Workbook wb, int[] page) {
        if (null != page && page.length > 0) {
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
                wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
            }
        }
    }

    /**
     * excel 转 pdf 返回文件流
     *
     * @param inputStream   exl文件流
     * @param convertSheets 需要转换的 sheet
     * @return 文件流
     */
    public static InputStream excel2pdf1(InputStream inputStream, int[] convertSheets) {
        ByteArrayOutputStream fileOs = null;
        try {
            // 验证 License
            getLicenseExl();
            Workbook wb = new Workbook(inputStream);
            fileOs = new ByteArrayOutputStream();
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);
            if (null != convertSheets) {
                printSheetPage(wb, convertSheets);
            }
            wb.save(fileOs, pdfSaveOptions);
            fileOs.flush();
            return new ByteArrayInputStream(fileOs.toByteArray());
        } catch (Exception e) {
            System.out.println("convert failed");
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                if (fileOs != null) {
                    fileOs.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            System.out.println("exl转pdf结束");
        }
        return null;
    }

    /**
     * 获取 生成的 pdf 文件路径,默认与源文件同一目录
     *
     * @param excelFilePath excel文件
     * @return 生成的 pdf 文件
     */
    private static String getPdfFilePath(String excelFilePath) {
        return excelFilePath.split(".")[0] + ".pdf";
    }

   

    /**
     * 隐藏workbook中不需要的sheet页。
     *
     * @param sheets 显示页的sheet数组
     */
    private static void printSheetPage(Workbook wb, int[] sheets) {
        for (int i = 1; i < wb.getWorksheets().getCount(); i++) {
            wb.getWorksheets().get(i).setVisible(false);
        }
        if (null == sheets || sheets.length == 0) {
            wb.getWorksheets().get(0).setVisible(true);
        } else {
            for (int i = 0; i < sheets.length; i++) {
                wb.getWorksheets().get(i).setVisible(true);
            }
        }
    }
}
 

  • 获取license文件 (EXCEL、WORD通用)

 /**
     * 获取 license 去除水印
     * 若不验证则转化出的pdf文档会有水印产生
     */
    private static void getLicenseExl() {
        InputStream is = null;
        try {
            ClassPathResource classPathResource = new ClassPathResource(FOP_EXL);
            is = classPathResource.getInputStream();
            License license = new License();
            license.setLicense(is);
        } catch (Exception e) {
            System.out.println("license verify failed");
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

  •  ExcelToPdf main方法测试

public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(EXCEL_PATH);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        excel2pdf(fileInputStream,PDF_PATH);
    }

  1. Word转换为PDF

import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.glaway.foundation.common.util.UUIDGenerator;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

/**
 * @author: youchao
 * @description:
 * @data: 2024/1/19 16:39
 **/
public class WordToPdf {

    /**
     * word 转 pdf
     *
     * @param wordFile word 文件路径
     * @param pdfFile  生成的 pdf 文件路径
     */
    public static void word2Pdf(String wordFile, String pdfFile) {
        File file = new File(pdfFile);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdir();
        }
        getLicenseWord();
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(pdfFile);
            Document doc = new Document(wordFile);
            doc.save(os, SaveFormat.PDF);
        } catch (Exception e) {
            System.out.println("word转pdf失败");
            e.printStackTrace();
        } finally {
            try {
                assert os != null;
                os.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            System.out.println("word转pdf结束");
        }
    }

    /**
     * word 转 pdf 生成文件到服务器
     *
     * @param inputStream word
     * @param pdfFile     生成的 pdf 文件路径
     */
    public static void word2Pdf(InputStream inputStream, String pdfFile) {
        System.out.println("word转pdf[开始]");
        File file = new File(pdfFile);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdir();
        }
        getLicenseWord();

        FileOutputStream os = null;
        try {
            os = new FileOutputStream(pdfFile);
            Document doc = new Document(inputStream);
            doc.save(os, SaveFormat.PDF);
        } catch (Exception e) {
            System.out.println("word转pdf失败");
            e.printStackTrace();
        } finally {
            assert os != null;
            try {
                inputStream.close();
                os.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            System.out.println("word转pdf结束");
        }
    }

    /**
     * word 转 pdf 返回文件流
     *
     * @param inputStream word文件流
     * @return 生成pdf文件流
     */
    public static InputStream word2Pdf(InputStream inputStream) {
        System.out.println("word转pdf[开始]");
        //去水印
        getLicenseWord();
        ByteArrayOutputStream os = null;
        try {
            os = new ByteArrayOutputStream();
            Document doc = new Document(inputStream);
            doc.save(os, SaveFormat.PDF);
            return new ByteArrayInputStream(os.toByteArray());
        } catch (Exception e) {
            System.out.println("word转pdf失败");
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            System.out.println("word转pdf[结束]");
        }
        return null;
    }
}

  • 18
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

AKYChao

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

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

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

打赏作者

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

抵扣说明:

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

余额充值