Wednesday 11 December 2019

Generate PDF with rake task



add these gems  in your gem file

gem 'wicked_pdf'
gem 'wkhtmltopdf-binary-edge', '~> 0.12.5.1'
gem "combine_pdf"

and run bundle

In views create directory pdf

create a partial file  _index.pdf.erb
<h1>Hello <%=  name %></h1>

in rake task write below-given code

    ac = ActionController::Base.new()
    header_html = ac.render_to_string(partial: 'pdf/_index.pdf.erb', locals: { name: 'Emissions Export'} )
    pdf = WickedPdf.new.pdf_from_string(header_html, orientation: 'Landscape', margin: { bottom: 20, top: 30 })

  save_path = Rails.root.join('public','mytest.pdf')
    File.open(save_path, 'wb') do |file|
      file << pdf
    end

------------------------------------------------------------------------
if you want to combine two pdf file in one pdf using below given code

pdf = WickedPdf.new.pdf_from_string(header_html, orientation: 'Landscape', margin: { bottom: 20, top: 30 })
    pdf1 = WickedPdf.new.pdf_from_string(header_html, orientation: 'Landscape', margin: { bottom: 20, top: 30 })
    #
    final_pdf = CombinePDF.new
    final_pdf << CombinePDF.parse(pdf)
    final_pdf << CombinePDF.parse(pdf1)

    save_path = Rails.root.join('public','mytest.pdf')
    File.open(save_path, 'wb') do |file|
      file << final_pdf.to_pdf
    end




No comments:

Post a Comment

Revert last commit or second last and more....

 Git revert commit_id -m 1 this command willl revert last commit  Git revert commit_id -m 2 this command will revert second commit with same...