SpringBoot在线预览PDF文件

本项目Demo使用了PDF.js插件实现PDF在线阅读功能PDF.js插件下载地址

1、创建SpringBoot项目,目录结构如下:

SpringBoot在线预览PDF文件_第1张图片

2、进行项目配置:

pom.xml:


	4.0.0
	com.han
	online-read-pdf
	0.0.1-SNAPSHOT
	
		org.springframework.boot
		spring-boot-starter-parent
		1.5.10.RELEASE
		
	
	
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			org.springframework.boot
			spring-boot-starter-thymeleaf
		
	

application.yml

spring.thymeleaf.cache = false
spring.thymeleaf.content-type = text/html
spring.thymeleaf.encoding = UTF-8
spring.thymeleaf.mode = HTML5
spring.thymeleaf.prefix = classpath:/templates/
spring.thymeleaf.suffix = .html	

PDFApplication.java

package com.han;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class PDFApplication {
	public static void main(String[] args) {
		SpringApplication.run(PDFApplication.class, args);
	}
}

IndexController.java

package com.han.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class IndexController {
	@RequestMapping("/index")
	public String index() {
		return "index";
	}
	@RequestMapping(value = "/preview", method = RequestMethod.GET)
	public void pdfStreamHandler(HttpServletRequest request, HttpServletResponse response) {
        //PDF文件地址
		File file = new File("E:\\pdf\\pdf\\GJB 8748-2015(GJB 6482-2008k).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();
				}
			}
		}
	}
}

index.html





在线阅读PDF文件



	

在线阅读PDF文件

运行结果效果图:

SpringBoot在线预览PDF文件_第2张图片

项目源码下载地址:https://download.csdn.net/download/semial/11142874

你可能感兴趣的:(SpringBoot)