« tsvタブ区切りテキストに行番号を入れる | トップページ | [Acrobat 2020]Acrobat 2020 製品版のアップデータの取得 »

TSV2QRバーコード(タブ区切りテキストからQRバーコードを生成する)

サンプルデータ入り

ダウンロード - maketsv2qr.zip


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
(*
com.cocolog-nifty.quicktimer.icefloe
TSVタブ区切りテキストからQRコードを生成します
*)
----+----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
property refNSNotFound : a reference to 9.22337203685477E+18 + 5807
##QRバーコードの最大幅
##(QRコード+クワイエットゾーンがあるのでひとまわり大きくなります)
property numMaxSize : 720 as integer

#################################
### 【1】入力ファイル
#################################
#ダイアログ
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 appFileManager to refMe's NSFileManager's defaultManager()
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
#
set listUTI to {"public.tab-separated-values-text"}
set strMes to ("ファイルを選んでください") as text
set strPrompt to ("ファイルを選んでください") as text
try
  ### ファイル選択時
  set aliasFilePath to (choose file strMes with prompt strPrompt default location aliasDesktopDirPath of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
if aliasFilePath is (missing value) then
return "選んでください"
end if
#パス
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)
#################################
### 【2】保存先
#################################
set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
set aliasContainerDirPath to (ocidContainerDirPathURL's absoluteURL()) as alias
set strMes to "フォルダを選んでください" as text
set strPrompt to "QRコードの保存先フォルダを選択してください\n同名ファイルがある場合\n『上書き』になります" as text
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 aliasResponse 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
#戻り値エイリアスをURLに
set strSaveDirPath to (POSIX path of aliasResponse) as text
set ocidSaveDirPathStr to (refMe's NSString's stringWithString:(strSaveDirPath))
set ocidSaveDirPath to ocidSaveDirPathStr's stringByStandardizingPath()
set ocidSaveDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSaveDirPath) isDirectory:true)
#################################
### 【3】本処理
#################################
#ファイル読み込み
set listResponse to (refMe's NSString's alloc()'s initWithContentsOfURL:(ocidFilePathURL) usedEncoding:(refMe's NSUTF8StringEncoding) |error|:(reference))
set ocidReadString to (item 1 of listResponse)
if ocidReadString = (missing value) then
  set strFileName to ocidFilePathURL's lastPathComponent() as text
  set strMes to ("文字コードを判定出来ませんでした : " & strFileName & "\n処理を中止します") as text
