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;
Related
I need to apply an image on all my pages from my PDF, but without flattening it ( I want to have the ability to move it in my PDF reader afterwards)
My code:
String basePath = "d:\\zPDF\\";
DirectoryInfo d = new DirectoryInfo(basePath);//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.pdf"); //Getting Text files
List<string> listS = new List<string>();
foreach (FileInfo file in Files)
{
listS.Add(file.Name);
}
foreach (string s in listS)
{
using (System.IO.Stream inputPdfStream = new FileStream(basePath + s, FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite))
//using (System.IO.Stream inputImageStream = new FileStream(basePath + "x1.wmf", FileMode.Open, System.IO.FileAccess.Read, FileShare.Read))
using (System.IO.Stream inputImageStream2 = new FileStream(basePath + "x2.wmf", FileMode.Open, System.IO.FileAccess.Read, FileShare.Read))
using (System.IO.Stream outputPdfStream = new FileStream(basePath + "zResult" + s, FileMode.Create, System.IO.FileAccess.Write, FileShare.None))
{
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
//stamper.FormFlattening = true;
//stamper.FreeTextFlattening = true;
int numberOfPages = reader.NumberOfPages;
Image myImage = Image.GetInstance(inputImageStream2);
float f-Image1, f-Image2;
for (int i = 1; i <= numberOfPages; i++)
{
int nr, plusMinus = 25;
Rectangle mediabox = reader.GetPageSize(i);
int getTOP = (int)mediabox.GetTop(0);
int getRight = (int)mediabox.GetRight(0);
var pdfContentByte = stamper.GetOverContent(i);
nr = getRight - 600;
f-Image1 = row1(nr, nr + plusMinus);
//row1 - generates a random number between those 2 values
nr = 40;
f-Image2 = row1(nr, nr + plusMinus);
//row1 - generates a random number between those 2 values
myImage.SetAbsolutePosition(f-Image1, f-Image2);
myImage.RotationDegrees = row1(-35, 35);
pdfContentByte.AddImage(myImage);
}
stamper.Close();
}
I've tried:
stamper.FormFlattening = false;
stamper.FreeTextFlattening = false;
but no results. The image is still flatten.
I think, after I've read some posts, that I need to set up my PdfStamper in useAppendMode() but I don't know how should I do this and, I don't know if this is this right direction.
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 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);
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!