Wednesday, October 9, 2024

Save a PDF generated from html2pdf in C#, MVC , html2pdf , Ajax code

 To save on server or disk a PDF generated from HTML in C# code example, you can use the     html2pdf js script   

html2pdf 

converts any webpage or element into a printable PDF entirely client-side using html2canvas and jsPDF

To use html2pdf is to download dist/html2pdf.bundle.min.js to your project folder and include it in your code with

<script src="html2pdf.bundle.min.js"></script>

C#, MVC

Create new project in visual studio

Step 1: Create a Model Class

csharp
public class pdfdata { public string PDFBase64 { get; set; } public string FileName { get; set; } }


Step 2: Create a Controller

Create a new controller called PdfController.cs

csharp

     public ActionResult Pdf() { return View(); }

// Ajax Call from srcipt
public JsonResult savepdf(pdfdata pdf) { byte[] bytes = Encoding.GetEncoding(28591).GetBytes(pdf.PDFBase64); System.IO.File.WriteAllBytes(@"yourlocation_path/pdf.Filename"+".pdf", bytes); var response = new { success = true, responseText = "Your file Saved successfuly !" }; return Json(response, JsonRequestBehavior.AllowGet); }


Step 3: Create a View

HTML
<button id="btnsavepdf" class="btn btn-primary btn-xs" > Click here to Save </button>
<div name="mycontents"> ... my pdf content <div>

<script src="jquery-3.3.1.min.js" type="text/javascript"></script> <script src="savepdf.js" type="text/javascript"></script> <script src="html2pdf.bundle.min.js" type="text/javascript"></script>

Create a javascript code or in seperate js file like i created

Script
window.addEventListener('load', function () { var btnsavepdf = document.getElementById('btnsavepdf'); function savePdf() { var element = ''; element = document.getElementsByName('mycontents')[0]; var opt = { margin: [2, 2, 2, 2], filename: 'myfile', image: { type: 'jpeg', quality: 0.7 }, html2canvas: { scale: 2, useCORS: true }, jsPDF: { format: 'a4', unit: 'mm' }, }; html2pdf().from(element).set(opt).toPdf().get('pdf').then(function (pdf) { pdf.setFontSize(10); }).get('pdf').then(function (pdf) { var pdfBase64 = pdf.output(); console.log(pdfBase64); var pdfcontent = {}; pdfcontent.PDFBase64 = pdfBase64; pdfcontent.FileName = fileName; $.ajax({ type: "POST", url: "/pdf/savepdf", data: "{pdfcontent:" + JSON.stringify(pdfcontent) + "}", contentType: "application/json;charset=utf-8", datatype: "json", complete: OnComplete }); }) } btnsavepdf.addEventListener('click', function () { savePdf(); }); })


Additional Notes

  • Ensure you have the necessary permissions to write to the directory.
  • Customize the HtmlContent with your desired HTML and CSS.
  • You can also load HTML from a body or desired element like div  <div name ='pdfcontent'>content...</div>.

Saturday, September 28, 2024

Problem To Send Mail C# Asp.net (Hosting Provider)

 How To send mail from asp.net C# 


especially when dealing with different hosting providers.


 Here is working Code 

First Create one email id  of  your domain From your hosting provider

using System.Net.Mail;

 public void sendLocalmail(String from, String to, String Cc, String subject , String Mailbody)

        {          

            MailMessage MM = new MailMessage();

            MM.Attachments.Add(new Attachment());

            MM.Body = Mailbody;            

            MM.From = new MailAddress(from);

            MM.To.Add(to);

            MM.CC.Add(Cc);

            MM.Subject = subject ;

            MM.IsBodyHtml = true;

            MM.BodyEncoding = System.Text.Encoding.UTF8;

            MM.Priority = MailPriority.Normal;

            SmtpClient client = new SmtpClient();

            client.Credentials = new System.Net.NetworkCredential(youremail@domain_name.com, "password");

//use your domain email id as username and its password

            client.Port = Convert.ToInt32("25");

//if port 25 not work 'use465 or 587 ports 

            client.Host = "mail.domain_name.com.";

//SMTP Host address of your domain name not required any gmail,hotmail email id check ur dns setting

            client.EnableSsl = true;

//on some server ssl my not suport then try to  client.EnableSsl = false;

            client.Send(MM);

        }

