首页 > 其他分享 >js vue中pdf与img互转

js vue中pdf与img互转

时间:2023-12-01 15:36:23浏览次数:45  
标签:canvas vue const url base64 blob 互转 pdf

需要 npm install vue-pdfnpm install pdfjs-dist,新建js文件 pdtToImg.js:

import pdf from "vue-pdf";
import JsPDF from 'pdfjs-dist';
const PDFJS = require('pdfjs-dist/build/pdf.js'); // import 会报错
window.pdfjsWorker=require('pdfjs-dist/build/pdf.worker') 
import { changeUrl } from "./changeUrl";//同目录下新建changeUrl.js文件
export function pdf_canvas(file,type,fileForm){
  // pdf转canvas
  const onl oadFile = {};
  const canvasArr = [];
  let numPages = 0;
  changeUrl(file,type,fileForm + '_url').then(perfix64 => {
    const CMAP_URL = "https://unpkg.com/[email protected]/cmaps/";
    const src = pdf.createLoadingTask({
      url: perfix64,
      withCredentials: false,
      cMapUrl: CMAP_URL,
      cMapPacked: true
    });
    src.promise.then(pdf => {
      for(let i = 1,l = pdf.numPages; i <= l; i++) {
        numPages = pdf.numPages;
        pdf.getPage(i).then((page) => {
          const canvas = document.createElement("canvas");
          const ctx = canvas.getContext('2d');
          const viewport = page.getViewport({ scale: 1.5 });
          canvas.height = viewport.height;
          canvas.width = viewport.width;
          canvas.style.width = viewport.width + 'px';
          canvas.style.height = viewport.height + 'px';
          page.render({
            canvasContext: ctx,
            viewport,
          });
          canvasArr.push(canvas);
          if(numPages == i){
            onl oadFile.Callback ? onl oadFile.Callback(canvasArr) : '';
          }
        });
      }
    })
    .catch(err => {
      console.error("pdf 加载失败", err);
    });
  });
  return onl oadFile
}
export function pdf_img(file,type,fileForm){
  // pdf转img
  const onl oadFile = {};
  const imgList = [];
  const canvas = pdf_canvas(file,type,fileForm);
  canvas.Callback = function (canvasArr){
    setTimeout(() => {
      for(let i = 0 ;i < canvasArr.length;i++){
        imgList.push(canvasArr[i].toDataURL("image/png"));
      }
      onl oadFile.Callback ? onl oadFile.Callback(imgList) : '';
    },1000);
  }
  console.log(imgList,'onloadFileonloadFileonloadFile')
  return imgList;
}
 
export function img_canvas(file,fileForm){
  // img转canvas
  const onl oadFile = {};
  changeUrl(file,fileForm,fileForm + '_url').then(url => {
    const img = new Image();  //创建一个临时存储
    img.src = url //将图片数据赋值即可
    img.onload = function(){  //定义加载图片后弹出显示
      const canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      this.ctx = canvas.getContext("2d");
      this.ctx.drawImage(img,0,0,img.width,img.height);
      onl oadFile.Callback ? onl oadFile.Callback(canvas) : '';
      img.remove();
    };
  })
  return onl oadFile;
}
 
export function img_pdf(file,fileForm){
  // img转pdf
  const onl oadFile = {};
  const canvas = img_canvas(file,fileForm);
  canvas.Callback = function(canvas){
    const base64pdf = canvas_pdf(canvas);
    onl oadFile.Callback ? onl oadFile.Callback(base64pdf) : '';
  }
  return onl oadFile;
}
 
export function canvas_pdf(canvas){
  // canvas转pdf
  const canvasUrl = canvas.toDataURL('image/jpeg');
  const pdf = new JsPDF('x', 'px', [canvas.width, canvas.height]);
  pdf.addImage(canvasUrl, 'PNG', 0, 0, canvas.width, canvas.height);
  let base64pdf = pdf.output('datauristring');
  base64pdf = base64pdf.replace('data:application/pdf;filename=generated.pdf;base64,', 'data:application/pdf;base64,');
  return base64pdf;
}

changeUrl.js文件:

const fileType = {
  "pdf":{
      type:"application/pdf;charset=utf-8",// 文件转换类型
      base64Type:"data:application/pdf;base64,",// base64前缀
  },
  "img":{
      // img适用所有通用图片格式
      type:"image/png",
      base64Type:"data:image/png;base64,",
  },
  "gif":{
      type:"image/gif",
      base64Type:"data:image/gif;base64,",
  },
  "doc":{
      type:"application/msword",
      base64Type:"data:application/msword;base64,"
  },
  "docx":{
      type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      base64Type:"data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,"
  },
  "xls":{
      type:"application/vnd.ms-excel",
      base64Type:"data:application/vnd.ms-excel;base64,"
  },
  "xlsx":{
      type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      base64Type:"data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,"
  },
  "ppt":{
      type:"application/vnd.ms-powerpoint",
      base64Type:"data:application/vnd.ms-powerpoint;base64,"
  },
  "pptx":{
      type:"application/vnd.openxmlformats-officedocument.presentationml.presentation",
      base64Type:"data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64,"
  },
  "txt":{
      type:"text/plain",
      base64Type:"data:text/plain;base64,"
  },
};
let files,types,changeTypes;

