Skip to content

Instantly share code, notes, and snippets.

@eatoncw
Last active June 7, 2019 01:44
Show Gist options
  • Save eatoncw/2deb6a62e3056e5e53b0af8cd39a1c36 to your computer and use it in GitHub Desktop.
Save eatoncw/2deb6a62e3056e5e53b0af8cd39a1c36 to your computer and use it in GitHub Desktop.
PDF to JPG conversion using Rails 5, Paperclip. Improved resolution of output
#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" }
@damuz91
Copy link

damuz91 commented Jun 7, 2019

Great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment