长沙网站 建设推广世云网络做任务赚佣金一单10块
1、简介
使用 pdf.js 库加载和显示 PDF 文件。
实现了翻页、缩放功能。
提供了基本的错误处理。
功能特点:
支持选择本地 PDF 文件。
可以逐页查看 PDF 内容。
支持放大缩小功能。
界面简洁,易于使用。
2、使用方法
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>PDF 阅读器@编码小哥</title><style>body {font-family: Arial, sans-serif;margin: 20px;background-color: #f5f5f5;}.container {max-width: 1200px;margin: 0 auto;}.upload-area {padding: 20px;border: 2px dashed #ccc;text-align: center;margin-bottom: 20px;}#pdfContainer {background-color: white;padding: 20px;border-radius: 5px;box-shadow: 0 0 10px rgba(0,0,0,0.1);}canvas {max-width: 100%;height: auto;}.controls {margin-top: 20px;text-align: center;}button {padding: 5px 15px;background-color: #4CAF50;color: white;border: none;border-radius: 3px;cursor: pointer;margin: 0 5px;}button:hover {background-color: #45a049;}</style>
</head>
<body><div class="container"><h1>PDF 阅读器</h1><!-- 文件上传区域 --><div class="upload-area"><input type="file" id="pdfInput" accept=".pdf" style="display: none;"><button onclick="document.getElementById('pdfInput').click()">选择 PDF 文件</button></div><!-- PDF 显示区域 --><div id="pdfContainer"></div><!-- 控制按钮 --><div class="controls"><button onclick="previousPage()">上一页</button><button onclick="nextPage()">下一页</button><button onclick="zoomIn()">放大</button><button onclick="zoomOut()">缩小</button></div></div><!-- 引入 pdf.js 库 --><script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.7.570/pdf.min.js"></script><script>let pdfDoc = null;let currentPage = 1;let scale = 1; // 初始缩放比例// 加载 PDF 文件document.getElementById('pdfInput').addEventListener('change', function(e) {const file = e.target.files[0];if (file) {const reader = new FileReader();reader.onload = function(e) {loadPdf(e.target.result);};reader.readAsArrayBuffer(file);}});// 加载 PDF 内容async function loadPdf(arrayBuffer) {try {pdfDoc = await pdfjsLib.getDocument(arrayBuffer).promise;displayPage(currentPage);} catch (error) {console.error('无法加载 PDF 文件:', error);}}// 显示指定页码的内容async function displayPage(pageNum) {const page = await pdfDoc.getPage(pageNum);const viewport = page.getViewport({ scale: scale });const canvas = document.createElement('canvas');const ctx = canvas.getContext('2d');canvas.width = viewport.width;canvas.height = viewport.height;// 渲染页面await page.render({canvasContext: ctx,viewport: viewport});// 清除之前的 PDF 内容并添加新的const pdfContainer = document.getElementById('pdfContainer');pdfContainer.innerHTML = '';pdfContainer.appendChild(canvas);}// 上一页function previousPage() {if (currentPage > 1) {currentPage--;displayPage(currentPage);}}// 下一页function nextPage() {if (currentPage < pdfDoc.numPages) {currentPage++;displayPage(currentPage);}}// 放大function zoomIn() {scale += 0.2;if (scale > 2) { // 设置最大缩放比例scale = 2;}displayPage(currentPage);}// 缩小function zoomOut() {scale -= 0.2;if (scale < 0.1) {scale = 0.1;}displayPage(currentPage);}</script>
</body>
</html>
将上述代码保存为一个 HTML 文件(例如 pdf-reader.html)。
打开浏览器,加载该文件。
选择 PDF 文件进行查看。
使用控制按钮进行翻页和缩放操作。