iText 的 PdfTemplate(繼承 PdfContentByte)沒有直接提供「設定粗體/斜體」的 API。本文揭示利用文字矩陣(setTextMatrix)進行幾何變換,模擬粗體(水平擴展)與斜體(傾斜切變)效果的實用技巧。
PDF 文字渲染使用 6 參數矩陣 [a, b, c, d, e, f] 對應 3x3 仿射變換矩陣:
[ a b 0 ]
[ c d 0 ]
[ e f 1 ]
a:水平縮放(預設 1)d:垂直縮放(預設 1)c:切變(傾斜)因子e, f:位移float ta = 1f, tb = 0f, tc = 0f, td = 1f, tx = 0f, ty = 0f;
ta += 0.15f; // 水平放大 15%
td += 0.05f; // 垂直微放大 5%
ty -= 0.15f; // 向下微移修正基線
tc += 0.3f; // 正值向右傾斜(約 16.7 度)
PdfTemplate template = cb.createTemplate(width, height);
cb.addTemplate(template, 1f, 0f, 0f, 1f, 0f, 0f); // 單位矩陣放置
// 一般文字
template.saveState();
template.beginText();
template.moveText(5f, 5f);
template.showText("Normal Text");
template.endText();
template.restoreState();
// 粗體 + 斜體文字
float ta = 1f, tb = 0f, tc = 0.3f, td = 1f, tx = 0f, ty = 0f;
ta += 0.15f; td += 0.05f; ty -= 0.15f; // 粗體參數
// tc = 0.3f 已設為斜體
template.saveState();
template.beginText();
template.moveText(5f, 5f);
template.setTextMatrix(ta, tb, tc, td, tx, ty); // 套用變換
template.showText("Bold & Italic Text");
template.endText();
template.restoreState();
SimSun-Bold.ttf、SimSun-Italic.ttf)並用 BaseFont.createFont 註冊。| 效果 | 調整參數 | 方向 |
|---|---|---|
| 放大/縮小 | a, d | >1 放大,<1 縮小 |
| 水平鏡像 | a = -1 | 左右翻轉 |
| 垂直鏡像 | d = -1 | 上下翻轉 |
| 順時針旋轉 90° | a=0, b=1, c=-1, d=0 | 旋轉 |
| 斜體(切變) | c (或 b) | 正值右傾/左傾 |
| 位移 | e (tx), f (ty) | 移動基線位置 |