在使用PdfPages生成的多页pdf中插入目录的简单方法

时间:2017-02-13 15:06:23

标签: python python-3.x pandas pdf matplotlib

我正在使用Pandas从一些数据文件中读取数据并使用PdfPages生成多页pdf,其中每个页面包含来自一个数据文件的matplotlib数字。能够在每个页面上获得链接的目录或书签会很好,这样我就可以轻松找到与给定数据文件相对应的数字。有没有一种简单的方法来实现这一点(例如通过以某种方式插入数据文件的名称)在python 3.5中?

4 个答案:

答案 0 :(得分:1)

使用Pandoc的简单解决方法。

  1. 首先导入几个必要的库。
import os
import numpy as np
import matplotlib.pyplot as plt
  1. 画一些数字。
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')
  1. 创建Markdown模板。在此玩具示例中,每个页面包含一个由matplotlib导出的图形。您可以根据需要定制功能render
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})")
  1. 最后,运行代码并导出pdf。
draw_fig()
pdf = PdfTemplate(figs=os.listdir("fig"))
pdf.render()
pdf.export()

内容页面: Contents page

图页: Figure page

答案 1 :(得分:0)

听起来您想生成fig {1、2,...,N} .pdf,然后生成一个LaTeX源文件,其中每个文件都提到一个\includegraphics,并生成ToC。如果您确实碰到了这种特殊的痒,请考虑将其打包以供其他人使用,因为这是一个非常通用的用例。

答案 2 :(得分:0)

有时候,我要做的就是根据需要在生成表格后将HTML文件转换为PDF文件。我知道这有点难,但是我可以控制文档中的任何元素。从逻辑上讲,如果要写入许多文件,这不是一个好的解决方案。另一个很好的解决方案是从Jupyter Notebook创建PDF。

答案 3 :(得分:0)

如果每个图形创建一个PDF,则可以使用PyPDF2将它们与书签合并。

以下是文档的链接:PdfFileMerger.addBookmark