自学内容网 自学内容网

【教学类-67-04】20240718毛毛虫ABC排序

背景需求

【教学类-67-01】20240715毛毛虫AB排序-CSDN博客文章浏览阅读747次,点赞17次,收藏8次。【教学类-67-01】20240715毛毛虫AB排序https://blog.csdn.net/reasonsummer/article/details/140443310【教学类-67-02】20240716毛毛虫ABB排序-CSDN博客文章浏览阅读308次。【教学类-67-02】20240716毛毛虫ABB排序https://blog.csdn.net/reasonsummer/article/details/140473546【教学类-67-03】20240717毛毛虫AAB排序-CSDN博客文章浏览阅读299次,点赞12次,收藏5次。【教学类-67-03】20240717毛毛虫AAB排序https://blog.csdn.net/reasonsummer/article/details/140486001

前期制作了AB、ABB、AAB的毛毛虫,

下面制作ABC

重点说明;

word模版

代码展示:




'''
名称:毛毛虫ABC排序
作者:星火讯飞、阿夏
实践:2024年7月18日
'''

print('----1、制作毛毛虫图纸-------')
from PIL import Image, ImageDraw
from itertools import permutations
import os, random,math
import shutil

path = r'C:\Users\jg2yXRZ\OneDrive\桌面\毛毛虫'
path2 = path+r'\04毛毛虫ABC'

# 创建一个空白画布
canvas_width = 900
canvas_height = 200
canvas = Image.new('RGB', (canvas_width, canvas_height), 'white')
draw = ImageDraw.Draw(canvas)

# colours = ["red", "orange", "yellow", "green",  "blue","purple"]
colours = ["red", "orange", "yellow", "green", "cyan", "blue","purple", "pink"]

# 使用itertools.permutations生成所有可能的排列
all_permutations = list(permutations(colours, 3))
print(f"一共有 {len(all_permutations)} 种不重复的方法")

for xx in range(len(all_permutations)):
    b = 20
    py = 20     #  偏移值
   
    w=6
    circle_spacing = (canvas_width - 3 * b) / 9

    # 创建一个新的空白画布
    canvas = Image.new('RGB', (canvas_width, canvas_height), 'white')
    draw = ImageDraw.Draw(canvas)

    # 绘制10个圆和线条
    for i in range(9):
        radius=10
       
        c = random.randint(10, 35)
        x = int(i * (circle_spacing) + b)  # 修改圆心位置,使圆的一半重叠,并加上左右上的间距,减去5像素以产生重叠效果
        # 第一个圆没有脚
        if i==0:            
            draw.line([(x +b +py+3, b+c+3), (50,10)], fill='black', width=w-3)  # 宽度乘以2,因为每磅等于2像素
            draw.ellipse((50-5,10-5,50+5,10+5), fill='white', outline='black', width=6)
            draw.line([(x + b+py+3, b+c+3), (100,10)], fill='black', width=w-3)  # 宽度乘以2,因为每磅等于2像素
            draw.ellipse((100-5,10-5,100+5,10+5), fill='white', outline='black', width=6)
            pass
        else:
            # 在每个圆的圆心位置向下画一条黑色3磅的线100磅长w
            draw.line([(x + b+py, int(canvas_height/2)), (x + b+py, int(canvas_height/2) + py*4)], fill='black', width=w)  # 宽度乘以2,因为每磅等于2像素
            # 在每个圆的圆心位置向下画一条黑色3磅的线100磅长
            draw.line([(x + b+py*2, int(canvas_height/2)), (x + b+py*2, int(canvas_height/2) + py*4)], fill='black', width=w)  # 宽度乘以2,因为每磅等于2像素
            # 两个脚
            draw.ellipse((x + b+py-5-radius, int(canvas_height/2) + py*4-radius, x + b+py+radius-5, int(canvas_height/2) + py*4+radius), fill='white', outline='black', width=6)
            draw.ellipse((x + b+py*2-5-radius, int(canvas_height/2) + py*4-radius, x + b+py*2+radius-5, int(canvas_height/2) + py*4+radius), fill='white', outline='black', width=6)

        if i == 0 or i==3:
            color = str(all_permutations[xx][0])
        elif i==1:
            color = str(all_permutations[xx][1])
        elif i==2:
            color = str(all_permutations[xx][2])
        else:
            color = 'white'
        
        # 在每个圆
        draw.ellipse((x, b + c, x + circle_spacing + b, circle_spacing + 2 * b + c), fill=color, outline='black', width=2)
