使用 Python 编写 Illustrator 脚本:保存 EPS 文件(COM 变体)

问题描述 投票:0回答:1

我正在尝试使用 Python 将 Illustrator 文件另存为 .eps。据我所知,Illustrator 通常不支持 Python,因此我下载了一个参考文件并将其导入到我的代码中。通常代码与 Illustrator 中使用的 javascript 非常相似。

我收到的错误是:

回溯(最近一次调用最后一次): 文件“s:\Workstation - DavidK\Code\Main\SAVETEST.py”,第 12 行,位于

doc.SaveAs(SaveIn = 'S:/Workstation - DavidK/Code/Main/DeleteLater/tempSheet.eps', 选项 = saveOpts)

文件“s:\Workstation - DavidK\Code\Main\illustrator_ref.py”,第 1998 行,另存为

 return self._oleobj_.InvokeTypes(1398161747, LCID, 1, (24, 0), ((8, 1), (12, 17)),SaveIn

 TypeError: Objects of type 'EPSSaveOptions' can not be converted to a COM VARIANT (but obtaining the buffer() of this object could)

我尝试过使用缓冲区,但我使用的是Python3,所以它必须需要内存视图,这需要字节,我根本不明白。

这是我的代码:

from illustrator_ref import *
import win32com.client as win32
from win32com.client import DispatchBaseClass
from win32com.client import CoClassBaseClass

app = win32.GetActiveObject("Illustrator.Application")
doc = app.activeDocument

saveOpts = EPSSaveOptions(CoClassBaseClass)
saveOpts.EmbedAllFonts = True
saveOpts.SaveMultipleArtboards = True
doc.SaveAs(SaveIn = 'S:/Workstation - DavidK/Code/Main/DeleteLater/tempSheet.eps', Options = saveOpts)

这是我无法理解的 illustrator_ref 代码:

# This CoClass is known by the name 'Illustrator.EPSSaveOptions.24'
class EPSSaveOptions(CoClassBaseClass): # A CoClass
    # Options which may be supplied when saving a document as an Illustrator EPS file
    CLSID = IID('{99D7941A-05F9-419A-BA50-4C6148B54187}')
    coclass_sources = [
    ]
    coclass_interfaces = [
        _EPSSaveOptions,
    ]
    default_interface = _EPSSaveOptions

class _EPSSaveOptions(DispatchBaseClass):
    'Options which may be supplied when saving a document as an Illustrator EPS file'
    CLSID = IID('{95CD20A7-AD72-11D3-B086-0010A4F5C335}')
    coclass_clsid = IID('{99D7941A-05F9-419A-BA50-4C6148B54187}')

    def SetObjectValue(self, arg0=defaultUnnamedArg):
        return self._oleobj_.InvokeTypes(0, LCID, 8, (24, 0), ((9, 0),),arg0
            )

    _prop_map_get_ = {
        # Method 'Application' returns object of type '_Application'
        "Application": (1667330160, 2, (9, 0), (), "Application", '{95CD20AA-AD72-11D3-B086-0010A4F5C335}'),
        "ArtboardRange": (1884304483, 2, (8, 0), (), "ArtboardRange", None),
        "CMYKPostScript": (1883459667, 2, (11, 0), (), "CMYKPostScript", None),
        "Compatibility": (1883849584, 2, (3, 0), (), "Compatibility", None),
        "CompatibleGradientPrinting": (1883457360, 2, (11, 0), (), "CompatibleGradientPrinting", None),
        "EmbedAllFonts": (1883586886, 2, (11, 0), (), "EmbedAllFonts", None),
        "EmbedLinkedFiles": (1883861065, 2, (11, 0), (), "EmbedLinkedFiles", None),
        "FlattenOutput": (1884243564, 2, (3, 0), (), "FlattenOutput", None),
        "IncludeDocumentThumbnails": (1883849588, 2, (11, 0), (), "IncludeDocumentThumbnails", None),
        "JapaneseFileFormat": (1883924070, 2, (11, 0), (), "JapaneseFileFormat", None),
        "Overprint": (1883131728, 2, (3, 0), (), "Overprint", None),
        "PostScript": (1884312428, 2, (3, 0), (), "PostScript", None),
        "Preview": (1634291798, 2, (3, 0), (), "Preview", None),
        "SaveMultipleArtboards": (1397571938, 2, (11, 0), (), "SaveMultipleArtboards", None),
    }
    _prop_map_put_ = {
        "ArtboardRange": ((1884304483, LCID, 4, 0),()),
        "CMYKPostScript": ((1883459667, LCID, 4, 0),()),
        "Compatibility": ((1883849584, LCID, 4, 0),()),
        "CompatibleGradientPrinting": ((1883457360, LCID, 4, 0),()),
        "EmbedAllFonts": ((1883586886, LCID, 4, 0),()),
        "EmbedLinkedFiles": ((1883861065, LCID, 4, 0),()),
        "FlattenOutput": ((1884243564, LCID, 4, 0),()),
        "IncludeDocumentThumbnails": ((1883849588, LCID, 4, 0),()),
        "JapaneseFileFormat": ((1883924070, LCID, 4, 0),()),
        "ObjectValue": ((0, LCID, 4, 0),()),
        "Overprint": ((1883131728, LCID, 4, 0),()),
        "PostScript": ((1884312428, LCID, 4, 0),()),
        "Preview": ((1634291798, LCID, 4, 0),()),
        "SaveMultipleArtboards": ((1397571938, LCID, 4, 0),()),
    }
    # Default method for this class is 'ObjectValue'
    def __call__(self, arg0=defaultUnnamedArg):
        return self._oleobj_.InvokeTypes(0, LCID, 8, (24, 0), ((9, 0),),arg0
            )

    def __unicode__(self, *args):
        try:
            return unicode(self.__call__(*args))
        except pythoncom.com_error:
            return repr(self)
    def __str__(self, *args):
        return str(self.__unicode__(*args))
    def __int__(self, *args):
        return int(self.__call__(*args))
    def __iter__(self):
        "Return a Python iterator for this object"
        try:
            ob = self._oleobj_.InvokeTypes(-4,LCID,3,(13, 10),())
        except pythoncom.error:
            raise TypeError("This object does not support enumeration")
        return win32com.client.util.Iterator(ob, None)

如果您想尝试重现问题,可以在此处下载参考文件:https://github.com/lohriialo/illustrator-scripting-python/tree/master/api_reference

python-3.x typeerror pywin32 adobe-illustrator
1个回答
0
投票

如果您使用 win32com.client 中的 Dispatch 方法,并且知道您正在使用的对象的名称,您可以在 python 中创建 illustrator 对象,并将它们与其他对象一样对待。这是我编写的一个简单程序,在 python 3.12.0 和 Win 10 中运行,它展示了它是如何完成的,希望这有所帮助:

#!/usr/bin/env python3
import os
import win32com.client as win32
from win32com.client import constants as win_const

"""
Module Docstring
"""

__author__ = "Jonathan M."
__version__ = "0.1.0"
__license__ = "MIT"

def main():
    """ Main entry point of the app """

    PATH_MAPPING = {
        "input_path" : r"-PUT YOUR INPUT PATH HERE-",
        "output_path" : r"-PUT YOUR OUTPUT PATH HERE-"
        }
    
    print("Starting")
    # Grab the Adobe Illustrator Application.
    try:
        adobe_app = win32.GetActiveObject("Illustrator.Application")
    except:
        adobe_app = win32.gencache.EnsureDispatch("Illustrator.Application")
        adobe_app.UserInteractionLevel = -1 #set DONTDISPLAYALERT flag
    
    for file_to_convert in os.listdir(PATH_MAPPING["input_path"]):
    
        adobe_app.Open(os.path.join(PATH_MAPPING["input_path"], file_to_convert))
        adobe_doc = adobe_app.ActiveDocument
        
        filename, extension = os.path.splitext(file_to_convert)
        
        #we don't need to specify a file extension, illustrator will do that for us
        save_as_path = os.path.join(PATH_MAPPING["output_path"], f"{filename}")
        
        save_options = win32.Dispatch("Illustrator.epsSaveOptions")
        save_options.EmbedAllFonts = True
        save_options.SaveMultipleArtboards = True
        
        adobe_doc.SaveAs(save_as_path, save_options)

        #Close the document without saving
        adobe_doc.Close(win_const.aiDoNotSaveChanges)
    
    if adobe_app is not None:
        try:
            adobe_app.Application.Quit()
        except Exception as err:
            os.system("taskkill /f /im  Illustrator.exe")
    
    print("Done")


if __name__ == "__main__":
    """ This is executed when run from the command line """
    main()
© www.soinside.com 2019 - 2024. All rights reserved.