[Python] 纯文本查看 复制代码 from docx import Document
from docx.shared import Inches
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import comtypes.client
import cairosvg
from PIL import Image
import io
def svg_to_white_bg_jpg(svg_file, output_jpg_file):
# 将SVG文件转换为PNG格式
png_data = cairosvg.svg2png(url=svg_file)
# 使用PIL库打开PNG文件
img = Image.open(io.BytesIO(png_data))
# 将图像背景设置为白色
white_bg_img = Image.new("RGBA", img.size, "white")
white_bg_img.paste(img, mask=img.split()[3]) # 使用alpha通道作为mask
# 将修改后的图像保存为JPG格式
white_bg_img.convert("RGB").save(output_jpg_file)
def word_to_pdf(word_path, pdf_path):
# 创建Word应用程序的实例
word = comtypes.client.CreateObject('Word.Application')
word.Visible = False # 不显示Word界面
# 打开Word文档
doc = word.Documents.Open(word_path)
# 将Word文档保存为PDF
doc.SaveAs(pdf_path, FileFormat=17) # 17代表PDF格式
# 关闭Word文档并退出Word应用程序
doc.Close()
word.Quit()
# 创建一个新的Word文档
doc = Document()
# 设置页边距
section = doc.sections[0]
section.top_margin = Inches(0)
section.bottom_margin = Inches(0)
section.left_margin = Inches(0)
section.right_margin = Inches(0)
# 移除页眉页脚
header = section.header
if header:
p = header.paragraphs[0]
p._element.getparent().remove(p._element)
footer = section.footer
if footer:
p = footer.paragraphs[0]
p._element.getparent().remove(p._element)
# 移除页眉页脚中的默认段落(如果有的话)
if doc.sections[0].header:
for paragraph in doc.sections[0].header.paragraphs:
p = paragraph._element
p.getparent().remove(p)
if doc.sections[0].footer:
for paragraph in doc.sections[0].footer.paragraphs:
p = paragraph._element
p.getparent().remove(p)
# 添加一个段落并设置其对齐方式(如果需要)
# 使用示例
svg_file = "d:/1.svg"
output_jpg_file = "d:/1.jpg"
svg_to_white_bg_jpg(svg_file, output_jpg_file)
# 插入图片(假设你已经将SVG转换为PNG,并命名为'image.png')
doc.add_picture('D:/1.jpg', width=Inches(8))
# 设置所有段落居中
for paragraph in doc.paragraphs:
paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# 保存文档
doc.save('d:/1.docx')
# 使用函数
word_to_pdf('d:/1.docx', 'd:/111.pdf')
|