python读取PDF文件中的指定页码的范围并存储到指定的文件名

读取PDF文件中的指定页码的范围并存储到指定的文件名

# -*- coding: utf-8 -*-
"""
Created on Mon Nov 27 21:36:12 2023

@author: cnliu
pip install pypdf2  #安装pypdf2  --3.o版
"""
from PyPDF2 import PdfWriter, PdfReader
import os
 
#pathToPDF = input('something like /home/pedro/Latin/ ... ')
pathToPDF = "d:/书/"
path2Extracts = 'd:/'
# get the names of the files available to extract from
files = os.listdir(pathToPDF)
# show the files in a loop so you can choose 1
# I haven't done that here
# choose a PDF from a list of PDFs from  as bookname
#bookTitle = bookname.replace('.pdf', '')
bookname = "AHaSuanFa.pdf"
# read the pdf
pdf = PdfReader(pathToPDF + bookname)
#pages = pdf.getNumPages() (deprecated)
pages = len(pdf.pages)
print('This pdf has ' + str(pages) + ' pages')
print('What pages do you want to get?')
startnum = input('what is the starting page number?  ')
print('If your last page is page 76, enter 76 for the end number')
endnum = input('what is the last page number?  ')
start = int(startnum) - 1
end = int(endnum)
# only need to open pdfWriter 1 time
pdf_writer = PdfWriter()
for page in range(start, end):
        pdf_writer.add_page(pdf.pages[page])
         
print('Enter the savename for this pdf, like CE3U8')
savename = input('Enter the name to save this pdf under, like CE3U8 No need to add .pdf ... ')
output_filename = savename + '.pdf'
 
with open(path2Extracts + output_filename, 'wb') as out:
        pdf_writer.write(out)
print(f'Created: {output_filename} and saved in', path2Extracts)
print('All done!')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值