预览在线的pdf
2021/8/31 23:08:23
本文主要是介绍预览在线的pdf,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
本案例借助了pdf.js实现的一个预览在线pdf的小案例,可选择跳转到指定页码。
ShowPDF接收三个参数:url:pdf在线地址,className:类名,page:跳转到的指定页码,默认是1。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="pdfDemo"></div> <img src="" alt="" srcset=""> </body> </html> <script src="https://cdn.bootcss.com/pdf.js/2.2.228/pdf.min.js"></script> <script> class ShowPDF { constructor({ className, url, page = 1 }) { if (!url) throw new Error('url是必填项'); if (!className) throw new Error('className是必填项'); this.className = className; this.url = url; this.page = page; this.pdf = null; } async show() { const imageArr = await this.getImageArr(this.url) console.log(imageArr); const html = this.getImageHtml(imageArr); const pdfDemo = document.querySelector(this.className); pdfDemo.innerHTML = html; const viewImage = document.querySelectorAll(`${this.className} img`)[this.page - 1] setTimeout(() => { viewImage.scrollIntoView({ behavior: "smooth", // 平滑过渡 block: "start", // 居中 }); }, 1000) } getImageArr(url) { return new Promise((resolve, reject) => { let loadingTask = pdfjsLib.getDocument(url); loadingTask.promise.then(async (pdf) => { this.pdf = pdf; const numPages = pdf._pdfInfo.numPages; const imgArr = [] for (let i = 1; i <= numPages; i++) { let imgUrl = await this.PdfToJpg(i) imgArr.push(imgUrl) } resolve(imgArr) }); }) } getImageHtml(imgArr) { let html = ""; imgArr.forEach(item => html += ` <img src="${item}">`) return html } //pdf转jpg PdfToJpg(pageNum, callback) { return new Promise(async (resolve, reject) => { const page = await this.pdf.getPage(pageNum) let canvas = document.createElement("canvas"); let context = canvas.getContext('2d'); let scale = 1.5; let viewport = page.getViewport({ scale: scale }); canvas.height = viewport.height; canvas.width = viewport.width; let renderContext = { canvasContext: context, viewport: viewport }; let renderTask = page.render(renderContext) renderTask.promise.then(function () { let imgUrl = canvas.toDataURL('image/jpeg'); //转换为base64 resolve(imgUrl) }) }) } } new ShowPDF({ url: "http://www.raomaiping.host/1.pdf", className: ".pdfDemo", page: 4 }).show() </script>
这篇关于预览在线的pdf的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-12百万架构师第十五课:源码分析:Spring 源码分析:SpringMVC核心原理及源码分析|JavaGuide
- 2025-01-11有哪些好用的家政团队管理工具?
- 2025-01-11营销人必看的GTM五个指标
- 2025-01-11办公软件在直播电商前期筹划中的应用与推荐
- 2025-01-11提升组织效率:上级管理者如何优化跨部门任务分配
- 2025-01-11酒店精细化运营背后的协同工具支持
- 2025-01-11跨境电商选品全攻略:工具使用、市场数据与选品策略
- 2025-01-11数据驱动酒店管理:在线工具的核心价值解析
- 2025-01-11cursor试用出现:Too many free trial accounts used on this machine 的解决方法
- 2025-01-11百万架构师第十四课:源码分析:Spring 源码分析:深入分析IOC那些鲜为人知的细节|JavaGuide