// file 附件
// type 文件类型(img,pdf)
// changeType 附件转换类型(base64 blob url),三者互转(列如:base64_url)
export async function changeUrl(file,type,changeType) { 
  if(!file || !type || !changeType || !fileFun[changeType]) {
      return file;
  }
  files = file;
  types = type;
  changeTypes = changeType;
  const fileWj = await fileFun[changeType](file);
  return fileWj;
}
function base64_url(file){
  // base64转url
  const blob = base64_blob(file);
  return window.URL.createObjectURL(blob);
}
function base64_blob(file){
  // base64转blob
  const arr = file.split(",");
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}
function blob_url(file){
   // blob转url
  const blob = new Blob([file], {type: fileType[types].type});
  return URL.createObjectURL(blob);
}
function blob_base64(file){
  // blob转base64
  return new Promise((resolve) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
          const arr = reader.result.split(",");
          resolve(fileType[types].base64Type + arr[1]);
      };
  });
}
async function url_blob(url) {
  // url转blob
  return new Promise((resolve) => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET',url,true);
      xhr.responseType = 'blob';
      xhr.onload = function(e) {
          const myBlob = this.response;
          // let files = new window.File([myBlob], myBlob.type, {type:myBlob.type}) // myBlob.type 自定义文件名
          resolve(myBlob);
      };
      xhr.send();
  })
}
async function url_base64(url){
  // url转base64
  const blob = await url_blob(url);
  return new Promise((resolve) => {
      blob_base64(blob).then(res => {
          resolve(res);
      });
  })
}

const fileFun = {
  "base64_url":base64_url,
  "blob_url":blob_url,
  "base64_blob":base64_blob,
  "blob_base64":blob_base64,
  "url_blob":url_blob,
  "url_base64":url_base64,
}

页面使用: this.urlList = pdf_img('data:application/pdf;base64,' + res.data.pdf_base64,'pdf','base64');
接收较慢可能是转换慢 通过使用setTimeout再次获取到setTimeout(()=>{ this.url = this.urlList},2000)

标签:canvas,vue,const,url,base64,blob,互转,pdf
From: https://www.cnblogs.com/cyapi/p/17869785.html

相关文章

  • 关于解决vue报错"Problems loading reference 'https://schemastore.azurewebsites.ne
    打开setting时会看到有一条三角形的警告信息 看问题描述:无法从该网站加载解决方法:打开设置,找到扩展下的json项 设置之后可以在settings.json文件中看到新增加一项 "json.schemaDownload.enable":false可以直接在界面上设置: "json.schemaDownload.enable":false......
  • Vue3快速上手(B站尚硅谷张天禹老师主讲vue全家桶)
    Vue3快速上手Vue3快速上手1.Vue3简介2.Vue3带来了什么1.性能的提升2.源码的升级3.拥抱TypeScript4.新的特性一、创建Vue3.0工程1.使用vue-cli创建2.使用vite创建二、常用CompositionAPI1.拉开序幕的setup2.ref函数3.reactive函数4.Vue3.0中的响应式原理vue2.x的响应式Vue3.0......
  • 直播系统源代码,vue二种方式根据条件判断显示不同样式
    直播系统源代码,vue二种方式根据条件判断显示不同样式1.v-if-v-else/v-show的方式,只显示其中之一#v-ifv-else <divclass="blue"v-if="item.num=='0'">{{item.num}}</div><divclass="orange"v-else>{{item.num}}</div> ​#v-s......
  • Vue3中的Pinia
    什么是Pinia官方文档:https://pinia.vuejs.org/zh/introduction.htmlPinia是Vue的专属状态管理库,它允许你跨组件或页面共享状态。如果你熟悉组合式API的话,你可能会认为可以通过一行简单的exportconststate=reactive({})来共享一个全局状态。对于单页应用来说确实可以,......
  • vue3 之 ArcoPro 后台管理系统
    一、资料链接ArcoDesign的官网:https://arco.design/ArcoDesign开箱的管理系统预览:https://vue-pro.arco.design/loginvue3项目创建的指南:https://arco.design/vue/docs/pro/start二、基本命令开始开发之前,请确认本地环境中安装好了 node, git ,这些肯定......
  • vue报错export 'default' (imported as 'VueRouter') was not found in 'vue-route
    直接使用npminstallvue-router-save安装的路由,运行报错 经排查后发现是安装的vue-router版本太高使用npmuninstallvue-router卸载之前安装的路由使用[email protected]安装低版本的路由问题解决!!! ......
  • el-check省市区选择组件 vue3
    引用组件//city_dialog.vue//PopWindow弹出层组件//AreaList省市区数据组件//areaData省市区数据<PopWindow:dialogVisible="dialogVisible"title="省市区选择"sizeType="large":btnType="2"@closeWin="closeWin"><div......
  • vue axios all 接口全部成功之后进行其它操作
    setSelf(){constarr:any=[]list?.forEach((item)=>{constobj={id:1}arr.push(obj)})arr.push()returnt......
  • 数字千分比格式化 vue3
    {{numberToCurrencyNo(1245)}}exportconstnumberToCurrencyNo=(value:any)=>{if(!value)return0;//获取整数部分constintPart=Math.trunc(value);//整数部分处理,增加,constintPartFormat=intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g......
  • 数组对比大小 vue3
    lett_data=sortByKey(pz_data.data,"yield_per_mu");//array:当前数组//key:数组中需要比较大小的值exportconstsortByKey=(array:any,key:any)=>{returnarray.sort(function(a:any,b:any){varx=b[key];vary=a[key];returnx&l......