使用 wicked_pdf 生成 pdf 时进行分页

Ask*_*kar 5 pdf-generation wicked-pdf ruby-on-rails-4

示例.erb.html

<p>Page 1</p1>

<p>Page 2</p2>
Run Code Online (Sandbox Code Playgroud)

因此,“第 1 页”之后的所有内容我都想打印在第 2 页上。

我怎样才能做到这一点?

SO中有一种解决方案,但对我不起作用。

例如,在 Prawn 的情况下,它有一个很好的功能叫做start_new_page

rde*_*an1 4

在你的CSS中

p{page-break-after: always;}
Run Code Online (Sandbox Code Playgroud)

更新

在几个问题之后,我将扩展我的答案以及如何在我的应用程序中使用它。

1 有时,wickedpdf 帮助程序不起作用,所以我添加一个初始化程序

_config/initializers/wiked_pdf.rb_

module WickedPdfHelper
  def wicked_pdf_stylesheet_link_tag(*sources)
    sources.collect { |source|
      "<style type='text/css'>#{Rails.application.assets.find_asset("#{source}.css")}</style>"
    }.join("\n").gsub(/url\(['"](.+)['"]\)(.+)/,%[url("#{wicked_pdf_image_location("\\1")}")\\2]).html_safe
  end

  def wicked_pdf_image_tag(img, options={})
    image_tag wicked_pdf_image_location(img), options
  end

  def wicked_pdf_image_location(img)
    "file://#{Rails.root.join('app', 'assets', 'images', img)}"
  end

  def wicked_pdf_javascript_src_tag(source)
    "<script type='text/javascript'>#{Rails.application.assets.find_asset("#{source}.js").body}</script>"
  end

  def wicked_pdf_javascript_include_tag(*sources)
    sources.collect{ |source| wicked_pdf_javascript_src_tag(source) }.join("\n").html_safe
  end

  WickedPdf.config = {

  }
end
Run Code Online (Sandbox Code Playgroud)

2 在应用程序控制器中使用常规配置参数创建一个配置方法

_应用程序/控制器/application_controller.rb_

class ApplicationController < ActionController::Base
  def pdf_config
    WickedPdf.config = {
        :wkhtmltopdf => "/usr/local/bin/wkhtmltopdf",
        :orientation  => 'Landscape',
        :layout => "pdf.html",
        :footer => {
            :left => "Rectores Lideres Transformadores",
            #:left => "#{Entidad.find(@current_user.entidad).nombre}",
            :right => "#{Time.now}",
            :font_size => 5,
            :center => '[page] de [topage]'
        },
        :disposition => 'attachment'

    }
  end

end
Run Code Online (Sandbox Code Playgroud)

3 为所有 pdf 文件创建通用布局。在这里,我使用我的应用程序 css 来保持 pdf 报告中网页的相同外观和感觉,只是我必须使用相同的类和 id

应用程序/布局/pdf.html.erb

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <%= wicked_pdf_stylesheet_link_tag "application" %> ----- HERE YOUR APPLICATION CSS -----
</head>
<div id="content">
  <%= yield %>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

4 在控制器中添加 pdf 重定向

_应用程序/控制器/user_controller.rb_

 def index
    @users = User.all

    respond_to do |format|
      format.pdf do
        pdf_config
        render  :pdf => "filename"
      end
    end
  end
Run Code Online (Sandbox Code Playgroud)

5 现在,在你的 css 中,选择哪个 html id 是页面刹车

 #brake{page-break-after: always;}
Run Code Online (Sandbox Code Playgroud)