CopyParagraphs.vb
  1. ''
  2. '' This code is part of Document Solutions for Word demos.
  3. '' Copyright (c) MESCIUS inc. All rights reserved.
  4. ''
  5. Imports System.IO
  6. Imports System.Drawing
  7. Imports System.Linq
  8. Imports GrapeCity.Documents.Word
  9. Imports GcFont = GrapeCity.Documents.Word.Font
  10.  
  11. '' Starting with the v3 release (fall of 2019), DsWord provides built-in
  12. '' support for copying and moving of content using the RangeBase.CopyTo()
  13. '' and RangeBase.MoveTo() methods, so this sample is now obsolete.
  14. ''
  15. '' The original SampleParagraphs.docx used in this sample can be
  16. '' seen by running the SampleParagraphs sample.
  17. Public Class CopyParagraphs
  18. Function CreateDocx() As GcWordDocument
  19. Const p1start = "This is the first paragraph of the original document"
  20. Const p2start = "This is the second paragraph of the original document"
  21. Const p3start = "This is the third paragraph of the original document"
  22. Const p4start = "This is the fourth paragraph of the original document"
  23.  
  24. Dim doc = New GcWordDocument()
  25.  
  26. '' Load an existing DOCX file:
  27. doc.Load(Path.Combine("Resources", "WordDocs", "SampleParagraphs.docx"))
  28.  
  29. Dim p1 = Nothing, p2 = Nothing, p3 = Nothing, p4 = Nothing
  30. For Each p In doc.Body.Paragraphs
  31. Dim t = p.GetRange().Text
  32. If (t.StartsWith(p1start)) Then
  33. p1 = p
  34. ElseIf (t.StartsWith(p2start)) Then
  35. p2 = p
  36. ElseIf (t.StartsWith(p3start)) Then
  37. p3 = p
  38. ElseIf (t.StartsWith(p4start)) Then
  39. p4 = p
  40. End If
  41. Next
  42. If p1 Is Nothing OrElse p2 Is Nothing OrElse p3 Is Nothing OrElse p4 Is Nothing Then
  43. Throw New Exception("Unexpected: could not find paragraphs.")
  44. End If
  45.  
  46. Dim swapResult = Helper.SwapParagraphs(p1, p3)
  47.  
  48. swapResult.Item1.GetRange().Runs.Insert("Second swapped paragraph (paragraph 3): ", InsertLocation.Start)
  49. swapResult.Item2.GetRange().Runs.Insert("First swapped paragraph (paragraph 1): ", InsertLocation.Start)
  50.  
  51. Dim joinResult = Helper.JoinParagraphs(doc.Body.Paragraphs.Add(), swapResult.Item1, swapResult.Item2)
  52. joinResult.GetRange().Runs.Insert("Jointed first and 3rd paragraphs: ", InsertLocation.Start)
  53.  
  54. '' Add a note at the end of the document:
  55. doc.Body.Paragraphs.Add($"Created by DsWord on {Util.TimeNow():R}.")
  56.  
  57. '' Done:
  58. Return doc
  59. End Function
  60.  
  61. '' A static helper class that provides methods to copy or move
  62. '' DsWord content objects such as paragraphs and runs.
  63. ''
  64. '' AddRun, AddPicture, AddField, AddText, AddParagraph methods accept parameter
  65. '' "withFormatting" which determines whether to copy just the content,
  66. '' or content and formatting. Note that if this parameter is true,
  67. '' direct formatting is applied to the newly created objects,
  68. '' so the connection to the original document style is broken
  69. '' (updating the style will not affect the new objects).
  70. Public Class Helper
  71. '' Swaps two paragraphs by inserting a new paragraph before each one,
  72. '' copying the content (and optionally formatting) from the other paragraph,
  73. '' and the removing the old paragraphs.
  74. Public Shared Function SwapParagraphs(ByRef p1 As Paragraph, ByRef p2 As Paragraph, Optional ByVal withFormatting As Boolean = True) As (Paragraph, Paragraph)
  75. If p1.ParentBody IsNot p2.ParentBody Then
  76. Throw New Exception("Both paragraphs must belong the same parent body.")
  77. End If
  78.  
  79. Dim newP2 = p1.GetRange().Paragraphs.Insert(InsertLocation.Before)
  80. CopyParagraph(newP2, p2, withFormatting)
  81. Dim newP1 = p2.GetRange().Paragraphs.Insert(InsertLocation.Before)
  82. CopyParagraph(newP1, p1, withFormatting)
  83. p1.Delete()
  84. p2.Delete()
  85. Return (newP1, newP2)
  86. End Function
  87.  
  88. '' Copies the contents (and optionally formatting) of two paragraphs into a third one.
  89. Public Shared Function JoinParagraphs(ByRef target As Paragraph, ByRef p1 As Paragraph, ByRef p2 As Paragraph, Optional ByVal withFormatting As Boolean = True) As Paragraph
  90. If p1.ParentBody IsNot p2.ParentBody Then
  91. Throw New Exception("Both paragraphs must belong the same parent body.")
  92. End If
  93.  
  94. CopyParagraph(target, p1, withFormatting)
  95. CopyParagraph(target, p2, withFormatting)
  96.  
  97. Return target
  98. End Function
  99.  
  100. '' Copy child objects from one content object to another.
  101. Private Shared Sub CopyChildren(ByRef target As ContentObject, ByRef source As ContentObject, ByVal withFormatting As Boolean)
  102. For Each child In source.Children
  103. Select Case child.GetType()
  104. Case GetType(Run)
  105. AddRun(target, child, withFormatting)
  106. Case GetType(SimpleField)
  107. AddField(target, child, withFormatting)
  108. Case GetType(Picture)
  109. AddPicture(target, child, withFormatting)
  110. Case GetType(Paragraph)
  111. AddParagraph(target, child, withFormatting)
  112. Case GetType(Text)
  113. AddText(target, child, withFormatting)
  114. Case Else
  115. Debug.Assert(False, "Unexpected: unknown content object type.")
  116. End Select
  117. Next
  118. End Sub
  119.  
  120. '' Joins two paragraphs.
  121. Private Shared Function JoinParagraphs(ByRef first As Paragraph, ByRef second As Paragraph, Optional ByVal withFormatting As Boolean = False) As Paragraph
  122. If first.ParentBody IsNot second.ParentBody Then
  123. Throw New Exception("Left and right paragraphs must belong the same parent body.")
  124. End If
  125.  
  126. Dim newParagraph = first.ParentBody.Paragraphs.Add()
  127. CopyParagraph(newParagraph, first, withFormatting)
  128. '' Note that second paragraph formatting overrides first paragraph formatting:
  129. CopyParagraph(newParagraph, second, withFormatting)
  130.  
  131. Return newParagraph
  132. End Function
  133.  
  134. '' Adds a copy of a paragraph to a body.
  135. Private Shared Sub AddParagraph(ByRef bod As Body, ByRef source As Paragraph, Optional ByVal withFormatting As Boolean = False)
  136. Dim newParagraph = bod.Paragraphs.Add()
  137. CopyParagraph(newParagraph, source, withFormatting)
  138. End Sub
  139.  
  140. '' Adds a copy of a paragraph to a content object.
  141. Private Shared Sub AddParagraph(ByRef target As ContentObject, ByRef source As Paragraph, Optional ByVal withFormatting As Boolean = False)
  142. Dim newParagraph = target.GetRange().Paragraphs.Add()
  143. CopyParagraph(newParagraph, source, withFormatting)
  144. End Sub
  145.  
  146. '' Adds a copy of a run to a content object.
  147. Private Shared Sub AddRun(ByRef target As ContentObject, ByRef source As Run, Optional ByVal withFormatting As Boolean = False)
  148. Dim newRun = target.GetRange().Runs.Add()
  149. CopyRun(newRun, source, withFormatting)
  150. End Sub
  151.  
  152. '' Copies a paragraph to another paragraph.
  153. Private Shared Sub CopyParagraph(ByRef target As Paragraph, ByRef source As Paragraph, Optional ByVal withFormatting As Boolean = False)
  154. CopyRevisionId(target.RevisionId, source.RevisionId)
  155. CopyChildren(target, source, withFormatting)
  156. If (withFormatting) Then
  157. CopyParagraphFormat(target, source)
  158. End If
  159. End Sub
  160.  
  161. '' Adds a copy of a text to a content object.
  162. Private Shared Sub AddText(ByRef target As ContentObject, ByRef source As Text, ByVal withFormatting As Boolean)
  163. Dim newText = target.GetRange().Texts.Add(source.Value)
  164. CopyText(newText, source, withFormatting)
  165.  
  166. End Sub
  167.  
  168. '' Copies a text to another text.
  169. Private Shared Sub CopyText(ByRef target As Text, ByRef source As Text, ByVal withFormatting As Boolean)
  170. target.PreserveSpace = source.PreserveSpace
  171. CopyChildren(target, source, withFormatting)
  172. End Sub
  173.  
  174. '' Adds a copy of a field to a content object.
  175. Private Shared Sub AddField(ByRef target As ContentObject, ByRef source As SimpleField, ByVal withFormatting As Boolean)
  176. Dim newField = target.GetRange().SimpleFields.Add(source.Code)
  177. CopySimpleField(newField, source, withFormatting)
  178. End Sub
  179.  
  180. '' Copies a simple field to another simple field.
  181. Private Shared Sub CopySimpleField(ByRef target As SimpleField, ByRef source As SimpleField, ByVal withFormatting As Boolean)
  182. target.Code = source.Code
  183. target.CustomData = source.CustomData
  184. target.Locked = source.Locked
  185. ''parse children
  186. CopyChildren(target, source, withFormatting)
  187. End Sub
  188.  
  189. '' Copies a run to another run.
  190. Private Shared Sub CopyRun(ByRef target As Run, ByRef source As Run, ByVal withFormatting As Boolean)
  191. CopyRevisionId(target.RevisionId, source.RevisionId)
  192. CopyChildren(target, source, withFormatting)
  193. If withFormatting Then
  194. target.Style = target.Style
  195. CopyFont(target.Font, source.Font)
  196. End If
  197. End Sub
  198.  
  199. '' Copies a revision ID.
  200. Private Shared Sub CopyRevisionId(ByRef target As RevisionId, ByRef source As RevisionId)
  201. target.AdditionId = source.AdditionId
  202. target.DeletionId = source.DeletionId
  203. target.PropertiesId = source.PropertiesId
  204. End Sub
  205.  
  206. '' Adds a copy of a picture to a content object.
  207. Private Shared Sub AddPicture(ByRef target As ContentObject, ByRef source As Picture, ByVal withFormatting As Boolean)
  208. Dim newPicture = target.GetRange().Pictures.Add()
  209. CopyPicture(newPicture, source, withFormatting)
  210. End Sub
  211.  
  212. '' Copies a picture to another picture.
  213. Private Shared Sub CopyPicture(ByRef target As Picture, ByRef source As Picture, ByVal withFormatting As Boolean)
  214. CopyImageData(target.ImageData, source.ImageData, withFormatting)
  215. target.Name = source.Name
  216. target.Title = source.Title
  217. CopyChildren(target, source, withFormatting)
  218.  
  219. If Not withFormatting Then
  220. Return
  221. End If
  222.  
  223. target.AlternativeText = source.AlternativeText
  224. target.Hidden = source.Hidden
  225.  
  226. CopyShapeRotation(target.Rotation, source.Rotation)
  227. CopyShapeSize(target.Size, source.Size)
  228. CopyWrapFormat(target.WrapFormat, source.WrapFormat)
  229. End Sub
  230.  
  231. '' Copies image data to another image data.
  232. Private Shared Sub CopyImageData(ByRef target As ImageData, ByRef source As ImageData, ByVal withFormatting As Boolean)
  233. target.Compression = source.Compression
  234. target.Source = source.Source
  235. target.SetImage(source.ToStream(), source.ContentType)
  236. If withFormatting Then
  237. CopyEdgeExtent(target.Crop, source.Crop)
  238. End If
  239. End Sub
  240.  
  241. '' Copies paragraph formatting to another paragraph.
  242. Private Shared Sub CopyParagraphFormat(ByRef target As Paragraph, ByRef source As Paragraph)
  243. target.Style = source.Style
  244. target.Mark.Style = source.Mark.Style
  245.  
  246. CopyParagraphFormatting(target.Format, source.Format)
  247. ''
  248. target.ListFormat.Template = source.ListFormat.Template
  249. target.ListFormat.LevelNumber = source.ListFormat.LevelNumber
  250. End Sub
  251.  
  252. '' Copies a font to another font.
  253. Private Shared Sub CopyFont(ByRef target As GcFont, ByRef source As GcFont)
  254. target.AllCaps = source.AllCaps
  255. target.AlwaysHidden = source.AlwaysHidden
  256. target.Animation = source.Animation
  257. target.Bidi = source.Bidi
  258. target.Bold = source.Bold
  259. target.BoldBi = source.BoldBi
  260. CopyBorder(target.Border, source.Border)
  261. CopyWordColor(target.Color, source.Color)
  262. target.ContextualAlternates = source.ContextualAlternates
  263. target.DisableCharacterSpaceGrid = source.DisableCharacterSpaceGrid
  264. target.DoubleStrikeThrough = source.DoubleStrikeThrough
  265. CopyEastAsianLayout(target.EastAsianLayout, source.EastAsianLayout)
  266. target.Emboss = source.Emboss
  267. target.EmphasisMark = source.EmphasisMark
  268. target.Engrave = source.Engrave
  269. target.FitTextId = source.FitTextId
  270. target.FitTextWidth = source.FitTextWidth
  271. target.Hidden = source.Hidden
  272. target.HighlightColor = source.HighlightColor
  273. target.HintType = source.HintType
  274. target.Italic = source.Italic
  275. target.ItalicBi = source.ItalicBi
  276. target.Kerning = source.Kerning
  277. target.Ligatures = source.Ligatures
  278. target.LocaleName = source.LocaleName
  279. target.LocaleNameBi = source.LocaleNameBi
  280. ''
  281. target.LocaleNameFarEast = source.LocaleNameFarEast
  282. target.Name = source.Name
  283. target.NameAscii = source.NameAscii
  284. target.NameBi = source.NameBi
  285. target.NameFarEast = source.NameFarEast
  286. target.NameOther = source.NameOther
  287. target.NoProofing = source.NoProofing
  288. target.NumberForm = source.NumberForm
  289. target.NumberSpacing = source.NumberSpacing
  290. target.Outline = source.Outline
  291. target.Position = source.Position
  292. target.RightToLeft = source.RightToLeft
  293. target.Scaling = source.Scaling
  294.  
  295. CopyShading(target.Shading, source.Shading)
  296. target.Shadow = source.Shadow
  297. target.Size = source.Size
  298. target.SizeBi = source.SizeBi
  299. target.SmallCaps = source.SmallCaps
  300. target.Spacing = source.Spacing
  301. target.StrikeThrough = source.StrikeThrough
  302. target.StylisticSets = source.StylisticSets
  303.  
  304. target.ThemeAscii = source.ThemeAscii
  305. target.ThemeBi = source.ThemeBi
  306. target.ThemeFarEast = source.ThemeFarEast
  307. target.ThemeOther = source.ThemeOther
  308. target.Underline = source.Underline
  309. CopyWordColor(target.UnderlineColor, source.UnderlineColor)
  310. target.VerticalPosition = source.VerticalPosition
  311. target.WebHidden = source.WebHidden
  312. End Sub
  313.  
  314. '' Copies East Asian layout.
  315. Private Shared Sub CopyEastAsianLayout(ByRef target As EastAsianLayout, ByRef source As EastAsianLayout)
  316. target.FitVerticalInLine = source.FitVerticalInLine
  317. target.HorizontalInVertical = source.HorizontalInVertical
  318. target.TwoLinesInOne = source.TwoLinesInOne
  319. target.TwoLinesInOneBrackets = source.TwoLinesInOneBrackets
  320. End Sub
  321.  
  322. '' Copies paragraph formatting.
  323. Private Shared Sub CopyParagraphFormatting(ByRef target As ParagraphFormat, ByRef source As ParagraphFormat)
  324. target.Alignment = source.Alignment
  325. target.BaseLineAlignment = source.BaseLineAlignment
  326. target.Bidi = source.Bidi
  327.  
  328. target.DisableLineHeightGrid = source.DisableLineHeightGrid
  329. target.FarEastLineBreakControl = source.FarEastLineBreakControl
  330. target.HalfWidthPunctuationOnTopOfLine = source.HalfWidthPunctuationOnTopOfLine
  331. target.HangingPunctuation = source.HangingPunctuation
  332. target.Hyphenation = source.Hyphenation
  333.  
  334. target.KeepTogether = source.KeepTogether
  335. target.KeepWithNext = source.KeepWithNext
  336. target.NoLineNumber = source.NoLineNumber
  337. target.OutlineLevel = source.OutlineLevel
  338. target.PageBreakBefore = source.PageBreakBefore
  339. target.TextboxTightWrap = source.TextboxTightWrap
  340. target.TextFlowDirection = source.TextFlowDirection
  341. target.WidowControl = source.WidowControl
  342. target.WordWrap = source.WordWrap
  343.  
  344. CopyShading(target.Shading, source.Shading)
  345. CopySpacing(target.Spacing, source.Spacing)
  346. CopyIndentation(target.Indentation, source.Indentation)
  347. ''copy TabStops
  348. For Each tabStop In source.TabStops
  349. If tabStop.Leader <> TabStopLeader.None Then
  350. target.TabStops.Add(tabStop.Position, tabStop.Alignment)
  351. Else
  352. target.TabStops.Add(tabStop.Position, tabStop.Alignment, tabStop.Leader)
  353. End If
  354. Next
  355. ''copy borders
  356. CopyBorder(target.Borders.Inside, source.Borders.Inside)
  357. CopyBorder(target.Borders.Left, source.Borders.Left)
  358. CopyBorder(target.Borders.Top, source.Borders.Top)
  359. CopyBorder(target.Borders.Right, source.Borders.Right)
  360. CopyBorder(target.Borders.Bottom, source.Borders.Bottom)
  361. End Sub
  362.  
  363. Private Shared Sub CopyIndentation(ByRef target As Indentation, ByRef source As Indentation)
  364. target.AutoAdjustRightIndent = source.AutoAdjustRightIndent
  365. target.CharacterUnitFirstLineIndent = source.CharacterUnitFirstLineIndent
  366. target.CharacterUnitLeftIndent = source.CharacterUnitLeftIndent
  367. target.CharacterUnitRightIndent = source.CharacterUnitRightIndent
  368. target.FirstLineIndent = source.FirstLineIndent
  369. target.LeftIndent = source.LeftIndent
  370. target.MirrorIndents = source.MirrorIndents
  371. target.RightIndent = source.RightIndent
  372. End Sub
  373.  
  374. Private Shared Sub CopySpacing(ByRef target As Spacing, ByRef source As Spacing)
  375. target.AddSpaceBetweenFarEastAndAlpha = source.AddSpaceBetweenFarEastAndAlpha
  376. target.AddSpaceBetweenFarEastAndDigit = source.AddSpaceBetweenFarEastAndDigit
  377. target.LineSpacing = source.LineSpacing
  378. target.LineSpacingRule = source.LineSpacingRule
  379. target.LineUnitAfter = source.LineUnitAfter
  380. target.LineUnitBefore = source.LineUnitBefore
  381. target.NoSpaceBetweenParagraphsOfSameStyle = source.NoSpaceBetweenParagraphsOfSameStyle
  382. target.SpaceAfter = source.SpaceAfter
  383. target.SpaceAfterAuto = source.SpaceAfterAuto
  384. target.SpaceBefore = source.SpaceBefore
  385. target.SpaceBeforeAuto = source.SpaceBeforeAuto
  386. End Sub
  387.  
  388. Private Shared Sub CopyShading(ByRef target As Shading, ByRef source As Shading)
  389.  
  390. CopyWordColor(target.BackgroundPatternColor, source.BackgroundPatternColor)
  391. CopyWordColor(target.ForegroundPatternColor, source.ForegroundPatternColor)
  392. target.Texture = source.Texture
  393. End Sub
  394.  
  395. Private Shared Sub CopyBorder(ByRef target As Border, ByRef source As Border)
  396. CopyWordColor(target.Color, source.Color)
  397. target.FrameEffect = source.FrameEffect
  398. target.LineStyle = source.LineStyle
  399. target.LineWidth = source.LineWidth
  400. target.Shadow = source.Shadow
  401. target.Space = source.Space
  402. target.Visible = source.Visible
  403. End Sub
  404.  
  405. Private Shared Sub CopyWordColor(ByRef target As WordColor, ByRef source As WordColor)
  406. target.RGB = source.RGB
  407. '' Note: current DsWord OM does not provide means to find where a concrete color
  408. '' comes from, so copying theme colors will overwrite RGB even if the RGB value
  409. '' should be used. So for this sample, we just ignore theme colors:
  410. '' target.ThemeColor = source.ThemeColor
  411. '' target.ThemeShade = source.ThemeShade
  412. '' target.ThemeTint = source.ThemeTint
  413. End Sub
  414.  
  415. Private Shared Sub CopyWrapFormat(ByRef target As WrapFormat, ByRef source As WrapFormat)
  416. target.BehindText = source.BehindText
  417. target.DistanceBottom = source.DistanceBottom
  418. target.DistanceLeft = source.DistanceLeft
  419. target.DistanceRight = source.DistanceRight
  420. target.DistanceTop = source.DistanceTop
  421. target.Side = source.Side
  422. target.Type = source.Type
  423. ''clone list
  424. If source.WrapPolygon IsNot Nothing Then
  425. target.WrapPolygon = source.WrapPolygon.ToList()
  426. End If
  427. End Sub
  428.  
  429. Private Shared Sub CopyShapeRotation(ByRef target As ShapeRotation, ByRef source As ShapeRotation)
  430. target.Angle = source.Angle
  431. target.HorizontalFlip = source.HorizontalFlip
  432. target.VerticalFlip = source.VerticalFlip
  433. End Sub
  434.  
  435. Private Shared Sub CopyShapeSize(ByRef target As ShapeSize, ByRef source As ShapeSize)
  436. CopyEdgeExtent(target.EffectExtent, source.EffectExtent)
  437. CopyShapeWidth(target.Width, source.Width)
  438. CopyShapeHeight(target.Height, source.Height)
  439. End Sub
  440.  
  441. Private Shared Sub CopyShapeWidth(ByRef target As ShapeWidth, ByRef source As ShapeWidth)
  442. target.Relative = source.Relative
  443. target.RelativeTo = source.RelativeTo
  444. target.Value = source.Value
  445. End Sub
  446.  
  447. Private Shared Sub CopyShapeHeight(ByRef target As ShapeHeight, ByRef source As ShapeHeight)
  448. target.Relative = source.Relative
  449. target.RelativeTo = source.RelativeTo
  450. target.Value = source.Value
  451. End Sub
  452.  
  453. Private Shared Sub CopyEdgeExtent(ByRef target As EdgeExtent, ByRef source As EdgeExtent)
  454. target.AllEdges = source.AllEdges
  455. target.BottomEdge = source.BottomEdge
  456. target.LeftEdge = source.LeftEdge
  457. target.RightEdge = source.RightEdge
  458. target.TopEdge = source.TopEdge
  459. End Sub
  460. End Class
  461. End Class
  462.