Ruby-on-rails 从 Rails 生成 PDF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/433136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:54:29  来源:igfitidea点击:

Generate PDF from Rails

ruby-on-railspdfpdf-generation

提问by Sebastian

The Ruby On Rails Wiki lists a couple of libraries that facilitate PDFgeneration in Rails. I need to print out address labels (in letter format, thus 12-15 addresses per page) and cannot decide which one to use. Any recommendations?

Ruby on Rails的维基列出了几个librarie的促进小号PDF中产生的Rails。我需要打印地址标签(以信件格式,因此每页 12-15 个地址)并且无法决定使用哪一个。有什么建议吗?

回答by btw

Prawn with Prawnto for sure. 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:

肯定有Prawnto的大虾。DSL 是一种真正的享受,因为能够将 PDF 视为 response_to 格式块中的任何其他格式的简单性:

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

There's a tutorial video on Prawn here:

有一个关于虾的教程视频在这里

回答by James A. Rosen

There's also RTeX. That works well if you're willing to translate to LaTeXfirst. LaTeX is a very good way to store marked-up documents. 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. If most of it is static, with just a couple of text-replacements for each, LaTeX might be a better choice.

还有RTeX。如果您愿意先翻译成LaTeX,那效果很好。LaTeX 是一种非常好的存储标记文档的方法。这仅取决于每个文档的静态程度。如果大部分文档都是动态的,使用 Prawn 或 PDF::Writer 可能会更好。如果大部分内容都是静态的,每个内容只有几个文本替换,那么 LaTeX 可能是更好的选择。

回答by dhulihan

If you're not doing anything too complex, You could also use HTMLDOC, which converts basic HTML to PDF. This prevents you from having to learn more proprietary layout syntax(like in the case of Prawn). It might save you some headaches :)

如果您不做任何太复杂的事情,您还可以使用 HTMLDOC,它将基本 HTML 转换为 PDF。这可以防止您必须学习更多专有布局语法(例如 Prawn 的情况)。它可能会为您节省一些头痛:)

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 的好指南:

回答by babttz

There is also PDFKit. It's quite interesting too.

还有PDFKit。这也很有趣。

回答by Jordan

Prawn is the way to go. Now with prawn-labels that is really easy to do.

大虾是要走的路。现在有了对虾标签,这真的很容易做到。

Check out the project's README here:

在此处查看项目的自述文件:

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. Don't forget to add gem 'prawn-labels'to your Gemfile.

这是一个在 Rails 控制器中使用的超级简单的例子。不要忘记添加gem 'prawn-labels'到您的 Gemfile 中。

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"

回答by Abie

I've used both PDF::Writer and Prawn and find Prawn much more pleasant to use. Check out Ruby Mendicantfor a comparisonthat demonstrates the joys of Prawn w/r/t PDF::Writer.

我使用过 PDF::Writer 和 Prawn,发现 Prawn 使用起来更加愉快。查看Ruby Mendicant进行比较,展示 Prawn w/r/t PDF::Writer 的乐趣。

Actually, just check out Ruby Mendicant anyway for a great design patternfor right livelihood as a developer.

实际上,无论如何,只要查看 Ruby Mendicant 就可以了解作为开发人员正确谋生的出色设计模式

回答by Seamus Abshere

For your use case, I agree with most other answers that prawnis 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 reportgem - check out Generate pdf from Rails 3 - what tool to choose?for an example of how to use.

要生成具有内置(自以为是的)表格样式、标题等的 PDF 报告,您可以使用reportgem - 查看从 Rails 3 生成 pdf - 选择什么工具?有关如何使用的示例。

回答by theirongiant

I've used flying saucer for pdf generation from html. It's a java library but you can use the Ruby-Java Bridge gem to access it in your rails app. It's css 2.1 compliant and has a few additions from css3 to allow some extra control over paging. 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。它是一个 Java 库,但您可以使用 Ruby-Java Bridge gem 在您的 Rails 应用程序中访问它。它符合 css 2.1,并且有一些来自 css3 的附加功能,以允许对分页进行一些额外的控制。我推荐它,因为它不需要您在 html 中放入“pdf 代码”,您可以使用与生成 pdf 相同的视图和部分显示到浏览器。

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

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

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

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

I use this module code to generate the pdfs

我使用此模块代码生成 pdf

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/" +  + '"' } # re-route absolute paths
    html_string.gsub!( /url\(["']+([^:]+?)["']/i ) { |m| "url\(\"file:///#{RAILS_ROOT}/public/" +  + '"' } # 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="' + .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

回答by JasonOng

Though not completely ruby, you could use OpenOffice .odt to generate PDFs by combining serenity and docsplit.

虽然不完全是 ruby​​,但您可以使用 OpenOffice .odt 通过结合 serenity 和 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 的 clamsy gem 生成 PDF。

http://github.com/ngty/clamsy

http://github.com/ngty/clamsy