Add Header to OpenXML Document - c#

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

Related

Open XML SDK ASP .NET - Creating a nested ordered list

I'm wondering how would one create an ordered nested list using Open XML SDK.
The outcome I'd like to have is:
Parent 1
a. Child 1
b. Child 2
I've tried doing numbering properties but all I'm getting is:
Parent 1
Child 1
Child 2
EDIT:
Here's my sample code, sorry:
Paragraph para1 = new Paragraph(
new ParagraphProperties(
new NumberingProperties(
new NumberingLevelReference() { Val = 1 },
new NumberingId() { Val = 1 }
),
new ParagraphStyleId() { Val = "ListParagraph" }
)
);
para1.AppendChild(
new Run(
new RunProperties(),
new Text("Parent item")
));
Paragraph para2 = new Paragraph(
new ParagraphProperties(
new NumberingProperties(
new NumberingLevelReference() { Val = 2 },
new NumberingId() { Val = 1 }
),
new ParagraphStyleId() { Val = "ListParagraph" }
)
);
para2.AppendChild(new Run(
new RunProperties(),
new Text("Child item")
));
body.AppendChild(para1);
body.AppendChild(para2);

OpenXML strange behaviour with font-size

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.

C# WordprocessingDocument - insert an image in a cell

I have a method that replaces the tags in the document specific text. How do I replace the label picture?
Here is a piece of code that looks for a cell with the text 'PersonMainPhoto' inside a table. The tabel-cell is cleared, and an image is inserted. Hopefully this can guide you in the right direction.
Inserting an image is a two part process:
Add image part to the document
Insert a reference to the image inside the body text - with all kinds of details regarding scaling, positioning etc.
The code for inserting the reference is taken from the brilliant OpenXML SDK documentation: https://msdn.microsoft.com/en-us/library/office/bb497430.aspx
using System.IO;
using System.Linq;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
namespace StackOverflow
{
class Program
{
static void Main(string[] args)
{
string file = #"c:\temp\mydoc.docx";
string imageFile = #"c:\temp\myimage.jpg";
string labelText = "PersonMainPhoto";
using (var document = WordprocessingDocument.Open(file, isEditable: true))
{
var mainPart = document.MainDocumentPart;
var table = mainPart.Document.Body.Descendants<Table>().First();
var pictureCell = table.Descendants<TableCell>().First(c => c.InnerText == labelText);
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
using (FileStream stream = new FileStream(imageFile, FileMode.Open))
{
imagePart.FeedData(stream);
}
pictureCell.RemoveAllChildren();
AddImageToCell(pictureCell, mainPart.GetIdOfPart(imagePart));
mainPart.Document.Save();
}
}
private static void AddImageToCell(TableCell cell, string relationshipId)
{
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 = relationshipId,
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
});
cell.Append(new Paragraph(new Run(element)));
}
}
}
how do the picture fit, just into tablecell!??
not to fix it .
Cx = 990000L, Cy = 792000L
like this?
TableCellProperties tableCellProperties1 = VARIABLE.GetFirstChild<TableCellProperties>();
TableCellWidth tableCellWidth1 = tableCellProperties1.GetFirstChild<TableCellWidth>();
int _width = Int32.Parse(tableCellWidth1.Width);
TableRowProperties tableRowProperties1 =
VARIABLE.Parent.GetFirstChild<TableRowProperties>();
TableRowHeight tableRowHeight1 =
tableRowProperties1.GetFirstChild<TableRowHeight>();
int _height = Int32.Parse(tableRowHeight1.Val);
document.MainDocumentPart.Document.Save();

watermarking a word document using OpenXML sdk

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.

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