欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于Python實(shí)現(xiàn)PDF轉(zhuǎn)換文件格式

 更新時(shí)間:2025年01月19日 15:48:25   作者:PandaCode輝  
這篇文章主要為大家詳細(xì)介紹了如何基于Python實(shí)現(xiàn)PDF轉(zhuǎn)換文件格式,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

最近工作中經(jīng)常遇到收到其他人提供的pdf文檔,想要編輯修改下或者復(fù)制部分內(nèi)容比較困難,想通過(guò)現(xiàn)有的pdf工具軟件轉(zhuǎn)換文檔格式,基本都要充錢,為了免費(fèi)實(shí)現(xiàn)pdf轉(zhuǎn)換工具,網(wǎng)上查了下相關(guān)技術(shù)方案,整理了下代碼,測(cè)試真實(shí)有效,分享下。

第一步,安裝相關(guān)第三方庫(kù)

pip install PyMuPDF -i https://mirrors.aliyun.com/pypi/simple
pip install pdf2docx -i https://mirrors.aliyun.com/pypi/simple

第二步,編寫代碼

pdfConverter.py:

import datetime
import os
# fitz就是pip install PyMuPDF
import fitz
# pdf2docx 也是封裝 fitz 模塊為基礎(chǔ)開發(fā)的
from pdf2docx import Converter
 
'''
pdf 轉(zhuǎn)換工具包
pdf 轉(zhuǎn)成 word
pdf 轉(zhuǎn)成 圖片
pdf 轉(zhuǎn)成 html
'''
 
 
def pdf2word(file_path):
    '''
    @方法名稱: pdf轉(zhuǎn)word
    @中文注釋: pdf轉(zhuǎn)word
    @入?yún)?
        @param file_path str pdf文件路徑
    @出參:
        @返回狀態(tài):
            @return 0 失敗或異常
            @return 1 成功
        @返回錯(cuò)誤碼
        @返回錯(cuò)誤信息
        @param doc_file str word文件名
    @作    者: PandaCode輝
    @創(chuàng)建時(shí)間: 2023-10-16
    @使用范例: pdf2word('test.pdf')
    '''
    try:
        if (not type(file_path) is str):
            return [0, "111111", "pdf文件路徑參數(shù)類型錯(cuò)誤,不為字符串", [None]]
        # 開始時(shí)間
        startTime = datetime.datetime.now()
        # 提取文件名,去除文件后綴
        file_name = file_path.split('.')[0]
        print(file_name)
        # word文件名
        doc_file = f'{file_name}.docx'
        print(doc_file)
        p2w = Converter(file_path)
        '''
        convert(doc_file,start,end)函數(shù)中
        doc_file:轉(zhuǎn)化完成后文件名
        start:轉(zhuǎn)化開始頁(yè)面
        end:轉(zhuǎn)化結(jié)束頁(yè)面
        注意點(diǎn):
        ①若不給start,end參數(shù)則默認(rèn)轉(zhuǎn)化全篇
        ②對(duì)于不連續(xù)的頁(yè)面,也可寫作convert(doc_file , pages = [2,4,6])
        '''
        p2w.convert(doc_file, start=0, end=None)
        p2w.close()
        endTime = datetime.datetime.now()  # 結(jié)束時(shí)間
        print('pdf轉(zhuǎn)word耗時(shí): %s 秒' % (endTime - startTime).seconds)
        print("pdf轉(zhuǎn)word成功")
        # 返回容器
        return [1, '000000', 'pdf轉(zhuǎn)word成功', [doc_file]]
 
    except Exception as e:
        p2w.close()
        print("pdf轉(zhuǎn)word異常," + str(e))
        return [0, '999999', "pdf轉(zhuǎn)word異常," + str(e), [None]]
 
 
