【PDF-js】移动端使用pdfjs预览pdf文件

需求:
在预览这个pdf文件时候,PC端可以直接 放地址, 在手机端直接放会变成下载,所以就要使用 pdfjs 来实现

背景:
文件地址: http://www.alioss.test.com/files/laofan.pdf
我的项目域名: http://www.test.com

官网地址: http://mozilla.github.io/pdf.js/
下载稳定版本

目录结构如下。你要先访问 web目录里的 viewer.html

把文件放到你得项目静态文件里
那么你访问 www.test.com/web/viewer.html , 如下图

项目中配置使用

nginx 配置反向代理,此时就代表 /alioss/ 在项目中就代替了 http://www.alioss.test.com


    #代理第三方文件访问
    location /alioss/ {
      proxy_pass http://www.alioss.test.com/;
    }

php文件接收访问的文件 ,格式为:http://www.test.com/file_view?file_url=http://www.alioss.test.com/files/laofan.pdf

      /**
     *预览
     * 依然范儿特西
     */
    public function file_view(Request $request)
    {
        
        $file_url = input("file_url");
        $parts = parse_url($file_url);
        //此处的  /alioss/ 代表 nginx反向代理的名字替换,$parts 里边有了 / , 所以此处写 /alioss
        $fally_path_url = '/alioss'.$parts['path'];
        $this->assign("file_url",$fally_path_url);
        return $this->fetch('webview/file_view');
   }


简单使用就用这个就可以

<iframe  src="__CPLUGINS__/pdfjs-2.4.456/web/viewer.html?file={$file_url}"   frameborder="0" style="width: 100vw; height:100vh;"></iframe>

html 完整代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <title>文件预览</title>
</head>

<body style="margin: 0;">
    <iframe id="xy" src="__CPLUGINS__/pdfjs-2.4.456/web/viewer.html?file={$file_url}"   frameborder="0" style="width: 100vw; height:100vh;"></iframe>
</body>
    <script type="text/javascript" src="__MJS__/jquery-2.1.0.js" ></script>
    <script type="text/javascript">
        $('#xy').load(function(){
            $('#xy').contents().find('body').find('#secondaryToolbarToggle').hide();
            $('#xy').contents().find('body').find('#viewFind').hide();
            $('#xy').contents().find('body').find('#sidebarToggle').hide();
            $('#xy').contents().find('body').find('#toolbarViewerMiddle').css('float','right');
        });
    </script>
</html>

过程中出现的问题

问题1 : file origin does not match viewer

因为我是本服务器 远程访问 阿里oss 的文件资源, 出现跨域,
解决办法 网上说是 /web/viewer.js 要注释掉判断信息

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

注释之后,还是报错跨域,
解决办法: nginx代理 模式

问题2 页面显示不全,之后头部一点,下边一大片空白,
解决办法: 在 iframe 里边 加 行内样式

frameborder="0"  style="width: 100vw; height:100vh;"

问题 3 : 整个页面左右晃动
解决办法,body里 加

 style="margin: 0;"
posted @ 2020-06-05 16:10  依然范儿特西  阅读(3577)  评论(3编辑  收藏  举报