Esempio n. 1
0
        /// <summary>
        /// 根据pdf模板写入数据生成新的pdf
        /// </summary>
        /// <param name="saveFile">保存的新pdf路径</param>
        /// <param name="sourceFile">原pdf路径</param>
        public static void AddNewPdf(string saveFile, string sourceFile)
        {
            //写入新的pdf地址
            //sourceFile = @"C:\Users\Administrator\Desktop\ABC\temp.pdf";
            //sourceFile = @"C:\Users\Administrator\Desktop\temp123.pdf";
            iTextSharp.text.pdf.PdfDocument document = new iTextSharp.text.pdf.PdfDocument();
            //读取的源pdf文件
            iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(sourceFile);
            PdfStamper pdfStamper    = new PdfStamper(pdfReader, new FileStream(saveFile, FileMode.OpenOrCreate));
            AcroFields pdfFormFields = pdfStamper.AcroFields;

            pdfStamper.FormFlattening = true;
            //BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            //BaseFont simheiBase = BaseFont.CreateFont(@"C:\Windows\Fonts\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            BaseFont simheiBase = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            pdfFormFields.AddSubstitutionFont(simheiBase);
            Dictionary <string, string> para = new Dictionary <string, string>();

            para.Add($"Numbering", "12369999995");
            for (int i = 1; i < 38; i++)
            {
                para.Add($"Numbering{i}", "12365");
            }
            foreach (KeyValuePair <string, string> parameter in para)
            {
                pdfStamper.AcroFields.SetField(parameter.Key, parameter.Value);
            }
            //pdfStamper.AcroFields.SetField("Names", "李朝强");
            //pdfStamper.AcroFields.SetField("chk", "yes", true);
            pdfStamper.Close();
            pdfReader.Close();
        }
Esempio n. 2
0
        public static void memorystream()
        {
            using (MemoryStream ms = new MemoryStream())
            {
                PdfReader  pdfReader  = new PdfReader(templateFile, null);
                PdfStamper pdfStamper = new PdfStamper(pdfReader, ms);

                AcroFields pdfFormFields = pdfStamper.AcroFields;
                pdfFormFields.AddSubstitutionFont(BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED));

                pdfFormFields.SetField("Radio Button1", "1");
                pdfFormFields.SetField("Check Box101", "是");
                pdfFormFields.SetField("Currency", "是");
                //String[] values = pdfFormFields.GetAppearanceStates("Check Box101");
                //foreach (String value in values) {
                //	Console.WriteLine("values=" + value);
                //}
                pdfFormFields.SetField("Text21", "()聖島國際專利商標聯合事務所");
                pdfFormFields.SetField("Text74", "台北市松山區南京東路三段248號11樓之1");

                //pdfStamper.Writer.CloseStream = false;
                //pdfStamper.FormFlattening = true;//平面化
                pdfStamper.Close();
                pdfReader.Close();

                System.IO.File.WriteAllBytes(outputFile, ms.ToArray());
            }
        }
Esempio n. 3
0
        protected void btnClick_Click(object sender, EventArgs e)
        {
            BaseFont   baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\Arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            PdfReader  template = new PdfReader(@"C:\temp\aktr.pdf"); // файл шаблона
            PdfStamper stamper  = new PdfStamper(template, new FileStream(@"C:\temp\akt.pdf", FileMode.Create));
            AcroFields fields   = stamper.AcroFields;

            fields.AddSubstitutionFont(baseFont);
            fields.SetField("dd", "10");
            fields.SetField("mm", "октября");
            fields.SetField("yy", "16");
            fields.SetField("Zakazshik", "Гл. инженер ООО Валеско Иванов И.И.");
            fields.SetField("Worker", "элекромеханик Кулахметов Х.И.");
            fields.SetField("address", "г. Апрелевка, ул.Ясная д.7");
            fields.SetField("sourse", "заявка № 10001.");
            fields.SetField("lift", "1/1/.01");
            fields.SetField("text", "замена ВЧ трансорматора ");
            fields.SetField("date", "10.10.2016 12:35:55");
            fields.SetField("name", "трансформатор ВЧ12000/1");
            fields.SetField("numID", "ID -123456");
            fields.SetField("prim", "неисправная деталь передана на склад");
            fields.SetField("FamZak", "Иванов И.И.");
            fields.SetField("Worker1", "электромеханик Пузин В.И.");
            fields.SetField("FamWorker", "Кулахметов Х.И.");
            fields.SetField("nunId", "123456");
            fields.SetField("kol", "1 шт.");
            stamper.FormFlattening = false;
            stamper.Close();
            //В разработке

            //  using (FileStream fs = new FileStream(@"C:\temp\akt.pdf", FileMode.Open))
            //  {
            //  }
        }
