Assets, rmagick and rails - ruby-on-rails

I am working on developing an app that will generate a digital card from the user. At the moment I am working on the rmagick code in a .rb file. Then just running it from the command line untill I figure it all out. I am having a few problems.
The source image I can't figure out the path to it. the only way I can get it to work is if I place it in the controllers directory with the cards.rb file. I want to have it in assets/cards/
Saving the file, same issue as above. I want to save it in assets/cards/#card_id.png
I'm trying to use a custom font in the assets/fonts/ dir I've tried self.font = “#{RAILS_ROOT}/assets/fonts/dreamorphansbd.ttf” but the code will not run. If I remove the quotes it runs but the font is not correct.
The last thing and I have yet to try it is adding the caption as the card.event from the db. I'm think it will along those line but not sure.
require 'RMagick'
include Magick
blank = Magick::Image.read("Blank-Card.png").first
text = Image.read("caption:Some big long text would go here.") do
self.gravity = CenterGravity
self.font = #{RAILS_ROOT}/app/assets/fonts/dreamorphansbd.ttf
self.background_color= "Transparent"
self.size = "638x"
self.pointsize = 40
end
blank.composite!(text[0], CenterGravity, Magick::OverCompositeOp)
blank.write("card.png")

try: Magick::Image.read(Rails.root.join('image', 'Blank-Card.png')).first
try: blank.write(Rails.root.join('image', 'card.png'))
With: Magick.fonts, you will see all available fonts
try: Image.read("caption:#{obj_active_record.your_attribute}")

Related

Ruby on Rails - How to convert to images some elements from a word document

