Example #1
0
        protected override string ExtractText(string extensionName, byte[] data)
        {
            StringBuilder stringBuilder = new StringBuilder();

            PdfDocumentBase doc = null;

            try
            {
                using (MemoryStream memoryStream = new MemoryStream(data))
                {
                    doc = SPdfDocument.MergeFiles(new Stream[] { memoryStream });
                    foreach (PdfPageBase page in doc.Pages)
                    {
                        stringBuilder.AppendLine(page.ExtractText());
                    }
                    doc.Close();
                }
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();
                }
            }
            return(stringBuilder.ToString());
        }
Example #2
0
        protected override Picture[] ExtractImages(string extensionName, byte[] data)
        {
            List <Picture>  pictures = new List <Picture>();
            PdfDocumentBase doc      = null;

            try
            {
                using (MemoryStream memoryStream = new MemoryStream(data))
                {
                    doc = SPdfDocument.MergeFiles(new Stream[] { memoryStream });
                    foreach (PdfPageBase page in doc.Pages)
                    {
                        foreach (Image image in page.ExtractImages())
                        {
                            pictures.Add(new Picture()
                            {
                                Data      = GetImageData(image),
                                Extension = ImageFormat.Jpeg.ToString(),
                                Width     = image.Width,
                                Height    = image.Height
                            });
                        }
                    }
                }
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();
                }
            }
            return(pictures.ToArray());
        }
Example #3
0
        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);
            }
        }
Example #4
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);
            }
        }
 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));
 }
Example #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);
                    }
                }
            }
        }
Example #7
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();
            }
        }
Example #8
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);
        }
Example #9
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);
     }
 }
Example #10
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
        }
Example #11
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);
        }
        /// <summary> SPIRE_JPEG 左上角有水印
        ///     分辨率:1280x 720
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="outputPath"></param>
        /// <returns></returns>
        List <PPTPage> spirePDF(string filepath, string outputPath)
        {
            List <PPTPage> pages = new List <PPTPage>();

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

            int pageCount = doc.Pages.Count;
            int width     = (int)doc.PageSettings.Width;
            int height    = (int)doc.PageSettings.Height;

            for (int i = 0; i < pageCount;)
            {
                string path = string.Format("{0}/img-{1}.jpeg", outputPath, i);

                System.Drawing.Image img = doc.SaveAsImage(i);
                img.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);

                pages.Add(new PPTPage()
                {
                    Cover = path
                });
                Console.WriteLine("PDF TO IMAGES - {0}/{1}", ++i, pageCount);
            }

            return(pages);
        }
Example #13
0
        public static byte[] SpirePDFHtmlToPDF(string html)
        {
            byte[] ret = null;

            //using (MemoryStream ms = new MemoryStream())
            //{
            //    Spire.Pdf.HtmlConverter.Qt.HtmlConverter.Convert(
            //    html,
            //    //memory stream
            //    ms,
            //    //enable javascript
            //    true,
            //    //load timeout
            //    10 * 1000,
            //    //page size
            //    new SizeF(612, 792),
            //    //page margins
            //    new Spire.Pdf.Graphics.PdfMargins(0),
            //    //load from content type
            //    LoadHtmlType.SourceCode
            //    );
            //}

            using (MemoryStream ms = new MemoryStream())
            {
                //Create a pdf document.
                Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();

                PdfPageSettings setting = new PdfPageSettings();

                //setting.Size = new SizeF(1000, 1000);
                setting.Size        = Spire.Pdf.PdfPageSize.A4;
                setting.Orientation = Spire.Pdf.PdfPageOrientation.Portrait;
                setting.Margins     = new Spire.Pdf.Graphics.PdfMargins(20);

                doc.Template.Top = GetHeader(doc, setting.Margins);
                //apply blank templates to other parts of page template
                doc.Template.Bottom = new PdfPageTemplateElement(doc.PageSettings.Size.Width, setting.Margins.Bottom);
                doc.Template.Left   = new PdfPageTemplateElement(setting.Margins.Left, doc.PageSettings.Size.Height);
                doc.Template.Right  = new PdfPageTemplateElement(setting.Margins.Right, doc.PageSettings.Size.Height);

                PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
                htmlLayoutFormat.IsWaiting = true;

                Thread thread = new Thread(() =>
                                           { doc.LoadFromHTML(html, true, setting, htmlLayoutFormat); });
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
                thread.Join();

                //Save pdf file.
                doc.SaveToStream(ms);
                doc.Close();

                ret = ms.ToArray();
            }

            return(ret);
        }
Example #14
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);
        }
Example #15
0
 private void Preview_Load(object sender, EventArgs e)
 {
     Spire.Pdf.PdfDocument pdfdocument = new Spire.Pdf.PdfDocument();
     if (File.Exists(_Analis.filename))
     {
         //   pdfDocumentViewer1.LoadFromFile(_Analis.filename);
     }
     pdfdocument.PrintDocument.Print();
     pdfdocument.Dispose();
 }
        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);
        }
Example #17
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();
        }
Example #18
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();
        }
Example #19
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");
         }
     }
 }
Example #20
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();
         }
     }
 }
Example #21
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);
            }
        }
Example #22
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();
        }
Example #23
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");
        }
Example #24
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);
        }
        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;
        }
Example #27
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();
            }
        }
Example #29
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();
            }
        }
Example #30
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();
        }