1.官方下载
官网地址:http://mozilla.github.io/pdf.js/
解压,找到 viewer.js 注释掉 var DEFAULT_URL = 'compressed.tracemonkey-pldi-09.pdf';
2.JAVA WEB 项目中实现跨域
拷贝到java web项目中
新建pdf.jsp:
<%@page import="java.io.OutputStream"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.InputStreamReader"%>
<%@page import="java.io.IOException"%>
<%@page import="java.net.MalformedURLException"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.net.URLConnection"%>
<%@page import="java.net.URL"%>
<%@ page language="java" pageEncoding="UTF-8"%>
<%StringBuffer readOneLineBuff = new StringBuffer();
String pdfurl = request.getParameter("pdf_url"); //远程文件url
System.out.println("查看PDF : "+pdfurl);
OutputStream o = null;
InputStream in = null;
try {URL url = new URL(pdfurl);
URLConnection conn = url.openConnection();
in = conn.getInputStream();
o = response.getOutputStream();
int index = 0;
byte buffer[] = new byte[1024];
while ((index = in.read(buffer)) != -1) {
o.write(buffer , 0, index);
}out.clear();
out=pageContext.pushBody();
o.close();
in.close();
} catch (Exception e) {System.out.println("查看PDF -- 错误 : "+pdfurl);
o.close();
in.close();
}
%>
修改viewer.html head中添加这段js
<script>
var DEFAULT_URL = "pdf.jsp?pdf_url="+getQueryStringByName('pdf_url');
function getQueryStringByName(name){
var result = location.search.match(new RegExp("[\?\&]" + name+ "=([^\&]+)","i"));
if(result == null || result.length < 1){
return "";
}
return result[1];
}
</script>
访问格式 pdf_url 后为远程加载的pdf地址
http://localhost:8080/demo/pdfjs/web/viewer.html?pdf_url=http://file.xxxx.cn/file/0010800000028005Sys.pdf
3.PHP中实现跨域
项目拷贝到php环境中,同理 pdf.jsp 变为 pdf.php
内容为:
<?php echo file_get_contents($_GET['pdf_url']); ?>
4.DEMO下载
pdf.js在java web 中跨域演示 : pdfjs_demo