分享一個Python批量ppt轉圖片,pdf轉圖片,word轉圖片腳本

前言

某天我們運營在編輯后臺的時候說每次上傳ppt,pdf,word時都要把每個文件先導出一次圖片,然后一個一個上傳(png用作預覽,ppt,pdf,word源文件不能直接下載的),說效率太低了,問有沒有辦法只要上傳文件就行。當時就想了想每個上傳都轉一次確實效率低,因為有些導出來可能有幾十張圖片。


12.jpg

最后通過GitHub和網(wǎng)友博客。最終把自動轉圖片問題解決。腳本有錯誤不優(yōu)雅的歡迎指出~

本文python版本3.9.5

腳本思路

運營人員上傳ppt,pdf,word到數(shù)據(jù)庫,腳本讀取文件遠程連接->下載到本地->轉圖片->上傳到云存儲->獲取遠程圖片連接->存儲到數(shù)據(jù)庫。

連接數(shù)據(jù)庫查詢需要轉的集合

    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, &quot;Courier New&quot;, 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;"># 獲取需要轉的文件集合
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轉圖片


# 初始化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, &quot;Courier New&quot;, 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轉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格式
        # 關閉打開的ppt文件
        ppt.Close()
    except IOError:
        print('PPT轉png失敗',url)
    else:
        print("PPT轉png成功",url)</pre>

pdf轉圖片

# pdf轉圖片
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)
            # 每個尺寸的縮放系數(shù)為1.3,這將為我們生成分辨率提高2.6的圖像。
            # 此處若是不做設置,默認圖片大小為: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轉png失敗',_url)
    else:
        print("pdf轉png成功",_url)</pre>

word轉圖片

word轉圖片要先中轉一次,先把word轉成pdf,然后再把pdf轉成圖片。

def word2pdf(word_file):
    '''
    將word文件轉換成pdf文件
    :param word_file: word文件
    :return:
    '''
    # 獲取word格式處理對象
    word = Dispatch('Word.Application')
    # 以Doc對象打開文件
    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,'----轉pdf成功')
    # 關閉doc對象
    doc_.Close()
    # 退出word對象
    word.Quit()
    return os.path.basename(word_file).split('.')[0]+'.pdf'</pre>

然后在調(diào)用上面的 pdf2png

上傳到對象存儲

這里就不貼出來了,我們用的是華為云的OBS。阿里云,騰訊云等對象存儲都有各自的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) #轉png
        imgArr = uploadImg(_url) #上傳圖片到云存儲拿到遠程鏈接
        setData(_url,id,imgArr,connect) #保存到數(shù)據(jù)庫
        time.sleep(2)
        print('\n')
        print('\n')
    connect['cur'].close()    #關閉游標
    connect['conn'].close()   #斷開數(shù)據(jù)庫,釋放資源
    powerpoint.Quit()
    input("輸入任意鍵結束")</pre>

因為是自己內(nèi)部用,所以可以使用pyinstaller打包成了一個exe,提供給運營用,資料上傳完運行下,便可批量自動轉圖片了。

pyinstaller -c -F -i a.ico ppt_to_img.py</pre>

最后

希望本文對你有一些幫助,如有問題,歡迎指正~

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容