7

3

There have been a couple of questions about incorporating labels and equations that were typeset in $\LaTeX$ into a *Mathematica* notebook. Ideally, this requires running `pdflatex`

(or `latex`

) from within *Mathematica* and then importing the generated `PDF`

document.

Unfortunately, importing of `PDF`

is known to be buggy, as discussed in these questions (among others, probably):

- Mathematica PDF import and fonts
- Difficulties with Importing PDFs in Mathematica
- Combine multiple PDF files into one document
- What kind of PDF files that MMA does not read (import)

The last two also mention `ghostscript`

as the way to solve some of the issues, in particular using the `pdfwrite`

device to re-generate a new `PDF`

from existing ones.

This could be used in a $\LaTeX$ workflow like this (I am assuming **Mac OS X** here):

```
Export["words.tex", "\n\\nonstopmode
\\documentclass[12pt]{article}
\\begin{document}\n
here\\qquad we\\qquad go
\\end{document}\n
", "Text"];
Run["pdflatex words"]
(* ==> 0 *)
Import["words.pdf"]
```

`Import::general: Expected cross reference table >>`

`Import::general: Expected cross reference table >>`

`Import::general: Could not find document trailer >>`

`General::stop:`

As was to be expected, here we get error messages similar to what the second question referenced above saw. So now try the `ghostscript`

workaround. Since this question aims at using $\LaTeX$, by assumption we have a working $\TeX$ installation which nowadays includes `ghostscript`

, so the following will be able to execute:

```
Run["gs -sDEVICE=pdfwrite -dNOCACHE \
-sOutputFile=words-nofont.pdf -q -dBatch -dNOPAUSE words.pdf -c quit"]
(* ==> 0 *)
Import["words-nofont.pdf"]
```

But the imported `PDF`

has incorrect spacings between the words. It should (as you can tell from the `\\qquad`

in the source) look more like

$\text{Here}\qquad \text{we}\qquad \text{go}$

This is just a somewhat artificial example illustrating the general problem of incorrect lengths and fonts upon import of a `PDF`

.

So the question is, how can one fix this, either by using $\TeX$ and its companion utilities differently, or by relying only on *Mathematica*'s capabilities? If this can be done, then it will be possible to automate the generation of $\LaTeX$ labels etc. from within *Mathematica*.

I'll post my answer based on `ghostscript`

below, hoping that eventually someone will come up with a fix for `PDF`

import that doesn't require external software.

I can't believe that even after writing MaTeX, I never noticed this thread before! – Szabolcs – 2017-03-09T21:42:53.617