def insert_rtf_content(file_path, content, sid, sae_name):
# rtf_url = os.path.join(settings.UPLOAD_PATH, file_id + ".rtf")
# if not os.path.exists(rtf_url):
# return False
print(file_path)
logger.info(f"写入文件信息{content}")
doc = aw.Document(file_path)
# 使用DocumentBuilder移动到文档的末尾
builder = aw.DocumentBuilder(doc)
builder.move_to_document_end()
new_run = builder.font
# 设置西文和中文字体
new_run.size = 12
new_run.name = "Times New Roman" # 设置西文是新罗马字体
new_run.name_far_east = "宋体"
paragraph_format = builder.paragraph_format
paragraph_format.alignment = aw.ParagraphAlignment.LEFT # 左对齐
for key, value in content.items():
if key == "detail":
for detail_item in value:
for detail_key, detail_value in detail_item.items():
if detail_key == 'pt名称':
new_run.bold = True
builder.paragraph_format.character_unit_first_line_indent = 0
builder.paragraph_format.line_spacing = 18
builder.writeln(detail_value)
builder.paragraph_format.clear_formatting()
else:
builder.paragraph_format.character_unit_first_line_indent = 2
builder.paragraph_format.line_spacing = 18
new_run.bold = False
builder.writeln(detail_value.strip('\n'))
builder.paragraph_format.clear_formatting()
else:
builder.paragraph_format.character_unit_first_line_indent = 2
builder.paragraph_format.line_spacing = 18
new_run.bold = False
builder.writeln(value.strip('\n'))
builder.paragraph_format.clear_formatting()
# 保存文档,另存为新的RTF文件
files_name = sid + "-" + sae_name
# 将UUID转换为字符串,并且只取前8位
files_path = os.path.join(settings.DOWNLOAD_PATH, files_name + ".rtf")
doc.save(files_path)
return files_path
怎么删除文档标题下面后面的所有内容
目前已经删除,下面代码存还存在在2个问题,
1、怎么把新的builder内容写到删除的内容后面,
2怎么把段落样式设置为BuzzContentStyle的样式
def refactor_template(sections, task_id, file_id):
file_path = os.path.join(settings.DOWNLOAD_PATH, f"{task_id}.docx")
doc = aw.Document(file_id)
for s in doc.sections:
sect = s.as_section()
delete_mode = False
for node in sect.body.get_child_nodes(aw.NodeType.ANY, True):
if node.node_type == aw.NodeType.PARAGRAPH:
node = node.as_paragraph()
if node.paragraph_format.outline_level in [0, 1, 2, 3, 4, 5]:
delete_mode = True
if delete_mode:
node.remove()
builder = aw.DocumentBuilder(doc)
for section in sections:
builder.paragraph_format.clear_formatting()
if section["type"] == 'title':
# 设置标题样式
level = section.get('level', 1)
builder.paragraph_format.style_identifier = getattr(
aw.StyleIdentifier, f"HEADING{level}"
)
# 添加标题内容
new_run = builder.font
# 设置西文和中文字体
new_run.bold = True
# 添加标题内容
title = section.get('contents', '').strip() # 获取标题内容
builder.writeln(title) # 写入标题到文档
elif section["type"] == 'toc':
page_setup = doc.first_section.page_setup
tab_stop_position = page_setup.page_width - page_setup.left_margin - page_setup.right_margin
builder.paragraph_format.tab_stops.add(tab_stop_position, aw.TabAlignment.RIGHT, aw.TabLeader.DOTS)
text_content = section.get('content', '')
builder.writeln(text_content)
elif section["type"] == 'text':
# 添加文本内容
new_run = builder.font
# 设置西文和中文字
new_run.size = 12
text_content = section.get('contents', '').strip() # 获取文本内容
builder.paragraph_format.character_unit_first_line_indent = 2
builder.paragraph_format.line_spacing = 18
builder.paragraph_format.style_identifier = aw.StyleIdentifier.NORMAL
builder.paragraph_format.line_unit_after = 0
builder.paragraph_format.space_after = 0
if text_content.startswith("表"):
builder.paragraph_format.alignment = aw.ParagraphAlignment.CENTER
new_run.bold = True
if text_content.startswith("图"):
text_content = text_content.replace(" SEQ 图 \* ARABIC", '')
builder.paragraph_format.alignment = aw.ParagraphAlignment.CENTER
new_run.bold = True
builder.writeln(text_content) # 写入文本到文档
elif section["type"] == 'image':
# 插入图片
image_path = section.get('contents', '').strip()
builder.insert_image(image_path)
elif section["type"] == 'table':
# 添加表格内容
table = builder.start_table() # 开始一个新表格
new_run = builder.font
new_run.bold = False
# 记录rowspan的数据
table_data = section["contents"]
for i in range(len(table_data)):
cell_data_index = 0
for row_data in table_data[i].get('content', []):
# 遍历表格单元格
for cell_data in row_data.get('content', []):
new_cell = builder.insert_cell() # 插入新的表格行
new_cell.cell_format.borders.line_style = aw.LineStyle.SINGLE
builder.cell_format.vertical_merge = aw.tables.CellMerge.NONE
row_index = table.index_of(new_cell)
cell_index = new_cell.parent_row.index_of(new_cell)
previous_row = table.rows[row_index - 1]
if previous_row is not None:
previous_cell = previous_row.cells[cell_index]
if previous_cell is not None and \
(previous_cell.cell_format.vertical_merge == aw.tables.CellMerge.FIRST or
previous_cell.cell_format.vertical_merge == aw.tables.CellMerge.PREVIOUS):
for y in range(i, -1, -1):
curr_row_span = table_data[y].get('content', [])[cell_data_index].get('attrs',
{}).get(
'rowspan', 1)
if curr_row_span > 1:
if curr_row_span >= table.rows.count - y:
builder.cell_format.vertical_merge = aw.tables.CellMerge.PREVIOUS
else:
builder.cell_format.vertical_merge = aw.tables.CellMerge.NONE
builder.cell_format.horizontal_merge = aw.tables.CellMerge.NONE
cell_content = '' # 单元格内容初始化为空字符串
if isinstance(cell_data, dict): # 检查单元格内容是否为字典类型
for paragraph_content in cell_data.get('content', []):
text = paragraph_content["text"] # 获取段落文本内容
cell_content += text # 将段落内容添加到单元格内容中
else:
cell_content = cell_data # 如果不是字典类型,则直接使用内容
new_cell.cell_format.wrap_text = True # 设置单元格内容自动换行
new_cell.cell_format.vertical_alignment = aw.tables.CellVerticalAlignment.CENTER # 设置单元格内容垂直居中
builder.write(cell_content) # 写入单元格内容
colspan = row_data.get('attrs', {}).get('colspan', 1) # 获取列合并数
rowspan = row_data.get('attrs', {}).get('rowspan', 1) # 获取行合并数
if colspan > 1 and rowspan > 1:
builder.cell_format.vertical_merge = aw.tables.CellMerge.FIRST
builder.cell_format.horizontal_merge = aw.tables.CellMerge.FIRST # 水平合并第一个单元格
for i in range(1, colspan):
builder.insert_cell()
builder.cell_format.horizontal_merge = aw.tables.CellMerge.PREVIOUS
elif colspan > 1:
builder.cell_format.horizontal_merge = aw.tables.CellMerge.FIRST # 水平合并第一个单元格
for i in range(1, colspan):
builder.insert_cell()
builder.cell_format.horizontal_merge = aw.tables.CellMerge.PREVIOUS
elif rowspan > 1:
builder.cell_format.vertical_merge = aw.tables.CellMerge.FIRST # 垂直合并第一个单元格
cell_data_index += 1
builder.end_row()
builder.end_table()
builder.insert_break(aw.BreakType.LINE_BREAK)
table.auto_fit(aw.tables.AutoFitBehavior.AUTO_FIT_TO_WINDOW)
# for row in table.rows:
# row = row.as_row()
# if row.is_first_row:
# for cell in row.cells:
# cell = cell.as_cell()
# cell.cell_format.borders.bottom.line_style = aw.LineStyle.SINGLE
# for cell in row.next_row.cells:
# cell = cell.as_cell()
# cell.cell_format.borders.top.line_style = aw.LineStyle.SINGLE
#
# if row.is_last_row:
# for cell in row.cells:
# cell = cell.as_cell()
# cell.cell_format.borders.top.line_style = aw.LineStyle.SINGLE
# for cell in row.previous_row.cells:
# cell = cell.as_cell()
# cell.cell_format.borders.bottom.line_style = aw.LineStyle.SINGLE
# 保存文档
doc.save(file_path)
return task_id
77777.docx (15.8 KB)
为什么删除会有空白页
def refactor_template(sections, task_id, file_id):
file_path = os.path.join(settings.DOWNLOAD_PATH, f"{task_id}.docx")
doc = aw.Document(file_id)
delete_mode = False
for s in doc.sections:
sect = s.as_section()
for node in sect.body.get_child_nodes(aw.NodeType.ANY, True):
if node.node_type == aw.NodeType.PARAGRAPH:
node = node.as_paragraph()
if node.paragraph_format.outline_level in [0, 1, 2, 3, 4, 5]:
delete_mode = True
if delete_mode:
node.remove()
doc.save(os.path.join(settings.DOWNLOAD_PATH, f"77777.docx"))
怎么找到模版里面的start_insert内容的位置进行直接替换
def refactor_template(sections, task_id, file_id):
file_path = os.path.join(settings.DOWNLOAD_PATH, f"{task_id}.docx")
doc = aw.Document(file_id)
builder = aw.DocumentBuilder(doc)
for section in sections:
sect = section.as_section()
for node in sect.body.get_child_nodes(aw.NodeType.ANY, True):
if node.node_type == aw.NodeType.PARAGRAPH:
node = node.as_paragraph()
if
builder.paragraph_format.clear_formatting()
if section["type"] == 'title':
# 设置标题样式
level = section.get('level', 1)
builder.paragraph_format.style_identifier = getattr(
aw.StyleIdentifier, f"HEADING{level}"
)
# 添加标题内容
new_run = builder.font
# 设置西文和中文字体
new_run.bold = True
# 添加标题内容
title = section.get('contents', '').strip() # 获取标题内容
builder.writeln(title) # 写入标题到文档
elif section["type"] == 'toc':
page_setup = doc.first_section.page_setup
tab_stop_position = page_setup.page_width - page_setup.left_margin - page_setup.right_margin
builder.paragraph_format.tab_stops.add(tab_stop_position, aw.TabAlignment.RIGHT, aw.TabLeader.DOTS)
text_content = section.get('content', '')
builder.writeln(text_content)
elif section["type"] == 'text':
# 添加文本内容
new_run = builder.font
# 设置西文和中文字
new_run.size = 12
text_content = section.get('contents', '').strip() # 获取文本内容
builder.paragraph_format.character_unit_first_line_indent = 2
builder.paragraph_format.line_spacing = 18
builder.paragraph_format.style_identifier = aw.StyleIdentifier.NORMAL
builder.paragraph_format.line_unit_after = 0
builder.paragraph_format.space_after = 0
if text_content.startswith("表"):
builder.paragraph_format.alignment = aw.ParagraphAlignment.CENTER
new_run.bold = True
if text_content.startswith("图"):
text_content = text_content.replace(" SEQ 图 \* ARABIC", '')
builder.paragraph_format.alignment = aw.ParagraphAlignment.CENTER
new_run.bold = True
builder.writeln(text_content) # 写入文本到文档
elif section["type"] == 'image':
# 插入图片
image_path = section.get('contents', '').strip()
builder.insert_image(image_path)
elif section["type"] == 'table':
# 添加表格内容
table = builder.start_table() # 开始一个新表格
new_run = builder.font
new_run.bold = False
# 记录rowspan的数据
table_data = section["contents"]
for i in range(len(table_data)):
cell_data_index = 0
for row_data in table_data[i].get('content', []):
# 遍历表格单元格
for cell_data in row_data.get('content', []):
new_cell = builder.insert_cell() # 插入新的表格行
new_cell.cell_format.borders.line_style = aw.LineStyle.SINGLE
builder.cell_format.vertical_merge = aw.tables.CellMerge.NONE
row_index = table.index_of(new_cell)
cell_index = new_cell.parent_row.index_of(new_cell)
previous_row = table.rows[row_index - 1]
if previous_row is not None:
previous_cell = previous_row.cells[cell_index]
if previous_cell is not None and \
(previous_cell.cell_format.vertical_merge == aw.tables.CellMerge.FIRST or
previous_cell.cell_format.vertical_merge == aw.tables.CellMerge.PREVIOUS):
for y in range(i, -1, -1):
curr_row_span = table_data[y].get('content', [])[cell_data_index].get('attrs',
{}).get(
'rowspan', 1)
if curr_row_span > 1:
if curr_row_span >= table.rows.count - y:
builder.cell_format.vertical_merge = aw.tables.CellMerge.PREVIOUS
else:
builder.cell_format.vertical_merge = aw.tables.CellMerge.NONE
builder.cell_format.horizontal_merge = aw.tables.CellMerge.NONE
cell_content = '' # 单元格内容初始化为空字符串
if isinstance(cell_data, dict): # 检查单元格内容是否为字典类型
for paragraph_content in cell_data.get('content', []):
text = paragraph_content["text"] # 获取段落文本内容
cell_content += text # 将段落内容添加到单元格内容中
else:
cell_content = cell_data # 如果不是字典类型,则直接使用内容
new_cell.cell_format.wrap_text = True # 设置单元格内容自动换行
new_cell.cell_format.vertical_alignment = aw.tables.CellVerticalAlignment.CENTER # 设置单元格内容垂直居中
builder.write(cell_content) # 写入单元格内容
colspan = row_data.get('attrs', {}).get('colspan', 1) # 获取列合并数
rowspan = row_data.get('attrs', {}).get('rowspan', 1) # 获取行合并数
if colspan > 1 and rowspan > 1:
builder.cell_format.vertical_merge = aw.tables.CellMerge.FIRST
builder.cell_format.horizontal_merge = aw.tables.CellMerge.FIRST # 水平合并第一个单元格
for i in range(1, colspan):
builder.insert_cell()
builder.cell_format.horizontal_merge = aw.tables.CellMerge.PREVIOUS
elif colspan > 1:
builder.cell_format.horizontal_merge = aw.tables.CellMerge.FIRST # 水平合并第一个单元格
for i in range(1, colspan):
builder.insert_cell()
builder.cell_format.horizontal_merge = aw.tables.CellMerge.PREVIOUS
elif rowspan > 1:
builder.cell_format.vertical_merge = aw.tables.CellMerge.FIRST # 垂直合并第一个单元格
cell_data_index += 1
builder.end_row()
builder.end_table()
builder.insert_break(aw.BreakType.LINE_BREAK)
table.auto_fit(aw.tables.AutoFitBehavior.AUTO_FIT_TO_WINDOW)
# for row in table.rows:
# row = row.as_row()
# if row.is_first_row:
# for cell in row.cells:
# cell = cell.as_cell()
# cell.cell_format.borders.bottom.line_style = aw.LineStyle.SINGLE
# for cell in row.next_row.cells:
# cell = cell.as_cell()
# cell.cell_format.borders.top.line_style = aw.LineStyle.SINGLE
#
# if row.is_last_row:
# for cell in row.cells:
# cell = cell.as_cell()
# cell.cell_format.borders.top.line_style = aw.LineStyle.SINGLE
# for cell in row.previous_row.cells:
# cell = cell.as_cell()
# cell.cell_format.borders.bottom.line_style = aw.LineStyle.SINGLE
# 保存文档
doc.save(file_path)
return task_id
@hhh1111 此外,您也可以不删除所有节点,而使用删除所有子节点来保留段落。
paragraph = paragraph.as_paragraph()
paragraph.remove_all_children()
builder.move_to(paragraph)
builder.paragraph_format.clear_formatting()
builder.write("This is new text of paragraph.")