AppleScript Python

[Python]PDFのメタデータのCreationDate と ModDateを削除します 作成日と修正日を削除 修正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({'/CreationDate': \"\", '/ModDate': \"\", })\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


|

[PyPDF2]PDFの開き方設定

pypdfでの不具合が出たので修正版

ダウンロード - set_page_mode.zip


#!/usr/bin/env python3
# coding: utf-8
import sys
# pypdf4でset_page_modeの不具合が出たためPyPDF2を利用する
from PyPDF2 import PdfReader, PdfWriter
from PyPDF2 import generic
file_path = sys.argv[1]
save_file_path = sys.argv[2]
str_layout = sys.argv[3]
str_mode = sys.argv[4]
#テスト用
# file_path = "/some/dir/some/input.pdf"
# save_file_path = "/some/dir/some/dist.pdf"
# str_layout = "/SinglePage"
# str_mode = "/UseOutlines"
# オープン
app_PdfReader = PdfReader(file_path)
app_PdfWriter = PdfWriter()
obj_writer_outline_root = app_PdfWriter.get_outline_root()

reader_meta = app_PdfReader.metadata
app_PdfWriter.add_metadata(reader_meta)

# PyPDF2ではoutlineのコピーはうまくいかない
# reader_outlines = app_PdfReader.outline
# writer_outlines = app_PdfWriter.get_outline_root()

# メタが移行できないのでページを付与する方式はやめた
# for itemReaderPage in app_PdfReader.pages:
# app_PdfWriter.add_page(itemReaderPage)
# 開き方>ページレイアウト
# app_PdfWriter.set_page_layout("/NoLayout") #ユーザー設定に依存
# app_PdfWriter.set_page_layout("/SinglePage") #単一ページ
# app_PdfWriter.set_page_layout("/OneColumn") #連続ページ
# app_PdfWriter.set_page_layout("/TwoColumnLeft") #見開連続
# app_PdfWriter.set_page_layout("/TwoColumnRight") #見開連続 表紙有り
# app_PdfWriter.set_page_layout("/TwoPageLeft") #見開
# app_PdfWriter.set_page_layout("/TwoPageRight") #見開表紙有り
app_PdfWriter.set_page_layout(str_layout)
# 開き方>表示
# app_PdfWriter.set_page_mode("/UseNone") #ページのみ
# app_PdfWriter.set_page_mode("/UseOutlines") #しおり
# app_PdfWriter.set_page_mode("/UseThumbs") #ページサムネイル
# app_PdfWriter.set_page_mode("/FullScreen") #フルスクリーン
# app_PdfWriter.set_page_mode("/UseOC") #レイヤーパネル
# app_PdfWriter.set_page_mode("/UseAttachments") #添付ファイル
app_PdfWriter.set_page_mode(str_mode)


# 開き方>表示 javaScript
# strJsPane = "this.pane = \"layers\";" #レイヤーパネル
# strJsPane = "this.pane = \"thumbnails\";" #ページサムネイル
# strJsPane = "this.pane = \"bookmarks\";" #しおり
# strJsPane = "this.pane = \"fullscreen\";" #フルスクリーン
# strJsPane = "this.pane = \"attachments\";" #添付ファイル
strJsPane = "this.pane = \"bookmarks\";"
################
# 開き方>表示
# 100 % 表示
# 全体表示
# 幅に合わせる
# 高さに合わせる
# 描画領域の幅に合わせる

# strJsZoomType = "this.zoomtype = zoomtype.none;" NoVary
# strJsZoomType = "this.zoomtype = zoomtype.fitP;" FitPage
# strJsZoomType = "this.zoomtype = zoomtype.fitW;" FitWidth
# strJsZoomType = "this.zoomtype = zoomtype.fitH;" FitHeight
# strJsZoomType = "this.zoomtype = zoomtype.fitV;" FitVisibleWidth
# strJsZoomType = "this.zoomtype = zoomtype.pref;" Preferred
# strJsZoomType = "this.zoomtype = zoomtype.refW;" ReflowWidth
strZoomType = "zoomtype.fitW"
strJsZoomType = "this.zoomtype = " + strZoomType + ";"
# JSセット
# strJsStrings = "function int(){" + strJsZoomType + strJsPane + "}int();"
# app_PdfWriter.add_js(strJsStrings)
#
#for page in app_PdfReader.pages:
# app_PdfWriter.add_page(page)

# BOOKMARK しおりのコピー(簡易版)
# 入れ子になった親子要素のあるoutlineは移行しません
obj_outline = app_PdfReader.outline
for outline_item in obj_outline:
print(outline_item)
    if isinstance(outline_item, dict):
obj_title = outline_item['/Title']
page_ref = outline_item['/Page']
page_number = app_PdfReader.get_page_number(page_ref)
print(obj_title)
print(page_number)
app_PdfWriter.add_outline_item(obj_title, page_number)


app_PdfWriter.clone_document_from_reader(app_PdfReader)
app_PdfWriter.clone_reader_document_root(app_PdfReader)

# 保存
with open(save_file_path, 'wb') as f:
app_PdfWriter.write(f)


|

[pypdf] PDFのbookmarkしおり=outlineのコピー(簡易版)

入れ子になった親子構造のoutlineはコピーしない簡易版

#!/usr/bin/env python3
# coding: utf-8
import sys
#ロード
#from PyPDF2 import PdfReader, PdfWriter
from pypdf import PdfReader, PdfWriter
#入力
file_path = "/some/dir/some/file.pdf"
save_file_path = "/some/dir/some/dist.pdf"
#初期化
app_PdfReader = PdfReader(file_path)
app_PdfWriter = PdfWriter()

#アウトラインをコピー
obj_outline = app_PdfReader.outline
for outline_item in obj_outline:
    #print(outline_item)
    if isinstance(outline_item, dict):
obj_title = outline_item['/Title']
page_ref = outline_item['/Page']
page_number = app_PdfReader.get_page_number(page_ref)
obj_child = outline_item
app_PdfWriter.add_outline_item(obj_title, page_number,)
#その他ドキュメント要素をコピー
# PyPDF2利用時はこちらも必要
#app_PdfWriter.clone_document_from_reader(app_PdfReader)
# pypdfはこちらだけでOK
app_PdfWriter.clone_reader_document_root(app_PdfReader)
# メタをコピー
obj_meta = app_PdfReader.metadata
app_PdfWriter.add_metadata(obj_meta)
#保存
with open(save_file_path, 'wb') as f:
app_PdfWriter.write(f)


|

[Font]postscript名を取得する(python利用)


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# python3を利用します
# fontToolsがインストールされていない場合インストールします
# インストールしたくない人は実行しないでください
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "UniformTypeIdentifiers"
use framework "AppKit"
use scripting additions

property refMe : a reference to current application

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

###python3のパスチェック
try
  set strCmdText to ("/usr/bin/which python3") as text
  set strBinPath to (do shell script strCmdText) as text
on error
return "python3が見つかりませんでした終了します"
end try
###fonttoolのインストールチェック
set strCmdText to ("\"" & strBinPath & "\" -m pip show fontTools") 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
  ##インストールされていなければインストールする
  set strCmdText to ("\"" & strBinPath & "\" -m pip install --user fontTools") as text
  set strPipDone to (do shell script strCmdText) as text
end try

###ダイアログを前面に出す
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 appFileManager to refMe's NSFileManager's defaultManager()
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSLibraryDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidLibraryDirPathURL to ocidURLsArray's firstObject()
set ocidFontsDirPathURL to ocidLibraryDirPathURL's URLByAppendingPathComponent:("Fonts")
set aliasFontsDirPath to (ocidFontsDirPathURL's absoluteURL()) as alias
#UTIリスト
set listUTI to {"public.opentype-font", "public.truetype-ttf-font", "public.truetype-collection-font", "public.opentype-collection-font"} as list
#メッセージ
set strMes to ("フォント・ファイルを選んでください") as text
set strPrompt to ("フォント・ファイルを選んでください") as text
try
  #ファイル選択
  set listAliasFilePath to (choose file strMes with prompt strPrompt default location aliasFontsDirPath of type listUTI with invisibles, multiple selections allowed and showing package contents) as list
on error
log "エラーしました"
return "エラーしました"
end try
if listAliasFilePath is {} then
return "選んでください"
end if


repeat with itemAliasFilePath in listAliasFilePath
  set strFontFilePath to (POSIX path of itemAliasFilePath) as text
  ##
  set ocidFilePathStr to (refMe's NSString's stringWithString:(strFontFilePath))
  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 ocidExtensionName to ocidFilePathURL's pathExtension()
  set strExtensionName to (ocidExtensionName's lowercaseString) as text
  #
  set strDefaultAnswer to ("") as text
  if ("ttf otf") contains strExtensionName then
log "単体フォントファイルです"
    ##【2】NameID=6
    set strCommandText to ("\"" & strBinPath & "\" -c \"from fontTools.ttLib import TTFont;print(TTFont('" & strFontFilePath & "')['name'].getDebugName(6));\"") as text
    set strPostScriptName to (do shell script strCommandText) as text
    if strPostScriptName is "None" then
      ##【2】NameID=6; PlatformID=1; EncodinglD=0; LanguageID=0 英語 Mac
      set strCommandText to ("\"" & strBinPath & "\" -c \"from fontTools.ttLib import TTFont;print(TTFont('" & strFontFilePath & "')['name'].getName(6, 1, 0, 0));\"") as text
      set strPostScriptName to (do shell script strCommandText) as text
    end if
    if strPostScriptName is "None" then
      ##【3】NameID=6; PlatformID=3; EncodinglD=1; LanguageID=1033 英語 Win
      set strCommandText to ("\"" & strBinPath & "\" -c \"from fontTools.ttLib import TTFont;print(TTFont('" & strFontFilePath & "')['name'].getName(6, 3, 1, 1033));\"") as text
      set strPostScriptName to (do shell script strCommandText) as text
    end if
    if strPostScriptName is "None" then
      set strDefaultAnswer to "取得に失敗しました"
    else
      set strDefaultAnswer to (strPostScriptName) as text
    end if
    ################################
  else if ("otc ttc") contains strExtensionName then
log "コレクションフォントです"
    ##同封されている書体数を数えて
    set strCommandText to ("\"" & strBinPath & "\" -c \"from fontTools.ttLib import TTCollection;print(len(TTCollection('" & strFontFilePath & "').fonts));\"") as text
    set numCntFont to (do shell script strCommandText) as integer
    
    repeat with itemIntNo from 0 to (numCntFont - 1) by 1
      ##【1】getDebugName
      set strCommandText to ("\"" & strBinPath & "\" -c \"from fontTools.ttLib import TTCollection;print(TTCollection('" & strFontFilePath & "').fonts[" & itemIntNo & "]['name'].getDebugName(6));\"") as text
      set strPostScriptName to (do shell script strCommandText) as text
      if strPostScriptName is "None" then
        ##【3】NameID=1; PlatformID=1; EncodinglD=0; LanguageID=0 英語 Mac
        set strCommandText to ("\"" & strBinPath & "\" -c \"from fontTools.ttLib import TTCollection;print(TTCollection('" & strFontFilePath & "').fonts[" & itemIntNo & "]['name'].getName(6, 1, 0, 0));\"") as text
        set strPostScriptName to (do shell script strCommandText) as text
      end if
      if strPostScriptName is "None" then
        ##【5】NameID=1; PlatformID=3; EncodinglD=1; LanguageID=1033 英語 Win
        set strCommandText to ("\"" & strBinPath & "\" -c \"from fontTools.ttLib import TTCollection;print(TTCollection('" & strFontFilePath & "').fonts[" & itemIntNo & "]['name'].getName(6, 3, 1, 1033));\"") as text
        set strPostScriptName to (do shell script strCommandText) as text
      end if
      if strPostScriptName is "None" then
        set strPostScriptName to "取得に失敗しました"
      end if
      set strDefaultAnswer to (strDefaultAnswer & strPostScriptName & "\n") as text
    end repeat
    
    
  end if
  ###ダイアログ
  #####ダイアログを前面に
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder" to activate
  else
    tell current application to activate
  end if
  set strSetValue to ("ID=6 PostScript Name名 戻り値です\n" & strFontFilePath) as text
  set aliasIconPath to (POSIX file "/System/Applications/Font Book.app/Contents/Resources/AppIcon.icns") as alias
  set recordResult to (display dialog strSetValue with title "PostScriptName" default answer strDefaultAnswer buttons {"クリップボードにコピー", "キャンセル", "OK"} default button "OK" cancel button "キャンセル" giving up after 20 with icon aliasIconPath without hidden answer)
  ###クリップボードコピー
  if button returned of recordResult is "クリップボードにコピー" then
    set strText to text returned of recordResult as text
    ####ペーストボード宣言
    set appPasteboard to refMe's NSPasteboard's generalPasteboard()
    set ocidText to (refMe's NSString's stringWithString:(strText))
appPasteboard's clearContents()
(appPasteboard's setString:(ocidText) forType:(refMe's NSPasteboardTypeString))
  end if
  
  
end repeat










|

[python3]フォント情報をHTMLで表示する

ダウンロード - fontinfo2htmlpy.zip


↑試す時はダウンロードして実行してください
セットアップ用のscriptを同封しています

#!/usr/bin/env python3
#coding: utf-8
import sys
import os
from fontTools.ttLib import TTFont
from fontTools.ttLib import TTCollection

#font_path = "/System/Library/Fonts/Supplemental/Arial Bold.ttf"
#font_path = "/System/Library/Fonts/ヒラギノ明朝 ProN.ttc"
font_path = sys.argv[1]

"""
NameID
NameID 内容 備考
0 著作権 Copyright notice
1 フォントファミリ Font Family name
2 サブファミリ Font Subfamily name
3 識別子 Unique font identifi
4 フォント名 Full font name
5 バージョン Version string
6 PostScript名 Postscript name
7 商標 Trademark
8 メーカー名 Manufacturer Name
9 デザイナー Designer
10 説明 Description
11 URL URL
12 デザイナーURL URL Designer
13 ライセンス License Description
14 ライセンスURL License Info URL
15 未使用
16 タイポファミリ名 Preferred Family
17 タイポサブファミリ名 Preferred Subfamily
18 Mac用のメニュー表示  
19 サンプルテキスト  
20 PostScriptCID find PostScriptCIDフォント名
21 WWS ファミリ名 weight width slope※
22 WWS サブファミリー名 weight width slope
23 CPALL Color Palette Light カラーフォント用
24 CPALD Color Palette Dark カラーフォント用
25 PostScriptバリエーション名 Multiple Master用


###LanguageID
Win 0x0411: 'ja',
Mac 11: 'ja',
0 1033 英語 0=English; 1033=United States;
11 1041 日本語 11=日本語 1041=日本
##EncodinglD
0 Roman;
1 Unicode
###Platform ID
0 Unicode Indicates Unicode version.
1 Macintosh QuickDraw Script Manager code.
2 (reserved; do not use)
3 Microsoft Microsoft encoding.

https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html/nfunction
"""

def ttc_func(font_path):
font_collection = TTCollection(font_path)
str_join_text = ""
str_join_text = str_join_text + (" \t" + str(font_path))
  for item_font in font_collection.fonts:
font_dic = item_font["name"].names
str_join_text = str_join_text + "\n" + str("-\t-" )
    for item in font_dic:
name_id = str(item.nameID)
item_value = str(item)
str_join_text = (str_join_text + "\n" + name_id + '\t' + item_value)

print(str_join_text)


def ttf_func(font_path):
font_single = TTFont(font_path)
font_dic = font_single["name"].names
  for item in font_dic:
name_id = str(item.nameID)
item_value = str(item)
str_join_text = ''.join(name_id + '\t' + item_value)
print(str_join_text)

#######
_, extension = os.path.splitext(font_path)
extension_lower = extension.lower()
if extension_lower == ".ttc":
ttc_func(font_path)
elif extension_lower == ".otc":
ttc_func(font_path)
elif extension_lower == ".otf":
ttf_func(font_path)
elif extension_lower == ".ttf":
ttf_func(font_path)

|

[python3]インストールしていないフォントのpostscript名を取得する(TTC・OTC対応)

ダウンロード - getpostscriptname.zip

試す場合は↑をダウンロードして使ってください
↓だけでは動作しません

#!/usr/bin/env python3
#coding: utf-8
import sys
import os
from fontTools.ttLib import TTFont
from fontTools.ttLib import TTCollection

#font_path = "/System/Library/Fonts/Supplemental/Arial Black.ttf"
#font_path = "/System/Library/Fonts/Supplemental/GillSans.ttc"
font_path = sys.argv[1]


def ttc_func(font_path):
font_collection = TTCollection(font_path)
  for item_font in font_collection.fonts:
postScriptName = item_font['name'].getDebugName(6)
print(postScriptName)

def ttf_func(font_path):
font_single = TTFont(font_path)
postScriptName = font_single['name'].getDebugName(6)
print(postScriptName)

#######
_, extension = os.path.splitext(font_path)
extension_lower = extension.lower()
if extension_lower == ".ttc":
ttc_func(font_path)
elif extension_lower == ".otc":
ttc_func(font_path)
elif extension_lower == ".otf":
ttf_func(font_path)
elif extension_lower == ".ttf":
ttf_func(font_path)

|

[qrcode]QRコードを生成する


【セットアップスクリプトを実行してください】|


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

#!/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

set strFilePath to ("~/Desktop/makeQRcode.png") as text

set strMaekString to ("美しい日本語") as text


set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
set strFilePath to ocidFilePath as text
set strExtension to ocidFilePath's pathExtension() as text


set strCommandText to ("/usr/bin/python3 -c \"import qrcode;qrdata = qrcode.make('" & strMaekString & "'); type(qrdata);qrdata.save('" & strFilePath & "');\"") as text


log strCommandText
do shell script strCommandText

|

[pyqrcode]QRコードを生成する

【セットアップスクリプトを実行してください】|


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

#!/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

set strFilePath to ("~/Desktop/makeQRcode.png") as text

set strMaekString to ("美しい日本語") as text


set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
set strFilePath to ocidFilePath as text
set strExtension to ocidFilePath's pathExtension() as text

if strExtension is "svg" then
  set strCommandText to ("/usr/bin/python3 -c \"import pyqrcode;qrdata = pyqrcode.create('" & strMaekString & "', encoding='utf-8', error='M'); qrdata.svg('" & strFilePath & "', scale=6, background='#eee', module_color='#36C', quiet_zone=3);\"") as text
else if strExtension is "png" then
  set strCommandText to ("/usr/bin/python3 -c \"import pyqrcode;qrdata = pyqrcode.create('" & strMaekString & "', encoding='utf-8', error='M'); qrdata.png('" & strFilePath & "', scale=6, background='#eee', module_color='#36C', quiet_zone=3);\"") as text
else if strExtension is "eps" then
  set strCommandText to ("/usr/bin/python3 -c \"import pyqrcode;qrdata = pyqrcode.create('" & strMaekString & "', encoding='utf-8', error='M'); qrdata.eps('" & strFilePath & "', scale=6, background='#eee', module_color='#36C', quiet_zone=3);\"") as text
  
end if

log strCommandText
do shell script strCommandText


|

[Terminal] python3 pip のアップデートとパッケージのアップデート


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

#!/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

###インストールするパッケージ
set listPackage to {"pip", "pypdf", "pypdf", "pdfautonup", "setuptools-scm", "stdeb", "PyPDF2", "PyPDF3", "pdfnup"} as list


try
do shell script "/usr/bin/xcode-select --install"
end try
##
try
  set strCmdText to ("/bin/mkdir -p $HOME/bin") as text
do shell script strCmdText
  set strCmdText to ("/bin/chmod 700 $HOME/Library/Caches/pip") as text
do shell script strCmdText
end try
##
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
end try
##
try
  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



## python3のパスチェック
try
  set strCmdText to ("/usr/bin/which python3") as text
  set strResponse to (do shell script strCmdText) as text
on error
return "python3が見つかりませんでした終了します"
end try
########################
#install
repeat with itemPackage in listPackage
  set strPackageName to itemPackage as text
  tell application "Terminal"
    set strCmdText to ("\"" & strResponse & "\" -m pip install --user \"" & strPackageName & "\"") as text
do script strCmdText
activate
  end tell
  
  repeat 5 times
    tell application "Terminal"
      set numCntWindow to (count of every window) as integer
      if numCntWindow = 1 then
log "Windowがありません"
        exit repeat
      end if
      tell front window
        set numWindowID to id
        tell front tab
          set boolBusy to busy as boolean
        end tell
      end tell
    end tell
    if boolBusy is false then
log "処理していないので閉じる"
      tell application "Terminal"
do script "\n\n" in window id numWindowID
do script "exit" in window id numWindowID
delay 1
close front window saving no
      end tell
      exit repeat
    else
log "busyなので1秒まつ"
delay 1
    end if
  end repeat
  tell application "Terminal"
    set numCntWindow to (count of every window) as integer
  end tell
  if numCntWindow = 1 then
log "Windowがありません"
  else
    ###
    tell application "Terminal"
      tell front window
        set numWindowID to id
        tell front tab
          set boolBusy to busy as boolean
        end tell
      end tell
    end tell
    if boolBusy is true then
      tell application "System Events"
        tell application "Terminal" to activate
keystroke "c" using {control down}
      end tell
      tell application "Terminal"
do script "\n\n" in window id numWindowID
do script "exit" in window id numWindowID
delay 1
close front window saving no
      end tell
    end if
  end if
end repeat
########################
#upgrade
repeat with itemPackage in listPackage
  set strPackageName to itemPackage as text
  tell application "Terminal"
    set strCmdText to ("\"" & strResponse & "\" -m pip install --upgrade --user \"" & strPackageName & "\"") as text
do script strCmdText
activate
  end tell
  
  repeat 5 times
    tell application "Terminal"
      set numCntWindow to (count of every window) as integer
      if numCntWindow = 1 then
log "Windowがありません"
        exit repeat
      end if
      tell front window
        set numWindowID to id
        tell front tab
          set boolBusy to busy as boolean
        end tell
      end tell
    end tell
    if boolBusy is false then
log "処理していないので閉じる"
      tell application "Terminal"
do script "\n\n" in window id numWindowID
do script "exit" in window id numWindowID
delay 1
close front window saving no
      end tell
      exit repeat
    else
log "busyなので1秒まつ"
delay 1
    end if
  end repeat
  tell application "Terminal"
    set numCntWindow to (count of every window) as integer
  end tell
  if numCntWindow = 1 then
log "Windowがありません"
  else
    ###
    tell application "Terminal"
      tell front window
        set numWindowID to id
        tell front tab
          set boolBusy to busy as boolean
        end tell
      end tell
    end tell
    if boolBusy is true then
      tell application "System Events"
        tell application "Terminal" to activate
keystroke "c" using {control down}
      end tell
      tell application "Terminal"
do script "\n\n" in window id numWindowID
do script "exit" in window id numWindowID
delay 1
close front window saving no
      end tell
    end if
  end if
end repeat


display notification "処理終了" with title "処理が終了" subtitle "処理が終了しました" sound name "Sonumi"
return


|

[python] html.escape Html Entities1ライナー


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

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

set strHTML to "&<\"'>=" as text

##クオトのエスケープ
set strHTML to doReplace(strHTML, "\"", "\\\"")
##pythonでのシングルクオトの取り扱い上困った
set strHTML to doReplace(strHTML, "'", "&apos;")
##エンティティ化する
set strHtmlEntities to doHtmlEntitiesPy(strHTML) as text

log strHtmlEntities


################################
## Entities
################################
on doHtmlEntitiesPy(argText)
  set strResponce to (do shell script "/usr/bin/python3 -c 'import html;[print(html.escape(\"" & argText & "\"))]';") as text
return strResponce as text
end doHtmlEntitiesPy

################################
## 置換
################################
to doReplace(argOrignalText, argSearchText, argReplaceText)
  set strDelim to AppleScript's text item delimiters
  set AppleScript's text item delimiters to argSearchText
  set listDelim to every text item of argOrignalText
  set AppleScript's text item delimiters to argReplaceText
  set strReturn to listDelim as text
  set AppleScript's text item delimiters to strDelim
return strReturn
end doReplace




|

その他のカテゴリー

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