AppleScript PDFDocumentPermissions

CGPDFContextで暗号化とパスワード設定

【スクリプトエディタで開く】

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use framework "Quartz"
use framework "QuartzCore"
use framework "CoreGraphics"
use framework "WebKit"
use scripting additions


property refMe : a reference to current application
set appFileManager to refMe's NSFileManager's defaultManager()
set appShardWorkspace to refMe's NSWorkspace's sharedWorkspace()
set ocidFalse to (refMe's NSNumber's numberWithBool:false)
set ocidTrue to (refMe's NSNumber's numberWithBool:true)

set listAliasFilePath to {} as list

####何が前面か
tell application "System Events"
  set strAppTitile to title of (front process whose frontmost is true)
end tell
if strAppTitile is "プレビュー" then
  tell application "Preview"
    tell document 1
      set strFilePath to path as text
      close
    end tell
  end tell
  ###開いているファイルパスをリストに追加
  set aliasFilePath to POSIX file of strFilePath as alias
  copy aliasFilePath to end of listAliasFilePath
else if strAppTitile is "Acrobat Reader" then
  tell application id "com.adobe.Reader"
    activate
    ##ファイルパス
    tell active doc
      try
        set aliasFilePath to file alias
        log aliasFilePath
      on error
        set strMes to "エラー:ファイルが開いていません" as text
        display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
        return "ファイルが選ばれていません"
      end try
    end tell
  end tell
  ###開いているファイルパスをリストに追加
  copy aliasFilePath to end of listAliasFilePath
  tell application id "com.adobe.Reader"
    activate
    set objAvtivDoc to active doc
    tell objAvtivDoc
      set boolMode to modified
      ###変更箇所があるなら保存する
      if boolMode is true then
        save
      end if
    end tell
    close objAvtivDoc
  end tell
else
  ###ダイアログを前面に出す
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder"
      activate
    end tell
  else
    tell current application
      activate
    end tell
  end if
  set ocidUserDesktopPathArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
  set ocidUserDesktopPath to ocidUserDesktopPathArray's objectAtIndex:0
  set listChooseFileUTI to {"com.adobe.pdf"}
  set strPromptText to "PDFファイルを選んでください" as text
  set listAliasFilePath to (choose file with prompt strPromptText default location (ocidUserDesktopPath as alias) of type listChooseFileUTI with invisibles and multiple selections allowed without showing package contents) as list
end if
####リストに格納されているファイルパスを数えて
set numCntFilePath to (count of listAliasFilePath) as integer
if numCntFilePath = 0 then
  set strMes to "エラー:ファイルが開いていません" as text
  display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
  return "ファイルが選ばれていません"
end if

