Why did not generate PDF report after Publish - c#

I am generating different type report about employee on my website. after publishing its could not generate clearly. if any case it not generate result a message will generate it have no value as result. it did not get after publishing. on local server its working fine. i give my code below. i don't know why this not working fine. how will set a path for all accessing (Client) machine.
my code is here.
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false); //base font
Font font = new Font(bfTimes, 8, Font.BOLD); //Header File
Font font1 = FontFactory.GetFont(FontFactory.TIMES, 7); //DateBase value
Font font2 = FontFactory.GetFont(FontFactory.TIMES, 7); //sub headings
DataTable dt = new DataTable();
DataSet ds = new DataSet();
DataTable dt2 = new DataTable();
DataSet ds2 = new DataSet();
Document doc = new Document(new Rectangle(570f, 600f));
// string path = Server.MapPath("~/Computer/F/reports/");
//PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(#"F:\\reports\\" + "Employeebloodreportsectionwise.pdf", FileMode.Create));
//PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(FilePath, FileMode.Create));
PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
PdfPCell cell = null;
Phrase phrase = null;
PdfPTable table = new PdfPTable(8);
//table.SetTotalWidth(new float[] { 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f ,40f});//column width
table.SetTotalWidth(new float[] {
40f, 100f, 120f, 100f, 100f, 70f, 100f, 75f
}); //column width
PdfPTable table2 = new PdfPTable(2);
table2.TotalWidth = 520f;
table2.LockedWidth = true;
table2.HorizontalAlignment = 0;
table.TotalWidth = 520f; //table size
//fix the absolute width of the table
table.LockedWidth = true;
//relative col widths in proportions - 1/3 and 2/3
//table.SetWidths(widths);
table.HorizontalAlignment = 0;
//leave a gap before and after the table
table.SpacingBefore = 10f; //both are used to mention the space from heading
table.SpacingAfter = 20f;
string imageURL = Server.MapPath(".") + "/companylogo.png";
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);
//Resize image depend upon your need
jpg.ScaleToFit(110f, 100f);
//Give space before image
jpg.SpacingBefore = 10f;
//Give some space after the image
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.ALIGN_LEFT;
doc.Add(jpg);
qry = "select CompanyName,Phone1,Address1,State,District from Company";
dr = conn1.query(qry);
if (dr.Read()) {
string company1 = dr[0].ToString();
Font times = new Font(bfTimes, 9, Font.BOLD, BaseColor.RED);
Paragraph p = (new Paragraph("" + company1 + "", times));
p.Alignment = Element.ALIGN_CENTER;
doc.Add(p);
string Address = dr[2].ToString();
string dist = dr[4].ToString();
string state1 = dr[3].ToString();
Font times1 = new Font(bfTimes, 7);
Paragraph p1 = (new Paragraph("Address:" + Address + "," + state1 + "," + dist + "", times1));
p1.Alignment = Element.ALIGN_CENTER;
doc.Add(p1);
string phone = dr[1].ToString();
//Font times1 = new Font(bfTimes, 10);
Paragraph p7 = (new Paragraph("PH:" + phone + "", times1));
p7.Alignment = Element.ALIGN_CENTER;
doc.Add(p7);
Font times2 = new Font(bfTimes, 8, Font.BOLD);
Paragraph p2 = (new Paragraph(" Department Wise Gender Report", times2));
p2.Alignment = Element.ALIGN_CENTER;
doc.Add(p2);
Paragraph p8 = (new Paragraph("Department:" + dddept.SelectedItem.Text + "", times1));
p8.Alignment = Element.ALIGN_CENTER;
doc.Add(p8);
cell = new PdfPCell(new Phrase("Sl.no", font));
cell.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cell);
cell = new PdfPCell(new Phrase("Emp Code", font));
cell.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cell);
cell = new PdfPCell(new Phrase("Name", font));
cell.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cell);
//cell = new PdfPCell(new Phrase("Department", font));
//cell.HorizontalAlignment = Element.ALIGN_LEFT;
//table.AddCell(cell);
cell = new PdfPCell(new Phrase("Section", font));
cell.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cell);
cell = new PdfPCell(new Phrase("Designation", font));
cell.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cell);
cell = new PdfPCell(new Phrase("Dob", font));
cell.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cell);
cell = new PdfPCell(new Phrase("Place", font));
cell.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cell);
cell = new PdfPCell(new Phrase("Mobile", font));
cell.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cell);
//cell = new PdfPCell(new Phrase("Blood Group", font));
//cell.HorizontalAlignment = Element.ALIGN_LEFT;
//table.AddCell(cell);
//qry = "select EmpCode from EmpDetails where StatusID=1";
//dt2 = conn1.gettable(qry);
//if (dt2.Rows.Count > 0)
//{
// foreach(DataRow row2 in dt2.Rows)
// {
// string code = Convert.ToString(row2["EmpCode"]);
qry = "select EmpCode,Name,DeptName,sectname,Desgname,convert(varchar(15),Dob,103)As Dob,Sex,Place,Mobile,Blood from View_EmpDetails where Blood='" + ddblood.SelectedItem.Text + "' and Deptid='" + dddept.SelectedItem.Value + "' And StatusID='1'";
dt = conn1.gettable(qry); {
if (dt.Rows.Count > 0) {
int slno = 1;
foreach(DataRow row in dt.Rows) {
cell = new PdfPCell(new Phrase("" + slno + "", font2));
table.AddCell(cell);
EmpCode = Convert.ToString(row["EmpCode"]);
cell = new PdfPCell(new Phrase("" + EmpCode + "", font2));
cell.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cell);
name = Convert.ToString(row["Name"]);
cell = new PdfPCell(new Phrase("" + name + "", font2));
cell.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cell);
//dept = Convert.ToString(row["DeptName"]);
//cell = new PdfPCell(new Phrase("" + dept + "", font2));
//cell.HorizontalAlignment = Element.ALIGN_LEFT;
//table.AddCell(cell);
sect = Convert.ToString(row["sectname"]);
cell = new PdfPCell(new Phrase("" + sect + "", font2));
cell.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cell);
string desig = Convert.ToString(row["Desgname"]);
cell = new PdfPCell(new Phrase("" + desig + "", font2));
cell.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cell);
string dob = Convert.ToString(row["Dob"]);
cell = new PdfPCell(new Phrase("" + dob + "", font2));
cell.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cell);
string place = Convert.ToString(row["Place"]);
cell = new PdfPCell(new Phrase("" + place + "", font2));
cell.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cell);
string mobile = Convert.ToString(row["Mobile"]);
cell = new PdfPCell(new Phrase("" + mobile + "", font2));
cell.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cell);
slno++;
}
table2.DefaultCell.Border = PdfPCell.NO_BORDER;
table2.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
table2.AddCell(new Phrase("Department: " + dddept.SelectedItem.Text + "", times2));
table2.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
table2.AddCell(new Phrase("Blood Group: " + ddblood.SelectedItem.Text + "", times2));
doc.Add(table2);
doc.Add(table);
DateTime today = System.DateTime.Today;
string today2 = today.ToString("dd/MM/yyyy");
Paragraph p6 = (new Paragraph("Genrated Date:" + today2 + "", times2));
p6.Alignment = Element.ALIGN_RIGHT;
doc.Add(p6);
//System.Diagnostics.Process.Start(#"F:\\reports\\" + "Employeebloodreportsectionwise.pdf");
System.Diagnostics.Process.Start(FilePath);
refresh();
} else {
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('No employees in selected blood group in this department ..!!');", true);
doc.Close();
}
doc.Close();
Response.ContentType = "application/pdf";
Response.AppendHeader("content-disposition", "attachment;filename=BloodGroupReport.pdf");
Response.Write(doc);
Response.Flush();
Response.End();
}

