繁体   English   中英

将aspx页面导出为pdf并通过asp.net中的邮件发送

[英]Export aspx page to pdf and sent it via mail in asp.net

我想通过电子邮件发送aspx页面。 所以我将其转换为pdf。 问题是在保存数据之前正在创建pdf。 因此,当我打开pdf时,我的测试框为空。 请给我找到解决方案。 下面是正在使用的代码。 我也想发送PDF文件作为附件。

     protected void SendMail()
    {

        var userName = "4.n-4@gmail.com";

        var toAddress = YourEmail.Text.ToString();

        const string Password = "Mypassword123#";

        string subject = YourSubject.Text.ToString();
        string body = "From: " + YourName.Text + "\n";
        body += "Email: " + YourEmail.Text + "\n";
        body += "Subject: " + YourSubject.Text + "\n";
        body += "Question: \n" + Comments.Text + "\n";

        var smtp = new System.Net.Mail.SmtpClient();
        {
            smtp.Host = "10.238.52.240";
            smtp.Port = 25;
            smtp.EnableSsl = false;
            smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            smtp.Credentials = new NetworkCredential(userName, Password);
            smtp.Timeout = 20000;
        }

        smtp.Send(userName, toAddress, subject, body);
    }

     protected void Button1_Click(object sender, EventArgs e)
    {

        Response.ContentType = "application/pdf"; 
        Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache); 
        StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); 
        this.Page.RenderControl(hw); 
        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f); 
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream); 
        pdfDoc.Open(); 
        htmlparser.Parse(sr); 

        Response.Write(pdfDoc);


         try
        {
             SendMail();

            DisplayMessage.Text = "Your Comments after sending the mail";
            DisplayMessage.Visible = true;
            YourSubject.Text = "";
            YourEmail.Text = "";
            YourName.Text = "";
            Comments.Text = "";
            pdfDoc.Close();
            Response.End();
        }
        catch (Exception) { }
    }
        }
      }

我不知道您后面的其余代码,但是我猜您缺少足够的PostBack处理。 当您单击提交按钮时,页面首先被发布(即“ PostBack”-重新处理整个页面生命周期,包括Page_Load事件;重新初始化页面),因此当您到达按钮的Click时事件发生后,该表单和您的文本框将为空。

您可以在msdn的 ASP.NET页面生命周期上阅读。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM