如何合并pdf并为输出文件中的每个输入文件创建书签?(Linux)

yan*_*pas 3 linux pdf bookmarks open-source merge

我正在使用 Linux,我想要软件(或脚本、方法)来合并一些 pdf 并创建一个包含书签的统一输出 pdf。书签由 pdf 文件的文件名命名,用于合并和指向这些文件开始的页码。

Adobe Acrobat 也有类似的可能性,但它是非免费的且仅适用于 Windows。

yan*_*pas 6

更新:我对结果不满意,并用漂亮的 GUI 编写了这个:

https://github.com/Yanpas/PdfMerger


学习python并在一小时内编写(修改)程序:

#! /usr/bin/env python
# Original author Nicholas Kim, modified by Yan Pashkovsky
# New license - GPL v3
import sys
import time
from PyPDF2 import utils, PdfFileReader, PdfFileWriter

def get_cmdline_arguments():
    """Retrieve command line arguments."""
    
    from optparse import OptionParser
    
    usage_string = "%prog [-o output_name] file1, file2 [, ...]"

    parser = OptionParser(usage_string)
    parser.add_option(
        "-o", "--output",
        dest="output_filename",
        default=time.strftime("output_%Y%m%d_%H%M%S"),
        help="specify output filename (exclude .pdf extension); default is current date/time stamp"
    )
    
    options, args = parser.parse_args()
    if len(args) < 2:
        parser.print_help()
        sys.exit(1)
    return options, args
    
def main():
    options, filenames = get_cmdline_arguments()
    output_pdf_name = options.output_filename + ".pdf"
    files_to_merge = []

    # get PDF files
    for f in filenames:
        try:
            next_pdf_file = PdfFileReader(open(f, "rb"))
        except(utils.PdfReadError):
            print >>sys.stderr, "%s is not a valid PDF file." % f
            sys.exit(1)
        except(IOError):
            print >>sys.stderr, "%s could not be found." % f
            sys.exit(1)
        else:
            files_to_merge.append(next_pdf_file)

    # merge page by page
    output_pdf_stream = PdfFileWriter()
    j=0
    k=0
    for f in files_to_merge:
        for i in range(f.numPages):
            output_pdf_stream.addPage(f.getPage(i))
            if i==0:
                output_pdf_stream.addBookmark(str(filenames[k]),j)
            j = j + 1
        k += 1
        
    # create output pdf file
    try:
        output_pdf_file = open(output_pdf_name, "wb")
        output_pdf_stream.write(output_pdf_file)
    finally:
        output_pdf_file.close()

    print "%s successfully created." % output_pdf_name


if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)

这个程序需要 PyPDF2,你可以通过 安装它sudo pip install pypdf2,在此之前你需要安装 pip :) 只需打开终端并输入./pdfmerger.py *.pdf

  • 我将 python 脚本更新为 3.X 兼容,并将其放入 [以下要点](https://gist.github.com/jrwrigh/563e27dfc6cfdfa793a27733a75b846a)。 (4认同)

Ger*_*mia 6

此 Bash 脚本将使目录中的每个 PDF 在其第一页包含一个书签以及 PDF 文件名的文本,然后将它们全部连接起来。它可以处理非 ASCII 文件名。

#!/usr/bin/bash

cattedPDFname="${1:?Concatenated PDF filename}"

# make each PDF contain a single bookmark to first page
tempPDF=`mktemp`
for i in *.pdf
do
    bookmarkTitle=`basename "$i" .pdf`
    bookmarkInfo="BookmarkBegin\nBookmarkTitle: $bookmarkTitle\nBookmarkLevel: 1\nBookmarkPageNumber: 1"
    pdftk "$i" update_info_utf8 <(echo -en $bookmarkInfo) output $tempPDF verbose
    mv $tempPDF "$i"
done

# concatenate the PDFs
pdftk *.pdf cat output "$cattedPDFname" verbose
Run Code Online (Sandbox Code Playgroud)