Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

カテゴリー: PDF

Finderで選択中のPDFを古い順に連結する v2

Posted on 5月 27, 2018 by Takaaki Naganoya

Finder上で選択中のファイルのうちPDFだけを作成日付で古い順に連結するAppleScriptです。

間違ってPDF以外のファイルを選択してしまった場合でも、それについては無視します。

こんな風にmacOS標準装備のScript Menuに入れて利用しています。

AppleScript名:Finderで選択中のPDFを古い順に連結する v2
— Created 2018-05-26 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "Quartz"

property |NSURL| : a reference to current application’s |NSURL|
property NSArray : a reference to current application’s NSArray
property NSPredicate : a reference to current application’s NSPredicate
property NSFileManager : a reference to current application’s NSFileManager
property NSURLPathKey : a reference to current application’s NSURLPathKey
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 NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey
property NSURLContentModificationDateKey : a reference to current application’s NSURLContentModificationDateKey
property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles

–set inFiles to (choose file of type {"pdf"} with prompt "Choose your PDF files:" with multiple selections allowed)
tell application "Finder"
  set inFiles to selection as alias list
end tell

if inFiles = {} then return

–指定のAlias listのうちPDFのみ抽出
set filRes1 to filterAliasListByUTI(inFiles, "com.adobe.pdf") of me

–選択中のファイルのうちの1つから親フォルダを求め、出力先ファイルパスを組み立てる
set outPathTarg to POSIX path of (first item of filRes1)
set pathString to current application’s NSString’s stringWithString:outPathTarg
set newPath to (pathString’s stringByDeletingLastPathComponent()) as string
set destPosixPath to newPath & "/" & ((current application’s NSUUID’s UUID()’s UUIDString()) as string) & ".pdf"

combinePDFsAndSaveIt(filRes1, destPosixPath) of me

on combinePDFsAndSaveIt(inFiles, destPosixPath)
  set inFilesSorted to my filesInListSortFromOldToNew(inFiles)
  
  
— make URL of the first PDF
  
set inNSURL to current application’s |NSURL|’s fileURLWithPath:(POSIX path of item 1 of inFilesSorted)
  
set theDoc to current application’s PDFDocument’s alloc()’s initWithURL:inNSURL
  
  
— loop through the rest
  
set oldDocCount to theDoc’s pageCount()
  
set inFilesSorted to rest of inFilesSorted
  
  
repeat with aFile in inFilesSorted
    set inNSURL to (current application’s |NSURL|’s fileURLWithPath:(POSIX path of aFile))
    
set newDoc to (current application’s PDFDocument’s alloc()’s initWithURL:inNSURL)
    
    
set newDocCount to newDoc’s pageCount()
    
repeat with i from 1 to newDocCount
      set thePDFPage to (newDoc’s pageAtIndex:(i – 1)) — zero-based indexes
      (
theDoc’s insertPage:thePDFPage atIndex:oldDocCount)
      
set oldDocCount to oldDocCount + 1
    end repeat
    
  end repeat
  
  
set outNSURL to current application’s |NSURL|’s fileURLWithPath:destPosixPath
  (
theDoc’s writeToURL:outNSURL)
end combinePDFsAndSaveIt

on filesInListSortFromOldToNew(aliasList)
  set keysToRequest to {NSURLPathKey, NSURLIsPackageKey, NSURLIsDirectoryKey, NSURLContentModificationDateKey}
  
  
set valuesNSArray to NSMutableArray’s array()
  
repeat with i in aliasList
    set oneNSURL to (|NSURL|’s fileURLWithPath:(POSIX path of i))
    (
valuesNSArray’s addObject:(oneNSURL’s resourceValuesForKeys:keysToRequest |error|:(missing value)))
  end repeat
  
  
set theNSPredicate to NSPredicate’s predicateWithFormat_("%K == NO OR %K == YES", NSURLIsDirectoryKey, NSURLIsPackageKey)
  
set valuesNSArray to valuesNSArray’s filteredArrayUsingPredicate:theNSPredicate
  
  
set theDescriptor to NSSortDescriptor’s sortDescriptorWithKey:(NSURLContentModificationDateKey) ascending:true
  
