使用Python将带有嵌入式CSS的SVG转换为PDF [英] Converting SVG with Embedded CSS to PDF in Python

查看:109
本文介绍了使用Python将带有嵌入式CSS的SVG转换为PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python从SVG图像生成PDF图像.我已经尝试了 CairoSVG svglib .问题在于,在两种情况下,生成的PDF均未应用任何嵌入式CSS样式.

I'm trying to generate a PDF image from an SVG image using Python. I've tried both CairoSVG and svglib. The problem is that in both cases the generated PDFs do not have any of the embedded CSS styles applied.

这是一个简单的SVG文件,该文件应呈现带有黑色边框的蓝色矩形:

Here is a simple SVG file which should render a blue rectangle with a black border:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="200" height="200" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <style type="text/css"><![CDATA[
      rect {
        fill: #1f77b4;
        stroke: black;
        stroke-width: 1;
        shape-rendering: crispEdges;
      }
    ]]></style>
  </defs>
  <rect x="50" y="50" width="100" height="100"></rect>
</svg>

使用CairoSVG渲染此SVG的PDF时,PDF图像被渲染为黑色矩形.使用svglib时,矩形没有应用任何笔触或样式,因此它是不可见的.有没有人知道用CSS样式将具有CSS样式的SVG转换为Python中的PDF图像的方法?

When rendering a PDF of this SVG using CairoSVG, the PDF image is rendered as a black rectangle. Using svglib, there is no stroke or style applied to the rectangle so it is not visible. Is anyone aware of a way to convert an SVG with CSS styles to a PDF image in Python?

推荐答案

(在@MonkeyWrench的帮助下,因为他没有发布答案.)

(With help from @MonkeyWrench, since he didn't post an answer.)

根据文档

CairoSVG可以使用lxml来解析SVG文件,tinycss加上cssselect可以应用未包含在标签的style属性中的CSS.如果这些软件包不可用,则样式属性仅支持CSS.

CairoSVG can use lxml to parse the SVG file, and tinycss plus cssselect to apply CSS not included in the style attribute of the tags. If these packages are not available, CSS will only be supported in the style attributes.

首先,我安装了所有依赖项,

To get started, I installed all the dependencies,

$ pip3 install cairosvg lxml tinycss cssselect

然后我创建了具有以下内容的image.svg:

Then I created image.svg with the following contents:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="200" height="200" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <style type="text/css"><![CDATA[
      rect {
        fill: #1f77b4;
        stroke: black;
        stroke-width: 1;
        shape-rendering: crispEdges;
      }
    ]]></style>
  </defs>
  <rect x="50" y="50" width="100" height="100"></rect>
</svg>

最后,我执行了cairosvg

Finally, I executed cairosvg

$ cairosvg image.svg -o image.pdf

当然,这是一个蓝色矩形.

And sure enough, it was a blue rectangle.

这篇关于使用Python将带有嵌入式CSS的SVG转换为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