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

使用PyMuPDF嵌入JS到PDF遇错误:Page无write_javascript属性

解决方案:AttributeError: 'Page' object has no attribute 'write_javascript'

核心问题

PyMuPDF(即fitz库)的Page对象并不存在write_javascript方法,你错误调用了不存在的页面级方法。PDF的JavaScript通常需添加到整个文档(全局),或绑定到页面的特定动作(如页面打开事件)。

修正步骤及完整代码

1. 调整JS添加逻辑

使用文档对象的set_js()方法添加全局JavaScript,同时修正原代码中的其他错误:

  • 原JS代码末尾错误混入Python函数调用,需移出JS字符串
  • 直接引用外部图片hidden.jpg无效,需先将图片嵌入为PDF附件,再通过PDF的JS API读取

2. 完整可运行代码

import fitz

def embed_image_and_js(pdf_file_path, image_path, output_path):
    doc = fitz.open(pdf_file_path)
    
    # 将图片嵌入为PDF附件
    with open(image_path, "rb") as img_file:
        img_data = img_file.read()
        doc.add_file("hidden.jpg", img_data)
    
    # 适配PDF环境的JavaScript代码(基于Acrobat API)
    js_code = '''
    function openImageAfterDelay() {
        var attachment = this.getAttachment("hidden.jpg");
        if (attachment) {
            var img = this.addImage(attachment.data);
            // 切换到第一页并替换内容为图片
            this.pageNum = 1;
            this.deletePages(1, this.numPages);
            var page = this.newPage();
            page.addImage(img, 0, 0, page.mediaBox.width, page.mediaBox.height);
        }
    }
    // 文档打开后延迟3秒执行
    setTimeout(openImageAfterDelay, 3000);
    '''
    
    # 给文档添加全局JavaScript
    doc.set_js(js_code)
    
    doc.save(output_path)
    doc.close()

# 替换为你的实际文件路径
pdf_file_path = 'original.pdf'
image_path = 'hidden.jpg'
output_path = 'modified.pdf'

embed_image_and_js(pdf_file_path, image_path, output_path)

关键说明

  • doc.set_js():PyMuPDF中给整个PDF文档添加全局JavaScript的正确方法
  • doc.add_file():将图片嵌入为PDF附件,确保JS能在PDF内部访问到图片资源
  • PDF的JS环境基于Acrobat API而非浏览器DOM,需用this(代表当前PDF文档对象)的方法操作页面和图片,不能使用document.body这类浏览器API

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 13:07:36