none
Open XML SDK. Вставка рисунка в колонтитул word документа. RRS feed

  • Вопрос

  • 'Загрузка рисунка и создание элемента Drawing

    Dim imagePart As ImagePart = mainPart.AddImagePart(imagePartType.Jpeg)

    Using stream As New FileStream(fileName, FileMode.Open) imagePart.FeedData(stream) End Using Dim relationshipId As String = mainPart.GetIdOfPart(imagePart) Dim img = New System.Windows.Media.Imaging.BitmapImage(New Uri(fileName, UriKind.RelativeOrAbsolute)) Dim widthPx = img.PixelWidth Dim heightPx = img.PixelHeight Dim horzRezDpi = img.DpiX Dim vertRezDpi = img.DpiY Const emusPerInch As Integer = 914400 'дьюйм Const emusPerCm As Integer = 360000 'см. ' Dim widthEmus = CLng(widthPx / horzRezDpi * emusPerInch) Dim heightEmus = CLng(heightPx / vertRezDpi * emusPerInch) Dim maxWidthEmus = CLng(System.Math.Truncate(WidthCm * emusPerCm)) If widthEmus > maxWidthEmus Then Dim ratio = (heightEmus * 1D) / widthEmus widthEmus = maxWidthEmus heightEmus = CLng(widthEmus * ratio) End If ' Define the reference of the image. Dim element = New Drawing( _ New DW.Inline( _ New DW.Extent() With {.Cx = widthEmus, .Cy = heightEmus}, _ New DW.EffectExtent() With {.LeftEdge = 0L, .TopEdge = 0L, .RightEdge = 0L, .BottomEdge = 0L}, _ New DW.DocProperties() With {.Id = CType(1UI, UInt32Value), .Name = "Picture1"}, _ 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 = "Koala.jpg"}, _ 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 = widthEmus, .Cy = heightEmus}), _ 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} _ )

    'Вставка элемента в заголовок Dim header As New Header() header.Append(New Paragraph( New ParagraphProperties(New Justification() With {.Val = JustificationValues.Right}), New Run(element))) ' Create a new header part and grab its id for the header reference. Dim headerPart As HeaderPart = mainPart.AddNewPart(Of HeaderPart)() Dim rId As String = mainPart.GetIdOfPart(headerPart) 'create our Header reference Dim headerRef As New HeaderReference() headerRef.Id = rId sectionProps.RemoveAllChildren(Of HeaderReference)() sectionProps.Append(headerRef) 'Now populate the header contents headerPart.Header = MakeHeader(mainPart) headerPart.Header.Save()


    Не работает. Word не может открыть, пишет ошибка в документе.
    • Изменено ildar323 19 апреля 2012 г. 15:59
    19 апреля 2012 г. 9:27

Ответы

  • Здравствуйте.

    Вот рабочий пример добавление заголовка в существующий документ:

            Dim Document As String = "D:\test.docx"
            Dim fileName As String = "D:\test.jpg"
            Dim WidthCm As Integer = 10
    
            Using wordprocessingDocument As WordprocessingDocument = wordprocessingDocument.Open(Document, True)
                Dim mainPart As MainDocumentPart = wordprocessingDocument.MainDocumentPart
                Dim headerPart As HeaderPart = mainPart.AddNewPart(Of HeaderPart)()
                Dim rId As String = mainPart.GetIdOfPart(headerPart)
    
                Dim headerRef As New HeaderReference()
                headerRef.Id = rId
    
                Dim sectPrs = mainPart.Document.Body.Elements(Of SectionProperties)()
                For Each sectPr In sectPrs
                    ' Delete existing references to headers.
                    sectPr.RemoveAllChildren(Of HeaderReference)()
    
                    ' Add new Header referces
                    sectPr.Append(headerRef)
                Next
    
                'Загрузка рисунка и создание элемента Drawing          
                Dim imagePart As ImagePart = headerPart.AddImagePart(ImagePartType.Jpeg)
                Using stream As New FileStream(fileName, FileMode.Open)
                    imagePart.FeedData(stream)
                End Using
                Dim relationshipId As String = headerPart.GetIdOfPart(imagePart)
    
                'Определение изображения
                Dim img = New System.Windows.Media.Imaging.BitmapImage(New Uri(fileName, UriKind.RelativeOrAbsolute))
                Dim widthPx = img.PixelWidth
                Dim heightPx = img.PixelHeight
                Dim horzRezDpi = img.DpiX
                Dim vertRezDpi = img.DpiY
                Const emusPerInch As Integer = 914400       'дьюйм
                Const emusPerCm As Integer = 360000         'см.
                '
                Dim widthEmus = CLng(widthPx / horzRezDpi * emusPerInch)
                Dim heightEmus = CLng(heightPx / vertRezDpi * emusPerInch)
                Dim maxWidthEmus = CLng(System.Math.Truncate(WidthCm * emusPerCm))
                If widthEmus > maxWidthEmus Then
                    Dim ratio = (heightEmus * 1D) / widthEmus
                    widthEmus = maxWidthEmus
                    heightEmus = CLng(widthEmus * ratio)
                End If
    
                ' Define the reference of the image.
                Dim element = New Drawing( _
                                      New DW.Inline( _
                                              New DW.Extent() With {.Cx = widthEmus, .Cy = heightEmus}, _
                                              New DW.EffectExtent() With {.LeftEdge = 0L, .TopEdge = 0L, .RightEdge = 0L, .BottomEdge = 0L}, _
                                              New DW.DocProperties() With {.Id = CType(1UI, UInt32Value), .Name = "Picture1"}, _
                                              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 = "Koala.jpg"}, _
                                                                    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 = widthEmus, .Cy = heightEmus}), _
                                                                    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} _
                                    )
    
    
                'добавляем ссылку на заголовок
                'mainPart.Document.Append(sectPrs)
                mainPart.Document.Save()
    
                headerPart.Header = New Header(New Paragraph(
                                            New ParagraphProperties(New Justification() With {.Val = JustificationValues.Right}),
                                            New Run(element)))
                headerPart.Header.Save()
            End Using


    Для связи [mail]

    • Помечено в качестве ответа ildar323 24 апреля 2012 г. 4:22
    20 апреля 2012 г. 14:14
    Модератор

