How can i create a word header from a html string - c#

I'm generating a word docx file from a html string and using various articles I've found how to add simple headers and footers to that document.
What I now need to do is generate the header from a html string too but I'm struggling to find an example of how this is done.
The author of this question:
Export docx/doc First Header and Footer as docx File Using openXML
says he has done it but unfortunately he hasn't posted an example.
My code below successfully adds a header but as you can see from the code it will only add the html as text in the header, whereas I want to pass in a html string and that to appear in the header as formatted html.
Has anyone done this?
static void AddHeaderPart(MainDocumentPart mainPart, string headerHtml, Encoding encoding)
{
if (mainPart == null || string.IsNullOrEmpty(headerHtml))
{return;}
// Create a new header part.
HeaderPart headerPart = mainPart.AddNewPart<HeaderPart>();
// Get Id of the headerPart.
string rId = mainPart.GetIdOfPart(headerPart);
// Call GenerateHeaderPartContent
GenerateHeaderPartContent(mainPart, headerPart, headerHtml, encoding);
// Get SectionProperties and Replace HeaderReference with new Id.
IEnumerable<SectionProperties> sectPrs = mainPart.Document.Body.Elements<SectionProperties>();
foreach (var sectPr in sectPrs)
{
// Delete existing references to headers.
sectPr.RemoveAllChildren<HeaderReference>();
// Create the new header reference node.
sectPr.PrependChild<HeaderReference>(new HeaderReference() { Id = rId, Type = HeaderFooterValues.Default });
}
}
static void GenerateHeaderPartContent(MainDocumentPart mainPart, HeaderPart headerPart, string headerHtml, Encoding encoding)
{
Header header1 = new Header() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
header1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
header1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
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("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();
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Header" };
paragraphProperties1.Append(paragraphStyleId1);
//This adds the headerHtml as text - how to add it as html?
Run run1 = new Run();
Text text1 = new Text();
text1.Text = headerHtml;
run1.Append(text1);
paragraph1.Append(paragraphProperties1);
paragraph1.Append(run1);
header1.Append(paragraph1);
headerPart.Header = header1;
}

So the code below uses an altChunk to add html into the header. It's not perfect as I get validation errors when I use the OpenXmlValidator to validate the generated document although the doc still opens ok in word but I'm posting it here as an answer as it does do what I asked above & it might help others:
static void GenerateHeaderPartContent(MainDocumentPart mainPart, HeaderPart headerPart, string headerHtml)
{
Header header1 = new Header() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
header1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
header1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
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("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();
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Header" };
paragraphProperties1.Append(paragraphStyleId1);
paragraph1.Append(paragraphProperties1);
string altChunkId = "AltChunkId1";
AlternativeFormatImportPart chunk = headerPart.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.Html, altChunkId);
// Note that headerHtml should be full html, not just a snippet
// eg. <html><h1>My Header</h1></html> is OK
// <h1>My Header</h1> is not OK
MemoryStream ms = new MemoryStream(new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(headerHtml)).ToArray());
chunk.FeedData(ms);
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
Run run1 = new Run();
RunProperties runProps = new RunProperties();
NoProof noProof1 = new NoProof();
runProps.Append(noProof1);
run1.Append(runProps);
run1.Append(altChunk);
paragraph1.Append(run1);
header1.Append(paragraph1);
headerPart.Header = header1;
}

Related

