使用inkscape创建模板,然后填充它们(如果愿意,可以将它们呈现为pdf格式)。
svglue的Python项目详细描述
svglue是一个小的库,它采用一个模板的形式 svg文档并填充文本和图像以创建输出svg文件。风格 保留不透明度、大小和顺序等信息。
它主要用于建立一个创建模板的良好工作流 对于PDF生成:
- Create your template in Inkscape, a placeholder text-element where you want to fill in text later, or a rectangle for filling in images.
- Add a custom attribute ^{tt1}$ to every ^{tt2}$ or ^{tt3}$ element that you want to replace. Each ^{tt1}$ must be a unique identifier.
- Using ^{tt5}$, you can programmatically replace every text or rect using its ^{tt1}$ with either a raster image, another SVG graphic or replacement text.
- Finally, use something like rsvg, CairoSVG or another SVG-renderer to create a PDF document.
示例代码:
第3步:
#!/usr/bin/env python import svglue # load the template from a file tpl = svglue.load(file='sample-tpl.svg') # replace some text tpl.set_text('sample-text', u'This was replaced.') # replace the pink box with 'hello.png'. if you do not specify the mimetype, # the image will get linked instead of embedded tpl.set_image('pink-box', file='hello.png', mimetype='image/png') # svgs are merged into the svg document (i.e. always embedded) tpl.set_svg('yellow-box', file='Ghostscript_Tiger.svg') # to render the template, cast it to a string. this also allows passing it # as a parameter to set_svg() of another template src = str(tpl) # write out the result as an SVG image and render it to pdf using cairosvg import cairosvg with open('output.pdf', 'w') as out, open('output.svg', 'w') as svgout: svgout.write(src) cairosvg.svg2pdf(bytestring=src, write_to=out)
需要注意的是,cairosvg的<;=0.5版本有一个bug 使老虎的比例不正确。现在,您可以使用不同的渲染器 为了更好的结果直到错误被修复。
安装
svglue是available via PyPI,所以 一个简单的pip install svglue就足够安装了。
API参考
注意,这个库的主要目标是python3。后来的
我不再在python2上编译cairosvg
的版本。
如果需要python2支持,请将svglue
的版本限制为<=0.2.1
。
加载(src=none,file=none)
加载模板,返回Template-对象。src/file加载 模式通过库使用-src是一个包含 svg文件的源,或者file可以是类似于文件的对象(具有 read()方法)或源文件的文件名。只有一个 src/file可以指定。
模板。设置文本(tid,文本)
替换元素<tspan id="tid">(其id是 使用指定的text实际tid。
template.set_image(tid,src=none,file=none,mimetype=none)
将ID为^{TT19}$(^{TT22}$)的矩形替换为 <image>标记以链接/嵌入指定的图像。如果mimetype是None, 图像已链接(因此file应该是该图像的路径/uri)。
如果给定mimetype(应该是image/png或image/jpeg), 提供的图像以内联方式存储在生成的svg文档中。
template.set_svg(tid,src=none,file=none)
在概念上类似于Template.set_image(),它替换了一个矩形 使用SVG图像。但是,不支持链接,SVG被复制到 生成的svg文档<defs>-节和<use>-元素替换 矩形。
由于Template.__str__()(见下文)用于呈现模板,因此 只需将模板作为第二个参数传递给 set_svg()。
模板。
呈现模板。返回包含所有提供信息的模板。