' create document
Dim word = New C1WordDocument()
word.Clear()
word.Info.Title = "Document with Table of Contents"
' add title
Dim titleFont As New Font("Tahoma", 24, RtfFontStyle.Bold)
Dim rcPage As Rect = WordUtils.PageRectangle(word)
Dim rc As Rect = WordUtils.RenderParagraph(word, word.Info.Title, titleFont, rcPage, rcPage, False)
rc.Y += 12
' create nonsense document
Dim bkmk = New List()
Dim headerFont As New Font("Arial", 14, RtfFontStyle.Bold)
Dim bodyFont As New Font("Times New Roman", 11)
For i As Integer = 0 To 29
' create ith header (as a link target and outline entry)
Dim header As String = String.Format("{0}. {1}", i + 1, BuildRandomTitle())
rc = WordUtils.RenderParagraph(word, header, headerFont, rcPage, rc, True, _
True)
' save bookmark to build TOC later
Dim pageNumber As Integer = 1
bkmk.Add(New String() {pageNumber.ToString(), header})
' create some text
rc.X += 36
rc.Width -= 36
For j As Integer = 0 To 3 + (rnd.[Next](20) - 1)
Dim text As String = BuildRandomParagraph()
rc = WordUtils.RenderParagraph(word, text, bodyFont, rcPage, rc)
rc.Y += 6
Next
rc.X -= 36
rc.Width += 36
rc.Y += 20
Next
' start Table of Contents
word.PageBreak()
' start TOC on a new page
rc = WordUtils.RenderParagraph(word, "Table of Contents", titleFont, rcPage, rcPage, True)
rc.Y += 12
rc.X += 30
rc.Width -= 40
' render Table of Contents
Dim dottedPen As New C1.WPF.Word.Pen(Colors.Gray, 1.5F)
dottedPen.DashStyle = C1.WPF.Word.DashStyle.Dot
Dim sfRight As New StringFormat()
sfRight.Alignment = HorizontalAlignment.Right
rc.Height = bodyFont.Size * 1.2
For Each entry As String() In bkmk
' get bookmark info
Dim page As String = entry(0)
Dim header As String = entry(1)
' render header name and page number
word.DrawString(header, bodyFont, Colors.Black, rc)
word.DrawString(page, bodyFont, Colors.Black, rc, sfRight)
' connect the two with some dots (looks better than a dotted line)
Dim dots As String = ". "
Dim wid = word.MeasureString(dots, bodyFont).Width
Dim x1 = rc.X + word.MeasureString(header, bodyFont).Width + 8
Dim x2 = rc.Right - word.MeasureString(page, bodyFont).Width - 8
Dim x = rc.X
rc.X = x1
While rc.X < x2
word.DrawString(dots, bodyFont, Colors.Gray, rc)
rc.X += wid
End While
rc.X = x
' move on to next entry
rc = WordUtils.Offset(rc, 0, rc.Height)
If rc.Bottom > rcPage.Bottom Then
word.PageBreak()
rc.Y = rcPage.Y
End If
Next
' get stream to save to
Dim dlg = New SaveFileDialog()
dlg.FileName = "Sample document"
dlg.DefaultExt = ".docx"
dlg.Filter = WordUtils.GetFileFilter(_extension)
Dim dr = dlg.ShowDialog()
If Not dr.HasValue OrElse Not dr.Value Then
Return
End If
' save document
Using stream = dlg.OpenFile()
word.Save(stream, If(dlg.FileName.ToLower().EndsWith(".docx"), FileFormat.OpenXml, FileFormat.Rtf))
End Using
MessageBox.Show("Word Document saved to " + dlg.SafeFileName)