c# – Cell alignment in itextsharp


I have a problem and I can't find a solution, I'm using itextesharp in a windowsfroms application, I created a table with 7 cells and I would like to align some to the right and others to be centered. unfortunately I'm only able to align either all the cells to the right or the left. through the table.DefaultCell.HorizontalAlignment = 0; I will post the code. I would like to thank anyone who can help, as I really need to finish this report.

            PdfPTable tabela = new PdfPTable(7);
            PdfPCell celula = new PdfPCell();
            tabela.TotalWidth = 790f;
            //  celula.HorizontalAlignment = 1;
            tabela.DefaultCell.HorizontalAlignment = 0;
            tabela.LockedWidth = true;
            float[] widths = new float[] { 16F, 40f,45F,60F,15f, 15f, 15f };
            tabela.HorizontalAlignment = 0;
            celula.HorizontalAlignment = 0;
            strSql= "  ";
            con = new SqlConnection(strcon);
            SqlCommand cmd2 = new SqlCommand(strSql, con);
            cmd2.Parameters.AddWithValue("@DataI", DateTime.Parse(mtbDtInicial.Text));
            cmd2.Parameters.AddWithValue("@DataF", DateTime.Parse(mtbDtFinal.Text));
            cmd2.Parameters.AddWithValue("@ifd", emn1);
            SqlDataReader ler = cmd2.ExecuteReader();
            while (ler.Read())
                tabela.AddCell (ler[4].ToString()); //conta a direita
                tabela.AddCell(ler[0].ToString());//título  a direita
                tabela.AddCell(ler[1].ToString());//subtitulo a direita
                tabela.AddCell(ler[2].ToString());//descr a direita
                tabela.AddCell(ler[6].ToString());//valor centralizado
                tabela.AddCell(ler[7].ToString());//perce centralizado
                tabela.AddCell(ler[8].ToString());//desp centralizado


I know it's a little late for your report to be delivered and I believe you've solved your problem, but I'll leave this answer as an aid to other users.

If you add a PdfPCell , the complete object, rather than just its contents, you can define other characteristics of the cell, such as alignment.

//Conta a direita
PdfPCell conta_cell = new PdfPCell(new Phrase(ler[4].ToString()));
conta_cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;

//título  a direita
PdfPCell titulo_cell = new PdfPCell(new Phrase(ler[0].ToString()));
titulo_cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;


//percentual centralizado
PdfPCell perce_cell = new PdfPCell(new Phrase(ler[7].ToString()));
perce_cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;

Scroll to Top