Monday, January 21, 2013

MS Word 2007: Hide Content Control Placeholder Text During Printing

Here's the code, which goes in the ThisDocument module of the stylesheet you'll be using.

Private WithEvents m_wd As Word.Application
Private m_showingPlaceholders As Boolean

Private Sub Document_Open()
   Set m_wd = Application
   m_showingPlaceholders = True
End Sub

Private Sub m_wd_DocumentBeforePrint(ByVal Doc As Document, Cancel As Boolean)
   Dim cc As ContentControl
   For Each cc In Doc.ContentControls
      If cc.ShowingPlaceholderText Then cc.Range.Font.Color = wdColorWhite
   m_showingPlaceholders = False
End Sub

Private Sub m_wd_WindowSelectionChange(ByVal Sel As Selection)
   Dim cc As ContentControl
   If Not m_showingPlaceholders Then
      For Each cc In Sel.Document.ContentControls
         If cc.ShowingPlaceholderText Then cc.Range.Font.Color = wdColorBlack
      m_showingPlaceholders = True
   End If
End Sub

So when the document opens, the Word.Application object is assigned to a WithEvents variable that allows us to handle application events in the stylesheet.

Then we handle the DocumentBeforePrint event, which provides a document object, Doc, which has a ContentControls collection, which we enumerate, and wherever the ContentControl.ShowingPlaceholderText property is true, we set the color of the text to white.  We also set a flag to indicate that placeholders are hidden.

After printing we handle the WindowSelectionChange event which is bound to occur when the user interacts with the document.  First we check our flag to see if the PlaceholderText is still hidden.  If so, we get our ContentControls collection from the Document object in the Selection object, Sel, that the WindowSelectionChange event provides.  We enumerate that collection and again, wherever the ContentControl.ShowingPlaceholderText property is true we set the color back to black.

No comments:

Post a Comment