本博客是自己在學習和工作途中的積累與總結,僅供自己參考,也歡迎大家轉載,轉載時請注明出處。
http://www.cnblogs.com/king-xg/p/6370890.html
如果覺得對您有幫助,請點擊推薦或收藏本博客,謝謝。
原因: 由於html轉pdf時,不能自動換行,因此才有下面的代碼.
注釋:完全模擬html頁面的自動換行!
最后的頁面展示效果:每一行的長度都一樣,看上去像<td></td>的自動換行一樣
package test; import java.io.UnsupportedEncodingException; /** * 解決pdf換行問題,在指定位置插入指定字符串,兼容中英文以及特殊字符 * * @author xg君 * */ public class app { public static void main(String[] args) throws UnsupportedEncodingException { System.out.println(addStr(10, "<br/>", "as阿薩德dsa阿斯蒂芬fladadasdsjf阿斯蒂芬ljdsljkjlfdsklfd啥地方都是skljdsasfasdfads")); } /** * 插入方法 * * @param num * 每隔幾個字符插入一個字符串(中文字符) * @param splitStr * 待指定字符串 * @param str * 原字符串 * @return 插入指定字符串之后的字符串 * @throws UnsupportedEncodingException */ public static String addStr(int num, String splitStr, String str) throws UnsupportedEncodingException { StringBuffer sb = new StringBuffer(); String temp = str; int len = str.length(); while (len > 0) { int idx = getEndIndex(temp, num); sb.append(temp.substring(0, idx + 1)).append(splitStr); temp = temp.substring(idx + 1); len = temp.length(); } return sb.toString(); } /** * 兩個數字/英文 * * @param str * 字符串 * @param num * 每隔幾個字符插入一個字符串 * @return int 最終索引 * @throws UnsupportedEncodingException */ public static int getEndIndex(String str, double num) throws UnsupportedEncodingException { int idx = 0; double val = 0.00; // 判斷是否是英文/中文 for (int i = 0; i < str.length(); i++) { if (String.valueOf(str.charAt(i)).getBytes("UTF-8").length >= 3) { // 中文字符或符號 val += 1.00; } else { // 英文字符或符號 val += 0.50; } if (val >= num) { idx = i; if (val - num == 0.5) { idx = i - 1; } break; } } if (idx == 0) { idx = str.length() - 1; } return idx; } }
效果: