Create a text document with some images and text highlights

PDF TIFF SVG JPG C# VB
Wetlands.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 System.Collections.Generic
  8. Imports GrapeCity.Documents.Pdf
  9. Imports GrapeCity.Documents.Text
  10. Imports GrapeCity.Documents.Drawing
  11. Imports GCTEXT = GrapeCity.Documents.Text
  12. Imports GCDRAW = GrapeCity.Documents.Drawing
  13.  
  14. '' This sample generates a text document with some images And text highlights,
  15. '' imports the TextLayout class to arrange text And images.
  16. Public Class Wetlands
  17. '' The main sample driver.
  18. Function CreatePDF(ByVal stream As Stream) As Integer
  19. Dim doc = New GcPdfDocument()
  20.  
  21. '' This will hold the llst of images so we can dispose them after saving the document
  22. Dim disposables As New Generic.List(Of IDisposable)
  23.  
  24. '' Page footer:
  25. Dim ftrImg = GCDRAW.Image.FromFile(Path.Combine("Resources", "ImagesBis", "logo-GC-devsol.png"))
  26. disposables.Add(ftrImg)
  27. Dim fx = ftrImg.HorizontalResolution / 72
  28. Dim fy = ftrImg.VerticalResolution / 72
  29. Dim ftrRc = New RectangleF(
  30. doc.PageSize.Width / 2 - ftrImg.Width / fx / 2,
  31. doc.PageSize.Height - 40,
  32. ftrImg.Width / fx,
  33. ftrImg.Height / fy)
  34.  
  35. Dim addFtr As Action =
  36. Sub()
  37. doc.Pages.Last.Graphics.DrawImage(ftrImg, ftrRc, Nothing, ImageAlign.StretchImage)
  38. End Sub
  39.  
  40. '' Color for the title:
  41. Dim colorBlue = Color.FromArgb(&H3B, &H5C, &HAA)
  42. '' Color for the highlights:
  43. Dim colorRed = Color.Red
  44. '' The text layout used to render text:
  45. Dim tl = New TextLayout(72) With {
  46. .MaxWidth = doc.PageSize.Width,
  47. .MaxHeight = doc.PageSize.Height,
  48. .MarginLeft = 72,
  49. .MarginRight = 72,
  50. .MarginTop = 72,
  51. .MarginBottom = 72
  52. }
  53. tl.DefaultFormat.Font = GCTEXT.Font.FromFile(Path.Combine("Resources", "Fonts", "segoeui.ttf"))
  54. tl.DefaultFormat.FontSize = 11
  55.  
  56. Dim page = doc.NewPage()
  57. addFtr()
  58.  
  59. Dim g = page.Graphics
  60.  
  61. '' Caption:
  62. tl.TextAlignment = TextAlignment.Center
  63. tl.Append("Introduction" + vbCrLf, New TextFormat() With {.FontSize = 16, .ForeColor = colorBlue})
  64. tl.Append("The Importance of Wetlands", New TextFormat() With {.FontSize = 13, .ForeColor = colorBlue})
  65. tl.PerformLayout(True)
  66. g.DrawTextLayout(tl, PointF.Empty)
  67.  
  68. '' Move below the caption for the first para:
  69. tl.MarginTop = tl.ContentHeight + 72 * 2
  70. tl.Clear()
  71. tl.TextAlignment = TextAlignment.Leading
  72. tl.ParagraphSpacing = 12
  73.  
  74. Dim addPara As Action(Of String) =
  75. Sub(para)
  76. '' We implement a primitive markup to highlight some fragments in red:
  77. Dim txt = para.Split(New String() {"<red>", "</red>"}, StringSplitOptions.None)
  78. For i = 0 To txt.Length - 1
  79. If i Mod 2 = 0 Then
  80. tl.Append(txt(i))
  81. Else
  82. tl.Append(txt(i), New TextFormat(tl.DefaultFormat) With {.ForeColor = colorRed})
  83. End If
  84. Next
  85. tl.AppendLine()
  86. End Sub
  87.  
  88. '' For the first para we want a bigger initial letter, but no first line indent,
  89. '' so we render it separately from the rest of the text:
  90. tl.Append(_paras(0).Substring(0, 1), New TextFormat(tl.DefaultFormat) With {.FontSize = 22})
  91. addPara(_paras(0).Substring(1))
  92. tl.PerformLayout(True)
  93. g.DrawTextLayout(tl, PointF.Empty)
  94.  
  95. '' Account for the first para, And set up the text layout
  96. '' for the rest of the text (a TextLayout allows rendering multiple paragraphs,
  97. '' but they all must have the same paragraph format):
  98. tl.MarginTop = tl.ContentRectangle.Bottom
  99. tl.Clear()
  100. tl.FirstLineIndent = 36
  101.  
  102. '' Add remaining paragraphs:
  103. For Each para In _paras.Skip(1)
  104. '' Paragraphs starting with '::' indicate images to be rendered across the page width:
  105. If (para.StartsWith("::")) Then
  106. Dim img = GCDRAW.Image.FromFile(Path.Combine("Resources", "ImagesBis", para.Substring(2)))
  107. disposables.Add(img)
  108. Dim w = tl.MaxWidth.Value - tl.MarginLeft - tl.MarginRight
  109. Dim h = img.Height / img.Width * w
  110. tl.AppendInlineObject(img, w, h)
  111. tl.AppendLine()
  112. Else
  113. addPara(para)
  114. End If
  115. Next
  116. '' Layout the paragraphs:
  117. tl.PerformLayout(True)
  118. '' Text split options allow you to implement widow and orphan control:
  119. Dim tso = New TextSplitOptions(tl) With {
  120. .RestMarginTop = 72,
  121. .MinLinesInFirstParagraph = 2,
  122. .MinLinesInLastParagraph = 2
  123. }
  124. '' Image alignment used to render the pictures:
  125. Dim ia = New ImageAlign(ImageAlignHorz.Left, ImageAlignVert.Top, True, True, True, False, False) With {.BestFit = True}
  126. '' In a loop, split And render the text
  127. While (True)
  128. Dim rest As TextLayout = Nothing
  129. Dim splitResult = tl.Split(tso, rest)
  130. g = doc.Pages.Last.Graphics
  131. doc.Pages.Last.Graphics.DrawTextLayout(tl, PointF.Empty)
  132. '' Render all images that occurred on this page:
  133. For Each inlobj In tl.InlineObjects
  134. doc.Pages.Last.Graphics.DrawImage(DirectCast(inlobj.Object, GCDRAW.Image), inlobj.ObjectRect.ToRectangleF(), Nothing, ia)
  135. Next
  136. '' Break unless there Is more to render
  137. If splitResult <> SplitResult.Split Then
  138. Exit While
  139. End If
  140. '' Assign the remaining text to the 'main' TextLayout, add a new page and continue:
  141. tl = rest
  142. doc.Pages.Add()
  143. addFtr()
  144. End While
  145.  
  146. '' Save the PDF:
  147. doc.Save(stream)
  148. '' Dispose images (can be done only after saving the document):
  149. disposables.ForEach(Sub(d_) d_.Dispose())
  150. '' Done:
  151. Return doc.Pages.Count
  152. End Function
  153.  
  154. '' The list of text paragraphs to render.
  155. '' Note:
  156. '' - if a para starts with "::", the rest of the string Is the name of an image file to insert
  157. '' - <red>..</red> mark up the text to highlight.
  158. Shared _paras() As String =
  159. {
  160. "Originally there were in excess of <red>two point three (2.3) million</red> hectares of wetlands in southern Ontario. Today there is a mere <red>twelve percent (12%)</red> remaining (Rowntree 1979). Yet, these same areas are vital to the continued existence of a whole host of wildlife species. Grebes,herons, bitterns, rails, shorebirds, gulls, terns, and numerous smaller birds, plus the waterfowl, nest in or use wetlands for feeding and resting. About <red>ninety-five percent (95%)</red> of all furbearers are taken in water (Rowntree 1979). Reptiles and amphibians must return there to breed. ",
  161. "::Birdswetland.jpg",
  162. "Several species of game fish live or spawn in wetlands. Hundreds, if not thousands, of invertebrates that form the food of birds also rely on water for most, if not all, phases of their existence. In fact, most all species of animals we have must spend at least part of the year in wetlands. To lose any more of these vital areas is almost unthinkable.",
  163. "Wetlands enhance and protect water quality in lakes and streams where additional species spend their time and from which we draw our water. Water from drainage may have five (5) times more phosphates or as much as fifty (50) times more nitrates than water from marshes. These nutrient loads act as fertilizers to aquatic plants whose growth may clog rivers, foul shorelines and deplete oxygen in the water making it unsuitable for fish. Wetlands handle as much as <red>fifty percent (50%)</red> of terrestrial denitrification whereby nitrogen is returned to the atmosphere. Wetlands act as settling and filtration basins collecting silt that might build up behind dams or clog navigation channels. Vegetation in wetlands protects shorelines from damage by tides and storms. Wetlands soak up tremendous amounts of rainwater, slowing runoff and decreasing flooding that will help to decrease erosion of streambanks and prevent property damage. Water maintained in wetlands also helps to maintain ground water levels.",
  164. "Wetlands provide valuable renewable resources of fur, wild rice, fish, bait, cranberries, game, etc. They are rich in plant and animal life and are, therefore, ideal for scientific studies and educational field trips. The recreational potential for wetlands is immense. About <red>eighty percent (80%)</red> of Canadians value wildlife conservation and spend some three (3) billion dollars annually on nonconsumptive wildlife related activities as well as another one (1) billion on consumptive pursuits. Photography, bird-watching, canoeing, nature study, hiking, fishing and hunting are all pursued in wetlands.",
  165. "::palo_verde.jpg",
  166. "The economic value of wetlands may far exceed the returns gained from converting them to other uses. In addition to recreational potential, the farming of wildlife for economic return has proven to be viable for many species (Smith et al. 1983). Wetlands may prove valuable to more than fur, rice or cranberries in future.",
  167. "The greatest threats to our remaining wetlands are from agricultural drainage and industrial or hoimports developments (Brynaert 1983). Vast sums are expended annually by federal and provincial government agencies to implement drainage programs with little or no consideration given to wildlife values. The extensive so-called stream improvements, channeling and ditching, are very much questionable. It is essential now to introduce measures that clearly place the onus on agricultural agencies to prove that drainage projects are economically viable and that they do not jeopardize our wetland habitats (Brynaert 1983).",
  168. "Wetlands are important to the productivity of the entire biosphere (Sanderson 1977). They are vital to effective management of many wildlife species that depend upon these habitats. Whether a hunter or a naturalist, the preservation of wetlands is an objective that should appeal to everyone (Brynaert 1983). The entire province, country and continent have suffered a great loss in natural resources because of wetland losses. If we cannot succeed in saving wetlands, we shall not be able to meet the greater challenge of safeguarding an environment that man can continue to inhabit (Rowntree 1979)."
  169. }
  170. End Class
  171.