PdfPTable cell width - c#

I'm using iTextSharp to create PDFs in my application. However I have to recreate a table, where I have to set the size for a very small column. Below is the picture that shows the size I want to set the column:
When the rest of the table creation all is well, I can't set this width.
Code:
PdfPTable table = new PdfPTable(2);
table.WidthPercentage = 82.0f;
PdfPCell cell = new PdfPCell(new Phrase("Com a assinatura autógrafa, o signatário desta Auto-declaração garante ter cumprido estas condições:", fontetexto));
cell.PaddingBottom = 10f;
cell.PaddingTop = 10f;
cell.Colspan = 2;
cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
table.AddCell(cell);
table.AddCell("1. ");
table.AddCell("Os óleos e gorduras vegetais velhos fornecidos são biomassa conforme o Decreto de biomassa.");

try with this code
PdfPTable table = new PdfPTable(new float[] { 30f, 400f });
table.HorizontalAlignment = 0;
table.TotalWidth = 500f;
table.LockedWidth = true;
table.SetWidths(widths);

You can do this with much less efforts if you use XmlParser rather then the normal HtmlParser
var document = new Document();
var workStream = new MemoryStream(); // or you can use fileStream also.
PdfWriter writer = PdfWriter.GetInstance(document, workStream);
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, stream, Encoding.UTF8);
Check this nuget MvcRazorToPdf ,I found this better then RazorPDF

The following code worked for me:
PdfPTable table = new PdfPTable(2);
table.TotalWidth = 500;
table.SetTotalWidth(new float[] { 30f, 400f });
PdfPCell c1 = new PdfPCell();
PdfPCell c2 = new PdfPCell();
c1.AddElement(new Phrase("first column"));
c1.AddElement(new Phrase("second column"));
table.Rows.Add(new PdfPRow(new PdfPCell[] { c1, c2 }));

The answer from #IntellectWizard help me to reach a solution.
float[] widths = new float[] { 100f, 4000f }; // Code #IntellectWizard
gives a corrupted file, then i try:
PdfPTable table = new PdfPTable(new float[] { 30f, 400f });
This works!

Related

I want to increase the width of the first column in itextsharp pdf creation

I want to increase the width of the first column matricule in itextsharp pdf creation
The picture shows what I want
enter image description here
PdfPTable pdfTable = new PdfPTable(dataGridView4.ColumnCount);
//pdfTable. = 5;
pdfTable.DefaultCell.Padding = 3;
pdfTable.DefaultCell.HorizontalAlignment = 0;
pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
pdfTable.WidthPercentage = 100;
// pdfTable.SetWidths(GetHeaderWidths(font.GetFont("ARIAL", 30), headers));
pdfTable.DefaultCell.VerticalAlignment = Element.ALIGN_CENTER;
pdfTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
//pdfTa = Element.ALIGN_MIDDLE;
pdfTable.DefaultCell.BorderWidth = 1;
//pdfTable.DefaultCell.Width = 10;(
//pdfTable.TotalWidth = 300;
pdfTable.DefaultCell.UseAscender = true;
iTextSharp.text.Font fon = FontFactory.GetFont("ARIAL", 30);
foreach (DataGridViewColumn column in dataGridView4.Columns)
{
int c = 0;
PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
if (c == 0)
{
// pdfTable.SetWidths(c);
// column.HeaderText = "330";
// dataGridView4.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
// pdfTable.AddCell(cell);
}
You can custom the width using pdfptable
PdfPTable table = new PdfPTable(5); // this will be your # of columns.
table.HorizontalAlignment = 0;
table.TotalWidth = 500f;
table.LockedWidth = true;
float[] widths = new float[] { 20f, 60f, 60f, 30f, 50f };
table.SetWidths(widths);
this is what you want to concentrate on:
float[] widths = new float[] { 20f, 60f, 60f, 30f, 50f };
here is the article which may help you:
Source
another complete example:
public static void main(String[] args) {
Document doc = new Document();
try {
PdfWriter.getInstance(doc, new FileOutputStream("TableColumnWidth.pdf"));
doc.open();
PdfPTable table = new PdfPTable(4);
table.addCell(new PdfPCell(new Phrase("Cell 1")));
table.addCell(new PdfPCell(new Phrase("Cell 2")));
table.addCell(new PdfPCell(new Phrase("Cell 3")));
table.addCell(new PdfPCell(new Phrase("Cell 4")));
// Defiles the relative width of the columns
float[] columnWidths = new float[]{10f, 20f, 30f, 10f};
table.setWidths(columnWidths);
doc.add(table);
} catch (DocumentException | FileNotFoundException e) {
e.printStackTrace();
} finally {
doc.close();
}
}
source

Align text in center of cell next to image in itexsharp

Here is visual what my problem looks like.
Here is my code that produce that result.
public void intervencionHeaderLogo(string pictureURL,int width, int height)
{
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath(pictureURL));
image.ScaleAbsolute(width, height);
image.Alignment = 2;
//Table
PdfPTable table = new PdfPTable(1);
PdfPCell cell = new PdfPCell();
BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 20, iTextSharp.text.Font.NORMAL);
Paragraph p = new Paragraph("Reporte de intervención", font);
//Cell no 1
cell = new PdfPCell();
cell.Border = 0;
cell.AddElement(p);
cell.HorizontalAlignment = Element.ALIGN_CENTER;
table.AddCell(cell);
//Cell no 2
cell = new PdfPCell();
cell.Border = 0;
cell.AddElement(image);
table.AddCell(cell);
//Add table to document
pdfDoc.Add(table);
}
Here is what I want to have.
Any help would be appriciated
I was able to fix it i made a mistake i create a table of 1 when i should have made it of size 2.
//Table
PdfPTable table = new PdfPTable(2);
and the i added a line break like this in the paragraph like this
Paragraph p = new Paragraph("\nReporte de intervención", font);

