开发者

Making PNG|jpeg from LaTeX in C or C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

Closed 5 years ago.

Improve this question

I'm looking for a library (or a cleverer solution) in C or C++ that would m开发者_运维技巧ake 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.


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)


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