Export Asp.Panel to PDF? - c#

I want to export Asp.Panel content(text, GridViews) with CSS to PDF from C#.NET. I am using iTextSharp and RenderControl with Asp.Panel, but CSS is not rendered in PDF.
How can I solve this problem(with iTextSharp(if is possible) or in another way) ?
This code generate PDF file:
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
StringReader sr;
string fileName = "C://pdf/GridView.pdf";
var doc = new Document(PageSize.A3, 45, 5, 5, 5);
var pdf = fileName;
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(pdf, FileMode.Create));
doc.Open();
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssResolver.AddCssFile(Server.MapPath("Content/PDFs.css"), true);
IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(doc, writer)));
XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser xmlParse = new XMLParser(true, worker);
this.pnlTabs.RenderControl(htw);
sr = new StringReader(sw.ToString());
xmlParse.Parse(sr);
xmlParse.Flush();
doc.Close();
This is the ASP Panel I want to send to PDF:
<asp:Panel ID="pnlTabs" runat="server" CssClass="TeamTabs">
<div class="repHeader">
<div class="row">
<div style="padding:12px;border-bottom:1px solid #ddd;margin-bottom:1px;overflow:hidden;">
<div class="col4">
<p> <font size="4.5"> <b>Client Scorecard</b> </font> <br>
Run Date: 11/1/2013 4:20:01 AM <br>
For Dates: 9/12013 - 10/31/2013 <br>
Oct 2013 - Filed to Service Complete: 31.18 <br>
Oct 2013 - State Average: 34.45
</p>
</div>
</div>
<p style="text-align: center; margin-top:1px"> <font size="3.5"> <b> BECKER POLIAKOFF (CORAL GABLES) </b>
</font> </p>
</div>
</div>
<div class="row" style="padding-bottom:36px;">
<div class="col9 col-first">
<asp:GridView ID="gvDashRep_Left_first" runat="server" ></asp:GridView>
<asp:GridView ID="gvDashRep_Left_second" runat="server" ></asp:GridView>
<asp:GridView ID="gvDashRep_Left_third" runat="server" ></asp:GridView>
</div>
<div class="col3">
<asp:GridView ID="gvDashRep_Right_first" runat="server" ></asp:GridView>
<asp:GridView ID="gvDashRep_Right_second" runat="server" ></asp:GridView>
<asp:GridView ID="gvDashRep_Right_third" runat="server" ></asp:GridView>
</div>
<p style="text-align: center; margin-top:1px"> <font size="2.5"> *For B/W, items with an asterisk indicate that higer number for Octomber 2013 is considered better. </font> </p>
<div class="col12 col-first">
<asp:GridView ID="gvComments" runat="server" ></asp:GridView>
</div>
</div>
</asp:Panel>
CSS File
div.row { min-height: 1%; width: 966px; margin: 0 auto; overflow: hidden; }
div.col3 {width:219px; float: left; margin-left: 30px;}

There is an additional download (XMLWorker) if you want to export to pdf using ITextSharp with css. You can get the XMLWorker from here
To set this up to apply your css you need to do something like the following
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
StringReader sr;
string fileName = Server.MapPath("PATH TO PDF");
var doc = new Document(PageSize.A3, 45, 5, 5, 5);
var pdf = fileName;
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(pdf, FileMode.Create));
doc.Open();
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssResolver.AddCssFile(Server.MapPath("PATH TO CSS"), true);
IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(doc, writer)));
XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser xmlParse = new XMLParser(true, worker);
control.RenderControl(htw);
sr = new StringReader(sw.ToString());
xmlParse.Parse(sr);
xmlParse.Flush();
Replace the PATH TO PDF (loacation to save the file) and PATH TO CSS (location were your css file is) with the relevant file paths. When I had to do this the css file had to be a external file (.css).

Related

Opening a file in a new tab of the web browser

