springboot开发指南(七)——整合pdf.js预览打印下载pdf文件

项目简介:需要在浏览器预览pdf文件,并能打印下载

目录

一.项目效果

二.使用的技术和项目依赖

三. 前端pdfview.html

四.后端PreviewController


需要源码,请加微信号,进技术交流群,发送springboot109,免费获取此文章源码

一.项目效果

单击文字后,出现如下

二.使用的技术和项目依赖

1.项目使用pdf.js插件

(1)pdf插件下载以及预览请点击。http://mozilla.github.io/pdf.js/

(2)将PDF插件目录放在工程里

2.项目依赖

themleaf ,web

三. 前端pdfview.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>预览PDF文件</title>
</head>
<script>
	function previewPDF() {
		window.open("asserts/js/web/viewer.html?file=/preview");
	}
</script>
<body>
<a onclick="previewPDF()">Click here to preview the PDF</a>
</body>

注意:open地址是工程中pdf插件文件viewer.html地址加上file=/。如果open("preview"),则无法有打印下载效果。

四.后端PreviewController

@Controller
public class PreviewController {
    @RequestMapping("/pdfview")
    public String index() {
        return "pdfview";
    }
    @RequestMapping(value = "/preview", method = RequestMethod.GET)
    public void pdfStreamHandler(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("=================preview==============");
        //PDF文件地址
        File file = new File("/Users/whale/Documents/aaa.pdf");
        if (file.exists()) {
            byte[] data = null;
            FileInputStream input=null;
            try {
                input= new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);
                response.getOutputStream().write(data);
            } catch (Exception e) {
                System.out.println("pdf文件处理异常:" + e);
            }finally{
                try {
                    if(input!=null){
                        input.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个问题涉及到前后端的代码实现,需要分别给出前端和后端的代码示例。 前端实现: 1. 安装 pdf.js 库:可以使用 npm 安装,命令为 `npm install pdfjs-dist --save` 2. 在 Vue 组件中引入 pdf.js 库: ``` import pdfjsLib from 'pdfjs-dist' ``` 3. 在组件中定义预览 PDF 的方法,代码如下: ``` previewPdf() { // 从服务器获取 PDF 文件的 URL const url = 'http://localhost:8080/api/pdf/preview?fileId=1234567890' // 创建一个 canvas 用于绘制 PDF const canvas = this.$refs.previewCanvas // 获取 PDF 渲染上下文 const context = canvas.getContext('2d') // 加载 PDF 文件 pdfjsLib.getDocument(url).promise.then(pdf => { // 获取 PDF 第一页 pdf.getPage(1).then(page => { // 设置 canvas 尺寸与页面大小相同 const viewport = page.getViewport({scale: 1}) canvas.width = viewport.width canvas.height = viewport.height // 渲染 PDF 到 canvas 上 page.render({ canvasContext: context, viewport: viewport }) }) }) } ``` 4. 在模板中添加 canvas 和按钮,代码如下: ``` <template> <div> <canvas ref="previewCanvas"></canvas> <button @click="previewPdf">预览 PDF</button> </div> </template> ``` 后端实现: 1. 使用 Spring Boot 框架实现一个 RESTful API,用于获取 PDF 文件的 URL。代码示例如下: ``` @RestController @RequestMapping("/api/pdf") public class PdfController { @Autowired private SftpService sftpService; @GetMapping("/preview") public ResponseEntity<Resource> previewPdf(@RequestParam("fileId") String fileId) { // 从 SFTP 服务器上下载文件到本地临时目录 File tempFile = sftpService.download(fileId); // 将文件转换为 Spring Resource 对象 Path path = tempFile.toPath(); ByteArrayResource resource = null; try { resource = new ByteArrayResource(Files.readAllBytes(path)); } catch (IOException e) { e.printStackTrace(); } // 返回文件内容和响应头 HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + tempFile.getName()); headers.add(HttpHeaders.CONTENT_TYPE, "application/pdf"); headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(tempFile.length())); return ResponseEntity.ok() .headers(headers) .body(resource); } } ``` 2. 在 Spring Boot 应用程序中配置 SFTP 服务器连接信息和文件保存路径,代码示例如下: ``` @Configuration public class SftpConfig { @Value("${sftp.host}") private String host; @Value("${sftp.port}") private int port; @Value("${sftp.username}") private String username; @Value("${sftp.password}") private String password; @Value("${sftp.remoteDirectory}") private String remoteDirectory; @Value("${sftp.localDirectory}") private String localDirectory; @Bean public SftpService sftpService() { SftpConfig config = new SftpConfig(); config.setHost(host); config.setPort(port); config.setUsername(username); config.setPassword(password); config.setRemoteDirectory(remoteDirectory); config.setLocalDirectory(localDirectory); return new SftpServiceImpl(config); } } ``` 3. 实现 SftpService 接口,用于下载 PDF 文件到本地临时目录。代码示例如下: ``` public interface SftpService { File download(String fileId); } @Service public class SftpServiceImpl implements SftpService { private final SftpConfig config; public SftpServiceImpl(SftpConfig config) { this.config = config; } @Override public File download(String fileId) { Session session = null; ChannelSftp channel = null; try { JSch jsch = new JSch(); session = jsch.getSession(config.getUsername(), config.getHost(), config.getPort()); session.setPassword(config.getPassword()); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); channel = (ChannelSftp) session.openChannel("sftp"); channel.connect(); channel.cd(config.getRemoteDirectory()); // 生成本地临时文件名 String localFileName = UUID.randomUUID().toString() + ".pdf"; File localFile = new File(config.getLocalDirectory() + File.separator + localFileName); // 下载文件到本地临时目录 channel.get(fileId, localFile.getAbsolutePath()); return localFile; } catch (JSchException | SftpException e) { e.printStackTrace(); } finally { if (channel != null) { channel.disconnect(); } if (session != null) { session.disconnect(); } } return null; } } ``` 需要注意的是,SFTP 服务器的连接信息需要在配置文件中进行配置,例如: ``` sftp.host=192.168.1.100 sftp.port=22 sftp.username=admin sftp.password=123456 sftp.remoteDirectory=/pdf sftp.localDirectory=/tmp ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值