itextsharp pdf creation run on local not in server - asp.net

I create a PDF file using iTextSharp and it's stored in my system desktop and opens successfully in my local system. Now if I upload the same code to a server, no error occurs and the PDF file isn't created. This is my partial code to create and open pdf.
PdfWriter.GetInstance(doc, new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Out.pdf", FileMode.Create));
doc.Open();
DataView DView = (DataView)Session["data_value"];
dtData = DView.ToTable();
dr = dtData.Select("fldemp_no='" + Session["EmployeeID"].ToString() + "'");
doc.NewPage();
iTextSharp.text.Image ObjImg = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Bin/Head.png"));
ObjImg.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
ObjImg.ScaleToFit(220f, 150f);
ObjImg.SpacingBefore = 13f;
ObjImg.SpacingAfter = 1f;
doc.Add(ObjImg);
maintable = new PdfPTable(1);
cell = new PdfPCell(new Phrase("Pay Slip for the month of " + dr[0]["fldmonth"].ToString(), fnt1));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.Border = 0;
maintable.AddCell(cell);
doc.Add(maintable);
maintable = new PdfPTable(2);
empdetright = new PdfPTable(2);
empdetleft = new PdfPTable(2);
cell = new PdfPCell(new Phrase("Emp No", fnt1));
cell.Border = 0;
empdetright.AddCell(cell);
cell = new PdfPCell(new Phrase(": " + dr[0]["fldemp_no"].ToString(), fnt1));
cell.Border = 0;
empdetright.AddCell(cell);
cell = new PdfPCell(new Phrase("Emp Name", fnt1));
cell.Border = 0;
empdetright.AddCell(cell);
cell = new PdfPCell(new Phrase(": " + dr[0]["fldempname"].ToString(), fnt1));
cell.Border = 0;
empdetright.AddCell(cell);
doc.Close();
Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/out.pdf");

In a web application you need to return the PDF document in the response stream. Here is a simple example:
var response = HttpContext.Current.Response;
response.Clear();
response.ContentType = "application/pdf";
MemoryStream mem = new MemoryStream(); // PDF data will be written here
PdfWriter writer = PdfWriter.GetInstance(doc, mem); // tie a PdfWriter instance to the stream
doc.Open();
// ... Doing the pdf generation
doc.Close();
// write the document data to response stream
writer.Flush();
response.OutputStream.Write(mem.GetBuffer(), 0, mem.GetBuffer().Length);
response.OutputStream.Flush();
response.OutputStream.Close();
response.End();

Related

Nested foreach() messing up

Good Day, guys.
I'm currentl making a full page overlay for navigation and I've been trying to figure out this problem for the past 2 days regarding my nested foreach() loops.
I have these pages which may be linked with posts. and here is what I'm trying to achieve:
Home Page
Technologies Page
Post 1/ Post 2/ Post3
Contact Us Page
About Us Page
But what I'm getting is:
Home Page
Technologies Page
Post 1/ Post 2/ Post3
Contact Us Page
Post 1/ Post 2/ Post3
About Us Page
Post 1/ Post 2/ Post3
Here are my code:
public DataTable GetMain()
{
string sql = "SELECT Id,Title,Slug from Pages";
SqlCommand SQLComm = new SqlCommand(sql, con);
SqlDataAdapter SQLAd = new SqlDataAdapter(SQLComm);
DataTable dt = new DataTable();
SQLAd.Fill(dt);
return dt;
}
private void GetAll()
{
DataTable dt = new DataTable();
HyperLink newhyperlink = new HyperLink();
Label newlabel = new Label();
foreach (DataRow row in GetMain().Rows)
{
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = #"<li class""dropdown"" data-toggle=""collapse""";
newlabel = new Label();
newhyperlink.ID = "Main";
MainMenu.Controls.Add(newhyperlink);
newhyperlink.Text = row["Title"].ToString();
newhyperlink.NavigateUrl = row["Slug"].ToString();
newhyperlink = new HyperLink();
html.Append("></li>");
html.Append("<ul class=\"list-group\">");
var sql2 = "SELECT po.Id as PostId, po.Slug as PostSlug, po.Title as PostTitle, pa.Slug as PageSlug, pa.Id as PageId FROM Posts po " +
"LEFT JOIN PagesPostsMap m ON po.Id = m.PostId " +
"LEFT JOIN Pages pa ON m.PageId = pa.Id " +
"WHERE pa.Id = "+row["Id"] + "";
SqlDataAdapter SQLAd = new SqlDataAdapter(sql2, con);
SQLAd.Fill(dt2);
foreach (DataRow row2 in dt2.Rows)
{
object value = row2["PostId"];
if (value != DBNull.Value)
{
if (row["Id"] != row2["PageId"])
{
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = #"<li class""dropdown-menu""";
newlabel = new Label();
newhyperlink.ID = "Sub" + i.ToString();
MainMenu.Controls.Add(newhyperlink);
newhyperlink.Text = row2["PostTitle"].ToString();
newhyperlink.NavigateUrl = row2["PageSlug"].ToString() + "/" + row2["PostSlug"].ToString();
newhyperlink = new HyperLink();
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = "</li>";
newlabel = new Label();
}
}
}
}
}
I'm sorry if the the classes and stuff are not adding up. I'm still trying to figure out how css and JS works.
And thank for helping me.
Your code is actually just doing what you tell it to do. For every row in your GetMain, you order everything in your dt2 (datatable2). If you want what you try to achive, you have to set a condition and put your second foreach into that condition.
if(tech parts row)
{
"your second foreach"
}
If I missunderstand anything, feel free to add more info
public DataTable GetMain()
{
string sql = "SELECT Id,Title,Slug from Pages";
SqlCommand SQLComm = new SqlCommand(sql, con);
SqlDataAdapter SQLAd = new SqlDataAdapter(SQLComm);
DataTable dt = new DataTable();
SQLAd.Fill(dt);
return dt;
}
private void GetAll()
{
DataTable dt = new DataTable();
HyperLink newhyperlink = new HyperLink();
Label newlabel = new Label();
foreach (DataRow row in GetMain().Rows)
{
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = #"<li class""dropdown"" data-toggle=""collapse""";
newlabel = new Label();
newhyperlink.ID = "Main";
MainMenu.Controls.Add(newhyperlink);
newhyperlink.Text = row["Title"].ToString();
newhyperlink.NavigateUrl = row["Slug"].ToString();
newhyperlink = new HyperLink();
html.Append("></li>");
html.Append("<ul class=\"list-group\">");
var sql2 = "SELECT po.Id as PostId, po.Slug as PostSlug, po.Title as PostTitle, pa.Slug as PageSlug, pa.Id as PageId FROM Posts po " +
"JOIN PagesPostsMap m ON po.Id = m.PostId " +
"JOIN Pages pa ON m.PageId = pa.Id " +
"WHERE pa.Id = "+row["Id"] + "";
SqlDataAdapter SQLAd = new SqlDataAdapter(sql2, con);
SQLAd.Fill(dt2);
foreach (DataRow row2 in dt2.Rows)
{
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = #"<li class""dropdown-menu""";
newlabel = new Label();
newhyperlink.ID = "Sub" + i.ToString();
MainMenu.Controls.Add(newhyperlink);
newhyperlink.Text = row2["PostTitle"].ToString();
newhyperlink.NavigateUrl = row2["PageSlug"].ToString() + "/" + row2["PostSlug"].ToString();
newhyperlink = new HyperLink();
newlabel.ID = "li";
MainMenu.Controls.Add(newlabel);
newlabel.Text = "</li>";
newlabel = new Label();
}
}
}

Water mark on image error inside list view asp dot net

i have this c# asp dot net code to add water mark on the asp image control which is working fine.
string watermarkText = "© water mark";
string fileName = Server.MapPath(myimg.ImageUrl);
FileStream fs = new FileStream(fileName, FileMode.Open);
using (Bitmap bmp = new Bitmap(fs, false))
{
using (Graphics grp = Graphics.FromImage(bmp))
{
Brush brush = new SolidBrush(Color.Red);
Font font = new System.Drawing.Font("Arial", 30, FontStyle.Bold, GraphicsUnit.Pixel);
SizeF textSize = new SizeF();
textSize = grp.MeasureString(watermarkText, font);
Point position = new Point((bmp.Width - ((int)textSize.Width + 10)), (bmp.Height - ((int)textSize.Height + 80)));
grp.DrawString(watermarkText, font, brush, position);
using (MemoryStream memoryStream = new MemoryStream())
{
bmp.Save(memoryStream, ImageFormat.Png);
string base64String = Convert.ToBase64String(memoryStream.ToArray());
string imageUrl = "data:image/png;base64," + base64String;
myimg.Attributes.Add("src", imageUrl);
}
}
}
but when i add the same water mark code inside listview on listview databound event like
System.Web.UI.WebControls.Image myimg;
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (!IsPostBack)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
myimg = ((System.Web.UI.WebControls.Image)e.Item.FindControl("Image1"));
string watermarkText = "© watermark";
string fileName = Server.MapPath(myimg.ImageUrl);
FileStream fs = new FileStream(fileName, FileMode.Open);
using (Bitmap bmp = new Bitmap(fs, false))
{
using (Graphics grp = Graphics.FromImage(bmp))
{
Brush brush = new SolidBrush(Color.Red);
Font font = new System.Drawing.Font("Arial", 30, FontStyle.Bold, GraphicsUnit.Pixel);
SizeF textSize = new SizeF();
textSize = grp.MeasureString(watermarkText, font);
Point position = new Point((bmp.Width - ((int)textSize.Width + 10)), (bmp.Height - ((int)textSize.Height + 80)));
grp.DrawString(watermarkText, font, brush, position);
using (MemoryStream memoryStream = new MemoryStream())
{
bmp.Save(memoryStream, ImageFormat.Png);
string base64String = Convert.ToBase64String(memoryStream.ToArray());
string imageUrl = "data:image/png;base64," + base64String;
myimg.Attributes.Add("src", imageUrl);
}
}
}
}
}
}
so it gives me following error CustomCoupon\ca00453f-c985-4794-9a87-36a60e2fa0e1.png' because it is being used by another process.
Please advice.
You can replace:
FileStream fs = new FileStream(fileName, FileMode.Open);
by:
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
...
}

