A simple way to render a long text spanning multiple pages

PDF TIFF SVG JPG C# VB
PaginatedText.vb
  1. ''
  2. '' This code is part of Document Solutions for PDF demos.
  3. '' Copyright (c) MESCIUS inc. All rights reserved.
  4. ''
  5. Imports System.IO
  6. Imports System.Drawing
  7. Imports GrapeCity.Documents.Pdf
  8. Imports GrapeCity.Documents.Text
  9. Imports GrapeCity.Documents.Drawing
  10.  
  11. '' This sample shows how to render a long text spanning multiple pages.
  12. Public Class PaginatedText
  13. Function CreatePDF(ByVal stream As Stream) As Integer
  14. Dim doc = New GcPdfDocument()
  15. ''
  16. '' Use TextLayout to render text:
  17. Dim tl = New TextLayout(72)
  18. '' If not specifying formats for individual runs, we MUST provide
  19. '' font and font size on TextLayout.DefaultFormat:
  20. tl.DefaultFormat.Font = StandardFonts.Times
  21. tl.DefaultFormat.FontSize = 12
  22. '' First line offset 1/2":
  23. tl.FirstLineIndent = 72 / 2
  24. ''
  25. '' All other formatting properties are left at their default values.
  26. '' In particular, TextLayout's default resolution is 72 dpi -
  27. '' the same as DsPdf's, and WordWrap is true.
  28. ''
  29. '' Set TextLayout's area to the whole page:
  30. tl.MaxWidth = doc.PageSize.Width
  31. tl.MaxHeight = doc.PageSize.Height
  32. '' ...and have it manage the page margins (1" all around):
  33. tl.MarginAll = tl.Resolution
  34. ''
  35. '' Append the text (20 paragraphs so they would not fit on a single page)
  36. '' (note that TextLayout interprets vbCrLf as paragraph delimiter):
  37. tl.Append(Util.LoremIpsum(20))
  38. ''
  39. '' When all text has been added, we must calculate the glyphs needed to render the text,
  40. '' and perform the layout. This can be done by a single call to PerformLayout, passing true to
  41. '' recalculate glyphs first (even though the text won't all fit in the specified max size,
  42. '' we only need to call PerformLayout once):
  43. tl.PerformLayout(True)
  44. '' Use split options to provide widow/orphan control:
  45. Dim tso = New TextSplitOptions(tl)
  46. tso.MinLinesInFirstParagraph = 2
  47. tso.MinLinesInLastParagraph = 2
  48. '' In a loop, split and render the text:
  49. While (True)
  50. '' 'rest' will accept the text that did not fit:
  51. Dim rest As TextLayout = Nothing
  52. Dim splitResult = tl.Split(tso, rest)
  53. doc.Pages.Add().Graphics.DrawTextLayout(tl, PointF.Empty)
  54. If splitResult <> SplitResult.Split Then
  55. Exit While
  56. End If
  57. tl = rest
  58. End While
  59. ''
  60. '' Done:
  61. doc.Save(stream)
  62. Return doc.Pages.Count
  63. End Function
  64. End Class
  65.