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

PDFフォームに入力して別名保存

Posted on 12月 5, 2019 by Takaaki Naganoya

入力フォームつきのPDFにデータ入力して別名保存するAppleScriptです。

PDFフォームといっても、別に入力したその場でどこかのサーバーにデータが送信されるわけでもなく、ただ紙に筆記用具で名前を書き込むがごとく、記入欄にデータが入力されたPDFが出来上がるだけです。

サンプルのフォーム入りPDFをみつくろって、チェックボックス項目だけ値を変更して、別名保存してみました。

本AppleScriptではフォームのうちチェックボックスのものの値だけ書き換えてみましたが、テキスト入力型の記入欄に文字データを突っ込むのも難しくはありません(多値ポップアップメニューからの選択がめんどくさい)。

AppleScript名:PDFフォームに入力して別名保存
— Created 2019-12-05 by Takaaki Naganoya
— 2019 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 PDFDocument : a reference to current application’s PDFDocument

set aHFSPath to (choose file of type {"com.adobe.pdf"} with prompt "Choose a PDF with Form")
set aPOSIX to POSIX path of aHFSPath
set aURL to (|NSURL|’s fileURLWithPath:aPOSIX)

set aPDFdoc to 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
if anoList is not equal to {missing value} then –指定PDF中にAnotationが存在する場合のみ処理
  repeat with i in anoList
    set aName to (i’s fieldName()) as string
    
    
if aName ends with "Check Box" then
      set aState to (i’s buttonWidgetState()) as boolean
      
if aState = false then
        (i’s setButtonWidgetState:true)
        
set bState to (i’s buttonWidgetState()) as boolean
      end if
    end if
  end repeat
end if

–PDFの保存先のファイル名を入力させる(あらかじめパス文字列を作成しておいてもよい)
set newFileName to POSIX path of (choose file name with prompt "Input File name to save")
if newFileName does not end with ".pdf" then
  set newFileName to newFileName & ".pdf"
end if

–フォーム内容を変更したPDFを指定のパスに新規保存
set pdfRes to (aPDFdoc’s writeToFile:newFileName) as boolean

★Click Here to Open This Script 

Posted in PDF | Tagged 10.14savvy 10.15savvy NSURL PDFDocument | Leave a comment

Double PDF v2.0完成に近づく

Posted on 11月 29, 2019 by Takaaki Naganoya

Mac App Storeで販売したはいいものの、途中(macOS 10.13)でド派手なバグをOS(PDFView)に作られ、AppleのDevelopper Supportに正式に連絡してもなしのつぶてでそのままMac App Storeに置かれている「Double PDF」。さすがに現状のままだとまずすぎるので、macOS 10.14/10.15上で動作するように改修作業を行なっている今日このごろ(macOS 10.13.xでは、動くことは動くんですがOS自体の未修正バグが多すぎて動作保証いたしかねます)。

# OSをアップデートすると機能が落ちるとは何事だろう?

PDFViewのド派手なバグ(currentPageを取得できない)を回避するために、自前でAppleScriptでいろいろ回避コードを走らせているので、ページめくりのスピードが落ちています(個人的にこれのために作ったので、テンションが落ちるところです)。

初版では画像処理にGPUImage.frameworkを同梱して利用していましたが、GPUImage1だとOpenGL経由でGPUの機能にアクセスしており、OpenGL自体が最新のmacOS 10.15では非推奨となっており、Mac App Storeでリジェクトされる危険性があります(より新しい代替APIであるMetalを使わないと因縁を付けられる気が、、、)。

そこで、GPUImageに依存しているコードをすべて書き換え、GPUImageを完全に取り外しました。これには、よくよく調べたら、PDFの各ページをグレースケール画像に変換する箇所でしか利用していなかったことが大きいです。これで、名実ともに「すべてAppleScriptで記述したアプリケーション」に。

GPUImageの除去は使い勝手には一切影響しません。若干の前向きな機能追加も行なっておきましょう。

これまでに意見として寄せられていないものの、どうもグレースケール画像で比較を行うことに不満を持っていたユーザーが一定数いるものとにらんでいたので、カラーのまま比較する機能を追加しました。

正直なところ、「カラー比較モード」は個人的には不要と思っている(文字主体の書籍の校正用に作った)のですが、念のためです。

Double PDFはデータ上のささいな違いを「見逃す」ように作ってあります。これは、Adobe AcrobatのPDF比較機能が、見た目には影響を及ぼさないデータ上の些細な違いばかりピックアップして実用性がまったくないことから思いついたものです。見た目に影響のない差異を見逃して、見た目や文字で差が発生している箇所を指摘するツールという味付けになっています。

画像サイズを小さくした上でグレースケール化して比較するのはそのための重要な機能です。ただ、間違って色が変わったことを検出したいような用途もあることでしょう。

あとは、PDFからテキスト抽出をしたときに、PDF書き出し時の環境(OSバージョン)によってはNo Width Spaceが検出されるものがあるため、No Width Spaceの削除機能を追加しました。

細かい箇所でまだ不具合点(右側のビューワーのノンブルが表示されないことがある)がありますが、とりあえず出してみてもよさそうな気配はしています。

地味なところで画像素材をDark Mode対応させました。Credits.rtfのダークモード対応など、地味に工数が増えるのは勘弁してほしいです。あとは、外部アプリケーション操作要求を行うためのInfo.plistのエントリ追加などもあります。これを追加しないと外部アプリケーションへの操作要求のダイアログ自体が出ない=一切操作できないので要注意点です。

ほかにも、現行のXcodeでCocoa AppleScriptアプリケーションのプロジェクトを作ると、デフォルトではソースコード開示状態のビルドセッティングになってしまうので、これも要チェック点でしょう。まさかと思ってこの設定を再確認してみたら、execute onlyになっていませんでした。怖すぎ、、、

Posted in AppleScript Application on Xcode Image PDF | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy | Leave a comment

Appleがいまだに直さない致命的なPDFViewのバグに対処v2

Posted on 11月 22, 2019 by Takaaki Naganoya

macOS 10.13のBetaの時にはなかったのに、Release版がバグだらけでリリース。PDFViewについて多大なる被害を受けております。PDFViewをScripting Bridge経由で使うと、macOS 10.14も10.15も状況は同じです。きちんと動かないので、仕様と言い切ることは難しいところでしょう。未修正のバグが放置されているという状況です。

Developper Supportに報告しても返答も何もないので、PDFViewのScripting Bridgeまわりはバグだらけのまま直すつもりもないのでしょう。Xcode上でプログラムを組みだすと、腹の立つことのオンパレードです。

AppleのDevelopperライセンスの延長時期がやってくると、日頃からバグだらけでOSをリリースするわバグは直さないわで、嫌がらせを受け続けているのになんでこれを契約延長しなくてはならないのか理解に苦しみます。

Apple系のMailing Listでは主流ともいえるCocoa-Dev ML上でもAppleのあり方に疑問を呈したり文句を(ていねいなお言葉で)述べる投稿がここ数週間(macOS 10.15のリリース以降)激増している今日このごろです。

いまいちどPDFViewまわりを確認してみると、PDFViewのcurrentPageを取得できない未修正の特大バグに続いて、goToPreviousPage、goToNextPageも効きません。つまり、現在表示中のページの取得も、前後ページへの移動もできないという状況です。


▲まともにオブジェクトを返してこないcurrentPage

とりあえず、Xcode上でヘッダーファイル「PDFView.h」を確認していると、currentPageのかわりになりそうなものを見つけました。それが、visiblePages。PDFView上で表示中のページを(複数)返してくるわけで、単ページ表示時にはなんとかこれが使えるかも? ということで試してみました。

–> Download pdfviewAgainstAppleBug (Xcode Project)


▲currentPageのかわりに使えそうなvisiblePages。こっちは機能している

これが使えたので応用し、かなり遠回りな処理にはなりますが、表示中のページの前後移動もできるようにしてみました。

ただ、PDFViewをもとにしたクリックスルーなPDFViewを使ってみると、いまひとつ想定どおりに動作してくれません。まだいろいろ試してみる必要がありそうです。
→ クリックスルーPDFViewは結局動作するようになり、Double PDF v2に実装できました

これらのほか、PDFViewはページ変更時のイベントやドキュメント変更時のイベントが送信されないなど、苦労させられまくりです。

Posted in Bug GUI PDF | Tagged 10.14savvy 10.15savvy PDFView | Leave a comment

macOS 10.15のPDFViewのバグに対処した簡易PDFリーダー

Posted on 11月 7, 2019 by Takaaki Naganoya

従来のmacOSではPDFリーダー「Skim」上で「applescript://」スキームのURLリンクをクリックした場合に正常にスクリプトエディタ/Script Debuggerに新規スクリプト作成のURLイベントが伝達されていました。

