OpenXML strange behaviour with font-size - c#

I am using a dll to create methods that generates me the logic to create a paragraph based on the parameters that are passed:
for example on my C# code i have this:
// document permission title
DocRun accessTypeTitle = new DocRun();
Run permissionTitle = accessTypeTitle.createParagraph("DOCUMENT ACCESS", PARAGRAPHCOLOR,FONTSIZETEXT,DEFAULTFONT);
i have my method on my dll that does the logic:
public class DocRun
{
public Run createParagraph(String text, String colorVal, String fontSize,String font)
{
Run run = new Run() { RsidRunProperties = "00C53974" };
RunProperties runProperties = new RunProperties();
RunFonts runFonts = new RunFonts() { Ascii = font, HighAnsi = font, EastAsia = "Segoe UI", ComplexScript = font };
Color color = new Color() { Val = colorVal };
//Kern kern = new Kern() { Val = (UInt32Value)24U };
FontSize fontSize11 = new FontSize() { Val = fontSize };
FontSizeComplexScript fontSizeComplexScript11 = new FontSizeComplexScript() { Val = fontSize };
runProperties.Append(runFonts);
runProperties.Append(color);
//runProperties.Append(kern);
runProperties.Append(fontSize11);
runProperties.Append(fontSizeComplexScript11);
Text t = new Text(text)
{
Text = text,
Space = SpaceProcessingModeValues.Preserve
};
run.Append(runProperties);
run.Append(t);
return run;
}
}
}
after i return the run, i can do the same with the images nd other paragraph and just append them to the doc like this:
var stream = new MemoryStream();
using (WordprocessingDocument doc = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document, true))
{
MainDocumentPart mainPart = doc.AddMainDocumentPart();
// Logo company construction
DocImage companyLogo = new DocImage();
Run imageLogo = companyLogo.imageCreator(mainPart,COMPANYLOGOPATH,COMPANYIMAGENAME,COMPANYLOGOWIDTH,COMPANYLOGOHEIGHT,COMPANYIMAGEALING);
DocImage titleShape = new DocImage();
Run imageShape = titleShape.imageCreator(mainPart, SHAPEIMAGEPATH, TITLESHAPEIMAGENAME, TITLESHAPEWIDTH, TITLESHAPEHEIGHT,SHAPEIMAGEALING);
DocImage clientImage = new DocImage();
Run clientLogo = titleShape.imageCreatorUrl(mainPart, SHAPEIMAGEPATH, TITLESHAPEIMAGENAME, TITLESHAPEWIDTHCLIENTLOGO, TITLESHAPEHEIGHTCLIENTLOGO, CLIENTIMAGEALIGN,clientLogoPath);
new Document(new Body()).Save(mainPart);
Body body = mainPart.Document.Body;
body.Append(new Paragraph(
new Run(imageLogo)));
body.Append(new Paragraph(
new Run(imageShape)));
body.Append(new Paragraph(
new Run(projectNameTxt)));
body.Append(new Paragraph(
new Run(clientLogo)));
body.Append(new Paragraph(
new Run(dateTxt)));
body.Append(new Paragraph(
new Run(permissionTitle)));
body.Append(new Paragraph(
new Run(permission)));
body.Append(new Paragraph(
new Run(disclaimerTitleTxt)));
body.Append(new Paragraph(
new Run(disclaimerDescriptionTxt)));
mainPart.Document.Save();
}
stream.Seek(0, SeekOrigin.Begin);
Directory.CreateDirectory(HostingEnvironment.MapPath(DOCUMENTSLOCATION));
System.IO.File.WriteAllBytes(HostingEnvironment.MapPath("~/Files/test5.docx"), stream.ToArray());
}
my problem is that the document generated font size are always half of the real size i defined on the openXML dll that i created.
I debuged the fontSize that i pass as the parameter and the fontsize received on the dll is the correct one, what is going on?
Thanks guys,

