iTextSharp不支持阿拉伯语?导出DataGridView阿拉伯语数据遇阻求助
解决DataGridView阿拉伯语数据导出PDF问题(iTextSharp实现)
原代码的核心问题
- 文件流重复创建且未关联:
PdfWriter用了new FileStream("123", FileMode.Create),和外层的Output.pdf无关,导致实际生成的是空白的123文件,而非目标文件。 - 未将创建好的
pdfTable添加到PDF文档中,导出的PDF仅包含"ID:"文本,无表格数据。 - 未处理阿拉伯语的字体支持和从右到左(RTL)排版:默认字体不包含阿拉伯语字符,且阿拉伯语需设置RTL方向才能正确显示。
- 未处理单元格空值:
cell.Value.ToString()会在单元格为空时抛出空引用异常。
修正后的实现代码
确保你有支持阿拉伯语的字体文件(如系统自带的Arial Unicode MS.ttf,或阿拉伯语专用字体Amiri),使用以下代码:
// 加载支持阿拉伯语的字体,替换为你的字体路径 string fontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF"); BaseFont arabicBaseFont = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font arabicFont = new Font(arabicBaseFont, 10); // 创建PDF表格,列数匹配DataGridView PdfPTable pdfTable = new PdfPTable(dataGridView1.Columns.Count); pdfTable.DefaultCell.Padding = 3; pdfTable.WidthPercentage = 100; // 设置表格整体为RTL方向,适配阿拉伯语排版 pdfTable.RunDirection = PdfWriter.RUN_DIRECTION_RTL; // 添加表头 foreach (DataGridViewColumn column in dataGridView1.Columns) { PdfPCell headerCell = new PdfPCell(new Phrase(column.HeaderText, arabicFont)); // 表头单元格设置RTL headerCell.RunDirection = PdfWriter.RUN_DIRECTION_RTL; pdfTable.AddCell(headerCell); } // 添加表格数据 foreach (DataGridViewRow row in dataGridView1.Rows) { // 跳过DataGridView默认的空新行 if (row.IsNewRow) continue; foreach (DataGridViewCell cell in row.Cells) { // 处理空值,避免空引用异常 string cellText = cell.Value?.ToString() ?? string.Empty; PdfPCell dataCell = new PdfPCell(new Phrase(cellText, arabicFont)); // 数据单元格设置RTL dataCell.RunDirection = PdfWriter.RUN_DIRECTION_RTL; pdfTable.AddCell(dataCell); } } // 生成PDF文档 using (FileStream stream = new FileStream("Output.pdf", FileMode.Create)) { Document pdfDoc = new Document(PageSize.A4, 20f, 20f, 20f, 20f); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); // 添加标题(阿拉伯语标题靠右对齐) Paragraph title = new Paragraph("ID:", arabicFont); title.Alignment = Element.ALIGN_RIGHT; pdfDoc.Add(title); // 添加换行 pdfDoc.Add(new Paragraph("\n")); // 将表格添加到文档 pdfDoc.Add(pdfTable); pdfDoc.Close(); }
关键注意事项
- 字体嵌入:必须使用支持阿拉伯语的字体并嵌入到PDF中,否则在无该字体的设备上会显示乱码。
- RTL方向设置:通过
RunDirection = PdfWriter.RUN_DIRECTION_RTL设置表格和单元格的文本方向,确保阿拉伯语从右到左正确排版。 - 空值处理:使用
cell.Value?.ToString() ?? string.Empty避免空单元格导致的异常。 - 文件流管理:通过
using语句自动管理文件流,无需手动调用stream.Close()。
若尝试过iTextSharp pdfCalligraph,上述代码已包含基础RTL处理,无需额外配置即可实现阿拉伯语的正确显示。
内容的提问来源于stack exchange,提问作者Etch
相关产品推荐
相关产品推荐

