Programmatic wrapper around ReportLab. reportlab 的一个包装库
https://github.com/matthiask/pdfdocument/
https://pypi.org/project/pdfdocument/
使用
from io import BytesIO
from pdfdocument.document import PDFDocument, register_fonts_from_paths
from reportlab.platypus.flowables import Image
def say_hello():
f = BytesIO()
register_fonts_from_paths("SimSun.ttf", font_name="SimSun")
pdf = PDFDocument(f)
pdf.init_report()
pdf.generate_style(font_name="SimSun")
pdf.h1('Hello World')
pdf.spacer()
img_file = "./img/img.png"
img = Image(img_file, width=400, height=300)
pdf.append(img)
pdf.spacer()
for i in range(100):
pdf.p("你好, 世界! reating PDFs made easy.")
pdf.generate()
return f.getvalue()
if __name__ == "__main__":
with open("test4.pdf", "wb") as f:
pdf = say_hello()
f.write(pdf)
# canPdf()
pass
图片操作
从string.io导入
import sys
import PIL
from cStringIO import StringIO
from reportlab.platypus.flowables import Image
# Method 1
data = open(sys.argv[1]).read()
img1 = StringIO(data)
# Method 2
img2 = StringIO()
PIL.Image.open(sys.argv[2]).save(img2, 'PNG')
img2.seek(0)
# Method 3 (fails)
img3 = StringIO(PIL.Image.open(sys.argv[2]).tostring())
story = [Image(img1), Image(img2)]
#Image(img3)
参考
simsun 下载 https://github.com/StellarCN/scp_zh/blob/master/fonts/SimSun.ttf
图片操作 https://blog.devzeng.com/blog/python-convert-images-to-pdf.html
从 PIL 图像或 StringIO 将图像插入 Reportlab https://stackoverflow.com/questions/13953659/insert-image-into-reportlab-either-from-pil-image-or-stringio