Gembox.document: How to set the custom font of the whole document before saving.
I have to process find & replace and it works fine. But before saving I want to change & set the custom font of the whole document irrespective of area/section/block etc.
I tired using: document.DefaultCharacterFormat.FontName = “Verdana”
but this does not work
Note: The custom font is installed in Windows & registered.
Changing the default font will only work for elements that specify the font neither directly nor on its style.
If you’re interested in learning about how formatting is inherited in document elements, then check this Style Resolution example.
Anyway, try using this:
var document = DocumentModel.Load("input.docx");
foreach (Run run in document.GetChildElements(true, ElementType.Run))
run.CharacterFormat.FontName = "Verdana";
document.Save("output.docx");
May I ask you. What if my docx has a text with Calibri, Helvetica, Arial fonts and I want to change Calibri on Consolas, Helvetica on Comics, Arial on TimesNewRoman fonts? How to do that?
void ChangeFont(CharacterFormat format)
{
switch (format.FontName)
{
case "Calibri":
format.FontName = "Consolas"; break;
case "Helvetica":
format.FontName = "Comics"; break;
case "Arial":
format.FontName = "Times New Roman"; break;
}
}
var document = DocumentModel.Load("input.docx");
ChangeFont(document.DefaultCharacterFormat);
foreach (var style in document.Styles)
{
switch (style)
{
case CharacterStyle characterStyle:
ChangeFont(characterStyle.CharacterFormat); break;
case ParagraphStyle paragraphStyle:
ChangeFont(paragraphStyle.CharacterFormat); break;
case TableStyle tableStyle:
ChangeFont(tableStyle.CharacterFormat); break;
}
}
foreach (var element in document.GetChildElements(true))
{
switch (element)
{
case Paragraph paragraph:
ChangeFont(paragraph.CharacterFormatForParagraphMark); break;
case Run run:
ChangeFont(run.CharacterFormat); break;
case SpecialCharacter specialCharacter:
ChangeFont(specialCharacter.CharacterFormat); break;
}
}
document.Save("output.docx");
Alternatively, if you’re saving to PDF, XPS, or image format, you could use the FontSettings.FontSelection event to override the selected font for the given font name.