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


實現(xiàn)步驟
先安裝pdfjs插件,插件開源免費
官網(wǎng):
https://github.com/mozilla/pdf.js
在vue或react項目中使用
https://github.com/mozilla/pdf.js/wiki/Setup-pdf.js-in-a-website
npm install pdfjs-dist --save

:

上面幾步完成后就完成80%了,剩下的就是把圖片繪制到canvans了
這里我直接貼源碼了,注意一點,官方的示例中沒有import 'pdfjs-dist/build/pdf.worker.mjs'; 這一段導入,會有一個報錯

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,將其轉成圖片
for (let i = 1; i <= pdf._pdfInfo.numPages; i++) {
// 獲取pdf頁
const page = await pdf.getPage(i);
// 獲取頁的尺寸
const viewport = page.getViewport({ scale: 1 });
// 設置canvas的尺寸
canvas.width = viewport.width;
canvas.height = viewport.height;
// 將pdf頁渲染到canvas上
await page.render({ canvasContext: context, viewport: viewport }).promise;
// 將canvas轉成圖片,并添加到頁面上
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>
最終效果:

問題
跨域


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

總結
到此這篇關于純前端使用插件pdfjs實現(xiàn)將pdf轉為圖片的文章就介紹到這了,更多相關插件pdfjs將pdf轉為圖片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JavaScript數(shù)組降維之將二維數(shù)組轉為一維數(shù)組的五種方案
本文介紹了五種數(shù)組降維方法,從最簡單的Array.prototype.flat()方法,到兼容舊版本的concat;spread方法,再到通用的reduce方法,以及處理任意深度嵌套的遞歸方法, 兌時建議總結不同方法的特點、適用場景和性能差異,需要的朋友可以參考下2026-05-05
JavaScript之BOM?location對象+navigator對象+history?對象
這篇文章主要介紹了JavaScript?BOM中的?location對象、navigator對象、history?對象,下面圍繞他們的相關語法及各種資料展開文章詳細內(nèi)容,需要的小伙伴可以參考一下,希望對大家有所幫助2021-12-12
Echarts如何自定義label標簽的樣式(formatter,rich,添加圖標等操作)
通常情況下,echarts中對于圖像的設置是統(tǒng)一的,下面這篇文章主要給大家介紹了關于Echarts如何自定義label標簽的樣式的相關資料,包括formatter,rich,添加圖標等操作,需要的朋友可以參考下2023-02-02

