AppleScript名:PDFの指定ページを削除 v4(複数ページ一括指定) |
— Modified 2017-08-19 by Takaaki Naganoya –Original By Shane Stanley use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "Quartz" property NSSortDescriptor : a reference to current application’s NSSortDescriptor property NSArray : a reference to current application’s NSArray property NSSet : a reference to current application’s NSSet property |NSURL| : a reference to current application’s |NSURL| property PDFDocument : a reference to current application’s PDFDocument set inFile to (choose file of type {"pdf"} with prompt "Choose your PDF files:") set targPageList to {1, 3, 5, 7, -1, -2} set pRes to removeSpecificPagesFromPDF(inFile, targPageList) of me –指定PDF書類の複数ページの一括削除 on removeSpecificPagesFromPDF(inFileAlias, targPageNumList as list) set inNSURL to |NSURL|’s fileURLWithPath:(POSIX path of inFileAlias) set theDoc to PDFDocument’s alloc()’s initWithURL:inNSURL –削除対象ページリストをユニーク化して降順ソート(後方から削除) set pRes to theDoc’s pageCount() set t3List to relativeToAbsNumList(targPageNumList, pRes) of me repeat with i in t3List copy i to targPageNum (theDoc’s removePageAtIndex:(targPageNum – 1)) end repeat –Overwrite Exsiting PDF set aRes to (theDoc’s writeToURL:inNSURL) as boolean return aRes end removeSpecificPagesFromPDF –絶対ページと相対ページが混在した削除対象ページリストを絶対ページに変換して重複削除して降順ソート on relativeToAbsNumList(aList, aMax) set newList to {} repeat with i in aList set j to contents of i if i < 0 then set j to aMax + j end if if (j ≤ aMax) and (j is not equal to 0) then set the end of newList to j end if end repeat set t1List to my uniquify1DList(newList, true) set t2List to my sort1DNumList:t1List ascOrder:false return t2List end relativeToAbsNumList on absNum(q) if q is less than 0 then set q to –q return q end absNum –1D/2D Listをユニーク化 on uniquify1DList(theList as list, aBool as boolean) set aArray to NSArray’s arrayWithArray:theList set bArray to aArray’s valueForKeyPath:"@distinctUnionOfObjects.self" return bArray as list end uniquify1DList –Sort 1-Dimension List(String Number List) on sort1DNumList:theList ascOrder:aBool tell NSSet to set theSet to setWithArray_(theList) tell NSSortDescriptor to set theDescriptor to sortDescriptorWithKey_ascending_("floatValue", aBool) set sortedList to theSet’s sortedArrayUsingDescriptors:{theDescriptor} return (sortedList) as list end sort1DNumList:ascOrder: |
タグ: 10.13savvy
PDFの指定ページを削除 v3(PDFDocument経由でアクセス)
AppleScript名:PDFの指定ページを削除 v3(PDFDocument経由でアクセス) |
— Modified 2017-08-19 by Takaaki Naganoya –Original By Shane Stanley use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "Quartz" –http://piyocast.com/as/archives/4781 property |NSURL| : a reference to current application’s |NSURL| property PDFDocument : a reference to current application’s PDFDocument set inFile to (choose file of type {"pdf"} with prompt "Choose your PDF files:") set targPage to 7 set pRes to removeSpecificPageInPDF(inFile, targPage) of me on removeSpecificPageInPDF(inFileAlias, targPageNum) set inNSURL to |NSURL|’s fileURLWithPath:(POSIX path of inFileAlias) set theDoc to PDFDocument’s alloc()’s initWithURL:inNSURL set pRes to theDoc’s pageCount() if absNum(targPageNum) of me > pRes or targPageNum = 0 then error "PDF Page Range error. This PDF document has " & (pRes as string) & " pages. But you pointed " & (targPageNum as string) & " page from your script. " & return & " (available abs range :1…" & (pRes as string) & ", relative range: -1…-" & (pRes as string) & ")" end if –Allow Relative Page Num ( -1 = the last page) if targPageNum ≤ 0 then set targPageNum to pRes + targPageNum + 1 end if theDoc’s removePageAtIndex:(targPageNum – 1) –Overwrite Exsiting PDF set aRes to (theDoc’s writeToURL:inNSURL) as boolean return aRes end removeSpecificPageInPDF on absNum(q) if q is less than 0 then set q to –q return q end absNum |
2つのPDFのテキストの指定ページの差分をVimdiffで表示する v2
2つのPDFの指定ページのテキスト内容をvimdiffで差分表示するAppleScriptです。
Terminal上でvimdiffによる差分比較を表示します。Mac AppStoreに出したアプリ(Double PDF)の部品として使ったらリジェクトされました。Terminal.appを使うものはリジェクトなんだそうで。
半日ぐらいですぐに別のルーチンに差し替えたので本Scriptはあっという間に闇から闇へと葬られました。
FileMergeがAppleScript用語辞書を持っていて単独配布されていたらいろいろ問題は解決される気がします。
AppleScript名:2つのPDFのテキストの指定ページの差分をVimdiffで表示する v2 |
— Created 2017-06-24 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "Quartz" set aPageNum to 103 –diffを表示する対象ページ set aPath to POSIX path of (choose file of type {"com.adobe.pdf"}) set a1Name to makeTmpFileStrPath(aPath) of me set aStr to retBodyStringFromPdf(aPath, aPageNum) of me set aStr1 to cleanUpText(aStr as string, string id 13, string id 10) of me –改行コードをCRからLFに置換 aStr1’s writeToFile:a1Name atomically:true encoding:(current application’s NSUTF8StringEncoding) |error|:(missing value) set bPath to POSIX path of (choose file of type {"com.adobe.pdf"}) set b1Name to makeTmpFileStrPath(bPath) of me set bStr to retBodyStringFromPdf(bPath, aPageNum) of me set bStr1 to cleanUpText(bStr as string, string id 13, string id 10) of me –改行コードをCRからLFに置換 bStr1’s writeToFile:b1Name atomically:true encoding:(current application’s NSUTF8StringEncoding) |error|:(missing value) set sText to "vimdiff " & quoted form of (a1Name as string) & " " & quoted form of (b1Name as string) doComInTerminalWindow(sText) of me on makeTmpFileStrPath(aPath) set aTmpPath to current application’s NSString’s stringWithString:(POSIX path of (path to temporary items)) set aUUID to current application’s NSUUID’s UUID()’s UUIDString() set aName to aUUID’s stringByAppendingPathExtension:"txt" set a1FullPath to (aTmpPath’s stringByAppendingString:aName) return a1FullPath end makeTmpFileStrPath on retBodyStringFromPdf(thePath as string, targPageNum as integer) set anNSURL to (current application’s |NSURL|’s fileURLWithPath:thePath) set theDoc to current application’s PDFDocument’s alloc()’s initWithURL:anNSURL set theCount to theDoc’s pageCount() as integer if targPageNum > theCount then return "" set aPage to (theDoc’s pageAtIndex:(targPageNum – 1)) set tmpStr to (aPage’s |string|()) return tmpStr end retBodyStringFromPdf on doComInTerminalWindow(aCMD) using terms from application "Terminal" tell application id "com.apple.Terminal" activate set wCount to count (every window whose visible is true) if wCount = 0 then –ウィンドウが1枚も表示されていない場合 do script "pwd" activate set size of front window to {1280, 700} do script aCMD in front window else –すでにウィンドウが表示されている場合 do script "pwd" in front window activate set size of front window to {1280, 700} do script aCMD in front window end if end tell end using terms from end doComInTerminalWindow on cleanUpText(someText, targStr, repStr) set theString to current application’s NSString’s stringWithString:someText set targString to current application’s NSString’s stringWithString:targStr set repString to current application’s NSString’s stringWithString:repStr set theString to theString’s stringByReplacingOccurrencesOfString:targString withString:repString options:(current application’s NSRegularExpressionSearch) range:{location:0, |length|:length of someText} return theString end cleanUpText |
PDFから本文テキストを抽出して配列にストアして文字列検索 v2
指定のPDFの本文テキストから、同義語をリストで与えて文字列検索を行い、出現ページのページ数を返すAppleScriptです。
PDFからの索引作成を行うために作成したものです。最初に対象PDFから本文テキストを(ページごとに)抽出してテキスト検索キャッシュを作成。
まずはこのテキスト検索キャッシュへの検索を行ったのち、ヒットしなかったらPDFに対して文字列検索を行います。
筆者の実行環境(MacBook Pro Retina 2012)で483ページある「AppleScript最新リファレンス」に対して本Scriptを実行して4.66 secぐらいです。
テキスト検索キャッシュの効果を発揮するためには、索引作成の同義語リストをまとめて与えて処理するのがベストでしょう。
AppleScript名:PDFから本文テキストを抽出して配列にストアして文字列検索 v2 |
— Created 2017-06-18 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "Quartz" use bPlus : script "BridgePlus" –検索対象の語群 set sList to {"Piyomaru Software", "ぴよまるソフトウェア"} –considering case set thePath to POSIX path of (choose file of type {"com.adobe.pdf"}) set aRes to findWordListInPDFContents(thePath, sList) of me –> {1, 3, 4, 71, 72, 75, 95, 96, 97, 98, 420, 429, 479, 483} —PDF本文テキスト中から、語群で出現ページをリストで取得(索引作成用) on findWordListInPDFContents(thePOSIXPath as string, sList as list) script spdPDF property textCache : missing value property aList : {} end script –PDFのテキスト内容をあらかじめページごとに読み取って、検索用のテキストキャッシュを作成 set anNSURL to (current application’s |NSURL|’s fileURLWithPath:thePOSIXPath) set theDoc to current application’s PDFDocument’s alloc()’s initWithURL:anNSURL set theCount to theDoc’s pageCount() as integer set (textCache of spdPDF) to current application’s NSMutableArray’s new() repeat with i from 0 to (theCount – 1) set aPage to (theDoc’s pageAtIndex:i) set tmpStr to (aPage’s |string|()) ((textCache of spdPDF)’s addObject:{pageIndex:i + 1, pageString:tmpStr}) end repeat –主にテキストキャッシュを対象にキーワード検索 repeat with s in sList –❶部分一致で抽出 set bRes to ((my filterRecListByLabel1((textCache of spdPDF), "pageString contains ’" & s & "’"))’s pageIndex) as list –❷、❶のページ単位のテキスト検索で見つからなかった場合(ページ間でまたがっている場合など) if bRes = {} then set bRes to {} set theSels to (theDoc’s findString:s withOptions:0) repeat with aSel in theSels set thePage to (aSel’s pages()’s objectAtIndex:0)’s label() set curPage to (thePage as integer) if curPage is not in bRes then set the end of bRes to curPage end if end repeat end if set the end of (aList of spdPDF) to bRes end repeat –2D list to 1D list conversion (Flatten) load framework set bList to (current application’s SMSForder’s arrayByFlattening:(aList of spdPDF)) as list –Uniquefy set cList to uniquifyList(bList) of me –Sort 1D List set anArray to current application’s NSArray’s arrayWithArray:cList set sortRes1 to (anArray’s sortedArrayUsingSelector:"compare:") as list of string or string –as anything set (textCache of spdPDF) to "" –Purge set (aList of spdPDF) to {} –Purge return sortRes1 end findWordListInPDFContents –リストに入れたレコードを、指定の属性ラベルの値で抽出 on filterRecListByLabel1(aRecList as list, aPredicate as string) set aArray to current application’s NSArray’s arrayWithArray:aRecList set aPredicate to current application’s NSPredicate’s predicateWithFormat:aPredicate set filteredArray to aArray’s filteredArrayUsingPredicate:aPredicate return filteredArray end filterRecListByLabel1 on uniquifyList(aList as list) set aArray to current application’s NSArray’s arrayWithArray:aList set bArray to aArray’s valueForKeyPath:"@distinctUnionOfObjects.self" return bArray as list end uniquifyList |
指定PDFの最初のページからアノテーションを取得する
AppleScript名:指定PDFの最初のページからアノテーションを取得する |
— Created 2017-06-08 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "Quartz" set aHFSPath to (choose file of type {"com.adobe.pdf"} with prompt "Choose a PDF with Annotation") set aPOSIX to POSIX path of aHFSPath set aURL to (current application’s |NSURL|’s fileURLWithPath:aPOSIX) set aPDFdoc to current application’s PDFDocument’s alloc()’s initWithURL:aURL set pCount to aPDFdoc’s pageCount() set firstPage to (aPDFdoc’s pageAtIndex:0) –> (PDFPage) PDFPage, label 1 set anoList to (firstPage’s annotations()) as list if anoList = {missing value} then return –指定PDF中にAnotationが存在しなかった log anoList (* {(PDFAnnotationMarkup) Type: ’Highlight’, Bounds: (81, 624) [434, 53] , (PDFAnnotationSquare) Type: ’Square’, Bounds: (50, 419) [212, 162] , (PDFAnnotationSquare) Type: ’Square’, Bounds: (301, 107) [244, 484] } *) repeat with i in anoList set aBounds to i’s |bounds|() log aBounds (* {origin:{x:80.79, y:624.4106}, size:{width:433.6944, height:52.8918}} *) (* {origin:{x:50.05553, y:419.1671}, size:{width:212.27807, height:162.3308}} *) (* {origin:{x:300.6213, y:106.8405}, size:{width:244.0961, height:484.4566}} *) end repeat |
指定PDFの最初のページからアノテーションを削除する
AppleScript名:指定PDFの最初のページからアノテーションを削除する |
— Created 2017-06-09 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "Quartz" set aHFSPath to (choose file of type {"com.adobe.pdf"} with prompt "Choose a PDF with Annotation") set aPOSIX to POSIX path of aHFSPath set aURL to (current application’s |NSURL|’s fileURLWithPath:aPOSIX) set aPDFdoc to current application’s PDFDocument’s alloc()’s initWithURL:aURL set pCount to aPDFdoc’s pageCount() set firstPage to (aPDFdoc’s pageAtIndex:0) set anoList to (firstPage’s annotations()) as list repeat with i in anoList (firstPage’s removeAnnotation:i) end repeat aPDFdoc’s writeToFile:aPOSIX |
指定PDFのすべてのページからすべてのアノテーションを削除する
AppleScript名:指定PDFのすべてのページからすべてのアノテーションを削除する |
— Created 2017-06-09 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "Quartz" set aHFSPath to (choose file of type {"com.adobe.pdf"} with prompt "Choose a PDF with Annotation") set aPOSIX to POSIX path of aHFSPath set aURL to (current application’s |NSURL|’s fileURLWithPath:aPOSIX) set aPDFdoc to current application’s PDFDocument’s alloc()’s initWithURL:aURL set pCount to aPDFdoc’s pageCount() repeat with ii from 0 to (pCount – 1) set firstPage to (aPDFdoc’s pageAtIndex:ii) set anoList to (firstPage’s annotations()) as list repeat with i in anoList (firstPage’s removeAnnotation:i) end repeat end repeat aPDFdoc’s writeToFile:aPOSIX |
指定PDFの最初のページに大量のスクウェアアノテーションを添付する
AppleScript名:指定PDFの最初のページに大量のスクウェアアノテーションを添付する |
— Created 2017-06-16 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "Quartz" use framework "AppKit" set aHFSPath to (choose file of type {"com.adobe.pdf"} with prompt "Select PDF") set aPOSIX to POSIX path of aHFSPath set aURL to (current application’s |NSURL|’s fileURLWithPath:aPOSIX) set aPDFdoc to current application’s PDFDocument’s alloc()’s initWithURL:aURL set pCount to aPDFdoc’s pageCount() set aPage to aPDFdoc’s pageAtIndex:0 set firstPage to (aPDFdoc’s pageAtIndex:0) –Remove Annotation my removeAnnotationFromPage:firstPage –Call by Reference –Get PDF size by Point set aBounds to aPage’s boundsForBox:(current application’s kPDFDisplayBoxMediaBox) set aSize to |size| of aBounds –Add Annotation repeat with xNum from 30 to ((width of aSize) – 30) by 50 repeat with yNum from 30 to ((height of aSize) – 30) by 50 set squAnn to (current application’s PDFAnnotationSquare’s alloc()’s initWithBounds:{origin:{x:xNum, y:yNum}, |size|:{width:40, height:40}}) (squAnn’s setValue:(current application’s NSColor’s blueColor()) forAnnotationKey:(current application’s kPDFAnnotationKey_Color)) (squAnn’s setValue:(current application’s NSColor’s clearColor()) forAnnotationKey:(current application’s kPDFAnnotationKey_InteriorColor)) (firstPage’s addAnnotation:squAnn) end repeat end repeat –Save It aPDFdoc’s writeToFile:aPOSIX –Remove All Annotation from a Page. Call by Reference on removeAnnotationFromPage:aPage set anoList to (aPage’s annotations()) as list repeat with i in anoList (aPage’s removeAnnotation:i) end repeat end removeAnnotationFromPage: |
指定PDFの最初のページに大量のサークルアノテーションを添付する
AppleScript名:指定PDFの最初のページに大量のサークルアノテーションを添付する |
— Created 2017-06-16 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "Quartz" use framework "AppKit" set aHFSPath to (choose file of type {"com.adobe.pdf"} with prompt "Select PDF") set aPOSIX to POSIX path of aHFSPath set aURL to (current application’s |NSURL|’s fileURLWithPath:aPOSIX) set aPDFdoc to current application’s PDFDocument’s alloc()’s initWithURL:aURL set pCount to aPDFdoc’s pageCount() set aPage to aPDFdoc’s pageAtIndex:0 set firstPage to (aPDFdoc’s pageAtIndex:0) –Remove Annotation my removeAnnotationFromPage:firstPage –Call by Reference –Get PDF size by Point set aBounds to aPage’s boundsForBox:(current application’s kPDFDisplayBoxMediaBox) set aSize to |size| of aBounds –Add Annotation repeat with xNum from 30 to ((width of aSize) – 30) by 25 repeat with yNum from 30 to ((height of aSize) – 30) by 25 set cAnn to (current application’s PDFAnnotationCircle’s alloc()’s initWithBounds:{origin:{x:xNum, y:yNum}, |size|:{width:20, height:20}}) (cAnn’s setValue:(current application’s NSColor’s redColor()) forAnnotationKey:(current application’s kPDFAnnotationKey_Color)) (firstPage’s addAnnotation:cAnn) end repeat end repeat –Save It aPDFdoc’s writeToFile:aPOSIX –Remove All Annotation from a Page. Call by Reference on removeAnnotationFromPage:aPage set anoList to (aPage’s annotations()) as list repeat with i in anoList (aPage’s removeAnnotation:i) end repeat end removeAnnotationFromPage: |
PDFのサイズをpointで取得
AppleScript名:PDFのサイズをpointで取得 |
— Created 2017-06-16 00:44:52 +0900 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "Quartz" use framework "AppKit" set aHFSPath to (choose file of type {"com.adobe.pdf"} with prompt "Select PDF") set aPOSIX to POSIX path of aHFSPath set aURL to (current application’s |NSURL|’s fileURLWithPath:aPOSIX) set aPDFdoc to current application’s PDFDocument’s alloc()’s initWithURL:aURL set pCount to aPDFdoc’s pageCount() set aPage to aPDFdoc’s pageAtIndex:0 –PDFのサイズを取得する(単位:Point) set aBounds to aPage’s boundsForBox:(current application’s kPDFDisplayBoxMediaBox) set aSize to |size| of aBounds –> {width:595.28, height:841.89} |
指定PDFの全ページからリンクアノテーションのURLを取得(http)v2
指定のPDFの全ページを走査してリンクアノテーションのURLのうちURL Schemeが”http”のものを抽出し、”http://piyocast.com/as/archives/” を含むURLを取得するAppleScriptです。
macOS 10.13以降でも動作するようにしてあります。電子書籍のPDFから本Blogへのリンクを張ってある箇所を検出するために作成したものです。
AppleScript名:指定PDFの全ページからリンクアノテーションのURLを取得(http)v2 |
— Created 2017-06-08 by Takaaki Naganoya — Modified 2018-02-14 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.5" use scripting additions use framework "Foundation" use framework "Quartz" property |NSURL| : a reference to current application’s |NSURL| property PDFDocument : a reference to current application’s PDFDocument set aPOSIX to POSIX path of (choose file of type {"com.adobe.pdf"} with prompt "Choose a PDF with Annotation") set linkList to getLinkURLFromPDF(aPOSIX, "http", "http://piyocast.com/as/archives/") of me –> {{pageNum:39, linkURL:"http://piyocast.com/as/archives/69"},….} on getLinkURLFromPDF(aPOSIX, urlScheme, condURL) set v2 to system attribute "sys2" –> macOS 10.12 =12 set aURL to (|NSURL|’s fileURLWithPath:aPOSIX) set aPDFdoc to PDFDocument’s alloc()’s initWithURL:aURL set pCount to aPDFdoc’s pageCount() set outList to {} –PDFのページでループ repeat with ii from 0 to (pCount – 1) set tmpPage to (aPDFdoc’s pageAtIndex:ii) set anoList to (tmpPage’s annotations()) as list if anoList is not equal to {missing value} then –指定PDF中にAnotationが存在した –対象PDFPage内で検出されたAnnotationでループ repeat with i in anoList if v2 < 13 then –to macOS Sierra set aType to (i’s type()) as string else –macOS High Sierra or later set aType to (i’s |Type|()) as string end if — if aType = "Link" then set tmpURL to i’s |URL|() if tmpURL is not equal to missing value then set tmpScheme to (tmpURL’s |scheme|()) as string if tmpScheme = urlScheme then set urlStr to (tmpURL’s absoluteString()) as string if (urlStr contains condURL) then set the end of outList to {pageNum:(ii + 1), linkURL:urlStr} end if end if end if end if end repeat end if end repeat return outList end getLinkURLFromPDF |
指定PDFの全ページからリンクアノテーションのURLを取得(applescript) v2
指定のPDFの全ページを走査してリンクアノテーションのURLのうちURL Schemeが”applescript”のものを抽出して、Link Scriptの内容を取得するAppleScriptです。
macOS 10.13以降でも動作するようにしてあります。
AppleScript名:指定PDFの全ページからリンクアノテーションのURLを取得(applescript) v2 |
— Created 2017-06-08 by Takaaki Naganoya — Modified 2018-02-14 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.5" use scripting additions use framework "Foundation" use framework "Quartz" property |NSURL| : a reference to current application’s |NSURL| property NSString : a reference to current application’s NSString property PDFDocument : a reference to current application’s PDFDocument property NSMutableDictionary : a reference to current application’s NSMutableDictionary property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding set aPOSIX to POSIX path of (choose file of type {"com.adobe.pdf"} with prompt "Choose a PDF with Annotation") set linkList to getLinkURLFromPDF(aPOSIX, "applescript") of me –> {{pageNum:95, linkScript:"set aStr to \"ぴよまるソフトウェア\" set aPath to choose file name……}} on getLinkURLFromPDF(aPOSIX, urlScheme) set v2 to system attribute "sys2" –> macOS 10.12 =12 set aURL to (|NSURL|’s fileURLWithPath:aPOSIX) set aPDFdoc to PDFDocument’s alloc()’s initWithURL:aURL set pCount to aPDFdoc’s pageCount() set outList to {} –PDFのページでループ repeat with ii from 0 to (pCount – 1) set tmpPage to (aPDFdoc’s pageAtIndex:ii) set anoList to (tmpPage’s annotations()) as list if anoList is not equal to {missing value} then –指定PDF中にAnotationが存在した –対象PDFPage内で検出されたAnnotationでループ repeat with i in anoList if v2 < 13 then –to macOS Sierra set aType to (i’s type()) as string else –macOS High Sierra or later set aType to (i’s |Type|()) as string end if — if aType = "Link" then set tmpURL to i’s |URL|() if tmpURL is not equal to missing value then set tmpScheme to (tmpURL’s |scheme|()) as string if tmpScheme = urlScheme then set urlStr to (tmpURL’s absoluteString()) as string set urlRec to parseQueryDictFromURLString(urlStr) of me set tmpScript to (urlRec’s |script|) as string set the end of outList to {pageNum:(ii + 1), linkScript:tmpScript} end if end if end if end repeat end if end repeat return outList end getLinkURLFromPDF on parseQueryDictFromURLString(aURLStr as string) if aURLStr = "" then error "No URL String" set aURL to |NSURL|’s URLWithString:aURLStr set aQuery to aURL’s query() –Get Query string part from URL if aQuery’s |length|() = 0 then return false set aDict to NSMutableDictionary’s alloc()’s init() set aParamList to (aQuery’s componentsSeparatedByString:"&") as list repeat with i in aParamList set j to contents of i if length of j > 0 then set tmpStr to (NSString’s stringWithString:j) set eList to (tmpStr’s componentsSeparatedByString:"=") set anElement to (eList’s firstObject()’s stringByReplacingPercentEscapesUsingEncoding:(NSUTF8StringEncoding)) set aValStr to (eList’s lastObject()’s stringByReplacingPercentEscapesUsingEncoding:(NSUTF8StringEncoding)) (aDict’s setObject:aValStr forKey:anElement) end if end repeat return aDict end parseQueryDictFromURLString |
画像の指定エリアを塗りつぶし
▲Before
▲After
AppleScript名:画像の指定エリアを塗りつぶし |
— Created 2017-11-19 by Takaaki Naganoya — Modified 2018-02-14 by Takaaki Naganoya use AppleScript version "2.5" use scripting additions use framework "Foundation" use framework "AppKit" property NSUUID : a reference to current application’s NSUUID property NSColor : a reference to current application’s NSColor property NSString : a reference to current application’s NSString property NSImage : a reference to current application’s NSImage property NSScreen : a reference to current application’s NSScreen property NSBezierPath : a reference to current application’s NSBezierPath property NSPNGFileType : a reference to current application’s NSPNGFileType property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep –塗りつぶしエリア(複数) set drawList to {{origin:{x:0, y:0}, |size|:{width:200, height:100}}, {origin:{x:300, y:100}, |size|:{width:50, height:50}}} set imgPath to POSIX path of (choose file of type {"public.image"}) set anImage to NSImage’s alloc()’s initWithContentsOfFile:imgPath set fillColor to (NSColor’s colorWithCalibratedRed:1.0 green:0.0 blue:0.0 alpha:0.9) –塗りつぶし処理呼び出し set resImage to drawImageWithColorFill(anImage, drawList, fillColor) of me set aUUIDstr to (NSUUID’s UUID()’s UUIDString()) as string set aPath to ((NSString’s stringWithString:imgPath)’s stringByDeletingLastPathComponent()’s stringByAppendingPathComponent:aUUIDstr)’s stringByAppendingPathExtension:"png" set fRes to saveImageRepAtPathAsPNG(resImage, aPath) of me on drawImageWithColorFill(anImage, drawList, fillColor) set retinaF to (NSScreen’s mainScreen()’s backingScaleFactor()) as real –> 2.0 (Retina) / 1.0 (Non Retina) anImage’s lockFocus() –描画開始 repeat with i in drawList set origX to (x of origin of i) / retinaF set origY to (y of origin of i) / retinaF set sizeX to (width of |size| of i) / retinaF set sizeY to (height of |size| of i) / retinaF set theRect to {{x:origX, y:origY}, {width:sizeX, height:sizeY}} set theNSBezierPath to NSBezierPath’s bezierPath (theNSBezierPath’s appendBezierPathWithRect:theRect) fillColor’s |set|() –色設定 theNSBezierPath’s fill() –ぬりつぶし end repeat anImage’s unlockFocus() –描画ここまで return anImage –returns NSImage end drawImageWithColorFill –画像を指定パスにPNG形式で保存 on saveImageRepAtPathAsPNG(anImage, outPath) set imageRep to anImage’s TIFFRepresentation() set aRawimg to NSBitmapImageRep’s imageRepWithData:imageRep –パスのチルダ展開処理 set pathString to NSString’s stringWithString:outPath set newPath to pathString’s stringByExpandingTildeInPath() set myNewImageData to (aRawimg’s representationUsingType:(NSPNGFileType) |properties|:(missing value)) return (myNewImageData’s writeToFile:newPath atomically:true) as boolean end saveImageRepAtPathAsPNG |
表示中のCotEditor書類の「前」のファイルを縦書きでオープン v2
CotEditorでオープン中の書類の「前」のファイルを縦書きでオープンするAppleScriptです。
CotEditorでオープン中の書類のパスを取得して、同一フォルダ内にあるファイル名一覧からオープン中の書類の「前」に該当する書類をオープンします。
ファイルオープン後にCotEditorのメニューをGUI Scriptingで強制的に操作して縦書きに設定します。
CotEditor v3.3.2のメニューにバグがあって、横書きのメニュー項目にも縦書きのメニュー項目にも「縦書き」と書いてあり、メニュー項目を名称で指定するとうまく動きません。そこだけItem No.で指定しています。このメニュー項目の不具合については、近い将来のアップデートで修正される見込みです。
▲CotEditor内蔵のScript Menuから実行するとGUI Scriptingの実行が制限されて縦書きにならない
▲OS側のScript Menuから実行すると問題なく実行できる
AppleScript名:表示中のCotEditor書類の「前」のファイルを縦書きでオープン v2 |
— Created 2017-12-15 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use bPlus : script "BridgePlus" property |NSURL| : a reference to current application’s |NSURL| property NSArray : a reference to current application’s NSArray property NSString : a reference to current application’s NSString property SMSForder : a reference to current application’s SMSForder property NSPredicate : a reference to current application’s NSPredicate property NSFileManager : a reference to current application’s NSFileManager property NSMutableArray : a reference to current application’s NSMutableArray property NSSortDescriptor : a reference to current application’s NSSortDescriptor property NSURLIsPackageKey : a reference to current application’s NSURLIsPackageKey property NSURLIsDirectoryKey : a reference to current application’s NSURLIsDirectoryKey property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles property NSDirectoryEnumerationSkipsPackageDescendants : a reference to current application’s NSDirectoryEnumerationSkipsPackageDescendants property NSDirectoryEnumerationSkipsSubdirectoryDescendants : a reference to current application’s NSDirectoryEnumerationSkipsSubdirectoryDescendants load framework tell application "CotEditor" set dCount to count every document if dCount = 0 then return tell front document set curPath to path end tell tell window 1 set aBounds to bounds end tell end tell set aPath to NSString’s stringWithString:curPath set fileName to (aPath’s lastPathComponent()) –ファイル名 set pathExtension to aPath’s pathExtension() as string set parentFol to (aPath’s stringByDeletingLastPathComponent()) as string —親フォルダ –同じフォルダから同じ拡張子のファイルのファイル名を取得 set fList to my getFilesByIncludedStringInName:(pathExtension) fromDirectory:(parentFol) exceptPackages:(true) –昇順ソート set aArray to NSArray’s arrayWithArray:fList set desc1 to NSSortDescriptor’s sortDescriptorWithKey:"self" ascending:true selector:"localizedCaseInsensitiveCompare:" set bArray to aArray’s sortedArrayUsingDescriptors:{desc1} –ファイル名検索 –set aIndex to bArray’s indexOfObjectIdenticalTo:fileName set aIndex to (SMSForder’s indexesOfItem:fileName inArray:bArray inverting:false) as list if aIndex = {} then display notification "Error: File Not Found" return end if set bIndex to (contents of first item of aIndex) + 1 – 1 –0 based to 1 based conversion & previous one set aLen to length of (bArray as list) if bIndex > aLen then display notification "Error: Out of bounds" return end if set newFile to contents of item bIndex of (bArray as list) set newPath to parentFol & "/" & newFile tell application "CotEditor" set oldDoc to front document open (POSIX file newPath) as alias tell window 1 set bounds to aBounds end tell close oldDoc without saving end tell makeWinVertical() of me –縦書き表示 –指定フォルダ内の指定文字列を含むファイル名のファイルをPOSIX pathのlistで抽出する on getFilesByIncludedStringInName:(fileNameStr as string) fromDirectory:(sourceFolder) exceptPackages:(packageF as boolean) set fileManager to NSFileManager’s defaultManager() set aURL to |NSURL|’s fileURLWithPath:sourceFolder set theOptions to ((NSDirectoryEnumerationSkipsPackageDescendants) as integer) + ((NSDirectoryEnumerationSkipsHiddenFiles) as integer) + ((NSDirectoryEnumerationSkipsSubdirectoryDescendants) as integer) set directoryContents to fileManager’s contentsOfDirectoryAtURL:aURL includingPropertiesForKeys:{} options:theOptions |error|:(missing value) set findPredicates to NSPredicate’s predicateWithFormat_("lastPathComponent CONTAINS %@", fileNameStr) set foundItemList to directoryContents’s filteredArrayUsingPredicate:findPredicates –Remove Folders From found URL Array set anArray to NSMutableArray’s alloc()’s init() repeat with i in foundItemList set j to contents of i set {theResult, isDirectory} to (j’s getResourceValue:(reference) forKey:(NSURLIsDirectoryKey) |error|:(missing value)) –Collect files if (isDirectory as boolean = false) then (anArray’s addObject:j) else if (packageF = false) then –Allow Package files? set {theResult, isPackage} to (j’s getResourceValue:(reference) forKey:(NSURLIsPackageKey) |error|:(missing value)) if (isPackage as boolean) = true then (anArray’s addObject:j) end if end if end repeat return (anArray’s valueForKey:"lastPathComponent") as list end getFilesByIncludedStringInName:fromDirectory:exceptPackages: –Make CotEditor’s front window to Vertical display mode (Tategaki) on makeWinVertical() activate application "CotEditor" tell application "System Events" tell process "CotEditor" try click menu item 3 of menu 1 of menu item "文章の方向" of menu 1 of menu bar item "フォーマット" of menu bar 1 end try end tell end tell end makeWinVertical |
表示中のCotEditor書類の「次」のファイルを縦書きでオープン v2
CotEditorでオープン中の書類の「次」のファイルを縦書きでオープンするAppleScriptです。
CotEditorでオープン中の書類のパスを取得して、同一フォルダ内にあるファイル名一覧からオープン中の書類の「次」に該当する書類をオープンします。
ファイルオープン後にCotEditorのメニューをGUI Scriptingで強制的に操作して縦書きに設定します。
CotEditor v3.3.2のメニューにバグがあって、横書きのメニュー項目にも縦書きのメニュー項目にも「縦書き」と書いてあり、メニュー項目を名称で指定するとうまく動きません。そこだけItem No.で指定しています。このメニュー項目の不具合については、近い将来のアップデートで修正される見込みです。
▲CotEditor内蔵のScript Menuから実行するとGUI Scriptingの実行が制限されて縦書きにならない
▲OS側のScript Menuから実行すると問題なく実行できる
AppleScript名:表示中のCotEditor書類の「次」のファイルを縦書きでオープン v2 |
— Created 2017-12-15 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use bPlus : script "BridgePlus" property |NSURL| : a reference to current application’s |NSURL| property NSArray : a reference to current application’s NSArray property NSString : a reference to current application’s NSString property SMSForder : a reference to current application’s SMSForder property NSPredicate : a reference to current application’s NSPredicate property NSFileManager : a reference to current application’s NSFileManager property NSMutableArray : a reference to current application’s NSMutableArray property NSSortDescriptor : a reference to current application’s NSSortDescriptor property NSURLIsPackageKey : a reference to current application’s NSURLIsPackageKey property NSURLIsDirectoryKey : a reference to current application’s NSURLIsDirectoryKey property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles property NSDirectoryEnumerationSkipsPackageDescendants : a reference to current application’s NSDirectoryEnumerationSkipsPackageDescendants property NSDirectoryEnumerationSkipsSubdirectoryDescendants : a reference to current application’s NSDirectoryEnumerationSkipsSubdirectoryDescendants load framework tell application "CotEditor" set dCount to count every document if dCount = 0 then return tell front document set curPath to path end tell tell window 1 set aBounds to bounds end tell end tell set aPath to NSString’s stringWithString:curPath set fileName to (aPath’s lastPathComponent()) –ファイル名 set pathExtension to aPath’s pathExtension() as string set parentFol to (aPath’s stringByDeletingLastPathComponent()) as string —親フォルダ –同じフォルダから同じ拡張子のファイルのファイル名を取得 set fList to my getFilesByIncludedStringInName:(pathExtension) fromDirectory:(parentFol) exceptPackages:(true) –昇順ソート set aArray to NSArray’s arrayWithArray:fList set desc1 to NSSortDescriptor’s sortDescriptorWithKey:"self" ascending:true selector:"localizedCaseInsensitiveCompare:" set bArray to aArray’s sortedArrayUsingDescriptors:{desc1} –ファイル名検索 set aIndex to (SMSForder’s indexesOfItem:fileName inArray:bArray inverting:false) as list if aIndex = {} then display notification "Error: File Not Found" return end if set bIndex to (contents of first item of aIndex) + 1 + 1 –0 based to 1 based conversion & next one set aLen to length of (bArray as list) if bIndex > aLen then display notification "Error: Out of bounds" return end if set newFile to contents of item bIndex of (bArray as list) set newPath to parentFol & "/" & newFile tell application "CotEditor" set oldDoc to front document open (POSIX file newPath) as alias tell window 1 set bounds to aBounds end tell close oldDoc without saving end tell makeWinVertical() of me –縦書き表示 –指定フォルダ内の指定文字列を含むファイル名のlistを抽出する on getFilesByIncludedStringInName:(fileNameStr as string) fromDirectory:(sourceFolder) exceptPackages:(packageF as boolean) set fileManager to NSFileManager’s defaultManager() set aURL to |NSURL|’s fileURLWithPath:sourceFolder set theOptions to (NSDirectoryEnumerationSkipsPackageDescendants as integer) + (NSDirectoryEnumerationSkipsHiddenFiles as integer) + (NSDirectoryEnumerationSkipsSubdirectoryDescendants as integer) set directoryContents to fileManager’s contentsOfDirectoryAtURL:aURL includingPropertiesForKeys:{} options:theOptions |error|:(missing value) set findPredicates to NSPredicate’s predicateWithFormat_("lastPathComponent CONTAINS %@", fileNameStr) set foundItemList to directoryContents’s filteredArrayUsingPredicate:findPredicates –Remove Folders From found URL Array set anArray to NSMutableArray’s alloc()’s init() repeat with i in foundItemList set j to contents of i set {theResult, isDirectory} to (j’s getResourceValue:(reference) forKey:(NSURLIsDirectoryKey) |error|:(missing value)) –Collect files if (isDirectory as boolean = false) then (anArray’s addObject:j) else if (packageF = false) then –Allow Package files? set {theResult, isPackage} to (j’s getResourceValue:(reference) forKey:(NSURLIsPackageKey) |error|:(missing value)) if (isPackage as boolean) = true then (anArray’s addObject:j) end if end if end repeat return (anArray’s valueForKey:"lastPathComponent") as list end getFilesByIncludedStringInName:fromDirectory:exceptPackages: –Make CotEditor’s front window to Vertical display mode (Tategaki) on makeWinVertical() activate application "CotEditor" tell application "System Events" tell process "CotEditor" try click menu item 3 of menu 1 of menu item "文章の方向" of menu 1 of menu bar item "フォーマット" of menu bar 1 end try end tell end tell end makeWinVertical |
AirServerで出力先名を宣言する
AppleScript名:AirServerで出力先名を宣言する |
tell application "AirServer" start broadcast as "Piyomaru MacBook Pro" end tell |
AirServer出力を停止する
AppleScript名:AirServer出力を停止する |
tell application "AirServer" stop broadcast end tell |
指定フォルダ以下のテキストファイルのファイル名冒頭についている数字から欠番を求める
AppleScript名:指定フォルダ以下のテキストファイルのファイル名冒頭についている数字から欠番を求める |
— Created 2017-09-04 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use framework "Foundation" use scripting additions use mdLib : script "Metadata Lib" version "1.0.0" –https://www.macosxautomation.com/applescript/apps/Script_Libs.html#Metadata_Lib use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html property NSString : a reference to current application’s NSString property SMSForder : a reference to current application’s SMSForder property NSIndexSet : a reference to current application’s NSIndexSet property NSMutableSet : a reference to current application’s NSMutableSet property NSMutableArray : a reference to current application’s NSMutableArray property NSRegularExpression : a reference to current application’s NSRegularExpression property NSRegularExpressionAnchorsMatchLines : a reference to current application’s NSRegularExpressionAnchorsMatchLines property NSRegularExpressionDotMatchesLineSeparators : a reference to current application’s NSRegularExpressionDotMatchesLineSeparators load framework –BridgePlus’s force framework loading command –選択したフォルダ以下のPlain TextをすべてSpotlightで求める(POSIX path list) set theFolder to (choose folder) set a1Dat to current application’s NSDate’s timeIntervalSinceReferenceDate() set aRes to retMissingNumberFromEachFiles(theFolder, {"public.plain-text"}) of me –> {} set b1Dat to current application’s NSDate’s timeIntervalSinceReferenceDate() set c1Dat to b1Dat – a1Dat on retMissingNumberFromEachFiles(theFolder, fileTypeList) set theFiles to mdLib’s searchFolders:{theFolder} searchString:"kMDItemContentType IN[c] %@" searchArgs:fileTypeList if theFiles = {} then return –取得したPOSIX Pathのリストからファイル名の部分のみ抽出 set anArray to NSMutableArray’s arrayWithArray:theFiles set bArray to (anArray’s valueForKeyPath:"lastPathComponent") as list –各ファイルの名称の冒頭から1~3桁 の数字を取り出して、全角–>半角変換を行いつつリストに追加 set nArray to NSMutableArray’s new() repeat with i in bArray set j to contents of i set aRes to (my findPattern:"^\\d{1,3}" inString:j) if aRes is not equal to {} then set jj to (contents of first item of aRes) as string set jj2 to (SMSForder’s transformedFrom:jj ICUTransform:"Fullwidth-Halfwidth" inverse:false) as integer (nArray’s addObject:jj2) end if end repeat –最大値、最小値をもとに連番リストを作成し、ファイル名から得られた配列データとの補集合を求める set maxRes to (nArray’s valueForKeyPath:"@max.self")’s intValue() set minRes to (nArray’s valueForKeyPath:"@min.self")’s intValue() –最小値から最大値までの連番リスト作成 set theIndexSet to NSIndexSet’s indexSetWithIndexesInRange:{minRes, maxRes} set theList to (SMSForder’s arrayWithIndexSet:theIndexSet) as list set aSet to NSMutableSet’s setWithArray:theList set bSet to NSMutableSet’s setWithArray:nArray aSet’s minusSet:bSet –補集合 return (aSet’s allObjects() as list) end retMissingNumberFromEachFiles on findPattern:thePattern inString:theString set theOptions to ((NSRegularExpressionDotMatchesLineSeparators) as integer) + ((NSRegularExpressionAnchorsMatchLines) as integer) set theRegEx to NSRegularExpression’s regularExpressionWithPattern:thePattern options:theOptions |error|:(missing value) set theFinds to theRegEx’s matchesInString:theString options:0 range:{location:0, |length|:length of theString} set theFinds to theFinds as list set theResult to {} set theNSString to NSString’s stringWithString:theString repeat with i in theFinds set theRange to (contents of i)’s range() set end of theResult to (theNSString’s substringWithRange:theRange) as string end repeat return theResult end findPattern:inString: |
指定フォルダ以下の指定形式の書類をすべてもとめて拡張子をはずしたファ
AppleScript名:指定フォルダ以下の指定形式の書類をすべてもとめて拡張子をはずしたファイル名に重複がないかチェック v2 |
— Created 2017-10-28 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use mdLib : script "Metadata Lib" version "1.0.0" –https://www.macosxautomation.com/applescript/apps/Script_Libs.html#Metadata_Lib set docUTIList to {"net.daringfireball.markdown", "com.apple.iwork.pages.sffpages"} set origFol to (choose folder) set dRes to detectDocNameDuplicateWithoutExt(origFol, docUTIList) of me –> true / false –origFolはaliasでもPOSIX pathでも可 on detectDocNameDuplicateWithoutExt(origFol, docTypeList as list) script spdMD property allResList : {} end script set (allResList of spdMD) to {} repeat with i in docTypeList set j to contents of i set aResList to (mdLib’s searchFolders:{origFol} searchString:("kMDItemContentTypeTree CONTAINS %@") searchArgs:{j}) if aResList = missing value or aResList = {} then –Hitしなかった else set (allResList of spdMD) to (allResList of spdMD) & aResList end if end repeat set aLen to length of contents of (allResList of spdMD) if aLen = 0 then error "No match" set anArray to current application’s NSArray’s arrayWithArray:(allResList of spdMD) set aRes to anArray’s valueForKeyPath:"lastPathComponent.stringByDeletingPathExtension" set b1Res to uniquify1DList(aRes as list, true) of me set b1Len to length of b1Res if aLen = b1Len then return true — No Duplicates else return false –Some duplicates end if end detectDocNameDuplicateWithoutExt –1D/2D Listをユニーク化 on uniquify1DList(theList as list, aBool as boolean) set aArray to current application’s NSArray’s arrayWithArray:theList set bArray to aArray’s valueForKeyPath:"@distinctUnionOfObjects.self" return bArray as list end uniquify1DList |
指定フォルダ以下の指定形式の書類をすべてもとめてファイル名に重複がないかチェック
AppleScript名:指定フォルダ以下の指定形式の書類をすべてもとめてファイル名に重複がないかチェック |
— Created 2017-10-28 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use mdLib : script "Metadata Lib" version "1.0.0" set origFol to POSIX path of (choose folder) set aResList to mdLib’s searchFolders:{origFol} searchString:("kMDItemContentTypeTree CONTAINS %@ || kMDItemContentTypeTree CONTAINS %@") searchArgs:{"net.daringfireball.markdown", "com.apple.iwork.pages.sffpages"} if aResList = missing value or aResList = {} then return false end if set anArray to current application’s NSArray’s arrayWithArray:aResList set aRes to anArray’s valueForKeyPath:"lastPathComponent" set bLen to length of (aRes as list) set b1Res to uniquify1DList(aRes as list, true) of me set b1Len to length of b1Res if bLen = b1Len then display dialog "No Duplicates" else display dialog "Some Duplicates" end if on getSameItemsInLists(aList as list, bList as list) –ASオブジェクトをCocoaオブジェクトに変換 set aArray to current application’s NSArray’s arrayWithArray:aList set bArray to current application’s NSArray’s arrayWithArray:bList — まとめる set allSet to current application’s NSMutableSet’s setWithArray:aArray allSet’s addObjectsFromArray:bArray –重複する要素のみ抜き出す set duplicateSet to current application’s NSMutableSet’s setWithArray:aArray duplicateSet’s intersectSet:(current application’s NSSet’s setWithArray:bArray) –重複部分だけを返す set resArray to duplicateSet’s allObjects() set resList to resArray as list return resList end getSameItemsInLists –1D/2D Listをユニーク化 on uniquify1DList(theList as list, aBool as boolean) set aArray to current application’s NSArray’s arrayWithArray:theList set bArray to aArray’s valueForKeyPath:"@distinctUnionOfObjects.self" return bArray as list end uniquify1DList |