I have a view which shows a list of xml files in a directory. Also i have a button which would display the content of the file name selected in the browser. Currently its showing the content in a the same tab. But i want to display it in a new tab of the browser..
for example if i select two file names from the list, then it should open different tab for both the files..
Please find the code below.
public ActionResult ViewFile(string[] Name)
{
byte[] ImageData = null;
for (int i = 0; i < Name.Length; i++)
{
string filepath = holdpath + #"\" + Name[i];
string result;
using (StreamReader streamReader = new StreamReader(filepath))
{
result = streamReader.ReadToEnd();
}
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
Document document = new Document(PageSize.A4, 10, 10, 10, 10);
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
Paragraph paragraph = new Paragraph();
paragraph.Add(result);
document.Add(paragraph);
document.Close();
ImageData = memoryStream.ToArray();
}
}
Response.AppendHeader("Content-Disposition", "inline; filename=MyFile.pdf");
return File(ImageData, "application/pdf");
}
Please note that i am using itextsharp because the file also needs to be downloaded as pdf if required
I have added the View here
#model IEnumerable<FileInfo>
#{
ViewBag.Title = "files";
}
<h2>Held files</h2>
#using (Html.BeginForm())
{
<div style="border:solid;width:100%;overflow-x:auto;">
<table align="center" style="width:100%">
<thead>
<tr>
<th>File Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (FileInfo file in Model)
{
<tr>
<td>
<input type="checkbox" name="Name" value="#file.Name" />
#file.Name
</td>
<td>
#Html.ActionLink("View", "ViewFile", "HoldFiles", new { Name = file.Name },
new { #class = "btn btn-primary btn-sm", target = "_blank" })
</td>
</tr>
}
</tbody>
</table>
</div>
}
In your view, put target="_blank" on your anchor element.
For example:
Open in new tab
or if using razor:
#Html.ActionLink("Text", "ActionMethodName", "ControllerName", new { id = Model.Id }, new { #class = "btn btn-primary btn-sm", target = "_blank" })

Convert HTML table to PDF(itextsharp)

I have got trouble parsing HTML table to PDF. Table is spreading and it's go out of page. How can I it fix?
I'm using HTMLWorker. It's converting HTML to PDF is good, but that table...
Here is my code(it's in method):
StyleSheet ST = new StyleSheet();
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial Unicode MS");
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);
HTMLWorker worker = new HTMLWorker(doc);
worker.SetStyleSheet(ST);
worker.StartDocument();
worker.Parse((TextReader)File.OpenText(xmlNode.ChildNodes[i].Attributes["path"].Value.ToString()));
worker.EndDocument();
worker.Close();
How can I tell HTMLWorker so it's create table in PDF is ok? Can I give to worker size of table?
Or maybe should I use other "workers" for example XMLWorkerHelper or XMLWorker. When I use XMLWorker or XMLWorkerHelper I can't set to "workers" my font(I need Cyrillic, and just don't understand how add font). And when I use this "workers" I have the same problem with table.
code with XMLWorker:
//working with XMLWorker
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
cssResolver.AddCss(fileCSS,true);
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
PdfWriterPipeline pdf = new PdfWriterPipeline(doc, writer);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
p.Parse(new FileStream(fileHTML, FileMode.Open, FileAccess.Read));
code with XMLWorkerHelper:
string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
FontFactory.Register(arialuniTff);
using (var msCss = new MemoryStream(Encoding.UTF8.GetBytes(fileCSS)))
{
using (FileStream fsHtml = new FileStream(fileHTML,FileMode.Open,FileAccess.Read))
{
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, fsHtml, msCss, FontFactory.FontImp as IFontProvider);
}
}
What can You advise to me?
Thank you!
Update
I found one article about XMLWorkerHelper with Cyrillic, but my code doesn't work. I can't understand why.
My code:
using (var msCss = new MemoryStream(Encoding.UTF8.GetBytes(fileCSS)))
{
using (FileStream fsHtml = new FileStream(fileHTMLTest,FileMode.Open,FileAccess.Read))
{
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontProvider.Register(arial);
FontFactory.FontImp = fontProvider;
doc.Add(new Paragraph("XMLWorkerHelper"));
doc.Add(new Paragraph("XMLWorkerHelper вот это да!"));
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, fsHtml, msCss, Encoding.UTF8, fontProvider);
}
}
My HTML code(test):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"content="text/html;charset=utf-8"></meta>
<title></title>
</head>
<body>
<p>Привет Мир!</p>
<table border="0">
<tr>
<td><h2 align="center">Акционерное общество «OOO "Ландыш"»</h2></td>
</tr>
<tr>
<td>
<p align="center">Тема:</p>
<p align="center">[THEME]</p>
</td>
</tr>
<tr>
<td>
<div align="right">
<p>Выполнил:</p>
<p>[AUTHOR]</p>
</div>
</td>
</tr>
<tr>
<td><p align="center">[CITY] [YEAR]г.</p></td>
</tr>
</table>
<table border="1">
<tr>
<td>Row 1, Column 1; Столбец 1, Строка 1 </td>
<td>Row 1, Column 2; Столбец 1, Строка 2</td>
</tr>
<tr>
<td>Row 2, Column 1; Столбец 2, Строка 1</td>
<td>Row 2, Column 2; Столбец 2, Строка 2</td>
</tr>
</table>
<img src="img.jpg" alt="picture"></img>
</body>
</html>

