……

js vue中pdf与img互转

Posted on 2023-12-01 15:22  WALL*E  阅读(306)  评论(0编辑  收藏  举报

需要 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 onloadFile = {};
  const canvasArr = [];
  let numPages = 0;
  changeUrl(file,type,fileForm + '_url').then(perfix64 => {
    const CMAP_URL = "https://unpkg.com/pdfjs-dist@2.0.943/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){
            onloadFile.Callback ? onloadFile.Callback(canvasArr) : '';
          }
        });
      }
    })
    .catch(err => {
      console.error("pdf 加载失败", err);
    });
  });
  return onloadFile
}
export function pdf_img(file,type,fileForm){
  // pdf转img
  const onloadFile = {};
  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"));
      }
      onloadFile.Callback ? onloadFile.Callback(imgList) : '';
    },1000);
  }
  console.log(imgList,'onloadFileonloadFileonloadFile')
  return imgList;
}
 
export function img_canvas(file,fileForm){
  // img转canvas
  const onloadFile = {};
  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);
      onloadFile.Callback ? onloadFile.Callback(canvas) : '';
      img.remove();
    };
  })
  return onloadFile;
}
 
export function img_pdf(file,fileForm){
  // img转pdf
  const onloadFile = {};
  const canvas = img_canvas(file,fileForm);
  canvas.Callback = function(canvas){
    const base64pdf = canvas_pdf(canvas);
    onloadFile.Callback ? onloadFile.Callback(base64pdf) : '';
  }
  return onloadFile;
}
 
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)