# -*- coding: utf-8 -*-
"""
Created on Tue Feb 22 22:35:47 2022
@author: Nhcode
"""
import os
from pptx import Presentation
from pptx.util import Inches, Pt, Cm, Mm
from pptx.enum.text import PP_ALIGN, MSO_ANCHOR, MSO_AUTO_SIZE
from pptx.dml.color import RGBColor
##self-func
def draw_imgBorder(img,borderwidth=10,col=0): #用于给图片添加黑框
from PIL import Image
img = Image.open(img)
new_pic = Image.new('RGB', (img.size[0] + borderwidth, img.size[1] + borderwidth), color=col)##设置像素的图片宽度
new_pic.paste(img, ( int(borderwidth / 2), int(borderwidth / 2) ))
return new_pic
#设置工作路径
work_path = r'C:/Users/13321/Desktop/python-pptxTest'
os.chdir(work_path)
#get file
file_dir_L = []
for maindir, subdirs, files in os.walk("./JPG/"):
for file in files:
# 筛选目标后缀文件,这里筛选了“png,jpg,jpeg”
if os.path.splitext(file)[1] in [".png", ".jpg", ".jpeg"]:
file_dir_L.append(os.path.join(maindir,file))
###grouping all Picture_file
picFile_group = []
for i in range(0, len(file_dir_L), 6):
picFile_group.append(file_dir_L[i:i+6])
#################################################my_main_func
##创建二进制IO流
from io import BytesIO
pic_tmp = BytesIO()
###初始化ppt对象
prs = Presentation()
prs.slide_height = Inches(9)
prs.slide_width = Inches(16)
###############################循环填充
for i in range(0,len(picFile_group),1):
slide = prs.slides.add_slide(prs.slide_layouts[6]) #新建空ppt页
#添加标题
txBox = slide.shapes.add_textbox(Mm(5), Mm(5), Cm(10), Cm(1))
txBox.text_frame.auto_size = MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT
txBox.text_frame.word_wrap = False
para = txBox.text_frame.paragraphs[0]
para.text = 'FRKS12Xg'
para.font.color.rgb = RGBColor(68, 114, 196)
para.alignment = PP_ALIGN.LEFT #居左
para.font.size = Pt(32)
para.font.bold = True
para.font.name = "等线"
#############################
###填充图像插入参数
pic_position_left_1 = 23
pic_position_left_2 = 23
pic_position_top_1 = 25
pic_position_top_2 = (25+83)
####每页ppt插入图片
for pic_index in range(0,len(picFile_group[i]),1):
#图片处理
my_file = picFile_group[i][pic_index]
print('当前图片::'+my_file)
new_pic = draw_imgBorder(my_file)
##清空缓存
pic_tmp.truncate(0)
pic_tmp.seek(0)
new_pic.save(pic_tmp,format='PNG') #图片对象载入内存
#设置图片排版
if (pic_index + 1) <= 3:
slide.shapes.add_picture( pic_tmp, left= Mm(pic_position_left_1), top= Mm(pic_position_top_1), width= Mm(120),height=Mm (83))
pic_position_left_1 += 120
else:
slide.shapes.add_picture( pic_tmp, left= Mm(pic_position_left_2), top= Mm(pic_position_top_2), width= Mm(120),height=Mm (83))
pic_position_left_2 += 120
prs.save("myTsest_version_1.pptx")
网友评论