@hhh1111 这里有一个 SpaceBefore 属性。
import aspose.words as aw
import jinja2
# 激活 Aspose.Words 许可证
lic = aw.License()
lic_path = "../Aspose.Total.Product.Family.lic"
lic.set_license(lic_path)
import aspose.pydrawing as drawing
import re
def set_paragraph_color(builder, color):
if color == "green":
builder.font.color = drawing.Color.green
elif color == "blue":
builder.font.color = drawing.Color.blue
else:
builder.font.clear_formatting()
def insert_title_content(doc_path, insertions):
doc = aw.Document(doc_path)
builder = aw.DocumentBuilder(doc)
for paragraph in doc.get_child_nodes(aw.NodeType.PARAGRAPH, True):
paragraph = paragraph.as_paragraph()
builder.paragraph_format.clear_formatting()
if "start_insert" in paragraph.get_text():
# 清除当前段落的内容
paragraph.get_child_nodes(aw.NodeType.RUN, True).clear()
builder.move_to(paragraph)
builder.paragraph_format.clear_formatting()
for title, content in insertions.items():
# 插入标题
builder.paragraph_format.space_before = 0
heading_level = 1 # 默认标题级别为1
builder.paragraph_format.style_identifier = getattr(aw.StyleIdentifier, f"HEADING{heading_level}")
builder.paragraph_format.line_unit_after = 0
builder.paragraph_format.space_after = 0
builder.writeln(title.strip())
# 处理和插入内容
content = content.replace("\n\n", "\n")
if content.strip('<br/').strip('<html>').strip('<br>'):
# 用正则表达式匹配表格和blue标签的内容
parts = re.split(
r'(<table.*?>.*?</table>|<blue>.*?</blue>|<green>.*?</green>|<sup>.*?</sup>|<small>.*?</small>)',
content,
flags=re.S)
for part in parts:
part = part.replace("<html>", '').replace("</html>", '')
builder.paragraph_format.style_identifier = aw.StyleIdentifier.NORMAL
if part.startswith('<table'):
# 处理表格内容
builder.insert_html(part)
table_node = builder.current_paragraph.previous_sibling
if table_node.node_type == aw.NodeType.TABLE:
table = table_node.as_table()
table.clear_borders()
table.clear_shading()
builder.cell_format.vertical_merge = aw.tables.CellMerge.NONE
table.style_identifier = aw.StyleIdentifier.TABLE_GRID
table.auto_fit(aw.tables.AutoFitBehavior.AUTO_FIT_TO_WINDOW)
elif part.startswith('<blue>'):
# 处理blue标签内容
color_content = re.sub(r'</?blue>', '', part) # 去掉<blue>标签
set_paragraph_color(builder, "blue") # 蓝色
builder.paragraph_format.style_name = "Normal"
builder.write(color_content.strip('<br>'))
set_paragraph_color(builder, None) # 恢复默认配色
elif part.startswith('<green>'):
# 处理blue标签内容
builder.paragraph_format.style_identifier = aw.StyleIdentifier.NORMAL
color_content = re.sub(r'</?green>', '', part) # 去掉<blue>标签
set_paragraph_color(builder, "green") #
builder.paragraph_format.style_name = "Normal"
builder.write(color_content.strip('<br>'))
set_paragraph_color(builder, None) # 恢复默认配色
elif part.startswith('<sup>'):
# 处理上标内容
super_content = re.sub(r'</?sup>', '', part) # 去掉<sup>标签
builder.font.superscript = True
builder.paragraph_format.style_name = "Normal"
builder.write(super_content.strip())
builder.paragraph_format.clear_formatting()
builder.font.superscript = False
elif part.startswith('<small>'):
# 处理small标签内容
small_content = re.sub(r'</?small>', '', part) # 去掉<small>标签
builder.font.size = 8 # 设置为小字体
builder.paragraph_format.style_name = "Normal"
builder.write(small_content.strip('<br>'))
builder.font.size = 12 # 恢复默认字体大小
else:
# 处理普通内容
builder.paragraph_format.style_identifier = aw.StyleIdentifier.NORMAL
builder.paragraph_format.style_name = "Normal"
builder.writeln(part.strip())
builder.paragraph_format.line_unit_after = 0
builder.paragraph_format.clear_formatting()
doc.save('result.docx')
import json
with open("result.json", "r", encoding="utf-8") as f:
data = json.load(f)
insert_title_content('a.docx', data)
为什么写完# 处理普通内容 在写蓝色或者其他颜色数据都换行写入了
@hhh1111 这很难说,但也许是因为当你从内容中获得parts
时,你有空数据,下面的代码在此基础上创建了一个新行。
else:
# 处理普通内容
builder.paragraph_format.style_identifier = aw.StyleIdentifier.NORMAL
builder.paragraph_format.style_name = "Normal"
builder.writeln(part.strip())
def read_table_docx(rtf_path):
_doc = aw.Document(rtf_path)
html = _doc.to_string(aw.SaveFormat.HTML)
# 使用 BeautifulSoup 解析 HTML
soup = BeautifulSoup(html, "html.parser")
_table = []
# 定义允许的标签及其需要保留的属性
allowed_tags = {
'table': [],
'tr': ['rowspan', 'colspan'],
'td': ['rowspan', 'colspan']
}
for tag in soup.find_all(True):
if tag.name not in allowed_tags:
tag.unwrap() # 只保留标签中的内容,删除标签本身
else:
tag.attrs = {key: tag.attrs[key] for key in allowed_tags[tag.name] if key in tag.attrs}
# 返回处理后的 HTML 字符串
clean_html = str(soup)
print(clean_html)
return clean_html
read_table_docx("表14.1.3.2 疾病基线特征 -FAS.rtf")
怎么只读取前3页的rtf文件为html
没有空数据 还是会写入空行