如何以交织的页面顺序合并2个PDF文件?


13

我有一个双面打印的多页文档,可使用线性批量扫描仪进行扫描。因此,结果是我得到2个PDF文件:一个包含所有奇数页,第二个包含所有偶数页。我需要将它们自然合并:

1. <- 1.1. (odd.pdf page 1 to result.pdf page 1)
2. <- 2.1. (even.pdf page 1 to result.pdf page 2)
3. <- 1.2. (odd.pdf page 2 to result.pdf page 3)
4. <- 2.2. (even.pdf page 2 to result.pdf page 4)

等等


只需找到一个PDF解析器,然后进行诸如此类的合并排序即可。
雏菊2012年

1
如果Stephane不能解决您的问题,您可以尝试使用perl模块CAM::PDF,稍后再给您一个脚本。这两个pdf的页数是否相同?
雏菊2012年

Answers:


7

请参阅中的pdfseparatepdfunite命令poppler-utils。第一个将页面从每个文档中分离成单独的文件,第二个将页面按所需的顺序合并到新文档中。

还要注意,由于扫描仪始终会为您提供光栅图像(有些像您可以将其连接成PDF文件),也许您可​​以将其配置为输出图像(png,tiff ...),然后自己将其连接成PDF。 ImageMagick。


这听起来像我需要的,让我们尝试...
Ivan

1
确实。优秀的。简单易用,可满足我的需求。顺便说一句,我当然要先问问谷歌,而我发现完全一样的解决方案要复杂得多。
伊万(Ivan)

我在Ubuntu 18.04上进行了尝试(使用@TCF中的有用脚本),它将两个约5.5Mb的文件转换为一个197Mb的文件,因此在完成此工作的同时,它仍然无法使用(我需要通过电子邮件发送结果!) 。
Reuben Thomas

12

pdftk有一个shuffle命令来整理页面:

pdftk A=odd.pdf B=even.pdf shuffle A B output collated.pdf

1
这对我来说效果很好,但是进行了一些调整以反转偶数页(假设我在未先反转页面顺序的情况下对其进行了扫描):pdftk A = recto.pdf B = verso.pdf shuffle整理了Bend-1输出。 pdf
Reuben Thomas

太棒了,谢谢-这非常好
infomaniac

2

只需使用bash一下即可pdfjam

构建一个输入参数数组:

for k in $(seq 1 ${N_PAGES}); do
    PAGES+=(odd.pdf);
    PAGES+=($k);
    PAGES+=(even.pdf);
    PAGES+=($k);
done

这应该允许您将其用作以下内容的输入列表pdfjoin

 pdfjoin ${PAGES[@]} --outfile shuffled.pdf

2
应该注意的是,这pdfjoin是一个包装器脚本,pdfjam它本身就是围绕pdfpagesLaTeX包(和pdflatex)的包装器脚本,因此这意味着它将LaTeX作为依赖项。
斯特凡Chazelas


0

我希望做的基本上是同一件事,而斯特凡·查泽拉斯(StéphaneChazelas)的回答非常有帮助。我经常这样做,以至于我使用他建议的命令编写了一个简单的Python脚本来自动化操作。默认情况下,它会反转偶数页的顺序,但是可以通过命令行标志来抑制。

这个问题有点陈旧,所以我希望原始问询者的需求已经得到满足。但是,该脚本可能对将来到达这里的人很有用,因此我将其放在下面。

#!/usr/bin/python
"""A simple script to merge two PDFs."""

import argparse
from os import listdir
from os.path import join as opjoin
import shutil
from subprocess import check_call, CalledProcessError
import tempfile

SEPARATE = 'pdfseparate %s %s'
MERGE = 'pdfunite %s %s'

def my_exec(command):
    """Execute a command from a shell, ignoring errors."""
    try:
        check_call(command, shell=True)
    except CalledProcessError:
        pass

def run(odd, even, out, reverse_odd=False, reverse_even=True):
    """Interleave odd and even pages from two PDF files."""
    folder = tempfile.mkdtemp()
    my_exec(SEPARATE % (odd, opjoin(folder, 'odd%d.pdf')))
    my_exec(SEPARATE % (even, opjoin(folder, 'even%d.pdf')))
    odd_files = []
    even_files = []
    for curr_file in listdir(folder):
        filepath = opjoin(folder, curr_file)
        if curr_file.startswith('odd'):
            odd_files.append((filepath, int(curr_file[3:-4])))
        elif curr_file.startswith('even'):
            even_files.append((filepath, int(curr_file[4:-4])))
    func = lambda x: x[1]
    odd_files.sort(key=func, reverse=reverse_odd)
    even_files.sort(key=func, reverse=reverse_even)
    parts = []
    for line in zip(odd_files, even_files):
        parts.append(line[0][0])
        parts.append(line[1][0])
    my_exec(MERGE % (' '.join(parts), out))
    shutil.rmtree(folder)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Merge two PDF files.')
    parser.add_argument('odd_pages', help='PDF containing the odd pages.')
    parser.add_argument('even_pages', help='PDF containing the even pages.')
    parser.add_argument('output_file', help='The target output file.')
    parser.add_argument('--reverse-odd', action='store_true', 
                        help='Insert the odd pages in reverse order.')
    parser.add_argument('--no-reverse-even', action='store_true',
                        help='Suppress reversal of the even pages.')
    args = parser.parse_args()
    run(args.odd_pages, args.even_pages, args.output_file,
        args.reverse_odd, not args.no_reverse_even)

