Search code examples
c#itextpdfptable

How to set width for PdfPTable and align table center in page


i'm starter in iTextSharp, i write this code for create RoundRectangle into PdfPTable and align table in page center

 string pdfpath = Server.MapPath("PDFs");
        RoundRectangle rr = new RoundRectangle();

        using (Document document = new Document())
        {
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfpath + "/Graphics6.pdf", FileMode.CreateNew));
            document.Open();
            PdfPTable table = new PdfPTable(1);
                           float[] f=new float[]{0.5f};

            table.SetWidths(f);
            PdfPCell cell = new PdfPCell()
            {
                CellEvent = rr,
                Border = PdfPCell.NO_BORDER,

                Phrase = new Phrase("test")
            };
            table.AddCell(cell);
            document.Add(table);

i want change table width i change code

 string pdfpath = Server.MapPath("PDFs");
        RoundRectangle rr = new RoundRectangle();

        using (Document document = new Document())
        {
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfpath + "/Graphics6.pdf", FileMode.CreateNew));
            document.Open();
            PdfPTable table = new PdfPTable(1);
            table.TotalWidth = 5;

            int[] w = new int[] { 12};
           table.SetWidths(w);
            PdfPCell cell = new PdfPCell()
            {
                CellEvent = rr,
                Border = PdfPCell.NO_BORDER,

                Phrase = new Phrase("test")
            };
            table.AddCell(cell);
            document.Add(table);

but no work and no change width table in page. please help me. thanks all


Solution

  • You can use TotalWidth property for set width for PdfPTable like this code:

    string pdfpath = Server.MapPath("PDFs");
    RoundRectangle rr = new RoundRectangle();
    
    using (Document document = new Document())
    {
        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfpath + "/Graphics200.pdf", FileMode.CreateNew));
        document.Open();
        PdfPTable table = new PdfPTable(1);
        table.TotalWidth = 144f;
    
        table.LockedWidth = true;
        PdfPCell cell = new PdfPCell()
        {
            CellEvent = rr,
            Border = PdfPCell.NO_BORDER,
            Phrase = new Phrase("test")
        };
        table.AddCell(cell);
        document.Add(table);
    }