Problem with generate pdf and display images - ruby-on-rails

I have a problem with displaying the images in pdf. 5 out of 100 attempts work. After saving all data to database, there is opened a new site with pdf generated by gem wkhtmltopdf. During getting the image from path /rails/active_storage/blobs/... service is stopped and report isn't generated. There are no errors on consoles .Only solution is stopped the server ( ctrl+c ) and start again the server.
The server is stopped on request :
Started GET "/rails/active_storage/blobs/...
I display image by line :
<%= image_tag(#object.image, class: '') if #object.image.attached? %>
There is a method for generate report (above this code there are the varialbes to display in report )
respond_to do |format|
format.html do
redirect_to index
end
format.pdf do
render pdf: "Raport",
template: "myFolder/report.html.erb",
:footer => {
:font_size => '8'
}
end
end
I'm using rails 5.2.3, ruby 2.5.3
I'm expect to generate the pdf with images.

Related

Rails - Ruby process sleep when open a file URL and not able to end or kill it

I am trying to open a image URL from Activestorage but ruby falls asleep and the last item in console log is:
Started GET "/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBCdz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--bfec3dc0d0745e49d7daa9faac7abdeaa46418c3/f2392748480.png" for 127.0.0.1 at 2018-12-02 14:45:01 -0600
and when it ends the error is: Net::ReadTimeout
This doesn't happened the first time, but after that it happen each time i run the method.
My method:
def upload_photos
require 'open-uri'
page_api = Koala::Facebook::API.new(params[:access_token])
image_urls = params[:images].map do |image|
open("#{request.protocol}#{request.host_with_port}#{image[:url]}") do |f|
page_api.put_picture(f, f.content_type, { "caption" => image[:filename] }, params[:id])
end
end
render json: { image_urls: image_urls, album_id: params }
end
It works the first time but not after that.
UPDATE: this works fine with external URLs but not with activestorage
This is due to Ruby is busy opening the file and when tries to reach the URL is not able to respond to that petition because is opening the file, is like trying to watch your own backhead in a mirror.

wickedpdf not rendering images?

i am using wickedpdf gem to generate pdf invoice from the html code.
gems:
gem 'wicked_pdf'
gem "wkhtmltopdf-binary"
gemfile.lock
wicked_pdf (1.0.6)
wkhtmltopdf-binary (0.9.9.3)
in controller:
def show_pdf_invoice
respond_to do |format|
format.html { render :layout => "pdf.pdf.erb" }
format.pdf do
render pdf: "show_pdf_invoice", :layout => 'pdf.pdf.erb'
#render :pdf => "pdf"#, :layout => 'pdf.html.erb'
end
end
end
in views/invoices/show_pdf_invoice.pdf.erb
<img id="image" src="https://www.google.co.in/logos/doodles/2016/holidays-2016-day-2-6356741311692800-scta.png" alt="logo" />
<%= wicked_pdf_image_tag 'https://www.google.co.in/logos/doodles/2016/holidays-2016-day-2-6356741311692800-scta.png' %>
pdf is getting generated. But the images are not showing. in the place of images empty boxes are coming. unable to find the issue.
I've had the same problem, mine was fixed by removing https for http. Have you tried this? and for the Amazon S3 part: You could use gsub for that as in: gsub("https", "http")
Using Rails 5.2 with Active Storage in combination with Amazon S3 storage I had the same problem.
In development on my local machine the images rendered perfectly, but on Heroku
they were presented as small empty rectangles.
To get the url from the logo uploaded to Active Storage I used: #my_object.logo.service_url.
Which used the standard url with https. As mentioned before, replacing this with http resolved the issue.
Full code used in my pdf generator view:
<%= wicked_pdf_image_tag #my_object.logo.service_url.gsub("https", "http") %>
Two Options
1. Upgrade to wkhtmltopdf 0.12.5.
-or-
2. Install libssl1.0-dev with apt-get install libssl1.0-dev.
See this issue for more information: https://github.com/wkhtmltopdf/wkhtmltopdf/issues/3001

Wicked pdf gem not creating correct data in pdf on rails production server

I am using Wicked pdf gem for creating pdf. It is absolutely working fine on my local. But on production it is giving serious issues. The pdf is generated but in spite of generating a single page it generates 14-15 pages with data like this:
")),this.$.write(e),this.$.close()},find:function(e){return new CKEDITOR.dom.nodeList(this.$.querySelectorAll(e))},findOne:function(e){return(e=this.$.querySelector(e))?new CKEDITOR.dom.element(e):null},_getHtml5ShivFrag:function(){var e=this.getCustomData("html5ShivFrag");return e||
(e=this.$.createDocumentFragment(),CKEDITOR.tools.enableHtml5Elements(e,!0),this.setCustomData("html5ShivFrag",e)),e}}),CKEDITOR.dom.nodeList=function(e){this.$=e},CKEDITOR.dom.nodeList.prototype={count:function(){return this.$.length},getItem:function(e){return
0>e||e>=this.$.length?null:(e=this.$[e])?new CKEDITOR.dom.node(e):null}},CKEDITOR.dom.element=function(e,t){"string"==typeof e&&(e=(t?t.$:document).createElement(e)),CKEDITOR.dom.domObject.call(this,e)},CKEDITOR.dom.element.get=function(e){return(e="string"==typeof e?
document.getElementById(e)||document.getElementsByName(e)[0]:e)&&(e.$?e:new CKEDITOR.dom.element(e))},CKEDITOR.dom.element.prototype=new CKEDITOR.dom.node,CKEDITOR.dom.element.createFromHtml=function(e,t){var n=new CKEDITOR.dom.element("div",t);return
n.setHtml(e),n.getFirst().remove()},CKEDITOR.dom.element.setMarker=function(e,t,n,i){var
r=t.getCustomData("list_marker_id")||t.setCustomData("list_marker_id",CKEDITOR.tools.getNextNumber()).getCustomData("list_marker_id"),o=t.getCustomData("list_marker_names")||t.setCustomData("list_marker_names",{}).getCustomData("list_marker_names");return
e[r]=t,o[n]=1,t.setCustomData(n,i)},CKEDITOR.dom.element.clearAllMarkers=function(e){for(var t in e)CKEDITOR.dom.element.clearMarkers(e,e[t],1)},CKEDITOR.dom.element.clearMarkers=function(e,t,n){var
i,r=t.getCustomData("list_marker_names"),o=t.getCustomData("list_marker_id");for(i in r)t.removeCustomData(i);t.removeCustomData("list_marker_names"),n&&(t.removeCustomData("list_marker_id"),delete e[o])},function(){function e(e,t){return-1<(" "+e+" ").replace(o," ").indexOf(" "+t+"
")}function t(e){var t=!0;return e.$.id||(e.$.id="cke_tmp_"+CKEDITOR.tools.getNextNumber(),t=!1),function(){t||e.removeAttribute("id")}}function n(e,t){var n=CKEDITOR.tools.escapeCss(e.$.id);return"#"+n+" "+t.split(/,\s*/).join(", #"+n+" ")}function i(e){for(var
t=0,n=0,i=a[e].length;i>n;n++)t+=parseInt(this.getComputedStyle(a[e][n])||0,10)||0;return t}var r=document.createElement("_").classList,r="undefined"!=typeof r&&null!==String(r.add).match(/[Native code]/gi),o=/[\n\t\r]/g;CKEDITOR.tools.extend(CKEDITOR.dom.element.prototype,
{type:CKEDITOR.NODE_ELEMENT,addClass:r?function(e){return this.$.classList.add(e),this}:function(t){var n=this.$.className;return n&&(e(n,t)||(n+=" "+t)),this.$.className=n||t,this},removeClass:r?function(e){var t=this.$;retur
The entire 14-15 pages are like this.
This is the method that creates pdf.
def generate_supplier_commission_pdf
#start_date = params[:start_date].to_date.strftime('%d/%m/%Y')
#end_date = params[:end_date].to_date.strftime('%d/%m/%Y')
if params[:sec_filter].present?
sec_filter = true
else
sec_filter = false
end
results = get_report_results_by_type(params[:report_type], #start_date, #end_date, sec_filter)
#results = JSON.parse(results)
#type = params[:report_type].to_i
respond_to do |format|
format.html
format.pdf do
render pdf: "report",
layout: 'pdf_layout',
template: 'reports/generate_supplier_commission_pdf.html.erb',
encoding: 'UTF8',
print_media_type: true,
disposition: 'attachment',
page_size: 'letter',
orientation: 'landscape',
lowquality: 'false',
debug: true
end
end
end
Each and everything like the wkhtml path or anything that can be taken of care of in the code is fine. The only difference I saw is in the logs i.e after this line
***************WICKED***************
Rendered reports/generate_supplier_commission_pdf.html.erb within layouts/pdf_layout (5.2ms)
The following line is not present on server logs.
"***************[\"/usr/bin/wkhtmltopdf\", \"-q\", \"--orientation\", \"landscape\", \"--page-size\", \"letter\", \"--encoding\", \"UTF8\", \"--lowquality\", \"--print-media-type\", \"file:///tmp/wicked_pdf20160903-24256-1v1ay70.html\", \"/tmp/wicked_pdf_generated_file20160903-24256-1da8k68.pdf\"]***************"
I will be really grateful if someone could point out what is going wrong in this case. Thanks in advance.
I managed to resolve this issue by commenting this line in my config/environments/production.rb
# config.assets.js_compressor = :uglifier
and adding this line in it's place:
config.assets.compress = true

Rails 3 Wicked PDF - include Paperclip S3 pdf files

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.

IMGKit returning corrupted image

I have the following code in Rails 3 application's controller:
respond_to do |format|
format.html
format.jpeg do
image = IMGKit.new("http://www.google.com").to_img(:jpg)
send_data(image, type: "image/jpeg", filename: "data.jpeg", disposition: "inline")
end
end
I expect that when I ask for a jpeg I get back a jpeg of the Google home page. However, I get back an image that looks like this. What am I doing wrong?
I'm on Windows 7, and the wkhtmltoimage command works fine from the command line. I have ruby verion ruby 1.9.3p125 (2012-02-16) [i386-mingw32].

Resources