You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用Adobe InDesign 2024+ JSX脚本报错求助

问题描述

尝试通过Python调用Adobe InDesign 2024或更高版本执行JSX脚本,参考旧版本示例代码编写测试脚本后,运行报错。

原测试代码:

import win32com.client

def create_indesign_document_with_text():
    try:
        # Initialize COM
        print("Initializing COM...")
        app = win32com.client.Dispatch('InDesign.Application')

        # Create a new InDesign document
        print("Creating a new InDesign document...")
        doc = app.Documents.Add()

        # Define the text content
        text_content = ("This is a sample text with some bold and italic words. "
                        "The quick brown fox jumps over the lazy dog. " * 5)
        # Define text attributes
        bold_text = "This is bold text."
        italic_text = "This is italic text."

        # Create a text frame
        print("Adding a text frame with sample content...")
        page = doc.Pages.Item(1)
        text_frame = page.TextFrames.Add()
        text_frame.GeometricBounds = ["12.7mm", "12.7mm", "287mm", "200mm"]  # Adjust the bounds as needed

        # Add the main text content
        text_frame.Contents = text_content

        # Apply formatting to parts of the text
        # Note: InDesign uses 0-based index for characters
        text_range = text_frame.Characters
        text_range.Item(0).ChangeTextPreferences.appliedFont = app.Fonts.Item("Arial")
        text_range.Item(0).ChangeTextPreferences.fontStyle = "Bold"
        text_range.Item(0).ChangeTextPreferences.pointSize = 12

        # Apply bold formatting to a specific range
        bold_start = text_content.find(bold_text)
        bold_end = bold_start + len(bold_text)
        text_range.ItemByRange(bold_start, bold_end - 1).ChangeTextPreferences.fontStyle = "Bold"

        # Apply italic formatting to a specific range
        italic_start = text_content.find(italic_text)
        italic_end = italic_start + len(italic_text)
        text_range.ItemByRange(italic_start, italic_end - 1).ChangeTextPreferences.fontStyle = "Italic"

        # Save the InDesign document
        save_path = r'INDESIGN_FILE_PATH'
        print(f"Saving the InDesign document to {save_path}...")
        doc.Save(save_path)

        # Call the JSX script
        jsx_script_path = r'JSX_FILE_PATH'
        print(f"Executing JSX script: {jsx_script_path}...")
        app.DoScript(jsx_script_path, 1246973031)  # Use ScriptLanguage.JAVASCRIPT

        print("Document created and script executed successfully.")

        # Close the document
        print("Closing the InDesign document without saving changes...")
        doc.Close(1)  # 1 means save changes

    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    create_indesign_document_with_text()

运行错误信息:

Initializing COM...
Creating a new InDesign document...
Adding a text frame with sample content...
An error occurred: (-2147352567, 'Exception occurred.',
 (30475, 'INDESIGN EXE PATH',  'The requested member of the collection does not exist.', None, 0, 0), None)
问题排查与修复方案

错误根源分析

  • 字符索引错误:InDesign的Characters集合采用1-based索引,原代码错误使用0-based(Item(0)),导致找不到对应成员。
  • 目标文本缺失:定义的bold_text和italic_text并未包含在text_content中,find()返回-1,后续ItemByRange使用无效索引触发报错。
  • ChangeTextPreferences用法错误:该对象用于全局文本修改偏好设置,不能直接通过单个Character对象赋值,应直接修改文本范围的属性。
  • 注释与代码矛盾:doc.Close(1)表示保存后关闭,但注释标注“不保存”,逻辑混乱。

修正后的代码

import win32com.client

def create_indesign_document_with_text():
    try:
        # Initialize COM
        print("Initializing COM...")
        app = win32com.client.Dispatch('InDesign.Application')

        # Create a new InDesign document
        print("Creating a new InDesign document...")
        doc = app.Documents.Add()

        # 修正:在文本内容中加入需要格式化的目标文本
        bold_text = "This is bold text."
        italic_text = "This is italic text."
        text_content = (f"This is a sample text with some bold and italic words. {bold_text} "
                        f"The quick brown fox jumps over the lazy dog. {italic_text} " * 5)

        # Create a text frame
        print("Adding a text frame with sample content...")
        # InDesign Pages集合是1-based索引,Item(1)正确
        page = doc.Pages.Item(1)
        text_frame = page.TextFrames.Add()
        # 修正:GeometricBounds使用数值(InDesign默认单位为点,12.7mm≈36pt)
        text_frame.GeometricBounds = [36, 36, 814, 567]

        # Add the main text content
        text_frame.Contents = text_content

        # Apply formatting to parts of the text
        # 修正:使用1-based索引获取字符范围,直接修改文本属性
        all_chars = text_frame.Characters
        # 设置第一个字符的格式(示例)
        first_char = all_chars.Item(1)
        first_char.appliedFont = app.Fonts.Item("Arial")
        first_char.fontStyle = "Bold"
        first_char.pointSize = 12

        # Apply bold formatting to a specific range
        bold_start = text_content.find(bold_text) + 1  # 转换为1-based索引
        bold_end = bold_start + len(bold_text) - 1
        bold_range = all_chars.ItemByRange(bold_start, bold_end)
        bold_range.fontStyle = "Bold"
        bold_range.appliedFont = app.Fonts.Item("Arial")

        # Apply italic formatting to a specific range
        italic_start = text_content.find(italic_text) + 1  # 转换为1-based索引
        italic_end = italic_start + len(italic_text) - 1
        italic_range = all_chars.ItemByRange(italic_start, italic_end)
        italic_range.fontStyle = "Italic"
        italic_range.appliedFont = app.Fonts.Item("Arial")

        # Save the InDesign document
        save_path = r'C:\test_indesign_document.indd'  # 替换为实际保存路径
        print(f"Saving the InDesign document to {save_path}...")
        doc.Save(save_path)

        # Call the JSX script
        jsx_script_path = r'C:\test_script.jsx'  # 替换为实际JSX路径
        print(f"Executing JSX script: {jsx_script_path}...")
        # ScriptLanguage.JAVASCRIPT的常量值为1246973031,正确
        app.DoScript(jsx_script_path, 1246973031)

        print("Document created and script executed successfully.")

        # Close the document
        print("Closing the InDesign document after saving changes...")
        doc.Close(1)  # 1 = 保存后关闭,修正注释

    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    create_indesign_document_with_text()

额外注意事项

  • 字体可用性:确保InDesign中已安装"Arial"字体,若未安装需替换为系统中存在的字体(如"宋体")。
  • 路径替换:需将save_path和jsx_script_path替换为实际的本地路径。
  • COM权限:运行Python脚本时需确保有足够权限访问InDesign COM接口,建议以管理员身份运行或关闭UAC限制。

内容的提问来源于stack exchange,提问作者user3391612

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 15:00:06