利用jsPDF實現(xiàn)將圖片轉(zhuǎn)為pdf
安裝依賴并引入
import jsPDF from 'jspdf'; import { PDFDocument, } from 'pdf-lib';
注意一、
jspdf將圖片(jpg/jpeg/png/bmp)轉(zhuǎn)pdf(記為pdfA),得到的pdf(pdfA)和需要合并的pdf(記為pdfB)類型不一致,需要將pdfA轉(zhuǎn)為pdfB類型,才能合并,使用arraybuffer轉(zhuǎn),具體如下
// pdf--pdfA--是使用jspdf將圖片生成的pdf // file--pdfB--是合并pdf需要的pdf格式 const jsPdfBytes = pdf.output('arraybuffer'); const file = await PDFDocument.load(jsPdfBytes);
注意二、
jspdf 可轉(zhuǎn)pdf的圖片類型有jpg、jpeg、png、bpm,不支持 tif 和 tiff 圖片類型
.tif和.tiff格式的文件需要通過安裝依賴
“tiff.js”: “^1.0.0”,
也是使用arrayBuffer,將圖片格式轉(zhuǎn)為base64,(jpg/jpeg格式,然后將該格式通過jspdf轉(zhuǎn)為pdf文件)
if(x.FILE_TYPE == '.tif' || x.FILE_TYPE == '.tiff' ){ const response = await fetch(imgUrl); const buffer = await response.arrayBuffer(); const Tiff = require("tiff.js"); const tiff = new Tiff({ buffer }); imgUrl = tiff.toDataURL(); }
注意三、
async/await 和 new Promise 控制異步任務(wù)順序執(zhí)行,執(zhí)行完imgToPdf()方法,再執(zhí)行合并pdf 方法
注意四、
jspdf 將圖片轉(zhuǎn)為pdf,注意圖片大小的自適應(yīng),可以通過設(shè)置圖片的最大寬度來控制圖片自適應(yīng)的大小
const imageWidth = 100;
注意五、
因為異步任務(wù)執(zhí)行可能導(dǎo)致批量選擇文件的順序與實際獲得的文件順序不一致,所以獲取到的this.pdfFileArr,需要通過id 調(diào)整為正確的pdf文件打印順序
圖片轉(zhuǎn)pdf代碼:
async imgToPdf(arr) { const promises = []; arr.forEach(async (x)=>{ const promise = new Promise(async (resolve,reject)=>{ //jsPdf 僅支持JPG/JPEG/PNG/BMP格式,不支持tif let id = x.ID let imgUrl = window.URL.createObjectURL(x.FILE) //如果是tif或者tiff文件,需要轉(zhuǎn)化后再進(jìn)行 圖片轉(zhuǎn)pdf操作 if(x.FILE_TYPE == '.tif' || x.FILE_TYPE == '.tiff' ){ const response = await fetch(imgUrl); const buffer = await response.arrayBuffer(); const Tiff = require("tiff.js"); const tiff = new Tiff({ buffer }); imgUrl = tiff.toDataURL(); } const pdf = new jsPDF(); //添加header //pdf.text('PDF Header', 10, 10); // 將圖片繪制到pdf中 const imageWidth = 100; // 設(shè)定圖片的最大寬度 const imageHeight = 0; // 設(shè)置為 0,將根據(jù)寬度等比例計算高度 const img = new Image(); img.src = imgUrl let finalWidth = imageWidth; let finalHeight = imageHeight; img.onload = function () { const width = img.width; const height = img.height; // 計算圖片適應(yīng) PDF 頁面的尺寸 const aspectRatio = width / height; if (finalHeight === 0) { finalHeight = finalWidth / aspectRatio; } else if (finalWidth === 0) { finalWidth = finalHeight * aspectRatio; } }; // 添加圖片到 PDF pdf.addImage(imgUrl, 'JPEG', 10, 10, finalWidth, finalHeight, null, 'SLOW') const jsPdfBytes = pdf.output('arraybuffer'); const file = await PDFDocument.load(jsPdfBytes); //const blob = new Blob([file], { type: 'application/PDF' }) let obj = { ID: id, FILE: file } console.log("執(zhí)行了------imgToPdf") resolve(obj) }).then((obj)=>{ this.pdfFileArr.push(obj) }).catch((error)=>{ this.loadLoading = false alert('錯誤信息為:'+error) }) promises.push(promise); }) return Promise.all(promises) },
合并pdf代碼
async mergePdf(sortList) { console.log('最終需要合并的pdf數(shù)組', sortList) let files = sortList // 創(chuàng)建一個新的PDF文檔 const mergedPdf = await PDFDocument.create(); // 遍歷選擇的每個文件 for (let i = 0; i < files.length; i++) { /** 這里為.pdf 文件的遍歷操作 通過FileReader 讀取.pdf文件,轉(zhuǎn)為合并pdf所需要的pdf類型 const file = files[i]; const url = window.URL.createObjectURL(file) const reader = new FileReader(); // 讀取文件內(nèi)容 const fileContents = await new Promise((resolve, reject) => { reader.onload = function (event) { resolve(event.target.result); }; reader.onerror = function (event) { reject(new Error("文件讀取錯誤。")); }; reader.readAsArrayBuffer(file); //blob }); // 將PDF文件添加到合并的PDF文檔中 const pdf = await PDFDocument.load(fileContents); console.log("合并pdf---", pdf) **/ const pdf = files[i]; const copiedPages = await mergedPdf.copyPages( pdf, pdf.getPageIndices() ); copiedPages.forEach((page) => { mergedPdf.addPage(page); }); } const uint8Array = await mergedPdf.save(); let mergeBuffer = Buffer.from(uint8Array); const url = window.URL.createObjectURL(new Blob([mergeBuffer], { type: 'application/pdf;charset=utf-8' })); this.mergePdfUrl = url console.log("pdf合并完成") console.log("新合并的pdf--", url) console.log("新合并的pdf--", mergedPdf) },
將獲得的pdf文件url給iframe即可預(yù)覽,iframe 自帶toolbar工具欄打印
<iframe ref="printPdf" id="printIframe" style="overflow:hidden;filter: Chroma(Color=white);border: none;width: 100%; height: 100%" :src="item.url + '#toolbar=0'"></iframe> <!-- #view=FitH,top -->
如果自己編寫打印接口,可以通過id獲取到該iframe,調(diào)起 contentWindow.print() 即可打印該dom元素
document.getElementById('printIframe').contentWindow.print();
到此這篇關(guān)于利用jsPDF實現(xiàn)將圖片轉(zhuǎn)為pdf的文章就介紹到這了,更多相關(guān)jsPDF圖片轉(zhuǎn)pdf內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
js判斷手機(jī)系統(tǒng)是android還是ios
本文主要介紹了js判斷手機(jī)系統(tǒng)是android還是ios的方法,具有很好的參考價值。下面跟著小編一起來看下吧2017-03-03JavaScript中this的學(xué)習(xí)筆記及用法整理
在本篇文章里小編給大家整理的是關(guān)于JavaScript中this的使用以及代碼實例,需要的朋友們學(xué)習(xí)下。2020-02-02微信小程序教程系列之頁面跳轉(zhuǎn)和參數(shù)傳遞(6)
這篇文章主要為大家詳細(xì)介紹了微信小程序教程系列之頁面跳轉(zhuǎn)和參數(shù)傳遞,微信小程序提供了3種頁面跳轉(zhuǎn)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04