问题
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?
回答1:
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'):]
来源:https://stackoverflow.com/questions/33340728/getting-svg-stored-in-a-variable-in-jinja2