I have a file which returns a pdf attachment as an output. I am using wicked pdf to generate this pdf.
def generate_pdf
render pdf: "#{#user.name}",
template: 'api/v1/doctors/get_report_4.html.erb',
:page_size => 'Letter',
layout: false, disposition: 'attachment',
:margin => {bottom: #margin_bottom, top: #margin_top, left: #margin_left, right: #margin_right},
wkhtmltopdf: %x(bundle exec which wkhtmltopdf).to_s.strip.presence || %x(which wkhtmltopdf).to_s.strip}
end
But while calling this API. I am getting the attachment with name "response.pdf" instead of username.pdf. Please help me with this.
Related
In rails 4, I am using wicked_pdf gem for .pdf file download. I have to add an image inside this pdf, right now image is rendering through wicked_pdf_image_tag in development but in test environment image(s3) is not rendering.
Used Gems are,
gem 'wicked_pdf', '1.0.3'
gem 'wkhtmltopdf-binary', '0.9.9.3'
In initializers,
class WickedPdf
wkhtmltopdf_path = Rails.env.production? ? "#{Rails.root}/bin/wkhtmltopdf-amd64" : "#{Rails.root}/bin/wkhtmltopdf-amd64"
WICKED_PDF = {
:exe_path => wkhtmltopdf_path,
:wkhtmltopdf => wkhtmltopdf_path
}
end
In controller,
respond_to do |format|
format.html {
render :pdf => "sample",
:margin => {:top => 10, :bottom => 10, :left => 10, :right => 10},
:orientation => 'Portrait', # default , Landscape,
:no_background => true
}
end
In views, I have tried to load through
<%= Rails.env.development? ? wicked_pdf_image_tag("img/logo.png") : wicked_pdf_image_tag("#{Rails.root}/public/assets/img/logo.png") %>
<%= Rails.env.development? ? wicked_pdf_image_tag("img/logo.png") : wicked_pdf_image_tag("#{Rails.root}/assets/img/logo.png") %>
<%= image_tag(ActionController::Base.helpers.asset_path('img/logo.png')) %>
How can I load s3 image in pdf file?
You can put the image in a s3 bucket and make it public. After that try it like below. If you use the below code no need to use separate syntax for different environments, it will works for all .Hope it works.
<%= wicked_pdf_image_tag('//s3.amazonaws.com/bucket_name/image.png') %>
I have worked on the similar functionality but using PDFKit gem. But I think rendering logic will be almost similar.
Below is the code where I rendered my partial in controller
def print_batch
batch = Batch.find(params[:id])
respond_to do |format|
format.pdf {
html = render_to_string("_batch",:formats => [:html], layout: false , locals: { batch: batch })
Rails.logger.debug(html.inspect)
kit = PDFKit.new(html)
send_data(kit.to_pdf, :filename => "file_name_#{batch.id}.pdf", :type => 'application/pdf') and return
}
format.html
format.json { render json: {id: batch.id, processed: batch.processed?} }
end
end
In _batch.html.haml. You can see I have used person.s3_logo for rendering the pdf image.
- logo_image_pdf = person.logo.present? ? person.s3_logo : default_credit_logo
- logo_image_html = person.logo.present? ? image_path(Person.logo.thumb('100x100').url) : image_path('default_credit_logo.png')
- logo_image = params[:format] == 'pdf' ? logo_image_pdf : logo_image_html
.bucks
%img.logo{src: logo_image }
In Person.rb model. Anyway we cannot directly render image in PDF file directly from s3. So any gem will first download it in /tmp folder and render it. This is how I have done it in my model file.
def s3_logo
file = open(self.logo.remote_url)
file.path if file
end
I have a Rails 3 app that uses these gems:
gem 'paperclip'
gem 'wicked_pdf'
gem 'combine_pdf'
I'm using wicked_pdf to open a pdf for a costproject. The costproject has an HTML page called viewproject.pdf.erb.
I'm trying to combine the wicked pdf with the costproject attachments into a single pdf.
This is my controller code:
def viewproject
#costproject = Costproject.find(params[:costproject_id])
respond_to do |format|
format.html
format.pdf do
pdf = CombinePDF.new
pdf2 = render_to_string pdf: "Costproject.pdf", template: "costprojects/viewproject", encoding: "UTF-8"
pdf << CombinePDF.new(pdf2)
#costproject.attachments.each do |attachment|
pdf << CombinePDF.new(attachment.attach.path)
end
send_data pdf.to_pdf, :disposition => 'inline', :type => "application/pdf"
end
end
end
The line pdf << CombinePDF.new(pdf2) is giving me:
string contains null byte
If I look at pdf2, it starts like this - so it looks like a pdf:
>> pdf2
=> "%PDF-1.4\n1 0 obj\n<<\n/Title (\xFE\xFF)\n/Producer (wkhtmltopdf)\n/CreationDate (D:20150405202628)\n>>\nendobj\n4 0 obj\n<<\n/Type /ExtGState\n/SA true\n/SM 0.02\n/ca 1.0\n/CA 1.0\n/AIS false\n/SMask /None>>\nendobj\n5 0 obj\n[/Pattern /DeviceRGB]\nendobj\n8 0 obj\n<<\n/Type /XObject\n/Subtype /Image\n/Width 71\n/Height 75\n/BitsPerComponent 8\n/ColorSpace /DeviceRGB\n/Length 9 0 R\n/Filter
I also tried pdf << CombinePDF.new(pdf2.to_pdf)
Thanks for the help!
UPDATE1
As a test, to see if pdf2 is working, I did this successfully:
def viewproject
#costproject = Costproject.find(params[:costproject_id])
respond_to do |format|
format.html
format.pdf do
pdf2 = render_to_string pdf: "Costproject.pdf", template: "costprojects/viewproject", encoding: "UTF-8"
send_data pdf2, :disposition => 'inline', :type => "application/pdf"
end
end
end
UPDATE2
Myst was correct about using parse. Thanks!
I am now using this line in the controller code:
pdf << CombinePDF.new(attachment.attach.url)
I get this error:
No such file or directory - http://s3.amazonaws.com/ ...
But, if I copy the http address and paste into the browser the pdf shows up.
I am editing this answer to reflect the issue of remotely stored PDF files.
I should point out that without a persistent connection to the S3 storage and without using the S3 API, the following solution WILL effect performance*.
As I pointed out, the CombinePDF.new method is the same as the CombinePDF.load method. It accepts a file name and attempts to open the file. The CombinePDF.parse method will accept raw PDF data and parses it into a PDF Object.
In the following code I use Net::HTTP.get(URI.parse(url)) to get the raw PDF data.
I recommend replacing this solution with a S3 native solution, so that the whole application can share one or more persistent connections. This is a performance issue that may or may not be important for you.
require 'net/http'
def viewproject
#costproject = Costproject.find(params[:costproject_id])
respond_to do |format|
format.html
format.pdf do
pdf = CombinePDF.new
pdf2 = render_to_string pdf: "Costproject.pdf", template: "costprojects/viewproject", encoding: "UTF-8"
pdf << CombinePDF.parse(pdf2)
#costproject.attachments.each do |attachment|
pdf << CombinePDF.parse( Net::HTTP.get( URI.parse( attachment.attach.url ) ) )
end
send_data pdf.to_pdf, :disposition => 'inline', :type => "application/pdf"
end
end
end
* The performance hit is dependent on the amount of PDF attachments you have, on the number of users your app has, on network traffic, on your framework (single/multi-thread) and other factors.
A persistent connection should reduce the performance hit in a dramatic way, mainly due to the fact that establishing connections is an expensive action.
Cheers! I'm using wicked_pdf to generate pdf docs from views:
pdf = WickedPdf.new.pdf_from_string(
render_to_string(
:layout => "pdf_report.haml",
:handlers => [:haml],
:formats => [:pdf, :haml],
:orientation => 'Landscape',
:encoding => "utf8",
:page_width => '2000',
:dpi => '300'
)
)
It's all ok, if pdf has one page:
But if pdf doc has more than one page, then width of the page is broken:
I wasn't able to reproduce your "only has one page" scenario with the code you posted, however there is a problem with the options you are passing. They aren't even getting to wkhtmltopdf, so it is probably deciding for you what kind of options to use.
render_to_string will silently discard any options it doesn't understand, but is not part of wicked_pdf.
pdf_from_string takes two params, the first being the string to pdf-ify, the second is a hash of pdf options from the README.
I've added your issue to the wicked_pdf_issues project here to reproduce and debug it:
https://github.com/unixmonkey/wicked_pdf_issues/commit/b722e8a06c42e1f2bcbb98281915d1e94b4fe2c9
You should get the results you are looking for by changing your code to something like this:
string = render_to_string(
template: 'pages/issue_330',
formats: [:pdf],
handlers: [:erb]
)
options = {
orientation: 'Landscape',
page_width: '2000',
dpi: '300'
}
pdf = WickedPdf.new.pdf_from_string(string, options)
Rails 4
*Mac OSX 10.8.4*
I'm using the following Gem for wicked_pdf pdf generation:
gem 'wkhtmltopdf-binary'
gem 'wicked_pdf'
Rendering Views as pdfs works fine and Google displays it's PDF viewer correctly. My PDFs look exactly how I want them to.
The problem arises when I try to save a pdf to disc, for the purpose of emailing them to a user.
For example, this works fine:
def command
#event = Event.find(params[:id])
#client = Contact.find(#event.client_id)
#organizer = Contact.find(#event.organizer_id)
render layout: 'command',
pdf: 'Event Command',
show_as_html: params[:debug].present?,
dpi: 300,
print_media_type: true,
margin: {
top: 0,
bottom: 0,
left: 0,
right: 0
}
end
That will render the pdf in the Google Chrome PDF viewer.
But here, is where I want to generate a PDF and save to file.
def send_email
#event = Event.find(params[:id])
#client = Contact.find(#event.client_id)
#organizer = Contact.find(#event.organizer_id)
proforma = render_to_string(
pdf: 'proforma.pdf',
template: 'events/proforma',
layout: 'proforma'
)
pdf = WickedPdf.new.pdf_from_string(
proforma
)
save_path = Rails.root.join('public','proforma.pdf')
File.open(save_path, 'wb') do |file|
file << pdf
end
end
But I'm getting the error:
Failed to execute:
Error: "\xFE" from ASCII-8BIT to UTF-8
Try this:
File.open(save_path, 'w:ASCII-8BIT') do |file|
file << pdf
end
The PDF rendered as a string in memory seems to be in ASCII, so save it as such :)
Right Now i am using Rails 3.0.0.i already installed the gem wicked_pdf.Now to want to save the pdf file inside the public folder.please help me.
If you need to just create a pdf and not display it:
# create a pdf from a string
pdf = WickedPdf.new.pdf_from_string('<h1>Hello There!</h1>')
# create a pdf from string using templates, layouts and content option for header or footer
WickedPdf.new.pdf_from_string(
render_to_string(:pdf => "pdf_file.pdf", :template => 'templates/pdf.html.erb', :layout => 'pdfs/layout_pdf'),
:footer => {:content => render_to_string({:template => 'templates/pdf_footer.html.erb', :layout => 'pdfs/layout_pdf'})}
# or from your controller, using views & templates and all wicked_pdf options as normal
pdf = render_to_string :pdf => "some_file_name"
# then save to a file
save_path = Rails.root.join('pdfs','filename.pdf')
File.open(save_path, 'wb') do |file|
file << pdf
end
This is top answer on How to convert string in pdf in ruby on rails
And if you aren't against i put one of the answer:
Some services returns pdf as a string like: JVBERi0xLjQKJeLjz9MKNCAwIG9iago8PC9Ue. . .
You can create a pdf file from the sting, with:
f = File.new("/tmp/file.pdf", "w")
f.write(Base64.decode64(invoice[:file]).force_encoding('UTF-8'))
f.close
And then you can open pdf file with AcrobatReader or another pdf reader.
Wish it helps.
Also, you can do this:
render :pdf => 'foo',
:save_to_file => Rails.root.join('public', "foo.pdf"),
:save_only => true