简体   繁体   English

从Rails生成PDF

[英]Generate PDF from Rails

The Ruby On Rails Wiki lists a couple of librarie s that facilitate PDF generation in Rails . Ruby On Rails Wiki列出了一些便于在Rails中生成PDF 的库 I need to print out address labels (in letter format, thus 12-15 addresses per page) and cannot decide which one to use. 我需要打印出地址标签(字母格式,每页12-15个地址),不能决定使用哪一个。 Any recommendations? 有什么建议?

Prawn with Prawnto for sure. Prawnt与Prawnto肯定。 The DSL is a real treat, as is the simplicity of being able to treat PDF as any other format in a respond_to format block: DSL是一种真正的享受,因为能够将PDF视为respond_to格式块中的任何其他格式的简单性:

respond_to do |format|
format.pdf { render :layout => false }

There's a tutorial video on Prawn here : 有一个关于虾的教程视频在这里

There's also RTeX . 还有RTeX That works well if you're willing to translate to LaTeX first. 如果你愿意首先翻译成LaTeX,这很有效。 LaTeX is a very good way to store marked-up documents. LaTeX是存储标记文档的一种非常好的方法。 It just depends on how static each document is. 它只取决于每个文档的静态程度。 If most of the document is dynamic, you might do better with Prawn or PDF::Writer. 如果大多数文档都是动态的,那么使用Prawn或PDF :: Writer可能会做得更好。 If most of it is static, with just a couple of text-replacements for each, LaTeX might be a better choice. 如果大多数是静态的,每个只有几个文本替换,LaTeX可能是更好的选择。

There is also PDFKit . 还有PDFKit It's quite interesting too. 这也很有趣。

If you're not doing anything too complex, You could also use HTMLDOC, which converts basic HTML to PDF. 如果您没有做太复杂的事情,您还可以使用HTMLDOC,它将基本HTML转换为PDF。 This prevents you from having to learn more proprietary layout syntax(like in the case of Prawn). 这可以防止您必须学习更多专有的布局语法(如Prawn的情况)。 It might save you some headaches :) 它可能会让你有些头疼:)

Here's a link to the ruby gem for HTMLDOC: 这是HTMLDOC的ruby gem的链接:

Also, here's a good guide for rendering a view in rails to pdf using HTMLDOC: 另外,这里有一个很好的指南,用于使用HTMLDOC在rails中呈现视图到pdf:

Prawn is the way to go. 对虾是要走的路。 Now with prawn-labels that is really easy to do. 现在用虾标签很容易做到。

Check out the project's README here: 在这里查看项目的README:

https://github.com/jordanbyron/prawn-labels#readme https://github.com/jordanbyron/prawn-labels#readme

This is a super simple example being used in a Rails controller. 这是一个在Rails控制器中使用的超级简单示例。 Don't forget to add gem 'prawn-labels' to your Gemfile. 别忘了在你的Gemfile中添加gem'prawn gem 'prawn-labels'

names = %w{Jordan Kelly Greg Bob}

labels = Prawn::Labels.render(names, :type => "Avery5160") do |pdf, name|
  pdf.text name
end

send_data labels, :filename => "names.pdf", :type => "application/pdf"

I've used both PDF::Writer and Prawn and find Prawn much more pleasant to use. 我已经使用了PDF :: Writer和Prawn,并且发现Prawn使用起来更加愉快。 Check out Ruby Mendicant for a comparison that demonstrates the joys of Prawn w/r/t PDF::Writer. 查看Ruby Mendicant进行比较 ,以展示Prawn w / r / t PDF :: Writer的乐趣。

Actually, just check out Ruby Mendicant anyway for a great design pattern for right livelihood as a developer. 实际上,无论如何,只需检查Ruby Mendicant作为开发人员的正确生计设计模式

For your use case, I agree with most other answers that prawn is the right choice because you need pixel-level control over the output. 对于您的用例,我同意大多数其他答案,即prawn是正确的选择,因为您需要对输出进行像素级控制。

For generating PDF reports with built-in (opinionated) table styling, headers, etc., you can use the report gem - check out Generate pdf from Rails 3 - what tool to choose? 为了生成具有内置(固定)表格样式,标题等的PDF报告,您可以使用report gem - 查看从Rails 3生成pdf - 选择什么工具? for an example of how to use. 以获取如何使用的示例。

