How to attach a PDF generated using jsPDF to the mail using c#

I need to know if there is any way to attach a PDF file generated using jsPDF and mail it in C#?

I have the following code in c#

MailMessage message = new MailMessage(fromAddress, toAddress);
        message.Subject = subject;
        message.IsBodyHtml = true;
        message.Body = StrContent.ToString();
        //message.Attachments.Add(new Attachment("getDPF()"));

and I’m using a JsPDF library as follows:
<script type="text/javascript" src="jsPdf/jspdf.min.js"></script>
<script type="text/javascript">
    function getPDF()
        var doc = new jsPDF();
        doc.text(20, 20, 'TEST Message');

Is there any way to attach it in the mail before send it?
Thanks in advance.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You cannot call client-side code (Javascript function) from server code (c#).
You can only communicate via the (HTTP/HTTPs) protocol.

I think you need to generate the PDF from the client and then send that PDF to server so that you can attach the PDF to an email.

In that case you need to first generate the PDF and send it to the server as a base64 string.

You can then convert the base64 string to PDF in C# and mail it as an attachment.

Client Side:

function generatePdf() {    
    var doc = new jsPdf();
    doc.text("jsPDF to Mail", 40, 30);    
    var binary = doc.output();
    return binary ? btoa(binary) : "";


Posting the base64 pdf content to the server:
  var reqData = generatePdf();
                data: JSON.stringify({data:reqData}),
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",

On the server (MVC Controller):
        public ActionResult YourMethod(string data)
            //create pdf
            var pdfBinary = Convert.FromBase64String(data);
            var dir = Server.MapPath("~/DataDump");

            if (!Directory.Exists(dir))

            var fileName = dir + "\PDFnMail-" + DateTime.Now.ToString("yyyyMMdd-HHMMss") + ".pdf";

            // write content to the pdf
            using (var fs = new FileStream(fileName, FileMode.Create))
            using (var writer = new BinaryWriter(fs))
                writer.Write(pdfBinary, 0, pdfBinary.Length);
            //Mail the pdf and delete it
            // .... call mail method here 
           return null; 

Check out here for more information

Method 2

Your code example use pdf.text(), but in most situations, you want to export a html page with table(s) or image(s). The latest version jsPDF html PlugIn instead of addHtml(). Below is an code example using jsPDF html() and Web API.

Client side:

function emailHtml() {
    let pdf = new jsPDF('p', 'pt', 'a3'); // a4: part of the page is cut off?
    pdf.html(document.body, {
        callback: function (pdf) {
            let obj = {};
            obj.pdfContent = pdf.output('datauristring');
            var jsonData = JSON.stringify(obj);
                url: '/api/jspdf/html2pdf',
                type: 'POST',
                contentType: 'application/json',
                data: jsonData

Note that the datauristring returned from pdf.html has a filename added to the string, filename=generated.pdf;. Also, SmtpClient is obsolete, consider to use MailKit instead.
public void Html2Pdf([FromBody] JObject jObject)
    dynamic obj = jObject;
        string strJson = obj.pdfContent;
        var match = Regex.Match(strJson, @"data:application/pdf;filename=generated.pdf;base64,(?<data>.+)");
        var base64Data = match.Groups["data"].Value;
        var binData = Convert.FromBase64String(base64Data);

        using (var memoryStream = new MemoryStream())
            var mail = new MailMessage
                From = new MailAddress("[FromEmail]")
            mail.Subject = "";
            mail.Body = "attached";
            mail.IsBodyHtml = true;
            mail.Attachments.Add(new Attachment(new MemoryStream(binData), "htmlToPdf.pdf"));

            var SmtpServer = new SmtpClient("[smtp]")
                Port = 25,
                Credentials = new NetworkCredential("[FromEmail]", "password"),
                EnableSsl = true

    catch (Exception ex)

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x