Text is not even between two cells when inserting an image and text in the same cell, ITextSharp

I have table with 3 columns and one row. In cell 1 I have a phrase and in cell 2, next to the phrase I have an Image and a text.
I am able to combine the image and the text in a same cell but. The problem I have now is that the text in cell 1 is in a higher position than the text in cell 2 and I don't know why. And I need them to be even.
this is the result:
this is my code:
private void btnCrear_Click(object sender, EventArgs e)
{
Document doc = new Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.GetInstance(doc,
new FileStream((Application.StartupPath+"\\PSC.pdf"), FileMode.Create));
doc.AddTitle("Recibo de Pago de Derechos Laborales");
doc.AddCreator("Errol");
doc.Open();
/*Get Image and set size*/
iTextSharp.text.Image SC = iTextSharp.text.Image.GetInstance(Application.StartupPath+"\\SimboloColones.png");
SC.ScaleAbsolute(5, 8);
PdfPTable table = new PdfPTable(3);/*3 columns*/
table.TotalWidth = 588;
table.LockedWidth = true;
/*Cell 1*/
PdfPCell cell = new PdfPCell(new Phrase("Preaviso"));
cell.Colspan = 1;
cell.HorizontalAlignment = 2;
cell.BorderColor = BaseColor.BLACK;
cell.BorderWidthBottom = 0;
cell.BorderWidthTop = 0;
cell.BorderWidthRight = 0;
cell.BorderWidthLeft = 0;
table.AddCell(cell);
/*Cell 2*/
cell = new PdfPCell();
cell.Colspan = 1;
cell.HorizontalAlignment = 0;
cell.BorderColor = BaseColor.BLACK;
/*Insert Image and text into the cell*/
Phrase pPreaviso = new Phrase();
pPreaviso.Add(new Chunk(SC, 0, 0));
pPreaviso.Add(new Chunk("Cant Pre"));
cell.AddElement(pPreaviso);
table.AddCell(cell);
/*Cell 3*/
cell = new PdfPCell(new Phrase(" "));
cell.Colspan = 1;
cell.HorizontalAlignment = 1;
cell.BorderColor = BaseColor.BLACK;
cell.BorderWidthBottom = 0;
cell.BorderWidthTop = 0;
cell.BorderWidthRight = 0;
cell.BorderWidthLeft = 0;
table.AddCell(cell);
doc.Add(table);
doc.Close();
writer.Close();
System.Diagnostics.Process.Start(Application.StartupPath+"\\PSC.pdf");
}
I don't know what is wrong with the code.
Thanks in advance
Thanks to #BrunoLowagie I was able to come up with a solution. However, I also nedded the text alignment to be centered, therefore I ended up using Paragraph instead of Phrase for all the texts in the cells.
This is the final result:
And, this is the code that ended up working for me:
private void btnCrear_Click(object sender, EventArgs e)
{
Document doc = new Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.GetInstance(doc,
new FileStream((Application.StartupPath+"\\PSC.pdf"), FileMode.Create));
doc.AddTitle("Recibo de Pago de Derechos Laborales");
doc.AddCreator("Errol");
doc.Open();
/*Get Image and set size*/
iTextSharp.text.Image SC = iTextSharp.text.Image.GetInstance(Application.StartupPath+"\\SimboloColones.png");
SC.ScaleAbsolute(5, 8);
PdfPTable table = new PdfPTable(3);/*3 columns*/
table.TotalWidth = 588;
table.LockedWidth = true;
/*Cell 1*/
Paragraph Preaviso = new Paragraph();
Preaviso.Add(new Chunk("Preaviso"));
Preaviso.Alignment = 2;
PdfPCell cell = new PdfPCell();
cell.Colspan = 1;
cell.HorizontalAlignment = 2;
cell.BorderColor = BaseColor.BLACK;
cell.BorderWidthBottom = 0;
cell.BorderWidthTop = 0;
cell.BorderWidthRight = 0;
cell.BorderWidthLeft = 0;
cell.AddElement(Preaviso);
table.AddCell(cell);
/*Cell 2*/
Paragraph pPreaviso = new Paragraph();
SC.ScaleAbsolute(5, 8);
pPreaviso.Add(new Chunk(SC, 0, 0));
pPreaviso.Add(new Chunk("Cant Pre"));
pPreaviso.Alignment = 0;
cell = new PdfPCell();
cell.Colspan = 1;
cell.HorizontalAlignment = 0;
cell.BorderColor = BaseColor.BLACK;
cell.AddElement(pPreaviso);
table.AddCell(cell);
/*Cell 3*/
cell = new PdfPCell(new Phrase(" "));
cell.Colspan = 1;
cell.HorizontalAlignment = 1;
cell.BorderColor = BaseColor.BLACK;
cell.BorderWidthBottom = 0;
cell.BorderWidthTop = 0;
cell.BorderWidthRight = 0;
cell.BorderWidthLeft = 0;
table.AddCell(cell);
doc.Add(table);
doc.Close();
writer.Close();
System.Diagnostics.Process.Start(Application.StartupPath+"\\PSC.pdf");
}

