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

Tho*_*ann 2 pdf encryption macos

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

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

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

我有哪些选择?

ben*_*ggy 5

如果您已经熟悉 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)
Run Code Online (Sandbox Code Playgroud)