0

我碰到了这个bash脚本,它假设您以相反的顺序扫描了偶数页,但是您可以更改此设置以删除-r行中的evenpages=($(ls "$evenbase-$key-"* | sort -r))(这是第46行)

#!/bin/bash
# Copyright Fabien André <fabien.andre@xion345.info>
# Distributed under the MIT license
# This script interleaves pages from two distinct PDF files and produces an
# output PDF file. The odd pages are taken from a first PDF file and the even
# pages are taken from a second PDF file passed respectively as first and second
# argument.
# The first two pages of the output file are the first page of the
# odd pages PDF file and the *last* page of the even pages PDF file. The two
# following pages are the second page of the odd pages PDF file and the
# second to last page of the even pages PDF file and so on.
#
# This is useful if you have two-sided documents scanned each side on a
# different file as it can happen when using a one-sided Automatic Document
# Feeder (ADF)
#
# It does a similar job to :
# https://github.com/weltonrodrigo/pdfapi2/blob/46434ab3f108902db2bc49bcf06f66544688f553/contrib/pdf-interleave.pl
# but only requires bash (> 4.0) and poppler utils.
# Print usage/help message
function usage {
echo "Usage: $0 <PDF-even-pages-file> <PDF-odd-pages-file>"
exit 1
}
# Add leading zeros to pad numbers in filenames matching the pattern
# $prefix$number.pdf. This allows filenames to be easily sorted using
# sort.
# $1 : The prefix of the filenames to consider
function add_leading_zero {
prefix=$1
baseprefix=$(basename $prefix | sed -e 's/[]\/()$*.^|[]/\\&/g')
dirprefix=$(dirname $prefix)
for filename in "$prefix"*".pdf"
do
base=$(basename "$filename")
index=$(echo "$base" | sed -rn "s/$baseprefix([0-9]+).pdf$/\1/p")
newbase=$(printf "$baseprefix%04d.pdf" $index)
mv $filename "$dirprefix/$newbase"
done
}
# Interleave pages from two distinct PDF files and produce an output PDF file.
# Note that the pages from the even pages file (second file) will be used in
# the reverse order (last page first).
# $1 : Odd pages filename
# $2 : Odd pages filename with extension removed
# $3 : Even pages filename
# $4 : Even pages filename with extension removed
# $5 : Unique key used for temporary files
# $6 : Output file
function pdfinterleave {
oddfile=$1
oddbase=$2
evenfile=$3
evenbase=$4
key=$5
outfile=$6
# Odd pages
pdfseparate $oddfile "$oddbase-$key-%d.pdf"
add_leading_zero "$oddbase-$key-"
oddpages=($(ls "$oddbase-$key-"* | sort))
# Even pages
pdfseparate $evenfile "$evenbase-$key-%d.pdf"
add_leading_zero "$evenbase-$key-"
evenpages=($(ls "$evenbase-$key-"* | sort -r))
# Interleave pages
pages=()
for((i=0;i<${#oddpages[@]};i++))
do
pages+=(${oddpages[i]})
pages+=(${evenpages[i]})
done
pdfunite ${pages[@]} "$outfile"
rm ${oddpages[@]}
rm ${evenpages[@]}
}
if [ $# -lt 2 ]
then
usage
fi
if [ $1 == $2 ]
then
echo "Odd pages file and even pages file must be different." >&2
exit 1
fi
if ! hash pdfunite 2>/dev/null || ! hash pdfseparate 2>/dev/null
then
echo "This script requires pdfunite and pdfseparate from poppler utils" \
"to be in the PATH. On Debian based systems, they are found in the" \
"poppler-utils package"
exit 1
fi
oddbase=${1%.*}
evenbase=${2%.*}
odddir=$(dirname $oddbase)
oddfile=$(basename $oddbase)
evenfile=$(basename $evenbase)
outfile="$odddir/$oddfile-$evenfile-interleaved.pdf"
key=$(tr -dc "[:alpha:]" < /dev/urandom | head -c 8)
if [ -e $outfile ]
then
echo "Output file $outfile already exists" >&2
exit 1
fi
pdfinterleave $1 $oddbase $2 $evenbase $key $outfile
# SO - Bash command that prints a message on stderr
# http://stackoverflow.com/questions/2643165/bash-command-that-prints-a-message-on-stderr
# SO - Check if a program exists from a bash script
# http://stackoverflow.com/questions/592620/check-if-a-program-exists-from-a-bash-script
# SO - How to debug a bash script?
# http://stackoverflow.com/questions/951336/how-to-debug-a-bash-script
# SO - Escape a string for sed search pattern
# http://stackoverflow.com/questions/407523/escape-a-string-for-sed-search-pattern

资源

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.