pdf.js acceso remoto entre dominios + flujo de archivos de acceso

pdf.js acceso remoto entre dominios + flujo de archivos de acceso

Prólogo: antes de usar pdf.js, primero debe determinar si necesita acceder al archivo PDF de este proyecto, archivo PDF remoto, archivo PDF, flujo de archivo local o flujo de archivo PDF remoto. Lo que uso aquí es la ruta de la secuencia de archivos remota ( con mi conocimiento actual: se puede acceder y descargar la ruta de la secuencia de archivos directamente ). Hay muchos tutoriales en Internet, ya sea solo sobre el acceso entre dominios de pdf.js o sobre el acceso a la secuencia de archivos de pdf.js. Por tanto, habrá casos en los que algunas personas no puedan acceder a él. Solo porque el mío es la ruta de flujo del archivo PDF. Aquí hay un registro de cómo encontré el acceso entre dominios a las secuencias de archivos.

  1. Descargar pdf.js web oficial . No hay mucha introducción aquí, hay muchas introducciones sobre la estructura del catálogo en Internet. Puede ver la información relevante.
  2. Copie toda la carpeta descargada al proyecto (aquí utilizo el último pdfjs-2.5.207-dist). Esta es una página de inicio, simplemente cópiela en un lugar donde pueda acceder a la página. Como se muestra abajo:
    Inserte la descripción de la imagen aquí
  3. Aquí se deben abordar dos cuestiones: dominio cruzado y acceso a secuencias de archivos .

Para los archivos PDF de este proyecto , el acceso es muy simple: el siguiente código:

<!-- ../js/pdfjs-2.5.207-dist/web/viewer.html是viewer.html的访问路径,file=后面是PDF文件路径。还有其他的访问方式,这里就不多介绍了,网上有很多 -->
<a href='../js/pdfjs-2.5.207-dist/web/viewer.html?file=PDF文件'>点击预览</a>

Para el procesamiento remoto de archivos PDF : primero debe modificar el contenido de dos archivos, viewer.html y viewer.js.

  • Permítanme hablar primero sobre el archivo viewer.js . Hay muchos códigos de archivo. Se recomienda utilizar el método de búsqueda:
    busque el siguiente código:
function webViewerLoad() {
    
    
  var config = getViewerConfiguration();
  window.PDFViewerApplication = pdfjsWebApp.PDFViewerApplication;
  window.PDFViewerApplicationOptions = pdfjsWebAppOptions.AppOptions;
  var event = document.createEvent('CustomEvent');
  event.initCustomEvent('webviewerloaded', true, true, {
    
    });
  document.dispatchEvent(event);
  pdfjsWebApp.PDFViewerApplication.run(config);
}

Modifique el código de la siguiente manera. Puede comentar el código anterior y agregar el siguiente código. Así es como lo hice:

window.webViewerLoad=function webViewerLoad(fileUrl) {
    
    //调整了此行
  var config = getViewerConfiguration();
  window.PDFViewerApplication = pdfjsWebApp.PDFViewerApplication;
  window.PDFViewerApplicationOptions = pdfjsWebAppOptions.AppOptions;
  var event = document.createEvent('CustomEvent');
  event.initCustomEvent('webviewerloaded', true, true, {
    
    });
  document.dispatchEvent(event);
  //调整了if 语句
  if(fileUrl){
    
    
    config.defaultUrl=fileUrl;
  }
  pdfjsWebApp.PDFViewerApplication.run(config);
}
  • Comente el siguiente código, este código está debajo del código anterior:
if (document.readyState === 'interactive' || document.readyState === 'complete') {
    
    
  webViewerLoad();
} else {
    
    
  document.addEventListener('DOMContentLoaded', webViewerLoad, true);
}
  • Busque el siguiente código:
run: function run(config) {
    
    
	this.initialize(config).then(webViewerInitialized);
 }
  //我的文件中不是这样的,是下面代码,两者是一样的
run(config) {
    
    
	this.initialize(config).then(webViewerInitialized);
},

Modifique el código de la siguiente manera:

run: function run(config) {
    
    
	//添加if语句
	if(config.defaultUrl){
    
    
		_app_options.AppOptions.set('defaultUrl',config.defaultUrl)
	}    
	this.initialize(config).then(webViewerInitialized);
},
//我的修改是如下,其实一样
run(config) {
    
    
   //添加if语句
   if(config.defaultUrl){
    
    
     _app_options.AppOptions.set('defaultUrl',config.defaultUrl)
   }
   this.initialize(config).then(webViewerInitialized);
 },
  • El siguiente es el archivo viewer.html . Antes de la modificación, se debe introducir el archivo jquery , porque aquí se necesita la solicitud ajax para resolver el problema entre dominios. El código que se agrega a continuación no necesita cambiarse y puede usarse directamente.
