js实现pdf下载
使用JavaScript实现PDF下载
方法一:使用HTML5的<a>标签下载
创建一个隐藏的<a>标签,设置其href属性为PDF文件的URL,并触发点击事件。
function downloadPDF(url, filename) {
const a = document.createElement('a');
a.href = url;
a.download = filename || 'document.pdf';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
// 使用示例
downloadPDF('https://example.com/document.pdf', 'myfile.pdf');
方法二:使用Blob对象和URL.createObjectURL
适用于需要从后端API获取PDF数据流或动态生成PDF的情况。
function downloadPDFFromBlob(blobData, filename) {
const blob = new Blob([blobData], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename || 'document.pdf';
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, 100);
}
// 使用示例(假设从API获取数据)
fetch('https://api.example.com/generate-pdf')
.then(response => response.blob())
.then(blob => downloadPDFFromBlob(blob, 'report.pdf'));
方法三:使用jsPDF库生成并下载PDF
适用于需要在浏览器端动态生成PDF的场景。
安装jsPDF库:
npm install jspdf
代码示例:
import { jsPDF } from "jspdf";
function generateAndDownloadPDF() {
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("generated.pdf");
}
// 或添加更复杂内容
function createComplexPDF() {
const doc = new jsPDF();
doc.setFontSize(16);
doc.text("Sample Report", 105, 15, { align: 'center' });
doc.setFontSize(12);
doc.text("This is a dynamically generated PDF document.", 10, 30);
doc.save('report.pdf');
}
方法四:使用PDFKit(Node.js后端方案)
适用于需要在服务器端生成PDF的情况。
安装PDFKit:
npm install pdfkit
服务器端代码示例:
const PDFDocument = require('pdfkit');
const fs = require('fs');
function generatePDF(res) {
const doc = new PDFDocument();
doc.pipe(fs.createWriteStream('output.pdf'));
doc.fontSize(25).text('Hello World', 100, 100);
doc.end();
// 或者直接发送给客户端
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'attachment; filename=download.pdf');
doc.pipe(res);
}
注意事项
- 跨域问题:确保PDF文件所在服务器允许跨域请求,或通过代理服务器获取
- 大文件处理:对于大型PDF文件,建议显示下载进度提示
- 移动端兼容性:部分移动浏览器可能限制程序化下载行为
- 文件名编码:处理包含特殊字符的文件名时需要进行编码
扩展功能
添加下载进度提示的示例:
function downloadWithProgress(url, filename) {
return fetch(url)
.then(response => {
const reader = response.body.getReader();
const contentLength = +response.headers.get('Content-Length');
let receivedLength = 0;
const chunks = [];
return new Promise((resolve, reject) => {
function pump() {
reader.read().then(({ done, value }) => {
if (done) {
const blob = new Blob(chunks);
resolve(blob);
return;
}
chunks.push(value);
receivedLength += value.length;
console.log(`Downloaded ${receivedLength} of ${contentLength}`);
pump();
}).catch(reject);
}
pump();
});
})
.then(blob => downloadPDFFromBlob(blob, filename));
}






