页面PDF预览控件pdf.js使用总结

一、插件下载

下载地址:http://mozilla.github.io/pdf.js/

内含demo页面,打开后显示效果如图所示:

二、使用方法

将控件的相应文件引入




页面可在viewer.html的基础上修改

pdf文件引入方法

方法1:修改viewer.js文件,直接将defaultUrl.value修改为项目内引用的pdf文件路径。

defaultUrl: {
	value: '../../js/plug/pdfjs/web/2019.pdf',
	kind: OptionKind.VIEWER
},

方法2:url路径引用。http://127.0.0.1:8020/pdfjs/demo.html?file=20190601.pdf,直接将pdf文件地址作为file的值传给页面,pdf文件须和页面在同一服务器。或者file后跟服务端请求方法,方法返回为pdf文件流。

方法3:推荐。基于方法1修改,将服务端返回的PDF文件流返回给defaultUrl.value

var pdfUrlMine = "";
var PDFData="";
$(function(){
	var productparam = {
		'productId': localStorage.getItem("productId"),
		'loanAcno': sessionStorage.getItem("loanAcno")
	};
	var params = {
		'token': localStorage.getItem("token"),
		'param': JSON.stringify(productparam)
	};
	$.ajax({
		type:"post",
		async:false,
		data: params,
		mimeType: 'text/plain;charset=x-user-defined',
		url:requestUrl + "/contract/getLoanAgreement",
		success:function(data){
			PDFData = data;
			var rawLength = PDFData.length;
			var arrayBf = new ArrayBuffer(rawLength)
			var array = new Uint8Array(arrayBf);
			for(i = 0; i < rawLength; i++) {
				array[i] = PDFData.charCodeAt(i) & 0xff;
			}
			pdfUrlMine = array;
			$("#pmask").remove();
		},
		error: function(xhr, textStatus) {
			$("#pmask").remove();
			mui.toast('系统开小差了,请返回重试');
			console.log('错误');
			console.log(xhr)
			console.log(textStatus)
		},
		complete: function(XMLHttpRequest, status) {
			$("#pmask").remove();
			if(status == 'timeout') {
				mui.toast('提示:网络不稳定');
			}
			if(status == 'error'){
				mui.toast('系统出错了,请刷新后再试');
			}
		}
	});
});

注意:ajax方法中的mimeType: 'text/plain;charset=x-user-defined',

viewer.js文件中需要修改的地方:

//    if (origin !== viewerOrigin && protocol !== 'blob:') {
//      throw new Error('file origin does not match viewer\'s');
//    }

//file = 'file' in params ? params.file : _app_options.AppOptions.get('defaultUrl');
  file = 'file' in params ? params.file : pdfUrlMine;

defaultUrl: {
//	  value: '../../js/plug/pdfjs/web/2019.pdf',
	value:pdfUrlMine,
	kind: OptionKind.VIEWER
},

  cMapUrl: {
//  value: '../web/cmaps/',
	value: '../../js/plug/pdfjs/web/cmaps/',//根据实际路径修改
    kind: OptionKind.API
  },

java服务端代码:返回pdf流

@RequestMapping("/agreementPDF/{type}")	
public void getRemoteFile(@PathVariable("type") String type, HttpServletResponse response) {  
	List list = agreementTemplateMapper.selectAll();
	List collect = list.stream().filter(a -> StringUtils.equals(type, a.getType())).collect(Collectors.toList());
	if(ObjectUtils.isEmpty(collect)){
		return;
	}
	AgreementTemplate agreementTemplate = collect.get(0);
	InputStream inputStream = null;  
	try {  
		try {
			File file = new File(agreementTemplate.getUrl());
			FileInputStream fileInputStream = new FileInputStream(file);
			inputStream = new BufferedInputStream(fileInputStream);
			// 取得输入流,并使用Reader读取
			int bytesum = 0;
			int byteread = 0;
			byte[] buffer = new byte[1024];
			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes()));
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			response.setHeader("Access-Control-Allow-Origin","*");
			bytesum = 0;
			byteread = 0;
			buffer = new byte[1024];
			while ((byteread = inputStream.read(buffer)) != -1) {
				bytesum += byteread;
				toClient.write(buffer, 0, byteread);
			}
			toClient.flush();
			inputStream.close();
			
			toClient.close();
		} catch (Exception e) {  
			e.printStackTrace();
			inputStream = null;  
		}  
	} catch (Exception e) {  
		e.printStackTrace();
		inputStream = null;  
	}  
}

 

你可能感兴趣的:(前端)