【kimol君的無聊小發明】—用python插入獨創性宣告
- 前言
- 一、代碼分析
- 二、完整代碼
- 寫在最后
前言
某個夜深人靜的夜晚,夜微涼風微揚,月光照進我的書房~
當我打開檔案夾以回顧往事之余,驚現許多看似雜亂的無聊代碼,我拍腿正坐,一個想法油然而生:“生活已然很無聊,不如再無聊些叭”,
于是,我決定開一個專題,便稱之為kimol君的無聊小發明,
妙…啊~~~
想必寫畢設的時候,大家都會遇到一個問題,那就是得在明評版的論文里面插入一個獨創性宣告,就因為這個事情,我折騰了好久,各種在線網站都試過了,然而基本都需要充值或者會員啥的,(小聲嚷嚷:“萬惡的資本”)
害~一不做二不休,我干脆自己寫個小工具好了,
一、代碼分析
利用PyPDF2庫便可輕松地對PDF檔案進行處理,具體用法大家可以參考這里,首先是安裝這個庫:
pip install PyPDF2
定義輸入和輸出物件:
# 定義輸出物件
outputName = 'output.pdf'
output = PdfFileWriter()
# 定義讀取物件
thesisPDF = PdfFileReader(open(thesisName,'rb'))
insertPDF = PdfFileReader(open(insertName,'rb'))
N_page = thesisPDF.getNumPages()
pos = int(input('論文一共有"%d"頁,請輸入需要插入的位置:'%N_page))
分別讀取論文的PDF和獨創性宣告的PDF,隨后將宣告插入到論文中的指定頁面:
# 將宣告插入到指定頁面
for i in range(pos):
output.addPage(thesisPDF.getPage(i))
output.addPage(insertPDF.getPage(0)) # 插入
for i in range(pos,N_page):
output.addPage(thesisPDF.getPage(i))
將結果保存到本地:
# 保存插入后的結果
output.write(open(outputName,'wb'))
到這里,我們就已經成功的把宣告插入到指定的頁面中了,你沒有看錯,就是這么簡單~
二、完整代碼
將以上幾部分整合起來,完整的代碼如下:
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 5 20:13:18 2020
@author: kimol_love
"""
import os
from PyPDF2 import PdfFileWriter, PdfFileReader
# 用戶輸入論文名
while True:
thesisName = input('請輸入論文的檔案名:')
if not os.path.exists(thesisName):
print('檔案不存在,請重新輸入!')
continue
if thesisName[-4:].lower() != '.pdf':
print('后綴錯誤,請重新輸入!')
continue
break
# 用戶輸入需要插入的頁面
while True:
insertName = input('請輸入宣告的檔案名:')
if not os.path.exists(insertName):
print('檔案不存在,請重新輸入!')
continue
if thesisName[-4:].lower() != '.pdf':
print('后綴錯誤,請重新輸入!')
continue
break
# 定義輸出物件
outputName = 'output.pdf'
output = PdfFileWriter()
# 定義讀取物件
thesisPDF = PdfFileReader(open(thesisName,'rb'))
insertPDF = PdfFileReader(open(insertName,'rb'))
N_page = thesisPDF.getNumPages()
pos = int(input('論文一共有"%d"頁,請輸入需要插入的位置:'%N_page))
# 將宣告插入到指定頁面
for i in range(pos):
output.addPage(thesisPDF.getPage(i))
output.addPage(insertPDF.getPage(0)) # 插入
for i in range(pos,N_page):
output.addPage(thesisPDF.getPage(i))
# 保存插入后的結果
output.write(open(outputName,'wb'))
print('"%s"已經成功插入到"%s"的第%d頁'%(insertName,thesisName,pos))
運行效果如下:

打開生成的output.pdf,可以發現已經成功插入,
寫在最后
最后,感謝各位大大的耐心閱讀,咋們下次再會~
創作不易,大俠請留步… 動起可愛的雙手,來個贊再走唄 (???←?)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/206277.html
標籤:其他