Placing DataBound Drop Down List into TableCell

I have a bound drop down list that I would like to place into a Table Cell. I am used to Labels and Text Boxes but I cannot seem to get the syntax working on this one. This code is inside of a Webmethod and my output has to be just the html. Thank you.
[System.Web.Services.WebMethod]
public static string gatherSurchargeData(string PriceListItemID, string ProdID, string ColorCode)
{
DataTable GetProductSizes = new DataTable();
GetProductSizes = DataLayer.PricingToolDL.getProductSizes(ProdID, ColorCode);
DataTable dt = new DataTable();
dt = DataLayer.PricingToolDL.getScharge(PriceListItemID);
Table tblScharges = new Table();
tblScharges.ID = "tblScharges";
TableHeaderRow th = new TableHeaderRow();
TableHeaderCell thSizeScharge = new TableHeaderCell();
thSizeScharge.Text = "Size";
th.Cells.Add(thSizeScharge);
tblScharges.Rows.Add(th);
int i = 0;
while (i <= dt.Rows.Count - 1)
{
TableRow tr = new TableRow();
tr.ID = "tableTr" + i;
TableCell tcSizeScharge = new TableCell();
DropDownList ddl = new DropDownList();
ddl.DataSource = GetProductSizes;
ddl.DataTextField = "FitSize";
ddl.DataValueField = "FitSize";
ddl.DataBind();
//string dtMovexSKU = dt.Rows[i]["MovexSKU"].ToString();
//DataRow[] GetProductSizesMovexSKU = GetProductSizes.Select("MovexSKU Like'" + dtMovexSKU + "'");
//tcSizeScharge.ID = "tcSizeScharge" + i;
//tcSizeScharge.Text = GetProductSizesMovexSKU[0][1].ToString();
tr.Cells.Add(tcSizeScharge);
tblScharges.Rows.Add(tr);
i++;
}
string html = "";
using (StringWriter sw = new StringWriter())
{
tblScharges.RenderControl(new HtmlTextWriter(sw));
html = sw.ToString();
}
return html;
}
The commented lines would be the code I would use if I were only wanting text to appear if that helps.
You need to add control in tablecell like this
tcSizeScharge.Controls.Add(ddl);

