예제 #1
0
        public async void SpireChange(string url)
        {
            //url = "https://openapi.bestsign.info/openapi/v2/storage/contract/download/?developerId=1552635811012161536&rtick=15879806269530&signType=rsa&sign=QIAwfvzYdj2VyEZiPQq10TkDhxxwnBPZQzuvfjSeER9qNcuff6fp6zI34UrnRyM8FQURyRaEt98H37Ntnccdv12SZ0KN1CRu1w3%2F0EODcZVfUMFucotHOGgoAagBHrZQS6Zc9rvDWaNazYQFRW8hYS3XnmDaQkCqSJ%2FOt%2BRqcNVX8hvyZkYqSuU6GDz7JbtdKV%2B2glUfGJyeNPQcLuzTFTqrLGwOIwRrela6f0CafNkwfpOURvkiTUgf0Hd4Gt5OXw22%2FL2EDYvEaXlIjyastkGc2WXLcNGMnTAk7HTKfULcmEFyBzVKYeuvhAt6pCDW01M7kQQPXi%2Fi6KA5KhZ%2F%2Bw%3D%3D&contractId=158797930501000001";
            url = "https://openapi.bestsign.info/openapi/v2/storage/contract/download/?developerId=1552635811012161536&rtick=15895128046650&signType=rsa&sign=Gh6GoWVXqfB%2FvGSn1TcXKfr%2Fjl4TdaQggmDSLfDHaUoduJXvns1r7ZlVFi9Q2HVtipuSiqYl0DnfTSoRDdd42LQOgB9BL56N9UJXB0D8tK4u3CZd7xtNCi%2Fwr%2BeyXi%2FvaiupJeIZnaXGL1rfsE%2BowLGJyFmbBhnpWMZze9v2Q3rXm49YvXrVZam0yYXU56v3UfLAwZh1zwGj5mVbLgW1UMAqfLRJnP%2FJVfRJZQrJ7Zl1uQxgZGRQjjilghbijTkA3Z3%2Fy9I1fV4JCW7QPbciBFyrg7wXFSAnKnuqGPbBRXsQpxdEdYYRAyw4H%2Be3kOE1ccOoROpxH%2Bc7qEiJRdVgkA%3D%3D&contractId=158797930501000001";
            //加载文档
            Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
            byte[] buffer             = await GetStream(url);

            doc.LoadFromBytes(buffer);
            StringBuilder str       = new StringBuilder();
            List <Image>  ListImage = new List <Image>();

            foreach (PdfPageBase page in doc.Pages)
            {
                // 获取所有pages里面的图片
                Image[] images = page.ExtractImages();
                if (images != null && images.Length > 0)
                {
                    ListImage.AddRange(images);
                }

                str.Append(page.ExtractText().Replace("Evaluation Warning : The document was created with Spire.PDF for .NET.", ""));

                /*PdfTextFind[] result = page.FindText("使用人确认签字", TextFindParameter.None).Finds;
                 * foreach (PdfTextFind text in result)
                 * {
                 *  //获取文字的坐标,宽度和高度
                 *  PointF pf = text.Position;
                 *  SizeF size = text.Size;
                 *  pf.X = pf.X;
                 *  pf.Y = pf.Y;
                 *  str.Append(pf + " size:" + size + Environment.NewLine);
                 * }*/
            }

            // 将提取到的图片保存到本地路径
            //if (ListImage.Count > 0)
            {
                for (int i = 0; i < ListImage.Count; i++)
                {
                    Image image = ListImage[i];
                    image.Save("image" + (i + 1).ToString() + ".png", System.Drawing.Imaging.ImageFormat.Png);
                }
            }

            doc.SaveToFile("PDF.html", FileFormat.HTML);
            doc.SaveToFile("下载.pdf", FileFormat.PDF);
            this.richTextBox1.Text = str.ToString();
        }
예제 #2
0
        /// <summary>
        /// 生成报表文件
        /// </summary>
        /// <param name="logpath">报表路径</param>
        /// <param name="log">报表内容</param>
        public static string WriteLogs(string logpath, string log)
        {
            string _Date = DateTime.Now.ToString("yyyy-MM-dd-hh-mm");

            Spire.Pdf.PdfDocument document = new Spire.Pdf.PdfDocument();

            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
            PdfMargins       margins  = new PdfMargins();
            PdfPageBase      page     = document.Pages.Add(PdfPageSize.A3, margins);

            PdfTrueTypeFont TitleFont = new PdfTrueTypeFont(new Font("宋体", 30f), true);

            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("宋体", 14f), true);
            PdfPen          pen  = new PdfPen(Color.Black);

            string text = log
                          + "\r\n\r\n" +
                          "检测时间:" + DateTime.Now;

            page.Canvas.DrawString("检测报告", TitleFont, pen, 350, 10);
            page.Canvas.DrawString(text, font, pen, 100, 50);

            string path = logpath + "\\" + _Date + ".pdf";

            document.SaveToFile(path);
            return(path);
        }
