Ruby on Rails中WickedPDF生成空白PDF邮件附件问题
解决ActionMailer发送WickedPDF生成的空白PDF附件问题
先看你代码里的明显问题:
- locals参数缺失赋值:你写了
locals: { current_user: },这里current_user没有传入具体值,模板如果依赖这个变量会直接渲染失败,导致生成空白PDF。要把当前用户实例传进去,比如locals: { current_user: current_user }(前提是你的mailer能拿到current_user变量)。
以下是其他常见问题及修复方案:
指定渲染格式为HTML:
render_to_string默认格式可能不是HTML,而WickedPDF需要基于HTML内容生成PDF,所以要显式添加format: :html:render_to_string( template: 'invoices/service', format: :html, locals: { current_user: current_user } )确保模板能获取到账单数据:你的模板
invoices/service大概率依赖@invoice数据,要么把@invoice也传入locals,要么确保模板能直接读取mailer里的实例变量:render_to_string( template: 'invoices/service', format: :html, locals: { current_user: current_user, invoice: @invoice } )之后在模板里用
invoice替代@invoice即可,或者保持模板用@invoice(因为mailer的实例变量默认能被视图访问)。显式配置WickedPDF参数:部分场景下需要指定页面尺寸、边距等参数,确保PDF正常渲染:
attachments['invoice.pdf'] = WickedPdf.new.pdf_from_string( render_to_string(...), page_size: 'A4', margin: { top: 10, bottom: 10, left: 10, right: 10 } )先验证HTML渲染结果:可以在控制台单独测试
render_to_string的输出,确认模板能正常生成有内容的HTML:html = render_to_string(template: 'invoices/service', format: :html, locals: { current_user: User.first, invoice: Invoice.first }) puts html # 查看输出是否包含账单内容检查wkhtmltopdf依赖:WickedPDF依赖wkhtmltopdf工具,终端执行
wkhtmltopdf --version确认工具已正确安装且能正常运行,版本不兼容也会导致空白PDF。
修复后的完整代码示例:
if params[:invoice_id].present? @invoice = Invoice.find(params[:invoice_id]) pdf_content = WickedPdf.new.pdf_from_string( render_to_string( template: 'invoices/service', format: :html, locals: { current_user: current_user, invoice: @invoice } ), page_size: 'A4' ) attachments['invoice.pdf'] = { content: pdf_content, mime_type: 'application/pdf' } end
这里显式声明了附件的mime类型,能避免部分邮件客户端识别附件异常的问题。
内容的提问来源于stack exchange,提问作者Roshan Lasiwa
相关产品推荐
相关产品推荐