display alert strMes
return
end if
##############################
#改行コード判定
set ocidCrRange to (ocidReadString's rangeOfString:("\r"))'s location()
set ocidLfRange to (ocidReadString's rangeOfString:("\n"))'s location()
if ocidCrRange = refNSNotFound then
log "Mac改行は無い"
  if ocidLfRange = refNSNotFound then
log "Mac改行もUNIX改行は無い=改行の無い1行か空のテキスト"
    set ocidLength to ocidReadString's |length|
    if ocidLength = (refMe's NSNumber's numberWithInteger:0) then
log "空のテキスト"
      set ocidNewLineChar to ocidSetNewLineChar
    else
log "改行無しの1行テキスト"
      set ocidNewLineChar to ocidSetNewLineChar
    end if
  else
log "Mac改行無+UNIX改行あり=UNIX改行"
    set ocidNewLineChar to (refMe's NSString's stringWithString:("\n"))
  end if
else
  if ocidLfRange = refNSNotFound then
log "MacがあるUNIX改行は無い=Mac改行"
    set ocidNewLineChar to (refMe's NSString's stringWithString:("\r"))
  else
log "Mac改行ある+UNIX改行あり=Windows改行"
    set ocidNewLineChar to (refMe's NSString's stringWithString:("\r\n"))
  end if
end if
#改行毎でリストにする
set ocidLineArray to (ocidReadString's componentsSeparatedByString:(ocidNewLineChar))
#################################
### 【4】ダイアログ
#################################
set ocidFirstLineString to ocidLineArray's firstObject()
set ocidFirstLineArray to (ocidFirstLineString's componentsSeparatedByString:("\t"))
set listFirstLineArray to ocidFirstLineArray as list
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
  # tell application id "com.apple.appkit.xpc.openAndSavePanelService" to activate
else
  tell current application to activate
end if
###
set strTitle to ("選んでください") as text
set strPrompt to ("どの項目で作成しますか?") as text
try
  set listResponse to (choose from list listFirstLineArray with title strTitle with prompt strPrompt default items (item 1 of listFirstLineArray) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed) as list
on error
log "エラーしました"
return "エラーしました"
end try
if (item 1 of listResponse) is false then
return "キャンセルしましたA"
else if (item 1 of listResponse) is "キャンセル" then
return "キャンセルしましたB"
end if
set strResponse to (item 1 of listResponse) as text
##何番目を選んだ?
set ocidIndex to ocidFirstLineArray's indexOfObject:(strResponse)
#Arrayの項目数
set numCntListLine to (count of ocidLineArray) as integer
#処理番号のカウント
set numCntRowNo to 1 as integer
#行毎処理
repeat with itemIntNo from 1 to (numCntListLine - 1) by 1
  set ocidLineData to (ocidLineArray's objectAtIndex:(itemIntNo))
  if (ocidLineData as text) is "" then
    exit repeat
  end if
  #行毎にタブ区切りでリスト化して
  set ocidRowLineArray to (ocidLineData's componentsSeparatedByString:("\t"))
  #選んだ項目をとりだす
  set ocidMakeString to (ocidRowLineArray's objectAtIndex:(ocidIndex))
  if strResponse contains "電話" then
    set strMakeString to ("tel:" & ocidMakeString) as text
  else if strResponse contains "メール" then
    set strMakeString to ("maileto:" & ocidMakeString) as text
  else
    set strMakeString to ocidMakeString as text
  end if
  #ファイル名に処理番号入れる場合
  set strFileName to (numCntRowNo & "-" & ocidMakeString) as text
  set ocidFileName to (refMe's NSString's stringWithString:(strFileName))
  #ファイル名に使えない文字を置換
  set ocidInvalidChar to (refMe's NSString's stringWithString:("[\\\\/:*?\"<>|]"))
  set ocidRegex to (refMe's NSRegularExpression's regularExpressionWithPattern:(ocidInvalidChar) options:(refMe's NSRegularExpressionCaseInsensitive) |error|:(reference))
  set ocidLength to refMe's NSMakeRange(0, (ocidFileName's |length|))
  set ocidSafeFileName to (ocidFileName's stringByReplacingOccurrencesOfString:(ocidInvalidChar) withString:("_") options:(refMe's NSRegularExpressionSearch) range:(ocidLength))
  #保存ファイル名とURLを定義しておく
  set ocidBaseSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(ocidSafeFileName))
  set ocidSaveFilePathURL to (ocidBaseSaveFilePathURL's URLByAppendingPathExtension:("png"))
  #QRコード生成を実行する
log doMakeQRcode(strMakeString, ocidSaveFilePathURL)
  set numCntRowNo to (numCntRowNo + 1) as integer
end repeat

set ocidSaveDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSaveDirPath) isDirectory:true)

#################################
### 【サブ】QRコード生成
#################################
to doMakeQRcode(argText, argSaveFilePathURL)
  #############################
  ### 【1】QRバーコード画像生成
  #############################
  #QRの内容になるテキスト
  set ocidInputString to refMe's NSString's stringWithString:(argText)
  #データに
  set ocidInputData to ocidInputString's dataUsingEncoding:(refMe's NSUTF8StringEncoding)
  ####CIQRCodeGenerator初期化
  set ocidQRcodeImage to refMe's CIFilter's filterWithName:("CIQRCodeGenerator")
ocidQRcodeImage's setDefaults()
  ###テキスト設定
ocidQRcodeImage's setValue:(ocidInputData) forKey:("inputMessage")
  ###読み取り誤差値設定L, M, Q, H
ocidQRcodeImage's setValue:("Q") forKey:("inputCorrectionLevel")
  ###QRコード本体のイメージ
  set ocidQRImage to ocidQRcodeImage's outputImage()
  ###QRコードの縦横取得 この数値が縦横のセル数
  set ocidQRDimension to ocidQRImage's extent()
  set listQRorigin to (item 1 of ocidQRDimension) as list
  set listQRsize to (item 2 of ocidQRDimension) as list
  set numQRsize to (item 1 of listQRsize) as integer
  ##############################
  
  ###整数で拡大しないとアレなので↑の値のニアなサイズになります
  ##この数値倍する
  set numScale to ((numMaxSize / numQRsize) div 1) as integer
  ####変換スケール作成-->拡大
  set recordScalse to refMe's CGAffineTransform's CGAffineTransformMakeScale(numScale, numScale)
  ##変換スケールを適応(元のサイズに元のサイズのスケール適応しても意味ないけど
  set ocidQRScaledImage to ocidQRImage's imageByApplyingTransform:(recordScalse)
  ###イメージデータを展開 拡大したQRコードのサイズ
  set ocidQRScaledRep to refMe's NSCIImageRep's imageRepWithCIImage:(ocidQRScaledImage)
  set ocidQRScaledSize to ocidQRScaledRep's |size|()
  set numQRScaledSize to (ocidQRScaledSize's width) as integer
  ##############################
  ###出力用のイメージの初期化
  set ocidNSImageScaled to refMe's NSImage's alloc()'s initWithSize:(ocidQRScaledSize)
  ###イメージデータを合成
ocidNSImageScaled's addRepresentation:(ocidQRScaledRep)
  ###出来上がったデータはOS_dispatch_data
  set ocidQRDispatchData to ocidNSImageScaled's TIFFRepresentation()
  ####NSBitmapImageRepに
  set ocidQRScaledBmpRep to refMe's NSBitmapImageRep's imageRepWithData:(ocidQRDispatchData)
  ###quiet zone用に画像をパディングする
  set numPadSize to (numQRScaledSize + (numScale * 6)) as integer
  ###左右に3セル分づつ余白 quiet zoneを足す
  ####まずは元のQRコードのサイズに3x2セルサイズ分足したサイズの画像を作って
  #QRコード自体に1セルクワイエットゾーンがあるので合計4セル分のクワイエットゾーンになる
  set ocidBaseRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numPadSize) pixelsHigh:(numPadSize) bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(refMe's NSCalibratedRGBColorSpace) bitmapFormat:(refMe's NSAlphaFirstBitmapFormat) bytesPerRow:0 bitsPerPixel:32)
  ###初期化
refMe's NSGraphicsContext's saveGraphicsState()
  ###Context
  set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidBaseRep))
  ###ビットマップイメージ
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
  ###塗り色を『白』に指定して