GMail not showing inline-images (cid) i'm sending with System.Net.Mail

When I send an email via outlook or gmail to a gmail email address I can add inline-images which are directly shown in the gmail webinterface:
Relevant raw mail-header and raw body parts of the working email:
--089e0158b6909948880520cef593
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
<div dir=3D"ltr">Image there?<div><img src=3D"cid:ii_if3zqhar0_15014363be0a=
41b2" width=3D"10" height=3D"3"><br>=E2=80=8BHope so!<br></div></div>
--089e0158b6909948880520cef593--
--089e0158b69099488c0520cef594
Content-Type: image/png; name="test.png"
Content-Disposition: inline; filename="test.png"
Content-Transfer-Encoding: base64
Content-ID: <ii_if3zqhar0_15014363be0a41b2>
X-Attachment-Id: ii_if3zqhar0_15014363be0a41b2
iVBORw0KGgoAAAANSUhEUgAAAAoAAAADCAIAAAAlXwkiAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJ
bWFnZVJlYWR5ccllPAAAADFJREFUeNpi+A8BDCf/wwDD/1VIbBABIudDmAchokwgag9QAiwHVcsM
Z/5fCdYJEGAAuthJ+AVi5KgAAAAASUVORK5CYII=
--089e0158b69099488c0520cef594--
Full working raw email: Working raw-email.
However, when I send such an email via System.Net.Mail from .NET it is not working in the gmail webinterface but any other email client (outlook, iphone, etc.):
Relevant raw mail-header and raw-body parts of non-working email:
----boundary_3_6a0761ee-57e2-4bdd-b1f1-7302b3c8a7a1
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable
Image there?<br /><img src=3D"cid:test.png#71236720.91827344" /><=
br />Hope so!
----boundary_3_6a0761ee-57e2-4bdd-b1f1-7302b3c8a7a1--
----boundary_5_979e00c0-3fb9-46a0-b25c-1cee82cc15eb
Content-Type: image/png; name=test.png
Content-Transfer-Encoding: base64
Content-Disposition: inline; filename=test.png
Content-ID: <test.png#71236720.91827344>
iVBORw0KGgoAAAANSUhEUgAAAAoAAAADCAIAAAAlXwkiAAAAGXRFWHRTb2Z0d2FyZQBB
ZG9iZSBJbWFnZVJlYWR5ccllPAAAADFJREFUeNpi+A8BDCf/wwDD/1VIbBABIudDmAch
okwgag9QAiwHVcsMZ/5fCdYJEGAAuthJ+AVi5KgAAAAASUVORK5CYII=
----boundary_5_979e00c0-3fb9-46a0-b25c-1cee82cc15eb--
Full non-working raw email: Nonworking raw-email.
This is my code to send inline-images:
SmtpClient client = new SmtpClient("real.server.on.the.internet");
MailMessage mail = new MailMessage("Flattiverse <xxx#flattiverse.com>", "Ghostie <xxx#gmail.com>");
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
AlternateView plainView = AlternateView.CreateAlternateViewFromString("Please view as HTML-Mail.", System.Text.Encoding.UTF8, "text/plain");
plainView.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("Image there?<br /><img src=\"cid:test.png#71236720.91827344\" /><br />Hope so!", System.Text.Encoding.UTF8, "text/html");
htmlView.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
mail.Subject = "7";
Attachment attachment = new Attachment("test.png", "image/png");
attachment.ContentId = "test.png#71236720.91827344";
attachment.ContentDisposition.Inline = true;
attachment.ContentDisposition.DispositionType = "inline; filename=test.png";
mail.Attachments.Add(attachment);
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("working_username", "working_password");
client.Send(mail);
I also tried cid in GMail format (eg. ii_012345678_9abcdef0123456789) and many other things stated in other related questions. (Using ' instead of " in mail body, etc.)
Question: What am I doing wrong that GMail doesn't display my inline-images? How do I need to change my code? Maybe what I want can't be achieved with System.Net.Mail?
The inline-image is ignored in GMail webinterface when added as attachment. When adding the image as alternate view it gets ignored by Outlook.
To add an inline-image compatible to GMail webinterface and Outlook (and iPhone mail client) you have to add it as LinkedResource.
The example code in the question must be fixed like this:
SmtpClient client = new SmtpClient("real.server.on.the.internet");
MailMessage mail = new MailMessage("Flattiverse <info#flattiverse.com>", "Ghostie <matthias.lukaseder.test#gmail.com>");
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
LinkedResource image = new LinkedResource("test.png", "image/png");
image.ContentId = "test.png#71236720.91827344";
image.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
image.ContentType.Name = "test.png#71236720.91827344";
image.ContentLink = new Uri("cid:test.png#71236720.91827344");
AlternateView plainView = AlternateView.CreateAlternateViewFromString("Please view as HTML-Mail.", System.Text.Encoding.UTF8, "text/plain");
plainView.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("Image there?<br /><img src=\"cid:test.png#71236720.91827344\" /><br />Hope so!", System.Text.Encoding.UTF8, "text/html");
htmlView.LinkedResources.Add(image);
htmlView.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
mail.Subject = "15";
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("working_username", "working_password");
client.Send(mail);
I had the same Problem with Pyhon (Django). Solved it by just adding the X-Attachment-Id header:
img.add_header('Content-ID', '<filename.png>')
img.add_header('X-Attachment-Id', 'filename.png')
img.add_header('Content-Disposition', 'inline', filename='filename.png')
message.attach(img)
Hope this helps someone :-)
I had the same issue (in Java, will be same for c#).
Resolved by adding contentId between the “<” and “>”
This one is working on Gmail,yahoo and Outlook.
Add it as LinkedResource.
I have a template called Confirm_Account_RegistrationInd.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Bienvenido Email de {6}</title>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center" valign="top" bgcolor="#fff" style="background-color:lightgray;">
<br>
<br>
<table width="600" border="0" cellspacing="0" cellpadding="0" >
<tr>
<td height="70" align="left" valign="middle"></td>
</tr>
<tr>
<td align="left" valign="top" bgcolor="#564319" style="background-color:#007ebd; font-family:Arial, Helvetica, sans-serif; padding:10px;">
<table>
<tr>
<td>
"<img id="logo" src="miimg_id" alt="logo" style="height: 60px; border: 3px solid #007ebd; border-radius: 43px;" />";
</td>
<td>
<div style="font-size:36px; color:#ffffff;">
<b>{0}</b>
</div>
<div style="font-size:13px; color:lightcyan;">
<b>{1} : {6}</b>
</div>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="left" valign="top" bgcolor="#ffffff" style="background-color:#ffffff;">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center" valign="middle" style="padding:10px; color:#564319; font-size:28px; font-family:Georgia, 'Times New Roman', Times, serif;">
¡Felicitaciones! <small>Estás Registrado.</small>
</td>
</tr>
</table>
<table width="95%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="100%" style="color:darkslategrey; font-family:Arial, Helvetica, sans-serif; padding:10px;">
<div style="font-size:16px;">
Apreciad# {2},
</div>
<div style="font-size:12px;text-align: justify;">
Ha sido creada una cuenta en el sitio.
Todo lo que necesitas es hacer clic en el botón en la parte de abajo (Te tomará solamente un momento)
Este correo es para la verificación de la propiedad del correo elctrónico.
<hr>
<center>
<button type="button" title="Confirmar cuenta" style="background: darkgoldenrod">
<a href="{5}" style="font-size:22px; padding: 10px; color: #ffffff">
Confirmar correo ahora
</a>
</button>
</center>
<hr>
</div>
</td>
</tr>
</table>
<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" style="margin-bottom:15px;">
<tr>
<td align="left" valign="middle" style="padding:15px; font-family:Arial, Helvetica, sans-serif;">
<div style="font-size:20px; color:#564319;">
<b>Por favor manten tus credenciales seguras, para usarlas en el futuro. </b>
</div>
<div style="font-size:16px; color:#525252;">
<b>Correo :</b> {3}
<br />
<b>Nombre de usuario :</b> {3}
<br />
{7}
<br />
</div>
</td>
</tr>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center" valign="middle" style="padding:15px; background-color:#007ebd; font-family:Arial, Helvetica, sans-serif;">
<div style="font-size:20px; color:#fff;">
<b>¡Actualiza tus contraseñas continuamente!</b>
</div>
<br>
<div style="font-size:13px; color:aliceblue;">
<br>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<br>
<br>
</td>
</tr>
</table>
</body>
</html>
The image that i want to show:
"<img id="logo" src="miimg_id" alt="logo" style="height: 60px; border: 3px solid #007ebd; border-radius: 43px;" />";
as you can show the src attribute has a value miimg_id
and into the view i have values to fill {}
I have my method where i will read my view as string, after get data to fill the values, called ReSendEmailAsync
[HttpPost]
public async Task<IActionResult> ReSendEmailAsync([FromBody] string id)
{
string returnUrl = null;
returnUrl = returnUrl ?? Url.Content("~/");
string empleadoNombre = "";
string attach = "";
string logoName = "logo_dif.png";
var user = await _unitOfWork.ApplicationUser.GetFirstOrDefaultAsync(u => u.Id == int.Parse(id), includeProperties: "Empleado");
if (user == null)
{
return Json(new { success = false, message = "Usuario Email" });
}
if (user.EmailConfirmed)
{
return Json(new { success = true, message = "Cuenta ya fue confirmada" });
}
try
{
empleadoNombre = user.Empleado.Nombre;
}
catch (Exception e)
{
}
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user).ConfigureAwait(true);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
protocol: Request.Scheme);
//Customizde email
var PathToFile = _webHostEnvironment.WebRootPath + Path.DirectorySeparatorChar.ToString()
+ "Templates" + Path.DirectorySeparatorChar.ToString()
+ "EmailTemplates" + Path.DirectorySeparatorChar.ToString()
+ "Confirm_Account_RegistrationInd.html";
var subject = "Confirmar Registro de cuenta";
string HtmlBody = "";
using (StreamReader streamReader = System.IO.File.OpenText(PathToFile))
{
HtmlBody = streamReader.ReadToEnd();
}
//{0} Subject
//{1} DateTime
//{2} Name
//{3} Email
//{4} Messaje
//{5} CallBack
//{6} AppName
//{7} Pass
// logo as attach
var PathToImage = _webHostEnvironment.WebRootPath + Path.DirectorySeparatorChar.ToString()
+ "Templates" + Path.DirectorySeparatorChar.ToString()
+ "EmailTemplates" + Path.DirectorySeparatorChar.ToString()
+ logoName;
attach = PathToImage;
string message = $"Por favor confirme su cuenta <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>Clic Aquí</a>.";
string messageBody = string.Format(HtmlBody,
subject,
String.Format("{0:dddd, d MMMM yyyy}", DateTime.Now),
empleadoNombre,
user.Email,
message,
callbackUrl,
"Indicadores",
""
);
try
{
MailRequest mailRequest = new MailRequest();
mailRequest.Body = messageBody;
mailRequest.ToEmail = user.Email;
mailRequest.Subject = "Confirmar su correo";
mailRequest.Attachments = new List<MailAttachment>
{ new MailAttachment{
Name = logoName,
Path = attach
} };
await _mailService.SendEmailAsync(mailRequest);
}
catch(Exception e)
{
return Json(new { success = false, message = "Al enviar email" });
}
return Json(new { success = true, message = "Operación exitosa" });
}
In my class MailService
Main methed is SendEmailAsync where i pass the values to the MailMessage object
but i have another method called Mail_Body that return a AlternateView object
public class MailService : IMailService
{
private readonly MailSettings _mailSettings;
public MailService(IOptions<MailSettings> mailSettings)
{
_mailSettings = mailSettings.Value;
}
public async Task SendEmailAsync(MailRequest mailRequest)
{
MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient();
message.From = new MailAddress(_mailSettings.UserName);
message.To.Add(new MailAddress(mailRequest.ToEmail));
message.Subject = mailRequest.Subject;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.SubjectEncoding = System.Text.Encoding.UTF8;
if (mailRequest.Attachments != null)
{
//int i = 0;
foreach (var attachmentStr in mailRequest.Attachments)
{
message.AlternateViews.Add(Mail_Body(mailRequest.Body, attachmentStr.Path, attachmentStr.Name));
}
}
message.IsBodyHtml = true;
smtp.Port = _mailSettings.Port;
smtp.Host = _mailSettings.Host;
smtp.EnableSsl = _mailSettings.EnableSSL;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(_mailSettings.UserName, _mailSettings.Password);
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
await smtp.SendMailAsync(message);
}
private AlternateView Mail_Body(string strr, string path, string contentId)
{
LinkedResource Img = new LinkedResource(path, "image/png");
Img.ContentId = "logo_img";
strr = strr.Replace("\"miimg_id\"", "cid:logo_img");
AlternateView AV =
AlternateView.CreateAlternateViewFromString(strr, null, MediaTypeNames.Text.Html);
AV.LinkedResources.Add(Img);
return AV;
}
}
the logo image is called logo_dif.png and is located in
finally the result in gmail:

How to display a dynamically created DIV next to another?

I am creating a page that will display log files on a page dynamically as they are created. Here is my front end:
<div id="container">
<asp:UpdatePanel UpdateMode="Conditional" runat="server" ID="ServerUpdates">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
Here is my css:
#container {
width:100%;
display: inline-block;
height:100%;
}
.textboxStatus
{
/*background-image:url('http://placehold.it/15/15');*/
background-repeat:no-repeat;
/* background-position:3px 3px;*/
border:solid 1px black;
padding:20px;
width:600px;
height:500px;
float:left;
clear:left;
/*position:relative;*/
}
/*.textbox input
{
border:none;
background:transparent;
width:100%;
outline: none;
}*/
.textboxURL
{
/*background-image:url('http://placehold.it/15/15');*/
background-repeat:no-repeat;
/* background-position:3px 3px;*/
border:solid 1px black;
padding:20px;
width:575px;
height:475px;
float:right;
/*clear: right;
position:relative;*/
display:inline;
}
Here is my code behind:
protected void CreateDiv(object sender, EventArgs e)
{
string path = #"\\server\d$\websites\Updates\Product\Production\Logs";
//int rowCount = 0;
DirectoryInfo dir = new DirectoryInfo(path);
List<FileInfo> FileList = dir.GetFiles().ToList();
ServerUpdates.ContentTemplateContainer.Controls.Add(new LiteralControl("<asp:GridView runat='server' ID='Grid' AutoGenerateColumns='false'>"));
ServerUpdates.ContentTemplateContainer.Controls.Add(new LiteralControl("<Columns>"));
foreach (FileInfo file in FileList)
{
StreamReader sr = new StreamReader(new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
// string[] findStatus = System.IO.Directory.Exists(path, "codepush.log.*", System.IO.SearchOption.TopDirectoryOnly);
// string[] findURL = System.IO.Directory.GetFiles(path, "sql.output.log.*", System.IO.SearchOption.TopDirectoryOnly);
bool findStatus = (file.Name.Contains("codepush.log.")) ? true : false;//File.Exists(Path.Combine(path, ".txt"));
bool findURL = (file.Name.Contains("sql.output.")) ? true : false;
if (findStatus == true)
{
//ServerUpdates.ContentTemplateContainer.Controls.Add(new LiteralControl(String.Format("<br /><div class=\"statusLog\"><asp:TextBox runat=\"server\" id=\"tbStatus{0}\"/> </div><div class=\"urlLog\"></div>", count)));
//(TextBox)ServerUpdates.ContentTemplateContainer.FindControl("tbStatus" + count.ToString());
ServerUpdates.ContentTemplateContainer.Controls.Add(new LiteralControl(string.Format("<asp:BoundField Datafield={0} /><div class='textboxStatus'>", rowCount)));
TextBox txt = new TextBox();
txt.TextMode = TextBoxMode.MultiLine;
txt.Wrap = false;
txt.Width = 600;
txt.Height = 500;
while (!sr.EndOfStream)
txt.Text = txt.Text + sr.ReadLine() + "\r\n";
//Panel txt = new Panel();
//txt.ScrollBars = ScrollBars.Vertical;
//txt.Wrap = true;
ServerUpdates.ContentTemplateContainer.Controls.Add(txt);
ServerUpdates.ContentTemplateContainer.Controls.Add(new LiteralControl("</div>"));
ServerUpdates.ContentTemplateContainer.Controls.Add(new LiteralControl("</Columns>"));
}
if (findURL == true)
{
//ServerUpdates.ContentTemplateContainer.Controls.Add(new LiteralControl(String.Format("<br /><div class=\"statusLog\"><asp:TextBox runat=\"server\" id=\"tbStatus{0}\"/> </div><div class=\"urlLog\"></div>", count)));
//(TextBox)ServerUpdates.ContentTemplateContainer.FindControl("tbStatus" + count.ToString());
ServerUpdates.ContentTemplateContainer.Controls.Add(new LiteralControl("<Columns>"));
ServerUpdates.ContentTemplateContainer.Controls.Add(new LiteralControl(string.Format("<asp:BoundField Datafield={0} /><div class='textboxURL'>", rowCount)));
TextBox txt = new TextBox();
txt.TextMode = TextBoxMode.MultiLine;
txt.Wrap = false;
txt.Width = 575;
txt.Height = 475;
while (!sr.EndOfStream)
txt.Text = txt.Text + sr.ReadLine() + "\r\n";
//Panel txt = new Panel();
//txt.ScrollBars = ScrollBars.Vertical;
//txt.Wrap = true;
ServerUpdates.ContentTemplateContainer.Controls.Add(txt);
ServerUpdates.ContentTemplateContainer.Controls.Add(new LiteralControl("</div>"));
ServerUpdates.ContentTemplateContainer.Controls.Add(new LiteralControl("</Columns>"));
}
//rowCount++;
}
ServerUpdates.ContentTemplateContainer.Controls.Add(new LiteralControl("</asp:GridView>"));
}
My issue is that it is not displaying the URL div next to the first Status div and so fourth. The URL div displays last.
I need it to display the URL div next to the Status div for each div (file).
I have been trying GridView so any suggestions would be helpful.
I am not sure I understand the problem, but to your issue " it is not displaying the URL div next to the first Status div and so fourth. The URL div displays last," I recommend the following:
<div class="row">
<div class="textboxStatus">
</div>
<div class="textboxURL">
</div>
</div>
Apply float: left; to both textboxStatus and textboxURL. I understand, this is dynamically generated, but instead, why not AJAX to fetch the content and then simply fill it?
You can easily use AJAX with webforms like so:
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
In your ".textboxStatus" css-class you have defined a "float:left" and are clearing the float at the same time with "clear:left".
Remove both attributes and in ".textboxURL" replace "float:right" with "float:left" and you should be fine.
first we will define the main div or body in which other will be contained for that div the style will be
#maindiv{
width: 100%;
font-size: 12px;
overflow: hidden;
background: #ccc
}
in your case it will be "container"
now when you are adding the divs as
then first div style will be
#leftdiv {
float: left;
width: 33%;
background-color: #bbb;
}
after that set the width of each div and put the width to the style of that d
#nextdiv {
float: left;
background-color: #eee;
width: 33%;
}
and so on..
You should generate a <TABLE> with one line <TR> and multiple columns <td> instead of generating an Asp.net Gridview control by Literal controls.
Remember to write Html tags when you use Literal controls
Example of final html:
<Table>
<tr>
<td>First div inside</td>
<td>Second div inside</td>
...
</tr>
</Table>