예제 #3
0
        public static void PrintPDF(DataTable dt, string path)
        {
            //新建PDF文档
            Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument();
            //添加页面
            PdfPageBase page = pdf.Pages.Add();
            //创建表格
            PdfTable table = new PdfTable();

            //将DataGridView的数据导入到表格
            table.DataSource = dt;

            //显示表头(默认为不显示)
            table.Style.ShowHeader = true;

            //设置单元格内容与边框的间距
            table.Style.CellPadding = 2;

            //设置表格的布局 (超过一页自动将表格续写到下一页)
            PdfTableLayoutFormat tableLayout = new PdfTableLayoutFormat();

            tableLayout.Break  = PdfLayoutBreakType.FitElement;
            tableLayout.Layout = PdfLayoutType.Paginate;

            //添加自定义事件
            table.BeginRowLayout += new BeginRowLayoutEventHandler(table_BeginRowLayout);

            //将表格绘制到页面并指定绘制的位置和范围
            table.Draw(page, new RectangleF(10, 50, 300, 300), tableLayout);

            pdf.SaveToFile(path);
            File.Open(path, FileMode.Open);
        }
예제 #4
0
파일: Preview.cs 프로젝트: radtek/PTS---git
        private bool CreateReportPdf(string docFile, string pdfFileExport)
        {
            try
            {
                Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument();

                PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
                PdfMargins       margin   = new PdfMargins();
                margin.Top    = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
                margin.Bottom = margin.Top;
                margin.Left   = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
                margin.Right  = margin.Left;

                PdfPageBase page = pdf.Pages.Add(PdfPageSize.A4, margin, PdfPageRotateAngle.RotateAngle0, PdfPageOrientation.Landscape);

                String rtf = System.IO.File.ReadAllText(docFile);
                page.LoadFromRTF(rtf, page.Canvas.ClientSize.Width, true);

                pdf.SaveToFile(pdfFileExport);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
예제 #5
0
        public static string ConvertePdfParaXps(string caminhoPdf)
        {
            string caminhoXps = caminhoPdf.Replace(".pdf", "Xps.xps");

            Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
            doc.LoadFromFile(caminhoPdf);
            doc.SaveToFile(caminhoXps, FileFormat.XPS);
            doc.Close();
            return(caminhoXps);
        }
예제 #6
0
        private void button1_Click(object sender, EventArgs e)
        {
            #region   将pdf分成许多份小文档
            Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument();
            pdf.LoadFromFile(textBox1.Text);
            label4.Text = "转换中......";
            label4.Refresh();
            for (int i = 0; i < pdf.Pages.Count; i += 5)
            {
                int j = 0;
                Spire.Pdf.PdfDocument newpdf = new Spire.Pdf.PdfDocument();
                for (j = i; j >= i && j <= i + 4; j++)
                {
                    if (j < pdf.Pages.Count)
                    {
                        Spire.Pdf.PdfPageBase page;
                        page = newpdf.Pages.Add(pdf.Pages[j].Size, new Spire.Pdf.Graphics.PdfMargins(0));
                        pdf.Pages[j].CreateTemplate().Draw(page, new PointF(0, 0));
                    }
                }
                newpdf.SaveToFile(textBox2.Text + "\\" + j.ToString() + ".pdf");
                PdfExtractWordAndPicture(textBox2.Text, j.ToString());
            }
            #endregion


            #region  合并word文档

            string filePath0 = textBox2.Text + "\\" + '5' + ".doc";
            for (int i = 10; i <= 0 - pdf.Pages.Count % 5 + pdf.Pages.Count; i += 5)
            {
                string filePath2 = textBox2.Text + "\\" + i.ToString() + ".doc";

                Spire.Doc.Document doc = new Spire.Doc.Document(filePath0);
                doc.InsertTextFromFile(filePath2, Spire.Doc.FileFormat.Doc);

                doc.SaveToFile(filePath0, Spire.Doc.FileFormat.Doc);
            }
            Spire.Doc.Document mydoc1 = new Spire.Doc.Document();
            mydoc1.LoadFromFile(textBox2.Text + "\\" + '5' + ".doc");
            mydoc1.SaveToFile(textBox2.Text + "\\" + "TheLastTransform" + ".doc", Spire.Doc.FileFormat.Doc);

            for (int i = 5; i <= 5 - pdf.Pages.Count % 5 + pdf.Pages.Count; i += 5)
            {
                File.Delete(textBox2.Text + "\\" + i.ToString() + ".doc");
                File.Delete(textBox2.Text + "\\" + i.ToString() + ".pdf");
            }

            #endregion

            label4.Text = "转换完成";
            label4.Refresh();
        }
예제 #7
0
        private void button8_Click(object sender, EventArgs e)
        {
            Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
            doc.LoadFromFile(@"\\192.168.12.33\inhouse-tax-documents\Supporting Documents.pdf");
            int    no_Of_Pages = doc.Pages.Count;
            string Author_Name = doc.DocumentInformation.Author.ToString();
            string Title       = doc.DocumentInformation.Title.ToString();

            doc.DocumentInformation.Author = "Test";
            doc.DocumentInformation.Title  = "niranjan";



            doc.SaveToFile(@"\\192.168.12.33\inhouse-tax-documents\Supporting Documents.pdf");
        }
예제 #8
0
        private void BtnRotate_ClickOrKeyPress(object sender, EventArgs e)
        {
            DataRow[] rPdfFiles = _dsPdfFiles.Tables["PDFFiles"].Select("Id = '" + _idActivePdf + "'");

            Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();

            doc.LoadFromFile(rPdfFiles[0]["PathAndFileName"].ToString());

            PdfPageBase page = doc.Pages[0];

            int rotation = (int)page.Rotation;

            // jeśli obracanie zostało wywołane klawiszem
            if (e.GetType() == typeof(KeyEventArgs))
            {
                KeyEventArgs arg = (KeyEventArgs)e;

                rotation += arg.KeyData == (Keys.Control | Keys.Right) ? (int)PdfPageRotateAngle.RotateAngle90 : (int)PdfPageRotateAngle.RotateAngle270;
            }

            // jeśli obracanie zostało wywołane myszką
            if (e.GetType() == typeof(MouseEventArgs))
            {
                MouseEventArgs arg = (MouseEventArgs)e;

                if (arg.Button == MouseButtons.Left)
                {
                    rotation += (int)PdfPageRotateAngle.RotateAngle270;
                }
                else if (arg.Button == MouseButtons.Right)
                {
                    rotation += (int)PdfPageRotateAngle.RotateAngle90;
                }
            }

            page.Rotation = (PdfPageRotateAngle)rotation;

            doc.SaveToFile(rPdfFiles[0]["PathAndFileName"].ToString());

            pdfDocumentViewer.LoadFromFile(rPdfFiles[0]["PathAndFileName"].ToString());

            _zoom = GetZoom(rPdfFiles[0]["PathAndFileName"].ToString());

            pdfDocumentViewer.ZoomTo(_zoom);

            pdfDocumentViewer.EnableHandTool();
        }
예제 #9
0
        private void PdfToWord_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();

            openFile.Filter = "Text Documents (.pdf)|*.pdf|All files (*.*) | *.*";
            var result = openFile.ShowDialog();

            if (result == true)
            {
                var path     = openFile.FileName;
                var fileName = openFile.SafeFileName;
                Spire.Pdf.PdfDocument pdfDoc = new Spire.Pdf.PdfDocument();
                pdfDoc.LoadFromFile(path);

                pdfDoc.ConvertOptions.SetPdfToDocOptions();
                pdfDoc.SaveToFile(System.IO.Path.Combine(BasePath, $"{fileName}.doc"), Spire.Pdf.FileFormat.DOC);
                pdfDoc.Close();
                pdfDoc.Dispose();
            }
        }
예제 #10
0
        //文档地址 https://www.e-iceblue.cn/spirepdfnet/spire-pdf-for-net-program-guide-content.html


        /// <summary>
        /// Spire插件添加二维码到PDF
        /// </summary>
        /// <param name="sourcePdf">pdf文件路径</param>
        /// <param name="sourceImg">二维码图片路径</param>
        public static void AddQrCodeToPdf(string sourcePdf, string sourceImg)
        {
            //初始化PdfDocument实例,导入PDF文件
            Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();

            //加载现有文档
            doc.LoadFromFile(sourcePdf);
            //添加一个空白页,目的为了删除jar包添加的水印,后面再移除这一页  (没有用)
            //PdfPageBase pb = doc.Pages.Add();
            //获取第二页
            //PdfPageBase page = doc.Pages[1];
            //获取第1页
            PdfPageBase page = doc.Pages[0];
            //加载图片到Image对象
            Image image = Image.FromFile(sourceImg);

            //调整图片大小
            int    width       = image.Width;
            int    height      = image.Height;
            float  scale       = 0.18f; //缩放比例0.18f;
            Size   size        = new Size((int)(width * scale), (int)(height * scale));
            Bitmap scaledImage = new Bitmap(image, size);

            //加载缩放后的图片到PdfImage对象
            Spire.Pdf.Graphics.PdfImage pdfImage = Spire.Pdf.Graphics.PdfImage.FromImage(scaledImage);

            //设置图片位置
            float x = 516f;
            float y = 8f;

            //在指定位置绘入图片
            //page.Canvas.DrawImage(pdfImage, x, y);
            page.Canvas.DrawImage(pdfImage, new PointF(x, y), size);
            //移除第一个页
            //doc.Pages.Remove(pb); //去除第一页水印
            //保存文档
            doc.SaveToFile(@sourcePdf);
            doc.Close();
            //释放图片资源
            image.Dispose();
        }
예제 #11
0
        public ActionResult getModel(FormModel postedModel)
        {
            RootObject MODELFROMDATABASE = new RootObject();
            PDFModel   PDFmdoel          = new PDFModel()
            {
                DuraionTime  = postedModel.formfillingtime,
                OperatorID   = postedModel.phone,
                hospitalName = GlobalVariables.name,
                timestamp    = postedModel.timestamp,
                PDFTitle     = postedModel.title,
                catID        = postedModel.catID,
            };

            if (GlobalVariables.address == "" || GlobalVariables.address == null)
            {
                string json = "";
                using (var client = new WebClient())
                {
                    json = client.DownloadString("http://www.supectco.com/webs/GDP/Admin/getHospitalDetail.php?active=true");

                    HospitalRoot log = JsonConvert.DeserializeObject <HospitalRoot>(json);
                    GlobalVariables.address   = log.hospitalDetail.First().address;
                    GlobalVariables.name      = log.hospitalDetail.First().name;
                    GlobalVariables.mohandes  = log.hospitalDetail.First().mohandes;
                    GlobalVariables.ostan     = log.hospitalDetail.First().ostan;
                    GlobalVariables.sharestan = log.hospitalDetail.First().sharestan;
                    GlobalVariables.phone     = log.hospitalDetail.First().phone;
                }
            }
            //if(GlobalVariables.modelList != "")
            //{


            //}


            using (var client = new WebClient())
            {
                GlobalVariables.modelList = client.DownloadString("http://www.supectco.com/webs/GDP/Admin/getListOfFeaterForApp.php?CatID=1");
            }

            try
            {
                string json3 = "";
                using (var client = new WebClient())
                {
                    json3 = client.DownloadString("http://www.supectco.com/webs/GDP/Admin/getLastPDFName.php?name=" + postedModel.title);
                }
                if (json3.Length > 1)
                {
                    List <string> firstList = json3.Split(',').ToList();
                    List <string> TagIds    = firstList[0].Split('_').ToList();
                    if (TagIds.Count() > 1)
                    {
                        postedModel.title = postedModel.title + "_" + (int.Parse(TagIds[1]) + 1).ToString();
                    }
                    else
                    {
                        postedModel.title = postedModel.title + "_1";
                    }


                    PDFmdoel.referer  = firstList[1];
                    PDFmdoel.PDFTitle = postedModel.title;
                }
            }
            catch (Exception e)
            {
                System.IO.File.WriteAllText(e.Message, postedModel.title);
            }

            //string txtpath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sample.txt");
            //System.IO.File.AppendAllText(txtpath, String.Empty);
            System.IO.File.WriteAllText(txtpath, postedModel.title);


            string id = "";

            try
            {
                MODELFROMDATABASE = JsonConvert.DeserializeObject <RootObject>(GlobalVariables.modelList);
                System.IO.File.AppendAllText(txtpath, " " + MODELFROMDATABASE.featurDataDetail.Count().ToString());

                string srt = postedModel.model;


                //  string txtpath2 = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sample2.txt");
                //System.IO.File.AppendAllText(txtpath, String.Empty);
                //System.IO.File.AppendAllText(txtpath, srt);



                List <model> mymodel = JsonConvert.DeserializeObject <List <model> >(srt);
                string       count   = mymodel.Count().ToString();
                System.IO.File.AppendAllText(txtpath, String.Empty);
                System.IO.File.AppendAllText(txtpath, count);

                var testFile = "";
                testFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PDF/pump.pdf");
                string emptyNamePDF = "";
                emptyNamePDF = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PDF/pumpEmpty.pdf");

                //set pdf in database ;


                //create pdf proccess

                //Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
                //doc.LoadFromFile(testFile);
                //PdfTextFind results = null;
                ////setting position for every title
                //PdfPageBase page;

                //foreach (var item in mymodel)
                //{

                //    int PAGE = Convert.ToInt32(item.page) - 1;
                //    page = doc.Pages[PAGE];
                //    if (item.value != "master")
                //    {
                //        results = page.FindText(item.title).Finds.First();
                //        float width = results.Size.Width;
                //        item.x = (results.Position.X + width).ToString();
                //        item.y = (results.Position.Y).ToString();
                //    }



                //}


                var    testFile2 = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), emptyNamePDF);
                string newFile   = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ResultPDF/result" + postedModel.title + ".pdf");
                string finalFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ResultPDF/" + postedModel.title + ".pdf");

                Spire.Pdf.PdfDocument doc2 = new Spire.Pdf.PdfDocument();
                doc2.LoadFromFile(testFile2);
                float pageheight = 0;

                foreach (PdfPageBase spipage in doc2.Pages)
                {
                    int index = doc2.Pages.IndexOf(spipage);
                    if (index == 0)
                    {
                        mymodel.Where(x => x.page == "1" && x.title == "address").FirstOrDefault().value       = GlobalVariables.address;
                        mymodel.Where(x => x.page == "1" && x.title == "hospital name").FirstOrDefault().value = GlobalVariables.name;
                        mymodel.Where(x => x.page == "1" && x.title == "mohandes").FirstOrDefault().value      = GlobalVariables.mohandes;
                        mymodel.Where(x => x.page == "1" && x.title == "ostan").FirstOrDefault().value         = GlobalVariables.ostan;
                        mymodel.Where(x => x.page == "1" && x.title == "shahrestan").FirstOrDefault().value    = GlobalVariables.sharestan;
                        mymodel.Where(x => x.page == "1" && x.title == "phone").FirstOrDefault().value         = GlobalVariables.phone;



                        foreach (var item in mymodel.Where(x => x.page == "1" && x.title == "mark"))
                        {
                            PDFmdoel.mark = PDFmdoel.mark + item.value;
                        }
                        foreach (var item in mymodel.Where(x => x.page == "1" && x.title == "model"))
                        {
                            PDFmdoel.model = PDFmdoel.model + item.value;
                        }
                        foreach (var item in mymodel.Where(x => x.page == "1" && x.title == "esteghrar"))
                        {
                            PDFmdoel.position = PDFmdoel.position + item.value;
                        }
                        PDFmdoel.serial = mymodel.Where(x => x.page == "1" && x.title == "serial").FirstOrDefault().value;
                        PDFmdoel.amval  = mymodel.Where(x => x.page == "1" && x.title == "amvaal").FirstOrDefault().value;

                        if (mymodel.Where(x => x.page == "1" && x.title == "Passed").FirstOrDefault() != null)
                        {
                            if (mymodel.Where(x => x.page == "1" && x.title == "Passed").FirstOrDefault().value == "true")
                            {
                                PDFmdoel.status = "Passed";
                            }
                        }
                        if (mymodel.Where(x => x.page == "1" && x.title == "Limited").FirstOrDefault() != null)
                        {
                            if (mymodel.Where(x => x.page == "1" && x.title == "Limited").FirstOrDefault().value == "true")
                            {
                                PDFmdoel.status = "Limited";
                            }
                        }
                        if (mymodel.Where(x => x.page == "1" && x.title == "Failed").FirstOrDefault() != null)
                        {
                            if (mymodel.Where(x => x.page == "1" && x.title == "Failed").FirstOrDefault().value == "true")
                            {
                                PDFmdoel.status = "Failed";
                            }
                        }
                        System.IO.File.WriteAllText(txtpath, "enter foreach");

                        foreach (var item in MODELFROMDATABASE.featurDataDetail.Where(x => x.referer != ""))
                        {
                            model chosen = mymodel.Where(x => x.title == item.title && x.page == item.page).SingleOrDefault();
                            System.IO.File.AppendAllText(txtpath, " " + item.title);
                            if (item.max == -1 && item.min != -1)
                            {
                                if (double.Parse(chosen.value) >= item.min)
                                {
                                    mymodel.Where(x => x.title == item.referer).SingleOrDefault().value = "Passed";
                                }
                                else
                                {
                                    mymodel.Where(x => x.title == item.referer).SingleOrDefault().value = "Failed";
                                }
                            }
                            else if (item.max != -1 && item.min == -1)
                            {
                                if (double.Parse(chosen.value) <= item.max)
                                {
                                    mymodel.Where(x => x.title == item.referer).SingleOrDefault().value = "Passed";
                                }
                                else
                                {
                                    mymodel.Where(x => x.title == item.referer).SingleOrDefault().value = "Failed";
                                }
                            }
                            else
                            {
                                if (double.Parse(chosen.value) >= item.min && double.Parse(chosen.value) <= item.max)
                                {
                                    mymodel.Where(x => x.title == item.referer).SingleOrDefault().value = "Passed";
                                }
                                else
                                {
                                    mymodel.Where(x => x.title == item.referer).SingleOrDefault().value = "Failed";
                                }
                            }
                        }


                        string flow10 = mymodel.Where(x => x.title == "flow10").FirstOrDefault().value;
                        if (flow10 != "")
                        {
                            mymodel.Where(x => x.title == "error10").FirstOrDefault().value = Math.Round(((decimal.Parse(flow10) - 10) * 10), 2).ToString().Replace("-", "");
                        }

                        string flow50 = mymodel.Where(x => x.title == "flow50").FirstOrDefault().value;
                        if (flow50 != "")
                        {
                            mymodel.Where(x => x.title == "error50").FirstOrDefault().value = Math.Round(((decimal.Parse(flow50) - 50) * 2), 2).ToString().Replace("-", "");
                        }

                        string flow100 = mymodel.Where(x => x.title == "flow100").FirstOrDefault().value;
                        if (flow100 != "")
                        {
                            mymodel.Where(x => x.title == "error100").FirstOrDefault().value = Math.Round((decimal.Parse(flow100) - 100), 2).ToString().Replace("-", "");
                        }
                        //ایمنی


                        if (mymodel.Where(x => x.title == "resmonfas").FirstOrDefault().value == "Passed" && mymodel.Where(x => x.title == "class").FirstOrDefault().value != "CLASS II")
                        {
                            mymodel.Where(x => x.title == "monfasel").FirstOrDefault().value = Math.Round(RandomNumberBetween(0.5, 0.1), 1).ToString();
                        }
                        if (mymodel.Where(x => x.title == "resmotas").FirstOrDefault().value == "Passed" && mymodel.Where(x => x.title == "class").FirstOrDefault().value != "CLASS II")
                        {
                            mymodel.Where(x => x.title == "motasel").FirstOrDefault().value = Math.Round(RandomNumberBetween(1.6, 0.2), 1).ToString();
                        }


                        if (mymodel.Where(x => x.title == "class").FirstOrDefault().value != "CLASS II")
                        {
                            int adi      = (int)RandomNumberBetween(4600, 4950);
                            int pluse    = (int)RandomNumberBetween(23, 47);
                            int tak      = (int)RandomNumberBetween(7200, 9700);
                            int takpluse = (int)RandomNumberBetween(180, 280);
                            if (mymodel.Where(x => x.title == "res12").FirstOrDefault().value == "Passed")
                            {
                                mymodel.Where(x => x.title == "nashti1").FirstOrDefault().value = ((int)adi).ToString();
                                mymodel.Where(x => x.title == "nashti2").FirstOrDefault().value = ((int)tak).ToString();
                            }
                            if (mymodel.Where(x => x.title == "res34").FirstOrDefault().value == "Passed")
                            {
                                mymodel.Where(x => x.title == "nashti3").FirstOrDefault().value = ((int)(adi + pluse)).ToString();
                                mymodel.Where(x => x.title == "nashti4").FirstOrDefault().value = ((int)(tak + takpluse)).ToString();
                            }
                        }

                        int nashtiBadiAdi      = (int)RandomNumberBetween(57, 83);
                        int nashtiBadiAdiPluse = (int)RandomNumberBetween(1, 7);
                        int nashtiBaditak      = (int)RandomNumberBetween(280, 470);
                        int nashtiBaditakPluse = (int)RandomNumberBetween(10, 15);

                        int badane2 = (int)nashtiBaditak;
                        int badane3 = badane2 + 3;
                        int badane5 = (int)nashtiBaditak + (int)nashtiBaditakPluse;
                        int badane6 = badane5 + 3;

                        if (mymodel.Where(x => x.title == "res123" && x.page == "4").FirstOrDefault().value == "Passed")
                        {
                            mymodel.Where(x => x.title == "badane1").FirstOrDefault().value = ((int)nashtiBadiAdi + (int)nashtiBadiAdiPluse).ToString();
                            mymodel.Where(x => x.title == "badane2").FirstOrDefault().value = badane2.ToString();
                            mymodel.Where(x => x.title == "badane3").FirstOrDefault().value = badane3.ToString();
                        }
                        if (mymodel.Where(x => x.title == "res456" && x.page == "4").FirstOrDefault().value == "Passed")
                        {
                            mymodel.Where(x => x.title == "badane4").FirstOrDefault().value = ((int)nashtiBadiAdi + (2 * (int)nashtiBadiAdiPluse)).ToString();
                            mymodel.Where(x => x.title == "badane5").FirstOrDefault().value = badane5.ToString();
                            mymodel.Where(x => x.title == "badane6").FirstOrDefault().value = badane6.ToString();
                        }
                        if (mymodel.Where(x => x.title == "res7" && x.page == "4").FirstOrDefault().value == "Passed")
                        {
                            mymodel.Where(x => x.title == "badane7").FirstOrDefault().value = ((int)nashtiBadiAdi).ToString();
                        }

                        int nashtiBadiAdi2      = (int)RandomNumberBetween(57, 83);
                        int nashtiBadiAdiPluse2 = (int)RandomNumberBetween(1, 7);
                        int nashtiBaditak2      = (int)RandomNumberBetween(280, 470);
                        int nashtiBaditakPluse2 = (int)RandomNumberBetween(10, 15);
                        int ptp2 = (int)nashtiBaditak2;
                        int ptp3 = ptp2 + 3;
                        int ptp5 = (int)nashtiBaditak2 + (int)nashtiBaditakPluse2;
                        int ptp6 = ptp5 + 3;

                        if (mymodel.Where(x => x.title == "res123" && x.page == "5").FirstOrDefault().value == "Passed")
                        {
                            mymodel.Where(x => x.title == "ptp1").FirstOrDefault().value = ((int)nashtiBadiAdi2 + nashtiBadiAdiPluse2).ToString();
                            mymodel.Where(x => x.title == "ptp2").FirstOrDefault().value = ptp2.ToString();
                            mymodel.Where(x => x.title == "ptp3").FirstOrDefault().value = ptp3.ToString();
                        }
                        if (mymodel.Where(x => x.title == "res456" && x.page == "5").FirstOrDefault().value == "Passed")
                        {
                            mymodel.Where(x => x.title == "ptp4").FirstOrDefault().value = ((int)nashtiBadiAdi2 + (2 * nashtiBadiAdiPluse2)).ToString();
                            mymodel.Where(x => x.title == "ptp5").FirstOrDefault().value = ptp5.ToString();
                            mymodel.Where(x => x.title == "ptp6").FirstOrDefault().value = ptp6.ToString();
                        }
                        if (mymodel.Where(x => x.title == "res7" && x.page == "5").FirstOrDefault().value == "Passed")
                        {
                            mymodel.Where(x => x.title == "ptp7").FirstOrDefault().value = ((int)nashtiBadiAdi2).ToString();
                        }



                        if (mymodel.Where(x => x.title == "class").FirstOrDefault().value == "CLASS II")
                        {
                            mymodel.Where(x => x.title == "monfasel").FirstOrDefault().value  = "----";
                            mymodel.Where(x => x.title == "motasel").FirstOrDefault().value   = "----";
                            mymodel.Where(x => x.title == "nashti1").FirstOrDefault().value   = "----";
                            mymodel.Where(x => x.title == "nashti2").FirstOrDefault().value   = "----";
                            mymodel.Where(x => x.title == "nashti3").FirstOrDefault().value   = "----";
                            mymodel.Where(x => x.title == "nashti4").FirstOrDefault().value   = "----";
                            mymodel.Where(x => x.title == "resmonfas").FirstOrDefault().value = "Not Checked";
                            mymodel.Where(x => x.title == "resmotas").FirstOrDefault().value  = "Not Checked";
                            mymodel.Where(x => x.title == "res12").FirstOrDefault().value     = "Not Checked";
                            mymodel.Where(x => x.title == "res34").FirstOrDefault().value     = "Not Checked";
                        }
                        else
                        {
                            if (mymodel.Where(x => x.title == "kablbargh").FirstOrDefault().value == "غیر قابل انفصال")
                            {
                                mymodel.Where(x => x.title == "monfasel").FirstOrDefault().value  = "----";
                                mymodel.Where(x => x.title == "resmonfas").FirstOrDefault().value = "Not Checked";
                            }
                            else
                            {
                                mymodel.Where(x => x.title == "motasel").FirstOrDefault().value  = "----";
                                mymodel.Where(x => x.title == "resmotas").FirstOrDefault().value = "Not Checked";
                            }
                        }
                    }
                    List <model> pageFieldes = mymodel.Where(x => x.page == (index + 1).ToString()).ToList();
                    pageheight = spipage.Size.Height;


                    foreach (var item in pageFieldes)
                    {
                        PdfTrueTypeFont             Arial  = new PdfTrueTypeFont(new System.Drawing.Font("Arial", 10f), true);
                        PdfTrueTypeFont             Arial9 = new PdfTrueTypeFont(new System.Drawing.Font("Arial", 9f), true);
                        Spire.Pdf.Graphics.PdfFont  font1  = new Spire.Pdf.Graphics.PdfFont(PdfFontFamily.TimesRoman, 9);
                        Spire.Pdf.Graphics.PdfBrush brush  = PdfBrushes.Black;
                        PdfStringFormat             format = new PdfStringFormat();
                        SizeF  size      = Arial9.MeasureString(item.value, format);
                        float  Xposition = float.Parse(item.x) - size.Width;
                        float  yposition = float.Parse(item.y) - 1;
                        PointF position  = new PointF(Xposition, float.Parse(item.y));

                        if (item.type == 1)
                        {
                            if (item.value == "true")
                            {
                                string imagepath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "checked.png");
                                Spire.Pdf.Graphics.PdfImage image = Spire.Pdf.Graphics.PdfImage.FromFile(imagepath);
                                float width  = image.Width * 0.75f;
                                float height = image.Height * 0.75f;
                                spipage.Canvas.DrawImage(image, Xposition, yposition, 10, 10);
                            }
                            else
                            {
                                string imagepath2 = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "unchecked.png");
                                Spire.Pdf.Graphics.PdfImage image2 = Spire.Pdf.Graphics.PdfImage.FromFile(imagepath2);
                                spipage.Canvas.DrawImage(image2, Xposition, yposition, 10, 10);
                            }
                        }
                        else
                        {
                            if (item.font == "E")
                            {
                                spipage.Canvas.DrawString(item.value, Arial, brush, position);
                            }
                            else
                            {
                                position.X = position.X;
                                spipage.Canvas.DrawString(item.value, Arial, brush, position, new PdfStringFormat()
                                {
                                    RightToLeft = true
                                });
                            }
                        }
                    }
                    ;
                }
                doc2.SaveToFile(newFile, FileFormat.PDF);
                doc2.Close();
                string srt2 = "";
                using (PdfReader pdfReader = new PdfReader(newFile))
                {
                    float widthTo_Trim = pageheight - 15;// iTextSharp.text.Utilities.MillimetersToPoints(450);


                    using (FileStream output = new FileStream(finalFile, FileMode.Create, FileAccess.Write))
                    {
                        using (PdfStamper pdfStamper = new PdfStamper(pdfReader, output))
                        {
                            iTextSharp.text.Rectangle cropBox = pdfReader.GetCropBox(1);
                            cropBox.Top = widthTo_Trim;
                            pdfReader.GetPageN(1).Put(PdfName.CROPBOX, new PdfRectangle(cropBox));
                            //for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                            //{

                            //}
                        }



                        PDFmdoel.PDFPath = finalFile;


                        returnModel m2 = new returnModel()
                        {
                            status  = 200,
                            message = "http://gdp.sup-ect.ir/ResultPDF/" + postedModel.title + ".pdf",
                        };
                        srt2 = JsonConvert.SerializeObject(m2);
                    }


                    pdfReader.Close();
                    setpdfindatabase(PDFmdoel);
                }

                return(Content(srt2));
            }
            catch (Exception e)
            {
                string txtpath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sample.txt");
                System.IO.File.AppendAllText(txtpath, e.Message);
                returnModel m = new returnModel()
                {
                    status  = 400,
                    message = e.Message + id,
                };
                string srt = JsonConvert.SerializeObject(m);
                return(Content(srt));
            }
        }
