none
Inserting watermark VB.net RRS feed

  • Question

  •    

    It doesn't seem to like "var"...

    Any ideas?

    Private Sub BuildUriPartDictionary()
            Dim queue As New System.Collections.Generic.Queue(Of OpenXmlPartContainer)()
            queue.Enqueue(document)
            While queue.Count > 0
                For Each part As var In queue.Dequeue().Parts
                    If Not UriPartDictionary.Keys.Contains(part.OpenXmlPart.Uri.ToString()) Then
                        UriPartDictionary.Add(part.OpenXmlPart.Uri.ToString(), part.OpenXmlPart)
                        queue.Enqueue(part.OpenXmlPart)
                    End If
                Next
            End While
        End Sub

    Tuesday, March 13, 2012 1:27 PM

Answers

  • Hi AcidTrash,

    To see whether this snippet can help you.

    Imports System.IO
    Imports System.Collections.Generic
    Imports System.ComponentModel
    Imports System.Data
    Imports System.Drawing
    Imports System.Linq
    Imports System.Text
    Imports System.Windows.Forms
    Imports DocumentFormat.OpenXml.Packaging
    Imports DocumentFormat.OpenXml.Wordprocessing
    Imports DocumentFormat.OpenXml
    Imports V = DocumentFormat.OpenXml.Vml
    Imports System.Diagnostics
    
    Namespace WindowsFormsApplication3
    	Public Partial Class Form1
    		Inherits Form
    		Public Sub New()
    			InitializeComponent()
    		End Sub
    
    		Private Sub button1_Click(sender As Object, e As EventArgs)
    			Using package As WordprocessingDocument = WordprocessingDocument.Open("C:\Users\*****\****.docx", True)
    				InsertCustomWatermark(package, "C:\Users\*******\****.jpg")
    			End Using
    		End Sub
    
    		Private Sub InsertCustomWatermark(package As WordprocessingDocument, p As String)
    			SetWaterMarkPicture(p)
    			Dim mainDocumentPart1 As MainDocumentPart = package.MainDocumentPart
    			If mainDocumentPart1 IsNot Nothing Then
    				mainDocumentPart1.DeleteParts(mainDocumentPart1.HeaderParts)
    				Dim headPart1 As HeaderPart = mainDocumentPart1.AddNewPart(Of HeaderPart)()
    				GenerateHeaderPart1Content(headPart1)
    				Dim rId As String = mainDocumentPart1.GetIdOfPart(headPart1)
    				Dim image As ImagePart = headPart1.AddNewPart(Of ImagePart)("image/jpeg", "rId999")
    				GenerateImagePart1Content(image)
    				Dim sectPrs As IEnumerable(Of SectionProperties) = mainDocumentPart1.Document.Body.Elements(Of SectionProperties)()
    				For Each sectPr As var In sectPrs
    					sectPr.RemoveAllChildren(Of HeaderReference)()
    					sectPr.PrependChild(Of HeaderReference)(New HeaderReference() With { _
    						Key .Id = rId _
    					})
    				Next
    			Else
    				MessageBox.Show("alert")
    			End If
    		End Sub
    		Private Sub GenerateHeaderPart1Content(headerPart1 As HeaderPart)
    			Dim header1 As New Header()
    			Dim paragraph2 As New Paragraph()
    			Dim run1 As New Run()
    			Dim picture1 As New Picture()
    			Dim shape1 As New V.Shape() With { _
    				Key .Id = "WordPictureWatermark75517470", _
    				Key .Style = "position:absolute;left:0;text-align:left;margin-left:0;margin-top:0;width:415.2pt;height:456.15pt;z-index:-251656192;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin", _
    				Key .OptionalString = "_x0000_s2051", _
    				Key .AllowInCell = False, _
    				Key .Type = "#_x0000_t75" _
    			}
    			Dim imageData1 As New V.ImageData() With { _
    				Key .Gain = "19661f", _
    				Key .BlackLevel = "22938f", _
    				Key .Title = "watermark", _
    				Key .RelationshipId = "rId999" _
    			}
    			shape1.Append(imageData1)
    			picture1.Append(shape1)
    			run1.Append(picture1)
    			paragraph2.Append(run1)
    			header1.Append(paragraph2)
    			headerPart1.Header = header1
    		End Sub
    		Private Sub GenerateImagePart1Content(imagePart1 As ImagePart)
    			Dim data As System.IO.Stream = GetBinaryDataStream(imagePart1Data)
    			imagePart1.FeedData(data)
    			data.Close()
    		End Sub
    		Private imagePart1Data As String = ""
    		Private Function GetBinaryDataStream(base64String As String) As System.IO.Stream
    			Return New System.IO.MemoryStream(System.Convert.FromBase64String(base64String))
    		End Function
    		Public Sub SetWaterMarkPicture(file As String)
    			Dim inFile As FileStream
    			Dim byteArray As Byte()
    			Try
    				inFile = New FileStream(file, FileMode.Open, FileAccess.Read)
    				byteArray = New Byte(inFile.Length - 1)   				Dim byteRead As Long = inFile.Read(byteArray, 0, CInt(inFile.Length))
    				inFile.Close()
    				imagePart1Data = Convert.ToBase64String(byteArray, 0, byteArray.Length)
    			Catch ex As Exception
    				Debug.Print(ex.Message)
    			End Try
    		End Sub
    	End Class
    End Namespace

    Have a good day,

    Tom


    Tom Xu [MSFT]
    MSDN Community Support | Feedback to us



    Wednesday, March 21, 2012 7:09 AM
    Moderator

