Rails 3和PDFKit,如何将HTML文件转换为横向PDF?

时间:2012-01-12 21:07:06

标签: ruby-on-rails ruby ruby-on-rails-3 pdfkit

我可以很好地将HTML页面转换为PDF文档。问题是,我不知道如何将HTML文件转换为横向PDF。有没有办法在控制器中设置它?

来自控制器...

def pdf_customer_shipments
  @customer = Customer.find(params[:id])
  @shipments = Shipment.where("customer_id = ? AND status = 'Open'", @customer.id)
  render :layout => 'pdf'
end

3 个答案:

答案 0 :(得分:7)

如果这有帮助,我使用PDFKit并可以使用以下方式渲染pdf:

respond_to do |format|
  format.html
  format.pdf {
    html = render_to_string(:layout => false , :action => "my_page.html.haml")
    kit = PDFKit.new(html, :orientation => 'Landscape')
    kit.stylesheets << "#{Rails.root}/public/stylesheets/views/pdf.css"
    send_data(kit.to_pdf, :filename => "some_name.pdf", :type => 'application/pdf')
    return # to avoid double render call
  }
end

我从这里得到了方向部分:https://github.com/pdfkit/pdfkit/issues/12

答案 1 :(得分:6)

你的html文件中需要一个元标记:

...
<head>
  <meta name="pdfkit-orientation" content="Landscape"/>
</head>
...

然后PDF处于横向。

答案 2 :(得分:0)

PDFKit应该接受wkhtmltopdf的选项,因此您应该能够使用以下方式在横向模式下渲染:

def pdf_customer_shipments   
  @customer = Customer.find(params[:id])   
  @shipments = Shipment.where("customer_id = ? AND status = 'Open'", @customer.id
  render :layout => 'pdf', :orientation => 'Landscape' 
end