
本文介绍如何通过纯前端 javascript(配合 pdf.js)读取用户输入的 pdf url(如本地服务器路径),获取其总页数并动态显示在 html 页面中,同时说明跨域限制及解决方案。
在 Web 开发中,常需动态解析 PDF 文档信息(如页数),但直接通过 zuojiankuohaophpcninput type="text"> 输入任意 PDF 链接(例如 Google Drive、外部网站)并用 fetch 读取时,会因浏览器 同源策略(CORS) 而失败——尤其是公共云存储(如 drive.google.com)默认不向第三方站点开放跨域访问头(Access-Control-Allow-Origin)。因此,该方案仅适用于同源 PDF 资源(即 PDF 文件托管在同一域名下,如 https://yoursite.com/docs/report.pdf 或 http://localhost:8080/sample.pdf)。
以下为完整可运行的实现方案:
✅ 正确实现步骤(同源 PDF)
- 用户在文本框中输入 PDF 的同源 URL;
- 点击按钮后,使用 fetch() 获取 PDF 二进制流;
- 将响应转为 Blob,再用 FileReader 读取为 ArrayBuffer;
- 交由 pdfjsLib.getDocument() 解析,并提取 pdf.numPages。
<!DOCTYPE html>
<html>
<head>
<title>Count Number of Pages inside PDF Document</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-4">
<h1 class="text-center">Count Pages inside PDF Document</h1>
<div class="form-group">
<input
type="text"
id="pdfFile"
class="form-control"
placeholder="Enter same-origin PDF URL (e.g., /docs/manual.pdf or http://localhost:3000/file.pdf)"
required
/>
<button id="btn" class="btn btn-primary mt-2">Get Number of Pages</button>
</div>
<br>
<h2 class="text-primary" id="result"></h2>
</div>
<!-- 加载 pdf.js(CDN 版本,兼容性好) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.12.313/pdf.min.js"></script>
<script>
document.getElementById("btn").addEventListener("click", async function () {
const url = document.getElementById("pdfFile").value.trim();
const resultEl = document.getElementById("result");
if (!url) {
resultEl.innerHTML = "<span class='text-danger'>⚠️ Please enter a valid PDF URL.</span>";
return;
}
try {
// Step 1: Fetch PDF as binary (only works for same-origin or CORS-enabled endpoints)
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
const blob = await response.blob();
const fileReader = new FileReader();
fileReader.onload = function () {
const typedarray = new Uint8Array(this.result);
const loadingTask = pdfjsLib.getDocument(typedarray);
loadingTask.promise.then(pdf => {
resultEl.innerHTML =
`<span class="text-success">✅ The number of pages in this PDF is: <strong>${pdf.numPages}</strong></span>`;
}).catch(err => {
resultEl.innerHTML =
`<span class="text-danger">❌ Failed to parse PDF: ${err.message}</span>`;
});
};
fileReader.onerror = () => {
resultEl.innerHTML = "<span class='text-danger'>❌ Error reading file.</span>";
};
// Step 2: Read as ArrayBuffer
fileReader.readAsArrayBuffer(blob);
} catch (err) {
resultEl.innerHTML =
`<span class="text-danger">❌ Network or CORS error: ${err.message}<br>
? Tip: Ensure the PDF is served from the same origin or has proper CORS headers.</span>`;
}
});
</script>
</body>
</html>⚠️ 重要注意事项
- ❌ Google Drive、OneDrive、Dropbox 等不支持直连:它们返回的是 HTML 重定向页,而非原始 PDF 流;即使强制加 &export=download,也因缺失 CORS 头而被浏览器拦截。
- ✅ 可行场景:
- 本地开发服务器(http://localhost:8080/report.pdf);
- 同一域名下的静态资源(https://yourdomain.com/files/book.pdf);
- 自建后端代理(如 Express/Nginx 添加 Access-Control-Allow-Origin: *);
- ?️ 安全提示:避免在生产环境对不可信 PDF 执行 getDocument(),存在潜在解析风险(建议服务端预校验);
- ? 替代方案(如需支持任意公网 PDF):必须引入服务端代理(Node.js/PHP/Python)绕过 CORS,或使用支持 CORS 的 PDF 托管服务(如 GitHub Pages + raw link + CORS proxy)。
综上,本方案是轻量、零依赖的前端页数检测方案,适用于可控环境下的 PDF 元数据快速提取。务必确认目标 PDF 可被浏览器合法跨域加载,否则将触发 TypeError: Failed to fetch 或 CORS 错误。










