Friday, July 15, 2011

Latex to PNG to Blogger

I just wanted to put at the top what you need to follow along with this post. Everything below is written assuming you're using a Unix terminal and you have pdflatex and imagemagick installed. For Ubunu, the de facto linux distribution, type this into your terminal window to get these programs:

sudo apt-get install imagemagick
sudo apt-get install pdflatex

Due to my failure in making nice looking equations in my last posts, I worked on discovering a solution. Naturally, I tried to google Latex and Blogger. Latex is what I usually use for formatting equations, so that is what I was hoping to find. Unfortunately, most of the ideas I found for inserting equations into Blogger relied on hosted scripts and random people providing image hosting. I tried two solutions described in blogs and both didn't work, due to the site hosting the rendering engine being down. If you would like to convert LaTeX code directly into PNGs on the web, you can try codecogs, but I find the website to appear pretty Spammy and you cannot have very much control over your results. But, hey, it works.

Next idea: use Latex to write equations, use pdflatex to turn them into PDFs, and then use ImageMagick to convert the PDFs into PNGs. Easy, right? Well, here are the results:





Pretty cool! So, here it is step by step. First, I need to create the LaTex for the equation:
The key point here for the LaTeX is that there needs to be the \pagestyle{empty}. That removes the footer (page numbers) in the output PDFs.

Next step is to create the PDF from the LaTeX code. Type this at in the terminal:
pdflatex eq.tex
At this point, you should have a giant PDF with a single equation at the top. Now, this is where the magick happens. Using the convert command from ImageMagick, we'll simultaneously crop it, center it, adjust the resolution and turn the equation into a PNG:
convert -trim +repage -density 150 eq.pdf eq.png
The density is what controls the resolution of the output. At this point, the equation looks like this:


Simple! Now, the last problem is the Blogger template I'm using puts a drop-shadow around images by default. You have to remove that in order to make it look like the equations actually belong in the blog. The actual code that needs to be removed from the Blogger HTML design varies depending on which template you're using, but I removed the HIGHLIGHTED LINES ONLY for the best results:

Finally, to put it all together, I created this bash script which takes in a file which should have equations listed with one on each line and converts them into PNGs labeled 1.png, 2.png, etc. Good for quick equations, but it won't work with multiple line equations.

No comments:

Post a Comment