| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 
 | Imports System
Imports System.IO
Imports System.Text
Imports System.Linq
Imports System.Xml
Imports System.Xml.Linq
Imports System.Collections.Generic
Imports System.Drawing.Graphics
Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports WP = DocumentFormat.OpenXml.Wordprocessing
Imports A = DocumentFormat.OpenXml.Drawing
Imports DW = DocumentFormat.OpenXml.Drawing.Wordprocessing
Imports PIC = DocumentFormat.OpenXml.Drawing.Pictures
 
Namespace SDEA
    Namespace Interop
        Public Class Word
            Implements IDisposable
 
#Region "Membres privés"
            Protected _wpd As WordprocessingDocument
            Protected _doc As MainDocumentPart
            Protected _modelePath As String
            Protected _finalDocPath As String
#End Region
 
#Region "Propriétés publiques"
            Public ReadOnly Property ModeleFullName() As String
                Get
                    Return _modelePath
                End Get
            End Property
 
            Public ReadOnly Property WordProcessingDocument() As WordprocessingDocument
                Get
                    Return _wpd
                End Get
            End Property
 
            Public ReadOnly Property MainDocumentPart() As MainDocumentPart
                Get
                    Return _doc
                End Get
            End Property
#End Region
 
#Region "Constructeurs/Destructeurs"
            Sub New(ByVal wordModel As String, ByVal finalDocFullPath As String)
                Try
                    FileCopy(wordModel, finalDocFullPath)
 
                    _modelePath = wordModel
                    _finalDocPath = finalDocFullPath
                    _wpd = WordProcessingDocument.Open(_finalDocPath, True)
                    _doc = _wpd.MainDocumentPart
                Catch ex As Exception
                    Throw ex
                End Try
            End Sub
#End Region
 
#Region "Procédures et fonctions publiques"
            Public Sub Save()
                _doc.Document.Save()
            End Sub
 
#Region "Insertion de texte"
            Public Sub InsertText(ByVal bookmark As String, ByVal text As String)
                Try
                    Dim body = _doc.Document.GetFirstChild(Of WP.Body)()
                    Dim paras = body.Descendants(Of WP.Paragraph)()
 
                    For Each para In paras
                        Dim bookMarkStarts = para.Elements(Of WP.BookmarkStart)()
                        Dim bookMarkEnds = para.Elements(Of WP.BookmarkEnd)()
 
                        For Each BookmarkStart In bookMarkStarts
                            If BookmarkStart.Name = bookmark Then
                                Dim id = BookmarkStart.Id.Value
                                Dim b = bookMarkEnds.First(Function(x) x.Id.Value = id)
                                Dim run = New WP.Run()
 
                                run.Append(New WP.Text(text))
                                para.InsertBefore(run, b)
                            End If
                        Next
                    Next
                Catch ex As Exception
                    Throw ex
                End Try
            End Sub
 
            Public Sub InsertText(ByVal dic As Dictionary(Of String, String))
                Try
                    Dim body = _doc.Document.GetFirstChild(Of WP.Body)()
                    Dim paras = body.Descendants(Of WP.Paragraph)()
 
                    For Each para In paras
                        Dim bookMarkStarts = para.Elements(Of WP.BookmarkStart)()
                        Dim bookMarkEnds = para.Elements(Of WP.BookmarkEnd)()
 
                        For Each BookmarkStart In bookMarkStarts
                            For Each elem In dic
                                If BookmarkStart.Name = elem.Key Then
                                    Dim id = BookmarkStart.Id.Value
                                    Dim b = bookMarkEnds.First(Function(x) x.Id.Value = id)
                                    Dim run = New WP.Run()
 
                                    run.Append(New WP.Text(elem.Value))
                                    para.InsertBefore(run, b)
                                End If
                            Next
                        Next
                    Next
                Catch ex As Exception
                    Throw ex
                End Try
            End Sub
 
            'Public Sub InsertText(ByVal tabIndex As Integer,
            '                      ByVal rowIndex As Integer,
            '                      ByVal cellIndex As Integer,
            '                      ByVal text As String)
 
            '    Try
            '        Dim body = _doc.Document.GetFirstChild(Of WP.Body)()
            '        Dim table = body.Elements(Of WP.Table)().ElementAt(tabIndex)
            '        Dim row = table.Elements(Of WP.TableRow)().ElementAt(rowIndex)
            '        Dim cell = row.Elements(Of WP.TableCell)().ElementAt(cellIndex)
            '        Dim p = cell.Elements(Of WP.Paragraph)().First()
            '        Dim r = p.Elements(Of WP.Run)().First()
            '        Dim t As New WP.Text()
 
            '        t.Text = text
            '        r.Append(t)
            '    Catch ex As Exception
            '        Throw ex
            '    End Try
            'End Sub
#End Region
 