set theSortedNSArray to valuesNSArray’s sortedArrayUsingDescriptors:{theDescriptor}
  
  
— extract just the paths and convert to an AppleScript list
  
return (theSortedNSArray’s valueForKey:(NSURLPathKey)) as list
end filesInListSortFromOldToNew

–Alias listから指定UTIに含まれるものをPOSIX pathのリストで返す
on filterAliasListByUTI(aList, targUTI)
  set newList to {}
  
repeat with i in aList
    set j to POSIX path of i
    
set tmpUTI to my retUTIfromPath(j)
    
set utiRes to my filterUTIList({tmpUTI}, targUTI)
    
if utiRes is not equal to {} then
      set the end of newList to j
    end if
  end repeat
  
return newList
end filterAliasListByUTI

–指定のPOSIX pathのファイルのUTIを求める
on retUTIfromPath(aPOSIXPath)
  set aURL to |NSURL|’s fileURLWithPath:aPOSIXPath
  
set {theResult, theValue} to aURL’s getResourceValue:(reference) forKey:NSURLTypeIdentifierKey |error|:(missing value)
  
  
if theResult = true then
    return theValue as string
  else
    return theResult
  end if
end retUTIfromPath

–UTIリストが指定UTIに含まれているかどうか演算を行う
on filterUTIList(aUTIList, aUTIstr)
  set anArray to NSArray’s arrayWithArray:aUTIList
  
set aPred to NSPredicate’s predicateWithFormat_("SELF UTI-CONFORMS-TO %@", aUTIstr)
  
set bRes to (anArray’s filteredArrayUsingPredicate:aPred) as list
  
return bRes
end filterUTIList

★Click Here to Open This Script 

Posted in file PDF Sort UTI | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

PDFを印刷するテスト v2

Posted on 4月 17, 2018 by Takaaki Naganoya
AppleScript名:PDFを印刷するテスト v2
— Created 2015-08-24 by Takaaki Naganoya
— Modified 2018-03-24 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "Quartz"
use framework "AppKit"

–Choose a PDF to print
set aDoc to POSIX path of (choose file of type {"com.adobe.pdf"})

my performSelectorOnMainThread:"printPDF:" withObject:aDoc waitUntilDone:true

on printPDF:anObject
  set aDocPath to current application’s NSString’s stringWithString:anObject
  
set aPDF to current application’s PDFDocument’s alloc()’s initWithURL:(current application’s |NSURL|’s fileURLWithPath:aDocPath)
  
  
–Make PDFView
  
set aPDFView to current application’s PDFView’s alloc()’s init()
  
aPDFView’s setDocument:aPDF
  
aPDFView’s setAutoScales:true
  
aPDFView’s setDisplaysPageBreaks:false
  
  
–Make Window
  
set aWin to current application’s NSWindow’s alloc()’s init()
  
aWin’s setContentSize:(aPDFView’s frame()’s |size|())
  
aWin’s setContentView:aPDFView
  
aWin’s |center|()
  
  
–Print PDF
  
set sharedPrintInfo to current application’s NSPrintInfo’s sharedPrintInfo()
  
aPDFView’s printWithInfo:sharedPrintInfo autoRotate:true
  
end printPDF:

★Click Here to Open This Script 

Posted in PDF | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定PDFの全ページからリンクアノテーションのURLを取得してURLを書きかえる

Posted on 3月 28, 2018 by Takaaki Naganoya

指定PDFの全ページのURLリンクアノテーションのURLを書き換えるAppleScriptです。

URL Linkアノテーションを添付したPDFに対して、Linkアノテーションのboundsを取得して削除し、同じboundsの異なるURLへのリンクアノテーションを作成して保存します。

Keynote、Pages、NumbersのiWorkアプリケーションにはオブジェクトに対してリンクを付加し、URLを指定することができるようになっていますが、URLスキームはhttpがデフォルトで指定されています。

Pages上でURLスキームを指定できたら、それはそれで使い道がいろいろありそうですが、リクエストを出してもここはhttp(かmailto)以外は有効になる気配がありません。

