Creating a Multipage PDF With Matplotlib

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to create a multipage PDF file with Python Matplotlib. The PDF file will contain several pages with different plots and metadata. You will also learn how to attach annotations to the PDF file.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/BasicConceptsGroup -.-> matplotlib/saving_figures("`Saving Figures to File`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") matplotlib/PlotCustomizationGroup -.-> matplotlib/titles_labels("`Adding Titles and Labels`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/custom_backends("`Custom Backends`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/matplotlib_config("`Customizing Matplotlib Configurations`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/date_time("`Date and Time`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} python/with_statement -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} matplotlib/figures_axes -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} matplotlib/saving_figures -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} matplotlib/line_plots -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} matplotlib/titles_labels -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} matplotlib/custom_backends -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} matplotlib/matplotlib_config -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} python/variables_data_types -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} python/booleans -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} python/lists -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} python/tuples -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} python/importing_modules -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} python/using_packages -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} python/standard_libraries -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} python/date_time -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} python/data_collections -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} python/numerical_computing -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} python/data_visualization -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} python/build_in_functions -.-> lab-48839{{"`Creating a Multipage PDF With Matplotlib`"}} end

Import Libraries

First, you need to import the necessary libraries for creating the PDF file. In this lab, we will use Matplotlib and datetime libraries.

import datetime
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages

Create the PdfPages Object

Next, you need to create a PdfPages object to which you will save the pages of the PDF file. You can use the 'with' statement to make sure that the PdfPages object is closed properly at the end of the block, even if an exception occurs.

with PdfPages('multipage_pdf.pdf') as pdf:

Create the First Page

In this step, you will create the first page of the PDF file. The page will contain a plot of a simple graph.

plt.figure(figsize=(3, 3))
plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
plt.title('Page One')
pdf.savefig()
plt.close()

Create the Second Page

In this step, you will create the second page of the PDF file. The page will contain a plot of a sine wave.

plt.rcParams['text.usetex'] = True
plt.figure(figsize=(8, 6))
x = np.arange(0, 5, 0.1)
plt.plot(x, np.sin(x), 'b-')
plt.title('Page Two')
pdf.attach_note("plot of sin(x)")  ## attach metadata (as pdf note) to page
pdf.savefig()
plt.close()

Create the Third Page

In this step, you will create the third page of the PDF file. The page will contain a plot of a parabola.

plt.rcParams['text.usetex'] = False
fig = plt.figure(figsize=(4, 5))
plt.plot(x, x ** 2, 'ko')
plt.title('Page Three')
pdf.savefig(fig)  ## or you can pass a Figure object to pdf.savefig
plt.close()

Set the Metadata of the PDF File

In this step, you will set the metadata of the PDF file. You can set the title, author, subject, keywords, and creation/modification date of the PDF file.

d = pdf.infodict()
d['Title'] = 'Multipage PDF Example'
d['Author'] = 'Jouni K. Sepp\xe4nen'
d['Subject'] = 'How to create a multipage pdf file and set its metadata'
d['Keywords'] = 'PdfPages multipage keywords author title subject'
d['CreationDate'] = datetime.datetime(2009, 11, 13)
d['ModDate'] = datetime.datetime.today()

Summary

In this lab, you learned how to create a multipage PDF file with Python Matplotlib. You also learned how to attach metadata and annotations to the PDF file. You can use these techniques to create professional reports with multiple plots and annotations.

Other Python Tutorials you may like