在 C 或 C++ 中从 LaTeX 制作 PNG|jpeg

发布于 2024-08-14 21:44:54 字数 1539 浏览 7 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

╰つ倒转 2024-08-21 21:44:54

我之前曾多次使用过 dvipng 路线,但是是在 python 中。这是一条常见的道路,很多人都走过了。这是代码,可以为您提供一些入门知识,以防万一有人想要 Python 代码。 我确实意识到您要求使用 C/C++;这是针对初学者或其他人的。这是为了生成方程,但将其调整为更通用的结构是微不足道的。它确实支持包。

在透明地整合方面,我感受到你的痛苦。当然,并不是每个人都有 tex/latex,如果没有,通常很难获得。我认为,最好的方法是将该功能作为 Web 服务提供 - 但当然这并不总是一种选择。

最后,记下 dvipng 的所有选项。它们通过各种抗锯齿选项等控制外观。我对它们进行了广泛的调整,以获得我认为看起来不错的效果。

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)

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)
奈何桥上唱咆哮 2024-08-21 21:44:54

如果您想将部分代码转换为 png 文件,而不一定是全部,请查看 预览包.根据他们的 README,它可以提取部分内容Latex 源文件来分隔 dvi 文件,并且这些文件可以转换为 png 文件。不使用 dvipng 获取 PNG 的另一种选择是将生成的 PDF/ps 文件直接转换为 PNG:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文