Related

Hide column from datagridview in a pdf file

I have exported data from database to a datagridview and then to a pdf file and I want to delete one column in this file because it is a photo - I get only type of it in a cell (System.Byte[]).
I've tried to make my column invisible in datagridview but it didn't worked. It didn't have any impact on a pdf file, only column in datagridview had become hidden.
BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN,
BaseFont.CP1250, BaseFont.EMBEDDED);
PdfPTable pdfTable = new PdfPTable(dgv.Columns.Count);
pdfTable.DefaultCell.Padding = 3;
pdfTable.WidthPercentage = 100;
pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
pdfTable.DefaultCell.BorderWidth = 1;
iTextSharp.text.Font text = new iTextSharp.text.Font(bf,10,iTextSharp.text.Font.NORMAL);
//Add header
foreach(DataGridViewColumn column in dgv.Columns)
{
PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, text));
cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
pdfTable.AddCell(cell);
}
//add datarow
foreach(DataGridViewRow row in dgv.Rows)
{
foreach(DataGridViewCell cell in row.Cells)
{
//dgv.Columns[7].Visible = false;
pdfTable.AddCell(new Phrase(cell.Value.ToString(), text));
}
}
var savefiledialoge = new SaveFileDialog();
savefiledialoge.FileName = filename;
savefiledialoge.DefaultExt = ".pdf";
if(savefiledialoge.ShowDialog()==DialogResult.OK)
{
using(FileStream stream = new FileStream(savefiledialoge.FileName,FileMode.Create))
{
Document pdfdoc = new Document(PageSize.A4,10f,10f,10f,0f);
PdfWriter.GetInstance(pdfdoc, stream);
pdfdoc.Open();
pdfdoc.Add(pdfTable);
pdfdoc.Close();
stream.Close();
}
}
That's because even if you're making it invisible you still getting it in the loop
so you just need to make a condition in your loop to check if the column is visible or not
like this :
foreach(DataGridViewColumn column in dgv.Columns)
{
if (!column.Visible) continue;
PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, text));
cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
pdfTable.AddCell(cell);
}
//add datarow
foreach(DataGridViewRow row in dgv.Rows)
{
foreach(DataGridViewCell cell in row.Cells)
{
if (!dgv.Columns[cell.ColumnIndex].Visible) continue;
//dgv.Columns[7].Visible = false;
pdfTable.AddCell(new Phrase(cell.Value.ToString(), text));
}
}
and now you can make your column to visible and it won't appear in the pdf file

