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" };
Related
I made a list with custom numbering but numbering itself gets a different style from paragraphs run. How can I make numbering have the same styles as paragraphs XWPFRun?
This is my numbering
XWPFNumbering numbering = document.CreateNumbering();
var ct_abn = new CT_AbstractNum();
var mlt = new CT_MultiLevelType();
mlt.val = ST_MultiLevelType.multilevel;
ct_abn.multiLevelType = mlt;
ct_abn.lvl = new System.Collections.Generic.List<CT_Lvl> {
new CT_Lvl {
ilvl = "0", start = new CT_DecimalNumber() {val = "1"}, numFmt = new CT_NumFmt() {val = ST_NumberFormat.#decimal},
lvlText = new CT_LevelText() {val = "%1."}, lvlJc = new CT_Jc() {val = ST_Jc.left},
pPr = new CT_PPr {ind = new CT_Ind {left = "360", hanging = 360}, }
},
new CT_Lvl {
ilvl = "1", start = new CT_DecimalNumber() {val = "1"}, numFmt = new CT_NumFmt() {val = ST_NumberFormat.#decimal},
lvlText = new CT_LevelText() {val = "%1.%2."}, lvlJc = new CT_Jc() {val = ST_Jc.left},
pPr = new CT_PPr {ind = new CT_Ind {left = "792", hanging = 792, firstLineSpecified = true}, }
},
new CT_Lvl {
ilvl = "2", start = new CT_DecimalNumber() {val = "1"}, numFmt = new CT_NumFmt() {val = ST_NumberFormat.#decimal},
lvlText = new CT_LevelText() {val = "%1.%2.%3."}, lvlJc = new CT_Jc() {val = ST_Jc.left},
pPr = new CT_PPr {ind = new CT_Ind {left = "792", hanging = 792}}
},
}
This is how it used:
var paragraph = document.CreateParagraph();
paragraph.Alignment = ParagraphAlignment.CENTER;
paragraph.SetNumID(numId, "0"); // applying numbering with lvl = 0
var run = paragraph.CreateRun();
run.SetText("ТЕРМІНИ, ЩО ВЖИВАЮТЬСЯ В ГАРАНТІЙНИХ УМОВАХ");
run.IsBold = true;
run.FontFamily = "Times New Roman";
run.FontSize = 12;
And here's what I get: paragraph itself has correct styles but a number has different
I will appreciate any help
If someone has the same problem, you should add your new style to the document and than use its StyleID to XWPFParagraph like this:
CT_Fonts ctFonts = new CT_Fonts();
ctFonts.ascii = "Times New Roman";
var styles = document.CreateStyles();
styles.AddStyle(
new XWPFStyle(
new CT_Style() {
styleId = "FirstLvlStyle",
rPr = new CT_RPr() {rFonts = ctFonts, b = new CT_OnOff() {val = true}, szCs = new CT_HpsMeasure() {val = 24}}, // gives val / 2 font size
})
);
var paragraph = document.CreateParagraph();
paragraph.Style = "FirstLvlStyle"; // use your StyleId to apply your style
paragraph.SetNumID(numId, "0"); // applying numbering with lvl = 0
UPDATED
Or you can specify style that you want in numbering configuration pPr (Paragraph properties) or rPr (Run properties) like this:
var ct_abn = new CT_AbstractNum();
var mlt = new CT_MultiLevelType();
mlt.val = ST_MultiLevelType.multilevel;
ct_abn.multiLevelType = mlt;
ct_abn.lvl = new System.Collections.Generic.List<CT_Lvl> {
new CT_Lvl {
ilvl = "0", start = new CT_DecimalNumber() {val = "1"}, numFmt = new CT_NumFmt() {val = ST_NumberFormat.#decimal},
lvlText = new CT_LevelText() {val = "%1."}, lvlJc = new CT_Jc() {val = ST_Jc.left},
rPr = new CT_RPr {b = new CT_OnOff {val = true}}, //make text bold
pPr = new CT_PPr {ind = new CT_Ind {left = "360", hanging = 360}}
},
}
I'm making a journal application for myself in c# where i can make journals with dates attached to it.
I'm using a foreach statement to let the data display in the textboxes. I can't figure out how to display the journals in order (old->new) with the dates in Textbox3 (t3). I live in Europe so It's DD/MM/YYYY. I hope it's clear, thanks.
string[] journalfolder = Directory.GetDirectories(#"D:\panel\Journal\", "*");
foreach (string file in journalfolder)
{
Color grey = new Color();
TextBox t1 = new TextBox();
t1.Name = "t1_" + (t1.Controls.Count + 1);
t1.Location = new Point(265, 20);
grey = Color.FromArgb(31, 31, 31);
t1.Width = 332;
t1.BackColor = grey;
t1.BorderStyle = BorderStyle.None;
t1.ForeColor = Color.White;
try
{
string[] lines = File.ReadAllLines(file + #"\text.txt");
t1.Text = lines[0];
}
catch { }
TextBox t2 = new TextBox();
t2.Name = "t2_" + (t2.Controls.Count + 1);
t2.Location = new Point(265, 39);
t2.Width = 332;
t2.Height = 155;
grey = Color.FromArgb(31,31,31);
t2.BackColor = grey;
t2.Multiline = true;
t2.BorderStyle = BorderStyle.None;
t2.ForeColor = Color.White;
try
{
using (var sr = new StreamReader(file + #"\text.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
t2.Text = line;
}
}
}
catch { }
TextBox t3 = new TextBox();
t3.Name = "t3_" + (t3.Controls.Count + 1);
t3.Location = new Point(265, 199);
grey = Color.FromArgb(31, 31, 31);
t3.Width = 332;
t3.BackColor = grey;
t3.BorderStyle = BorderStyle.None;
t3.ForeColor = Color.White;
try
{
string[] lines = File.ReadAllLines(file + #"\date.txt");
t3.Text = lines[0];
}
catch { }
Panel image = new Panel();
image.Name = "image" + (image.Controls.Count + 1);
image.Location = new Point(20, 20);
image.BackgroundImageLayout = ImageLayout.Zoom;
image.Width = 223;
image.Width = 192;
try
{
string supportedExtensions = "*.jpg,*.gif,*.png,*.bmp,*.jpe,*.jpeg,*.wmf,*.ico,*.eps,*.tif,*.tiff";
foreach (string imageFile in Directory.GetFiles(file + #"\Files", "*.*", SearchOption.AllDirectories).Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower())))
{
Console.WriteLine(imageFile);
image.BackgroundImage = Image.FromFile(imageFile);
}
}
catch { }
Panel p = new Panel();
p.Name = "panel" + (flowLayoutPanel1.Controls.Count + 1);
p.BackColor = Color.FromArgb(49,49,49);
p.Width = 628;
p.Height = 236;
p.Controls.Add(t1);
p.Controls.Add(t2);
p.Controls.Add(t3);
p.Controls.Add(image);
flowLayoutPanel1.Controls.Add(p);
}
I'm not quite sure I understand your requirement correctly, but I'll give it a try ...
The date is managed in a date.txt file. It contains the date in the format DD/MM/YYYY, correct?
DateTime timestamp = DateTime.Parse("ValueFromFile");
It is best to put the title, text and date in a class or struct. Maybe something like this:
public class Data
{
public string Title { get; set; }
public string Text { get; set; }
public DateTime Timestamp { get; set; }
}
You should put all the elements you have read into a list or a dictionary before displaying them on the UI and processing them further. Once all the data is in this list, you can easily sort it by date using LINQ.
List<Data> values = new List<Data>();
// TODO
// Add the items
foreach (Data item in values.OrderBy((item) => item.Timestamp))
{
}
// Or
foreach (Data item in values.OrderByDescending((item) => item.Timestamp))
{
}
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;
}
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();
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);
}