Continue PDFtable on next page with headers

this is my code:
PdfPTable tableSumme = new PdfPTable(dtUebersicht.Columns.Count-1);
widthsSumme = new float[] { 4.2f, 5f, 5f, 5f, 5f };
tableSumme.SetWidths(widthsSumme);
tableSumme.WidthPercentage = 100;
tableSumme.TotalWidth = 500f;
foreach (DataColumn c in dtUebersicht.Columns)
{
PdfPCell Spalte = new PdfPCell(new Phrase(c.ColumnName, VerdanaFont));
Spalte.HorizontalAlignment = Element.ALIGN_CENTER;
Spalte.VerticalAlignment = Element.ALIGN_MIDDLE;
tableSumme.AddCell(Spalte);
}
PdfContentByte cbSumme = writerSumme.DirectContent;
foreach (DataRow dr in dtUebersicht.Rows)
{
PdfPCell Spalte0 = new PdfPCell(new Phrase(dr[0].ToString(), VerdanaFont));
Spalte0.HorizontalAlignment = Element.ALIGN_CENTER;
Spalte0.VerticalAlignment = Element.ALIGN_MIDDLE;
PdfPCell Spalte1 = new PdfPCell(new Phrase(dr[1].ToString(), VerdanaFont));
Spalte1.HorizontalAlignment = Element.ALIGN_CENTER;
Spalte1.VerticalAlignment = Element.ALIGN_MIDDLE;
tableSumme.AddCell(Spalte0);
tableSumme.AddCell(Spalte1);
}
tableSumme.WriteSelectedRows(0, -1, 35, 757, cbSumme);
This gives me a PDF with one page and the data on it. The data is longer than the page so I want to insert every 50th row a new page. How can I solve this?
A simple
if (Rowindex % 50 == 0)
{ documentSumme.NewPage(); }
doesn't work. Thanks
Here is a small example following the comment by #Bruno Lowagie.
When the end of the page is reached before all rows are added, they will be added on the next page.
Document doc = new Document();
FileStream fs = new FileStream(#"your path", FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
doc.Open();
List<string> columns = new List<string> {"col1", "col2", "col3", "col4", "col5"};
PdfPTable table = new PdfPTable(columns.Count);
table.SetWidths(new[] { 5f, 5f, 5f, 5f, 5f });
table.WidthPercentage = 100;
table.TotalWidth = 500f;
table.HeaderRows = 1;
foreach (string col in columns)
{
PdfPCell cell = new PdfPCell(new Phrase(col));
table.AddCell(cell);
}
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < columns.Count; j++)
{
PdfPCell cell = new PdfPCell(new Phrase($"{i},{j}"));
table.AddCell(cell);
}
}
doc.Add(table);
doc.Close();

Hiding table border in iTextSharp

