pdf.js跨域解决方法——远程加载pdf
pdf.js
PDF Reader in JavaScript
项目地址:https://gitcode.com/gh_mirrors/pd/pdf.js
免费下载资源
·
思路:通过将需要浏览的pdf通过后台转为文件流传给前端,来解决跨域问题。
js代码写在viewer.html里,放到引用pdf.js的位置前面
js代码,来接收文件流:
<script>
var PDFData = "";
$.ajax({
type:"get",
crossDomain:true,
async:false, // false是不采用异步的方式
mimeType:'text/plain;charset=x-user-defined',
url:"http://localhost:8080/Convert?type=getPdf",
success:function (data) {
PDFData = data; // data是byte[]数组
}
});
var rawLength = PDFData.length;
// 转换成pdf.js能直接解析的Uint8Array类型,见pdf.js-4068
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(var i = 0;i<rawLength;i++){
array[i] = PDFData.charCodeAt(i)&0xff;
}
var pdf_url = array;
</script>
后台,我写通过java了一个servlet来把文件转成文件流:
package main;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
@WebServlet(name = "Convert")
public class Convert extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/pdf");
response.setHeader("Access-Control-Allow-Origin", "*"); // 解决请求头跨域问题
ServletOutputStream sos = response.getOutputStream();
String destUrl = "http://39.107.117.248/pdf-store/caseFile.pdf";
URL url = new URL(destUrl);
HttpURLConnection httpUrl = (HttpURLConnection)url.openConnection();
// 连接指定的网络资源
httpUrl.connect();
// 获取网络输入流
BufferedInputStream bis = new BufferedInputStream(httpUrl.getInputStream());
int b;
while ((b = bis.read())!= -1){
sos.write(b);
}
sos.close(); // 这里有点和c语言里的读取文件有点像
bis.close();
}
}
参考链接:https://blog.csdn.net/anciend/article/details/80062213,感谢Anciend的分享
GitHub 加速计划 / pd / pdf.js
47.48 K
9.86 K
下载
PDF Reader in JavaScript
最近提交(Master分支:3 个月前 )
18284815
[Editor] Update the disclaimer string in the new alt-text dialog (bug 1911738) 3 个月前
fc602c65
And tweak the css in order to take into account that disclaimer can be on two (or more lines).
3 个月前
更多推荐
已为社区贡献3条内容
所有评论(0)