Skip to content

Implement PdfPages for backend pgf #10548

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 26 commits into from
Feb 28, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ result_images

# Nose/Pytest generated files #
###############################
.pytest_cache/
.cache/
.coverage
.coverage.*
Expand Down
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ addons:
- texlive-latex-extra
- texlive-latex-recommended
- texlive-xetex
- texlive-luatex

env:
global:
Expand Down
4 changes: 4 additions & 0 deletions doc/faq/howto_faq.rst
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,10 @@ Finally, the multipage pdf object has to be closed::

pp.close()

The same can be done using the pgf backend::

from matplotlib.backends.backend_pgf import PdfPages


.. _howto-subplots-adjust:

Expand Down
19 changes: 19 additions & 0 deletions doc/users/next_whats_new/pgf_pdfpages.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Multipage PDF support for pgf backend
-------------------------------------

The pgf backend now also supports multipage PDF files.

.. code-block:: python

from matplotlib.backends.backend_pgf import PdfPages
import matplotlib.pyplot as plt

with PdfPages('multipage.pdf') as pdf:
# page 1
plt.plot([2, 1, 3])
pdf.savefig()

# page 2
plt.cla()
plt.plot([3, 1, 2])
pdf.savefig()
10 changes: 5 additions & 5 deletions doc/users/whats_new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ revision, see the :ref:`github-stats`.
..
For a release, add a new section after this, then comment out the include
and toctree below by indenting them. Uncomment them after the release.
.. include:: next_whats_new/README.rst
.. toctree::
:glob:
:maxdepth: 1
.. include:: next_whats_new/README.rst
.. toctree::
:glob:
:maxdepth: 1

next_whats_new/*
next_whats_new/*


New in Matplotlib 2.2
Expand Down
4 changes: 4 additions & 0 deletions examples/misc/multipage_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@

This is a demo of creating a pdf file with several pages,
as well as adding metadata and annotations to pdf files.

If you want to use a multipage pdf file using LaTeX, you need
to use `from matplotlib.backends.backend_pgf import PdfPages`.
This version however does not support `attach_note`.
"""

import datetime
Expand Down
238 changes: 237 additions & 1 deletion lib/matplotlib/backends/backend_pgf.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,15 @@
import weakref

import matplotlib as mpl
from matplotlib import _png, rcParams
from matplotlib import _png, rcParams, __version__
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase,
RendererBase)
from matplotlib.backends.backend_mixed import MixedModeRenderer
from matplotlib.cbook import is_writable_file_like
from matplotlib.path import Path
from matplotlib.figure import Figure
from matplotlib._pylab_helpers import Gcf


###############################################################################
Expand All @@ -50,13 +52,30 @@
warnings.warn('error getting fonts from fc-list', UserWarning)


_luatex_version_re = re.compile(
'This is LuaTeX, Version (?:beta-)?([0-9]+)\.([0-9]+)\.([0-9]+)'
)


def get_texcommand():
"""Get chosen TeX system from rc."""
texsystem_options = ["xelatex", "lualatex", "pdflatex"]
texsystem = rcParams["pgf.texsystem"]
return texsystem if texsystem in texsystem_options else "xelatex"


def _get_lualatex_version():
"""Get version of luatex"""
output = subprocess.check_output(['lualatex', '--version'])
return _parse_lualatex_version(output.decode())


def _parse_lualatex_version(output):
'''parse the lualatex version from the output of `lualatex --version`'''
match = _luatex_version_re.match(output)
return tuple(map(int, match.groups()))


def get_fontspec():
"""Build fontspec preamble from rc."""
latex_fontspec = []
Expand Down Expand Up @@ -990,4 +1009,221 @@ def _cleanup_all():
LatexManager._cleanup_remaining_instances()
TmpDirCleaner.cleanup_remaining_tmpdirs()


atexit.register(_cleanup_all)


class PdfPages:
"""
A multi-page PDF file using the pgf backend

Examples
--------

>>> import matplotlib.pyplot as plt
>>> # Initialize:
>>> with PdfPages('foo.pdf') as pdf:
... # As many times as you like, create a figure fig and save it:
... fig = plt.figure()
... pdf.savefig(fig)
... # When no figure is specified the current figure is saved
... pdf.savefig()
"""
__slots__ = (
'_outputfile',
'keep_empty',
'_tmpdir',
'_basename',
'_fname_tex',
'_fname_pdf',
'_n_figures',
'_file',
'metadata',
)

def __init__(self, filename, *, keep_empty=True, metadata=None):
"""
Create a new PdfPages object.

Parameters
----------

filename : str
Plots using :meth:`PdfPages.savefig` will be written to a file at
this location. Any older file with the same name is overwritten.
keep_empty : bool, optional
If set to False, then empty pdf files will be deleted automatically
when closed.
metadata : dictionary, optional
Information dictionary object (see PDF reference section 10.2.1
'Document Information Dictionary'), e.g.:
`{'Creator': 'My software', 'Author': 'Me',
'Title': 'Awesome fig'}`

The standard keys are `'Title'`, `'Author'`, `'Subject'`,
`'Keywords'`, `'Producer'`, `'Creator'` and `'Trapped'`.
Values have been predefined for `'Creator'` and `'Producer'`.
They can be removed by setting them to the empty string.
"""
self._outputfile = filename
self._n_figures = 0
self.keep_empty = keep_empty
self.metadata = metadata or {}

# create temporary directory for compiling the figure
self._tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_pdfpages_")
self._basename = 'pdf_pages'
self._fname_tex = os.path.join(self._tmpdir, self._basename + ".tex")
self._fname_pdf = os.path.join(self._tmpdir, self._basename + ".pdf")
self._file = open(self._fname_tex, 'wb')

def _write_header(self, width_inches, height_inches):
supported_keys = {
'title', 'author', 'subject', 'keywords', 'creator',
'producer', 'trapped'
}
infoDict = {
'creator': 'matplotlib %s, https://matplotlib.org' % __version__,
'producer': 'matplotlib pgf backend %s' % __version__,
}
metadata = {k.lower(): v for k, v in self.metadata.items()}
infoDict.update(metadata)
hyperref_options = ''
for k, v in infoDict.items():
if k not in supported_keys:
raise ValueError(
'Not a supported pdf metadata field: "{}"'.format(k)
)
hyperref_options += 'pdf' + k + '={' + str(v) + '},'

latex_preamble = get_preamble()
latex_fontspec = get_fontspec()
latex_header = r"""\PassOptionsToPackage{{
{metadata}
}}{{hyperref}}
\RequirePackage{{hyperref}}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

any reason why it's not a standard "usepackage[...]{hyperref}"? (perhaps, I dunno)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because People might use hyperref in their rc params latex header and like this it avoids the "hyperref loaded with incompatible options" error

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so that's equivalent to "if hyperref is already loaded by the preamble, then merge these options with those passed in the preamble"? (again, just asking)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, and the user specified options take precedence.

\documentclass[12pt]{{minimal}}
\usepackage[
paperwidth={width}in,
paperheight={height}in,
margin=0in
]{{geometry}}
{preamble}
{fontspec}
\usepackage{{pgf}}
\setlength{{\parindent}}{{0pt}}

\begin{{document}}%%
""".format(
width=width_inches,
height=height_inches,
preamble=latex_preamble,
fontspec=latex_fontspec,
metadata=hyperref_options,
)
self._file.write(latex_header.encode('utf-8'))

def __enter__(self):
return self

def __exit__(self, exc_type, exc_val, exc_tb):
self.close()

def close(self):
"""
Finalize this object, running LaTeX in a temporary directory
and moving the final pdf file to `filename`.
"""
self._file.write(rb'\end{document}\n')
self._file.close()

if self._n_figures > 0:
try:
self._run_latex()
finally:
try:
shutil.rmtree(self._tmpdir)
except:
TmpDirCleaner.add(self._tmpdir)
elif self.keep_empty:
open(self._outputfile, 'wb').close()

def _run_latex(self):
texcommand = get_texcommand()
cmdargs = [
str(texcommand),
"-interaction=nonstopmode",
"-halt-on-error",
os.path.basename(self._fname_tex),
]
try:
subprocess.check_output(
cmdargs, stderr=subprocess.STDOUT, cwd=self._tmpdir
)
except subprocess.CalledProcessError as e:
raise RuntimeError(
"%s was not able to process your file.\n\nFull log:\n%s"
% (texcommand, e.output.decode('utf-8')))

# copy file contents to target
shutil.copyfile(self._fname_pdf, self._outputfile)

def savefig(self, figure=None, **kwargs):
"""
Saves a :class:`~matplotlib.figure.Figure` to this file as a new page.

Any other keyword arguments are passed to
:meth:`~matplotlib.figure.Figure.savefig`.

Parameters
----------

figure : :class:`~matplotlib.figure.Figure` or int, optional
Specifies what figure is saved to file. If not specified, the
active figure is saved. If a :class:`~matplotlib.figure.Figure`
instance is provided, this figure is saved. If an int is specified,
the figure instance to save is looked up by number.
"""
if not isinstance(figure, Figure):
if figure is None:
manager = Gcf.get_active()
else:
manager = Gcf.get_fig_manager(figure)
if manager is None:
raise ValueError("No figure {}".format(figure))
figure = manager.canvas.figure

try:
orig_canvas = figure.canvas
figure.canvas = FigureCanvasPgf(figure)

width, height = figure.get_size_inches()
if self._n_figures == 0:
self._write_header(width, height)
else:
self._file.write(self._build_newpage_command(width, height))

figure.savefig(self._file, format="pgf", **kwargs)
self._n_figures += 1
finally:
figure.canvas = orig_canvas

def _build_newpage_command(self, width, height):
'''LuaLaTeX from version 0.85 removed the `\pdf*` primitives,
so we need to check the lualatex version and use `\pagewidth` if
the version is 0.85 or newer
'''
texcommand = get_texcommand()
if texcommand == 'lualatex' and _get_lualatex_version() >= (0, 85, 0):
cmd = r'\page'
else:
cmd = r'\pdfpage'

newpage = r'\newpage{cmd}width={w}in,{cmd}height={h}in%' + '\n'
return newpage.format(cmd=cmd, w=width, h=height).encode('utf-8')

def get_pagecount(self):
"""
Returns the current number of pages in the multipage pdf file.
"""
return self._n_figures
Loading