Linux下PDF操作-拆分、合并、旋转


下文需要基础Linux shell知识。
分割,拼接PDF
pdfunite & pdfseparte(这两个命令行工具很多Linux发行版都自带)。
pdfseparte,用于将一个PDF文件分割成单页的文件,用户可以删除不需要的页面。pdfunite,用于拼接(合并)pdf文件,支持glob模式的通配符。
mkdir sep
pdfseparte -f 101 -l 303 filename.pdf sep/sample-%03d.pdf
cd sep
pdfunite sample-* sample.pdf
注释: -f 101 -l 303 表明提取101-303页,不加这一句就是提取首页至末页。%03d表达的是一种格式,分割后的第一页是sample-001.pdf,而不是sample-1.pdf。这样的编页格式对于后续的pdfunite(合并pdf)很重要,确保页码不会乱序。
%03d的详细解释,%[flags][width][.precision][length]specifier, flags是0,width是3,所以第一页是sample-001.pdf。see more on `printf < https://www. cplusplus.com/reference /cstdio/printf/ >`_
pdfseparate和pdfunite上都是poppler-utils里的命令,里面还有一个pdftotext比较有用。不过它仅对文字版的PDF有较好的效果,不支持扫描版的PDF。poppler-utils也有相当大的局限性 。 其中的pdf*工具,都只支持pdf向别的格式(单向)转换,而不支持类似jpeg to pdf这样的转换。
[todo] 经查,似乎GhostScript可以做一些其他奇奇怪怪的事情,比如pdfmark(标签)。
Rotate PDF 旋转PDF
ImageMagick套件的曲线救国,本质上是一整个图片编辑系统,也可以用于PDF文件操作,但用它操作PDF被诟病"a bad idea but works."。
关于bad idea的简单说明。因为ImageMagick本质上是在操作图片,在实现旋转PDF页面功能的时候,经过了将PDF页面转换成图片、旋转图片、转回PDF三步骤,而诸如Adobe Acrobat之类的PDF 编辑器,则是通过直接编辑PDF实现的,用它旋转PDF页面,只有一步。see more details `Command line: How do you rotate a PDF file 90 degrees? < https:// unix.stackexchange.com/ questions/394065/command-line-how-do-you-rotate-a-pdf-file-90-degrees/459596 >`_ 引文如下:
There are no "authorative solutions", but you should keep in mind what method the various solutions use: Direct manipulation of PDF structure (pdftk, Adobe Acrobat, and other programs), converting to an image and then converting back to a PDF (e.g. Imagemagick's convert, printing using PDF printer etc.). The latter is obviously a bad idea.
ImageMagick自带了一堆工具,与PDF旋转功能相关的是convert和mogrify。根据其官网,mogrify: This tool is similar to magick except that the original image file is overwritten. 网上诸多ImageMagick的教程本质上也适用于mogrify,convert -rotate "90" in.jpg out.jpg
旋转所有filename-*.pdf只需要如下一句::
mogrify -density 150 -colorspace Gray -quality 70 -rotate 180 filename-*.pdf
便捷起见,可以为相关命令添加别名。
在~/.bash_aliases中添加:
alias pdfrotate180='mogrify -density 150 -colorspace Gray -quality 70 -rotate 180'
alias pdfrotate='mogrify -density 150 -colorspace Gray -quality 70 -rotate'
.. caution:: It's extremely important that there are no spaces between the environment variable name, the equal sign, and the value. If you put any spaces in the assignment, the bash shell interprets the value as a separate command.