上下文:我的代码从一些 png 文档中获取一组坐标,然后在某些字段中执行一些编辑(它使用这些坐标在某些区域绘制矩形)。
我希望我的最终输出是一个 pdf,每个编辑图像作为页面。我可以用 fpdf 包毫无问题地实现这一点。
但是,我打算将此 pdf 文件作为电子邮件(base64 编码)附件发送。有没有办法从 fpdf 输出中获取 base64 字符串?
最重要的是,我可以在 fpdf 图像方法中使用图像二进制字符串吗?
请参阅下面的 redact_pdf 方法(我在此处放置了一些评论以便更清楚)
代码:
class Redaction:
def __init__(self,png_image_list,df_coordinates):
self.png_image_list = png_image_list
self.df_coordinates = df_coordinates
def _redact_images(self):
redacted_images_bin = []
for page_num,page_data in enumerate(self.png_image_list):
im_page = Image.open(io.BytesIO(page_data))
draw = ImageDraw.Draw(im_page)
df_filtered = self.df_coordinates[self.df_coordinates['page_number'] == page_num+1]
for index, row in df_filtered.iterrows():
x0 = row['x0'] * im_page.size[0]
y0 = row['y0'] * im_page.size[1]
x1 = row['x1'] * im_page.size[0]
y1 = row['y1'] * im_page.size[1]
x2 = row['x2'] * im_page.size[0]
y2 = row['y2'] * im_page.size[1]
x3 = row['x3'] * im_page.size[0]
y3 = row['y3'] * im_page.size[1]
coords = [x0,y0,x1,y1,x2,y2,x3,y3]
draw.polygon(coords,outline='blue',fill='yellow')
redacted_images_bin.append(im_page)
return redacted_images_bin
def redacted_pdf(self):
redacted_images = self._redact_images()
pdf = FPDF()
pdf.set_auto_page_break(0)
for index,img_redacted in enumerate(redacted_images):
img_redacted.save(f"image_{index}.png")
pdf.add_page()
pdf.image(f"image_{index}.png",w=210,h=297)
os.remove(f"image_{index}.png") # I would like to avoid file handling!
pdf.output("doc.pdf","F") # I would like to avoid file handling!
#return pdf #this is what I want, to return the pdf as base64 or binary