macOS 10.15.xには、PDFView上でPDF閲覧中にクリックしたURLが「applescript://」プロトコルの場合に、正確にデコードされるべき内容がデコードされずにスクリプトエディタに転送されるというバグが確認されています。

このmacOS 10.15のPDFViewのバグに対処するための簡易PDFリーダーのアプリケーション「PiyoREADER」を作成してみました。フリーで配布いたします。コード署名はしてありますが、ダウンロードして初回起動時にハネられるので、システム環境設定の「セキュリティとプライバシー」>「一般」で「そのまま起動」を選ぶ必要があります。

–> Download PiyoReader(2.1MB)

この簡易PDFリーダーにはもう1つ重要な機能があります。PDF中の「http://」スキームのURLリンククリック時に、本BlogのURLである場合には内部テーブルにもとづきURLをフォワードするという機能です。つまり、2018年1月末のXserver.jpによるBlog消去以前のURLを、現行のBlog上のURLに変換してオープンするというものです。

なお、PDF内に仕込まれた「applescript://」スキームのURLリンクはスクリプトエディタに、「http://」スキームのURLリンクはSafariに伝えるように固定しています。

PiyoReaderはmacOS 10.10以降で動作し、macOS 10.15以外のまともに「applescript://」スキームのURLを扱えるOSでは、「AppleScriptの穴」BlogのURL変換の機能が活用できる簡易PDFリーダーということになります。

Piyomaru Softwareが執筆・刊行している各種電子書籍には「applescript://」URLリンクが埋め込んであり、ご好評をいただいておりますが、この書籍の価値をmacOS 10.15上でも維持するためにこの簡易PDFリーダーを作成する必要に迫られました。こんなバグをAppleが作らなければ必要のなかった作業です。

レポートずみではありますが、Appleがこのバグを認識して早期に修正することを希望してやみません。

Posted in PDF URL | Tagged 10.15savvy | 4 Comments

PDFのサイズをpointで取得 v2

Posted on 9月 28, 2019 by Takaaki Naganoya

指定PDFのサイズ(幅、高さ)をPointで取得するAppleScriptです。

以前に掲載したバージョンでは、macOS 10.13以降でboundsの値の返り方が変わったことに対応できていないので(それ以前に作ったので無理もないというか、勝手にAppleが仕様を変えたのが悪い)、対処してみました。

AppleScript名:PDFのサイズをpointで取得 v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/09/28
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "Quartz"
use framework "AppKit"

property |NSURL| : a reference to current application’s |NSURL|
property PDFDocument : a reference to current application’s PDFDocument

set aHFSPath to (choose file of type {"com.adobe.pdf"} with prompt "Select PDF")
set sizeRes to retPDFSizeInfo(aHFSPath) of me
–>  {​​​​​width:595.28, ​​​​​height:841.89​​​}

–PDFのサイズを取得する(単位:Point)
on retPDFSizeInfo(aHFSPath)
  set aPOSIX to POSIX path of aHFSPath
  
set aURL to (|NSURL|’s fileURLWithPath:aPOSIX)
  
  
set aPDFdoc to PDFDocument’s alloc()’s initWithURL:aURL
  
set pCount to aPDFdoc’s pageCount()
  
set aPage to aPDFdoc’s pageAtIndex:0
  
  
set aBounds to aPage’s boundsForBox:(current application’s kPDFDisplayBoxMediaBox)
  
  
set aClass to class of aBounds
  
if aClass = record then
    set aSize to |size| of aBounds
  else if aClass = list then
    set aWidth to item 1 of item 2 of aBounds
    
set aHeight to item 2 of item 2 of aBounds
    
set aSize to {width:aWidth, height:aHeight}
  else
    error "Wrong PDF….Can not get bounds from PDF"
  end if
  
  
return aSize
end retPDFSizeInfo

★Click Here to Open This Script 

Posted in list PDF Record | Tagged 10.12savvy 10.13savvy 10.14savvy NSURL PDFDocument | Leave a comment

指定フォルダ以下のWordのファイルをすべてPDFに書き出す

Posted on 6月 22, 2019 by Takaaki Naganoya

指定フォルダ以下のWordファイルをSpotlight機能でリストアップし、かたっぱしからPDF書き出しするAppleScriptです。

Wordの制御以外はありもののルーチンを組み合わせただけなので、とくにたいした手間がかかっているわけではありません。

逆に、Wordでファイルをオープンするという動作が割とたいへんだということがわかりました。Wordの書類によっては変換の必要があるようで、オープン時に形式を聞かれました。Word書類を作成したWordのバージョン次第のようですが、注意したいところです。Script中ではオートで変換してくれるように指定しておいたものの、それほど現場でさまざまな書類を処理したわけではありません。

処理する書類の古さや、作成したWordがどのOS上で作られたかによっては、さらに何かを追加指定する必要があるかもしれません(確認は作成時最新のWord v16.24+macOS 10.12.6にて行いました)。

Spotlightでサーチして、指定フォルダ以下のWord書類をすべてリストアップしたあと、オープンしてPDFに書き出してクローズ、という動作を繰り返します。実にAppleScript「らしい」処理です。

これを、GUI Scripting(メニューやボタンの強制的な操作)だけで行うサンプルもあるようですが、GUI Scriptingは各アプリケーションの持っているAppleScriptのコマンド(AppleScript用語辞書に書かれています)に記載のない命令を「仕方なく」「例外的に」実行するだけのものであって、こういう「命令が最初から用意されているコマンド」を実行させてもメリットが何もありません。

GUI Scriptingを使ったScriptを評して「遅い」とか「確実性がない」と言われることが多いようですが、それはGUI Scriptingを使っているからです。GUI Scriptingを使うと、AppleScript本来の処理速度よりも10〜100倍ぐらい遅くなる(Cocoaの機能を活用している現代のAppleScriptだとそこから50倍ぐらい高速)ものなので、GUI Scriptingが(System Eventsを用いてメニューやボタンのクリックが行われている)多用されているAppleScriptは、本来の性能を活かせない可能性が高い(もっと高速に処理できる余地がある)ことを知っていただきたいところです。

本Scriptはそのような意味をこめて作成・公開したものです。

–> Download WordFileToPDFExporter Run-Only (Applet)

AppleScript名:WordFileToPDFExporter.scptd
— Created 2019-06-20 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use mdLib : script "Metadata Lib" version "2.0.0" –https://www.macosxautomation.com/applescript/apps/Script_Libs.html#Metadata_Lib

property NSString : a reference to current application’s NSString
property NSFileManager : a reference to current application’s NSFileManager
property NSOrderedSame : a reference to current application’s NSOrderedSame

set basePath to (path to desktop) as string –Target Folder to write PDFs
set origPath to POSIX path of (choose folder with prompt "Select Word File Orig Folder") –(path to documents folder)

–Find Word (.doc & .docx ) files by Spotlight
set resList to mdLib’s searchFolders:{origPath} searchString:("kMDItemContentTypeTree == %@ || kMDItemContentTypeTree == %@") searchArgs:{"org.openxmlformats.wordprocessingml.document", "com.microsoft.word.doc"}

if resList = {} then
  –No Word Files or Spotlight index is broken
  
display dialog "There is no Word File within your folder.." buttons {"OK"} default button 1 with icon 1
  
return
end if

set resNumLen to length of ((length of resList) as string)

–Close Word Documents without saving
closeEveryWordDocs() of me

set sCount to 1 –saving file counter
set erCount to 0

–Loop by Word files
repeat with i in resList
  set j to contents of i
  
set anAlias to (POSIX file j) as alias
  
set dRes to openWordFile(anAlias) of me
  
  
if dRes is not equal to false then
    set numStr to retZeroPaddingText(sCount, resNumLen + 1) of me
    
set newFile to basePath & numStr & "_" & (repFileNameExtension(dRes, ".pdf") of me)
    
saveWordDocAsPDF(newFile) of me
  else
    set erCount to erCount + 1
  end if
  
  
set sCount to sCount + 1 –Increment
end repeat

–Report Finish
if erCount = 0 then
  activate
  
display dialog (sCount as string) & " Word files are converted to PDF.." buttons {"OK"} default button 1 with icon 1
else
  if erCount = 1 then
    set pluralStr to ""
  else
    set pluralStr to "s"
  end if
  
  
activate
  
display dialog (sCount as string) & " Word files are converted to PDF.." & return & "But " & (erCount as string) & "file" & pluralStr & " caused error to open" buttons {"OK"} default button 1 with icon 1
end if

–最前面のWord Documentを指定パスにPDFとして書き出す
on saveWordDocAsPDF(saveHFSpathStr)
  tell application "Microsoft Word"
    save as active document file name saveHFSpathStr file format format PDF
    
close front document saving no
  end tell
end saveWordDocAsPDF

