最近在寫代碼時,發現代碼報錯,原來在spire.pdf繪制表格的時候,如果某個字段的內容超過一定的長度就會出現index and length must refer to a location within the string的報錯
PdfGrid grid = new PdfGrid();
//設置單元格邊距和表格默認字體
grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);
Font font = new Font("Arial", 8, FontStyle.Regular, GraphicsUnit.Point, 1, true);
grid.Style.Font = new PdfTrueTypeFont(new Font("Arial Unicode MS", 8f), true);
//10列的表格
grid.Columns.Add(11);
//設置列寬
foreach (PdfGridColumn col in grid.Columns)
{
col.Width = 45f;
}
PdfPageBase page = sec.Pages.Add();
grid.Draw(page, new PointF(0, y));
當表格中某一列內容出現多種字符的時候,會出現bug
foreach (PdfGridColumn col in grid.Columns)
{
// col.Width = 45f;
}
row1 = grid.Rows.Add();
row1.Cells[0].Value = minMonthAssCode.Substring(0, 4) + "-" + minMonthAssCode.Substring(4, 2);
row1.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row1.Cells[0].Style.BackgroundBrush = PdfBrushes.White;
string voucherDesc = drV["voucher_desc"].ToString();
row1.Cells[1].Value = voucherDesc; //voucherDesc 這個變量如果出現多種字符就容易報錯
row1.Cells[1].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row1.Cells[1].Style.BackgroundBrush = PdfBrushes.White;
row1.Cells[2].ColumnSpan = 2;
row1.Cells[2].Value = "期初余額";
row1.Cells[2].StringFormat = new PdfStringFormat(PdfTextAlignment.Left);
row1.Cells[2].Style.BackgroundBrush = PdfBrushes.White;
row1.Cells[4].Value = " ";
row1.Cells[4].ColumnSpan = 2;
row1.Cells[4].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row1.Cells[4].Style.BackgroundBrush = PdfBrushes.White;
row1.Cells[6].Value = " ";
row1.Cells[6].ColumnSpan = 2;
row1.Cells[6].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row1.Cells[6].Style.BackgroundBrush = PdfBrushes.White;
row1.Cells[8].Value = amt_begin_dir;
row1.Cells[8].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row1.Cells[8].Style.BackgroundBrush = PdfBrushes.White;
row1.Cells[9].Value = (amt_begin_dir == "借" ? amt_begin_dr.ToString("n2") : amt_begin_dir == "貸" ? amt_begin_cr.ToString("n2") : " ");
row1.Cells[9].ColumnSpan = 2;
row1.Cells[9].StringFormat = new PdfStringFormat(PdfTextAlignment.Right);
row1.Cells[9].Style.BackgroundBrush = PdfBrushes.White;
經過幾天調試發現,這個指定列寬導致上面的問題出現,注釋后就再也沒報錯了。懷疑這個spire.pdf 在計算列寬的時候,自動切割出錯。因為我的內容里面包含多種字符,比如漢字,特殊字符,全角半角的大小括號。所幸終于解決了。
浙公網安備 33010602011771號