Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding SVG in PDF using Wicked_PDF (wkhtmltopdf)

When I try to include an SVG in a PDF generated by wicked_pdf (wkhtmltopdf), it comes out blank. Any idea how to get the svg to display in the pdf?

app/views/barcodes/to_pdf.html.haml

<descriptive text here>
%object#code_image{:data=>"/barcodes/generate_svg?code=4567898", :type=>"image/svg+xml", :height=>70}

barcodes controller

def generate_svg
  require 'barby'
  require 'barby/barcode/code_128'
  require 'barby/outputter/svg_outputter'
  barcode = Barby::Code128B.new(params[:code])
  render :text => barcode.to_svg({:height=>30, :width => 170})
end


def to_pdf
 render :pdf        => 'file_name'      
end
like image 236
Lee Quarella Avatar asked Oct 24 '11 18:10

Lee Quarella


3 Answers

I got it to work using this method of embedding SVG.

Display Inline SVG Using the Tag

Replace

"data:image/svg+xml;base64,PD94bWwgdmVy..."

with

"data:image/svg+xml;base64,#{Base64.encode64(barcode.to_svg)}"
like image 134
user1632065 Avatar answered Sep 20 '22 21:09

user1632065


this is how i adapted user1632065 answer to work in both html and pdf

in your GemFile

gem 'cairo'
gem 'barby'

in your model

class ExampleModel
  def barcode
    require 'barby'
    require 'barby/barcode/code_128'
    require 'barby/outputter/cairo_outputter'
    Barby::CairoOutputter.new(Barby::Code128B.new('bla bla this is barcode source'))
  end
end

in your view(in my case haml)

%img{:width => ExampleModelObject.barcode.width, :src=> "data:image/svg+xml;base64,#{Base64.encode64(ExampleModelObject.barcode.to_svg)}"}

this way you get correct barcode width

like image 40
Saulius Morkevicius Avatar answered Sep 18 '22 21:09

Saulius Morkevicius


I use wicked_pdf in one of my Rails 3.0.x app and it works like a charm. I use SVG code embedded directly into HTML (erb/haml views). No or - just pure tag with given 'width' and 'height' attributes. It does not work for some browsers (Opera, IE<9), but I don't care about that in my case. Maybe you could try going with your stuff that way?

like image 25
rawonstack Avatar answered Sep 20 '22 21:09

rawonstack