SpringBoot集成aspose实现cad、word、excle、ppt在线预览

该博客介绍了如何在SpringBoot项目中利用aspose库将CAD、Word、Excel和PPT文件转换为PDF,并结合pdfjs进行在线预览。详细步骤包括引入依赖、编写转换工具类、调用工具类以及前端页面的配置和JS处理。

实现思路:
将cad(dwg、dxf、dwf)、word(doc、docx)、excle(xls,xlsx)、ppt(ppt,pptx)等类型的文件转为pdf
然后前端通过pdfjs实现预览

一、引入依赖

<!-- 导入本地jar -->
<!-- 操作ppt -->
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-slides</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/lib/aspose.slides-15.9.0.jar</systemPath>
</dependency>
<!-- 操作excel -->
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-cells</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/lib/aspose-cells-8.5.2.jar</systemPath>
</dependency>
<!-- 操作word-->
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-words</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/lib/aspose-words-18.6-jdk16.jar</systemPath>
</dependency>
<!-- 操作cad-->
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-cad</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/lib/aspose-cad-19.9.jar</systemPath>
</dependency>
<!-- 操作文本文件-->
<dependency>
    <groupId>com.itextpdf</groupId>
     <artifactId>itextpdf</artifactId>
     <version>5.5.13</version>
 </dependency>

二、编写工具类

package com.logan.base.util;
import com.aspose.cad.Color;
import com.aspose.cad.Image;
import com.aspose.cad.imageoptions.CadRasterizationOptions;
import com.aspose.cad.imageoptions.PdfOptions;
import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.core.io.ClassPathResource;
import java.io.*;

/**
* @author:logan
* @ClassName: PdfUtil
* @date: 2021/6/3  17:27
* @Description: TODO
*/
public class PdfUtil {

    private static final String myLicense = "<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>";

  public static void othersToPdf(String extension,InputStream in,OutputStream out) {
        if ("doc".equalsIgnoreCase(extension) || "docx".equalsIgnoreCase(extension)) {
            wordToPdf(in,out);
        }else if ("xls".equalsIgnoreCase(extension) || "xlsx".equalsIgnoreCase(extension)) {
            excelToPdf(in,out);
        }else if ("ppt".equalsIgnoreCase(extension) || "pptx".equalsIgnoreCase(extension)) {
            pptToPdf(in,out);
        }else if ("txt".equalsIgnoreCase(extension)) {
            txtToPdf(in,out);
        }else if ("dwg".equalsIgnoreCase(extension)||"dwf".equalsIgnoreCase(extension)
                ||"dxf".equalsIgnoreCase(extension)) {
            cadToPdf(in,out);
        }
    }

    /**
     * word转pdf
     * @param inputStream
     * @param outputStream
     */
    public static void wordToPdf(InputStream inputStream, OutputStream outputStream) {
        ByteArrayInputStream licenseInputStream = null;
        try{
            //设置证书
            licenseInputStream = new ByteArrayInputStream(myLicense.getBytes());
            License wordLicense = new License();
            wordLicense.setLicense(licenseInputStream);
            //转化
            Document document = new Document(inputStream);
            document.save(outputStream, SaveFormat.PDF);
            licenseInputStream.close();
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("word转PDF失败");
        }
    }

    /**
     * excel转pdf
     * @param inputStream
     * @param outputStream
     */
    public static void excelToPdf(InputStream inputStream,OutputStream outputStream){
        ByteArrayInputStream licenseInputStream = null;
        try {
            //设置证书
            licenseInputStream = new ByteArrayInputStream(myLicense.getBytes());
            com.aspose.cells.License wordLicense = new com.aspose.cells.License();
            wordLicense.setLicense(licenseInputStream);
            //转化
            Workbook workbook = new Workbook(inputStream);
            workbook.save(outputStream, 13);
            licenseInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("excel转pdf失败");
        }
    }

    /**
     * ppt转pdf
     * @param inputStream
     * @param outputStream
     */
    public static void pptToPdf(InputStream inputStream,OutputStream outputStream){
        ByteArrayInputStream licenseInputStream = null;
        try {
            //设置证书
            licenseInputStream = new ByteArrayInputStream(myLicense.getBytes());
            com.aspose.slides.License wordLicense = new com.aspose.slides.License();
            wordLicense.setLicense(licenseInputStream);
            //转化
            Presentation presentation = new Presentation(inputStream);
            presentation.save(outputStream, 1);
            licenseInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("ppt转pdf失败");
        }
    }

