我在python中使用pyfpdf生成pdf文件。我有一个Base64,我想将它插入pdf文件,而不必将其另存为文件系统中的图像。但是pyfpdf图片功能仅接受文件路径。
fpdf.image(name, x = None, y = None, w = 0, h = 0, type = '', link = '')
有没有一种方法(破解)直接从内存中插入base64或缓冲的图像,而不必事先保存到文件系统中?我什至在github上检查了它们的源代码,无法确定。
正如注释中提到的@pvg一样,用base64功能覆盖load_resource功能可以解决问题。
import base64,io
def load_resource(self, reason, filename):
if reason == "image":
if filename.startswith("http://") or filename.startswith("https://"):
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的示例代码。我在代码中注释了一些说明。
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("http://") or filename.startswith("https://"):
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 : https://pastebin.com/CaZJ7n6s
pdf = PDF()
pdf.add_page()
pdf_path = # give path to where you want to save pdf
pdf.sample_pdf(img,pdf_path)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句