Ruby-on-rails Rails:将 HTML 转换为 PDF?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/357212/
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:50:17  来源:igfitidea点击:

Rails: Convert HTML to PDF?

ruby-on-railspdf

提问by rip747

What is the best and easiest way of taking HTML and converting it into a PDF, similar to use CFDOCUMENT on ColdFusion?

获取 HTML 并将其转换为 PDF 的最佳和最简单的方法是什么,类似于在 ColdFusion 上使用 CFDOCUMENT?

UPDATE:I really appreciate all the comments and suggestions that people have given so far, however I feel that people leaving their answers are missing the point.

更新:我真的很感谢人们到目前为止给出的所有评论和建议,但是我觉得人们离开他们的答案没有抓住要点。

1) the solution has to be free or open sourced. one person suggested using pricexml and the other pd4ml. both of these solutions costs money (pricexml costing an arm and a leg) which i'm not about the fork over.

1) 解决方案必须是免费的或开源的。一个人建议使用 pricexml 和另一个 pd4ml。这两种解决方案都需要花钱(pricexml 需要花费一条胳膊和一条腿),我不是在讨论这个问题。

2) they must be able to take in html (either from a file, url or a string variable) and then produce the pdf. libraries like prawn, rprf, rtex are produced using their own methods and not taking in html.

2) 他们必须能够接收 html(来自文件、url 或字符串变量),然后生成 pdf。像 prawn、rprf、rtex 这样的库是使用它们自己的方法生成的,而不是采用 html。

please don't think i'm ungrateful for the suggestions, it's just that pdf generation seems like a really problem for people like me who use ColdFusion but want to convert to Rails.

请不要认为我对这些建议忘恩负义,只是对于像我这样使用 ColdFusion 但想转换为 Rails 的人来说,生成 pdf 似乎是一个真正的问题。

回答by Sebastian

The gem, WickedPDF, does exactlythat.

宝石,WickedPDF,不正是这一点。

回答by fl00r

回答by Sajjad Murtaza

Try WickedPDF, PDF generator (from HTML) plugin.

试试 WickedPDF,PDF 生成器(来自 HTML)插件。

Here is example

这是例子

gem 'wicked_pdf'  
gem 'wkhtmltopdf-binary' 
#wicked_pdf is a wrapper for wkhtmltopdf, you'll need to install that, too

In Your Controller(I supposed you are in show method):

在你的控制器中(我假设你在 show 方法中):

    respond_to  do |format|
      format.html
      format.pdf do
        pdf = render_to_string :pdf => 'test',
                         layout: 'pdf.html.erb',
                         template: 'show.pdf.slim',
                         header: { :right => '[page] of [topage]'},
                         margin: {top: 0,
                                  bottom: 0,
                                  left: 0,
                                  right: 0},
                         outline: {outline: true,
                                   outline_depth: 2}
        end
     end

In your view for PDF link

在您看来,PDF 链接

= link_to 'Download Pdf', you_show_path(@uour_object, format: :pdf)

If you want to send pdf in email attachment, first save your pdf file in public or temp folder then in mailer class (e.g. in mailers/e_mailer.rb)

如果您想在电子邮件附件中发送 pdf,首先将您的 pdf 文件保存在 public 或 temp 文件夹中,然后在邮件程序类中(例如在 mailers/e_mailer.rb 中)

attachments["test.pdf"] = File.read(Rails.root.join('public',"test.pdf"))
mail(:to => to, :cc => cc , :subject => "subject")

After sending email you can delete file

发送电子邮件后,您可以删除文件

File.delete(Rails.root.join("public", "test.pdf"))

回答by Michael Irey

I know this question is almost 5 years old at this point. However, new options are available.

我知道这个问题在这一点上已经有将近 5 年的历史了。但是,有新的选项可用。

Try Shrimp! https://github.com/adeven/shrimp

试试虾!https://github.com/adeven/shrimp

回答by tsdbrown

After After a lot of blood sweat and tears I managed to write a pretty simple rails app that allows the user to write letter templates via TinyMce, these are then saved and can be viewed as pdf documents.

经过大量的血汗和泪水之后,我设法编写了一个非常简单的 Rails 应用程序,允许用户通过TinyMce编写信函模板,然后将这些模板保存起来并可以作为 pdf 文档查看。

I decided to restrict the options in the wysiwyg editor as much as possible as some of the options don't work exactly as expected, but that's nothing a little gsub-ing couldn't solve if needed.

我决定尽可能地限制所见即所得编辑器中的选项,因为某些选项不能完全按预期工作,但是如果需要,gsub-ing 解决不了任何问题。

There is a ruby gem that wraps HTMLDOC which you'll need: PDF::HTMLDoc

有一个包装 HTMLDOC 的 ruby​​ gem,您将需要它:PDF::HTMLDoc

Once you've got that, register the mime type, then you can do something like:

