如何将散景图另存为 PDF?

问题描述 投票:0回答:1

我经常使用 Bokeh,并且正在寻找一种从我创建的图形创建 PDF 的方法。

有办法实现这个目标吗?

python pdf bokeh reportlab
1个回答
1
投票

这可以通过三个 python 包

bokeh
svglib
reportlab
的组合来实现,这对我来说非常适合。

这将包括 3 个步骤:

  1. 创建散景 svg 输出
  2. 阅读此 svg
  3. 将此 svg 保存为 pdf

最小示例

要展示这是如何工作的,请参阅以下示例。

from bokeh.plotting import figure
from bokeh.io import export_svgs
import svglib.svglib as svglib
from reportlab.graphics import renderPDF

test_name = 'bokeh_to_pdf_test'

# Example plot p
p = figure(plot_width=400, plot_height=400, tools="")
p.circle(list(range(1,6)),[2, 5, 8, 2, 7], size=10)
# See comment 1
p.xaxis.axis_label_standoff = 12
p.xaxis.major_label_standoff = 12

# step 1: bokeh save as svg
p.output_backend = "svg"
export_svgs(p, filename = test_name + '.svg')

# see comment 2
svglib.register_font('helvetica', '/home/fonts/Helvetica.ttf')
# step 2: read in svg
svg = svglib.svg2rlg(test_name+".svg")

# step 3: save as pdf
renderPDF.drawToFile(svg, test_name+".pdf")

评论1

对于

axis_label_standoff
major_label_standoff
使用了额外的信息,因为在没有此定义的情况下,x 轴的刻度正在移动,这看起来不太好。

评论2

如果您收到一长串警告,例如

Unable to find a suitable font for 'font-family:helvetica'
Unable to find a suitable font for 'font-family:helvetica'
....
Unable to find a suitable font for 'font-family:helvetica'

pdf 仍然被创建。出现此警告是因为散景中的默认字体名为

helvetica
,而
svglib
不知道该字体。
svglib
在定义的位置查找此字体。如果该字体不存在,则会出现该消息。这意味着散景将使用自己的默认字体。

要摆脱此消息,您可以像这样在

svglib
中注册字体

#                    name in svglib, path to font
svglib.register_font('helvetica'   , f'/{PATH_TO_FONT}/Helvetica.ttf')

在打电话之前

svglib.svg2rlg()

输出

此代码将创建相同的图形两次,一次带有后缀

.svg
,一次带有后缀
.pdf

图是这样的:

© www.soinside.com 2019 - 2024. All rights reserved.