Skip to main content
 首页 » 编程设计

python之将 svg 存储在 jinja2 的变量中

2024年10月24日20qlqwjy

我正在尝试使用 viivakoodi library 获取字母数字编码的条形码.我得到了我需要的条形码,但我无法使用 Jinja2 在我的 HTML 页面中显示它。这是我的代码:

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() 

我目前将条形码存储为 SVG,但无法在 HTML 页面中显示它。使用 {{ encoded_ouput | safe }} 在 HTML 页面中显示条码不显示结果:

<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> 

或者是否有任何 Jinja2 过滤器可以获取 SVG?

请您参考如下方法:

生成的 SVG 输出包括 XML header 和文档类型:

>>> 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'> 

虽然您的代码可以在 Chrome 中运行,但其他浏览器可能不会如此宽容包含额外的 header 。我会将它们从生成的输出中分离出来:

encoded_output = encoded_output[encoded_output.find('<svg'):]