|
|
Title | Remove pictures from a Word document using VB.NET |
Keywords | VB.NET, NET, Word, picture, shape, InlineShape, remove, graphic |
Categories | Office, Utilities, VB.NET |
|
|
Note that this program requires a reference to the Microsoft Word Object Library (In the Project menu, select Add Reference, click the COM tab, click Microsoft Word 10.0 Object Library, click the Select button, and click OK).
This example demonstrates two methods. First, it creates a Word server object and opens the source file. It uses the Selection.Find object to find and replace all graphic objects with nothing. This removes InlineShapes but not Shapes.
When it is finished, the program saves the Word document with a new name and closes the Word server.
|
|
Private Sub btnReplacePictures_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
btnReplacePictures.Click
Dim word_app As New Word.Application()
word_app.Documents.Open( _
FileName:=txtSourceFile.Text, _
ConfirmConversions:=False, _
ReadOnly:=True, _
AddToRecentFiles:=False, _
Format:=Word.WdOpenFormat.wdOpenFormatAuto)
With word_app.Selection.Find
.ClearFormatting()
.Replacement.ClearFormatting()
.Text = "^g"
.Replacement.Text = ""
.Forward = True
.Wrap = Word.WdFindWrap.wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute(Replace:=Word.WdReplace.wdReplaceAll)
End With
' Save the file.
word_app.ActiveDocument.SaveAs( _
FileName:=txtResult.Text, _
AddToRecentFiles:=False)
CType(word_app, Word.ApplicationClass).Quit()
word_app = Nothing
MsgBox("Okay")
End Sub
|
|
In the second method, the program creates a Word server object and opens the source file as before. It then loops through the document's InlineShapes and Shapes collections, deleting all of their entries. Note that this removes objects other than pictures (for example, OLE objects). You could make the code test the type of object to see what it is deleting if you want.
When it is finished, the program again saves the Word document with a new name and closes the Word server.
|
|
Private Sub btnRemoveShapes_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
btnRemoveShapes.Click
Dim word_app As New Word.Application()
Dim word_doc As Word.Document
word_doc = word_app.Documents.Open( _
FileName:=txtSourceFile.Text, _
ConfirmConversions:=False, _
ReadOnly:=True, _
AddToRecentFiles:=False, _
Format:=Word.WdOpenFormat.wdOpenFormatAuto)
' Delete InlineShapes.
With word_doc.InlineShapes
Do While .Count > 0
.Item(1).Delete()
Loop
End With
' Delete Shapes.
With word_doc.Shapes
Do While .Count > 0
.Item(1).Delete()
Loop
End With
' Save the file.
word_doc.SaveAs( _
FileName:=txtResult.Text, _
AddToRecentFiles:=False)
CType(word_doc, Word.DocumentClass).Close()
word_doc = Nothing
CType(word_app, Word.ApplicationClass).Quit()
word_app = Nothing
MsgBox("Okay")
End Sub
|
|
|
|
|
|