The FontSize is specified with a value which measures in half-points. So if you need a 11 point font, you need to specify the value to be 22.
This is also documented on page 13 in the e-book "Open XML Explained" by Wouter Van Vugt.

Related

Constructing an OpenXmlElement from bitmap picture to append into a Run instance

I have the following code:
string replaceValueString = parameterValue.ToString();
Run replaceRun = new Run();
replaceRun.Append(new Text(replaceValueString));
contentControl.InsertAfterSelf(replaceRun);
I need to add a similar logic, but instead of Text, I need to add Picture (or some other type of image instance), like that:
replaceRun.Append(new Picture(data));
I have a Bitmap class, I can also pass byte[] or Steam of the image. My only problem is, I found virtually no example how to construct this Picture class, inherited from OpenXmlCompositeElement.
Can someone provide me with some examples and guides, in order to convert from Bitmap/data[]/Steam image into DocumentFormat.OpenXml.Wordprocessing.Picture (or any other OpenXmlElement)?
So far I found only this example:
https://learn.microsoft.com/en-us/office/open-xml/how-to-insert-a-picture-into-a-word-processing-document
...it creates a Drawing class instead of a picture, and it uses some DW SDK, which I don't have access to.
The example you have provided can seem daunting at first but it is very useable if you work through it...
it uses some DW SDK, which I don't have access to.
The DW is simply just an alias to some namespaces that you will no doubt have access to already. Make sure you include the following at the top of your class file:
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
With that in mind. Let's start with your Bitmap. First, you want to use that to create an ImagePart. The following code may seem like it is adding an image straight to the main document, but it doesn't quite work like that. Don't worry, we will move it to your run later.
MainDocumentPart mainDocumentPart = wordDoc.MainDocumentPart;
ImagePart imagePart = mainDocumentPart.AddImagePart(ImagePartType.Bmp);
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
stream.Position = 0;
imagePart.FeedData(stream);
}
We need to get the ID of the image part, so that we can use that when creating the Drawing object.
string imagePartId = mainDocumentPart.GetIdOfPart(imagePart);
Next, we need to use that code that you didn't like from here.
Let's just take everything we have so far and stick it into a function that will create a Drawing from a Bitmap.
static Drawing ConvertBitmapToDrawing(WordprocessingDocument wordDoc, System.Drawing.Bitmap image)
{
MainDocumentPart mainDocumentPart = wordDoc.MainDocumentPart;
ImagePart imagePart = mainDocumentPart.AddImagePart(ImagePartType.Bmp);
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
stream.Position = 0;
imagePart.FeedData(stream);
}
string imagePartId = mainDocumentPart.GetIdOfPart(imagePart);
var element =
new Drawing(
new DW.Inline(
new DW.Extent() { Cx = 990000L, Cy = 792000L },
new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L,
RightEdge = 0L, BottomEdge = 0L },
new DW.DocProperties() { Id = (UInt32Value)1U,
Name = "Picture 1" },
new DW.NonVisualGraphicFrameDrawingProperties(
new A.GraphicFrameLocks() { NoChangeAspect = true }),
new A.Graphic(
new A.GraphicData(
new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{ Id = (UInt32Value)0U,
Name = "New Bitmap Image.jpg" },
new PIC.NonVisualPictureDrawingProperties()),
new PIC.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension()
{ Uri =
"{28A0092B-C50C-407E-A947-70E740481C1C}" })
)
{ Embed = imagePartId,
CompressionState =
A.BlipCompressionValues.Print },
new A.Stretch(
new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(
new A.Offset() { X = 0L, Y = 0L },
new A.Extents() { Cx = 990000L, Cy = 792000L }),
new A.PresetGeometry(
new A.AdjustValueList()
) { Preset = A.ShapeTypeValues.Rectangle }))
) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
) { DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U, EditId = "50D07946" });
return element;
}
With this function, you can finally just do something like this:
Drawing drawing = ConvertBitmapToDrawing(wordProcessingDocument, myBitmap);
Run newRun = new Run(drawing);
contentControl.InsertAfterSelf(newRun);

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 })));