All replies

  • Hi,
       I have inserted water mark to presentation files. Are you looking this in word/powerpoint?

    Wednesday, March 14, 2012 3:35 PM
  • Below is my code to upload a word document to SQL server, inserting watermark beforehand.  I have seen it once add the watermark, but it has stopped doing that and now it takes the original file, corrupts it, but uploads a functioning copy of the document.  I am seriously losing the plot with this.  Please help!!!

    I know that you can't use marcos in a word object to insert watermark.  I have tried it and it does work but you would need office.interop components whihc microsoft do not recommend for very good reasons...

    http://support.microsoft.com/kb/257757

    I have to use Open XML

    What I dont understand here is why it is processing the source document but uploading a an unprocessed document.  And I would also like to know why my open XML method is corrupting the file rather than inserting a watermark.

    Option Strict Off
    Imports System.Data.SqlClient
    Imports FreeTextBoxControls
    Imports System.IO
    Imports System.Xml
    Imports Microsoft.VisualBasic
    Imports DocumentFormat.OpenXml.Wordprocessing
    Imports DocumentFormat.OpenXml
    Imports V = DocumentFormat.OpenXml.Vml
    Imports Ovml = DocumentFormat.OpenXml.Vml.Office
    Imports Wvml = DocumentFormat.OpenXml.Vml.Wordprocessing
    Imports DocumentFormat.OpenXml.Packaging
    Imports Ap = DocumentFormat.OpenXml.ExtendedProperties
    Imports Vt = DocumentFormat.OpenXml.VariantTypes
    Imports System.Web.Mvc
    Imports System.Collections.Generic
    Imports System.Text
    Imports DocumentFormat.OpenXml.Vml
    Imports DocumentFormat.OpenXml.Vml.Office
    Imports DocumentFormat.OpenXml.Vml.Wordprocessing
    Imports HorizontalAnchorValues = DocumentFormat.OpenXml.Vml.Wordprocessing.HorizontalAnchorValues
    Imports Lock = DocumentFormat.OpenXml.Vml.Office.Lock
    Imports VerticalAnchorValues = DocumentFormat.OpenXml.Vml.Wordprocessing.VerticalAnchorValues
    
    Partial Class blogupdate
        Inherits System.Web.UI.Page
        Private UriPartDictionary As System.Collections.Generic.IDictionary(Of System.String, OpenXmlPart) = New System.Collections.Generic.Dictionary(Of System.String, OpenXmlPart)()
        Private UriNewDataPartDictionary As System.Collections.Generic.IDictionary(Of System.String, DataPart) = New System.Collections.Generic.Dictionary(Of System.String, DataPart)()
        Private document As WordprocessingDocument
        
    
        Private Sub ChangePackage(filepath As String)
    
            Dim sourceBytes As Byte() = File.ReadAllBytes(filepath)
    
            Dim inMemoryStream As New MemoryStream()
            inMemoryStream.Write(sourceBytes, 0, CInt(sourceBytes.Length))
    
            Dim document = WordprocessingDocument.Open(inMemoryStream, True)
    
            Dim queue As New System.Collections.Generic.Queue(Of OpenXmlPartContainer)()
            queue.Enqueue(document)
    
            Dim part
            While queue.Count > 0
                For Each part In queue.Dequeue().Parts
                    If Not UriPartDictionary.Keys.Contains(part.OpenXmlPart.Uri.ToString()) Then
                        UriPartDictionary.Add(part.OpenXmlPart.Uri.ToString(), part.OpenXmlPart)
                        queue.Enqueue(part.OpenXmlPart)
                    End If
                Next
            End While
    
            document.MainDocumentPart.ChangeIdOfPart(UriPartDictionary("/word/theme/theme1.xml"), "generatedTmpID1")
            document.MainDocumentPart.ChangeIdOfPart(UriPartDictionary("/word/fontTable.xml"), "generatedTmpID2")
            document.MainDocumentPart.ChangeIdOfPart(UriPartDictionary("/word/theme/theme1.xml"), "rId8")
            document.MainDocumentPart.ChangeIdOfPart(UriPartDictionary("/word/fontTable.xml"), "rId7")
    
            Dim headerPart1 As HeaderPart = document.MainDocumentPart.AddNewPart(Of HeaderPart)("headers")
            GenerateHeaderPart1Content(headerPart1)
            ChangeMainDocumentPart1(document.MainDocumentPart)
    
            document.MainDocumentPart.Document.Save()
            document.Close()
    
            Using fileStream As New FileStream(filepath, System.IO.FileMode.Create)
                inMemoryStream.WriteTo(fileStream)
            End Using
    
            Using Conn As New SqlConnection(ConfigurationManager.ConnectionStrings("cerberusConnectionString").ConnectionString)
    
                Dim strDocids As String
                Dim SQL As String = "INSERT INTO [tbl_wikidocs] ([DocumentTitle],[document],[docmimetype],[filesize]) VALUES (@DocumentTitle, @document, @docmimetype,@filesize)"
                Dim SQL2 As String = "INSERT INTO [tbl_WIKIblog] ([Title],[post]) VALUES (@DocumentTitle)"
                Dim myCommand As New SqlCommand(SQL, Conn)
    
                Dim docmimetypes As String = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    
                myCommand.Parameters.AddWithValue("@DocumentTitle", doctitle.Text.Trim())
                myCommand.Parameters.AddWithValue("@Docmimetype", docmimetypes)
                Dim imageBytes(UploadedFile.PostedFile.InputStream.Length) As Byte
                UploadedFile.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length)
                myCommand.Parameters.AddWithValue("@document", imageBytes)
                myCommand.Parameters.AddWithValue("@filesize", imageBytes.Length)
    
                Conn.Open()
                myCommand.ExecuteNonQuery()
                Conn.Close()
                SQL = "select max(docids) from [tbl_wikidocs]"
                Dim myCommand2 As New SqlCommand(SQL, Conn)
                Conn.Open()
                strDocids = myCommand2.ExecuteScalar
                Conn.Close()
    
                inMemoryStream.Close()
                inMemoryStream.Dispose()
                inMemoryStream = Nothing
    
                Dim nurl As String = "docview.aspx?docids=" + strDocids
                HyperLink1.NavigateUrl = (nurl)
                HyperLink1.Text = ("Your document can be found here..." + nurl)
    
                Dim FreeTextBox1 As FreeTextBox = CType(DetailsView1.FindControl("FreeTextBox1"), FreeTextBox)
    
                FreeTextBox1.Text = FreeTextBox1.Text + "<BR><P>Your document can be found <a href='" + nurl + "'>here</a>."
    
            End Using
    
        End Sub
    
        Private Sub GenerateHeaderPart1Content(headerPart1 As HeaderPart)
            Dim header1 As New Header()
            header1.AddNamespaceDeclaration("ve", "http://schemas.openxmlformats.org/markup-compatibility/2006")
            header1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office")
            header1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships")
            header1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math")
            header1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml")
            header1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing")
            header1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word")
            header1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")
            header1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml")
    
            Dim paragraph1 As New Paragraph() With { _
             .RsidParagraphAddition = "00D178F6", _
             .RsidRunAdditionDefault = "001028BC" _
            }
    
            Dim paragraphProperties1 As New ParagraphProperties()
            Dim paragraphStyleId1 As New ParagraphStyleId() With { _
             .Val = "Header" _
            }
    
            paragraphProperties1.Append(paragraphStyleId1)
    
            Dim run1 As New Run()
    
            Dim runProperties1 As New RunProperties()
            Dim noProof1 As New NoProof()
    
            runProperties1.Append(noProof1)
    
            Dim picture1 As New Picture()
    
            Dim shapetype1 As New V.Shapetype() With { _
             .Id = "_x0000_t136", _
             .CoordinateSize = "21600,21600", _
             .OptionalNumber = 136, _
             .Adjustment = "10800", _
             .EdgePath = "m@7,l@8,m@5,21600l@6,21600e" _
            }
    
            Dim formulas1 As New V.Formulas()
            Dim formula1 As New V.Formula() With { _
             .Equation = "sum #0 0 10800" _
            }
            Dim formula2 As New V.Formula() With { _
             .Equation = "prod #0 2 1" _
            }
            Dim formula3 As New V.Formula() With { _
             .Equation = "sum 21600 0 @1" _
            }
            Dim formula4 As New V.Formula() With { _
             .Equation = "sum 0 0 @2" _
            }
            Dim formula5 As New V.Formula() With { _
             .Equation = "sum 21600 0 @3" _
            }
            Dim formula6 As New V.Formula() With { _
             .Equation = "if @0 @3 0" _
            }
            Dim formula7 As New V.Formula() With { _
             .Equation = "if @0 21600 @1" _
            }
            Dim formula8 As New V.Formula() With { _
             .Equation = "if @0 0 @2" _
            }
            Dim formula9 As New V.Formula() With { _
             .Equation = "if @0 @4 21600" _
            }
            Dim formula10 As New V.Formula() With { _
             .Equation = "mid @5 @6" _
            }
            Dim formula11 As New V.Formula() With { _
             .Equation = "mid @8 @5" _
            }
            Dim formula12 As New V.Formula() With { _
             .Equation = "mid @7 @8" _
            }
            Dim formula13 As New V.Formula() With { _
             .Equation = "mid @6 @7" _
            }
            Dim formula14 As New V.Formula() With { _
             .Equation = "sum @6 0 @5" _
            }
    
            formulas1.Append(formula1)
            formulas1.Append(formula2)
            formulas1.Append(formula3)
            formulas1.Append(formula4)
            formulas1.Append(formula5)
            formulas1.Append(formula6)
            formulas1.Append(formula7)
            formulas1.Append(formula8)
            formulas1.Append(formula9)
            formulas1.Append(formula10)
            formulas1.Append(formula11)
            formulas1.Append(formula12)
            formulas1.Append(formula13)
            formulas1.Append(formula14)
            Dim path1 As New V.Path() With { _
             .AllowTextPath = True, _
             .ConnectionPointType = Ovml.ConnectValues.[Custom], _
             .ConnectionPoints = "@9,0;@10,10800;@11,21600;@12,10800", _
             .ConnectAngles = "270,180,90,0" _
            }
            Dim textPath1 As New V.TextPath() With { _
             .[On] = True, _
             .FitShape = True _
            }
    
            Dim shapeHandles1 As New V.ShapeHandles()
            Dim shapeHandle1 As New V.ShapeHandle() With { _
             .Position = "#0,bottomRight", _
             .XRange = "6629,14971" _
            }
    
            shapeHandles1.Append(shapeHandle1)
            Dim lock1 As New Ovml.Lock() With { _
             .Extension = V.ExtensionHandlingBehaviorValues.Edit, _
             .TextLock = True, _
             .ShapeType = True _
            }
    
            shapetype1.Append(formulas1)
            shapetype1.Append(path1)
            shapetype1.Append(textPath1)
            shapetype1.Append(shapeHandles1)
            shapetype1.Append(lock1)
    
            Dim shape1 As New V.Shape() With { _
             .Id = "_x0000_s3074", _
             .Style = "position:absolute;margin-left:-1in;margin-top:-36pt;width:9pt;height:2.25pt;z-index:251659264", _
             .Type = "#_x0000_t136" _
            }
            Dim shadow1 As New V.Shadow() With { _
             .Color = "#868686" _
            }
            Dim textPath2 As New V.TextPath() With { _
             .Style = "font-family:""Calibri"";font-size:1pt;v-text-kern:t", _
             .FitPath = True, _
             .Trim = True, _
             .[String] = "UNCONTROLLED" _
            }
    
            shape1.Append(shadow1)
            shape1.Append(textPath2)
    
            picture1.Append(shapetype1)
            picture1.Append(shape1)
    
            run1.Append(runProperties1)
            run1.Append(picture1)
    
            Dim run2 As New Run() With { _
             .RsidRunAddition = "00E17A7B" _
            }
    
            Dim runProperties2 As New RunProperties()
            Dim noProof2 As New NoProof()
    
            runProperties2.Append(noProof2)
    
            Dim picture2 As New Picture()
    
            Dim shape2 As New V.Shape() With { _
             .Id = "762362640", _
             .Style = "position:absolute;margin-left:0;margin-top:0;width:527.75pt;height:131.95pt;rotation:315;z-index:251658240;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin",
     _
             .OptionalString = "_x0000_s3073", _
             .FillColor = "silver", _
             .Stroked = False, _
             .Type = "#_x0000_t136" _
            }
            Dim fill1 As New V.Fill() With { _
             .Opacity = ".5" _
            }
            Dim shadow2 As New V.Shadow() With { _
             .Color = "#868686" _
            }
            Dim textPath3 As New V.TextPath() With { _
             .Style = "font-family:""Calibri"";font-size:1pt;v-text-kern:t", _
             .FitPath = True, _
             .Trim = True, _
             .[String] = "UNCONTROLLED" _
            }
            Dim lock2 As New Ovml.Lock() With { _
             .Extension = V.ExtensionHandlingBehaviorValues.Edit, _
             .AspectRatio = True _
            }
            Dim textWrap1 As New Wvml.TextWrap() With { _
             .Side = Wvml.WrapSideValues.Largest, _
             .AnchorX = Wvml.HorizontalAnchorValues.Margin, _
             .AnchorY = Wvml.VerticalAnchorValues.Margin _
            }
    
            shape2.Append(fill1)
            shape2.Append(shadow2)
            shape2.Append(textPath3)
            shape2.Append(lock2)
            shape2.Append(textWrap1)
    
            picture2.Append(shape2)
    
            run2.Append(runProperties2)
            run2.Append(picture2)
    
            paragraph1.Append(paragraphProperties1)
            paragraph1.Append(run1)
            paragraph1.Append(run2)
    
            header1.Append(paragraph1)
    
            headerPart1.Header = header1
        End Sub
    
    
    
        Private Sub ChangeMainDocumentPart1(mainDocumentPart1 As MainDocumentPart)
            Dim document1 As Document = mainDocumentPart1.Document
    
            Dim body1 As Body = document1.GetFirstChild(Of Body)()
    
            Dim paragraph1 As Paragraph = body1.GetFirstChild(Of Paragraph)()
            Dim sectionProperties1 As SectionProperties = body1.GetFirstChild(Of SectionProperties)()
            paragraph1.RsidParagraphMarkRevision = "00EB482D"
            paragraph1.RsidParagraphProperties = "00EB482D"
            sectionProperties1.RsidRPr = "00EB482D"
    
            Dim pageSize1 As PageSize = sectionProperties1.GetFirstChild(Of PageSize)()
    
            Dim headerReference1 As New HeaderReference() With { _
             .Type = HeaderFooterValues.[Default], _
             .Id = "rId6" _
            }
            sectionProperties1.InsertBefore(headerReference1, pageSize1)
        End Sub


    • Edited by AcidTrash Thursday, March 15, 2012 9:41 AM
    • Merged by Forrest GuoModerator Sunday, March 18, 2012 2:07 PM same topic, let's focus on thread, thanks
    Thursday, March 15, 2012 9:20 AM
  • That's correct. There's no keyword var in VB.NET.  var is keyword in C#. You can simply use the Dim without a type.  In this case, people will need

    Option Strict On
    Option Infer On

    Sample would like:

    Option Strict On
    Option Infer On

    Imports System

    Module MainModule
       
    Sub Main()
           
    Dim i = 42
           
    Dim s = "Hello"
           
    Console.WriteLine("{0}, {1}", i.GetType(), s.GetType())
           
    ' Prints System.Int32, System.String '
       
    End Sub
    End Module
    Btw, to insert Wartermark to Word document, you can refer to VBA code:

    Application.Templates( _
            "C:\Users\forrestg\AppData\Roaming\Microsoft\Document Building Blocks\1033\14\Built-In Building Blocks.dotx" _
            ).BuildingBlockEntries("DO NOT COPY 1").Insert Where:=Selection.Range, _
            RichText:=True

    Hope your question will get clear soon.


    Forrest Guo | MSDN Community Support | Feedback to us

    Thursday, March 15, 2012 9:42 AM
    Moderator
  • Thank you.

    Not having fun with this.  Still can't get it working...

    http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/thread/2ca5a836-69c1-486c-ab81-61de57f98069

    • Edited by AcidTrash Friday, March 16, 2012 9:42 AM
    Friday, March 16, 2012 9:40 AM
  • I have cut out the call for...
    ChangeMainDocumentPart1(mainDocumentPart1 As MainDocumentPart)
    It no longer corrupts the word file but it doesn't insert a watermark either.
    Friday, March 16, 2012 11:23 AM
  • I have now changed the header scrtipt to the folloowing code.  Using the productivity tool, I am able to deduce that it does insert all the watermark code but it does not display

    Private Sub GenerateHeaderPart1Content(headerPart1 As HeaderPart)
            Dim header1 As New Header()
            header1.AddNamespaceDeclaration("ve", "http://schemas.openxmlformats.org/markup-compatibility/2006")
            header1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office")
            header1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships")
            header1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math")
            header1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml")
            header1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing")
            header1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word")
            header1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")
            header1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml")
    
            Dim sdtBlock1 As New SdtBlock()
    
            Dim sdtProperties1 As New SdtProperties()
            Dim sdtId1 As New SdtId() With { _
             .Val = 116258157 _
            }
    
            Dim sdtContentDocPartObject1 As New SdtContentDocPartObject()
            Dim docPartGallery1 As New DocPartGallery() With { _
             .Val = "Watermarks" _
            }
            Dim docPartUnique1 As New DocPartUnique()
    
            sdtContentDocPartObject1.Append(docPartGallery1)
            sdtContentDocPartObject1.Append(docPartUnique1)
    
            sdtProperties1.Append(sdtId1)
            sdtProperties1.Append(sdtContentDocPartObject1)
    
            Dim sdtContentBlock1 As New SdtContentBlock()
    
            Dim paragraph3 As New Paragraph() With { _
             .RsidParagraphAddition = "0003787E", _
             .RsidRunAdditionDefault = "0003787E" _
            }
    
            Dim paragraphProperties2 As New ParagraphProperties()
            Dim paragraphStyleId2 As New ParagraphStyleId() With { _
             .Val = "Header" _
            }
    
            paragraphProperties2.Append(paragraphStyleId2)
    
            Dim run2 As New Run()
    
            Dim runProperties1 As New RunProperties()
            Dim noProof1 As New NoProof()
            Dim languages1 As New Languages() With { _
             .EastAsia = "zh-TW" _
            }
    
            runProperties1.Append(noProof1)
            runProperties1.Append(languages1)
    
            Dim picture1 As New Picture()
    
            Dim shapetype1 As New V.Shapetype() With { _
             .Id = "_x0000_t136", _
             .CoordinateSize = "21600,21600", _
             .OptionalNumber = 136, _
             .Adjustment = "10800", _
             .EdgePath = "m@7,l@8,m@5,21600l@6,21600e" _
            }
    
            Dim formulas1 As New V.Formulas()
            Dim formula1 As New V.Formula() With { _
             .Equation = "sum #0 0 10800" _
            }
            Dim formula2 As New V.Formula() With { _
             .Equation = "prod #0 2 1" _
            }
            Dim formula3 As New V.Formula() With { _
             .Equation = "sum 21600 0 @1" _
            }
            Dim formula4 As New V.Formula() With { _
             .Equation = "sum 0 0 @2" _
            }
            Dim formula5 As New V.Formula() With { _
             .Equation = "sum 21600 0 @3" _
            }
            Dim formula6 As New V.Formula() With { _
             .Equation = "if @0 @3 0" _
            }
            Dim formula7 As New V.Formula() With { _
             .Equation = "if @0 21600 @1" _
            }
            Dim formula8 As New V.Formula() With { _
             .Equation = "if @0 0 @2" _
            }
            Dim formula9 As New V.Formula() With { _
             .Equation = "if @0 @4 21600" _
            }
            Dim formula10 As New V.Formula() With { _
             .Equation = "mid @5 @6" _
            }
            Dim formula11 As New V.Formula() With { _
             .Equation = "mid @8 @5" _
            }
            Dim formula12 As New V.Formula() With { _
             .Equation = "mid @7 @8" _
            }
            Dim formula13 As New V.Formula() With { _
             .Equation = "mid @6 @7" _
            }
            Dim formula14 As New V.Formula() With { _
             .Equation = "sum @6 0 @5" _
            }
    
            formulas1.Append(formula1)
            formulas1.Append(formula2)
            formulas1.Append(formula3)
            formulas1.Append(formula4)
            formulas1.Append(formula5)
            formulas1.Append(formula6)
            formulas1.Append(formula7)
            formulas1.Append(formula8)
            formulas1.Append(formula9)
            formulas1.Append(formula10)
            formulas1.Append(formula11)
            formulas1.Append(formula12)
            formulas1.Append(formula13)
            formulas1.Append(formula14)
            Dim path1 As New V.Path() With { _
             .AllowTextPath = True, _
             .ConnectionPointType = Ovml.ConnectValues.[Custom], _
             .ConnectionPoints = "@9,0;@10,10800;@11,21600;@12,10800", _
             .ConnectAngles = "270,180,90,0" _
            }
            Dim textPath1 As New V.TextPath() With { _
             .[On] = True, _
             .FitShape = True _
            }
    
            Dim shapeHandles1 As New V.ShapeHandles()
            Dim shapeHandle1 As New V.ShapeHandle() With { _
             .Position = "#0,bottomRight", _
             .XRange = "6629,14971" _
            }
    
            shapeHandles1.Append(shapeHandle1)
            Dim lock1 As New Ovml.Lock() With { _
             .Extension = V.ExtensionHandlingBehaviorValues.Edit, _
             .TextLock = True, _
             .ShapeType = True _
            }
    
            shapetype1.Append(formulas1)
            shapetype1.Append(path1)
            shapetype1.Append(textPath1)
            shapetype1.Append(shapeHandles1)
            shapetype1.Append(lock1)
    
            Dim shape1 As New V.Shape() With { _
             .Id = "PowerPlusWaterMarkObject357476642", _
             .Style = "position:absolute;margin-left:0;margin-top:0;width:527.85pt;height:131.95pt;rotation:315;z-index:-251656192;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin", _
             .OptionalString = "_x0000_s2049", _
             .AllowInCell = False, _
             .FillColor = "silver", _
             .Stroked = False, _
             .Type = "#_x0000_t136" _
            }
            Dim fill1 As New V.Fill() With { _
             .Opacity = ".5" _
            }
            Dim textPath2 As New V.TextPath() With { _
             .Style = "font-family:""Calibri"";font-size:1pt", _
             .[String] = "UNCONTROLLED" _
            }
            Dim textWrap1 As New Wvml.TextWrap() With { _
             .AnchorX = Wvml.HorizontalAnchorValues.Margin, _
             .AnchorY = Wvml.VerticalAnchorValues.Margin _
            }
    
            shape1.Append(fill1)
            shape1.Append(textPath2)
            shape1.Append(textWrap1)
    
            picture1.Append(shapetype1)
            picture1.Append(shape1)
    
            run2.Append(runProperties1)
            run2.Append(picture1)
    
            paragraph3.Append(paragraphProperties2)
            paragraph3.Append(run2)
    
            sdtContentBlock1.Append(paragraph3)
    
            sdtBlock1.Append(sdtProperties1)
            sdtBlock1.Append(sdtContentBlock1)
    
            header1.Append(sdtBlock1)
    
            headerPart1.Header = header1
        End Sub
    

    Friday, March 16, 2012 11:59 AM
  • I can only assume that there is another bit of XML the word document needs in order to display it.  Does anyone know what this would be, and how would one insert it?
    Friday, March 16, 2012 12:05 PM
  • Hi,

    There's a piece of code from community demonstrate the way to work out this problem:

    byte[] sourceBytes = File.ReadAllBytes(@"C:\Users\loggedinuser\Desktop\TestDoc.docx");

    instead of

    var doc = WordprocessingDocument.Open(@"C:\Users\loggedinuser\Desktop\TestDoc.docx", true);

    Would you check if you can find idea here: http://stackoverflow.com/questions/7002341/open-xml-how-to-add-a-watermark-to-a-docx-document

    Hope your issue will get resolved soon.


    Forrest Guo | MSDN Community Support | Feedback to us

    Sunday, March 18, 2012 2:16 PM
    Moderator
  • Hi AcidTrash,

    Thanks for posting in the MSDN Forum.

    I think this thread might help you. http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/thread/010e55ae-dc56-4e55-af23-02ad268d6bb9.

    Have a good day,

    Tom


    Tom Xu [MSFT]
    MSDN Community Support | Feedback to us

    Monday, March 19, 2012 5:31 AM
    Moderator
  • I have already been through those threads and every thread on the subject.  They were helpful in getting this far but they dont convert to VB very well and ended up with a mess of code that didn't come close to working.

    I need to know what is wrong with my code which does at least run.

    Monday, March 19, 2012 9:56 AM
  • This is my new code to upload a word document to SQL server, inserting watermark beforehand. For some reason it corrupts the word file and does not insert a watermark.  I would like very much that it did not do this and instead uploaded the word file in tact with a water mark.  I have now read every forum post on the subject and I am still none the wiser and I am now on three weeks into this one seemingly simple task.  Can anyone please save me?  Thank you.

        Private Sub ChangePackage(filepath As String)
    
            Dim sourceBytes As Byte() = File.ReadAllBytes(filepath)
    
            Dim inMemoryStream As New MemoryStream()
            inMemoryStream.Write(sourceBytes, 0, CInt(sourceBytes.Length))
    
            Dim document = WordprocessingDocument.Open(inMemoryStream, True)
    
            Dim headerPart1 As HeaderPart = document.MainDocumentPart.AddNewPart(Of HeaderPart)("headers")
            GenerateHeaderPart1Content(headerPart1)
    
            document.MainDocumentPart.Document.Save()
            document.Close()
    
            Using Conn As New SqlConnection(ConfigurationManager.ConnectionStrings("cerberusConnectionString").ConnectionString)
    
                Dim strDocids As String
                Dim SQL As String = "INSERT INTO [tbl_wikidocs] ([DocumentTitle],[document],[docmimetype],[filesize]) VALUES (@DocumentTitle, @document, @docmimetype,@filesize)"
                Dim SQL2 As String = "INSERT INTO [tbl_WIKIblog] ([Title],[post]) VALUES (@DocumentTitle)"
                Dim myCommand As New SqlCommand(SQL, Conn)
    
                Dim docmimetypes As String = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    
                myCommand.Parameters.AddWithValue("@DocumentTitle", doctitle.Text.Trim())
                myCommand.Parameters.AddWithValue("@Docmimetype", docmimetypes)
                Dim imageBytes(inMemoryStream.Length) As Byte
                UploadedFile.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length)
                myCommand.Parameters.AddWithValue("@document", imageBytes)
                myCommand.Parameters.AddWithValue("@filesize", imageBytes.Length)
    
                Conn.Open()
                myCommand.ExecuteNonQuery()
                Conn.Close()
                SQL = "select max(docids) from [tbl_wikidocs]"
                Dim myCommand2 As New SqlCommand(SQL, Conn)
                Conn.Open()
                strDocids = myCommand2.ExecuteScalar
                Conn.Close()
    
                inMemoryStream.Close()
                inMemoryStream.Dispose()
                inMemoryStream = Nothing
    
                Dim nurl As String = "docview.aspx?docids=" + strDocids
                HyperLink1.NavigateUrl = (nurl)
                HyperLink1.Text = ("Your document can be found here..." + nurl)
    
                Dim FreeTextBox1 As FreeTextBox = CType(DetailsView1.FindControl("FreeTextBox1"), FreeTextBox)
    
                FreeTextBox1.Text = FreeTextBox1.Text + "<BR><P>Your document can be found <a href='" + nurl + "'>here</a>."
    
            End Using
    
        End Sub
    
        Private Sub GenerateHeaderPart1Content(headerPart1 As HeaderPart)
            Dim header1 As New Header()
            header1.AddNamespaceDeclaration("ve", "http://schemas.openxmlformats.org/markup-compatibility/2006")
            header1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office")
            header1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships")
            header1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math")
            header1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml")
            header1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing")
            header1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word")
            header1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")
            header1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml")
    
            Dim sdtBlock1 As New SdtBlock()
    
            Dim sdtProperties1 As New SdtProperties()
            Dim sdtId1 As New SdtId() With { _
             .Val = 116258157 _
            }
    
            Dim sdtContentDocPartObject1 As New SdtContentDocPartObject()
            Dim docPartGallery1 As New DocPartGallery() With { _
             .Val = "Watermarks" _
            }
            Dim docPartUnique1 As New DocPartUnique()
    
            sdtContentDocPartObject1.Append(docPartGallery1)
            sdtContentDocPartObject1.Append(docPartUnique1)
    
            sdtProperties1.Append(sdtId1)
            sdtProperties1.Append(sdtContentDocPartObject1)
    
            Dim sdtContentBlock1 As New SdtContentBlock()
    
            Dim paragraph3 As New Paragraph() With { _
             .RsidParagraphAddition = "0003787E", _
             .RsidRunAdditionDefault = "0003787E" _
            }
    
            Dim paragraphProperties2 As New ParagraphProperties()
            Dim paragraphStyleId2 As New ParagraphStyleId() With { _
             .Val = "Header" _
            }
    
            paragraphProperties2.Append(paragraphStyleId2)
    
            Dim run2 As New Run()
    
            Dim runProperties1 As New RunProperties()
            Dim noProof1 As New NoProof()
            Dim languages1 As New Languages() With { _
             .EastAsia = "zh-TW" _
            }
    
            runProperties1.Append(noProof1)
            runProperties1.Append(languages1)
    
            Dim picture1 As New Picture()
    
            Dim shapetype1 As New V.Shapetype() With { _
             .Id = "_x0000_t136", _
             .CoordinateSize = "21600,21600", _
             .OptionalNumber = 136, _
             .Adjustment = "10800", _
             .EdgePath = "m@7,l@8,m@5,21600l@6,21600e" _
            }
    
            Dim formulas1 As New V.Formulas()
            Dim formula1 As New V.Formula() With { _
             .Equation = "sum #0 0 10800" _
            }
            Dim formula2 As New V.Formula() With { _
             .Equation = "prod #0 2 1" _
            }
            Dim formula3 As New V.Formula() With { _
             .Equation = "sum 21600 0 @1" _
            }
            Dim formula4 As New V.Formula() With { _
             .Equation = "sum 0 0 @2" _
            }
            Dim formula5 As New V.Formula() With { _
             .Equation = "sum 21600 0 @3" _
            }
            Dim formula6 As New V.Formula() With { _
             .Equation = "if @0 @3 0" _
            }
            Dim formula7 As New V.Formula() With { _
             .Equation = "if @0 21600 @1" _
            }
            Dim formula8 As New V.Formula() With { _
             .Equation = "if @0 0 @2" _
            }
            Dim formula9 As New V.Formula() With { _
             .Equation = "if @0 @4 21600" _
            }
            Dim formula10 As New V.Formula() With { _
             .Equation = "mid @5 @6" _
            }
            Dim formula11 As New V.Formula() With { _
             .Equation = "mid @8 @5" _
            }
            Dim formula12 As New V.Formula() With { _
             .Equation = "mid @7 @8" _
            }
            Dim formula13 As New V.Formula() With { _
             .Equation = "mid @6 @7" _
            }
            Dim formula14 As New V.Formula() With { _
             .Equation = "sum @6 0 @5" _
            }
    
            formulas1.Append(formula1)
            formulas1.Append(formula2)
            formulas1.Append(formula3)
            formulas1.Append(formula4)
            formulas1.Append(formula5)
            formulas1.Append(formula6)
            formulas1.Append(formula7)
            formulas1.Append(formula8)
            formulas1.Append(formula9)
            formulas1.Append(formula10)
            formulas1.Append(formula11)
            formulas1.Append(formula12)
            formulas1.Append(formula13)
            formulas1.Append(formula14)
            Dim path1 As New V.Path() With { _
             .AllowTextPath = True, _
             .ConnectionPointType = Ovml.ConnectValues.[Custom], _
             .ConnectionPoints = "@9,0;@10,10800;@11,21600;@12,10800", _
             .ConnectAngles = "270,180,90,0" _
            }
            Dim textPath1 As New V.TextPath() With { _
             .[On] = True, _
             .FitShape = True _
            }
    
            Dim shapeHandles1 As New V.ShapeHandles()
            Dim shapeHandle1 As New V.ShapeHandle() With { _
             .Position = "#0,bottomRight", _
             .XRange = "6629,14971" _
            }
    
            shapeHandles1.Append(shapeHandle1)
            Dim lock1 As New Ovml.Lock() With { _
             .Extension = V.ExtensionHandlingBehaviorValues.Edit, _
             .TextLock = True, _
             .ShapeType = True _
            }
    
            shapetype1.Append(formulas1)
            shapetype1.Append(path1)
            shapetype1.Append(textPath1)
            shapetype1.Append(shapeHandles1)
            shapetype1.Append(lock1)
    
            Dim shape1 As New V.Shape() With { _
             .Id = "PowerPlusWaterMarkObject357476642", _
             .Style = "position:absolute;margin-left:0;margin-top:0;width:527.85pt;height:131.95pt;rotation:315;z-index:-251656192;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin", _
             .OptionalString = "_x0000_s2049", _
             .AllowInCell = False, _
             .FillColor = "silver", _
             .Stroked = False, _
             .Type = "#_x0000_t136" _
            }
            Dim fill1 As New V.Fill() With { _
             .Opacity = ".5" _
            }
            Dim textPath2 As New V.TextPath() With { _
             .Style = "font-family:""Calibri"";font-size:1pt", _
             .[String] = "CONFIDENTIAL" _
            }
            Dim textWrap1 As New Wvml.TextWrap() With { _
             .AnchorX = Wvml.HorizontalAnchorValues.Margin, _
             .AnchorY = Wvml.VerticalAnchorValues.Margin _
            }
    
            shape1.Append(fill1)
            shape1.Append(textPath2)
            shape1.Append(textWrap1)
    
            picture1.Append(shapetype1)
            picture1.Append(shape1)
    
            run2.Append(runProperties1)
            run2.Append(picture1)
    
            paragraph3.Append(paragraphProperties2)
            paragraph3.Append(run2)
    
            sdtContentBlock1.Append(paragraph3)
    
            sdtBlock1.Append(sdtProperties1)
            sdtBlock1.Append(sdtContentBlock1)
    
            header1.Append(sdtBlock1)
    
            headerPart1.Header = header1
        End Sub


    Monday, March 19, 2012 10:15 AM
  • I am using the following code to do this.  The code runs but it does not insert a watermark.  Can someone please suggest a reason why?

     Private Sub ChangePackage(filepath As String)
    
            Dim sourceBytes As Byte() = File.ReadAllBytes(filepath)
    
            Dim inMemoryStream As New MemoryStream()
            inMemoryStream.Write(sourceBytes, 0, sourceBytes.Length)
    
            Dim document = WordprocessingDocument.Open(inMemoryStream, True)
    
            Dim headerPart1 As HeaderPart = document.MainDocumentPart.AddNewPart(Of HeaderPart)("headers")
            GenerateHeaderPart1Content(headerPart1)
    
            document.MainDocumentPart.Document.Save()
            document.Close()
    
            Using Conn As New SqlConnection(ConfigurationManager.ConnectionStrings("cerberusConnectionString").ConnectionString)
    
                Dim strDocids As String
                Dim SQL As String = "INSERT INTO [tbl_wikidocs] ([DocumentTitle],[document],[docmimetype],[filesize]) VALUES (@DocumentTitle, @document, @docmimetype,@filesize)"
                Dim SQL2 As String = "INSERT INTO [tbl_WIKIblog] ([Title],[post]) VALUES (@DocumentTitle)"
                Dim myCommand As New SqlCommand(SQL, Conn)
    
                Dim docmimetypes As String = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    
                myCommand.Parameters.AddWithValue("@DocumentTitle", doctitle.Text.Trim())
                myCommand.Parameters.AddWithValue("@Docmimetype", docmimetypes)
                Dim imageBytes(inMemoryStream.Length) As Byte
                myCommand.Parameters.AddWithValue("@document", imageBytes)
                myCommand.Parameters.AddWithValue("@filesize", imageBytes.Length)
    
                Conn.Open()
                myCommand.ExecuteNonQuery()
                Conn.Close()
                SQL = "select max(docids) from [tbl_wikidocs]"
                Dim myCommand2 As New SqlCommand(SQL, Conn)
                Conn.Open()
                strDocids = myCommand2.ExecuteScalar
                Conn.Close()
    
                inMemoryStream.Close()
                inMemoryStream.Dispose()
                inMemoryStream = Nothing
    
                Dim nurl As String = "docview.aspx?docids=" + strDocids
                HyperLink1.NavigateUrl = (nurl)
                HyperLink1.Text = ("Your document can be found here..." + nurl)
    
                Dim FreeTextBox1 As FreeTextBox = CType(DetailsView1.FindControl("FreeTextBox1"), FreeTextBox)
    
                FreeTextBox1.Text = FreeTextBox1.Text + "<BR><P>Your document can be found <a href='" + nurl + "'>here</a>."
    
            End Using
    
        End Sub
    
        Private Sub GenerateHeaderPart1Content(headerPart1 As HeaderPart)
            Dim header1 As New Header()
            header1.AddNamespaceDeclaration("ve", "http://schemas.openxmlformats.org/markup-compatibility/2006")
            header1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office")
            header1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships")
            header1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math")
            header1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml")
            header1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing")
            header1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word")
            header1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")
            header1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml")
    
            Dim sdtBlock1 As New SdtBlock()
    
            Dim sdtProperties1 As New SdtProperties()
            Dim sdtId1 As New SdtId() With { _
             .Val = 116258157 _
            }
    
            Dim sdtContentDocPartObject1 As New SdtContentDocPartObject()
            Dim docPartGallery1 As New DocPartGallery() With { _
             .Val = "Watermarks" _
            }
            Dim docPartUnique1 As New DocPartUnique()
    
            sdtContentDocPartObject1.Append(docPartGallery1)
            sdtContentDocPartObject1.Append(docPartUnique1)
    
            sdtProperties1.Append(sdtId1)
            sdtProperties1.Append(sdtContentDocPartObject1)
    
            Dim sdtContentBlock1 As New SdtContentBlock()
    
            Dim paragraph3 As New Paragraph() With { _
             .RsidParagraphAddition = "0003787E", _
             .RsidRunAdditionDefault = "0003787E" _
            }
    
            Dim paragraphProperties2 As New ParagraphProperties()
            Dim paragraphStyleId2 As New ParagraphStyleId() With { _
             .Val = "Header" _
            }
    
            paragraphProperties2.Append(paragraphStyleId2)
    
            Dim run2 As New Run()
    
            Dim runProperties1 As New RunProperties()
            Dim noProof1 As New NoProof()
            Dim languages1 As New Languages() With { _
             .EastAsia = "zh-TW" _
            }
    
            runProperties1.Append(noProof1)
            runProperties1.Append(languages1)
    
            Dim picture1 As New Picture()
    
            Dim shapetype1 As New V.Shapetype() With { _
             .Id = "_x0000_t136", _
             .CoordinateSize = "21600,21600", _
             .OptionalNumber = 136, _
             .Adjustment = "10800", _
             .EdgePath = "m@7,l@8,m@5,21600l@6,21600e" _
            }
    
            Dim formulas1 As New V.Formulas()
            Dim formula1 As New V.Formula() With { _
             .Equation = "sum #0 0 10800" _
            }
            Dim formula2 As New V.Formula() With { _
             .Equation = "prod #0 2 1" _
            }
            Dim formula3 As New V.Formula() With { _
             .Equation = "sum 21600 0 @1" _
            }
            Dim formula4 As New V.Formula() With { _
             .Equation = "sum 0 0 @2" _
            }
            Dim formula5 As New V.Formula() With { _
             .Equation = "sum 21600 0 @3" _
            }
            Dim formula6 As New V.Formula() With { _
             .Equation = "if @0 @3 0" _
            }
            Dim formula7 As New V.Formula() With { _
             .Equation = "if @0 21600 @1" _
            }
            Dim formula8 As New V.Formula() With { _
             .Equation = "if @0 0 @2" _
            }
            Dim formula9 As New V.Formula() With { _
             .Equation = "if @0 @4 21600" _
            }
            Dim formula10 As New V.Formula() With { _
             .Equation = "mid @5 @6" _
            }
            Dim formula11 As New V.Formula() With { _
             .Equation = "mid @8 @5" _
            }
            Dim formula12 As New V.Formula() With { _
             .Equation = "mid @7 @8" _
            }
            Dim formula13 As New V.Formula() With { _
             .Equation = "mid @6 @7" _
            }
            Dim formula14 As New V.Formula() With { _
             .Equation = "sum @6 0 @5" _
            }
    
            formulas1.Append(formula1)
            formulas1.Append(formula2)
            formulas1.Append(formula3)
            formulas1.Append(formula4)
            formulas1.Append(formula5)
            formulas1.Append(formula6)
            formulas1.Append(formula7)
            formulas1.Append(formula8)
            formulas1.Append(formula9)
            formulas1.Append(formula10)
            formulas1.Append(formula11)
            formulas1.Append(formula12)
            formulas1.Append(formula13)
            formulas1.Append(formula14)
            Dim path1 As New V.Path() With { _
             .AllowTextPath = True, _
             .ConnectionPointType = Ovml.ConnectValues.[Custom], _
             .ConnectionPoints = "@9,0;@10,10800;@11,21600;@12,10800", _
             .ConnectAngles = "270,180,90,0" _
            }
            Dim textPath1 As New V.TextPath() With { _
             .[On] = True, _
             .FitShape = True _
            }
    
            Dim shapeHandles1 As New V.ShapeHandles()
            Dim shapeHandle1 As New V.ShapeHandle() With { _
             .Position = "#0,bottomRight", _
             .XRange = "6629,14971" _
            }
    
            shapeHandles1.Append(shapeHandle1)
            Dim lock1 As New Ovml.Lock() With { _
             .Extension = V.ExtensionHandlingBehaviorValues.Edit, _
             .TextLock = True, _
             .ShapeType = True _
            }
    
            shapetype1.Append(formulas1)
            shapetype1.Append(path1)
            shapetype1.Append(textPath1)
            shapetype1.Append(shapeHandles1)
            shapetype1.Append(lock1)
    
            Dim shape1 As New V.Shape() With { _
             .Id = "PowerPlusWaterMarkObject357476642", _
             .Style = "position:absolute;margin-left:0;margin-top:0;width:527.85pt;height:131.95pt;rotation:315;z-index:-251656192;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin", _
             .OptionalString = "_x0000_s2049", _
             .AllowInCell = False, _
             .FillColor = "silver", _
             .Stroked = False, _
             .Type = "#_x0000_t136" _
            }
            Dim fill1 As New V.Fill() With { _
             .Opacity = ".5" _
            }
            Dim textPath2 As New V.TextPath() With { _
             .Style = "font-family:""Calibri"";font-size:1pt", _
             .[String] = "BUTT FUCKING SON OF A BITCH" _
            }
            Dim textWrap1 As New Wvml.TextWrap() With { _
             .AnchorX = Wvml.HorizontalAnchorValues.Margin, _
             .AnchorY = Wvml.VerticalAnchorValues.Margin _
            }
    
            shape1.Append(fill1)
            shape1.Append(textPath2)
            shape1.Append(textWrap1)
    
            picture1.Append(shapetype1)
            picture1.Append(shape1)
    
            run2.Append(runProperties1)
            run2.Append(picture1)
    
            paragraph3.Append(paragraphProperties2)
            paragraph3.Append(run2)
    
            sdtContentBlock1.Append(paragraph3)
    
            sdtBlock1.Append(sdtProperties1)
            sdtBlock1.Append(sdtContentBlock1)
    
            header1.Append(sdtBlock1)
    
            headerPart1.Header = header1
        End Sub
    

    Tuesday, March 20, 2012 4:28 PM
  • Hi AcidTrash,

    To see whether this snippet can help you.

    Imports System.IO
    Imports System.Collections.Generic
    Imports System.ComponentModel
    Imports System.Data
    Imports System.Drawing
    Imports System.Linq
    Imports System.Text
    Imports System.Windows.Forms
    Imports DocumentFormat.OpenXml.Packaging
    Imports DocumentFormat.OpenXml.Wordprocessing
    Imports DocumentFormat.OpenXml
    Imports V = DocumentFormat.OpenXml.Vml
    Imports System.Diagnostics
    
    Namespace WindowsFormsApplication3
    	Public Partial Class Form1
    		Inherits Form
    		Public Sub New()
    			InitializeComponent()
    		End Sub
    
    		Private Sub button1_Click(sender As Object, e As EventArgs)
    			Using package As WordprocessingDocument = WordprocessingDocument.Open("C:\Users\*****\****.docx", True)
    				InsertCustomWatermark(package, "C:\Users\*******\****.jpg")
    			End Using
    		End Sub
    
    		Private Sub InsertCustomWatermark(package As WordprocessingDocument, p As String)
    			SetWaterMarkPicture(p)
    			Dim mainDocumentPart1 As MainDocumentPart = package.MainDocumentPart
    			If mainDocumentPart1 IsNot Nothing Then
    				mainDocumentPart1.DeleteParts(mainDocumentPart1.HeaderParts)
    				Dim headPart1 As HeaderPart = mainDocumentPart1.AddNewPart(Of HeaderPart)()
    				GenerateHeaderPart1Content(headPart1)
    				Dim rId As String = mainDocumentPart1.GetIdOfPart(headPart1)
    				Dim image As ImagePart = headPart1.AddNewPart(Of ImagePart)("image/jpeg", "rId999")
    				GenerateImagePart1Content(image)
    				Dim sectPrs As IEnumerable(Of SectionProperties) = mainDocumentPart1.Document.Body.Elements(Of SectionProperties)()
    				For Each sectPr As var In sectPrs
    					sectPr.RemoveAllChildren(Of HeaderReference)()
    					sectPr.PrependChild(Of HeaderReference)(New HeaderReference() With { _
    						Key .Id = rId _
    					})
    				Next
    			Else
    				MessageBox.Show("alert")
    			End If
    		End Sub
    		Private Sub GenerateHeaderPart1Content(headerPart1 As HeaderPart)
    			Dim header1 As New Header()
    			Dim paragraph2 As New Paragraph()
    			Dim run1 As New Run()
    			Dim picture1 As New Picture()
    			Dim shape1 As New V.Shape() With { _
    				Key .Id = "WordPictureWatermark75517470", _
    				Key .Style = "position:absolute;left:0;text-align:left;margin-left:0;margin-top:0;width:415.2pt;height:456.15pt;z-index:-251656192;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin", _
    				Key .OptionalString = "_x0000_s2051", _
    				Key .AllowInCell = False, _
    				Key .Type = "#_x0000_t75" _
    			}
    			Dim imageData1 As New V.ImageData() With { _
    				Key .Gain = "19661f", _
    				Key .BlackLevel = "22938f", _
    				Key .Title = "watermark", _
    				Key .RelationshipId = "rId999" _
    			}
    			shape1.Append(imageData1)
    			picture1.Append(shape1)
    			run1.Append(picture1)
    			paragraph2.Append(run1)
    			header1.Append(paragraph2)
    			headerPart1.Header = header1
    		End Sub
    		Private Sub GenerateImagePart1Content(imagePart1 As ImagePart)
    			Dim data As System.IO.Stream = GetBinaryDataStream(imagePart1Data)
    			imagePart1.FeedData(data)
    			data.Close()
    		End Sub
    		Private imagePart1Data As String = ""
    		Private Function GetBinaryDataStream(base64String As String) As System.IO.Stream
    			Return New System.IO.MemoryStream(System.Convert.FromBase64String(base64String))
    		End Function
    		Public Sub SetWaterMarkPicture(file As String)
    			Dim inFile As FileStream
    			Dim byteArray As Byte()
    			Try
    				inFile = New FileStream(file, FileMode.Open, FileAccess.Read)
    				byteArray = New Byte(inFile.Length - 1)   				Dim byteRead As Long = inFile.Read(byteArray, 0, CInt(inFile.Length))
    				inFile.Close()
    				imagePart1Data = Convert.ToBase64String(byteArray, 0, byteArray.Length)
    			Catch ex As Exception
    				Debug.Print(ex.Message)
    			End Try
    		End Sub
    	End Class
    End Namespace

    Have a good day,

    Tom


    Tom Xu [MSFT]
    MSDN Community Support | Feedback to us



    Wednesday, March 21, 2012 7:09 AM
    Moderator