PDF.js在访问pdf文件的时候,有时候会涉及到跨域问题,介绍一种.NET和PDF.js配合使用的方法。
前端代码:
<script type="text/javascript">
var PDFData = "";
$.ajax({
type: "get",
crossDomain: true,
async: false, // false是不采用异步的方式
mimeType: 'text/plain;charset=x-user-defined',
//这里是后台方法,根据实际情况编写自己的参数,主要是返回文件流
url: "http://localhost:61582/Seal/DownLoad?Name=20171107&ProjectId=1&SignCount=2",
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;
// var url = 'default.pdf';
var pdfh5 = new Pdfh5('.pdfjs', {
pdfurl: pdf_url
});
//监听当前加载的pdf页数,currentPageDom当前加载的pdf的dom,currentNum当前加载的pdf页数,
pdfh5.on("renderPages",function(currentPageDom){
console.log(this.currentNum)
console.log(pdfh5.currentNum)
})
</script>
注意前端代码那里的URL,根据实际情况编写所需参数,主要是返回文件流,就可以。
后端代码:
public void DownLoad(string Name, int ProjectId,int SignCount)
{
Response.ContentType = "application/x-zip-compressed";
Response.AddHeader("Content-Disposition", "attachment;filename=" + Name + ".pdf");
string filename = Server.MapPath(EM.getPdfpath((EM.ProjectFold)ProjectId) + (SignCount==1? "signone\\" : "signtwo\\") + Name + ".pdf");
Response.TransmitFile(filename);
}
filename根据项目实际情况,获取到文件所在路径地址,再使用上边的代码,这样就可以了。
注意webconfig中需要添加一个设置,在system.webServer中添加如下内容:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />
</customHeaders>
</httpProtocol>