Ejemplo n.º 1
0
        private void PdfExtractWordAndPicture(string savePathCache, string midName)//参数:保存地址,处理过程中文件名称(不包含后缀)
        {
            #region   提取PDF中的文字

            try
            {
                PdfDocument doc = new PdfDocument();
                doc.LoadFromFile(savePathCache + "\\" + midName + ".pdf");      //加载文件
                StringBuilder content = new StringBuilder();
                foreach (PdfPageBase page in doc.Pages)
                {
                    content.Append(page.ExtractText());
                }


                System.IO.File.WriteAllText(savePathCache + "\\mid.txt", content.ToString());

                Spire.Doc.Document document = new Spire.Doc.Document();
                document.LoadFromFile(savePathCache + "\\mid.txt");
                document.Replace(" ", "", true, true);
                document.Replace("Evaluation Warning : The document was created with Spire.PDF for .NET.", "", true, true);
                document.SaveToFile(savePathCache + "\\" + midName + ".doc", Spire.Doc.FileFormat.Doc);

                File.Delete(savePathCache + "\\mid.txt");
            }
            catch (Exception)
            {
                MessageBox.Show("请填写正确的路径");
            }
            #endregion

            #region  提取PDF中的图片
            //创建一个PdfDocument类对象并加载PDF sample
            Spire.Pdf.PdfDocument mydoc = new Spire.Pdf.PdfDocument();
            mydoc.LoadFromFile(savePathCache + "\\" + midName + ".pdf");

            //声明一个IList类,元素为image
            IList <Image> images = new List <Image>();
            //遍历PDF文档中诊断是否包含图片,并提取图片
            foreach (PdfPageBase page in mydoc.Pages)
            {
                if (page.ExtractImages() != null)
                {
                    foreach (Image image in page.ExtractImages())
                    {
                        images.Add(image);
                    }
                }
            }
            mydoc.Close();

            //遍历提取的图片,保存并命名图片
            int index = 0;
            foreach (Image image in images)
            {
                String imageFileName = String.Format(midName + "Image-{0}.png", index++);
                image.Save(savePathCache + "\\" + imageFileName, ImageFormat.Png);
            }
            #endregion
        }
