Last active
June 7, 2019 01:44
-
-
Save eatoncw/2deb6a62e3056e5e53b0af8cd39a1c36 to your computer and use it in GitHub Desktop.
PDF to JPG conversion using Rails 5, Paperclip. Improved resolution of output
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Accepts all image files and pdfs. If the upload is a pdf, it is converted to a jpg | |
#Paperclip incorporates ImageMagick. If a multipage page PDF, only the first page is converted | |
#Model | |
#here the original style needs to be given source_file_options. It's critical that the original file is not passed geometry | |
#or the resolution won't really improve | |
has_attached_file :avatar, | |
styles: lambda { |attachment| | |
styles = {} | |
if attachment.content_type =~ /application.pdf/ | |
styles[:thumb] = { | |
geometry: "800x800#", | |
format: :jpg | |
} | |
styles[:medium] = { | |
geometry: "1920x1920>", | |
format: :jpg | |
} | |
styles[:original] = { | |
format: :jpg, | |
source_file_options: lambda { |a| "-quality 100 -density 400" } | |
} | |
else | |
styles = {thumb: "800x800#", drawingboard: "1920x1920>"} | |
end | |
styles | |
} | |
#model validation | |
validates_attachment_content_type :drawingboard_image, content_type: [/\Aimage\/.*\z/, 'application/pdf'] | |
#in Paperclip initializer | |
#Prevent paperclip spoof settings from breaking file conversion | |
Paperclip.options[:content_type_mappings] = { pdf: "image/jpeg" } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great!