前言
某天我們運(yùn)營在編輯后臺(tái)的時(shí)候說每次上傳ppt,pdf策菜,word時(shí)都要把每個(gè)文件先導(dǎo)出一次圖片,然后一個(gè)一個(gè)上傳(png用作預(yù)覽,ppt晶疼,pdf,word源文件不能直接下載的)又憨,說效率太低了翠霍,問有沒有辦法只要上傳文件就行。當(dāng)時(shí)就想了想每個(gè)上傳都轉(zhuǎn)一次確實(shí)效率低蠢莺,因?yàn)橛行?dǎo)出來可能有幾十張圖片寒匙。
最后通過GitHub和網(wǎng)友博客。最終把自動(dòng)轉(zhuǎn)圖片問題解決浪秘。腳本有錯(cuò)誤不優(yōu)雅的歡迎指出~
本文python版本3.9.5
腳本思路
運(yùn)營人員上傳ppt蒋情,pdf埠况,word到數(shù)據(jù)庫耸携,腳本讀取文件遠(yuǎn)程連接->下載到本地->轉(zhuǎn)圖片->上傳到云存儲(chǔ)->獲取遠(yuǎn)程圖片連接->存儲(chǔ)到數(shù)據(jù)庫。
連接數(shù)據(jù)庫查詢需要轉(zhuǎn)的集合
conn = pymysql.connect(host='127.0.0.1', user='root', password="",database ='pic',port=3306)
# host=localhost #也可以寫,如果127.0.0.1不能用的話# 登錄數(shù)據(jù)庫
cur = conn.cursor(pymysql.cursors.DictCursor)
return {
"conn":conn,
"cur":cur
}</pre>
<pre class="prettyprint hljs python" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># 獲取需要轉(zhuǎn)的文件集合
def getUrlArr(cur):
sql = 'select * from pic' # 寫自己的sql語句
arr = ''
try:
cur.execute(sql)
ex = cur.execute(sql)
arr = cur.fetchmany(ex)
except Exception as e:
raise e
finally:
return arr</pre>
下載文件到本地
def downLoad(url):
print('----url-----',url)
filename=''
try:
suffix = os.path.basename(url).split('.')[1]
filename = "miaohui."+suffix
if os.path.exists(filename): # 如果文件存在 刪除文件
os.remove(filename)
wget.download(url,filename)
except IOError:
print('下載失敗',url)
else:
print('\n')
print('下載成功',url)
return filename</pre>
ppt轉(zhuǎn)圖片
# 初始化PPT
def init_powerpoint():
powerpoint = win32com.client.Dispatch('PowerPoint.Application') #comtypes.client.CreateObject("Powerpoint.Application")
powerpoint.Visible = 1
return powerpoint</pre>
<pre class="prettyprint hljs python" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># PPT轉(zhuǎn)png
def ppt2png(url,pptFileName,powerpoint):
try:
ppt_path = os.path.abspath(pptFileName)
ppt = powerpoint.Presentations.Open(ppt_path)
#保存為圖片
img_path = os.path.abspath(downLoad_path + '.png')
ppt.SaveAs(img_path, 18) # 17保存為jpg格式
# 關(guān)閉打開的ppt文件
ppt.Close()
except IOError:
print('PPT轉(zhuǎn)png失敗',url)
else:
print("PPT轉(zhuǎn)png成功",url)</pre>
pdf轉(zhuǎn)圖片
# pdf轉(zhuǎn)圖片
def pdf2png(_url,pptFileName):
imagePath = os.path.abspath(downLoad_path)
try:
pdfDoc = fitz.open(pptFileName)
for pg in range(pdfDoc.pageCount):
page = pdfDoc[pg]
rotate = int(0)
# 每個(gè)尺寸的縮放系數(shù)為1.3辕翰,這將為我們生成分辨率提高2.6的圖像夺衍。
# 此處若是不做設(shè)置,默認(rèn)圖片大小為:792X612, dpi=96
zoom_x = 1.33333333 # (1.33333333-->1056x816) (2-->1584x1224)
zoom_y = 1.33333333
mat = fitz.Matrix(zoom_x, zoom_y).prerotate(rotate)
pix = page.get_pixmap(matrix=mat, alpha=False)
if not os.path.exists(imagePath): # 判斷存放圖片的文件夾是否存在
os.makedirs(imagePath) # 若圖片文件夾不存在就創(chuàng)建
pix.save(imagePath + '/' + '幻燈片%s.png' % pg) # 將圖片寫入指定的文件夾內(nèi)
except IOError:
print('pdf轉(zhuǎn)png失敗',_url)
else:
print("pdf轉(zhuǎn)png成功",_url)</pre>
word轉(zhuǎn)圖片
word轉(zhuǎn)圖片要先中轉(zhuǎn)一次喜命,先把word轉(zhuǎn)成pdf沟沙,然后再把pdf轉(zhuǎn)成圖片。
def word2pdf(word_file):
'''
將word文件轉(zhuǎn)換成pdf文件
:param word_file: word文件
:return:
'''
# 獲取word格式處理對(duì)象
word = Dispatch('Word.Application')
# 以Doc對(duì)象打開文件
doc_ = word.Documents.Open(word_file)
# 另存為pdf文件
suffix = os.path.basename(word_file).split('.')[1]
doc_.SaveAs(word_file.replace(suffix, "pdf"), FileFormat=17)
print(word_file,'----轉(zhuǎn)pdf成功')
# 關(guān)閉doc對(duì)象
doc_.Close()
# 退出word對(duì)象
word.Quit()
return os.path.basename(word_file).split('.')[0]+'.pdf'</pre>
然后在調(diào)用上面的 pdf2png
上傳到對(duì)象存儲(chǔ)
這里就不貼出來了壁榕,我們用的是華為云的OBS矛紫。阿里云,騰訊云等對(duì)象存儲(chǔ)都有各自的Python版SDK牌里,接入也很方便颊咬。
最后組在一起調(diào)用
connect = connectDatabase()
powerpoint = init_powerpoint()
downArr = getUrlArr(connect['cur'])
for i in downArr:
if(os.path.exists('./'+downLoad_path)):
removeFileInFirstDir('./'+downLoad_path)
_url = unquote(i['url'])
id = i['id']
pptFileName = downLoad(_url)#下載文件
if(('.pdf' in _url) ==True):
pdf2png(_url,pptFileName)
elif (('.doc' in _url) ==True):
_file = os.path.abspath(pptFileName)
pdfNmae = word2pdf(_file)
pdf2png(_url,pdfNmae)
else:
ppt2png(_url,pptFileName,powerpoint) #轉(zhuǎn)png
imgArr = uploadImg(_url) #上傳圖片到云存儲(chǔ)拿到遠(yuǎn)程鏈接
setData(_url,id,imgArr,connect) #保存到數(shù)據(jù)庫
time.sleep(2)
print('\n')
print('\n')
connect['cur'].close() #關(guān)閉游標(biāo)
connect['conn'].close() #斷開數(shù)據(jù)庫,釋放資源
powerpoint.Quit()
input("輸入任意鍵結(jié)束")</pre>
因?yàn)槭亲约簝?nèi)部用,所以可以使用pyinstaller打包成了一個(gè)exe牡辽,提供給運(yùn)營用喳篇,資料上傳完運(yùn)行下,便可批量自動(dòng)轉(zhuǎn)圖片了态辛。
pyinstaller -c -F -i a.ico ppt_to_img.py</pre>
最后
希望本文對(duì)你有一些幫助麸澜,如有問題,歡迎指正~