带有pdf_from_string的邪恶pdf页面背景图片

时间:2019-04-28 11:57:32

标签: ruby-on-rails ruby wicked-pdf

我需要使用pdf_from_string方法将背景图像添加到生成的PDF中。

这是我的代码

pdf = WickedPdf.new.pdf_from_string(html,
           header: {
                content: render_to_string('pdf/pdf_header.html.erb', layout: 'pdf_layout.html.erb')
           },
           footer: {
                content: render_to_string('pdf/pdf_footer.html.erb', layout: 'pdf_layout.html.erb')
           },
           background: true,
           save_to_file: Rails.root.join("pdfs","#{pdf_name}.pdf"),
           save_only: true
        )

页眉和页脚工作正常,但是我找不到添加背景图像选项的方法,我们非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我通过使用render_to_string方法并将HTML内容作为本地内容传递给模板,从而解决了该问题,如下所示:

pdf = WickedPdf.new.pdf_from_string(
        render_to_string('pdf/pdf_full_page.html.erb', layout:'pdf_layout.html.erb', locals: { content: html}),
           header: {
                content: render_to_string('pdf/pdf_header.html.erb', layout: 'pdf_layout.html.erb')
           },
           footer: {
                content: render_to_string('pdf/pdf_footer.html.erb', layout: 'pdf_layout.html.erb')
           },
           layout: 'pdf_layout.html.erb',
           debug: true,
           background: true,
           no_background: false,
           save_to_file: Rails.root.join("pdfs","#{pdf_name}.pdf"),
           save_only: true
        )

pdf_full_page.html.erb查看代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PDF Full page</title>
</head>
<body>
    <%= content.html_safe %>
</body>
</html>

我希望它可以帮助其他人