import base64
import sys
import PyPDF2
import fitz, os, datetime
def pdf_split(file_path, out_dir):
"""
单个pdf按页拆分pdf
@param file_path: 源文件路径(绝对路径)
@param out_dir: 输出pdf目录文件夹(绝对)
@return: 输出文件目录文件夹(绝对)
"""
pdf_file = open(file_path, 'rb') # 获取原 PDF 文件
pdf_reader = PyPDF2.PdfFileReader(pdf_file) # 创建 PDF 对象
source_name = pdf_file.name # 获取源文件名称,包含绝对路径
print("source_name", source_name)
output_dir = r"{}\{}".format(out_dir,source_name.split("\\")[-1].split(".")[0])
print("output_dir", output_dir)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
pdf_writer = PyPDF2.PdfFileWriter() # 创建一个空白 PDF 对象
for page_num in range(pdf_reader.numPages): # 将每页内容分别写入一个新文件
page_obj = pdf_reader.getPage(page_num)
pdf_writer.addPage(page_obj) # 向空白 PDF 对象中添加要复制的 PDF页面
new_name = "{}\{}.pdf".format(output_dir, str(page_num))
# print("new_name", new_name)
pdf_new_file = open(new_name, 'wb') # 创建一个新文件
pdf_writer.write(pdf_new_file) # 将添加了内容的空白 PDF 对象,写入到新建文件中
pdf_new_file.close()
pdf_writer.__init__() # 将 PDF 对象初始化
pdf_file.close()
return output_dir
def pyMuPDF_fitz(pdfPath, imagePath):
"""
单个pdf按页拆分为图片
"""
startTime_pdf2img = datetime.datetime.now()#开始时间
print("imagePath="+imagePath)
pdfDoc = fitz.open(pdfPath)
for pg in range(pdfDoc.pageCount):
page = pdfDoc[pg]
rotate = int(0)
# 每个尺寸的缩放系数为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.getPixmap(matrix=mat, alpha=False)
if not os.path.exists(imagePath):#判断存放图片的文件夹是否存在
os.makedirs(imagePath) # 若图片文件夹不存在就创建
pix.writePNG(imagePath+'/'+'images_%s.png' % pg)#将图片写入指定的文件夹内
endTime_pdf2img = datetime.datetime.now()#结束时间
print('pdf2img时间=',(endTime_pdf2img - startTime_pdf2img).seconds)
# 调用
# pdf拆为pdf
# file_path = r'E:\work\样本\doc01680420210428144150.pdf' # 源文件所在的绝对路径
# root_obj = r'E:\work\样本拆分'
# pdf_outputdir = pdf_split(file_path, root_obj)
# pdf拆分成图片
pdfPath = r'E:\work\样本\4.pdf'
imagePath = r'E:\work\4'
pyMuPDF_fitz(pdfPath, imagePath)
PDF按页拆分为PDF单页或者图片
最新推荐文章于 2023-06-29 09:19:49 发布