最近在写代码时,发现代码报错,原来在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号