Remove the last page of a pdf file using PDFtk?

妖精的绣舞 提交于 2020-07-16 16:15:39

问题


Can someone please tell me how to remove the last page of a PDF file, using PDFtk?


回答1:


Using the cat operation, and specifying a page range.

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



回答2:


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".

A tool like 'pdfinfo' from Poppler (http://poppler.freedesktop.org/) can provide this.

Wrapping this in a bit of bash scripting can easily automate this process:

page_count=`pdfinfo "$INFILE" | grep 'Pages:' | awk '{print $2}'`
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 "$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



回答3:


With cpdf, you can reference a page by how far it is from the end of the document, using a tilde, as well as the beginning.

So, we can do

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


来源:https://stackoverflow.com/questions/17705974/remove-the-last-page-of-a-pdf-file-using-pdftk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!