I was recently asked if I had a macro that would create a jpg file for each part in a directory. The code below is what I came up with. It finds all of the files of a certain type within a specified directory and creates an image file for each one.
The primary function this macro uses to accomplish this is the SaveAsBitmap method. This method is on the View object, which represents a graphics window. The SaveAsBitmap method saves the contents of that window as an image. You can specify one of several different image types and you can also specify the size of the output image. The supported image types are bmp, jpg, png, tiff, and gif. The type to write out is inferred by the extension of the image file you specify. The sample below will create jpg files. Being able to specify the size of the output image is also powerful because then you’re not limited by the size of the window and the resulting image is not just a scaled bitmap of the current window contents but is an image rendered specifically at the specified size.
It’s also very simple in that there isn’t any user-interface. All inputs, the directory to process and the input and output file types, are hard-coded within the program.
Public Sub SaveImages()
' Specify the size of the output image in pixels. If you
' use zero then it will be the actual size of the window.
Dim pixelWidth As Integer
Dim pixelHeight As Integer
pixelWidth = 800
pixelHeight = 800
' Specify the path where the files exist. The rest of the
' code expects this path name to end with a backslash.
Dim dirName As String
dirName = "C:\Temp\"
' Loop through the files in the specified directory.
' Depending on the file type you want to generate the
' images for you may need to change the file extension.
' In this case it will create images for all the part
' files in the specified directory. Editing "*.ipt" to
' "*.iam" will generate images for all assemblies.
Dim filename As String
filename = Dir(dirName & "*.ipt")
Do While filename <> ""
' Save the current silent operation state.
Dim silentState As Boolean
silentState = ThisApplication.SilentOperation
' Turn on silent operation.
ThisApplication.SilentOperation = True
' Open the document.
Dim doc As Document
Set doc = ThisApplication.Documents.Open(dirName & filename)
' Restore the state to its previous value.
ThisApplication.SilentOperation = silentState
' Get the currently active view, which will be for
' the document just opened.
Dim window As view
Set window = ThisApplication.ActiveView
' Create the filename for the output file. This uses
' the same name as the original file and replaces the
' extension with .jpg
Dim imageFilename As String
imageFilename = dirName & _
Left$(filename, InStr(filename, ".")) & "jpg"
Call window.SaveAsBitmap(imageFilename, _
' Close the current document.
' Get the next filename.
filename = Dir
ThisApplication.StatusBarText = "Finished processing."