AppleScript PDFKit

[PDF]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.8"
use framework "Foundation"
use framework "AppKit"
use framework "PDFKit"
use scripting additions

property refMe : a reference to current application

###ダイアログを前面に出す
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
############ デフォルトロケーション
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias

set listUTI to {"com.adobe.pdf"}
set strMes to ("PDFファイルを選んでください") as text
set strPrompt to ("PDFファイルを選んでください") as text
try
  ### ファイル選択時
  set aliasFilePath to (choose file strMes with prompt strPrompt default location (aliasDesktopDirPath) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
######
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
######
set strFilePath to (POSIX path of aliasFilePath) 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 ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
set aliasContainerDirPath to (ocidContainerDirPathURL's absoluteURL()) as alias

set strMes to "保存先フォルダを選んでください" as text
set strPrompt to "保存先フォルダを選択してください" as text
try
  set aliasSaveDirPath to (choose folder strMes with prompt strPrompt default location aliasContainerDirPath with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
set strSaveDirPath to (POSIX path of aliasSaveDirPath) as text
set ocidSaveDirPathStr to refMe's NSString's stringWithString:(strSaveDirPath)
set ocidSaveDirPath to ocidSaveDirPathStr's stringByStandardizingPath()

###NSDATAに読み込んでから
set ocidSaveDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSaveDirPath) isDirectory:false)
###
set ocidOption to (refMe's NSDataReadingMappedIfSafe)
set listReadData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidFilePathURL) options:(ocidOption) |error|:(reference)
if (item 2 of listReadData) ≠ (missing value) then
log (item 2 of listReadStings)'s localizedDescription() as text
return "PPDファイルの読み込みに失敗しました"
else
  set ocidReadData to (item 1 of listReadData)
end if
###PDFDocumentに読み込む
set ocidActiveDoc to refMe's PDFDocument's alloc()'s initWithData:(ocidReadData)
set numCntPage to ocidActiveDoc's pageCount()
###ページ数分々
repeat with itemIntNo from 0 to (numCntPage - 1) by 1
  #ページを取り出して
  set ocidActivePage to (ocidActiveDoc's pageAtIndex:(itemIntNo))
  #テキストを抽出
  set ocidPageText to ocidActivePage's |string|()
  #保存する
  set strSaveFileNameText to (itemIntNo & ".txt") as text
  set ocidSaveFilePathURLText to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileNameText) isDirectory:(false))
  set listDone to (ocidPageText's writeToURL:(ocidSaveFilePathURLText) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference))
  if (item 1 of listDone) is true then
log (itemIntNo + 1) & "ページ目:正常終了" as text
  else if (item 1 of listDone) is false then
log (item 2 of listDone)'s localizedDescription() as text
return (itemIntNo + 1) & "ページ目:保存に失敗しました" as text
  end if
  #アトリビュートテキストを抽出して
  set ocidPageAttarText to ocidActivePage's attributedString()
  #RTFデータに変換して
  set ocidAttarTextRange to refMe's NSMakeRange(0, ocidPageAttarText's |length|())
  set ocidAttarData to (ocidPageAttarText's RTFFromRange:(ocidAttarTextRange) documentAttributes:(missing value))
  #保存する
  set strSaveFileNameRtf to (itemIntNo & ".rtf") as text
  set ocidSaveFilePathURLRtf to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileNameRtf) isDirectory:(false))
  set ocidOption to (refMe's NSDataWritingAtomic)
  set listDone to (ocidAttarData's writeToURL:(ocidSaveFilePathURLRtf) options:(ocidOption) |error|:(reference))
  if (item 1 of listDone) is true then
log (itemIntNo + 1) & "ページ目:正常終了" as text
  else if (item 1 of listDone) is false then
log (item 2 of listDone)'s localizedDescription() as text
return (itemIntNo + 1) & "ページ目:保存に失敗しました" as text
  end if
  
end repeat




|

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.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

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 aliasFilePath to (choose file with prompt "PDFファイルを選んでください" default location (path to desktop folder from user domain) of type {"com.adobe.pdf"} with invisibles and showing package contents without multiple selections allowed) as alias

set strFilePath to (POSIX path of aliasFilePath) as text
set ocidFilePath to refMe's NSString's stringWithString:(strFilePath)
set ocidFilePathURL to refMe's NSURL's fileURLWithPath:(ocidFilePath)
####読み込み
set ocidActiveDoc to refMe's PDFDocument's alloc()'s initWithURL:(ocidFilePathURL)
#####暗号化チェック
set boolEncrypted to ocidActiveDoc's isEncrypted()
if boolEncrypted is true then
  set strMes to "エラー:" & (ocidFileName as text) & "は暗号化されています" as text
display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
return "暗号化されているので変更できません"
end if
#####ロック確認
set boolLocked to ocidActiveDoc's isLocked()
if boolLocked is true then
  set strMes to "エラー:" & (ocidFileName as text) & "はパスワードでロックされています" as text
display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
return "パスワードでロックされているので変更できません"
end if
####ページ数
set ocidPageCnt to ocidActiveDoc's pageCount()
##リストを作る
set ocidPageArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(ocidPageCnt)
repeat with itemIntNo from 1 to (ocidPageCnt - 0) by 1
(ocidPageArray's addObject:(itemIntNo))
end repeat
set listPageArray to ocidPageArray as list
set strTitle to "削除するページを選択(複数可)" as text
set strPrompt to "削除するページ番号を選択してください\r\r複数選択はコマンド⌘キーを押しながらクリック" as text

set listResponse to (choose from list listPageArray with title strTitle with prompt strPrompt default items (item 1 of listPageArray) OK button name "OK" cancel button name "キャンセル" with multiple selections allowed and empty selection allowed) as list
if listResponse = {} then
return "何も選択していないので処理中止しました"
else if (item 1 of listResponse) is false then
return "キャンセルしました"
else
log "削除処理実行します"
end if
##最後のページから処理するためリストを並び替える
set ocidDelPageArray to refMe's NSMutableArray's arrayWithArray:(listResponse)
#
set ocidDescriptorArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(false) selector:("compare:")
ocidDescriptorArray's addObject:(ocidDescriptor)
set ocidSortedArray to ocidDelPageArray's sortedArrayUsingDescriptors:(ocidDescriptorArray)

##################
#ダイアログを全面に
set strName to (name of current application) as text
#スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  #スクリプトエディタで実行
  tell current application to activate
end if
#
set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
set aliasSaveDirPath to (ocidContainerDirPathURL's absoluteURL()) as alias
#
set ocidBaseFilePathURL to ocidFilePathURL's URLByDeletingPathExtension()
set ocidBaseName to ocidBaseFilePathURL's lastPathComponent()
set ocidSaveFileName to ocidBaseName's stringByAppendingPathExtension:("処理済.pdf")
set strPromptText to "名前を決めてください" as text
set strMesText to "名前を決めてください" as text
###ファイル名 ダイアログ
set aliasSaveFilePath to (choose file name strMesText default location aliasSaveDirPath default name (ocidSaveFileName as text) with prompt strPromptText) as «class furl»
###パス
set strSaveFilePath to (POSIX path of aliasSaveFilePath) as text
set ocidSaveFilePathStr to refMe's NSString's stringWithString:(strSaveFilePath)
set ocidSaveFilePath to ocidSaveFilePathStr's stringByStandardizingPath()
set ocidSaveFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSaveFilePath) isDirectory:false)
set ocidSaveContainerDirPathURL to ocidSaveFilePathURL's URLByDeletingLastPathComponent()
###拡張子
set strSaveExtension to (ocidSaveFilePathURL's pathExtension()) as text
###最後のアイテムがファイル名
set strSaveFileName to (ocidSaveFilePathURL's lastPathComponent()) as text
###拡張子のつけ忘れ対策
if strSaveFileName does not contain "pdf" then
  set strSaveFileName to (strSaveFileName & ".pdf") as text
  set ocidSaveFilePathURL to ocidSaveContainerDirPathURL's URLByAppendingPathComponent:(strSaveFileName)
end if
###############
###本処理
###############
repeat with itemPageNo in ocidSortedArray
  set numPageNO to itemPageNo as integer
(ocidActiveDoc's removePageAtIndex:(numPageNO - 1))
end repeat
###############
###保存
###############
set ocidOptionDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidOptionDict's setValue:(missing value) forKey:(refMe's PDFDocumentOwnerPasswordOption))
(ocidOptionDict's setValue:(missing value) forKey:(refMe's PDFDocumentUserPasswordOption))
#(ocidOptionDict's setValue:(true) forKey:(refMe's PDFDocumentOptimizeImagesForScreenOption))
# (ocidOptionDict's setValue:(1) forKey:(refMe's PDFPageImageInitializationOptionCompressionQuality))
set boolDone to (ocidActiveDoc's writeToURL:(ocidSaveFilePathURL) withOptions:(ocidOptionDict))
ocidActiveDoc's release()

|

[PDFKit]暗号化 機能制限パスワードを設定する


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

#!/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 framework "CoreGraphics"
use scripting additions

property refMe : a reference to current application

####所有者パスワード
property boolOwnerPW : true as boolean
####アクアセス権
## property intAllowNo : 0 as integer
(*
例:全部OKの場合 255 全部ロックは0
許可する番号を『足し算』する
低解像度印刷 (*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
*)

on run
  ###ダイアログを前面に出す
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder" to activate
  else
    tell current application to activate
  end if
  set appFileManager to refMe's NSFileManager's defaultManager()
  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 listDropObject 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
open listDropObject
end run

on open listDropObject
  
  set recordOption to {|0開封PW付与|:999, |1低解像度印刷禁止|:1, |2高解像度印刷禁止|:2, |4文書に変更禁止|:4, |8内容変更禁止|:8, |16コンテンツコピー禁止|:16, |32補助装置利用禁止|:32, |64コメント注釈禁止|:64, |128フォーム入力禁止|:128} as record
  
  set ocidOptionDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidOptionDict's setDictionary:(recordOption)
  set ocidAllKeys to ocidOptionDict's allKeys()
  set ocidSortedArray to ocidAllKeys's sortedArrayUsingSelector:("localizedStandardCompare:")
  set listAllKeys to ocidSortedArray as list
  
  ##############################
  ###ダイアログを前面に出す
  tell current application
    set strName to name as text
  end tell
  ###スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder" to activate
  else
    tell current application to activate
  end if
  ###
  set strTitle to "『禁止設定する』オプション選択(複数可)" as text
  set strPrompt to "『禁止設定』するオプションを選択してください\r何も選択しない=全部許可\r何も選択しない場合所有者PWの設定とページ抽出とコンテンツの変更は禁止になります\r\r複数選択はコマンド⌘キーを押しながらクリック" as text
  try
    set listResponse to (choose from list listAllKeys with title strTitle with prompt strPrompt default items (item 1 of listAllKeys) OK button name "OK" cancel button name "キャンセル" with multiple selections allowed and empty selection allowed) as list
  on error
log "エラーしました"
return "エラーしました"
    error "エラーしました" number -200
  end try
  if listResponse = {} then
log "何も選択していない"
    set boolOpenPW to false as boolean
    set intAllowNo to 0 as integer
  else if (item 1 of listResponse) is false then
return "キャンセルしました"
    error "キャンセルしました" number -200
  else
    set boolOpenPW to false as boolean
    set intAllowNo to 0 as integer
    repeat with itemResponse in listResponse
      set intValue to (ocidOptionDict's valueForKey:(itemResponse)) as integer
      if intValue = 999 then
        set boolOpenPW to true as boolean
      else
        set intAllowNo to intAllowNo + intValue
      end if
    end repeat
  end if
  
  set intAllowNo to (255 - intAllowNo) as integer
  
  ###############################
  ##実際の処理するPDFのURLを格納するリスト
  set ocidDropPathURLArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
  ###ドロップされたエイリアスの数だけ繰り返し
  repeat with itemDropObject in listDropObject
    ###処理除外するエイリアスを判定する
    set strFilePaht to (POSIX path of itemDropObject) as text
    set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePaht))
    set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
    set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath))
    ###フォルダか?判定
    set listURLvalue to (ocidFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLIsDirectoryKey) |error|:(reference))
    set ocidURLvalue to (item 2 of listURLvalue)
    if ocidURLvalue = (refMe's NSNumber's numberWithBool:false) then
      set listURLvalue to (ocidFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLContentTypeKey) |error|:(reference))
      set strURLvalue to (item 2 of listURLvalue)'s identifier() as text
      ###getResourceValueの戻り値がNULLだった場合対策
      if strURLvalue is "" then
        tell application "Finder"
          set objInfo to info for aliasFilePath
          set strURLvalue to type identifier of objInfo as text
        end tell
      end if
      ###UTIがPDFのエイリアスだけ処理する
      if strURLvalue is "com.adobe.pdf" then
        #####PDFDocumentとして読み込み
        set ocidChkDoc to (refMe's PDFDocument's alloc()'s initWithURL:(ocidFilePathURL))
        ########################################
        #####暗号化チェック
        set boolEncrypted to ocidChkDoc's isEncrypted()
        if boolEncrypted is true then
          set strMes to "エラー:すでに暗号化されているので変更できません\n暗号化を解除してから再設定してください" as text
display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
return strMes
        end if
        ########################################
        #####ロック確認
        set boolLocked to ocidChkDoc's isLocked()
        if boolLocked is true then
          set strMes to "エラー:すでにパスワードでロックされているので変更できません\nパスワードでロックを解除してから再設定してください" as text
display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
return strMes
        end if
(ocidDropPathURLArray's addObject:(ocidFilePathURL))
      else
        set strMes to "エラー:PDF専用です" as text
display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
return strMes
      end if
    else
      set strMes to "エラー:PDF専用です" as text
display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
return strMes
    end if
  end repeat
  
  repeat with itemPathURL in ocidDropPathURLArray
    set ocidFileName to itemPathURL's lastPathComponent()
    set strBaseFileName to ocidFileName's stringByDeletingPathExtension() as text
    ###PW設定は複製したPDFに対して行うため保存先ディレクトリを作る
    set strDirName to (strBaseFileName & "_PW設定済")
    set ocidContainerDirURL to itemPathURL's URLByDeletingLastPathComponent()
    set ocidDistDirPathURL to (ocidContainerDirURL's URLByAppendingPathComponent:(strDirName) isDirectory:(true))
    #同名チェック
    set appFileManager to refMe's NSFileManager's defaultManager()
    set ocidDistDirPath to ocidDistDirPathURL's |path|()
    set boolDirExists to (appFileManager's fileExistsAtPath:(ocidDistDirPath) isDirectory:(true))
    if boolDirExists = true then
      repeat with itemIntNo from 1 to (100) by 1
        set strDirName to (strBaseFileName & "_PW設定済 " & itemIntNo)
        set ocidDistDirPathURL to (ocidContainerDirURL's URLByAppendingPathComponent:(strDirName) isDirectory:(true))
        set ocidDistDirPath to ocidDistDirPathURL's |path|()
        set boolExistsDir to (appFileManager's fileExistsAtPath:(ocidDistDirPath) isDirectory:(true))
        if boolExistsDir is false then
          exit repeat
        end if
      end repeat
    else if boolDirExists is false then
log "処理開始します"
    end if
  end repeat
  
  repeat with itemPathURL in ocidDropPathURLArray
    set ocidSavePdfURL to (ocidDistDirPathURL's URLByAppendingPathComponent:(ocidFileName))
    ####ファイル移動先
    set appFileManager to refMe's NSFileManager's defaultManager()
    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:(ocidDistDirPathURL) withIntermediateDirectories:true attributes:ocidAttrDict |error|:(reference))
    ####コピー
    set lisrBoolDone to (appFileManager's copyItemAtURL:(itemPathURL) toURL:(ocidSavePdfURL) |error|:(reference))
    #####PDFDocumentとして読み込み
    set ocidActivDoc to (refMe's PDFDocument's alloc()'s initWithURL:(ocidSavePdfURL))
    ########################################
    #####パスワード生成 UUIDを利用
    set strTextFileName to strBaseFileName & ".PassWord.txt"
    set ocidTextFilePathURL to (ocidDistDirPathURL'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
    if boolOpenPW is true then
      #####生成した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
    end if
    set ocidPWString to (refMe's NSString's stringWithString:strTextFile)
    set ocidUUIDData to (ocidPWString's dataUsingEncoding:(refMe's NSUTF8StringEncoding))
    ##PWをテキストで保存する
    set boolResults to (ocidUUIDData's writeToURL:ocidTextFilePathURL atomically:true)
    ########################################
    #####保存OPTION
    set ocidOptionDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
    if boolOwnerPW = true then
(ocidOptionDict's setObject:(strOwnerPassword) forKey:(refMe's PDFDocumentOwnerPasswordOption))
    end if
    if boolOpenPW = true then
      ####開封パスワード
(ocidOptionDict's setObject:(strUserPassword) forKey:(refMe's PDFDocumentUserPasswordOption))
    end if
    ###セキュリティ設定
(ocidOptionDict's setObject:(intAllowNo) forKey:(refMe's PDFDocumentAccessPermissionsOption))
    ##################
    ###保存
    ##################
    set boolResults to (ocidActivDoc's writeToURL:(ocidSavePdfURL) withOptions:(ocidOptionDict))
  end repeat
end open

|

[PDFkit]暗号化機能制限解除(所有者パスワードは必要) 修正しました


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

#!/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)


####何が前面か
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
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
  ###開いているファイルパスをリストに追加
  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
end if
###パス
set strFilePath to POSIX path of aliasFilePath 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)
#####PDFDocumentとして読み込み
set ocidActiveDoc to (refMe's PDFDocument's alloc()'s initWithURL:ocidFilePathURL)
###
set boolEnc to ocidActiveDoc's isEncrypted
if boolEnc = ocidFalse then
  set boolLock to ocidActiveDoc's isLocked
  if boolLock = ocidFalse then
return "暗号化もロックもされていません"
  end if
end if
########################
## クリップボードの中身取り出し
###初期化
set appPasteboard to refMe's NSPasteboard's generalPasteboard()
set ocidPastBoardTypeArray to appPasteboard's types
###テキストがあれば
set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
if boolContain = true then
  ###値を格納する
  tell application "Finder"
    set strResponse to (the clipboard as text) as text
  end tell
  ###Finderでエラーしたら
else
  set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
  if boolContain = true then
    set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
    set strResponse to ocidReadString as text
  else
log "テキストなし"
    set strResponse to "PDFの所有者の暗号化解除パスワード" as text
  end if
end if
try
  set aliasIconPath to POSIX file "/System/Applications/Preview.app/Contents/Resources/AppIcon.icns" as alias
  set recordResponse to (display dialog "PDFの所有者の暗号化解除パスワード" 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




###拡張子とって
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)

(ocidActiveDoc's unlockWithPassword:(strPW))
#必要なデータを取得
set ocidOutLine to ocidActiveDoc's outlineRoot()
set ocidAttribute to ocidActiveDoc's documentAttributes()
###新しいPDFへ↑のデータを付与
set ocidSaveDoc to refMe's PDFDocument's alloc()'s init()
(ocidSaveDoc's setOutlineRoot:(ocidOutLine))
(ocidSaveDoc's setDocumentAttributes:(ocidAttribute))
###ページ数数えて
set numCntAllPage to ocidActiveDoc's pageCount() as integer
##全ページ取得
repeat with itemIntNo from 0 to (numCntAllPage - 1) by 1
  #暗号化PDFからページを取り出して
  set ocidPDFpage to (ocidActiveDoc's pageAtIndex:(itemIntNo))
  #保存するPDFにセットしていく
(ocidSaveDoc's insertPage:(ocidPDFpage) atIndex:(itemIntNo))
end repeat

###保存する
set ocidOptionDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidOptionDict's setValue:(missing value) forKey:(refMe's PDFDocumentOwnerPasswordOption))
(ocidOptionDict's setValue:(missing value) forKey:(refMe's PDFDocumentUserPasswordOption))
#(ocidOptionDict's setValue:(true) forKey:(refMe's PDFDocumentOptimizeImagesForScreenOption))
# (ocidOptionDict's setValue:(1) forKey:(refMe's PDFPageImageInitializationOptionCompressionQuality))
set boolDone to (ocidSaveDoc's writeToURL:(ocidSaveFilePathURL) withOptions:(ocidOptionDict))
ocidActiveDoc's release()





|

ブランクのPDFを生成するmm指定 大きく変更


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
(*
ダイアログ部ベーススクリプト
https://www.macscripter.net/t/edit-db123s-dialog-for-use-with-asobjc/73636/2
*)
# 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 "Carbon"
use framework "PDFKit"
use framework "UniformTypeIdentifiers"
use scripting additions

property refMe : a reference to current application

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

##############################
#####ダイアログ
##############################
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 dialogResult to my doShowDialog()
if dialogResult is missing value then
return "【エラー】キャンセルしました"
end if
set strReturnW to (strOne of dialogResult) as text
set strReturnH to (strTwo of dialogResult) as text
#戻り値整形
set ocidReturnW to (refMe's NSString's stringWithString:(strReturnW))
set ocidReturnH to (refMe's NSString's stringWithString:(strReturnH))
###タブと改行を除去しておく
set ocidTextW to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
ocidTextW's appendString:(ocidReturnW)
set ocidTextH to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
ocidTextH's appendString:(ocidReturnH)
##改行除去
set ocidTextW to ocidTextW's stringByReplacingOccurrencesOfString:("\n") withString:("")
set ocidTextW to ocidTextW's stringByReplacingOccurrencesOfString:("\r") withString:("")
set ocidTextH to ocidTextH's stringByReplacingOccurrencesOfString:("\n") withString:("")
set ocidTextH to ocidTextH's stringByReplacingOccurrencesOfString:("\r") withString:("")
##タブ除去
set ocidTextW to ocidTextW's stringByReplacingOccurrencesOfString:("\t") withString:("")
set ocidTextH to ocidTextH's stringByReplacingOccurrencesOfString:("\t") withString:("")
####戻り値を半角にする
set ocidNSStringTransform to (refMe's NSStringTransformFullwidthToHalfwidth)
set ocidTextW to (ocidTextW's stringByApplyingTransform:ocidNSStringTransform |reverse|:false)
set ocidTextH to (ocidTextH's stringByApplyingTransform:ocidNSStringTransform |reverse|:false)
##カンマ置換
set ocidTextW to ocidTextW's stringByReplacingOccurrencesOfString:(",") withString:("")
set ocidTextH to ocidTextH's stringByReplacingOccurrencesOfString:(",") withString:("")
#計算用にNSDecimalNumberにする
set ocidW to refMe's NSDecimalNumber's alloc()'s initWithString:(ocidTextW)
set ocidH to refMe's NSDecimalNumber's alloc()'s initWithString:(ocidTextH)
###割り算
#フルニエ
# set ocidMMtoPT to refMe's NSDecimalNumber's alloc()'s initWithString:("0.34882")
#DITTO
# set ocidMMtoPT to refMe's NSDecimalNumber's alloc()'s initWithString:("0.375972")
#JIS
# set ocidMMtoPT to refMe's NSDecimalNumber's alloc()'s initWithString:("0.351460009")
#DTP
set ocidMMtoPT to refMe's NSDecimalNumber's alloc()'s initWithString:("0.3527777778")
set ocidFloatW to (ocidW's decimalNumberByDividingBy:(ocidMMtoPT))
set ocidFloatH to (ocidH's decimalNumberByDividingBy:(ocidMMtoPT))
###小数点4位まで
set ocidFormatter to refMe's NSNumberFormatter's alloc()'s init()
ocidFormatter's setRoundingMode:(refMe's NSNumberFormatterRoundFloor)
ocidFormatter's setNumberStyle:(refMe's NSNumberFormatterDecimalStyle)
ocidFormatter's setMaximumFractionDigits:(4)
set ocidRoundW to ocidFormatter's stringFromNumber:(ocidFloatW)
set ocidRoundH to ocidFormatter's stringFromNumber:(ocidFloatH)
###PT
set strPtW to ocidRoundW as text
set strPtH to ocidRoundH as text

###########################
###ダイアログを前面に出す
###########################
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 strDefaultName to "ファイル名.pdf" as text
set strExtension to "pdf"
set aliasDefaultLocation to (path to desktop folder from user domain) as alias
set strPromptText to "名前を決めてください" as text
set strMesText to "名前を決めてください" as text
set aliasFilePath to (choose file name strMesText default location aliasDefaultLocation default name strDefaultName with prompt strPromptText) as «class furl»
set strFilePath to (POSIX path of aliasFilePath) as text
###パスをリストにして
set AppleScript's text item delimiters to "/"
set listPathComponent to every text item of strFilePath
set AppleScript's text item delimiters to ""
####最後のアイテムがファイル名
set strFileName to (last item of listPathComponent) as text
###拡張子取っちゃった場合対応用
if strFileName does not contain strExtension then
  set strFileName to (strFileName & "." & strExtension) as text
end if
###保存先ファイルURL
set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath
set ocidFilePathURL to refMe's NSURL's fileURLWithPath:(ocidFilePath)

###########################
###PDFKIT本処理
###########################
####ドキュメントの初期化
set ocidActiveDoc to refMe's PDFDocument's alloc()'s init()
####メタデータ
set ocidAttributesDictionaryM to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
###タイトルはファイル名
ocidAttributesDictionaryM's setValue:(strFileName) forKey:"Title"
###作者はログインユーザー
set strUserName to (refMe's NSFullUserName()) as text
ocidAttributesDictionaryM's setValue:(strUserName) forKey:"Author"
set ocidActiveDoc's documentAttributes to ocidAttributesDictionaryM
####ページの初期化
set ocidPDFPage to refMe's PDFPage's alloc()'s init()
###メディアサイズ
set ocidMediaRect to refMe's CGRectMake(0, 0, strPtW, strPtH)
ocidPDFPage's setBounds:(ocidMediaRect) forBox:(refMe's kPDFDisplayBoxMediaBox)
ocidPDFPage's setBounds:(ocidMediaRect) forBox:(refMe's kPDFDisplayBoxBleedBox)
###CropとTrim
set ocidCropRect to refMe's CGRectMake(0, 0, strPtW, strPtH)
ocidPDFPage's setBounds:(ocidCropRect) forBox:(refMe's kPDFDisplayBoxCropBox)
ocidPDFPage's setBounds:(ocidCropRect) forBox:(refMe's kPDFDisplayBoxTrimBox)
###ARTBOXは本来指定しないが空のPDFなのでCROPと同値にする
ocidPDFPage's setBounds:(ocidCropRect) forBox:(refMe's kPDFDisplayBoxArtBox)
###PDFドキュメントにPDFページを挿入
ocidActiveDoc's insertPage:ocidPDFPage atIndex:0
ocidPDFPage's release()
###保存する
set ocidOptionDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidOptionDict's setValue:(missing value) forKey:(refMe's PDFDocumentOwnerPasswordOption)
ocidOptionDict's setValue:(missing value) forKey:(refMe's PDFDocumentUserPasswordOption)
ocidOptionDict's setValue:(true) forKey:(refMe's PDFDocumentOptimizeImagesForScreenOption)
ocidOptionDict's setValue:(1) forKey:(refMe's PDFPageImageInitializationOptionCompressionQuality)
set boolDone to ocidActiveDoc's writeToURL:(ocidFilePathURL) withOptions:(ocidOptionDict)
ocidActiveDoc's release()

return



####################################
###### ダイアログ
####################################
property appDialogWindow : missing value
property strOneTextField : missing value
property strTwoTextField : missing value
property appCancelButton : missing value
property appOkButton : missing value
property strOne : missing value
property strTwo : missing value
property appOkClicked : false
property refNSNotFound : a reference to 9.22337203685477E+18 + 5807

on doShowDialog()
  if refMe's AEInteractWithUser(-1, missing value, missing value) ≠ 0 then
return missing value
  end if
  if refMe's NSThread's isMainThread() then
my doPerformDialog:(missing value)
  else
its performSelectorOnMainThread:("doPerformDialog:") withObject:(missing value) waitUntilDone:true
  end if
  if my appOkClicked then
return {strOne:my strOne as text, strTwo:my strTwo as text}
  end if
return missing value
end doShowDialog

on doPerformDialog:(args)
  set strOneLabel to refMe's NSTextField's labelWithString:("幅(mm):")
strOneLabel's setFrame:(refMe's NSMakeRect(10, 85, 70, 20))
  
  set my strOneTextField to refMe's NSTextField's textFieldWithString:""
strOneTextField's setFrame:(refMe's NSMakeRect(87, 85, 245, 20))
strOneTextField's setEditable:true
strOneTextField's setBordered:true
strOneTextField's setPlaceholderString:("幅サイズmm")
  
  
  set strTwoLabel to refMe's NSTextField's labelWithString:("高(mm):")
strTwoLabel's setFrame:(refMe's NSMakeRect(10, 55, 70, 20))
  
  set my strTwoTextField to refMe's NSTextField's textFieldWithString:("")
strTwoTextField's setFrame:(refMe's NSMakeRect(87, 55, 245, 20))
strTwoTextField's setEditable:true
strTwoTextField's setBordered:true
strTwoTextField's setPlaceholderString:("高サイズmm")
strTwoTextField's setDelegate:(me)
  set my appCancelButton to refMe's NSButton's buttonWithTitle:"Cancel" target:me action:"doButtonAction:"
appCancelButton's setFrameSize:{94, 32}
appCancelButton's setFrameOrigin:{150, 10}
appCancelButton's setKeyEquivalent:(character id 27)
  
  set my appOkButton to refMe's NSButton's buttonWithTitle:"OK" target:me action:"doButtonAction:"
appOkButton's setFrameSize:{94, 32}
appOkButton's setFrameOrigin:{245, 10}
appOkButton's setKeyEquivalent:return
appOkButton's setEnabled:false
  
  set ocidWindowSize to refMe's NSMakeRect(0, 0, 355, 125)
  set ocidWinStyle to (refMe's NSWindowStyleMaskTitled as integer) + (refMe's NSWindowStyleMaskClosable as integer)
  set my appDialogWindow to refMe's NSWindow's alloc()'s initWithContentRect:(ocidWindowSize) styleMask:(ocidWinStyle) backing:(refMe's NSBackingStoreBuffered) defer:true
  
