1 Star 1 Fork 3

Lilililin / runoobPDF资源

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
merge_pdf_with_toc.py 1.95 KB
一键复制 编辑 原始数据 按行查看 历史
pingjing 提交于 2019-03-17 03:01 . first commit without download page
# -*- coding: utf-8 -*-
#! /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()
print(options, filenames)
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()
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/lilililinlinlin/runoobpdf_resource.git
git@gitee.com:lilililinlinlin/runoobpdf_resource.git
lilililinlinlin
runoobpdf_resource
runoobPDF资源
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891