Esempio n. 4
0
        public void FillForm(
            Dictionary <string, string> items,
            Stream formStream)
        {
            PdfStamper pdfStamper    = new PdfStamper(pdfReader, formStream);
            AcroFields pdfFormFields = pdfStamper.AcroFields;
            BaseFont   arialBaseFont;
            string     arialFontPath;

            try
            {
                arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
                arialBaseFont = BaseFont.CreateFont(arialFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            }
            catch (IOException)
            {
                arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIAL.TTF");
                arialBaseFont = BaseFont.CreateFont(arialFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            }

            pdfFormFields.AddSubstitutionFont(arialBaseFont);
            foreach (KeyValuePair <string, string> item in items)
            {
                pdfFormFields.SetFieldProperty(item.Key, "textfont", arialBaseFont, null);
                if (item.Value != null)
                {
                    pdfFormFields.SetField(item.Key, item.Value);
                }
            }
            pdfStamper.FormFlattening = false;
            pdfStamper.Close();
        }
Esempio n. 5
0
        public string Pdf(string p0, string p4, string p6, string p60, string p102, int p7, string p8, string p9, string p10, string p11, string p12, int p101, string p13, string p14, string p15, string p17, string p18, string p61, string p103, string p16, int p21, string p24, string p5, string p22, string p104, string p105, string p106, string p107, string p108, string p109, string p110)
        {
            string pathsafe             = settings.safepathpdf + p4 + "_" + p0 + ".pdf";
            string pathsafetemplatefont = settings.safepath + "\\Template\\Tahoma.ttf";

            BaseFont   baseFont = BaseFont.CreateFont(pathsafetemplatefont, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            PdfReader  template = new PdfReader(settings.safepathetemplate);
            PdfStamper stamper  = new PdfStamper(template, new FileStream(pathsafe, FileMode.Create));
            AcroFields fields   = stamper.AcroFields;

            fields.AddSubstitutionFont(baseFont);

            // Поля для не срочного платежного поручения

            fields.SetField("p4", p4);
            fields.SetField("p3", p0);
            fields.SetField("p6", p6);
            fields.SetField("p7", p7.ToString());
            fields.SetField("p8", p8);
            fields.SetField("p60", p60);
            fields.SetField("p102", p102.ToString());
            fields.SetField("p9", p9);
            fields.SetField("p10", p10);
            fields.SetField("p11", p11);
            fields.SetField("p12", p12);
            fields.SetField("p101", p101.ToString());
            fields.SetField("p13", p13);
            fields.SetField("p14", p14);
            fields.SetField("p15", p15);
            fields.SetField("p17", p17);
            fields.SetField("p18", p18);
            fields.SetField("p61", p61);
            fields.SetField("p103", p103.ToString());
            fields.SetField("p16", p16);
            fields.SetField("p21", p21.ToString());
            fields.SetField("p24", p24);


            // Поля срочного платежного поручения
            fields.SetField("p5", p5);

            // Поля бюджетного платежного поручения
            fields.SetField("p22", p22);
            fields.SetField("p104", p104);
            fields.SetField("p105", p105);
            fields.SetField("p106", p106);
            fields.SetField("p107", p107);
            fields.SetField("p108", p108);
            fields.SetField("p109", p109);
            fields.SetField("p110", p110);

            //Форматирование
            stamper.FormFlattening = false;
            stamper.Close();

            MessageBox.Show("Платежное поручение в pdf сохранено");
            return(pathsafe);
        }
Esempio n. 6
0
        public static bool GetPdf(string templatePath, string newFilePath, Dictionary <string, string> parameters)
        {
            bool result = true;

            try
            {
                PdfReader  pdfReader  = new PdfReader(templatePath);
                PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFilePath, FileMode.Create));


                //加密
                pdfStamper.SetEncryption(PdfWriter.STRENGTH128BITS, "", null, PdfWriter.AllowPrinting);

                //通过iTextAsian调用中文字体
                //iTextSharp.text.io.StreamUtil.AddToResourceSearch(Assembly.LoadFile(Utils.GetMapPath(Utils.GetAppSettingValue("appName")+"lib/iTextAsian.dll")));
                //iTextSharp.text.io.StreamUtil.AddToResourceSearch(Assembly.LoadFile(Utils.GetMapPath(Utils.GetAppSettingValue("appName") + "lib/iTextAsianCmaps.dll")));
                //BaseFont baseFT = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
                // BaseFont baseFT1 = BaseFont.CreateFont("MHei-Medium", "UniCNS-UCS2-H", BaseFont.EMBEDDED);


                //调用系统字体
                BaseFont baseFT = BaseFont.CreateFont(@"C:\Windows\Fonts\MSYH.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                //BaseFont baseFT1 = BaseFont.CreateFont(@"C:\Windows\Fonts\msyhbd.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                BaseFont baseFT1 = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);


                //获取域的集合;
                AcroFields pdfFormFields = pdfStamper.AcroFields;

                //设置域的字体;生成文件几十K

                pdfFormFields.AddSubstitutionFont(baseFT);

                //为需要赋值的域设置值;
                foreach (KeyValuePair <string, string> parameter in parameters)
                {
                    if (parameter.Key == "titile")
                    {
                        pdfFormFields.SetFieldProperty(parameter.Key, "textfont", baseFT1, null);
                    }

                    //pdfFormFields.SetFieldProperty(parameter.Key, "textfont", baseFT, null );//生成文件过大(十几MB左右) 摒弃掉了
                    pdfFormFields.SetField(parameter.Key, parameter.Value);
                }
                //这句很重要,如果为false那么生成的PDF文件还能编辑,一定要设为true;
                pdfStamper.FormFlattening = true;
                pdfStamper.Close();
                pdfReader.Close();
            }
            catch
            {
                result = false;
                throw;
            }

            return(result);
        }
Esempio n. 7
0
        ///
        /// 向pdf模版填充内容,并生成新的文件
        ///
        /// 模版路径
        /// 生成文件保存路径
        /// 标签字典(即模版中需要填充的控件列表)
        public static void FillForm(string pdfTemplate, string newFile, Dictionary <string, string> dic)
        {
            PdfReader    pdfReader  = null;
            PdfStamper   pdfStamper = null;
            FileStream   fs         = null;
            MemoryStream ms         = null;

            try
            {
                //fs = new FileStream(newFile, FileMode.Create);
                ms        = new MemoryStream();
                pdfReader = new PdfReader(pdfTemplate);
                //pdfStamper = new PdfStamper(pdfReader, fs);
                pdfStamper = new PdfStamper(pdfReader, ms);
                AcroFields pdfFormFields = pdfStamper.AcroFields;
                //设置支持中文字体
                //BaseFont baseFont = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

                BaseFont baseFont = BaseFont.CreateFont(FontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                pdfFormFields.AddSubstitutionFont(baseFont);
                foreach (KeyValuePair <string, string> de in dic)
                {
                    pdfFormFields.SetField(de.Key, de.Value);
                }
                pdfStamper.FormFlattening = true;
            }
            catch (Exception ex)
            {
                //LogHelper.Error(ex.Message);
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }
                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
                if (fs != null)
                {
                    fs.Close();
                }
                if (ms != null)
                {
                    ms.Close();
                    ms.Dispose();
                }
                string tempPath = $"{System.Environment.CurrentDirectory}\\{Guid.NewGuid().ToString()}.pdf";
                File.WriteAllBytes(tempPath, ms.ToArray());
                EmailHelp.SendEmail("*****@*****.**", "1", "2", tempPath);
            }
        }
Esempio n. 8
0
        public void ManipulatePdf(String src, String dest, IDictionary <string, string> pdfParams)
        {
            PdfReader  reader   = new PdfReader(src);
            Rectangle  pagesize = reader.GetPageSize(1);
            PdfStamper stamper  = new PdfStamper(reader, new FileStream(dest, FileMode.Create));
            AcroFields form     = stamper.AcroFields;

            byte[] fontBinary;
            using (var client = new WebClient())
                fontBinary = client.DownloadData("http://beta.adahi.linkdev.com/Style%20Library/Adahi/fonts/Tahoma.ttf");
            var arialBaseFont = BaseFont.CreateFont("Tahoma.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, false, fontBinary, null);

            form.GenerateAppearances = true;
            form.AddSubstitutionFont(arialBaseFont);

            foreach (var param in pdfParams)
            {
                form.SetField(param.Key, param.Value);
            }

            PdfPTable table = new PdfPTable(2);

            table.AddCell("#");
            table.AddCell("description");
            table.HeaderRows = 1;
            table.SetWidths(new int[] { 1, 15 });
            for (int i = 1; i <= 150; i++)
            {
                table.AddCell(i.ToString());
                table.AddCell("test " + i);
            }
            ColumnText column    = new ColumnText(stamper.GetOverContent(1));
            Rectangle  rectPage1 = new Rectangle(36, 36, 559, 540);

            column.SetSimpleColumn(rectPage1);
            column.AddElement(table);
            int       pagecount = 1;
            Rectangle rectPage2 = new Rectangle(36, 36, 559, 806);
            int       status    = column.Go();

            while (ColumnText.HasMoreText(status))
            {
                status = TriggerNewPage(stamper, pagesize, column, rectPage2, ++pagecount);
            }
            stamper.FormFlattening = false;
            stamper.Close();
            reader.Close();
        }
Esempio n. 9
0
        /**
         * Manipulates a PDF file src with the file dest as result
         * @param src the original PDF
         */
        public byte[] ManipulatePdfFont2(byte[] src)
        {
            PdfReader reader = new PdfReader(src);

            using (MemoryStream ms = new MemoryStream()) {
                using (PdfStamper stamper = new PdfStamper(reader, ms)) {
                    AcroFields form    = stamper.AcroFields;
                    BaseFont   unicode = BaseFont.CreateFont(
                        "c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED
                        );
                    form.AddSubstitutionFont(unicode);
                    form.SetField("description", BINJIP);
                }
                return(ms.ToArray());
            }
        }
Esempio n. 10
0
 protected void Edit_Click(object sender, EventArgs e)
 {
     using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DefaultConnection"].ToString()))
     {
         string dd = DateTime.Now.Day.ToString();
         string mm = DateTime.Now.Month.ToString();
         string yy = DateTime.Now.Year.ToString();
         conn.Open();
         SqlCommand cmd = new SqlCommand("select d.[img], d.namefile from DocUM d " +
                                         "where d.Id=@id ", conn);
         cmd.Parameters.AddWithValue("id", _wz);
         //чтение из базы
         SqlDataReader datareader = cmd.ExecuteReader();
         datareader.Read();
         int    bLength = (int)datareader.GetBytes(0, 0, null, 0, int.MaxValue);
         byte[] bBuffer = new byte[bLength];
         datareader.GetBytes(0, 0, bBuffer, 0, bLength);
         BaseFont   baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\Arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
         PdfReader  read     = new PdfReader(bBuffer);
         PdfStamper stamper  = new PdfStamper(read, new FileStream(@"C:\temp\mgm.pdf", FileMode.Create));
         AcroFields fields   = stamper.AcroFields;
         fields.AddSubstitutionFont(baseFont);
         if (TextZak.Text != "")
         {
             fields.SetField("Podt", TextZak.Text); //ФИО заказчика
         }
         fields.SetField("dateP", dd + "." + mm + "." + yy + "г.");
         fields.SetField("aspP", "pin: ok"); //подпись заказчика
         stamper.FormFlattening = true;      // ложь - открыт для записи, истина - закрыт
         stamper.Close();
         datareader.Close();
         // запись в БД
         FileStream fs  = new FileStream(@"C:\temp\mgm.pdf", FileMode.Open);
         Byte[]     pdf = new byte[fs.Length];
         fs.Read(pdf, 0, pdf.Length);
         cmd = new SqlCommand("update DocUM set img=@img, status=@st where Id=@id", conn);
         cmd.Parameters.AddWithValue("id", _wz);
         cmd.Parameters.Add("img", SqlDbType.Image).Value = pdf;
         cmd.Parameters.AddWithValue("st", "подписан заказчиком");
         cmd.ExecuteNonQuery();
         fs.Close();
         //  Thread.Sleep(10000);
         Response.ContentType = "image"; //image/Jpeg
         Response.BinaryWrite(pdf);
         //  просмотр в браузере
     }
 }
Esempio n. 11
0
        public static void multiplePage()
        {
            List <Byte[]> result = new List <byte[]>();

            for (int i = 1; i <= 2; i++)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    PdfReader  pdfReader  = new PdfReader(templateFile);
                    PdfStamper pdfStamper = new PdfStamper(pdfReader, ms);

                    AcroFields    pdfFormFields = pdfStamper.AcroFields;
                    List <String> keys          = new List <String>(pdfFormFields.Fields.Keys);
                    foreach (var key in keys)
                    {
                        // rename the fields
                        pdfFormFields.RenameField(key, String.Format("{0}_{1}", key, i));
                    }
                    pdfFormFields.AddSubstitutionFont(BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED));

                    pdfFormFields.SetField("Radio Button1_" + i, "1");
                    pdfFormFields.SetField("Check Box101_" + i, "是");
                    pdfFormFields.SetField("Currency_" + i, "是");
                    //String[] values = pdfFormFields.GetAppearanceStates("Check Box101");
                    //foreach (String value in values) {
                    //	Console.WriteLine("values=" + value);
                    //}
                    pdfFormFields.SetField("Text21_" + i, "(" + i + ")聖島國際專利商標聯合事務所");
                    pdfFormFields.SetField("Text74_" + i, "台北市松山區南京東路三段248號11樓之1");

                    pdfStamper.Writer.CloseStream = false;
                    //pdfStamper.FormFlattening = true;//平面化

                    pdfStamper.Close();
                    pdfReader.Close();

                    result.Add(ms.ToArray());
                }
            }

            MemoryStream outStream = new MemoryStream();

            outStream = MergePdfForms(result);

            System.IO.File.WriteAllBytes(outputFile, outStream.ToArray());
        }
