是否可以在RBPDF中添加DataUrl Image?

时间:2017-08-04 14:40:53

标签: ruby-on-rails pdf data-url

我正在使用ruby on rails上的DataUrl Image制作pdf文件。

我选择了RBPDF在服务器端生成pdf文件。

但是在这段代码中我有以下错误

 @pdf.Image(object["src"] , object["left"], object["top"], object["width"], object["height"])

此处对象[" src"]是DataUrl Image。

  

RuntimeError(RBPDF错误:缺少图像文件:   数据:图像/ JPEG; BASE64,/ 9J / 4REORXhp ...

是否无法从DataUrl图像添加RBPDF图像?

我认为动态添加文件无效。

1 个答案:

答案 0 :(得分:1)

你可以修补origin method

我使用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