java预览word、 pdf文件

思路是将文件转为pdf文件,在线预览

1.转换工具类

(转换工具类引用原文地址:Java实现在线预览,支持doc/docx/pptx/ppt/xls/xlsx格式转为pdf进行在线预览_写代码也要酷酷的的博客-CSDN博客


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

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @Author zx0326
 * @Date 2023/8/30 15:27
 */
public class OnlinePreviewUtil {

    /**
     * 文件转换
     *
     * @param source:源文件地址 如:C://test/test.doc,target:转换后文件路径  如 C://test/pdf
     * @return
     */
    public static String officeToPdf(InputStream source, OutputStream target, String fileName) {

        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
        if ("doc".equals(fileExt) || "docx".equals(fileExt)) {
            doc2pdf(source, target);
        }
        if ("xls".equals(fileExt) || "xlsx".equals(fileExt)) {
            excel2pdf(source, target);
        }
//        if ("ppt".equals(fileExt) || "pptx".equals(fileExt)) {
//            ppt2pdf(source, target);
//        }

        if ("doc,docx,xls,xlsx,ppt,pptx".indexOf(fileExt) > 0) {
            return target +  File.separator + (fileName.replace(fileExt, "pdf"));
        }
        return null;
    }

    /**
     * @description: 验证ExcelLicense
     */
    public static boolean getExcelLicense() {
        boolean result = false;
        try {
            //  license.xml应放在..\WebRoot\WEB-INF\classes路径下
            InputStream is = OnlinePreviewUtil.class.getClassLoader().getResourceAsStream("license.xml");
            com.aspose.cells.License aposeLic = new com.aspose.cells.License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * @description: 验证License
     */
    public static boolean getDocLicense() {
        boolean result = false;
        try {
            //  license.xml应放在..\WebRoot\WEB-INF\classes路径下
            InputStream is = OnlinePreviewUtil.class.getClassLoader().getResourceAsStream("license.xml");
            com.aspose.words.License aposeLic = new com.aspose.words.License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @description: doc转pdf
     * @params: source:源文件,target:转换后文件
     */
    public static void doc2pdf(InputStream source, OutputStream target) {
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getDocLicense()) {
            return;
        }
        try {
            Document doc = new Document(source);
            doc.save(target, com.aspose.words.SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * @description: excel转pdf
     * @params: source:源文件地址,target:转换后文件路径,fileExt:后缀
     */
    public static void excel2pdf(InputStream source, OutputStream target) {
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getExcelLicense()) {
            return;
        }
        try {
            // 原始excel路径
            Workbook wb = new Workbook(source);
            wb.save(target, com.aspose.cells.SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    /**
//     * @description: ppt转pdf
//     * @params: source:源文件地址,target:转换后文件路径,fileExt:后缀
//     */
//    public static void ppt2pdf(InputStream source, OutputStream target) {
//        // 验证License 若不验证则转化出的pdf文档会有水印产生
//        if (!getPPTLicense()) {
//            return;
//        }
//        try {
//            //输入pdf路径
//            Presentation pres = new Presentation(source);
//            pres.save(target, SaveFormat.PDF);
//            target.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

}

2. 配置文件,放在resource目录下

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>

3. 调用方式

 /**
     * 文件转PDF 预览
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/previewToPdf", method = RequestMethod.GET)
    public void previewToPdf(HttpServletResponse response) throws RuntimeException, IOException {

        File file = new File("F:\\文件\\moka\\dzqz\\电子签章概要设计.docx");
        InputStream in = null;
        try {
            in = Files.newInputStream(file.toPath());
            
            OnlinePreviewUtil.officeToPdf(in, response.getOutputStream(), file.getName());

            response.setHeader("Content-Type", "application/pdf");
            IOUtils.write(IOUtils.toByteArray(in), response.getOutputStream());
        }catch (Exception e){
            throw new RuntimeException("加载失败");
        }finally {
            in.close();
        }

    }
window.open("/previewController/previewToPdf");

4. maven依赖

aspose依赖引不到解决

链接:https://pan.baidu.com/s/1sUsYf4WJXaJw47GGK_M2VA?pwd=27w1 
提取码:27w1


<!--        word-pdf start-->
        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>fr.opensagres.poi.xwpf.converter.pdf-gae</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>15.8.0</version>
        </dependency>
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>8.5.2</version>
        </dependency>
        <!--      <dependency>-->
        <!--          <groupId>com.aspose</groupId>-->
        <!--          <artifactId>aspose-slides</artifactId>-->
        <!--          <version>15.9.0</version>-->
        <!--      </dependency>-->
        <!--        word-pdf end-->

5. 本地引入maven jar

maven将本地jar包添加到本地仓库_maven仓库上传jar包_打'更人的博客-CSDN博客

install:install-file 
-Dfile=D:\Idea\WorkSapce\jar\aspose-cells-8.5.2.jar
-DgroupId=com.aspose
-DartifactId=aspose-cells
-Dversion=8.5.2
-Dpackaging=jar
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用Apache POI和Aspose.Words这两个Java库来实现在线Word文档的功能。 Apache POI是一个用于读取、创建和修改Microsoft Office格式文件(如Word、Excel和PowerPoint)的Java库。可以使用它来读取Word文档内容并将其转换为HTML格式,然后通过浏器进行在线。 Aspose.Words是一个专门用于处理Word文档的Java库,它可以将Word文档转换为HTML格式或PDF格式,然后通过浏器进行在线。 以下是使用Apache POI和Aspose.Words实现在线Word文档的示例代码: 1. 使用Apache POI将Word文档转换为HTML格式: ```java import java.io.*; import org.apache.poi.hwpf.*; import org.apache.poi.hwpf.extractor.*; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; public class WordToHtmlConverter { public static void main(String[] args) throws Exception { // 读取Word文档内容 FileInputStream fis = new FileInputStream(new File("test.doc")); HWPFDocument doc = new HWPFDocument(fis); WordExtractor extractor = new WordExtractor(doc); String content = extractor.getText(); // 将Word文档内容转换为HTML格式 Document html = Jsoup.parse(content); String htmlContent = html.html(); System.out.println(htmlContent); } } ``` 2. 使用Aspose.Words将Word文档转换为HTML格式: ```java import com.aspose.words.*; public class WordToHtmlConverter { public static void main(String[] args) throws Exception { // 加载Word文档 Document doc = new Document("test.doc"); // 将Word文档转换为HTML格式 HtmlSaveOptions options = new HtmlSaveOptions(); doc.save("test.html", options); // 读取HTML文件内容 FileInputStream fis = new FileInputStream(new File("test.html")); byte[] data = new byte[fis.available()]; fis.read(data); String htmlContent = new String(data); System.out.println(htmlContent); } } ``` 需要注意的是,以上示例代码仅供参考,实际使用时可能需要根据具体情况进行修改。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值