I am using ITextSharp 5.5.7. I have the following code and everything is working. However, I need to remove the white space between each cell. I have tried all the suggestions found and still the white spaces are not removed. Here is the code:
private PdfPTable createTable()
{
// Table (No border, just to hold all objects)
PdfPTable sheetTable = new PdfPTable(1);
sheetTable.WidthPercentage = 100;
sheetTable.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
sheetTable.SpacingBefore = 0f;
sheetTable.SpacingAfter = 0f;
// Add Heading One
sheetTable.AddCell(createHeadingOne());
// Add Heading two
sheetTable.AddCell(createHeadingTwo());
return sheetTable;
}
private PdfPTable createHeadingOne()
{
PdfPCell cell = new PdfPCell();
PdfPTable headingTable = new PdfPTable(2);
// Set widths of columns
int[] headingTablewidths = { 50, 50 }; // percentage
headingTable.SetWidths(headingTablewidths);
cell = new PdfPCell(new Phrase("col1row1", FontFactory.GetFont(FontFactory.HELVETICA, 8, BaseColor.BLACK)));
headingTable.AddCell(cell);
cell = new PdfPCell(new Phrase("col2row1", FontFactory.GetFont(FontFactory.HELVETICA, 8, BaseColor.BLACK)));
headingTable.AddCell(cell);
return headingTable;
}
private PdfPTable createHeadingTwo()
{
PdfPCell cell = new PdfPCell();
PdfPTable headingTable = new PdfPTable(2);
// Set widths of columns
int[] headingTablewidths = { 50, 50 }; // percentage
headingTable.SetWidths(headingTablewidths);
cell = new PdfPCell(new Phrase("col1row2", FontFactory.GetFont(FontFactory.HELVETICA, 8, BaseColor.BLACK)));
headingTable.AddCell(cell);
cell = new PdfPCell(new Phrase("col2row2", FontFactory.GetFont(FontFactory.HELVETICA, 8, BaseColor.BLACK)));
headingTable.AddCell(cell);
return headingTable;
}
Update #1 The blue lines is the area were I need to remove the spacing:
Update #2, Fixed. Here is the code Bruno provided:
PdfPCell cell;
cell = new PdfPCell(createHeadingOne());
cell.Padding = 0;
sheetTable.AddCell(cell);
cell = new PdfPCell(createHeadingTwo());
cell.Padding = 0;
sheetTable.AddCell(cell);
I would solve this like this:
PdfPCell cell;
cell = new PdfPCell(createHeadingOne());
cell.Padding = 0;
sheetTable.AddCell(cell);
cell = new PdfPCell(createHeadingTwo());
cell.Padding = 0;
sheetTable.AddCell(cell);
Related
I'm trying to create PDF from the DataTable in web api using ADO.Net. Unfortunately based on filters some times I may get very less records & able to download without any problem. Sometimes may be very huge like 200 thousand of records. When I'm checking in local my system its getting hang while converting the dt to PDF. My code is like below:
private FileContentResult ExportPDF(DataTable dataTable)
{
string Name = "Logs";
System.IO.MemoryStream mStream = new System.IO.MemoryStream();
byte[] content = null;
try
{
string[] columnNames = (from dc in dataTable.Columns.Cast<DataColumn>() select dc.ColumnName).ToArray();
int count = columnNames.Length;
object[] array = new object[count];
dataTable.Rows.Add(array);
Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, mStream);
int cols = dataTable.Columns.Count;
int rows = dataTable.Rows.Count;
HeaderFooter header = new HeaderFooter(new Phrase(Name), false);
// Remove the border that is set by default
header.Border = iTextSharp.text.Rectangle.TITLE;
// Align the text: 0 is left, 1 center and 2 right.
header.Alignment = Element.ALIGN_CENTER;
pdfDoc.Header = header;
// Header.
pdfDoc.Open();
iTextSharp.text.Table pdfTable = new iTextSharp.text.Table(cols, rows);
pdfTable.BorderWidth = 1; pdfTable.Width = 100;
pdfTable.Padding = 1; pdfTable.Spacing = 4;
//creating table headers
for (int i = 0; i < cols; i++)
{
Cell cellCols = new Cell();
Chunk chunkCols = new Chunk();
iTextSharp.text.Font ColFont = FontFactory.GetFont(FontFactory.HELVETICA, 14, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.Black);
chunkCols = new Chunk(dataTable.Columns[i].ColumnName, ColFont);
cellCols.Add(chunkCols);
pdfTable.AddCell(cellCols);
}
//creating table data (actual result)
for (int k = 0; k < rows; k++)
{
for (int j = 0; j < cols; j++)
{
Cell cellRows = new Cell();
iTextSharp.text.Font RowFont = FontFactory.GetFont(FontFactory.HELVETICA, 12);
Chunk chunkRows = new Chunk(dataTable.Rows[k][j].ToString(), RowFont);
cellRows.Add(chunkRows);
pdfTable.AddCell(cellRows);
}
}
pdfDoc.Add(pdfTable);
pdfDoc.Close();
content = mStream.ToArray();
return File(content, "application/pdf", "LogReports.pdf");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
I am trying to set the background color of my footer. I can't seem to find any code that can assist in doing this. Please see my code for the OnEndPage event.
I have tried cb.SetColorFill(BaseColor.LIGHT_GRAY);, but that does not work :/
Which property or method is used to add a background color to the footer?
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
{
base.OnEndPage(writer, document);
iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
var headerImagePath = System.Web.HttpContext.Current.Server.MapPath("~/Content/misc/proactive-reg-form-header.jpg");
var headerImage = Image.GetInstance(headerImagePath);
if (headerImage.Height > headerImage.Width)
{
//Maximum height is 800 pixels.
float percentage = 0.0f;
percentage = 700 / headerImage.Height;
headerImage.ScalePercent(percentage * 100);
}
else
{
//Maximum width is 600 pixels.
float percentage = 0.0f;
percentage = 572 / headerImage.Width;
headerImage.ScalePercent(percentage * 100);
}
//Create PdfTable object
PdfPTable pdfTab = new PdfPTable(1);
//We will have to create separate cells to include image logo and 2 separate strings
//Row 1
//PdfPCell pdfCell1 = new PdfPCell();
PdfPCell pdfCell2 = new PdfPCell(headerImage);
//PdfPCell pdfCell3 = new PdfPCell();
String text = "Page " + writer.PageNumber + " of ";
//Add paging to footer
{
cb.BeginText();
cb.SetFontAndSize(bf, 10);
cb.SetTextMatrix(document.PageSize.GetRight(100), document.PageSize.GetBottom(30));
cb.ShowText(text);
cb.EndText();
float len = bf.GetWidthPoint(text, 10);
cb.AddTemplate(footerTemplate, document.PageSize.GetRight(100) + len, document.PageSize.GetBottom(30));
//add image to footer
writer.DirectContent.AddImage(footerImage);
}
pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM;
pdfCell2.Border = 0;
pdfTab.AddCell(pdfCell2);
pdfTab.TotalWidth = 100f;
pdfTab.WidthPercentage = 100f;
//call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
//first param is start row. -1 indicates there is no end row and all the rows to be included to write
//Third and fourth param is x and y position to start writing
pdfTab.WriteSelectedRows(0, -1, 10, document.PageSize.Height - 10, writer.DirectContent);
//set pdfContent value
if (document.PageNumber != 1)
{
//Move the pointer and draw line to separate header section from rest of page
cb.MoveTo(10, document.PageSize.Height - 60);
cb.LineTo((document.PageSize.Width - 10), document.PageSize.Height - 60);
cb.Stroke();
}
}
Got it!
So I amended the following code:
//Add paging to footer
{
cb.BeginText();
cb.SetFontAndSize(bf, 10);
cb.SetTextMatrix(document.PageSize.GetRight(100), document.PageSize.GetBottom(30));
cb.ShowText(text);
cb.EndText();
float len = bf.GetWidthPoint(text, 10);
cb.AddTemplate(footerTemplate, document.PageSize.GetRight(100) + len, document.PageSize.GetBottom(30));
//add image to footer
writer.DirectContent.AddImage(footerImage);
}
with
//Add paging to footer
{
cb.BeginText();
cb.SetFontAndSize(bf, 10);
cb.SetTextMatrix(document.PageSize.GetRight(100), document.PageSize.GetBottom(30));
cb.ShowText(text);
cb.EndText();
float len = bf.GetWidthPoint(text, 10);
cb.AddTemplate(footerTemplate, document.PageSize.GetRight(100) + len, document.PageSize.GetBottom(30));
//this part adds the background color
cb.SetColorFill(BaseColor.LIGHT_GRAY);
cb.Rectangle(0, 0, document.PageSize.Width, 50);
cb.FillStroke();
//add image to footer
writer.DirectContent.AddImage(footerImage);
}
Below is my sample application where I am getting an error on line
Add2CellRow(table, "Age", 1, "Gender", 2);
I think the rowspan value is creating the issue as the next line is not building.
Can someone help on the same?
The code is for Arabic Culture so need to set
Thread.CurrentThread.CurrentCulture = new CultureInfo("ar-SA");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("ar-SA");
private static void Add3CellRow(PdfPTable table, string cell1Value, string cell2Value, int rowspan, string imgPath)
{
PdfPCell new1Cell = new PdfPCell(new Phrase(cell1Value, tableFont));
new1Cell.VerticalAlignment = Element.ALIGN_MIDDLE;
new1Cell.MinimumHeight = 25f;
new1Cell.Padding = 6f;
table.AddCell(new1Cell);
PdfPCell new2Cell = new PdfPCell(new Phrase(cell2Value, tableFont));
new2Cell.VerticalAlignment = Element.ALIGN_MIDDLE;
new2Cell.MinimumHeight = 25f;
new2Cell.Padding = 6f;
new2Cell.Colspan = 2;
table.AddCell(new2Cell);
PdfPCell new3Cell = null;
if (!String.IsNullOrWhiteSpace(imgPath))
{
Image img = Image.GetInstance(imgPath);
img.ScaleToFit(150, 150);
new3Cell = new PdfPCell(img);
}
else
{
new3Cell = new PdfPCell(new Phrase(String.Empty));
}
new3Cell.VerticalAlignment = Element.ALIGN_MIDDLE;
new3Cell.HorizontalAlignment = Element.ALIGN_CENTER;
new3Cell.MinimumHeight = 25f;
new3Cell.Rowspan = rowspan;
new3Cell.Colspan = 2;
new3Cell.Padding = 6f;
table.AddCell(new3Cell);
}
private static void Add2CellRow(PdfPTable table, string cell1Value, int colspanCell1, string cell2Value, int colspanCell2 = 2)
{
PdfPCell new1Cell = new PdfPCell(new Phrase(cell1Value, tableFont));
new1Cell.VerticalAlignment = Element.ALIGN_MIDDLE;
new1Cell.MinimumHeight = 25f;
new1Cell.Colspan = colspanCell1;
table.AddCell(new1Cell);
PdfPCell new2Cell = new PdfPCell(new Phrase(cell2Value, tableFont));
new2Cell.VerticalAlignment = Element.ALIGN_MIDDLE;
new2Cell.Colspan = colspanCell2;
new2Cell.MinimumHeight = 25f;
new2Cell.Padding = 6f;
table.AddCell(new2Cell);
}
public static MemoryStream Generate()
{
var doc = new Document(PageSize.A4, 10, 10, 90, 110);
MemoryStream memoryStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);
doc.Open();
PdfPTable table = new PdfPTable(5);
table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
table.WidthPercentage = 89.5f;
table.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
table.DefaultCell.Padding = 6f;
table.DefaultCell.UseAscender = true;
table.DefaultCell.UseDescender = true;
Add3CellRow(table,"Name","Harshit Verma",4,"");
Add2CellRow(table, "Age", 1, "Gender", 2);
Add2CellRow(table, "Age", 1, "Gender", 2);
Add2CellRow(table, "Age", 1, "Gender", 2);
table.SplitLate = false;
Paragraph p = new Paragraph("");
doc.Add(p);
table.SpacingBefore = 30f;
doc.Add(table);
writer.CloseStream = false;
doc.Close();
memoryStream.Position = 0;
return memoryStream;
}
I have a form fill pdf where we dynamically add text field values to pdf. after adding this i need to add the table in the same page of the pdf.
if i add table it creates new pdf with only table. all other existing data are cleared.
I am using below code :
private void AddTableToPDF()
{
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 100, 100);
try
{
string pdfFilePath = #"D:\Temp\PDF\Inspection Form - Steel Girder.pdf";
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pdfFilePath, FileMode.Append));
doc.Open();//Open Document to write
System.IO.MemoryStream mStream = new System.IO.MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, mStream);
DataTable dt = GetDataTable();
DataTable dtHeader = new DataTable();
dtHeader = GetHeaderDataTable();
if (dtHeader != null)
{
PdfPTable PdfTable = new PdfPTable(dtHeader.Columns.Count);
PdfPCell PdfPCell = null;
for (int rows = 0; rows < dtHeader.Rows.Count; rows++)
{
for (int column = 0; column < dtHeader.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dtHeader.Rows[rows][column].ToString(), font8)));
PdfTable.AddCell(PdfPCell);
}
}
doc.Add(PdfTable); // add pdf table to the document
}
if (dt != null)
{
PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
PdfPCell PdfPCell = null;
PdfPCell = new PdfPCell(new Phrase(new Chunk("Reference", font8)));
PdfTable.AddCell(PdfPCell);
PdfPCell = new PdfPCell(new Phrase(new Chunk("Remark", font8)));
PdfTable.AddCell(PdfPCell);
PdfPCell = new PdfPCell(new Phrase(new Chunk("Description", font8)));
PdfTable.AddCell(PdfPCell);
for (int rows = 0; rows < dt.Rows.Count; rows++)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
PdfTable.AddCell(PdfPCell);
}
}
doc.Add(PdfTable); // add pdf table to the document
}
}
catch (DocumentException docEx)
{
Response.Write(docEx.Message);
}
catch (IOException ioEx)
{
Response.Write(ioEx.Message);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
doc.Close();
}
}
Suppose your main PDF is named with m1.pdf. you just create a new PDF with name m2.pdf which will contain the new Table that you need to add. now just merge these Two PDF (m1.pdf & m2.pdf) in to new one 'MergedNerw.pdf')
To Merge Two PDF please use following code this Works fine i have Tested it:
protected void BtnMerge_Click(object sender, EventArgs e)
{
String[] files = #"d:\m1.pdf,d:\m2.pdf".Split(',');
MergeFiles(#"d:\MergedNew.pdf", files);
}
public void MergeFiles(string destinationFile, string[] sourceFiles)
{
if (System.IO.File.Exists(destinationFile))
System.IO.File.Delete(destinationFile);
string[] sSrcFile;
sSrcFile = new string[2];
string[] arr = new string[2];
for (int i = 0; i <= sourceFiles.Length - 1; i++)
{
if (sourceFiles[i] != null)
{
if (sourceFiles[i].Trim() != "")
arr[i] = sourceFiles[i].ToString();
}
}
if (arr != null)
{
sSrcFile = new string[2];
for (int ic = 0; ic <= arr.Length - 1; ic++)
{
sSrcFile[ic] = arr[ic].ToString();
}
}
try
{
int f = 0;
PdfReader reader = new PdfReader(sSrcFile[f]);
int n = reader.NumberOfPages;
//Response.Write("There are " + n + " pages in the original file.");
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
while (f < sSrcFile.Length)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(PageSize.A4);
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
//Response.Write("\n Processed page " + i);
}
f++;
if (f < sSrcFile.Length)
{
reader = new iTextSharp.text.pdf.PdfReader(sSrcFile[f]);
//get the numnber of pages
n = reader.NumberOfPages;
//Response.Write("There are " + n + " pages in the original file.");
}
}
//Response.Write("Success");
document.Close();
}
catch (Exception e)
{
//Response.Write(e.Message);
}
}
Hope this helps you!
Does anyone know how to left align a iTextSharp table?
You can use the PdfPTable's HorizontalAlignment property.
Here's a C# test method you can use to experiment:
private void TestTableCreation() {
using (FileStream fs = new FileStream("TableTest.pdf", FileMode.Create)) {
Document doc = new Document(PageSize.A4);
PdfWriter.GetInstance(doc, fs);
doc.Open();
PdfPTable table = new PdfPTable(4);
table.WidthPercentage = 50.0f;
// Options: Element.ALIGN_LEFT (or 0), Element.ALIGN_CENTER (1), Element.ALIGN_RIGHT (2).
table.HorizontalAlignment = Element.ALIGN_LEFT;
for (int i = 1; i <= 20; i++) {
PdfPCell cell = new PdfPCell(new Phrase(String.Format("Cell # {0}", i)));
cell.FixedHeight = 30.0f;
cell.HorizontalAlignment = Element.ALIGN_LEFT;
cell.VerticalAlignment = Element.ALIGN_MIDDLE;
table.AddCell(cell);
}
doc.Add(table);
doc.Close();
}
}
table.HorizontalAlignment = 1;
1:center
0:left
2:right
There are two ways of doing it:
cell.HorizontalAlignment = Element.ALIGN_LEFT;
cell.HorizontalAlignment = 0;