246

I need to convert my LaTeX documents into PNG. The problem is, I also need the resulting image to be as short as possible (height-wise). I've tried latex followed by dvipng, but the result is always the size of a page. For instance, take a .tex file containing:

\documentclass{article}  
\begin{document}  
Hello. This is a test.
\begin{equation}
  L = 2                                                                     
\end{equation}  
\end{document}

If I compile it with latex, and then run dvipng, I get a PNG file that's the size of a full page. What I need is for the PNG file to be only as tall as needed for everything to fit. So the image would end immediately after the equation. The image still needs to have full width (because of the equation numbering).

Is there a way to achieve that?

lockstep
  • 250,273
Malabarba
  • 6,972
  • Why do you want to do this? If it's to serve them on a web page inlined with text, try MathJax instead. – Matthew Leingang Feb 23 '11 at 18:34
  • 4
    @matthew: It's to insert inside a word document. – Malabarba Feb 23 '11 at 18:48
  • 75
    @Bruce: Ah. My sympathies. :-) – Matthew Leingang Feb 23 '11 at 20:32
  • @Bruce: Years ago I tested a plugin for Word which allowed you to enter equations as LaTeX code. It was running latex in the background and converted it to a PNG by itself. The result was a nice picture, but the LaTeX code could be changed anytime. I can't recall the name but you should find it using Google with the right keywords. – Martin Scharrer Feb 23 '11 at 20:37
  • 5
    @Bruce: Something like: http://texpoint.necula.org/ or http://www.dessci.com/en/products/mathtype/ – Martin Scharrer Feb 23 '11 at 20:40
  • @Martin: That's interesting, I'll keep it mind next time. I did try a tex2doc converter which kept crashing on the fourth page (probably because of the amount of equations), but I haven't actually tried a plugin that works inside MSWord. – Malabarba Feb 23 '11 at 22:10
  • 3
    Try this: http://sourceforge.net/projects/texsword/ – amorua Nov 12 '11 at 16:32
  • @MatthewLeingang: MathJax is not a standards-based approach, it's a (beautifully executed) gigantic hack to work around IE's lack of an implementation for mathml without a plugin that most users will never install. The standards-based approaches would be a bitmapped image or mathml. –  Mar 10 '13 at 19:26
  • I am quite surprised that no one has mentioned simple screenshotting of the pdf. That way one can see how the actual output looks, with all the differences rendering of different pdf viewers. Just enlarge the portion of the pdf which you want to image to full screen size and then screenshot it so as to get the maximum resolution possible. The size of the images can be adjusted manually. – Apoorv Potnis Jan 25 '22 at 11:45
  • @ApoorvPotnis First, taking screenshot is rather obvious solution, so it hardly needs to be mentioned. Also, taking screenshot only works if your screen resolution is larger than the image size you need. It is not something that needs to be mentioned. – Dalija Prasnikar Jan 25 '22 at 12:06

15 Answers15

330

You can use the standalone class for this. It loads the preview package automatically to crop the resulting PDF to the content. This makes the usage of pdfcrop unnecessary.

Simply exchange the article class with standalone. (It uses article internally but another class can be specified using the class option.) Note that since v1.0 the default option has been changed from preview to crop. The latter is better for pictures etc. but doesn't support line breaks. Either select preview manually or use the varwidth option.

\documentclass[preview]{standalone}
\begin{document}
Hello. This is a test.
\begin{equation}
L = 2
\end{equation}
\end{document}

There is a border class option which sets the border around the content (the default is 0.5bp). This option accepts one (border for all sides), two (left/right, top/bottom) or four values (left, bottom, right, top).

To convert it to a PNG I recommend to use the convert command of Image Magick:

pdflatex file
convert -density 300 file.pdf -quality 90 file.png

Here the density is 300 DPI which can be adapted to your needs. The quality setting selects the compression level and other things and 90 is AFAIK the optimum.

You can also select the DPI resolution for X and Y separately and also resize the resulting image, e.g.:

