-
-
Save efatsi/456ed99988f59969a2be7c414e66cf58 to your computer and use it in GitHub Desktop.
This file contains 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
module ImagePdfHelper | |
def image_or_pdf_tag(attachment, width:, height: nil, with_link: false, mime_type: nil) | |
height ||= width | |
# fetch mime_type of attachment is one isn't passed in as an argument | |
mime_type ||= attachment.mime_type | |
output = if mime_type == "application/pdf" | |
render_pdf(attachment, width, height) | |
else | |
image_tag attachment.thumb("#{width}x#{height}").url | |
end | |
if with_link | |
link_to(attachment.url, target: :_blank) do | |
output | |
end | |
else | |
output | |
end | |
end | |
def render_pdf(attachment, width, height) | |
load_pdf_js | |
uid = SecureRandom.hex(20) | |
content_tag(:div, content_tag(:span, "", id: uid)).tap do | |
build_canvas_on_div(uid, attachment, width) | |
end | |
end | |
def load_pdf_js | |
return if @loaded_pdf_js | |
content_for(:after_scripts) do | |
tag.script src: "//npmcdn.com/pdfjs-dist/build/pdf.js" | |
end | |
@loaded_pdf_js = true | |
end | |
def build_canvas_on_div(uid, attachment, width) | |
# assumes you have <%= content_for(:after_scripts) %> in your application layout | |
content_for(:after_scripts) do | |
script = <<-JS | |
<script> | |
var previewDiv#{uid} = document.getElementById("#{uid}") | |
pdfjsLib.getDocument("#{attachment.url}").then(function (doc) { | |
doc.getPage(1).then(function(page) { | |
var vp = page.getViewport(1) | |
var canvas = document.createElement("canvas") | |
canvas.width = #{width} | |
canvas.height = #{width} * (vp.height / vp.width) | |
var scale = Math.min(canvas.width / vp.width, canvas.height / vp.height) | |
return page.render({ | |
canvasContext: canvas.getContext("2d"), | |
viewport: page.getViewport(scale) | |
}).then(function () { | |
previewDiv#{uid}.appendChild(canvas) | |
}) | |
}) | |
}) | |
</script> | |
JS | |
script.html_safe | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment