I am new to Open XML. This is what I have been able to achieve so far:
- Create a Word Document
- Add a Paragraph with some text
- Align text by changing justification property of paragraph
- Change font size & bold (on/off)
I am trying to add two paragraphs with different font size and justifications. This is my code:
Dim FontHeading As New DocumentFormat.OpenXml.Wordprocessing.FontSize
FontHeading.Val = New StringValue("28")
Dim FontSubHeading As New DocumentFormat.OpenXml.Wordprocessing.FontSize
FontSubHeading.Val = New StringValue("24")
Dim wordDocument As WordprocessingDocument = WordprocessingDocument.Create(Server.MapPath("/test.docx"), WordprocessingDocumentType.Document)
Dim mainPart As MainDocumentPart = wordDocument.AddMainDocumentPart()
mainPart.Document = New Document()
Dim dbody As New Body
dbody.AppendChild(AddParagraph("PREM CORPORATE", FontHeading, FontBold, CenterJustification))
dbody.AppendChild(AddParagraph("Company Incorporation Documents", FontSubHeading, FontBold, CenterJustification))
mainPart.Document.AppendChild(dbody)
mainPart.Document.Save()
wordDocument.Close()
Function to add paragraph:
Private Function AddParagraph(ByVal txt As String, ByVal fsize As DocumentFormat.OpenXml.Wordprocessing.FontSize, ByVal fbold As Bold, ByVal pjustification As Justification) As Paragraph
Dim runProp As New RunProperties
runProp.Append(fsize)
runProp.Append(fbold)
Dim run As New Run
run.Append(runProp)
run.Append(New Text(txt))
Dim pp As New ParagraphProperties
pp.Justification = pjustification
Dim p As Paragraph = New Paragraph
p.Append(pp)
p.Append(run)
Return p
End Function
The above results in an empty document. If I remove the second dbody.AppendChild line, then it successfully adds the first paragraph.
Please help what do I need to change/add.
You're trying to add the same instance of the
Bold
andJustification
objects to differentParagraphs
. This isn't allowed and should result in the error:To get round this you should create a new
Bold
and a newJustification
each time you need one.In your
AddParagraph
method you could just take aBoolean
to denote whether or not the text should be bold and aJustificationValues
to denote the justification to use then create new instances of each as required:Your calls to add the
Paragraphs
would then be something like this: