rst2pdf:生成带公式的PDF

1 投票
1 回答
1121 浏览
提问于 2025-04-18 09:58

我需要生成一个包含公式的报告。我找到了一个叫做rst2pdf的库。我很喜欢用这个库,但在生成带公式的PDF时遇到了问题。为了生成公式,我使用了数学角色(math role)。下面的代码无法正常工作。错误发生在PIL模块中。我该如何解决这个问题呢?

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from rst2pdf.createpdf import RstToPdf

mytext = u"""
================
Name of document
================

Title
---------

====================  ==========  ==========
Header row, column 1  Header 2    Header 3
====================  ==========  ==========
body row 1, column 1  column 2    column 3
body row 2, column 1  column 2    column 3
body row 3, column 1  column 2    column 3
====================  ==========  ==========

:math:`\\frac{1}{\\sigma\\sqrt{2\\pi}}\\exp\\left(-\\frac{(x-\\mu)^2}{2\\sigma^2}\\right) = 123`

"""

pdf = RstToPdf()
pdf.createPdf(text = mytext, output='foo.pdf')

脚本的输出结果

File "C:\Python27\lib\site-packages\PIL\Image.py", line 1549, in save
    raise KeyError(ext) # unknown extension
KeyError: '.png'

1 个回答

0

这个错误发生在PIL/Pillow不认识你选择的文件扩展名时。

from PIL import Image
im = Image.new("RGB", (100, 100))
im.save("test", ".png")

会出现这样的错误

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "lib/python3.7/site-packages/PIL/Image.py", line 1939, in save
     save_handler = SAVE[format.upper()]
KeyError: '.PNG'

这是因为“.png”不是一个有效的格式,而“png”才是。你需要做的是

im.save("test", "png")

或者

im.save("test.png")

撰写回答