How to Convert Json to Grid on a server side

I have a json that I want to convert to a HTML grid view on the server side and return the HTML as a string
StringBuilder sb = new StringBuilder();
var serializer = new JavaScriptSerializer();
string g = serializer.Serialize(ox)
//here convert g to html table
sb.Append(g);
return sb.ToString();
private String Serialize2HTMLTable(List<conversion> ox)
{
var serializer = new JavaScriptSerializer();
DataTable dt = (DataTable)JsonConvert.DeserializeObject(serializer.Serialize(ox), (typeof(DataTable)));
StringWriter sw = new StringWriter();
HtmlTextWriter w = new HtmlTextWriter(sw);
//Create a table
Table tbl = new Table();
tbl.BorderStyle = BorderStyle.Solid;
tbl.BorderWidth = 1;
//Create column header row
TableHeaderRow thr = new TableHeaderRow();
foreach (DataColumn col in dt.Columns)
{
TableHeaderCell th = new TableHeaderCell();
th.Text = col.Caption;
thr.Controls.Add(th);
}
tbl.Controls.Add(thr);
//Create table rows
foreach (DataRow row in dt.Rows)
{
TableRow tr = new TableRow();
foreach (var value in row.ItemArray)
{
TableCell td = new TableCell();
td.BorderStyle = BorderStyle.Solid;
td.BorderWidth = 1;
td.Text = value.ToString();
tr.Controls.Add(td);
}
tbl.Controls.Add(tr);
}
tbl.RenderControl(w);
return sw.ToString();
}

