我正在用ruby在rails中从DataUrl图像制作pdf文件。
我选择了RBPDF在服务器端生成pdf文件。
但是在此代码中,我有以下错误
@pdf.Image(object["src"] , object["left"], object["top"], object["width"], object["height"])
这里的对象["src"]是DataUrl图像。
运行时错误 (RBPDF 错误: 缺少图像文件: 数据:图像/JPEG;base64,/9j/4REORXhp...
是否无法从数据网址图像添加RBPDF图像?
我认为动态添加文件是无效的。
你可以猴子修补原始方法。
我使用 data_uri gem 来解析图像数据。
require 'data_uri'
require 'rmagick'
module Rbpdf
alias_method :old_getimagesize, :getimagesize
# @param [String] date_url
def getimagesize(date_url)
if date_url.start_with? 'data:'
uri = URI::Data.new date_url
image_from_blob = Magick::Image.from_blob(uri.data)
origin_process_image(image_from_blob[0])
else
old_getimagesize date_url
end
end
# this method is extracted without comments from the origin implementation of getimagesize
def origin_process_image(image)
out = Hash.new
out[0] = image.columns
out[1] = image.rows
case image.mime_type
when "image/gif"
out[2] = "GIF"
when "image/jpeg"
out[2] = "JPEG"
when "image/png"
out[2] = "PNG"
when " image/vnd.wap.wbmp"
out[2] = "WBMP"
when "image/x-xpixmap"
out[2] = "XPM"
end
out[3] = "height="#{image.rows}" width="#{image.columns}""
out['mime'] = image.mime_type
case image.colorspace.to_s.downcase
when 'cmykcolorspace'
out['channels'] = 4
when 'rgbcolorspace', 'srgbcolorspace' # Mac OS X : sRGBColorspace
if image.image_type.to_s == 'GrayscaleType' and image.class_type.to_s == 'PseudoClass'
out['channels'] = 0
else
out['channels'] = 3
end
when 'graycolorspace'
out['channels'] = 0
end
out['bits'] = image.channel_depth
out
end
end