–指定パスのWord書類をオープンする
on openWordFile(aFileAlias)
  tell application "Microsoft Word"
    try
      –このあたり、予想外にいろいろオープン処理を止めるダイアログ表示などがあるようなので試行錯誤が必要
      
open aFileAlias file converter open format auto
      
tell front document
        set dName to name
      end tell
    on error
      return false
    end try
  end tell
  
return dName
end openWordFile

–Word書類をすべてクローズ。未保存のものも破棄してクローズ
on closeEveryWordDocs()
  try
    tell application "Microsoft Word"
      close every document without saving
    end tell
  end try
end closeEveryWordDocs

–ファイル名から拡張子を置換する
on repFileNameExtension(origName, newExt)
  set aName to current application’s NSString’s stringWithString:origName
  
set theExtension to aName’s pathExtension()
  
if (theExtension as string) is not equal to "" then
    set thePathNoExt to aName’s stringByDeletingPathExtension()
    
set newName to (thePathNoExt’s stringByAppendingString:newExt)
  else
    set newName to (aName’s stringByAppendingString:newExt)
  end if
  
  
return newName as string
end repFileNameExtension

–数値にゼロパディングしたテキストを返す
on retZeroPaddingText(aNum, aLen)
  set tText to ("0000000000" & aNum as text)
  
set tCount to length of tText
  
set resText to text (tCount – aLen + 1) thru tCount of tText
  
return resText
end retZeroPaddingText

★Click Here to Open This Script 

Posted in file PDF | Tagged 10.12savvy 10.13savvy 10.14savvy NSFileManager NSOrderedSame NSString Word | Leave a comment

Keynoteで選択中のスライドだけをデスクトップに画像で書き出す

Posted on 6月 20, 2019 by Takaaki Naganoya

Keynoteでオープン中の最前面の書類で、選択中のスライドだけをデスクトップにPNG画像で書き出すAppleScriptです。Keynote 9.xを必要とします(macOS 10.13以降)。

ちょっとした説明のためにKeynoteの資料の一部だけを画面上でキャプチャして、メールなどに添付して送ることはよくあります(全部送ると量がおおすぎたり、焦点がぼやけたり)。

そこで、複数枚のスライド(ページ)を選択しておくと、それらのみを画像書き出しするAppleScriptを作ってみました。Keynoteにそんな機能はないのですが、「選択中のページ番号」は取れるので、書類全体をPDF書き出ししておいて、書き出したPDFから指定ページを画像として再書き出しを行い、PDFを削除しています。

手品のように見える処理でも、実際に行える機能を組み合わせて地道に作っているだけです。問題は、「手品」が実は地道な調査と機能確認、こまごまとしたライブラリの整備の末に実現されていることが、一般の方にはわかりにくいということでしょうか(いきなり手品を求められて絶句すること多し)。

仕事の合間に作ったので、割と雑な作りです。書き出し画像のファイル名衝突チェックなどは入れていません。

それでも、スクリプトメニューに入れて利用するとなかなか便利です。

AppleScript名:Keynoteで選択中のスライドだけをデスクトップに画像で書き出す.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/06/20
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.7" — 10.13 or later
use framework "Foundation"
use framework "Quartz"
use framework "AppKit"
use scripting additions

set dtPath to (path to desktop) as string

tell application "Keynote"
  set aVer to version
  
  
considering numeric strings
    if aVer < "9.0" then
      display dialog "Too old version for this Script." buttons {"OK"} default button 1 with icon 1
      
return
    end if
  end considering
  
  
tell front document
    set aSel to selection –選択中のスライドオブジェクトへの参照がリストで入る
    
set pList to {}
    
repeat with i in aSel
      set tmpPage to slide number of i
      
set the end of pList to tmpPage
    end repeat
    
  end tell
end tell

–Keynote書類を指定フォルダにPDF書き出し(全ページ書き出し)
set savedPDFPath to exportKeynoteDocToPDF(dtPath) of me
if savedPDFPath = false then return –Error

set aPOSIXpath to POSIX path of savedPDFPath

–書き出したPDFから、部分的にPNG画像に書き出す
repeat with p in pList
  –PDFの指定ページをNSImageとして取り出す
  
set tmpNSImage to getNSImageFromPDFPage(aPOSIXpath, p) of me
  
  
–PDFの書き出しファイル名に子番号にスライド番号をつける
  
set bPath to addStringbeforeExtension(aPOSIXpath, "_" & (p as string)) of me
  
  
–PDF書き出しファイル名に
  
set newPath to repFilePathExtension(bPath, ".png") of me
  
  
–指定のNSImageを指定のパスにPNG形式で保存
  
set sRes to saveNSImageAtPathAsPNG(tmpNSImage, newPath) of me
end repeat

–書き出したPDFを削除
tell application "Finder"
  delete savedPDFPath
end tell

–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

–指定のPDFから、指定のページをNSImageで返す
on getNSImageFromPDFPage(aPOSIX, aPage as number)
  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 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
  
  
set thisPage to (aPDFdoc’s pageAtIndex:(aPage – 1))
  
set anNSImage to (current application’s NSImage’s alloc()’s initWithData:(thisPage’s dataRepresentation()))
  
  
if anNSImage = missing value then error "Error in getting imagerep from PDF"
  
  
return anNSImage
end getNSImageFromPDFPage

–ファイル名の拡張子の直前に子番号的な文字列を入れる
on addStringbeforeExtension(aPath, extraString)
  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:theExtension
  
return newPath as string
end addStringbeforeExtension

–与えられたパスの拡張子を付け替える
on repFilePathExtension(origPath, newExt)
  set aName to current application’s NSString’s stringWithString:origPath
  
set theExtension to aName’s pathExtension()
  
if (theExtension as string) is not equal to "" then
    set thePathNoExt to aName’s stringByDeletingPathExtension()
    
set newName to (thePathNoExt’s stringByAppendingString:newExt)
  else
    set newName to (aName’s stringByAppendingString:newExt)
  end if
  
return newName as string
end repFilePathExtension

–NSImageを指定パスにPNG形式で保存
on saveNSImageAtPathAsPNG(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep
  
set pathString to current application’s NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
return aRes –true/false
end saveNSImageAtPathAsPNG

★Click Here to Open This Script 

Posted in file File path Image PDF | Tagged 10.13savvy 10.14savvy Finder Keynote NSBitmapImageRep NSImage NSScreen NSString NSURL PDFDocument | Leave a comment

CotEditorで編集中のMarkdown書類をPDFプレビュー

Posted on 6月 15, 2019 by Takaaki Naganoya

CotEditorで編集中のMarkdown書類を、MacDownでPDF書き出しして、Skimでオープンして表示するAppleScriptです。

CotEditorにMarkdownのプレビュー機能がついたらいいと思っている人は多いようですが、MarkdownはMarkdownで、方言は多いし標準がないし、1枚もののMarkdown書類だけ編集できればいいのか、本などのプロジェクト単位で編集とか、目次が作成できないとダメとか、リンクした画像の扱いをどうするのかとか、対応しようとすると「ほぼ別のソフトを作るのと同じ」ぐらい手間がかかりそうです(メンテナー様ご本人談)。

そこで、AppleScript経由で他のソフトを連携させてPDFプレビューさせてみました。これなら、誰にも迷惑をかけずに、今日この時点からすぐにMarkdownのプレビューが行えます(当然、HTML書き出ししてSafariでプレビューするバージョンははるかかなた昔に作ってあります)。

ただし、OS側の機能制限の問題で、CotEditor上のスクリプトメニューから実行はできません(GUI Scriptingの実行が許可されない)。OS側のスクリプトメニューに登録して実行する必要があります。

GUI Scriptingを利用してメニュー操作を行なっているため、システム環境設定で許可しておく必要があります。

本来であれば、PDFの書き出し先フォルダ(この場合は書き出しダイアログで、GUI Scirptingを用いてCommand-Dで指定して一律に場所指定が行えるデスクトップフォルダ)に同名のPDFが存在しないかどうかチェックし、存在すれば削除するといった処理が必要ですが、面倒だったのであらかじめMarkdown書類をUUIDにリネームしておくことで、書き出されたPDFも同じくUUIDのファイル名になるため、論理上はファイル名の衝突を回避できるため、削除処理を省略しています。

AppleScript名:🌏レンダリングしてPDFプレビュー
— Created 2019-06-15 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSUUID : a reference to current application’s NSUUID
property NSWorkspace : a reference to current application’s NSWorkspace

–オープン中のMarkdown書類を取得する
tell application "CotEditor"
  tell front document
    set cStyle to coloring style
    
if cStyle is not equal to "Markdown" then
      display dialog "編集中のファイルはMarkdown書類ではないようです。" buttons {"OK"} default button 1
      
return
    end if
    
    
set aPath to path
  end tell
end tell

–一時フォルダにMarkdown書類をコピー
set sPath to (path to temporary items)
tell application "Finder"
  set sRes to (duplicate ((POSIX file aPath) as alias) to folder sPath with replacing)
end tell

–コピーしたMarkdown書類をリネーム
set s1Res to sRes as alias
set aUUID to NSUUID’s UUID()’s UUIDString() as text –UUIDを作成する
tell application "Finder"
  set name of s1Res to (aUUID & ".md")
end tell

–Markdown書類をデスクトップにPDF書き出し
set pdfRes to exportFromMacDown(POSIX path of s1Res) of me

–PDF Viewerでオープン
tell application "Skim" –Preview.appでもOK
  activate
  
open pdfRes
end tell

–一時フォルダに書き出したMarkdown書類を削除
tell application "Finder"
  delete s1Res
end tell

–指定のMacDownファイル(alias)をデスクトップ上にPDFで書き出し
on exportFromMacDown(anAlias)
  set s1Text to paragraphs of (do shell script "ls ~/Desktop/*.pdf") –pdf書き出し前のファイル一覧
  
  
tell application "MacDown"
    open {anAlias}
  end tell
  
  
macDownForceSave() of me
  
  
tell application "MacDown"
    close every document without saving
  end tell
  
  
do shell script "sync" –ねんのため
  
  
set s2Text to paragraphs of (do shell script "ls ~/Desktop/*.pdf") –pdf書き出し後のファイル一覧
  
  
set dRes to getDiffBetweenLists(s1Text, s2Text) of me –デスクトップ上のPDFファイル名一覧の差分を取得
  
set d2Res to (addItems of dRes)
  
  
if length of d2Res ≥ 1 then
    return contents of first item of d2Res
  else
    error "Error in exporting PDF to desktop folder…."
  end if
end exportFromMacDown

on getDiffBetweenLists(aArray as list, bArray as list)
  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)
  
  