Create PDF from WebAPI response

Hey guys hope you're all doing well, well my problem here is that i want to return a PDF file from my WebAPI response, this is the code im using to get the responses to create the pdf file.
[Route("Reporte")]
public async Task<HttpResponseMessage> createReport(RequestIdSugeridoModel request)
{
Thread.CurrentThread.CurrentCulture = culture;
ResponseEncabezadoSugeridoModel encabezado = new ResponseEncabezadoSugeridoModel();
List<ResponseDetalleSugeridoModel> detalle = new List<ResponseDetalleSugeridoModel>();
SolicitudSugeridoController solicitud;
Document document;
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
try
{
using (SqlConnection CN_SGE = new SqlConnection(CNSGE))
{
solicitud = new SolicitudSugeridoController();
await CN_SGE.OpenAsync();
await solicitud.GetObtenEncabezadoSugerido(CN_SGE, encabezado, request);
await solicitud.GetObtenDetSugerido(CN_SGE, detalle, request);
}
//start with pdf creation
document = new Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.AddTitle("Reporte de Compras");
document.AddCreator("Disisa");
document.Open();
// set standard font type and size
iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 9, iTextSharp.text.Font.NORMAL, Color.BLACK);
//write document header
document.Add(new Paragraph(encabezado.razonsocial));
//document.Add(Chunk.NEWLINE);
document.Add(new Paragraph("COMPRAS SUGERIDAS"));
//document.Add(Chunk.NEWLINE);
document.Add(new Paragraph(encabezado.nombresucursal));
//document.Add(Chunk.NEWLINE);
// Create table for pdf
PdfPTable tableHeader = new PdfPTable(2);
PdfPCell cellFolio = new PdfPCell(new Phrase("FOLIO: " + encabezado.folio + " " + "SEMANA: " + encabezado.semana, _standardFont));
PdfPCell cellFecha = new PdfPCell(new Phrase("FECHA: " + encabezado.fecha, _standardFont));
// set border and aligment for the cells
cellFolio.Border = 0;
cellFolio.HorizontalAlignment = 0; // 0=left, 1=center, 2=right
cellFecha.Border = 0;
cellFecha.HorizontalAlignment = 2; // 0=left, 1=center, 2=right
// Add cells to the table header
tableHeader.AddCell(cellFolio);
tableHeader.AddCell(cellFecha);
PdfPTable mainTable = new PdfPTable(8);
mainTable.HorizontalAlignment = 1;
// here we will add table headers for report details
PdfPCell cellProducto = new PdfPCell(new Phrase("NOMBRE DEL PRODUCTO", _standardFont));
PdfPCell cellExistencia = new PdfPCell(new Phrase("EXISTENCIA", _standardFont));
PdfPCell cellMes1 = new PdfPCell(new Phrase(encabezado.mes1, _standardFont));
PdfPCell cellMes2 = new PdfPCell(new Phrase(encabezado.mes2, _standardFont));
PdfPCell cellMes3 = new PdfPCell(new Phrase(encabezado.mes3, _standardFont));
PdfPCell cellMes4 = new PdfPCell(new Phrase(encabezado.mes4, _standardFont));
PdfPCell cellSugerido = new PdfPCell(new Phrase("SUGERIDO", _standardFont));
PdfPCell cellObservacion = new PdfPCell(new Phrase("OBSERVACIONES", _standardFont));
mainTable.AddCell(cellProducto);
mainTable.AddCell(cellExistencia);
mainTable.AddCell(cellMes1);
mainTable.AddCell(cellMes2);
mainTable.AddCell(cellMes3);
mainTable.AddCell(cellMes4);
mainTable.AddCell(cellSugerido);
mainTable.AddCell(cellObservacion);
foreach (var item in detalle)
{
mainTable.AddCell(item.nombreproducto);
mainTable.AddCell(item.existencia.ToString());
mainTable.AddCell(item.mes1.ToString());
mainTable.AddCell(item.mes2.ToString());
mainTable.AddCell(item.mes3.ToString());
mainTable.AddCell(item.mes4.ToString());
mainTable.AddCell(item.sugerido.ToString());
mainTable.AddCell(item.observacion);
}
// Add tableHeader to document
document.Add(tableHeader);
// Add mainTable to document
document.Add(mainTable);
//return Request.CreateResponse(System.Net.HttpStatusCode.OK, document);
memoryStream.Position = 0;
HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.OK)
{
Content = new StreamContent(memoryStream)
{
Headers = {
ContentType = new MediaTypeHeaderValue(System.Net.Mime.MediaTypeNames.Applicat‌​ion.Pdf),
ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "PdfFileName.pdf" }
}
}
};
// close document and writer
document.Close();
writer.Flush();
return response;
}
catch (ApplicationException ex)
{
ErrorModel _errors = new ErrorModel();
_errors.message = ex.Message;
return Request.CreateResponse(System.Net.HttpStatusCode.InternalServerError, _errors);
}
catch (Exception ex)
{
ErrorModel _errors = new ErrorModel();
_errors.message = ex.Message;
return Request.CreateResponse(System.Net.HttpStatusCode.InternalServerError, _errors);
}
}
Right now the only thing i get in my response when im testing it with postman is this:
{
"PageNumber": 0,
"LeftMargin": 36,
"RightMargin": 36,
"TopMargin": 36,
"BottomMargin": 36,
"Left": 36,
"Right": 576,
"Top": 756,
"Bottom": 36,
"PageSize": {
"Type": 30,
"Chunks": [],
"Width": 612,
"Height": 792,
"Rotation": 0
},
"JavaScript_onLoad": null,
"JavaScript_onUnLoad": null,
"HtmlStyleClass": null
}
How can i achieve this?
Thanks in advance. I have updated the code the way it is now, with the answer provided by #ckuri