そこで、URLだけダミーのものをこれらのiWorkアプリケーション上で割り振っておいていったんPDF書き出しを行い、書き出されたPDFのLinkアノテーションをあとでAppleScriptから書き換えることで、任意のURLリンクを埋め込むのと同じことができるようになるだろう、と考えて実験してみました。

ただ、1つのグラフィックオブジェクトに対してKeynote上でリンクを付与してPDF書き出しすると、Keynoteがオブジェクトの領域を細分化してリンクを作成するようです。文字とグラフィックにリンクを指定しただけなのに、やたらと大量のリンクアノテーションが検出されるので、念のためにチェックしてみたらこんな(↓)感じでした。

AppleScript名:指定PDFの全ページからリンクアノテーションのURLを取得してURLを書きかえる
— Created 2017-06-08 by Takaaki Naganoya
— Modified 2018-03-14 by Takaaki Naganoya
— 2017, 2018 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 PDFActionURL : a reference to current application’s PDFActionURL
property PDFDocument : a reference to current application’s PDFDocument
property PDFAnnotationLink : a reference to current application’s PDFAnnotationLink

set aPOSIX to POSIX path of (choose file of type {"com.adobe.pdf"} with prompt "Choose a PDF with Annotation")
set linkList to replaceLinkURLFromPDF(aPOSIX, "http://www.apple.com/jp", "applescript://com.apple.scripteditor?action=new&script=display%20dialog%20%22TEST%22") of me

on replaceLinkURLFromPDF(aPOSIX, origURL, toURL)
  set v2 to system attribute "sys2" –> case: 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()
  
  
–PDFのページ(PDFPage)でループ
  
repeat with ii from 0 to (pCount – 1)
    set tmpPage to (aPDFdoc’s pageAtIndex:ii) –PDFPage
    
    
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
          set aType to (i’s type()) as string –to macOS Sierra (10.10, 10.11 & 10.12)
        else
          set aType to (i’s |Type|()) as string –macOS High Sierra (10.13) or later
        end if
        
        
–Link Annotationの削除と同様のサイズでLink Annotationの新規作成
        
if aType = "Link" then
          set tmpURL to (i’s |URL|()’s absoluteString()) as string
          
          
if tmpURL = origURL then
            set theBounds to i’s |bounds|() –削除する前にLink Annotationの位置情報を取得
            
–> {origin:{x:78.65625, y:454.7188}, size:{width:96.96875, height:4.0937}}
            
            (
tmpPage’s removeAnnotation:i) –PDFPageから指定のLink Annotationを削除  
            
            
set theLink to (PDFAnnotationLink’s alloc()’s initWithBounds:theBounds)
            
set theAction to (PDFActionURL’s alloc()’s initWithURL:(current application’s |NSURL|’s URLWithString:toURL))
            (
theLink’s setMouseUpAction:theAction)
            (
tmpPage’s addAnnotation:theLink)
            
            
log {ii + 1, theBounds, origURL}
          end if
        end if
      end repeat
    end if
  end repeat
  
  
return (aPDFdoc’s writeToFile:aPOSIX) as boolean
end replaceLinkURLFromPDF

★Click Here to Open This Script 

Posted in file PDF URL | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

Pages書類からPDF書き出し v2

Posted on 2月 25, 2018 by Takaaki Naganoya
AppleScript名:Pages書類からPDF書き出し v2
— Created 2017-03-28 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set tmpPath to (path to desktop) as string
set aRes to exportPagesDocToPDF(tmpPath)

–Pages書類からPDF書き出し
on exportPagesDocToPDF(targFolderPath as string)
  tell application "Pages"
    set dCount to count every document
    
if dCount = 0 then
      return false
    end if
    
set aPath to file of document 1
  end tell
  
  
set curPath to (current application’s NSString’s stringWithString:(POSIX path of aPath))’s lastPathComponent()’s stringByDeletingPathExtension()’s stringByAppendingString:".pdf"
  
set outPath to (targFolderPath & curPath)
  
  
  
tell application "Pages"
    set anOpt to {class:export options, image quality:Best}
    
