【MacOS】Install GhostScript to batch merge pdf files

Installing GhostScript on MacOS

brew install ghostscript
# 安装完成后,确认是否安装成功
gs --version
# 成功则输出版本号,比如我的是10.01.2
10.01.2

Merge multiple pdf files into 1 pdf file

gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=merged.pdf -dPDFSETTINGS=/prepress 1.pdf 2.pdf 3.pdf 4.pdf 5.pdf

After the above command is executed, the pdf files numbered 1-5 will be merged into merged.pdf
-q: The execution process suppresses log printing
-dNOPAUSE: The option tells Ghostscript not to pause at the end of each page and each file, but to process all pages. and file immediately exit. This option speeds up processing because Ghostscript doesn't have to pause at the end of every page and file.
-dBATCH: option tells Ghostscript to exit after processing all files rather than waiting for user input. This option tells Ghostscript not to enter interactive mode, but to exit as soon as processing is complete.
-sDEVICE=pdfwrite:Indicates that the output file format is pdf
-sOutputFile=merged.pdf:Indicates the output file name
-dPDFSETTINGS=/prepress: The option can improve the quality of the output file and keep the size of each page consistent, but it will increase the file size

Shell script to batch merge multiple pdf files

When you have a large number of pdf files that need to be merged, and the file names are in the following format:
a-1.pdf a-2.pdf a-3.pdf

z-1.pdf z-2.pdf z-3.pdf
needs to be merged into a -merge.pdf … z-merge.pdf

#!/bin/bash
# 合并pdf,打印执行耗时
function merge_pdf() {
    
    
  start=$(date +%s)
  eval "$3"
  end=$(date +%s)
  echo "$1: $2 cost:" `expr $end - $start` "s"
}
# 扫描pdf原始数据获取前缀名数组
arr=`ls -al pdf-dir/ |grep ".pdf"|awk -F ' ' '{print $9}'|awk -F '_' '{print $1}'|uniq`
# 计数
i=0;
# 遍历
for name in ${arr[*]}; do
	let "i++"
	# 生产合并pdf的命令行
	command="gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=./res/${name}-merged.pdf -dPDFSETTINGS=/prepress ./pdf-dir/${name}*.pdf"
	# 异步执行合并pdf函数,日志信息输出到logs/merger_pdf.log
	merge_pdf $i $name "$command" >> logs/merger_pdf.log 2>&1 &
done

Guess you like

Origin blog.csdn.net/u011308433/article/details/131444448