使用pdf-lib实现按钮下载PDF时VS Code提示download未定义
解决SvelteKit中download函数VS Code标红问题
问题原因
功能正常但VS Code提示“Cannot find name 'download'”,本质是download是通过CDN引入的全局变量,TypeScript/SvelteKit的类型检查无法识别这个未声明的全局函数;而浏览器运行时能通过CDN脚本拿到全局的download,所以实际功能不受影响。
解决方案
方案1:声明全局变量
在脚本块顶部添加全局变量声明,让TypeScript识别该函数:
<script> import { PDFDocument, StandardFonts, rgb } from 'pdf-lib'; // 声明全局download函数类型 declare var download: (data: Blob | Uint8Array, filename: string, mimeType: string) => void; async function createPdf() { // ... 原有代码不变 download(pdfBytes, "pdf-lib_creation_example.pdf", "application/pdf"); } </script>
方案2:改用ES模块导入downloadjs
既然已安装downloadjs npm包,直接用模块导入替代CDN,VS Code会自动识别类型:
- 移除
<head>里的downloadjs CDN脚本 - 在脚本中导入download:
<script> import { PDFDocument, StandardFonts, rgb } from 'pdf-lib'; import download from 'downloadjs'; async function createPdf() { // ... 原有代码不变 download(pdfBytes, "pdf-lib_creation_example.pdf", "application/pdf"); } </script>
方案3:不依赖downloadjs,手动实现下载逻辑
完全自定义下载逻辑,避免外部依赖:
<script> import { PDFDocument, StandardFonts, rgb } from 'pdf-lib'; async function createPdf() { // ... 原有代码不变 const pdfBytes = await pdfDoc.save(); // 手动实现下载流程 const blob = new Blob([pdfBytes], { type: 'application/pdf' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = "pdf-lib_creation_example.pdf"; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } </script>
修改后完整代码示例(方案2)
<body> <p>Click the button to create a new PDF document with <code>pdf-lib</code></p> <button on:click={createPdf}>Create PDF</button> <p class="small">(Your browser will download the resulting file)</p> </body> <script> import { PDFDocument, StandardFonts, rgb } from 'pdf-lib'; import download from 'downloadjs'; async function createPdf() { const pdfDoc = await PDFDocument.create(); const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman); const page = pdfDoc.addPage(); const { width, height } = page.getSize(); const fontSize = 30; page.drawText('Creating PDFs in JavaScript is awesome!', { x: 50, y: height - 4 * fontSize, size: fontSize, font: timesRomanFont, color: rgb(0, 0.53, 0.71), }); const pdfBytes = await pdfDoc.save(); download(pdfBytes, "pdf-lib_creation_example.pdf", "application/pdf"); } </script> <style> body { width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center; flex-direction: column; } p { font-family: helvetica; font-size: 24px; text-align: center; margin: 25px; } .small { font-family: helvetica; font-size: 18px; text-align: center; margin: 25px; } button { background-color: #008CBA; border: none; color: white; padding: 15px 32px; text-align: center; font-size: 16px; } </style>
内容的提问来源于stack exchange,提问作者Josh Hayles
相关产品推荐
相关产品推荐

