0

I would like to extract pages from various PDF files and create a new PDF file from those pages. What tool(s) should I use?

1 Answer 1

1

The basic answer is to use pdftk like so:

pdftk B=<input-file-1.pdf> C=<input-file-2.pdf> ... cat B<pagenum1> C<pagenum2> ... output <outputfile.pdf>;

Here is a script that takes an input file with each line having a PDF file (without a space in the name!!) then a page number:

<input-file-1.pdf> <pagenum1>
<input-file-2.pdf> <pagenum2>
...
#!/bin/bash

declare -a input_lines;
declare -a page_spec;
character_set=({A..Z});

handle="A";

increment_character() {
    for (( i=0; i < "${#character_set[@]}"; ++i )); do
        if [[ "$1" == "${character_set[$i]}" ]]; then
            echo "${character_set[$((i+1))]}";
            return;
        fi;
    done;
    echo "error";
}

increase_handle() {
    rolled_over=n;
    for (( l=${#handle}; l>0; --l )); do
        letter=${handle:$((l-1)):1};
        prefix="${handle:0:$((l-1))}";
        suffix="${handle:$((l))}";
        if [[ "$letter" == "${character_set[-1]}" ]]; then
            handle="${prefix}A$suffix";
            rolled_over=y;
        else
            new_letter=$(increment_character "$letter");
            handle="$prefix$new_letter$suffix";
            rolled_over=n;
            break;
        fi;
    done;
    if [[ "$rolled_over" == 'y' ]]; then
        handle=A"$handle";
        true;
    fi;
    echo "$handle";
}

echo "extracting...";
while IFS=' ' read -r file page; do
    if [[ "$file" = "#"* ]]; then
        # Comment
        continue;
    fi;
    if [[ -z "$file" ]]; then
        # Empty line
        continue;
    fi;
    handle="$(increase_handle)";
    input_lines+=("$handle=$file");
    page_num="$page";
    page_spec+=("$handle$page_num");
    echo "  $file";
    echo "      page $page_num";
done < "$1"

pdftk "${input_lines[@]}" cat "${page_spec[@]}" output "$1".pdf;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .