9

我在 python 中编写了一个脚本,该脚本生成 matplotlib 图形并使用reportlab.

我很难将 SVG 图像文件嵌入到我的 PDF 文件中。我在使用 PNG 图像时没有遇到任何问题,但我想使用 SVG 格式,因为这样可以在 PDF 报告中生成质量更好的图像。

这是我收到的错误消息:

IOError: cannot identify image file

有没有人有建议或者你以前克服过这个问题?

4

4 回答 4

11

昨天我成功使用 svglib 将 SVG 图像添加为 reportlab Flowable。

所以这个绘图是reportlab绘图的一个实例,见这里:

from reportlab.graphics.shapes import Drawing

一个reportlab绘图继承Flowable:

from reportlab.platypus import Flowable

这是一个最小的示例,它还显示了如何正确缩放它(您必须只指定路径和因子):

from svglib.svglib import svg2rlg
drawing = svg2rlg(path)
sx = sy = factor
drawing.width, drawing.height = drawing.minWidth() * sx, drawing.height * sy
drawing.scale(sx, sy)
#if you want to see the box around the image
drawing._showBoundary = True
于 2017-01-23T12:20:22.757 回答
3

正如skidzo所提到的,你完全可以用svglib包做到这一点,你可以在这里找到:https ://pypi.python.org/pypi/svglib/

根据该网站,Svglib 是一个纯 Python 库,用于读取 SVG 文件并使用 ReportLab 开源工具包将它们(在合理的程度上)转换为其他格式。

您可以使用pip安装 svglib。

这是一个完整的示例脚本:

# svg_demo.py

from reportlab.graphics import renderPDF, renderPM
from reportlab.platypus import SimpleDocTemplate
from svglib.svglib import svg2rlg


def svg_demo(image_path, output_path):
    drawing = svg2rlg(image_path)
    renderPDF.drawToFile(drawing, output_path)

if __name__ == '__main__':
    svg_demo('/path/to/image.svg', 'svg_demo.pdf')
于 2018-04-11T18:28:47.120 回答
3

skidzo 的回答非常有帮助,但并不是如何在 reportlab PDF 中将 SVG 文件用作可流动文件的完整示例。希望这对其他试图弄清楚最后几个步骤的人有所帮助:

from io import BytesIO

import matplotlib.pyplot as plt
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import SimpleDocTemplate, Paragraph
from svglib.svglib import svg2rlg


def plot_data(data):
    # Plot the data using matplotlib.
    plt.plot(data)

    # Save the figure to SVG format in memory.
    svg_file = BytesIO()
    plt.savefig(svg_file, format='SVG')

    # Rewind the file for reading, and convert to a Drawing.
    svg_file.seek(0)
    drawing = svg2rlg(svg_file)

    # Scale the Drawing.
    scale = 0.75
    drawing.scale(scale, scale)
    drawing.width *= scale
    drawing.height *= scale

    return drawing


def main():
    styles = getSampleStyleSheet()
    pdf_path = 'sketch.pdf'
    doc = SimpleDocTemplate(pdf_path)

    data = [1, 3, 2]
    story = [Paragraph('Lorem ipsum!', styles['Normal']),
             plot_data(data),
             Paragraph('Dolores sit amet.', styles['Normal'])]

    doc.build(story)


main()
于 2020-03-08T17:48:48.937 回答
0

您需要确保在代码中导入 PIL(Python 图像库),以便 ReportLab 可以使用它来处理 SVG 等图像类型。否则它只能支持几种基本的图像格式。

也就是说,我记得即使在使用 PIL 和矢量图形时也遇到了一些麻烦。我不知道我是否尝试过 SVG,但我记得 EPS 遇到了很多麻烦。

于 2013-05-13T12:59:18.430 回答