AppleScript PDF

PDF内容を画像化したPDFにする(TIFF圧縮無し)ドロップレット修正版


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

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

property refMe : a reference to current application

on run
  
  set aliasIconPass to (POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/MultipleItemsIcon.icns") as alias
  set strDialogText to "ドロップしても利用できます"
  set strTitleText to "PDFファイルを選んでください"
  set listButton to {"ファイルを選びます", "キャンセル"} as list
display dialog strDialogText buttons listButton default button 1 cancel button 2 with title strTitleText with icon aliasIconPass giving up after 1 with hidden answer
  
  set aliasDefaultLocation to (path to desktop folder from user domain) as alias
  set listChooseFileUTI to {"com.adobe.pdf"}
  set strPromptText to "ファイルを選んでください" as text
  set strPromptMes to "PDFファイルを選んでください" as text
  set listAliasFilePath to (choose file strPromptMes with prompt strPromptText default location (aliasDefaultLocation) of type listChooseFileUTI with showing package contents, invisibles and multiple selections allowed) as list
  
  -->値をOpenに渡たす
open listAliasFilePath
end run


on open listAliasFilePath
  repeat with itemFilePath in listAliasFilePath
    tell application "Finder"
      set strKindName to (kind of itemFilePath) as text
    end tell
    if strKindName is "フォルダ" then
display alert "フォルダは処理しません"
return "フォルダは処理しません"
    else if strKindName is not "PDF書類" then
display alert "PDF書類専用です"
return "PDF書類専用です"
    end if
  end repeat
  ################################
  ###カラープロファイルを読み出しておく ファイルはお好みで
  set strIccFilePath to "/System/Library/ColorSync/Profiles/sRGB Profile.icc"
  
  set ocidIccFilePathStr to (refMe's NSString's stringWithString:strIccFilePath)
  set ocidIccFilePath to ocidIccFilePathStr's stringByStandardizingPath
  set ocidIccFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidIccFilePath isDirectory:false)
  set ocidProfileData to refMe's NSData's alloc()'s initWithContentsOfURL:ocidIccFilePathURL
  
  ##########################
  ####ファイルの数だけ繰り返し
  ##########################
  
  repeat with itemAliasFilePath in listAliasFilePath
    ####まずはUNIXパスにして
    set strFilePath to (POSIX path of itemAliasFilePath) as text
    set ocidFilePathStr to (refMe's NSString's stringWithString:strFilePath)
    set ocidFilePath to ocidFilePathStr's stringByStandardizingPath
    set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath)
    ####ファイル名を取得
    set ocidFileName to ocidFilePathURL's lastPathComponent()
    ####ファイル名から拡張子を取っていわゆるベースファイル名を取得
    set strPrefixName to ocidFileName's stringByDeletingPathExtension as text
    ####コンテナディレクトリを取得
    set ocidContainerDirURL to ocidFilePathURL's URLByDeletingLastPathComponent()
    ###################################
    #####保存ダイアログ
    ###################################
    ###保存ファイル名
    set strSaveFileName to (strPrefixName & ".imaged.pdf") as text
    ###
    set ocidSaveFilePathURL to (ocidContainerDirURL's URLByAppendingPathComponent:strSaveFileName isDirectory:true)
    ###
    set aliasSaveFilePath to ocidSaveFilePathURL as «class furl»
    ####パス
    set strSaveFilePath to POSIX path of aliasSaveFilePath as text
    ####保存先URL
    set ocidSaveFilePathStr to (refMe's NSString's stringWithString:strSaveFilePath)
    set ocidSaveFilePath to ocidSaveFilePathStr's stringByStandardizingPath
    set ocidSaveFilePathURL to (refMe's NSURL's fileURLWithPath:ocidSaveFilePath)
    
    #####################
    #### 本処理
    #####################
    #読み込み
    set ocidActiveDoc to (refMe's PDFDocument's alloc()'s initWithURL:(ocidFilePathURL))
    #ページ数数えて
    set numCntPage to ocidActiveDoc's pageCount() as integer
    #ページ数繰り返し
    repeat with itemIntNo from 0 to (numCntPage - 1) by 1
      #ページ読み込み
      set ocidPdfPage to (ocidActiveDoc's pageAtIndex:(itemIntNo))
      #DATAに変換
      set ocidPdfPageData to ocidPdfPage's dataRepresentation()
      set ocidPageData to (refMe's NSData's alloc()'s initWithData:(ocidPdfPageData))
      #NSPDFImageRepに変換
      set ocidPdfPep to (refMe's NSPDFImageRep's alloc()'s initWithData:(ocidPageData))
(ocidPdfPep's setCurrentPage:0)
      #NSimageに変換
      set ocidPageImage to refMe's NSImage's alloc()'s init()
(ocidPageImage's addRepresentation:(ocidPdfPep))
      #NSBitmapImageRepに変換
      set ocidPageDispatchData to ocidPageImage's TIFFRepresentation()
      set ocidPageBmpImageRep to (refMe's NSBitmapImageRep's imageRepWithData:(ocidPageDispatchData))
      #TIFFにする この方法だとプロパティがうまく反映されない
      set ocidPropertyDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
      #set ocidNum to (refMe's NSNumber's numberWithFloat:(0.5))
      #(ocidPropertyDict's setObject:(ocidNum) forKey:(refMe's NSImageCompressionFactor))
      #(ocidPropertyDict's setObject:(refMe's NSTIFFCompressionLZW) forKey:(refMe's NSImageCompressionMethod))
(ocidPropertyDict's setObject:(refMe's NSTIFFCompressionNone) forKey:(refMe's NSImageCompressionMethod))
(ocidPropertyDict's setObject:(ocidProfileData) forKey:(refMe's NSImageColorSyncProfileData))
      set ocidFileType to (refMe's NSBitmapImageFileTypeTIFF)
      set ocidPageInlineData to (ocidPageBmpImageRep's representationUsingType:(ocidFileType) |properties|:(ocidPropertyDict))
      #####TIFFをPDFpageに
      set ocidPageImageData to (refMe's NSImage's alloc()'s initWithData:(ocidPageInlineData))
      set ocdiAddPage to (refMe's PDFPage's alloc()'s initWithImage:(ocidPageImageData))
(ocidActiveDoc's insertPage:(ocdiAddPage) atIndex:(itemIntNo))
      #####元あったページを削除する
(ocidActiveDoc's removePageAtIndex:(itemIntNo + 1))
    end repeat
    
    ####保存
    set ocidOptionDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidOptionDict's setValue:(missing value) forKey:(refMe's PDFDocumentOwnerPasswordOption))
(ocidOptionDict's setValue:(missing value) forKey:(refMe's PDFDocumentUserPasswordOption))
    set boolDone to (ocidActiveDoc's writeToURL:(ocidSaveFilePathURL) withOptions:(ocidOptionDict))
    
  end repeat
end open


|

[Python]PDFのメタデータのCreator と Producerを削除します 修正pypdfに変更


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# メタデータを削除します
# Creator と Producerを削除します
# pythonを利用します
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.6"
use framework "Foundation"
use framework "PDFKit"
use framework "Quartz"
use scripting additions


property refMe : a reference to current application

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

set ocidFalse to (refMe's NSNumber's numberWithBool:false)
set ocidTrue to (refMe's NSNumber's numberWithBool:true)

####何が前面か
tell application "System Events"
  set strAppTitile to title of (front process whose frontmost is true)
end tell

set listAliasFilePath to {}
###前面がプレビュー
if strAppTitile is "プレビュー" then
  tell application "Preview"
    tell front document
      set strFilePath to path as text
      set boolMode to modified
      ###変更箇所があるなら保存する
      if boolMode is true then
close saving yes
      else
close saving no
      end if
    end tell
  end tell
  set aliasFilePath to POSIX file strFilePath
  copy aliasFilePath to end of listAliasFilePath
  ###前面がリーダー
else if strAppTitile is "Acrobat Reader" then
  tell application id "com.adobe.Reader"
activate
    ##ファイルパス
    tell active doc
      set aliasFilePath to file alias
    end tell
  end tell
  set strFilePath to (POSIX path of aliasFilePath) as text
  tell application id "com.adobe.Reader"
activate
    set objAvtivDoc to active doc
    tell objAvtivDoc
      set boolMode to modified
      ###変更箇所があるなら保存する
      if boolMode is true then
save
      end if
    end tell
close objAvtivDoc
  end tell
  copy aliasFilePath to end of listAliasFilePath
  ###それ以外ならダイアログ
else
  ##############################
  #####ダイアログを前面に出す
  ##############################
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder"
activate
    end tell
  else
    tell current application
activate
    end tell
  end if
  #######################################
  #####ファイル選択ダイアログ
  #######################################
  ###ダイアログのデフォルト
  set ocidUserDesktopPath to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
  set aliasDefaultLocation to ocidUserDesktopPath as alias
  tell application "Finder"
  end tell
  set listChooseFileUTI to {"com.adobe.pdf"}
  set strPromptText to "PDFファイルを選んでください" as text
  set listAliasFilePath to (choose file with prompt strPromptText default location (aliasDefaultLocation) of type listChooseFileUTI with invisibles and multiple selections allowed without showing package contents) as list
end if


#######################################
###ダイアログで選択した書類の数だけ繰り返し
#######################################
repeat with itemAliasFilePath in listAliasFilePath
  set strFilePath to POSIX path of itemAliasFilePath as text
  set ocidFilePathStr to (refMe's NSString's stringWithString:strFilePath)
  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath
  set strFileName to ocidFilePath's lastPathComponent() as text
  set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath isDirectory:false)
  #####PDFDocumentとして読み込み
  set ocidActivDoc to (refMe's PDFDocument's alloc()'s initWithURL:ocidFilePathURL)
  ########################################
  #####暗号化チェック
  set boolEncrypted to ocidActivDoc's isEncrypted()
  if boolEncrypted is true then
    set strMes to "エラー:" & strFileName & "暗号化されています" as text
display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
return "暗号化されているので変更できません"
  end if
  ########################################
  #####ロック確認
  set boolLocked to ocidActivDoc's isLocked()
  if boolLocked is true then
    set strMes to "エラー:" & strFileName & "パスワードでロックされています" as text
display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
return "パスワードでロックされているので変更できません"
  end if
  ########################################
  ###Pythonイストールチェック
  
  set listReturn to doChkPython3()
  set boolDone to (item 1 of listReturn) as boolean
  set strBinPath to (item 2 of listReturn) as text
  
  if boolDone is false then
    set strMes to "エラー:Pythonパッケージのインストールに失敗しました" as text
display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
return "エラー:Pythonパッケージのインストールに失敗しました"
    
  else if strBinPath is ("missing value") then
    set strMes to "エラー:Pythonがインストールされていません" as text
display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
return "Pythonがインストールされていません"
  end if
  ########################################
  #Pyファイル保存先
  set ocidTempDirURL to appFileManager's temporaryDirectory()
  set ocidUUID to refMe's NSUUID's alloc()'s init()
  set ocidUUIDString to ocidUUID's UUIDString
  set ocidSaveDirPathURL to (ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:true)
  set ocidAttrDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions))
  set listBoolMakeDir to (appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference))
  ###パス
  set strFileName to "Context.py" as text
  set ocidSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:false)
  #Pyファイルを生成 旧バージョン
  # set strPyString to ("#!/usr/bin/env python3\n# coding: utf-8\nimport sys\nfrom PyPDF2 import PdfReader, PdfWriter\nfile_path = sys.argv[1]\nreader = PdfReader(file_path)\nwriter = PdfWriter()\nfor page in reader.pages:\n writer.add_page(page)\nwriter.add_metadata({\"/Producer\": \"\", \"/Creator\": \"\",})\nwith open(file_path, \"wb\") as f:\n writer.write(f)\n") as text
  #新バージョン
  set strPyString to ("#!/usr/bin/env python3\n# coding: utf-8\nimport sys\nfrom pypdf import PdfReader, PdfWriter\nfile_path = sys.argv[1]\napp_PdfReader = PdfReader(file_path)\napp_PdfWriter = PdfWriter(clone_from=file_path)\napp_PdfWriter.add_metadata({'/Producer': \"\", '/Creator': \"\", })\nwith open(file_path, \"wb\") as f:\n app_PdfWriter.write(f)\n") as text
  
  
  
  set ocidPyString to (refMe's NSString's stringWithString:(strPyString))
  #Pyファイル保存
  set listDone to (ocidPyString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference))
  #Pyファイルアクセス権
  set ocidFilePath to ocidSaveFilePathURL's |path|
  set listDone to (appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidFilePath) |error|:(reference))
  ##コマンド整形
  set strPyPath to ocidFilePath as text
  set strCommandText to ("\"" & strBinPath & "\" \"" & strPyPath & "\" \"" & strFilePath & "\"") as text
  #コマンド実行
  set strResponse to (do shell script strCommandText) as text
  
  ####解放
  set ocidActivDoc to ""
  set ocidDocAttrDict to ""
end repeat
#########################
###出来上がったPDFを開く
#########################
if strAppTitile is "プレビュー" then
  tell application "Preview"
open (ocidFilePathURL as alias)
  end tell
else if strAppTitile is "Acrobat Reader" then
  tell application id "com.adobe.Reader"
activate
open (ocidFilePathURL as alias)
  end tell
else
  tell application "Preview"
activate
open (ocidFilePathURL as alias)
  end tell
  
end if
return "処理終了"

####################
## python3のチェック
####################
to doChkPython3()
  ## python3のパス
  try
    set strCmdText to ("/usr/bin/which python3") as text
    set strBinPath to (do shell script strCmdText) as text
  on error
log "python3が見つかりませんでした終了します"
return {false, (missing value)} as list
  end try
  ###PyPDF2のインストールチェック
  set strCmdText to ("\"" & strBinPath & "\" -m pip show pypdf") as text
  try
    set strPipDone to (do shell script strCmdText) as text
  on error
    try
      set strCmdText to ("/bin/mkdir -p $HOME/Library/Caches/pip") as text
do shell script strCmdText
      set strCmdText to ("/bin/chmod 777 $HOME/Library/Caches/pip") as text
do shell script strCmdText
      set strCmdText to ("/bin/mkdir -p $HOME/Library/Python/3.9/lib/python/site-packages") as text
do shell script strCmdText
      set strCmdText to ("/bin/chmod 755 $HOME/Library/Python/3.9/lib/python/site-packages") as text
do shell script strCmdText
    end try
    try
      ##pipのアップデート
      set strCmdText to ("\"" & strBinPath & "\" -m pip install --upgrade --user pip") as text
      set strPipDone to (do shell script strCmdText) as text
    on error
log "pipのアップデートに失敗しました"
return {false, (missing value)} as list
    end try
    try
      ##インストールされていなければインストールする
      set strCmdText to ("\"" & strBinPath & "\" -m pip install --user pypdf") as text
      set strPipDone to (do shell script strCmdText) as text
    on error
log "PyPDF2のインストールに失敗しました"
return {false, (missing value)} as list
    end try
  end try
return {true, strBinPath} as list
end doChkPython3


|

[PDFKIT]しおり メタ 注釈を別ファイルにコピー

ダウンロード - pdfmetacopy.zip


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

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

property refMe : a reference to current application



##################################
### パス関連 A
##################################
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder"
activate
  end tell
else
  tell current application
activate
  end tell
end if
##PDF
set aliasFilePath to (choose file with prompt "PDFファイルを選んでください" default location (path to desktop folder from user domain) of type {"com.adobe.pdf"} with invisibles and showing package contents without multiple selections allowed) as alias

set strFilePath to POSIX path of aliasFilePath as text
set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath
set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)

##################################
### パス関連 B
##################################
##PDF
set aliasFilePathDist to (choose file with prompt "PDFファイルを選んでください" default location (path to desktop folder from user domain) of type {"com.adobe.pdf"} with invisibles and showing package contents without multiple selections allowed) as alias


set strSaveFilePath to POSIX path of aliasFilePathDist as text
set ocidSaveFilePathStr to refMe's NSString's stringWithString:(strSaveFilePath)
set ocidSaveFilePath to ocidSaveFilePathStr's stringByStandardizingPath
set ocidSaveFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSaveFilePath) isDirectory:false)

##################################
### データ読み込み
##################################
#元データ
set ocidActivDocA to refMe's PDFDocument's alloc()'s initWithURL:(ocidFilePathURL)
#コピー先
set ocidActivDocB to refMe's PDFDocument's alloc()'s initWithURL:(ocidSaveFilePathURL)


##################################
### 処理 アトリビュートのコピー
##################################
##アトリビュート取得
set ocidAttributesA to ocidActivDocA's documentAttributes()
##アトリビュートセット
ocidActivDocB's setDocumentAttributes:(ocidAttributesA)

##################################
### 処理 アウトライン ブックマークのコピー
##################################
##アウトライン取得
set ocidOutLineRootA to ocidActivDocA's outlineRoot()
##アウトラインセット
ocidActivDocB's setOutlineRoot:(ocidOutLineRootA)

##################################
### 処理 注釈アノテーションのコピー
### 注釈はページ単位でコピー
##################################
####元ページ数を数える
set numCntPdfPage to ocidActivDocA's pageCount()
repeat with itemIntNo from 0 to (numCntPdfPage - 1) by 1
  ##元ページのアノテーションを取得して
  set ocidActivePageA to (ocidActivDocA's pageAtIndex:(itemIntNo))
  set ocidPageAnotArray to ocidActivePageA's annotations()
  ##コピー先の同ページ
  set ocidActivePageB to (ocidActivDocB's pageAtIndex:(itemIntNo))
  ##ページ内の注釈をコピーする
  repeat with itemAnot in ocidPageAnotArray
(ocidActivePageB's addAnnotation:(itemAnot))
  end repeat
end repeat

##################################
### 保存
##################################

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

|

[xpdf]コマンドライン・ヘルパ8種

添付操作のデタッチ pdfdetach
フォントツール pdffonts
基本情報取得 pdfinfo
EPS書き出し pdftops
PS書き出し pdftops
PNG書き出し pdftopng
HTML書き出し pdftohtml
テキスト書き出し pdftotext
pdftohtml HTMLへの書き出しツールはサブセットされたフォントデータを取り出すこともできる優れもの

ダウンロード - xpdf.zip



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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# xpdfコマンドラインツールをインストールします
# インストール不要な方は実行しないでください
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions

property refMe : a reference to current application
set appFileManager to refMe's NSFileManager's defaultManager()

###モジュールチェックが不要な場合は削除
set strBinPath to ("~/bin/xpdf/binARM/pdftohtml") as text
set ocidBinPathStr to refMe's NSString's stringWithString:(strBinPath)
set ocidBinPath to ocidBinPathStr's stringByStandardizingPath()
set ocidBinPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidBinPath) isDirectory:false)
set strBinPath to (ocidBinPathURL's |path|) as text

set ocidArmDirPathURL to ocidBinPathURL's URLByDeletingLastPathComponent()
set ocidContainerDirPathURL to ocidArmDirPathURL's URLByDeletingLastPathComponent()
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidContainerDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
set strContainerDirPath to (ocidContainerDirPathURL's |path|) as text
##
set boolFileExists to (appFileManager's fileExistsAtPath:(ocidBinPath) isDirectory:false)
if boolFileExists is true then
log "pdffontsインストール済み"
else if boolFileExists is false then
log "インストールします"
  set strURL to ("https://dl.xpdfreader.com/xpdf-tools-mac-4.05.tar.gz") as text
  set ocidURLstr to (refMe's NSString's stringWithString:(strURL))
  set ocidURL to refMe's NSURL's alloc()'s initWithString:(ocidURLstr)
  set listResponse to refMe's NSData's dataWithContentsOfURL:(ocidURL) options:(refMe's NSDataReadingMappedIfSafe) |error|:(reference)
  if (item 2 of listResponse) is not (missing value) then
log "ダウンロードに失敗しました"
return (item 2 of listResponse)'s localizedDescription() as text
  else
    set ocidGzData to (item 1 of listResponse)
  end if
  #
  set ocidTempDirPathURL to appFileManager's temporaryDirectory()
  set strTempDirPath to (ocidTempDirPathURL's |path|) as text
  set ocidGzFilePathURL to ocidTempDirPathURL's URLByAppendingPathComponent:"xpdf.tar.gz" isDirectory:false
  set strGzFilePathURL to (ocidGzFilePathURL's |path|) as text
  set listDone to ocidGzData's writeToURL:(ocidGzFilePathURL) options:(refMe's NSDataWritingAtomic) |error|:(reference)
  if (item 1 of listDone) is false then
log "ダウンロードに失敗しました"
return (item 2 of listDone)'s localizedDescription() as text
  else
    try
      set strCommandText to ("/usr/bin/bsdtar -xzvf \"" & strGzFilePathURL & "\" -C \"" & strTempDirPath & "\"") as text
do shell script strCommandText
    on error
return "ファイルの解凍に失敗しました"
    end try
    try
      set strCommandText to ("/usr/bin/ditto \"" & strTempDirPath & "/xpdf-tools-mac-4.05\" \"" & strContainerDirPath & "\"") as text
do shell script strCommandText
    on error
return "ファイルのコピーに失敗しました"
    end try
  end if
end if

##################################
#### ファイルを選択
##################################
####ダイアログで
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder"
activate
  end tell
else
  tell current application
activate
  end tell
end if
##PDF
set aliasFilePath to (choose file with prompt "PDFファイルを選んでください" default location (path to desktop folder from user domain) of type {"com.adobe.pdf"} with invisibles and showing package contents without multiple selections allowed) as alias

##################################
### パス関連
##################################
set strFilePath to POSIX path of aliasFilePath as text
set ocidFilePathStr to (refMe's NSString's stringWithString:strFilePath)
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath
set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath isDirectory:false)
set ocidFileName to ocidFilePathURL's lastPathComponent()
set ocidBaseFileName to ocidFileName's stringByDeletingPathExtension() as text
##################################
#### 保存先
##################################
set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
set aliasContainerDirPath to (ocidContainerDirPathURL's absoluteURL()) as alias
set strMes to "保存先フォルダを選んでください" as text
set strPrompt to "保存先フォルダを選択してください" as text
try
  set aliasSaveDirPath to (choose folder strMes with prompt strPrompt default location aliasContainerDirPath with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
##
set strSaveDirPath to POSIX path of aliasSaveDirPath as text
set ocidSaveDirPathStr to (refMe's NSString's stringWithString:(strSaveDirPath))
set ocidSaveDirPath to ocidSaveDirPathStr's stringByStandardizingPath
set ocidSaveURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSaveDirPath) isDirectory:true)
set ocidSaveDirPathURL to ocidSaveURL's URLByAppendingPathComponent:(ocidBaseFileName) isDirectory:(true)
set strSaveDirPath to (ocidSaveDirPathURL's |path|) as text

####コマンド実行
set strCommandText to ("\"" & strBinPath & "\" -overwrite \"" & strFilePath & "\" \"" & strSaveDirPath & "\"")
log strCommandText
set ocidCommandText to refMe's NSString's stringWithString:strCommandText
set ocidTermTask to refMe's NSTask's alloc()'s init()
ocidTermTask's setLaunchPath:"/bin/zsh"
ocidTermTask's setArguments:({"-c", ocidCommandText})
set ocidPipe to refMe's NSPipe's pipe
ocidTermTask's setStandardOutput:(ocidPipe)
ocidTermTask's |launch|()
ocidTermTask's waitUntilExit()

if (ocidTermTask's terminationStatus as text) is "0" then
  set ocidHandle to ocidPipe's fileHandleForReading()
  set ocidResponse to ocidHandle's readDataToEndOfFile()
  set ocidResponseStr to refMe's NSString's alloc()'s initWithData:(ocidResponse) encoding:(refMe's NSUTF8StringEncoding)
else
log ocidTermTask's terminationStatus as text
log ocidTermTask's terminationReason as text
return "コマンド実行でエラーしました"
end if


set aliasOpenDirPath to (ocidSaveDirPathURL's absoluteURL()) as alias
tell application "Finder"
open location aliasOpenDirPath
end tell

|

[PDF]メタデータ タイトル設定


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
(*
exiftoolが別途必要です
https://quicktimer.cocolog-nifty.com/icefloe/2024/01/post-e7e51d.html

*)
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.6"
use framework "Foundation"
use framework "PDFKit"
use framework "Quartz"
use scripting additions

property refMe : a reference to current application


#####
#設定項目
# set strBinPath to ("/usr/local/bin/exiftool") as text --通常はこちら
set strBinPath to ("~/bin/exiftool/exiftool") as text


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


##############################
#####ダイアログを前面に出す
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder"
activate
  end tell
else
  tell current application
activate
  end tell
end if
#######################################
#####ファイル選択ダイアログ
#######################################
###ダイアログのデフォルト
set ocidUserDesktopPath to (objFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set aliasDefaultLocation to ocidUserDesktopPath as alias
tell application "Finder"
end tell
set listChooseFileUTI to {"com.adobe.pdf"}
set strPromptText to "PDFファイルを選んでください" as text
set listAliasFilePath to (choose file with prompt strPromptText default location (aliasDefaultLocation) of type listChooseFileUTI with invisibles and multiple selections allowed without showing package contents) as list

#######################################
## クリップボードの中身取り出し
#######################################
###初期化
set appPasteboard to refMe's NSPasteboard's generalPasteboard()
set ocidPastBoardTypeArray to appPasteboard's types
###テキストがあれば
set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
if boolContain = true then
  ###値を格納する
  tell application "Finder"
    set strReadString to (the clipboard as text) as text
  end tell
  ###Finderでエラーしたら
else
  set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
  if boolContain = true then
    set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
    set strReadString to ocidReadString as text
  else
log "テキストなし"
    set aliasFirstFilePath to (item 1 of listAliasFilePath) as alias
    tell application "Finder"
      set strFirstFileName to name of aliasFirstFilePath as text
    end tell
    set strReadString to strFirstFileName as text
  end if
end if
########################
##ダイアログを前面に出す
set strName to (name of current application) as text
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
########################
##ダイアログ
set aliasIconPath to (POSIX file "/System/Library/CoreServices/Tips.app/Contents/Resources/AppIcon.icns") as alias
set strTitle to ("入力してください") as text
set strMes to ("タイトルを入力してください\r") as text
set recordResult to (display dialog strMes with title strTitle default answer strReadString buttons {"キャンセル", "OK"} default button "OK" cancel button "キャンセル" giving up after 30 with icon aliasIconPath without hidden answer)
if (gave up of recordResult) is true then
return "時間切れです"
else if (button returned of recordResult) is "キャンセル" then
return "キャンセルです"
else
  set strReturnedText to (text returned of recordResult) as text
end if
set ocidReturnedText to refMe's NSString's stringWithString:(strReturnedText)
########################
##改行を取る
set ocidReturned to ocidReturnedText's stringByReplacingOccurrencesOfString:("\r") withString:("")
set ocidReturnedText to ocidReturned's stringByReplacingOccurrencesOfString:("\n") withString:("")
set strSetText to ocidReturnedText as string
#####BIN path
set ocidBinPathStr to refMe's NSString's stringWithString:(strBinPath)
set ocidBinPath to ocidBinPathStr's stringByStandardizingPath()
set ocidBinPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidBinPath) isDirectory:false)
set strBinPath to ocidBinPathURL's |path| as text


#######################################
###ダイアログで選択した書類の数だけ繰り返し
#######################################
repeat with itemAliasFilePath in listAliasFilePath
  set strFilePath to POSIX path of itemAliasFilePath as text
  set ocidFilePathStr to (refMe's NSString's stringWithString:strFilePath)
  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath
  set strFileName to ocidFilePath's lastPathComponent() as text
  set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath isDirectory:false)
  #####PDFDocumentとして読み込み
  set ocidActivDoc to (refMe's PDFDocument's alloc()'s initWithURL:ocidFilePathURL)
  ########################################
  #####暗号化チェック
  set boolEncrypted to ocidActivDoc's isEncrypted()
  if boolEncrypted is true then
    set strMes to "エラー:" & strFileName & "暗号化されています" as text
display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
return "暗号化されているので変更できません"
  end if
  ########################################
  #####ロック確認
  set boolLocked to ocidActivDoc's isLocked()
  if boolLocked is true then
    set strMes to "エラー:" & strFileName & "パスワードでロックされています" as text
display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
return "パスワードでロックされているので変更できません"
  end if
  ########################################
  #####アトリビュートを取得して
  set ocidAttributes to ocidActivDoc's documentAttributes()
  ######可変ディクショナリに格納
  set ocidAttrDict to (refMe's NSMutableDictionary's alloc()'s initWithDictionary:ocidAttributes)
log ocidAttrDict as record
  ###Titleキーの内容を設定
(ocidAttrDict's setValue:(ocidReturnedText) forKey:"Title")
(ocidAttrDict's setValue:"" forKey:"Creator")
  #####値を変更したレコードをセットする
(ocidActivDoc's setDocumentAttributes:ocidAttrDict)
  ##################
  ###保存
  ##################
(ocidActivDoc's writeToURL:ocidFilePathURL)
  ####解放
  set ocidActivDoc to ""
  set ocidDocAttrDict to ""
  ##################
  ### exifToolでXMPを削除
  ##################
  set strCommandText to ("\"" & strBinPath & "\" -m -overwrite_original -title=\"" & strSetText & "\" -xmp:Title=\"" & strSetText & "\" -xmp:dc:Title=\"" & strSetText & "\" -IPTC:ObjectName=\"" & strSetText & "\" \"" & strFilePath & "\"") as text
  try
do shell script strCommandText
  end try
end repeat


return "処理終了"






|

[exiftool]PDFのメタデータ全部削除


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
(*
exiftoolが別途必要です
https://quicktimer.cocolog-nifty.com/icefloe/2024/01/post-e7e51d.html

*)
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.6"
use framework "Foundation"
use framework "PDFKit"
use framework "Quartz"
use scripting additions

property refMe : a reference to current application


#####
#設定項目
# set strBinPath to ("/usr/local/bin/exiftool") as text --通常はこちら
set strBinPath to ("~/bin/exiftool/exiftool") as text


set objFileManager to refMe's NSFileManager's defaultManager()
#
set ocidBinPathStr to refMe's NSString's stringWithString:(strBinPath)
set ocidBinPath to ocidBinPathStr's stringByStandardizingPath()
set ocidBinPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidBinPath) isDirectory:false)
set strBinPath to ocidBinPathURL's |path| as text

##############################
#####ダイアログを前面に出す
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder"
activate
  end tell
else
  tell current application
activate
  end tell
end if
#######################################
#####ファイル選択ダイアログ
#######################################
###ダイアログのデフォルト
set ocidUserDesktopPath to (objFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set aliasDefaultLocation to ocidUserDesktopPath as alias
tell application "Finder"
end tell
set listChooseFileUTI to {"com.adobe.pdf"}
set strPromptText to "PDFファイルを選んでください" as text
set listAliasFilePath to (choose file with prompt strPromptText default location (aliasDefaultLocation) of type listChooseFileUTI with invisibles and multiple selections allowed without showing package contents) as list
#######################################
###ダイアログで選択した書類の数だけ繰り返し
#######################################
repeat with itemAliasFilePath in listAliasFilePath
  set strFilePath to POSIX path of itemAliasFilePath as text
  set ocidFilePathStr to (refMe's NSString's stringWithString:strFilePath)
  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath
  set strFileName to ocidFilePath's lastPathComponent() as text
  set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath isDirectory:false)
  #####PDFDocumentとして読み込み
  set ocidActivDoc to (refMe's PDFDocument's alloc()'s initWithURL:ocidFilePathURL)
  ########################################
  #####暗号化チェック
  set boolEncrypted to ocidActivDoc's isEncrypted()
  if boolEncrypted is true then
    set strMes to "エラー:" & strFileName & "暗号化されています" as text
display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
return "暗号化されているので変更できません"
  end if
  ########################################
  #####ロック確認
  set boolLocked to ocidActivDoc's isLocked()
  if boolLocked is true then
    set strMes to "エラー:" & strFileName & "パスワードでロックされています" as text
display alert strMes buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 3
return "パスワードでロックされているので変更できません"
  end if
  ########################################
  #####アトリビュートを取得して
  set ocidAttributes to ocidActivDoc's documentAttributes()
  ######可変ディクショナリに格納
  set ocidAttrDict to (refMe's NSMutableDictionary's alloc()'s initWithDictionary:ocidAttributes)
log ocidAttrDict as record
  ###Titleキーの内容をブランクにする
(ocidAttrDict's setValue:"" forKey:"Title")
(ocidAttrDict's setValue:"" forKey:"Creator")
(ocidAttrDict's setValue:"" forKey:"Author")
(ocidAttrDict's setValue:"" forKey:"Keywords")
(ocidAttrDict's setValue:"" forKey:"Producer")
(ocidAttrDict's setValue:"" forKey:"Subject")
(ocidAttrDict's setValue:"" forKey:"ModificationDate")
(ocidAttrDict's setValue:"" forKey:"CreationDate")
  
  #####値を変更したレコードをセットする
(ocidActivDoc's setDocumentAttributes:ocidAttrDict)
  ##################
  ###保存
  ##################
(ocidActivDoc's writeToURL:ocidFilePathURL)
  ####解放
  set ocidActivDoc to ""
  set ocidDocAttrDict to ""
  ##################
  ### exifToolでXMPを削除
  ##################
  set strCommandText to ("\"" & strBinPath & "\" -overwrite_original -all= \"" & strFilePath & "\"") as text
  try
do shell script strCommandText
  end try
end repeat


return "処理終了"






|

[cupsfilter]postscriptファイルをPDFに変換する

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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application

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

#############################
###AcrobatPPDの有無を確認
#############################
set ocidUserPathArray to (appFileManager's URLsForDirectory:(refMe's NSUserDirectory) inDomains:(refMe's NSLocalDomainMask))
set ocidUserPathURL to ocidUserPathArray's objectAtIndex:0
set ocidPPDFilePathURL to ocidUserPathURL's URLByAppendingPathComponent:"Shared/Library/Printers/PPDs/Contents/Resources/Acrobat/ADPDF9J.PPD" isDirectory:true
set boolFileExists to (appFileManager's fileExistsAtPath:(ocidPPDFilePathURL's |path|()) isDirectory:false)

############PPDファイル
if boolFileExists is true then
  log "PPDはインストール済み"
  set strPPDsFilePath to ocidPPDFilePathURL's |path|() as text
else
  log "AcrobatPPDは未インストールなので標準PPDを使用"
  set strPPDsFilePath to "/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/PrintCore.framework/Versions/A/Resources/Generic.ppd" as text
end if

#############################
#####ファイル選択ダイアログ
#############################
###ダイアログを前面に出す
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder"
    activate
  end tell
else
  tell current application
    activate
  end tell
end if
###ダイアログのデフォルト
set ocidUserDesktopPath to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set aliasDefaultLocation to ocidUserDesktopPath as alias
tell application "Finder"
  
end tell
set listChooseFileUTI to {"com.adobe.postscript"}
set strPromptText to "ファイルを選んでください" as text
set listAliasFilePath to (choose file with prompt strPromptText default location (aliasDefaultLocation) of type listChooseFileUTI with invisibles and multiple selections allowed without showing package contents) as list



repeat with itemAliasFilePath in listAliasFilePath
  ###エイリアス
  set aliasFilePath to itemAliasFilePath as alias
  ###パステキスト
  set strFilePath to (POSIX path of aliasFilePath) as text
  ####入力ファイルパス確定
  set strInputFilePath to strFilePath as text
  ###パス
  set ocidFilePath to (refMe's NSString's stringWithString:strFilePath)
  ###NSURL
  set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath)
  ###ファイル名
  set ocidFileName to ocidFilePathURL's lastPathComponent()
  ###拡張子を取ったベースファイル名
  set strBaseFileName to ocidFileName's stringByDeletingPathExtension() as text
  ####入力ファイルの1階層上のフォルダURL
  set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
  ####ディレクトリのURLコンポーネント
  set strContainerDirPath to ocidContainerDirPathURL's |path|() as text
  
  ####出力ファイル名
  set strNewFileName to (strBaseFileName & ".pdf") as text
  ####ディレクトリのURLコンポーネント
  set ocidNewFilePathURL to (ocidContainerDirPathURL's URLByAppendingPathComponent:strNewFileName)
  ####ファイルの有無チェック
  set boolFileExist to (ocidNewFilePathURL's checkResourceIsReachableAndReturnError:(missing value)) as boolean
  ###すでに同名ファイルがある場合は日付時間入りのファイル名
  if boolFileExist is true then
    ####日付情報の取得
    set ocidDate to refMe's NSDate's |date|()
    ###日付のフォーマットを定義
    set ocidNSDateFormatter to refMe's NSDateFormatter's alloc()'s init()
(ocidNSDateFormatter's setDateFormat:"yyyyMMdd-hhmm")
    set ocidDateAndTime to (ocidNSDateFormatter's stringFromDate:ocidDate)
    set strDateAndTime to ocidDateAndTime as text
    ####ファイル名に日付を入れる
    set strNewFilePath to (strContainerDirPath & "/" & strBaseFileName & "." & strDateAndTime & ".pdf") as text
  else
    ####出力ファイルパス
    set strNewFilePath to (strContainerDirPath & "/" & strNewFileName & "") as text
  end if
  ################################################
  ####コマンドパス
  set strBinPath to "/usr/sbin/cupsfilter"
  #####コマンド整形
  set strCommandText to ("\"" & strBinPath & "\" -f \"" & strInputFilePath & "\" -m \"application/pdf\" -p \"" & strPPDsFilePath & "\" -e -t \"" & strBaseFileName & "\" > \"" & strNewFilePath & "\"")
  ####ターミナルで開く
  tell application "Terminal"
    launch
    activate
    set objWindowID to (do script "\n\n")
    delay 1
do script strCommandText in objWindowID
  end tell
end repeat



|

[pstopdf]EPSをPDF化する

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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application


#############################
#####ファイル選択ダイアログ
#############################
###ダイアログを前面に出す
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder"
    activate
  end tell
else
  tell current application
    activate
  end tell
end if
###ダイアログのデフォルト
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidUserDesktopPath to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set aliasDefaultLocation to ocidUserDesktopPath as alias
set listChooseFileUTI to {"com.adobe.encapsulated-postscript", "com.adobe.postscript"}
set strPromptText to "ファイルを選んでください" as text
set listAliasFilePath to (choose file with prompt strPromptText default location (aliasDefaultLocation) of type listChooseFileUTI with invisibles and multiple selections allowed without showing package contents) as list
####複数ファイル対応
repeat with itemAliasFilePath in listAliasFilePath
  ###エイリアス
  set aliasFilePath to itemAliasFilePath as alias
  ###パステキスト
  set strFilePath to (POSIX path of aliasFilePath) as text
  ####入力ファイルパス確定
  set strInputFilePath to strFilePath as text
  ###パス
  set ocidFilePath to (refMe's NSString's stringWithString:strFilePath)
  ###NSURL
  set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath)
  ###ファイル名
  set ocidFileName to ocidFilePathURL's lastPathComponent()
  ###拡張子を取ったベースファイル名
  set strBaseFileName to ocidFileName's stringByDeletingPathExtension() as text
  ####入力ファイルの1階層上のフォルダURL
  set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
  ####ディレクトリのURLコンポーネント
  set strContainerDirPath to ocidContainerDirPathURL's |path|() as text
  
  ####出力ファイル名
  set strNewFileName to (strBaseFileName & ".pdf") as text
  ####ディレクトリのURLコンポーネント
  set ocidNewFilePathURL to (ocidContainerDirPathURL's URLByAppendingPathComponent:strNewFileName)
  ####ファイルの有無チェック
  set boolFileExist to (ocidNewFilePathURL's checkResourceIsReachableAndReturnError:(missing value)) as boolean
  ###すでに同名ファイルがある場合は日付時間入りのファイル名
  if boolFileExist is true then
    ####日付情報の取得
    set ocidDate to refMe's NSDate's |date|()
    ###日付のフォーマットを定義
    set ocidNSDateFormatter to refMe's NSDateFormatter's alloc()'s init()
(ocidNSDateFormatter's setDateFormat:"yyyyMMddhhmm")
    set ocidDateAndTime to (ocidNSDateFormatter's stringFromDate:ocidDate)
    set strDateAndTime to ocidDateAndTime as text
    ####ファイル名に日付を入れる
    set strNewFilePath to (strContainerDirPath & "/" & strBaseFileName & "." & strDateAndTime & ".pdf") as text
  else
    ####出力ファイルパス
    set strNewFilePath to (strContainerDirPath & "/" & strNewFileName & "") as text
  end if
  ################################################
  ####コマンドパス
  set strBinPath to "/usr/bin/pstopdf"
  #####コマンド整形
  set strCommandText to ("\"" & strBinPath & "\"  \"" & strInputFilePath & "\" -o \"" & strNewFilePath & "\"") as text
  do shell script strCommandText
  (*
####ターミナルで開く
tell application "Terminal"
launch
activate
set objWindowID to (do script "\n\n")
delay 1
do script strCommandText in objWindowID
end tell
*)
end repeat



|

[pstopdf]postscriptファイルをコンテンツを画像化したPDFにする

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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application


###################################
#####ダイアログ
###################################a
tell application "Finder"
  ##set aliasDefaultLocation to container of (path to me) as alias
  set aliasDefaultLocation to (path to desktop folder from user domain) as alias
end tell
set listChooseFileUTI to {"com.adobe.postscript"}
set strPromptText to "ファイルを選んでください" as text
set listAliasFilePath to (choose file with prompt strPromptText default location (aliasDefaultLocation) of type listChooseFileUTI with invisibles and showing package contents without multiple selections allowed) as list
###################################
#####パス処理
###################################
###エリアス
set aliasFilePath to item 1 of listAliasFilePath as alias
###UNIXパス
set strFilePath to POSIX path of aliasFilePath as text
###String
set ocidFilePath to refMe's NSString's stringWithString:(strFilePath)
###NSURL
set ocidFilePathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false
####ファイル名を取得
set ocidFileName to ocidFilePathURL's lastPathComponent()
####拡張子を取得
set ocidFileExtension to ocidFilePathURL's pathExtension()
####ファイル名から拡張子を取っていわゆるベースファイル名を取得
set ocidPrefixName to ocidFileName's stringByDeletingPathExtension
####コンテナディレクトリ
set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()

###################################
#####保存ダイアログ
###################################
###ファイル名
set strPrefixName to ocidPrefixName as text
###拡張子
###同じ拡張子の場合
##set strFileExtension to ocidFileExtension as text
###拡張子変える場合
set strFileExtension to "pdf"
###ダイアログに出すファイル名
set strDefaultName to (strPrefixName & ".output." & strFileExtension) as text
set strPromptText to "名前を決めてください"
###選んだファイルの同階層をデフォルトの場合
set aliasDefaultLocation to ocidContainerDirPathURL as alias
####デスクトップの場合
##set aliasDefaultLocation to (path to desktop folder from user domain) as alias
####ファイル名ダイアログ
####実在しない『はず』なのでas «class furl»で
set aliasSaveFilePath to (choose file name default location aliasDefaultLocation default name strDefaultName with prompt strPromptText) as «class furl»
####UNIXパス
set strSaveFilePath to POSIX path of aliasSaveFilePath as text
####ドキュメントのパスをNSString
set ocidSaveFilePath to refMe's NSString's stringWithString:(strSaveFilePath)
####ドキュメントのパスをNSURLに
set ocidSaveFilePathURL to refMe's NSURL's fileURLWithPath:(ocidSaveFilePath)
###拡張子取得
set strFileExtensionName to ocidSaveFilePathURL's pathExtension() as text
###ダイアログで拡張子を取っちゃった時対策
if strFileExtensionName is not strFileExtension then
  set ocidSaveFilePathURL to ocidSaveFilePathURL's URLByAppendingPathExtension:(strFileExtension)
end if

###################################
#####テンポラリーにPDFを生成する
###################################
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidTemporaryDirURL to appFileManager's temporaryDirectory()
set str8Digit to (random number from 10000000 to 99999999) as text
set strTempFileName to (str8Digit & ".pdf") as text
set ocidTemporaryFileURL to ocidTemporaryDirURL's URLByAppendingPathComponent:(strTempFileName)
set strTemporaryFileURL to (ocidTemporaryFileURL's |path|()) as text
####コマンドパス
set strBinPath to "/usr/bin/pstopdf"
#####コマンド整形
set strCommandText to ("\"" & strBinPath & "\"  \"" & strFilePath & "\" -o \"" & strTemporaryFileURL & "\"")
do shell script strCommandText

###################################
#####本処理
###################################
###カラープロファイルを読み出しておく ファイルはお好みで
set strIccFilePath to "/System/Library/ColorSync/Profiles/sRGB Profile.icc"

set ocidIccFilePathStr to (refMe's NSString's stringWithString:strIccFilePath)
set ocidIccFilePath to ocidIccFilePathStr's stringByStandardizingPath
set ocidIccFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidIccFilePath isDirectory:false)
set ocidProfileData to refMe's NSData's alloc()'s initWithContentsOfURL:ocidIccFilePathURL

###NSDATAに読み込む
set ocidReadPdfData to (refMe's NSData's alloc()'s initWithContentsOfURL:ocidTemporaryFileURL)
####NSPDFImageRepに変換
set ocidPdfPep to (refMe's NSPDFImageRep's alloc()'s initWithData:ocidReadPdfData)
###ページ数数えて
set numPageCnt to ocidPdfPep's pageCount() as integer
###ページカウントの書き出しファイル用のページ番号
set numCntPageNo to 1 as integer
###ページカウントの初期値JS
set numCntPageNoJs to numCntPageNo - 1 as integer
####################
#####保存されるPDF
####################
set ocidSaveDoc to (refMe's PDFDocument's alloc()'s init())
####################
#####ページ数だけ繰り返し
####################
repeat numPageCnt times
  ####順番にページデータを読み出し
(ocidPdfPep's setCurrentPage:numCntPageNoJs)
  ##################################
  ####ページデータをNSIMAGEに格納
  ##################################
  set ocidPageImageData to refMe's NSImage's alloc()'s init()
(ocidPageImageData's addRepresentation:ocidPdfPep)
  ###中間ファイルとしてのTIFFに変換
  set ocidOsDispatchData to ocidPageImageData's TIFFRepresentation()
  ####出力されるBmpImageRepに格納 TIFFのままにする
  set ocidBmpImageRep to (refMe's NSBitmapImageRep's imageRepWithData:ocidOsDispatchData)
  set ocidPropertyDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidPropertyDict's setObject:1 forKey:(refMe's NSImageCompressionFactor))
(ocidPropertyDict's setObject:(refMe's NSTIFFCompressionNone) forKey:(refMe's NSImageCompressionMethod))
(ocidPropertyDict's setObject:ocidProfileData forKey:(refMe's NSImageColorSyncProfileData))
  set ocidFileType to refMe's NSBitmapImageFileTypeTIFF
  ##########変換
  set ocidNSInlineData to (ocidBmpImageRep's representationUsingType:ocidFileType |properties|:ocidPropertyDict)
  ##################################
  ###変換済みイメージをページデータに
  ##################################
  set ocidPageImageData to refMe's NSImage's alloc()'s initWithData:ocidNSInlineData
  set ocdiAddPage to refMe's PDFPage's alloc()'s initWithImage:ocidPageImageData
ocidSaveDoc's insertPage:ocdiAddPage atIndex:numCntPageNoJs
  #############カウントアップ
  set numCntPageNoJs to numCntPageNoJs + 1 as integer
  ###データ解放
  set ocidNSInlineData to ""
  set ocidPageImageData to ""
  set ocidOsDispatchData to ""
  set ocidBmpImageRep to ""
end repeat

(ocidSaveDoc's writeToURL:ocidSaveFilePathURL)

|

[pypdf]開き方設定Layout

ダウンロード - e8a1a8e7a4bae696b9e6b395layout.zip




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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
#                       com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application


##################################
#### 文書を開いているか?
##################################
tell application id "com.adobe.Reader"
  activate
  tell active doc
    ###javascript無効になっているとここでエラーになる
    set numAllPage to do script ("this.numPages;")
    set numNowPage to do script ("this.pageNum;")
    try
      if numAllPage is "undefined" then
        error number -1708
      end if
    on error
      display alert "エラー:文書が選択されていません" buttons {"OK", "キャンセル"} default button "OK" as informational giving up after 10
      return "エラー:文書が選択されていません"
    end try
  end tell
end tell
##################################
#### パス取得
##################################
tell application id "com.adobe.Reader"
  activate
  set objAvtivDoc to active doc
  tell objAvtivDoc
    ####ファイルエリアス取得
    set aliasFilePath to file alias as alias
  end tell
end tell
##################################
### パス関連
##################################
set strFilePath to POSIX path of aliasFilePath as text
set ocidFilePathStr to (refMe's NSString's stringWithString:strFilePath)
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath
set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath isDirectory:false)
##################################
#### 保存
##################################
tell application id "com.adobe.Reader"
  activate
  set objAvtivDoc to active doc
  tell objAvtivDoc
    set boolMode to modified
    ###変更箇所があるなら保存する
    if boolMode is true then
      save
    end if
  end tell
  close objAvtivDoc
end tell
##################################
#### ダイアログ
##################################
###ダイアログを前面に出す
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder"
    activate
  end tell
else
  tell current application
    activate
  end tell
end if

set listZoomType to {"1:設定しない", "2:単ページ", "3:連続ページ", "4:見開き単", "5:見開き単表紙有", "6:見開き連続", "7:見開き連続表紙有"} as list
set listZoomTyepeJS to {"NoLayout", "SinglePage", "OneColumn", "TwoColumnLeft", "TwoColumnRight", "TwoPageLeft", "TwoPageRight"} as list
try
  set listResponse to (choose from list listZoomType with title "選んでください" with prompt "ページ表示設定" default items (item 3 of listZoomType) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed)
on error
  log "エラーしました"
  return "エラーしました"
end try
if (item 1 of listResponse) is false then
  return "キャンセルしました"
end if
set strChoose to (item 1 of listResponse) as text
set numChoose to (character 1 of strChoose) as integer
set strZoomtype to item numChoose of listZoomTyepeJS as text
##################################
#### ダイアログ
##################################




####パス整形
tell application "Finder"
  set aliasPathToMe to (container of (path to me)) as alias
  set thePathToMe to (POSIX path of aliasPathToMe) as Unicode text
end tell
####コマンドへのパス
set strPyPath to ("" & thePathToMe & "bin/addOpenOption.py")
#####コマンドライン整形
set strCommandText to ("python3 \"" & strPyPath & "\" \"" & strFilePath & "\" \"" & strZoomtype & "\"") as text
log strCommandText
#####コマンド実行
do shell script strCommandText



##################################
#### ファイルを開く
##################################
tell application id "com.adobe.Reader"
  activate
  try
    set strJsCommandText to "app.openDoc({cPath:\"" & strFilePath & "\", bHidden: false,cDest:\"objAvtivDoc\", bUseConv:true});" as text
    set strResults to do script strJsCommandText
  on error
    #######JavascriptでエラーしたらAppleScriptでオープンを試みる
    set strResults to open (ocidFilePathURL as alias) options "zoom=50&pagemode=thumbs"
  end try
  
  
end tell

return



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

#!/usr/bin/env python3
import sys
import pypdf
###zoomType修正

#########################################入力ファイル受け取り
argGetData = sys.argv
strFilePath = str(argGetData[1])
strPageLayout = str(argGetData[2])
#########################################オープン
objInputData = open(strFilePath, 'rb'
#########################################ライター初期化
objReader = pypdf.PdfReader(objInputData)
objWriter = pypdf.PdfWriter()
#########################################複製
objWriter.clone_document_from_reader(objReader)
##########################################開き方設定
# objWriter.set_page_mode( "/UseNone")
# objWriter.set_page_mode( "/UseOutlines")
# objWriter.set_page_mode( "/UseThumbs")
# objWriter.set_page_mode( "/FullScreen")
# objWriter.set_page_mode( "/UseOC")
# objWriter.set_page_mode( "/UseAttachments")
################
##objWriter.set_page_layout("/NoLayout")
# objWriter.set_page_layout("/SinglePage")
##objWriter.set_page_layout("/OneColumn")
##objWriter.set_page_layout("/TwoColumnLeft")
##objWriter.set_page_layout("/TwoColumnRight")
##objWriter.set_page_layout("/TwoPageLeft")
##objWriter.set_page_layout("/TwoPageRight")

objWriter.set_page_layout("/" + strPageLayout + "")
##########################################開き方設定JS
# strJsPane = "this.pane = \"layers\";"
# strJsPane = "this.pane = \"thumbnails\";"
# strJsPane = "this.pane = \"bookmarks\";"
# strJsPane = "this.pane = \"fullscreen\";"
# strJsPane = "this.pane = \"attachments\";"

# strJsStrings = "function int(){" + strJsPane + "}int();"
################
# strJsZoomType = "this.zoomtype = zoomtype.none;"
# strJsZoomType = "this.zoomtype = zoomtype.fitP;"
# strJsZoomType = "this.zoomtype = zoomtype.fitW;"
# strJsZoomType = "this.zoomtype = zoomtype.fitH;"
# strJsZoomType = "this.zoomtype = zoomtype.fitV;"
# strJsZoomType = "this.zoomtype = zoomtype.pref;"
# strJsZoomType = "this.zoomtype = zoomtype.refW;"
# strJsZoomType = "this.zoomtype = " + strZoomType +  ";"
# strJsStrings = "function int(){" + strJsZoomType + "}int();"

# objWriter.add_js(strJsStrings)
##########################################保存
objInputData.close()
with open(strFilePath, 'wb') as objOutputData:
  objWriter.write(objOutputData)



|

より以前の記事一覧

その他のカテゴリー

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