Pybean <<
Previous Next >> RoboDK
PDF
從單機程式到全球資訊網服務:
Essential Computer Science 是 2021 年出版的電子書, 在校園裡可以直接下載 pdf 檔案, 以下 CPython 程式套用 PyPDF2 模組, 可以分割或合併 pdf 檔案.
# pip install PyPDF2
from PyPDF2 import PdfFileWriter, PdfFileReader
import os
def SplitPdf(pdfFileName, newFileName, fromPage, toPage):
"""Action to split user uploaded files
"""
pdfReader = PdfFileReader(open(pdfFileName, "rb"))
information = [(newFileName, fromPage, toPage)]
pdf_writer = PdfFileWriter()
pdf_writer.addPage(pdfReader.getPage(1))
for i in range(13, 18):
pdf_writer.addPage(pdfReader.getPage(i))
for page in range(len(information)):
start = information[page][1]
end = information[page][2]
while start<=end:
pdf_writer.addPage(pdfReader.getPage(start-1))
start+=1
if not os.path.exists("./"):
os.makedirs(savepath)
output_filename = '{}_{}_page_{}.pdf'.format(information[page][0], information[page][1], information[page][2])
with open(output_filename,'wb') as out:
pdf_writer.write(out)
outstring = "已經將 " + pdfFileName + " 中的第 " + str(fromPage) + " 到第 " + str(toPage) + "頁, 存為 " + output_filename
return outstring
def CombinePdf(pdfFileNames, newFileName):
"""Action to split user uploaded files
"""
# pdfFileNames is []
pdf_write_object = PdfFileWriter()
filenameString = ""
for filename in pdfFileNames:
pdf_read_object = PdfFileReader(open(filename, "rb"))
filenameString += filename + ", "
for page in range(pdf_read_object.numPages):
pdf_write_object.addPage(pdf_read_object.getPage(page))
final_file_object = open(newFileName + ".pdf", 'wb')
pdf_write_object.write(final_file_object)
final_file_object.close()
outstring = "已經將 " + filenameString+ " 合併為: "+ newFileName + ".pdf"
return outstring
pdfFileName = "2021_Book_EssentialComputerScience.pdf"
newFileName = "cp2022_textbook_part1.pdf"
fromPage = 21
toPage = 98
SplitPdf(pdfFileName, newFileName, fromPage, toPage)
print("done")
上列程式只能在單機執行, 假如再套用 Flask 全球資訊網框架. 就可以將單機程式配置在 server 上, 讓參與協同產品設計的成員可以在任何地方透過瀏覽器使用分割與合併 pdf 檔案的功能.
cp2022_CPython_pypdf2_Flask_project1.7z (for cp2022 @gm users only) / cp2022_CPython_pypdf2_Flask_project1.7z for @nfu
Pybean <<
Previous Next >> RoboDK