Generate PDF's with Prawn - ruby-on-rails

My objective is generate every month a PDF.
I am using Prawn Gem.
Likes this:
../Generatepdf/July2015.pdf
../Generatepdf/August2015.pdf
../Generatepdf/Setember2015.pdf
etc...
So my problem is how to define the urls?
I got a controller "Generatepdf" with a view "index.html"
I only can access of my PDF via:
../generatepdf/index.pdf
Controller:
class GeneratepdfController < ApplicationController
def index
respond_to do |format|
format.html
format.pdf do
pdf = ConsumptionsPdf.new
send_data pdf.render, filename: "lol2.pdf",
type: "application/pdf",
disposition: "inline"
end
end
end
end
Class:
class ConsumptionsPdf < Prawn::Document
def initialize
super
text "example"
end
end

Related

Rails 6 ActiveStorage Attach file url not working

I have an application where a user can upload a PDF document, when the pdf document is uploaded (with a front-end Stimulus controller using ActiveStorage DirectUpload), I then process the PDF to strip content out to place into an Excel Spreadsheet. Everything is uploaded to an s3 bucket.
My model looks like this:
class Export < ApplicationRecord
has_one_attached :pdf
has_one_attached :spreadsheet
validates :pdf, attached: true, content_type: 'application/pdf'
def process_pdf!
self.pdf.open(tmpdir: "#{Rails.root}/tmp") do |file|
tmpfile = File.open(file.path)
file_name = File.basename(file.path).sub(".pdf", "")
op = PdfScraper.call(pdf_file: tmpfile, output_name: file_name)
attach_spreadsheet(file_name: file_name)
end
end
private
def attach_spreadsheet(file_name:)
self.spreadsheet.attach(
io: File.open("#{Rails.root}/tmp/#{file_name}.xlsx"),
filename: "#{file_name}.xlsx",
identify: false,
content_type: "application/vnd.ms-excel"
)
end
end
The controller looks like this:
class ExportsController < ApplicationController
def create
#export = Export.new(export_params)
#export.uuid = cookies[:visitor_uuid]
respond_to do |format|
if #export.save
#export.process_pdf!
flash[:notice] = "Success!"
format.html { redirect_to download_path }
else
flash[:error] = #export.errors
format.html { redirect_to root_path }
end
end
end
private
def export_params
params.require(:export).permit(:pdf)
end
end
When the redirect happens back to the download_path, I am finding the Export based on the cookie ID but when I attempt to inspect (or view) the download URL for the attached spreadsheet, I am getting the following error:
undefined method `persisted?' for nil:NilClass
The View looks like:
<p>
<%= polymorphic_url(#export.spreadsheet) %>
</p>
I even tried the rails_blob_url(#export.spreadsheet) and it doesn't work. If I look up the URL via the rails console, it seems to work.

Rails - Dynamically generate PDF from HTML and show link to download

I have a rails application in which a user can click a link on a page and a little popup opens up with some HTML on it. I'd like to put another link next to it called 'Download as PDF' and when someone clicks this link, I'd like to dynamically generate a PDF from the HTML and allow the user to download the generated PDF onto their system. I've seen a few pages on stackoverflow which talk about using pdfkit to generate pdf from html but nothing about dynamically generating the pdf and then making it available to download. Please help!
The best way to do this is by using gem prawn
Here is youtube of how to upload it to your ruby on rails website https://www.youtube.com/watch?v=BW5zwqj37Lo&t=233s
https://github.com/prawnpdf/prawn
Here is example of how to add gem prawn
gem 'prawn', '~> 1.2.1'
gem 'prawn-table', '~> 0.1.0’
Mime::Type.register "application/pdf", :pdf
def index
#users = User.order("id DESC").all
respond_to do |format|
format.html
format.pdf do
pdf = Prawn::Document.new
pdf.text “hello
send_data pdf.render, filename: 'member.pdf', type: 'application/pdf', disposition: "inline"
end
end
end
<%= link_to 'PDF File', members_path(format: 'pdf') %>
def index
#users = User.order("id DESC").all
respond_to do |format|
format.html
format.pdf do
pdf = MemberPdf.new(#users)
send_data pdf.render, filename: 'member.pdf', type: 'application/pdf', disposition: "inline"
end
end
end
pdfs folder
member_pdf.rb
class MemberPdf < Prawn::Document
def initialize(users)
super(top_margin: 170)
#users=User.order("id DESC").all
user_id
end
def user_id
move_down 20
table user_id_row do
row(0).font_style = :bold
columns(1..3).align = :right
self.row_colors = ["DDDDDD","FFFFFF"]
self.header = true
end
end
def user_id_row
[["id","First","Middle","LastName","Email","Address","Address2","City","PostalCode","phone","Status","Child","Intrest"]] +
#users.map do |user|
[user.id,user.first_name,user.middle_name,user.last_name,user.email,user.street_address,user.street_address2,user.city,user.postal_code,user.phone_number,user.status,user.child,user.interest]
end
end
end

Rails Exporting CSV ignore blanks

I'm trying to create a simple CSV export in Rails. The export works fine except when deleting/archiving table items. I'm guessing this is because the export is encountering blanks.
This is working:
= link_to transactions_path(format: :csv) do
Except when there is a item missing from the transaction.
Tried this
= link_to transactions_path(format: :csv,skip_blanks: true) do
but I still get a ERR_INVALID_RESPONSE when calling the export
TransactionController:
respond_to :html, :json, :csv
def index
#shops = current_user.shops
respond_with(#shops) do |format|
format.csv do
response.headers['Content-Type'] = 'text/csv'
response.headers['Content-Disposition'] = "attachment; filename=transactions-#{Time.now.strftime('%Y%m%d%H%M')}.csv"
render inline: #shops.to_csv
end
end
end
Any suggestions?
Change to_csv to pass skip_blanks.
#shops.to_csv(skip_blanks: true)
If you want a link to download a CSV file, you should use send_data instead. If you want to display the file in the browser, use render text: #shops.to_csv
http://railscasts.com/episodes/362-exporting-csv-and-excel
respond_to :html, :json, :csv
def index
#shops = current_user.shops
respond_with(#shops) do |format|
format.csv do
send_data #shops.to_csv, type:'text/csv', filename: "transactions-#{Time.now.strftime('%Y%m%d%H%M')}.csv"
end
end
end
Change your link_to back to what you had before.
= link_to transactions_path(format: :csv)
Maybe using send_data:
def index
respond_to do |format|
format.csv { send_data #current_user.shops.to_csv, filename: "transactions-#{Time.now.strftime('%Y%m%d%H%M')}.csv" }
end
end
Also, is the to_csv an instance method?

Rails forcing the file name with send_data

I've a Clients controller:
class ClientsController < ApplicationController
def index
#clients = Client.all
respond_to do |format|
format.text do
file_name = "clients_emails.txt"
send_data #clients.pluck(:email).join('; '), file_name: file_name
end
end
end
end
There is a link in the application that points to this controller index action :
link_to "Extract Email List", clients_path(format: "text")
When I press the link the file is automatically downloaded but the name of the file is clients.text
It looks like :file_name option is being ignored.
Is there a way with send_data to force the browser to create a file with a given name?
Try it with filename:
send_data #clients.pluck(:email).join('; '), filename: file_name

Ruby on Rails respond_with and image formats

I have a controller that responds_to html and png ( I load the image dynamically and render it as text ). That makes the controller code messy and today I found respond_with, which looks very cool, but I can't found out how to make it work with formats, different than html, json and xml ( like the png )
I expected that this would work, but it stills tries to find a template file and ignores my method :(
models/user.rb
class User < ActiveRecord::Base
def to_png
File.read("some_file.png")
end
end
controllers/users_controller.rb
class UsersController < ApplicationController
respond_to :html, :png
# GET /users/1
def show
#user = User.find(params[:id])
respond_with(#user)
end
end
Try to add in file [YOUR_APP]/config/initializers/mime_types.rb:
Mime::Type.register "image/png", :png
and restart your application
if you need to use a MIME type which isn’t supported by default, you
can register your own handlers in environment.rb as follows.
Mime::Type.register "image/jpg", :jpg
http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to
in environment.rb
Mime::Type.register "image/png", :png
then
respond_to do |format|
format.png do
#do stuff here
end
end
or
respond_with #user do |format|
format.png do
#do stuff here
end
end

Resources