我对以编程方式将 Excel 电子表格/工作簿转换为 PDF 文件感兴趣。其他人已经提出并回答了这个问题(参见 How to convert Word and Excel documents to PDF programmatically? 和 convert excel to pdf in python ),但这些都没有做我想做的事情:
在我看来,一个简单的方法应该是使用 MacOS 内置的“快速查看”系统。 MacOS 有预览任何文档的方法(在 Finder 中选择它并按下空格)。它还具有将内容转换为 PDF 的方法。应该有一种方法可以使用 Apple 内置的关于如何渲染 XLS 和 XLSX 文件的知识。我只是不知道如何从命令行使用 QuickLook 以及如何让它生成 PDF 输出到文件。
Apple 确实提供了一个名为
qlmanage
的程序可用于以编程方式生成 HTML 文件和 PNG,但它生成一组 HTML 文件,而不是 PDF 文件。
最佳答案
好吧,我想出了一个解决方案,涉及使用 qlmanage
和 wkhtmltopdf
.基本上,我运行 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/