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
相关产品推荐
相关产品推荐

