我使用python中的pyfpdf来生成pdf文件。我有一个Base64,我想插入到一个pdf文件,而不必将它作为图像保存在我的文件系统。但是pyfpdf图像函数只接受文件路径。
fpdf.image(name, x = None, y = None, w = 0, h = 0, type = '', link = '')有没有一种直接从内存中插入base64或缓冲图像的方法(黑客),而不必事先保存到文件系统中?我甚至在github上查看了他们的源代码,却搞不清楚。
发布于 2017-11-13 11:36:09
正如注释中提到的@pvg,用load_resource功能覆盖base64函数是很有意义的。
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) 发布于 2020-04-07 18:18:33
我最近一直面临着这个问题,Uchiha Madara的回答在我的案例中行不通,所以我用一种稍微不同的方式解决了这个问题。当我用Uchiha的方法尝试它时,如果您提供一个图像而不修改代码(没有FileNotFound函数),我就会犯相同的load_resource错误。因为我真的需要一个解决方案,而且没有办法解决,所以我查看了模块代码,这些代码可以在
C:/Users/user/AppData/Local/Programs/Python/Python38/Lib/site-packages/fpdf/fpdf.py
如果您四处看看,您会注意到图像是通过_parsepng函数导入的。因此,我们需要编辑它来接受base64数据字符串。
基本上,您需要做些什么来修复它:
在函数中,您需要在顶部添加一个elif,以检查"filename“是否包含一个指示它是base64的字符串,并且您需要导入两个新模块。
复制并粘贴下面的第一个if-语句以检查URL:
elif "data:image/png;base64" in name:
f = name.split('base64,')[1]
f = base64.b64decode(f)
f = io.BytesIO(f)这只是查找字符串,这是典型的每一个base64 64编码的图像,如果它在那里,并解码它。
您需要在脚本顶部导入base64和io模块,所以只需通过
import base64, io现在,您只需像您通常所做的那样,将您的base64字符串作为文件路径提供,并且它应该可以工作(在我用python3.8进行的测试中)。
如果您有任何问题,请与我联系,希望今后能帮助一些人阅读。
https://stackoverflow.com/questions/47195075
复制相似问题