Output a Document (preferably a PDF) from Python

2019-09-06 03:02发布

I've got a Python script (3.5) that will go through a whole battery of tests. The user gets to select which tests get run out of N possible tests. So, the user could run 1 tests up to N tests.

Right now, I'm just outputting the results of the test to a plot with matplotlib and that looks OK, but they're just saved as individual files. Also, the code has some PASS/FAIL criteria for each test.

So, the issue is, I would like to use some tool with Python to output the whole story of the test sequence as a PDF. I'd like to be able to keep some Boiler-Plate stuff and update some stuff in the middle....For example:

Test was run for 7 minutes. Maximum power was recorded as -69.5dBm. Graph The thing that is the same each time is:

Test was run for minutes. Maximum power was recorded as dBm.

And, the number of minutes and the number for maximum power is pulled in from the results of the test. Also, the graph is pulled in from 'matplotlib'.

So, for each test, I'd like to append some Boiler-plate text, fill in some blanks with real data, and slap in an image where appropriate, and I'd like to do it with Python.

I looked at some of the suggestions on SO, but for the most part it looks like the solutions are for appending or watermarking existing PDFs. Also, Google turns up a lot of results for automating the generation of Python Code Documentation...Not Code for generating Documentation with Python.

Reportlab looked promising, but it looks like it's been abandoned.

Also, I'm not married to the requirement that the output be a PDF. This is for internal use only, so there's some flexability. HTML, Word or something else that can be converted to a PDF manually by the user afterwards is fine too. I know PDFs can be somewhat troublesome due to their binary nature.

1条回答
放荡不羁爱自由
2楼-- · 2019-09-06 04:08

You can do all of this directly in matplotlib. It is possible to create several figures and afterwards save them all to the same pdf document using matplotlib.backends.backend_pdf.PdfPages.
The text can be set using the text() command.

Here is a basic example on how that would work.

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

N=10
text =  "The maximum is {}, the minimum is {}"

# create N figures
for i in range(N):
    data = np.random.rand(28)
    fig = plt.figure(i+1)
    ax= fig.add_subplot(111)
    ax.plot(np.arange(28), data)
    # add some text to the figure
    ax.text(0.1, 1.05,text.format(data.max(),data.min()), transform=ax.transAxes)

# Saving all figures to the same pdf
pp = PdfPages('multipage.pdf')
for i in range(N):
    fig = plt.figure(i+1)
    fig.savefig(pp, format='pdf')
pp.close()
查看更多
登录 后发表回答