export document 1 to file outPath as PDF with properties anOpt
  end tell
end exportPagesDocToPDF

★Click Here to Open This Script 

Posted in file PDF | Tagged 10.11savvy 10.12savvy 10.13savvy Pages | Leave a comment

Keynote書類からPDF書き出し v2

Posted on 2月 25, 2018 by Takaaki Naganoya
AppleScript名:Keynote書類からPDF書き出し v2
— Created 2017-01-21 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set tmpPath to (path to desktop) as string
set aRes to exportKeynoteDocToPDF(tmpPath)

–Keynote書類からPDF書き出し
on exportKeynoteDocToPDF(targFolderPath as string)
  
  
tell application "Keynote"
    set dCount to count every document
    
if dCount = 0 then
      return false
    end if
    
set aPath to file of document 1
  end tell
  
  
set curPath to (current application’s NSString’s stringWithString:(POSIX path of aPath))’s lastPathComponent()’s stringByDeletingPathExtension()’s stringByAppendingString:".pdf"
  
set outPath to (targFolderPath & curPath)
  
  
tell application "Keynote"
    set anOpt to {class:export options, export style:IndividualSlides, all stages:false, skipped slides:true, PDF image quality:Best}
    
export document 1 to file outPath as PDF with properties anOpt
  end tell
  
  
return (outPath as alias)
  
end exportKeynoteDocToPDF

★Click Here to Open This Script 

Keynote Control 1

Keynote Control 2

Posted in file PDF | Tagged 10.11savvy 10.12savvy 10.13savvy Keynote | Leave a comment

Numbers書類からPDF書き出し v2

Posted on 2月 25, 2018 by Takaaki Naganoya
AppleScript名:Numbers書類からPDF書き出し v2
— Created 2017-03-28 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set tmpPath to (path to desktop) as string
set aRes to exportNumbersDocToPDF(tmpPath)

–Pages書類からPDF書き出し
on exportNumbersDocToPDF(targFolderPath as string)
  tell application "Numbers"
    set dCount to count every document
    
if dCount = 0 then
      return false
    end if
    
set aPath to file of document 1
  end tell
  
  
set curPath to (current application’s NSString’s stringWithString:(POSIX path of aPath))’s lastPathComponent()’s stringByDeletingPathExtension()’s stringByAppendingString:".pdf"
  
set outPath to (targFolderPath & curPath)
  
  
  
tell application "Numbers"
    set anOpt to {class:export options, image quality:Best}
    
export document 1 to file outPath as PDF with properties anOpt
  end tell
end exportNumbersDocToPDF

★Click Here to Open This Script 

Posted in file PDF | Tagged 10.11savvy 10.12savvy 10.13savvy Numbers | Leave a comment

連番JPEGファイルを読み込んで連結したPDFを作成(新規作成)

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:連番JPEGファイルを読み込んで連結したPDFを作成(新規作成)
— Created 2016-09-20 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "QuartzCore"
use framework "Quartz"
use framework "AppKit"

set aExt to ".jpg"
set aFol to choose folder
set fList to getFilePathList(aFol, aExt) of me
set f2List to my sort1DList:fList ascOrder:true –sort by ascending

set newFile to POSIX path of (choose file name with prompt "新規PDFファイルの名称を選択")
set newFilePath to current application’s NSString’s stringWithString:newFile

–Make Blank PDF
set aPDFdoc to current application’s PDFDocument’s alloc()’s init()

set pageNum to 0

repeat with i in f2List
  set j to contents of i
  
set aURL to (current application’s |NSURL|’s fileURLWithPath:j)
  
set bImg to (current application’s NSImage’s alloc()’s initWithContentsOfURL:aURL)
  (
aPDFdoc’s insertPage:(current application’s PDFPage’s alloc()’s initWithImage:bImg) atIndex:pageNum)
  
set pageNum to pageNum + 1
end repeat

aPDFdoc’s writeToFile:newFilePath

–ASOCで指定フォルダのファイルパス一覧取得(拡張子指定つき)
on getFilePathList(aFol, aExt)
  set aPath to current application’s NSString’s stringWithString:(POSIX path of aFol)
  