iTextSharp Table Span Pages using Stamper

I have a template PDF that contains form data that is a constant height. Under that data, I need to add a table that has a dynamic height. This table may only be one line, and one row, or it may contain 1000 lines and/or 1-1000 rows.
This is the Code that I have that works fine, except, the table will not span to a new page if it is to large.
private void InsertCurrentNeightborsOlder(string FileName)
{
//Create new PDF document
Document document = new Document(PageSize.LETTER, 20f, 20f, 0f, 20f);
iTextSharp.text.Font fntTableFontHdr = FontFactory.GetFont("Times New Roman", 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
iTextSharp.text.Font fntTableFont = FontFactory.GetFont("Times New Roman", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
try {
PdfWriter.GetInstance(document, new FileStream(FileName, FileMode.Create));
PdfPTable nTbl = new PdfPTable(5);
// Build the header
PdfPCell CellOneHdr = new PdfPCell(new Phrase("Name", fntTableFontHdr));
nTbl.AddCell(CellOneHdr);
PdfPCell CellTwoHdr = new PdfPCell(new Phrase("Address", fntTableFontHdr));
CellTwoHdr.HorizontalAlignment = Element.ALIGN_CENTER;
nTbl.AddCell(CellTwoHdr);
PdfPCell CellTreeHdr = new PdfPCell(new Phrase("Phone #", fntTableFontHdr));
CellTreeHdr.HorizontalAlignment = Element.ALIGN_CENTER;
nTbl.AddCell(CellTreeHdr);
PdfPCell CellFouHdr = new PdfPCell(new Phrase("Method", fntTableFontHdr));
CellFouHdr.HorizontalAlignment = Element.ALIGN_CENTER;
nTbl.AddCell(CellFouHdr);
PdfPCell CellFivHdr = new PdfPCell(new Phrase("Comments", fntTableFontHdr));
nTbl.AddCell(CellFivHdr);
//create column sizes
float[] rows = {
100f,
100f,
70f,
100f,
100f
};
//set row width
nTbl.SetTotalWidth(rows);
nTbl.CompleteRow();
// Add the Cells to the data table
if (ReportDataSet.Tables("CurrentNeighbors").Rows.Count > 0) {
foreach (DataRow r in ReportDataSet.Tables("CurrentNeighbors").Rows) {
nTbl.AddCell(new Paragraph(r("FullName").ToString, fntTableFont));
nTbl.AddCell(new Paragraph(r("Address").ToString, fntTableFont));
PdfPCell cell = new PdfPCell(new Paragraph(r("PhoneNumber").ToString, fntTableFont));
cell.HorizontalAlignment = 1;
nTbl.AddCell(cell);
// nTbl.AddCell(New Paragraph(r("PhoneNumber").ToString, fntTableFont))
nTbl.AddCell(new Paragraph(r("ContactMethod").ToString, fntTableFont));
nTbl.AddCell(new Paragraph(r("Comments").ToString, fntTableFont));
}
} else {
nTbl.AddCell(new Paragraph("Nothing Entered", fntTableFont));
nTbl.AddCell(new Paragraph(" ", fntTableFont));
nTbl.AddCell(new Paragraph(" ", fntTableFont));
nTbl.AddCell(new Paragraph(" ", fntTableFont));
nTbl.AddCell(new Paragraph(" ", fntTableFont));
}
document.Open();
nTbl.HeaderRows = 1;
nTbl.SplitLate = false;
document.Add(nTbl);
} catch (Exception ex) {
} finally {
document.Close();
}
}
The "FileName" Parameter passed contains the location of the original file that I want to add the table to.
Is it even possible to do, and if so, what am I missing?
EDIT:
Here is another function that I tried (Using the Stamper). I may be way off on this one too, but that is what I am attempting to find out:
private void InsertCurrentNeightbors(string FileName)
{
// This is the Temporary File that we are working with. This file already has data in it
string oldFile = FileName;
// Create a new Temporary file that we can write to
string newFile = My.Computer.FileSystem.GetTempFileName();
iTextSharp.text.pdf.PdfReader reader = null;
iTextSharp.text.pdf.PdfStamper stamper = null;
iTextSharp.text.pdf.PdfContentByte cb = null;
iTextSharp.text.Rectangle rect = null;
int pageCount = 0;
try {
reader = new iTextSharp.text.pdf.PdfReader(oldFile);
rect = reader.GetPageSizeWithRotation(1);
stamper = new iTextSharp.text.pdf.PdfStamper(reader, new System.IO.FileStream(newFile, System.IO.FileMode.Create));
iTextSharp.text.Font fntTableFontHdr = FontFactory.GetFont("Times New Roman", 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
iTextSharp.text.Font fntTableFont = FontFactory.GetFont("Times New Roman", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
cb = stamper.GetOverContent(1);
dynamic ct = new ColumnText(cb);
ct.Canvas = stamper.GetOverContent(reader.NumberOfPages + 1);
ct.Alignment = Element.ALIGN_LEFT;
ct.SetSimpleColumn(70, 36, PageSize.A4.Width - 36, PageSize.A4.Height - 300);
PdfPTable nTbl = new PdfPTable(5);
// Build the header
PdfPCell CellOneHdr = new PdfPCell(new Phrase("Name", fntTableFontHdr));
nTbl.AddCell(CellOneHdr);
PdfPCell CellTwoHdr = new PdfPCell(new Phrase("Address", fntTableFontHdr));
CellTwoHdr.HorizontalAlignment = Element.ALIGN_CENTER;
nTbl.AddCell(CellTwoHdr);
PdfPCell CellTreeHdr = new PdfPCell(new Phrase("Phone #", fntTableFontHdr));
CellTreeHdr.HorizontalAlignment = Element.ALIGN_CENTER;
nTbl.AddCell(CellTreeHdr);
PdfPCell CellFouHdr = new PdfPCell(new Phrase("Method", fntTableFontHdr));
CellFouHdr.HorizontalAlignment = Element.ALIGN_CENTER;
nTbl.AddCell(CellFouHdr);
PdfPCell CellFivHdr = new PdfPCell(new Phrase("Comments", fntTableFontHdr));
nTbl.AddCell(CellFivHdr);
//create column sizes
float[] rows = {
100f,
100f,
70f,
100f,
100f
};
//set row width
nTbl.SetTotalWidth(rows);
nTbl.CompleteRow();
// Add the Cells to the data table
if (ReportDataSet.Tables("CurrentNeighbors").Rows.Count > 0) {
foreach (DataRow r in ReportDataSet.Tables("CurrentNeighbors").Rows) {
nTbl.AddCell(new Paragraph(r("FullName").ToString, fntTableFont));
nTbl.AddCell(new Paragraph(r("Address").ToString, fntTableFont));
nTbl.AddCell(new Paragraph(r("PhoneNumber").ToString, fntTableFont));
nTbl.AddCell(new Paragraph(r("ContactMethod").ToString, fntTableFont));
nTbl.AddCell(new Paragraph(r("Comments").ToString, fntTableFont));
}
} else {
nTbl.AddCell(new Paragraph("Nothing Entered", fntTableFont));
nTbl.AddCell(new Paragraph(" ", fntTableFont));
nTbl.AddCell(new Paragraph(" ", fntTableFont));
nTbl.AddCell(new Paragraph(" ", fntTableFont));
nTbl.AddCell(new Paragraph(" ", fntTableFont));
}
nTbl.SplitLate() = false;
nTbl.WriteSelectedRows(0, 25, 85, 490, stamper.GetOverContent(reader.NumberOfPages));
stamper.Close();
reader.Close();
ct.Go();
// Now that the new temp file has been written, we need to delete the old temp file
// and rename the new temp file to the old temp file name
// Delete Old Temp file
My.Computer.FileSystem.DeleteFile(FileName);
// Rename the new temp file to the old temp file
My.Computer.FileSystem.RenameFile(newFile, System.IO.Path.GetFileName(FileName));
} catch (Exception ex) {
throw ex;
}
}
I did try the link that you provided, but it did not work as expected. All “I” was able to do is repeat the source page 100 times onto the destination page. I know that it was all to do with my interpretation of the source code, and the conversion, but this is what I got:
private void manipulatePdf(string src, string dest)
{
try {
// Read the template file into the reader variable
PdfReader reader = new PdfReader(src);
// Get the page side of the template file
iTextSharp.text.Rectangle pagesize = reader.GetPageSize(1);
// Create a Stamper for the destination file
PdfStamper stamper = new PdfStamper(reader, new System.IO.FileStream(dest, System.IO.FileMode.Create));
// Create a new Paragraph
Paragraph p = new Paragraph();
// Add Text into the new paragraph
p.Add(new Chunk("Hello "));
p.Add(new Chunk("World"));
// Declare your AcroFields so we can get the last field's position
AcroFields form = stamper.AcroFields();
// Get the Last AcroField's Position
Rectangle rect = form.GetFieldPositions("MethodOfVerification")(0).position;
int status = 0;
PdfImportedPage newPage = null;
ColumnText column = new ColumnText(stamper.GetOverContent(1));
column.SetSimpleColumn(rect);
int pagecount = 1;
// Add's 100 Items
int i = 0;
while (i < 100) {
i += 1;
// Creates a new paragraph object
column.AddElement(new Paragraph("Hello " + i.ToString));
// Adds the paragraph object to the column
column.AddElement(p);
// Draw content of column
status = column.Go();
if (ColumnText.HasMoreText(status)) {
// Creates a new page and stamps the Source PDF into the Destination PDF
newPage = loadPage(newPage, reader, stamper);
triggerNewPage(stamper, pagesize, newPage, column, rect, System.Threading.Interlocked.Increment(pagecount));
}
}
stamper.FormFlattening = true;
stamper.Close();
reader.Close();
} catch (Exception ex) {
}
}
public PdfImportedPage loadPage(PdfImportedPage page, PdfReader reader, PdfStamper stamper)
{
if (page == null) {
return stamper.GetImportedPage(reader, 1);
}
return page;
}
public void triggerNewPage(PdfStamper stamper, Rectangle pagesize, PdfImportedPage page, ColumnText column, Rectangle rect, int pagecount)
{
stamper.InsertPage(pagecount, pagesize);
PdfContentByte canvas = stamper.GetOverContent(pagecount);
canvas.AddTemplate(page, 0, 0);
// column.setCanvas(canvas)
column.Canvas() = canvas;
column.SetSimpleColumn(rect);
column.Go();
}
I don't know if this helps but I've ported and slightly modified Bruno sample code to a C# version. The first block (file_1) creates a sample file and stores the last known coordinate so that we can resume with a table later. The second block (file_2) then uses a PdfStamper and a ColumnText to start the table and continuously adds pages until the table fits. The code itself, especially the second block, has comments that better explain things.
You should be able to re-work the first block to your form's logic to get the coordinates (it seems like you've got that part down) and then just use the second block with your local table.
//Working folder
var exportFolder = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "SO_17589177");
System.IO.Directory.CreateDirectory(exportFolder);
//File 1 is our "template" file, File 2 is our final file
var file_1 = System.IO.Path.Combine(exportFolder, "file_1.pdf");
var file_2 = System.IO.Path.Combine(exportFolder, "file_2.pdf");
//Will hold a rectangle based on the last known coordinates
iTextSharp.text.Rectangle tableRectStart;
using (var fs = new FileStream(file_1, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var doc = new Document()) {
using (var writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
for (var i = 0; i < 10; i++) {
doc.Add(new Paragraph("Hello world"));
}
//Store our coordinates for later
tableRectStart = new iTextSharp.text.Rectangle(doc.Left, doc.Bottom, doc.Right, writer.GetVerticalPosition(false));
doc.Close();
}
}
}
using (var r = new PdfReader(file_1)) {
using (var fs = new FileStream(file_2, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var stamper = new PdfStamper(r, fs)) {
//We want to target the last page of the previous PDF
int pageNumber = r.NumberOfPages;
//Store the last page's size which is what we'll use for new pages later
var docRect = r.GetPageSize(pageNumber);
//Create a giant table
var t = new PdfPTable(2);
for (var i = 0; i < 1000; i++) {
t.AddCell(String.Format("This is cell {0}", i));
}
//Create our stamper bound to the last page of our source document
var ct = new ColumnText(stamper.GetOverContent(pageNumber));
//Add our table to the stamper
ct.AddElement(t);
//Set the drawing area for the table
ct.SetSimpleColumn(tableRectStart);
//Infinite loop below that is responsible for breaking itself out
//Might want to add guards in case content gets too big and always overflows
while (true) {
//Draw the text and pass the status back to a helper
//method that tells us if there's more text to be drawn
if (! ColumnText.HasMoreText(ct.Go())) {
//If there isn't any more text then exit the infinite loop
break;
}
//Reset our rectangle to the document's rectangle
tableRectStart = docRect;
//Increment the current page number (which we need to keep track of)
//and insert a new page
stamper.InsertPage(++pageNumber, docRect);
//Tell the ColumnText to draw on a new page
ct.Canvas = stamper.GetOverContent(pageNumber);
//Reset the drawing canvas area
//TODO: Include some margin logic here probably
ct.SetSimpleColumn(docRect);
}
}
}
}

phrase text too big for one page

I have a PDfTable like below, my problem is if Phrase text too big than it makes blank line between header and phrase. How can I bound together so if phrase text too big for one page than fit what ever text you can on the same page with headers and rest of the phrase text you can start with new page.
problem:
.............................
. header1 : header2 :header3: Page1 // here I want to fit the phrase as much as can if phrase needs new page than put rest of the text on the next page
. :
. phrase too big to fit here:
............................:
.............................
. phrase starts here . Page2
. .
.............................
code:
private String WritePDF(DataTable dt)
{
String fileName = "";
//Creating iTextSharp Table from the DataTable data
PdfPTable pdfTable = new PdfPTable(m_PDFColumnCount);
pdfTable.DefaultCell.Padding = 1;
pdfTable.WidthPercentage = 100;
pdfTable.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
pdfTable.DefaultCell.BackgroundColor = new iTextSharp.text.BaseColor(194, 214, 155);
//pdfTable.DefaultCell.BorderWidth = 1;
this.BuildPDFHeader(pdfTable, "DATE");
this.BuildPDFHeader(pdfTable, "TIME");
this.BuildPDFHeader(pdfTable, "RESULT");
this.BuildPDFHeader(pdfTable, "FULLNAME");
this.BuildPDFHeader(pdfTable, "REGARDING");
//Adding DataRow
for (int intIndex = 0; intIndex < dt.Rows.Count; intIndex++)
{
dt.Rows[intIndex]["details"] = getplaintext(dt.Rows[intIndex]["details"].ToString());
pdfTable.AddCell(dt.Rows[intIndex]["date"].ToString());
pdfTable.AddCell(dt.Rows[intIndex]["time"].ToString());
pdfTable.AddCell(dt.Rows[intIndex]["result"].ToString());
pdfTable.AddCell(dt.Rows[intIndex]["fullname"].ToString());
pdfTable.AddCell(dt.Rows[intIndex]["regarding"].ToString());
PdfPCell cell = new PdfPCell(new Phrase(dt.Rows[intIndex]["details"].ToString()));
cell.BackgroundColor = new iTextSharp.text.BaseColor(227, 234, 235);
cell.Colspan = 5;
pdfTable.AddCell(cell);
}
//String folderPath = ConfigurationManager.AppSettings["Path"].ToString();
String folderPath = "C:\\PDFs\\";
fileName = String.Format("{0}{1}{2}",folderPath, dt.Rows[0]["id"].ToString(),".pdf" );
//Exporting to PDF
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate ))
{
Document pdfDoc = new Document(PageSize.A4, 20, 20, 20, 20);
PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();
pdfDoc.Add(pdfTable);
pdfDoc.Close();
stream.Close();
}
return fileName;
}
private void BuildPDFHeader( PdfPTable pdfTable, String strText)
{
PdfPCell cell = new PdfPCell(new Phrase(strText));
cell.BackgroundColor = new iTextSharp.text.BaseColor(51, 102,102);
pdfTable.AddCell(cell);
}
Introduce the following line right after you define the table:
pdfTable.SplitLate = false;
This will split rows early. In you case, the rows are split only if a row takes up the space of an entire page.