#######################################
###書類の数だけ繰り返し
#######################################
repeat with itemAliasFilePath in listAliasFilePath
  set strFilePath to POSIX path of itemAliasFilePath as text
  set ocidFilePathStr to (refMe's NSString's stringWithString:strFilePath)
  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath
  set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath)
  #####PDFDocumentとして読み込み
  set ocidActivDoc to (refMe's PDFDocument's alloc()'s initWithURL:ocidFilePathURL)
  ########################################
  #####暗号化チェック
  set boolEncrypted to ocidActivDoc's isEncrypted()
  if boolEncrypted is true then
    set strMes to "エラー:すでに暗号化されているので変更できません" as text
    display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
    return strMes
  end if
  ########################################
  #####ロック確認
  set boolLocked to ocidActivDoc's isLocked()
  if boolLocked is true then
    set strMes to "エラー:すでにパスワードでロックされているので変更できません" as text
    display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
    return strMes
  end if
  ####ファイルパス
  set ocidFileName to ocidFilePathURL's lastPathComponent()
  set strFileName to ocidFileName as text
  set coidBaseFileName to ocidFileName's stringByDeletingPathExtension()
  set ocidContainerDirURL to ocidFilePathURL's URLByDeletingLastPathComponent()
  set ocidDistFolderURL to (ocidContainerDirURL's URLByAppendingPathComponent:coidBaseFileName)
  ####ファイル移動先
  set ocidAttrDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
  (ocidAttrDict's setValue:511 forKey:(refMe's NSFilePosixPermissions))
  set listResults to (appFileManager's createDirectoryAtURL:ocidDistFolderURL withIntermediateDirectories:true attributes:ocidAttrDict |error|:(reference))
  ########################################
  #####パスワード生成 UUIDを利用
  set strTextFileName to strFileName & ".pw.txt"
  set ocidTextFilePathURL to (ocidDistFolderURL's URLByAppendingPathComponent:strTextFileName)
  #####生成したUUIDからハイフンを取り除く
  set ocidUUIDString to (refMe's NSMutableString's alloc()'s initWithCapacity:0)
  set ocidConcreteUUID to refMe's NSUUID's UUID()
  (ocidUUIDString's setString:(ocidConcreteUUID's UUIDString()))
  set ocidUUIDRange to (ocidUUIDString's rangeOfString:ocidUUIDString)
  (ocidUUIDString's replaceOccurrencesOfString:("-") withString:("") options:(refMe's NSRegularExpressionSearch) range:ocidUUIDRange)
  set strOwnerPassword to ocidUUIDString as text
  set strTextFile to "所有者用Pw\n" & strOwnerPassword & "\n\n" as text
  #####生成したUUIDからハイフンを取り除く
  set ocidUUIDString to (refMe's NSMutableString's alloc()'s initWithCapacity:0)
  set ocidConcreteUUID to refMe's NSUUID's UUID()
  (ocidUUIDString's setString:(ocidConcreteUUID's UUIDString()))
  set ocidUUIDRange to (ocidUUIDString's rangeOfString:ocidUUIDString)
  (ocidUUIDString's replaceOccurrencesOfString:("-") withString:("") options:(refMe's NSRegularExpressionSearch) range:ocidUUIDRange)
  set strUserPassword to ocidUUIDString as text
  set strTextFile to strTextFile & "利用者用(他者に教える場合はこちら)Pw\n" & strUserPassword & "\n" as text
  set ocidPWString to (refMe's NSString's stringWithString:strTextFile)
  set ocidUUIDData to (ocidPWString's dataUsingEncoding:(refMe's NSUTF8StringEncoding))
  set boolResults to (ocidUUIDData's writeToURL:ocidTextFilePathURL atomically:true)
  ########################################
  #####OPTION
  set ocidOptionDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
  ########################################
  #####通常はこの方法でアクセス権付与する
  ####(ocidOptionDict's setObject:strOwnerPassword forKey:(refMe's PDFDocumentOwnerPasswordOption))
  ####開封パスワード コメントアウトで開封パスワード無しになります
  ####  (ocidOptionDict's setObject:strUserPassword forKey:(refMe's PDFDocumentUserPasswordOption))
  #####PDFDocumentAccessPermissionsOption
  ####(*1*) PDFAllowsLowQualityPrinting 
  ####(*2*) refMe's PDFAllowsHighQualityPrinting
  ####(*4*) refMe's PDFAllowsDocumentChanges
  ####(*8*) refMe's PDFAllowsDocumentAssembly
  ####(*16*) refMe's PDFAllowsContentCopying
  ####(*32*) refMe's PDFAllowsContentAccessibility 
  ####(*64*) refMe's PDFAllowsCommenting 
  ####(*128*) refMe's PDFAllowsFormFieldEntry 
  ###全部禁止の場合は0
  ###(ocidOptionDict's setObject:0 forKey:(refMe's PDFDocumentAccessPermissionsOption))
  ###例 印刷OKの場合は2
  ##  (ocidOptionDict's setObject:0 forKey:(refMe's PDFDocumentAccessPermissionsOption))
  ########################################
  ####CGPDFContextで暗号化とパスワード設定する
  ###暗号化の深度デフォルトは40だって(8 between 40 and 128)
  (ocidOptionDict's setObject:(128 as number) forKey:"kCGPDFContextEncryptionKeyLength")
  ###印刷禁止-->コンテンツ:ページの抽出も出来ません
  (ocidOptionDict's setObject:ocidFalse forKey:"kCGPDFContextAllowsPrinting")
  ###コピー禁止
  (ocidOptionDict's setObject:ocidFalse forKey:"kCGPDFContextAllowsCopying")
  ###閲覧パスワードを付与する場合はコメント外す
  ###(ocidOptionDict's setObject:(strUserPassword as text) forKey:"kCGPDFContextUserPassword")
  ###所有者パスワード
  (ocidOptionDict's setObject:(strOwnerPassword as text) forKey:"kCGPDFContextOwnerPassword")
  
  ##################
  ###保存
  ##################
  set boolResults to (ocidActivDoc's writeToURL:ocidFilePathURL withOptions:ocidOptionDict)
  
  ###PDFファイル移動
  set ocidPdfFilePath to (ocidDistFolderURL's URLByAppendingPathComponent:ocidFileName)
  set listResults to (appFileManager's moveItemAtURL:ocidFilePathURL toURL:ocidPdfFilePath |error|:(reference))
  
  
end repeat


return
########################################
#### 開く  テキストエディットで開く場合
set strSaveRTFPath to ocidSaveRTFURL's |path|() as text
tell application "TextEdit"
  activate
  open (ocidSaveHTMLURL as alias)
  
  (* リッチテキストがいい場合はこっち
tell front document
save in strSaveRTFPath
end tell
tell front document
close
end tell
open ocidSaveRTFURL as alias
  *)
end tell

|

[PDF]パスワード暗号化設定してPWと一緒に保存

【スクリプトエディタで開く】

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use framework "PDFKit"
use framework "Quartz"
use framework "QuartzCore"
use scripting additions


property refMe : a reference to current application
set appFileManager to refMe's NSFileManager's defaultManager()
set appShardWorkspace to refMe's NSWorkspace's sharedWorkspace()

set listAliasFilePath to {} as list

####何が前面か
tell application "System Events"
  set strAppTitile to title of (front process whose frontmost is true)
end tell
if strAppTitile is "プレビュー" then
  tell application "Preview"
    tell document 1
      set strFilePath to path as text
      close
    end tell
  end tell
  ###開いているファイルパスをリストに追加
  set aliasFilePath to POSIX file of strFilePath as alias
  copy aliasFilePath to end of listAliasFilePath
else if strAppTitile is "Acrobat Reader" then
  tell application id "com.adobe.Reader"
    activate
    ##ファイルパス
    tell active doc
      try
        set aliasFilePath to file alias
        log aliasFilePath
      on error
        set strMes to "エラー:ファイルが開いていません" as text
        display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
        return "ファイルが選ばれていません"
      end try
    end tell
  end tell
  ###開いているファイルパスをリストに追加
  copy aliasFilePath to end of listAliasFilePath
  tell application id "com.adobe.Reader"
    activate
    set objAvtivDoc to active doc
    tell objAvtivDoc
      set boolMode to modified
      ###変更箇所があるなら保存する
      if boolMode is true then
        save
      end if
    end tell
    close objAvtivDoc
  end tell
else
  ###ダイアログを前面に出す
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder"
      activate
    end tell
  else
    tell current application
      activate
    end tell
  end if
  set ocidUserDesktopPathArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
  set ocidUserDesktopPath to ocidUserDesktopPathArray's objectAtIndex:0
  set listChooseFileUTI to {"com.adobe.pdf"}
  set strPromptText to "PDFファイルを選んでください" as text
  set listAliasFilePath to (choose file with prompt strPromptText default location (ocidUserDesktopPath as alias) of type listChooseFileUTI with invisibles and multiple selections allowed without showing package contents) as list
end if
####リストに格納されているファイルパスを数えて
set numCntFilePath to (count of listAliasFilePath) as integer
if numCntFilePath = 0 then
  set strMes to "エラー:ファイルが開いていません" as text
  display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
  return "ファイルが選ばれていません"
end if

#######################################
###書類の数だけ繰り返し
#######################################
repeat with itemAliasFilePath in listAliasFilePath
  set strFilePath to POSIX path of itemAliasFilePath as text
  set ocidFilePathStr to (refMe's NSString's stringWithString:strFilePath)
  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath
  set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath)
  #####PDFDocumentとして読み込み
  set ocidActivDoc to (refMe's PDFDocument's alloc()'s initWithURL:ocidFilePathURL)
  ########################################
  #####暗号化チェック
  set boolEncrypted to ocidActivDoc's isEncrypted()
  if boolEncrypted is true then
    set strMes to "エラー:すでに暗号化されているので変更できません" as text
    display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
    return strMes
  end if
  ########################################
  #####ロック確認
  set boolLocked to ocidActivDoc's isLocked()
  if boolLocked is true then
    set strMes to "エラー:すでにパスワードでロックされているので変更できません" as text
    display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
    return strMes
  end if
  ####ファイルパス
  set ocidFileName to ocidFilePathURL's lastPathComponent()
  set strFileName to ocidFileName as text
  set coidBaseFileName to ocidFileName's stringByDeletingPathExtension()
  set ocidContainerDirURL to ocidFilePathURL's URLByDeletingLastPathComponent()
  set ocidDistFolderURL to (ocidContainerDirURL's URLByAppendingPathComponent:coidBaseFileName)
  ####ファイル移動先
  set ocidAttrDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
  (ocidAttrDict's setValue:511 forKey:(refMe's NSFilePosixPermissions))
  set listResults to (appFileManager's createDirectoryAtURL:ocidDistFolderURL withIntermediateDirectories:true attributes:ocidAttrDict |error|:(reference))
  ########################################
  #####パスワード生成 UUIDを利用
  set strTextFileName to strFileName & ".pw.txt"
  set ocidTextFilePathURL to (ocidDistFolderURL's URLByAppendingPathComponent:strTextFileName)
  #####生成したUUIDからハイフンを取り除く
  set ocidUUIDString to (refMe's NSMutableString's alloc()'s initWithCapacity:0)
  set ocidConcreteUUID to refMe's NSUUID's UUID()
  (ocidUUIDString's setString:(ocidConcreteUUID's UUIDString()))
  set ocidUUIDRange to (ocidUUIDString's rangeOfString:ocidUUIDString)
  (ocidUUIDString's replaceOccurrencesOfString:("-") withString:("") options:(refMe's NSRegularExpressionSearch) range:ocidUUIDRange)
  set strOwnerPassword to ocidUUIDString as text
  set strTextFile to "所有者用Pw\n" & strOwnerPassword & "\n" as text
  #####生成したUUIDからハイフンを取り除く
  set ocidUUIDString to (refMe's NSMutableString's alloc()'s initWithCapacity:0)
  set ocidConcreteUUID to refMe's NSUUID's UUID()
  (ocidUUIDString's setString:(ocidConcreteUUID's UUIDString()))
  set ocidUUIDRange to (ocidUUIDString's rangeOfString:ocidUUIDString)
  (ocidUUIDString's replaceOccurrencesOfString:("-") withString:("") options:(refMe's NSRegularExpressionSearch) range:ocidUUIDRange)
  set strUserPassword to ocidUUIDString as text
  set strTextFile to strTextFile & "利用者用(他者に教える場合はこちら)Pw\n" & strUserPassword & "\n" as text
  set ocidPWString to (refMe's NSString's stringWithString:strTextFile)
  set ocidUUIDData to (ocidPWString's dataUsingEncoding:(refMe's NSUTF8StringEncoding))
  set boolResults to (ocidUUIDData's writeToURL:ocidTextFilePathURL atomically:true)
  ########################################
  #####OPTION
  set ocidOptionDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
  (ocidOptionDict's setObject:strOwnerPassword forKey:(refMe's PDFDocumentOwnerPasswordOption))
  ####開封パスワードなし
  ####(ocidOptionDict's setObject:strUserPassword forKey:(refMe's PDFDocumentUserPasswordOption))
  #####PDFDocumentAccessPermissionsOption
  (*
(*1*) PDFAllowsLowQualityPrinting 
(*2*) refMe's PDFAllowsHighQualityPrinting
(*4*) refMe's PDFAllowsDocumentChanges
(*8*) refMe's PDFAllowsDocumentAssembly
(*16*) refMe's PDFAllowsContentCopying
(*32*) refMe's PDFAllowsContentAccessibility 
(*64*) refMe's PDFAllowsCommenting 
(*128*) refMe's PDFAllowsFormFieldEntry 
例:全部OKの場合
  (ocidOptionDict's setObject:255 forKey:(refMe's PDFDocumentAccessPermissionsOption))
    ###印刷OKの場合は2
  (ocidOptionDict's setObject:3 forKey:(refMe's PDFDocumentAccessPermissionsOption))
*)
  ###印刷と注釈OK 1+64で65を設定
  (ocidOptionDict's setObject:65 forKey:(refMe's PDFDocumentAccessPermissionsOption))
  ##################
  ###保存
  ##################
  set boolResults to (ocidActivDoc's writeToURL:ocidFilePathURL withOptions:ocidOptionDict)
  
  ###PDFファイル移動
  set ocidPdfFilePath to (ocidDistFolderURL's URLByAppendingPathComponent:ocidFileName)
  set listResults to (appFileManager's moveItemAtURL:ocidFilePathURL toURL:ocidPdfFilePath |error|:(reference))
  
  
end repeat


|

PDFの暗号化を解除したPDFを作成する

要PDFの所有者パスワード
AppleScript単体では暗号化解除が難しそうなので
新しいドキュメントに全てのページコンテンツを入れて新規ドキュメントをつくっちゃう方法
(だから…暗号化を解除しているわけではない)



【スクリプトエディタで開く】

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.6"
use framework "Foundation"
use framework "PDFKit"
use framework "Quartz"
use scripting additions


property refMe : a reference to current application

set appFileManager to refMe's NSFileManager's defaultManager()
set appShardWorkspace to refMe's NSWorkspace's sharedWorkspace()

set ocidFalse to (refMe's NSNumber's numberWithBool:false)
set ocidTrue to (refMe's NSNumber's numberWithBool:true)


set listAliasFilePath to {} as list

####何が前面か
tell application "System Events"
  set strAppTitile to title of (front process whose frontmost is true)
end tell
if strAppTitile is "プレビュー" then
  tell application "Preview"
    tell document 1
      set strFilePath to path as text
      close
    end tell
  end tell
  ###開いているファイルパスをリストに追加
  set aliasFilePath to POSIX file of strFilePath as alias
  copy aliasFilePath to end of listAliasFilePath
else if strAppTitile is "Acrobat Reader" then
  tell application id "com.adobe.Reader"
    activate
    ##ファイルパス
    tell active doc
      try
        set aliasFilePath to file alias
        log aliasFilePath
      on error
        set strMes to "エラー:ファイルが開いていません" as text
        display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
        return "ファイルが選ばれていません"
      end try
    end tell
  end tell
  ###開いているファイルパスをリストに追加
  copy aliasFilePath to end of listAliasFilePath
  tell application id "com.adobe.Reader"
    activate
    set objAvtivDoc to active doc
    tell objAvtivDoc
      set boolMode to modified
      ###変更箇所があるなら保存する
      if boolMode is true then
        save
      end if
    end tell
    close objAvtivDoc
  end tell
else
  ###ダイアログを前面に出す
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder"
      activate
    end tell
  else
    tell current application
      activate
    end tell
  end if
  set ocidUserDesktopPathArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
  set ocidUserDesktopPath to ocidUserDesktopPathArray's objectAtIndex:0
  set listChooseFileUTI to {"com.adobe.pdf"}
  set strPromptText to "PDFファイルを選んでください" as text
  set aliasFilePath to (choose file with prompt strPromptText default location (ocidUserDesktopPath as alias) of type listChooseFileUTI without invisibles, multiple selections allowed and showing package contents) as alias
  ###ファイルパスをリストに追加
  copy aliasFilePath to end of listAliasFilePath
  
end if
####リストに格納されているファイルパスを数えて
set numCntFilePath to (count of listAliasFilePath) as integer
if numCntFilePath = 0 then
  set strMes to "エラー:ファイルが開いていません" as text
  display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
  return "ファイルが選ばれていません"
else
  set aliasIconPath to POSIX file "/System/Applications/Preview.app/Contents/Resources/AppIcon.icns" as alias
  set strResponse to "PDFの所有者の暗号化解除パスワード" as text
  try
    set recordResponse to (display dialog strResponse with title "パスワード入力" default answer strResponse buttons {"OK", "キャンセル"} default button "OK" cancel button "キャンセル" with icon aliasIconPath giving up after 30 without hidden answer)
  on error
    log "エラーしました"
    return "エラーしました"
    error number -128
  end try
  if true is equal to (gave up of recordResponse) then
    return "時間切れですやりなおしてください"
    error number -128
  end if
  if "OK" is equal to (button returned of recordResponse) then
    set strPW to (text returned of recordResponse) as text
  else
    log "エラーしました"
    return "エラーしました"
    error number -128
  end if
end if


repeat with itemAliasFilePath in listAliasFilePath
  ###パス
  set strFilePath to POSIX path of itemAliasFilePath as text
  set ocidFilePathStr to (refMe's NSString's stringWithString:strFilePath)
  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath
  set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath isDirectory:false)
  ###拡張子とって
  set ocidBaseFilePath to ocidFilePathURL's URLByDeletingPathExtension()
  ###拡張子を取ったファイル名
  set strFileName to ocidBaseFilePath's lastPathComponent() as text
  ###保存用の新しいファイル名
  set strNewFileName to strFileName & ".decrypt" & ".pdf" as text
  ####元ファイルのコンテナ
  set ocidContainerDirURL to ocidFilePathURL's URLByDeletingLastPathComponent()
  ###コンテナに新しいファイル名追加して新しいファイルのURL
  set ocidSaveFilePathURL to (ocidContainerDirURL's URLByAppendingPathComponent:strNewFileName isDirectory:false)
  #####PDFDocumentとして読み込み
  set ocidActivDoc to (refMe's PDFDocument's alloc()'s initWithURL:ocidFilePathURL)
  (ocidActivDoc's unlockWithPassword:strPW)
  ###ページ数数えて
  set numCntAllPage to ocidActivDoc's pageCount() as integer
  ###新しいPDF
  set ocidNewDoc to refMe's PDFDocument's alloc()'s init()
  set numCntPageNo to 0 as integer
  ###元のPDFのペー数分繰り返し
  repeat numCntAllPage times
    ###元のページを取得して
    set ocidPdfPage to (ocidActivDoc's pageAtIndex:numCntPageNo)
    ####新しいPDFにインサート
    (ocidNewDoc's insertPage:ocidPdfPage atIndex:numCntPageNo)
    ###カウントアップ
    set numCntPageNo to numCntPageNo + 1 as integer
  end repeat
end repeat
set boolResults to (ocidNewDoc's writeToURL:ocidSaveFilePathURL)

|

[PDFKit]PDFにパスワードとアクセス権を設定する

【スクリプトエディタで開く】

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.6"
use framework "Foundation"
use framework "PDFKit"
use framework "Quartz"
use scripting additions


property refMe : a reference to current application

set objFileManager to refMe's NSFileManager's defaultManager()

set ocidFalse to (refMe's NSNumber's numberWithBool:false)
set ocidTrue to (refMe's NSNumber's numberWithBool:true)

##############################
#####ダイアログを前面に出す
##############################
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder"
    activate
  end tell
else
  tell current application
    activate
  end tell
end if
#######################################
#####ファイル選択ダイアログ
#######################################
###ダイアログのデフォルト
set ocidUserDesktopPath to (objFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set aliasDefaultLocation to ocidUserDesktopPath as alias
tell application "Finder"
end tell
set listChooseFileUTI to {"com.adobe.pdf"}
set strPromptText to "PDFファイルを選んでください" as text
set listAliasFilePath to (choose file with prompt strPromptText default location (aliasDefaultLocation) of type listChooseFileUTI with invisibles and multiple selections allowed without showing package contents) as list

#######################################
###ダイアログで選択した書類の数だけ繰り返し
#######################################
repeat with itemAliasFilePath in listAliasFilePath
  set strFilePath to POSIX path of itemAliasFilePath as text
  set ocidFilePathStr to (refMe's NSString's stringWithString:strFilePath)
  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath
  set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath isDirectory:false)
  set ocidBaseFilePath to ocidFilePathURL's URLByDeletingPathExtension()
  set strFileName to ocidBaseFilePath's lastPathComponent() as text
  
  set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
  
  #####PDFDocumentとして読み込み
  set ocidActivDoc to (refMe's PDFDocument's alloc()'s initWithURL:ocidFilePathURL)
  ########################################
  #####暗号化チェック
  set boolEncrypted to ocidActivDoc's isEncrypted()
  if boolEncrypted is true then
    log strFileName & "暗号化されています"
    return "暗号化されているので変更できません"
  end if
  ########################################
  #####ロック確認
  set boolLocked to ocidActivDoc's isLocked()
  if boolLocked is true then
    log strFileName & "パスワードでロックされています"
    return "パスワードでロックされているので変更できません"
  end if
  ########################################
  #####パスワード生成 UUIDを利用
  set strTextFileName to strFileName & ".pw.txt"
  set ocidTextFilePathURL to (ocidContainerDirPathURL's URLByAppendingPathComponent:strTextFileName)
  #####ファイルの中身
  set ocidConcreteUUID to refMe's NSUUID's UUID()
  set ocidUUIDString to ocidConcreteUUID's UUIDString()
  set strOwnerPassword to ocidUUIDString as text
  set strTextFile to "所有者用Pw\n" & strOwnerPassword & "\n" as text
  set ocidConcreteUUID to refMe's NSUUID's UUID()
  set ocidUUIDString to ocidConcreteUUID's UUIDString()
  set strUserPassword to ocidUUIDString as text
  set strTextFile to strTextFile & "利用者用(他者に教える場合はこちら)Pw\n" & strUserPassword & "\n" as text
  set ocidPWString to (refMe's NSString's stringWithString:strTextFile)
  
  
  set ocidUUIDData to (ocidPWString's dataUsingEncoding:(refMe's NSUTF8StringEncoding))
  #####パスワードを書いたテキストファイルを保存
  set boolResults to (ocidUUIDData's writeToURL:ocidTextFilePathURL atomically:true)
  ########################################
  #####OPTION
  set ocidOptionDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
  (ocidOptionDict's setObject:strOwnerPassword forKey:(refMe's PDFDocumentOwnerPasswordOption))
  (ocidOptionDict's setObject:strUserPassword forKey:(refMe's PDFDocumentUserPasswordOption))
  
  #####PDFDocumentAccessPermissionsOption
  (*
(*1*) PDFAllowsLowQualityPrinting 
(*2*) refMe's PDFAllowsHighQualityPrinting
(*4*) refMe's PDFAllowsDocumentChanges
(*8*) refMe's PDFAllowsDocumentAssembly
(*16*) refMe's PDFAllowsContentCopying
(*32*) refMe's PDFAllowsContentAccessibility 
(*64*) refMe's PDFAllowsCommenting 
(*128*) refMe's PDFAllowsFormFieldEntry 
*)
  ###全部禁止の場合は0
  (ocidOptionDict's setObject:0 forKey:(refMe's PDFDocumentAccessPermissionsOption))
  ###例 印刷OKの場合は2
  ##  (ocidOptionDict's setObject:3 forKey:(refMe's PDFDocumentAccessPermissionsOption))
  
  
  ##################
  ###保存
  ##################
  set boolResults to (ocidActivDoc's writeToURL:ocidFilePathURL withOptions:ocidOptionDict)
  
  
  ####解放
  set ocidActivDoc to ""
  set ocidDocAttrDict to ""
end repeat


return "処理終了"


|

[CGPDFContext] kCGPDFContextAllowsPrinting 印刷可の設定 

サンプルは印刷不可に設定します

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use framework "PDFKit"
use framework "Quartz"

use scripting additions

######ログ表示
doLogView()

property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSMutableString : a reference to refMe's NSMutableString
property refNSURL : a reference to refMe's NSURL
property refNSImage : a reference to refMe's NSImage
property refPDFDocument : a reference to refMe's PDFDocument
property refNSMutableDictionary : a reference to refMe's NSMutableDictionary

#####ここはご自分で設定してね
####今回はユーザーパスワードは使いません
###set strUserPassword to "1234"
###管理者パスワード
set strOwnerPassword to "4321"

####ダイアログで使うデフォルトロケーション
tell application "Finder"
set aliasDefaultLocation to (path to desktop folder from user domain) as alias
end tell

####UTIリスト PDFのみ
set listUTI to {"com.adobe.pdf"}

####ダイアログを出す
set aliasFilePath to (choose file with prompt "PDFファイルを選んでください" default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias


###ダイアログの戻り値をUNIXパスに
set strFilePath to POSIX path of aliasFilePath
log strFilePath
##NSStringのファイルパス
set ocidFilePath to refNSString's stringWithString:strFilePath
log ocidFilePath as text
log className() of ocidFilePath as text
###NSURLのファイルパス
set ocidFilePahtURL to refNSURL's fileURLWithPath:ocidFilePath
log ocidFilePahtURL as text
log className() of ocidFilePahtURL as text
##URLPDFドキュメントを格納
set ocidPdfDoc to refPDFDocument's alloc()'s initWithURL:ocidFilePahtURL
log ocidPdfDoc
log className() of ocidPdfDoc as text
###permissionsStatus
log ocidPdfDoc's permissionsStatus()
log ocidPdfDoc's isEncrypted()
log ocidPdfDoc's isLocked()
###Permission Properties
log ocidPdfDoc's allowsCopying()
log ocidPdfDoc's allowsPrinting()
log ocidPdfDoc's allowsCommenting()
log ocidPdfDoc's allowsContentAccessibility()
log ocidPdfDoc's allowsDocumentAssembly()
log ocidPdfDoc's allowsDocumentChanges()
log ocidPdfDoc's allowsFormFieldEntry()
#########設定する値をレコードで用意
set ocidPdfOption to {} as record
##set ocidPdfOption to ocidPdfOption & {PDFDocumentUserPasswordOption:strUserPassword}
set ocidPdfOption to ocidPdfOption & {PDFDocumentOwnerPasswordOption:strOwnerPassword}
###印刷出来ない設定
set ocidPdfOption to ocidPdfOption & {kCGPDFContextAllowsPrinting:false}
###値やテキスト等をコピー出来ない設定
set ocidPdfOption to ocidPdfOption & {kCGPDFContextAllowsCopying:false}
set ocidPdfOption to ocidPdfOption & {kCGPDFContextOwnerPassword:strOwnerPassword}
##set ocidPdfOption to ocidPdfOption & {kCGPDFContextUserPassword:strUserPassword}
log ocidPdfOption
log ocidPdfDoc's accessPermissions()


###上書き保存
set boolSaveJob to ocidPdfDoc's writeToURL:ocidFilePahtURL withOptions:ocidPdfOption
log boolSaveJob

#########################ログ表示
to doLogView()

tell application "System Events"
set listAppList to title of (every process where background only is false)
end tell
repeat with objAppList in listAppList
set strAppList to objAppList as text
if strAppList is "スクリプトエディタ" then
tell application "Script Editor"
if frontmost is true then
try
tell application "System Events" to click menu item "ログを表示" of menu "表示" of menu bar item "表示" of menu bar 1 of application process "Script Editor"
end try
end if
end tell
tell application "Script Editor"
tell application "System Events"
tell process "Script Editor"
tell window 1
tell splitter group 1
tell splitter group 1
tell group 1
tell checkbox "返された値"
set boolValue to value as boolean
end tell
if boolValue is false then
click checkbox "返された値"
end if
end tell
end tell
end tell
end tell
end tell
end tell
end tell
end if
end repeat

end doLogView
#########################

|

その他のカテゴリー

Acrobat Acrobat Annotation Acrobat Dialog Acrobat Form Acrobat JS Acrobat Open Acrobat Plugin Acrobat python Acrobat Reader Acrobat Sequ Acrobat Stamps Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin System Information Admin Tools Admin Users Admin Volumes Adobe Apple AppleScript AppleScript Guide AppleScript Accessibility AppleScript AppKit AppleScript Applications AppleScript AppStore AppleScript Archive AppleScript Attributes AppleScript Automator AppleScript AVAsset AppleScript AVconvert AppleScript AVFoundation AppleScript AVURLAsset AppleScript BackUp AppleScript Barcode AppleScript Bash AppleScript Basic AppleScript Basic Path AppleScript Bluetooth AppleScript BOX AppleScript Browser AppleScript Calendar AppleScript CD/DVD AppleScript Choose AppleScript Chrome AppleScript CIImage AppleScript CloudStorage AppleScript Color AppleScript com.apple.LaunchServices.OpenWith AppleScript Console AppleScript Contacts AppleScript CotEditor AppleScript CURL AppleScript current application AppleScript Date&Time AppleScript delimiters AppleScript Desktop AppleScript Device AppleScript Disk AppleScript do shell script AppleScript Dock AppleScript DropBox AppleScript eMail AppleScript Encode Decode AppleScript Error AppleScript EXIFData AppleScript ffmpeg AppleScript File AppleScript Finder AppleScript Firefox AppleScript Folder AppleScript Fonts AppleScript GIF AppleScript HTML AppleScript Icon AppleScript Illustrator AppleScript Image Events AppleScript Image2PDF AppleScript ImageOptim Applescript iWork AppleScript Javascript AppleScript Jedit AppleScript Json AppleScript Label AppleScript List AppleScript locationd AppleScript LRC AppleScript LSSharedFileList AppleScript m3u8 AppleScript MakePDF AppleScript Map AppleScript Math AppleScript Microsoft AppleScript Microsoft Edge AppleScript Microsoft Excel AppleScript Mobileconfig AppleScript Mouse AppleScript Movie AppleScript Music AppleScript NetWork AppleScript Notes AppleScript NSArray AppleScript NSBitmapImageRep AppleScript NSBundle AppleScript NSCFBoolean AppleScript NSCharacterSet AppleScript NSColor AppleScript NSColorList AppleScript NSData AppleScript NSDictionary AppleScript NSError AppleScript NSEvent AppleScript NSFileAttributes AppleScript NSFileManager AppleScript NSFont AppleScript NSFontManager AppleScript NSImage AppleScript NSIndex AppleScript NSKeyedArchiver AppleScript NSKeyedUnarchiver AppleScript NSLocale AppleScript NSMutableArray AppleScript NSMutableDictionary AppleScript NSMutableString AppleScript NSNotFound AppleScript NSNumber AppleScript NSOpenPanel AppleScript NSPasteboard AppleScript NSPDFImageRep AppleScript NSpoint AppleScript NSPredicate AppleScript NSRange AppleScript NSRegularExpression AppleScript NSRunningApplication AppleScript NSScreen AppleScript NSSize AppleScript NSString AppleScript NSStringCompareOptions AppleScript NSTask AppleScript NSTimeZone AppleScript NSURL AppleScript NSURL File AppleScript NSURLBookmark AppleScript NSURLComponents AppleScript NSURLResourceKey AppleScript NSUserDefaults AppleScript NSUUID AppleScript NSView AppleScript NSWorkspace AppleScript Numbers AppleScript OAuth AppleScript ObjC AppleScript OneDrive AppleScript Osax AppleScript PDF AppleScript PDFAnnotationWidget AppleScript PDFContext AppleScript PDFDisplayBox AppleScript PDFDocumentPermissions AppleScript PDFKit AppleScript PDFnUP AppleScript PDFOutline AppleScript Photos AppleScript Photoshop AppleScript Plist System Events AppleScript PostScript AppleScript prefPane AppleScript Preview AppleScript Python AppleScript QR AppleScript QR Decode AppleScript QuickLook AppleScript QuickTime AppleScript record AppleScript Regular Expression AppleScript Reminders AppleScript ReName AppleScript Repeat AppleScript RTF AppleScript Safari AppleScript SaveFile AppleScript ScreenCapture AppleScript ScreenSaver AppleScript Script Editor AppleScript Script Menu AppleScript Shortcuts AppleScript Shortcuts Events AppleScript Sort AppleScript Sound AppleScript Spotlight AppleScript SRT AppleScript StandardAdditions AppleScript stringByApplyingTransform AppleScript System Events AppleScript System Settings AppleScript TemporaryItems AppleScript Terminal AppleScript Text AppleScript Text CSV AppleScript Text TSV AppleScript TextEdit AppleScript Translate AppleScript Trash AppleScript Twitter AppleScript UI AppleScript Unit Conversion AppleScript UTType AppleScript valueForKeyPath AppleScript Video AppleScript VisionKit AppleScript Visual Studio Code AppleScript webarchive AppleScript webp AppleScript Wifi AppleScript XML AppleScript XML EPUB AppleScript XML OPML AppleScript XML Plist AppleScript XML RSS AppleScript XML SVG AppleScript XML TTML AppleScript XML webloc AppleScript YouTube AppleScript Zero Suppress Applications Barcode OnLine Tools CityCode Design iPhone List Logs lsappinfo Memo Music perl PlistBuddy pluginkit postalcode ReadMe SF Symbols character id SF Symbols Entity sips Skype Slack sqlite TCC Tools Typography Video Wacom zoom