3

I'm trying to get an alphanumeric-encoded barcode using the viivakoodi library. I got the barcode which I needed but I'm not able to display it in my HTML page using Jinja2. Here's my code:

import barcode
from StringIO import StringIO

encoding_std = barcode.get_barcode_class('code128')
ean = encoding_std('Test123')
fp = StringIO()
ean.write(fp)
encoded_output = fp.getvalue()
fp.close()

I'm currently storing the barcode as SVG and I'm not able to display that in the HTML page. Using {{ encoded_ouput | safe }} in the HTML page to display the barcode does not show me the results:

<div class="row border-bottom no-margin" style="height: 15%">
    <div class="float-left border-right"
         style="width: 100%; padding: 5px; height: 100%;font-family:arial">
        <p style="font-weight:bold; margin-bottom: 0; font-family:arial; font-size:13px">
            <b>Generated Barcode Space:</b></p><b>
            {{ encoded_output | safe }}

    </b></div>
</div>

Or any Jinja2 filters are there to get the SVG?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Prasad
  • 61
  • 1
  • 4
  • Can you show us your Jinja2 code too please? A complete test page will do (so only the tags that are meant to show the SVG generated). – Martijn Pieters Oct 26 '15 at 07:50
  • Also, what `barcode` package are you using? The pyBarcode project [doesn't seem to support that class](https://pythonhosted.org/pyBarcode/codes.html). – Martijn Pieters Oct 26 '15 at 07:58
  • I m using viivakoodi library, link for that library https://pypi.python.org/pypi/viivakoodi/0.8.0, i used this library bcoz i'm using python27. I guess pyBarcode doesnt provide Alpha numeric encoding of barcodes so i used this lib – Prasad Oct 26 '15 at 08:06
  • Your code *works*, at least when I tried your template with `| safe` and the viivakoodi library. – Martijn Pieters Oct 26 '15 at 08:22

1 Answers1

2

The SVG output produced includes an XML header and doctype:

>>> print '\n'.join(encoded_output.splitlines()[:4])
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg
  PUBLIC '-//W3C//DTD SVG 1.1//EN'
  'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>

Although your code works in Chrome, other browsers may not be so forgiving of the extra headers being included. I'd split those from the output generated:

encoded_output = encoded_output[encoded_output.find('<svg'):]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343