-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathextract_pdf_pages.sh
executable file
·60 lines (50 loc) · 1.9 KB
/
extract_pdf_pages.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/bin/bash -e
# /opt/scripts/extract_pdf_pages.sh
# @author: Nestor Urquiza
# @date: 20140402
USAGE="Usage: `basename $0` <pdf_from_file> <pdf_to_file> <space_separated_page_numbers> [password]"
if [ $# -lt "3" ]
then
echo $USAGE
exit 1
fi
pdf_from_file=$1
pdf_to_file=$2
space_separated_page_numbers=$3
password=$4
pdf_merged_file=$(mktemp /tmp/pdf_merged_file.XXXXXXX).pdf
pdf_new_to_merge_file=$(mktemp /tmp/pdf_new_to_merge_file.XXXXXXX).pdf
if [ -z $password ]
then
user_pwd_switch=""
owner_pwd_switch=""
pdf_pwd_switch=""
else
user_pwd_switch="-sUserPassword=$password"
owner_pwd_switch="-sOwnerPassword=$password"
pdf_pwd_switch="-sPDFPassword=$password"
fi
for page in $space_separated_page_numbers ; do
gs $pdf_pwd_switch -dBATCH -dNOPAUSE -q -sOutputFile=$pdf_new_to_merge_file \
-dFirstPage=$page -dLastPage=$page -sDEVICE=pdfwrite \
"$pdf_from_file"
# Keep on merging to the output pdf if it exist
if [ -f "$pdf_to_file" ]
then
# Merge into existing output file
gs $pdf_pwd_switch -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite \
-sOutputFile="$pdf_merged_file" "$pdf_to_file" "$pdf_new_to_merge_file"
# Use the merged file as a new output file
mv "$pdf_merged_file" "$pdf_to_file"
# Use the below instead if you need to use the same password to encrypt the result
# gs $owner_pwd_switch $user_pwd_switch -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=$pdf_to_file "$pdf_merged_file"
else
# Use the new to merge file as a new output file
mv "$pdf_new_to_merge_file" "$pdf_to_file"
# Use the below instead if you need to use the same password to encrypt the result
# gs $owner_pwd_switch $user_pwd_switch -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=$pdf_to_file "$pdf_new_to_merge_file"
fi
# cleanup
rm -f "$pdf_new_to_merge_file"
rm -f "$pdf_merged_file"
done