admin管理员组

文章数量:1605637

😊 @ 作者: 一恍过去 💖 @ 主页: https://blog.csdn/zhuocailing3390 🎊 @ 社区: Java技术栈交流 🎉 @ 主题: SpringBoot实现Excel、Word转换为PDF ⏱️ @ 创作时间: 2022年03月15日

目录

  • 前言
  • 1、配置license
  • 2、excel转pdf
  • 3、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。
    • Workbook workbook = new Workbook(inputFilePath);
    • workbook.save(outputFilePath, SaveFormat.PDF);
  • 使用Aspose.Words包来处理Word 文档将 Word 文档转换为 PDF。
    • Document doc = new Document(inputFilePath);
    • doc.save(outputFilePath, SaveFormat.PDF);

1、配置license

resources目录下创建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>

引入jar包:
aspose没有相应的maven地址,所有手动引入jar包;

aspose-cells-20.4 - c.jar
aspose-words-18.10-jdk16.jar

下载地址:https://download.csdn/download/zhuocailing3390/76147206

2、excel转pdf

封装工具类:

import com.aspose.cells.*;
import com.aspose.cells.License;
import com.aspose.cells.LoadOptions;
import com.aspose.cells.PdfSaveOptions;

import java.io.*;

/**
 * @Author: LiHuaZhi
 * @Date: 2021/7/13 14:21
 * @Description:
 **/
public class Excel2PdfUtil {

    /**
     * 加载配置文件
     * @return
     */
    private static boolean getLicense() {
        boolean result = false;
        try (InputStream in = Doc2PdfUtil.class.getClassLoader().getResourceAsStream("license.xml")) {
            License license = new License();
            license.setLicense(in);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @param inputStream
     * @param docPath
     * @param pdfPath
     * @description 如果流不为空则使用转pdf,反之则用docPath进行转pdf
     */
    public static File excel2Pdf(InputStream inputStream, String docPath, String pdfPath) {
        System.out.println("pdf转换中...");
        long old = System.currentTimeMillis();
        File pdfFile = new File(pdfPath);
        try (FileOutputStream fos = new FileOutputStream(pdfFile)) {
            // 验证
            if (!getLicense()) {
                throw new RuntimeException("文件转换失败!");
            }
            // 设置字体包位置 - 不同环境可用从配置文件中获取
            IndividualFontConfigs configs = new IndividualFontConfigs();
            // configs.setFontFolder("/usr/share/fonts/chinese", true);
            configs.setFontFolder("C:\\Windows\\Fonts", true);
            LoadOptions loadOptions = new LoadOptions();
            loadOptions.setFontConfigs(configs);

            Workbook workbook;
            if (inputStream != null) {
                workbook = new Workbook(inputStream, loadOptions);
            } else {
                workbook = new Workbook(docPath, loadOptions);
            }
            PdfSaveOptions opts = new PdfSaveOptions();
            // 设置excel不换行在pdf显示
            // opts.setAllColumnsInOnePagePerSheet(true);
            // 设置一个sheet在一页pdf
            opts.setOnePagePerSheet(true);
            workbook.save(fos, opts);
            long now = System.currentTimeMillis();
            System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");
            return pdfFile;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件转换失败!");
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Controller实现:

    @RequestMapping("/excel")
    @ResponseBody
    public void uploadExcel(@RequestParam("file") MultipartFile file) throws Exception {
        String docPath = "C:\\Users\\LiGezZ\\Desktop\\ad.xlsx";
        String pdfPath = "C:\\Users\\LiGezZ\\Desktop\\test.pdf";
        File pdf = Excel2PdfUtil.excel2Pdf(file.getInputStream(), docPath, pdfPath);
    }

3、word转pdf

封装工具类:

import java.io.*;

import com.aspose.words.*;

/**
 * @Author: LiHuaZhi
 * @Date: 2021/7/13 14:21
 * @Description:
 **/
public class Doc2PdfUtil {

    /**
     * 加载配置文件
     *
     * @return
     */
    private static boolean getLicense() {
        boolean result = false;
        try (InputStream in = Doc2PdfUtil.class.getClassLoader().getResourceAsStream("license.xml")) {
            License license = new License();
            license.setLicense(in);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * doc转pdf
     *
     * @param docPath doc文件路径,包含.doc
     * @param pdfPath pdf文件路径,包含.pdf
     * @description 如果流不为空则使用转pdf,反正则用docPath进行转pdf
     */
    public static File doc2Pdf(InputStream inputStream, String docPath, String pdfPath) {
        System.out.println("pdf转换中...");
        long old = System.currentTimeMillis();

        File pdfFile = new File(pdfPath);
        try (FileOutputStream fos = new FileOutputStream(pdfFile)) {
            // 验证
            if (!getLicense()) {
                throw new RuntimeException("文件转换失败!");
            }
            // FontSettings.getDefaultInstance().setFontsFolder("/usr/share/fonts/chinese", true);
            FontSettings.getDefaultInstance().setFontsFolder("C:\\Windows\\Fonts", true);

            Document document;
            if (inputStream != null) {
                document = new Document(inputStream);
            } else {
                document = new Document(docPath);
            }
            //  DocumentBuilder builder = new DocumentBuilder(document);
            // 设置纸张大小
            //  builder.getPageSetup().setPaperSize(PaperSize.A3);
            // 设置横向
            // builder.getPageSetup().setOrientation(Orientation.LANDSCAPE);
            document.save(fos, SaveFormat.PDF);
            long now = System.currentTimeMillis();
            System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");
            return pdfFile;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件转换失败!");
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

Controller实现:

    @RequestMapping("/word")
    @ResponseBody
    public void uploadWord(@RequestParam("file") MultipartFile file) throws Exception {
        String docPath = "C:\\Users\\LiGezZ\\Desktop\\test.docx";
        String pdfPath = "C:\\Users\\LiGezZ\\Desktop\\test.pdf";
        File pdf = Doc2PdfUtil.doc2Pdf(file.getInputStream(), docPath, pdfPath);
    }

本文标签: 转换为ExcelSpringBootPDFword