How to increase the table height from the code behind file in ASP.Net while using StringWriter?

I am generating one PDF from the Code Behind File using StringWriter and HtmlTextWriter.
The Coding is given below:
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView gv = new GridView();
gv.BorderStyle = BorderStyle.None;
gv.DataSource = dt2;
gv.DataBind();
gv.RenderControl(hw);
string str = sw.ToString();
string str1 = "<table width='100%' border='1'><tr><td><img src='" + Server.MapPath("App_Themes/Ribo/ribologo.bmp") + "' alt='' width=75px height=75px /></td><td align='center' colspan='8' font size='3'><h2><b>MATERIAL RECEIPT CUM INSPECTION REPORT(MRIR)</b></h2</td></tr>";
str1 += "<tr><td font size='3'>MRIR NO</td><td font size='3'>Date</td><td align='center' font size='3'>JOB DESCRIPTION</td><td font size='3'>SUPPLIER NAME</td><td font size='3'>DC NO</td><td font size='3'>DATE</td><td font size='3'>LWB NO/DATE</td><td font size='3'>INVOICE NO</td><td font size='3'>DATE</td></tr>";
str1 += "<tr><td font size='3'>" + txtMRVNumber.Text + "</td><td font size='3'></td><td font size='3'></td><td font size='3'>" + TDSSVendor.Text + "</td><td font size='3'>" + txtDCNumber.Text + "</td><td font size='3'></td><td font size='3'>" + txtLWBNo.Text + "</td><td font size='3'>" + txtInvoiceNo.Text + "</td><td font size='3'></td></tr>";
str1 += "<tr><td rowspan='2' font size='3'>DESCRIPTION</td><td font size='3' colspan='2' align='center'>SIZE(mm)</td><td colspan='6'></td></tr>";
str1 += "<tr><td font size='3' colspan='2'>" + sw + "</td><td colspan='6'></td></tr></table>";
if (str.StartsWith("<div>"))
{
str = str1;
}
System.IO.StringReader sr = new System.IO.StringReader(str);
iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A3.Rotate(), 40f, 10f, 40f, 2f);
iTextSharp.text.html.simpleparser.HTMLWorker htmlparser = new iTextSharp.text.html.simpleparser.HTMLWorker(pdfDoc);
iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
Here, I generated my desired PDF. But the table is displaying at the top of the PDF. So I want to display at the centre of the PDF as well as I want to increase the height of the Table. How to do this?
I tried like the below:
string str1 = "<table **height='100%'** width='100%' border='1'><tr>.....
But it displays as the same. How to increase the height of the table? I need all your suggestions please.
That alone is not going to do it. You can wrap the generated .pdf in another table (1 row, 1 column), and place that table in the sole TD of the new table, then just vertical align (valign='middle') the enclosing TD.
This is the only way I know how to do what you are asking, although I do not know if it will work for you:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<!-- Put this on your presentation page -->
<style type="text/css">
html, body {
margin: 0;
padding: 0;
height: 100%;
border: none;
}
</style>
</head>
<body>
<table style="height: 100%" width="100%" align="center">
<tr>
<td valign="middle" align="center">
<table>
<tr>
<td valign="middle">
<!-- Embed your .pdf here -->
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
from the taking the height of the table u can set parameter of below Document class constructor.
Dim doc As Document = New Document(PageSize.A4, 1, 0, 0, 30)
Hope this will helps you...

Categories