–重複部分を削除する
  
allSet’s minusSet:duplicateSet
  
set resArray to (allSet’s allObjects()) as list
  
  
set aSet to current application’s NSMutableSet’s setWithArray:aArray
  
set bSet to current application’s NSMutableSet’s setWithArray:resArray
  
aSet’s intersectSet:bSet –積集合
  
set addRes to aSet’s allObjects() as list
  
  
set cSet to current application’s NSMutableSet’s setWithArray:bArray
  
cSet’s intersectSet:bSet –積集合
  
set minusRes to cSet’s allObjects() as list
  
  
return {addItems:minusRes, minusItems:addRes}
end getDiffBetweenLists

–注意!! ここでGUI Scriptingを使用。バージョンが変わったときにメニュー階層などの変更があったら書き換え
on macDownForceSave()
  activate application "MacDown"
  
tell application "System Events"
    tell process "MacDown"
      — File > Export > PDF
      
click menu item 2 of menu 1 of menu item 14 of menu 1 of menu bar item 3 of menu bar 1
      
      
–Go to Desktop Folder
      
keystroke "d" using {command down}
      
      
–Save Button on Sheet
      
click button 1 of sheet 1 of window 1
    end tell
  end tell
end macDownForceSave

–Bundle IDからアプリケーションのPathを返す
on retAppAbusolutePathFromBundleID(aBundleID)
  set appPath to NSWorkspace’s sharedWorkspace()’s absolutePathForAppBundleWithIdentifier:aBundleID
  
if appPath = missing value then return false
  
return appPath as string
end retAppAbusolutePathFromBundleID

★Click Here to Open This Script 

Posted in file File path GUI Scripting Markdown PDF shell script | Tagged 10.11savvy 10.12savvy 10.13savvy CotEditor Finder MacDown NSUUID NSWorkspace Skim | Leave a comment

Photoshop CCでファイルをオープン

Posted on 5月 29, 2019 by Takaaki Naganoya

Photoshop CCで画像ファイル/PDFをオープンするAppleScriptです。

作成と動作確認はmacOS 10.14.5+Photoshop CC2019で行っています。一般的な画像ファイルのオープンはこちら。

Adobeのアプリケーションの操作を行っていると、5分に1回ぐらい首をひねる瞬間がやってきますが、疑問に思っても無駄なので、各種操作はサブルーチンに追い出して、直接Adobeアプリケーションの相手をしないほうが精神衛生上よいと思われます(contentsという超重要な予約語がコンフリクトしているのでオブジェクトを取り出してループするときに途方に暮れるとか、アプリケーションによってはオブジェクトの座標情報の順序がおかしいとかいろいろ)。

その中でもとびきりおかしいのが、この、Photoshopでのファイルオープン時のファイルパスの取り扱いです。

結局このおかしな書き方でしかオープンしてくれない(aliasを直接openできない謎仕様)という状況で、ここで疑問が生まれると、ふたたびAdobeのアプリケーションのおかしな仕様をひととおり体験することになるのです。

# 後から気づきましたが、Photoshopのopen命令は返り値がないですね、、、、

AppleScript名:Photoshop CCで画像ファイルをオープンする
set a to choose file

set aPosix to POSIX path of a

tell application id "com.adobe.photoshop"
  open file aPosix
end tell

★Click Here to Open This Script 

PDFのオープンはこちらです。PDFをbounding boxでトリミングしてオープンするのは、Cocoaの機能を利用してもなかなか骨が折れるので、かえってPhotoshopを呼び出してPDF→画像変換を行うほうが簡単なようです。

AppleScript名:Photoshop CCでPDFをオープンする
set aFile to (choose file)
set aPOSIX to POSIX path of aFile

set aPage to 1
set aResol to 300

tell application id "com.adobe.photoshop"
  open file aPOSIX as PDF with options {class:PDF open options, page:aPage, crop page:bounding box, resolution:aResol, mode:RGB}
end tell

★Click Here to Open This Script 

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

PDFのしおり(TOC)の内容を取得する v3

Posted on 4月 11, 2019 by Takaaki Naganoya

指定のTOCつきPDFからTOCをrecord in listで取得するAppleScriptです。各TOC項目のページ数、アウトラインレベル、ラベル(ページ名称)を順次取得して配列に出力します。

先日発売したBlogアーカイブ本のTOCを本Scriptで取得すると、以下のようになります(抜粋)。

{{pageIndex:1, outlineLevel:1, outLabel:"表紙"}, {pageIndex:2, outlineLevel:1, outLabel:"商標について"}, {pageIndex:3, outlineLevel:1, outLabel:"本書をご覧になるために"}, ... {pageIndex:34, outlineLevel:1, outLabel:"2011/1"}, {pageIndex:35, outlineLevel:2, outLabel:"リスト同士のdiffをとる"}, {pageIndex:40, outlineLevel:2, outLabel:"日本の月呼称を返す"}, {pageIndex:42, outlineLevel:2, outLabel:"指定の月を1月分リスト化"},...... {pageIndex:450, outlineLevel:1, outLabel:"奥付"}}

あれ? 「本書について」(2P)という記事が掲載もれしているのを、TOC出力から見つけてしまった、、、、、、、、

AppleScript名:PDFのしおり(TOC)の内容を取得する v3
— Created 2017-01-09 by Takaaki Naganoya
— Modified 2019-04-10 by Takaaki Naganoya
— 2019 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 PDFDocument : a reference to current application’s PDFDocument
property titleList : {}

set my titleList to {}

set aFile to POSIX path of (choose file of type {"com.adobe.pdf"})

set fileURL to |NSURL|’s fileURLWithPath:aFile
set aPDFdoc to PDFDocument’s alloc()’s initWithURL:fileURL

–TOCの読み込み
set parentOL to aPDFdoc’s outlineRoot() –あらかじめTOCが存在していないとmissing valueになる
if parentOL is equal to missing value then
  display dialog "本PDFにはTOCが添付されていないため、処理を終了します" with title "No TOC Error:"
  
return
end if

getChilds(parentOL) of me
return (my titleList)
–> {{pageIndex:1, outlineLevel:1, outLabel:"表紙"}, {pageIndex:2, outlineLevel:1, outLabel:"商標について"}, {pageIndex:3, outlineLevel:1, outLabel:"本書をご覧になるために"}, {pageIndex:5, outlineLevel:1, outLabel:"まえがき"},…… {pageIndex:33, outlineLevel:1, outLabel:"2011年"}, {pageIndex:34, outlineLevel:1, outLabel:"2011/1"}, {pageIndex:35, outlineLevel:2, outLabel:"リスト同士のdiffをとる"}, {pageIndex:40, outlineLevel:2, outLabel:"日本の月呼称を返す"},…….}

–PDFOutlineを再帰で取得する
on getChilds(parentOL)
  set outLineStr to parentOL’s label()
  
