【发布时间】:2017-09-16 05:11:49
【问题描述】:
我正在使用 python3 中的 BeautifulSoup 模块来修改我用 Inkscape 创建的一些 svg 文件。具体来说,我正在修改这些文件中的一些文本,并在某些情况下更改某些对象的颜色。我注意到,无论我做什么,所有文本的位置总是在输出 svg 文件中移动。 例如参见: svg in/out files + png versions
与原始文件相比,输出 svg 中的文本对象的大小似乎有所不同。我可以将文本对象从输出文件复制到原始文件,但我不再看到这种转变,但这是一个烦人的解决方案。
有谁知道导致文本对象大小发生这种变化的原因以及可以防止这种变化吗?
这是我运行的一段代码示例(输入和输出 svg 的副本在上面的链接中):
from bs4 import BeautifulSoup
svgFile = "test_in.svg"
outputFile = "test_out.svg"
svg = open(svgFile, 'r').read()
soup = BeautifulSoup(svg, features = 'xml')
texts = soup.findAll('text')
for t in texts:
if t['id'] == 'testID':
print(t, '\n')
t.contents[0].string = 'new text'
print(t, '\n')
# Output the edited SVG file
f = open(outputFile, "w")
f.write(soup.prettify())
f.close()
xml/svg 树中的文本元素似乎没有任何变化,所以我觉得问题必须来自对文件其他部分的更改。 (另外,我可以省略t.contents[0].string = 'new text' 并且文本移动仍然发生。)第一个print(t) 给出:
<text id="testID" inkscape:label="#text3581" sodipodi:linespacing="125%" style="font-size:20px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;line-height:125%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Arial;-inkscape-font-specification:Arial" transform="matrix(0,1,-1,0,0,0)" x="449.63721" xml:space="preserve" y="-280.92737"><tspan id="tspan3583" sodipodi:role="line" style="font-size:14px;font-weight:normal;-inkscape-font-specification:Arial" x="449.63721" y="-280.92737">Text to change</tspan></text>
第二个 print(t) 的输出看起来完全一样,除了 'text to change' 现在是 'new text':
<text id="testID" inkscape:label="#text3581" sodipodi:linespacing="125%" style="font-size:20px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;line-height:125%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Arial;-inkscape-font-specification:Arial" transform="matrix(0,1,-1,0,0,0)" x="449.63721" xml:space="preserve" y="-280.92737"><tspan id="tspan3583" sodipodi:role="line" style="font-size:14px;font-weight:normal;-inkscape-font-specification:Arial" x="449.63721" y="-280.92737">new text</tspan></text>
任何见解都将不胜感激!
【问题讨论】:
-
请发布一个在转换过程中移动的文本对象的小 svg 示例。
-
已编辑以包含输入和输出 svg 文件的 png 版本
标签: python python-3.x svg beautifulsoup inkscape