iTextSharp does not render Custom urdu font

I am using custom Urdu Font Jameel Noori Nastaleeq with iTextSharp but it is not showing text at all. It shows text when I use built-in forms like times.ttf etc.
Code is given below:
private void button1_Click(object sender, EventArgs e)
{
Document document = new Document();
try
{
PdfWriter writer = PdfWriter.GetInstance(document, new System.IO.FileStream("C:\\iTextSharpHelloworld.pdf", System.IO.FileMode.Create));
document.Open();
string fontpath = Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts\\Jameel Noori Nastaleeq.ttf";
//string fontpath = Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts\\times.ttf";
BaseFont basefont = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
iTextSharp.text.Font arabicFont = new iTextSharp.text.Font(basefont, 24, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLUE);
var el = new Chunk();
iTextSharp.text.Font f2 = new iTextSharp.text.Font(basefont, el.Font.Size,
el.Font.Style, el.Font.Color);
el.Font = arabicFont;
PdfPTable table = new PdfPTable(1);
table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
var str = "نام : ";
PdfPCell cell = new PdfPCell(new Phrase(10, str, el.Font));
table.AddCell(cell);
document.Add(table);
document.Close();
MessageBox.Show("Done");
}
catch (DocumentException de)
{
// this.Message = de.Message;
MessageBox.Show(de.Message);
}
catch (System.IO.IOException ioe)
{
// this.Message = ioe.Message;
MessageBox.Show(ioe.Message);
}
// step 5: we close the document
document.Close();
}
}
Update: Setting cell.ArabicOptions = ColumnText.DIGITS_EN2AN; does render font in my desired font but does not any other text.
to write in Arabic I use the following font:
here is an example to create an Order in Arabic is the same for Urdu
BaseFont basefontArabic = BaseFont.CreateFont("c:\\\\windows\\\\fonts\\\\TIMES.ttf", BaseFont.IDENTITY_H, true);
iTextSharp.text.Font farabicNormal = new iTextSharp.text.Font(basefontArabic, 10, iTextSharp.text.Font.NORMAL);
iTextSharp.text.Font farabicBold = new iTextSharp.text.Font(basefontArabic, 12, iTextSharp.text.Font.BOLD);
`Document document = new Document(PageSize.A4);
document.SetMargins(10f, 10f, 10f, 30f);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(FileName+ ".pdf", FileMode.Create));
document.Open();
PdfPTable table = new PdfPTable(5) { RunDirection = PdfWriter.RUN_DIRECTION_RTL, HeaderRows = 1 };
table.SetWidths(new float[] { 1, 1, 1, 2, 1 });
table.AddCell(new PdfPCell(new Phrase("الكمية", ReportDesigner.farabicNormal)) { GrayFill = 0.95f, HorizontalAlignment=Element.ALIGN_CENTER });
table.AddCell(new PdfPCell(new Phrase("نوع السلعة", ReportDesigner.farabicNormal)) { GrayFill = 0.95f, HorizontalAlignment = Element.ALIGN_CENTER });
table.AddCell(new PdfPCell(new Phrase("الوزن الصافي", ReportDesigner.farabicNormal)) { GrayFill = 0.95f, HorizontalAlignment = Element.ALIGN_CENTER });
table.AddCell(new PdfPCell(new Phrase("س . ف", ReportDesigner.farabicNormal)) { GrayFill = 0.95f, HorizontalAlignment = Element.ALIGN_CENTER });
table.AddCell(new PdfPCell(new Phrase("الجملة", ReportDesigner.farabicNormal)) { GrayFill = 0.95f, HorizontalAlignment = Element.ALIGN_CENTER });
foreach (OrderDetailsEntity item in Order.Details)
{
table.AddCell(new PdfPCell(new Phrase(item.Quantité.ToString("N3"), ReportDesigner.farabicNormal)));
table.AddCell(new PdfPCell(new Phrase(item.ArticleLigneFacture.Désignation, ReportDesigner.farabicNormal)));
table.AddCell(new PdfPCell(new Phrase(item.QantitéEmballage.ToString("N3"), ReportDesigner.farabicNormal)));
table.AddCell(new PdfPCell(new Phrase(item.PrixAchatUnitaire.ToString("N3"), ReportDesigner.farabicNormal)));
table.AddCell(new PdfPCell(new Phrase(item.TotalLigneFacture.ToString("N3"), ReportDesigner.farabicNormal)));
}
document.Add(table);
document.Close();`

Categories