set outLineCount to (parentOL’s numberOfChildren()) as number
  
  
repeat with i from 0 to (outLineCount – 1)
    set anOut to (parentOL’s childAtIndex:i)
    
    
–Label (Page Title)
    
set tmpOut to (anOut’s label()) as string
    
    
–Page Indel Label
    
set tmpInd to (anOut’s destination()’s page()’s label()) as integer
    
    
–Outline Level
    
set outlevel to 0
    
copy anOut to aTmpOut
    
repeat
      set aTmpOut to aTmpOut’s |parent|()
      
if aTmpOut = missing value then exit repeat
      
set outlevel to outlevel + 1
    end repeat
    
    
set the end of my titleList to {pageIndex:tmpInd, outlineLevel:outlevel, outLabel:tmpOut}
    
    
set tmpChild to (anOut’s numberOfChildren()) as integer
    
    
if tmpChild is not equal to 0 then
      getChilds(anOut) of me
    end if
  end repeat
end getChilds

★Click Here to Open This Script 

Posted in list PDF Record recursive call | Tagged 10.12savvy 10.13savvy 10.14savvy NSURL PDFDocument | Leave a comment

PDFのしおり(TOC)の内容を取得する v2

Posted on 4月 10, 2019 by Takaaki Naganoya

指定のTOCつきPDFからTOCを1Dリスト(1次元配列)で取得するAppleScriptです。各TOC項目のlabelの文字列を順次取得して1次元配列に出力します。

AppleScript名:PDFのしおり(TOC)の内容を取得する v2
— Created 2017-01-09 by Takaaki Naganoya
— 2017 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 PDFDocument : a reference to current application’s PDFDocument
property titleList : {}

set my titleList to {}

set aFile to POSIX path of (choose file of type {"com.adobe.pdf"})

set fileURL to |NSURL|’s fileURLWithPath:aFile
set aPDFdoc to PDFDocument’s alloc()’s initWithURL:fileURL

–TOCの読み込み
set parentOL to aPDFdoc’s outlineRoot() –あらかじめTOCが存在していないとmissing valueになる
if parentOL is equal to missing value then
  display dialog "本PDFにはTOCが添付されていないため、処理を終了します" with title "No TOC Error:"
  
return
end if

getChilds(parentOL) of me
return (my titleList)

–再帰処理してみた
on getChilds(parentOL)
  set outLineStr to parentOL’s label()
  
set outLineCount to (parentOL’s numberOfChildren()) as number
  
  
repeat with i from 0 to (outLineCount – 1)
    set anOut to (parentOL’s childAtIndex:i)
    
set tmpOut to (anOut’s label()) as string
    
set the end of my titleList to tmpOut
    
set tmpChild to (anOut’s numberOfChildren()) as integer
    
    
if tmpChild is not equal to 0 then
      getChilds(anOut) of me
    end if
  end repeat
end getChilds

★Click Here to Open This Script 

Posted in list PDF recursive call | Tagged 10.12savvy 10.13savvy 10.14savvy NSURL PDFDocument | Leave a comment

Appleがいまだに直さないPDFViewのバグを回避する

Posted on 4月 10, 2019 by Takaaki Naganoya

PDFViewからcurrentPage()が取れないという、最低最悪レベルのバグが放置されたOSがリリースされ続けて2年。Devlopper Supportに報告しても返事の1つもない今日このごろです。

Apple Developper Connectionのインシデントを消費して質問しても返答がないので、本当に頭にきています。

この、macOS 10.13のBetaでは存在しなかったのにRelease版で作られた画期的なバグを回避するために、いろいろ工夫をしてみました。

テストしてみたところ、Objective-CやSwiftでは発生していないため、Scripting Bridgeのみで発生しているらしきバグのようです。こんな基本的な箇所でバグを作って直さない連中の気が知れません。

AppleのDevelopper Supportが役立たずで仕事をしないのは今日にはじまった話ではないので(Mailing Listが落ちた状態で、報告しても1か月放置した事件など)、仕方なく回避策を検討してみました。

(1)PDFViewまわりのWrapping ClassをObjective-Cで書いて使う
(2)Objective-Cでユーティリティを書いて、パラメータとして与えたPDFViewからObjective-CでcurrentPageを取得する
(3)今後もAppleがバグを作り続けることが予想されるため、サードパーティのPSPDFKitを導入する

といった対策を検討していたのですが、最も手短なものとして、

(4)表示中のページを自前で管理して、PDFViewに指定ページの内容を随時切り出して表示する

という対処を行ってみました。

PDFをオープンしてPDFViewで表示させ、左右の矢印キーでページをめくることができます。なお、macOS 10.14.5beta+Xcode 10.2上でビルドと確認を行いましたが、内容的にはXcodeのバージョンは関係ありません。

–> Download Xcode Project Archive (pdfTestZ)

AppleScript名:AppDelegate.applescript
—
— AppDelegate.applescript
— pdfTestZ
—
— Created by Takaaki Naganoya on 2019/04/09.
— Copyright © 2019 Piyomaru Software. All rights reserved.
—

script AppDelegate
  property parent : class "NSObject"
  
  
— IBOutlets
  
property theWindow : missing value
  
property aView : missing value
  
property maxPageNum : 0
  
property curPageIndex : 0
  
property aPDFDoc : missing value
  
property pLabelField : missing value
  
  
  
on applicationWillFinishLaunching:aNotification
  
end applicationWillFinishLaunching:
  
  
on applicationShouldTerminate:sender
    return current application’s NSTerminateNow
  end applicationShouldTerminate:
  
  
  
on clicked:aSender
    set aTag to (tag of aSender) as integer
    
    
if aTag = 100 then
      set aPath to choose file of type {"com.adobe.pdf"}
      
      
set pPath to POSIX path of aPath
      
set aURL to current application’s |NSURL|’s fileURLWithPath:pPath
      
set my aPDFDoc to current application’s PDFDocument’s alloc()’s initWithURL:aURL
      
      
set myFileName to (current application’s NSString’s stringWithString:pPath)’s lastPathComponent()
      
theWindow’s setTitle:myFileName
      
      
set maxPageNum to ((aPDFDoc’s pageCount()) as integer) – 1
      
set curPageIndex to 0
      
      
log {"maxPageNum", maxPageNum}
      
      
aView’s setAutoScales:true
      
aView’s setDisplaysPageBreaks:true
      
      
my dispCurPageDoc()
      
set tmpStr to ((maxPageNum + 1) as string) & "/" & ((curPageIndex + 1) as string)
      
pLabelField’s setStringValue:tmpStr
      
    else if aTag = 200 then
      
      
set tmpPage to my (aPDFDoc’s pageAtIndex:(curPageIndex))
      
set curPageLabel to tmpPage’s label()
      
      
tell current application
        display dialog (curPageLabel as string)
      end tell
      
    else if aTag = 1000 then
      my decPage()
      
my dispCurPageDoc()
      
    else if aTag = 1010 then
      my incPage()
      
my dispCurPageDoc()
      
    end if
    
  end clicked:
  
  
on dispCurPageDoc()
    set tmpPage to my (aPDFDoc’s pageAtIndex:(curPageIndex))
    
set tmpDoc to (current application’s PDFDocument’s alloc()’s initWithData:(tmpPage’s dataRepresentation()))
    
aView’s setDocument:tmpDoc
    
    
set tmpStr to ((maxPageNum + 1) as string) & "/" & ((curPageIndex + 1) as string)
    
pLabelField’s setStringValue:tmpStr
  end dispCurPageDoc
  
  
  
on incPage()
    if curPageIndex = maxPageNum then
      –何もしない
    else if curPageIndex < maxPageNum then
      set curPageIndex to curPageIndex + 1
    end if
  end incPage
  
  
on decPage()
    if curPageIndex = 0 then
      –何もしない
    else if curPageIndex > 0 then
      set curPageIndex to curPageIndex – 1
    end if
  end decPage
end script

★Click Here to Open This Script 

Posted in AppleScript Application on Xcode PDF | Tagged 10.13savvy 10.14savvy NSString NSURL PDFDocument PDFPage | 1 Comment

Blogアーカイブ本の作成時に利用するAppleScript

Posted on 4月 1, 2019 by Takaaki Naganoya

「AppleScriptの穴」Blogアーカイブ本の作成作業には、大量のAppleScriptが使用されています。編集や執筆といった地味で地道な作業には、自動化のテクノロジーを投下しないととてもやっていられません。

「生きた事例」としてそれらをどのように使っているかをご紹介します。

・指定フォルダ以下にあるMDとPagesをソートしてPDFに書き出して連結 v4(連続複数出力可能、末尾空白ページ削除)