# 
        r2=random.randint(3, radius-3)
        #   添加第一个眼睛
        if i==0:     
             #白眼珠    
            draw.ellipse((x+py*2-radius*2-10, b+c+py*2-radius*2, x+py*2-10 +radius*2,  b+c+py*2+radius*2), fill='white', outline='black', width=2)
            draw.ellipse((x+py*4-radius*2-10, b+c+py*2-radius*2, x+py*4-10 +radius*2,  b+c+py*2+radius*2), fill='white', outline='black', width=2)
             #黑眼珠 
            draw.ellipse((x+py*2-r2-10, b+c+py*2-r2, x+py*2-10 +r2,  b+c+py*2+r2), fill='black', outline='black', width=2)
            draw.ellipse((x+py*4-r2-10, b+c+py*2-r2, x+py*4-10 +r2,  b+c+py*2+r2), fill='black', outline='black', width=2)
           
            # 嘴巴白
            for bb in ['+1+1','+1-1','-1+1','-1-1']:
                center_x, center_y, radius, start_angle, end_angle, width, color = x+py*2.5+int(bb[:2]), b+c+py*3.5+int(bb[2:4]), 30, 0, 180, 6, 'white'
                points = [(center_x + radius * math.cos(math.radians(angle)), center_y + radius * math.sin(math.radians(angle))) for angle in range(start_angle, end_angle + 1)]
                draw.line(points, fill=color, width=width)

             # 嘴巴黑
            center_x, center_y, radius, start_angle, end_angle, width, color = x+py*2.5, b+c+py*3.5, 30, 0, 180, 6, 'black'
            points = [(center_x + radius * math.cos(math.radians(angle)), center_y + radius * math.sin(math.radians(angle))) for angle in range(start_angle, end_angle + 1)]
            draw.line(points, fill=color, width=width)
        else:
            pass

    # 保存并显示图像
    w1 = path2 + r'\04毛毛虫ABC'
    os.makedirs(w1, exist_ok=True)
    canvas.save(w1 + fr'\{xx:03d}.png')

# 生成分开的圆圈
for xx in range(len(all_permutations)):
    b = 20
    py = 20     #  偏移值
   
    w=6
    circle_spacing = (canvas_width - 3 * b) / 9

    # 创建一个新的空白画布
    canvas = Image.new('RGB', (canvas_width, canvas_height), 'white')
    draw = ImageDraw.Draw(canvas)

    # 绘制10个圆和线条
    for i in range(6):
        radius=10    
       
        x = int(i * (circle_spacing+50) + b)  # 修改圆心位置,使圆的一半重叠,并加上左右上的间距,减去5像素以产生重叠效果       

        # 添加圆形
        if i ==0  or i == 3 :
            color = str(all_permutations[xx][1])
        elif i == 1 or i == 4 :
            color = str(all_permutations[xx][2])   
        elif i == 2 or i == 5 :
            color = str(all_permutations[xx][0])       
        
        
        # 在每个圆
        draw.ellipse((x, b , x + circle_spacing + b, circle_spacing + 2 * b ), fill=color, outline='black', width=2)

      

    # 保存并显示图像
    w2 = path2 + r'\04毛毛虫ABC圆圈'
    os.makedirs(w2, exist_ok=True)
    canvas.save(w2 + fr'\{xx:03d}.png')




print('-----2、读取毛毛虫图纸合并成PDF,读取圆圈图纸合并成pdf-------')
# 第3步,读取图片写入docx,合并PDF

