使用pyfpdf将Base64图像插入pdf

编程入门 行业动态 更新时间:2024-10-21 13:35:30
本文介绍了使用pyfpdf将Base64图像插入pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在python中使用pyfpdf生成pdf文件.我有一个Base64,我想插入到pdf文件中,而不必将其另存为文件系统中的图像.但是pyfpdf图片功能仅接受文件路径.

I'm using pyfpdf in python to generate pdf files. I have a Base64 which I want to insert into a pdf file without having to save it as an image in my file system. But the pyfpdf image function only accepts file path.

fpdf.image(name, x = None, y = None, w = 0, h = 0, type = '', link = '')

是否有一种方法(破解)直接从内存中插入base64或缓冲的图像,而无需事先保存到文件系统中?我什至在github上检查了它们的源代码,无法确定.

Is there a way (hack) to directly insert base64 or buffered image from memory, without having to save into the file system beforehand? I even checked their source code on github and couldn't figure.

链接: github/reingart/pyfpdf/tree/master /fpdf

推荐答案

正如注释中提到的@pvg一样,用base64功能覆盖load_resource函数可以解决问题.

As @pvg mentioned in the comments, overriding load_resource function with your base64 functionality does the trick.

import base64,io def load_resource(self, reason, filename): if reason == "image": if filename.startswith("") or filename.startswith(""): f = BytesIO(urlopen(filename).read()) elif filename.startswith("data"): f = filename.split('base64,')[1] f = base64.b64decode(f) f = io.BytesIO(f) else: f = open(filename, "rb") return f else: self.error("Unknown resource loading reason \"%s\"" % reason)

这是将图像插入pdf的示例代码.我在代码中评论了一些说明.

This is a sample code to insert images into pdf. I commented some instructions in code.

from fpdf import FPDF import os import io import base64 class PDF(FPDF): def load_resource(self, reason, filename): if reason == "image": if filename.startswith("") or filename.startswith(""): f = BytesIO(urlopen(filename).read()) elif filename.startswith("data"): f = filename.split('base64,')[1] f = base64.b64decode(f) f = io.BytesIO(f) else: f = open(filename, "rb") return f else: self.error("Unknown resource loading reason \"%s\"" % reason) def sample_pdf(self,img,path): self.image(img,h=70,w=150,x=30,y=100,type="jpg") #make sure you use appropriate image format here jpg/png pdf.output(path, 'F') if __name__ == '__main__': img = # pass your base64 image # you can find sample base64 here : pastebin/CaZJ7n6s pdf = PDF() pdf.add_page() pdf_path = # give path to where you want to save pdf pdf.sample_pdf(img,pdf_path)

更多推荐

使用pyfpdf将Base64图像插入pdf

本文发布于:2023-07-27 00:10:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1219165.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图像   pyfpdf   pdf

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!