我有一个如下所示的 SVG 对象:
各内<g>
元素有<path>
就在其中。
我想将此 SVG 导出为 PDF,以便将组转换为图层 (OCG),如下所示:
<ThroughCut>
<Path>
<Path>
<Path>
<Path>
<Graphics>
<Path>
<Path>
<Path>
<Path>
然而,我为此尝试过的任何工具都将所有对象放在同一层中,并且基本上丢弃了有关组的信息。
首选 JavaScript 或 Python 解决方案,但任何在 UNIX 计算机上从命令行执行的解决方案都可以。
最佳答案
我按照此处所述解决了我的问题 this PyMuPDF issue在 Github 上。
由于我可以控制输入 SVG,因此我设法通过将两个 SVG 解析为 PDF 并将它们组合到新文档的不同层中来解决该问题。 这就是我正在做的:
import fitz
from svglib.svglib import svg2rlg
from reportlab.graphics.renderPDF import drawToString
def svg_to_doc(path):
"""Using this function rather than `fitz`' `convertToPDF` because the latter
fills every shape with black for some reason.
"""
drawing = svg2rlg(path)
pdfbytes = drawToString(drawing)
return fitz.open("pdf", pdfbytes)
# Create a new blank document
doc = fitz.open()
page = doc.new_page()
# Create "Layer1" and "Layer2" OCGs and get their `xref`s
xref_1 = doc.add_ocg('Layer1', on=True)
xref_2 = doc.add_ocg('Layer2', on=True)
# Load "layer_1" and "layer_2" svgs and convert to pdf
doc_1 = svg_to_doc("my_layer_1.svg")
doc_2 = svg_to_doc("my_layer_2.svg")
# Set the `page` dimensions. Note: for me it makes sense to set the bounding
# box of the output to the same as `doc_1`, because I know `doc_1` contains
# `doc_2`. If that were not the case, I would set `bb` to be a new
# `fits.Rect` object that contained both `doc_1` and `doc_2`.
bb = doc_1[0].rect
page.setMediaBox(bb)
# Put the docs in their respective OCGs
page.show_pdf_page(bb, doc_1, 0, oc=xref_1)
page.show_pdf_page(bb, doc_2, 0, oc=xref_2)
# Save
doc.save("output.pdf")
如果我在 Adobe Acrobat 中加载“output.pdf”,则会显示图层。奇怪的是,Adobe Illustrator 的情况并非如此(这里它们只是“剪辑组”)。无论如何,我相信这可以解决上述问题。
关于javascript - 将 SVG 导出为 PDF,且组/图层完好无损,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68803091/