将 LaTeX 编译为特定宽度和 DPI 质量的 PNG,并尽可能裁剪

将 LaTeX 编译为特定宽度和 DPI 质量的 PNG,并尽可能裁剪

我想将 LaTeX 文件直接编译为 PNG(最好跳过 PDF),并尽可能地裁剪输出的 PNG 内容。

PNG 输出需要非常高的质量,并且宽度不能超过 500px,文件大小不能超过 500KB。

为了进行实验,我将其中一个 LaTeX 文件的 PDF 转换为 600DPI PNG,效果不错。我将同一个 PDF 转换为 300DPI PNG,效果很糟糕。

我在 Windows 10 PC 上通过 Texmaker 使用 MikTeX。我有大约 400 个这样的 LaTeX 文件,但每周处理大约 50 个就够了。

下面是两个典型的 LaTeX 文件示例,我尝试使用几何包来控制宽度。

\documentclass[fleqn]{article}
\nofiles
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage[papersize={500px,100px},margin=1cm]{geometry}
\pagenumbering{gobble}

\begin{document}

\noindent Differentiate: $f(x)=\sqrt[8]{x}-\frac{5}{\sqrt{x}}$.

\end{document}
\documentclass[fleqn]{article}
\nofiles
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage[papersize={500px,100px},margin=1cm]{geometry}
\pagenumbering{gobble}

\begin{document}

\noindent It is estimated that $t$ years from now, the population of a certain suburban community will be $p(t)=40-\frac{5}{7 t+3}$ thousand people. At what rate will the population be growing 5 years from now?

\end{document}

答案1

欢迎来到本网站!

正如我在评论中提到的,这是我的做法。我将上面的第一个例子复制到名为的文件中sample.tex。然后我运行以下批处理文件(在 Windows 上)。

pdflatex sample.tex
pdfcrop sample.pdf sample.pdf
magick convert -alpha off -density 1000 sample.pdf -scale 25%% sample.png

这会编译为sample.pdf,裁剪白色边框,然后调用 Imagemagickconvert命令来写入 PNG。convert我使用的标志执行以下操作...

-alpha off意味着 PNG 背景不会透明。

-density 1000转换为 1000 dpi。

-scale 25%%(DOS 中需要双百分号)然后将 PNG 缩小到 25%

使用高 DPI 然后缩小尺寸被称为“过采样”。在这种情况下,它比仅使用 250 DPI 的图像效果好得多。在此示例中,最终图像的宽度为 476 像素。

pdfcrop 和 imagemagick 都是开源的、可免费使用的程序。祝你好运!

在此处输入图片描述

编辑:我认为以下批处理脚本将循环遍历.tex当前目录中的所有文件。我今晚无法访问我的 Windows 计算机,因此我尚未对其进行测试。

for %%f in (*.tex) do (
    pdflatex %%~nf.tex
    pdfcrop %%~nf.pdf %%~nf.pdf
    magick convert -alpha off -density 1000 %%~nf.pdf -scale 25%% %%~nf.png
)

相关内容