精华内容
下载资源
问答
  • vue下载pdf文件

    千次阅读 2020-12-07 14:19:55
    注意这个npm下载的这个download.js是有问题的,它能下载下来pdf文件,但是打不开这个pdf,在文章末尾的话,我会附上一个修改完的js。 <template> <div class="home"> <!-- <HelloWorld @...

    一、引入download.js

    npm install downloadjs 
    地址:https://www.npmjs.com/package/downloadjs
    

    注意这个npm下载的这个download.js是有问题的,它能下载下来pdf文件,但是打不开这个pdf,在文章末尾的话,我会附上一个修改完的js。

    <template>
      <div class="home">
        <!-- <HelloWorld @listener="show" ref="child" />
        <span>这是父组件的样式:</span> <span class="cssColor">color</span> -->
        <button @click="down">下载</button>
      </div>
    </template>
    
    <script>
    // @ is an alias to /src
    // 引入download.js
    import download from "downloadjs";
    export default {
      mounted() {
        // eslint-disable-next-line no-console
      },
      methods: {
        down() {
        /*我们只是需要这个地址放到这个里面就可以了*/
          download(
            "http://myweb-bucket.oss-cn-beijing.aliyuncs.com/2020/10/17/3fb95de68d8d45ebbf31d2c8f0724490新建 DOC 文档 (2).pdf"
          );
        }
      }
    };
    </script>
    <style lang="scss" scoped>
    /deep/ .cssColor {
      color: red;
    }
    </style>
    

    // 你下载完后,需要替换一下你的这个js,这个才是可靠的

    //download.js v4.21, by dandavis; 2008-2018. [MIT] see http://danml.com/download.html for tests/usage
    // v1 landed a FF+Chrome compatible way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
    // v2 added named files via a[download], msSaveBlob, IE (10+) support, and window.URL support for larger+faster saves than dataURLs
    // v3 added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support. 3.1 improved safari handling.
    // v4 adds AMD/UMD, commonJS, and plain browser support
    // v4.1 adds url download capability via solo URL argument (same domain/CORS only)
    // v4.2 adds semantic variable names, long (over 2MB) dataURL support, and hidden by default temp anchors
    // https://github.com/rndme/download
    
    /**
     * @typedef {Object} RequestData
     * @property {String} url - file url to download
     * @property {String} filename - custom filename to save
     * @property {String} data - data to save
     * @property {String} mimetype - custom file type
     */
    
    (function (root, factory) {
    	if (typeof define === 'function' && define.amd) {
    		// AMD. Register as an anonymous module.
    		define([], factory);
    	} else if (typeof exports === 'object') {
    		// Node. Does not work with strict CommonJS, but
    		// only CommonJS-like environments that support module.exports,
    		// like Node.
    		module.exports = factory();
    	} else {
    		// Browser globals (root is window)
    		root.download = factory();
      }
    }(this, function () {
    	var self = window, // this script is only for browsers anyway...
    		defaultMime = "application/octet-stream", // this default mime also triggers iframe downloads
    		blob,
    		reader,
    		anchor = document.createElement("a"),
    		toString = function (a) { return String(a); },
    		myBlob = (self.Blob || self.MozBlob || self.WebKitBlob || toString),
    		myBlob= myBlob.call ? myBlob.bind(self) : Blob ;
    	
    	var processData = function(payload, fileName, mimeType){
    		//go ahead and download dataURLs right away
    		if(/^data:([\w+-]+\/[\w+.-]+)?[,;]/.test(payload)){
    		
    			if(payload.length > (1024*1024*1.999) && myBlob !== toString ){
    				payload=dataUrlToBlob(payload);
    				mimeType=payload.type || defaultMime;
    			}else{			
    				return navigator.msSaveBlob ?  // IE10 can't do a[download], only Blobs:
    					navigator.msSaveBlob(dataUrlToBlob(payload), fileName) :
    					saver(payload) ; // everyone else can save dataURLs un-processed
    			}
    			
    		}else{//not data url, is it a string with special needs?
    			if(/([\x80-\xff])/.test(payload)){			  
    				var i=0, tempUiArr= new Uint8Array(payload.length), mx=tempUiArr.length;
    				for(i;i<mx;++i) tempUiArr[i]= payload.charCodeAt(i);
    			 	payload=new myBlob([tempUiArr], {type: mimeType});
    			}		  
    		}
    		blob = payload instanceof myBlob ?
    			payload :
    			new myBlob([payload], {type: mimeType}) ;
    
    		function dataUrlToBlob(strUrl) {
    			var parts= strUrl.split(/[:;,]/),
    			type= parts[1],
    			indexDecoder = strUrl.indexOf("charset")>0 ? 3: 2,
    			decoder= parts[indexDecoder] == "base64" ? atob : decodeURIComponent,
    			binData= decoder( parts.pop() ),
    			mx= binData.length,
    			i= 0,
    			uiArr= new Uint8Array(mx);
    
    			for(i;i<mx;++i) uiArr[i]= binData.charCodeAt(i);
    
    			return new myBlob([uiArr], {type: type});
    		 }
    
    		function saver(url, winMode){
    
    			var _clickEvt = function(e) {
    				e.stopPropagation();
    				this.removeEventListener('click', _clickEvt);
    			}
    			if ('download' in anchor) { //html5 A[download]
    				anchor.href = url;
    				anchor.setAttribute("download", fileName);
    				anchor.className = "download-js-link";
    				anchor.innerHTML = "downloading...";
    				anchor.style.display = "none";
    				
    				anchor.addEventListener('click', _clickEvt);
    				document.body.appendChild(anchor);
    				setTimeout(function() {
    					anchor.click();
    					document.body.removeChild(anchor);
    					if(winMode===true){setTimeout(function(){ self.URL.revokeObjectURL(anchor.href);}, 250 );}
    				}, 66);
    				return true;
    			}
    
    			// handle non-a[download] safari as best we can:
    			if(/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
    				if(/^data:/.test(url))	url="data:"+url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
    				if(!window.open(url)){ // popup blocked, offer direct download:
    					if(confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")){ location.href=url; }
    				}
    				return true;
    			}
    
    			//do iframe dataURL download (old ch+FF):
    			var f = document.createElement("iframe");
    			document.body.appendChild(f);
    
    			if(!winMode && /^data:/.test(url)){ // force a mime that will download:
    				url="data:"+url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
    			}
    			f.src=url;
    			setTimeout(function(){ document.body.removeChild(f); }, 333);
    
    		}//end saver
    
    		if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
    			return navigator.msSaveBlob(blob, fileName);
    		}
    
    		if(self.URL){ // simple fast and modern way using Blob and URL:
    			saver(self.URL.createObjectURL(blob), true);
    		}else{
    			// handle non-Blob()+non-URL browsers:
    			if(typeof blob === "string" || blob.constructor===toString ){
    				try{
    					return saver( "data:" +  mimeType   + ";base64,"  +  self.btoa(blob)  );
    				}catch(y){
    					return saver( "data:" +  mimeType   + "," + encodeURIComponent(blob)  );
    				}
    			}
    
    			// Blob but not URL support:
    			reader=new FileReader();
    			reader.onload=function(e){
    				saver(this.result);
    			};
    			reader.readAsDataURL(blob);
    		}
    		return true;
    	}
    
    	/**
    	 * data maybe String|{RequestData}|Blob, can download file with url given
    	 * strFileName if provided, it only work with data saver
    	 * strMimeType type of mime type, work like strFileName
    	 */
    	return function download(data, strFileName, strMimeType) {
    		var mimeType = strMimeType || defaultMime,
    			payload = data,
    			url = !strFileName && !strMimeType && payload,
    			fileName = strFileName || "";
    
    	  
    		if(String(this)==="true"){ //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
    			payload=[payload, mimeType];
    			mimeType=payload[0];
    			payload=payload[1];
    		}
    
    		if (data instanceof Object) {
    			if ('url' in data || 'data' in data) { // indicate this is new request type
    				url = data['url'] || false;
    				payload = data['data'];
    				fileName = data['filename'] || fileName;
    				mimeType = data['mimetype'] || mimeType;
    			} else {
    				return false;
    			}
    		}
    
    
    		if (url && url.length < 2048) { // if no filename and no mime, assume a url was passed as the only argument
    			fileName = fileName || url.split("/").pop().split("?")[0];
    			anchor.href = url; // assign href prop to temp anchor
    			if (anchor.href.match(/^https?:\/\//) != null) { // if the browser determines that it's a potentially valid url path:
    				var ajax = new XMLHttpRequest();
    				ajax.open("GET", url, true);
    				ajax.responseType = 'blob';
    				ajax.onload = function (e) {
    					//   download(e.target.response, fileName, defaultMime);
    					processData(e.target.response, fileName, defaultMime);
    				};
    				setTimeout(function () { ajax.send(); }, 0); // allows setting custom ajax headers using the return:
    				return ajax;
    			} // end if valid url?
    		} else { // end if url?
    			processData(payload, fileName, mimeType);
    		}
    	}; /* end download() */
    }));
    

    简单记录一下遇到的问题,如果有帮助到你记得三连。

    展开全文
  • vue 下载pdf文件

    千次阅读 2019-11-19 16:57:10
    首先安装依赖 npm install html2canvas jspdf --save 封装方法: // pdfMethod.js ...点这里下载 ...这里用class类名包裹的所有html样式都会按照vue展现的样式被canvas绘出来并以pdf文件输出
    1. 首先安装依赖npm install html2canvas jspdf --save
    2. 封装方法:
    // pdfMethod.js
    import html2canvas from 'html2canvas'
    import JsPDF from 'jspdf'
    const generateResume = (el, name) => {
      html2canvas(el).then(canvas => {
        let contentWidth = canvas.width
        let contentHeight = canvas.height
        //一页pdf显示html页面生成的canvas高度;
        let pageHeight = (contentWidth / 592.28) * 841.89
        //未生成pdf的html页面高度
        let leftHeight = contentHeight
        //页面偏移
        let position = 0
        //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
        let imgWidth = 595.28
        let imgHeight = (592.28 / contentWidth) * contentHeight
        let pageData = canvas.toDataURL('image/jpeg', 1.0)
        let pdf = new JsPDF('', 'pt', 'a4')
        //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
        //当内容未超过pdf一页显示的范围,无需分页
        if (leftHeight < pageHeight) {
          pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
        } else {
          while (leftHeight > 0) {
            //arg3-->距离左边距;arg4-->距离上边距;arg5-->宽度;arg6-->高度
            pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
            leftHeight -= pageHeight
            position -= 841.89
            //避免添加空白页
            if (leftHeight > 0) {
              //添加新页
              pdf.addPage()
            }
          }
        }
        pdf.save(`${name}.pdf`)
      })
    }
    export default generateResume
    
    1. 开始使用:
    <template>
      <div class="priview_resume_container">
        <div style="font-size: 30px" @click="getResume">点这里下载</div>
      </div>
    </template>
    
    <script>
      export default {
        name: 'priviewResume',
        methods: {
          getResume() {
            generateResume(
            document.getElementsByClassName('priview_resume_container')[0],
            '测试'
            )
          }
        },
        components: {}
      }
    </script>
    

    这里用class类名包裹的所有html样式都会按照vue展现的样式被canvas绘出来并以pdf文件输出

    展开全文
  • vue下载本地pdf文件

    千次阅读 2020-02-19 14:03:08
    Vue下载本地pdf文件 html: <button @click="downloadPDf">downloadPDf</button> js: downloadPDf() { axios.post('http://localhost:8080/static/test....

    Vue下载本地pdf文件

    html:

    <button @click="downloadPDf">downloadPDf</button>
     

    js:

    
     
    1. downloadPDf() {
    2. axios.post( 'http://localhost:8080/static/test.pdf', {
    3. responseType: 'blob', //重要
    4. }).then( response => {
    5. const url = window.URL.createObjectURL( new Blob([response.data]));
    6. const link = document.createElement( 'a');
    7. let fname = 'report.pdf';
    8. link.href = url;
    9. link.setAttribute( 'download', fname);
    10. document.body.appendChild(link);
    11. link.click();
    12. })
    13. }
    14. }

    记住本地文件一定要放在static文件夹下面。

    展开全文
  • vue项目,axios去请求...//下载用户手册PDF时请求的接口 export const getGuide = (param) => { return request({ url:"请求url", method:"get", params:param, //一定要加responseType responseType: "blob

    vue项目,axios去请求接口

    request文件中代码:

    import request from "封装好的axios请求文件"
    
    //下载用户手册PDF时请求的接口
    export const getGuide = (param) => {
        return request({
          url:"请求url",
          method:"get",
          params:param,
          //一定要加responseType
          responseType: "blob"
        })
      }
    

    页面中点击下载按钮时,去请求文件流,然后执行下载操作
    代码如下:

    downloadGuide(){
            getGuide().then(res => {
              let blob = new Blob([res], {type: 'application/pdf'});
              let downloadElement = document.createElement("a");
              let href = window.URL.createObjectURL(blob); //创建下载的链接
              downloadElement.href = href;
              downloadElement.download = `用户手册-${this.name}`    //下载后的文件名,根据需求定义
              document.body.appendChild(downloadElement);
              downloadElement.click(); //点击下载
              document.body.removeChild(downloadElement); //下载完成移除元素
              window.URL.revokeObjectURL(href); //释放掉blob对象
            })
        }
    
    展开全文
  • vue+ts+elementUI:后端返回文件流,前端下载pdf文件到本地 1.配置接口 //下载天气信息pdf export const downWeatherPdfService = (paramsData: any) => { const res: any = service.post('/weaapi/api/dispatch/...
  • vue 本地pdf文件展示

    2021-08-27 14:09:44
    src="../../../static/plugins/pdf/2021海宁智能化改造案例.pdf" frameborder="0" /> --> <!-- 第二种 iframe 元素会创建包含另外一个文档的内联框架(即行内框架)。 --> <iframe .
  • vue下载文件到本地

    千次阅读 2019-04-17 17:46:29
    在我们写项目的时候经常会遇到下载图片、下载表格的操作, 传入的data是后台返回的二进制流,name是要下载的图片名称,可以跟后台商量一下name在什么地方拿,比如response里返回headers的一个字段 我们正常使用axios...
  • npm install --save vue-pdf 2、页面引入 3、具体实现 <div class="pdf" v-show="fileType === 'pdf'"> <p class="arrow"> <span @click="changePdfPage(0)" class="turn
  • vue实现下载pdf文件

    2021-06-25 10:49:30
    2.这里是pdf文件已经由后台生成并且传了阿里云,所以这边直接传入线上地址即可,其他小伙伴没有线上地址的 可以先实现阿里云上传或者其他方法获取线上地址在调用。 this.fileLinkToStreamDownload(url) //直接...
  • 因为是在没有网络的内网开发,所以我是在外网安装的,安装好后拷贝了以下四个文件到项目的 node_modules step2: 点击翻页需求 template部分 <template> <div class="pdf"> <p class="arrow">...
  • vue 本地pdf或excel等文件下载

    千次阅读 2020-07-28 10:29:22
    也就是获取静态资源文件export.pdf,将pdf文档下载本地。 拿这个需求后,找了些方案,如下 方案1:在vue cli中安装一些插件,如jquery,利用jquery下载本地文件; 方案2:直接使用原生ajax下载本地文件; ...
  • Vue 读取 PDF文件

    千次阅读 2020-09-14 22:15:03
    采用vue-pdf用于PDF文件前端显示时,无法读取本地(static路径意外)的PDF。因此,首先Flask 将PDF转成base64 文件流 传入 前端,再由base64转成Blob,并由Vue-pdf 在前端显示/ FLASK后端 def return_img_stream...
  • vue预览本地pdf文件方法之iframe

    千次阅读 2020-11-24 18:01:32
    1、vue预览本地pdf文件方法之a标签 2、vue预览本地pdf文件方法之vue-pdf组件 都不符合需求想要的效果 方法1只是重新打开窗口,适用于pdf预览简单需求 方法2因为是单页展现,还需要上一页下一页的切换,也不合适 ...
  • 使用vue-pdf预览pdf文件

    2021-08-13 14:51:28
    本地预览的话,如果是使用cli/3,需要把pdf文件 public 文件下中,新建一个 static 文件夹,放入其中 使用 安装 vue-pdf 只能使用绝对路径,而且 / 就表示 public 文件夹,所以需要忽略掉,如下 <pdf src...
  • vue axios PDF文件下载

    2020-03-26 14:30:59
    this.axios({ method: "post", url: '/jishi/jishi.daochu', responseType: ... //下载文件的名字 link.href = objectUrl; link.setAttribute("download", fname); document.body.appendChild(link); link.click(); })
  • 使用vue引入pdf文件

    千次阅读 2020-10-02 17:04:11
    vue使用iframe引入pdf文件 在网上找的很多文章都显示需要添加pdf.js来引入vue文件,但是还有一个很简单的办法就是使用iframe框架引入pdf 效果 使用iframe框架引入的话代码会变得非常简洁 <template> <div ...
  • 注意:vue-cli2本地文件需要放在静态文件static下 <a href="javascript:void(0);" @click="download">帮助文档</a> <a href="javascript:void(0);" @click="download">帮助文档</a> ...
  • PDF文件在线预览的功能相信大家都是有遇到过的,这边有两种实现方法,大家可以借鉴参考下 第一种,使用vue-pdf 安装 npm install --save vue-pdf 页面代码 <template> <div> <pdf ref="pdf" v-...
  • vue下载文件导出保存到本地

    千次阅读 2021-03-10 10:56:12
    先分析如何下载:先有一个链接地址,然后使用 location.href或window.open()下载到本地 看看返回数据 res.config.url 中是下载链接地址,res.data 中是返回的二进制数据 如何下载 ... <el-button icon="el-icon-...
  • 前言vue中简单使用vue-pdf预览pdf文件,解决打印预览乱码问题vue-pdf 使用安装npm install --save vue-pdf引入import pdf from "vue-pdf自定义封装pdf预览组件:visible.sync="pdfDialog":close-on-click-modal=...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 2,338
精华内容 935
关键字:

vue下载pdf文件到本地

vue 订阅