PDF.js在前后端<iframe>标签中在线预览PDF文件的使用心得

2022-09-30 13:07:54

前端时间项目中需要在前后端预览PDF文件(后端使用jsp,前端H5),因为页面中还包含点赞,分享等功能,所以考虑用<iframe>标签来打开PDF文件进行预览,之前没有做过所以花了点时间研究了一下,

现在记录一下,希望能够帮到有需要的朋友。(PDF.js可以在网上搜索自行下载,具体怎样使用PDF.js请自行搜索,这里不多讲)

1、后台jsp的使用

      项目中的PDF文件是上传到百度云的所以在上传和下载的时候依赖的这个包,上传后将路径保存在content字段中。

      后台读取上传在百度云上的PDF文件:

@RequestMapping(value = "/getPdfFile/{id}")
	public void getPDF(HttpServletResponse response,@PathVariable("id") String id) {
		try {
			Map<String,String> map = proReportService.getConfiguration();
			String bos_cdn = map.get("bos_cdn");
			ProReport proReport = proReportService.get(id);

			//处理content字段
			String content = proReport.getContent();
			if(content.contains("split-web-and-phone")){
				String[] contentStr = content.split("split-web-and-phone");
				if(contentStr.length>1){
					content = contentStr[1];
				}else{
					content = "";
				}
				proReport.setContent(content);
			}
			String pdfUrl = bos_cdn+proReport.getContent();

			URL url = new URL(pdfUrl);
			URLConnection con = url.openConnection();
			con.setConnectTimeout(3 * 1000);
			InputStream inputStream = con.getInputStream();
			response.setHeader("Content-Disposition", "attachment;fileName=test.pdf");
			response.setContentType("multipart/form-data");
			OutputStream outputStream = response.getOutputStream();
			IOUtils.write(IOUtils.toByteArray(inputStream), outputStream);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

   jsp页面展示:

<iframe src="<c:url value="${ctxStatic}/pdf/web/viewer.html" />?file=${ctx}/report/strategy/getPdfFile/${proReport.id} " frameborder="0" scrolling="auto" id="openPDF" style="width: 100%;height: 550px;"></iframe>

   需要在项目中引入PDF.js

   这样的话,在jsp页面使用<iframe>标签预览PDF基本就不会有问题,项目中加入了分享功能,在安卓和ios端打开分享连接也可以直接预览PDF文件。

2、APP端预览PDF文件(H5页面)

    首先在移动端引入PDF.js

    在后台组装好PDF文件的访问路径:

Map<String,String> stringMap = proReportService.getConfiguration();
			String bos_cdn = stringMap.get("bos_cdn");
			String pdfUrl = bos_cdn+content;
			map.put("pdfUrl", pdfUrl);

  然后在APP前端页面(H5)通过<iframe>标签预览,不过安卓和ios的实现方式有所不同:

if (m.os.plus && m.os.android) {
						self.isShow = '2';
						self.pdfUrl = "../../../js/pdf/web/viewer.html?file="+rs.pdfUrl;
					}else{
						self.isShow = '1';
						self.pdfUrl = app.api_url+"/static/pdf/web/viewer.html?file="+app.api_url+'/api/report/getPdfFile/'+self.detail.id;
					}

  安卓端可以直接通过PDF.js加上PDF文件路径预览,而ios则需要通过后台才能使用PDF.js预览(H5页面使用<iframe>标签在ios端使用安卓的那种方式预览PDF是有问题的,所以才通过后台的方式来预览)。

   H5页面使用<iframe>标签预览PDF(H5页面使用vue.js)

<iframe scrolling="auto" frameborder="0" :src="pdfUrl" width="100%" height="100%"></iframe>
  • 作者:lwl827
  • 原文链接:https://blog.csdn.net/lwl827/article/details/115196400
    更新时间:2022-09-30 13:07:54