def pdf2image(file_path, image_path):
    '''
    @方法名稱: pdf轉(zhuǎn)圖片
    @中文注釋: pdf轉(zhuǎn)圖片
    @入?yún)?
        @param file_path str pdf文件路徑
        @param image_path str 輸出圖片路徑
    @出參:
        @返回狀態(tài):
            @return 0 失敗或異常
            @return 1 成功
        @返回錯(cuò)誤碼
        @返回錯(cuò)誤信息
        @param image_path str 輸出圖片路徑
    @作    者: PandaCode輝
    @創(chuàng)建時(shí)間: 2023-10-16
    @使用范例: pdf2image('test.pdf', './images')
    '''
    try:
        if (not type(file_path) is str):
            return [0, "111111", "pdf文件路徑參數(shù)類型錯(cuò)誤,不為字符串", [None]]
        if (not type(image_path) is str):
            return [0, "111112", "輸出圖片路徑參數(shù)類型錯(cuò)誤,不為字符串", [None]]
        # 開始時(shí)間
        startTime = datetime.datetime.now()
        print("pdfPath=" + file_path)
        # 提取文件名,去除文件后綴
        file_name = file_path.split('.')[0]
        print(file_name)
        print("imagePath=" + imagePath)
        # 打開pdf文檔
        pdfDoc = fitz.open(file_path)
        # 判斷存放圖片的文件夾是否存在
        if not os.path.exists(image_path):
            # 若圖片文件夾不存在就創(chuàng)建
            os.makedirs(image_path)
        # Document.page_count	頁(yè)數(shù) (int)
        # 循環(huán)頁(yè)數(shù)
        for pg in range(pdfDoc.page_count):
            print('=======%s========' % (pg + 1))
            '''
            頁(yè)面(Page)處理是MuPDF功能的核心。
            您可以將頁(yè)面呈現(xiàn)為光柵或矢量(SVG)圖像,可以選擇縮放、旋轉(zhuǎn)、移動(dòng)或剪切頁(yè)面。
            您可以提取多種格式的頁(yè)面文本和圖像,并搜索文本字符串。
            對(duì)于PDF文檔,可以使用更多的方法向頁(yè)面添加文本或圖像。
            '''
            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是一個(gè)Pixmap對(duì)象,它(在本例中)包含頁(yè)面的RGB圖像,可用于多種用途。
            方法Page.get_pixmap()提供了許多用于控制圖像的變體:分辨率、顏色空間(例如,生成灰度圖像或具有減色方案的圖像)、
            透明度、旋轉(zhuǎn)、鏡像、移位、剪切等。        
            例如:創(chuàng)建RGBA圖像(即,包含alpha通道),指定pix=page.get_pixmap(alpha=True)。        
            Pixmap包含以下引用的許多方法和屬性。其中包括整數(shù)寬度、高度(每個(gè)像素)和跨距(一個(gè)水平圖像行的字節(jié)數(shù))。
            屬性示例表示表示圖像數(shù)據(jù)的矩形字節(jié)區(qū)域(Python字節(jié)對(duì)象)。        
            還可以使用page.get_svg_image()創(chuàng)建頁(yè)面的矢量圖像。
            '''
            pix = page.get_pixmap(matrix=mat, alpha=False)
            # 將圖片寫入指定的文件夾內(nèi)
            pix.save(image_path + '/' + file_name + '_%s.png' % (pg + 1))
        endTime = datetime.datetime.now()  # 結(jié)束時(shí)間
        print('pdf轉(zhuǎn)圖片耗時(shí): %s 秒' % (endTime - startTime).seconds)
        print("pdf轉(zhuǎn)圖片成功")
        # 返回容器
        return [1, '000000', '"pdf轉(zhuǎn)圖片成功', [image_path]]
 
    except Exception as e:
        print("pdf轉(zhuǎn)圖片異常," + str(e))
        return [0, '999999', "pdf轉(zhuǎn)圖片異常," + str(e), [None]]
 
 
def pdf2html(file_path):
    '''
    @方法名稱: pdf轉(zhuǎn)html
    @中文注釋: pdf轉(zhuǎn)html
    @入?yún)?
        @param file_path str pdf文件路徑
    @出參:
        @返回狀態(tài):
            @return 0 失敗或異常
            @return 1 成功
        @返回錯(cuò)誤碼
        @返回錯(cuò)誤信息
        @param out_file str html文件名
    @作    者: PandaCode輝
    @創(chuàng)建時(shí)間: 2023-10-16
    @使用范例: pdf2html('test.pdf')
    '''
    try:
        if (not type(file_path) is str):
            return [0, "111111", "pdf文件路徑參數(shù)類型錯(cuò)誤,不為字符串", [None]]
        # 開始時(shí)間
        startTime = datetime.datetime.now()
        print("pdfPath=" + pdfPath)
        # 打開pdf文檔
        pdfDoc = fitz.open(pdfPath)
        # 提取文件名,去除文件后綴
        file_name = pdfPath.split('.')[0]
        print(file_name)
        out_file = f'{file_name}.html'
        print(out_file)
        # 打開文件,首次創(chuàng)建寫入
        fo = open(out_file, "w+", encoding="utf-8")
        # Document.page_count	頁(yè)數(shù) (int)
        # 循環(huán)頁(yè)數(shù)
        for pg in range(pdfDoc.page_count):
            print('=======%s========' % (pg + 1))
            '''
            頁(yè)面(Page)處理是MuPDF功能的核心。
            您可以將頁(yè)面呈現(xiàn)為光柵或矢量(SVG)圖像,可以選擇縮放、旋轉(zhuǎn)、移動(dòng)或剪切頁(yè)面。
            您可以提取多種格式的頁(yè)面文本和圖像,并搜索文本字符串。
            對(duì)于PDF文檔,可以使用更多的方法向頁(yè)面添加文本或圖像。
            '''
            page = pdfDoc[pg]
            '''
            提取文本和圖像 page.get_text(opt) 
                我們還可以以多種不同的形式和細(xì)節(jié)級(jí)別提取頁(yè)面的所有文本、圖像和其他信息:
                對(duì)opt使用以下字符串之一以獲取不同的格式:
                "text":(默認(rèn))帶換行符的純文本。無(wú)格式、無(wú)文字位置詳細(xì)信息、無(wú)圖像
                "blocks":生成文本塊(段落)的列表
                "words":生成單詞列表(不包含空格的字符串)
                "html":創(chuàng)建頁(yè)面的完整視覺(jué)版本,包括任何圖像。這可以通過(guò)internet瀏覽器顯示
                "dict" / "json":與HTML相同的信息級(jí)別,但作為Python字典或resp.JSON字符串。
                "rawdict" / "rawjson":"dict" / "json"
                的超級(jí)集合。它還提供諸如XML之類的字符詳細(xì)信息。
                "xhtml":文本信息級(jí)別與文本版本相同,但包含圖像。
                "xml":不包含圖像,但包含每個(gè)文本字符的完整位置和字體信息。使用XML模塊進(jìn)行解釋
            '''
            # html 格式保存原PDF文本和圖片樣式還行
            # text = page.get_text('html')
            # xhtml 格式保存原PDF文本和圖片樣式更好
            text = page.get_text('xhtml')
            # 寫入文件
            fo.write(text)
        # 關(guān)閉文件
        fo.close()
        endTime = datetime.datetime.now()  # 結(jié)束時(shí)間
        print('pdf轉(zhuǎn)html耗時(shí): %s 秒' % (endTime - startTime).seconds)
        print("pdf轉(zhuǎn)html成功")
        # 返回容器
        return [1, '000000', '"pdf轉(zhuǎn)html成功', [out_file]]
 
    except Exception as e:
        # 關(guān)閉文件
        fo.close()
        print("pdf轉(zhuǎn)html異常," + str(e))
        return [0, '999999', "pdf轉(zhuǎn)html異常," + str(e), [None]]
 
 
if __name__ == "__main__":
    # PDF地址
    pdfPath = 'test.pdf'
 
    # 1,pdf轉(zhuǎn)word
    pdf2word(pdfPath)
 
    # 儲(chǔ)存圖片的目錄
    imagePath = './images'
    # 2,pdf轉(zhuǎn)圖片
    pdf2image(pdfPath, imagePath)
 
    # 3,pdf轉(zhuǎn)html
    pdf2html(pdfPath)

第三步,運(yùn)行查看效果

到此這篇關(guān)于基于Python實(shí)現(xiàn)PDF轉(zhuǎn)換文件格式的文章就介紹到這了,更多相關(guān)Python PDF轉(zhuǎn)換文件格式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論