appDialogWindow's contentView()'s addSubview:(strOneLabel)
appDialogWindow's contentView()'s addSubview:(strOneTextField)
appDialogWindow's contentView()'s addSubview:(strTwoLabel)
appDialogWindow's contentView()'s addSubview:(strTwoTextField)
appDialogWindow's contentView()'s addSubview:(appCancelButton)
appDialogWindow's contentView()'s addSubview:(appOkButton)
  
appDialogWindow's setTitle:"サイズ指定mm"
appDialogWindow's setLevel:(refMe's NSModalPanelWindowLevel)
appDialogWindow's setDelegate:(me)
appDialogWindow's orderFront:(me)
appDialogWindow's |center|()
  
refMe's NSApp's activateIgnoringOtherApps:true
refMe's NSApp's runModalForWindow:(appDialogWindow)
end doPerformDialog:

on doButtonAction:(sender)
  if sender is my appOkButton then
    set my strOne to strOneTextField's stringValue()
    set my strTwo to strTwoTextField's stringValue()
    set my appOkClicked to true
  end if
my appDialogWindow's |close|()
end doButtonAction:

on controlTextDidChange:(objNotification)
  set sender to objNotification's object()
  if sender is my strTwoTextField then
    if sender's stringValue() as text ≠ "" then
my (appOkButton's setEnabled:true)
    else
my (appOkButton's setEnabled:false)
    end if
  end if
end controlTextDidChange:

on windowWillClose:(objNotification)
refMe's NSApp's stopModal()
end windowWillClose:


return



|

PDFの各ページをPDF内部の天地向きに回転させる


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

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

property refMe : a reference to current application

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

####何が前面か
tell application "System Events"
  set strAppTitile to title of (front process whose frontmost is true)
end tell
set listAliasFilePath to {}
###前面がプレビュー
if strAppTitile is "プレビュー" then
  tell application "Preview"
    tell front document
      set strFilePath to path as text
      set boolMode to modified
      ###変更箇所があるなら保存する
      if boolMode is true then
close saving yes
      else
close saving no
      end if
    end tell
  end tell
  set aliasFilePath to POSIX file strFilePath
  copy aliasFilePath to end of listAliasFilePath
  ###前面がリーダー
else if strAppTitile is "Acrobat Reader" then
  tell application id "com.adobe.Reader"
activate
    ##ファイルパス
    tell active doc
      set aliasFilePath to file alias
    end tell
  end tell
  set strFilePath to (POSIX path of aliasFilePath) as text
  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
  end tell
  copy aliasFilePath to end of listAliasFilePath
  ###それ以外ならダイアログ
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 aliasDefaultLocation to path to desktop folder from user domain as alias
  #ダイアログ
  set aliasFilePath to (choose file with prompt "PDFファイルを選んでください" default location aliasDefaultLocation of type {"com.adobe.pdf"} without multiple selections allowed, showing package contents and invisibles) as alias
end if
###パス処理
set strFilePath to (POSIX path of aliasFilePath) 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 ocidFileName to ocidFilePathURL's lastPathComponent()
set ocidBaseFileName to ocidFileName's stringByDeletingPathExtension() as text
###回転
set strTitle to ("選んでください") as text
set strPrompt to ("付与する回転を選んでください\nPDFの内部の天地向きを0として回転します\n0を選ぶとPDFページ内部の天地向になります\n90=右90度回転\n180=上下180回転\n270=左90度回転") as text
set listRotation to {0, 90, 180, 270} as list
try
  set listResponse to (choose from list listRotation with title strTitle with prompt strPrompt default items (item 1 of listRotation) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed) as list
on error
log "エラーしました"
return "エラーしました"
end try
if (item 1 of listResponse) is false then
return "キャンセルしましたA"
else if (item 1 of listResponse) is "キャンセル" then
return "キャンセルしましたB"
else
  set strResponse to (item 1 of listResponse) as text
end if

#### 保存先
set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
set aliasContainerDirPath to (ocidContainerDirPathURL's absoluteURL()) as alias
set ocidFileName to ocidFilePathURL's lastPathComponent()
set ocidBaseFileName to ocidFileName's stringByDeletingPathExtension()
set ocidSaveFileName to ocidBaseFileName's stringByAppendingPathExtension:("処理済.pdf")
set ocidSaveFilePathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:(ocidSaveFileName)
set strSaveFileName to ocidSaveFilePathURL's lastPathComponent() as text
set strPromptText to "名前を決めてください" as text
set strMesText to "名前を決めてください" as text
###ファイル名 ダイアログ
set aliasSaveFilePath to (choose file name strMesText default location aliasContainerDirPath default name strSaveFileName with prompt strPromptText) as «class furl»
###パス
set strSaveFilePath to (POSIX path of aliasSaveFilePath) as text
set ocidSaveFilePathStr to refMe's NSString's stringWithString:(strSaveFilePath)
set ocidSaveFilePath to ocidSaveFilePathStr's stringByStandardizingPath()
set ocidSaveFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSaveFilePath) isDirectory:false)
set ocidContainerSaveDirPathURL to ocidSaveFilePathURL's URLByDeletingLastPathComponent()
###拡張子
set strSaveExtension to (ocidSaveFilePathURL's pathExtension()) as text
###最後のアイテムがファイル名
set strSaveFileName to (ocidSaveFilePathURL's lastPathComponent()) as text
###拡張子のつけ忘れ対策
if strSaveFileName does not contain "pdf" then
  set strFileName to (strSaveFileName & ".pdf") as text
  set ocidSaveFilePathURL to ocidContainerSaveDirPathURL's URLByAppendingPathComponent:(strFileName)
end if
##

##########################
####PDFファイルを格納
set ocidActiveDoc to (refMe's PDFDocument's alloc()'s initWithURL:(ocidFilePathURL))
#####暗号化チェック
set boolEncrypted to ocidActiveDoc's isEncrypted()
if boolEncrypted is true then
  set strMes to "エラー:" & (ocidFileName as text) & "は暗号化されています" as text
display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
return "暗号化されているので変更できません"
end if
#####ロック確認
set boolLocked to ocidActiveDoc's isLocked()
if boolLocked is true then
  set strMes to "エラー:" & (ocidFileName as text) & "はパスワードでロックされています" as text
display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
return "パスワードでロックされているので変更できません"
end if
####ページ数
set numPageCnt to ocidActiveDoc's pageCount() as integer

repeat with itemIntNo from 0 to (numPageCnt - 1) by 1
  set ocidPdfPage to (ocidActiveDoc's pageAtIndex:(itemIntNo))
  set numNowRotation to ocidPdfPage's |rotation|()
(ocidPdfPage's setRotation:(strResponse as integer))
  
end repeat

#################################
###保存する
set ocidOptionDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidOptionDict's setValue:(missing value) forKey:(refMe's PDFDocumentOwnerPasswordOption)
ocidOptionDict's setValue:(missing value) forKey:(refMe's PDFDocumentUserPasswordOption)
set boolDone to ocidActiveDoc's writeToURL:(ocidSaveFilePathURL) withOptions:(ocidOptionDict)
set aliasSaveFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias
#################################
###開く
tell application "Preview"
open file aliasSaveFilePath
end tell
##################################
### インスペクタを表示
tell application "Preview"
activate
  tell application "System Events"
    tell process "Preview"
      try
click menu item "インスペクタを表示" of menu 1 of menu bar item "ツール" of menu bar 1
      on error
log "たぶん、インスペクタを表示済み"
      end try
    end tell
  end tell
end tell
return

|

PDF各ページの回転確認(全ページ対象)


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

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

property refMe : a reference to current application

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

####何が前面か
tell application "System Events"
  set strAppTitile to title of (front process whose frontmost is true)
end tell
set listAliasFilePath to {}
###前面がプレビュー
if strAppTitile is "プレビュー" then
  tell application "Preview"
    tell front document
      set strFilePath to path as text
      set boolMode to modified
      ###変更箇所があるなら保存する
      if boolMode is true then
close saving yes
      else
close saving no
      end if
    end tell
  end tell
  set aliasFilePath to POSIX file strFilePath
  copy aliasFilePath to end of listAliasFilePath
  ###前面がリーダー
else if strAppTitile is "Acrobat Reader" then
  tell application id "com.adobe.Reader"
activate
    ##ファイルパス
    tell active doc
      set aliasFilePath to file alias
    end tell
  end tell
  set strFilePath to (POSIX path of aliasFilePath) as text
  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
  end tell
  copy aliasFilePath to end of listAliasFilePath
  ###それ以外ならダイアログ
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 aliasDefaultLocation to path to desktop folder from user domain as alias
  #ダイアログ
  set aliasFilePath to (choose file with prompt "PDFファイルを選んでください" default location aliasDefaultLocation of type {"com.adobe.pdf"} without multiple selections allowed, showing package contents and invisibles) as alias
end if
###パス処理
set strFilePath to (POSIX path of aliasFilePath) 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)


##########################
####PDFファイルを格納
set ocidActiveDoc to (refMe's PDFDocument's alloc()'s initWithURL:(ocidFilePathURL))
set numPageCnt to ocidActiveDoc's pageCount() as integer
###出力用テキスト
set ocidOutPutString to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
(ocidOutPutString's appendString:("ページ番号"))
(ocidOutPutString's appendString:(": \t"))
(ocidOutPutString's appendString:("回転角度右"))
(ocidOutPutString's appendString:("\n"))
repeat with itemIntNo from 0 to (numPageCnt - 1) by 1
  set ocidPdfPage to (ocidActiveDoc's pageAtIndex:(itemIntNo))
  set numNowRotation to ocidPdfPage's |rotation|()
  set strSetValue to (itemIntNo + 1) as text
(ocidOutPutString's appendString:(strSetValue))
(ocidOutPutString's appendString:(": \t"))
(ocidOutPutString's appendString:(numNowRotation as text))
(ocidOutPutString's appendString:("\n"))
end repeat

####保存
###ディレクトリ
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidTempDirURL to appFileManager's temporaryDirectory()
set ocidUUID to refMe's NSUUID's alloc()'s init()
set ocidUUIDString to ocidUUID's UUIDString
set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:true
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)

###パス
set strFileName to "Rotation.text" as text
set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:false
set listDone to ocidOutPutString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
if (item 1 of listDone) is true then
log "正常終了"
  set aliasSaveFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias
else if (item 1 of listDone) is false then
log (item 2 of listDone)'s localizedDescription() as text
return "保存に失敗しました"
end if
###保存したテキストを表示

tell application "Finder"
open location aliasSaveFilePath
  
end tell



|

PDFファイル2つをマージする


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

#!/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 scripting additions

property refMe : a reference to current application

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



####通常はダイアログでファイルを選択
set aliasFilePathA to (choose file with prompt "マージされる側のPDFファイルを選んでください" default location (path to desktop folder from user domain) of type {"com.adobe.pdf"} with invisibles and showing package contents without multiple selections allowed) as alias
-->alias



####通常はダイアログでファイルを選択
set aliasFilePathB to (choose file with prompt "挿入する側のPDFファイルを選んでください" default location (path to desktop folder from user domain) of type {"com.adobe.pdf"} with invisibles and showing package contents without multiple selections allowed) as alias
-->alias


################################################
####【元A】ファイル
set strFilePathA to (POSIX path of aliasFilePathA) as text
set ocidFilePathA to refMe's NSString's stringWithString:(strFilePathA)
set ocidFilePathURLA to refMe's NSURL's fileURLWithPath:(ocidFilePathA)
set ocidFileName to ocidFilePathURLA's lastPathComponent
set strFileExtension to (ocidFilePathURLA's pathExtension) as text
set strPrefixName to (ocidFileName's stringByDeletingPathExtension) as text
####コンテナ
set ocidContainerDirPathURL to ocidFilePathURLA's URLByDeletingLastPathComponent()
set strAddFixName to ("_Merged") as text
set strSaveFileName to (strPrefixName & strAddFixName & "." & strFileExtension) as text
####保存先パス
set ocidSaveFilePathURL to (ocidContainerDirPathURL's URLByAppendingPathComponent:(strSaveFileName))
####【元】PDFファイルを格納
set ocidActiveDoc to refMe's PDFDocument's alloc()'s initWithURL:(ocidFilePathURLA)
####【元】ページ数を数える
set numCntPageActiveDoc to ocidActiveDoc's pageCount()

################################################
####【挿入B】マージするドキュメントのパスをNSString
set strFilePathB to (POSIX path of aliasFilePathB) as text
set ocidFilePathB to refMe's NSString's stringWithString:(strFilePathB)
set ocidFilePathURLB to refMe's NSURL's fileURLWithPath:(ocidFilePathB)
set ocidInsertDoc to refMe's PDFDocument's alloc()'s initWithURL:(ocidFilePathURLB)
####【挿入】マージページ数を数える
set numCntPageInsertDoc to ocidInsertDoc's pageCount()

################################################
###ページの挿入
repeat with itemIntNo from 0 to (numCntPageInsertDoc - 1) by 1
  #####ページをocidPdfPageObjに格納
  set ocidInsertPage to (ocidInsertDoc's pageAtIndex:itemIntNo)
  set numInsertPos to (numCntPageActiveDoc + itemIntNo) as integer
  ##インサート
(ocidActiveDoc's insertPage:(ocidInsertPage) atIndex:(numInsertPos))
end repeat

####保存
set ocidOptionDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidOptionDict's setValue:(missing value) forKey:(refMe's PDFDocumentOwnerPasswordOption))
(ocidOptionDict's setValue:(missing value) forKey:(refMe's PDFDocumentUserPasswordOption))
set boolDone to (ocidActiveDoc's writeToURL:(ocidSaveFilePathURL) withOptions:(ocidOptionDict))




|

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 appFileManager to refMe's NSFileManager's defaultManager()


##################################
#### 文書を開いているか?
##################################
####何が前面か
tell application "System Events"
  set strAppTitile to title of (front process whose frontmost is true)
end tell

set listAliasFilePath to {}
###前面がプレビュー
if strAppTitile is "プレビュー" then
  tell application "Preview"
    tell front document
      set strFilePath to path as text
      set boolMode to modified
      ###変更箇所があるなら保存する
      if boolMode is true then
close saving yes
      else
close saving no
      end if
    end tell
  end tell
  set aliasFilePath to POSIX file strFilePath
  copy aliasFilePath to end of listAliasFilePath
  ###前面がリーダー
else if strAppTitile is "Acrobat Reader" then
  tell application id "com.adobe.Reader"
activate
    ##ファイルパス
    tell active doc
      set aliasFilePath to file alias
    end tell
  end tell
  set strFilePath to (POSIX path of aliasFilePath) as text
  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
  copy aliasFilePath to end of listAliasFilePath
  ###それ以外ならダイアログ
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 ocidUserDesktopPath to (appFileManager'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 aliasFilePath to (choose file with prompt strPromptText default location (aliasDefaultLocation) of type listChooseFileUTI without invisibles, multiple selections allowed and showing package contents) as alias
end if

##############################
#####ダイアログを前面に出す
##############################
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 listChooser to {"JPEG", "PNG", "BMP", "TIFF"}
try
  set listResponse to (choose from list listChooser with title "選んでください" with prompt "書き出し形式" default items (item 2 of listChooser) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed)
on error
log "エラーしました"
return "エラーしました"
end try
if listResponse is false then
return "キャンセルしました"
end if
set strResponse to (item 1 of listResponse) as text
################################
###カラープロファイルを読み出しておく ファイルはお好みで
set strIccFilePath to "/System/Library/ColorSync/Profiles/sRGB Profile.icc"
set ocidIccFilePathStr to (refMe's NSString's stringWithString:strIccFilePath)
set ocidIccFilePath to ocidIccFilePathStr's stringByStandardizingPath
set ocidIccFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidIccFilePath isDirectory:false)
set ocidProfileData to refMe's NSData's alloc()'s initWithContentsOfURL:ocidIccFilePathURL

####まずはUNIXパスにして
set strFilePath to (POSIX path of aliasFilePath) 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)
####ファイル名を取得
set ocidFileName to ocidFilePathURL's lastPathComponent()
####ファイル名から拡張子を取っていわゆるベースファイル名を取得
set ocidPrefixName to ocidFileName's stringByDeletingPathExtension
####コンテナディレクトリを取得
set ocidContainerDirURL to ocidFilePathURL's URLByDeletingLastPathComponent()
########################
###保存先ディレクトリを作成
set strPrefixName to ocidPrefixName as text
###ディレクトリ名はお好みで
set ocidSaveDirName to (strPrefixName & "_images") as text
##保存先URL
set ocidSaveFileDirPathURL to (ocidContainerDirURL's URLByAppendingPathComponent:ocidSaveDirName isDirectory:true)
###フォルダ作成
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidAttrDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidAttrDict's setValue:511 forKey:(refMe's NSFilePosixPermissions))
set listBoolMakeDir to (appFileManager's createDirectoryAtURL:(ocidSaveFileDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference))
#####################
#### 本処理
#####################
####PDFファイルを格納
set ocidActivDoc to (refMe's PDFDocument's alloc()'s initWithURL:ocidFilePathURL)
####書き出し用のPDF
set ocidExpDoc to (refMe's PDFDocument's alloc()'s init())

####################################
####注釈削除
####ページ数
set numPageCnt to ocidActivDoc's pageCount() as integer
###ページ数カウンター
set numCntPageNoJs to 0 as number

repeat numPageCnt times
  ####PDFの対象ページを格納
  set ocidPdfPage to (ocidActivDoc's pageAtIndex:numCntPageNoJs)
(ocidPdfPage's setDisplaysAnnotations:true)
  ###アノテーション注釈を削除
  set ocidAnotationArray to ocidPdfPage's annotations()
  repeat with itemAnotationArray in ocidAnotationArray
(ocidPdfPage's removeAnnotation:itemAnotationArray)
  end repeat
(ocidPdfPage's setDisplaysAnnotations:false)
ocidPdfPage's removeAnnotation:ocidAnotationArray
ocidExpDoc's insertPage:ocidPdfPage atIndex:numCntPageNoJs
  
  set numCntPageNoJs to numCntPageNoJs + 1 as number
end repeat


###################################
####PDFDocumentとNSDataに変換して
set ocidDataRep to ocidExpDoc's dataRepresentation()
####NSdataに格納
set ocidReadPdfData to (refMe's NSData's alloc()'s initWithData:ocidDataRep)
####NSPDFImageRepに変換
set ocidPdfPep to (refMe's NSPDFImageRep's alloc()'s initWithData:ocidReadPdfData)
###ページ数数えて
set numPageCnt to ocidPdfPep's pageCount() as integer
###ページカウントの書き出しファイル用のページ番号
set numCntPageNo to 1 as integer
###ページカウントの初期値JS
set numCntPageNoJs to numCntPageNo - 1 as integer
####################
#####ページ数だけ繰り返し
####################
repeat numPageCnt times
  
  ####順番にページデータを読み出し
(ocidPdfPep's setCurrentPage:numCntPageNoJs)
  ####ページデータをNSIMAGEに格納
  set ocidPageImageData to refMe's NSImage's alloc()'s init()
(ocidPageImageData's addRepresentation:ocidPdfPep)
  ###中間ファイルとしてのTIFFに変換
  set ocidOsDispatchData to ocidPageImageData's TIFFRepresentation()
  ####出力されるBmpImageRepに格納
  set ocidBmpImageRep to (refMe's NSBitmapImageRep's imageRepWithData:ocidOsDispatchData)
  #############################
  #####変換設定 オプション設定
  #############################
  if strResponse is "JPEG" then
    ###可変レコードに
    set ocidPropertyDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
    ###各種値をキーでセットしておく
(ocidPropertyDict's setObject:1 forKey:(refMe's NSImageCompressionFactor))
    set ocidSetColor to refMe's NSColor's whiteColor()
(ocidPropertyDict's setObject:ocidSetColor forKey:(refMe's NSImageFallbackBackgroundColor))
(ocidPropertyDict's setObject:ocidProfileData forKey:(refMe's NSImageColorSyncProfileData))
    ####ファイルタイプの指定
    set ocidFileType to refMe's NSBitmapImageFileTypeJPEG
    ###パスで使う拡張子
    set strExtension to "jpg"
    
  else if strResponse is "PNG" then
    set ocidPropertyDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidPropertyDict's setObject:true forKey:(refMe's NSImageInterlaced))
    ####ガンマ値が不要な場合はコメントアウト
(ocidPropertyDict's setObject:0.45455 forKey:(refMe's NSImageGamma))
(ocidPropertyDict's setObject:ocidProfileData forKey:(refMe's NSImageColorSyncProfileData))
    set ocidFileType to refMe's NSBitmapImageFileTypePNG
    set strExtension to "png"
    
  else if strResponse is "BMP" then
    set ocidPropertyDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
    set ocidFileType to refMe's NSBitmapImageFileTypeBMP
    set strExtension to "bmp"
    
  else if strResponse is "TIFF" then
    set ocidPropertyDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidPropertyDict's setObject:1 forKey:(refMe's NSImageCompressionFactor))
(ocidPropertyDict's setObject:(refMe's NSTIFFCompressionNone) forKey:(refMe's NSImageCompressionMethod))
(ocidPropertyDict's setObject:ocidProfileData forKey:(refMe's NSImageColorSyncProfileData))
    set ocidFileType to refMe's NSBitmapImageFileTypeTIFF
    set strExtension to "tiff"
    
  end if
  ##########変換
  set ocidNSInlineData to (ocidBmpImageRep's representationUsingType:ocidFileType |properties|:ocidPropertyDict)
  
  ############################
  #########保存
  ###########################
  ###ページ数連番ゼロサプレス
  set strZeroAdd to ("0000" & numCntPageNo) as text
  set strPageNO to text -4 through -1 of strZeroAdd as text
  ###ファイル名に整形して
  set strSaveImageFileName to ("" & strPrefixName & "." & strPageNO & "." & strExtension & "") as text
  ####保存先URL
  set ocidSaveFilePathURL to (ocidSaveFileDirPathURL's URLByAppendingPathComponent:strSaveImageFileName isDirectory:false)
  #####保存
  set boolDone to (ocidNSInlineData's writeToURL:ocidSaveFilePathURL options:(refMe's NSDataWritingAtomic) |error|:(reference))
  
  #############カウントアップ
  set numCntPageNoJs to numCntPageNoJs + 1 as integer
  set numCntPageNo to numCntPageNo + 1 as integer
  ###データ解放
  set ocidNSInlineData to ""
  set ocidPageImageData to ""
  set ocidOsDispatchData to ""
  set ocidBmpImageRep to ""
end repeat


return "処理終了"



|

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 appFileManager to refMe's NSFileManager's defaultManager()


##################################
#### 文書を開いているか?
##################################
####何が前面か
tell application "System Events"
  set strAppTitile to title of (front process whose frontmost is true)
end tell

set listAliasFilePath to {}
###前面がプレビュー
if strAppTitile is "プレビュー" then
  tell application "Preview"
    tell front document
      set strFilePath to path as text
      set boolMode to modified
      ###変更箇所があるなら保存する
      if boolMode is true then
close saving yes
      else
close saving no
      end if
    end tell
  end tell
  set aliasFilePath to POSIX file strFilePath
  copy aliasFilePath to end of listAliasFilePath
  ###前面がリーダー
else if strAppTitile is "Acrobat Reader" then
  tell application id "com.adobe.Reader"
activate
    ##ファイルパス
    tell active doc
      set aliasFilePath to file alias
    end tell
  end tell
  set strFilePath to (POSIX path of aliasFilePath) as text
  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
  copy aliasFilePath to end of listAliasFilePath
  ###それ以外ならダイアログ
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 ocidUserDesktopPath to (appFileManager'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 aliasFilePath to (choose file with prompt strPromptText default location (aliasDefaultLocation) of type listChooseFileUTI without invisibles, multiple selections allowed and showing package contents) as alias
end if

##############################
#####ダイアログを前面に出す
##############################
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 listChooser to {"JPEG", "PNG", "BMP", "TIFF"}
try
  set listResponse to (choose from list listChooser with title "選んでください" with prompt "書き出し形式" default items (item 2 of listChooser) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed)
on error
log "エラーしました"
return "エラーしました"
end try
if listResponse is false then
return "キャンセルしました"
end if
set strResponse to (item 1 of listResponse) as text
################################
###カラープロファイルを読み出しておく ファイルはお好みで
set strIccFilePath to "/System/Library/ColorSync/Profiles/sRGB Profile.icc"
set ocidIccFilePathStr to (refMe's NSString's stringWithString:strIccFilePath)
set ocidIccFilePath to ocidIccFilePathStr's stringByStandardizingPath
set ocidIccFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidIccFilePath isDirectory:false)
set ocidProfileData to refMe's NSData's alloc()'s initWithContentsOfURL:ocidIccFilePathURL


####まずはUNIXパスにして
set strFilePath to (POSIX path of aliasFilePath) 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)
####ファイル名を取得
set ocidFileName to ocidFilePathURL's lastPathComponent()
####ファイル名から拡張子を取っていわゆるベースファイル名を取得
set ocidPrefixName to ocidFileName's stringByDeletingPathExtension
####コンテナディレクトリを取得
set ocidContainerDirURL to ocidFilePathURL's URLByDeletingLastPathComponent()
########################
###保存先ディレクトリを作成
set strPrefixName to ocidPrefixName as text
###ディレクトリ名はお好みで
set ocidSaveDirName to (strPrefixName & "_images") as text
##保存先URL
set ocidSaveFileDirPathURL to (ocidContainerDirURL's URLByAppendingPathComponent:ocidSaveDirName isDirectory:true)
###フォルダ作成
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidAttrDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidAttrDict's setValue:511 forKey:(refMe's NSFilePosixPermissions))
set listBoolMakeDir to (appFileManager's createDirectoryAtURL:(ocidSaveFileDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference))
#####################
#### 本処理
#####################
####PDFファイルを格納
set ocidActivDoc to (refMe's PDFDocument's alloc()'s initWithURL:ocidFilePathURL)
####PDFDocumentとNSDataに変換して
set ocidDataRep to ocidActivDoc's dataRepresentation()
####NSdataに格納
set ocidReadPdfData to (refMe's NSData's alloc()'s initWithData:ocidDataRep)
####NSPDFImageRepに変換
set ocidPdfPep to (refMe's NSPDFImageRep's alloc()'s initWithData:ocidReadPdfData)
###ページ数数えて
set numPageCnt to ocidPdfPep's pageCount() as integer
###ページカウントの書き出しファイル用のページ番号
set numCntPageNo to 1 as integer
###ページカウントの初期値JS
set numCntPageNoJs to numCntPageNo - 1 as integer
####################
#####ページ数だけ繰り返し
####################
repeat numPageCnt times
  ####順番にページデータを読み出し
(ocidPdfPep's setCurrentPage:numCntPageNoJs)
  ####ページデータをNSIMAGEに格納
  set ocidPageImageData to refMe's NSImage's alloc()'s init()
(ocidPageImageData's addRepresentation:ocidPdfPep)
  ###中間ファイルとしてのTIFFに変換
  set ocidOsDispatchData to ocidPageImageData's TIFFRepresentation()
  ####出力されるBmpImageRepに格納
  set ocidBmpImageRep to (refMe's NSBitmapImageRep's imageRepWithData:ocidOsDispatchData)
  #############################
  #####変換設定 オプション設定
  #############################
  if strResponse is "JPEG" then
    ###可変レコードに
    set ocidPropertyDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
    ###各種値をキーでセットしておく
(ocidPropertyDict's setObject:1 forKey:(refMe's NSImageCompressionFactor))
    set ocidSetColor to refMe's NSColor's whiteColor()
(ocidPropertyDict's setObject:ocidSetColor forKey:(refMe's NSImageFallbackBackgroundColor))
(ocidPropertyDict's setObject:ocidProfileData forKey:(refMe's NSImageColorSyncProfileData))
    ####ファイルタイプの指定
    set ocidFileType to refMe's NSBitmapImageFileTypeJPEG
    ###パスで使う拡張子
    set strExtension to "jpg"
    
  else if strResponse is "PNG" then
    set ocidPropertyDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidPropertyDict's setObject:true forKey:(refMe's NSImageInterlaced))
    ####ガンマ値が不要な場合はコメントアウト
(ocidPropertyDict's setObject:0.45455 forKey:(refMe's NSImageGamma))
(ocidPropertyDict's setObject:ocidProfileData forKey:(refMe's NSImageColorSyncProfileData))
    set ocidFileType to refMe's NSBitmapImageFileTypePNG
    set strExtension to "png"
    
  else if strResponse is "BMP" then
    set ocidPropertyDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
    set ocidFileType to refMe's NSBitmapImageFileTypeBMP
    set strExtension to "bmp"
    
  else if strResponse is "TIFF" then
    set ocidPropertyDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidPropertyDict's setObject:1 forKey:(refMe's NSImageCompressionFactor))
(ocidPropertyDict's setObject:(refMe's NSTIFFCompressionNone) forKey:(refMe's NSImageCompressionMethod))
(ocidPropertyDict's setObject:ocidProfileData forKey:(refMe's NSImageColorSyncProfileData))
    set ocidFileType to refMe's NSBitmapImageFileTypeTIFF
    set strExtension to "tiff"
    
  end if
  ##########変換
  set ocidNSInlineData to (ocidBmpImageRep's representationUsingType:ocidFileType |properties|:ocidPropertyDict)
  
  ############################
  #########保存
  ###########################
  ###ページ数連番ゼロサプレス
  set strZeroAdd to ("000" & numCntPageNo) as text
  set strPageNO to text -3 through -1 of strZeroAdd as text
  ###ファイル名に整形して
  set strSaveImageFileName to ("" & strPrefixName & "." & strPageNO & "." & strExtension & "") as text
  ####保存先URL
  set ocidSaveFilePathURL to (ocidSaveFileDirPathURL's URLByAppendingPathComponent:strSaveImageFileName isDirectory:false)
  #####保存
  set boolDone to (ocidNSInlineData's writeToURL:ocidSaveFilePathURL options:(refMe's NSDataWritingAtomic) |error|:(reference))
  
  #############カウントアップ
  set numCntPageNoJs to numCntPageNoJs + 1 as integer
  set numCntPageNo to numCntPageNo + 1 as integer
  ###データ解放
  set ocidNSInlineData to ""
  set ocidPageImageData to ""
  set ocidOsDispatchData to ""
  set ocidBmpImageRep to ""
end repeat


return "処理終了"



|

より以前の記事一覧

その他のカテゴリー

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