#Region "Insertion d'image"
            Public Sub InsertImage(ByVal bookmark As String,
                                   ByVal filename As String,
                                   Optional ByVal imageScale As Integer = 100,
                                   Optional ByVal imageType As ImagePartType = ImagePartType.Jpeg)
                Try
                    Dim body = _doc.Document.GetFirstChild(Of WP.Body)()
                    Dim paras = body.Descendants(Of WP.Paragraph)()
 
                    For Each para In paras
                        Dim bookMarkStarts = para.Elements(Of WP.BookmarkStart)()
                        Dim bookMarkEnds = para.Elements(Of WP.BookmarkEnd)()
 
                        For Each BookmarkStart In bookMarkStarts
                            If BookmarkStart.Name = bookmark Then
                                Dim id = BookmarkStart.Id.Value
                                Dim b = bookMarkEnds.First(Function(x) x.Id.Value = id)
                                Dim run = New WP.Run()
                                Dim img As ImagePart = _doc.AddImagePart(imageType)
 
                                Using s As New FileStream(filename, FileMode.Open)
                                    img.FeedData(s)
                                End Using
 
                                run.Append(CreateImageReference(_doc.GetIdOfPart(img), imageScale))
                                para.InsertBefore(run, b)
                            End If
                        Next
                    Next
                Catch ex As Exception
                    Throw ex
                End Try
            End Sub
 
            Protected Function CreateImageReference(ByVal relationshipId As String, ByVal zoom As Integer) As WP.Drawing
                Dim element = New WP.Drawing( _
                                  New DW.Inline( _
                              New DW.Extent() With {.Cx = Convert.ToInt64(800 * zoom / 100) * 9525, .Cy = Convert.ToInt64(400 * zoom / 100) * 9525}, _
                              New DW.EffectExtent() With {.LeftEdge = 0L, .TopEdge = 0L, .RightEdge = 0L, .BottomEdge = 0L}, _
                              New DW.DocProperties() With {.Id = CType(1UI, UInt32Value), .Name = relationshipId}, _
                              New DW.NonVisualGraphicFrameDrawingProperties( _
                                  New A.GraphicFrameLocks() With {.NoChangeAspect = True} _
                                  ), _
                              New A.Graphic(New A.GraphicData( _
                                            New PIC.Picture( _
                                                New PIC.NonVisualPictureProperties( _
                                                    New PIC.NonVisualDrawingProperties() With {.Id = 0UI, .Name = relationshipId}, _
                                                    New PIC.NonVisualPictureDrawingProperties() _
                                                    ), _
                                                New PIC.BlipFill( _
                                                    New A.Blip( _
                                                        New A.BlipExtensionList( _
                                                            New A.BlipExtension() With {.Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"}) _
                                                        ) With {.Embed = relationshipId, .CompressionState = A.BlipCompressionValues.Print}, _
                                                    New A.Stretch( _
                                                        New A.FillRectangle() _
                                                        ) _
                                                    ), _
                                                New PIC.ShapeProperties( _
                                                    New A.Transform2D( _
                                                        New A.Offset() With {.X = 0L, .Y = 0L}, _
                                                        New A.Extents() With {.Cx = Convert.ToInt64(800 * zoom / 100) * 9525, .Cy = Convert.ToInt64(400 * zoom / 100) * 9525}), _
                                                    New A.PresetGeometry( _
                                                        New A.AdjustValueList() _
                                                        ) With {.Preset = A.ShapeTypeValues.Rectangle} _
                                                    ) _
                                                ) _
                                            ) With {.Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"} _
                                        ) _
                                    ) With {.DistanceFromTop = 0UI, _
                                            .DistanceFromBottom = 0UI, _
                                            .DistanceFromLeft = 0UI, _
                                            .DistanceFromRight = 0UI} _
                                )
 
                Return element
            End Function
#End Region
 
#Region "Insertion de tableau"
            'Public Sub InsererTableau(ByVal bookmark As String,
            '                          Optional ByVal nbRows As Integer = 1,
            '                          Optional ByVal nbCols As Integer = 1,
            '                          Optional ByVal widthPercent As Integer = 100,
            '                          Optional ByVal style As String = "")
 
            '    Dim body = _doc.Document.GetFirstChild(Of WP.Body)()
            '    Dim paras = body.Descendants(Of WP.Paragraph)()
 
            '    For Each para In paras
            '        Dim bookMarkStarts = para.Elements(Of WP.BookmarkStart)()
            '        Dim bookMarkEnds = para.Elements(Of WP.BookmarkEnd)()
 
            '        For Each BookmarkStart In bookMarkStarts
            '            If BookmarkStart.Name = bookmark Then
            '                Dim id = BookmarkStart.Id.Value
            '                Dim b = bookMarkEnds.First(Function(x) x.Id.Value = id)
            '                Dim run = New WP.Run()
 
            '                run.Append(CreateTable(style, widthPercent, nbRows, nbCols))
            '                para.InsertBefore(run, b)
            '            End If
            '        Next
            '    Next
            'End Sub
 
            Public Sub InsererTableau(ByVal bookmark As String,
                                      ByRef tableSource As System.Web.UI.WebControls.Table,
                                      Optional ByVal widthPercent As Integer = 100,
                                      Optional ByVal style As String = "")
 
                Dim body = _doc.Document.GetFirstChild(Of WP.Body)()
                Dim paras = body.Descendants(Of WP.Paragraph)()
 
                For Each para In paras
                    Dim bookMarkStarts = para.Elements(Of WP.BookmarkStart)()
                    Dim bookMarkEnds = para.Elements(Of WP.BookmarkEnd)()
 
                    For Each BookmarkStart In bookMarkStarts
                        If BookmarkStart.Name = bookmark Then
                            Dim id = BookmarkStart.Id.Value
                            Dim b = bookMarkEnds.First(Function(x) x.Id.Value = id)
                            Dim run = New WP.Run()
 
                            run.Append(CreateTable(tableSource, style, widthPercent))
                            para.InsertBefore(run, b)
                        End If
                    Next
                Next
            End Sub
 
            Protected Function CreateTable(ByVal wordTheme As String, ByVal widthPercent As Integer, ByVal nbRows As Integer, ByVal nbCols As Integer) As WP.Table
                Dim t As New WP.Table()
 
                '* Ajout des propriétés générales du tableau
                t.Append(CreateTableProperties(wordTheme, widthPercent))
 
                '* Création du tableau avec le nombre de lignes et de colonnes demandé
                For i As Integer = 0 To nbRows - 1
                    Dim tr As New WP.TableRow()
 
                    For j As Integer = 0 To nbCols - 1
                        Dim td As New WP.TableCell()
                        Dim para As New WP.Paragraph()
 
                        td.Append(para)
                        tr.Append(td)
                    Next
 
                    t.Append(tr)
                Next
 
                Return t
            End Function
 
            Protected Function CreateTable(ByVal tb As System.Web.UI.WebControls.Table, ByVal wordTheme As String, ByVal widthPercent As Integer) As WP.Table
                Dim t As New WP.Table()
 
                '* Ajout des propriétés générales du tableau
                t.Append(CreateTableProperties(wordTheme, widthPercent))
 
                '* Création du tableau en parcourant le tableau VB
                For i As Integer = 0 To tb.Rows.Count - 1
                    Dim tr As New WP.TableRow()
 
                    For j As Integer = 0 To tb.Rows(i).Cells.Count - 1
                        Dim td As New WP.TableCell()
                        Dim para As New WP.Paragraph()
                        Dim txt As New WP.Text()
                        Dim run As New WP.Run()
 
                        txt.Text = tb.Rows(i).Cells(j).Text
                        run.Append(txt)
                        para.Append(run)
                        td.Append(para)
                        tr.Append(td)
                    Next
 
                    t.Append(tr)
                Next
 
                Return t
            End Function
 
            Protected Function CreateTableProperties(ByVal wordTheme As String, ByVal widthPercent As Integer) As WP.TableProperties
                Dim tableProp As New WP.TableProperties()
                Dim tableStyle As New WP.TableStyle() With {.Val = wordTheme}
                Dim tableWidth As New WP.TableWidth() With {.Width = widthPercent.ToString & "%", .Type = WP.TableWidthUnitValues.Pct}
                Dim tableLook As New WP.TableLook() With {.FirstRow = True, _
                                                          .LastRow = False, _
                                                          .FirstColumn = True, _
                                                          .LastColumn = False, _
                                                          .NoHorizontalBand = False, _
                                                          .NoVerticalBand = True}
 
                With tableProp
                    .Append(tableStyle)
                    .Append(tableWidth)
                    .Append(tableLook)
                End With
 
                Return tableProp
            End Function
#End Region
#End Region
 
#Region "IDisposable Support"
            Private disposedValue As Boolean
 
            Protected Overridable Sub Dispose(disposing As Boolean)
                If Not Me.disposedValue Then
                    If disposing Then
                        ' TODO: supprimez l'état managé (objets managés).
                        _wpd.Close()
                        _wpd.Dispose()
                    End If
 
                    ' TODO: libérez les ressources non managées (objets non managés) et substituez la méthode Finalize() ci-dessous.
                    ' TODO: définissez les champs volumineux à null.
                End If
                Me.disposedValue = True
            End Sub
 
            ' TODO: substituez Finalize() uniquement si Dispose(ByVal disposing As Boolean) ci-dessus comporte du code permettant de libérer des ressources non managées.
            Protected Overrides Sub Finalize()
                ' Ne modifiez pas ce code. Ajoutez du code de nettoyage dans Dispose(ByVal disposing As Boolean) ci-dessus.
                Dispose(False)
                MyBase.Finalize()
            End Sub
 
            Public Sub Dispose() Implements IDisposable.Dispose
                Dispose(True)
                GC.SuppressFinalize(Me)
            End Sub
#End Region
        End Class
    End Namespace
End Namespace |