tags:

views:

112

answers:

2

I'm looking for a library (or a cleverer solution) in C or C++ that would make an image file (PNG|jpeg) from LaTeX code. The use of packages is a prerequisite.

For now I'm thinking of compiling a .tex file into a .dvi and using dvipng to get a .PNG.

There's also the possibility of compiling a .tex file into a .ps file and then converting it into a .PNG by the mean of extern utilities like pstopng or pstoedit.

But these solutions are cumbersome and not always portable. I would like to integrate this conversion in my program transparently.

+2  A: 

I've used the dvipng route several times before, but in python. It's a common path, that lots of people have taken. Here's the code, to give you something to get started, and in case anyone wants Python code. I do realise you asked for C/C++; this is for a starter, or for others. This is for generating equations, but it would be trivial to adapt it for more general structures. It does support packages.

In terms of integrating it transparently, I feel your pain. Not everyone has tex / latex of course, and if they don't, it's often a pain to get. The best way to do it, I think, is to provide that functionality as a web service - but of course that's not always an option.

Finally, note all the options for dvipng. They control the appearance, via various anti-alisaing options etc. I tuned them extensively to get what I thought looked good.

def geneq(f, eq, dpi, wl, outname, packages):
    # First check if there is an existing file.
    eqname = os.path.join(f.eqdir, outname + '.png')

    # Open tex file.
    tempdir = tempfile.gettempdir()
    fd, texfile = tempfile.mkstemp('.tex', '', tempdir, True)
    basefile = texfile[:-4]
    g = os.fdopen(fd, 'w')

    preamble = '\documentclass{article}\n'
    for p in packages:
        preamble += '\usepackage{%s}\n' % p

    preamble += '\pagestyle{empty}\n\\begin{document}\n'
    g.write(preamble)

    # Write the equation itself.
    if wl:
        g.write('\\[%s\\]' % eq)
    else:
        g.write('$%s$' % eq)

    # Finish off the tex file.
    g.write('\n\\newpage\n\end{document}')
    g.close()

    exts = ['.tex', '.aux', '.dvi', '.log']
    try:
        # Generate the DVI file
        latexcmd = 'latex -file-line-error-style -interaction=nonstopmode ' + \
               '-output-directory %s %s' % (tempdir, texfile)
        p = Popen(latexcmd, shell=True, stdout=PIPE)
        rc = p.wait()
        if rc != 0:
            for l in p.stdout.readlines():
                print '  ' + l.rstrip()
            exts.remove('.tex')
            raise Exception('latex error')

        dvifile = basefile + '.dvi'
        dvicmd = 'dvipng --freetype0 -Q 9 -z 3 --depth -q -T tight -D %i -bg Transparent -o %s %s' % (dpi, eqname, dvifile)
        # discard warnings, as well.
        p = Popen(dvicmd, shell=True, stdout=PIPE, stderr=PIPE)
        rc = p.wait()
        if rc != 0:
            print p.stderr.readlines()
            raise Exception('dvipng error')
        depth = int(p.stdout.readlines()[-1].split('=')[-1])
    finally:
        # Clean up.
        for ext in exts:
            g = basefile + ext
            if os.path.exists(g):
                os.remove(g)
Peter
Thanks for the answer. The supplied command line options of dvipng are especially helpful.
anno
+1  A: 

If you want to convert parts of your code to png files, and not necessarily everything, have a look at the preview package. As per their README, it can extract parts of a Latex source file to separate dvi files, and those can be converted to png files. Another option instead of using dvipng to get PNGs would be to convert the generated PDF/ps files to PNG directly:

gs -sDEVICE=png16m -dTextAlphaBits=4 -r300 -dGraphicsAlphaBits=4 -dSAFER -dBATCH -dNOPAUSE -sOutputFile=file.png file.pdf
Alok