using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UdPdfWeb
{
    /// <summary>
    /// 本程序用于PDF文件的在线加密演示，通过调用命令行工具的PDF文件进行在线加密
    /// </summary>
    public partial class Encrypt : System.Web.UI.Page
    {      
        const string PASSWORD = "123abc";     //加密密码，可自定义

        protected void Page_Load(object sender, EventArgs e)
        {
           
        }

        protected void btnEncrypt_Click(object sender, EventArgs e)
        {
            if (Request.Files["upload"].ContentLength == 0)
            {
                lblInfo.Text = "<font color='red'>请先上传文件</font>"; ;
            }
            else
            {
                string fileName = System.IO.Path.GetFileName(Request.Files["upload"].FileName);
                string pdfFile = Server.MapPath("upload/" + fileName);
                string encCmd = Server.MapPath("UdPdf/UdPdfTools.exe");
                Request.Files["upload"].SaveAs(pdfFile);
                string args = string.Format("-input {0} -password {1}", pdfFile, PASSWORD);

                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.FileName = encCmd;
                p.StartInfo.Arguments = args;
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
                p.StartInfo.CreateNoWindow = true;//不显示程序窗口
                p.Start();
                p.WaitForExit();
                string strOutput = p.StandardOutput.ReadToEnd();
                if (p.ExitCode == 0)
                {
                    System.IO.File.Delete(pdfFile);
                    lblInfo.Text = "加密成功，<a href='UdPdf.aspx?file=" + Server.UrlEncode(System.IO.Path.GetFileNameWithoutExtension(fileName)) + "'>点这里查看加密文件</a>";
                    //lblInfo.Text += "<br>" + strOutput;
                }
                else
                {
                    lblInfo.Text = "<font color='red'>加密失败，错误码：" + p.ExitCode + "<br>" + strOutput + "</font>";
                }
            }

        }
    }
}