set aFM to current application’s NSFileManager’s defaultManager()
  
set nameList to (aFM’s contentsOfDirectoryAtPath:aPath |error|:(missing value)) as list
  
set anArray to current application’s NSMutableArray’s alloc()’s init()
  
  
repeat with i in nameList
    set j to i as text
    
if (j ends with aExt) and (j does not start with ".") then –exclude invisible files
      set newPath to (aPath’s stringByAppendingString:j)
      (
anArray’s addObject:newPath)
    end if
  end repeat
  
  
return anArray as list
end getFilePathList

–1D List(文字)をsort / ascOrderがtrueだと昇順ソート、falseだと降順ソート
on sort1DList:theList ascOrder:aBool
  set aDdesc to current application’s NSSortDescriptor’s sortDescriptorWithKey:"self" ascending:aBool selector:"localizedCaseInsensitiveCompare:"
  
set theArray to current application’s NSArray’s arrayWithArray:theList
  
return (theArray’s sortedArrayUsingDescriptors:{aDdesc}) as list
end sort1DList:ascOrder:

★Click Here to Open This Script 

Posted in Image PDF | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

連番JPEGファイルを読み込んで連結したPDFを作成(既存のPDFに追加)

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:連番JPEGファイルを読み込んで連結したPDFを作成(既存のPDFに追加)
— Created 2016-09-20 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "QuartzCore"
use framework "Quartz"
use framework "AppKit"

set aExt to ".jpg"

set targAlias to retFrontFinderWindowsTargetIfExits(path to desktop) of me
set aFol to choose folder with prompt "追記するJPEG画像ファイルが入っているフォルダを選択" default location targAlias

set fList to getFilePathList(aFol, aExt) of me
set f2List to my sort1DList:fList ascOrder:true –sort by ascending

set newFile to POSIX path of (choose file of type {"com.adobe.pdf"} with prompt "既存のPDFファイルを選択(このPDF末尾に画像を追加)")
set newFilePath to current application’s NSString’s stringWithString:newFile
set newFileURL to current application’s |NSURL|’s fileURLWithPath:newFile

–Get Exsisting PDF’s URL and Use it
set aPDFdoc to current application’s PDFDocument’s alloc()’s initWithURL:newFileURL
set pageNum to ((aPDFdoc’s pageCount()) as integer)

repeat with i in f2List
  set j to contents of i
  
set aURL to (current application’s |NSURL|’s fileURLWithPath:j)
  
set bImg to (current application’s NSImage’s alloc()’s initWithContentsOfURL:aURL)
  (
aPDFdoc’s insertPage:(current application’s PDFPage’s alloc()’s initWithImage:bImg) atIndex:pageNum)
  
set pageNum to pageNum + 1
end repeat

aPDFdoc’s writeToFile:newFilePath

–ASOCで指定フォルダのファイルパス一覧取得(拡張子指定つき)
on getFilePathList(aFol, aExt)
  set aPath to current application’s NSString’s stringWithString:(POSIX path of aFol)
  
set aFM to current application’s NSFileManager’s defaultManager()
  
set nameList to (aFM’s contentsOfDirectoryAtPath:aPath |error|:(missing value)) as list
  
set anArray to current application’s NSMutableArray’s alloc()’s init()
  
  
repeat with i in nameList
    set j to i as text
    
if (j ends with aExt) and (j does not start with ".") then –exclude invisible files
      set newPath to (aPath’s stringByAppendingString:j)
      (
anArray’s addObject:newPath)
    end if
  end repeat
  
  
return anArray as list
end getFilePathList

–1D List(文字)をsort / ascOrderがtrueだと昇順ソート、falseだと降順ソート
on sort1DList:theList ascOrder:aBool
  set aDdesc to current application’s NSSortDescriptor’s sortDescriptorWithKey:"self" ascending:aBool selector:"localizedCaseInsensitiveCompare:"
  
set theArray to current application’s NSArray’s arrayWithArray:theList
  
return (theArray’s sortedArrayUsingDescriptors:{aDdesc}) as list
end sort1DList:ascOrder:

on retFrontFinderWindowsTargetIfExits(aDefaultLocation)
  tell application "Finder"
    set wCount to count every window
    
if wCount ≥ 1 then
      tell front window
        set aTarg to target as alias
      end tell
      
return aTarg
    else
      return aDefaultLocation
    end if
  end tell
end retFrontFinderWindowsTargetIfExits

★Click Here to Open This Script 

Posted in Image PDF | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定フォルダ内のPDFの1ページ目をすべて別のPDFにまとめる

Posted on 2月 15, 2018 by Takaaki Naganoya
AppleScript名:指定フォルダ内のPDFの1ページ目をすべて別のPDFにまとめる
— Created 2017-09-12 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "QuartzCore"

property |NSURL| : a reference to current application’s |NSURL|
property NSPredicate : a reference to current application’s NSPredicate
property NSFileManager : a reference to current application’s NSFileManager
property PDFDocument : a reference to current application’s PDFDocument
property NSMutableArray : a reference to current application’s NSMutableArray
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

set aFol to POSIX path of (choose folder with prompt "Choose folder" default location (path to pictures folder))
set targPDF to POSIX path of (choose file name with prompt "Choose File Name" default location (path to desktop folder) default name ((do shell script "uuidgen") & ".pdf"))
set pRes to gatherEachFirstPage(aFol, targPDF) of me

on gatherEachFirstPage(aFol, targPDF)
  set aURL to (|NSURL|’s fileURLWithPath:targPDF)
  
  
set outPDFdoc to PDFDocument’s alloc()’s init()
  
  
set aList to my getFilesByExtension:{"pdf"} fromDirectory:(aFol)
  
  
set outPDFPageCount to 0
  
repeat with i in aList
    –集めたPDFの1ページ目を取得
    
set bURL to (|NSURL|’s fileURLWithPath:(POSIX path of i))
    
set bPDFdoc to (PDFDocument’s alloc()’s initWithURL:bURL)
    
set bPage to (bPDFdoc’s pageAtIndex:0) –first page
    
    
–まとめ先のPDFに追記
    (
outPDFdoc’s insertPage:bPage atIndex:outPDFPageCount)
    
set outPDFPageCount to outPDFPageCount + 1
  end repeat
  
  
return (outPDFdoc’s writeToURL:aURL) as boolean
end gatherEachFirstPage

–指定フォルダ内の指定拡張子のファイルを抽出する
on getFilesByExtension:listOfExtensions fromDirectory:sourceFolder
  set fileManager to NSFileManager’s defaultManager()
  
set aURL to |NSURL|’s fileURLWithPath:sourceFolder
  
set theOptions to ((NSDirectoryEnumerationSkipsPackageDescendants) as integer) + ((NSDirectoryEnumerationSkipsHiddenFiles) as integer)
  
set directoryContents to fileManager’s contentsOfDirectoryAtURL:aURL includingPropertiesForKeys:{} options:theOptions |error|:(missing value)
  
set foundItemList to NSPredicate’s predicateWithFormat_("pathExtension.lowercaseString IN %@", listOfExtensions)
  
set foundItemList to directoryContents’s filteredArrayUsingPredicate:foundItemList
  
# Return as a list POSIX Paths
  
set foundItemList to (foundItemList’s valueForKey:"path") as list
  
return foundItemList
end getFilesByExtension:fromDirectory:

★Click Here to Open This Script 

Posted in PDF | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

PDFをページごとに分解してJPEGで保存する v3

Posted on 2月 15, 2018 by Takaaki Naganoya
AppleScript名:PDFをページごとに分解してJPEGで保存する v3
— Created 2014-12-26 by Takaaki Naganoya
— Modified 2015-09-26 by Takaaki Naganoya
— Modified 2015-10-01 by Takaaki Naganoya
— Modified 2016-07-27 by Takaaki Naganoya–Save each PDF page as jpeg
— Modified 2016-07-27 by Takaaki Naganoya–Zero padding function, Consider Retina Env
— 2016 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 "ページごとに分解するPDFを指定してください")
set aPOSIX to POSIX path of aHFSPath
set aURL to (current application’s |NSURL|’s fileURLWithPath:aPOSIX)

