阿里云 springboot word 转pdf

阿里云 word 转pdf

pom.xml



<!-- 目前的版本对应  poi 4.1.2   和 xmlbeans 3.1.0   , poi 3.17   和 xmlbeans 2.6.0 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.xmlbeans</groupId>
            <artifactId>xmlbeans</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!-- easypoi导出word -->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-spring-boot-starter</artifactId>
            <version>4.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.2</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>5.5.13.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.31</version>
        </dependency>
        <dependency>
            <groupId>gui.ava</groupId>
            <artifactId>html2image</artifactId>
            <version>2.0.1</version>
        </dependency>

      <!-- word  to pdf jar  -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>imm20200930</artifactId>
            <version>2.1.13</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>tea-openapi</artifactId>
            <version>0.2.8</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>tea-console</artifactId>
            <version>0.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>tea-util</artifactId>
            <version>0.2.16</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>tea</artifactId>
            <version>1.1.14</version>
        </dependency>

controller

/**
     * 下载word
     *
     * @param response
     * @throws Exception
     */
    @ApiOperation("下载word")
    @PostMapping("/exportToWord")
    public Result<DownloadReportVO> exportToWord(HttpServletResponse response) {
        Integer userId = SecurityContextHolder.getUserId();
        String secCode = SecurityContextHolder.getUserStockCode();
//        Integer userId = 241437;
//        String secCode = "300804";
        String today = DateUtil.today();
        HengShenCompanyInfoDto companyInfoDto = remoteBasicService.getCompanyInfoByCode(secCode).getData();
        //判断该公司是否满一年
        String listedDate = companyInfoDto.getListedDate();
        // 定义日期格式
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 将字符串转换为LocalDate对象
        Date date1 = DateUtil.parse(today);
        Date date2 = DateUtil.parse(listedDate);
        // 判断日期是否相差大于一年
        long difference = Math.abs(date2.getTime() - date1.getTime());
        long differenceInYears = difference / (1000L * 60 * 60 * 24 * 365); // milliseconds to years

        String companyReferred = companyInfoDto.getCompanyReferred();
        String day = DateUtil.format(new Date(), "yyyyMMdd");
        String wordFileName = companyReferred + "(" + secCode + ")" + "市值诊断报告_" + day;
        try {
            //获取当前公司是否已经生成过报告
            //boolean fileExist = ossService.getFileExist("user/market_value", wordFileName, ".docx");
            boolean fileExist = false;
            if (fileExist) {
                String filePath = ossService.getFilePreview("user/market_value", wordFileName, ".docx");
                DownloadReportVO reportVO = new DownloadReportVO();
                reportVO.setFileName(wordFileName + ".docx");
                reportVO.setFilePath(filePath);
                return Result.ok(reportVO);
            } else {
                Map<String, Object> wordInitDataMaps = downloadReportExecutorService.exportToWordExecutorService(userId, secCode, this.getReportSearchVo(secCode));

                this.getReportBasic(companyInfoDto, wordInitDataMaps, today);

                XWPFDocument word = null;
                try {
                    if (differenceInYears > 1) {
                        //大于一年
                        word = WordExportUtil.exportWord07(phantomjsRoot + "/MVDR_YYYYMMDD_Template.docx", wordInitDataMaps);
                    } else {
                        //小于一年
                        word = WordExportUtil.exportWord07(phantomjsRoot + "/MVDR_YYYYMMDD_Template_2.docx", wordInitDataMaps);
                    }
                } catch (Exception e) {
                    log.error("下载市值报告转换word失败!", e);
                }

                //创建一个ByteArray输出流
                ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
                //用buffered包装一下
                OutputStream outputStream = new BufferedOutputStream(arrayOutputStream);
                word.write(outputStream);
                outputStream.close();
                word.close();
                //创建ByteArrayResource用ByteArray输出流的字节数组
                InputStream inputStream = new ByteArrayInputStream(arrayOutputStream.toByteArray());

                String ossUrl = ossService.fileUploadOssUrl("user/market_value", wordFileName, ".docx", inputStream);
                DownloadReportVO reportVO = new DownloadReportVO();
                reportVO.setFileName(wordFileName + ".docx");
                reportVO.setFilePath(ossUrl);

                //转pdf文件
                String pdfPath = this.getPdfPath("user/market_value" + format.format(new Date()) + "/" + wordFileName);
                if (Objects.nonNull(pdfPath)) {
                    reportVO.setPdfFilePath(pdfPath);
                }
                return Result.ok(reportVO);
            }
        } catch (Exception e) {
            log.error("市值报告处理失败!", e);
        }
        return Result.fail("市值报告下载失败");
    }


