I am using the Itextsharp PDF tool to generate PDF using asp.net and C# , In that in one PDFPtable the last row data is repeating on next page means part of a table forwarded to next page. so want to show header for that Table on next page.
This is my code.
Document doc = new Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 20, 10);
string pdfFilePath = Server.MapPath(".") + "/pdf/myPdf" + Guid.NewGuid().ToString("N") + ".pdf";
try
{
//Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
FileStream fs = new FileStream(pdfFilePath, FileMode.Create);
//
PdfWriter wri = PdfWriter.GetInstance(doc, fs);
//Header Section
string strImagePath = Server.MapPath("Images");
string strReportName = oReportDTO.strReportName + " " + oReportDTO.oDateRange.FromDate.ToString(DateFormat);
Chunk headerchunk = new Chunk(strReportName, new Font(1, 8.0f));
HeaderFooter oHeader = new HeaderFooter(new Phrase(headerchunk), false);
oHeader.Border = Rectangle.NO_BORDER;
oHeader.Alignment = 1;
doc.Header = oHeader;
//Footer Section
string name ="Logged in as : " +currentLoggedInUser.UserName + new string(' ',70)+ "Page Number : " + doc.PageNumber;
Chunk Footerchunk1 = new Chunk(name, new Font(1, 5.0f));
HeaderFooter oFooter1 = new HeaderFooter(new Phrase(Footerchunk1), true);
oFooter1.Border = Rectangle.NO_BORDER;
oFooter1.Alignment = 1;
doc.Footer = oFooter1;
iTextSharp.text.Image imgFooter = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromFile(strImagePath + "/TransRisk Logo168x97.png"), System.Drawing.Imaging.ImageFormat.Jpeg);
imgFooter.ScaleAbsolute(80, 50);
Chunk footerchunk = new Chunk(imgFooter, 260.0f, 0.0f);
HeaderFooter oFooter = new HeaderFooter(new Phrase(name),new Phrase(footerchunk));
oFooter.Border =Rectangle.NO_BORDER;
doc.Footer = oFooter;
doc.Open();//Open Document to write
Font font8 = FontFactory.GetFont("ARIAL", 7);
HtmlTable dt = customMatrixReport;
if (dt.Rows.Count > 0)
{
//Craete instance of the pdf table and set the number of column in that table
int startColumnPosition = 1;
int endColumnPosition = 13;//End Column number in Pdf Page
int NoOfReports = Convert.ToInt32(Math.Ceiling((decimal)(dt.Rows[0].Cells.Count - 1) / endColumnPosition));//Count How many Pages to show
int pageRowCount = 0;
List<PdfPCell> lstHeaderCells = new List<PdfPCell>();
PdfPTable oPdfTable = null;
PdfPCell oPdfPCell = null;
for (int report = 1; report <= NoOfReports; ++report)
{
doc.Add(oHeader);
//ColumnText.ShowTextAligned(
int noOfColumns = -1;
if (endColumnPosition > dt.Rows[0].Cells.Count - 1) { endColumnPosition = dt.Rows[0].Cells.Count - 1; noOfColumns = (endColumnPosition - startColumnPosition) + 2; oPdfTable = new PdfPTable(noOfColumns); }
else
{
oPdfTable = new PdfPTable(14);
//Widths Count
noOfColumns = 14;
}
oPdfTable.TotalWidth = 650f;
List<float> lstwidths = new List<float>();
lstwidths.Add(100f);
for (int i = 2; i <= noOfColumns; ++i)
{
lstwidths.Add(80f);
}
oPdfTable.SetTotalWidth(lstwidths.ToArray());
pageRowCount = 0;
for (int rows = 0; rows < dt.Rows.Count; rows++)
{
//PageRowCount
pageRowCount = pageRowCount + 1;
//Description celll
if (rows == 0 )
{
//Background color for table header
oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[0].InnerText, new Font(1, 8.0f, 1, Color.WHITE))));
oPdfPCell.BackgroundColor = new Color(118, 147, 199);
oPdfTable.AddCell(oPdfPCell);
}
else
{
//background color for Table cells
oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[0].InnerText,new Font(1, 8.0f))));
oPdfPCell.BackgroundColor = new Color(232, 237, 255);
oPdfTable.AddCell(oPdfPCell);
}
//for header cel
if (rows == 0)
{
lstHeaderCells.Add(oPdfPCell);
}
for (int column = startColumnPosition; column <= endColumnPosition; column++)
{
if (rows == 0)
{
oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[column].InnerText, new Font(1, 8.0f, 1, Color.WHITE))));
oPdfPCell.BackgroundColor = new Color(118, 147, 199);
oPdfTable.AddCell(oPdfPCell);
}
else
{
oPdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows].Cells[column].InnerText, new Font(1, 8.0f))));
oPdfPCell.BackgroundColor = new Color(232, 237, 255);
oPdfPCell.Column.Alignment = 2;
oPdfTable.AddCell(oPdfPCell);
}
if (rows == 0)
{
lstHeaderCells.Add(oPdfPCell);
}
}
if (pageRowCount >= 40 && rows != (dt.Rows.Count - 1))
{
pageRowCount = 0; doc.Add(oPdfTable); doc.NewPage(); doc.Add(oHeader); oPdfTable = new PdfPTable(noOfColumns); oPdfTable.SetTotalWidth(lstwidths.ToArray()); foreach (PdfPCell oHeaderCell in lstHeaderCells) { oPdfTable.AddCell(oHeaderCell); }
}
}
startColumnPosition = endColumnPosition + 1;
endColumnPosition = endColumnPosition + 13;
oPdfTable.SpacingBefore = 10;
oPdfTable.SpacingAfter = 10;
doc.Add(oPdfTable);
//doc.NewPage();
}
}
else
doc.Add(oHeader);
}
finally
{
doc.Close();
}
help me..
Change this line-
if (endColumnPosition > dt.Rows[0].Cells.Count - 1) { endColumnPosition = dt.Rows[0].Cells.Count - 1; noOfColumns = (endColumnPosition - startColumnPosition) + 2; oPdfTable = new PdfPTable(noOfColumns); }
To this-
if (endColumnPosition > dt.Rows[0].Cells.Count - 1) { endColumnPosition = dt.Rows[0].Cells.Count - 1; noOfColumns = (endColumnPosition - startColumnPosition) + 2; oPdfTable = new PdfPTable(noOfColumns); oPdfTable.HeaderRows = 1;}
After this line-
oPdfTable = new PdfPTable(14);
Add this-
oPdfTable.HeaderRows = 1;
Change this line-
pageRowCount = 0; doc.Add(oPdfTable); doc.NewPage(); doc.Add(oHeader); oPdfTable = new PdfPTable(noOfColumns); oPdfTable.SetTotalWidth(lstwidths.ToArray()); foreach (PdfPCell oHeaderCell in lstHeaderCells) { oPdfTable.AddCell(oHeaderCell); }
To this-
pageRowCount = 0; doc.Add(oPdfTable); doc.NewPage(); doc.Add(oHeader); oPdfTable = new PdfPTable(noOfColumns); oPdfTable.HeaderRows = 1; oPdfTable.SetTotalWidth(lstwidths.ToArray()); foreach (PdfPCell oHeaderCell in lstHeaderCells) { oPdfTable.AddCell(oHeaderCell); }
Related
I have created report in excel sheet which Is described in image1 and this image should give redar diagram which in in Image2 in different excel sheet like given in screenshot.
there are two excel sheet in one excel as you can see in screenshot so in chart sheet there should be redar diagram and sheet named sheet there is excel report valud as you can see in screenshot
I have already done piechart and excel report as well and I get stocked while making redar diagram ,
example of that I had made piechart and excel report :
public static class TestRunTestCaseExportHelper {
public static byte[] TestRunTestCaseByTestRunIdToExcel(List<TestRunTestCaseExportModel> data1, List<TestRunTestCaseExportTestResultCountModel> datas, List<FunctionModuleModel> funcitonData, TestRunTestCaseCountPercentageModel testRunStatusCountPercentage)
{
try
{
byte[] result;
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var package = new ExcelPackage())
{
int cellNumb = 1;
string[] totalColumns = {
"SN",
"Test Case",
"Test Plan",
"Status"
};
string[] totalColumn = {
"Test Plan",
"Passed",
"Failed",
"Pending",
"Blocked",
};
string[] totalColumn3 = {
"Function",
"Count"
};
string[] totalColumn4 = {
"Status",
"Percentage",
};
var worksheet = package.Workbook.Worksheets.Add("Chart");
var worksheets = package.Workbook.Worksheets.Add("sheet");
//worksheet.InsertRow(5, 2);
var rand = new Random();
var testRunStatusCountPercentages = testRunStatusCountPercentage;
var data = new List<KeyValuePair<string, int>>
{
new KeyValuePair<string, int>("Passed", testRunStatusCountPercentages.PassedPercentage),
new KeyValuePair<string, int>("Failed", testRunStatusCountPercentages.FailedPercentage),
new KeyValuePair<string, int>("Pending",85),
new KeyValuePair<string, int>("Blocked", 15),
};
for (var i = 0; i < totalColumn4.Length; i++)
{
worksheets.Cells[1, i + 16].Value = totalColumn4[i]; //populate header row
}
var m = 2;
//Fill the table
var startCell = worksheets.Cells[1, 16];
if (testRunStatusCountPercentage != null)
{
for (var i = 0; i < data.Count(); i++)
{
startCell.Offset(i + 1, 0).Value = data[i].Key;
startCell.Offset(i + 1, 1).Value = data[i].Value;
}
using (ExcelRange Rng = worksheets.Cells[1, 16, 5, data.Count + 13])
{
Rng.Style.Border.Top.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Left.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Right.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
}
}
//Add the chart to the sheet
var pieChart = worksheet.Drawings.AddChart("Chart1", eChartType.Pie);
pieChart.SetPosition(data.Count + 1, 0, 0, 0);
pieChart.Title.Text = "Test Case Excution Status";
pieChart.Title.Font.Bold = true;
pieChart.Title.Font.Size = 12;
//Set the data range
var series = pieChart.Series.Add(worksheets.Cells[2, 17, data.Count + 1, 17], worksheets.Cells[2, 16, data.Count + 1, 16]);
var pieSeries = (ExcelPieChartSerie)series;
pieSeries.Explosion = 5;
//Format the labels
pieSeries.DataLabel.Font.Bold = true;
pieSeries.DataLabel.ShowValue = true;
pieSeries.DataLabel.ShowPercent = true;
pieSeries.DataLabel.ShowLeaderLines = true;
pieSeries.DataLabel.Separator = ";";
pieSeries.DataLabel.Position = eLabelPosition.BestFit;
//Format the legend
pieChart.Legend.Add();
pieChart.Legend.Border.Width = 0;
pieChart.Legend.Font.Size = 12;
pieChart.Legend.Font.Bold = true;
pieChart.Legend.Position = eLegendPosition.Right;
// add a new worksheet to the empty workbook
using (var cells = worksheets.Cells[1, 1, 1, totalColumns.Length]) //(1,1) => (1,10)
{
cells.Style.Font.Bold = true;
}
using (var cells = worksheets.Cells[1, 7, 1, totalColumn.Length + 7]) //(1,1) => (1,10)
{
cells.Style.Font.Bold = true;
}
using (var cells = worksheets.Cells[1, 13, 1, totalColumn3.Length + 13]) //(1,1) => (1,10)
{
cells.Style.Font.Bold = true;
}
using (var cells = worksheets.Cells[1, 16, 1, totalColumn4.Length + 16]) //(1,1) => (1,10)
{
cells.Style.Font.Bold = true;
}
var records = data1.ToList();
var list = datas.ToList();
var funValue = funcitonData.ToList();
int totalRows = data1.Count + 1; //data including header row
int totalRowsList = datas.Count + 2;
var totalRowsForFuntion = funcitonData.Count + 1;
for (var i = 0; i < totalColumns.Length; i++)
{
worksheets.Cells[1, i + 1].Value = totalColumns[i]; //populate header row
}
for (var i = 0; i < totalColumn.Length; i++)
{
worksheets.Cells[1, i + 7].Value = totalColumn[i]; //populate header row
}
for (var i = 0; i < totalColumn3.Length; i++)
{
worksheets.Cells[1, i + 13].Value = totalColumn3[i]; //populate header row
}
//Add values
var j = 2; //to start data from second row after the header row.
var k = 2;
var l = 2;
if (data1 != null)
{
foreach (var item in records)
{
worksheets.Cells["A" + j].Value = cellNumb;
worksheets.Cells["B" + j].Value = item.TestCaseName;
worksheets.Cells["C" + j].Value = item.TestPlanName;
worksheets.Cells["D" + j].Value = item.Status;
j++;
cellNumb++;
}
using (ExcelRange Rng = worksheets.Cells[1, 1, totalRows, totalColumns.Length])
{
Rng.Style.Border.Top.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Left.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Right.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
}
}
if (datas != null)
{
foreach (var item in datas)
{
worksheets.Cells["G" + k].Value = item.TestPlanNameForCount;
worksheets.Cells["H" + k].Value = item.TotalPassedCount;
worksheets.Cells["I" + k].Value = item.TotalFailedCount;
worksheets.Cells["J" + k].Value = item.TotalPendingCount;
worksheets.Cells["K" + k].Value = item.TotalBlockCount;
k++;
}
worksheets.Cells["G" + k].Value = "Total";
worksheets.Cells["H" + k].Value = datas.Sum(x => x.TotalPassedCount);
worksheets.Cells["I" + k].Value = datas.Sum(x => x.TotalFailedCount);
worksheets.Cells["J" + k].Value = datas.Sum(x => x.TotalPendingCount);
worksheets.Cells["K" + k].Value = datas.Sum(x => x.TotalBlockCount);
using (ExcelRange Rng = worksheets.Cells[1, 7, totalRowsList, totalColumn.Length + 6])
{
Rng.Style.Border.Top.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Left.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Right.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
}
}
if (funcitonData != null)
{
foreach (var item in funValue)
{
worksheets.Cells["M" + l].Value = item.FunctionName;
worksheets.Cells["N" + l].Value = item.TotalCountTestCaseByTestRunId;
l++;
}
using (ExcelRange Rng = worksheets.Cells[1, 13, totalRowsForFuntion, totalColumn3.Length + 12])
{
Rng.Style.Border.Top.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Left.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Right.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
}
}
worksheets.Cells.AutoFitColumns();
result = package.GetAsByteArray();
return result;
}
}
catch (Exception ex)
{
throw new Exception($"Download failed : {ex.Message}");
}
}
}
var redarChart = worksheet.Drawings.AddRadarChart("RadarChart",
eRadarChartType.RadarMarkers);
redarChart.SetPosition(42, 0, 0, 0);
redarChart.SetSize(700, 300);
redarChart.Title.Text = "Function Map";
redarChart.Title.Font.Bold = true;
redarChart.Title.Font.Size = 12;
var serie = redarChart.Series.Add(worksheets.Cells[2, 14, funValue.Count + 1, 14], worksheets.Cells[2, 13, funValue.Count + 1, 13]);
serie.HeaderAddress = new ExcelAddress("'sheet'!N1");
redarChart.StyleManager.SetChartStyle(ePresetChartStyleMultiSeries.RadarChartStyle4);
redarChart.Fill.Color = System.Drawing.Color.Black;
redarChart.Legend.Position = eLegendPosition.TopRight;
//If you want to apply custom styling do that after setting the chart style so its not overwritten.
redarChart.Legend.Effect.SetPresetShadow(ePresetExcelShadowType.OuterTopLeft);
var radarSeries = (ExcelRadarChartSerie)serie;
radarSeries.Marker.Size = 5;
According to this case's answer by Alexey, we can utilize different renderers with customized RootLayoutArea to achieve such layout behavior as below.
Here is the code:
public void ManipulatePdf(String dest)
{
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc, PageSize.A4);
doc.SetMargins(36, 36, 36, 36);
Paragraph p = new Paragraph();
p.SetBorder(new SolidBorder(0.5f));
for (int i = 1; i <= 500; i++)
{
p.Add(new Text(i + " "));
}
doc.Add(p);
RootLayoutArea endOfFullWidthContentArea = (RootLayoutArea)doc.GetRenderer().GetCurrentArea();
ExtendedDocumentRenderer renderer1 = new ExtendedDocumentRenderer(doc,
new RootLayoutArea(endOfFullWidthContentArea.GetPageNumber(), endOfFullWidthContentArea.GetBBox().Clone().SetWidth(200)));
doc.SetRightMargin(doc.GetRightMargin() + doc.GetPageEffectiveArea(PageSize.A4).GetWidth() - 200);
doc.SetRenderer(renderer1);
//The paragraph drawn in the left
Paragraph p1 = new Paragraph();
p1.SetBorder(new SolidBorder(0.5f));
for (int i = 1; i <= 500; i++)
{
p1.Add(new Text(i + " "));
}
doc.Add(p1);
ExtendedDocumentRenderer renderer2 = new ExtendedDocumentRenderer(doc,
new RootLayoutArea(endOfFullWidthContentArea.GetPageNumber(),
endOfFullWidthContentArea.GetBBox().Clone().MoveRight(200 + 20)
.SetWidth(endOfFullWidthContentArea.GetBBox().GetWidth() - 200 - 20)));
doc.SetRightMargin(36);
doc.SetLeftMargin(200 + 36 + 20);
doc.SetRenderer(renderer2);
Paragraph p2 = new Paragraph();
for (int i = 1; i <= 1000; i++)
{
p2.Add(new Text(i + " "));
}
doc.Add(p2);
//Compute which free area is lower in the document
RootLayoutArea areaColumn1 = (RootLayoutArea)renderer1.GetCurrentArea();
RootLayoutArea areaColumn2 = (RootLayoutArea)renderer2.GetCurrentArea();
RootLayoutArea downArea =
areaColumn1.GetPageNumber() > areaColumn2.GetPageNumber() ? areaColumn1 :
(areaColumn1.GetPageNumber() < areaColumn2.GetPageNumber() ? areaColumn2 :
(areaColumn1.GetBBox().GetTop() < areaColumn2.GetBBox().GetTop() ? areaColumn1 : areaColumn2));
doc.SetMargins(36, 36, 36, 36);
DocumentRenderer renderer3 = new ExtendedDocumentRenderer(doc,
new RootLayoutArea(downArea.GetPageNumber(), downArea.GetBBox().Clone().SetX(36).SetWidth(doc.GetPageEffectiveArea(PageSize.A4).GetWidth())));
doc.SetRenderer(renderer3);
Paragraph p3 = new Paragraph();
for (int i = 1; i <= 1000; i++)
{
p3.Add(new Text(i + " "));
}
doc.Add(p3);
doc.Close();
}
private class ExtendedDocumentRenderer : DocumentRenderer
{
public ExtendedDocumentRenderer(Document document, RootLayoutArea currentArea) : base(document)
{
this.currentArea = new RootLayoutArea(currentArea.GetPageNumber(), currentArea.GetBBox().Clone());
this.currentPageNumber = this.currentArea.GetPageNumber();
}
}
We can see that the Paragraph 1 in the left column spans two pages, and the Paragraph 2 spans three pages, under this scenario the code runs well.
But if we add more contents to Paragraph 1 and make it span 3 pages as following:
//The paragraph drawn in the left has more contents
Paragraph p1 = new Paragraph();
p1.SetBorder(new SolidBorder(0.5f));
for (int i = 1; i <= 800; i++)
{
p1.Add(new Text(i + " "));
}
doc.Add(p1);
When the Paragraph 2 is rendering, it throws the exception of "Cannot draw elements on already flushed pages". How to solve this problem? Thank you!
If you elements can span multiple pages then you need to apply immediateFlush=false setting of the DocumentRenderer which goes to its constructor.
You will need to modify your ExtendedDocumentRenderer custom implementation in the following way:
private class ExtendedDocumentRenderer : DocumentRenderer
{
public ExtendedDocumentRenderer(Document document, RootLayoutArea currentArea) : base(document, false)
{
this.currentArea = new RootLayoutArea(currentArea.GetPageNumber(), currentArea.GetBBox().Clone());
this.currentPageNumber = this.currentArea.GetPageNumber();
}
}
And then you will need to call Document#Flush whenever you are done with another document renderer. Essentially in your code sample that call needs to be done after adding each new element. Here is the full code:
Document doc = new Document(pdfDocument, PageSize.A4);
doc.SetMargins(36, 36, 36, 36);
Paragraph p = new Paragraph();
p.SetBorder(new SolidBorder(0.5f));
for (int i = 1; i <= 500; i++)
{
p.Add(new Text(i + " "));
}
doc.Add(p);
RootLayoutArea endOfFullWidthContentArea = (RootLayoutArea)doc.GetRenderer().GetCurrentArea();
ExtendedDocumentRenderer renderer1 = new ExtendedDocumentRenderer(doc,
new RootLayoutArea(endOfFullWidthContentArea.GetPageNumber(), endOfFullWidthContentArea.GetBBox().Clone().SetWidth(200)));
doc.SetRightMargin(doc.GetRightMargin() + doc.GetPageEffectiveArea(PageSize.A4).GetWidth() - 200);
doc.SetRenderer(renderer1);
//The paragraph drawn in the left
Paragraph p1 = new Paragraph();
p1.SetBorder(new SolidBorder(0.5f));
for (int i = 1; i <= 800; i++)
{
p1.Add(new Text(i + " "));
}
doc.Add(p1);
doc.Flush();
ExtendedDocumentRenderer renderer2 = new ExtendedDocumentRenderer(doc,
new RootLayoutArea(endOfFullWidthContentArea.GetPageNumber(),
endOfFullWidthContentArea.GetBBox().Clone().MoveRight(200 + 20)
.SetWidth(endOfFullWidthContentArea.GetBBox().GetWidth() - 200 - 20)));
doc.SetRightMargin(36);
doc.SetLeftMargin(200 + 36 + 20);
doc.SetRenderer(renderer2);
Paragraph p2 = new Paragraph();
for (int i = 1; i <= 1000; i++)
{
p2.Add(new Text(i + " "));
}
doc.Add(p2);
doc.Flush();
//Compute which free area is lower in the document
RootLayoutArea areaColumn1 = (RootLayoutArea)renderer1.GetCurrentArea();
RootLayoutArea areaColumn2 = (RootLayoutArea)renderer2.GetCurrentArea();
RootLayoutArea downArea =
areaColumn1.GetPageNumber() > areaColumn2.GetPageNumber() ? areaColumn1 :
(areaColumn1.GetPageNumber() < areaColumn2.GetPageNumber() ? areaColumn2 :
(areaColumn1.GetBBox().GetTop() < areaColumn2.GetBBox().GetTop() ? areaColumn1 : areaColumn2));
doc.SetMargins(36, 36, 36, 36);
DocumentRenderer renderer3 = new ExtendedDocumentRenderer(doc,
new RootLayoutArea(downArea.GetPageNumber(), downArea.GetBBox().Clone().SetX(36).SetWidth(doc.GetPageEffectiveArea(PageSize.A4).GetWidth())));
doc.SetRenderer(renderer3);
Paragraph p3 = new Paragraph();
for (int i = 1; i <= 1000; i++)
{
p3.Add(new Text(i + " "));
}
doc.Add(p3);
doc.Flush();
doc.Close();
After stepping on the pit before, you can try calling three parameter constructors and setting immediateflush to false.
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
// setting immediateflush to false
Document doc = new Document(pdfDoc, PageSize.A4, false);
I am working on digital signature in pdf. I am able to add a single signature in PDF, But when I am trying to add same signature at multiple place I getting issue invalid signature.
I am using below code to digitally sign the single PDF file at multiple location but sign appear at one place .
At the other place its not showing.(invalid signature).
I am using below is the code
string dttime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
PdfReader pdfReader = null;
PdfStamper stamper = null;
try
{
pdfReader = new PdfReader(In_File_Name);
stamper = PdfStamper.CreateSignature(pdfReader, new FileStream(New_File_Name, FileMode.Create, FileAccess.Write), '\0', null, true);
//Annotation code for multiple signatures
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
appearance.Reason = "";// ConfigurationManager.AppSettings["APPEARANCE_REASON"].ToString();
appearance.Location = "";// ConfigurationManager.AppSettings["APPEARANCE_LOCATION"].ToString();
appearance.SignDate = DateTime.Now.AddMinutes(3);
appearance.Image = null;
appearance.Acro6Layers = true;
//appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(540, 290, 430, 320), 1, null);
string Page_Attrb = "1(540, 290, 430, 320);2(540, 290, 430, 320)"; //In_Page_Attrb;
String[] Pageattr = Page_Attrb.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
String[] Pageattr1 = Pageattr[0].Split(new[] { "(", ")" }, StringSplitOptions.RemoveEmptyEntries);
int PageNo = int.Parse(Pageattr1[0]);//1
float lx = 0, ly = 0, hx = 0, hy = 0; string[] Attr = Pageattr1[1].Split(',');
if (Attr.Length > 3)
{
lx = float.Parse(Attr[0]);
ly = float.Parse(Attr[1]);
hx = float.Parse(Attr[2]);
hy = float.Parse(Attr[3]);
}
int csize = 8192;
PdfContentByte canvas = stamper.GetOverContent(1);
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.COURIER_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);
iTextSharp.text.Font f = new iTextSharp.text.Font(bfTimes, iTextSharp.text.Font.BOLD, 15);
canvas.SetFontAndSize(bfTimes, 6);
canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
for (int page = 0; page <= 1; page++)
{
String[] Pageattr2 = Pageattr[page].Split(new[] { "(", ")" }, StringSplitOptions.RemoveEmptyEntries);
int PageNo1 = int.Parse(Pageattr2[0]);
float lx1 = 0, ly1 = 0, hx1 = 0, hy1 = 0;
string[] Attr1 = Pageattr2[1].Split(',');
if (Attr1.Length > 3)
{
lx1 = float.Parse(Attr1[0]);
ly1 = float.Parse(Attr1[1]);
hx1 = float.Parse(Attr1[2]);
hy1 = float.Parse(Attr1[3]);
}
iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(lx1, ly1, hx1, hy1);
PdfAnnotation annotation = PdfAnnotation.CreateFreeText(stamper.Writer, rect, appearance.Layer2Text, canvas);
PdfAppearance tp = PdfAppearance.CreateAppearance(stamper.Writer, 444, 555);
annotation.Flags = PdfAnnotation.FLAGS_READONLY | PdfAnnotation.FLAGS_LOCKED | PdfAnnotation.FLAGS_PRINT;
PdfDate pdfdate = new PdfDate();
annotation.Title = "dsds";
annotation.Border = new PdfBorderArray(0, 0, 0, new PdfDashPattern());
annotation.Put(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
stamper.AddAnnotation(annotation, PageNo1);
}
Dictionary<PdfName, int> exclusionSizes = new Dictionary<PdfName, int>();
exclusionSizes[PdfName.CONTENTS] = csize * 2 + 2;
appearance.CryptoDictionary = (PdfDictionary)new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED)
{
Reason = appearance.Reason,
Location = appearance.Location,
Contact = appearance.Contact,
Date = new PdfDate(appearance.SignDate)
};
appearance.PreClose(exclusionSizes);
Stream s = appearance.GetRangeStream();
//byte[] by = GetStreamAsByteArray(s);
//string hashdocument = GenerateFilehash256Hex(by);
string hashdocument = genaratePDFHash(s);
string eSignReq = Esigndoc(In_OTP, In_Aadhaar_No, hashdocument);
string res = postXMLData(ConfigurationManager.AppSettings["eSignURL"].ToString(), eSignReq);
//Fetch the Esign XML response..
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(res);
XmlNode xmlNode = xmlDocument.SelectSingleNode("EsignResp");
if (xmlNode.Attributes["errCode"] != null && xmlNode.Attributes["errCode"].Value != "NA")
{
}
else
{
byte[] numArray3 = this.SignDocument(res);
byte[] bytes1 = new byte[csize];
Array.Copy((Array)numArray3, 0, (Array)bytes1, 0, numArray3.Length);
PdfDictionary update = new PdfDictionary();
update.Put(PdfName.CONTENTS, (PdfObject)new PdfString(bytes1).SetHexWriting(true));
appearance.Close(update);
//progressBar1.Value = 100;
// MessageBox.Show("eSign Operation completed successfully.");
//fileStream1.Close();
//fileStream.Close();
//lblMsg.Text = "File Signed Successfully";
//For Multiple eSign Doc Start Here ...............
//if (Pageattr.Length > 1)
//{
// for (int k = 1; k <= Pageattr.Length - 1; k++)
// {
// String[] Pageattr1 = Pageattr[k].Split(new[] { "(", ")" }, StringSplitOptions.RemoveEmptyEntries);
// PageNo = int.Parse(Pageattr1[0]);
// lx = 0; ly = 0; hx = 0; hy = 0;
// string[] Attr = Pageattr1[1].Split(',');
// if (Attr.Length > 3)
// lx = float.Parse(Attr[0]);
// ly = float.Parse(Attr[1]);
// hx = float.Parse(Attr[2]);
// hy = float.Parse(Attr[3]);
// }
// New_File_Name = PdfeSign(New_File_Name, PageNo, res, lx, ly, hx, hy, strLayer2Text);
// }
//}
//For Multiple eSign Doc End Here ...............
}
}
catch (Exception ex)
{
stamper.Close();
pdfReader.Close();
}
finally
{
stamper.Close();
pdfReader.Close();
}
I am facing issue while generating pdf from Windows form using iTextSharp dll. I am populating more than 70 records at a time in a dataset and I am binding same to new table(pdfptable) by looping. But it says Object reference not set to instance of object. when I reduced number of rows to 68 it works fine. After analysis I found that table is not able to split along the multiple pages.
I am using following piece of code. Please help
float[] widths1 = new float[] { 1f, 2f,1f,1f,1f,1f,1f};
PdfPTable grd = new PdfPTable(GrdAnoSecList.Columns.Count);
grd.SetWidths(widths1);
for (int i = 0; i < GrdAnoSecList.Columns.Count; i++)
{
PdfPCell ph;
if (Convert.ToString(GrdAnoSecList.Columns[i].HeaderText) == "Job Name")
{
ph = new PdfPCell(new Phrase(GrdAnoSecList.Columns[i].HeaderText, grdfontHdr));
ph.BackgroundColor = new iTextSharp.text.Color(240, 240, 240);
ph.BorderWidthTop = 0;
ph.BorderWidthRight = 0;
ph.HorizontalAlignment = 1;
}
else
{
ph= new PdfPCell(new Phrase(GrdAnoSecList.Columns[i].HeaderText, grdfontHdr));
ph.BackgroundColor = new iTextSharp.text.Color(240, 240, 240);
ph.BorderWidthTop = 0;
ph.BorderWidthRight = 0;
ph.HorizontalAlignment = 1;
//ph.Width = 100f;
}
grd.AddCell(ph);
}
int ct = 0;
foreach (DataGridViewRow row in GrdAnoSecList.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
ct++;
PdfPCell ph2;
if (Convert.ToString(cell.Value) == "Total")
{
ph2 = new PdfPCell(new Phrase(cell.Value.ToString(), grdfontHdr));
}
else
{
ph2 = new PdfPCell(new Phrase(cell.Value.ToString(), myfont));
}
if (cell.ValueType == typeof(decimal) || cell.ValueType == typeof(Int32))
{
ph2.HorizontalAlignment = 2;
}
else if (cell.ColumnIndex == 1 && Convert.ToString(cell.Value) != "Total")
{
ph2.HorizontalAlignment = 0;
}
else
{
ph2.HorizontalAlignment = 1;
}
grd.AddCell(ph2);
}
}
PdfPCell cellAmountText1 = new PdfPCell(new PdfPTable(grd));
cellAmountText1.Colspan = 6;
table.AddCell(cellAmountText1);
I've added an header and a footer on my document by PdfPageEventHelper.
The document has several "large" tables populated at runtime.
I've tried to add those tables simply by "documen.Add(table)", but my header and my footer results overwritten.
I've already tried both methods to add the tables (WriteSelectedRows and document.Add(myPdfPtable).
Here is the code of the PageEventHelper for Head:
public override void OnEndPage(PdfWriter writer, Document doc)
{
Phrase phrase = null;
PdfPCell cell = null;
PdfPTable maintable = new PdfPTable(2);
maintable.TotalWidth = 500f;
maintable.LockedWidth = true;
maintable.SetWidths(new float[] { 50f, 400f });
#region checklogo
if (IsLogo!=0)
{
// code for display head like logo, etc
}
#endregion CheckSchoolNameandAddress
maintable.WriteSelectedRows(0, -1, 50, 835, writer.DirectContent);
Color color = new Color(System.Drawing.ColorTranslator.FromHtml("#A9A9A9"));
DrawLine(writer, 25f, 780f, doc.PageSize.Width - 25f, 780f,color);
DrawLine(writer, 25f, 780f, doc.PageSize.Width - 25f, 780f, color);
}
Here is the code of the PageEventHelper for footer:
public override void OnEndPage(PdfWriter writer, Document doc)
{
Phrase phrase = null;
PdfPCell cell = null;
PdfPCell cell1 = null;
PdfPCell cell2 = null;
int pageN = writer.PageNumber;
String text = "Page " + pageN;
PdfPTable foootertable = new PdfPTable(3);
foootertable.TotalWidth = 500f;
foootertable.LockedWidth = true;
foootertable.SetWidths(new float[] { 50f, 60f, 50f });
#region checkprintedbyReportNamePageNo
if (Isfooter != 0)
{
// code for footer like pageno, etc
}
#endregion CheckprintedbyReportNamePageNo
foootertable.WriteSelectedRows(0, -1, 30,30, writer.DirectContent);
color = new Color(System.Drawing.ColorTranslator.FromHtml("#A9A9A9"));
DrawLine(writer, 25f, 32f, doc.PageSize.Width - 25f, 32f, color);
DrawLine(writer, 25f, 32f, doc.PageSize.Width - 25f, 32f, color);
}
Table code which display on all page like reportdiaplay
public ActionResult DetailReportPDF(int TempId, int ReportModuleId, string BoardStageId, string ShiftId, string ClassDivisionId, string Subjects)
{
try
{
var BaseUrl = string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));
IBoard board = Session["SchoolAdmin"] as IBoard;
if (board != null)
{
int yearid = 0; IYears currentyear = YearsDomain.GetCurrentYears(board.Board_Id); if (currentyear != null) yearid = currentyear.Year_Id;
string SchoolAddress = "";
string SchoolName = "";
string SchoolLogo = "";
SchoolName = board.Board_Name != null ? board.Board_Name.ToUpper() : "";
SchoolAddress = (board.Board_Address1 != null ? board.Board_Address1.ToUpper() + "," : "") + (board.Board_City != null ? board.Board_City + "," : "") + (board.Board_State != null ? board.Board_State + ", " : "") + (board.Board_Country != null ? board.Board_Country + " - " : "") + (board.Board_Pincode != null ? board.Board_Pincode + "." : "");
SchoolLogo = Session["SchoolLogo"] != null ? Session["SchoolLogo"].ToString() : "";
string filename = "";
DateTime now = DateTime.Now;
Document document = new Document(PageSize.A4);
document.SetMargins(88, 88, 80, 10f);
iTextSharp.text.Font NormalFont = FontFactory.GetFont("Arial Unicode MS,Arial", 12, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
iTextSharp.text.Font VNormalFont = FontFactory.GetFont("Arial Unicode MS,Arial", 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
iTextSharp.text.Font LARGFont = FontFactory.GetFont("Arial Unicode MS,Arial", 14, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
Phrase phrase = null;
PdfPCell cell = null;
PdfPTable maintable = null;
PdfPTable table = null;
PdfPTable secondTable = null;
PdfPCell TableCell = new PdfPCell();
PdfPCell secondTableCell = new PdfPCell();
secondTableCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
iTextSharp.text.Color color = null;
document.Open();
List<ReportSetLayout> lst = new List<ReportSetLayout>();
IReportTemplate RTD = ReportTemplateDomain.GetReportTemplateFromId(TempId);
string Newstr = "";
int IsLogo = 0;
string LogoSize="";
string LogoPosition="";
int IsSchoolName=0;
int IsSchoolAddress=0;
string SchoolNameSize = "";
string SchoolNamePosition = "";
string SchoolAddressSize = "";
string SchoolAddressPosition = "";
int Isfooter = 0;
int IsPrintedBy =0;
int IsReportName =0;
int PageNo =0;
string ShowPrintedBy="";
string ShowReportName ="";
string ShowPageNo = "";
IReportModule ReportModule = ReportModuleDomain.GetReportModulesFromId(ReportModuleId);
IBoardUserRights boarduserrights = BoardUserRightsDomain.GetBoardUserRights(board.Board_Id, "Reports", Session["BoardUserName"].ToString());
IBoardUser BU = BoardUserDomain.getBoardUserById(Convert.ToInt32(boarduserrights.Board_User_Id));
if (RTD != null)
{
#region forLogo
// code for get value for header logo
#endregion forLogo
#region forschoolName&address
// code for get value for header address
#endregion forschoolName&address
#region forprintedbyReportNamePageNo
// code for get value for footer
#endregion forprintedbyReportNamePageNo
}
writer.PageEvent = new Header() { SName = SchoolName, SAddress = SchoolAddress, SLogo = SchoolLogo, IsLogo=IsLogo, LogoSize = LogoSize, LogoPosition = LogoPosition ,IsSchoolName=IsSchoolName , IsSchoolAddress=IsSchoolAddress, SchoolNameSize=SchoolNameSize ,SchoolNamePosition=SchoolNamePosition,SchoolAddressSize=SchoolAddressSize,SchoolAddressPosition=SchoolAddressPosition};
// writer.PageEvent = new Header();
writer.PageEvent = new Footer(){ Isfooter=Isfooter,IsPrintedBy=IsPrintedBy,IsReportName=IsReportName,IsPageNo=PageNo,PrintedBy=ShowPrintedBy,ReportName=ShowReportName};
#region ReportBind
string Shortby = "";
List<string> lstformat = new List<string>();
List<string> lstWrap = new List<string>();
List<ReportColumnDetails> lstReportColumn = new List<ReportColumnDetails>();
lstReportColumn = ReportColumnDomain.GetReportColumnsFromReportModule(ReportModuleId);
List<IReportTemplateColumn> lstRptempcol = new List<IReportTemplateColumn>();
lstRptempcol = ReportTemplateColumnDomain.GetAllReportTemplateColumnbyID(TempId);
List<int> colindexid = new List<int>();
List<int> ColWidth = new List<int>();
foreach (var col in lstRptempcol)
{
ColWidth.Add(Convert.ToInt32(col.ColumnWidth));
colindexid.Add(Convert.ToInt32(col.Column_Index_Id));
}
foreach (var shortName in lstRptempcol)
{
if (shortName.Sortby == Convert.ToByte(1))
{
Shortby = lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault();
}
if (lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault().Contains("Date"))
{
lstformat.Add(lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault() + "_" + shortName.Format);
}
if (lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault().Contains("Gender"))
{
lstformat.Add(lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault() + "_" + shortName.Format);
}
if (shortName.Wrap == Convert.ToByte(1))
{
lstWrap.Add(lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault());
}
}
//string[] cols = Columns.TrimEnd(',').Split(',');
//string[] colsindex = ColumnsIndex.TrimEnd(',').Split(',');
string str = "";
string str1 = "";
// DataTable dt = new DataTable("ReportTable");
if (ReportModule != null)
{
if (ReportModule.Report_Module_Name == "Teacher")
{
var items = new List<int>(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 });
string H1 = "Sr.No", H2 = "Teacher Name", H3 = "Contact No", H4 = "Address", H5 = "Gender", H6 = "Marital Status", H7 = "Join Date", H8 = "Leave Date", H9 = "Physically Challenged ", H10 = "Photo", H11 = "EmailId", H12 = "EmployeeId", H13 = "Group", H14 = "Religion", H15 = "Cast Category", H16 = "Cast", H17 = "Designation", H18 = "Service Category", H19 = "Anniversary Date", H20 = "Education";
#region trimdata
List<int> lstBoardStageId = new List<int>();
if (BoardStageId != "" || BoardStageId != null)
{
string[] BSId = BoardStageId.TrimEnd(',').Split(',');
for (int i = 0; i <= BSId.Count() - 1; i++)
{
if (BSId[i] != "")
lstBoardStageId.Add(Convert.ToInt32(BSId[i]));
}
}
List<int> lstShiftId = new List<int>();
if (ShiftId != "" || ShiftId != null)
{
string[] ShiftIDs = ShiftId.TrimEnd(',').Split(',');
for (int i = 0; i <= ShiftIDs.Count() - 1; i++)
{
if (ShiftIDs[i] != "")
lstShiftId.Add(Convert.ToInt32(ShiftIDs[i]));
}
}
List<int> lstClassDivisionId = new List<int>();
if (ClassDivisionId != "" || ClassDivisionId != null)
{
string[] classDiv = ClassDivisionId.TrimEnd(',').Split(',');
for (int i = 0; i <= classDiv.Count() - 1; i++)
{
if (classDiv[i] != "")
lstClassDivisionId.Add(Convert.ToInt32(classDiv[i]));
}
}
List<int> lstSubjects = new List<int>();
//if (Subjects != "" || Subjects != null)
//{
string[] subjs = Subjects.TrimEnd(',').Split(',');
for (int i = 0; i <= subjs.Count() - 1; i++)
{
if (subjs[i] != "")
lstSubjects.Add(Convert.ToInt32(subjs[i]));
}
//}
#endregion trimdata
List<ReportTecaherDetails> resultTeacher = new List<ReportTecaherDetails>();
resultTeacher = TeacherDomain.GetReportTeacher1(board.Board_Id, lstBoardStageId, lstShiftId, lstSubjects, lstClassDivisionId, Shortby, lstformat, yearid);
float[] widthArry = new float[20];
float widthCount = 0;
for (int i = 0; i < ColWidth.Count; i++)
{
widthArry[i] = ColWidth[i];
widthCount += ColWidth[i];
}
widthArry = widthArry.Where(x => x != 0).ToArray();
table = new PdfPTable(widthArry);
table.TotalWidth = 550f;
table.LockedWidth = true;
table.SetWidths(widthArry);
#region CheckHeaderText
foreach (var HeaderText in lstRptempcol)
{
//code for headerText
}
#endregion CheckHeaderText
int Srno = 1;
int count = 0;
for (int a = 0; a < colindexid.Count; a = a + 1)
{
if (colindexid.Contains(Convert.ToInt32(a.ToString())))
{
#region addcolumnHeadeName
if (a.ToString() == Convert.ToString(0))
{
// dt.Columns.Add(new DataColumn(H1, typeof(string)));
phrase = new Phrase();
phrase.Add(new Chunk(H1, FontFactory.GetFont("Arial Unicode MS,Arial", 8, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)));
cell = PhraseCell(phrase, PdfPCell.ALIGN_CENTER);
cell.BorderColor = new iTextSharp.text.Color(229, 229, 229);
cell.FixedHeight = 10f;
table.AddCell(cell);
}
else if (a.ToString() == Convert.ToString(1))
{
// dt.Columns.Add(new DataColumn(H1, typeof(string)));
phrase = new Phrase();
phrase.Add(new Chunk(H2, FontFactory.GetFont("Arial Unicode MS,Arial", 8, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)));
cell = PhraseCell(phrase, PdfPCell.ALIGN_CENTER);
cell.BorderColor = new iTextSharp.text.Color(229, 229, 229);
cell.FixedHeight = 10f;
table.AddCell(cell);
}
// .... else if{} same as above
#endregion addcolumnHeadeName
}
}
document.Add(table);
secondTable = new PdfPTable(widthArry);
secondTable.TotalWidth = 550f;
secondTable.LockedWidth = true;
secondTable.SetWidths(widthArry);
foreach (var item in resultTeacher)
{
#region rowadd
if (colindexid.Contains(Convert.ToInt32(0)))
{
phrase = new Phrase();
phrase.Add(new Chunk(Convert.ToString(Srno), FontFactory.GetFont("Arial Unicode MS,Arial", 8, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)));
secondTableCell = PhraseCell(phrase, PdfPCell.ALIGN_CENTER);
secondTableCell.BorderColor = new iTextSharp.text.Color(229, 229, 229);
secondTableCell.FixedHeight = 50f;
secondTable.AddCell(secondTableCell);
}
else
{
}
// .... if{} same as above
#endregion rowadd
Srno++;
}
document.Add(secondTable);
}
}
#endregion ReportBind
filename = filename + now.Hour.ToString("00") + now.Minute.ToString("00") + now.Second.ToString("00") + now.Millisecond.ToString() + now.DayOfYear.ToString("000") + now.Day.ToString("00") + now.Month.ToString("00") + now.Year.ToString("0000") + ".pdf";
document.Close();
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
Response.Close();
}
return View();
}
else
{
return Redirect(BaseUrl);
}
}
catch (Exception ex)
{
throw ex;
}
}
You Can try
Image.ScaleToFitLineWhenOverflow = false;
Refer SO Answer # Set Pagination in Itextsharp Table