<!-- 在<script src="viewer.js"></script>之前引入以下代码,再次强调,需要引入jquery -->
    <script type="text/javascript">
      $(()=>{
     
     
        //获取要跨域访问的pdf地址
        var url = getUrlParam("urlPath");
        console.log(url)
        xhrPdf(url,function(href){
     
     
          //调用viewer.js方法预览pdf
          webViewerLoad(href)
        })
      })
      //获取url中的参数
      function getUrlParam(name) {
     
     
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]); return null; //返回参数值
      }
      //添加xhrPdf函数
      function xhrPdf(urlPath,callback) {
     
     
        $.ajax({
     
     
          type: "post",
          async: false,
          mimeType: 'text/plain; charset=x-user-defined',
          url: "/WechatApp/manual/pdfStreamHandler", //请求服务器数据 获取pdf数据流,
          data:{
     
     
            urlPath:urlPath
          },
          success: function(data) {
     
     
            var rawLength = data.length;
            //转换成pdf.js能直接解析的Uint8Array类型,见pdf.js-4068
            var array = new Uint8Array(new ArrayBuffer(rawLength));
            for (var i = 0;i < rawLength; i++) {
     
     
              array[i] = data.charCodeAt(i) & 0xff;
            }
            var href = window.URL.createObjectURL(new Blob([array]));//数据流转换成createObjectURL能解析的Blob类型
            callback(href)   //返回url
          }
        });
      }
    </script>
  • Aquí no hay una solución real para el problema de dominios cruzados, se resuelve mediante conversión indirecta. Principalmente al llamar al mapeo de back-end, el archivo PDF se convierte en un flujo de archivos PDF para operar, este tutorial en línea está en todas partes. Pero, ¿qué pasa si la ruta ya conocida es la secuencia del archivo PDF? Aquí debe crear una solicitud en el controlador de back-end, realizar el procesamiento correspondiente y luego transmitir los datos de flujo al front-end, para que el front-end pueda acceder al archivo PDF.
    Lo trato de la siguiente manera: crea el siguiente mapeo
    @RequestMapping(value = "/pdfStreamHandler")
    public void getRemoteFile(String urlPath, HttpServletResponse response) {
    
    
        InputStream inputStream = null;
        try {
    
    
            try {
    
    
                String strUrl = urlPath.trim();
                URL url = new URL(strUrl);
                //打开请求连接
                URLConnection connection = url.openConnection();
                HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
                httpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                // 取得输入流,并使用Reader读取
                inputStream = httpURLConnection.getInputStream();
                /**
                 * 以上的操作处理是处理文件流的,如果访问的是远程PDF文件
                 * 可以直接new File("文件路径"),然后传给inputStream,
                 * 然后以下操作不变。
                 */
                int bytesum = 0;
                int byteread = 0;
                byte[] buffer = new byte[1024];
                // 清空response
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename=" + new String("cbzm.pdf".getBytes()));
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                bytesum = 0;
                byteread = 0;
                buffer = new byte[1024];
                while ((byteread = inputStream.read(buffer)) != -1) {
    
    
                    bytesum += byteread;
                    toClient.write(buffer, 0, byteread);
                }
                toClient.flush();
                inputStream.close();

                toClient.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
                inputStream = null;
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
            inputStream = null;
        }
    }
  • El método de llamada es el siguiente:
<!-- 其实和上面的调用没什么区别,知识把file换成了urlPath,如果需要自定义参数名的话,可以修改viewer.html中getUrlParam("urlPath")这个方法的参数,起成自己喜欢的名字 -->
<!-- 因为viewer.html的调用方法很多,我就这这样子举例,如果说想研究的话,可以尝试其他方法是否可以调用 -->
<a href='../js/pdfjs-2.5.207-dist/web/viewer.html?urlPath=PDF路径即可'>点击预览</a>
  • Articulo de referencia:
  • https://blog.csdn.net/wf001015/article/details/93307643?utm_medium=distribute.pc_relevant.none-task-blog-baidulandingword-2&spm=1001.2101.3001.4242
  • https://blog.csdn.net/baby97/article/details/83410628
  • https://www.cnblogs.com/best-coder/p/11550409.html

Supongo que te gusta

Origin blog.csdn.net/qq_30385099/article/details/110490911
Recomendado
Clasificación