refMe's NSColor's whiteColor()'s |set|()
  ###画像にする
refMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:numPadSize, height:numPadSize}})
  ###出来上がった画像にQRバーコードを左右3セル分ずらした位置にCompositeSourceOverする
  set numPxWidth to ocidQRScaledBmpRep's pixelsWide()
  set numPadPxSize to (numPadSize - numPxWidth) / 2 as integer
ocidQRScaledBmpRep's drawInRect:{origin:{x:(numPadPxSize), y:(numPadPxSize)}, |size|:{width:numPadSize, Hight:numPadSize}} fromRect:{origin:{x:0, y:0}, |size|:{width:numPadSize, height:numPadSize}} operation:(refMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value)
  ####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
  ####PNG用のプロパティ
  #保存用オプション
  set ocidPropertyDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidPropertyDict's setObject:(refMe's NSNumber's numberWithBool:(false)) forKey:(refMe's NSImageInterlaced))
(ocidPropertyDict's setObject:(refMe's NSNumber's numberWithFloat:(1 / 2.2)) forKey:(refMe's NSImageGamma))
  set ocidImageType to (refMe's NSBitmapImageFileTypePNG)
  #インラインデータに変換して
  set ocidSaveImageData to (ocidBaseRep's representationUsingType:(ocidImageType) |properties|:(ocidPropertyDict))
  #保存
  set listDone to (ocidSaveImageData's writeToURL:(argSaveFilePathURL) options:0 |error|:(reference))
end doMakeQRcode

|

« tsvタブ区切りテキストに行番号を入れる | トップページ | [Acrobat 2020]Acrobat 2020 製品版のアップデータの取得 »

Barcode QR」カテゴリの記事

Text TSV」カテゴリの記事