TransWikia.com

Best Way to Convert .tex to .png With Cropping & Conversion Error from PS to PNG using ImageMagick

TeX - LaTeX Asked by David De Martin on February 4, 2021

I am trying to render latex formulas as pngs. I have tried many different methods: first I used the SymPy preview function to give a png, but I was getting errors when working with tikz pictures. Thus, I turned to ImageMagick and was using pdflatex in conjunction with ImageMagick’s convert function (to convert from pdf to png). However, I like the -T tight option for dvipng becuase it gives better cropped images so I tried that. Unfortunately, I found that you cannot use dvipng with tikz pictures since tikz embeds PostScript snippets within the dvi file and dvipng cannot interpret them, giving errors (which is why SymPy stopped working… it uses dvipng). Therefore, to catch all these errors, I found dvips and am currently converting .tex to .dvi (using latex) to .ps (using dvips) to .png (using ImageMagick). However, now I am getting another error from ImageMagick when attempting to convert from .ps to .png. I am using the following command: convert -density 1200 file.ps -quality 90 image.png but getting the following error: convert-im6.q16: no images defined 'image.png' @ error/convert.c/ConvertImageCommand/3258. Also, this method of converting to so many different file types is very slow.

First, how can I fix the above error?
Second, is there a better way to convert latex to pngs with nice cropping (similar to using dvipng and -T tight) with a single package while also allowing tikz pictures?

One Answer

I can suggest the following workflow:

  • Use the preview package with the tightpage option for your LaTeX file with formulas, put each one into a separate preview environment.
  • Use pdflatex (actually any compiler will do);
  • Use convert to turn the emitted PDF into a bunch of PNG images.

Here is a sample code:

documentclass[11pt]{article}
usepackage[active,tightpage]{preview}
usepackage{tikz}

begin{document}
begin{preview}
$displaystyleint_{-infty}^{+infty}e^{-x^2}dx=sqrt{pi}$
end{preview}

begin{preview}
begin{tikzpicture}
  draw (0,0) rectangle (1,1);
  node (A) at (0.5,0.5) {A};
end{tikzpicture}
end{preview}
end{document}

It outputs a two-page PDF with page sizes that match the object sizes. After

convert -density 1200 test.pdf test%d.png

I get two PNG images without any extra margins:

enter image description here

enter image description here

Answered by Sergei Golovan on February 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP