• Python实现PDF转换文件格式


    最近工作中经常遇到收到其他人提供的pdf文档,想要编辑修改下或者复制部分内容比较困难,想通过现有的pdf工具软件转换文档格式,基本都要充钱,为了免费实现pdf转换工具,网上查了下相关技术方案,整理了下代码,测试真实有效,分享下。

    第一步,安装相关第三方库

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

    第二步,编写代码

    pdfConverter.py:

    1. import datetime
    2. import os
    3. # fitz就是pip install PyMuPDF
    4. import fitz
    5. # pdf2docx 也是封装 fitz 模块为基础开发的
    6. from pdf2docx import Converter
    7. '''
    8. pdf 转换工具包
    9. pdf 转成 word
    10. pdf 转成 图片
    11. pdf 转成 html
    12. '''
    13. def pdf2word(file_path):
    14. '''
    15. @方法名称: pdf转word
    16. @中文注释: pdf转word
    17. @入参:
    18. @param file_path str pdf文件路径
    19. @出参:
    20. @返回状态:
    21. @return 0 失败或异常
    22. @return 1 成功
    23. @返回错误码
    24. @返回错误信息
    25. @param doc_file str word文件名
    26. @作 者: PandaCode辉
    27. @创建时间: 2023-10-16
    28. @使用范例: pdf2word('test.pdf')
    29. '''
    30. try:
    31. if (not type(file_path) is str):
    32. return [0, "111111", "pdf文件路径参数类型错误,不为字符串", [None]]
    33. # 开始时间
    34. startTime = datetime.datetime.now()
    35. # 提取文件名,去除文件后缀
    36. file_name = file_path.split('.')[0]
    37. print(file_name)
    38. # word文件名
    39. doc_file = f'{file_name}.docx'
    40. print(doc_file)
    41. p2w = Converter(file_path)
    42. '''
    43. convert(doc_file,start,end)函数中
    44. doc_file:转化完成后文件名
    45. start:转化开始页面
    46. end:转化结束页面
    47. 注意点:
    48. ①若不给start,end参数则默认转化全篇
    49. ②对于不连续的页面,也可写作convert(doc_file , pages = [2,4,6])
    50. '''
    51. p2w.convert(doc_file, start=0, end=None)
    52. p2w.close()
    53. endTime = datetime.datetime.now() # 结束时间
    54. print('pdf转word耗时: %s 秒' % (endTime - startTime).seconds)
    55. print("pdf转word成功")
    56. # 返回容器
    57. return [1, '000000', 'pdf转word成功', [doc_file]]
    58. except Exception as e:
    59. p2w.close()
    60. print("pdf转word异常," + str(e))
    61. return [0, '999999', "pdf转word异常," + str(e), [None]]
    62. def pdf2image(file_path, image_path):
    63. '''
    64. @方法名称: pdf转图片
    65. @中文注释: pdf转图片
    66. @入参:
    67. @param file_path str pdf文件路径
    68. @param image_path str 输出图片路径
    69. @出参:
    70. @返回状态:
    71. @return 0 失败或异常
    72. @return 1 成功
    73. @返回错误码
    74. @返回错误信息
    75. @param image_path str 输出图片路径
    76. @作 者: PandaCode辉
    77. @创建时间: 2023-10-16
    78. @使用范例: pdf2image('test.pdf', './images')
    79. '''
    80. try:
    81. if (not type(file_path) is str):
    82. return [0, "111111", "pdf文件路径参数类型错误,不为字符串", [None]]
    83. if (not type(image_path) is str):
    84. return [0, "111112", "输出图片路径参数类型错误,不为字符串", [None]]
    85. # 开始时间
    86. startTime = datetime.datetime.now()
    87. print("pdfPath=" + file_path)
    88. # 提取文件名,去除文件后缀
    89. file_name = file_path.split('.')[0]
    90. print(file_name)
    91. print("imagePath=" + imagePath)
    92. # 打开pdf文档
    93. pdfDoc = fitz.open(file_path)
    94. # 判断存放图片的文件夹是否存在
    95. if not os.path.exists(image_path):
    96. # 若图片文件夹不存在就创建
    97. os.makedirs(image_path)
    98. # Document.page_count 页数 (int)
    99. # 循环页数
    100. for pg in range(pdfDoc.page_count):
    101. print('=======%s========' % (pg + 1))
    102. '''
    103. 页面(Page)处理是MuPDF功能的核心。
    104. 您可以将页面呈现为光栅或矢量(SVG)图像,可以选择缩放、旋转、移动或剪切页面。
    105. 您可以提取多种格式的页面文本和图像,并搜索文本字符串。
    106. 对于PDF文档,可以使用更多的方法向页面添加文本或图像。
    107. '''
    108. page = pdfDoc[pg]
    109. rotate = int(0)
    110. # 每个尺寸的缩放系数为1.3,这将为我们生成分辨率提高2.6的图像。
    111. # 此处若是不做设置,默认图片大小为:792X612, dpi=96
    112. zoom_x = 1.33333333 # (1.33333333-->1056x816) (2-->1584x1224)
    113. zoom_y = 1.33333333
    114. mat = fitz.Matrix(zoom_x, zoom_y).prerotate(rotate)
    115. '''
    116. pix是一个Pixmap对象,它(在本例中)包含页面的RGB图像,可用于多种用途。
    117. 方法Page.get_pixmap()提供了许多用于控制图像的变体:分辨率、颜色空间(例如,生成灰度图像或具有减色方案的图像)、
    118. 透明度、旋转、镜像、移位、剪切等。
    119. 例如:创建RGBA图像(即,包含alpha通道),指定pix=page.get_pixmap(alpha=True)。
    120. Pixmap包含以下引用的许多方法和属性。其中包括整数宽度、高度(每个像素)和跨距(一个水平图像行的字节数)。
    121. 属性示例表示表示图像数据的矩形字节区域(Python字节对象)。
    122. 还可以使用page.get_svg_image()创建页面的矢量图像。
    123. '''
    124. pix = page.get_pixmap(matrix=mat, alpha=False)
    125. # 将图片写入指定的文件夹内
    126. pix.save(image_path + '/' + file_name + '_%s.png' % (pg + 1))
    127. endTime = datetime.datetime.now() # 结束时间
    128. print('pdf转图片耗时: %s 秒' % (endTime - startTime).seconds)
    129. print("pdf转图片成功")
    130. # 返回容器
    131. return [1, '000000', '"pdf转图片成功', [image_path]]
    132. except Exception as e:
    133. print("pdf转图片异常," + str(e))
    134. return [0, '999999', "pdf转图片异常," + str(e), [None]]
    135. def pdf2html(file_path):
    136. '''
    137. @方法名称: pdf转html
    138. @中文注释: pdf转html
    139. @入参:
    140. @param file_path str pdf文件路径
    141. @出参:
    142. @返回状态:
    143. @return 0 失败或异常
    144. @return 1 成功
    145. @返回错误码
    146. @返回错误信息
    147. @param out_file str html文件名
    148. @作 者: PandaCode辉
    149. @创建时间: 2023-10-16
    150. @使用范例: pdf2html('test.pdf')
    151. '''
    152. try:
    153. if (not type(file_path) is str):
    154. return [0, "111111", "pdf文件路径参数类型错误,不为字符串", [None]]
    155. # 开始时间
    156. startTime = datetime.datetime.now()
    157. print("pdfPath=" + pdfPath)
    158. # 打开pdf文档
    159. pdfDoc = fitz.open(pdfPath)
    160. # 提取文件名,去除文件后缀
    161. file_name = pdfPath.split('.')[0]
    162. print(file_name)
    163. out_file = f'{file_name}.html'
    164. print(out_file)
    165. # 打开文件,首次创建写入
    166. fo = open(out_file, "w+", encoding="utf-8")
    167. # Document.page_count 页数 (int)
    168. # 循环页数
    169. for pg in range(pdfDoc.page_count):
    170. print('=======%s========' % (pg + 1))
    171. '''
    172. 页面(Page)处理是MuPDF功能的核心。
    173. 您可以将页面呈现为光栅或矢量(SVG)图像,可以选择缩放、旋转、移动或剪切页面。
    174. 您可以提取多种格式的页面文本和图像,并搜索文本字符串。
    175. 对于PDF文档,可以使用更多的方法向页面添加文本或图像。
    176. '''
    177. page = pdfDoc[pg]
    178. '''
    179. 提取文本和图像 page.get_text(opt)
    180. 我们还可以以多种不同的形式和细节级别提取页面的所有文本、图像和其他信息:
    181. 对opt使用以下字符串之一以获取不同的格式:
    182. "text":(默认)带换行符的纯文本。无格式、无文字位置详细信息、无图像
    183. "blocks":生成文本块(段落)的列表
    184. "words":生成单词列表(不包含空格的字符串)
    185. "html":创建页面的完整视觉版本,包括任何图像。这可以通过internet浏览器显示
    186. "dict" / "json":与HTML相同的信息级别,但作为Python字典或resp.JSON字符串。
    187. "rawdict" / "rawjson":"dict" / "json"
    188. 的超级集合。它还提供诸如XML之类的字符详细信息。
    189. "xhtml":文本信息级别与文本版本相同,但包含图像。
    190. "xml":不包含图像,但包含每个文本字符的完整位置和字体信息。使用XML模块进行解释
    191. '''
    192. # html 格式保存原PDF文本和图片样式还行
    193. # text = page.get_text('html')
    194. # xhtml 格式保存原PDF文本和图片样式更好
    195. text = page.get_text('xhtml')
    196. # 写入文件
    197. fo.write(text)
    198. # 关闭文件
    199. fo.close()
    200. endTime = datetime.datetime.now() # 结束时间
    201. print('pdf转html耗时: %s 秒' % (endTime - startTime).seconds)
    202. print("pdf转html成功")
    203. # 返回容器
    204. return [1, '000000', '"pdf转html成功', [out_file]]
    205. except Exception as e:
    206. # 关闭文件
    207. fo.close()
    208. print("pdf转html异常," + str(e))
    209. return [0, '999999', "pdf转html异常," + str(e), [None]]
    210. if __name__ == "__main__":
    211. # PDF地址
    212. pdfPath = 'test.pdf'
    213. # 1,pdf转word
    214. pdf2word(pdfPath)
    215. # 储存图片的目录
    216. imagePath = './images'
    217. # 2,pdf转图片
    218. pdf2image(pdfPath, imagePath)
    219. # 3,pdf转html
    220. pdf2html(pdfPath)

    第三步,运行查看效果

  • 相关阅读:
    基于sanic的服务使用celery完成动态修改定时任务
    面试官:你知道Comparable 和 Comparator 的区别吗?我:巴拉巴拉
    02 DevOps 之 Jenkins
    Fiddler 抓取 HTTPS 请求大全
    NC20242 [SCOI2005]最大子矩阵
    基于改进遗传算法把最优功率损耗降至最低(Matlab代码实现)
    Docker从入门到进阶之基础操作(3)—— 仓库(Repository)
    高可用篇_A Docker容器化技术_I Docker基本概念
    【PXIE301-211】基于PXIE总线的16路并行LVDS数据采集、4路低速、2路隔离RS422数据处理平台
    JDK中自带的JVM分析工具
  • 原文地址:https://blog.csdn.net/xionghui2007/article/details/133861909