예제 #12
0
 private bool WriteToPDFDocument(string text, string path)
 {
     try
     {
         PDF.PdfDocument doc = new PDF.PdfDocument();
         doc.XmpMetaData.SetAuthor(Environment.UserName);
         doc.XmpMetaData.SetCreateDate(DateTime.Now);
         doc.XmpMetaData.SetCreator(Environment.UserName);
         doc.XmpMetaData.SetKeywords(string.Format("Календарь, {0}", this.dateTime.Year));
         doc.XmpMetaData.SetProducer(Environment.UserName);
         doc.XmpMetaData.SetSubject("Календари");
         doc.XmpMetaData.SetTitle(string.Format("Календарь на {0} г.", this.dateTime.Year));
         PDFGraphics.PdfMargins       margin        = new PDFGraphics.PdfMargins();
         PDFGraphics.PdfUnitConvertor unitConvertor = new PDFGraphics.PdfUnitConvertor();
         margin.Top    = unitConvertor.ConvertUnits(0.71f, PDFGraphics.PdfGraphicsUnit.Centimeter, PDFGraphics.PdfGraphicsUnit.Point);
         margin.Bottom = margin.Top;
         margin.Left   = unitConvertor.ConvertUnits(1.76f, PDFGraphics.PdfGraphicsUnit.Centimeter, PDFGraphics.PdfGraphicsUnit.Point);
         margin.Right  = margin.Left;
         PDF.PdfPageBase             page          = doc.Pages.Add(PDF.PdfPageSize.A4, margin);
         PDFGraphics.PdfTrueTypeFont timesNewRoman = new PDFGraphics.PdfTrueTypeFont(@"C:\Windows\Fonts\times.ttf", 16.0f);
         PDFGraphics.PdfTrueTypeFont courierNew    = new PDFGraphics.PdfTrueTypeFont(@"C:\Windows\Fonts\cour.ttf", 12.0f);
         PDFGraphics.PdfStringFormat alignCenter   = new PDFGraphics.PdfStringFormat(PDFGraphics.PdfTextAlignment.Center);
         page.Canvas.DrawString(string.Format("Календарь на {0} г.", this.dateTime.Year), timesNewRoman, new PDFGraphics.PdfSolidBrush(Color.Blue), page.Canvas.ClientSize.Width / 2, 0, alignCenter);
         float    y     = 43;
         string[] lines = text.Split(new char[] { '\n' }, StringSplitOptions.None);
         foreach (string item in lines)
         {
             bool isFound = false;
             if (item.Trim().StartsWith(@"Дн\Нед"))
             {
                 page.Canvas.DrawRectangle(new PDFGraphics.PdfSolidBrush(Color.Yellow), new RectangleF(0, y, courierNew.MeasureString(item, courierNew.Size).Width *item.Length, 13));
             }
             else
             {
                 for (int i = 0; i < daysOfWeek.Length; i++)
                 {
                     if (item.Trim().StartsWith(daysOfWeek[i]))
                     {
                         string temp = item.Substring(4, 3);
                         SizeF  size = courierNew.MeasureString(temp, courierNew.Size);
                         page.Canvas.DrawRectangle(new PDFGraphics.PdfSolidBrush(Color.Yellow), new RectangleF(size.Width * 4, y, size.Width * temp.Length, 13));
                         if (i >= 5)
                         {
                             page.Canvas.DrawString(item, courierNew, new PDFGraphics.PdfSolidBrush(Color.Red), 0, y);
                         }
                         else
                         {
                             page.Canvas.DrawString(item, courierNew, new PDFGraphics.PdfSolidBrush(Color.Black), 0, y);
                         }
                         isFound = true;
                         break;
                     }
                 }
             }
             if (!isFound)
             {
                 page.Canvas.DrawString(item, courierNew, new PDFGraphics.PdfSolidBrush(Color.Black), 0, y);
             }
             y += 13;
         }
         doc.SaveToFile(path, PDF.FileFormat.PDF);
         return(true);
     }
     catch (Exception exception)
     {
         MessageBox.Show(exception.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return(false);
     }
 }