欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

純前端使用插件pdfjs實(shí)現(xiàn)將pdf轉(zhuǎn)為圖片的步驟

 更新時(shí)間:2025年01月18日 09:08:07   作者:鍵.  
這篇文章主要介紹了純前端使用插件pdfjs實(shí)現(xiàn)將pdf轉(zhuǎn)為圖片的步驟,在實(shí)現(xiàn)過程中遇到了跨域問題,后臺(tái)設(shè)置跨域但前端配置無效,最終采用后臺(tái)返回PDF的base64格式,通過PDF.js將base64轉(zhuǎn)換為二進(jìn)制數(shù)據(jù)加載PDF,需要的朋友可以參考下

需求來源

預(yù)覽簡歷功能在移動(dòng)端,由于用了一層iframe把這個(gè)功能嵌套在了app端,再用一個(gè)iframe來預(yù)覽,只有ios能看到,安卓就不支持,查了很多資料和插件,原理基本上都是用iframe實(shí)現(xiàn)的。最終轉(zhuǎn)換思路,將pdf下載轉(zhuǎn)為圖片然后繪制到canvans中也是一樣的效果。

實(shí)現(xiàn)步驟

先安裝pdfjs插件,插件開源免費(fèi)

官網(wǎng):

https://github.com/mozilla/pdf.js

在vue或react項(xiàng)目中使用
https://github.com/mozilla/pdf.js/wiki/Setup-pdf.js-in-a-website

npm install pdfjs-dist --save

上面幾步完成后就完成80%了,剩下的就是把圖片繪制到canvans了

這里我直接貼源碼了,注意一點(diǎn),官方的示例中沒有import 'pdfjs-dist/build/pdf.worker.mjs'; 這一段導(dǎo)入,會(huì)有一個(gè)報(bào)錯(cuò)

gihub上有解釋
https://github.com/mozilla/pdf.js/issues/10478

<template>
  <div ref="showpdfRef"></div>
</template>

<script setup>
import { ref } from 'vue';
import { getDocument } from 'pdfjs-dist/legacy/build/pdf.mjs';
import 'pdfjs-dist/build/pdf.worker.mjs';

const showpdfRef = ref(null);

const pdfPath ='xxxxxxxx'

const loadingTask = getDocument(pdfPath);
loadingTask.promise
  .then(async (pdf) => {
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    // 循環(huán)遍歷每一頁pdf,將其轉(zhuǎn)成圖片
    for (let i = 1; i <= pdf._pdfInfo.numPages; i++) {
      // 獲取pdf頁
      const page = await pdf.getPage(i);
      // 獲取頁的尺寸
      const viewport = page.getViewport({ scale: 1 });
      // 設(shè)置canvas的尺寸
      canvas.width = viewport.width;
      canvas.height = viewport.height;
      // 將pdf頁渲染到canvas上
      await page.render({ canvasContext: context, viewport: viewport }).promise;
      // 將canvas轉(zhuǎn)成圖片,并添加到頁面上
      const img = document.createElement('img');
      img.src = canvas.toDataURL('image/png');
      showpdfRef.value.appendChild(img);
    }
   
  })
  .then(
    function () {
      console.log('# End of Document');
    },
    function (err) {
      console.error('Error: ' + err);
    },
  );
</script>

<style scoped></style>

最終效果:

問題

跨域

我直接放入設(shè)置了跨域的鏈接到url是可以直接得到pdf的,但是目前這個(gè)跨域問題,后臺(tái)說是有設(shè)置跨域,但是我請(qǐng)求有跨域,我在前端配置了跨域也還是不行。多番嘗試后這個(gè)問題還是沒有解決。由于時(shí)間緊迫,所以采用備用方案:后臺(tái)在接口返回了pdf的base64格式,pdfjs官方案例中說需要將base64轉(zhuǎn)為二進(jìn)制數(shù)據(jù)就可以加載。
https://github.com/mozilla/pdf.js/blob/master/examples/learning/helloworld64.html

總結(jié)

到此這篇關(guān)于純前端使用插件pdfjs實(shí)現(xiàn)將pdf轉(zhuǎn)為圖片的文章就介紹到這了,更多相關(guān)插件pdfjs將pdf轉(zhuǎn)為圖片內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論