Sunday, May 10, 2009

Create a server form with PowerShell 2 & Word 2007 (Part 4)

Previous part of this article is HERE !

This is the last part. We will be able to generate server form using PowerShell !

All we have to do is to write some functions to update our Word document.

function Set-OpenXmlText($objNode, $objNsMgr, $strData)
    $blnIsCheckBox = $false
    $objNodeT = $null
    $objNodeR = $null

    $objNodeTmp = $objNode.SelectSingleNode('w:tc', $objNsMgr)
    if ($objNodeTmp -ne $null) { $objNode = $objNodeTmp }
    $objNodeTmp = $objNode.SelectSingleNode('w:p', $objNsMgr)
    if ($objNodeTmp -ne $null) { $objNode = $objNodeTmp }
    $objNodes = $objNode.SelectNodes('w:r', $objNsMgr)
    foreach ($objNodeR in $objNodes) {
        $objNodeSYM = $objNodeR.SelectSingleNode('w:sym', $objNsMgr)
        $blnIsCheckBox = $objNodeSYM -ne $null
        if ($blnIsCheckBox) {
            $objAttr = $objNodeSYM.Attributes |
                       where-Object { $_.Name -eq 'w:char'}
            $objAttr.Value = 'F0A8'
            if ($strData -eq $true) { $objAttr.Value = '00FE' }
        $objNodeT = $objNodeR.SelectSingleNode('w:t', $objNsMgr)
        if ($objNodeT -ne $null) { $objNodeT.InnerText = '' }
    if ((-not $blnIsCheckBox-And ($objNodeT -ne $null)) {
        $objNodeT.InnerText = $strData

We won't go inside the OpenXML format however we will need an overview and some basis to understand Set-OpenXmlText function. Nothing complex, don't worry !

The first thing we need is to understand what's happen when a content control is inserted:

When we change the content of the Word document, we change the file /word/document.xml in the DOCX package. In fact, we add the following tags:

The content control tag is w:sdt which is divided into two parts (green et red color on the image).

Green part (w:sdtPr tag) gathers all content control properties : by example, its name. In the example, the content control name is FctNetworkInfrastructure. This name is get by Get-OpenXmlContentCtrlAlias function which is detailed in the previous article!

Set-OpenXmlText function will change the blue part (w:sdtContent tag) which is the content of the content control!

That's all !

No comments:

Post a Comment