Springboot实现PDF预览、下载、读取

背景:项目中实现pdf文件的预览以及下载

  • 环境:jdk1.8、SpringBoot2.0
  • PDF.js下载地址将下载的源码拷入项目中
  • 修改viewer.js:
将defaultUrl: {
    value: 'compressed.tracemonkey-pldi-09.pdf',---此处是默认的pdf的路径
    kind: OptionKind.VIEWER
  }
  修改为:
  defaultUrl: {
    value: '',
    kind: OptionKind.VIEWER
  }
  • 打开新窗口预览:
     <input type="button" value="预览" id="viewBtn">
	<script type="text/javascript">
		$("#viewBtn")
				.click(
						function() {
							var curWwwPath = window.document.location.href;
							var pathName = window.document.location.pathname;
							var pos = curWwwPath.indexOf(pathName);
							var localhostPath = curWwwPath.substring(0, pos);
							window.open(localhostPath
											+ "/js/pdf/web/viewer.html?file="
											+ encodeURIComponent("/preview?fileName=0602.pdf"));
						});
	//后台controller代码,根据前端传入的fileName到指定目录读取pdf文件,进行展示
	@RequestMapping(value = "/preview", method = RequestMethod.GET)
	public void prePDF(String fileName, HttpServletRequest request, HttpServletResponse response) {
		logger.info("文件名:" + fileName);
		File file = new File("E:/pdf/" + fileName);
		if (file.exists()) {
			byte[] data = null;
			try {
				FileInputStream input = new FileInputStream(file);
				data = new byte[input.available()];
				input.read(data);
				response.getOutputStream().write(data);
				input.close();
			} catch (Exception e) {
				logger.info("pdf文件处理异常...");
			}
		}
	}
  • PDF文件下载:
<input type="button" value="下载" id="download">
$("#download").click(function() {
			var form = $("<form>");
			form.attr("style", "display:none");
			form.attr("target", "");
			form.attr("method", "post");//提交方式为post
			form.attr("action", "/downloadFile");//定义action
			$("body").append(form);
			form.submit();
		});
//后台代码
@RequestMapping(value="/downloadFile")
	public void downloadFile(HttpServletResponse response) {
		String downloadFilePath = "E:/pdf/";	//被下载的文件在服务器中的路径,
		String fileName = "0602.pdf";			//被下载文件的名称
	
		File file = new File(downloadFilePath+fileName);
		if (file.exists()) {
			response.setContentType("application/force-download");// 设置强制下载不打开            
			response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
			byte[] buffer = new byte[1024];
			FileInputStream fis = null;
			BufferedInputStream bis = null;
			try {
				fis = new FileInputStream(file);
				bis = new BufferedInputStream(fis);
				OutputStream outputStream = response.getOutputStream();
				int i = bis.read(buffer);
				while (i != -1) {
				  outputStream.write(buffer, 0, i);
				  i = bis.read(buffer);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if(bis != null) {
					try {
						bis.close();
					}catch(IOException e) {
						e.printStackTrace();
					}
				}
				if(fis != null) {
					try {
						fis.close();
					}catch(IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

  • 预览页面顶部会有相应的工具栏,打印、下载、翻页、放大等,根据个人实际需要,可以查看页面源码,在viewer.html中注释掉相应的功能.

  • 也可以通过pdfbox读取PDF文件内容:

引入jar包:
<!-- PDF读取依赖 -->
		<dependency>
			<groupId>org.apache.pdfbox</groupId>
			<artifactId>pdfbox</artifactId>
			<version>2.0.4</version>
		</dependency>

后台读取pdf文件代码:

public String viewPDF(String proCode,String fileName,String originPage, HttpServletRequest request) {
		request.setAttribute("dse_sessionId", request.getParameter("dse_sessionId").trim());
		logger.info("披露报告预览文件名:" + fileName);
		File file = new File(constant.getExposeLocalDir() + fileName);
		if (!file.exists()) { // 文件不存在,则 从FTP下载文件到本地
			}
		}
		//读取pdf文件内容-代码实现
		try {
			PDDocument document = PDDocument.load(file);
			document.getClass();
			if(!document.isEncrypted()) {
				PDFTextStripperByArea stripper = new PDFTextStripperByArea();
				stripper.setSortByPosition(true);
				PDFTextStripper textStripper = new PDFTextStripper();
				String exposeContent = textStripper.getText(document);
				String[] content = exposeContent.split("\\n");
				StringBuffer stringBuffer = new StringBuffer();
				for(String line:content) {
					stringBuffer.append(line); 
				}
			}
			
		} catch (Exception e) {
			logger.info("读取pdf文件异常...");
		}
	
		return "";
	}
  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现PDF预览可以使用以下步骤: 1. 后端使用SpringBoot框架,引入pdfbox库(可以使用Maven等工具进行管理),用于读取PDF文件内容。 2. 前端使用Vue框架,引入pdf.js库,用于在网页中展示PDF文件。 3. 后端提供一个接口,用于获取PDF文件内容,并返回给前端。 4. 前端通过Ajax请求后端接口,获取PDF文件内容,并使用pdf.js库在网页中展示PDF文件。 具体实现步骤如下: 后端实现: 1. 在pom.xml文件中添加pdfbox依赖: ```xml <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.17</version> </dependency> ``` 2. 定义一个Controller,提供一个接口用于获取PDF文件内容: ```java @RestController @RequestMapping("/api/pdf") public class PdfController { @GetMapping("/{filename}") public String getPdfContent(@PathVariable String filename) throws IOException { File file = new File("path/to/pdf/" + filename); PDDocument document = PDDocument.load(file); PDFTextStripper stripper = new PDFTextStripper(); String content = stripper.getText(document); document.close(); return content; } } ``` 3. 启动SpringBoot应用,访问`http://localhost:8080/api/pdf/test.pdf`即可获取test.pdf文件的内容。 前端实现: 1. 在Vue组件中引入pdf.js库: ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.3.200/pdf.min.js"></script> ``` 2. 在Vue组件中定义一个方法,用于获取PDF文件内容并展示: ```javascript methods: { loadPdf(filename) { axios.get(`/api/pdf/${filename}`) .then(response => { const data = response.data; const pdfDoc = pdfjsLib.getDocument({data: data}); pdfDoc.promise.then(pdf => { for (let i = 1; i <= pdf.numPages; i++) { pdf.getPage(i).then(page => { const canvas = document.createElement('canvas'); const scale = 1.5; const viewport = page.getViewport({scale: scale}); const context = canvas.getContext('2d'); canvas.height = viewport.height; canvas.width = viewport.width; const renderContext = { canvasContext: context, viewport: viewport }; page.render(renderContext).promise.then(() => { const img = canvas.toDataURL(); // 将img添加到页面中展示 }); }); } }); }) .catch(error => { console.error(error); }); } } ``` 3. 调用loadPdf方法,传入PDF文件名即可展示PDF文件。 以上就是使用SpringBoot和Vue实现PDF预览的步骤,可以根据实际需求进行调整和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值