.net C# 让pdf.js显示远程pdf文件

   

   

   1.下载pdf.js

   官网下载页面:http://mozilla.github.io/pdf.js/getting_started/#download

   下载链接:https://github.com/mozilla/pdf.js/releases/download/v2.0.943/pdfjs-2.0.943-dist.zip

   

   解压出来放到web目录下访问里面的viewr.html (不能直接双击打开访问)

   

   如:

   localhost:8888/Scripts/pdfjs-2.0.943/web/viewer.html

    

   2.C# 后端代码 这里用的mvc,用aspx的话也一样,只是访问url有所不同.

using System;        
using System.Net;        
using System.Web.Mvc;       
        
namespace Himall.Web.Areas.Web.Controllers
{        
    public class TransformController : Controller        
    {        
        // GET: Web/Transform        
        public string Index()        
        {        
            return "";        
        }      
        
        public void Pdf(string url="")        
        {        
            try        
            {
        
                using (WebClient wc = new WebClient())        
                {        
                    Uri uri = new Uri(url);        
                    byte[] buffer = wc.DownloadData(uri);     
        
                    Response.AddHeader("Content-Length", buffer.Length.ToString());        
                    Response.ContentType = "application/pdf";        
                    Response.AddHeader("Content-Disposition", "inline;FileName=local.pdf");       

                    Response.BinaryWrite(buffer);        
                    Response.OutputStream.Flush();        
                    Response.OutputStream.Close();        
                };        
            }        
            catch (Exception ex)        
            {        
                Response.Write(ex.Message);        
            }                
        }        
    }        
}

   

   3.网上随手搜索一个pdf文档(不小心搜到了国务院的文件)作为参数传进去:

   localhost:8888/Transform/pdf?url=http://www.gov.cn/zhengce/pdfFile/2019_PDF.pdf

   

   注:如果把pdf放在iframe里嵌套在页面上显示,url部分要encode

<iframe width="910" height="600" frameborder="0" scrolling="auto" src="/Scripts/pdfjs-2.0.943/web/[email protected]("/TransformResource/pdf?url="+resourceUrl)"></iframe>

 

   效果:

pdf.js

   

   

   原因:pdf.js只能显示本服务器文件

   

   原理:把远程pdf以byte[]的格式读取到本地再在页面上转成pdf的方式再给pdf.js

     

类别:DotNET   阅读(0)   评论(0)    发表时间:2019-05-18 16:32  星期六

评论区

发表评论

        姓名:
邮箱|网站:
        内容:

  (可按Ctrl+Enter提交)