excel - Mac : How to convert Excel (and other) file types to PDF programmatically

标签 excel macos pdf-generation xls

我对以编程方式将 Excel 电子表格/工作簿转换为 PDF 文件感兴趣。其他人已经提出并回答了这个问题(参见 How to convert Word and Excel documents to PDF programmatically?convert excel to pdf in python ),但这些都没有做我想做的事情:

  • 我想要一个不需要使用 Microsoft Office 的命令行工具。
  • 我希望它可以在 Mac 上运行。
  • 我希望它做完整的电子表格; Perl 解决方案只做常量。
  • 我想使用已经调试过的东西,而不是编写代码。

  • 在我看来,一个简单的方法应该是使用 MacOS 内置的“快速查看”系统。 MacOS 有预览任何文档的方法(在 Finder 中选择它并按下空格)。它还具有将内容转换为 PDF 的方法。应该有一种方法可以使用 Apple 内置的关于如何渲染 XLS 和 XLSX 文件的知识。我只是不知道如何从命令行使用 QuickLook 以及如何让它生成 PDF 输出到文件。

    Apple 确实提供了一个名为 qlmanage 的程序可用于以编程方式生成 HTML 文件和 PNG,但它生成一组 HTML 文件,而不是 PDF 文件。

    最佳答案

    好吧,我想出了一个解决方案,涉及使用 qlmanagewkhtmltopdf .基本上,我运行 qlmanage 来制作 HTML,并使用 wkhtmltopdf 将 HTML 转换为 PDF。不幸的是,HTML 页面是按或多或少的随机顺序生成的,所以我需要查看属性列表来确定将哪个页面放在哪里。幸运的是,在我的工作簿上,可以对页面进行排序。

    #!/usr/bin/python
    # 
    # convert an excel workbook to a PDF on a Mac
    #
    #
    from subprocess import Popen,call,PIPE
    import os, os.path, sys
    import xml.dom.minidom
    import plistlib
    
    if len(sys.argv)==1:
        print("Usage: %s filename.xls output.pdf" % sys.argv[0])
        exit(1)
    
    if os.path.exists("xdir"):
        raise RuntimeError,"xdir must not exists"
    os.mkdir("xdir")
    call(['qlmanage','-o','xdir','-p',sys.argv[1]])
    
    # Now we need to find the sheets and sort them.
    # This is done by reading the property list
    qldir = sys.argv[1] + ".qlpreview"
    propfile = open("%s/%s/%s" % ('xdir',qldir,'PreviewProperties.plist'))
    plist = plistlib.readPlist(propfile)
    attachments = plist['Attachments']
    sheets = []
    for k in attachments.keys():
        if k.endswith(".html"):
            basename = os.path.basename(k)
            fn = attachments[k]['DumpedAttachmentFileName']
            print("Found %s -> %s" % (basename,fn))
            sheets.append((basename,fn))
    sheets.sort()
    
    # Finally use wkhtmltopdf to generate the PDF output
    os.chdir("%s/%s" % ('xdir',qldir))
    cmd = ['wkhtmltopdf'];
    for (basename,fn) in  sheets:
        cmd.append(fn)
    cmd.append(sys.argv[2])
    call(cmd)
    os.chdir("../..")
    call(['/bin/rm','-rf','xdir'])
    

    关于excel - Mac : How to convert Excel (and other) file types to PDF programmatically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5274174/

    相关文章:

    c++ - Excel VBA C++ .dll

    java - 从 excel : suggestions for design or approach for better performance 批量加载 Hibernate

    excel - 是否可以创建一个不活动的新工作簿?

    objective-c - 使用 Cocoa 在 HDD 上下载并保存图像文件

    c - OS X : CMake ignores CMAKE_C_COMPILER

    python - "no module named PyPDF2"错误

    pdf-generation - IE 忽略八位字节流 - 如何强制下载?

    excel - 在用户窗体中编辑电子表格上的文本

    xcode - 包含来自 Xcode 上添加的框架的 header

    pdf-generation - wkhtmltopdf/tables/acrobat-reader 的 PDF 显示错误