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;
}
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 want to add custom text on BarChart like this:
How to do this using OpenXML which feature?
Please help
This can be achieved by adding text on shape which is not part of chart. It can be placed by positioning spreadsheet rows. Here's are sample codes:
string[] strGenerator = new string[] { "2213969", "2213963", "2213979", "2213969", "2213963", "2213979" };
string[] strRowId = new string[] { "22", "20", "18","18","20","22" };
string[] strColumnId = new string[] { "1", "1", "1", "10", "10", "10" };
string[] strRowOffset = new string[] { "18000", "27000", "27000", "50000", "50000", "50000" }; //{ "80000", "186266", "95036", "81643", "27214", "136071" };
string[] strColumnOffset = new string[] { "489858", "508606", "520699", "497453", "497453", "497453" }; //{ "489858", "508606", "520699", "197453", "182032", "163285" };
for (i = 0; i < 6; i++)
{
Xdr.OneCellAnchor oneCellAnchor6 = new Xdr.OneCellAnchor();
Xdr.FromMarker fromMarker8 = new Xdr.FromMarker();
Xdr.ColumnId columnId10 = new Xdr.ColumnId();
columnId10.Text = strColumnId[i]; // "1";
Xdr.ColumnOffset columnOffset10 = new Xdr.ColumnOffset();
columnOffset10.Text = strColumnOffset[i]; // "520699"
Xdr.RowId rowId10 = new Xdr.RowId();
rowId10.Text = strRowId[i]; //"16";
Xdr.RowOffset rowOffset10 = new Xdr.RowOffset();
rowOffset10.Text = strRowOffset[i];//"95036"; // Convert.ToString(95036*(i+1));// "95036";
fromMarker8.Append(columnId10);
fromMarker8.Append(columnOffset10);
fromMarker8.Append(rowId10);
fromMarker8.Append(rowOffset10);
//Xdr.Extent extent6 = new Xdr.Extent() { Cx = 1782535L, Cy = 204108L };
Xdr.Extent extent6 = new Xdr.Extent() { Cx = 1782535L, Cy = 204108L };
Xdr.Shape shape6 = new Xdr.Shape() { Macro = "", TextLink = "" };
Xdr.NonVisualShapeProperties nonVisualShapeProperties6 = new Xdr.NonVisualShapeProperties();
Xdr.NonVisualDrawingProperties nonVisualDrawingProperties8 = new Xdr.NonVisualDrawingProperties() { Id = (UInt32Value)21U, Name = "TextBox 20" };
A.NonVisualDrawingPropertiesExtensionList nonVisualDrawingPropertiesExtensionList8 = new A.NonVisualDrawingPropertiesExtensionList();
A.NonVisualDrawingPropertiesExtension nonVisualDrawingPropertiesExtension8 = new A.NonVisualDrawingPropertiesExtension() { Uri = "{FF2B5EF4-FFF2-40B4-BE49-F238E27FC236}" };
OpenXmlUnknownElement openXmlUnknownElement9 = OpenXmlUnknownElement.CreateOpenXmlUnknownElement("<a16:creationId xmlns:a16=\"http://schemas.microsoft.com/office/drawing/2014/main\" id=\"{6230E3EC-6B4D-47AE-A392-192F8AB4F7CE}\" />");
nonVisualDrawingPropertiesExtension8.Append(openXmlUnknownElement9);
nonVisualDrawingPropertiesExtensionList8.Append(nonVisualDrawingPropertiesExtension8);
nonVisualDrawingProperties8.Append(nonVisualDrawingPropertiesExtensionList8);
Xdr.NonVisualShapeDrawingProperties nonVisualShapeDrawingProperties6 = new Xdr.NonVisualShapeDrawingProperties() { TextBox = true };
nonVisualShapeProperties6.Append(nonVisualDrawingProperties8);
nonVisualShapeProperties6.Append(nonVisualShapeDrawingProperties6);
Xdr.ShapeProperties shapeProperties6 = new Xdr.ShapeProperties();
A.Transform2D transform2D6 = new A.Transform2D();
A.Offset offset8 = new A.Offset() { X = 1130299L, Y = 3276903L };
A.Extents extents8 = new A.Extents() { Cx = 1782535L, Cy = 204108L };
//A.Offset offset8 = new A.Offset() { X = 0, Y = 0 };
//A.Extents extents8 = new A.Extents() { Cx = 0, Cy = 0 };
transform2D6.Append(offset8);
transform2D6.Append(extents8);
A.PresetGeometry presetGeometry6 = new A.PresetGeometry() { Preset = A.ShapeTypeValues.Rectangle };
A.AdjustValueList adjustValueList6 = new A.AdjustValueList();
presetGeometry6.Append(adjustValueList6);
A.NoFill noFill6 = new A.NoFill();
shapeProperties6.Append(transform2D6);
shapeProperties6.Append(presetGeometry6);
shapeProperties6.Append(noFill6);
Xdr.ShapeStyle shapeStyle6 = new Xdr.ShapeStyle();
A.LineReference lineReference6 = new A.LineReference() { Index = (UInt32Value)0U };
A.RgbColorModelPercentage rgbColorModelPercentage16 = new A.RgbColorModelPercentage() { RedPortion = 0, GreenPortion = 0, BluePortion = 0 };
lineReference6.Append(rgbColorModelPercentage16);
A.FillReference fillReference6 = new A.FillReference() { Index = (UInt32Value)0U };
A.RgbColorModelPercentage rgbColorModelPercentage17 = new A.RgbColorModelPercentage() { RedPortion = 0, GreenPortion = 0, BluePortion = 0 };
fillReference6.Append(rgbColorModelPercentage17);
A.EffectReference effectReference6 = new A.EffectReference() { Index = (UInt32Value)0U };
A.RgbColorModelPercentage rgbColorModelPercentage18 = new A.RgbColorModelPercentage() { RedPortion = 0, GreenPortion = 0, BluePortion = 0 };
effectReference6.Append(rgbColorModelPercentage18);
A.FontReference fontReference6 = new A.FontReference() { Index = A.FontCollectionIndexValues.Minor };
A.SchemeColor schemeColor29 = new A.SchemeColor() { Val = A.SchemeColorValues.Text1 };
fontReference6.Append(schemeColor29);
shapeStyle6.Append(lineReference6);
shapeStyle6.Append(fillReference6);
shapeStyle6.Append(effectReference6);
shapeStyle6.Append(fontReference6);
Xdr.TextBody textBody6 = new Xdr.TextBody();
A.BodyProperties bodyProperties6;
// if (i == 2)
// {
// bodyProperties6 = new A.BodyProperties() { VerticalOverflow = A.TextVerticalOverflowValues.Clip, HorizontalOverflow = A.TextHorizontalOverflowValues.Clip, Wrap = A.TextWrappingValues.Square, RightToLeftColumns = false, Anchor = A.TextAnchoringTypeValues.Bottom };
// }
// else
// {
bodyProperties6 = new A.BodyProperties() { VerticalOverflow = A.TextVerticalOverflowValues.Clip, HorizontalOverflow = A.TextHorizontalOverflowValues.Clip, Wrap = A.TextWrappingValues.Square, RightToLeftColumns = false, Anchor = A.TextAnchoringTypeValues.Top };
// }
A.NoAutoFit noAutoFit6 = new A.NoAutoFit();
bodyProperties6.Append(noAutoFit6);
A.ListStyle listStyle6 = new A.ListStyle();
A.Paragraph paragraph6 = new A.Paragraph();
A.ParagraphProperties paragraphProperties3 = new A.ParagraphProperties() { Alignment = A.TextAlignmentTypeValues.Left };
A.Run run9 = new A.Run();
A.RunProperties runProperties9 = new A.RunProperties() { Language = "en-US", FontSize = 1100, Bold = false, Italic = false, Underline = A.TextUnderlineValues.None, Strike = A.TextStrikeValues.NoStrike };
A.SolidFill solidFill15 = new A.SolidFill();
A.SchemeColor schemeColor30 = new A.SchemeColor() { Val = A.SchemeColorValues.Background1 };
solidFill15.Append(schemeColor30);
A.EffectList effectList7 = new A.EffectList();
A.LatinFont latinFont6 = new A.LatinFont() { Typeface = "+mn-lt" };
A.EastAsianFont eastAsianFont6 = new A.EastAsianFont() { Typeface = "+mn-ea" };
A.ComplexScriptFont complexScriptFont6 = new A.ComplexScriptFont() { Typeface = "+mn-cs" };
runProperties9.Append(solidFill15);
runProperties9.Append(effectList7);
runProperties9.Append(latinFont6);
runProperties9.Append(eastAsianFont6);
runProperties9.Append(complexScriptFont6);
A.Text text9 = new A.Text();
text9.Text = strGenerator[i];
run9.Append(runProperties9);
run9.Append(text9);
A.Run run10 = new A.Run();
A.RunProperties runProperties10 = new A.RunProperties() { Language = "en-US", FontSize = 1200 };
A.SolidFill solidFill16 = new A.SolidFill();
A.SchemeColor schemeColor31 = new A.SchemeColor() { Val = A.SchemeColorValues.Background1 };
solidFill16.Append(schemeColor31);
runProperties10.Append(solidFill16);
A.Text text10 = new A.Text();
text10.Text = "";
run10.Append(runProperties10);
run10.Append(text10);
paragraph6.Append(paragraphProperties3);
paragraph6.Append(run9);
paragraph6.Append(run10);
textBody6.Append(bodyProperties6);
textBody6.Append(listStyle6);
textBody6.Append(paragraph6);
shape6.Append(nonVisualShapeProperties6);
shape6.Append(shapeProperties6);
shape6.Append(shapeStyle6);
shape6.Append(textBody6);
Xdr.ClientData clientData8 = new Xdr.ClientData();
oneCellAnchor6.Append(fromMarker8);
oneCellAnchor6.Append(extent6);
oneCellAnchor6.Append(shape6);
oneCellAnchor6.Append(clientData8);
drawingspart.WorksheetDrawing.Append(oneCellAnchor6);
}
I followed the watermarking code given below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Vml;
using DocumentFormat.OpenXml.Vml.Office;
using DocumentFormat.OpenXml.Vml.Wordprocessing;
using DocumentFormat.OpenXml.Wordprocessing;
using HorizontalAnchorValues = DocumentFormat.OpenXml.Vml.Wordprocessing.HorizontalAnchorValues;
using Lock = DocumentFormat.OpenXml.Vml.Office.Lock;
using VerticalAnchorValues = DocumentFormat.OpenXml.Vml.Wordprocessing.VerticalAnchorValues;
namespace DocumentWatermarkTest
{
class Program
{
static void Main(string[] args)
{
byte[] sourceBytes = File.ReadAllBytes(#"C:\Users\loggedinuser\Desktop\TestDoc.docx");
MemoryStream inMemoryStream = new MemoryStream();
inMemoryStream.Write(sourceBytes, 0, (int)sourceBytes.Length);
var doc = WordprocessingDocument.Open(inMemoryStream, true);
AddWatermark(doc);
doc.MainDocumentPart.Document.Save();
doc.Close();
doc.Dispose();
doc = null;
using (FileStream fileStream = new FileStream(#"C:\Users\loggedinuser\Desktop\TestDoc.docx", System.IO.FileMode.Create))
{
inMemoryStream.WriteTo(fileStream);
}
inMemoryStream.Close();
inMemoryStream.Dispose();
inMemoryStream = null;
}
static Header MakeHeader()
{
var header = new Header();
var paragraph = new Paragraph();
var run = new Run();
var text = new Text();
text.Text = "";
run.Append(text);
paragraph.Append(run);
header.Append(paragraph);
return header;
}
static void AddWatermark(WordprocessingDocument doc)
{
if (doc.MainDocumentPart.HeaderParts.Count() == 0)
{
doc.MainDocumentPart.DeleteParts(doc.MainDocumentPart.HeaderParts);
var newHeaderPart = doc.MainDocumentPart.AddNewPart<HeaderPart>();
var rId = doc.MainDocumentPart.GetIdOfPart(newHeaderPart);
var headerRef = new HeaderReference();
headerRef.Id = rId;
var sectionProps = doc.MainDocumentPart.Document.Body.Elements<SectionProperties>().LastOrDefault();
if (sectionProps == null)
{
sectionProps = new SectionProperties();
doc.MainDocumentPart.Document.Body.Append(sectionProps);
}
sectionProps.RemoveAllChildren<HeaderReference>();
sectionProps.Append(headerRef);
newHeaderPart.Header = MakeHeader();
newHeaderPart.Header.Save();
}
foreach (HeaderPart headerPart in doc.MainDocumentPart.HeaderParts)
{
var sdtBlock1 = new SdtBlock();
var sdtProperties1 = new SdtProperties();
var sdtId1 = new SdtId() { Val = 87908844 };
var sdtContentDocPartObject1 = new DocPartObjectSdt();
var docPartGallery1 = new DocPartGallery() { Val = "Watermarks" };
var docPartUnique1 = new DocPartUnique();
sdtContentDocPartObject1.Append(docPartGallery1);
sdtContentDocPartObject1.Append(docPartUnique1);
sdtProperties1.Append(sdtId1);
sdtProperties1.Append(sdtContentDocPartObject1);
var sdtContentBlock1 = new SdtContentBlock();
var paragraph2 = new Paragraph()
{
RsidParagraphAddition = "00656E18",
RsidRunAdditionDefault = "00656E18"
};
var paragraphProperties2 = new ParagraphProperties();
var paragraphStyleId2 = new ParagraphStyleId() { Val = "Header" };
paragraphProperties2.Append(paragraphStyleId2);
var run1 = new Run();
var runProperties1 = new RunProperties();
var noProof1 = new NoProof();
var languages1 = new Languages() { EastAsia = "zh-TW" };
runProperties1.Append(noProof1);
runProperties1.Append(languages1);
var picture1 = new Picture();
var shapetype1 = new Shapetype()
{
Id = "_x0000_t136",
CoordinateSize = "21600,21600",
OptionalNumber = 136,
Adjustment = "10800",
EdgePath = "m#7,l#8,m#5,21600l#6,21600e"
};
var formulas1 = new Formulas();
var formula1 = new Formula() { Equation = "sum #0 0 10800" };
var formula2 = new Formula() { Equation = "prod #0 2 1" };
var formula3 = new Formula() { Equation = "sum 21600 0 #1" };
var formula4 = new Formula() { Equation = "sum 0 0 #2" };
var formula5 = new Formula() { Equation = "sum 21600 0 #3" };
var formula6 = new Formula() { Equation = "if #0 #3 0" };
var formula7 = new Formula() { Equation = "if #0 21600 #1" };
var formula8 = new Formula() { Equation = "if #0 0 #2" };
var formula9 = new Formula() { Equation = "if #0 #4 21600" };
var formula10 = new Formula() { Equation = "mid #5 #6" };
var formula11 = new Formula() { Equation = "mid #8 #5" };
var formula12 = new Formula() { Equation = "mid #7 #8" };
var formula13 = new Formula() { Equation = "mid #6 #7" };
var formula14 = new Formula() { Equation = "sum #6 0 #5" };
formulas1.Append(formula1);
formulas1.Append(formula2);
formulas1.Append(formula3);
formulas1.Append(formula4);
formulas1.Append(formula5);
formulas1.Append(formula6);
formulas1.Append(formula7);
formulas1.Append(formula8);
formulas1.Append(formula9);
formulas1.Append(formula10);
formulas1.Append(formula11);
formulas1.Append(formula12);
formulas1.Append(formula13);
formulas1.Append(formula14);
var path1 = new Path()
{
AllowTextPath = DocumentFormat.OpenXml.Vml.BooleanValues.True,
ConnectionPointType = ConnectValues.Custom,
ConnectionPoints = "#9,0;#10,10800;#11,21600;#12,10800",
ConnectAngles = "270,180,90,0"
};
var textPath1 = new TextPath()
{
On = DocumentFormat.OpenXml.Vml.BooleanValues.True,
FitShape = DocumentFormat.OpenXml.Vml.BooleanValues.True
};
var shapeHandles1 = new Handles();
var shapeHandle1 = new Handle()
{
Position = "#0,bottomRight",
XRange = "6629,14971"
};
shapeHandles1.Append(shapeHandle1);
var lock1 = new Lock
{
Extension = ExtensionHandlingBehaviorValues.Edit,
TextLock = DocumentFormat.OpenXml.Vml.Office.BooleanValues.True,
ShapeType = DocumentFormat.OpenXml.Vml.Office.BooleanValues.True
};
shapetype1.Append(formulas1);
shapetype1.Append(path1);
shapetype1.Append(textPath1);
shapetype1.Append(shapeHandles1);
shapetype1.Append(lock1);
var shape1 = new Shape()
{
Id = "PowerPlusWaterMarkObject357476642",
Style = "position:absolute;left:0;text-align:left;margin-left:0;margin-top:0;width:527.85pt;height:131.95pt;rotation:315;z-index:-251656192;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin",
OptionalString = "_x0000_s2049",
AllowInCell = DocumentFormat.OpenXml.Vml.BooleanValues.False,
FillColor = "silver",
Stroked = DocumentFormat.OpenXml.Vml.BooleanValues.False,
Type = "#_x0000_t136"
};
var fill1 = new Fill() { Opacity = ".5" };
TextPath textPath2 = new TextPath()
{
Style = "font-family:\"Calibri\";font-size:1pt",
String = "DRAFT"
};
var textWrap1 = new TextWrap()
{
AnchorX = HorizontalAnchorValues.Margin,
AnchorY = VerticalAnchorValues.Margin
};
shape1.Append(fill1);
shape1.Append(textPath2);
shape1.Append(textWrap1);
picture1.Append(shapetype1);
picture1.Append(shape1);
run1.Append(runProperties1);
run1.Append(picture1);
paragraph2.Append(paragraphProperties2);
paragraph2.Append(run1);
sdtContentBlock1.Append(paragraph2);
sdtBlock1.Append(sdtProperties1);
sdtBlock1.Append(sdtContentBlock1);
headerPart.Header.Append(sdtBlock1);
headerPart.Header.Save();
//break;
}
}
}
}
When I use this code, the watermarked text lies below the actual contents of the word document. If there are images in the word document, the watermarked text gets hidden completely and is not visible. Can I somehow place the watermarked text on top of the contents of the word document? Any help would be really appreciated.
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" };
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();