答案1
以下是通过脚本可能的解决方案。首先,TeX 文档 ( mydoc.tex
):
\documentclass{article}
\begin{document}
\thispagestyle{empty}
This page is not entirely blank.
\end{document}
我可以将转换嵌入到我的脚本中,但让我们简化这个过程:
$ convert mydoc.pdf -density 300 -flatten img.png
现在,考虑以下 Python 代码(howmuch.py
):
from PIL import Image
ps = Image.open('img.png').getdata()
bp = 0
for p in ps:
if p != 255:
bp = bp + 1
print('Your page is {:.4f}% blank.'.format((1 - bp / float(len(ps))) * 100))
然后只需发出:
$ python howmuch.py
Your page is 99.9104% blank.
完毕。
更新:感谢 Torbjørn,这里有一个改进的版本,它尝试根据之前的迭代猜测最接近的值。我相信代码背后的逻辑非常不言自明。
from PIL import Image
from subprocess import call
def calculate(template, context, engine = 'pdflatex'):
with open('page.tex', 'w') as page:
page.write(template.format(**context))
call([engine, 'page.tex'])
call(['convert', 'page.pdf', '-density', '300', '-flatten', 'img.png'])
ps = Image.open('img.png').getdata()
bp = 0
for p in ps:
bp += 1 if p != 255 else 0
return (1 - bp / float(len(ps))) * 100
doc = r'''
\documentclass{{article}}
\begin{{document}}
\thispagestyle{{empty}}
This page is not entirely blank.
It is {percentage}\% empty.
\end{{document}}
'''
guess = 99.8
max_attempts = 99
attempt_count = 0
tolerance = 0.01
while attempt_count < max_attempts:
d = calculate(doc, { 'percentage' : guess }) - guess
if abs(d) < tolerance:
break
else:
guess = guess - 0.01 if d < 0 else guess + 0.01
attempt_count += 1
print('Done.')
在这个特殊情况下,经过 5 次迭代,我们实现了收敛。:)
我们就这样开始了。