EPUB 內含 Illustrator 製作的 SVG 圖檔時的問題

2015.6.2

用 Adobe Illustrator 製作的 SVG 缺字圖檔,如果放在 EPUB 裡,validate 時會有錯誤:

External DTD entities are not allowed. Remove the DOCTYPE.
...
element "sodipodi:namedview" not allowed anywhere
...
attribute "inkscape:connector-curvature" not allowed here;
...
attribute "sodipodi:nodetypes" not allowed here

上傳到 Google Books 時也會有錯誤:「無法為 ePub 掃描病毒」。

這可能是因為 Illustrator 在 SVG 圖檔裡多放了一些不是標準的東西,以下這支 ruby 小程式可以移除這些不標準的東西:

require 'nokogiri'
IN = '../glyphs'
OUT = '../output/glyphs'
def handle_node(e)

ns = e.namespace

unless ns.nil?

if e.namespace.prefix == 'sodipodi'

e.remove

return

end

end

e.attribute_nodes.each do |a|

ns = a.namespace

unless ns.nil?

if %w(sodipodi inkscape).include? ns.prefix

e.remove_attribute(a.node_name)

end

end

end

e.children.each { |c| handle_node(c) }

end
Dir["#{IN}/*.svg"].each do |p|

basename = File.basename(p)

puts basename

t = File.read(p)

t.sub!(%r{<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">}, '')

doc = Nokogiri::XML(t)

handle_node(doc.root)

t = doc.to_xml

fno = File.join(OUT, basename)

File.write(fno, t)

end