'*************************************************************
' 
' ADOBE SYSTEMS INCORPORATED 
' Copyright 2005-2006 Adobe Systems Incorporated 
' All Rights Reserved 

' NOTICE:  Adobe permits you to use, modify, and 
' distribute this file in accordance with the terms
' of the Adobe license agreement accompanying it.  
' If you have received this file from a source 
' other than Adobe, then your use, modification,
' or distribution of it requires the prior 
' written permission of Adobe. 
' 
'*************************************************************

' CollectForOutput.vbs

' DESCRIPTION

' This sample opens a document with placed items, copies the placed item files
' to a folder on the desktop, then relinks and saves the document to the same folder
' as the copied files.
' NOTE: You can change the path and use any other folder.
' 
' *************************************************************

Set appRef = CreateObject("Illustrator.Application")
Set myFSO = CreateObject("Scripting.FileSystemObject")

' Find path to desktop desktop
const DESKTOP = &H0&
set myShell = CreateObject("Shell.Application")
set myDesktopFolder = myShell.Namespace(DESKTOP)
set myDesktopFolderItem = myDesktopFolder.Self

' Create a reference to the output folder on the desktop
myOutputFolderPath = myDesktopFolderItem.Path & "\CollectForOutput"
If (not myFSO.FolderExists(myOutputFolderPath)) Then
	myFSO.CreateFolder(myOutputFolderPath)
End If

' Change sample file name here if needed
inputFileName = "sample.ai"
inputFilePath = appRef.Path & "\Scripting\Sample Scripts\Visual Basic\Collect for Output\Sample File\" & inputFileName
msgFileName = Replace( inputFilePath, "\", "\\" )

myMsg = "alert(""Path to the sample file: " & CStr(msgFileName) & _
"   Please change the script if you want to use a different file."")"
appRef.DoJavaScript myMsg

' Open input doc
appRef.Open(inputFilePath)
Set docRef = appRef.ActiveDocument

'Loop thru placed items
const READONLY = 1
For i = 1 To docRef.PlacedItems.Count
	' copy linked file to output folder
	sourceFilePath = docRef.PlacedItems(i).File
	sourceFileName = myFSO.GetFileName(sourceFilePath)
	targetFilePath = myOutputFolderPath & "\" & sourceFileName
	myFSO.CopyFile sourceFilePath, targetFilePath, true
	' relink the placed item to the copied file in output folder
	docRef.PlacedItems(i).File = targetFilePath
	' Clear any read-only flag in the target file 
	' so we can run the script multiple times. 
	set f = myFSO.GetFile(targetFilePath)
	if f.attributes and READONLY then
		f.attributes = f.attributes - READONLY
	end if

Next

'Save Illustrator doc to output directory
myOutputFilePath = myOutputFolderPath & "\" & inputFileName
docRef.SaveAs (myOutputFilePath)
docRef.Close()

myMsg = "alert(""Output collected in folder: " & myOutputFolderPath  & """)"
myMsg = Replace( myMsg, "\", "\\" )
appRef.DoJavaScript myMsg