Esempio n. 12
0
        private void button2_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listView.Items.Count; i++)
            {
                PdfReader    reader       = new PdfReader(Template);
                BaseFont     bsFont       = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                ListViewItem lv           = listView.Items[i];
                string       FileNamePath = ExportPath(lv.SubItems[3].Text);
                FileStream   fileStream   = new FileStream(FileNamePath, FileMode.Create);

                //PDF字段操作
                PdfStamper stamper         = new PdfStamper(reader, fileStream);
                AcroFields coderAcroFields = stamper.AcroFields;
                coderAcroFields.AddSubstitutionFont(bsFont);

                //PDF字段填充



                // coderAcroFields.SetFieldProperty("ProjectName", "textfont", 15, null);


                coderAcroFields.SetField("ProjectName", tbxmmc.Text);
                coderAcroFields.SetField("ServerAdd", tbfwdz.Text);
                coderAcroFields.SetField("User", lv.SubItems[1].Text);
                coderAcroFields.SetField("Tel", tblxdh.Text);
                coderAcroFields.SetField("Engineer", lv.SubItems[2].Text);
                coderAcroFields.SetField("OderTime", lv.SubItems[3].Text);
                coderAcroFields.SetField("Note", lv.SubItems[4].Text);
                coderAcroFields.SetField("ServerType", lv.SubItems[5].Text);
                coderAcroFields.SetField("Server", lv.SubItems[6].Text);
                coderAcroFields.SetField("Parts", lv.SubItems[7].Text);
                coderAcroFields.SetField("Others", lv.SubItems[8].Text);

                //stamper.FormFlattening = true;

                stamper.Close();
                reader.Close();
            }



            System.Diagnostics.Process.Start("Explorer.exe", tbpath.Text);
        }
