简介

采用vue-pdf用于PDF文件前端显示时,无法读取本地(static路径意外)的PDF。因此,首先Flask 将PDF转成base64 文件流 传入 前端,再由base64转成Blob,并由Vue-pdf 在前端显示/

FLASK后端

def return_img_stream(img_local_path):
  img_stream = ''
  with open(img_local_path, 'rb') as img_f:
    print ('ok')
    img_stream = img_f.read()
    img_stream = base64.b64encode(img_stream)
  return img_stream 

Vue前端

mounted() {
	this.postRequest()
        },
methods: {
	postRequest(){
	this.$axios.post('/api/RequestForm',JSON.stringify(this.$store.state.form),{headers:{'Content-Type':'application/x-www-form-urlencoded'}})
		.then(res=>{
			const blob = this.base64ToBlob(res.data,'application/pdf')
			console.log(blob)
			this.PDFfile= window.URL.createObjectURL(blob)
						console.log('here')
							})
		.catch(function (error) {
			console.log(error);
						})
				},

	base64ToBlob(b64Data, contentType='', sliceSize=512) {
		const byteCharacters = atob(b64Data);
		const byteArrays = [];

		for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
			const slice = byteCharacters.slice(offset, offset + sliceSize);

			const byteNumbers = new Array(slice.length);
			for (let i = 0; i < slice.length; i++) {
					byteNumbers[i] = slice.charCodeAt(i);
					}

					const byteArray = new Uint8Array(byteNumbers);
					byteArrays.push(byteArray);
				}

		const blob = new Blob(byteArrays, {type: contentType});
				return blob;
				}
}
Logo

前往低代码交流专区

更多推荐