gpt4 book ai didi

python - 将两个图形添加到一个 pdf 文件中

转载 作者:行者123 更新时间:2023-12-01 00:32:42 25 4
gpt4 key购买 nike

如何在一个 pdf 文件中添加两个图形(一个 条形图 和一个 表格)?我现在正在做的是:

from plotly import graph_objs as go
import numpy as np
import os
from IPython.display import Image

# Chart product views
fig = go.Figure(
data = [go.Bar(
x=[
"01/09/2019 - 07/09/2019",
"08/09/2019 - 14/09/2019",
"15/09/2019 - 21/09/2019",
"22/09/2019 - 28/09/2019"
],
y=[15, 25, 35, 32]
),
],
layout=dict(
yaxis=dict(
title="Product views"
),
autosize=False,
width=1000,
height=600,
),
)

# Table product views
fig2 = go.Figure(
data=[
go.Table(
header=dict(values=["Period", "Views"]),
cells=dict(values=[
[
"01/09/2019 - 07/09/2019",
"08/09/2019 - 14/09/2019",
"15/09/2019 - 21/09/2019",
"22/09/2019 - 28/09/2019"
],
[15, 25, 35, 32]
])
)
],
layout=dict(
autosize=False,
width=800,
height=300,
title=dict(
text="<b>Library Shelving</b> statistic"
)
)
)

if not os.path.exists("images"):
os.mkdir("images")

fig.write_image("images/fig1.pdf")
fig2.write_image("images/fig2.pdf")

成功创建 2 个 pdf。有没有办法实现这一点?

最佳答案

我已经能够使用以下方法完成此任务:

  • plotly.io.to_image() 将数字写入图像字节数据
  • PIL.Image.open() 读取字节数据
  • PIL.Image.convert() 将字节数据转换为RGB
  • io.BytesIO()临时存储转换后的图像数据
  • PIL.Image.save() 将第一张图像保存为 PDF 并将图形列表中的所有其他 PDF 附加到第一张图像

结果将是多页 PDF 图像。

您可能需要pip安装pillow

import plotly.io as pio
import io
from PIL import Image

figures = [fig1, fig2, fig3]
image_list = [pio.to_image(fig, format='png', width=1440, height=900, scale=1.5) for fig in figures]
for index, image in enumerate(image_list):
with io.BytesIO() as tmp:
tmp.write(image) # write the image bytes to the io.BytesIO() temporary object
image = Image.open(tmp).convert('RGB') # convert and overwrite 'image' to prevent creating a new variable
image_list[index] = image # overwrite byte image data in list, replace with PIL converted image data

# pop first item from image_list, use that to access .save(). Then refer back to image_list to append the rest
image_list.pop(0).save(r'/Users/USERNAME/plotly_dash.pdf', 'PDF',
save_all=True, append_images=image_list, resolution=100.0) # TODO improve resolution

关于python - 将两个图形添加到一个 pdf 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58048033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com