openOffice pdf.js spring boot 微信在线预览office pdf文件

文章介绍了一个Java应用,该应用结合OpenOffice和JODConverter库将不同格式的文档转换为PDF,并且利用pdf.js展示在线预览。用户通过提供URL,系统首先将文件转换为PDF,然后使用pdf.js在浏览器中呈现预览。
摘要由CSDN通过智能技术生成

在这里插入图片描述

下载openoffice 并安装

//pdf.js 案例
https://mozilla.github.io/pdf.js/examples/index.html#interactive-examples

//openoffice 连接不上 进入安装目录 cmd 运行以下命令
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
       <!--openoffice-->
        <dependency>
            <groupId>com.artofsolving</groupId>
            <artifactId>jodconverter</artifactId>
            <version>2.2.1</version>
        </dependency>

import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;


/**
 * office 转 pdf 工具
 *
 * @author kong
 */
public class OfficeTools {
    /**
     * 默认转换后文件后缀
     */
    private static final String DEFAULT_SUFFIX = "pdf";
    /**
     * openoffice port
     */
    private static final Integer OPENOFFICE_PORT = 8100;

    /**
     * 方法描述  将文件以流的形式转换
     *
     * @param is     源文件输入流
     * @param suffix 源文件后缀
     * @return InputStream 转换后文件输入流
     */
    public static InputStream covert(InputStream is, String suffix) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        OpenOfficeConnection conn = new SocketOpenOfficeConnection(OPENOFFICE_PORT);
        conn.connect();
        DocumentConverter converter = new StreamOpenOfficeDocumentConverter(conn);
        DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
        DocumentFormat targetFormat = formatReg.getFormatByFileExtension(DEFAULT_SUFFIX);
        DocumentFormat sourceFormat = formatReg.getFormatByFileExtension(suffix);
        converter.convert(is, sourceFormat, out, targetFormat);
        conn.disconnect();
        return outputStreamConvertInputStream(out);
    }

    /**
     * 方法描述 outputStream转inputStream
     */
    public static ByteArrayInputStream outputStreamConvertInputStream(final OutputStream out) throws Exception {
        ByteArrayOutputStream os = (ByteArrayOutputStream) out;
        return new ByteArrayInputStream(os.toByteArray());
    }

}

import com.jianmu.constant.SysApiConstant;
import com.jianmu.exception.ErrorException;
import com.jianmu.service.i.UploadService;
import com.jianmu.tools.OfficeTools;
import com.jianmu.tools.OssFileTools;
import com.jianmu.tools.log.LogTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author kong
 */
@RestController
@RequestMapping(SysApiConstant.OPEN_MOBILE_API + "office")
public class MbOpenOfficeApi {

    private final UploadService uploadService;

    @Autowired
    public MbOpenOfficeApi(UploadService uploadService) {
        this.uploadService = uploadService;
    }

    /**
     * office在线预览接口
     */
    @GetMapping("/preview")
    public void preview(@RequestParam("url") String url, HttpServletResponse response) {
        //获取文件类型
        String suffix = url.substring(url.lastIndexOf(".") + 1);
        //
        String defaultConvertSuffix = "doc";
        if (!defaultConvertSuffix.equals(suffix)) {
            throw new ErrorException("文件格式不支持预览");
        }
        try (InputStream is = OssFileTools.getOssFileInputStream(url, this.uploadService.getUploadConfig());
             InputStream in = OfficeTools.covert(is, suffix);
             OutputStream outputStream = response.getOutputStream()) {
            byte[] buff = new byte[1024];
            int n;
            while ((n = in.read(buff)) != -1) {
                outputStream.write(buff, 0, n);
            }
            outputStream.flush();
        } catch (Exception e) {
            LogTools.err(e);
        }
    }
}

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.3.122/pdf.min.js"></script>
</head>

<body>
    <canvas id="the-canvas"></canvas>

    <script>

        // 通过 <script> 标签加载,创建访问 PDF.js 导出的快捷方式。
        var pdfjsLib = window['pdfjs-dist/build/pdf'];

        // 使用 DocumentInitParameters 对象加载二进制数据。
        var loadingTask = pdfjsLib.getDocument(
            "http://192.168.3.56:8700/vt/api/mb/open/office/preview?url=upload/doc/20230217095659/1626400282622058498.doc"
            );
        loadingTask.promise.then(function (pdf) {
            console.log('PDF loaded');

            // 获取第一页
            var pageNumber = 1;
            pdf.getPage(pageNumber).then(function (page) {
                console.log('Page loaded');

                var scale = 1.5;
                var viewport = page.getViewport({
                    scale: scale
                });

                // Prepare canvas using PDF page dimensions
                var canvas = document.getElementById('the-canvas');
                var context = canvas.getContext('2d');
                canvas.height = viewport.height;
                canvas.width = viewport.width;

                // 将 PDF 页面渲染到画布上下文中
                var renderContext = {
                    canvasContext: context,
                    viewport: viewport
                };
                var renderTask = page.render(renderContext);
                renderTask.promise.then(function () {
                    console.log('Page rendered');
                });
            });
        }, function (reason) {
            // PDF加载错误
            console.error(reason);
        });
    </script>
</body>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

等一场春雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值