我有一份由许多其他文件组成的文件。在某一特定点上,我需要更改特定部分中的所有文本。我有一个字体需要更改的部分的引用。
如何更改特定部分内的文字字体?
由于某种原因,当将一个文档的内容插入到当前文档时,所有字段的字体从“Times New Roman”(我正在插入的文档设置为)变为“Courier” “(这是我插入的当前文档的字体)。
所以,我只是试图以编程方式更改字体。搜索文档不会产生更改部分字体的结果。
答案 0 :(得分:1)
请使用以下代码更改部分内的文字字体名称:
Document doc = new Document(MyDir + @"input.docx");
Section sec = doc.LastSection;
FontChanger changer = new FontChanger();
sec.Accept(changer);
doc.Save(MyDir + @"17.4.docx");
/// <summary>
/// Class inherited from DocumentVisitor, that changes font.
/// </summary>
class FontChanger : DocumentVisitor
{
/// <summary>
/// Called when a FieldEnd node is encountered in the document.
/// </summary>
public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
{
//Simply change font name
ResetFont(fieldEnd.Font);
return VisitorAction.Continue;
}
/// <summary>
/// Called when a FieldSeparator node is encountered in the document.
/// </summary>
public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
{
ResetFont(fieldSeparator.Font);
return VisitorAction.Continue;
}
/// <summary>
/// Called when a FieldStart node is encountered in the document.
/// </summary>
public override VisitorAction VisitFieldStart(FieldStart fieldStart)
{
ResetFont(fieldStart.Font);
return VisitorAction.Continue;
}
/// <summary>
/// Called when a Footnote end is encountered in the document.
/// </summary>
public override VisitorAction VisitFootnoteEnd(Footnote footnote)
{
ResetFont(footnote.Font);
return VisitorAction.Continue;
}
/// <summary>
/// Called when a FormField node is encountered in the document.
/// </summary>
public override VisitorAction VisitFormField(FormField formField)
{
ResetFont(formField.Font);
return VisitorAction.Continue;
}
/// <summary>
/// Called when a Paragraph end is encountered in the document.
/// </summary>
public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
{
ResetFont(paragraph.ParagraphBreakFont);
return VisitorAction.Continue;
}
/// <summary>
/// Called when a Run node is encountered in the document.
/// </summary>
public override VisitorAction VisitRun(Run run)
{
ResetFont(run.Font);
return VisitorAction.Continue;
}
/// <summary>
/// Called when a SpecialChar is encountered in the document.
/// </summary>
public override VisitorAction VisitSpecialChar(SpecialChar specialChar)
{
ResetFont(specialChar.Font);
return VisitorAction.Continue;
}
private void ResetFont(Aspose.Words.Font font)
{
// Add your font changing code here
font.Name = mNewFontName;
font.Size = mNewFontSize;
}
private double mNewFontSize = 18;
private string mNewFontName = "Times New Roman";
}
希望,这有帮助。
我使用Aspose作为开发者传播者