import os,time
from docx import Document
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from PyPDF2 import PdfMerger
from docx.shared import Cm

n=1
for c in [path2 + r'\04毛毛虫ABC',path2 + r'\04毛毛虫ABC圆圈']:
    # 读取123文件夹中的所有图片地址
    new_folder = path2+r'\零时文件夹'
    os.makedirs(new_folder, exist_ok=True)

    image_files = [os.path.join(c, file) for file in os.listdir(c) if file.endswith('.png')]

    # 每8个图片一组进行处理
    grouped_files = [image_files[i:i+6] for i in range(0, len(image_files), 6)]
    print(grouped_files)

    # 处理每一组图片
    for group_index, group in enumerate(grouped_files):
        # 创建新的Word文档
        doc = Document(path+r'\毛毛虫模版.docx')
        print(group)
        
        # 遍历每个单元格,并插入图片
        for cell_index, image_file in enumerate(group):
            # 计算图片长宽(单位:厘米)
        
            
            # 插入图片到单元格
            table = doc.tables[0]
            cell = table.cell(int(cell_index / 1), cell_index % 1)
            # 只有1列,两个都是1
            cell_paragraph = cell.paragraphs[0]
            cell_paragraph.clear()
            run = cell_paragraph.add_run()
            run.add_picture(image_file, width=Cm(19.6), height=Cm(4.35))
            
        # 保存Word文档
        doc.save(os.path.join(new_folder, f'{group_index + 1:03d}.docx'))
        

    # 所有docx合并成PDF

    # 将10个docx转为PDF
    import os
    from docx2pdf import convert
    from PyPDF2 import PdfFileMerger
    # from PyPDF4 import PdfMerger

    # output_folder = output_folder

    pdf_output_path = path2+fr'\{n}毛毛虫ABC({len(all_permutations)}个).pdf'
    # pdf_output_path = path+fr'\黑白三角1-10宫格随机每款{f*ys}图共{ys}张一黑一白黑点白边黑白.pdf'
    n+=1

    # 将所有DOCX文件转换为PDF
    for docx_file in os.listdir(new_folder):
        if docx_file.endswith('.docx'):
            docx_path = os.path.join(new_folder, docx_file)
            convert(docx_path, docx_path.replace('.docx', '.pdf'))


    # 合并零时文件里所有PDF文件
    merger = PdfFileMerger()
    for pdf_file in os.listdir(new_folder):
        if pdf_file.endswith('.pdf'):
            pdf_path = os.path.join(new_folder, pdf_file)
            merger.append(pdf_path)
    time.sleep(2)

    # 保存合并后的PDF文件
    merger.write(pdf_output_path)
    merger.close()

    import shutil
    # 删除输出文件夹
    import time
    shutil.rmtree(new_folder)
    # shutil.rmtree(w1)
    # shutil.rmtree(w2)
    time.sleep(2)

print('-----3、毛毛虫图纸和圆圈图纸合并-------')

import os
import PyPDF2

# 指定包含PDF文件的文件夹路径
# folder_path = '123'

# 获取文件夹中所有的PDF文件
pdf_files = [f for f in os.listdir(path2) if f.endswith('.pdf')]

# 创建一个新的PDF文件用于合并
merger = PyPDF2.PdfFileMerger()

# 遍历文件夹中的每个PDF文件
for pdf_file in pdf_files:
    # 读取PDF文件
    with open(os.path.join(path2, pdf_file), 'rb') as file:
        merger.append(file)

# 将合并后的PDF文件保存到新文件中
output_file = path+fr'\04毛毛虫ABC({len(colours)}色{len(all_permutations)}图,图纸和圆圈).pdf'
with open(os.path.join(path2,output_file), 'wb') as output:
    merger.write(output)

# 删除原始PDF文件
for pdf_file in pdf_files:
    os.remove(os.path.join(path2, pdf_file))

print("PDF文件已合并并删除原始文件。")

shutil.rmtree(w1)
shutil.rmtree(w2)

  



原文地址:https://blog.csdn.net/reasonsummer/article/details/140511251

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!