MarkdownによるPDF書籍の作成時にはなくてはならないScriptです。指定フォルダ以下のMarkdownとPages書類をすべてSpotlightで取得し、順次デスクトップにPDFで書き出しを行い、それらを連結します。PDFは記事単位で生成され、明示的な空白ページ(1ページの空白書類)以外の連結時には最終ページが空白であるかのチェックを行い、空白時には削除したうえで連結します。

「連続複数出力可能」というのは、複数の書籍の順次出力をサポートしているという意味です。Book1こと「AppleScript最新リファレンス」とBook2こと「最新事情がわかるAppleScript 10大最新技術」を同時に作成したので(作成期間が実質1か月ちょっとでしぬかと思いました)、その時に両方とも同時に全記事のPDF出力を行えるよう開発。複数の書籍のフォルダを指定して順次出力を行います。さすがにこれはBlogに載せていません。

電子書籍の執筆中は執筆しながら体裁を確認し、出力用のツールScriptも開発して「筆者」「編集者」「デザイナー」「開発者」という1人で何役もこなして目が回っていましたが、ツール類は一度作れば作業効率を大幅に上げたまま別の仕事(Blogアーカイブ本、とか)に使用できるのでたいへんに役立っています。自分が「原稿を書くだけの人」だったら、バイトを雇ったりしないととてもやっていられません。

また、これにInDesignの書類やPDF原稿を含めるように機能追加してもいいわけで、非常に拡張しやすく、システム化のためのベースとして活用したいところです。

・Skimのcurrent page indexをNumbers上のセルに転送してカーソル移動

PDFのTOCのデータをNumbers書類上に作成するさいに使用しています。Skimで現在表示中のページ番号をNumbersの表中の選択中のセルに文字列で転送し、Numbers上のカーソルを下方向に1つ移動させます。いいかげんTOCのデータ作成も全自動化したいところですが、PDF上で確認しつつ半自動で作成しています。それでも、すべて手作業で行うよりははるかに労力を削減できています。

・Numbersの最前面の書類からデータを取り出して指定PDFのTOCを作成する v2.scptd

Numbers上に作成したTOC(PDFしおり)データから実際に指定のPDFに階層構造つきTOCを作成するAppleScriptです。「TOCなしの数百ページのPDFなんか読みたくない」「TOCつけろ」という読者の方のありがたいアドバイスにより実戦投入。いまのバージョンはNumbersの表中の選択中のセルからデータを取得しているので、選択しなくても大丈夫なように、、、、書き換えておきます。こうして、作業上問題が発生しそうな箇所はつねにアップデートしています。

・現在表示中のページをJPEG画像で書き出す

Skim用のAppleScriptです。販売サイトに掲載する表紙などの紹介画像を作成するさいに、Skimで表示中のPDFから表示中のページの内容をJPEG画像としてデスクトップに生成します。このあたりを自動化していないと、サンプルページの掲載だけでも相当手間がかかります。

・PDFから指定ページ以降を削除

販売物を掲載したあとに、「お試し版」PDFを作成する段階で使用します。指定PDFから指定ページ以降をすべて削除するものです。これでおおよそ削除しておいてから、Adobe Acrobatで編集してTOCのうちページが存在しないものを削除したり、こまかいページの削除を行なっています。

Posted in How To PDF | Leave a comment

PSPDFkitのじっけん

Posted on 8月 30, 2018 by Takaaki Naganoya

サードパーティの有償Framework「PSPDFkit」をAppleScriptからコントロールする実験のAppleScriptです。

PSPDFkitについては以前から知っていました。サンプルもAppleよりきちんとしているので、いいんじゃないかと思っていました。

PSPDFの重要性を痛感したのは、AppleがmacOS 10.13の開発で大失敗して、α版以下のバグだらけのOSをリリースしたからです。

もはや、「公開デバッグを1年かけて行うので、最新版は使わないでね」という状態です。はい。10.13を積極的に使う意味など何もありません。

とくに、PDFKitまわりは問題だらけで、自分がMac App Storeで売っているソフトウェアも、macOS 10.13では起動してもまともに動きません(Betaで問題なく動くことを確認していたんですがー)。Developper Supportに質問を投げても返事すら来ません(本当)。

そんなわけで、PDF処理でAppleがOS内に作った機能が正しく維持される保証がなく、むしろ悪くなりそうな気配すらある昨今、PSPDFを使うのも悪くないと思えてきました。

問題は、

 ・ライセンス契約の問題 たんに「たまに動かす程度のScript」で使うのに合ったライセンス形態があるのかないのか

といったあたりでしょう。ライセンス価格表が掲載されているわけでもないので、いまひとつ不明です(ありがちー)。

→ PSPDFkitのsalesと話をしてみたら、ユーザー数と用途、OSプラットフォームなどに応じて、年ごとのビルドライセンス+実行ライセンスで契約するようです。ちなみに、試用ライセンスが切れるとスクリプトエディタ上で実行はできてしまうものの、実行直後にスクリプトエディタが終了させられます

何はともあれ、実際にPSPDFkit for macOSの試用版をダウンロードし、試用ライセンスキーを取得して(今度は真剣に)いろいろ試してみました。

ダウンロードしてきた試用版のPSPDFkit.frameworkを~/Library/Frameworksにインストールして、取得したPSPDFkitの試用版ライセンスを「current application’s PSPDFKit’s setLicenseKey:」のパラメータに書き、Control-Command-Rで「最前面で実行」(実際にはメインスレッド実行だが)を行うと動作します。

いろいろ検討してPSPDFkitは使いませんでした。macOS用だとPDFViewに該当する部品が提供されていないため、PDFView自体の代替にならないためです(そこにScripting Bridgeのバグが集中しているので)。

AppleScript名:PSPDFkitのじっけん(Script Editor)
— Created 2018-08-29 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "PSPDFKit" –https://pspdfkit.com

–This Script have to run in foreground

property PSPDFKit : a reference to current application’s PSPDFKit
property PSPDFDocument : a reference to current application’s PSPDFDocument

current application’s PSPDFKit’s setLicenseKey:"XxXX_XXXXXxXxxXXXXxxXxxxXXXxxXXXXXxXXXxXXXX"

set aPDFfile to POSIX path of (choose file)
set aURL to current application’s |NSURL|’s fileURLWithPath:aPDFfile

set aDoc to current application’s PSPDFDocument’s alloc()’s initWithURL:aURL
set pCount to (aDoc’s pageCount()) as integer
log pCount

set aVf to (aDoc’s isValid()) as boolean
log aVf

set fList to aDoc’s features()

set fName to (aDoc’s fileName()) as string

set f0Name to aDoc’s fileNameForPageAtIndex:10
set f1Name to (aDoc’s title()) as string

★Click Here to Open This Script 

この「最前面で実行」(メインスレッドで実行)する機能がScript Debuggerには存在していないので、一部Scriptを書き換えて、Script Debugger上でも動くようにしてみました。今回はたまたま動きましたが、「スクリプトエディタ上で動作するのにScript Debugger上では動作しない」ことも往々にしてありうるので、ご注意を。

AppleScript名:PSPDFkitのじっけん(Script Debugger)
— Created 2018-08-29 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "PSPDFKit" –https://pspdfkit.com

–This Script have to run in foreground

property PSPDFKit : a reference to current application’s PSPDFKit
property PSPDFDocument : a reference to current application’s PSPDFDocument

my performSelectorOnMainThread:"setLicence:" withObject:(missing value) waitUntilDone:true

set aPDFfile to POSIX path of (choose file)
set aURL to current application’s |NSURL|’s fileURLWithPath:aPDFfile

set aDoc to current application’s PSPDFDocument’s alloc()’s initWithURL:aURL
set pCount to (aDoc’s pageCount()) as integer
log pCount

set aVf to (aDoc’s isValid()) as boolean
log aVf

set fList to aDoc’s features()

set fName to (aDoc’s fileName()) as string

set f0Name to aDoc’s fileNameForPageAtIndex:10
set f1Name to (aDoc’s title()) as string

on setLicence:(anObj)
  current application’s PSPDFKit’s setLicenseKey:"XxXX_XXXXXxXxxXXXXxxXxxxXXXxxXXXXXxXXXxXXXX"
end setLicence:

★Click Here to Open This Script 

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

Skimで表示中のページ数を現在のNumbersのセルに入れて、選択セルを下にひとつ移動

Posted on 8月 18, 2018 by Takaaki Naganoya

Skimで現在表示中のPDFの現在のページ番号を、Numbers書類で選択中のセルに入れて、Numbersの選択中のセルを1つ下に移動させるAppleScriptです。

–> Watch Demo Movie

作業をちょっとだけ楽にするために作成したAppleScriptです。本来は、すべてのワークフローを自動化するのが筋ですが、限られた時間で限られた範囲の作業のみを自動化するだけでも十分な効果が得られる場合があります。

複数のアプリケーションをまたいでデータのコピー&ペーストを行うようなケースだと、ちょっとした複合作業を自動化することで作業が圧倒的に楽になります。

