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

React+TypeScript项目pdfmake生产环境PDF加载空白问题求助

解决React+TypeScript生产环境下pdfmake生成空白PDF的问题

针对开发环境正常、生产打包后PDF空白的问题,可通过以下步骤排查修复:

1. 修正字体资源挂载逻辑,避免Tree-shaking误删

生产构建时,Vite/Rollup的Tree-shaking会将看似无意义的pdfMake.vfs赋值移除,导致pdfmake找不到字体资源,最终生成空白PDF。修改初始化代码:

// 替换原有的导入与赋值
import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';

// 显式挂载字体资源,添加生产环境标记避免被优化
pdfMake.vfs = pdfFonts.pdfMake.vfs;
if (import.meta.env.PROD) {
  Object.assign(pdfMake, { vfs: pdfFonts.pdfMake.vfs });
}

2. 修复customersReports为空时的边界错误

当customersReports为undefined时,itemsCustomerReport会是undefined,展开到表格body中会导致pdfmake渲染失败(生产环境静默报错)。给相关变量添加默认值:

// 修正表格body的展开逻辑
body: [
  [
    { text: 'CLIENTE', style: 'tableHeader', fontSize: 8 },
    { text: 'DATA', style: 'tableHeader', fontSize: 8 },
    { text: 'Q.ENTREGAS', style: 'tableHeader', fontSize: 8 },
    { text: '', style: 'tableHeader', fontSize: 8 },
  ],
  ...(itemsCustomerReport || []), // 添加空数组默认值
  // 合计行代码保持不变
]

同时修正taxa和valorEntrega的计算逻辑,避免出现NaN:

const taxa = customersReports?.length 
  ? (customersReports[0].qtdeEntrega <= totalQuantity 
      ? customersReports[0].valor_entrega_pedido_maior 
      : customersReports[0].valor_entrega_pedido_menor)
  : 0;

const valorEntrega = customersReports?.length 
  ? customersReports[0].valor_entregas - Number(taxa)
  : 0;

3. 调整Vite构建配置,强制保留pdfmake资源

在vite.config.ts中添加Rollup配置,避免pdfmake相关文件被误优化:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          pdfmake: ['pdfmake', 'pdfmake/build/vfs_fonts']
        }
      }
    },
    optimizeDeps: {
      include: ['pdfmake', 'pdfmake/build/vfs_fonts']
    }
  }
});

4. 添加错误捕获,方便生产环境排查

给PDF生成函数添加错误捕获,快速定位生产环境的隐藏问题:

export default async function ListCompaniesReports(customersReports: ListCompaniesReportOptions[] | undefined) {
  try {
    // 原有业务逻辑...

    pdfMake.createPdf(reportDefinitions).open();
  } catch (error) {
    console.error('PDF生成失败:', error);
    alert('无法生成PDF,请稍后重试');
  }
}

内容的提问来源于stack exchange,提问作者Marcelo Ribeiro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 08:45:03