当前位置:   article > 正文

vue 把PDF的base64 转成图片 预览_vue pdf转图片

vue pdf转图片
  1. //页面显示转换后的图片
  2. <img
  3. v-for="(item, i) in imageBase64"
  4. :key="i"
  5. :src="item.url"
  6. />
  7. imageBase64: [], // 附件预览

 根据后端返回的base64 我这没有返回前缀 所以手动加上

  1. import { pdf_img } from '@/components/test/FileTypeConversion.js';
  2. querytest(tab) {
  3. // 预览附件
  4. this.imageBase64 = [];
  5. querytest(obj)
  6. .then((res) => {
  7. if (res.data.code == '0') {
  8. const arr = res.data.data;
  9. const a = pdf_img(
  10. 'data:application/pdf;base64,' + arr[i].imageBase64,
  11. 'pdf',
  12. 'base64',
  13. );
  14. a.Callback = (obg) => {
  15. for (let i = 0; i < obg.length; i++) {
  16. let obj = {};
  17. obj.url = obg[i];
  18. this.imageBase64.push(obj);
  19. }
  20. };
  21. }
  22. })
  23. },

 封装好的工具类 FileTypeConversion.js

  1. import pdf from "vue-pdf";
  2. import JsPDF from 'jspdf';
  3. import { changeUrl } from "./appendix.js";
  4. export function pdf_canvas(file,type,fileForm){
  5. // pdf转canvas
  6. const onloadFile = {};
  7. const canvasArr = [];
  8. let numPages = 0;
  9. changeUrl(file,type,fileForm + '_url').then(perfix64 => {
  10. const CMAP_URL = "https://unpkg.com/pdfjs-dist@2.0.943/cmaps/";
  11. const src = pdf.createLoadingTask({
  12. url: perfix64,
  13. withCredentials: false,
  14. cMapUrl: CMAP_URL,
  15. cMapPacked: true
  16. });
  17. src.promise.then(pdf => {
  18. for(let i = 1,l = pdf.numPages; i <= l; i++) {
  19. numPages = pdf.numPages;
  20. pdf.getPage(i).then((page) => {
  21. const canvas = document.createElement("canvas");
  22. const ctx = canvas.getContext('2d');
  23. const viewport = page.getViewport({ scale: 1.5 });
  24. canvas.height = viewport.height;
  25. canvas.width = viewport.width;
  26. canvas.style.width = viewport.width + 'px';
  27. canvas.style.height = viewport.height + 'px';
  28. page.render({
  29. canvasContext: ctx,
  30. viewport,
  31. });
  32. canvasArr.push(canvas);
  33. if(numPages == i){
  34. onloadFile.Callback ? onloadFile.Callback(canvasArr) : '';
  35. }
  36. });
  37. }
  38. })
  39. .catch(err => {
  40. console.error("pdf 加载失败", err);
  41. });
  42. });
  43. return onloadFile
  44. }
  45. export function canvas_img(canvas){
  46. // canvas转img
  47. return canvas.toDataURL("image/png");
  48. }
  49. export function pdf_img(file,type,fileForm){
  50. // pdf转img
  51. const onloadFile = {};
  52. const imgList = [];
  53. const canvas = pdf_canvas(file,type,fileForm);
  54. canvas.Callback = function(canvasArr){
  55. setTimeout(() => {
  56. for(let i = 0 ;i < canvasArr.length;i++){
  57. imgList.push(canvasArr[i].toDataURL("image/png"));
  58. }
  59. onloadFile.Callback ? onloadFile.Callback(imgList) : '';
  60. },(1000+150*canvasArr.length));
  61. }
  62. return onloadFile;
  63. }
  64. export function img_canvas(file,fileForm){
  65. // img转canvas
  66. const onloadFile = {};
  67. changeUrl(file,fileForm,fileForm + '_url').then(url => {
  68. const img = new Image(); //创建一个临时存储
  69. img.src = url //将图片数据赋值即可
  70. img.onload = function(){ //定义加载图片后弹出显示
  71. const canvas = document.createElement("canvas");
  72. canvas.width = img.width;
  73. canvas.height = img.height;
  74. this.ctx = canvas.getContext("2d");
  75. this.ctx.drawImage(img,0,0,img.width,img.height);
  76. onloadFile.Callback ? onloadFile.Callback(canvas) : '';
  77. img.remove();
  78. };
  79. })
  80. return onloadFile;
  81. }
  82. export function img_pdf(file,fileForm){
  83. // img转pdf
  84. const onloadFile = {};
  85. const canvas = img_canvas(file,fileForm);
  86. canvas.Callback = function(canvas){
  87. const base64pdf = canvas_pdf(canvas);
  88. onloadFile.Callback ? onloadFile.Callback(base64pdf) : '';
  89. }
  90. return onloadFile;
  91. }
  92. export function canvas_pdf(canvas){
  93. // canvas转pdf
  94. const canvasUrl = canvas.toDataURL('image/jpeg');
  95. const pdf = new JsPDF('x', 'px', [canvas.width, canvas.height]);
  96. pdf.addImage(canvasUrl, 'PNG', 0, 0, canvas.width, canvas.height);
  97. let base64pdf = pdf.output('datauristring');
  98. base64pdf = base64pdf.replace('data:application/pdf;filename=generated.pdf;base64,', 'data:application/pdf;base64,');
  99. return base64pdf;
  100. }