Context
In our platform we allow users to upload word documents, those documents are stored in google drive and then dowloaded again to our platform in HTML format to create a section where the users can interact with that content.
Rails 5.0.7
Ruby 2.5.7p206
selenium-webdriver 3.142.7 (latest stable version compatible with our ruby and rails versions)
Problem
Some of the documents have charts or graphics inside that are not processed correctly giving wrong results after all the process.
We have been trying to fix this problem at the moment we get the word document and before to send it to google drive.
I'm looking for a simple way to export the entire chart and/or table as an image, if anyone knows of a way to do this the advice would be much appreciated.
Edit 1: Adding some screenshots:
This screenshot is from the original word doc:
And this is how it looks in our systems:
Here are the approaches I have tried that haven't worked for me so far.
Approach 1
Using nokogiri to read the document and found the nodes that contain the charts (we've found that they are called drawing) and then use Selenium to navigate through the file and take and screenshot of that particular section.
The problem we found with this approach is that the versions our gems are not compatible with the latest versions of selenium and its web drivers (chrome or firefox) and it is not posible to perform this action.
Other problem, and it seems is due to security, is that selenium is not able to browse inside local files and open it.
options = Selenium::WebDriver::Firefox::Options.new(binary: '/usr/bin/firefox', headless: true)
driver = Selenium::WebDriver.for :firefox, options: options
path = "#{Rails.root}/doc_file.docx"
driver.navigate.to("file://#{path}")
# Here occurs the first issue, it is not able to navigate to the file
puts "Title: #{driver.title}"
puts "URL: #{driver.current_url}"
# Below is the code that I am trying to use to replace the images with the modified images
drawing_elements = driver.find_elements(:css, 'w|drawing')
modified_paragraphs = []
drawing_elements.each do |drawing_element|
paragraph_element = drawing_element.find_element(:xpath, '..')
paragraph_element.screenshot.save('paragraph.png')
modified_paragraph = File.read('paragraph.png')
modified_paragraphs << modified_paragraph
end
driver.quit
file = File.open(File.join(Rails.root, 'doc_file.docx'))
doc = Nokogiri::XML(file)
drawing_elements = doc.css('w|drawing')
drawing_elements.each_with_index do |drawing_element, i|
paragraph_element = drawing_element.parent
paragraph_element.replace(modified_paragraphs[i])
end
new_doc_file = File.write('modified_doc.docx', doc.to_xml)
s3_client.put_object(bucket: bucket, key: #document_path, body: new_doc_file)
File.delete('doc_file.docx')
Approach 2
Using nokogiri to get the drawing elements and the try to convert it directly to an image using rmagick or mini_magick.
It is only possible if the drawing element actually contains an image, it can convert that correctly to an image, but the problem is when inside of the drawing element are not images but other elements like graphicData, pic, blipFill, blip. It needs to start looping into the element and rebuilding it, but at that point of time it seems that the element is malformed and it can't rebuild it.
Other issue with this approach is when it founds elements that seem to conform an svg file, it also needs to loop into all the elements and try to rebuild it, but the same as the above issue, it seems that the element is malformed.
response = s3_client.get_object(bucket: bucket, key: #document_path)
docx = response.body.read
Zip::File.open_buffer(docx) do |zip|
doc = zip.find_entry("word/document.xml")
doc_xml = doc.get_input_stream.read
doc = Nokogiri::XML(doc_xml)
drawing_elements = doc.xpath("//w:drawing")
drawing_elements.each do |drawing_element|
node = get_chil_by_name(drawing_element, "graphic")
if node.xpath("//a:graphicData/a:pic/a:blipFill/a:blip").any?
img_data = node.xpath("//a:graphicData/a:pic/a:blipFill/a:blip").first.attributes["r:embed"].value
img = Magick::Image.from_blob(img_data).first
img.write("node.jpeg")
node.replace("<img src='#{img.to_blob}'/>")
elsif node.xpath("//a:graphicData/a:svg").any?
svg_data = node.xpath("//a:graphicData/a:svg").to_s
Prawn::Document.generate("node.pdf") do |pdf|
pdf.svg svg_data, at: [0, pdf.cursor], width: pdf.bounds.width
end
else
puts "unsupported format"
end
end
# update the file in S3
s3.put_object(bucket: bucket, key: #document_path, body: doc)
end
Approach 3
Convert the elements since its parents to a pdf file and then to an image.
Basically the same issue as in the approach 2, it needs to loop inside all the elements and try to rebuild it, we haven't found a way to do that.

Rails: Received string from web service should be converted to a pdf image to be displayed

When using a web service I receive a string that looks like this:
JVBERi0xLjIgDQoxIDAgb2JqDQo8PA0KL1R5cGUgL0NhdGFsb2cNCi9QYWdlcyAzIDAgUg0KL1BhZ2VNb2RlIC9Vc2VOb25lDQovUGFnZUxheW91dCAvU2luZ2xlUGFnZQ0KPj4NCmVuZG9iag0KMiAwIG9iag0KPDwNCi9Qcm9kdWNlciAoUGRmQ3JlYXRvciB2ZXJzaW9uIDEuMCkNCi9BdXRob3IgKCkNCi9DcmVhdGlvbkRhdGUgKEQ6MjAxNzA4MjUxMTM0MDApDQovQ3JlYXRvciAoKQ0KL0tleXdvcmRzICgpDQovU3ViamVjdCAoKQ0KL1RpdGxlICgpDQovTW9kRGF0ZSAoRDoyMDE3MDgyNTExMzQwMCkNCj4+DQplbmRvYmoNCjMgMCBvYmoNCjw8DQovVHlwZSAvUGFnZXMNCi9LaWRzIFs0IDAgUiBdDQovQ291bnQgMQ0KPj4NCmVuZG9iag0KNCAwIG9iag0KPDwNCi9UeXBlIC9QYWdlDQovUGFyZW50IDMgMCBSDQovTWVkaWFCb3ggWzAgMCA0MjUgMjkyIF0NCi9SZXNvdXJjZXMgPDwNCi9Gb250IDw8DQovRjAgNiAwIFINCi9GMSA4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IgNzIyIDcyMiA2NjcgNjY3IDYxMSA1NTYgNTU2IDU1NiA1NTYgNTU2IDU1NiA4ODkgNTU2IDU1NiA1NTYgNTU2IDU1NiAyNzggMjc4IDI3OCAyNzggNjExIDYxMSA2MTEgNjExIDYxMSA2MTEgNjExIDU4NCA2MTEgNjExIDYxMSA2MTEgNjExIDU1NiA2MTEgNTU2IF0NCi9OYW1lIC9GMQ0KPj4NCmVuZG9iag0KeHJlZg0KMCA5DQowMDAwMDAwMDAwIDY1NTM1IGYNCjAwMDAwMDAwMTEgMDAwMDAgbg0KMDAwMDAwMDExMSAwMDAwMCBuDQowMDAwMDAwMjk4IDAwMDAwIG4NCjAwMDAwMDAzNjMgMDAwMDAgbg0KMDAwMDAwMDU3MyAwMDAwMCBuDQowMDAwMDAxMDc0IDAwMDAwIG4NCjAwMDAwMDMwMDcgMDAwMDAgbg0KMDAwMDAwNDk1MSAwMDAwMCBuDQp0cmFpbGVyDQo8PA0KL1NpemUgOQ0KL1Jvb3QgMSAwIFINCi9JbmZvIDIgMCBSDQo+Pg0Kc3RhcnR4cmVmDQo2ODg4DQolJUVPRg0K
Sorry for that.
Anyway, this should be a pdf because that was one of the request parameters. (I could also have chosen for .gif, or .jpg in different qualities.)
I tried reading the content, like this:
#label_binary = #response_label[:generate_label_response][:response_shipments][:response_shipment][:labels][:label][:content]
binary_data = Base64.decode64(#label_binary)
#label = File.open('file_name.pdf', 'wb') {|f| f.write(Base64.decode64(binary_data))}
But what this prints then as #label is just a number (three of four digits). Same when I use urlsafe_decode64.
Not very helpful.
Preferred end-result would be a pdf image file that I can immediately display (in this case a barcode on top of an invoice for sending a package).
Could I for this purpose save the file temporarily? Meaning: every time I need to display I rebuild this image. I think that would be best.
EDIT
I am making the call now directly to a 600dpi .jpg image and then:
base_64_binary_data = #response_label[:generate_label_response][:response_shipments][:response_shipment][:labels][:label][:content]
#jpg_file = File.open('label.jpg', 'wb') do |file|
content = Base64.decode64 base_64_binary_data
file << content
end
This file shows up at my_apps_name/label.jpg.
In my filesystem I can see the picture crystal clear.
In my view I then put:
<%= image_tag #jpg_file.path %>
When I inspect my html in the browser I see:
<img src="/images/label.jpg" alt="Label">
I suppose this is easily fixed, suggestions are still welcome of course, but...
..more importantly: What if this call is made several times at once. Will rails manage? Should I maybe save these images (to my S3) or build some kind of chronejob to manage it?
(I am not sure of the added value of mini_magic anymore, since I can see the .jpg being already there.)
Then on a complete side note, maybe better left for a separate question: what if the API on the other side fails?
Step one
decode http response
require "base64"
BASE_64_BINARY_DATA = "PASTE YOUR BIG STRING HERE"
pdf_file = File.open('your_pdf.pdf', 'wb') do |file|
content = Base64.decode64 BASE_64_BINARY_DATA
file << content
end
Step two
convert pdf file to an image
add to gemfile 'gem 'mini_magick' and use 'bundle install' command
put somewhere in your code
require 'mini_magick'
pdf = MiniMagick::Image.new(pdf_file.path)
pdf.pages.first.write("preview.png")
image saved as preview.png
To display pdf image put in the view
<%= image_tag ("path_to_image/preview.jpg")%>

Ruby, RSVG and PNG streams

I'm trying to do an image conversion in a rails app from SVG to PNG. ImageMagick didn't work out for me, due to Heroku not able / wanting to upgrade IM at this time. I'm testing out some ideas of using RSVG2 / Cairo in dev but running into a roadblock.
I can easily convert and save the SVG to PNG like this:
#svg_test.rb
require 'debugger'
require 'rubygems'
require 'rsvg2'
SRC = 'test.svg'
DST = 'test.png'
svg = RSVG::Handle.new_from_file(SRC)
surface = Cairo::ImageSurface.new(Cairo::FORMAT_ARGB32, 800, 800)
context = Cairo::Context.new(surface)
context.render_rsvg_handle(svg)
surface.write_to_png(DST)
But this only lets me write PNG files out. In the app, I need to be able to generate these on the fly, then send them down to the client browser as data. And I can't figure out how to do this, or even if its supported. I know I can call surface.data to get the raw data at least, but I don't know enough about image formats to know how to get this as a PNG.
Thanks
Ah ha! I was so close and its pretty obvious in hindsight. Simply call the surface.write_to_png function with a StringIO object. This fills the string object, which you can then get the bytes for. Here's the finished svg_to_png function I wrote, along with a sample controller that calls it. Hope this helps someone else somewhere.
ImageConvert function:
def self.svg_to_png(svg)
svg = RSVG::Handle.new_from_data(svg)
surface = Cairo::ImageSurface.new(Cairo::FORMAT_ARGB32, 800, 800)
context = Cairo::Context.new(surface)
context.render_rsvg_handle(svg)
b = StringIO.new
surface.write_to_png(b)
return b.string
end
Test controller:
def svg_img
path = File.expand_path('../../../public/images/test.svg', __FILE__)
f = File.open(path, 'r')
t = ImageConvert.svg_to_png(f.read)
send_data(t , :filename => 'test.png', :type=>'image/png')
end

Converting PDF to PNG with transparent background

We have a Ruby on Rails application that needs to convert a PDF into a PNG with a transparent background. We're using rmagick 2.13.1. On our development machines the following code works exactly how we want it.
pages = Magick::Image.from_blob(book.to_pdf.render){ self.density = 300 }
page = pages[0]
image_file = Tempfile.new(['preview_image', '.png'])
image_file.binmode
image_file.write( page.to_blob { |opt| opt.format = "PNG" } )
We thens save the image_file and all is peachy. When we deployed to a review server on Heroku, though, the generated image has a white background. It turns out that Heroku's cedar stack is using imagemagick ImageMagick 6.5.7-8 2010-12-02 where we're using ImageMagick 6.7.5-7 2012-05-08 on our development machines.
I've scoured the net for older posts that might apply to the older version to try and figure out how to generate the transparent PNGs. It's surely supported, but, so far I haven't been able to figure out the right combination of settings.
To verify that it wasn't the PDF generation that was the problem, I downloaded a PDF generated on Heroku and successfully converted it using the above code (slightly modified to read the file in instead of generate it) to a transparent PNG.
Some of the things I've tried in various combinations are:
page.matte = true
page.format = "PNG32"
page.background_color = "none"
page.transparent_color = "white"
page.transparent("white")
So, the question is "is this possible?". If so, which settings do I need to set on the image before writing it out?
I'm also investigating including a compiled binary of a more up to date Imagemagick on Heroku.
Any help is appreciated.
This should no longer be an issue, as Heroku has ImageMagick versions 6.7-6.9 on their various stacks.

Not Identified By ImageMagick Error when there is a space in the filename

I am getting the width and height of an image stored on Amazon S3 using Paperclip as follows:
Paperclip::Geometry.from_file(user.avatar.url)
It has been working fine, but it is erroring on an image that has a space in the filename:
Paperclip::NotIdentifiedByImageMagickError: my_amazon_s3_path_is_here/Martian landslide.jpg?1294675113 is not recognized by the 'identify' command.
The image loads okay when you go to the URL in a browser. What can I do to fix this?
EDIT: Forgot to mention that images without a space in their filename work fine, so it's not an issue with Imagemagick/Paperclip setup.
Do you need to URL Encode the url's? eg replace spaces with %20
Usually when you see:
not recognized by the 'identify' command.
It means ImageMagick isn't set up correctly. Are other images working correctly?
Have you tweaked this setting yet?
Paperclip.options[:command_path] = "/opt/local/bin"
It needs to point to the location where identify is installed. From the command line, you can determine this with:
which identify
I have the same problem and file 'Снимок экрана от 2013-02-28 14:36:49.png' returns the same error. But it works correctly on heroku. So I think the problem is in ImageMagick

Resources