Skip to content

Instantly share code, notes, and snippets.

@secretpray
Last active October 28, 2024 09:31
Show Gist options
  • Save secretpray/64ec770182596bd1b5509d9343162fa1 to your computer and use it in GitHub Desktop.
Save secretpray/64ec770182596bd1b5509d9343162fa1 to your computer and use it in GitHub Desktop.
Export html page to PDF (Rails 6, Heroku)
----- Model: Recipe -----
1)
Gemfile
==========
gem 'grover' (https://github.com/Studiosity/grover)
Terminal
============
yarn add puppeteer
2) routes
==========
resources :recipes do
member do
get "to_pdf", to: "recipes#to_pdf"
end
end
3) RecipesController
====================
def to_pdf
if params[:format] == 'pdf' # Избыточно (redundantly)
url = request.url.remove("/to_pdf.pdf")
pdf = Grover.new(url, format: 'A3', emulate_media: 'screen', landscape: true ).to_pdf
Tempfile.create do |tmp|
tmp.binmode
tmp.write(pdf)
tmp.rewind
tmp.close
send_data(
File.open(tmp.path, 'rb').read,
type: 'application/pdf',
filename: "test.pdf",
disposition: 'inline'
)
end
end
end
4) recires#show
===============
<%= link_to "Export as PDF", to_pdf_recipe_path(@recipe, format: :pdf), target: '_blank', title: 'Click to Export as PDF', class: 'ms-2' %>
or
<%= link_to to_pdf_recipe_path(@recipe, format: :pdf), target: '_blank', title: 'Click to Export as PDF', class: 'ms-2' do %>
<%= image_tag("pdf.png", size: "32x32", alt: "Export as PDF", class: 'export-pdf') %>
<% end %>
2Run on Heroku!
=============
heroku buildpacks:add heroku/nodejs --index=1
heroku buildpacks:add jontewks/puppeteer --index=2
heroku config:set GROVER_NO_SANDBOX=true
PS work in console:
url = 'http://localhost:3000/recipes/ultimate-falafel-wrap?lang=ru'
pdf = Grover.new(url, format: 'A4', emulate_media: 'screen', landscape: true ).to_pdf
File.open(Rails.root.join('tmp/github-fronpage.pdf'), 'wb') { |f| f.write(pdf)}
------ Open file in folder tmp --------
@yshmarov
Copy link

interesting

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment