word在线预览 (含doc,docx等)

思路:

项目中遇到这种在线预览,绝大部分的解决方案是word转pdf  然后调用pdfjs去完成页面预览。

1.引入pom依赖

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

 

上代码!

controller

    /**
     *@description 预览文档(word转pdf预览)
     *@param
     *@return 
     *@creator ly
     *@date 2021/3/19
     */
    @GetMapping("/previewDoc")
    public void previewReportPdf(@RequestParam(name="imageId") Integer imageId ,@RequestParam(name = "fileName") String fileName, HttpServletResponse response, HttpServletRequest request) throws Exception {
         iFileUploadService.previewWord(imageId, fileName , response, request);
    }

serviceIml实现

   /**
     *@description word转pdf,预览pdf
     *@param
     *@return
     *@creator ly
     *@date 2021/3/19
     */
    @Override
    public void previewWord(Integer imageId, String fileName, HttpServletResponse response, HttpServletRequest request) throws Exception {
        Validate.notNull(imageId,tipsConfig.getParam_isblank());
        Validate.notNull(fileName,tipsConfig.getParam_isblank());
        ProductParam productParam = new ProductParam();
        productParam.setProductId(Long.valueOf(imageId));
        DsProduct dsProduct = iDsProductMapper.findListByParam(productParam).get(0);
        //根据产品id获取相关联的文件
        List<DsProductFile> dsProductFileList = iDsProductFileMapper.selectByProductId(dsProduct.getProductId());
        if (dsProductFileList.isEmpty()) {
            return;
        }
        //相对路径
        String relativePath = dsProduct.getRelativePath() + "/" + fileName;
        //服务器对象
        Server server = serverMapper.selectByPkId(dsProduct.getServerId());
        String fileAbs = server.getDataPath() + relativePath;
        String renameFileAbs = server.getDataPath() + dsProduct.getRelativePath()+ "/"+fileName.substring(0,fileName.lastIndexOf("."))+REPORT_FILE_FORMAT_PDF;

        fileAbs = fileAbs.replace("\\", File.separator);
        //word转pdf
        File fPdf = PdfUtils.wordToPdf(fileAbs, renameFileAbs);
        //pdf预览
        DownloadUtil.previewReportPdf(renameFileAbs,  response);
    }

wordToPdf方法 

  public static File wordToPdf(String destFullPath, String path){
        LOGGER.info("word:" + destFullPath + "pdf:" +path);
        return DocUtils.docToPdf(destFullPath, path);
    }
    /**
     * DOC转PDF,返回File
     * @param fromPath
     * @param toPath
     */
    public static File docToPdf(String fromPath,String toPath) {
        source2Traget(fromPath,toPath,SaveFormat.PDF);
        return new File(toPath);
    }
  public static void source2Traget(String sPath,String tPath,int type) {
        logger.info("DocUtils:文档转换开始》》》》》》》》》》》》");
        logger.info("DocUtils:文档转换资源路径为》》》》》》》》》》》》"+sPath);
        logger.info("DocUtils:文档转换目标路径为》》》》》》》》》》》》"+tPath);
        logger.info("DocUtils:文档转换类型为》》》》》》》》》》》》"+type);
        if (!getLicense()) {          // 验证License 若不验证则转化出的pdf文档会有水印产生
            logger.info("DocUtils:文档转化验证License失败!》》》》》》");
        }
        if(!ArrayUtils.contains(formatType,type)){
            logger.info("DocUtils:文档转化失败,类型不存在!》》》》》》"+type);
        }
        try {
            File file = new File(tPath);  //新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(sPath); //sPath是将要被转化的word文档
            doc.save(os, type);
            os.flush();
            os.close();
            logger.error("DocUtils:文档转化成功》》》》》》");
        } catch (Exception e) {
            logger.error("DocUtils:文档转化失败》》》》》》"+e.getMessage());
        }
        logger.info("DocUtils:文档转换结束》》》》》》》》》》》》");
    }

    /**
     * 验证是否有去水印xml
     * @return
     */
    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream in =PropertyUtil.class.getClassLoader().getResourceAsStream("license/license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(in);
            in.close();
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
/**
 * 属性文件的操作
 * @version <1> 2017-05-08 cxj : Created.
 */
public class PropertyUtil {

    public static String getPropertiesForConfig(String key){
        return  getProperties("config.properties").getProperty(key);
    }

    public static String getPropertiesForConfig(String key,String configFileName){
        return  getProperties(configFileName).getProperty(key);
    }

    /**
     * 读取属性文件
     * @version <1> 2017-05-08 cxj : Created.
     */
    public static Properties getProperties(String propFile){
        Properties p = null;
        try{
            InputStream in = PropertyUtil.class.getClassLoader().getResourceAsStream(propFile);
            p = new Properties();
            p.load(in);
        }catch(Exception e){
            e.printStackTrace();
        }
        return p;
    }
}

 

previewReportPdf方法:

/**
    * 预览pdf文件报告
    * @param filePath 文件路径
    * @return:
    * @version <1> 2020/11/5 13:54 HanShuGuang:Created.
    */
    public static void previewReportPdf(String filePath, HttpServletResponse response) throws Exception{

        InputStream iStream = null;
        OutputStream outStrem = null;
        try {
            File file = new File(filePath);
            response.setContentType("application/pdf");
            response.setHeader("Access-Control-Allow-Headers", "Range");
            response.setHeader("Access-Control-Expose-Headers", "Accept-Ranges, Content-Encoding, Content-Length, Content-Range");
            outStrem = response.getOutputStream();
            if(file.exists()) {
                iStream = new FileInputStream(filePath);
                byte[] data = readInputStream(iStream);
                outStrem.write(data);
                outStrem.flush();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }finally {
            if(iStream != null){
                try {
                    iStream.close();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
            if(outStrem != null){
                try {
                    outStrem.close();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
        }
    }

注意  license/license.xml是去掉水印的关键!!!

附上文件位置:

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>

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值