PDFビューワー「Skim」上でPDFを表示、Numbers上の表にページ数のデータを入れたい。

本AppleScriptを実行すると、

Numbersの選択セルにデータを突っ込んで、選択セルを1つ下に移動させます。

こうして、PDFにTOCをつけてみました(Blogアーカイブ書籍のマイナーバージョンアップ版のため。再ダウンロードでアップデート可能になります)。元データがあるんだから、TOCごと自動で作ってもいいようなものですが、久しぶりだったので(TOC用データを)手で作ってみました。

ここで、意地でもGUI Scriptingを使わないで処理すると、バックグラウンドでも安全に処理できるので大きなメリットがあります。GUI Scriptingだと最前面(フォアグラウンド)でしか操作が保証されていないので、バックグラウンドで操作できたとしてもそれは「ラッキー」でしかありません。

AppleScript名:Skimで表示中のページ数を現在のNumbersのセルに入れて、選択セルを下にひとつ移動
— Created 2018-08-18 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

tell application "Skim"
  tell front document
    set curPage to index of current page
  end tell
end tell

set curPageStr to curPage as string

tell application "Numbers"
  tell front document
    tell active sheet
      tell table 1
        set mySelectedRanges to properties of selection range
        
set value of cells of selection range to {curPageStr}
        
        
set selName to name of selection range –選択範囲のrange情報を取得
        
set {s1, s2} to parseByDelim(selName, ":") of me
        
        
set s1Row to (address of row of range s1) as integer
        
set colStr to (name of column of range s1) as string
        
        
set rowStr to (s1Row + 1) as string
        
        
set adrStr to colStr & rowStr
        
set rangeStr to adrStr & ":" & adrStr
        
try
          set selection range to range rangeStr
        on error
          –Range Over Error from table 1
          
display dialog "表の範囲をオーバーします"
          
return
        end try
      end tell
    end tell
  end tell
end tell

–テキストを指定デリミタでリスト化
on parseByDelim(aData, aDelim)
  set aText to current application’s NSString’s stringWithString:aData
  
set aList to aText’s componentsSeparatedByString:aDelim
  
return aList as list
end parseByDelim

★Click Here to Open This Script 

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

PDFから指定ページ以降を削除

Posted on 7月 10, 2018 by Takaaki Naganoya

PDFから指定ページ以降を削除するAppleScriptです。

こんな(↑)418ページもあるPDFから、おためし版の、冒頭から40ページだけ抽出したPDFを作成する際に使用したものです。

もともとは418ページありましたが、、、

実行後は40ページに、、、

AppleScript名:PDFから指定ページ以降を削除
— Modified 2018-07-08 by Takaaki Naganoya
–Original By Shane Stanley
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "QuartzCore"
use aBplus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

property NSSet : a reference to current application’s NSSet
property |NSURL| : a reference to current application’s |NSURL|
property NSArray : a reference to current application’s NSArray
property SMSForder : a reference to current application’s SMSForder
property NSIndexSet : a reference to current application’s NSIndexSet
property PDFDocument : a reference to current application’s PDFDocument
property NSSortDescriptor : a reference to current application’s NSSortDescriptor

load framework

set sPage to 41 –ここから末尾までのページを削除
set inFile to (choose file of type {"pdf"} with prompt "Choose your PDF files:")
set pRes to removePDFPageAfter(inFile, sPage) of me

–指定パスのPDFの指定ページ以降をすべて削除
on removePDFPageAfter(inFile, sPage)
  set pCount to pdfPageCount(inFile) of me
  
set eCount to pCount – sPage + 1
  
  
set aindexSet to NSIndexSet’s indexSetWithIndexesInRange:(current application’s NSMakeRange(sPage, eCount))
  
set targPageList to (SMSForder’s arrayWithIndexSet:aindexSet) as list
  
  
return removeSpecificPagesFromPDF(inFile, targPageList) of me
end removePDFPageAfter

–指定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 uniquify1DList(newList, true) of me
  
set t2List to sort1DNumListWithOrder(t1List, false) of me
  
  
return t2List
end relativeToAbsNumList

–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 sort1DNumListWithOrder(theList as list, aBool as boolean)
  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 sort1DNumListWithOrder

–指定PDFのページ数をかぞえる(10.9対応。普通にPDFpageから取得)
–返り値:PDFファイルのページ数(整数値)
on pdfPageCount(aFile)
  set aFile to POSIX path of aFile
  
set theURL to |NSURL|’s fileURLWithPath:aFile
  
set aPDFdoc to PDFDocument’s alloc()’s initWithURL:theURL
  
set aRes to aPDFdoc’s pageCount()
  
return aRes as integer
end pdfPageCount

★Click Here to Open This Script 

Posted in file PDF | Tagged 10.11savvy 10.12savvy 10.13savvy NSArray NSIndexSet NSSet NSSortDescriptor NSURL PDFDocument | Leave a comment

SkimでPDF表示モードを「単一」と「2ページ見開き」でトグル切り替え

Posted on 7月 1, 2018 by Takaaki Naganoya

オープンソースのPDFビューワー「Skim」でPDF表示モードを「単一ページ」と「2ページ見開き」でトグル切り替えするAppleScriptです。


▲Skim 単一ページ表示モード


▲Skim 2ページ見開きモード

一応、macOS標準搭載のScript Menuから呼び出して実行できることを確認していますが、、、

正直なところ、ウィンドウ上のボタンを操作したほうがScript Menuを操作するよりも手っ取り早いので、本Scriptに実用性はほとんどありません。

単に、SkimのPDF表示モードの指定方法を調べたので、その方法をScriptで記述しておいた(スケッチ)ぐらいの意味合いです。

AppleScript名:SkimでPDF表示モードを「単一」と「2ページ見開き」でトグル切り替え
tell application "Skim"
  tell front document
    set curViewSets to view settings
    
–> {auto scales:true, displays as book:false, displays page breaks:true, scale factor:1.235772357724, display mode:two up, display box:crop box}
    
    
set curMode to display mode of curViewSets
    
    
if curMode = single page then
      set display mode of curViewSets to two up
    else
      set display mode of curViewSets to single page
    end if
    
    
set view settings to curViewSets
  end tell
end tell

★Click Here to Open This Script 

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

Skimで現在表示中のPDFのページをJPEG画像で書き出す

Posted on 6月 30, 2018 by Takaaki Naganoya

オープンソースのPDFビューワー「Skim」で現在表示中のPDFの現在表示中のページをJPEG画像で書き出すAppleScriptです。

macOS標準装備のPreview.appはつい最近AppleScriptからの制御が公式に行えるようになった程度で、対応度も最低限です。Skimであれば、こうした「現在オープン中のPDFの表示中のページ」の番号を取得することもできます。

macOS標準装備のScript Menuから呼び出して利用することを前提に作成してあります。

Skimでオープン中の最前面のPDFと同じフォルダに、元ファイル名に対してページの数値をゼロパディングして追加したものをJPEG画像のファイル名に指定しています。ファイル名の重複回避などは行っていません。

ただし、Skimで表示モードが「単一」(1ページ分のみビューワーに表示)以外になっていると、カレントページ(現在表示中のページ)が画面上とアプリケーション側で管理しているものがズレることがあるので、表示モードを「単一」に切り替えてから「このページでよいか?」といった確認をユーザーに対して行うとよいかもしれません。

AppleScript名:Skimで現在表示中のPDFのページをJPEG画像で書き出す
— Created 2018-06-30 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "Quartz"
use framework "AppKit"

property |NSURL| : a reference to current application’s |NSURL|
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 NSNumber : a reference to current application’s NSNumber
property NSZeroPoint : a reference to current application’s NSZeroPoint
property PDFDocument : a reference to current application’s PDFDocument
property NSJPEGFileType : a reference to current application’s NSJPEGFileType
property NSCompositeCopy : a reference to current application’s NSCompositeCopy
property NSGraphicsContext : a reference to current application’s NSGraphicsContext
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
property NSNumberFormatter : a reference to current application’s NSNumberFormatter
property NSImageInterpolationHigh : a reference to current application’s NSImageInterpolationHigh

tell application "Skim"
  set docCount to count every document
  
if docCount = 0 then return
  
  
tell front document
    set curInd to index of current page
    
set docFile to file of it
  end tell
end tell

set aPOSIX to POSIX path of docFile
set aURL to (|NSURL|’s fileURLWithPath:aPOSIX)

set aPDFdoc to 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 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でファイル書き出し
set i to (curInd – 1) –AppleScript index (1 based) to Cocoa index (0 based) conversion