set aPOSIXpath to POSIX path of aHFSPath —書き出し先パスをPOSIX pathで用意しておく(あとで加工)

set aPDFdoc to current application’s PDFDocument’s alloc()’s initWithURL:aURL
set pCount to aPDFdoc’s pageCount()

set compFactor to 1.0 –1.0 — 0.0 = max jpeg compression, 1.0 = none

–Detect Retina Environment
set retinaF to current application’s NSScreen’s mainScreen()’s backingScaleFactor()
if retinaF = 1.0 then
  set aScale to 2.0 –Non Retina Env
else
  set aScale to 1.0 –Retina Env
end if

–PDFをページごとに分割してJPEGでファイル書き出し
repeat with i from 0 to (pCount – 1)
  –Pick Up a PDF page as an image
  
set thisPage to (aPDFdoc’s pageAtIndex:(i))
  
set thisDoc to (current application’s NSImage’s alloc()’s initWithData:(thisPage’s dataRepresentation()))
  
if thisDoc = missing value then error "Error in getting imagerep from PDF in page:" & (i as string)
  
  
–Resize Image
  
set pointSize to thisDoc’s |size|()
  
set newSize to current application’s NSMakeSize((pointSize’s width) * aScale, (pointSize’s height) * aScale)
  
set newImage to (current application’s NSImage’s alloc()’s initWithSize:newSize)
  
  
newImage’s lockFocus()
  (
thisDoc’s setSize:newSize)
  (
current application’s NSGraphicsContext’s currentContext()’s setImageInterpolation:(current application’s NSImageInterpolationHigh))
  (
thisDoc’s drawAtPoint:(current application’s NSZeroPoint) fromRect:(current application’s CGRectMake(0, 0, newSize’s width, newSize’s height)) operation:(current application’s NSCompositeCopy) fraction:1.0)
  
newImage’s unlockFocus()
  
  
–Save Image as JPEG
  
set theData to newImage’s TIFFRepresentation()
  
set newRep to (current application’s NSBitmapImageRep’s imageRepWithData:theData)
  
set targData to (newRep’s representationUsingType:(current application’s NSJPEGFileType) |properties|:{NSImageCompressionFactor:compFactor, NSImageProgressive:false})
  
set zText to retZeroPaddingText((i + 1), 4) of me
  
set outPath to addString_beforeExtensionIn_addingExtension_("_" & zText, aPOSIXpath, "jpg")
  
  (
targData’s writeToFile:outPath atomically:true) –書き出し
end repeat

–ファイルパス(POSIX path)に対して、文字列(枝番)を追加。任意の拡張子を追加
on addString:extraString beforeExtensionIn:aPath addingExtension:aExt
  set pathString to current application’s NSString’s stringWithString:aPath
  
set theExtension to pathString’s pathExtension()
  
set thePathNoExt to pathString’s stringByDeletingPathExtension()
  
  
set newPath to (thePathNoExt’s stringByAppendingString:extraString)’s stringByAppendingPathExtension:aExt
  
return newPath as string
end addString:beforeExtensionIn:addingExtension:

on retZeroPaddingText(aNum as integer, aDigitNum as integer)
  if aNum > (((10 ^ aDigitNum) as integer) – 1) then return "" –Range Check
  
set aFormatter to current application’s NSNumberFormatter’s alloc()’s init()
  
aFormatter’s setUsesGroupingSeparator:false
  
aFormatter’s setAllowsFloats:false
  
aFormatter’s setMaximumIntegerDigits:aDigitNum
  
aFormatter’s setMinimumIntegerDigits:aDigitNum
  
aFormatter’s setPaddingCharacter:"0"
  
set aStr to aFormatter’s stringFromNumber:(current application’s NSNumber’s numberWithFloat:aNum)
  
return aStr as string
end retZeroPaddingText

★Click Here to Open This Script 

Posted in file Image PDF | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

PDFの指定ページを削除 v4(複数ページ一括指定)

