Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Convert HTML to PDF? [closed]

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

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.

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.

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.

like image 938
rip747 Avatar asked Dec 10 '08 19:12

rip747


4 Answers

The gem, WickedPDF, does exactly that.

like image 99
Sebastian Avatar answered Nov 12 '22 10:11

Sebastian


The greatest thing nowaday is PDFKit for this job:

  • https://github.com/pdfkit/PDFKit
  • http://railscasts.com/episodes/220-pdfkit
like image 30
fl00r Avatar answered Nov 12 '22 09:11

fl00r


Try WickedPDF, PDF generator (from HTML) plugin.

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):

    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

= 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)

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"))
like image 13
Sajjad Murtaza Avatar answered Nov 12 '22 09:11

Sajjad Murtaza


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

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

like image 4
Michael Avatar answered Nov 12 '22 10:11

Michael