PDFAnnotation

PDFの注釈の一覧をテキストで出力する


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003(*
004com.cocolog-nifty.quicktimer.icefloe
005PDFの各ページに入っている注釈を一覧にします
006出力はページ毎
007全ページの2種
008*)
009----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
010use AppleScript version "2.8"
011use framework "Foundation"
012use framework "AppKit"
013use framework "PDFKit"
014use scripting additions
015
016property refMe : a reference to current application
017
018
019########################
020#設定項目
021#ポップアップ分も出力するか? true false
022set boolAddPopup to false as boolean
023#注釈が無いページも出力するか? true false
024set boolZeroAno to false as boolean
025
026########################
027#ダイアログ 入力
028set strName to (name of current application) as text
029if strName is "osascript" then
030  tell application "Finder" to activate
031else
032  tell current application to activate
033end if
034# デフォルトロケーション
035set appFileManager to refMe's NSFileManager's defaultManager()
036set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
037set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
038set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
039set listUTI to {"com.adobe.pdf"}
040set strMes to ("PDFファイルを選んでください") as text
041set strPrompt to ("PDFファイルを選んでください") as text
042try
043  #ファイル選択時
044  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
045on error
046  log "エラーしました"
047  return "エラーしました"
048end try
049########################
050#入力ファイルパス
051set strFilePath to (POSIX path of aliasFilePath) as text
052set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
053set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
054set ocidFilePathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:(false)
055set strFilePathURL to ocidFilePathURL's absoluteString() as text
056
057########################
058#ダイアログ 出力先フォルダ
059(*  ファイル名から自動生成に変更
060set strName to (name of current application) as text
061if strName is "osascript" then
062  tell application "Finder" to activate
063else
064  tell current application to activate
065end if
066# デフォルトロケーション
067#選択したPDFファイルと同じディレクトリ
068set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
069set aliasContainerDirPath to (ocidContainerDirPathURL's absoluteURL()) as alias
070#
071set strMes to ("保存先フォルダを選んでください\nページ数が多い場合はフォルダ作成した方がいいです") as text
072set strPrompt to ("保存先フォルダを選んでください\nページ数が多い場合はフォルダ作成した方がいいです") as text
073try
074  set aliasSaveDirPath to (choose folder strMes with prompt strPrompt default location aliasContainerDirPath with invisibles and showing package contents without multiple selections allowed) as alias
075on error
076  log "エラーしました"
077  return "エラーしました"
078end try
079*)
080#出力先フォルダパス
081set ocidBaseFilePathURL to ocidFilePathURL's URLByDeletingPathExtension()
082set strSaveDirName to (ocidFilePathURL's lastPathComponent())'s mutableCopy()
083(strSaveDirName's appendString:("-注釈一覧"))
084#set strBaseFileName to (ocidFilePathURL's lastPathComponent()) as text
085#set strSaveDirName to (strBaseFileName & "-テキスト抽出")
086set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
087set ocidSaveDirPathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:(strSaveDirName) isDirectory:(true)
088#フォルダ作成
089set appFileManager to refMe's NSFileManager's defaultManager()
090set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
091ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
092set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference)
093
094########################
095#NSDATA
096set ocidOption to (refMe's NSDataReadingMappedIfSafe)
097set listReadData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidFilePathURL) options:(ocidOption) |error| :(reference)
098set ocidReadData to (item 1 of listReadData)
099
100########################
101#PDFDocument
102set ocidActiveDoc to refMe's PDFDocument's alloc()'s initWithData:(ocidReadData)
103#総ページ数
104set numCntPage to ocidActiveDoc's pageCount()
105#出力用テキスト
106set ocidAllAnnotstring to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
107(ocidAllAnnotstring's appendString:(strFilePathURL))
108(ocidAllAnnotstring's appendString:("\n"))
109(ocidAllAnnotstring's appendString:("\n"))
110#ページ数分繰り返し
111repeat with itemIntNo from 0 to (numCntPage - 1) by 1
112  #ページを取り出して
113  set ocidActivePage to (ocidActiveDoc's pageAtIndex:(itemIntNo))
114  #ページ用テキスト
115  set ocidPageOutputString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
116  ##################
117  #テキストを抽出
118  set ocidAnnotationsArray to ocidActivePage's annotations()
119  #注釈の数
120  set numCntPageAnnot to ocidAnnotationsArray's |count|() as integer
121  (ocidPageOutputString's appendString:(strFilePathURL))
122  (ocidPageOutputString's appendString:("\n"))
123  set strSetValue to ((itemIntNo + 1) & "ページの注釈数: " & numCntPageAnnot) as text
124  (ocidPageOutputString's appendString:(strSetValue))
125  (ocidPageOutputString's appendString:("\n"))
126  (ocidAllAnnotstring's appendString:("-------------\n"))
127  (ocidAllAnnotstring's appendString:(strSetValue))
128  (ocidAllAnnotstring's appendString:("\n"))
129  #注釈の数だけ繰り返す
130  repeat with itemAnnotation in ocidAnnotationsArray
131    set strType to itemAnnotation's type() as text
132    if strType is "Popup" then
133      if boolAddPopup is true then
134        set strUserName to itemAnnotation's userName() as text
135        set dateMod to itemAnnotation's modificationDate() as date
136        if strType is "Stamp" then
137          set strContents to itemAnnotation's |stampName|() as text
138        else
139          set strContents to itemAnnotation's |contents|() as text
140        end if
141        set strSetValue to (strType & "\t" & strContents & "\t" & strUserName & "\t" & dateMod) as text
142        (ocidPageOutputString's appendString:(strSetValue))
143        (ocidPageOutputString's appendString:("\n"))
144        (ocidAllAnnotstring's appendString:(strSetValue))
145        (ocidAllAnnotstring's appendString:("\n"))
146      end if
147    else
148      set strUserName to itemAnnotation's userName() as text
149      set dateMod to itemAnnotation's modificationDate() as date
150      if strType is "Stamp" then
151        set strContents to itemAnnotation's |stampName|() as text
152      else
153        set strContents to itemAnnotation's |contents|() as text
154      end if
155      
156      set strSetValue to (strType & "\t" & strContents & "\t" & strUserName & "\t" & dateMod) as text
157      (ocidPageOutputString's appendString:(strSetValue))
158      (ocidPageOutputString's appendString:("\n"))
159      (ocidAllAnnotstring's appendString:(strSetValue))
160      (ocidAllAnnotstring's appendString:("\n"))
161    end if
162  end repeat
163  (ocidPageOutputString's appendString:("\n"))
164  (ocidAllAnnotstring's appendString:("\n"))
165  if numCntPageAnnot = 0 then
166    if boolZeroAno is true then
167      #保存するファイル名
168      set strSaveFileNameText to ((itemIntNo + 1) & ".txt") as text
169      #保存先パス
170      set ocidSaveFilePathURLText to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileNameText) isDirectory:(false))
171      #保存
172      set listDone to (ocidPageOutputString's writeToURL:(ocidSaveFilePathURLText) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error| :(reference))
173      if (item 1 of listDone) is true then
174        log (itemIntNo + 1) & "ページ目:正常終了" as text
175      else if (item 1 of listDone) is false then
176        log (item 2 of listDone)'s localizedDescription() as text
177        return (itemIntNo + 1) & "ページ目:保存に失敗しました" as text
178      end if
179    end if
180  else
181    #保存するファイル名
182    set strSaveFileNameText to ((itemIntNo + 1) & ".txt") as text
183    #保存先パス
184    set ocidSaveFilePathURLText to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileNameText) isDirectory:(false))
185    #保存
186    set listDone to (ocidPageOutputString's writeToURL:(ocidSaveFilePathURLText) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error| :(reference))
187    if (item 1 of listDone) is true then
188      log (itemIntNo + 1) & "ページ目:正常終了" as text
189    else if (item 1 of listDone) is false then
190      log (item 2 of listDone)'s localizedDescription() as text
191      return (itemIntNo + 1) & "ページ目:保存に失敗しました" as text
192    end if
193    
194  end if
195end repeat
196set strSaveFileNameText to ("_注釈一覧.txt") as text
197#保存先パス
198set ocidSaveFilePathURLText to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strSaveFileNameText) isDirectory:(false))
199#保存
200set listDone to (ocidAllAnnotstring's writeToURL:(ocidSaveFilePathURLText) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error| :(reference))
201if (item 1 of listDone) is true then
202  log (itemIntNo + 1) & "ページ目:正常終了" as text
203else if (item 1 of listDone) is false then
204  log (item 2 of listDone)'s localizedDescription() as text
205  return (itemIntNo + 1) & "ページ目:保存に失敗しました" as text
206end if
207
208
209return "終了"
AppleScriptで生成しました

|

注釈の内容(詳細)を確認(スクリプトエディタのログに表示)

20240901011956_1400x1460
AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#  com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "APPKit"
009use framework "Quartz"
010use framework "PDFKit"
011use scripting additions
012
013property refMe : a reference to current application
014set appFileManager to refMe's NSFileManager's defaultManager()
015
016#############################
017###ダイアログを前面に出す
018set strName to (name of current application) as text
019if strName is "osascript" then
020  tell application "Finder" to activate
021else
022  tell current application to activate
023end if
024############ デフォルトロケーション
025set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
026set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
027set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
028
029############UTIリスト
030set listUTI to {"com.adobe.pdf"}
031set strMes to ("PDFファイルを選んでください") as text
032set strPrompt to ("PDFファイルを選んでください") as text
033try
034  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
035on error
036  log "エラーしました"
037  return "エラーしました"
038end try
039
040###################################
041#####パス処理
042###################################
043set strFilePath to (POSIX path of aliasFilePath) as text
044set ocidFilePathstr to refMe's NSString's stringWithString:(strFilePath)
045set ocidFilePath to ocidFilePathstr's stringByStandardizingPath()
046set ocidFilePathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false
047
048###################################
049#####本処理
050###################################
051set ocidActivDoc to refMe's PDFDocument's alloc()'s initWithURL:(ocidFilePathURL)
052#ページ数を数えて
053set numCntPDFPage to ocidActivDoc's pageCount()
054
055#ページの数だけ繰り返し
056repeat with itemPageNO from 0 to (numCntPDFPage - 1) by 1
057  
058  ###ページ
059  set ocidActivPage to (ocidActivDoc's pageAtIndex:0)
060  ###アノテーション
061  set ocidAnnotationArray to ocidActivPage's annotations()
062  
063  ###アノテーションの数だけ繰り返し
064  repeat with itemAnnotationArray in ocidAnnotationArray
065    log itemAnnotationArray's type() as text
066    set ocidAnnotDict to itemAnnotationArray's annotationKeyValues()
067    set ocidAllKeysArray to ocidAnnotDict's allKeys()
068    repeat with itemKey in ocidAllKeysArray
069      log itemKey as text
070      log (ocidAnnotDict's valueForKey:(itemKey)) as list
071    end repeat
072  end repeat
073  log "----------"
074end repeat
075
076
077
AppleScriptで生成しました

|

[PDFKit]文字列検索してマッチした箇所にアンダーライン注釈を入れる(少し修正)


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004# 正規表現の限界で誤マッチするケースがある
005#com.cocolog-nifty.quicktimer.icefloe
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "UniformTypeIdentifiers"
010use framework "AppKit"
011use framework "PDFKit"
012use scripting additions
013
014property refMe : a reference to current application
015
016set appFileManager to refMe's NSFileManager's defaultManager()
017
018
019##################################
020#
021set strAnnotAuther to ("車寅次郎") as text
022set strAnnotName to ("検索結果ハイライト") as text
023set strAnnotContents to ("検索結果") as text
024
025#ハイライトの色 RGBの場合
026#set ocidSetColor to (refMe's NSColor's colorWithSRGBRed:(0.4392) green:(0.8196) blue:(0.7764) alpha:(0.85))
027#ハイライトの色 CMYKの場合
028set ocidSetColor to (refMe's NSColor's colorWithDeviceCyan:(0.0) magenta:(0.2) yellow:(1) black:(0.0) alpha:(0.85))
029
030
031##################################
032#ダイアログ
033set strReadString to doGetPasteboard()
034set aliasIconPath to doGetAppIconAliasFilePath("com.apple.Preview")
035#前面に
036set strName to (name of current application) as text
037if strName is "osascript" then
038  tell application "Finder" to activate
039else
040  tell current application to activate
041end if
042#
043set strTitle to ("検索語句を入力してください") as text
044set strMes to ("検索語句を入力 単語") as text
045set recordResult to (display dialog strMes with title strTitle default answer strReadString buttons {"キャンセル", "OK"} default button "OK" cancel button "キャンセル" giving up after 30 with icon aliasIconPath without hidden answer)
046if (gave up of recordResult) is true then
047  return "時間切れです"
048else if (button returned of recordResult) is "キャンセル" then
049  return "キャンセルです"
050else
051  set strReturnedText to (text returned of recordResult) as text
052  #注釈にコンテンツとしてセットする
053  set strAnnotContents to (strAnnotContents & ": " & strReturnedText)
054end if
055
056
057##################################
058#改行 タブ除去
059set ocidResponseText to refMe's NSString's stringWithString:(strReturnedText)
060set ocidTextM to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
061ocidTextM's appendString:(ocidResponseText)
062##改行除去
063set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\n") withString:("")
064set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\r") withString:("")
065##タブ除去
066set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\t") withString:("")
067set strSearchString to ocidTextM as text
068set ocidSearchString to refMe's NSString's stringWithString:(strSearchString)
069
070##濁音 半濁音対策
071set recordChkStr to {|が|:"か", |ぎ|:"き", |ぐ|:"く", |げ|:"け", |ご|:"こ", |ざ|:"さ", |じ|:"し", |ず|:"す", |ぜ|:"せ", |ぞ|:"そ", |だ|:"た", |ぢ|:"ち", |づ|:"つ", |で|:"で", |ど|:"と", |ば|:"は", |び|:"ひ", |ぶ|:"ふ", |べ|:"へ", |ぼ|:"ほ", |ぱ|:"は", |ぴ|:"ひ", |ぷ|:"ふ", |ぺ|:"へ", |ぽ|:"ほ", |ガ|:"カ", |ギ|:"キ", |グ|:"ク", |ゲ|:"ケ", |ゴ|:"コ", |ザ|:"サ", |ジ|:"シ", |ズ|:"ス", |ゼ|:"セ", |ゾ|:"ソ", |ダ|:"タ", |ヂ|:"チ", |ヅ|:"ツ", |デ|:"デ", |ド|:"ト", |バ|:"ハ", |ビ|:"ヒ", |ブ|:"フ", |ベ|:"へ", |ボ|:"ホ", |パ|:"ハ", |ピ|:"ヒ", |プ|:"フ", |ペ|:"へ", |ポ|:"ホ"} as record
072
073##濁音 半濁音対策 改行を考慮しない場合のレコード
074#set recordChkStr to {|が|:"か.", |ぎ|:"き.", |ぐ|:"く.", |げ|:"け.", |ご|:"こ.", |ざ|:"さ.", |じ|:"し.", |ず|:"す.", |ぜ|:"せ.", |ぞ|:"そ.", |だ|:"た.", |ぢ|:"ち.", |づ|:"つ.", |で|:"で.", |ど|:"と.", |ば|:"は.", |び|:"ひ.", |ぶ|:"ふ.", |べ|:"へ.", |ぼ|:"ほ.", |ぱ|:"は.", |ぴ|:"ひ.", |ぷ|:"ふ.", |ぺ|:"へ.", |ぽ|:"ほ.", |ガ|:"カ.", |ギ|:"キ.", |グ|:"ク.", |ゲ|:"ケ.", |ゴ|:"コ.", |ザ|:"サ.", |ジ|:"シ.", |ズ|:"ス.", |ゼ|:"セ.", |ゾ|:"ソ.", |ダ|:"タ.", |ヂ|:"チ.", |ヅ|:"ツ.", |デ|:"デ.", |ド|:"ト.", |バ|:"ハ.", |ビ|:"ヒ.", |ブ|:"フ.", |ベ|:"へ.", |ボ|:"ホ.", |パ|:"ハ.", |ピ|:"ヒ.", |プ|:"フ.", |ペ|:"へ.", |ポ|:"ホ."} as record
075#DICTに格納して
076set ocidChkStrDict to refMe's NSDictionary's dictionaryWithDictionary:(recordChkStr)
077#キーをリストに
078set ocidAllKeys to ocidChkStrDict's allKeys()
079set nunCntReplace to 0 as integer
080#全てのキーを繰り返し
081repeat with itemKey in ocidAllKeys
082  #キーの値を取り出して
083  set ocidSetValue to (ocidChkStrDict's valueForKey:(itemKey))
084  #置換する
085  set ocidReplacedStrings to (ocidSearchString's stringByReplacingOccurrencesOfString:(itemKey) withString:(ocidSetValue))
086  if ocidReplacedStrings = ocidSearchString then
087    set nunCntReplace to nunCntReplace + 0 as integer
088  else
089    set nunCntReplace to nunCntReplace + 1 as integer
090  end if
091  set ocidSearchString to ocidReplacedStrings
092end repeat
093#検索文字の文字数
094set numCntSearchString to ocidSearchString's |length|() as integer
095set numCntSearchString to (numCntSearchString + nunCntReplace) as integer
096#文字毎のリストにして
097set strSearchString to ocidSearchString as text
098set strDelim to AppleScript's text item delimiters
099set AppleScript's text item delimiters to ""
100set listSearchString to (every text item of strSearchString) as list
101set AppleScript's text item delimiters to strDelim
102set numCntList to (count of listSearchString) as integer
103set strPatternString to "" as text
104#正規表現用にパターンを生成する
105repeat with itemNo from 1 to (numCntList) by 1
106  #1文字づつ
107  set strItemString to (item itemNo of listSearchString) as text
108  #最後の文字を除いて正規表現パターン付与する
109  if itemNo < numCntList then
110    set strPatternString to strPatternString & (strItemString & ".{0,3}?") as text
111    #set strPatternString to strPatternString & (strItemString & ".*?") as text
112  else
113    set strPatternString to strPatternString & (strItemString) as text
114  end if
115end repeat
116#正規表現用のパターン
117set ocidPatternString to refMe's NSString's stringWithString:(strPatternString)
118log strPatternString as text
119
120#############################
121###ダイアログを前面に出す
122set strName to (name of current application) as text
123if strName is "osascript" then
124  tell application "Finder" to activate
125else
126  tell current application to activate
127end if
128############ デフォルトロケーション
129set appFileManager to refMe's NSFileManager's defaultManager()
130set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
131set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
132set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
133
134############UTIリスト
135set listUTI to {"com.adobe.pdf"}
136set strMes to ("PDFファイルを選んでください") as text
137set strPrompt to ("PDFファイルを選んでください") as text
138try
139  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
140on error
141  log "エラーしました"
142  return "エラーしました"
143end try
144
145###################################
146#####パス処理
147###################################
148set strFilePath to (POSIX path of aliasFilePath) as text
149set ocidFilePathstr to refMe's NSString's stringWithString:(strFilePath)
150set ocidFilePath to ocidFilePathstr's stringByStandardizingPath()
151set ocidFilePathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false
152####ファイル名を取得
153set ocidFileName to ocidFilePathURL's lastPathComponent()
154####拡張子を取得
155set ocidFileExtension to ocidFilePathURL's pathExtension()
156####ファイル名から拡張子を取っていわゆるベースファイル名を取得
157set ocidPrefixName to ocidFileName's stringByDeletingPathExtension
158####選んだファイルのディレクトリ
159set ocidContainerDirURL to ocidFilePathURL's URLByDeletingLastPathComponent()
160
161###################################
162#####保存ダイアログ
163###################################
164###ファイル名
165set strPrefixName to ocidPrefixName as text
166###拡張子変える場合
167set strFileExtension to "PDF"
168###ダイアログに出すファイル名
169set strDefaultName to (strPrefixName & ".注釈入." & strFileExtension) as text
170set strPromptText to "保存する名前を決めてください"
171set strMesText to "保存する名前を決めてください"
172###選んだファイルの同階層をデフォルトの場合
173set aliasDefaultLocation to (ocidContainerDirURL's absoluteURL) as alias
174####ファイル名ダイアログ
175####実在しない『はず』なのでas «class furl»で
176set aliasSaveFilePath to (choose file name strMesText default location aliasDefaultLocation default name strDefaultName with prompt strPromptText) as «class furl»
177####UNIXパス
178set strSaveFilePath to POSIX path of aliasSaveFilePath as text
179####ドキュメントのパスをNSString
180set ocidSaveFilePath to refMe's NSString's stringWithString:strSaveFilePath
181####ドキュメントのパスをNSURLに
182set ocidSaveFilePathURL to refMe's NSURL's fileURLWithPath:ocidSaveFilePath
183###拡張子取得
184set strFileExtensionName to ocidSaveFilePathURL's pathExtension() as text
185###ダイアログで拡張子を取っちゃった時対策
186if strFileExtensionName is not strFileExtension then
187  set ocidSaveFilePathURL to ocidSaveFilePathURL's URLByAppendingPathExtension:strFileExtension
188end if
189###################################
190##NSDATAに読み込む
191set ocidOption to (refMe's NSDataReadingMappedIfSafe)
192set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidFilePathURL) options:(ocidOption) |error| :(reference)
193if (item 2 of listResponse) = (missing value) then
194  log "正常処理"
195  set ocidReadData to (item 1 of listResponse)
196else if (item 2 of listResponse) ≠ (missing value) then
197  set strErrorNO to (item 2 of listResponse)'s code() as text
198  set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
199  refMe's NSLog("■:" & strErrorNO & strErrorMes)
200  return "エラーしました" & strErrorNO & strErrorMes
201end if
202###################################
203#NSDATAをPDFDocumentに読み込んで
204set ocidReadDoc to refMe's PDFDocument's alloc()'s initWithData:(ocidReadData)
205#ページ数を数えて
206set numCntPDFPage to ocidReadDoc's pageCount()
207#ページの数だけ繰り返し
208repeat with itemPageNO from 0 to (numCntPDFPage - 1) by 1
209  #ページを取り出して
210  set ocidPDFPage to (ocidReadDoc's pageAtIndex:(itemPageNO))
211  #全文字する
212  set numCntCharOfPage to ocidPDFPage's numberOfCharacters()
213  log numCntCharOfPage as integer
214  #ページのテキストを取り出して
215  set ocidPageString to ocidPDFPage's |string|()
216  #標準テキスト化すると文字の位置 セレクションの値が異なるので行わない
217  # set ocidPageString to ocidPageReadString's precomposedStringWithCompatibilityMapping()
218  #文字す
219  set numLengthCharOfString to ocidPageString's |length|()
220  log numLengthCharOfString as integer
221  #文字数チェック
222  if numCntCharOfPage ≠ numLengthCharOfString then
223    return "ページ内に文字数差異が出たので処理終了"
224  else
225    #レンジを生成して
226    set ocidStringRange to refMe's NSRange's NSMakeRange(0, numLengthCharOfString)
227    log ocidStringRange
228  end if
229  #正規表現を行う
230  set ocidOption to (refMe's NSRegularExpressionDotMatchesLineSeparators)
231  set listRegex to (refMe's NSRegularExpression's regularExpressionWithPattern:(strPatternString) options:(ocidOption) |error| :(reference))
232  set ocidRegex to (item 1 of listRegex)
233  set ocidMatchRangeArray to (ocidRegex's matchesInString:(ocidPageString) options:0 range:(ocidStringRange))
234  #マッチした数だけ繰り返し
235  repeat with itemArray in ocidMatchRangeArray
236    #RANGEをとって
237    set ocidMatchRange to itemArray's range()
238    #RANGEの文字数
239    set numMatchLength to ocidMatchRange's |length|()
240    #文字数が同じでない=途中にスペース=行をまたいでのマッチの場合
241    if numCntSearchString ≠ numMatchLength then
242      #テキストを取り出して
243      set ocidMatchText to (ocidPageString's substringWithRange:(ocidMatchRange))
244      if (ocidMatchText as text) contains " " then
245        #スペース=行またぎ直前の文字までの値で
246        set ocidReturnRange to (ocidMatchText's rangeOfString:(" "))
247        set ocidReturnLoc to ocidMatchRange's location()
248        set ocidReturnLeng to (ocidReturnRange's location())
249        #改行前までのRANGEを生成して
250        set ocidSetReturnRange to refMe's NSRange's NSMakeRange(ocidReturnLoc, ocidReturnLeng)
251      else
252        set ocidSetReturnRange to ocidMatchRange
253      end if
254      #改行までをマッチ範囲とする
255      set ocidMatchSelection to (ocidPDFPage's selectionForRange:(ocidSetReturnRange))
256    else
257      #行をまたがない場合はマッチ範囲=そのままセレクトエリア
258      set ocidMatchSelection to (ocidPDFPage's selectionForRange:(ocidMatchRange))
259    end if
260    #マッチ範囲のRECTを取得して
261    set ocidMatchRect to (ocidMatchSelection's boundsForPage:(ocidPDFPage))
262    ######################
263    set ocidPropertiesDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
264    #注釈をセットする
265    (ocidPropertiesDict's setValue:(strAnnotAuther) forKey:("/T"))
266    (ocidPropertiesDict's setValue:(strAnnotName) forKey:(refMe's PDFAnnotationKeyName))
267    (ocidPropertiesDict's setValue:(28) forKey:(refMe's PDFAnnotationKeyFlags))
268    (ocidPropertiesDict's setValue:(ocidSetColor) forKey:(refMe's PDFAnnotationKeyColor))
269    (ocidPropertiesDict's setValue:(strAnnotContents) forKey:(refMe's PDFAnnotationKeyContents))
270    (ocidPropertiesDict's setValue:(refMe's kPDFLineStyleNone) forKey:(refMe's PDFAnnotationKeyLineEndingStyles))
271    #(ocidPropertiesDict's setValue:(ocidMatchRect) forKey:(refMe's PDFAnnotationKeyRect))
272    #注釈はハイライト
273    set ocidTyep to (refMe's PDFAnnotationSubtypeHighlight)
274    set ocidAddAnot to (refMe's PDFAnnotation's alloc()'s initWithBounds:(ocidMatchRect) forType:(ocidTyep) withProperties:(ocidPropertiesDict))
275    (ocidPDFPage's addAnnotation:(ocidAddAnot))
276    
277  end repeat
278  
279end repeat
280#処理が終わったら保存
281set boolDone to ocidReadDoc's writeToURL:(ocidSaveFilePathURL)
282
283
284########################
285## クリップボードの中身取り出し
286########################
287on doGetPasteboard()
288  set appPasteboard to refMe's NSPasteboard's generalPasteboard()
289  set ocidPastBoardTypeArray to appPasteboard's types
290  ###テキストがあれば
291  set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
292  if boolContain = true then
293    ###値を格納する
294    tell application "Finder"
295      set strReadString to (the clipboard as text) as text
296    end tell
297    ###Finderでエラーしたら
298  else
299    set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
300    if boolContain = true then
301      set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
302      set strReadString to ocidReadString as text
303    else
304      log "テキストなし"
305      set strReadString to "入力してください" as text
306    end if
307  end if
308  return strReadString
309end doGetPasteboard
310
311
312########################
313#AppIconのパスを求める
314########################
315on doGetAppIconAliasFilePath(argBundleID)
316  #
317  set appFileManager to refMe's NSFileManager's defaultManager()
318  set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
319  set ocidAppBundle to (refMe's NSBundle's bundleWithIdentifier:(argBundleID))
320  if ocidAppBundle ≠ (missing value) then
321    set ocidAppPathURL to ocidAppBundle's bundleURL()
322  else if ocidAppBundle = (missing value) then
323    set ocidAppPathURL to (appSharedWorkspace's URLForApplicationWithBundleIdentifier:(argBundleID))
324  end if
325  if ocidAppBundle ≠ (missing value) then
326    set ocidAppPathURL to ocidAppBundle's bundleURL()
327  else if ocidAppBundle = (missing value) then
328    set ocidAppPathURL to (appSharedWorkspace's URLForApplicationWithBundleIdentifier:(argBundleID))
329  end if
330  if ocidAppPathURL = (missing value) then
331    tell application "Finder"
332      try
333        set aliasAppApth to (application file id strBundleID) as alias
334      on error
335        return "アプリケーションが見つかりませんでした"
336      end try
337    end tell
338    set strAppPath to POSIX path of aliasAppApth as text
339    set strAppPathStr to refMe's NSString's stringWithString:(strAppPath)
340    set strAppPath to strAppPathStr's stringByStandardizingPath()
341    set ocidAppPathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:true
342  end if
343  ####ダイアログに指定アプリのアイコンを表示する
344  ###アイコン名をPLISTから取得
345  set ocidPlistPathURL to ocidAppPathURL's URLByAppendingPathComponent:("Contents/Info.plist") isDirectory:false
346  set ocidPlistDict to refMe's NSMutableDictionary's alloc()'s initWithContentsOfURL:(ocidPlistPathURL)
347  set strIconFileName to (ocidPlistDict's valueForKey:("CFBundleIconFile")) as text
348  ###ICONのURLにして
349  set strPath to ("Contents/Resources/" & strIconFileName) as text
350  set ocidIconFilePathURL to ocidAppPathURL's URLByAppendingPathComponent:(strPath) isDirectory:false
351  ###拡張子の有無チェック
352  set strExtensionName to (ocidIconFilePathURL's pathExtension()) as text
353  if strExtensionName is "" then
354    set ocidIconFilePathURL to ocidIconFilePathURL's URLByAppendingPathExtension:"icns"
355  end if
356  ##-->これがアイコンパス
357  log ocidIconFilePathURL's absoluteString() as text
358  ###ICONファイルが実際にあるか?チェック
359  set boolExists to appFileManager's fileExistsAtPath:(ocidIconFilePathURL's |path|)
360  ###ICONがみつかない時用にデフォルトを用意する
361  if boolExists is false then
362    set aliasIconPath to POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/AlertNoteIcon.icns"
363  else
364    set aliasIconPath to ocidIconFilePathURL's absoluteURL() as alias
365  end if
366  return aliasIconPath
367end doGetAppIconAliasFilePath
368
AppleScriptで生成しました

|

[PDFKit]文字列検索してマッチした箇所にアンダーライン注釈を入れる

濁音半濁音が2文字になる仕様
行をまたいだ語句マッチの場合
正規表現の私の技術の限界で…誤マッチする事がある
でも
マッチしない事はないのでこれでよしとすることにした

AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004# 正規表現の限界で誤マッチするケースがある
005#com.cocolog-nifty.quicktimer.icefloe
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "UniformTypeIdentifiers"
010use framework "AppKit"
011use framework "PDFKit"
012use scripting additions
013
014property refMe : a reference to current application
015
016set appFileManager to refMe's NSFileManager's defaultManager()
017
018
019##################################
020#ダイアログ
021set strReadString to doGetPasteboard()
022set aliasIconPath to doGetAppIconAliasFilePath("com.apple.Preview")
023#前面に
024set strName to (name of current application) as text
025if strName is "osascript" then
026  tell application "Finder" to activate
027else
028  tell current application to activate
029end if
030#
031set strTitle to ("検索語句を入力してください") as text
032set strMes to ("検索語句を入力 単語") as text
033set recordResult to (display dialog strMes with title strTitle default answer strReadString buttons {"キャンセル", "OK"} default button "OK" cancel button "キャンセル" giving up after 30 with icon aliasIconPath without hidden answer)
034if (gave up of recordResult) is true then
035  return "時間切れです"
036else if (button returned of recordResult) is "キャンセル" then
037  return "キャンセルです"
038else
039  set strReturnedText to (text returned of recordResult) as text
040end if
041
042
043##################################
044#改行 タブ除去
045set ocidResponseText to refMe's NSString's stringWithString:(strReturnedText)
046set ocidTextM to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
047ocidTextM's appendString:(ocidResponseText)
048##改行除去
049set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\n") withString:("")
050set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\r") withString:("")
051##タブ除去
052set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\t") withString:("")
053set strSearchString to ocidTextM as text
054set ocidSearchString to refMe's NSString's stringWithString:(strSearchString)
055
056##濁音 半濁音対策
057set recordChkStr to {|が|:"か", |ぎ|:"き", |ぐ|:"く", |げ|:"け", |ご|:"こ", |ざ|:"さ", |じ|:"し", |ず|:"す", |ぜ|:"せ", |ぞ|:"そ", |だ|:"た", |ぢ|:"ち", |づ|:"つ", |で|:"で", |ど|:"と", |ば|:"は", |び|:"ひ", |ぶ|:"ふ", |べ|:"へ", |ぼ|:"ほ", |ぱ|:"は", |ぴ|:"ひ", |ぷ|:"ふ", |ぺ|:"へ", |ぽ|:"ほ", |ガ|:"カ", |ギ|:"キ", |グ|:"ク", |ゲ|:"ケ", |ゴ|:"コ", |ザ|:"サ", |ジ|:"シ", |ズ|:"ス", |ゼ|:"セ", |ゾ|:"ソ", |ダ|:"タ", |ヂ|:"チ", |ヅ|:"ツ", |デ|:"デ", |ド|:"ト", |バ|:"ハ", |ビ|:"ヒ", |ブ|:"フ", |ベ|:"へ", |ボ|:"ホ", |パ|:"ハ", |ピ|:"ヒ", |プ|:"フ", |ペ|:"へ", |ポ|:"ホ"} as record
058#DICTに格納して
059set ocidChkStrDict to refMe's NSDictionary's dictionaryWithDictionary:(recordChkStr)
060#キーをリストに
061set ocidAllKeys to ocidChkStrDict's allKeys()
062set nunCntReplace to 0 as integer
063#全てのキーを繰り返し
064repeat with itemKey in ocidAllKeys
065  #キーの値を取り出して
066  set ocidSetValue to (ocidChkStrDict's valueForKey:(itemKey))
067  #置換する
068  set ocidReplacedStrings to (ocidSearchString's stringByReplacingOccurrencesOfString:(itemKey) withString:(ocidSetValue))
069  if ocidReplacedStrings = ocidSearchString then
070    set nunCntReplace to nunCntReplace + 0 as integer
071  else
072    set nunCntReplace to nunCntReplace + 1 as integer
073  end if
074  set ocidSearchString to ocidReplacedStrings
075end repeat
076#検索文字の文字数
077set numCntSearchString to ocidSearchString's |length|() as integer
078set numCntSearchString to (numCntSearchString + nunCntReplace) as integer
079#文字毎のリストにして
080set strSearchString to ocidSearchString as text
081set strDelim to AppleScript's text item delimiters
082set AppleScript's text item delimiters to ""
083set listSearchString to (every text item of strSearchString) as list
084set AppleScript's text item delimiters to strDelim
085set numCntList to (count of listSearchString) as integer
086set strPatternString to "" as text
087#正規表現用にパターンを生成する
088repeat with itemNo from 1 to (numCntList) by 1
089  #1文字づつ
090  set strItemString to (item itemNo of listSearchString) as text
091  #最後の文字を除いて正規表現パターン付与する
092  if itemNo < numCntList then
093    set strPatternString to strPatternString & (strItemString & ".{0,3}?") as text
094  else
095    set strPatternString to strPatternString & (strItemString) as text
096  end if
097end repeat
098#正規表現用のパターン
099set ocidPatternString to refMe's NSString's stringWithString:(strPatternString)
100log strPatternString as text
101
102#############################
103###ダイアログを前面に出す
104set strName to (name of current application) as text
105if strName is "osascript" then
106  tell application "Finder" to activate
107else
108  tell current application to activate
109end if
110############ デフォルトロケーション
111set appFileManager to refMe's NSFileManager's defaultManager()
112set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
113set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
114set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
115
116############UTIリスト
117set listUTI to {"com.adobe.pdf"}
118set strMes to ("PDFファイルを選んでください") as text
119set strPrompt to ("PDFファイルを選んでください") as text
120try
121  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
122on error
123  log "エラーしました"
124  return "エラーしました"
125end try
126
127###################################
128#####パス処理
129###################################
130set strFilePath to (POSIX path of aliasFilePath) as text
131set ocidFilePathstr to refMe's NSString's stringWithString:(strFilePath)
132set ocidFilePath to ocidFilePathstr's stringByStandardizingPath()
133set ocidFilePathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false
134####ファイル名を取得
135set ocidFileName to ocidFilePathURL's lastPathComponent()
136####拡張子を取得
137set ocidFileExtension to ocidFilePathURL's pathExtension()
138####ファイル名から拡張子を取っていわゆるベースファイル名を取得
139set ocidPrefixName to ocidFileName's stringByDeletingPathExtension
140####選んだファイルのディレクトリ
141set ocidContainerDirURL to ocidFilePathURL's URLByDeletingLastPathComponent()
142
143###################################
144#####保存ダイアログ
145###################################
146###ファイル名
147set strPrefixName to ocidPrefixName as text
148###拡張子変える場合
149set strFileExtension to "PDF"
150###ダイアログに出すファイル名
151set strDefaultName to (strPrefixName & ".注釈入." & strFileExtension) as text
152set strPromptText to "保存する名前を決めてください"
153set strMesText to "保存する名前を決めてください"
154###選んだファイルの同階層をデフォルトの場合
155set aliasDefaultLocation to (ocidContainerDirURL's absoluteURL) as alias
156####ファイル名ダイアログ
157####実在しない『はず』なのでas «class furl»で
158set aliasSaveFilePath to (choose file name strMesText default location aliasDefaultLocation default name strDefaultName with prompt strPromptText) as «class furl»
159####UNIXパス
160set strSaveFilePath to POSIX path of aliasSaveFilePath as text
161####ドキュメントのパスをNSString
162set ocidSaveFilePath to refMe's NSString's stringWithString:strSaveFilePath
163####ドキュメントのパスをNSURLに
164set ocidSaveFilePathURL to refMe's NSURL's fileURLWithPath:ocidSaveFilePath
165###拡張子取得
166set strFileExtensionName to ocidSaveFilePathURL's pathExtension() as text
167###ダイアログで拡張子を取っちゃった時対策
168if strFileExtensionName is not strFileExtension then
169  set ocidSaveFilePathURL to ocidSaveFilePathURL's URLByAppendingPathExtension:strFileExtension
170end if
171###################################
172##NSDATAに読み込む
173set ocidOption to (refMe's NSDataReadingMappedIfSafe)
174set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidFilePathURL) options:(ocidOption) |error| :(reference)
175if (item 2 of listResponse) = (missing value) then
176  log "正常処理"
177  set ocidReadData to (item 1 of listResponse)
178else if (item 2 of listResponse) ≠ (missing value) then
179  set strErrorNO to (item 2 of listResponse)'s code() as text
180  set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
181  refMe's NSLog("■:" & strErrorNO & strErrorMes)
182  return "エラーしました" & strErrorNO & strErrorMes
183end if
184###################################
185#NSDATAをPDFDocumentに読み込んで
186set ocidReadDoc to refMe's PDFDocument's alloc()'s initWithData:(ocidReadData)
187#ページ数を数えて
188set numCntPDFPage to ocidReadDoc's pageCount()
189#ページの数だけ繰り返し
190repeat with itemPageNO from 0 to (numCntPDFPage - 1) by 1
191  #ページを取り出して
192  set ocidPDFPage to (ocidReadDoc's pageAtIndex:(itemPageNO))
193  #全文字する
194  set numCntCharOfPage to ocidPDFPage's numberOfCharacters()
195  log numCntCharOfPage as integer
196  #ページのテキストを取り出して
197  set ocidPageString to ocidPDFPage's |string|()
198  #標準テキスト化すると文字の位置 セレクションの値が異なるので行わない
199  # set ocidPageString to ocidPageReadString's precomposedStringWithCompatibilityMapping()
200  #文字す
201  set numLengthCharOfString to ocidPageString's |length|()
202  log numLengthCharOfString as integer
203  #文字数チェック
204  if numCntCharOfPage ≠ numLengthCharOfString then
205    return "ページ内に文字数差異が出たので処理終了"
206  else
207    #レンジを生成して
208    set ocidStringRange to refMe's NSRange's NSMakeRange(0, numLengthCharOfString)
209    log ocidStringRange
210  end if
211  #正規表現を行う
212  set ocidOption to (refMe's NSRegularExpressionDotMatchesLineSeparators)
213  set listRegex to (refMe's NSRegularExpression's regularExpressionWithPattern:(strPatternString) options:(ocidOption) |error| :(reference))
214  set ocidRegex to (item 1 of listRegex)
215  set ocidMatchRangeArray to (ocidRegex's matchesInString:(ocidPageString) options:0 range:(ocidStringRange))
216  #マッチした数だけ繰り返し
217  repeat with itemArray in ocidMatchRangeArray
218    #RANGEをとって
219    set ocidMatchRange to itemArray's range()
220    #RANGEの文字数
221    set numMatchLength to ocidMatchRange's |length|()
222    #文字数が同じでない=途中にスペース=行をまたいでのマッチの場合
223    if numCntSearchString ≠ numMatchLength then
224      #テキストを取り出して
225      set ocidMatchText to (ocidPageString's substringWithRange:(ocidMatchRange))
226      if (ocidMatchText as text) contains " " then
227        #スペース=行またぎ直前の文字までの値で
228        set ocidReturnRange to (ocidMatchText's rangeOfString:(" "))
229        set ocidReturnLoc to ocidMatchRange's location()
230        set ocidReturnLeng to (ocidReturnRange's location())
231        #改行前までのRANGEを生成して
232        set ocidSetReturnRange to refMe's NSRange's NSMakeRange(ocidReturnLoc, ocidReturnLeng)
233      end if
234      #改行までをマッチ範囲とする
235      set ocidMatchSelection to (ocidPDFPage's selectionForRange:(ocidSetReturnRange))
236    else
237      #行をまたがない場合はマッチ範囲=そのままセレクトエリア
238      set ocidMatchSelection to (ocidPDFPage's selectionForRange:(ocidMatchRange))
239    end if
240    #マッチ範囲のRECTを取得して
241    set ocidMatchRect to (ocidMatchSelection's boundsForPage:(ocidPDFPage))
242    #注釈をセットする
243    set ocidPropertiesDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
244    (ocidPropertiesDict's setValue:("検索結果") forKey:(refMe's PDFAnnotationKeyName))
245    (ocidPropertiesDict's setValue:(28) forKey:(refMe's PDFAnnotationKeyFlags))
246    set ocidSetColor to (refMe's NSColor's colorWithSRGBRed:(0.4392) green:(0.8196) blue:(0.7764) alpha:(0.85))
247    (ocidPropertiesDict's setValue:(ocidSetColor) forKey:(refMe's PDFAnnotationKeyColor))
248    #注釈はハイライト
249    set ocidTyep to (refMe's PDFAnnotationSubtypeHighlight)
250    set ocidAddAnot to (refMe's PDFAnnotation's alloc()'s initWithBounds:(ocidMatchRect) forType:(ocidTyep) withProperties:(ocidPropertiesDict))
251    (ocidPDFPage's addAnnotation:(ocidAddAnot))
252    
253  end repeat
254  
255end repeat
256#処理が終わったら保存
257set boolDone to ocidReadDoc's writeToURL:(ocidSaveFilePathURL)
258
259
260
261
262
263
264########################
265## クリップボードの中身取り出し
266########################
267on doGetPasteboard()
268  set appPasteboard to refMe's NSPasteboard's generalPasteboard()
269  set ocidPastBoardTypeArray to appPasteboard's types
270  ###テキストがあれば
271  set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
272  if boolContain = true then
273    ###値を格納する
274    tell application "Finder"
275      set strReadString to (the clipboard as text) as text
276    end tell
277    ###Finderでエラーしたら
278  else
279    set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
280    if boolContain = true then
281      set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
282      set strReadString to ocidReadString as text
283    else
284      log "テキストなし"
285      set strReadString to "入力してください" as text
286    end if
287  end if
288  return strReadString
289end doGetPasteboard
290
291
292########################
293#AppIconのパスを求める
294########################
295on doGetAppIconAliasFilePath(argBundleID)
296  #
297  set appFileManager to refMe's NSFileManager's defaultManager()
298  set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
299  set ocidAppBundle to (refMe's NSBundle's bundleWithIdentifier:(argBundleID))
300  if ocidAppBundle ≠ (missing value) then
301    set ocidAppPathURL to ocidAppBundle's bundleURL()
302  else if ocidAppBundle = (missing value) then
303    set ocidAppPathURL to (appSharedWorkspace's URLForApplicationWithBundleIdentifier:(argBundleID))
304  end if
305  if ocidAppBundle ≠ (missing value) then
306    set ocidAppPathURL to ocidAppBundle's bundleURL()
307  else if ocidAppBundle = (missing value) then
308    set ocidAppPathURL to (appSharedWorkspace's URLForApplicationWithBundleIdentifier:(argBundleID))
309  end if
310  if ocidAppPathURL = (missing value) then
311    tell application "Finder"
312      try
313        set aliasAppApth to (application file id strBundleID) as alias
314      on error
315        return "アプリケーションが見つかりませんでした"
316      end try
317    end tell
318    set strAppPath to POSIX path of aliasAppApth as text
319    set strAppPathStr to refMe's NSString's stringWithString:(strAppPath)
320    set strAppPath to strAppPathStr's stringByStandardizingPath()
321    set ocidAppPathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:true
322  end if
323  ####ダイアログに指定アプリのアイコンを表示する
324  ###アイコン名をPLISTから取得
325  set ocidPlistPathURL to ocidAppPathURL's URLByAppendingPathComponent:("Contents/Info.plist") isDirectory:false
326  set ocidPlistDict to refMe's NSMutableDictionary's alloc()'s initWithContentsOfURL:(ocidPlistPathURL)
327  set strIconFileName to (ocidPlistDict's valueForKey:("CFBundleIconFile")) as text
328  ###ICONのURLにして
329  set strPath to ("Contents/Resources/" & strIconFileName) as text
330  set ocidIconFilePathURL to ocidAppPathURL's URLByAppendingPathComponent:(strPath) isDirectory:false
331  ###拡張子の有無チェック
332  set strExtensionName to (ocidIconFilePathURL's pathExtension()) as text
333  if strExtensionName is "" then
334    set ocidIconFilePathURL to ocidIconFilePathURL's URLByAppendingPathExtension:"icns"
335  end if
336  ##-->これがアイコンパス
337  log ocidIconFilePathURL's absoluteString() as text
338  ###ICONファイルが実際にあるか?チェック
339  set boolExists to appFileManager's fileExistsAtPath:(ocidIconFilePathURL's |path|)
340  ###ICONがみつかない時用にデフォルトを用意する
341  if boolExists is false then
342    set aliasIconPath to POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/AlertNoteIcon.icns"
343  else
344    set aliasIconPath to ocidIconFilePathURL's absoluteURL() as alias
345  end if
346  return aliasIconPath
347end doGetAppIconAliasFilePath
348
AppleScriptで生成しました

|

[PDFAnnotationSubtypeText]テキスト注釈の追加(デモ)


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#! /usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003(*
004テキスト注釈のアイコン指定方法
0051−4までのどの方法でも結果は同じ
006*)
007#  com.cocolog-nifty.quicktimer.icefloe
008----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
009use AppleScript version "2.8"
010use framework "Foundation"
011use framework "AppKit"
012use framework "PDFKit"
013use scripting additions
014
015property refMe : a reference to current application
016set appFileManager to refMe's NSFileManager's defaultManager()
017
018################################
019#設定項目 出力ページサイズPT
020set numSetSizePtW to 595 as integer
021set numSetSizePtH to 842 as integer
022
023################################
024#背景画像を作成 透過
025set ocidArtBoardRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numSetSizePtW) pixelsHigh:(numSetSizePtH) bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(refMe's NSCalibratedRGBColorSpace) bitmapFormat:(refMe's NSAlphaFirstBitmapFormat) bytesPerRow:0 bitsPerPixel:32)
026
027################################
028#初期化
029set appGraphicsContext to (refMe's NSGraphicsContext)
030#編集開始
031appGraphicsContext's saveGraphicsState()
032#イメージ読み込み
033set ocidReadImageContext to appGraphicsContext's graphicsContextWithBitmapImageRep:(ocidArtBoardRep)
034#出力サイズイメージ読み込み
035appGraphicsContext's setCurrentContext:(ocidReadImageContext)
036#透過色
037set ocidArtBoardColor to refMe's NSColor's colorWithRed:(1.0) green:(1.0) blue:(1.0) alpha:(0.0)
038#塗り色を『白』に指定して
039ocidArtBoardColor's |set|()
040#画像として色を塗る
041set ocidFillRect to refMe's NSRect's NSMakeRect(0, 0, numSetSizePtW, numSetSizePtH)
042refMe's NSRectFill(ocidFillRect)
043#編集終了
044appGraphicsContext's restoreGraphicsState()
045
046################################
047#念の為NSBitmapImageRepにサイズをセット
048#サイズを生成して
049set ocidOutPutSize to refMe's NSSize's NSMakeSize(numSetSizePtW, numSetSizePtH)
050#サイズを設定(ここで設定するのはPTサイズ)
051ocidArtBoardRep's setSize:(ocidOutPutSize)
052
053################################
054#NSBitmapImageRepをNSImageに変換
055set ocidPageImage to refMe's NSImage's alloc()'s initWithSize:(ocidOutPutSize)
056ocidPageImage's addRepresentation:(ocidArtBoardRep)
057
058################################
059#↑で作った画像でPDFPageを作成
060set ocidActivPage to refMe's PDFPage's alloc()'s initWithImage:(ocidPageImage)
061
062################################
063#PDFDocumentの初期化
064set ocidActivDoc to (refMe's PDFDocument's alloc()'s init())
065#ページをセット
066ocidActivDoc's insertPage:(ocidActivPage) atIndex:(0)
067
068################################
069#追加する注釈を作成(テキスト注釈)原点左下0/0
070#左上
071set ocidMakeRect to refMe's NSRect's NSMakeRect(10, (842 - 40), 30, 30)
072#左下
073# set ocidMakeRect to refMe's NSRect's NSMakeRect(10, 10, 30, 30)
074#右上
075# set ocidMakeRect to refMe's NSRect's NSMakeRect((numSetSizePtW - 40), (numSetSizePtH - 40), 30, 30)
076#右下
077# set ocidMakeRect to refMe's NSRect's NSMakeRect((numSetSizePtW - 40), 10, 30, 30)
078#プロパティを指定していきます
079set ocidPropertiesDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
080#NAME
081ocidPropertiesDict's setValue:("DC1") forKey:(refMe's PDFAnnotationKeyName)
082#許可番号
083ocidPropertiesDict's setValue:(28) forKey:(refMe's PDFAnnotationKeyFlags)
084#主要なテキスト項目
085ocidPropertiesDict's setValue:("ラベルテキスト") forKey:(refMe's PDFAnnotationKeyTextLabel)
086ocidPropertiesDict's setValue:("キャプションテキスト") forKey:(refMe's PDFAppearanceCharacteristicsKeyCaption)
087ocidPropertiesDict's setValue:("美しい日本語のコメント") forKey:(refMe's PDFAnnotationKeyContents)
088ocidPropertiesDict's setValue:("サブジェクトテキスト") forKey:("/Subj")
089#ポップアップ時のフォント指定
090ocidPropertiesDict's setValue:("/BIZUDGothic-Regular 18 Tf 0 g") forKey:("/DA")
091#色指定 透過指定できます
092set ocidSetColor to refMe's NSColor's colorWithSRGBRed:(0.4392) green:(0.8196) blue:(0.7764) alpha:(0.85)
093ocidPropertiesDict's setValue:(ocidSetColor) forKey:(refMe's PDFAnnotationKeyColor)
094
095################################
096#注釈の作成時のプロパティとして指定する方法
097#【1】アイコン指定方法 テキスト
098#ocidPropertiesDict's setValue:("/Help") forKey:(refMe's PDFAnnotationKeyIconName)
099#ocidPropertiesDict's setValue:("/Comment") forKey:(refMe's PDFAnnotationKeyIconName)
100#ocidPropertiesDict's setValue:("/Key") forKey:(refMe's PDFAnnotationKeyIconName)
101#ocidPropertiesDict's setValue:("/Note") forKey:(refMe's PDFAnnotationKeyIconName)
102#ocidPropertiesDict's setValue:("/NewParagraph") forKey:(refMe's PDFAnnotationKeyIconName)
103#ocidPropertiesDict's setValue:("/Paragraph") forKey:(refMe's PDFAnnotationKeyIconName)
104#ocidPropertiesDict's setValue:("/Insert") forKey:(refMe's PDFAnnotationKeyIconName)
105
106#【2】アイコン指定方法 定数
107#ocidPropertiesDict's setValue:(refMe's PDFAnnotationTextIconTypeHelp) forKey:(refMe's PDFAnnotationKeyIconName)
108#ocidPropertiesDict's setValue:(refMe's PDFAnnotationTextIconTypeComment) forKey:(refMe's PDFAnnotationKeyIconName)
109#ocidPropertiesDict's setValue:(refMe's PDFAnnotationTextIconTypeKey) forKey:(refMe's PDFAnnotationKeyIconName)
110#ocidPropertiesDict's setValue:(refMe's PDFAnnotationTextIconTypeNote) forKey:(refMe's PDFAnnotationKeyIconName)
111#ocidPropertiesDict's setValue:(refMe's PDFAnnotationTextIconTypeNewParagraph) forKey:(refMe's PDFAnnotationKeyIconName)
112#ocidPropertiesDict's setValue:(refMe's PDFAnnotationTextIconTypeParagraph) forKey:(refMe's PDFAnnotationKeyIconName)
113#ocidPropertiesDict's setValue:(refMe's PDFAnnotationTextIconTypeInsert) forKey:(refMe's PDFAnnotationKeyIconName)
114
115################################
116#注釈を作成
117set ocidTyep to (refMe's PDFAnnotationSubtypeText)
118set ocidAddAnot to refMe's PDFAnnotation's alloc()'s initWithBounds:(ocidMakeRect) forType:(ocidTyep) withProperties:(ocidPropertiesDict)
119
120################################
121#↑で作った注釈にアイコンを指定する方法
122#【3】アイコン番号で指定する
123#ocidAddAnot's setIconType:(refMe's kPDFTextAnnotationIconHelp)
124#ocidAddAnot's setIconType:(refMe's kPDFTextAnnotationIconComment)
125#ocidAddAnot's setIconType:(refMe's kPDFTextAnnotationIconKey)
126#ocidAddAnot's setIconType:(refMe's kPDFTextAnnotationIconNote)
127#ocidAddAnot's setIconType:(refMe's kPDFTextAnnotationIconNewParagraph)
128#ocidAddAnot's setIconType:(refMe's kPDFTextAnnotationIconParagraph)
129#ocidAddAnot's setIconType:(refMe's kPDFTextAnnotationIconInsert)
130
131#【4】アイコン名で指定する
132ocidAddAnot's setValue:(refMe's PDFAnnotationTextIconTypeHelp) forAnnotationKey:(refMe's PDFAnnotationKeyIconName)
133#ocidAddAnot's setValue:(refMe's PDFAnnotationTextIconTypeComment) forAnnotationKey:(refMe's PDFAnnotationKeyIconName)
134#ocidAddAnot's setValue:(refMe's PDFAnnotationTextIconTypeKey) forAnnotationKey:(refMe's PDFAnnotationKeyIconName)
135#ocidAddAnot's setValue:(refMe's PDFAnnotationTextIconTypeNote) forAnnotationKey:(refMe's PDFAnnotationKeyIconName)
136#ocidAddAnot's setValue:(refMe's PDFAnnotationTextIconTypeNewParagraph) forAnnotationKey:(refMe's PDFAnnotationKeyIconName)
137#ocidAddAnot's setValue:(refMe's PDFAnnotationTextIconTypeParagraph) forAnnotationKey:(refMe's PDFAnnotationKeyIconName)
138#ocidAddAnot's setValue:(refMe's PDFAnnotationTextIconTypeInsert) forAnnotationKey:(refMe's PDFAnnotationKeyIconName)
139
140
141################################
142#共通ICON 名
143(* Foxit Acrobat PDFKit共通 アイコン名
144ocidAddAnot's setValue:("/Comment") forAnnotationKey:("/Name")
145ocidAddAnot's setValue:("/Help") forAnnotationKey:("/Name")
146ocidAddAnot's setValue:("/Insert") forAnnotationKey:("/Name")
147ocidAddAnot's setValue:("/Key") forAnnotationKey:("/Name")
148ocidAddAnot's setValue:("/NewParagraph") forAnnotationKey:("/Name")
149ocidAddAnot's setValue:("/Note") forAnnotationKey:("/Name")
150ocidAddAnot's setValue:("/Paragraph") forAnnotationKey:("/Name")
151#Foxit Acrobat 共通ICON 名
152ocidAddAnot's setValue:("/Check") forAnnotationKey:("/Name")
153ocidAddAnot's setValue:("/Circle") forAnnotationKey:("/Name")
154ocidAddAnot's setValue:("/Cross") forAnnotationKey:("/Name")
155ocidAddAnot's setValue:("/RightArrow") forAnnotationKey:("/Name")
156ocidAddAnot's setValue:("/RightPointer") forAnnotationKey:("/Name")
157ocidAddAnot's setValue:("/Star") forAnnotationKey:("/Name")
158ocidAddAnot's setValue:("/UpArrow") forAnnotationKey:("/Name")
159ocidAddAnot's setValue:("/UpLeftArrow") forAnnotationKey:("/Name")
160#Acrobat ICON名
161ocidAddAnot's setValue:("/Checkmark") forAnnotationKey:("/Name")
162ocidAddAnot's setValue:("/CrossHairs") forAnnotationKey:("/Name")
163*)
164
165################################
166#【本処理】注釈を追加する
167ocidActivPage's addAnnotation:(ocidAddAnot)
168
169################################
170#NSDATAに変換して
171set ocidPDFdata to ocidActivDoc's dataRepresentation()
172
173################################
174#保存 パス
175set strSaveFilePath to "~/Desktop/AddAnotDone.pdf" as text
176set ocidSaveFilePathStr to (refMe's NSString's stringWithString:(strSaveFilePath))
177set ocidSaveFilePath to ocidSaveFilePathStr's stringByStandardizingPath()
178set ocidSaveFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSaveFilePath) isDirectory:false)
179
180################################
181#ファイルに保存する
182set ocidOption to (refMe's NSDataWritingAtomic)
183set listDone to ocidPDFdata's writeToURL:(ocidSaveFilePathURL) options:(ocidOption) |error| :(reference)
184if (item 1 of listDone) is true then
185  log "正常処理"
186else if (item 2 of listDone) ≠ (missing value) then
187  set strErrorNO to (item 2 of listDone)'s code() as text
188  set strErrorMes to (item 2 of listDone)'s localizedDescription() as text
189  refMe's NSLog("■:" & strErrorNO & strErrorMes)
190  return "エラーしました" & strErrorNO & strErrorMes
191end if
192
193
194
195
196
AppleScriptで生成しました

|

[PDFAnnotation]TextIconType


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#! /usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#  com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use scripting additions
009property refMe : a reference to current application
010
011#PDFTextAnnotationIconType
012log (refMe's kPDFTextAnnotationIconComment) as text
013log (refMe's kPDFTextAnnotationIconKey) as text
014log (refMe's kPDFTextAnnotationIconNote) as text
015log (refMe's kPDFTextAnnotationIconHelp) as text
016log (refMe's kPDFTextAnnotationIconNewParagraph) as text
017log (refMe's kPDFTextAnnotationIconParagraph) as text
018log (refMe's kPDFTextAnnotationIconInsert) as text
019#PDFAnnotationTextIconType
020log (refMe's PDFAnnotationTextIconTypeComment) as text
021log (refMe's PDFAnnotationTextIconTypeKey) as text
022log (refMe's PDFAnnotationTextIconTypeNote) as text
023log (refMe's PDFAnnotationTextIconTypeHelp) as text
024log (refMe's PDFAnnotationTextIconTypeNewParagraph) as text
025log (refMe's PDFAnnotationTextIconTypeParagraph) as text
026log (refMe's PDFAnnotationTextIconTypeInsert) as text
027
028(*0*)
029(*1*)
030(*2*)
031(*3*)
032(*4*)
033(*5*)
034(*6*)
035(*/Comment*)
036(*/Key*)
037(*/Note*)
038(*/Help*)
039(*/NewParagraph*)
040(*/Paragraph*)
041(*/Insert*)
AppleScriptで生成しました

|

その他のカテゴリー

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