html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>H5 PDF 预览</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.min.js"></script>
<style>
body { margin: 0; padding: 10px; box-sizing: border-box; }
#pdfContainer { width: 100%; min-height: 80vh; border: 1px solid #eee; }
.loading { text-align: center; padding: 20px; color: #666; }
.error { text-align: center; padding: 20px; color: red; }
</style>
</head>
<body>
<div class="loading" id="loading">正在加载PDF...</div>
<div class="error" id="error" style="display: none;"></div>
<div id="pdfContainer"></div>
<script>
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.worker.min.js';
// 从URL参数获取PDF地址
function getPdfUrlFromParams() {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get('pdfUrl');
}
// 初始化PDF渲染
async function renderPdf() {
const container = document.getElementById('pdfContainer');
const loading = document.getElementById('loading');
const errorDiv = document.getElementById('error');
// 获取PDF URL
const pdfUrl = getPdfUrlFromParams();
if (!pdfUrl) {
loading.style.display = 'none';
errorDiv.style.display = 'block';
errorDiv.textContent = '未提供PDF文件地址';
return;
}
try {
// 获取PDF文档
const pdfDoc = await pdfjsLib.getDocument(pdfUrl).promise;
loading.style.display = 'none';
// 渲染每一页PDF
for (let pageNum = 1; pageNum <= pdfDoc.numPages; pageNum++) {
const page = await pdfDoc.getPage(pageNum);
// 设置渲染尺寸(适配移动端宽度)
const viewport = page.getViewport({ scale: 1 });
const scale = window.innerWidth / viewport.width;
const scaledViewport = page.getViewport({ scale: scale });
// 创建画布容器
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.width = scaledViewport.width;
canvas.height = scaledViewport.height;
container.appendChild(canvas);
// 渲染页面
await page.render({
canvasContext: context,
viewport: scaledViewport
}).promise;
}
} catch (error) {
loading.style.display = 'none';
errorDiv.style.display = 'block';
errorDiv.textContent = 'PDF加载失败,请检查文件地址';
console.error('PDF加载错误:', error);
}
}
// 页面加载完成后执行
window.onload = renderPdf;
</script>
</body>
</html>
将这个文件放在服务器上,让后直接用webView打开,拼接上 pdfUrl= 链接,就Ok了