## Print PDF from any Linux program

Related: convert image stack to PDF

On Linux, the
CUPS PDF
program saves printed PDFs to the `~/PDF`

directory from *any* program.

`apt install cups-pdf`

The output directory can be configured by editing the “Out” directory in `/etc/cups/cups-pdf.conf`

However, many times we print from Matlab, GNU Octave or Matplotlib using the APIs built-in as described below.

## Matlab / GNU Octave

Example to save figure to PDF: this will create a color PDF `test.pdf`

in your current directory from Matlab or Octave.

```
imagesc(rand(10))
print(gcf, '-dpdf', 'test.pdf')
```

or

```
imagesc(rand(10))
saveas(gcf, 'test.pdf')
```

Comparing print() vs. saveas():

- print() allows controlling image DPI via the
`-rDPI`

option, while saveas() is fixed at 150 DPI - saveas() is an “easier” version of print(), since saveas() is actually making calls to print() for both Matlab and Octave.

## Matplotlib

This can be accomplished by either

- save to PDF from the Matplotlib figure GUI
- use figure.savefig() to save to PDF from Matplotlib.

For situations where local display of figures is not desired, that is, you wish to save figures to disk without displaying them onscreen first, which is generally significantly faster, first do:

```
import matplotlib
matplotlib.use('Agg')
... (plotting commands)
```

The Agg Matplotlib backend is commonly used in web/cloud services.

Example:

```
from matplotlib.pyplot import figure
fg = figure()
ax = fg.gca()
ax.plot(range(10))
fg.savefig('line.pdf',bbox_inches='tight',dpi=300)
```