完成后,注册 mime 类型,然后您可以执行以下操作:

@letter_template = LetterTemplate.find(params[:id])

respond_to do |format|
      format.html
      format.pdf { send_data render_to_pdf({:action => 'show.rpdf',  :layout => 'pdf_report'}), :filename => @letter_template.name + ".pdf",  :disposition => 'inline' }
    end

In the application controller i've added the render_to_pdf method like:

在应用程序控制器中,我添加了 render_to_pdf 方法,如:

def render_to_pdf(options =nil)
    data = render_to_string(options)
    pdf = PDF::HTMLDoc.new
    pdf.set_option :bodycolor, :white
    pdf.set_option :toc, false
    pdf.set_option :portrait, true
    pdf.set_option :links, false
    pdf.set_option :webpage, true
    pdf.set_option :left, '2cm'
    pdf.set_option :right, '2cm'
    pdf.set_option :footer, "../"
    pdf.set_option :header, "..."
    pdf.set_option :bottom, '2cm'
    pdf.set_option :top, '2cm'
    pdf << data
    pdf.generate
  end

You'll find more documentation on HTMLDOC site that Travis Beale Linked to. Hope this helps get you on your way and unless your documents are really complicated it should suffice. Let us know how you get on.

您将在 Travis Beale 链接到的 HTMLDOC 站点上找到更多文档。希望这可以帮助您继续前进,除非您的文件非常复杂,否则就足够了。让我们知道您的身体情况如何。

回答by rip747

The closest thing I found as a "solution" to this is by using JRuby and then using The Flying Saucer Project. I just wish that it would get ported over to Ruby so it could be a native solution. God I wish I was better at Java.

我找到的最接近的“解决方案”是使用 JRuby,然后使用The Flying Saucer Project。我只是希望它可以移植到 Ruby 上,这样它就可以成为本机解决方案。上帝,我希望我在 Java 方面做得更好。

回答by mat

  • There is RPDFin which you describe your pdf's in as a view.
  • There also is RTEXwhich uses (La)TeX to generates pdf's.
  • RPDF,您可以在其中将 pdf 描述为视图。
  • 还有使用 (La)TeX 生成 pdf 的RTEX

回答by Thomas

The project may have stagnated, but Pisa (aka XHTML2PDF) is a Python lib which does CSS+HTML to PDF. used it in a (low-traffic) Rails app a while back by driving it as a commandline tool -- worked pretty well.

该项目可能停滞不前,但 Pisa(又名XHTML2PDF)是一个 Python 库,可将 CSS+HTML 转换为 PDF。不久前,通过将其作为命令行工具驱动,在(低流量)Rails 应用程序中使用了它——效果很好。

回答by Johnny

I would like to suggest you the HTML to PDF solution by https://grabz.it.

我想通过https://grabz.it向您推荐 HTML to PDF 解决方案。

They have a very flexible and simple-to-use screenshot API which can be used by any type of Ruby application.

它们具有非常灵活且易于使用的屏幕截图 API,可供任何类型的 Ruby 应用程序使用。

If you want to try it, at first you should get the authorization app key + secretand the development free SDK

如果你想尝试,首先你应该得到授权应用程序密钥+秘密开发免费的SDK

Then, in your app, the implementation steps would be:

然后,在您的应用程序中,实施步骤将是:

//initialization    
require 'grabzit'
grabzItClient = GrabzIt::Client.new("APPLICATION KEY", "APPLICATION SECRET")

//capturing the url to PDF
grabzItClient.url_to_pdf("http://www.google.com")   

Next is the saving. You can use one of the two save methods, saveif accessible callback handle available:

接下来是储蓄。save如果可访问的回调句柄可用,您可以使用两种保存方法之一:

grabzItClient.save("http://www.example.com/handler/index")  

And save_toif you need a synchronous save (which will force your application to wait while the screenshot is created):

save_to如果你需要一个同步保存(这将迫使你的应用程序等待创建截图):

filepath = "images/result.jpg"
grabzItClient.save_to(filepath) 

Check the documentation for detailsabout the saving.

有关保存的详细信息,请查看文档。

That's all. It's possible to get other kinds of screenshots such as image screenshotsas well.

就这样。也可以获取其他类型的屏幕截图,例如图像屏幕截图

回答by Kurt Pfeifle

HTMLDOC?

HTMLDOC?

  • converts HTML to PDF;
  • Free and Open Source (commercial support available);
  • can be used as...
    • ...standalone application,
    • ...for batch document processing,
    • ...or run as a web-based service;
  • interface is CLI or GUI.
  • 将 HTML 转换为 PDF;
  • 免费和开源(提供商业支持);
  • 可以用作...
    • ...独立应用程序,
    • ...用于批处理文档,
    • ...或作为基于 Web 的服务运行;
  • 界面是 CLI 或 GUI。