将 PDF 转换为 PNG
我正在尝试将 PDF 转换为 PNG 图像(至少是一张的封面).我正在使用 pdftk 成功提取 PDF 的第一页.我正在使用 imagemagick 进行转换:
I'm trying to convert a PDF to a PNG image (at least the cover of one). I'm successfully extracting the first page of the PDF with pdftk. I'm using imagemagick to do the conversion:
convert cover.pdf cover.png
这是可行的,但不幸的是,cover.png 渲染不正确(PDF 中的某些 alpha 对象未正确渲染).我知道 ImageMagick 使用 GhostScript 进行转换,如果我直接使用 gs 进行转换,我可以获得所需的结果,但我更愿意使用 convert 库,因为它有其他我想利用的工具.
This works, but unfortunately the cover.png comes through incorrectly rendered (some of the alpha object in the PDF aren't rendered properly). I know ImageMagick uses GhostScript to do the conversion and if I do it directly with gs I can get the desired results, but I'd rather use the convert library as it has other tools I'd like to leverage.
GhostScript 中的这个命令完成了所需的图像:
This command in GhostScript accomplishes the desired image:
gs -sDEVICE=pngalpha -sOutputFile=cover.png -r144 cover.pdf
我想知道有什么方法可以通过转换为 GhostScript 来传递参数,还是我坚持直接调用 GhostScript?
I'm wondering is there any way to pass arguments through convert to GhostScript or am I stuck with calling GhostScript directly?
您可以使用一个命令行和通过管道连接的两个命令(gs
、convert
),如果第一个命令可以将其输出写入 stdout,如果第二个命令可以从 stdin 读取其输入.
You can use one commandline with two commands (gs
, convert
) connected through a pipe, if the first command can write its output to stdout, and if the second one can read its input from stdin.
- 幸运的是,gs 可以写入标准输出(
... -o %stdout ...
). - 幸运的是,convert 可以从 stdin 读取(
convert -background transparent - output.png
).
问题解决:
- GS 用于处理特殊图像的 alpha 通道,
- convert 用于创建透明背景,
- 用于避免在磁盘上写出临时文件的管道.
完整的解决方案:
gs -sDEVICE=pngalpha
-o %stdout
-r144 cover.pdf
|
convert
-background transparent
-
cover.png
更新
如果您希望每个 PDF 页面有一个单独的 PNG,您可以使用 %d
语法:
gs -sDEVICE=pngalpha -o file-%03d.png -r144 cover.pdf
这将创建名为 page-000.png
、page-001.png
、...(注意 %d
-counting 是从零开始的 -- file-000.png
对应于 PDF 的第 1 页,001
对应于第 2 页...
This will create PNG files named page-000.png
, page-001.png
, ... (Note that the %d
-counting is zero-based -- file-000.png
corresponds to page 1 of the PDF, 001
to page 2...
或者,如果您想保留透明背景,对于 100 页的 PDF,请执行
Or, if you want to keep your transparent background, for a 100-page PDF, do
for i in {1..100}; do
gs -sDEVICE=pngalpha
-dFirstPage="${i}"
-dLastPage="${i}"
-o %stdout
-r144 input.pdf
|
convert
-background transparent
-
page-${i}.png ;
done