    /**
     * txt文档转pdf
     * @param inputStream
     * @param outputStream
     */
    public static void txtToPdf(InputStream inputStream,OutputStream outputStream) {
        com.itextpdf.text.Document document = new com.itextpdf.text.Document();
        ClassPathResource classPathResource = new ClassPathResource("/font/simhei.ttf");
        try {
            PdfWriter.getInstance(document,outputStream);
            document.open();
            BaseFont baseFont = BaseFont.createFont(classPathResource.getPath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            Font font = new Font(baseFont);
            InputStreamReader isr = new InputStreamReader(inputStream, "GBK");
            BufferedReader bufferedReader = new BufferedReader(isr);
            String str = "";
            while ((str = bufferedReader.readLine()) != null) {
                document.add(new Paragraph(str, font));
            }
            document.close();
        } catch (DocumentException e) {
            e.printStackTrace();
            System.out.println("txt转pdf失败");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * cad文件转pdf
     * @param inputStream
     * @param outputStream
     */
    public static void cadToPdf(InputStream inputStream,OutputStream outputStream) {
        Image objImage = Image.load(inputStream);
        CadRasterizationOptions rasterizationOptions = new  CadRasterizationOptions();
        //设置属性
        rasterizationOptions.setBackgroundColor(Color.getBlack());
        rasterizationOptions.setPageWidth(1400);
        rasterizationOptions.setPageHeight(650);
        rasterizationOptions.setAutomaticLayoutsScaling(true);
        rasterizationOptions.setNoScaling (false);
        rasterizationOptions.setDrawType(1);
        PdfOptions pdfOptions = new PdfOptions();
        pdfOptions.setVectorRasterizationOptions(rasterizationOptions);
        objImage.save(outputStream,pdfOptions);
        objImage.close();
    }

}

三、使用工具类

@ApiOperation(value = "下载:文件(pdf格式)",notes = "下载文件(pdf格式)")
@GetMapping("/download/{fileId}")
public void download(@ApiParam(value = "fileId",required = true)
                             @PathVariable(value = "fileId",required = true)Integer fileId,
                             HttpServletResponse response) {
    InputStream in;
    try {
        Map<String,Object> file = commonService.getMaterialFile(fileId);
        String fileName = MapUtil.getString(file,"FILENAME");
        String extension = MapUtil.getString(file,"EXTENSION");
        String newFileName = fileName.substring(0,fileName.lastIndexOf("."));
        //原始下载操作
        in = commonService.downloadMaterial(fileId);
        response.setContentType("application/x-msdownload;charset=utf-8");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + URLEncoder.encode(newFileName+".pdf","UTF-8")+ "\"");
        OutputStream out = response.getOutputStream();
        //pdf的直接返回文件流
        if ("pdf".equalsIgnoreCase(extension)) {
            IOUtils.copy(in,out);
        }else {
            //其他类型转为pdf
            PdfUtil.othersToPdf(extension,in,out);
        }
        out.close();
        in.close();
    }catch (IOException e) {
        e.printStackTrace();
    }
}

四、前端使用pdfjs预览pdf

pdfjs结构

1.引入js后在html定义一个div
<!-- 全屏弹出框=>文件预览     -->
<div id="dialogFull" class="bui-dialog" style="display: none;">
    <div ng-show="!notSupport" class="bui-dialog-head">{{filePopUpData.FILENAME}}</div>
    <div ng-show="notSupport">当前文件不支持预览</div>
    <!-- pdf文件预览 -->
    <div class="bui-dialog-main" id="pdf-div" style="width: 100%;height: 900px">
    </div>
    <div class="bui-dialog-close"><i class="icon-close"></i></div>
</div>
2.对应html的js中将文件下载地址按格式拼接在预览地址后
//固定格式:/static/pdfjs/web/viewer.html?file=+文件路径
url = "../static/pdfjs/web/viewer.html?file=" + fileUrl;
$('#pdf-div').media({
    src: url,
    width: "100%",
    height: "667px"
});
//弹出
DialogFull.open();
评论 7
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值