changURl-->appendix.js

  1. const fileType = {
  2. "pdf":{
  3. type:"application/pdf;charset=utf-8",// 文件转换类型
  4. base64Type:"data:application/pdf;base64,",// base64前缀
  5. },
  6. "img":{
  7. // img适用所有通用图片格式
  8. type:"image/png",
  9. base64Type:"data:image/png;base64,",
  10. },
  11. "gif":{
  12. type:"image/gif",
  13. base64Type:"data:image/gif;base64,",
  14. },
  15. "doc":{
  16. type:"application/msword",
  17. base64Type:"data:application/msword;base64,"
  18. },
  19. "docx":{
  20. type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  21. base64Type:"data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,"
  22. },
  23. "xls":{
  24. type:"application/vnd.ms-excel",
  25. base64Type:"data:application/vnd.ms-excel;base64,"
  26. },
  27. "xlsx":{
  28. type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  29. base64Type:"data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,"
  30. },
  31. "ppt":{
  32. type:"application/vnd.ms-powerpoint",
  33. base64Type:"data:application/vnd.ms-powerpoint;base64,"
  34. },
  35. "pptx":{
  36. type:"application/vnd.openxmlformats-officedocument.presentationml.presentation",
  37. base64Type:"data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64,"
  38. },
  39. "txt":{
  40. type:"text/plain",
  41. base64Type:"data:text/plain;base64,"
  42. },
  43. }
  44. let files,types,changeTypes;
  45. // file 附件
  46. // type 文件类型(img,pdf)
  47. // changeType 附件转换类型(base64 blob url),三者互转(列如:base64_url)
  48. export async function changeUrl(file,type,changeType) {
  49. if(!file || !type || !changeType || !fileFun[changeType]) {
  50. return file;
  51. };
  52. files = file;
  53. types = type;
  54. changeTypes = changeType;
  55. const fileWj = await fileFun[changeType](file);
  56. return fileWj;
  57. }
  58. function base64_url(file){
  59. // base64转url
  60. const blob = base64_blob(file);
  61. return window.URL.createObjectURL(blob);
  62. }
  63. function base64_blob(file){
  64. // base64转blob
  65. const arr = file.split(",")
  66. const mime = arr[0].match(/:(.*?);/)[1];
  67. const bstr = atob(arr[1]);
  68. let n = bstr.length;
  69. const u8arr = new Uint8Array(n);
  70. while (n--) {
  71. u8arr[n] = bstr.charCodeAt(n)
  72. }
  73. return new Blob([u8arr], { type: mime });
  74. }
  75. function blob_url(file){
  76. // blob转url
  77. const blob = new Blob([file], {type: fileType[types].type});
  78. return URL.createObjectURL(blob);
  79. }
  80. function blob_base64(file){
  81. // blob转base64
  82. return new Promise((resolve) => {
  83. const reader = new FileReader();
  84. reader.readAsDataURL(file);
  85. reader.onload = () => {
  86. const arr = reader.result.split(",");
  87. resolve(fileType[types].base64Type + arr[1]);
  88. };
  89. });
  90. }
  91. async function url_blob(url) {
  92. // url转blob
  93. return new Promise((resolve) => {
  94. const xhr = new XMLHttpRequest();
  95. xhr.open('GET',url,true);
  96. xhr.responseType = 'blob';
  97. xhr.onload = function(e) {
  98. const myBlob = this.response;
  99. // let files = new window.File([myBlob], myBlob.type, {type:myBlob.type}) // myBlob.type 自定义文件名
  100. resolve(myBlob)
  101. };
  102. xhr.send();
  103. })
  104. }
  105. async function url_base64(url){
  106. // url转base64
  107. const blob = await url_blob(url);
  108. return new Promise((resolve) => {
  109. blob_base64(blob).then(res => {
  110. resolve(res)
  111. });
  112. })
  113. }
  114. const fileFun = {
  115. "base64_url":base64_url,
  116. "blob_url":blob_url,
  117. "base64_blob":base64_blob,
  118. "blob_base64":blob_base64,
  119. "url_blob":url_blob,
  120. "url_base64":url_base64,
  121. }

最后预览效果

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/256192
推荐阅读
相关标签
  

闽ICP备14008679号