How to draw Arabic text in .NET PDF library grid cell?
The Syncfusion Essential® PDF is a feature-rich and high performance .NET PDF library used to create, read, and edit PDF documents programmatically without Adobe dependencies. Using this library, you can preserve Arabic text in a PDF table cell using C#.
Steps to preserve Arabic text properly in a PDF document programmatically:
- Create a new console application project.
- Install the Syncfusion.Pdf.Net.Core NuGet package as a reference to your console application from Nuget.org.
- Include the following namespaces in the Program.cs file.
C#
using Syncfusion.Pdf;
using Syncfusion.Pdf.Grid;
using System.Data;
using Syncfusion.Drawing;
using Syncfusion.Pdf.Graphics;
- Use the following code sample in Program.cs to preserve Arabic text properly in a PDF document.
C#
//Create a new PDF document.
PdfDocument document = new PdfDocument();
//Add a page.
PdfPage page = document.Pages.Add();
// Open a file stream.
FileStream fontStream = new FileStream(@"../../../arial.ttf", FileMode.Open, FileAccess.Read);
// Create a PdfTrueTypeFont object.
PdfFont font = new PdfTrueTypeFont(fontStream, 14);
// Create a PdfStringFormat object for text formatting.
PdfStringFormat format = new PdfStringFormat();
// Enable complex script support for the string format.
format.ComplexScript = true;
//Set right-to-left text direction for RTL text.
format.TextDirection = PdfTextDirection.RightToLeft;
//Create a PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
//Create a DataTable.
DataTable dataTable = new DataTable();
//Add columns to the DataTable.
dataTable.Columns.Add("ID");
dataTable.Columns.Add("Name");
//Add rows to the DataTable.
dataTable.Rows.Add(new object[] { "E01", "مرحبا" });
dataTable.Rows.Add(new object[] { "E02", "وداعا" });
pdfGrid.Style.Font = font;
//Assign data source.
pdfGrid.DataSource = dataTable;
PdfGridCell cell = pdfGrid.Rows[1].Cells[1];
cell.StringFormat = format;
PdfGridCell cell1 = pdfGrid.Rows[0].Cells[1];
cell1.StringFormat = format;
//Draw grid to the page of PDF document.
pdfGrid.Draw(page, new PointF(10, 10));
//Creating the stream object.
MemoryStream stream = new MemoryStream();
//Save the PDF document to stream.
document.Save(stream);
// Write the content of the memory stream to an output PDF file.
File.WriteAllBytes("Output.pdf", stream.ToArray());
//Close the document.
document.Close(true);
A complete working sample can be downloaded from Preserve_Arabic_text.zip
By executing the program, you will get the PDF document as follows.
Take a moment to peruse the documentation for working with Text, where you can find the other options like drawing right-to-left text, multicolumn text, consuming TrueType fonts, Standards fonts, and CJK fonts.
Click here to explore the rich set of Syncfusion Essential® PDF features.