uniapp 生成PDF文件并进行预览
先用 npm 引入包到你的项目中去
npm install html2canvas
npm install jspdf
这里的 id 要和下面的 id 一致。 id底下包的内容就是你要预览和打印的数据
<view id="contentToPrint " class="center">
这里是你要导出的数据
</view>
先写一个点击事件,或者直接调用方法也行
<div class="look marginClass">
<el-button @click="preview()" >PDF Preview</el-button>
</div>
这里有一个 #contentToPrint , 这里的 id 和 上面的要预览的 id 一致,剩下的直接复制就行。复制就能用了。
//预览PDF文件 const preview = async()=>{ uni.showLoading({ title: '正在生成PDF...', mask: true }); try { // var title = 'test' html2Canvas(document.querySelector('#contentToPrint'), { allowTaint: true, useCORS: true }).then(function (canvas) { let contentWidth = canvas.width let contentHeight = canvas.height let pageHeight = contentWidth / 592.28 * 841.89 let leftHeight = contentHeight let position = 0 let imgWidth = 595.28 let imgHeight = 592.28 / contentWidth * contentHeight let pageData = canvas.toDataURL('image/jpeg', 1.0) let PDF = new JsPDF('', 'pt', 'a4') if (leftHeight < pageHeight) { PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight) } else { while (leftHeight > 0) { PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight) leftHeight -= pageHeight position -= 841.89 if (leftHeight > 0) { PDF.addPage() } } } // PDF.save(title + '.pdf') //这个方法是直接保存,一般来说不建议,因为新开的页面也包含了下载的按钮。
//如果需要直接保存需要放开上面的 title previewPDF(PDF) uni.hideLoading(); } ) }catch (error) { uni.showToast({ title: '生成PDF失败', icon: 'none', duration: 3000 }); } } //预览PDF const previewPDF=(pdf)=>{ // H5端预览 const pdfBlob = pdf.output('blob'); const pdfUrl = URL.createObjectURL(pdfBlob); // 在新窗口打开 const newWindow = window.open('', '_blank'); newWindow.document.write(` <iframe width="100%" height="100%" src="${pdfUrl}" frameborder="0" style="position:fixed; top:0; left:0; right:0; bottom:0;" ></iframe> `); }

浙公网安备 33010602011771号