I try to generate word document using this code:
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/doc";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;
filename=" + DateTime.Now + ".doc");
var strHTMLContent = new StringBuilder();
strHTMLContent.Append(
"<h1 title='Heading' align='Center'style='font-family: verdana; font
-size: 80 % ;color: black'><u>Document Heading</u> </h1> ");
strHTMLContent.Append("<br>");
strHTMLContent.Append("<table align='Center'>");
// Row with Column headers
strHTMLContent.Append("<tr>");
strHTMLContent.Append("<td style='width:100px; background:# 99CC00'>
<b>Column1 </b> </td>");
strHTMLContent.Append("<td style='width:100px;background:# 99CC00'>
<b>Column2 </b> </td>");
strHTMLContent.Append("<td style='width:100px; background:# 99CC00'>
<b>Column 3</b></td>");
strHTMLContent.Append(" </tr> ");
// First Row Data
strHTMLContent.Append("<tr>");
strHTMLContent.Append(
"<td style='width:100px'></td>");
strHTMLContent.Append(
"<td style='width:100px'>b</td>");
strHTMLContent.Append(
"<td style='width:100px'>c</td>");
strHTMLContent.Append("</tr>");
// Second Row Data
strHTMLContent.Append("<tr>");
strHTMLContent.Append(
"<td style='width:100px'>d</td>");
strHTMLContent.Append(
"<td style='width:100px'>e</td>");
strHTMLContent.Append(
"<td style='width:100px'>f</td>");
strHTMLContent.Append("</tr>");
strHTMLContent.Append("</table>");
strHTMLContent.Append("<br><br>");
strHTMLContent.Append(
"<p align='Center'> Note : This is a dynamically
generated word document </p> ");
HttpContext.Current.Response.Write(strHTMLContent);
// HttpContext.Current.Response.BinaryWrite(strHTMLContent);
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
It work fine but I want to make it landscape and in Print Layout cause it appears in Web Layout
Can anybody help me?
I found solution in this post. Solve like this:
Response.Write("<html>")
Response.Write("<head>")
Response.Write("<META HTTP-EQUIV=""Content-Type"" CONTENT=""text/html;
charset=UTF-8"">")
Response.Write("<meta name=ProgId content=Word.Document>")
Response.Write("<meta name=Generator content=""Microsoft Word 9"">")
Response.Write("<meta name=Originator content=""Microsoft Word 9"">")
Response.Write("<style>")
Response.Write("#page Section1 {size:595.45pt 841.7pt; margin:1.0in 1.25in 1.0in
1.25in;mso-header-margin:.5in;mso-footer-margin:.5in;mso-paper-source:0;}")
Response.Write("div.Section1 {page:Section1;}")
Response.Write("#page Section2 {size:841.7pt 595.45pt;mso-page-orientation:
landscape;margin:1.25in 1.0in 1.25in 1.0in;mso-header-margin:.5in;
mso-footer-margin:.5in;mso-paper-source:0;}")
Response.Write("div.Section2 {page:Section2;}")
Response.Write("</style>")
Response.Write("</head>")
Response.Write("<body>")
Response.Write("<div class=Section2>")
I solve this, it's work fine for me.
<style>
#page
{
mso-page-border-surround-header: no;
mso-page-border-surround-footer: no;
}
#page Section1
{
size:841.9pt 595.3pt;
mso-page-orientation:landscape;
margin: 0.7cm 0.7cm 0.7cm 0.7cm;
mso-header-margin: 42.55pt;
mso-footer-margin: 49.6pt;
mso-paper-source: 0;
layout-grid: 18.0pt;
}
div.Section1
{
page: Section1;
}
</style>
<div class="Section1"></div>
For Print layout use this code....
string strBody = string.Empty;
strBody = #"<html xmlns:o='urn:schemas-microsoft-com:office:office' " +
"xmlns:w='urn:schemas-microsoft-com:office:word'" +
"xmlns='http://www.w3.org/TR/REC-html40'>";
strBody = strBody + "<!--[if gte mso 9]>" +
"<xml>" +
"<w:WordDocument>" +
"<w:View>Print</w:View>" +
"<w:Zoom>100</w:Zoom>" +
"</w:WordDocument>" +
"</xml>" +
"<![endif]-->";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.ms-word";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=ContentDocument.doc");
StringBuilder htmlCode = new StringBuilder();
htmlCode.Append("<html>");
htmlCode.Append("<head>"+strBody+" <style type=\"text/css\">body {font-family:arial;font-size:14.5;}</style></head>");
htmlCode.Append("<body>");
... populate htmlCode ...
htmlCode.Append("</body></html>");
HttpContext.Current.Response.Write(htmlCode.ToString());
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
I have not tried it myself but dont see the reason why it should not work
If you are already writing your html then show it as Word document, why not use css for page orientation like this :
#media screen and (orientation:landscape) {
body { opacity: 0; }
}
Related
This is my grid which is dynamic. It is saving customer description against each checkbox. That is, if I mark the checkbox against Individual then it saves Y in my database otherwise N. so Now I just want to show tick on checkboxes that are saved Y in the database. Below is the code for my dynamic grid:
public string getCustomerStateGrid()
{
string html = ""; int Count = 1;
DataTable dt = getDataTableFromQuery(#"select Id,cuscheckbox,CustomerDescription from CustomerState3");
html = "<h2> Customer State </h2><br/><table class=\"display unbreakable\" id=\"tblCustomerDetail\" style=\"width:100%; border-collapse: collapse;\"><thead>";
#region Header
html += "<tr><th height='40' class=\"Greyheader\" style=\"width:5%\">S.No</th>";
html += "<th height='40' class=\"Greyheader\" style=\"width:30%\">Customer Status</th>";
html += "<th height='40' class=\"Greyheader\" style=\"width:15%\">Customer Description</th>";
//html += "<th class=\"Greyheader\" style=\"width:12%\">Action</th>";
html += "</tr></thead>";
#endregion
#region Body
html += "<tbody>";
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
html += "<tr class=\"GreyBorder\" id='tblCustomerDetail_" + dr["Id"].ToString() + "' pkid=\"" + dr["Id"].ToString() + "\" class=\"DataRow\">";
html += "<td class=\"GreyBorder\" style=\"text-align:center !important;\">" + Count + "</td>";
html += "<td class=\"GreyBorder\"><input id='txtcuscheckbox_" + dr["Id"].ToString() + "' type=\"checkbox\" style=\" text-align: right; width:95;\" value='" + dr["cuscheckbox"].ToString() + "' class=\"mediumTextField Customer Status\" /></td>";
html += "<td class=\"GreyBorder\"><input id='txtCustomerDescription_" + dr["Id"].ToString() + "' type=\"textbox\" style=\" text-align: right; width:95;\" value='" + dr["CustomerDescription"].ToString() + "' class=\"mediumTextField Customer Description\" /></td>";
html += "</tr>";
Count++;
}
}
else
{
html += "<tr class=\"GreyBorder\" ><td style=\"text-align:center !important;\" class=\"GreyBorder\" colspan='6'>No Data.</td></tr>";
html += "</tr>";
}
html += "</tbody>";
#endregion
html += "<tfoot><tr class='GreyBorder'>";
html += "<td class='GreyBorder' colspan='2'></td> ";
html += "</tr></tfoot>";
html += "</table><br/>";
return html.ToString();
}
I just want to customize this line of code
html += "<td class=\"GreyBorder\"><input
id='txtcuscheckbox_" + dr["Id"].ToString() + "'
type=\"checkbox\"
style=\" text-align: right; width:95;\" value='" + d
dr["cuscheckbox"].ToString() + "' class=\"mediumTextField
Customer Status\" /></td>";
so that it shows tick on checkbox. Can anyone modify my code to achieve this result? Is there any way we can do using ternary operator?
Well in essence you need:
var isChecked = 'Y';
html += isChecked == 'Y' ? "<input type=\"checkbox\" checked>" : "<input type=\"checkbox\">";
However, you are mixing front-end with back-end logic. Wouldnt it better to create a JSON endpoint that returns the data to the front-end and have the front-end generate the HTML?
EDIT:
To modify the current logic you could replace the line for creating the textbox with something like this:
var isChecked = dr["cuscheckbox"].ToString().ToUpper() == "Y" ? "checked" : string.Empty;
html += $"<td class=\"GreyBorder\"><input id='txtcuscheckbox_{dr["Id"].ToString()}' type=\"checkbox\" style=\" text-align: right; width:95;\" class=\"mediumTextField Customer Status\" {isChecked}/></td>";
I'm creating emails that has to be sent out to technicians. There are about 12 emails (only one will be sent out depending on which printer model was chosen). The emails everything is sending out fine. The only problem I'm having is that the images are not displaying, they are showing as attachments with a .bin extention. I'm using a case statement to send out the emails. Any help on what I'm doing wrong will be greatly appreciated. Thanks.
This is how my code looks like:
In case statement:
string headerPath = Server.MapPath("~\\Images\\EmailImages\\1022_03.png");
LinkedResource img1022_03 = new LinkedResource(headerPath);
img1022_03.ContentId = "1022_03";
string tonerPath = Server.MapPath("~\\Images\\EmailImages\\TonerSignature.png");
LinkedResource TonerSignature = new LinkedResource(tonerPath);
TonerSignature.ContentId = "TonerSignature";
string img1022_11Path = Server.MapPath("~\\Images\\EmailImages\\1022_11.png");
LinkedResource img1022_11 = new LinkedResource(img1022_11Path);
img1022_11.ContentId = "1022_11";
AlternateView avDefault = AlternateView.CreateAlternateViewFromString(SendOMD(), null, MediaTypeNames.Text.Html);
avDefault.LinkedResources.Add(img1022_03);
avDefault.LinkedResources.Add(TonerSignature);
avDefault.LinkedResources.Add(img1022_11);
Mail.AlternateViews.Add(avDefault);
This code is inside a case statement of default. Outside the case I add the smtp details:
System.Configuration.Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration("~/web.config");
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
if (mailSettings != null)
{
int port = mailSettings.Smtp.Network.Port;
string host = mailSettings.Smtp.Network.Host;
string password = mailSettings.Smtp.Network.Password;
string username = mailSettings.Smtp.Network.UserName;
}
SmtpClient SMTP = new SmtpClient();
SMTP.Send(Mail);
This is what my email method looks like:
private string SendOMD()
{
string techType = radTechnicianType.SelectedValue.ToString();
string techString = "";
if (techType == "Field Technician")
techString = "Please send a technician to replace the toner on the above mentioned machine.";
else if (techType == "Onsite technician")
techString = "Please replace the toner on the above mentioned machine.";
else
techString = "Please send a technician to replace the toner on the above mentioned machine.";
StringBuilder stringBuilt = new StringBuilder();
stringBuilt.AppendLine(#"<style type=""text/css"">");
stringBuilt.AppendLine(".divStyle { font-family:Verdana,sans-serif, Arial, Helvetica; font-size:10pt; font-weight: bold; }");
stringBuilt.AppendLine(".par { font-family:Verdana,sans-serif, Arial, Helvetica; font-size:10pt; width:658px; }");
stringBuilt.AppendLine("table { border: 1px solid #000; border-collapse: collapse; font-family:Verdana; font-size:10pt; background-color:#dcdcdc; }");
stringBuilt.AppendLine("table td { border-left: 1px solid #000; font-family:Verdana,sans-serif, Arial, Helvetica; font-size:10pt; background-color:snow; border-bottom: 1px solid #000; padding-left:2px; margin-left:2px; padding-right:5px; margin-right:5px; }");
stringBuilt.AppendLine("table td:first-child { border-left: none; font-family:Verdana,sans-serif, Arial, Helvetica; font-size:10pt; background:#dcdcdc; background-color:#dcdcdc; border-bottom: 1px solid #000; }");
stringBuilt.AppendLine("</style>");
stringBuilt.AppendLine(#"<img alt="" src=""cid:1022_03"" width=""817"" height=""123"" />");
stringBuilt.AppendLine("<br/>");
stringBuilt.AppendLine(#"<p class=""par"">Dear " + txtClient.Text.Trim() + ",</p>");
stringBuilt.AppendLine("Details:");
stringBuilt.AppendLine("<br/>");
stringBuilt.AppendLine("<table>");
stringBuilt.AppendLine(#"<tr><td style=""background-color:#dcdcdc; widht:350px;"" >Model: </td><td style=""widht:250px;""> " + lstModelType.SelectedValue.ToString() + " </td></tr>");
stringBuilt.AppendLine(#"<tr><td style=""background-color:#dcdcdc; widht:350px;"" >Serial No: </td><td style=""widht:250px;""> " + txtSerial.Text.Trim() + " </td></tr>");
stringBuilt.AppendLine(#"<tr><td style=""background-color:#dcdcdc; widht:350px;"" >IP Address: </td><td style=""widht:250px;""> " + txtIPAddress.Text.Trim() + " </td></tr>");
stringBuilt.AppendLine(#"<tr><td style=""background-color:#dcdcdc; widht:350px;"" >AD Sharename: </td><td style=""widht:250px;""> " + txtADSharename.Text.Trim() + " </td></tr>");
stringBuilt.AppendLine(#"<tr><td style=""background-color:#dcdcdc; widht:350px;"">Department: </td><td style=""widht:250px;""> " + txtDepartment.Text.Trim() + " </td></tr>");
stringBuilt.AppendLine(#"<tr><td style=""background-color:#dcdcdc; widht:350px;"">Colour: </td><td style=""widht:250px;""> " + lstColour.SelectedValue.ToString() + " </td></tr>");
stringBuilt.AppendLine("</table>");
stringBuilt.AppendLine(#"<p class=""par""><em>" + techString + "</em></p>");
stringBuilt.AppendLine("<br/>");
stringBuilt.AppendLine(#"<div class=""divStyle""> Regards, ");
stringBuilt.AppendLine("<br/>");
stringBuilt.AppendLine(lstApprover.SelectedValue.ToString());
stringBuilt.AppendLine("</div>");
stringBuilt.AppendLine(#"<img alt="" src=""cid:TonerSignature"" width=""300"" height=""70"" />");
stringBuilt.AppendLine("<br/>");
stringBuilt.AppendLine(#"<img alt="" src=""1022_11"" width=""815"" height=""54"" />");
return stringBuilt.ToString();
}
You need to Add mime type to your resources.
for ex : LinkedResource img1022_11 = new LinkedResource(img1022_11Path,MediaTypeNames.Image.Gif);
you can add Jpg, Tiff, Gif images, for png files there is a workaround.
use this.
htmlView.LinkedResources.Add(
new LinkedResource("../EmailTemplate/ContactDetails.png")
{
ContentId = "ContactDetails",
TransferEncoding = TransferEncoding.Base64,
ContentType = new ContentType("image/png")
});
instead of Server.MapPath use website path to get the images
I am just trying to add an image to my pdf document using XMLWorker. but for some reason its wanting a close img tag. but even when i put one in it still fails.
C# CODE
Byte[] bytes;
using (var ms = new MemoryStream())
{
using (var doc = new Document(PageSize.A4.Rotate()))
{
using (var writer = PdfWriter.GetInstance(doc, ms))
{
//Open the document for writing
doc.Open();
//Our HTML and CSS
string exampleHtml = #"<div style='position: relative; width: 100%'>" +
"<img src='/Content/images/certificate.jpg'><img>" +
"<div style='position: absolute; top: 100px; left: 100px; width: 800px; height: 550px; text-align: center;'>" +
"<h1>" +
"<img src='/Content/images/CertTitle.png' alt='CERTIFICATE PDF' style='width: 800px;'/>" +
"</h1>" +
"<p>" +
"The School certifies that<br/>" +
"<h2>FIRSTNAME LAST NAME TITLE</h2>" +
"has participated in the class titled<br />" +
"<h2>COURSCODE - COURSENAME</h2>" +
"This activity was designated for # Credit(s)™" +
"</p>" +
"<div style='float: left; position: absolute; bottom: 50px;'>" +
"<i>Date issued: DATE<br/></i><img src='Content/images/ceo-signature.jpg' style='border-bottom: solid #000 1px;'>" +
"</div>" +
"</div>" +
"</div>";
using (var srHtml = new StringReader(exampleHtml))
{
//Parse the HTML
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml); //right here is where it crashes ({"Invalid nested tag div found, expected closing tag img."} {"The document has no pages."}
}
doc.Close();
}
}
bytes = ms.ToArray();
}
var testFile = HttpContext.Server.MapPath("~/Content/documents/UserCertificates/test.pdf"); ;
System.IO.File.WriteAllBytes(testFile, bytes);
Response.AddHeader("Content-Disposition", "inline; filename=test.pdf");
return File(testFile, "application/pdf");
I've never used closing img tags, so I'm curious if I'm doing something wrong here?
As far as I know img tag be like this < img src="" />
but you wrote it like this < img src="" >< img>
Your image tag is not being closed correctly. To do it properly, you need to change <img src='...'><img> to either <img src='...'/> or <img src='...'></img>.
See How to close tag properly answer by M. Rabe
I want export data from DataTable into excel file using Response.Write.
However some of the data missing from the excel file. Can help me fix this.
I already try create html using StringBuilder and nothing wrong with the loop, can get all the data, only when export to excel it's missing. Please help me with this.
Response.Buffer = true;
Response.ClearContent();
Response.Write(HEADER);
Response.Write(STYLE);
Response.Write("</head><body><table border=\"0\" style=\"font-size:11pt\"><tr>");
Response.AddHeader("content-disposition", attachment);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Response.Write(strTitle);
Response.Write("</tr>");
Response.Write("<tr><td colspan=3>From Date: " + lblFromDate.Text + " To: " + lblToDate.Text + "</td></tr>");
Response.Write("<tr><td colspan=9>Protocol: " + lblProtocol.Text + "</td></tr>");
Response.Write("<tr><td colspan=9>Production Line: " + lblPL.Text + "</td></tr>");
Response.Write("<tr></tr></table>");
Response.Write("<table border=\"1\" style=\"font-size:11pt\">");
Response.Write("<tr>");
for (int i = 0; i < summaryreporttable.Columns.Count - 2; i++)
{
Response.Write(" <th>" + summaryreporttable.Columns[i].ToString() + "</th>");
}
Response.Write("</tr>");
for (int r = 0; r < summaryreporttable.Rows.Count; r++)
{
Response.Write("<tr>");
Response.Write("<td>"+r+"</td>");
for (int i = 0; i < summaryreporttable.Columns.Count - 2; i++)
{
if (summaryreporttable.Columns[i].ToString() == "Issue Date")
{
//Response.Write("<td class=\"x167\" valign=\"top\">" + summaryreporttable.Rows[r][i] + "</td>");
Response.Write(String.Format("<td class=\"x167\" valign=\"top\"> {0} </td>", summaryreporttable.Rows[r][i]));
}
else
{
//Response.Write("<td class=\"x169\" valign=\"top\">" + summaryreporttable.Rows[r][i] + "</td>");
Response.Write(String.Format("<td class=\"x169\" valign=\"top\"> {0} </td>", summaryreporttable.Rows[r][i]));
}
}
Response.Write("</tr>");
Response.Flush();
}
Response.Write("</table></body></html>");
}
catch (Exception ex)
{
}
finally
{
Response.End();
}
As you can see, the data between is missing.
I want to explain our way. This is usefull then yours.
1-we have a literal in the web page like this
<asp:Literal ID="lblData" runat="server" />
2-In the code we have some string variables. And we grow with html like drawing on a screen.
// our html datas
// you can use foreach for repating
sTEXT = #"<table class='table'><thead>";
sTEXT += #"<th>";
sTEXT += #"Caption A";
sTEXT += #"</th>";
sTEXT += #"</thead>";
sTEXT += #"<tr>";
sTEXT += #"<td>abcdef</td>";
sTEXT += #"<td>ghjklm</td>";
sTEXT += #"</tr>";
sTEXT += #"</table>";
// our screen literaldata sets
lblData.Text = sTEXT;
// excel output code
// carefull end of the "Responce.Write"" sentence
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1254");
Response.Charset = "windows-1254";
Response.AppendHeader("content-disposition", "attachment;filename=ExportedHtml.xls");
Response.Buffer = true;
this.EnableViewState = false;
Response.ContentType = "application/vnd.ms-excel";
Response.Write("<style> TABLE { border: 1px solid gray; } TD { border: 1px solid gray; } </style> " + lblData.Text);
Response.End();
I have images stored as Base64, but I'm having trouble displaying them. I'm using ASP.NET, and here is part of the code:
int visitorId = int.Parse(Request.QueryString["id"]);
classes.Visitor visitor = new classes.Visitor(visitorId, PageExtension_CurrentUser.Community.Id);
StringBuilder sb = new StringBuilder();
sb.Append("<table>");
sb.Append(#"<tr><td colspan=""2""><div style=""width:320px; height:240px; border: 1px dotted #000;"">");
if (visitor.VisitorImage != "")
{
sb.Append(#"<img style=""width:320px; height:240px;"" alt="" src=""data:image/jpeg;base64, " + visitor.VisitorImage + #""" />");
}
else
{
sb.Append(#"No image");
}
sb.Append("</div></td></tr>");
sb.Append("<tr><td style='width:200px;'><b>Visitor Name</b></td><td>" + visitor.GetFullname() + "</td></tr>");
sb.Append("<tr><td><b>Company/Address</b></td><td>" + visitor.AddressOrCompany + "</td></tr>");
Interesting to note, is that:
the DIV with dotted border displayed, however no image is shown.
The remaining are not printed out??
The image data is fine, I have already tested it on http://base64online.org/decode/ and i see the image im using for testing.
I am assuming it is the data, but why is it not shown? Any ideas?
This line of code is wrong:
sb.Append(#"<img style=""width:320px; height:240px;"" alt="" src=""data:image/jpeg;base64, " + visitor.VisitorImage + #""" />");
It should be:
sb.Append(#"<img style=""width:320px; height:240px;"" alt="""" src=""data:image/jpeg;base64, " + visitor.VisitorImage + #""" />");