软件需求

以下软件包可用于Windows和Linux系统,并且是完整,有效的解决方案所必需的:

一般步骤

解决方案的工作原理如下:

FONT

该脚本为包含长度均小于80个字符的行的源文件生成宽度完全相同的图像。行长超过80个字符的源文件会生成足够宽的图像,以保留整行。

安装

将组件安装到以下位置:

C:\Program Files\VimC:\Program Files\Vim\vim73\colorsC:\Program Files\wkhtmlC:\Program Files\ImageMagickC:\Program Files\GnuWin32
convert.execonvertconvert.exePATH

环境变量

"C:\Program Files\Vim\vim73";"C:\Program Files\wkhtml";"C:\Program Files\GnuWin32\bin"

批处理文件

使用以下命令运行它:

src2png.bat src2png.bat
src2png.bat
@ECHO OFF

SET NUMBERS=-c "set number"
IF "%2" == "" SET NUMBERS=

ECHO Converting %1 to %1.html...
gvim -e %1 -c "set nobackup" %NUMBERS% -c ":colorscheme moria" ^
  -c :TOhtml -c wq -c :q

REM Remove all background-color occurrences (without being self-referential)
sed -i "s/background-color: #......; \(.*\)}$/\1 }/g" %1.html

ECHO Converting %1.html to %1.png...
wkhtmltoimage --format png --transparent --minimum-font-size 80 ^
  --quality 100 --width 3600 ^
  %1.html %1.png

move %1.png %1.orig.png

REM If the text file has lines that exceed 80 characters, don't crop the
REM resulting image. (The book automatically shrinks large images to fit.)
REM The 3950 is the 80 point font at 80 characters with padding for line
REM numbers.
SET LENGTH=0
FOR /F %%l IN ('gawk ^
  "BEGIN {x=0} {if( length($0)>x ) x=length()} END {print x;}" %1') ^
DO (
  SET LENGTH=%%l
)
SET EXTENT=-extent 3950x
IF %LENGTH% GTR 80 SET EXTENT=

REM Trim the image height, then extend the width for 80 columns, if needed.
REM The result is that all images will be resized the same amount, thus
REM making the font size the same maximum for all source listings. Source
REM files beyond the 80 character limit will be scaled as necessary.
ECHO Trimming %1.png...
"C:\programs\ImageMagick\convert.exe" -format png %1.orig.png ^
  -density 150x150 ^
  -background none -antialias -trim +repage ^
  %EXTENT% ^
  -bordercolor none -border 25 ^
  %1.png

ECHO Removing old files...
IF EXIST %1.orig.png DEL /q %1.orig.png
IF EXIST %1.html DEL /q %1.html
IF EXIST sed*. DEL /q sed*.

欢迎进行改进和优化。

注意:最新版本的wkhtmltoimage可以正确处理覆盖背景色。因此,从理论上讲,不再需要为背景色移除CSS的行。