gpt4 book ai didi

macos - 如何以编程方式在 macOS 上加密 PDF 文件

转载 作者:行者123 更新时间:2023-12-04 16:08:09 24 4
gpt4 key购买 nike

我的软件使用内置 API (PDFKit) 生成 PDF 文件。

我现在需要以编程方式创建一个受密码保护(通过加密)的 PDF 文件。 PDFKit 似乎不支持这一点。

我曾希望可以使用 AppleScript 告诉 Preview 打开 PDF,然后使用密码保存它,但 Preview 的 AppleScript 字典似乎没有提供此选项。 p>

我有什么选择?

最佳答案

如果您已经熟悉 Apple 的 PDFKit API,那么加密 PDF 就非常容易。

使用 kCGPDFContextOwnerPasswordkCGPDFContextAllowsCopying 等项目的键/值创建辅助字典。然后使用 PDFDocumentwriteToFile:withOptions 方法。

https://developer.apple.com/documentation/pdfkit/pdfdocument/1436053-writetofile?language=objc

这是一个用于加密 PDF 的 Python 脚本,但将其转换为 Swift 或 ObjC 应该很容易。该字典名为“options”。

在命令行上,提供 PDF 的文件名作为参数。您还可以在 Automator“运行 Shell 脚本”操作中使用它。

#!/usr/bin/python
# coding: utf-8

import os, sys
from Quartz import PDFDocument, kCGPDFContextAllowsCopying, kCGPDFContextAllowsPrinting, kCGPDFContextUserPassword, kCGPDFContextOwnerPassword
from CoreFoundation import (NSURL)

copyPassword = "12345678" # Password for copying and printing
openPassword = copyPassword # Password to open the file.
# Set openPassword as '' to allow opening with no password.

def encrypt(filename):
filename =filename.decode('utf-8')
if not filename:
print 'Unable to open input file'
sys.exit(2)
shortName = os.path.splitext(filename)[0]
outputfile = shortName+" locked.pdf"
pdfURL = NSURL.fileURLWithPath_(filename)
pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL)
if pdfDoc :
options = {
kCGPDFContextAllowsCopying: False,
kCGPDFContextAllowsPrinting: False,
kCGPDFContextOwnerPassword: copyPassword,
kCGPDFContextUserPassword: openPassword}
pdfDoc.writeToFile_withOptions_(outputfile, options)
return

if __name__ == "__main__":
for filename in sys.argv[1:]:
encrypt(filename)

关于macos - 如何以编程方式在 macOS 上加密 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54672404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com