jsp页面在线显示pdf文件

实现功能

知识库系统中存在一个附件就是一个知识,当全文搜索到这个附件知识的时候需要能在线查看这个知识也就是附件里的文章内容。(如果不是pdf格式的文档,我们这边是先将不同格式的附件转成PDF格式)

实现代码

本项目中我在jsp页面中用了embed 标签

<embed :src="file/open.action" type="application/pdf" width="100%" height="100%">

标签里src的file/open.action里面主要是读写附件文件的IO流的一个action。直接上代码:

package com.ssm.controlle;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author chenjida
 * @create 2019-09-05
 */

@Controller
@RequestMapping("/file")
public class FileController {

    @RequestMapping("/openAttach")
    @ResponseBody
    public void openAttach(HttpServletResponse response) {

        FileInputStream fIn = null;
        OutputStream out = null;
        
        try {
            response.addHeader("Content-Disposition",
                    "filename=\"" + new String("D:\\7c8f4802-a6aa-4517-b7db-a752987fcf6c.pdf".getBytes("gb2312"), "ISO8859-1") + "\"");
            response.setHeader("Content-Type", "application/pdf");

            File file = new File("D:\\7c8f4802-a6aa-4517-b7db-a752987fcf6c.pdf");
            if(!file.exists()){
                return;
            }
            // 读取下载文件
            fIn = new FileInputStream(file);
            // 输出流
            out = response.getOutputStream();
            // 缓冲区
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fIn.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            } finally {
                IOUtils.closeQuietly(fIn);
                IOUtils.closeQuietly(out);
            }
    }
}

实现效果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值