convert -density 600x600 file.pdf -quality 90 -resize 1080x800 file.png

Update 2011/12/21:

The new version 1.0 standalone now has the ability to call the above command line (and others) automatically, e.g.:

\documentclass[convert={density=300,size=1080x800,outext=.png}]{standalone}

or simply (using default setting 300dpi, no resizing, PNG):

\documentclass[convert]{standalone}

This needs the -shell-escape compiler option to allow the execution of the conversion program from within the LaTeX document.

SdaliM
  • 103
Martin Scharrer
  • 262,582
  • 5
    Matin, this seem extremely useful. Any idea as to when this will be released? I'd like to do something very similar, except only specify a minimum height for the page (and allow it to grow beyond that if needed), I still want the width of the PNG fixed. – Peter Grill May 05 '11 at 06:20
  • Another +1 (I didn't know the standalone class allows to pass ImageMagick command). – chl Nov 10 '11 at 12:37
  • @chl: Well, the develop version does. The current stable version on CTAN doesn't include this yet. – Martin Scharrer Nov 10 '11 at 12:57
  • Is invoking GhostScript directly more efficient than invoking ImageMagick's convert in this case? – kiss my armpit Dec 21 '11 at 17:08
  • @CounterTerrorist: Both is supported. IMHO, Image Magick provides a nicer interface and supports more output formats (like GIFs, even animated ones). However, it will call Ghostscript in the background, AFAIK. – Martin Scharrer Dec 21 '11 at 19:08
  • 2
    Regarding "90 is optimum" — from my reading of the ImageMagick docs, it sounds like the convert option -quality sets the compression level for PNG images. Since PNG is lossless, this only affects the file size, not image quality. http://www.imagemagick.org/script/command-line-options.php#quality – Todd Lehman Feb 18 '12 at 09:17
  • @MartinScharrer: Is there a way to specify with this the anti-aliasing bit depth? I agree that convert has a much nicer interface than gs, but one of the things I love about gs is that it has -dTextAlphaBits and -dGraphicsAlphaBits. Another benefit of gs is that it supports -sDEVICE=pnmraw, which is really nice for doing stream postprocessing with the Netpbm tools, i.e., piping the output of gs to pnmcrop and then to pnmtopng. – Todd Lehman Feb 18 '12 at 09:25
  • @ToddLehman: Yes, for PNG the -quality number specifies the compression used. AFAIK 90 is the optimum, because it result in the smallest file size for the majority of files. I wasn't talking about optimal quality. About the anti-aliasing: Can't help you with this, I never looked at this options. – Martin Scharrer Feb 18 '12 at 09:48
  • According to preview manual, the default value is 0.50001bp. – kiss my armpit Mar 25 '12 at 20:05
  • @DamienWalters: Yes, the extra 0.00001bp is to avoid rounding issues, so that twice the amount is 1.0bp or more not lower. It doesn't make any practical difference, therefore I wasn't that accurate in my post. – Martin Scharrer Mar 25 '12 at 20:15
  • 3
    Great answer, thanks! I wrote a shellscript that takes care of all the repetitive wrapping and conversion stuff. Find it here and do whatever GPL3 allows you to do with it. – Raphael Mar 29 '12 at 11:41
  • 1
    @Raphael: Thanks! That sounds great. I might update the question and add a link to your script. – Martin Scharrer Mar 29 '12 at 12:45
  • @MartinScharrer, somehow the density=300 setting does not take effect on PNG outputs. I opened a new question regarding this: http://tex.stackexchange.com/q/82599/791 – Kit Nov 13 '12 at 17:20
  • Note that 'convert -trim' crops to content. (You will still usually want to drop page numbers in the TeX itself.) – Mohan Dec 10 '12 at 07:19
  • @Mohan: the standalone class does disable the page numbers by default – Martin Scharrer Dec 10 '12 at 21:01
  • good tip using ImageMagick, however Ghostscript is also required to be executed properly – escalator Sep 20 '13 at 09:11
  • @MartinScharrer BugReport What I get is: 'imgconvert' is not recognized as an internal or external command, operable program or batch file. Seem sto me that imgconvert is not part of Image Magic. Workaround was to rename convert.exe in Image Magic directory to imgconvert.exe. – Pygmalion Sep 18 '15 at 19:10
  • 2
    @Pygmalion: Not a bug but a documented choice. convert is actually the Windows build-in to convert FAT32 to NTFS, so for safety I named it imgconvert and state in the manual that you need to rename the .exe of ImageMagick or the setting in standalone. – Martin Scharrer Sep 20 '15 at 15:32
  • 8
    I generally get better results with poppler's pdftoppm, the anti-aliasing is way better. pdftoppm -png -r 600 out.pdf > out.png – MaxNoe Feb 24 '16 at 11:24
  • would be nice to have example of shell escape in the answer as well as an example use of the border class – baxx Oct 23 '16 at 12:05
  • My pdf file consists of hundred pages, but I want to convert a few pages to images. How can we achieve this? – Say OL Oct 26 '16 at 19:16
  • 1
    @SayOL: You shouldn't use LaTeX for this. Use a tool like Ghostscript directly. Of course you could try using the pdfpages package together with standalone but I never tested if both work together. – Martin Scharrer Nov 02 '16 at 20:45
  • I hope it's not inappropriate to ping you here, but could you please have a look at this post. It seems that there is a typo in the manual of your great package. –  Mar 20 '18 at 16:47
  • It is better to convert image in command line, set "convert" option in standalone is a little slow, and it needs to enable -shell-escape. – biajia Nov 14 '20 at 16:04
  • is it possible to do this in Overleaf and getting a JPG / PNG output file ? – Muhammad Yasir Dec 08 '22 at 23:41
  • @MuhammadYasir: I cannot say as I do not use Overleaf. – Martin Scharrer Feb 07 '23 at 08:02
44

One thing that's easy to miss is page numbers. The page number restricts the height of the final image so it's best to leave it out. An easy way to do that is to use the empty page style.

What I do when doing images for this place is to have a document a bit like:

\documentclass{article}
\thispagestyle{empty}
\begin{document}
Hello. This is a test.
\begin{equation}
L = 2
\end{equation}
\end{document}

Then run pdflatex on it to get a PDF; next run pdfcrop (comes with TeXLive) to make it as small as possible; finally convert it to PNG using the NetPBM library tools. (This is on a Unix machine.) So my workflow is:

pdflatex document.tex
pdfcrop document.pdf
pdftoppm document-crop.pdf|pnmtopng > document.png

et voila:

small png

Andrew Stacey
  • 153,724
  • 43
  • 389
  • 751
  • Is there a way to fine tune the resolution in the third command? – Malabarba Feb 23 '11 at 18:40
  • 1
    @Bruce: The manpage for pdftoppm says that you can specify the resolution by using the argument -r RES. The default is 150DPI so experiment with that to find one that you like. – Andrew Stacey Feb 23 '11 at 22:04
  • 2
    You can merge the last two commands: pdftopnm doc.pdf | pnmcrop | pnmtopng > doc.png. – Paul Gaborit Aug 10 '12 at 00:14
  • 1
    @egreg Minimal class? What minimal class? But seriously, this was written over 5 years ago (and a year before the "universal" question about the minimal class was asked) when I was young and naïve. In this modern era, I use the standalone class for this task. Anyway, I've editted it to use the empty page style instead. Happy now?? – Andrew Stacey Nov 15 '16 at 18:07
  • @PaulGaborit I got an error 'pdftopnm' is not recognized as an internal or external command, what should I install on my Windows? – Diaa Jan 22 '18 at 02:16
  • 1
    @DiaaAbidou The correct command is pdftoppm (instead of pdftopnm). To install it, you can read How to install Poppler on Windows. – Paul Gaborit Jan 22 '18 at 05:47
  • I guess the mentioned "universal" question about the minimal class is this one. – TFulop Jul 25 '20 at 06:45
19

If you have a dvi file file.dvi, running dvipng -T tight file.dvi will produce a png with the image automatically cropped as much as possible. (You might also want to set the output resolution using the -D flag, as in dvipng -T tight -D 150 file.dvi for 150 dots per inch.)

As Andrew points out in his answer, getting rid of the page numbers is a good idea.

11

I had a few issues using the standalone package and ImageMagick. Running the

pdflatex -shell-escape file.tex

command did not generate the png file. I fixed this in two steps:

  1. Renaming the "convert.exe" file to "imgconvert.exe" in the ImageMagick folder (C:\Program Files\ImageMagick-6.9.0-Q16).
  2. Installing a newer version of Ghostview (direct link: http://sourceforge.net/projects/ghostscript/files/GPL%20Ghostscript/9.01/gs901w32.exe/download)

Before I did this I got errors saying that no conversion had happened:

Class standalone Warning: Conversion unsuccessful!
(standalone)              There might be something wrong with your
(standalone)              conversation software or the file permissions!

Earlier in the compilation was a line saying imgconvert was not a recognized command so that suggests that the standalone package expects the convert.exe file to be renamed (found that solution here:Conversion problem using standalone and imagemagick).

Renaming the file connected the standalone package and ImageMagick, but the Ghostview file "gswin32c.exe" stopped working every time I attempted a conversion. Installing a newer version solved that problem, as described here: http://freewarestyle.blogspot.com/2011/04/gswin32cexe-gswin32cexe-error-cutepdf.html

Just thought this could be useful for somebody else.

Edit If I may, I add that it might not be sufficient/necessary for the first step to rename the "convert.exe" file, you alternatively can add the directory within your editor search path where your ImageMagick is installed.

For example for TexStudio users, this is done by clicking on "Options -> Configure TexStudio" then click on tab "Build" and add the directory to the "Commands($PATH)".

Eric Jensen
  • 111
  • 1
  • 4
7

If you are on Linux, you can try pnglatex. It's pretty simple; to generate your formula you write

$ pnglatex -f "E=mc^2"

If the image was created using pnglatex you can also reverse the process.

$ pnglatex -r formula.png
E=mc^2

It supports piping. So, assuming formula.tex is a text file containing your formula, you can generate and open your image with a one-liner.

cat formula.tex | pnglatex | xargs eog

It has a number of options:

-b <color>       Set the background color
-B <color>       Set the border color
-d <dpi>         Set the output resolution to the specified dpi
-e <environment> Set the environment for the formula (i.e. displaymath or eqnarray)
-f <formula>     The LaTeX formula
-F <color>       Set the foreground color
-h               Print the help message
-H <header>      Input file in header
-l <file>        Log file
-m <margin>      Set the margin
-M               Strip meta information
-o <file>        Specify the output file name
-O               Optimize the image
-p <packages>    A colon separated list of LaTeX package names
-P <padding>     Set the padding
-r <file>        Read an image and print the LaTeX formula
-s <size>        Set the font size
-S               Don't print image file name
-v               Show version
mneri
  • 261
6

If you have access to an Apple computer, I highly recommend LaTeXiT, which exports formulas as PNG. If you're on a Mac it's included in MacTeX...

Habi
  • 7,694
5

i use this technique to prepare examples for posting to tex.sx, but it could presumably be used for any situation in which a small .png file is needed.

  • create a dedicated input file, limiting the input to exactly what should be in the example. be sure to specify \thispagestyle{empty} (after \begin{document}).
    the input file i use is just a cut-down version of whatever document the example is extracted from; i haven't had good luck with standalone or other "minimal" classes.
  • run pdflatex.
  • pdfcrop -margin 3 in-name.pdf out-name.pdf
  • convert -trim -density 200 out-name.pdf out-name.png
    (this requires imagemagick).

this requires two "external" programs, and can probably be scripted.

5

The answers here are pretty great if you just have a single equation you'd like to export. What if you have a list of equations in some file that you'd like to export?

% equation 1 %
\[ y = mx + b \]

% equation 2 %
e = \lim_{n \rightarrow \infty} \left ( 1 + \frac{1}{n} \right )^n

You'd like to automatically export each of these equations to a separate image file. I would suggest one of the following two approaches.

Approach #1 (not so good, but easy) - Use matplotlib, which can render basic equations using the plt.text() command. Here is a snippet of code that handles some nice formatting (centering and padding for the equation: https://gist.github.com/ahwillia/c7e54f875913ebc3de3852e9f51ccc69

The main formatting trick is to use the get_window_extent() function as suggested in this StackOverflow discussion, and then set the size of the figure appropriately.

Approach #2 (more powerful) - Use a python script to make a bunch of temporary .tex files following the various templates suggested in this thread. And the use the subprocess module to compile the latex, rename to an appropriate filename and delete .log and .aux files.

I have a basic script that works for my needs here: https://gist.github.com/ahwillia/ce9a842f122757518c65d0bd545f28c1#file-equations-tex-L2

There is also a more polished package called texscrap, though I haven't tried it extensively yet. It accepts a text file of one-liner equations as input, but I'm not sure if there are edge cases it fails on. Seem very promising though.

  • does this extend to using aligned environments , multiline equations and such? – baxx Oct 23 '16 at 12:35
  • Yes I've successfuly done (with my janky code) e.g. - https://jcnts.wordpress.com/2009/11/11/formatting-optimization-problems-with-latex/ – digbyterrell Oct 24 '16 at 00:20
  • That doesn't seem to use matplotlib at all? – baxx Oct 24 '16 at 00:21
  • Sorry - I thought you meant approach #2. The matplotlib approach is pretty limited. Don't think that you can do multiline. I'll edit the answer to reflect that. – digbyterrell Oct 24 '16 at 00:24
  • Another approach which I am using and which I believe to be as powerful as your script, but does not require any external tools, is the preview package, which was also mentioned in another answer. – hans_meine Nov 25 '19 at 08:12
4

Another approach with preview package directly.

% host.tex
\documentclass[preview,border=12pt,12pt]{standalone}
\usepackage{filecontents}

\begin{filecontents}{main.tex} % this is main.tex \documentclass[12pt]{article} \usepackage[active,tightpage]{preview} \PreviewBorder=12pt\relax \begin{document} \preview Hello. This is a test. \begin{equation} L = 2 \end{equation} \endpreview \end{document} \end{filecontents}

\usepackage{graphicx} \immediate\write18{pdflatex main.tex} \immediate\write18{convert -density 100 -alpha remove main.pdf main.png} %\immediate\write18{magick convert -density 100 -alpha remove main.pdf main.png} % for Windows users! \begin{document} The following is a PNG image.\newline \fbox{\includegraphics{main.png}} \end{document}

enter image description here

Notes

  • ImageMagick must be installed on your machine.
  • Compile the host.tex with pdflatex -shell-escape host.tex.
  • -alpha switch can be set to either on, off, or remove. Mostly we use remove to get the best output (without imperfection).
Display Name
  • 46,933
4

Without using standalone, I used to transform my .pdf output in a .png file by an online converter (I don't give the link because I don't know if it is reliable, however, you can easily find it googling around) but since I installed arara package I've done this conversion more quickly.

I have Windows 10 but I think this works with every operating system, you only need to have ImageMagick (it's free) and arara package installed.

Modifying the animate rule provided by cmhughes, which creates a .gif file, I have created a convert.yaml rule and put in ...\MiKTeX 2.9\scripts\arara\rules (the path varies according to which operating system and TeX distribution you are using, I have MiKTeX):

!config
# Convert .pdf to any format file allowed by ImageMagick convert command (the default is png)
# author: CarLaTeX
# last edited by: CarLaTeX, Dicember 26th 2016
# requires arara 3.0+
#
# Sample usage: 
# - these both create a .png file
# % arara: convert
# % arara: convert: {format: png}
#
# - this creates a .gif file with red background
# % arara: convert: {format: gif, background: red}
#
# - this creates a .png file with a trimmed image 
#   (use the parameter "otheroptions" to add any option not already explicitly considered by the rule, 
#   that is any option different from -background, -alpha, -density and -quality}
# % arara: convert: {otheroptions: -trim +repage}
#
#
# This rule is really just a shortcut for commands like the following:
#
#  convert -density 300 myfile.pdf myfile.png
#
# which will output myfile.png
#
identifier: convert
name: convert
commands: 
- <arara> @{ isWindows( "cmd /c convert", "convert" ) } -background @{background} -alpha @{alpha} -density @{density} @{otheroptions} "@{ getBasename(file) }.pdf" -quality @{quality} "@{ getBasename(file) }.@{format}"
arguments:
- identifier: density
  flag: <arara> @{parameters.density}
  default: 150
- identifier: otheroptions
  flag: <arara> @{parameters.otheroptions}
- identifier: quality
  flag: <arara> @{parameters.quality}
  default: 100
- identifier: background
  flag: <arara> @{parameters.background}
  default: white
- identifier: alpha
  flag: <arara> @{parameters.alpha}
  default: remove
- identifier: format
  flag: <arara> @{parameters.format}
  default: png

(Take into account that I'm not an expert, maybe this could be done better).

Of course, you have to do this once for all, then it is sufficient to put:

% arara: pdflatex               (or any other command you are using to compile)
% arara: ...                    (possible other commands)
% arara: convert

at the beginning of your document and compile it with arara.

For example, if you have this myfile.tex:

% arara: pdflatex
% arara: convert
\documentclass{article}
\begin{document}
    Quack!
\end{document}

and you run arara myfile.tex, you will get a myfile.pdf and a myfile.png.

For an analogous solution using Ghostscript, see this answer of mine.

CarLaTeX
  • 62,716
  • How could you change the output format? For example if I want density of 300 with jpg format, what should I write? – Diaa Jan 21 '18 at 13:53
  • 1
    @DiaaAbidou % arara: convert: {format: jpg, density: 300} should work... – CarLaTeX Jan 21 '18 at 16:53
4
\usepackage[displaymath]{pst-pdf}
    

then dvipng crops the whitespace on top and bottom

2

If you only want to use the PNG image to include it into MS Word you can choose among several programs that will greatly simplify your task. By hand you have to go through the whole process every time you modify the LaTeX part of your document.

As far as I know there is:

They all have different properties, some are freeware, shareware or opensource but it improves your workflow quite a bit if you can simply change the figure in Word directly and use LaTeX in the background for nice typesetting. Internally they all use some VBA or .NET code to connect the LaTeX, dvips, convert toolchain to MS Word.

Alexander
  • 9,163
2

I failed all suggested methods for getting png. The simplest way to get (quite good) png file of the pdf file of a TikZ picture for me so far is the following: Use Miktex/Texmaker to get a pdf file with build-in pdf viewer (Option/Configure Texmaker/Quick Build/, then select build-in viewer in PDF VIEWER); after compiling and getting pdf, just right click to the pdf picture and choose: Convert page to a PNG picture.

Black Mild
  • 17,569
2

You can install TikzEDT which has a stanalone feature. From here you can directly export you picture into .pdf,.jpg,.png etc without any trouble.

0

Hi i am probably a bit late, but if you want to create a pdf that fits your content just do

\documentclass[a4paper, 10pt]{article}
%%packages%%
\hoffset=-1in
\voffset=-1in
\setbox0\hbox{
%%content%%
}
\pdfpageheight=\dimexpr\ht0+\dp0\relax
\pdfpagewidth=\wd0
\shipout\box0
\stop

I also programmed a small libary in python that can do that https://pypi.org/project/easylatex2image/ and converts your latex code directly to an image. You just need Miktex installed.