多页PDF

这是一个创建包含多个页面的pdf文件,以及向pdf文件添加元数据和注释的演示。

如果要使用LaTeX使用多页pdf文件,则需要使用 matplotlib.backends.backend_pgf 导入PdfPages。 但是这个版本不支持 attach_note

  1. import datetime
  2. import numpy as np
  3. from matplotlib.backends.backend_pdf import PdfPages
  4. import matplotlib.pyplot as plt
  5. # Create the PdfPages object to which we will save the pages:
  6. # The with statement makes sure that the PdfPages object is closed properly at
  7. # the end of the block, even if an Exception occurs.
  8. with PdfPages('multipage_pdf.pdf') as pdf:
  9. plt.figure(figsize=(3, 3))
  10. plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
  11. plt.title('Page One')
  12. pdf.savefig() # saves the current figure into a pdf page
  13. plt.close()
  14. # if LaTeX is not installed or error caught, change to `usetex=False`
  15. plt.rc('text', usetex=True)
  16. plt.figure(figsize=(8, 6))
  17. x = np.arange(0, 5, 0.1)
  18. plt.plot(x, np.sin(x), 'b-')
  19. plt.title('Page Two')
  20. pdf.attach_note("plot of sin(x)") # you can add a pdf note to
  21. # attach metadata to a page
  22. pdf.savefig()
  23. plt.close()
  24. plt.rc('text', usetex=False)
  25. fig = plt.figure(figsize=(4, 5))
  26. plt.plot(x, x ** 2, 'ko')
  27. plt.title('Page Three')
  28. pdf.savefig(fig) # or you can pass a Figure object to pdf.savefig
  29. plt.close()
  30. # We can also set the file's metadata via the PdfPages object:
  31. d = pdf.infodict()
  32. d['Title'] = 'Multipage PDF Example'
  33. d['Author'] = 'Jouni K. Sepp\xe4nen'
  34. d['Subject'] = 'How to create a multipage pdf file and set its metadata'
  35. d['Keywords'] = 'PdfPages multipage keywords author title subject'
  36. d['CreationDate'] = datetime.datetime(2009, 11, 13)
  37. d['ModDate'] = datetime.datetime.today()

下载这个示例