Ejemplo n.º 2
0
        private void Print()
        {
            try
            {
                Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
                doc.LoadFromFile(@"c:\Temp\Out.PDF");
                doc.PageScaling = PdfPrintPageScaling.ActualSize;

                PrintDialog dialogPrint = new PrintDialog();
                dialogPrint.AllowPrintToFile            = true;
                dialogPrint.AllowSomePages              = true;
                dialogPrint.PrinterSettings.MinimumPage = 1;
                dialogPrint.PrinterSettings.MaximumPage = doc.Pages.Count;
                dialogPrint.PrinterSettings.FromPage    = 1;
                dialogPrint.PrinterSettings.ToPage      = doc.Pages.Count;

                //Set the pagenumber which you choose as the start page to print
                doc.PrintFromPage = dialogPrint.PrinterSettings.FromPage;
                //Set the pagenumber which you choose as the final page to print
                doc.PrintToPage = dialogPrint.PrinterSettings.ToPage;
                //Set the name of the printer which is to print the PDF
                doc.PrinterName = dialogPrint.PrinterSettings.PrinterName;

                PrintDocument printDoc = doc.PrintDocument;
                dialogPrint.Document = printDoc;
                printDoc.PrinterSettings.PrinterName = impressora;
                printDoc.Print();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ocorreu um problema ao processar a DANFE.\n{ex.Message}", "ERRO", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 3
0
 void PdftoIMG(string pdfpath)
 {
     Spire.Pdf.PdfDocument pdfdocument = new Spire.Pdf.PdfDocument();
     pdfdocument.LoadFromFile(pdfpath);
     System.Drawing.Image image = pdfdocument.SaveAsImage(0, 96, 96);
     image.Save(string.Format(Server.MapPath("~/Images/UIDimage/New.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg));
 }
Ejemplo n.º 4
0
        private void btnPrint_Click(object sender, EventArgs e)
        {
            string printPath = Path.GetTempFileName();

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

            doc.LoadFromFile(printPath);

            PrintDialog dialogPrint = new PrintDialog();

            dialogPrint.AllowPrintToFile            = true;
            dialogPrint.AllowSomePages              = true;
            dialogPrint.PrinterSettings.MinimumPage = 1;
            dialogPrint.PrinterSettings.MaximumPage = doc.Pages.Count;
            dialogPrint.PrinterSettings.FromPage    = 1;
            dialogPrint.PrinterSettings.ToPage      = doc.Pages.Count;

            if (dialogPrint.ShowDialog() == DialogResult.OK)
            {
                doc.PrintFromPage = dialogPrint.PrinterSettings.FromPage;
                doc.PrintToPage   = dialogPrint.PrinterSettings.ToPage;
                doc.PrinterName   = dialogPrint.PrinterSettings.PrinterName;
                PrintDocument printDoc = doc.PrintDocument;
                printDoc.Print();
            }
        }
Ejemplo n.º 5
0
 internal static int PrintPDF(string PrintDir, int index)
 {
     if (ConfigurationManager.AppSettings["Mode"] == "Diagnostic")
     {
         logger.Log(NLog.LogLevel.Info, "Inside PrintPDFs function. print dir:" + PrintDir);
     }
     using (PdfDocument pdf = new PdfDocument())
     {
         pdf.PrintSettings.PrinterName = ConfigurationManager.AppSettings["PhotoPrinterName"];
         //search all files prresent in "printdir"
         //load and print them one by one.
         FileInfo file = new FileInfo(PrintDir + "//Print" + index.ToString() + ".pdf");
         if (file.Exists)
         {
             pdf.PrintSettings.PrinterName = ConfigurationManager.AppSettings["PhotoPrinterName"];
             pdf.LoadFromFile(file.FullName);
             pdf.Print();
         }
         else
         {
             return(1);
         }
         return(0);
     }
 }
Ejemplo n.º 6
0
        internal static void PrintPDFs(string PrintDir)
        {
            using (PdfDocument pdf = new PdfDocument())
            {
                if (ConfigurationManager.AppSettings["Mode"] == "Diagnostic")
                {
                    logger.Log(NLog.LogLevel.Info, "Inside PrintPDFs function. print dir:" + PrintDir);
                }

                pdf.PrintSettings.PrinterName = ConfigurationManager.AppSettings["PhotoPrinterName"];
                //search all files prresent in "printdir"
                //load and print them one by one.
                IEnumerable <FileInfo> files = new DirectoryInfo(PrintDir).EnumerateFiles();
                foreach (var item in files)
                {
                    // for pdf, show page selection dialog
                    //pdf.PrintSettings.SelectSomePages()
                    pdf.LoadFromFile(item.FullName);
                    pdf.Print();
                    if (ConfigurationManager.AppSettings["Mode"] == "Diagnostic")
                    {
                        logger.Log(NLog.LogLevel.Info, "Printing image file :" + item.FullName);
                    }
                }
            }
        }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
0
        private void CreatePrintPreview()
        {
            // Generate a preview of the saved file
            PdfDocument pdf = new PdfDocument();

            pdf.LoadFromFile("Grocery List.pdf");
            this.printPreviewControl1.Rows    = 1;
            this.printPreviewControl1.Columns = 1;
            pdf.Preview(printPreviewControl1);
        }
Ejemplo n.º 9
0
        private void btnPrint_Click(object sender, EventArgs e)
        {
            Document doc  = GeneratePDF("temp");
            string   jour = DateTime.Today.Day.ToString() + "." + DateTime.Today.Month.ToString() + "." + DateTime.Today.Year.ToString();

            //it is necessary to specify Spire.Pdf because iText7 uses the same Class Name
            Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument();
            pdf.LoadFromFile("C:\\temp\\list" + jour + ".pdf");
            pdf.PrintSettings.PrinterName = "\\\\SC-PRNT-SV30\\sc-c236-pr02.cpnv.ch";
            pdf.Print();
        }
Ejemplo n.º 10
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();
        }
Ejemplo n.º 11
0
 internal static void PrintReceipt(string receiptDir, string taxinvoicenumber)
 {
     using (PdfDocument pdf = new PdfDocument())
     {
         pdf.LoadFromFile(receiptDir + taxinvoicenumber + ".pdf");
         pdf.PrintSettings.PrinterName = ConfigurationManager.AppSettings["ReceiptPrinterName"];
         pdf.Print();
         if (ConfigurationManager.AppSettings["Mode"] == "Diagnostic")
         {
             logger.Log(NLog.LogLevel.Info, "Printing receipt file :" + taxinvoicenumber + ".pdf");
         }
     }
 }
Ejemplo n.º 12
0
 internal static void PrintPic(string pic)
 {
     using (PdfDocument pdf = new PdfDocument())
     {
         pic = pic.Replace("thumbs/", "");
         FileInfo file = new FileInfo(pic);
         if (file.Exists)
         {
             pdf.PrintSettings.PrinterName = ConfigurationManager.AppSettings["PhotoPrinterName"];
             pdf.LoadFromFile(file.FullName);
             pdf.Print();
         }
     }
 }
Ejemplo n.º 13
0
        public MemoryStream SpireFields(Dictionary <string, string> formFields)
        {
            if (string.IsNullOrEmpty(this._location.Trim()))
            {
                return(null);
            }
            byte[] fileBytes;
            var    doc = new Spire.Pdf.PdfDocument();

            doc.LoadFromFile(this._location);
            var form = doc.Form as PdfFormWidget;

            doc.Pages[0].BackgroudOpacity = 1.0f;
            form.AutoNaming      = false;
            form.NeedAppearances = true;



            foreach (var field in form.FieldsWidget.List)
            {
                var formField = field as PdfField;

                if (field is PdfTextBoxFieldWidget)
                {
                    var textField = field as PdfTextBoxFieldWidget;
                    if (formFields.ContainsKey(textField.Name))
                    {
                        textField.Text = formFields[textField.Name];
                    }
                }

                else if (field is PdfCheckBoxWidgetFieldWidget)
                {
                    var checkBoxField = field as PdfCheckBoxWidgetFieldWidget;
                    if (formFields.ContainsKey(checkBoxField.Name))
                    {
                        checkBoxField.Checked = formFields[checkBoxField.Name].ToUpper() == "TRUE" ? true : false;
                    }
                }
                formField.Flatten = true;
            }

            using (var str = new MemoryStream())
            {
                doc.SaveToStream(str);
                doc.Close();

                return(str);
            }
        }
Ejemplo n.º 14
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");
        }
Ejemplo n.º 15
0
        private int CountLines()
        {
            PdfDocument document = new PdfDocument();

            document.LoadFromFile("Grocery List.pdf");

            StringBuilder builder = new StringBuilder();

            // It is assumed that we will only print single page grocery lists per errand
            builder.Append(document.Pages[0].ExtractText());
            string content   = builder.ToString();
            int    lineCount = content.Split('\n').Length - 1;

            //MessageBox.Show(lineCount.ToString());
            return(lineCount);
        }
Ejemplo n.º 16
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();
        }
        private void FormPrintOrderMission_Load(object sender, EventArgs e)
        {
            vtts.BAL.MissionManagement.PrintOrderMission printOrderMission = new vtts.BAL.MissionManagement.PrintOrderMission();
            printOrderMission.HeaderImgDirectory = @"C:\USers\DELL\Desktop\vtts-windows-app\Images\Header.png";
            printOrderMission.Ordre         = MissionOrder.OrderNumber;
            printOrderMission.Date          = MissionOrder.DateOrder;
            printOrderMission.Region        = "Le Directeur Regional de la DRNOII";
            printOrderMission.City          = "Tanger";
            printOrderMission.Mensieur      = "Monsieur   :   Bouybanin Anass";
            printOrderMission.Matricule     = " 13716";
            printOrderMission.Category      = "Cadre Principale";
            printOrderMission.Affectation   = "I.S.M.O.N.T.I.C Tanger";
            printOrderMission.Place         = "CDC TIC Casa Blanca";
            printOrderMission.Theme         = "Pour assister aux atelier NETACAD CISCO";
            printOrderMission.DepartureDate = "24/04/2017";
            printOrderMission.ReturnDate    = "29/04/2017";
            printOrderMission.DepartureHour = "13h00";
            printOrderMission.ReturnHour    = "13h00";
            //PublicTransport , MissionCar, PersonalCar
            printOrderMission.TransportType = "PublicTransport";
            // In Other Cases
            //if(printOrderMission.TransportType == "MissionCar")
            //{
            //    printOrderMission.MissionCarmark = "Mark";
            //    printOrderMission.MissionCarPlatNumber = "Numero de plaque";
            //}
            //if(printOrderMission.TransportType == "PersonalCar")
            //{
            //    printOrderMission.PersonalCarmark = "Mark";
            //    printOrderMission.PersonalCarPlatNumber = "Numero de plaque";
            //    printOrderMission.PersonalCarFiscalPower = "Puissance Fiscale";
            //}
            //

            printOrderMission.FirstPersonne   = "Abdelhamid ELMECHRAFI";
            printOrderMission.SecondePersonne = "Abdelmoula SADIK";
            this.PathPDF = printOrderMission.CreatePDF();


            // Print Document with Spire Library
            Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
            doc.LoadFromFile(this.PathPDF);

            printPreviewControl1.Document = doc.PrintDocument;
        }
Ejemplo n.º 18
0
        public void updatePostion(string deviceID)
        {
            string json;

            deviceID = "1";
            using (var client = new WebClient())
            {
                json = client.DownloadString("http://www.supectco.com/webs/GDP/Admin/getListOfFeatures.php?CatID=" + deviceID);
            }

            FeatureModel log = JsonConvert.DeserializeObject <FeatureModel>(json);

            var testFile = "";

            testFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PDF/pump.pdf");
            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 log.featureData.First().subFeatures)
            {
                if (item.title == "keyfidalilyek")
                {
                }
                int PAGE = Convert.ToInt32(item.page) - 1;
                page = doc.Pages[PAGE];
                string xposition = "";
                string yposition = "0";
                if (item.value != "master")
                {
                    results = page.FindText(item.title).Finds.First();
                    float width = results.Size.Width;
                    xposition = (results.Position.X + width).ToString();
                    yposition = (results.Position.Y).ToString();
                }
                string json2;
                using (var client = new WebClient())
                {
                    json2 = client.DownloadString("http://www.supectco.com/webs/GDP/Admin/setPositionForFeatures.php?ID=" + item.ID + "&xpos=" + xposition + "&ypos=" + yposition);
                }
            }
        }
        private void metroTile1_Click(object sender, EventArgs e)
        {
            // Print Document with Spire Library
            Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
            doc.LoadFromFile(this.PathPDF);


            //var ppd = new PrintPreviewDialog();
            //ppd.Document = doc.PrintDocument;
            //ppd.ShowDialog(this); // renders Image1 attached


            //printPreviewDialog1.Document = doc.PrintDocument;

            ///////
            ////Use the default printer to print all the pages
            //doc.PrintDocument.Print();

            //Set the printer and select the pages you want to print

            PrintDialog dialogPrint = new PrintDialog();

            dialogPrint.AllowPrintToFile            = true;
            dialogPrint.AllowSomePages              = true;
            dialogPrint.PrinterSettings.MinimumPage = 1;
            dialogPrint.PrinterSettings.MaximumPage = doc.Pages.Count;
            dialogPrint.PrinterSettings.FromPage    = 1;
            dialogPrint.PrinterSettings.ToPage      = doc.Pages.Count;

            if (dialogPrint.ShowDialog() == DialogResult.OK)
            {
                //Set the pagenumber which you choose as the start page to print
                doc.PrintFromPage = dialogPrint.PrinterSettings.FromPage;
                //Set the pagenumber which you choose as the final page to print
                doc.PrintToPage = dialogPrint.PrinterSettings.ToPage;
                //Set the name of the printer which is to print the PDF
                doc.PrinterName = dialogPrint.PrinterSettings.PrinterName;

                PrintDocument printDoc = doc.PrintDocument;
                dialogPrint.Document = printDoc;
                printDoc.Print();
            }
        }
Ejemplo n.º 20
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();
            }
        }
Ejemplo n.º 21
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();
        }
Ejemplo n.º 22
0
        private void printBttn_Click(object sender, EventArgs e)
        {
            PdfDocument pdf = new PdfDocument();

            pdf.LoadFromFile("Grocery List.pdf");

            PrintDialog dialogPrint = new PrintDialog();

            dialogPrint.AllowPrintToFile            = true;
            dialogPrint.AllowSomePages              = true;
            dialogPrint.PrinterSettings.MinimumPage = 1;
            dialogPrint.PrinterSettings.MaximumPage = pdf.Pages.Count;
            dialogPrint.PrinterSettings.FromPage    = 1;
            dialogPrint.PrinterSettings.ToPage      = pdf.Pages.Count;

            if (dialogPrint.ShowDialog() == DialogResult.OK)
            {
                pdf.PrintSettings.SelectPageRange(dialogPrint.PrinterSettings.FromPage, dialogPrint.PrinterSettings.ToPage);
                pdf.PrintSettings.PrinterName = dialogPrint.PrinterSettings.PrinterName;

                pdf.Print();
            }
        }
Ejemplo n.º 23
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));
            }
        }
        private void FormPrintOrderMission_Load(object sender, EventArgs e)
        {
            vtts.BAL.MissionManagement.PrintOrderMission printOrderMission = new vtts.BAL.MissionManagement.PrintOrderMission();
            printOrderMission.HeaderImgDirectory = @"C:\USers\DELL\Desktop\vtts-windows-app\Images\Header.png";
            printOrderMission.Ordre  = MissionOrder.OrderNumber;
            printOrderMission.Date   = MissionOrder.DateOrder;
            printOrderMission.Region = "Le Directeur Regional de la ";//+MissionOrder.MissionConvocation.Institution.Region;
            printOrderMission.City   = "Tanger";

            if (MissionOrder.Staff.Sex)
            {
                printOrderMission.Mensieur = "Monsieur   :  " + MissionOrder.Staff.LastName + "  " + MissionOrder.Staff.FirstName;
            }
            if (!MissionOrder.Staff.Sex)
            {
                printOrderMission.Mensieur = "Madame   :  " + MissionOrder.Staff.LastName + "  " + MissionOrder.Staff.FirstName;
            }
            printOrderMission.Matricule = MissionOrder.Staff.RegistrationNumber;

            if (MissionOrder.Staff.Grade != null)
            {
                printOrderMission.Category = MissionOrder.Staff.Grade.Name + "";
            }
            else
            {
                MessageBox.Show(new Exception("grade is null").ToString());
            }


            printOrderMission.Affectation   = "I.S.M.N.T.I.C Tanger  ";                                        //MissionOrder.MissionConvocation.Institution.Region.Name.Current;
            printOrderMission.Place         = MissionOrder.MissionConvocation.Institution.Name.Current + "  "; //MissionOrder.MissionConvocation.Institution.Region.Name.Current
            printOrderMission.Theme         = MissionOrder.MissionConvocation.Theme.Current;
            printOrderMission.DepartureDate = MissionOrder.DepartureDate.ToShortDateString();
            printOrderMission.ReturnDate    = MissionOrder.ArrivalDate.ToShortDateString();
            printOrderMission.DepartureHour = MissionOrder.DepartureTime + "h00";
            printOrderMission.ReturnHour    = MissionOrder.ArrivingTime + "h00";
            printOrderMission.Category      = MissionOrder.MissionConvocation.MissionCategory.Name.Current;
            //PublicTransport , MissionCar, PersonalCar
            printOrderMission.TransportType = MissionOrder.MeansTransportCategory.ToString();
            // In Other Cases

            if (printOrderMission.TransportType == MeansTransportCategories.Public.ToString())

            {
                printOrderMission.MissionCarmark       = MissionOrder.Car.Mark;
                printOrderMission.MissionCarPlatNumber = MissionOrder.Car.PlateNumber;
            }

            if (printOrderMission.TransportType == MeansTransportCategories.Voiture_Personnel.ToString() || printOrderMission.TransportType == MeansTransportCategories.Voiture_de_Service.ToString())

            {
                printOrderMission.PersonalCarmark        = MissionOrder.Car.Mark;
                printOrderMission.PersonalCarPlatNumber  = MissionOrder.Car.PlateNumber;
                printOrderMission.PersonalCarFiscalPower = MissionOrder.Car.TaxPower + "";
            }


            printOrderMission.FirstPersonne   = "Abdelhamid ELMECHRAFI";
            printOrderMission.SecondePersonne = "Abdelmoula SADIK";
            this.PathPDF = printOrderMission.CreatePDF();


            // Print Document with Spire Library
            Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
            doc.LoadFromFile(this.PathPDF);

            printPreviewControl1.Document = doc.PrintDocument;
        }
        public String ConvertPdfToImage(imgformat img, String Route)
        {
            string dataDir = Server.MapPath(Route);

            ////string[] extensions = { ".jpg", ".txt", ".asp", ".css", ".cs", ".xml" };
            string[] extensions   = { ".pdf" };
            String   Outfilename  = String.Empty;
            String   FinalSaveJPG = String.Empty;

            try
            {
                //////////////    String[] FilesPath = Directory.GetFiles(dataDir, "*.*")
                //////////////            .Where(f => extensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();

                FileInfo[] FilesPathArray = new DirectoryInfo(dataDir).GetFiles()
                                            .OrderBy(f => f.LastWriteTime)
                                            .ToArray();

                int FilesCount = FilesPathArray.Length;
                for (int i = 0; i < FilesCount; i++)
                {
                    Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
                    //doc.LoadFromFile(FilesPath[i]);
                    String kookoko = (String.Format("{0}\\{1}", dataDir, FilesPathArray[i]));

                    doc.LoadFromFile(String.Format("{0}\\{1}", dataDir, FilesPathArray[i]));
                    System.Drawing.Image bmp = doc.SaveAsImage(0);

                    System.Drawing.Image emf     = doc.SaveAsImage(0, Spire.Pdf.Graphics.PdfImageType.Metafile);
                    System.Drawing.Image zoomImg = new System.Drawing.Bitmap((int)(emf.Size.Width * 2), (int)(emf.Size.Height * 2));
                    using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(zoomImg))
                    {
                        g.ScaleTransform(2.0f, 2.0f);
                        g.DrawImage(emf, new System.Drawing.Rectangle(new System.Drawing.Point(0, 0), emf.Size), new System.Drawing.Rectangle(new System.Drawing.Point(0, 0), emf.Size), System.Drawing.GraphicsUnit.Pixel);
                    }

                    Outfilename  = fileName.Replace(".pdf", "");
                    FinalSaveJPG = String.Format("{0}\\{1}\\{2}", rootPath, AssignedFolder, IMGexportedPath);
                    fn.CreateFolderUpload(FinalSaveJPG);

                    switch (img)
                    {
                    case imgformat.jpg:
                        zoomImg.Save(Server.MapPath(String.Format("{0}\\{1}[{2}].jpg", FinalSaveJPG, i, Outfilename)), ImageFormat.Jpeg);
                        break;

                    case imgformat.bmp:
                        zoomImg.Save(Server.MapPath(String.Format("{0}\\{1}[{2}].bmp", FinalSaveJPG, i, Outfilename)), ImageFormat.Bmp);
                        break;

                    case imgformat.png:
                        zoomImg.Save(Server.MapPath(String.Format("{0}\\{1}[{2}].png", FinalSaveJPG, i, Outfilename)), ImageFormat.Png);
                        break;

                    case imgformat.tiff:
                        zoomImg.Save(Server.MapPath(String.Format("{0}\\{1}[{2}].tiff", FinalSaveJPG, i, Outfilename)), ImageFormat.Tiff);
                        break;
                    }
                }
                return(FinalSaveJPG);
            }
            catch (Exception)
            {
                return(null);
            }
            #region comenteed
            //String aaa = "asddasdasmkld";
            //emf.Save(Server.MapPath(rootPathUpload)+ @"\" + "convertToBmp.jpg", ImageFormat.Jpeg);

            //emf.Save(Server.MapPath(rootPathUpload) + @"\" + "convertToBmp.bmp", ImageFormat.Bmp);
            ////System.Diagnostics.Process.Start("convertToBmp.bmp");
            //emf.Save(Server.MapPath(rootPathUpload) + @"\" + "convertToEmf.png", ImageFormat.Png);
            //System.Diagnostics.Process.Start("convertToEmf.png");
            //zoomImg.Save(Server.MapPath(rootPathUpload) + @"\" + "convertToZoom.png", ImageFormat.Tiff);

            //zoomImg.Save(Server.MapPath(rootPathUpload) + @"\" + "convertToZoom.png", ImageFormat.Wmf);
            //zoomImg.Save(Server.MapPath(rootPathUpload) + @"\" + "convertToZoom.png", ImageFormat.Exif);
            //zoomImg.Save(Server.MapPath(rootPathUpload) + @"\" + "convertToZoom.png", ImageFormat.Gif);
            //zoomImg.Save(Server.MapPath(rootPathUpload) + @"\" + "convertToZoom.png", ImageFormat.Icon);
            //zoomImg.Save(Server.MapPath(rootPathUpload) + @"\" + "convertToZoom.png", ImageFormat.Wmf);

            //System.Diagnostics.Process.Start("convertToZoom.png");

            /////return "";
            #endregion
        }