Add Header to OpenXML Document

I'm working on as asp.net webform that when completed the user needs to download a word document that will summarize the answers that they chose. I've successfully done this with saving html as a .doc but now the client would like .docx. I've been able to successfully generate a document that they can download but for the life of me I can't get a header to show up.
One thing that seems a little off is if I use the Open SML productivity tool a document that I create in word will have /word/header1.xml 2 and 3 tags, my documents will just have /word/header.xml. But I can't figure out how to change that.
Here's all the code I've been using:
public static void CreateWordprocessingDocument(string filepath)
{
// Create a document by supplying the filepath.
using (WordprocessingDocument wordDocument =
WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
AddSettingsToMainDocumentPart(mainPart);
// Create the document structure and add some text.
mainPart.Document = new Document();
HeaderPart headerPart = mainPart.AddNewPart<HeaderPart>("rId7");
GenerateHeader(headerPart);
Body body = mainPart.Document.AppendChild(new Body());
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text("Testing text"));
}
}
private static void GenerateHeader(HeaderPart part)
{
Header header1 = new Header() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 w15 w16se wp14" } };
header1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
header1.AddNamespaceDeclaration("cx", "http://schemas.microsoft.com/office/drawing/2014/chartex");
header1.AddNamespaceDeclaration("cx1", "http://schemas.microsoft.com/office/drawing/2015/9/8/chartex");
header1.AddNamespaceDeclaration("cx2", "http://schemas.microsoft.com/office/drawing/2015/10/21/chartex");
header1.AddNamespaceDeclaration("cx3", "http://schemas.microsoft.com/office/drawing/2016/5/9/chartex");
header1.AddNamespaceDeclaration("cx4", "http://schemas.microsoft.com/office/drawing/2016/5/10/chartex");
header1.AddNamespaceDeclaration("cx5", "http://schemas.microsoft.com/office/drawing/2016/5/11/chartex");
header1.AddNamespaceDeclaration("cx6", "http://schemas.microsoft.com/office/drawing/2016/5/12/chartex");
header1.AddNamespaceDeclaration("cx7", "http://schemas.microsoft.com/office/drawing/2016/5/13/chartex");
header1.AddNamespaceDeclaration("cx8", "http://schemas.microsoft.com/office/drawing/2016/5/14/chartex");
header1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
header1.AddNamespaceDeclaration("aink", "http://schemas.microsoft.com/office/drawing/2016/ink");
header1.AddNamespaceDeclaration("am3d", "http://schemas.microsoft.com/office/drawing/2017/model3d");
header1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
header1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
header1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
header1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
header1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
header1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
header1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
header1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
header1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
header1.AddNamespaceDeclaration("w15", "http://schemas.microsoft.com/office/word/2012/wordml");
header1.AddNamespaceDeclaration("w16se", "http://schemas.microsoft.com/office/word/2015/wordml/symex");
header1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
header1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
header1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
header1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");
Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "00B22010", RsidRunAdditionDefault = "00B22010" };
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Header" };
paragraphProperties1.Append(paragraphStyleId1);
Run run1 = new Run();
Text text1 = new Text() { Space = SpaceProcessingModeValues.Preserve };
text1.Text = "This is a ";
run1.Append(text1);
Run run2 = new Run();
Text text2 = new Text();
text2.Text = "header";
run2.Append(text2);
BookmarkStart bookmarkStart1 = new BookmarkStart() { Name = "_GoBack", Id = "0" };
BookmarkEnd bookmarkEnd1 = new BookmarkEnd() { Id = "0" };
paragraph1.Append(paragraphProperties1);
paragraph1.Append(run1);
paragraph1.Append(run2);
paragraph1.Append(bookmarkStart1);
paragraph1.Append(bookmarkEnd1);
header1.Append(paragraph1);
part.Header = header1;
}
private static void AddSettingsToMainDocumentPart(MainDocumentPart part)
{
DocumentSettingsPart settingsPart = part.AddNewPart<DocumentSettingsPart>();
settingsPart.Settings = new Settings(
new Compatibility(
new CompatibilitySetting()
{
Name = new EnumValue<CompatSettingNameValues>(CompatSettingNameValues.CompatibilityMode),
Val = new StringValue("16"),
Uri = new StringValue("http://schemas.microsoft.com/office/word")
}
)
);
settingsPart.Settings.Save();
}
Ludovic Perrichon (http://www.ludovicperrichon.com/) helped me find an answer for this one. While we didn't get my code to work the code here
https://msdn.microsoft.com/en-us/library/ee355228(v=office.12).aspx
does work and allows me to generate a header with the new document.
Slightly modified from the link above:
public static void CreateWordprocessingDocument(string filepath)
{
string documentPath = filepath;
using (WordprocessingDocument package =
WordprocessingDocument.Create(
documentPath, WordprocessingDocumentType.Document))
{
AddParts(package);
}
}
private static void AddParts(WordprocessingDocument parent)
{
var mainDocumentPart = parent.AddMainDocumentPart();
GenerateMainDocumentPart().Save(mainDocumentPart);
var documentSettingsPart =
mainDocumentPart.AddNewPart
<DocumentSettingsPart>("rId1");
GenerateDocumentSettingsPart().Save(documentSettingsPart);
var firstPageHeaderPart =
mainDocumentPart.AddNewPart<HeaderPart>("rId2");
GeneratePageHeaderPart(
"First page header").Save(firstPageHeaderPart);
var firstPageFooterPart =
mainDocumentPart.AddNewPart<FooterPart>("rId3");
GeneratePageFooterPart(
"First page footer").Save(firstPageFooterPart);
var evenPageHeaderPart =
mainDocumentPart.AddNewPart<HeaderPart>("rId4");
GeneratePageHeaderPart(
"Even page header").Save(evenPageHeaderPart);
var evenPageFooterPart =
mainDocumentPart.AddNewPart<FooterPart>("rId5");
GeneratePageFooterPart(
"Even page footer").Save(evenPageFooterPart);
var oddPageheaderPart =
mainDocumentPart.AddNewPart<HeaderPart>("rId6");
GeneratePageHeaderPart(
"Odd page header").Save(oddPageheaderPart);
var oddPageFooterPart =
mainDocumentPart.AddNewPart<FooterPart>("rId7");
GeneratePageFooterPart(
"Odd page footer").Save(oddPageFooterPart);
}
private static Document GenerateMainDocumentPart()
{
var element =
new Document(
new Body(
new Paragraph(
new Run(
new Text("Page 1 content"))
),
new Paragraph(
new Run(
new Break() { Type = BreakValues.Page })
),
new Paragraph(
new Run(
new LastRenderedPageBreak(),
new Text("Page 2 content"))
),
new Paragraph(
new Run(
new Break() { Type = BreakValues.Page })
),
new Paragraph(
new Run(
new LastRenderedPageBreak(),
new Text("Page 3 content"))
),
new Paragraph(
new Run(
new Break() { Type = BreakValues.Page })
),
new Paragraph(
new Run(
new LastRenderedPageBreak(),
new Text("Page 4 content"))
),
new Paragraph(
new Run(
new Break() { Type = BreakValues.Page })
),
new Paragraph(
new Run(
new LastRenderedPageBreak(),
new Text("Page 5 content"))
),
new SectionProperties(
new HeaderReference()
{
Type = HeaderFooterValues.First,
Id = "rId2"
},
new FooterReference()
{
Type = HeaderFooterValues.First,
Id = "rId3"
},
new HeaderReference()
{
Type = HeaderFooterValues.Even,
Id = "rId4"
},
new FooterReference()
{
Type = HeaderFooterValues.Even,
Id = "rId5"
},
new HeaderReference()
{
Type = HeaderFooterValues.Default,
Id = "rId6"
},
new FooterReference()
{
Type = HeaderFooterValues.Default,
Id = "rId7"
},
new PageMargin()
{
Top = 1440,
Right = (UInt32Value)1440UL,
Bottom = 1440,
Left = (UInt32Value)1440UL,
Header = (UInt32Value)720UL,
Footer = (UInt32Value)720UL,
Gutter = (UInt32Value)0UL
},
new TitlePage()
)));
return element;
}
private static Footer GeneratePageFooterPart(string FooterText)
{
var element =
new Footer(
new Paragraph(
new ParagraphProperties(
new ParagraphStyleId() { Val = "Footer" }),
new Run(
new Text(FooterText))
));
return element;
}
private static Header GeneratePageHeaderPart(string HeaderText)
{
var element =
new Header(
new Paragraph(
new ParagraphProperties(
new ParagraphStyleId() { Val = "Header" }),
new Run(
new Text(HeaderText))
));
return element;
}
private static Settings GenerateDocumentSettingsPart()
{
var element =
new Settings(new EvenAndOddHeaders());
return element;
}
I've automated this process of creating Headers and Footers using OpenXML in my OfficeIMO C# Library (MIT licensed) with support for Different Odd and Event Pages, Different First Page and support for sections to the point where it's just as easy as this:
document.AddHeadersAndFooters();
document.DifferentOddAndEvenPages = true;
document.DifferentFirstPage = true;
full code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OfficeIMO.Word;
using SixLabors.ImageSharp;
namespace OfficeIMO.Examples.Word {
internal static partial class HeadersAndFooters {
internal static void Example_BasicWordWithHeaderAndFooter0(string folderPath, bool openWord) {
Console.WriteLine("[*] Creating standard document with Headers and Footers");
string filePath = System.IO.Path.Combine(folderPath, "Basic Document with Headers and Footers Default.docx");
using (WordDocument document = WordDocument.Create(filePath)) {
document.AddHeadersAndFooters();
document.DifferentOddAndEvenPages = true;
document.DifferentFirstPage = true;
document.Header.Default.AddParagraph().SetColor(Color.Red).SetText("Test Header");
document.Footer.Default.AddParagraph().SetColor(Color.Blue).SetText("Test Footer");
Console.WriteLine("Header Default Count: " + document.Header.Default.Paragraphs.Count);
Console.WriteLine("Header Even Count: " + document.Header.Even.Paragraphs.Count);
Console.WriteLine("Header First Count: " + document.Header.First.Paragraphs.Count);
Console.WriteLine("Header text: " + document.Header.Default.Paragraphs[0].Text);
Console.WriteLine("Footer Default Count: " + document.Footer.Default.Paragraphs.Count);
Console.WriteLine("Footer Even Count: " + document.Footer.Even.Paragraphs.Count);
Console.WriteLine("Footer First Count: " + document.Footer.First.Paragraphs.Count);
Console.WriteLine("Footer text: " + document.Footer.Default.Paragraphs[0].Text);
document.Save();
}
using (WordDocument document = WordDocument.Load(filePath)) {
Console.WriteLine("Header Default Count: " + document.Header.Default.Paragraphs.Count);
Console.WriteLine("Header Even Count: " + document.Header.Even.Paragraphs.Count);
Console.WriteLine("Header First Count: " + document.Header.First.Paragraphs.Count);
Console.WriteLine("Header text: " + document.Header.Default.Paragraphs[0].Text);
Console.WriteLine("Footer Default Count: " + document.Footer.Default.Paragraphs.Count);
Console.WriteLine("Footer Even Count: " + document.Footer.Even.Paragraphs.Count);
Console.WriteLine("Footer First Count: " + document.Footer.First.Paragraphs.Count);
Console.WriteLine("Footer text: " + document.Footer.Default.Paragraphs[0].Text);
document.Save(openWord);
}
}
}
}
OfficeIMO GitHub Page

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;
}

how can I change the font open xml

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();

Categories

Resources