How to replace text with Image / Table in OpenXML (C# .Net core 3.1)

I am just using OpenXML for manipulating docx document. I have templates that has notation like
{{userFirstName}}
{{tableOfUsers}}
{{signatureImage}} etc
I need to replace those text with table, image etc. How to do that in Openxml ?
I'm using C# .Net core 3.1 with OpenXML 2.5
My code was like this, but the table still not inserted into the right place:
var fileName = Path.Combine(_hostingEnv.WebRootPath, "test/test.docx");
var fileNameResult = Path.Combine(_hostingEnv.WebRootPath, "test/result.docx");
byte[] byteArray = System.IO.File.ReadAllBytes(fileName);
using (MemoryStream stream = new MemoryStream())
{
stream.Write(byteArray, 0, (int)byteArray.Length);
using (WordprocessingDocument wd = WordprocessingDocument.Open(stream, true))
{
Table table = new Table();
// Create a TableProperties object and specify its border information.
TableProperties tblProp = new TableProperties(
new TableBorders(
new TopBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new BottomBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new LeftBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new RightBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new InsideHorizontalBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new InsideVerticalBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
}
)
);
// Append the TableProperties object to the empty table.
table.AppendChild<TableProperties>(tblProp);
// Create a row.
TableRow tr = new TableRow();
// Create a cell.
TableCell tc1 = new TableCell();
// Specify the width property of the table cell.
tc1.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
// Specify the table cell content.
tc1.Append(new Paragraph(new Run(new Text("some text"))));
// Append the table cell to the table row.
tr.Append(tc1);
// Create a second table cell by copying the OuterXml value of the first table cell.
TableCell tc2 = new TableCell(tc1.OuterXml);
// Append the table cell to the table row.
tr.Append(tc2);
// Append the table row to the table.
table.Append(tr);
var tblStr = table.ToString();
//wd.MainDocumentPart.Document.Body.Append(table);
Text tablePl = wd.MainDocumentPart.Document.Body.Descendants<Text>().Where(x => x.Text == "{{tableOfUsers}}").First();
if(tablePl != null)
{
var parent = tablePl.Parent;
tablePl.Parent.InsertAfter<Table>(table, tablePl);
tablePl.Remove();
}
string docText = null;
using (StreamReader sr = new StreamReader(wd.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
Regex regexText = new Regex("{{name}}");
docText = regexText.Replace(docText, "Claire " + DateTime.Now.ToString());
// Regex regextable = new Regex("{{tableOfUsers}}");
// docText = regextable.Replace(docText, tblStr);
using (StreamWriter sw = new StreamWriter(wd.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
await System.IO.File.WriteAllBytesAsync(fileNameResult, stream.ToArray());
}
_fileRepo.SetPath("test");
string fileName2 = "result.docx";
var data = await _fileRepo.DownloadFile(fileName2);
return File(data, "application/octet-stram", "filename.docx");
}
My docx file looks like
Hello {{name}}
Here is the list of users : {{tableOfUsers}}
Sincerely,
{{signatureImage}}
Use the code below to insert a table:
............
string tablePlaceholder = "{{tableOfUsers}}";
Text tablePl = wd.MainDocumentPart.Document.Body
.Descendants<Text>()
.Where(x => x.Text.Contains(tablePlaceholder))
.First();
if (tablePl != null)
{
//Insert the table after the paragraph.
var parent = tablePl.Parent.Parent.Parent;
parent.InsertAfter(table, tablePl.Parent.Parent);
tablePl.Text = tablePl.Text.Replace(tablePlaceholder, "");
wd.MainDocumentPart.Document.Save();
}
string docText = wd.MainDocumentPart.Document.Body.OuterXml;
Regex regexText = new Regex("{{name}}");
docText = regexText.Replace(docText, "Claire " + DateTime.Now.ToString());
wd.MainDocumentPart.Document.Body = new Body(docText);
wd.MainDocumentPart.Document.Save();
.............
You are looking for {{table}} in your code, but the notation in your template is {{tableOfUsers}}.

how to download docx file created with the open xml sdk?

Document.cs:
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
namespace GeneratedCode
{
public class GeneratedClass
{
// Creates an Document instance and adds its children.
public Document GenerateDocument()
{
Document document1 = new Document(){ MCAttributes = new MarkupCompatibilityAttributes(){ Ignorable = "w14 w15 wp14" } };
document1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
document1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
document1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
document1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
document1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
document1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
document1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
document1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
document1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
document1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
document1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
document1.AddNamespaceDeclaration("w15", "http://schemas.microsoft.com/office/word/2012/wordml");
document1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
document1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
document1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
document1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");
Body body1 = new Body();
Paragraph paragraph1 = new Paragraph(){ RsidParagraphMarkRevision = "00100E91", RsidParagraphAddition = "009D5F75", RsidRunAdditionDefault = "00100E91" };
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
Languages languages1 = new Languages(){ Val = "en-US" };
paragraphMarkRunProperties1.Append(languages1);
paragraphProperties1.Append(paragraphMarkRunProperties1);
Run run1 = new Run();
RunProperties runProperties1 = new RunProperties();
Languages languages2 = new Languages(){ Val = "en-US" };
runProperties1.Append(languages2);
Text text1 = new Text();
text1.Text = "Hello";
run1.Append(runProperties1);
run1.Append(text1);
BookmarkStart bookmarkStart1 = new BookmarkStart(){ Name = "_GoBack", Id = "0" };
BookmarkEnd bookmarkEnd1 = new BookmarkEnd(){ Id = "0" };
paragraph1.Append(paragraphProperties1);
paragraph1.Append(run1);
paragraph1.Append(bookmarkStart1);
paragraph1.Append(bookmarkEnd1);
SectionProperties sectionProperties1 = new SectionProperties(){ RsidRPr = "00100E91", RsidR = "009D5F75" };
PageSize pageSize1 = new PageSize(){ Width = (UInt32Value)11906U, Height = (UInt32Value)16838U };
PageMargin pageMargin1 = new PageMargin(){ Top = 1134, Right = (UInt32Value)850U, Bottom = 1134, Left = (UInt32Value)1701U, Header = (UInt32Value)708U, Footer = (UInt32Value)708U, Gutter = (UInt32Value)0U };
Columns columns1 = new Columns(){ Space = "708" };
DocGrid docGrid1 = new DocGrid(){ LinePitch = 360 };
sectionProperties1.Append(pageSize1);
sectionProperties1.Append(pageMargin1);
sectionProperties1.Append(columns1);
sectionProperties1.Append(docGrid1);
body1.Append(paragraph1);
body1.Append(sectionProperties1);
document1.Append(body1);
return document1;
}
}
}
I want to get the document created on this code (code from Open XML SDK).
how by pressing the button to get ready document (get hello.docx)?
Created project: asp.net mvc 4
add:
1) Controller
2) View-> code:
#using (Html.BeginForm())
{
<input type="submit" value="Get docx file" />
}
Thank you all.
The problem is solved.
Method:
public ActionResult GetFile()
{
try
{
byte[] document = new GeneratedClass().CreateDocumenBytes();
return File(document, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "Contract.docx");
}
catch (Exception ex)
{
ViewBag.ErrorMessage = ex.Message;
throw;
}
}
View:
#using (Html.BeginForm())
{
#Html.ActionLink("Экспорт договора в Word","GetFile","get")
}
You simply need to create an action that returns a FileResult or a ContentResult. I.e. your action should make a call to
return File(...);
or
return Content(...);
You must specify parameters for the file name, file content, encoding... Look at the documentation of:
[FileResult][1]
[ContentResult][2]
And the documentation of the Content and File methods of the Controller class (mentioned above).
If you want to do it using a submit button, your action must be decorated with [HttpPost]. You can also expose it as a link, and implement a GET action. In any case, you should send extra information so that the servers know whic document is being requested (form values, if you use POST, or Url parameters, if you use GET).

How to delete data or table within two bookmarks from word document using OpenXml in C#

I am creating word document in C# using OpenXML.
I can insert my Text after specified bookmark, but how can delete data within two bookmarks.
Following is the code to insert text after specified Bookmark.
string fileName = #"C:\Users\sharepointadmin\Desktop\volc.docx";
TableValues ObjTableValues = new TableValues();
List<TableValues> allValues = new System.Collections.Generic.List<TableValues>();
for (int i = 1; i <= 5; i++)
{
ObjTableValues = new TableValues();
ObjTableValues.EmpID = i.ToString();
ObjTableValues.EmpName = "Emp" + i.ToString();
ObjTableValues.EmpDesig = "SE";
ObjTableValues.EmpDept = "Software";
allValues.Add(ObjTableValues);
//ConvertMailMergeEscape(fileName);
}
AddTable(fileName, allValues);
}
using (var document = WordprocessingDocument.Open(fileName, true))
{
IDictionary<String, BookmarkStart> bookmarkMap = new Dictionary<String, BookmarkStart>();
var doc = document.MainDocumentPart.Document;
var mainpart = document.MainDocumentPart;
var res = from ObjTableValues in mainpart.Document.Body.Descendants<BookmarkStart>() where ObjTableValues.Name == "testbookmark" select ObjTableValues;
var bookmark = res.SingleOrDefault();
if (bookmark != null)
{
var parent = bookmark.Parent;
run.Append(text);
Paragraph newParagraph = new Paragraph(run);
// insert after bookmark parent
parent.InsertAfterSelf(newParagraph);
foreach (BookmarkStart bookmarkStart in document.MainDocumentPart.RootElement.Descendants<BookmarkStart>())
{
bookmarkMap[bookmarkStart.Name] = bookmarkStart;
}
MoveToRangeStart ranstart = new MoveToRangeStart();
foreach (BookmarkStart bookmarkStart in bookmarkMap.Values)
{
Run bookmarkText = bookmarkStart.NextSibling<Run>();
if (bookmarkText != null)
{
//bookmarkText.GetFirstChild<Text>().Text = "blah";
}
}
DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();
TableProperties props = new TableProperties(
new TableBorders(
new TopBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new BottomBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new LeftBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new RightBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideHorizontalBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideVerticalBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
}));
table.AppendChild<TableProperties>(props);
foreach (TableValues Tableitem in allValues)
{
var tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
var tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
tc.Append(new Paragraph(new Run(new Text(Tableitem.EmpID))));
tr.Append(tc);
tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
tc.Append(new Paragraph(new Run(new Text(Tableitem.EmpName))));
tr.Append(tc);
tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
tc.Append(new Paragraph(new Run(new Text(Tableitem.EmpDesig))));
tr.Append(tc);
tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
tc.Append(new Paragraph(new Run(new Text(Tableitem.EmpDept))));
tr.Append(tc);
table.Append(tr);
}
doc.Body.Append(table);
doc.Save();
}
}
}
}
Can any one help me please.
I assume you want to delete some table or data from word document. If this is the case than I will suggest you to enable the developer tab in Microsoft Word. For Microsoft Word 2007 if you click on Office Button and than go to "Word Options" button which is at the bottom of drop down menue. Now enable Show "Developer tab in The Ribbon".
Once you have activated the developer tab now you can see an additional tab "Developer" in your Microsoft Word. From this tab if you click on the Rich Text icon (Marked with Aa), will insert a tag on your word document. Now, If you right click on the tag, you can give this tag a name and id.
Now you can access this tag by its id or name in C#.
e.g. the tag name you have given is 'Test Tag'
MainDocumentPart mainPart = doc.MainDocumentPart;
List<SdtBlock> taggedContentControls = mainPart.Document.Descendants<SdtBlock>().ToList();
foreach (var tagControl in taggedContentControls)
{
string tagName = tagControl.Descendants<SdtAlias>().First().Val.Value;
if(tagName== "Test Tag")
{
// you can insert any data in this tag over here
}
Now, with similar approach let's suppose you have a table and some other data in this tag that you want to delete
foreach (var tagControl in taggedContentControls)
{
string tagName = tagControl.Descendants<SdtAlias>().First().Val.Value;
if (tagName.Contains("Test Tag"))
{
// If we want to delete table only
//tagControl.SdtContentBlock.Descendants<Table>().First().Remov();
// If you want to remove everything in this tag
tagControl.SdtContentBlock.Remove();
}
}
dont forget to save your document at the end of this operation
i mean mainpart.Document.Save();
for simplicity I have written multiple LINQ statements to fetch tag from the document. You can change them according to your understanding.
I hope it will help you to get your problem sorted.
Regards

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

Creating docx paragraphs from strings array

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

Categories

Resources