PostScriptで表を作るとき、長い文字列でも枠からはみ出さないように文字列の横幅を自動調整して印字する手続きを作りましたが、今度は同じ機能ですが、横幅をスタックにつんで渡すバージョンです。辞書によるローカル変数を使っていますのでコードがすっきりして分かりやすいものになっています。
%!PS-Adobe-3.0 2.834645669 2.834645669 scale newpath /vPosition 297 20 sub def % A4 297mm /CellW 100 def % 枠の幅 /Space 3 def % 枠と文字の距離 /ADJW CellW Space 2 mul sub def % 枠幅からスペースを削除した幅 0.3 setlinewidth % 線の太さ /Left 20 def % --------------------------------------------------------- % 水平書き込み開始位置:左位置 + スペース % --------------------------------------------------------- /hPosition Left Space add def /MS-Mincho-90ms-RKSJ-H findfont 10 scalefont setfont % --------------------------------------------------------- % 文字列が指定された幅より大きい場合は横の比率を縮小して印字 % --------------------------------------------------------- /sameLendict 1 dict def % stack : string width /SameLength { sameLendict begin /str exch def % 入力文字列 /boxWidth exch def % 指定幅 /strWidth str stringwidth pop def % 文字列幅算出 /lengthRatio strWidth boxWidth div def % 文字列幅と指定幅の比率 % 比率を STDOUT に出力 (lengthRatio=) print lengthRatio == gsave % 比率が1より大きいときは ((1 / 横比率) 1 scale) を実行します。 lengthRatio 1 gt { 1 lengthRatio div 1 scale } if str show grestore end } def % --------------------------------------------------------- % 改行処理です。垂直位置を-15 して、指定位置に移動します。 % --------------------------------------------------------- /newline { /vPosition vPosition 15 sub def hPosition vPosition moveto } def % 枠を表示 Left vPosition moveto CellW 0 rlineto 0 -100 rlineto CellW neg 0 rlineto closepath stroke hPosition vPosition moveto newline ADJW (本日は晴天なり) SameLength % => lengthRatio=0.744671285 newline ADJW (本日は晴天なり本日は晴天なり) SameLength % => lengthRatio=1.48934257 newline ADJW (本日は晴天なり本日は晴天なり本日は晴天なり) SameLength % => lengthRatio=2.2340138 newline ADJW (本日は晴天なり本日は晴天なり本日は晴天なり本日は晴天なり) SameLength % => lengthRatio=2.97868514 newline ADJW (我輩は猫である。名前はまだない。) SameLength % => lengthRatio=1.70210576 newline ADJW (枠内に入るよう横幅を調整しています。) SameLength % => lengthRatio=1.91486895 showpage