前端在线预览PDFJS在线预览PDFcmyang2024-02-202024-02-211. PDFJS简介2. 单页面简单示例1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PDF.js Preview</title> <!-- 加载 PDF.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script> <!-- 样式 --> <style> #pdfContainer { width: 100%; max-width: 800px; /* 设置最大宽度以适应手机端 */ margin: 0 auto; } canvas { display: block; margin: 10px auto; max-width: 100%; height: auto; } </style></head><body><div id="pdfContainer"></div><script> // PDF.js 配置 const pdfUrl = 'https://oss-dev.xxx.com/cmyang/SkyWalking.pdf'; // 替换为你的 PDF 文件 URL const scale = 1.5; // 初始化 PDF.js function renderPages(pdfDoc) { const numPages = pdfDoc.numPages; for (let pageNum = 1; pageNum <= numPages; pageNum++) { pdfDoc.getPage(pageNum).then(function(page) { let canvas = document.getElementById("pdf-canvas-" + pageNum); const context = canvas.getContext('2d'); const viewport = page.getViewport({ scale }); canvas.height = viewport.height; canvas.width = viewport.width; const renderContext = { canvasContext: context, viewport: viewport }; page.render(renderContext); }); } } function createCanvas(numPages) { for (let pageNum = 1; pageNum <= numPages; pageNum++) { let pdfContainer = document.getElementById('pdfContainer'); const canvas = document.createElement('canvas'); canvas.id = 'pdf-canvas-' + pageNum; pdfContainer.appendChild(canvas); } } // 加载 PDF pdfjsLib.getDocument(pdfUrl).promise.then(function(pdfDoc) { const numPages = pdfDoc.numPages; createCanvas(numPages); renderPages(pdfDoc); }).catch(console.error);</script></body></html> 如果要引用本地的js,需要同时下载pdf.js和pdf.worker.js 加载pdf时,添加pdfjsLib.GlobalWorkerOptions.workerSrc = 'scripts/pdf.worker.min.js';