前言:正常情况下需要在HTML中嵌入本地docx或pdf文件时,我们会有以下解决办法:
1. 使用<iframe>标签
2. 使用<embed>标签
3. 使用<object>标签
4. 使用第三方库(如PDF.js)
当实际操作时,会发现前三种方式在pc端支持,但在移动端不支持,因为这些标签在移动端浏览器中的支持并不统一。
为了兼容移动端,我使用了第4种方案解决,当然网上很多教程咯~
随便找了一个ppt,放入html中使用第三方插件后展示的效果如下:
完整代码如下:
<!DOCTYPE html> <html> <head> <title>移动端引入pdf</title> <style> * { margin: 0; padding: 0; } .pdf_box, #pdf-container { width: 100vw; height: 100vh; overflow: scroll; } canvas { width: 100vw; } </style> </head> <body> <!-- <iframe src="test.pdf" class="pdf_box"></iframe> <embed src="test.pdf" class="pdf_box"> <object data="test.pdf" class="pdf_box"></object> --> <div id="pdf-container"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.js"></script> <script> pdfjsLib.GlobalWorkerOptions.workerSrc = "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.worker.js"; const pdfUrl = "test.pdf", _targetDom = "pdf-container"; pdfjsLib.getDocument("test.pdf").promise.then(async (doc) => { let _i = 0; for (let item of new Array(doc.numPages).fill()) { await renderOtherPage(doc, ++_i, _targetDom); } }); function renderOtherPage(pdfDoc, pageNumber) { return new Promise((resolve) => { pdfDoc.getPage(pageNumber).then((page) => { const scale = 1; const viewport = page.getViewport({ scale: scale }); const canvas = document.createElement("canvas"); const context = canvas.getContext("2d"); canvas.height = viewport.height; canvas.width = viewport.width; document.getElementById(_targetDom).appendChild(canvas); const renderContext = { canvasContext: context, viewport: viewport, }; page.render(renderContext); resolve(); }); }); } </script> </body> </html>
标签:canvas,const,demo,H5,width,pdf,移动,viewport From: https://www.cnblogs.com/cat-eol/p/18258695