how can I change the font open xml - c#

How can I change the font family of the document via OpenXml ?
I tried some ways but, when I open the document, it's always in Calibri
Follow my code, and what I tried.
The Header Builder I think is useless to post
private static void BuildDocument(string fileName, List<string> lista, string tipo)
{
using (var w = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
{
var mp = w.AddMainDocumentPart();
var d = new DocumentFormat.OpenXml.Wordprocessing.Document();
var b = new Body();
var p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
var r = new Run();
// Get and format the text.
for (int i = 0; i < lista.Count; i++)
{
Text t = new Text();
t.Text = lista[i];
if (t.Text == " ")
{
r.Append(new CarriageReturn());
}
else
{
r.Append(t);
r.Append(new CarriageReturn());
}
}
// What I tried
var rPr = new RunProperties(new RunFonts() { Ascii = "Arial" });
lista.Clear();
p.Append(r);
b.Append(p);
var hp = mp.AddNewPart<HeaderPart>();
string headerRelationshipID = mp.GetIdOfPart(hp);
var sectPr = new SectionProperties();
var headerReference = new HeaderReference();
headerReference.Id = headerRelationshipID;
headerReference.Type = HeaderFooterValues.Default;
sectPr.Append(headerReference);
b.Append(sectPr);
d.Append(b);
// Customize the header.
if (tipo == "alugar")
{
hp.Header = BuildHeader(hp, "Anúncio Aluguel de Imóvel");
}
else if (tipo == "vender")
{
hp.Header = BuildHeader(hp, "Anúncio Venda de Imóvel");
}
else
{
hp.Header = BuildHeader(hp, "Aluguel/Venda de Imóvel");
}
hp.Header.Save();
mp.Document = d;
mp.Document.Save();
w.Close();
}
}

In order to style your text with a specific font follow the steps listed below:
Create an instance of the RunProperties class.
Create an instance of the RunFont class. Set the Ascii property to the desired font familiy.
Specify the size of your font (half-point font size) using the FontSize class.
Prepend the RunProperties instance to your run containing the text to style.
Here is a small code example illustrating the steps described above:
private static void BuildDocument(string fileName, List<string> text)
{
using (var wordDoc = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
{
var mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document();
var run = new Run();
foreach (string currText in text)
{
run.AppendChild(new Text(currText));
run.AppendChild(new CarriageReturn());
}
var paragraph = new Paragraph(run);
var body = new Body(paragraph);
mainPart.Document.Append(body);
var runProp = new RunProperties();
var runFont = new RunFonts { Ascii = "Arial" };
// 48 half-point font size
var size = new FontSize { Val = new StringValue("48") };
runProp.Append(runFont);
runProp.Append(size);
run.PrependChild(runProp);
mainPart.Document.Save();
wordDoc.Close();
}
}
Hope, this helps.

If you are using Stylesheet just add an instance of FontName property at appropriate font index during Fonts initilaization.
private Stylesheet GenerateStylesheet()
{
Stylesheet styleSheet = null;
Fonts fonts = new Fonts(
new Font( // Index 0 - default
new FontSize() { Val = 8 },
new FontName() { Val = "Arial"} //i.e. or any other font name as string
);
Fills fills = new Fills( new Fill(new PatternFill() { PatternType = PatternValues.None }));
Borders borders = new Borders( new Border() );
CellFormats cellFormats = new CellFormats( new CellFormat () );
styleSheet = new Stylesheet(fonts, fills, borders, cellFormats);
return styleSheet;
}
Then use it in Workbook style part as below.
WorkbookStylesPart stylePart = workbookPart.AddNewPart<WorkbookStylesPart>();
stylePart.Stylesheet = GenerateStylesheet();
stylePart.Stylesheet.Save();

Related

How to set font size in empty cell of a Word table using the Open XML SDK?

I am creating a table in OpenXml with C# in a Word file. I used some code mentioned in this question to set the fontsize of the text in the cells. It works fine for the cells that contain text, but the empty cells seem to be given the normal style, and with that a bigger font size, which makes the row height bigger.
Here is my sample code with a single row with a single cell, where the font size should be 9:
TableRow tr = new TableRow();
TableCell tc = new TableCell();
Paragraph par = new Paragraph();
Run run = new Run();
Text txt = new Text("txt");
RunProperties runProps = new RunProperties();
FontSize fontSize = new Fontsize() { Val = "18" }; // font size 9
runProps.Append(fontSize);
run.Append(runProps);
run.Append(txt);
para.Append(run);
tc.Append(para);
tr.Append(tc);
Here is an example of the resulting table. As you can see the middle row is taller than the others. In the cells that say "txt" the font size is 9, but in the blank cell the font size is 11. The code above is used for all the cells, where the empty cell simply has the text "". When I looked at the file with the Open XML Tool, I can see that the RunProperties with value 18 is there for all the cells including the empty one.
How do I set the font size of a cell without displaying any text?
I confirm what you report. One way around it would be to substitute a space " " for the "empty" string, adding "space preserve" to the text run, of course.
Another possibility would be to create a character style and apply it to the table cells. This turned out to be trickier than it sounds as the style needs to be applied twice to cells that contain text: once to the ParagraphMarkRunProperties and once to the RunProperties. For empty cells the style need be applied only to the ParagraphMarkRunProperties.
Actually, on reflection, you can use the same approach for the font size...
I've included both approaches in the code below. The one for just the font size is commented out (four lines).
The sample code assumes that the third cell of the one-row, four column table, has no content. Run and Text information is added only when there is content.
private void btnCreateTable_Click(object sender, EventArgs e)
{
string filePath = #"C:\X\TestCreateTAble.docx";
using (WordprocessingDocument pkg = WordprocessingDocument.Open(filePath, true))
{
MainDocumentPart partDoc = pkg.MainDocumentPart;
Document doc = partDoc.Document;
StyleDefinitionsPart stylDefPart = partDoc.StyleDefinitionsPart;
Styles styls = stylDefPart.Styles;
Style styl = CreateTableCharacterStyle();
stylDefPart.Styles.AppendChild(styl);
Table t = new Table();
TableRow tr = new TableRow();
for (int i = 1; i <= 4; i++)
{
TableCell tc = new TableCell(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "500" }));
Paragraph para = new Paragraph();
ParagraphProperties paraProps = new ParagraphProperties();
ParagraphMarkRunProperties paraRunProps = new ParagraphMarkRunProperties();
RunStyle runStyl = new RunStyle() { Val = "Table9Point" };
paraRunProps.Append(runStyl);
// FontSize runFont = new FontSize() {Val = "18" };
// paraRunProps.Append(runFont);
paraProps.Append(paraRunProps);
para.Append(paraProps);
Run run = new Run();
Text txt = null;
if (i == 3)
{
}
else
{
txt = new Text("txt");
txt.Space = SpaceProcessingModeValues.Preserve;
RunProperties runProps = new RunProperties();
RunStyle inRunStyl = (RunStyle) runStyl.Clone();
runProps.Append(inRunStyl);
// FontSize inRunFont = (FontSize) runFont.Clone();
// runProps.Append(inRunFont);
run.Append(runProps);
run.Append(txt);
para.Append(run);
}
tc.Append(para);
tr.Append(tc);
}
t.Append(tr);
//Insert at end of document
SectionProperties sectProps = doc.Body.Elements<SectionProperties>().LastOrDefault();
doc.Body.InsertBefore(t, sectProps);
}
}
private Style CreateTableCharacterStyle()
{
Style styl = new Style()
{
CustomStyle = true,
StyleId = "Table9Point",
Type = StyleValues.Character,
};
StyleName stylName = new StyleName() { Val = "Table9Point" };
styl.AppendChild(stylName);
StyleRunProperties stylRunProps = new StyleRunProperties();
stylRunProps.FontSize = new FontSize() { Val = "18" };
styl.AppendChild(stylRunProps);
BasedOn basedOn1 = new BasedOn() { Val = "DefaultParagraphFont" };
styl.AppendChild(basedOn1);
return styl;
}
Just need to set the FontSize and FontSizeComplexScript for the ParagraphProperties and RunProperties, like this:
var cell = new TableCell(
new Paragraph(
new ParagraphProperties(
new SpacingBetweenLines { LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0" },
new RunProperties(
new FontSize { Val = "18" },
new FontSizeComplexScript { Val = "18" })),
new Run(
new RunProperties(
new FontSize { Val = "18" },
new FontSizeComplexScript { Val = "18" }),
new Text { Text = String.Empty, Space = SpaceProcessingModeValues.Preserve })));

Open XML Table Generation Using Generic List

I have written a method to insert a table in a word document using Open XML. The method accepts a generic list and a few parameters to control number of columns, column headings etc.
That all works fine.
However when populating the cells in the table I want to pull out the values for each row and place them in their corresponding columns. Given the names of the properties are going to change depending on the contents of the generic list, I am not sure how to accomplish this.
Anyone that can point me in the right direction it would be appreciated.
void InsertTable<T>(List<T> tableData, int[] tableHeadingCount, string[] columnHeadings, string locationInDocument)
{
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(_newDocument, true))
{
var docPart = myDoc.MainDocumentPart;
var doc = docPart.Document;
var table = new Table();
var tableBorderTop = new TopBorder();
var tableBorderBottom = new BottomBorder();
var tableBorderLeft = new LeftBorder();
var tableBorderRight = new RightBorder();
var tableBorderHorizontal = new InsideHorizontalBorder();
var tableBorderVertical = new InsideVerticalBorder();
var tableProperties = new TableProperties();
var borders = new TableBorders();
// Set Border Styles for Table
tableBorderTop.Val = BorderValues.Single;
tableBorderTop.Size = 6;
tableBorderBottom.Val = BorderValues.Single;
tableBorderBottom.Size = 6;
tableBorderLeft.Val = BorderValues.Single;
tableBorderLeft.Size = 6;
tableBorderRight.Val = BorderValues.Single;
tableBorderRight.Size = 6;
tableBorderHorizontal.Val = BorderValues.Single;
tableBorderHorizontal.Size = 6;
tableBorderVertical.Val = BorderValues.Single;
tableBorderVertical.Size = 6;
// Assign Border Styles to Table Borders
borders.TopBorder = tableBorderTop;
borders.BottomBorder = tableBorderBottom;
borders.LeftBorder = tableBorderLeft;
borders.RightBorder = tableBorderRight;
borders.InsideHorizontalBorder = tableBorderHorizontal;
borders.InsideVerticalBorder = tableBorderVertical;
// Append Border Styles to Table Properties
tableProperties.Append(borders);
// Assign Table Properties to Table
table.Append(tableProperties);
var tableRowHeader = new TableRow();
tableRowHeader.Append(new TableRowHeight() { Val = 2000 });
for (int i = 0; i < tableHeadingCount.Length; i++)
{
var tableCellHeader = new TableCell();
//Assign Font Properties to Run
var runPropHeader = new RunProperties();
runPropHeader.Append(new Bold());
runPropHeader.Append(new Color() { Val = "000000" });
//Create New Run
var runHeader = new Run();
//Assign Font Properties to Run
runHeader.Append(runPropHeader);
var columnHeader = new Text();
//Assign the Pay Rule Name to the Run
columnHeader = new Text(columnHeadings[i]);
runHeader.Append(columnHeader);
//Create Properties for Paragraph
var justificationHeader = new Justification();
justificationHeader.Val = JustificationValues.Left;
var paraPropsHeader = new ParagraphProperties(justificationHeader);
SpacingBetweenLines spacing = new SpacingBetweenLines() { Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0" };
paraPropsHeader.Append(spacing);
var paragraphHeader = new Paragraph();
paragraphHeader.Append(paraPropsHeader);
paragraphHeader.Append(runHeader);
tableCellHeader.Append(paragraphHeader);
var tableCellPropertiesHeader = new TableCellProperties();
var tableCellWidthHeader = new TableCellWidth();
tableCellPropertiesHeader.Append(new Shading() { Val = ShadingPatternValues.Clear, Color = "auto", Fill = "#C0C0C0" });
var textDirectionHeader = new TextDirection();
textDirectionHeader.Val = TextDirectionValues.BottomToTopLeftToRight;
tableCellPropertiesHeader.Append(textDirectionHeader);
tableCellWidthHeader.Type = TableWidthUnitValues.Dxa;
tableCellWidthHeader.Width = "2000";
tableCellPropertiesHeader.Append(tableCellWidthHeader);
tableCellHeader.Append(tableCellPropertiesHeader);
tableRowHeader.Append(tableCellHeader);
}
tableRowHeader.AppendChild(new TableHeader());
table.Append(tableRowHeader);
//Create New Row in Table for Each Record
foreach (var record in tableData)
{
var tableRow = new TableRow();
for (int i = 0; i < tableHeadingCount.Length; i++)
{
//**** This is where I dynamically want to iterate through selected properties and output the value ****
var propertyText = "Test";
var tableCell = new TableCell();
//Assign Font Properties to Run
var runProp = new RunProperties();
runProp.Append(new Bold());
runProp.Append(new Color() { Val = "000000" });
//Create New Run
var run = new Run();
//Assign Font Properties to Run
run.Append(runProp);
//Assign the text to the Run
var text = new Text(propertyText);
run.Append(text);
//Create Properties for Paragraph
var justification = new Justification();
justification.Val = JustificationValues.Left;
var paraProps = new ParagraphProperties(justification);
var paragraph = new Paragraph();
paragraph.Append(paraProps);
paragraph.Append(run);
tableCell.Append(paragraph);
var tableCellProperties = new TableCellProperties();
var tableCellWidth = new TableCellWidth();
tableCellWidth.Type = TableWidthUnitValues.Dxa;
tableCellWidth.Width = "2000";
tableCellProperties.Append(tableCellWidth);
tableCell.Append(tableCellProperties);
tableRow.Append(tableCell);
}
table.Append(tableRow);
}
var res = from bm in docPart.Document.Body.Descendants<BookmarkStart>()
where bm.Name == locationInDocument
select bm;
var bookmark = res.SingleOrDefault();
var parent = bookmark.Parent; // bookmark's parent element
Paragraph newParagraph = new Paragraph();
parent.InsertAfterSelf(newParagraph);
if (bookmark != null)
{
newParagraph.InsertBeforeSelf(table);
}
}
}
I resolved this issue by tackling the problem another way. Essentially rather than passing a List to the Insert Table Method. I decided to Pass a Multi-Dimensional Array with all the data need for the table including the table headings. This essentially meant that the Insert Table method would be more generic and any customization i.e. Generating Data, Specifying Column Headings etc would be done in the Method calling Insert Table.

openxml sdk 2.0 - Font not set on vowel mutations

I'm using the openxml sdk 2.0 for generating some word files. My problem now is that for german vowel mutations (äöÄÖÜ) the font isn't applied.
Here's an example:
Tried it with some other fonts but even with them it's not working, the font is always set to "Calibri".
Anyone knows some hints to get the style appended to these special german characters?
Thanks in advice.
.
This is my Method to create the character styles:
public static void CreateAndAddCharacterStyle(StyleDefinitionsPart styleDefinitionsPart,
string styleid, string stylename, string aliases = "")
{
Styles styles = styleDefinitionsPart.Styles;
DocumentFormat.OpenXml.Wordprocessing.Style style = new DocumentFormat.OpenXml.Wordprocessing.Style()
{
Type = StyleValues.Character,
StyleId = styleid,
CustomStyle = true
};
Aliases aliases1 = new Aliases() { Val = aliases };
StyleName styleName1 = new StyleName() { Val = stylename };
LinkedStyle linkedStyle1 = new LinkedStyle() { Val = styleid + "Para" };
if (aliases != "")
style.Append(aliases1);
style.Append(styleName1);
style.Append(linkedStyle1);
StyleRunProperties styleRunProperties1 = new StyleRunProperties();
if (styleid == "textfett")
{
RunFonts font1 = new RunFonts() { Ascii = "Gotham Narrow Medium" };
styleRunProperties1.Append(font1);
}
else
{
RunFonts font1 = new RunFonts() { Ascii = "Gotham Narrow Light" };
styleRunProperties1.Append(font1);
}
style.Append(styleRunProperties1);
styles.Append(style);
}
and my code for writing text:
List<Run> runs = new List<Run>();
Run r = new Run(new Text(node.Attributes["titel"].InnerText) { Space = SpaceProcessingModeValues.Preserve });
r.RunProperties = new RunProperties();
r.RunProperties.RunStyle = new RunStyle();
r.RunProperties.RunStyle.Val = "textfett";
runs.Add(r);
r = new Run(new Break());
runs.Add(r);
foreach (System.Xml.XmlNode node2 in node.ChildNodes)
{
if (node2.Name == "info")
{
r = new Run(new Text(node2.Attributes["name"].InnerText + ":") { Space = SpaceProcessingModeValues.Preserve });
r.RunProperties = new RunProperties();
r.RunProperties.RunStyle = new RunStyle();
r.RunProperties.RunStyle.Val = "textfett";
runs.Add(r);
r = new Run(new Text(" " + node2.InnerText + " ") { Space = SpaceProcessingModeValues.Preserve });
r.RunProperties = new RunProperties();
r.RunProperties.RunStyle = new RunStyle();
r.RunProperties.RunStyle.Val = "textnormal";
runs.Add(r);
}
if (node2.Name == "ende")
{
//r = new Run(new Break());
//runs.Add(r);
r = new Run(new Text(node2.InnerText) { Space = SpaceProcessingModeValues.Preserve });
r.RunProperties = new RunProperties();
r.RunProperties.RunStyle = new RunStyle();
r.RunProperties.RunStyle.Val = "textnormal";
runs.Add(r);
}
}
Paragraph p = new Paragraph();
foreach (Run run in runs)
{
p.AppendChild<Run>(run);
}
doc.MainDocumentPart.Document.Body.AppendChild(p);
I had the same problem with French accented chars.
You need to set these properties for the font to be applied to accented characters. For instance :
RunFonts font = new RunFonts();
font.Ascii = font.HighAnsi = font.ComplexScript = #"Calibri";
So for modify your code as the following :
RunFonts font1 = new RunFonts() {
Ascii = "Gotham Narrow Medium",
HighAnsi = "Gotham Narrow Medium",
ComplexScript = "Gotham Narrow Medium" };

Inserting WorkSheet comment with Open XML Programatically - “…unreadable content…”

I was trying to add excel comment dynamically, after adding comment through c# code and try to open that xlsx spreadsheet showing error dilaog box
"Excel found unreadble content in bulkupload.xlsx.Do you want to...." showing , If Clik yes then it is not appearing comment
Please help any one.
Below My sample code
private static void GenerateWorksheetCommentsPart1Content(WorksheetCommentsPart worksheetCommentsPart1)
{
Comments comments1 = new Comments();
Authors authors1 = new Authors();
Author author1 = new Author();
author1.Text = "Geny";
Author author2 = new Author();
author2.Text = "rose";
authors1.Append(author1);
authors1.Append(author2);
CommentList commentList1 = new CommentList();
Comment comment1 = new Comment() { Reference = "B2", AuthorId = (UInt32Value)0U };
CommentText commentText1 = new CommentText();
Run run1 = new Run();
RunProperties runProperties1 = new RunProperties();
Bold bold1 = new Bold();
FontSize fontSize1 = new FontSize() { Val = 9D };
Color color1 = new Color() { Indexed = (UInt32Value)81U };
RunFont runFont1 = new RunFont() { Val = "Tahoma" };
FontFamily fontFamily1 = new FontFamily() { Val = 2 };
runProperties1.Append(bold1);
runProperties1.Append(fontSize1);
runProperties1.Append(color1);
runProperties1.Append(runFont1);
runProperties1.Append(fontFamily1);
Text text1 = new Text();
text1.Text = "add comment 1";
run1.Append(runProperties1);
run1.Append(text1);
commentText1.Append(run1);
comment1.Append(commentText1);
Comment comment2 = new Comment() { Reference = "B7", AuthorId = (UInt32Value)1U };
CommentText commentText2 = new CommentText();
Run run2 = new Run();
RunProperties runProperties2 = new RunProperties();
Bold bold2 = new Bold();
FontSize fontSize2 = new FontSize() { Val = 8D };
Color color2 = new Color() { Indexed = (UInt32Value)81U };
RunFont runFont2 = new RunFont() { Val = "Tahoma" };
RunPropertyCharSet runPropertyCharSet1 = new RunPropertyCharSet() { Val = 1 };
runProperties2.Append(bold2);
runProperties2.Append(fontSize2);
runProperties2.Append(color2);
runProperties2.Append(runFont2);
runProperties2.Append(runPropertyCharSet1);
Text text2 = new Text();
text2.Text = "add second comment";
run2.Append(runProperties2);
run2.Append(text2);
Run run3 = new Run();
RunProperties runProperties3 = new RunProperties();
FontSize fontSize3 = new FontSize() { Val = 8D };
Color color3 = new Color() { Indexed = (UInt32Value)81U };
RunFont runFont3 = new RunFont() { Val = "Tahoma" };
RunPropertyCharSet runPropertyCharSet2 = new RunPropertyCharSet() { Val = 1 };
runProperties3.Append(fontSize3);
runProperties3.Append(color3);
runProperties3.Append(runFont3);
runProperties3.Append(runPropertyCharSet2);
Text text3 = new Text() { Space = SpaceProcessingModeValues.Preserve };
text3.Text = "\ntested";
run3.Append(runProperties3);
run3.Append(text3);
commentText2.Append(run2);
commentText2.Append(run3);
comment2.Append(commentText2);
commentList1.Append(comment1);
commentList1.Append(comment2);
comments1.Append(authors1);
comments1.Append(commentList1);
worksheetCommentsPart1.Comments = comments1;
}

Creating docx paragraphs from strings array

I have in document placeholder with some text. This text consists from several strings, splitted by "<line>". How can I replace this text witha scoupe of paragraphs, each containing only one string?
I've found a solution. It was only necessary to break the string and for each string create a paragraph with formatting, otherwise the elements are created as OpenXmlUnknownElement.
XDocument customXml = GenerateXmlForReport(report);
String customXmlId = AddCustomXml(document, customXml);
DataBind(document, customXml, customXmlId);
document.MainDocumentPart.Document.Body.GetFirstChild<SdtBlock>().RemoveAllChildren();
string[] lines = Regex.Split(report.ReportTextBody, "</line>");
foreach (var line in lines)
{
Paragraph p = new Paragraph();
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "BodyText" };
ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
RunFonts runFonts1 = new RunFonts() { Ascii = "Arial", HighAnsi = "Arial" };
paragraphMarkRunProperties1.Append(runFonts1);
paragraphProperties1.Append(paragraphStyleId1);
paragraphProperties1.Append(paragraphMarkRunProperties1);
RunProperties runProperties1 = new RunProperties();
RunStyle runStyle1 = new RunStyle() { Val = "PlaceholderText" };
runProperties1.Append(runStyle1);
Run run = new Run();
Text txt = new Text(line);
run.Append(txt);
p.Append(run);
document.MainDocumentPart.Document.Body.GetFirstChild<SdtBlock>().Append(p);
}

Categories

Resources