//its working code like php contact form always work


Sunday, September 24, 2023

sweetalerts with @ViewBag.Message mvc 5


How To Show success alert with sweetalert 


Show Success Message On Create, Edit  Mvc 5

Controller:

Add  ViewBag.Message in  Controller --> ActionResult Edit, Create

[HttpPost]

        public ActionResult Edit(model)

        {

              --your Code here

                ViewBag.Message = "Details Edited successfully";

            }

           return View();

        }


View:

 From your Scripts lib folder

 <script src="~/Scripts/jquery-1.11.3.min.js">  </script>

CDN

 <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.28/dist/sweetalert2.min.css />

 <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.28/dist/sweetalert2.all.min.js">

</script>


    @if (ViewBag.Message != null)

    {

        <script type="text/javascript">

             $(window).load(function () {

                new swal({                    

                    text: "@ViewBag.Message",

                    type: "success"

                }).then(okay => {

                    if (okay) {

                        window.location.href = "@Url.Action("Index", "any")";

                    }

                });

  });


        </script>


sweetalert  alert



Tuesday, April 16, 2013

Adding multiple series in asp.net chart dynamically (from sql table for each rows) Asp.net

Add Chart Control on design




In Code behind getdata from dataset for each row from table create series dynamically and add to chart series look in code it will be easy


 public void Bindchart()
    {
        DataSet myDataSet2 = getdatafromsql();
        string series="series";

        foreach (DataRow row in myDataSet2.Tables[0].Rows)
        {
            series=series+row.ToString();
            chart1.Series.Add(series);

            for (int colIndex = 1; colIndex < myDataSet2.Tables[0].Columns.Count; colIndex++)
            {

                // for each column (column 1 and onward), add the value as a point

                string columnName1 = myDataSet2.Tables[0].Columns[colIndex].ColumnName.ToString();

                

                int YVal1 = Convert.ToInt32(row[columnName1]);

                string  emp = Convert.ToString(row[0]);
                chart1.Series[series].Points.AddXY(columnName1, YVal1);
                chart1.Series[series].LegendText  = emp;
                 chart1.Series[ser].ToolTip = emp + "= #VALY";


            }
        }
       
    }


Tuesday, March 5, 2013

Find duplicate record from table -sql server database



Use fallowing query For  searching duplicate Record from table


SELECT record_feild,
 COUNT(record_feild) AS Occurrences_count
FROM Record_table
GROUP BY record_feild
HAVING ( COUNT(record_feild) > 1 )



Use fallowing query deleting  duplicate Record from table
delete
FROM Record_table
WHERE record_id NOT IN
(
SELECT MAX(record_id)
FROM Record_table
GROUP BY record_feild)











Tuesday, July 10, 2012

aggregate functions in where/having clause

sum, avg, count, min, max, and count(*).these are sql functions to calculate and
summarize data


but it can be possible to use these function in query condition clause
Example : product_stock contains purchase sale

detail of product we have to find product
whose stock is greater than 100
here is,

select product_id, product_name from
product_master inner join on product_stock on
product_master.product_id=product_stock.product_id
group by product_id, product_name
having Sum(product_stock.stock_value)>100

Monday, July 9, 2012

Alter Query sql Sever

Alter Commands in sql Server

Change Datatype of sql server database table column

ALTER TABLE MyTable ALTER COLUMN NullCOl NVARCHAR(20) NOT NULL;

drop Column  from sql server database table column

ALTER TABLE table_name
DROP COLUMN column_name

Change Coloumn Name of sql server database table column

Alter table table_name change old_column_name   new_column_name type size


Change primery key CONSTRAINT of sql server database table
ALTER TABLE table_name
DROP CONSTRAINT PK_table_name_Col1 new_column_name old_column_name column_name datatype

Save a PDF generated from html2pdf in C#, MVC , html2pdf , Ajax code

 To save on server or disk a PDF generated from HTML in C# code example, you can use the      html2pdf js script     html2pdf   converts any...