Posted on 2月 15, 2018 by Takaaki Naganoya
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:

★Click Here to Open This Script 

Posted in PDF | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

PDFの指定ページを削除 v3(PDFDocument経由でアクセス)

Posted on 2月 15, 2018 by Takaaki Naganoya
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

★Click Here to Open This Script 

Posted in PDF | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

2つのPDFのテキストの指定ページの差分をVimdiffで表示する v2

Posted on 2月 15, 2018 by Takaaki Naganoya

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

★Click Here to Open This Script 

Posted in PDF Text | Tagged 10.11savvy 10.12savvy 10.13savvy Terminal | 1 Comment

PDFから本文テキストを抽出して配列にストアして文字列検索 v2

Posted on 2月 14, 2018 by Takaaki Naganoya

指定の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

★Click Here to Open This Script 

Posted in PDF Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定PDFの最初のページからアノテーションを取得する

Posted on 2月 14, 2018 by Takaaki Naganoya
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

★Click Here to Open This Script 

Posted in PDF | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定PDFの最初のページからアノテーションを削除する

Posted on 2月 14, 2018 by Takaaki Naganoya
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

★Click Here to Open This Script 

Posted in PDF | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定PDFのすべてのページからすべてのアノテーションを削除する

Posted on 2月 14, 2018 by Takaaki Naganoya
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

★Click Here to Open This Script 

Posted in PDF | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定PDFの最初のページに大量のスクウェアアノテーションを添付する

Posted on 2月 14, 2018 by Takaaki Naganoya
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:

★Click Here to Open This Script 

Posted in PDF | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定PDFの最初のページに大量のサークルアノテーションを添付する

Posted on 2月 14, 2018 by Takaaki Naganoya
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:

★Click Here to Open This Script 

Posted in PDF | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

PDFのサイズをpointで取得

Posted on 2月 14, 2018 by Takaaki Naganoya
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​​​}

★Click Here to Open This Script 

Posted in PDF | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

Post navigation

  • Older posts
  • Newer posts

電子書籍(PDF)をオンラインストアで販売中!

Google Search

Popular posts

  • macOS 14, Sonoma
  • macOS 13.6.5 AS系のバグ、一切直らず
  • PowerPoint書類の各スライドのタイトルを取得
  • Apple純正マウス、キーボードのバッテリー残量取得
  • 指定画像をbase64エンコード文字列に変換→デコード
  • CotEditorで2つの書類の行単位での差分検出
  • 出るか?「AppleScript最新リファレンス」のバージョン2.8対応版
  • macOS 14の変更がmacOS 13にも反映
  • Finder上で選択中のPDFのページ数を加算
  • Cocoa-AppleScript Appletランタイムが動かない?
  • macOS 13 TTS環境の変化について
  • 与えられた文字列の1D Listのすべての順列組み合わせパターン文字列を返す v3(ベンチマーク用)
  • 当分、macOS 14へのアップデートを見送ります
  • macOS 14、英語環境で12時間表記文字と時刻の間に不可視スペースを入れる仕様に
  • ディスプレイをスリープ状態にして処理続行
  • HammerspoonでLuaを実行
  • 新刊発売 AppleScript最新リファレンス v2.8対応
  • PowerPointで最前面の書類をPDF書き出し
  • macOS 14, Sonoma 9月27日にリリース
  • Adobe AcrobatをAppleScriptから操作してPDF圧縮

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1390) 10.14savvy (586) 10.15savvy (434) 11.0savvy (278) 12.0savvy (195) 13.0savvy (97) 14.0savvy (42) CotEditor (62) Finder (48) iTunes (19) Keynote (105) NSAlert (60) NSArray (51) NSBezierPath (18) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (18) NSImage (41) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (117) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (59) Pages (44) Safari (41) Script Editor (23) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • Beginner
  • Benchmark
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • Clipboard
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • diff
  • drive
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • parallel processing
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2024年7月
  • 2024年6月
  • 2024年5月
  • 2024年4月
  • 2024年3月
  • 2024年2月
  • 2024年1月
  • 2023年12月
  • 2023年11月
  • 2023年10月
  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC