Reputation: 111
I am using Pandas to read data from some datafiles and generate a multiple-page pdf using PdfPages, in which each page contains the matplotlib figures from one datafile. It would be nice to be able to get a linked table of contents or bookmarks at each page, so that i can easily find figures corresponding to a given datafile . Is there a simple way to achieve this (for example by somehow inserting the name of the data file) in python 3.5?
Upvotes: 11
Views: 2511
Reputation: 341
A simple workaround using Pandoc.
import os
import numpy as np
import matplotlib.pyplot as plt
def draw_fig():
# a simple case of plotting matplotlib figures.
if not os.path.exists('fig'):
os.mkdir('fig')
x = np.linspace(0, 5, 100)
for i in range(1, 6):
y = x + i
plt.figure()
plt.plot(x, y)
plt.savefig(f'fig/fig{i}.png')
render
according to your requirements.class PdfTemplate():
def __init__(self, figs, filename="output", toc=True):
self.figs = figs
self.toc = toc
self.filename = filename
self.text = []
def render(self):
self._pagebreak()
for fig in self.figs:
self._h1(fig.split(".")[0])
self._img(os.path.join("fig", fig))
self._pagebreak()
self.text = "\n\n".join(self.text)
def export(self):
md_file = f"{self.filename}.md"
pdf_file = f"{self.filename}.pdf"
pandoc = ["pandoc", f"{md_file}", f"-o {pdf_file}"]
with open(md_file, "w") as f:
f.write(self.text)
if self.toc:
pandoc.append("--toc")
os.system(" ".join(pandoc))
def _pagebreak(self):
self.text.append("\pagebreak")
def _h1(self, text):
self.text.append(f"# {text}")
def _img(self, img):
self.text.append(f"![]({img})")
draw_fig()
pdf = PdfTemplate(figs=os.listdir("fig"))
pdf.render()
pdf.export()
Upvotes: 1
Reputation: 57
If you create one PDF per figure, then you can use PyPDF2 to merge them with bookmarks.
Here is the link to the documentation: PdfFileMerger.addBookmark
Upvotes: 0
Reputation: 411
What I do sometimes is generate a HTML file with my tables as I want and after I convert to PDF file. I know this is a little harder but I can control any element on my documents. Logically, this is not a good solution if you want write many files. Another good solution is make PDF from Jupyter Notebook.
Upvotes: 0
Reputation: 20450
It sounds like you want to generate fig{1, 2, ..., N}.pdf and then generate a LaTeX source file which mentions an \includegraphics
for each of them, and produces a ToC. If you do scratch this particular itch, consider packaging it up for others to use, as it is a pretty generic use case.
Upvotes: 0