Java-Aspose实现上传Excel、Word转换为PDF并进行下载

导读:本篇文章讲解 Java-Aspose实现上传Excel、Word转换为PDF并进行下载,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

1、加载Aspose包

1、下载:
Aspose官网没有提供相应的maven地址,所有手动引入jar包:

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

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

2、配置lib目录:
在项目的resources目录下,创建lib目录,并且将下载的两个jar包放入其中
在这里插入图片描述
3、引入pom:
引入自定义配置的maven坐标:

	<dependencys>
		<dependency>
            <groupId>com.aspose.cells</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>20.4 - c</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/lib/aspose-cells-20.4 - c.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>com.aspose.words</groupId>
            <artifactId>aspose-words</artifactId>
            <version>words-18.10-jdk16</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/lib/aspose-words-18.10-jdk16.jar</systemPath>
        </dependency>
    </dependencys>

2、配置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>

2、word转pdf

封装工具类:

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

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @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的包路径必须为com.aspose.words.License
            License license = new License();
            license.setLicense(in);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * doc转pdf
     *
     * @param inputStream
     * @param fileName
     * @param response
     * @return
     */
    public static void doc2Pdf(InputStream inputStream,String fileName, HttpServletResponse response) {
        System.out.println("pdf转换中...");
        long old = System.currentTimeMillis();

        try (ByteArrayOutputStream fos = new ByteArrayOutputStream()) {
            // 验证
            if (!getLicense()) {
                throw new RuntimeException("文件转换失败!");
            }
            // 加载字体
            FontSettings settings = FontSettings.getDefaultInstance();
            settings.setFontsFolder("C:\\Windows\\Fonts", true);
            LoadOptions loadOptions = new LoadOptions();
            loadOptions.setFontSettings(settings);

            // 也可以直接指定路径 document = new Document(docPath);
            Document document = new Document(inputStream, loadOptions);

            //  DocumentBuilder builder = new DocumentBuilder(document);
            // 设置纸张大小
            //  builder.getPageSetup().setPaperSize(PaperSize.A3);
            // 设置横向
            // builder.getPageSetup().setOrientation(Orientation.LANDSCAPE);

            document.save(fos, SaveFormat.PDF);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".pdf", "UTF-8"));
            byte[] buffer = fos.toByteArray();
            InputStream arrayInputStream = new ByteArrayInputStream(buffer);
            byte[] buf = new byte[4096];
            int len = -1;
            while ((len = arrayInputStream.read(buf)) != -1) {
                response.getOutputStream().write(buf, 0, len);
            }
            long now = System.currentTimeMillis();
            System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件转换失败!");
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Controller实现:

@RestController
@RequestMapping("/test")
public class TestController {
    /**
     * 导入word文件
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/word")
    @ResponseBody
    public void uploadWord(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception {
		if (file.isEmpty()) {
            return;
        }
        String originalFilename = file.getOriginalFilename();
        String fileName = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        
        Doc2PdfUtil.doc2Pdf(file.getInputStream(), fileName, response);
    }
}

postMan测试:
请求接口,比如:http://127.0.0.1:9090/test/word
在这里插入图片描述

3、excel转pdf

封装工具类:

import com.aspose.cells.*;
import com.aspose.words.Document;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class Excel2PdfUtil {

    /**
     * 加载配置文件
     *
     * @return
     */
    private static boolean getLicense() {
        boolean result = false;
        try (InputStream in = Excel2PdfUtil.class.getClassLoader()
                .getResourceAsStream("license.xml")) {
            // License的包路径必须为com.aspose.cells.License
            License license = new License();
            license.setLicense(in);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * @param inputStream
     * @param fileName
     * @param response
     */
    public static void excel2Pdf(InputStream inputStream,String fileName, HttpServletResponse response) {
        System.out.println("pdf转换中...");
        long old = System.currentTimeMillis();
        try (ByteArrayOutputStream fos = new ByteArrayOutputStream()) {
            // 验证
            if (!getLicense()) {
                throw new RuntimeException("文件转换失败!");
            }
            // 设置字体包位置
            IndividualFontConfigs configs = new IndividualFontConfigs();
            configs.setFontFolder("C:\\Windows\\Fonts", true);
            LoadOptions loadOptions = new LoadOptions();
            loadOptions.setFontConfigs(configs);

            // 也可以直接指定路径 workbook = new Workbook(docPath, loadOptions);
            Workbook workbook = new Workbook(inputStream, loadOptions);

            PdfSaveOptions opts = new PdfSaveOptions();
            // 设置excel不换行在pdf显示
            // opts.setAllColumnsInOnePagePerSheet(true);
            // 设置一个sheet在一页pdf
            opts.setOnePagePerSheet(true);
            workbook.save(fos, opts);

            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".pdf", "UTF-8"));
            byte[] buffer = fos.toByteArray();
            InputStream arrayInputStream = new ByteArrayInputStream(buffer);
            byte[] buf = new byte[4096];
            int len = -1;
            while ((len = arrayInputStream.read(buf)) != -1) {
                response.getOutputStream().write(buf, 0, len);
            }

            long now = System.currentTimeMillis();
            System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件转换失败!");
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Controller实现:

@RestController
@RequestMapping("/test")
public class TestController {
        /**
     * 导入excel文件
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/excel")
    @ResponseBody
    public void uploadExcel(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception {
	    if (file.isEmpty()) {
            return;
        }
        String originalFilename = file.getOriginalFilename();
        String fileName = originalFilename.substring(0, originalFilename.lastIndexOf("."));

        Excel2PdfUtil.excel2Pdf(file.getInputStream(), fileName, response);
    }
}

postMan测试:
请求接口,比如:http://127.0.0.1:9090/test/excel
在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/18006.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!