Linux 使用PDFtk删除pdf文件的最后一页?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17705974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove the last page of a pdf file using PDFtk?
提问by user1974753
Can someone please tell me how to remove the last page of a PDF file, using PDFtk?
有人可以告诉我如何使用 PDFtk 删除 PDF 文件的最后一页吗?
回答by This isn't my real name
Using the cat
operation, and specifying a page range.
使用cat
操作,并指定页面范围。
pdftk infile.pdf cat 1-r2 output outfile.pdf
回答by Kingsley
You need to find out the page count, then use this with the pdftk cat function, since (AFAICT) pdftk does not allow one to specify an "offset from last".
您需要找出页数,然后将其与 pdftk cat 函数一起使用,因为(AFAICT)pdftk 不允许指定“与上次的偏移量”。
A tool like 'pdfinfo' from Poppler (http://poppler.freedesktop.org/) can provide this.
来自 Poppler ( http://poppler.freedesktop.org/) 的“pdfinfo”等工具可以提供此功能。
Wrapping this in a bit of bash scripting can easily automate this process:
将其包装在一些 bash 脚本中可以轻松自动化此过程:
page_count=`pdfinfo "$INFILE" | grep 'Pages:' | awk '{print }'`
page_count=$(( $page_count - 1 ))
pdftk A="$INFILE" cat A1-$page_count output "$OUTFILE"
Obviously adding parameters, error checking, and what-not also could be placed in said script:
显然,添加参数、错误检查等也可以放在上述脚本中:
#! /bin/sh
### Path to the PDF Toolkit executable 'pdftk'
pdftk='/usr/bin/pdftk'
pdfinfo='/usr/bin/pdfinfo'
####################################################################
script=`basename "cpdf in.pdf 1-~2 -o out.pdf
"`
### Script help
if [ "" = "" ] || [ "" = "-h" ] || [ "" = "--help" ] || [ "" = "-?" ] || [ "" = "/?" ]; then
echo "$script: <input-file.PDF> [<output-file.PDF>]"
echo " Removes the last page from the PDF, overwriting the source"
echo " if no output filename is given"
exit 1
fi
### Check we have pdftk available
if [ ! -x "$pdftk" ] || [ ! -x "$pdfinfo" ]; then
echo "$script: The PDF Toolkit and/or Poppler doesn't seem to be installed"
echo " (was looking for the [$pdftk] and [$pdfinfo] executables)"
exit 2
fi
### Check our input is OK
INFILE=""
if [ ! -r "$INFILE" ]; then
echo "$script: Failed to read [$INFILE]"
exit 2
fi
OUTFILE=""
if [ "$OUTFILE" = "" ]; then
echo "$script: Will overwrite [$INFILE] if processing is ok"
fi
timestamp=`date +"%Y%m%d-%H%M%S"`
tmpfile="/tmp/$script.$timestamp"
page_count=`$pdfinfo "$INFILE" | grep 'Pages:' | awk '{print }'`
page_count=$(( $page_count - 1 ))
### Do the deed!
$pdftk A="$INFILE" cat A1-$page_count output "$tmpfile"
### Was it good for you?
if [ $? -eq 0 ]; then
echo "$script: PDF Toolkit says all is good"
if [ "$OUTFILE" = "" ]; then
echo "$script: Overwriting [$INFILE]"
cp -f "$tmpfile" "$INFILE"
else
echo "$script: Creating [$OUTFILE]"
cp -f "$tmpfile" "$OUTFILE"
fi
fi
### Clean Up
if [ -f "$tmpfile" ]; then
rm -f "$tmpfile"
fi