public String getPdfPath(String path) {
        com.aliyun.imm20200930.Client client = null;
        try {
            client = PDFSampleUtils.createClient("LTAI5tJufQSPPKiyXXXXX", "AAGktYt9Mixy5t4a6oLEXXX");

            com.aliyun.imm20200930.models.CreateOfficeConversionTaskRequest createOfficeConversionTaskRequest = new com.aliyun.imm20200930.models.CreateOfficeConversionTaskRequest()
                    .setTargetType("pdf") //设置要转的格式
                    .setProjectName("word2pdf") // 设置要转的文件to格式
                    .setSourceURI("oss://realizedongmi/" + path + ".docx") //转换前的地址 :oss://。。。
                    .setTargetURI("oss://realizedongmi/" + path + ".pdf");//转换前的地址 :oss://。。。
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            com.aliyun.imm20200930.models.CreateOfficeConversionTaskResponse resp = client.createOfficeConversionTaskWithOptions(createOfficeConversionTaskRequest, runtime);
            com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(resp)); //json格式的返回 获取到taskId 去走WordSampleUtils
            PcjsonRootBean pcjsonRootBeanObj = JSON.parseObject(Common.toJSONString(com.aliyun.teautil.Common.toJSONString(resp)), PcjsonRootBean.class);

            com.aliyun.imm20200930.models.GetTaskRequest getTaskRequest = new com.aliyun.imm20200930.models.GetTaskRequest()
                    .setProjectName("word2pdf")//与PDFSampleUtils的同步
                    .setTaskId(pcjsonRootBeanObj.getBody().getTaskid()) //在PDFSampleUtils获取到taskId 替换掉,执行
                    .setTaskType("OfficeConversion")
                    .setRequestDefinition(true);
            com.aliyun.teautil.models.RuntimeOptions runtime2 = new com.aliyun.teautil.models.RuntimeOptions();
            com.aliyun.imm20200930.models.GetTaskResponse resp2 = client.getTaskWithOptions(getTaskRequest, runtime);
            com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(resp2));
            PcjsonRootBean pcjsonRootBean = JSON.parseObject(Common.toJSONString(com.aliyun.teautil.Common.toJSONString(resp2)), PcjsonRootBean.class);
            if (pcjsonRootBean.getStatuscode() == 200) {
                return "https://oss.imvib.com/" + path + ".pdf";
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
PDFSampleUtils.java

package com.realize.market.value.utils;

import com.aliyun.tea.*;

/**
 *
 **/
public class PDFSampleUtils {

    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.imm20200930.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填,您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填,您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "imm.cn-shanghai.aliyuncs.com";
        return new com.aliyun.imm20200930.Client(config);
    }

    /**
     * 使用STS鉴权方式初始化账号Client,推荐此方式。
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @param securityToken
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.imm20200930.Client createClientWithSTS(String accessKeyId, String accessKeySecret, String securityToken) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填,您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填,您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret)
                // 必填,您的 Security Token
                .setSecurityToken(securityToken)
                // 必填,表明使用 STS 方式
                .setType("sts");
        // 访问的域名
        config.endpoint = "imm.cn-shanghai.aliyuncs.com";
        return new com.aliyun.imm20200930.Client(config);
    }

    //先启动这个
    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        // 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
        // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378657.html
        com.aliyun.imm20200930.Client client = PDFSampleUtils.createClient("LTAI5tJufQSPPKiyXXXXX", "LTAI5tJufQSPPKiyXXXXX");
        com.aliyun.imm20200930.models.CreateOfficeConversionTaskRequest createOfficeConversionTaskRequest = new com.aliyun.imm20200930.models.CreateOfficeConversionTaskRequest()
                .setTargetType("pdf") //设置要转的格式
                .setProjectName("word2pdf") // 设置要转的文件to格式
                .setSourceURI("oss://realizedongmi/user/market_value/2023/07/06/中国石化(600028)市值诊断报告_20230706.docx") //转换前的地址 :oss://。。。
                .setTargetURI("oss://realizedongmi/user/market_value/2023/07/06/中国石化(600028)市值诊断报告_20230706.pdf");//转换前的地址 :oss://。。。
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        com.aliyun.imm20200930.models.CreateOfficeConversionTaskResponse resp = client.createOfficeConversionTaskWithOptions(createOfficeConversionTaskRequest, runtime);
        com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(resp)); //json格式的返回 获取到taskId 去走WordSampleUtils
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值