I've used flying saucer for pdf generation from html. 我从html使用飞碟进行pdf生成。 It's a java library but you can use the Ruby-Java Bridge gem to access it in your rails app. 它是一个java库,但您可以使用Ruby-Java Bridge gem在rails应用程序中访问它。 It's css 2.1 compliant and has a few additions from css3 to allow some extra control over paging. 它符合css 2.1并且有一些来自css3的附加功能,可以对分页进行一些额外的控制。 I'd recommend it as it doesn't require you to put 'pdf code' in your html, you can use the same views and partials to display to the browser as you do to generate pdfs. 我推荐它,因为它不要求你在你的html中加入'pdf code',你可以使用相同的视图和部分显示到浏览器,就像你生成pdfs一样。

Flying Saucer: https://github.com/flyingsaucerproject/flyingsaucer 飞碟: https//github.com/flyingsaucerproject/flyingsaucer

Ruby Java Bridge: http://rjb.rubyforge.org/ Ruby Java Bridge: http//rjb.rubyforge.org/

I use this module code to generate the pdfs 我使用这个模块代码来生成pdfs

require 'rubygems'
require 'rjb'

module Html2Pdf

  def self.included(controller)
      controller.send :helper_method, :create_pdf
  end

  def create_pdf(options = {})
      itext = "#{RAILS_ROOT}/lib/html2pdf/jars/iText-2.0.8.jar"
      core_renderer = "#{RAILS_ROOT}/lib/html2pdf/jars/core-renderer.jar"
      xerces = "#{RAILS_ROOT}/lib/html2pdf/jars/xml-apis-xerces-2.9.1.jar" 
      joinchar = (RUBY_PLATFORM.include? 'mswin') ? ';' : ':'
          classpath = [itext, core_renderer, xerces].join(joinchar)
      Rjb::load(classpath, jvmargs=['-Djava.awt.headless=true'])
      if options[:htmlstring].nil?
      options[:layout] ||= false
          options[:template] ||= File.join(controller_path,action_name+".pdf.erb")
          html_string = render_to_string(:template => options[:template], :layout => options[:layout])
    else
          html_string = options[:htmlstring]
    end
    # Make all paths relative, on disk paths...
    html_string.gsub!(".com:/",".com/") # strip out bad attachment_fu URLs
    html_string.gsub!( /src=["']+([^:]+?)["']/i ) { |m| "src=\"file:///#{RAILS_ROOT}/public/" + $1 + '"' } # re-route absolute paths
    html_string.gsub!( /url\(["']+([^:]+?)["']/i ) { |m| "url\(\"file:///#{RAILS_ROOT}/public/" + $1 + '"' } # re-route absolute paths
    # Remove asset ids on images with a regex // tbh i can't remember what this line is for but i'm sure it did something awesome
    html_string.gsub!( /src=["'](\S+\?\d*)["']/i ) { |m| 'src="' + $1.split('?').first + '"' } 
    filename = "#{RAILS_ROOT}/public/pdfs/"+options[:filename]+".pdf"
    fileOutputStream = Rjb::import('java.io.FileOutputStream')
      iTextRenderer = Rjb::import('org.xhtmlrenderer.pdf.ITextRenderer')
      renderer = iTextRenderer.new
      renderer.setDocumentFromString(html_string)
      os = fileOutputStream.new(filename)
      renderer.layout()
      renderer.createPDF(os)
      os.close()
  end

end

Calling it with code like this: 用这样的代码调用它:

def generate_pdf  
  htmlsrc = render_to_string(:partial => 'invoice', :layout => false)
  rnd = Time.now.to_s(:datentime).gsub!(/[\/ \.:]/,'')
  filename = "docstore/tmp_#{rnd}"
  create_pdf(:htmlstring => htmlsrc, :filename => filename)
  contents = open("#{RAILS_ROOT}/public/pdfs/#{filename}.pdf", "rb") { |io| io.read }
  File.delete("#{RAILS_ROOT}/public/pdfs/#{filename}.pdf")
  respond_to do | wants |
    wants.html { render :text => contents, :content_type => 'application/pdf' }
  end    
end

Though not completely ruby, you could use OpenOffice .odt to generate PDFs by combining serenity and docsplit. 虽然不是完全红宝石,但您可以使用OpenOffice .odt通过结合宁静和docsplit来生成PDF。

http://github.com/kremso/serenity http://github.com/kremso/serenity

http://documentcloud.github.com/docsplit/ http://documentcloud.github.com/docsplit/

Or you could use the clamsy gem which uses odt and cups-pdf to generate the PDF. 或者您可以使用使用odt和cups-pdf生成PDF的clamsy gem。

http://github.com/ngty/clamsy http://github.com/ngty/clamsy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM