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();
}
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;
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); }
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
I want to read binary file and insert strings to listView and each string to one line
I have made a code but i don`t know why the code is not working
String input = string.Empty;
OpenFileDialog openFileDialog3 = new OpenFileDialog();
openFileDialog3.Filter = "bin files (*.bin)|*.bin";
if (openFileDialog3.ShowDialog() == DialogResult.OK)
if (openFileDialog3.FileName == String.Empty)
return;
BinaryReader br = new BinaryReader(File.OpenRead(openFileDialog3.FileName), Encoding.Unicode);
br.BaseStream.Position = 0x8;
int Pntrnum = br.ReadInt16();
menuItem11.Visible = true;
menuItem11.Text = Pntrnum.ToString();
List<int> offsets = new List<int>();
br.BaseStream.Position = 0x10;
for (int i = 0; i < Pntrnum; i++)
{
offsets.Add(br.ReadInt32());
}
Dictionary<int, string> values = new Dictionary<int, string>();
for (int i = 0; i < offsets.Count; i++)
{
int currentOffset = offsets[i];
int nextOffset = (i + 1) < offsets.Count ? offsets[i + 1] : (int)br.BaseStream.Length;
int stringLength = (nextOffset - currentOffset - 1) / 2;
br.BaseStream.Position = currentOffset;
var chars = br.ReadChars(stringLength);
values.Add(currentOffset, new String(chars));
}
foreach (int offset in offsets)
{
listView1.Items.Add(offset.ToString("X")).SubItems.Add(values[offset]);
}
br.Close();
br = null;
Is there an other code or there is mistakes
Does any know how to merge two pdf (one of them have cropbox and the other don't have, and they have different page size) using iText?
here is the code, that I use for PDF merge:
public bool MergeFiles(string destinationFile, string[] sourceFiles)
{
bool bSucess = true;
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();
}
}
string sPDFPath = Server.MapPath(#"pdftemp/");
Scripting.FileSystemObject fso = new Scripting.FileSystemObjectClass();
try
{
int f = 0;
PdfReader reader = new PdfReader(sSrcFile[f]);
int n = reader.NumberOfPages;
Console.WriteLine("There are " + n + " pages in the original file.");
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
PdfDate st = new PdfDate(DateTime.Today);
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);
}
Console.WriteLine("Processed page " + i);
}
f++;
if (f < sSrcFile.Length)
{
reader = new PdfReader(sSrcFile[f]);
n = reader.NumberOfPages;
Console.WriteLine("There are " + n + " pages in the original file.");
}
}
document.Close();
}
catch (Exception e)
{
bSucess = false;
}
return bSucess;
}
But it seems not handling cropbox difference between pages (content mis-position on page that have cropbox) , anyone have a better code to put the content in the right position?
You're doing it the hard way:
PdfReader reader = null;
PdfCopy copier = new PdfCopy(outputStream);
String paths[] = ...;
for (String path : paths) {
reader = new PdfReader(path);
for (int pageNum = 1; pageNum <= reader.getNumberOfPages(); ++pageNum) {
copier.addPage(copier.getImportedPage(reader, pageNum) );
}
}
That'll copy page annotations as well as page contents. Note that it Will Not copy document-level stuff those annotations might need to function properly (document script for a form fields' validation entry point for example).
And it'll copy the original page verbatim, regardless of various page box sizes or rotation.