–Pick Up a PDF page as an image
set thisPage to (aPDFdoc’s pageAtIndex:(i))
set thisDoc to (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 (NSImage’s alloc()’s initWithSize:newSize)

newImage’s lockFocus()
(
thisDoc’s setSize:newSize)
(
NSGraphicsContext’s currentContext()’s setImageInterpolation:(NSImageInterpolationHigh))
(
thisDoc’s drawAtPoint:(NSZeroPoint) fromRect:(current application’s CGRectMake(0, 0, newSize’s width, newSize’s height)) operation:(NSCompositeCopy) fraction:2.0)
newImage’s unlockFocus()

–Save Image as JPEG
set theData to newImage’s TIFFRepresentation()
set newRep to (NSBitmapImageRep’s imageRepWithData:theData)
set targData to (newRep’s representationUsingType:(NSJPEGFileType) |properties|:{NSImageCompressionFactor:compFactor, NSImageProgressive:false})
set zText to retZeroPaddingText((i + 1), 4) of me
set outPath to addString_beforeExtensionIn_addingExtension_("_" & zText, aPOSIX, "jpg")

(targData’s writeToFile:outPath atomically:true) –書き出し

–ファイルパス(POSIX path)に対して、文字列(枝番)を追加。任意の拡張子を追加
on addString:extraString beforeExtensionIn:aPath addingExtension:aExt
  set pathString to 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 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:(NSNumber’s numberWithFloat:aNum)
  
return aStr as string
end retZeroPaddingText

★Click Here to Open This Script 

Posted in Image PDF | Tagged 10.11savvy 10.12savvy 10.13savvy NSBitmapImageRep NSImage NSNumber NSNumberFormatter NSScreen NSString NSURL PDFDocument Skim | Leave a comment

Finder上で選択中のPDFのファイル名の数字部分で小さいものから大きなものへとソート

Posted on 6月 27, 2018 by Takaaki Naganoya

Finder上で選択中のPDFのうち、ファイル名中の数字が小さいものから大きなものへソートを行うAppleScriptです。

Finder上で選択中のPDFをファイル名順でソートするような用途に使用します。選択中のファイルのうちPDFに該当しないものは無視します。

Finderで選択中の各PDFファイルに数字以外の文字がファイル名に混入していても無視します。

ファイル名はいったん数値として評価してソートするため、ファイル名にゼロパディングしてある場合には無視します。

Finder上で選択中のPDFを連結するさいに、ファイル名順で連結するScriptがあったほうが便利なので、そのために作ったものです。

ソートを行う際に、ファイル名の中の数字以外の部分をすべて無視するようにしています。そのため、Finder上の並び順と関係なく、ファイル名の中の数字部分のみをピックアップしてソートします。Finder自体にもFinderのルールでファイル名をソートして返すAppleScriptの機能がありますが、あれに甘えているとまともな処理はできません。

「test1_0004.pdf」というファイル名があった場合には10004という数値を検出するため、こうしたケースに対応する必要があるかもしれませんが、現時点では無用な数字の除去はしていません(それこそ一括処理で行うものではなくユーザーの目で見て判断してもらうような処理なので)。

AppleScript名:Finder上で選択中のPDFの数字のファイル名で小さいものから大きなものへとソート
— Created 2018-06-26 by Takaaki Naganoya
— 2018 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/
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

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 NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey

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

–ファイル名
set cList to {}
repeat with i in (filRes1 as list)
  set j to contents of i
  
set aFileName to ((current application’s NSString’s stringWithString:j)’s valueForKeyPath:"lastPathComponent.stringByDeletingPathExtension")
  
  
set aNumF to returnNumberCharsOnly(aFileName) of me
  
set the end of cList to {numDat:(aNumF as integer), pathDat:j}
end repeat

set aResList to sortRecListByLabel(cList, "numDat", true) of me –昇順ソート
set bResList to (aResList’s valueForKeyPath:"pathDat") as list of string or string
–>  {​​​​​"/Users/me/Pictures/243.pdf", ​​​​​"/Users/me/Pictures/244.pdf", ​​​​​"/Users/me/Pictures/245.pdf", ​​​​​"/Users/me/Pictures/246.pdf", ​​​​​"/Users/me/Pictures/247.pdf", ​​​​​"/Users/me/Pictures/248.pdf", ​​​​​"/Users/me/Pictures/249.pdf", ​​​​​"/Users/me/Pictures/250.pdf", ​​​​​"/Users/me/Pictures/251.pdf", ​​​​​"/Users/me/Pictures/252.pdf", ​​​​​"/Users/me/Pictures/253.pdf", ​​​​​"/Users/me/Pictures/254.pdf", ​​​​​"/Users/me/Pictures/255.pdf", ​​​​​"/Users/me/Pictures/256.pdf", ​​​​​"/Users/me/Pictures/257.pdf"​​​}

–文字列中から
on returnNumberCharsOnly(aStr)
  set anNSString to current application’s NSString’s stringWithString:aStr
  
set anNSString to anNSString’s stringByReplacingOccurrencesOfString:"[^0-9]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, anNSString’s |length|()}
  
return anNSString as text
end returnNumberCharsOnly

–リストに入れたレコードを、指定の属性ラベルの値でソート
on sortRecListByLabel(aRecList as list, aLabelStr as string, ascendF as boolean)
  –ListからNSArrayへの型変換
  
set aArray to current application’s NSArray’s arrayWithArray:aRecList
  
  
–ソート
  
set sortDesc to current application’s NSSortDescriptor’s alloc()’s initWithKey:aLabelStr ascending:ascendF
  
set sortDescArray to current application’s NSArray’s arrayWithObjects:sortDesc
  
set sortedArray to aArray’s sortedArrayUsingDescriptors:sortDescArray
  
return sortedArray
end sortRecListByLabel

–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 File path PDF Sort | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a comment

Finderで選択中のPDFを反時計方向に90°回転させる

Posted on 6月 4, 2018 by Takaaki Naganoya

Finder上で選択中のPDFを反時計方向に90°回転(=時計方向に270°回転)させるAppleScriptです。

Finder上で選択中の項目の中にPDF以外のものがあった場合には処理をスキップし、選択中のアイテムがない場合には処理を行いません。

実際には、macOS標準装備のScript Menuに、それぞれの角度(90°、180°、270°)への回転Scriptを個別に入れて使っています。1本のScriptで角度入力を行って回転させるよりも、あらかじめ固定の角度に回転させるものを複数用意しておいたほうが使い勝手がよいためです。

ドキュメントスキャナで紙の資料をPDFにスキャンするような時に、紙がヨレていて1枚ずつでないとスキャンできないような場合で、さらに穴が空いていたりヨレていて通常方向に紙を入れられなかった場合に、他の方向に入れてスキャンしておき、本Scriptのようなプログラムであとでまとめて回転させるなどの処理をよく行っています。

AppleScript名:Finderで選択中のPDFを反時計方向に90°回転させる
— Created 2018-05-26 by Takaaki Naganoya
— Modified 2018-06-02 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 NSUUID : a reference to current application’s NSUUID
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property NSPredicate : a reference to current application’s NSPredicate
property PDFDocument : a reference to current application’s PDFDocument
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 targDegree to 270 — targDegree have to be in {0, 90, 180, 270, 360} in clockwise

–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
if filRes1 = {} then return

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

repeat with i in filRes1
  set destPosixPath to newPath & "/" & ((NSUUID’s UUID()’s UUIDString()) as string) & ".pdf"
  
rotatePDFandSaveAt(i, destPosixPath, targDegree) of me
end repeat

–与えられたPOSIX pathのPDFを指定の角度に回転させて新規指定パスに書き出す
on rotatePDFandSaveAt(oldPath as string, newPath as string, aDegree as integer)
  
  
–Error Check
  
if aDegree is not in {0, 90, 180, 270, 360} then error "Wrong Degree"
  
  
set aURL to current application’s |NSURL|’s fileURLWithPath:oldPath
  
set aPDFdoc to PDFDocument’s alloc()’s initWithURL:aURL
  
  
set pCount to aPDFdoc’s pageCount() –count pages
  
  
–Make Blank PDF
  
set newPDFdoc to PDFDocument’s alloc()’s init()
  
  
–Rotate Each Page
  
repeat with i from 0 to (pCount – 1)
    set aPage to (aPDFdoc’s pageAtIndex:i)
    
    
–Set Degree
    
set curDegree to aPage’s |rotation|() –Get Current Degree
    (
aPage’s setRotation:(aDegree + curDegree)) –Set New Degree
    
    (
newPDFdoc’s insertPage:aPage atIndex:i)
  end repeat
  
  
set aRes to newPDFdoc’s writeToFile:newPath
  
return aRes as boolean
  
end rotatePDFandSaveAt

–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 | Tagged 10.11savvy 10.12savvy 10.13savvy Finder | Leave a 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 (197) 13.0savvy (100) 14.0savvy (45) 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 (42) 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