Все ответы

  • Здравствуйте.

    Вот рабочий пример добавление заголовка в существующий документ:

            Dim Document As String = "D:\test.docx"
            Dim fileName As String = "D:\test.jpg"
            Dim WidthCm As Integer = 10
    
            Using wordprocessingDocument As WordprocessingDocument = wordprocessingDocument.Open(Document, True)
                Dim mainPart As MainDocumentPart = wordprocessingDocument.MainDocumentPart
                Dim headerPart As HeaderPart = mainPart.AddNewPart(Of HeaderPart)()
                Dim rId As String = mainPart.GetIdOfPart(headerPart)
    
                Dim headerRef As New HeaderReference()
                headerRef.Id = rId
    
                Dim sectPrs = mainPart.Document.Body.Elements(Of SectionProperties)()
                For Each sectPr In sectPrs
                    ' Delete existing references to headers.
                    sectPr.RemoveAllChildren(Of HeaderReference)()
    
                    ' Add new Header referces
                    sectPr.Append(headerRef)
                Next
    
                'Загрузка рисунка и создание элемента Drawing          
                Dim imagePart As ImagePart = headerPart.AddImagePart(ImagePartType.Jpeg)
                Using stream As New FileStream(fileName, FileMode.Open)
                    imagePart.FeedData(stream)
                End Using
                Dim relationshipId As String = headerPart.GetIdOfPart(imagePart)
    
                'Определение изображения
                Dim img = New System.Windows.Media.Imaging.BitmapImage(New Uri(fileName, UriKind.RelativeOrAbsolute))
                Dim widthPx = img.PixelWidth
                Dim heightPx = img.PixelHeight
                Dim horzRezDpi = img.DpiX
                Dim vertRezDpi = img.DpiY
                Const emusPerInch As Integer = 914400       'дьюйм
                Const emusPerCm As Integer = 360000         'см.
                '
                Dim widthEmus = CLng(widthPx / horzRezDpi * emusPerInch)
                Dim heightEmus = CLng(heightPx / vertRezDpi * emusPerInch)
                Dim maxWidthEmus = CLng(System.Math.Truncate(WidthCm * emusPerCm))
                If widthEmus > maxWidthEmus Then
                    Dim ratio = (heightEmus * 1D) / widthEmus
                    widthEmus = maxWidthEmus
                    heightEmus = CLng(widthEmus * ratio)
                End If
    
                ' Define the reference of the image.
                Dim element = New Drawing( _
                                      New DW.Inline( _
                                              New DW.Extent() With {.Cx = widthEmus, .Cy = heightEmus}, _
                                              New DW.EffectExtent() With {.LeftEdge = 0L, .TopEdge = 0L, .RightEdge = 0L, .BottomEdge = 0L}, _
                                              New DW.DocProperties() With {.Id = CType(1UI, UInt32Value), .Name = "Picture1"}, _
                                              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 = "Koala.jpg"}, _
                                                                    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 = widthEmus, .Cy = heightEmus}), _
                                                                    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} _
                                    )
    
    
                'добавляем ссылку на заголовок
                'mainPart.Document.Append(sectPrs)
                mainPart.Document.Save()
    
                headerPart.Header = New Header(New Paragraph(
                                            New ParagraphProperties(New Justification() With {.Val = JustificationValues.Right}),
                                            New Run(element)))
                headerPart.Header.Save()
            End Using


    Для связи [mail]

    • Помечено в качестве ответа ildar323 24 апреля 2012 г. 4:22
    20 апреля 2012 г. 14:14
    Модератор
  • Спасибо! Я значит вместо headerPart, картинку загружал в mainPart.
    24 апреля 2012 г. 4:23