Esempio n. 13
0
        /// <summary>
        /// 指定pdf模板为其文本域赋值
        /// </summary>
        /// <param name="pdfTemplate">pdf模板路径</param>
        /// <param name="tempFilePath">pdf导出路径</param>
        /// <param name="parameters">pdf模板域键值</param>
        public void PutText(string pdfTemplate, string tempFilePath, Dictionary <string, string> parameters)
        {
            PdfReader  pdfReader  = null;
            PdfStamper pdfStamper = null;

            try
            {
                if (File.Exists(tempFilePath))
                {
                    File.Delete(tempFilePath);
                }

                pdfReader  = new PdfReader(pdfTemplate);
                pdfStamper = new PdfStamper(pdfReader, new FileStream(tempFilePath, FileMode.OpenOrCreate));

                AcroFields pdfFormFields = pdfStamper.AcroFields;
                pdfStamper.FormFlattening = true;

                BaseFont bf         = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                BaseFont simheiBase = BaseFont.CreateFont(@"C:\Windows\Fonts\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

                pdfFormFields.AddSubstitutionFont(simheiBase);

                foreach (KeyValuePair <string, string> parameter in parameters)
                {
                    if (pdfFormFields.Fields[parameter.Key] != null)
                    {
                        pdfFormFields.SetField(parameter.Key, parameter.Value);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                pdfStamper.Close();
                pdfReader.Close();

                pdfStamper = null;
                pdfReader  = null;
            }
        }
Esempio n. 14
0
        protected void Email_Click(object sender, EventArgs e)
        {
            using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DefaultConnection"].ToString()))
            {
                conn.Open();
                string name = "", id = "", kol = "";
                string name1 = "", id1 = "", kol1 = "";
                string name2 = "", id2 = "", kol2 = "";
                string name3 = "", id3 = "", kol3 = "";
                string name4 = "", id4 = "", kol4 = "";
                string dat = DateTime.Now.Date.ToLongDateString();
                string dd  = DateTime.Now.Day.ToString();
                string mm  = DateTime.Now.Month.ToString();
                string yy  = DateTime.Now.Year.ToString();
                string hh  = DateTime.Now.Hour.ToString() + "час." + DateTime.Now.Minute.ToString() + "мин.";
                //   _wz = Int32.Parse(EventId.Text);
                App_Code.Base db = new App_Code.Base(WebConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
                //   DataTable data = db.GetEvent(_wz);
                DataTable dt = db.GetPartsList(_wz);
                try
                {
                    name = dt.Rows[0]["Name"].ToString();
                    id   = dt.Rows[0]["NumID"].ToString();
                    kol  = dt.Rows[0]["Kol"].ToString();
                }
                catch { }
                try
                {
                    name1 = dt.Rows[1]["Name"].ToString();
                    id1   = dt.Rows[1]["NumID"].ToString();
                    kol1  = dt.Rows[1]["Kol"].ToString();
                }
                catch { }
                try
                {
                    name2 = dt.Rows[2]["Name"].ToString();
                    id2   = dt.Rows[2]["NumID"].ToString();
                    kol2  = dt.Rows[2]["Kol"].ToString();
                }
                catch { }
                try
                {
                    name3 = dt.Rows[3]["Name"].ToString();
                    id3   = dt.Rows[3]["NumID"].ToString();
                    kol3  = dt.Rows[3]["Kol"].ToString();
                }
                catch { }
                try
                {
                    name4 = dt.Rows[4]["Name"].ToString();
                    id4   = dt.Rows[4]["NumID"].ToString();
                    kol4  = dt.Rows[4]["Kol"].ToString();
                }

                catch { }

                BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\Arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

                PdfReader  template = new PdfReader(@"C:\temp\kp.pdf");    // файл шаблона
                PdfStamper stamper  = new PdfStamper(template, new FileStream(@"C:\temp\zkp.pdf", FileMode.Create));
                AcroFields fields   = stamper.AcroFields;
                fields.AddSubstitutionFont(baseFont);
                fields.SetField("dd", dd);
                fields.SetField("mm", mm);
                fields.SetField("yy", yy);
                if (name != "")
                {
                    fields.SetField("npp1", " 1.");
                }
                fields.SetField("name", name);
                if (name1 != "")
                {
                    fields.SetField("npp2", " 2.");
                }
                fields.SetField("name1", name1);
                if (name2 != "")
                {
                    fields.SetField("npp3", " 3.");
                }
                fields.SetField("name2", name2);
                if (name3 != "")
                {
                    fields.SetField("npp4", " 4.");
                }
                fields.SetField("name3", name3);
                if (name4 != "")
                {
                    fields.SetField("npp5", " 5.");
                }
                fields.SetField("name4", name4);
                fields.SetField("id", id);
                fields.SetField("id1", id1);
                fields.SetField("id2", id2);
                fields.SetField("id3", id3);
                fields.SetField("id4", id4);
                fields.SetField("kol", kol);
                fields.SetField("kol1", kol1);
                fields.SetField("kol2", kol2);
                fields.SetField("kol3", kol3);
                fields.SetField("kol4", kol4);
                // fields.SetField("kol1", kol1);
                fields.SetField("dni", "один");
                stamper.FormFlattening = false;    // ложь - открыт для записи, истина - закрыт
                stamper.Close();
                // запись в БД
                FileStream fs  = new FileStream(@"C:\temp\zkp.pdf", FileMode.Open);
                Byte[]     pdf = new byte[fs.Length];
                fs.Read(pdf, 0, pdf.Length);
                SqlCommand cmd = new SqlCommand("insert into Documents (Name, NumEvent, Image, NameFile, Status) values (@name, @nev, @img, @namefile, @st )", conn);
                cmd.Parameters.AddWithValue("name", "запрос КП");
                cmd.Parameters.AddWithValue("nev", Id.Text);
                cmd.Parameters.Add("img", SqlDbType.Image).Value         = pdf;
                cmd.Parameters.Add("namefile", SqlDbType.NVarChar).Value = Id.Text + "/ЗКП.pdf";
                cmd.Parameters.AddWithValue("st", "отправлен");
                cmd.ExecuteNonQuery();
                fs.Close();

                //  Response.ContentType = "image"; //image/Jpeg
                //  Response.BinaryWrite(pdf);
            }

            string text = "Здравствуйте! Вышлите пожалуйста коммерческое предложение на перечень запчастей во вложенном файле";

            if (!IsAllSelected(Post))
            {
                List <string> sel = GetSelectedEmails(Post);
                for (int i = 0; i < sel.Count; i++)
                {
                    Send(sel[i], text);
                }
            }
            Msg.Text = "Запрос нв КП разослан по выбранным адресам!";
        }
Esempio n. 15
0
        static void Main(string[] args)
        {
            string     pdfTemplate   = @"C:\Users\Administrator\Desktop\DownloadedPdfs\Pdf Form\ShipmentDocumentNew.pdf";
            string     newFile       = @"C:\Users\Administrator\Desktop\DownloadedPdfs\Pdf Form\ShipmentDocumentFormNewReplaced.pdf";
            PdfReader  pdfReader     = new PdfReader(pdfTemplate);
            PdfStamper pdfStamper    = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
            AcroFields pdfFormFields = pdfStamper.AcroFields;

            byte[] fontBinary;
            using (var client = new WebClient())
                fontBinary = client.DownloadData("file:///C:/Worspace/Adahi/CMS/Linkdev.Adahi.SP.Content/Style%20Library/Adahi/fonts/Tahoma.ttf");

            var arialBaseFont = BaseFont.CreateFont("Tahoma.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, false, fontBinary, null);
            var font          = new Font(arialBaseFont, 11, Font.BOLD);

            pdfFormFields.GenerateAppearances = true;

            pdfFormFields.AddSubstitutionFont(arialBaseFont);

            List <string> filesToWrite = new List <string>();

            foreach (var de in pdfReader.AcroFields.Fields)
            {
                filesToWrite.Add(de.Key);
                pdfFormFields.SetField(de.Key, $"{de.Key}");
            }

            PdfPTable table;
            bool      internalShipment = false;

            if (internalShipment)
            {
                table = new PdfPTable(6)
                {
                    RunDirection = PdfWriter.RUN_DIRECTION_RTL,
                };
                table.AddCell(new PdfPCell(new Phrase("جهة الارسالية", font))
                {
                    HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_CENTER
                });
                table.AddCell(new Phrase("", font));
                table.AddCell(new PdfPCell(new Phrase("المحافظة", font))
                {
                    HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_CENTER
                });
                table.AddCell(new Phrase("", font));
                table.AddCell(new PdfPCell(new Phrase("المدينة المرسل لها", font))
                {
                    HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_CENTER
                });
                table.AddCell(new Phrase("", font));
                table.AddCell(new PdfPCell(new Phrase("العنوان", font))
                {
                    HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_CENTER
                });
                table.AddCell(new PdfPCell(new Phrase("", font))
                {
                    Colspan = 2
                });
                table.AddCell(new PdfPCell(new Phrase("الهاتف", font))
                {
                    HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_CENTER
                });
                table.AddCell(new PdfPCell(new Phrase("", font))
                {
                    Colspan = 2, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_CENTER
                });
                table.SetTotalWidth(new float[] { 115, 115, 115, 60, 130, 100 });
            }
            else
            {
                table = new PdfPTable(4)
                {
                    RunDirection = PdfWriter.RUN_DIRECTION_RTL,
                };
                table.AddCell(new PdfPCell(new Phrase("Mission Country", font))
                {
                    HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_CENTER
                });
                table.AddCell(new Phrase("", font));
                table.AddCell(new PdfPCell(new Phrase("Mission Entity", font))
                {
                    HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_CENTER
                });
                table.AddCell(new Phrase("", font));
                table.AddCell(new PdfPCell(new Phrase("Port of Entry / City", font))
                {
                    HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_CENTER
                });
                table.AddCell(new Phrase("", font));
                table.AddCell(new PdfPCell(new Phrase("Entity Contact Person", font))
                {
                    HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_CENTER
                });

                var p = new Paragraph("احمد مجدي,01090510845\n", font)
                {
                    "احمد مجدي,01090510845\n",
                    "احمد مجدي,01090510845\n"
                };
                p.Alignment = Element.ALIGN_CENTER;
                table.AddCell(new PdfPCell(p));
                table.SetTotalWidth(new float[] { 175, 140, 190, 130 });
            }

            ColumnText column = new ColumnText(pdfStamper.GetOverContent(1));
            var        internalShipmentTableHeight = internalShipment ? 1 : 0;
            Rectangle  rectPage1 = new Rectangle(-30, 600 - (25 * internalShipmentTableHeight), table.TotalWidth, table.CalculateHeights());

            column.SetSimpleColumn(rectPage1);
            column.AddElement(table);
            column.AddElement(new Chunk("\n"));
            column.AddElement(table);
            column.AddElement(new Chunk("\n"));
            column.AddElement(table);
            column.AddElement(new Chunk("\n"));
            column.Go();

            pdfStamper.FormFlattening = true;
            // close the pdf
            pdfStamper.Close();
        }
Esempio n. 16
0
        public static void AddNewPdf()
        {
            string tempFilePath = @"C:\Users\Administrator\Desktop\ABC\temp.pdf";

            iTextSharp.text.pdf.PdfDocument document  = new iTextSharp.text.pdf.PdfDocument();
            iTextSharp.text.pdf.PdfReader   pdfReader = new iTextSharp.text.pdf.PdfReader(@"C:\Users\Administrator\Desktop\temp123.pdf");
            PdfStamper pdfStamper    = new PdfStamper(pdfReader, new FileStream(tempFilePath, FileMode.OpenOrCreate));
            AcroFields pdfFormFields = pdfStamper.AcroFields;

            pdfStamper.FormFlattening = true;
            //BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            //BaseFont simheiBase = BaseFont.CreateFont(@"C:\Windows\Fonts\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            BaseFont simheiBase = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            pdfFormFields.AddSubstitutionFont(simheiBase);
            Dictionary <string, string> para = new Dictionary <string, string>();

            para.Add($"Numbering", "12369999995");
            for (int i = 1; i < 38; i++)
            {
                para.Add($"Numbering{i}", "12365");
            }
            foreach (KeyValuePair <string, string> parameter in para)
            {
                pdfStamper.AcroFields.SetField(parameter.Key, parameter.Value);
            }
            //pdfStamper.AcroFields.SetField("Names", "李朝强");
            //pdfStamper.AcroFields.SetField("chk", "yes", true);
            pdfStamper.Close();
            pdfReader.Close();


            ////获取中文字体,第三个参数表示为是否潜入字体,但只要是编码字体就都会嵌入。
            //BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            ////读取模板文件
            //PdfReader reader = new PdfReader(@"C:\Users\Administrator\Desktop\temp123.pdf");

            ////创建文件流用来保存填充模板后的文件
            //MemoryStream stream = new MemoryStream();

            //PdfStamper stamp = new PdfStamper(reader, stream);
            ////设置表单字体,在高版本有用,高版本加入这句话就不会插入字体,低版本无用
            ////stamp.AcroFields.AddSubstitutionFont(baseFont);

            //AcroFields form = stamp.AcroFields;
            ////表单文本框是否锁定
            //stamp.FormFlattening = true;
            //Dictionary<string, string> para = new Dictionary<string, string>();
            //for (int i = 0; i < 38; i++)
            //{
            //    para.Add($"{i}", "tttt");
            //}


            ////填充表单,para为表单的一个(属性-值)字典
            //foreach (KeyValuePair<string, string> parameter in para)
            //{
            //    //要输入中文就要设置域的字体;
            //    form.SetFieldProperty(parameter.Key, "textfont", baseFont, null);
            //    //为需要赋值的域设置值;
            //    form.SetField(parameter.Key, parameter.Value);
            //}


            ////最后按顺序关闭io流

            //stamp.Close();
            //reader.Close();
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            char[] delimiterCharsFirst         = { '|' };
            char[] delimiterCharsSecond        = { ':' };
            Dictionary <string, string> Params = new Dictionary <string, string>();

            string input      = "";
            string output     = "";
            string parameters = "";

            for (int i = 0; i < args.Length; i++)
            {
                if (args[i] == "/input")
                {
                    if (!String.IsNullOrEmpty(args[i + 1]))
                    {
                        input = args[i + 1];
                    }
                    else
                    {
                        return;
                    }
                }
                if (args[i] == "/output")
                {
                    if (!String.IsNullOrEmpty(args[i + 1]))
                    {
                        output = args[i + 1];
                    }
                    else
                    {
                        return;
                    }
                }
                if (args[i] == "/parameters")
                {
                    if (!String.IsNullOrEmpty(args[i + 1]))
                    {
                        parameters = args[i + 1];
                    }
                    else
                    {
                        return;
                    }
                }
            }

            string[] elements = parameters.Split(delimiterCharsFirst);
            foreach (string element in elements)
            {
                string[] split_parameters = element.Split(delimiterCharsSecond);
                if (split_parameters.Length == 2)
                {
                    if (split_parameters[1].Trim() != "")
                    {
                        try
                        {
                            if (!Params.ContainsKey(split_parameters[0].Trim()))
                            {
                                Params.Add(split_parameters[0].Trim(), split_parameters[1].Trim());
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
            }

            try
            {
                var        doc     = new Document();
                PdfReader  reader  = new PdfReader(input);                                                  //Application.StartupPath + @"\input1.pdf" //input
                PdfStamper stamper = new PdfStamper(reader, new FileStream(output, FileMode.OpenOrCreate)); //Application.StartupPath + @"\output.pdf" //output
                AcroFields fields  = stamper.AcroFields;

                //if (fields.Fields.Count < Params.Count)
                //    return;

                BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\calibri.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                //Font font = FontFactory.GetFont(FontFactory.COURIER_BOLD, 11f, iTextSharp.text.Font.BOLD);
                fields.AddSubstitutionFont(baseFont);

                foreach (KeyValuePair <string, string> Par in Params)
                {
                    try
                    {
                        fields.SetFieldProperty(Par.Key, "textsize", 11f, null);
                        fields.SetField(Par.Key, Par.Value);
                    }
                    catch
                    {
                        continue;
                    }
                }
                stamper.FormFlattening     = false;
                fields.GenerateAppearances = true;
                stamper.Close();
                reader.Close();
            }
            catch (IOException e)
            {
                string console_string = @"<Директория исполняемой программы>/Setfielder.exe /input ""<Директория входного файла>\<Имя файла>.pdf"" /output ""<Директория выходного файла>\<Имя файла>.pdf"" /parameters ""name.0:Тест Тест Тест | zaemchik:Yes | name.3:Hello""";
                MessageBox.Show("Ошибка печати PDF макета: " + e.Message + "\r\nОбратитесь к программисту.\r\nПример строки запуска из консоли: " + console_string, "Проблема печати");
                return;
            }
        }
Esempio n. 18
0
        public void Templet(int NumberButten, String NameTable, String NameTemplet, BaseColor FontColor, String FontType, String Fontsize)
        {
            int    count_doc = 0;
            String Date_tody = DateTime.Now.ToString("d/M/yyyy");

            count = 0;

            cheaked_erorr_send = 0;


            foreach (DataGridViewRow it in guna2DataGridView1.Rows)
            {
                if (bool.Parse(it.Cells[0].Value.ToString()) == true)
                {
                    DB.CloseDB();


                    //    it.Cells[1].Value.ToString()

                    String Query = "Select [refNo],[fName],[lName],[mi],[email] ,[supervisorName] FROM[intern]where[refNo] = '" + it.Cells[1].Value.ToString() + "'";

                    count++;
                    SqlDataReader Read_Data_1 = DB.getDataFromDataDase(Query);
                    //path
                    pdfTemplate = Path_Templte + "\\" + NameTemplet;
                    // +".pdf"


                    Read_Data_1.Read();
                    //string name = Read_Data_1["arabicName"].ToString();
                    //get first name of intern
                    //  String[] cutFristName = name.Split(' ');
                    if (NumberButten == 1)
                    {
                        //" + Read_Data_1["refNo"].ToString() + "
                        newFile = txtUploadFile.Text.ToString() + "\\" + Read_Data_1["refNo"].ToString() + "_" + NameTemplet + ".pdf";
                    }
                    else
                    {
                        newFile = txtUploadFile.Text.ToString() + "\\" + Read_Data_1["refNo"].ToString() + "" + NameTemplet + ".pdf";
                        // newFile = Path_Files + "\\" + Read_Data_1["refNo"].ToString() + "_" + Read_Data_1["refNo"].ToString() + "_" + NameTemplet + ".pdf";
                    }
                    Read_Data_1.Close();
                    DB.CloseDB();
                    pdfReader     = new PdfReader(pdfTemplate);
                    pdfStamper    = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
                    pdfFormFields = pdfStamper.AcroFields;
                    //MAJALLA.TTF
                    var arialBaseFont = BaseFont.CreateFont(Path_language + "\\" + FontType + ".TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                    pdfFormFields.AddSubstitutionFont(arialBaseFont);


                    SqlDataReader dbm = DB.getDataFromDataDase(@"Select * from " + NameTable + "");

                    //for (int i = 0; i < Var.Length; i++)
                    dbm.Read();
                    int   i        = 0;
                    float FontSize = float.Parse(Fontsize);
                    while (i < dbm.FieldCount)//number column
                    {
                        //try                     name               omar
                        //{                      name column
                        pdfFormFields.SetFieldProperty(dbm.GetName(i), "textsize", FontSize, null);
                        pdfFormFields.SetFieldProperty(dbm.GetName(i), "textcolor", FontColor, null);
                        pdfFormFields.SetField(dbm.GetName(i), dbm[i].ToString());


                        pdfFormFields.SetFieldProperty(dbm.GetName(i), "setfflags", PdfFormField.FF_READ_ONLY, null);

                        i++;
                    }



                    pdfStamper.FormFlattening = false;


                    pdfStamper.Close();



                    if (NumberButten != 1)
                    {
                        Boolean cheakEmail = false;
                        if (NumberButten != 1)
                        {
                            if (NumberButten == 2)
                            {
                                String BodyEmail = @"Dear student:
thank you for end of internship this is your certificate";
                                Supject    = @"File# " + Read_Data_1["refNo"].ToString() + "_Distance Training 2020 for " + Read_Data_1["fName"].ToString() + Read_Data_1["lName"].ToString();
                                cheakEmail = EmailSend.SendEmaile(Read_Data_1["email"].ToString(), newFile, Supject, BodyEmail);
                            }
                            if (NumberButten == 3)
                            {
                                String MessgEmail = @"Dear Supervaisor:
this is your student information";
                                Supject    = "ID# " + Read_Data_1["collegeId"].ToString() + "Name#" + Read_Data_1["arabicName"].ToString();
                                cheakEmail = EmailSend.SendEmaile(Read_Data_1["supervisorName"].ToString(), newFile, Supject, MessgEmail);
                            }
                            if (cheakEmail == false)
                            {
                                cheaked_erorr_send++;
                                MessageBox.Show("Send Email Failure ((" + Read_Data_1["collegeId"].ToString() + ")" + Read_Data_1["arabicName"].ToString() + "");
                            }
                            else
                            {
                                File.Delete(newFile);
                            }
                        }
                    }
                    dbm.Close();
                }
            }


            if (count > 0)
            {
                if (cheaked_erorr_send != count)
                {
                    if (NumberButten == 1)
                    {
                        MessageBox.Show("Save successful.....");
                    }
                    else
                    {
                        MessageBox.Show("Send Email successful.....");
                    }
                }
            }
            else
            {
                MessageBox.Show("Please Chooes Intern");
            }
            pdfReader.Close();
            DB.CloseDB();
        }
Esempio n. 19
0
        public static response_item_type[] FillForm(pdf_stamper_request request, string mapping_root_path, string template_root_path, string output_root_path, DataTable data, string fonts_root_path, bool force_unc)
        {
            lock (_lock) {
                try {
                    List <Item> items_with_path = new List <Item>();
                    mappings    mapping         = new mappings();
                    if (File.Exists(mapping_root_path))
                    {
                        mapping = File.ReadAllText(mapping_root_path).DeserializeXml2 <mappings>();
                    }

                    FileInfo mapping_path = new FileInfo(mapping_root_path);

                    /*
                     * string fox_helper_path = Path.Combine(mapping_path.DirectoryName, "Fox.txt");
                     * if (!File.Exists(fox_helper_path)) {
                     *  StringBuilder b = new StringBuilder();
                     *  b.Append(@"
                     * DIMENSION laArray[30,2]
                     * laArray[1,1] = 'Obrazac1'
                     * laArray[2,1] = 'Obrazac2'
                     * laArray[3,1] = 'Obrazac3'
                     * laArray[4,1] = 'Obrazac4'
                     * laArray[5,1] = 'Obrazac5'
                     * laArray[6,1] = 'Obrazac6'
                     * laArray[7,1] = 'Obrazac7'
                     * laArray[8,1] = 'Obrazac8'
                     * laArray[9,1] = 'Obrazac9'
                     * laArray[10,1] ='Obrazac10'
                     * laArray[11,1] = 'Obrazac11'
                     * laArray[12,1] = 'Obrazac12'
                     * laArray[13,1] = 'Obrazac13'
                     * laArray[14,1] = 'Obrazac14'
                     * laArray[15,1] = 'Obrazac15'
                     * laArray[16,1] = 'Obrazac16'
                     * laArray[17,1] = 'Obrazac17'
                     * laArray[18,1] = 'Obrazac18'
                     * laArray[19,1] = 'Obrazac19'
                     * laArray[20,1] ='Obrazac20'
                     * laArray[21,1] = 'Obrazac21'
                     * laArray[22,1] = 'Obrazac22'
                     * laArray[23,1] = 'Obrazac23'
                     * laArray[24,1] = 'Obrazac24'
                     * laArray[25,1] = 'Obrazac25'
                     * laArray[26,1] = 'Obrazac26'
                     * laArray[27,1] = 'Obrazac27'
                     * laArray[28,1] = 'Obrazac28'
                     * laArray[29,1] = 'Obrazac29'
                     * laArray[30,1] ='Obrazac30'
                     * ");
                     *  int current_index = -1;
                     *  foreach (var item in mapping.mapping_item) {
                     *      current_index = Int32.Parse(item.pdf_template.ToString().Replace("Obrazac", ""));
                     *      string source_document_path = item.file_path.Replace("@root", template_root_path);
                     *      FileInfo info = new FileInfo(source_document_path);
                     *      string value = string.Format("laArray[{0},2] = '{1}'", current_index, info.Name.Replace(info.Extension,String.Empty));
                     *      b.AppendLine(value);
                     *  }
                     *  File.WriteAllText(fox_helper_path,b.ToString());
                     *
                     * }
                     */
                    if (data.Rows.Count == 0)
                    {
                        Logging.Singleton.WriteDebug("There is no data in the provided data table!");

                        foreach (var template in request.pdf_template_list)
                        {
                            mapping_item_type selected = mapping.mapping_item.Where(p => p.pdf_template == template).First();

                            string source_document_path = selected.file_path.Replace("@root", template_root_path);
                            items_with_path.Add(new Item()
                            {
                                Path = source_document_path, PdfTemplate = template
                            });
                        }
                        if (request.merge_output == true)
                        {
                            string merged_document_path = Path.Combine(output_root_path, String.Format("{0}_{1}{2}", "merged", DateTime.Now.ToFileTimeUtc().ToString(), ".pdf"));

                            PdfMerge merge = new PdfMerge();
                            foreach (var item in items_with_path)
                            {
                                merge.AddDocument(item.Path);
                            }
                            merge.EnablePagination = false;
                            merge.Merge(merged_document_path);
                            string result = Convert.ToBase64String(File.ReadAllBytes(merged_document_path));
                            return(new response_item_type[] { new response_item_type()
                                                              {
                                                                  pdf_template = template.MergedContent, data = force_unc? string.Empty : result, unc_path = merged_document_path
                                                              } });
                        }
                        else
                        {
                            List <response_item_type> items = new List <response_item_type>();
                            foreach (var item in items_with_path)
                            {
                                var temp = new response_item_type()
                                {
                                    pdf_template = item.PdfTemplate, data = force_unc ? string.Empty : Convert.ToBase64String(File.ReadAllBytes(item.Path)), unc_path = item.Path
                                };
                                items.Add(temp);
                            }
                            return(items.ToArray());
                        }
                    }
                    else
                    {
                        DataRow row    = data.Rows[0];
                        string  id_pog = string.Empty;
                        if (data.Columns.Contains("id_pog"))
                        {
                            id_pog = row["id_pog"].ToString();
                        }

                        if (request.debug_mode)
                        {
                            foreach (DataColumn column in data.Columns)
                            {
                                Logging.Singleton.WriteDebugFormat("Data column [{0}] has a value [{1}]", column.ToString(), row[column].ToString());
                            }
                        }

                        foreach (var template in request.pdf_template_list)
                        {
                            mapping_item_type selected = mapping.mapping_item.Where(p => p.pdf_template == template).First();

                            string   source_document_path = selected.file_path.Replace("@root", template_root_path);
                            FileInfo f = new FileInfo(source_document_path);

                            string destination_document_path = Path.Combine(output_root_path,
                                                                            String.Format("{0}_{1}_{2}{3}",
                                                                                          id_pog.Replace("/", "-").Trim(),
                                                                                          f.Name.Replace(f.Extension, ""),
                                                                                          DateTime.Now.ToFileTimeUtc().ToString(),
                                                                                          f.Extension)
                                                                            );

                            items_with_path.Add(new Item()
                            {
                                Path = destination_document_path, PdfTemplate = template
                            });

                            PdfReader reader = new PdfReader(source_document_path);
                            using (PdfStamper stamper = new PdfStamper(reader, new FileStream(destination_document_path, FileMode.Create))) {
                                AcroFields fields = stamper.AcroFields;


                                //Full path to the Unicode Arial file
                                //string ARIALUNI_TFF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");

                                //Create a base font object making sure to specify IDENTITY-H
                                //BaseFont bf = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

                                //Create a specific font object
                                //Font f = new Font(bf, 12, Font.NORMAL);
                                iTextSharp.text.pdf.BaseFont baseFont = iTextSharp.text.pdf.BaseFont.CreateFont(Path.Combine(fonts_root_path, "arial.ttf"), "Windows-1250", true);

                                fields.AddSubstitutionFont(baseFont);
                                if (request.debug_mode)
                                {
                                    foreach (var key in fields.Fields.Keys)
                                    {
                                        Logging.Singleton.WriteDebugFormat("Pdf field [{0}]. Data type [{1}]", key, fields.GetFieldType(key));
                                    }
                                }

                                foreach (var key in fields.Fields.Keys)
                                {
                                    var items = selected.mapping.Where(p => p.data_field == key);
                                    if (items.Count() == 1)
                                    {
                                        var item = items.First();
                                        if (item.column_name == UNKNOWN)
                                        {
                                            continue;
                                        }
                                        if (data.Columns.Contains(item.column_name))
                                        {
                                            string value = row[item.column_name].ToString();

                                            if (item.field_type == data_field_type.CheckBox)
                                            {
                                                int  int_value     = 0;
                                                bool boolean_value = false;
                                                if (Int32.TryParse(value, out int_value))
                                                {
                                                    value = int_value == 0? "No" : "Yes";
                                                }
                                                else if (Boolean.TryParse(value, out boolean_value))
                                                {
                                                    value = boolean_value == false? "No" : "Yes";
                                                }
                                                else
                                                {
                                                    throw new NotImplementedException(string.Format("Invalid Value [{0}] was provided for Check box type field!", value));
                                                }
                                            }
                                            fields.SetField(key, value);
                                        }
                                        else
                                        {
                                            Logging.Singleton.WriteDebugFormat("Column {0} does not belong to table {1}! Check your mappings for template {2}", item.column_name, data.TableName, template);
                                        }
                                    }
                                    else if (items.Count() == 0)
                                    {
                                        var current = selected.mapping.ToList();

                                        data_field_type field_type = data_field_type.Text;
                                        if (key.Contains("Check"))
                                        {
                                            field_type = data_field_type.CheckBox;
                                        }
                                        else if (key.Contains("Radio"))
                                        {
                                            field_type = data_field_type.RadioButton;
                                        }

                                        current.Add(new mapping_type()
                                        {
                                            column_name = UNKNOWN, data_field = key, field_type = field_type
                                        });

                                        selected.mapping = current.ToArray();

                                        File.WriteAllText(mapping_root_path, mapping.SerializeXml());
                                    }
                                    else
                                    {
                                        throw new NotImplementedException();
                                    }
                                }
                                // flatten form fields and close document
                                if (request.read_only || (request.merge_output && request.pdf_template_list.Length > 1))
                                {
                                    Logging.Singleton.WriteDebugFormat("Form flattening requested... Read only {0}, Merge output {1}, Template list count {2}", request.read_only, request.merge_output, request.pdf_template_list.Length);
                                    stamper.FormFlattening = true;
                                }

                                stamper.Close();
                            }
                        }
                        if (items_with_path.Count() == 1)
                        {
                            string path   = items_with_path.First().Path;
                            var    bytes  = File.ReadAllBytes(path);
                            string result = Convert.ToBase64String(bytes);
                            Logging.Singleton.WriteDebugFormat("Response lenght is {0} bytes", bytes.Length);
                            return(new response_item_type[] { new response_item_type()
                                                              {
                                                                  pdf_template = items_with_path.First().PdfTemplate, data = force_unc ? string.Empty : result, unc_path = path
                                                              } });
                            //return new response_item_type[] { new response_item_type() { pdf_template = items_with_path.First().PdfTemplate, data = Convert.ToBase64String(new byte[] {1,2,3,4,5,6,7,8,9}) } };
                        }
                        else
                        {
                            if (request.merge_output == true)
                            {
                                string merged_document_path = Path.Combine(output_root_path, String.Format("{0}_{1}{2}{3}", id_pog.Replace("/", "-").Trim(), "merged", DateTime.Now.ToFileTimeUtc().ToString(), ".pdf"));

                                //List<string> file_names = new List<string>();
                                //foreach (var item in items_with_path) {
                                //    file_names.Add(item.Path);
                                //}
                                //var path = MergePdfForms(file_names, merged_document_path);

                                PdfMerge merge = new PdfMerge();
                                foreach (var item in items_with_path)
                                {
                                    merge.AddDocument(item.Path);
                                }



                                merge.EnablePagination = false;
                                merge.Merge(merged_document_path);
                                //using (FileStream file = new FileStream(merged_document_path, FileMode.Create, System.IO.FileAccess.Write)) {
                                //    byte[] bytes = new byte[stream.Length];
                                //    stream.Read(bytes, 0, (int)stream.Length);
                                //    file.Write(bytes, 0, bytes.Length);
                                //    stream.Close();
                                //}

                                var    bytes  = File.ReadAllBytes(merged_document_path);
                                string result = Convert.ToBase64String(bytes);
                                Logging.Singleton.WriteDebugFormat("Response lenght is {0} bytes", bytes.Length);
                                return(new response_item_type[] { new response_item_type()
                                                                  {
                                                                      pdf_template = template.MergedContent, data = force_unc ? string.Empty : result, unc_path = merged_document_path
                                                                  } });
                            }
                            else
                            {
                                List <response_item_type> items = new List <response_item_type>();
                                foreach (var item in items_with_path)
                                {
                                    var    bytes  = File.ReadAllBytes(item.Path);
                                    string result = Convert.ToBase64String(bytes);
                                    Logging.Singleton.WriteDebugFormat("Response lenght is {0} bytes", bytes.Length);
                                    var temp = new response_item_type()
                                    {
                                        pdf_template = item.PdfTemplate, data = force_unc ? string.Empty : result, unc_path = item.Path
                                    };
                                    //var temp = new response_item_type() { pdf_template = item.PdfTemplate, data = Convert.ToBase64String(new byte[] {1,2,3,4,5,6,7,8,9}) };
                                    items.Add(temp);
                                }

                                return(items.ToArray());
                            }
                        }
                    }
                }
                catch (Exception ex) {
                    string message = Logging.CreateExceptionMessage(ex);
                    Logging.Singleton.WriteDebug(message);
                    return(null);
                }
            }
        }
Esempio n. 20
0
        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folder = new FolderBrowserDialog();

            folder.ShowDialog();

            var path = folder.SelectedPath;

            if (string.IsNullOrEmpty(txtBelgeNo.Text))
            {
                MessageBox.Show("Belge No girmediniz!");
            }
            else if (string.IsNullOrEmpty(path))
            {
                MessageBox.Show("Geçerli bir dosya yolu seçin!");
            }
            else
            {
                var result = 0;
                try
                {
                    using (var conn = new SQLiteConnection(ConnStr))
                    {
                        var checkCmd = new SQLiteCommand("select count(*) from FaturaNo where BelgeNo=@belgeno", conn);
                        checkCmd.Parameters.AddWithValue("@belgeno", txtBelgeNo.Text.Trim());
                        conn.Open();
                        var checkResult = (long)checkCmd.ExecuteScalar();
                        if (checkResult == 0)
                        {
                            var cmd = new SQLiteCommand("INSERT INTO FaturaNo (BelgeNo,CrtDate) values (@belgeno,@CrtDate);", conn);
                            cmd.Parameters.AddWithValue("@belgeno", txtBelgeNo.Text.Trim());
                            cmd.Parameters.AddWithValue("@CrtDate", DateTime.Now);

                            result = cmd.ExecuteNonQuery();

                            if (result > 0)
                            {
                                // Template dosyası okunuyor...
                                PdfReader  pdfReader     = new PdfReader("2.pdf");
                                var        fileName      = path + "\\Fatura_" + txtAdSoyad.Text.Replace(' ', '_') + ".pdf";
                                PdfStamper pdfStamper    = new PdfStamper(pdfReader, new FileStream(fileName, FileMode.Create));
                                AcroFields pdfFormFields = pdfStamper.AcroFields;


                                // Türkçe karakter için font seçiliyor...
                                BaseFont ARIAL = BaseFont.CreateFont("C:\\windows\\fonts\\arial.ttf", "windows-1254", true);
                                pdfFormFields.AddSubstitutionFont(ARIAL);
                                foreach (var f in pdfReader.AcroFields.Fields)
                                {
                                    pdfFormFields.SetFieldProperty(f.Key.ToString(), "textsize", (float)7, null);
                                }

                                pdfFormFields.SetField("AdSoyad", txtAdSoyad.Text.Trim());
                                pdfFormFields.SetField("Sehir", txtSehir.Text.Trim());
                                pdfFormFields.SetField("TCKimlikno", txtTc.Text.Trim());
                                pdfFormFields.SetField("BelgeNo", txtBelgeNo.Text.Trim());
                                pdfFormFields.SetField("FaturaTarihi", txtFaturaTarihi.Text.Trim());
                                pdfFormFields.SetField("DuzenlemeTarihi", txtDuzenlemeTarihi.Text.Trim());
                                pdfFormFields.SetField("DuzenlemeZamani", txtDuzenlemeZamani.Text.Trim());
                                pdfFormFields.SetField("Ettn", txtEttn.Text.Trim());

                                pdfFormFields.SetField("Kod", txtMalKod.Text.Trim());
                                pdfFormFields.SetField("MalAd", txtMalAd.Text.Trim());
                                pdfFormFields.SetField("MalAciklama", txtMalAciklama.Text.Trim());
                                pdfFormFields.SetField("Miktar", txtMalMiktar.Text.Trim() + " ADET");
                                pdfFormFields.SetField("BirimFiyat", txtMalBirimFiyat.Text.Trim() + " TL");
                                pdfFormFields.SetField("KdvOrani", "% " + txtMalKdvOrani.Text.Trim());
                                pdfFormFields.SetField("KdvTutar", txtMalKdvTutar.Text.Trim() + " TL");
                                pdfFormFields.SetField("HizmetTutar", txtMalTutar.Text.Trim() + " TL");

                                pdfFormFields.SetField("ToplamTutar", txtToplamTutar.Text.Trim() + " TL");
                                pdfFormFields.SetField("HesaplananKdv", txtHesaplananKdv.Text.Trim() + " TL");
                                pdfFormFields.SetField("VergilerDahilToplam", txtToplamVergi.Text.Trim() + " TL");
                                pdfFormFields.SetField("OdenecekTutar", txtOdenecekTutar.Text.Trim() + " TL");

                                pdfFormFields.SetField("OdemeKosulu", txtOdemeKosulu.Text.Trim());
                                pdfFormFields.SetField("GenelAciklama", txtGenelAciklama.Text.Trim());
                                pdfFormFields.SetField("KartNo", txtKartNo.Text.Trim());

                                pdfStamper.Close();
                                MessageBox.Show("Belge Kaydedildi");
                            }
                            else
                            {
                                MessageBox.Show("Belge Kaydedilemedi!", "UYARI");
                            }
                        }
                        else
                        {
                            MessageBox.Show("Belge No Daha önce kullanılmış");
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Hata Oldu: " + ex.ToString());
                }
            }
        }
Esempio n. 21
0
        protected void Akt_Click(object sender, EventArgs e)
        {
            //блок формирования акта
            if (Label1.Text == "")
            {
                Msg.Text = "Для формирования актов требуется ПИН-код!"; return;
            }
            string PodpEmic = Spec + " " + WorkPin;

            using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DefaultConnection"].ToString()))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("select t.Ttx from Ttx t " +
                                                "join LiftsTtx l on l.TtxId=t.Id " +
                                                //   "join Ttx tt on tt.Id=t.Id " +
                                                "where t.TtxTitleId=1 and l.LiftId=@t", conn);
                cmd.Parameters.AddWithValue("t", LiftId.SelectedValue);
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    adrs = dr[0].ToString();
                }
                dr.Close();
                cmd = new SqlCommand("select PlantNum from PhisicalAddr where LiftId=@lift", conn);
                cmd.Parameters.AddWithValue("lift", LiftId.Text);
                SqlDataReader dn = cmd.ExecuteReader();
                if (dn.Read())
                {
                    numlift = dn[0].ToString();
                }
                dn.Close();
                int    _wz = 0;
                string dat = DateTime.Now.Date.ToLongDateString();
                string dd  = DateTime.Now.Day.ToString();
                string mm  = DateTime.Now.Month.ToString();
                string yy  = DateTime.Now.Year.ToString();
                string hh  = DateTime.Now.Hour.ToString() + "час." + DateTime.Now.Minute.ToString() + "мин.";
                _wz = Int32.Parse(NumEvent.Text);
                App_Code.Base db       = new App_Code.Base(WebConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
                DataTable     data     = db.GetEvent(_wz);
                string        worker   = data.Rows[0]["Family"].ToString() + " " + data.Rows[0]["IO"].ToString();
                BaseFont      baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\Arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                if (TypeAkt.SelectedValue == "Акт дефектовки")
                {
                    PdfReader  template = new PdfReader(@"C:\temp\aktDef.pdf"); // файл шаблона
                    PdfStamper stamper  = new PdfStamper(template, new FileStream(@"C:\temp\akt.pdf", FileMode.Create));
                    AcroFields fields   = stamper.AcroFields;
                    fields.AddSubstitutionFont(baseFont);
                    fields.SetField("NaktDef", NumEvent.Text + "-А1.1"); //номер акта
                    fields.SetField("adr", adrs);
                    fields.SetField("Nlift", LiftId.SelectedValue + " № " + numlift);
                    fields.SetField("opis1", Text.Text);
                    fields.SetField("lift", LiftId.SelectedValue);
                    fields.SetField("opis1", data.Rows[0]["EventId"].ToString());
                    fields.SetField("fill_6", Chel.SelectedValue);
                    fields.SetField("fill_7", Chas.SelectedValue);
                    fields.SetField("dateS", dd + "." + mm + "." + yy + "г.");
                    fields.SetField("dateP", dd + "." + mm + "." + yy + "г.");
                    fields.SetField("Podt", FamZak.Text);
                    fields.SetField("Sost", Label1.Text);
                    fields.SetField("name1", Name1.Text);
                    if (Name1.Text != "")
                    {
                        fields.SetField("npp1", " 1.");
                    }
                    fields.SetField("name2", Name2.Text);
                    if (Name2.Text != "")
                    {
                        fields.SetField("npp2", " 2.");
                    }
                    fields.SetField("name3", Name3.Text);
                    if (Name3.Text != "")
                    {
                        fields.SetField("npp3", " 3.");
                    }
                    fields.SetField("name4", Name4.Text);
                    if (Name4.Text != "")
                    {
                        fields.SetField("npp4", " 4.");
                    }
                    fields.SetField("name5", Name5.Text);
                    if (Name5.Text != "")
                    {
                        fields.SetField("npp5", " 5.");
                    }
                    fields.SetField("obz1", Obz1.Text);
                    fields.SetField("obz2", Obz2.Text);
                    fields.SetField("obz3", Obz3.Text);
                    fields.SetField("obz4", Obz4.Text);
                    fields.SetField("obz5", Obz5.Text);
                    fields.SetField("ID1", ID1.Text);
                    fields.SetField("ID2", ID2.Text);
                    fields.SetField("ID3", ID3.Text);
                    fields.SetField("ID4", ID4.Text);
                    fields.SetField("ID5", ID5.Text);
                    fields.SetField("kol1", Kol1.Text);
                    fields.SetField("kol2", Kol2.Text);
                    fields.SetField("kol3", Kol3.Text);
                    fields.SetField("kol4", Kol4.Text);
                    fields.SetField("kol5", Kol5.Text);
                    stamper.FormFlattening = false;// ложь - открыт для записи, истина - закрыт
                    stamper.Close();
                    // запись в БД
                    FileStream fs  = new FileStream(@"C:\temp\akt.pdf", FileMode.Open);
                    Byte[]     pdf = new byte[fs.Length];
                    fs.Read(pdf, 0, pdf.Length);
                    cmd = new SqlCommand("insert into Documents (Name, NumEvent, Image, NameFile, Status, Usr) values (@name, @nev, @img, @namefile, @st, @usr )", conn);
                    cmd.Parameters.AddWithValue("name", "акт дефектовки");
                    cmd.Parameters.AddWithValue("nev", NumEvent.Text);
                    cmd.Parameters.AddWithValue("usr", Label1.Text);
                    cmd.Parameters.Add("img", SqlDbType.Image).Value         = pdf;
                    cmd.Parameters.Add("namefile", SqlDbType.NVarChar).Value = NumEvent.Text + "-A1_1.pdf";
                    cmd.Parameters.AddWithValue("st", "не подписан заказчиком");
                    cmd.ExecuteNonQuery();
                    fs.Close();

                    /*     string commandText = @"C:\temp\akt.pdf";
                     *   var proc = new System.Diagnostics.Process();
                     *   proc.StartInfo.FileName = commandText;
                     *   proc.StartInfo.UseShellExecute = true;
                     *   proc.Start();
                     */
                    Response.ContentType = "image"; //image/Jpeg
                    Response.BinaryWrite(pdf);
                }
                else if (TypeAkt.SelectedValue == "Акт повреждения оборудования")
                {
                    PdfReader  template = new PdfReader(@"C:\temp\aktPovr.pdf"); // файл шаблона
                    PdfStamper stamper  = new PdfStamper(template, new FileStream(@"C:\temp\akt.pdf", FileMode.Create));
                    AcroFields fields   = stamper.AcroFields;
                    fields.AddSubstitutionFont(baseFont);
                    fields.SetField("NaktPovr", NumEvent.Text + "-А3.1"); //номер акта
                    fields.SetField("adr", adrs);
                    fields.SetField("Nlift", LiftId.SelectedValue + " № " + numlift);
                    fields.SetField("opis1", Text.Text);
                    fields.SetField("lift", LiftId.SelectedValue);
                    fields.SetField("opis1", data.Rows[0]["EventId"].ToString());
                    fields.SetField("fill_6", Chel.SelectedValue);
                    fields.SetField("fill_7", Chas.SelectedValue);
                    fields.SetField("dateS", dd + "." + mm + "." + yy + "г.");
                    fields.SetField("dateP", dd + "." + mm + "." + yy + "г.");
                    fields.SetField("Podt", FamZak.Text);
                    fields.SetField("Sost", Label1.Text);
                    fields.SetField("name1", Name1.Text);
                    if (Name1.Text != "")
                    {
                        fields.SetField("npp1", " 1.");
                    }
                    fields.SetField("name2", Name2.Text);
                    if (Name2.Text != "")
                    {
                        fields.SetField("npp2", " 2.");
                    }
                    fields.SetField("name3", Name3.Text);
                    if (Name3.Text != "")
                    {
                        fields.SetField("npp3", " 3.");
                    }
                    fields.SetField("name4", Name4.Text);
                    if (Name4.Text != "")
                    {
                        fields.SetField("npp4", " 4.");
                    }
                    fields.SetField("name5", Name5.Text);
                    if (Name5.Text != "")
                    {
                        fields.SetField("npp5", " 5.");
                    }
                    fields.SetField("obz1", Obz1.Text);
                    fields.SetField("obz2", Obz2.Text);
                    fields.SetField("obz3", Obz3.Text);
                    fields.SetField("obz4", Obz4.Text);
                    fields.SetField("obz5", Obz5.Text);
                    fields.SetField("ID1", ID1.Text);
                    fields.SetField("ID2", ID2.Text);
                    fields.SetField("ID3", ID3.Text);
                    fields.SetField("ID4", ID4.Text);
                    fields.SetField("ID5", ID5.Text);
                    fields.SetField("kol1", Kol1.Text);
                    fields.SetField("kol2", Kol2.Text);
                    fields.SetField("kol3", Kol3.Text);
                    fields.SetField("kol4", Kol4.Text);
                    fields.SetField("kol5", Kol5.Text);
                    stamper.FormFlattening = false;
                    stamper.Close();
                    // запись в БД
                    FileStream fs  = new FileStream(@"C:\temp\akt.pdf", FileMode.Open);
                    Byte[]     pdf = new byte[fs.Length];
                    fs.Read(pdf, 0, pdf.Length);
                    cmd = new SqlCommand("insert into Documents (Name, NumEvent, Image, NameFile, Status, Usr) values (@name, @nev, @img, @namefile, @st, @usr )", conn);
                    cmd.Parameters.AddWithValue("name", "акт повреждения оборудования");
                    cmd.Parameters.AddWithValue("nev", NumEvent.Text);
                    cmd.Parameters.AddWithValue("usr", Label1.Text);
                    cmd.Parameters.Add("img", SqlDbType.Image).Value         = pdf;
                    cmd.Parameters.Add("namefile", SqlDbType.NVarChar).Value = NumEvent.Text + "-A3_1.pdf";
                    cmd.Parameters.AddWithValue("st", "не подписан заказчиком");
                    cmd.ExecuteNonQuery();
                    fs.Close();

                    /*   string commandText = @"C:\temp\akt.pdf";
                     *  var proc = new System.Diagnostics.Process();
                     *  proc.StartInfo.FileName = commandText;
                     *  proc.StartInfo.UseShellExecute = true;
                     *  proc.Start();
                     */
                    Response.ContentType = "image"; //image/Jpeg
                    Response.BinaryWrite(pdf);
                }
            }
        }