Programmatic wrapper around ReportLab. reportlab 的一个包装库
https://github.com/matthiask/pdfdocument/
https://pypi.org/project/pdfdocument/

使用

  1. from io import BytesIO
  2. from pdfdocument.document import PDFDocument, register_fonts_from_paths
  3. from reportlab.platypus.flowables import Image
  4. def say_hello():
  5. f = BytesIO()
  6. register_fonts_from_paths("SimSun.ttf", font_name="SimSun")
  7. pdf = PDFDocument(f)
  8. pdf.init_report()
  9. pdf.generate_style(font_name="SimSun")
  10. pdf.h1('Hello World')
  11. pdf.spacer()
  12. img_file = "./img/img.png"
  13. img = Image(img_file, width=400, height=300)
  14. pdf.append(img)
  15. pdf.spacer()
  16. for i in range(100):
  17. pdf.p("你好, 世界! reating PDFs made easy.")
  18. pdf.generate()
  19. return f.getvalue()
  20. if __name__ == "__main__":
  21. with open("test4.pdf", "wb") as f:
  22. pdf = say_hello()
  23. f.write(pdf)
  24. # canPdf()
  25. pass

image.png
reportlab-userguide.pdf

图片操作

从string.io导入

  1. import sys
  2. import PIL
  3. from cStringIO import StringIO
  4. from reportlab.platypus.flowables import Image
  5. # Method 1
  6. data = open(sys.argv[1]).read()
  7. img1 = StringIO(data)
  8. # Method 2
  9. img2 = StringIO()
  10. PIL.Image.open(sys.argv[2]).save(img2, 'PNG')
  11. img2.seek(0)
  12. # Method 3 (fails)
  13. img3 = StringIO(PIL.Image.open(sys.argv[2]).tostring())
  14. story = [Image(img1), Image(img2)]
  15. #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