Ejemplo n.º 26
0
        public ActionResult Hash(string certUserBase64 = "", string fileName = "", int LoaiChuKy = 0, int numberPage = 1)
        {
            var statusResultHashFile = "error";
            var descErrorHashFile    = "";
            var serialNumber         = "";
            var hashBase64           = "";

            try
            {
                if (certUserBase64 == null || certUserBase64.Trim().Length == 0)
                {
                    descErrorHashFile = "Cert Chain is empty";
                    return(Json(new
                    {
                        statusResultHashFile = statusResultHashFile,
                        descErrorHashFile = descErrorHashFile,
                        serialNumber = "",
                        hashBase64 = ""
                    }, JsonRequestBehavior.AllowGet));
                }
                if (fileName == null || fileName.Trim().Length == 0 || fileName.IndexOf(".pdf") == -1)
                {
                    descErrorHashFile = "Chưa chọn File cần ký";
                    return(Json(new
                    {
                        statusResultHashFile = statusResultHashFile,
                        descErrorHashFile = descErrorHashFile,
                        serialNumber = "",
                        hashBase64 = ""
                    }, JsonRequestBehavior.AllowGet));
                }

                //Get the servers upload directory real path name

                string HCC_FILE_PDF = GetUrlFileDefaut();
                string fileFullPath = Path.Combine(HCC_FILE_PDF, fileName);

                bool exists = System.IO.File.Exists(fileFullPath);
                if (!exists)
                {
                    descErrorHashFile = "File không tồn tại";
                    return(Json(new
                    {
                        statusResultHashFile = statusResultHashFile,
                        descErrorHashFile = descErrorHashFile,
                        serialNumber = "",
                        hashBase64 = ""
                    }, JsonRequestBehavior.AllowGet));
                }

                string[] stringSeparators = new string[] { "," };
                String[] chainBase64      = certUserBase64.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

                if (chainBase64 == null || chainBase64.Length == 0)
                {
                    descErrorHashFile = "Lấy Chứng thư số không thành công";
                    return(Json(new
                    {
                        statusResultHashFile = statusResultHashFile,
                        descErrorHashFile = descErrorHashFile,
                        serialNumber = "",
                        hashBase64 = ""
                    }, JsonRequestBehavior.AllowGet));
                }
                X509Certificate x509Cert = CertUtils.GetX509Cert(chainBase64[0]);
                //Check chứng thư số còn giá trị
                //#if DEBUG

                //#else
                //    var tokenValid = x509Cert.IsValidNow;
                //    if (tokenValid != true)
                // {
                //        descErrorHashFile = "Chứng thư số đã hết hiệu lực.";
                //                    return Json(new
                //                    {
                //                        statusResultHashFile = statusResultHashFile,
                //                        descErrorHashFile = descErrorHashFile,
                //                        serialNumber = "",
                //                        hashBase64 = ""
                //                    }, JsonRequestBehavior.AllowGet);
                // }
                //#endif

                if (x509Cert == null)
                {
                    descErrorHashFile = "Lấy Chứng thư số không thành công";
                    return(Json(new
                    {
                        statusResultHashFile = statusResultHashFile,
                        descErrorHashFile = descErrorHashFile,
                        serialNumber = "",
                        hashBase64 = ""
                    }, JsonRequestBehavior.AllowGet));
                }
                X509Certificate certCA = null;
                if (chainBase64.Length > 1)
                {
                    certCA = CertUtils.GetX509Cert(chainBase64[1]);
                }
                X509Certificate[] certChain = null;
                if (certCA != null)
                {
                    certChain = new X509Certificate[] { x509Cert, certCA };
                }
                else
                {
                    string          certViettelCABase64 = "MIIEKDCCAxCgAwIBAgIKYQ4N5gAAAAAAETANBgkqhkiG9w0BAQUFADB+MQswCQYDVQQGEwJWTjEzMDEGA1UEChMqTWluaXN0cnkgb2YgSW5mb3JtYXRpb24gYW5kIENvbW11bmljYXRpb25zMRswGQYDVQQLExJOYXRpb25hbCBDQSBDZW50ZXIxHTAbBgNVBAMTFE1JQyBOYXRpb25hbCBSb290IENBMB4XDTE1MTAwMjAyMzIyMFoXDTIwMTAwMjAyNDIyMFowOjELMAkGA1UEBhMCVk4xFjAUBgNVBAoTDVZpZXR0ZWwgR3JvdXAxEzARBgNVBAMTClZpZXR0ZWwtQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDLdiGZcPhwSm67IiLUWELaaol8kHF+qHPmEdcG0VDKf0FtpSWiE/t6NPzqqmoF4gbIrue1/TzUs7ZeAj28o6Lb2BllA/zB6YFrXfppD4jKqHMO139970MeTbDrhHTbVugX4t2QHS+B/p8+8lszJpuduBrnZ/LWxbhnjeQRr21g89nh/W5q1VbIvZnq4ci5m0aDiJ8arhK2CKpvNDWWQ5E0L7NTVoot8niv6/Wjz19yvUCYOKHYsq97y7eBaSYmpgJosD1VtnXqLG7x4POdb6Q073eWXQB0Sj1qJPrXtOqWsnnmzbbKMrnjsoE4gg9B6qLyQS4kRMp0RrUV0z041aUFAgMBAAGjgeswgegwCwYDVR0PBAQDAgGGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFAhg5h8bFNlIgAtep1xzJSwgDfnWMB8GA1UdIwQYMBaAFM1iceRhvf497LJAYNOBdd06rGvGMDwGA1UdHwQ1MDMwMaAvoC2GK2h0dHA6Ly9wdWJsaWMucm9vdGNhLmdvdi52bi9jcmwvbWljbnJjYS5jcmwwRwYIKwYBBQUHAQEEOzA5MDcGCCsGAQUFBzAChitodHRwOi8vcHVibGljLnJvb3RjYS5nb3Yudm4vY3J0L21pY25yY2EuY3J0MA0GCSqGSIb3DQEBBQUAA4IBAQCHtdHJXudu6HjO0571g9RmCP4b/vhK2vHNihDhWYQFuFqBymCota0kMW871sFFSlbd8xD0OWlFGUIkuMCz48WYXEOeXkju1fXYoTnzm5K4L3DV7jQa2H3wQ3VMjP4mgwPHjgciMmPkaBAR/hYyfY77I4NrB3V1KVNsznYbzbFtBO2VV77s3Jt9elzQw21bPDoXaUpfxIde+bLwPxzaEpe7KJhViBccJlAlI7pireTvgLQCBzepJJRerfp+GHj4Z6T58q+e3a9YhyZdtAHVisWYQ4mY113K1V7Z4D7gisjbxExF4UyrX5G4W0h0gXAR5UVOstv5czQyDraTmUTYtx5J";
                    X509Certificate certViettelCA       = CertUtils.GetX509Cert(certViettelCABase64);
                    if (certViettelCA != null)
                    {
                        certChain = new X509Certificate[] { x509Cert, certViettelCA };
                    }
                }

                if (certChain == null || certChain.Length != 2)
                {
                    descErrorHashFile = "Lấy Chứng thư số không thành công. Không lấy được CTS CA.";
                    return(View());
                }

                String base64Hash = null;

                //Trước khi insert thì kiểm tra chữ ký
                if (LoaiChuKy == 0)
                {
                    //Lấy ra các loại chữ ký
                    var lstChuKy = (from t in _chuKyRepos.GetAll() where t.IsActive == true && t.UserId == UserSession.Id select t).ToList();
                    if (lstChuKy.Count == 0)
                    {
                        descErrorHashFile = "Người dùng chưa import chữ ký, Vui lòng import chữ ký";
                        return(Json(new
                        {
                            statusResultHashFile = statusResultHashFile,
                            descErrorHashFile = descErrorHashFile,
                            serialNumber = "",
                            hashBase64 = ""
                        }, JsonRequestBehavior.AllowGet));
                    }
                    if (lstChuKy.Count > 0)
                    {
                        int   trangky   = 1;
                        float vitrix    = 0;
                        float vitriy    = 0;
                        float widthImg  = 0;
                        float heightImg = 0;

                        Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
                        doc.LoadFromFile(fileFullPath);
                        PdfTextFind[] results = null;

                        int checkChuKy = 0;
                        for (int k = 0; k < doc.Pages.Count; k++)

                        {
                            PdfPageBase page = doc.Pages[k];
                            for (int i = 0; i < lstChuKy.Count; i++)
                            {
                                var machu = "ATTP_" + lstChuKy[i].MaChuKy;
                                results = page.FindText(machu).Finds;
                                if (results.Length > 0)
                                {
                                    foreach (PdfTextFind text in results)
                                    {
                                        var ImageData = lstChuKy[i].DataImage;
                                        var urlImage  = (Path.Combine(HCC_FILE_PDF, lstChuKy[i].UrlImage));
                                        if (!string.IsNullOrEmpty(urlImage))
                                        {
                                            if (!System.IO.File.Exists(urlImage))
                                            {
                                                descErrorHashFile = "Chữ ký người dùng chưa import";
                                                return(Json(new
                                                {
                                                    statusResultHashFile = statusResultHashFile,
                                                    descErrorHashFile = descErrorHashFile,
                                                    serialNumber = "",
                                                    hashBase64 = ""
                                                }, JsonRequestBehavior.AllowGet));
                                            }

                                            ImageData = System.IO.File.ReadAllBytes(urlImage);
                                        }
                                        //System.Drawing.Image image = null;
                                        //using (var ms = new MemoryStream(ImageData))
                                        //{
                                        //    image = Image.FromStream(ms);
                                        //}

                                        trangky   = k + 1;
                                        vitrix    = text.Position.X;
                                        vitriy    = page.Size.Height - text.Position.Y - 20;
                                        widthImg  = 80;
                                        heightImg = 40;
                                        if (lstChuKy[i].LoaiChuKy == (int)CommonENum.LOAI_CHU_KY.CHU_KY)
                                        {
                                            if (machu == "ATTP_CK_1_1")
                                            {
                                                widthImg  = 171;
                                                heightImg = 100;
                                                vitrix    = text.Position.X - 30;
                                                vitriy    = page.Size.Height - text.Position.Y - 80;
                                            }
                                            else
                                            {
                                                widthImg  = 80;
                                                heightImg = 40;
                                                vitriy    = page.Size.Height - text.Position.Y - 20;
                                            }

                                            //điều chỉnh kích thước theo cấu hình của chữ ký
                                            if (lstChuKy[i].ChieuRong.HasValue && lstChuKy[i].ChieuRong > 0)
                                            {
                                                widthImg = lstChuKy[i].ChieuRong.Value;
                                            }
                                            if (lstChuKy[i].ChieuCao.HasValue && lstChuKy[i].ChieuCao > 0)
                                            {
                                                heightImg = lstChuKy[i].ChieuCao.Value;
                                            }
                                        }
                                        if (lstChuKy[i].LoaiChuKy == (int)CommonENum.LOAI_CHU_KY.DAU_CUA_CUC)
                                        {
                                            widthImg  = 75;
                                            heightImg = 75;
                                            vitrix    = text.Position.X - (widthImg / 2);
                                            vitriy    = page.Size.Height - text.Position.Y - heightImg;
                                        }
                                        base64Hash = HashFilePDF.GetHashTypeImage_ExistedSignatureField(fileFullPath, certChain, k + 1, urlImage, vitrix, vitriy, widthImg, heightImg);
                                        checkChuKy = 1;
                                    }
                                }
                            }
                        }
                        if (checkChuKy == 0)
                        {
                            base64Hash = HashFilePDF.GetHashTypeRectangleText(1, fileFullPath, certChain);
                        }
                    }
                }
                else if (LoaiChuKy == 1)
                {
                    base64Hash = HashFilePDF.GetHashTypeRectangleText(numberPage, fileFullPath, certChain);
                }
                else
                {
                    base64Hash = HashFilePDF.GetHashTypeRectangleText(numberPage, fileFullPath, certChain);
                }
                if (base64Hash == null)
                {
                    descErrorHashFile = "Tạo Hash không thành công";
                    return(View());
                }

                statusResultHashFile = "success";
                serialNumber         = x509Cert.SerialNumber.ToString(16);
                hashBase64           = base64Hash;
                return(Json(new
                {
                    statusResultHashFile = statusResultHashFile,
                    descErrorHashFile = descErrorHashFile,
                    serialNumber = serialNumber,
                    hashBase64 = hashBase64
                }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception)
            {
                descErrorHashFile = "Lỗi trong quá trình xử lý";
                return(Json(new
                {
                    statusResultHashFile = statusResultHashFile,
                    descErrorHashFile = descErrorHashFile,
                    serialNumber = "",
                    hashBase64 = ""
                }, JsonRequestBehavior.AllowGet));
            }
        }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            //data holder
            var pdf_text = new object();

            MLContext mlContext = new MLContext();
            var       emptylist = new List <Input>();
            //convert list into dataview
            var emptyDataView = mlContext.Data.LoadFromEnumerable(emptylist);

            //create the transformation pipeline
            var textPipeline = mlContext.Transforms.Text.NormalizeText("Text")
                               .Append(mlContext.Transforms.Text.TokenizeIntoWords("Tokens", "Text"))
                               .Append(mlContext.Transforms.Text.RemoveDefaultStopWords("Tokens", "Tokens",
                                                                                        Microsoft.ML.Transforms.Text.StopWordsRemovingEstimator.Language.English))
                               .Append(mlContext.Transforms.Text.ApplyWordEmbedding("Features", "Tokens",
                                                                                    WordEmbeddingEstimator.PretrainedModelKind.SentimentSpecificWordEmbedding));
            //fit estimator to data
            var textTransformer = textPipeline.Fit(emptyDataView);
            //prediction engine
            var predictionEngine = mlContext.Model.CreatePredictionEngine <Input, TransformedText>(textTransformer);


            //using word document
            //Load Document

            Document document1 = new Document();

            document1.LoadFromFile(@"C:/Users/ben/Documents/attachments/CV1.docx");

            //using pdf document
            //Load Document
            Spire.Pdf.PdfDocument pdoc = new Spire.Pdf.PdfDocument();
            pdoc.LoadFromFile(@"C:/Users/ben/Documents/Volvo_Resume.pdf");

            //Initialzie StringBuilder Instance for pdf document
            StringBuilder sbpdf = new StringBuilder();

            //Extract text from all pages
            foreach (PdfPageBase page in pdoc.Pages)
            {
                sbpdf.Append(page.ExtractText());
            }


            //Initialzie StringBuilder Instance for word document
            StringBuilder sb = new StringBuilder();

            //Extract Text from Word and Save to StringBuilder Instance
            foreach (Section section in document1.Sections)
            {
                foreach (Paragraph paragraph in section.Paragraphs)

                {
                    sb.AppendLine(paragraph.Text);
                }
            }


            //get the input text from pdf file
            var data = new Input()
            {
                Text = pdf_text.ToString()
            };

            //text from the doc file
            var data1 = new Input()
            {
                Text = sb.ToString()
            };

            //text from the doc file
            //var data2 = new Input() { Text = sbpdf.ToString() };

            //Test data with job specification
            var test_data = new Input()
            {
                Text = "Sofware Developer"
            };

            //call the prediction API
            var prediction = predictionEngine.Predict(data);


            //predict test data
            var test_pred = predictionEngine.Predict(test_data);


            //Print the length off embedding vector for PDF File
            Console.WriteLine($"Number of Features: {prediction.Features.Length}");

            //Print embedding vector
            Console.Write("Features: ");
            foreach (var f in prediction.Features)
            {
                Console.Write($"{f:F4} ");
            }


            //Randomly Retreive some of the feature gotten from the word embeddings vector
            float word  = (float)prediction.Features.GetValue(40);
            float word2 = (float)prediction.Features.GetValue(89);
            float word3 = (float)prediction.Features.GetValue(100);
            float word4 = (float)prediction.Features.GetValue(3);
            float word5 = (float)prediction.Features.GetValue(9);
            float word6 = (float)prediction.Features.GetValue(0);
            float word7 = (float)prediction.Features.GetValue(78);
            float word8 = (float)prediction.Features.GetValue(20);

            //Randomly Retrieve features from the test data
            float test_word  = (float)test_pred.Features.GetValue(0);
            float test_word2 = (float)test_pred.Features.GetValue(39);
            float test_word3 = (float)test_pred.Features.GetValue(45);
            float test_word4 = (float)test_pred.Features.GetValue(99);
            float test_word5 = (float)test_pred.Features.GetValue(30);
            float test_word6 = (float)test_pred.Features.GetValue(24);
            float test_word7 = (float)test_pred.Features.GetValue(26);


            //calculating mikownski distance
            //create a dictionary to add the word embeddings vector
            Dictionary <string, List <double> > map = new Dictionary <string, List <double> >();
            List <double> listA = new List <double>(new double[] {
                (double)word, (double)word2, (double)word3, (double)word4, (double)word5, (double)word6, (double)word7
            });

            map.Add("Feature1", listA);

            //a testlist to hold the job description word embedding vector
            List <double> testList = new List <double>(new double[] {
                (double)test_word, (double)test_word2, (double)test_word3, (double)test_word4, (double)test_word5, (double)test_word6, (double)test_word7
            });

            string similar_word = mostSimilarKey(testList, map);

            Console.WriteLine("Most similar key is: " + similar_word);
        }
Ejemplo n.º 28
0
        private void SendToPrinter()
        {
            var     basePath            = AppDomain.CurrentDomain.BaseDirectory;
            var     guidNumber          = Guid.NewGuid().ToString().Substring(0, 6);
            var     barcodeGeneratePath = basePath + "BarcodePdfs\\" + guidNumber;
            Barcode b = new Barcode()
            {
                Height       = 100,
                IncludeLabel = true
            };

            System.Drawing.Image img = b.Encode(TYPE.CODE128, productCode.Text);
            img.Save(barcodeGeneratePath + ".png");
            //BarcodeSettings bs = new BarcodeSettings();
            //bs.Data = TextBox1.Text;
            //bs.Data2D = TextBox1.Text;
            //bs.ShowText = true;
            ////bs.BarHeight = 1;
            ////bs.X = 1;
            ////bs.Y = 1;
            //BarCodeGenerator generator = new BarCodeGenerator(bs);
            //System.Drawing.Image barcode = generator.GenerateImage();

            //var basePath = AppDomain.CurrentDomain.BaseDirectory;
            //var guidNumber = Guid.NewGuid().ToString().Substring(0, 6);
            //var barcodeGeneratePath = basePath + "BarcodePdfs\\" + guidNumber;
            ////save the barcode as an image
            //barcode.Save(barcodeGeneratePath + ".png");


            Spire.Pdf.PdfDocument doc     = new Spire.Pdf.PdfDocument();
            PdfSection            section = doc.Sections.Add();
            PdfPageBase           page    = doc.Pages.Add();

            //PdfImage image = PdfImage.FromFile(barcodeGeneratePath + ".png");
            ////Set image display location and size in PDF

            ////float widthFitRate = image.PhysicalDimension.Width / page.Canvas.ClientSize.Width;
            ////float heightFitRate = image.PhysicalDimension.Height / page.Canvas.ClientSize.Height;
            ////float fitRate = Math.Max(widthFitRate, heightFitRate);
            ////float fitWidth = image.PhysicalDimension.Width / fitRate;
            ////float fitHeight = image.PhysicalDimension.Height / fitRate;

            //var barcodeImageWidth = 100;
            //var barcodeImageHeigth = 40;

            //page.Canvas.DrawImage(image, 30, 30, barcodeImageWidth, barcodeImageHeigth);

            //doc.SaveToFile(barcodeGeneratePath + ".pdf");
            //doc.Close();
            var strHtml = System.IO.File.ReadAllText(basePath + "PrintPage.html");

            strHtml = strHtml.Replace("##CompanyName##", companyName.Text);
            strHtml = strHtml.Replace("##BarcodeImage##", guidNumber + ".png");
            strHtml = strHtml.Replace("##ProductName##", productName.Text);

            // instantiate a html to pdf converter object

            HtmlToPdf converter = new HtmlToPdf();

            //// set converter options
            //converter.Options.PdfPageSize = pageSize;
            //converter.Options.PdfPageOrientation = pdfOrientation;
            //converter.Options.WebPageWidth = webPageWidth;
            //converter.Options.WebPageHeight = webPageHeight;

            // create a new pdf document converting an url
            SelectPdf.PdfDocument pdfDoc = converter.ConvertHtmlString(strHtml, basePath + "BarcodePdfs\\");

            // save pdf document
            pdfDoc.Save(barcodeGeneratePath + ".pdf");

            // close pdf document
            pdfDoc.Close();



            doc.LoadFromFile(barcodeGeneratePath + ".pdf");
            doc.PrintDocument.Print();
        }