Process.start not working on server

I create a PDF file using itextsharp. It's created successfully and open with adobe reader 9 not in adobe reader 7 and 8. Please help me to fix this error.
This is my partial code :
try
{
//yourFont = BaseFont.CreateFont(Application.StartupPath + "/verdana.TTF", BaseFont.WINANSI, BaseFont.EMBEDDED);
pgSize = new iTextSharp.text.Rectangle(320, 455);
doc = new Document(pgSize, 15, 5, 12, 4);
fnt = new iTextSharp.text.Font(yourFont, 7, 3);
fnt1 = new iTextSharp.text.Font(yourFont, 5, 0);
fnt2 = new iTextSharp.text.Font(yourFont, 3, 2);
fnt3 = new iTextSharp.text.Font(yourFont, 4, 6);
PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("Payslip.pdf"), FileMode.Create));
//PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("Payslip.pdf"), FileMode.Create)); //Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Payslip.pdf"
doc.Open();
DataView DView = (DataView)Session["data_value"];
dtData = DView.ToTable();
dr = dtData.Select("fldemp_no='" + Session["EmployeeID"].ToString() + "'");
doc.NewPage();
iTextSharp.text.Image ObjImg = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Bin/Head.png"));
ObjImg.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
ObjImg.ScaleToFit(220f, 150f);
ObjImg.SpacingBefore = 13f;
ObjImg.SpacingAfter = 1f;
doc.Add(ObjImg);
maintable = new PdfPTable(1);
cell = new PdfPCell(new Phrase("Pay Slip for the month of " + dr[0]["fldmonth"].ToString(), fnt1));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.Border = 0;
maintable.AddCell(cell);
doc.Add(maintable);
maintable = new PdfPTable(2);
empdetright = new PdfPTable(2);
empdetleft = new PdfPTable(2);
cell = new PdfPCell(new Phrase("Emp No", fnt1));
cell.Border = 0;
empdetright.AddCell(cell);
cell = new PdfPCell(new Phrase(": " + dr[0]["fldemp_no"].ToString(), fnt1));
cell.Border = 0;
empdetright.AddCell(cell);
cell = new PdfPCell(new Phrase("Emp Name", fnt1));
cell.Border = 0;
empdetright.AddCell(cell);
cell = new PdfPCell(new Phrase(": " + dr[0]["fldempname"].ToString(), fnt1));
cell.Border = 0;
empdetright.AddCell(cell);
.......
doc.Close();
Process.Start(Server.MapPath("Payslip.pdf"));
The above code is run on local machine not on server. Please help me to fix this error..
Process.Start will attempt to open the file in the computer it is running (the server).
This is unlikely to be what you want. You should be uploading the file to the browser and let it decide (using Response.WriteFile, for instance).

Resources