使用PDFtk删除pdf文件的最后一页?

时间:2013-07-17 17:04:59

标签: linux pdf pdftk

有人可以告诉我如何使用PDFtk删除PDF文件的最后一页吗?

3 个答案:

答案 0 :(得分:70)

使用cat操作,并指定页面范围。

pdftk infile.pdf cat 1-r2 output outfile.pdf

答案 1 :(得分:5)

您需要查找页数,然后将其与pdftk cat函数一起使用,因为(AFAICT)pdftk不允许指定“从上一次偏移”。

来自Poppler(http://poppler.freedesktop.org/)的'pdfinfo'之类的工具可以提供此功能。

在一些bash脚本中包装它可以轻松地自动执行此过程:

page_count=`pdfinfo "$INFILE" | grep 'Pages:' | awk '{print $2}'`
page_count=$(( $page_count - 1 ))
pdftk A="$INFILE" cat A1-$page_count output "$OUTFILE"

显然,添加参数,错误检查以及什么也不能放在所述脚本中:

#! /bin/sh

### Path to the PDF Toolkit executable 'pdftk'
pdftk='/usr/bin/pdftk'
pdfinfo='/usr/bin/pdfinfo'


####################################################################
script=`basename "$0"`


### Script help
if [ "$1" = "" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ] || [ "$1" = "-?" ] || [ "$1" = "/?" ]; 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="$1"
if [ ! -r "$INFILE" ]; then
    echo "$script: Failed to read [$INFILE]"
    exit 2
fi

OUTFILE="$2"
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 $2}'`
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

答案 2 :(得分:3)

使用cpdf,您可以使用代字号和开头来引用页面与文档末尾的距离。

所以,我们可以做到

cpdf in.pdf 1-~2 -o out.pdf