How can i hide the table border using iTextSharp. I am using following code to generate a file:
var document = new Document(PageSize.A4, 50, 50, 25, 25);
// Create a new PdfWriter object, specifying the output stream
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(document, output);
document.Open();
PdfPTable table = new PdfPTable(3);
var bodyFont = FontFactory.GetFont("Arial", 10, Font.NORMAL);
PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns"));
cell.Colspan = 3;
cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
table.AddCell(cell);
Font arial = FontFactory.GetFont("Arial", 6, BaseColor.BLUE);
cell = new PdfPCell(new Phrase("Font test is here ", arial));
cell.PaddingLeft = 5f;
cell.Colspan = 1;
table.AddCell(cell);
cell = new PdfPCell(new Phrase("XYX"));
cell.Colspan = 2;
table.AddCell(cell);
cell = new PdfPCell(new Phrase("Hello World"));
cell.PaddingLeft = 5f;
cell.Colspan = 1;
table.AddCell(cell);
cell = new PdfPCell(new Phrase("XYX"));
cell.Colspan = 2;
table.AddCell(cell);
table.SpacingBefore = 5f;
document.Add(table);
document.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=Receipt-test.pdf");
Response.BinaryWrite(output.ToArray());
Do I need to specify no borders for individual cells or I can specify no borders for table itself.
Thank you
Although I upvoted the answer by Martijn, I want to add a clarification.
Only cells have borders in iText; tables don't have a border. Martijn's suggestion to set the border of the default cell to NO_BORDER is correct:
table.DefaultCell.Border = Rectangle.NO_BORDER;
But it won't work for the code snippet provided in the question. The properties of the default cell are only used if iText needs to create a PdfPCell instance implicitly (for instance: if you use the addCell() method passing a Phrase as parameter).
In the code snippet provided by #Brown_Dynamite, the PdfPCell objects are created explicitly. This means that you need to set the border of each of these cells to NO_BORDER.
Usually, I write a factory class to create cells. That way, I can significantly reduce the amount of code in the class that creates the table.
This should do the trick:
table.DefaultCell.Border = Rectangle.NO_BORDER;
or
table.borderwidth= 0;
First we can set all cell borders as 0 and After assigning all cell to table we can use the following code for for only pdfptable outer border.
PdfPCell cell = new PdfPCell();
cell.AddElement(t);
cell.BorderWidthBottom=1f;
cell.BorderWidthLeft=1f;
cell.BorderWidthTop=1f;
cell.BorderWidthRight = 1f;
PdfPTable t1 = new PdfPTable(1);
t1.AddCell(cell);
Here we can add table to one cell and can set border and again add that cell to another table and we can use as per our requirement.
If your PdfPTable is nested within another PdfPTable, the nested table will show table borders. The only way to get rid of the table borders is to put the nested PdfPTable into a PdfPCell of the main PdfPTable and set the border width of that cell to 0.
iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(1); //<-- Main table
table.TotalWidth = 540f;
table.LockedWidth = true;
float[] widths = new float[] { 540f };
table.SetWidths(widths);
table.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
table.SpacingAfter = 10;
PdfPTable bodyTable = new PdfPTable(1); //<--Nested Table
bodyTable.TotalWidth = 540f;
bodyTable.LockedWidth = true;
float[] bodyWidths = new float[] { 540f };
bodyTable.SetWidths(bodyWidths);
bodyTable.HorizontalAlignment = 0;
bodyTable.SpacingAfter = 10;
bodyTable.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
var para1 = new Paragraph("This is a long paragraph", blackNormal);
para1.SetLeading(3f, 1f);
PdfPCell bodyCell1 = new PdfPCell();
bodyCell1.AddElement(para1);
bodyCell1.Border = 0;
bodyTable.AddCell(bodyCell1);
iTextSharp.text.pdf.PdfPCell cellBody = new iTextSharp.text.pdf.PdfPCell(bodyTable);
cellBody.BorderWidth = 0; //<--- This is what sets the border for the nested table
table.AddCell(cellBody);
Took me a long time to figure this out. It works for me now.
PdfPTable table = new PdfPTable(4);
table.TotalWidth = 400f;
table.LockedWidth = true;
PdfPCell header = new PdfPCell(new Phrase("Header"));
header.Colspan = 4;
table.AddCell(header);
table.AddCell("Cell 1");
table.AddCell("Cell 2");
table.AddCell("Cell 3");
table.AddCell("Cell 4");
PdfPTable nested = new PdfPTable(1);
nested.AddCell("Nested Row 1");
nested.AddCell("Nested Row 2");
nested.AddCell("Nested Row 3");
PdfPCell nesthousing = new PdfPCell(nested);
nesthousing.Padding = 0f;
table.AddCell(nesthousing);
PdfPCell bottom = new PdfPCell(new Phrase("bottom"));
bottom.Colspan = 3;
table.AddCell(bottom);
doc.Add(table);
PdfPTable table = new PdfPTable(3);
table.TotalWidth = 144f;
table.LockedWidth = true;
table.HorizontalAlignment = 0;
PdfPCell left = new PdfPCell(new Paragraph("Rotated"));
left.Rotation = 90;
table.AddCell(left);
PdfPCell middle = new PdfPCell(new Paragraph("Rotated"));
middle.Rotation = -90;
table.AddCell(middle);
table.AddCell("Not Rotated");
doc.Add(table);
Check this link pls
try this code
yourtable.DefaultCell.Border = 0;

Categories

Resources