You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor Server项目用jsPDF导出PDF遇“jspdf未定义”错误求助

Blazor Server中使用jsPDF导出PDF时“jspdf is not defined”错误的解决方法

问题分析

你在Blazor Server的ReportDetails.razor页面调用jsPDF生成PDF时出现jspdf is not defined错误,结合代码来看,核心问题集中在语法错误和函数作用域暴露不当,以下是具体修复步骤:


修复步骤

1. 修正jsPDF实例化的语法错误

你的exportPDF.js中创建PDF实例时写了重复的new关键字,这是语法错误,同时要确保UMD版本的jsPDF全局引用正确:

// 错误写法
const pdf = new new jspdf.jsPDF();

// 正确写法
const pdf = new jspdf.jsPDF();

2. 调整函数暴露方式

你使用了ES模块的export function语法,但直接在HTML中引入普通脚本时,该函数不会暴露到全局作用域,导致Blazor的JSRuntime无法找到。需要将函数挂载到window对象:

// 替换原export语法为挂载到window
window.exportPDF = function(update) {
    console.log("JavaScript function exportPDF invoked!");

    const pdf = new jspdf.jsPDF();

    pdf.setProperties({
        title: 'Emergency Report',
        subject: 'Incident details',
        author: 'BDRRMO Admin',
        keywords: 'emergency, report',
    });

    var content = `
    Report Details:
    Reported By: ${update.Email}
    Date & Time: ${update.DateTime}
    Description: ${update.Description}
    Location: ${update.Location}
    Status: ${update.Status}
    Remarks: ${update.Remarks}
    Responder: ${update.Responder}
    Emergency Medical Responder: ${update.MedicalResponder}
    Time of Departure: ${update.Departure}
    Time of Arrival at the scene: ${update.Arrival}
    Total Response Time: ${update.ResponseTime}
    For Vehicle Accident, the patient is: ${update.VehicleAccident}
    For Fire Incident, the patient is: ${update.Fire}
    For Crime Incident, the patient is: ${update.Crime}
  `;

    pdf.text(content, 10, 10);
    pdf.save('Emergency_Report.pdf');

    console.log("PDF generation completed successfully!");
}

3. 确认脚本引入顺序

确保jspdf.umd.min.js在你的自定义脚本之前加载,保证jsPDF全局对象已初始化:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
<script src="~/PDFExport.js"></script>

4. 可选:添加调用前的存在性检查

在Blazor代码中添加函数存在性校验,便于快速排查问题:

private async Task ExportAsPDF()
{
    try
    {
        var isFunctionExist = await JSRuntime.InvokeAsync<bool>("typeof exportPDF !== 'undefined'");
        if (!isFunctionExist)
        {
            Console.WriteLine("exportPDF 函数未在全局作用域中找到");
            return;
        }
        await JSRuntime.InvokeVoidAsync("exportPDF", update);
    }
    catch (Exception ex)
    {
        Console.WriteLine($"导出PDF出错: {ex.Message}");
    }
}

内容的提问来源于stack exchange,提问作者Joey Martinez Jr.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 16:33:25