Exemple #1
0
        public static void SpireMultiThreadAPI()
        {
            try
            {
                Stopwatch watch = new Stopwatch();
                watch.Start();
                string url = @"C:\Users\BuzzBuzzUser\Pictures\PDFSImages.pdf";

                //HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                //HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse();
                //string fileName = url.Substring(url.LastIndexOf("/"));

                //MemoryStream memStream;
                //using (var stream = httpWebReponse.GetResponseStream())
                //{
                //    memStream = new MemoryStream();

                //    byte[] buffer = new byte[1024];
                //    int byteCount;
                //    do
                //    {
                //        byteCount = stream.Read(buffer, 0, buffer.Length);
                //        memStream.Write(buffer, 0, byteCount);
                //    } while (byteCount > 0);
                //}
                //memStream.Seek(0, SeekOrigin.Begin);

                watch.Stop();
                Console.WriteLine("It took {0} milliseconds to download the file", watch.ElapsedMilliseconds);
                watch.Restart();

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

                doc.LoadFromFile(url);
                //doc.LoadFromStream(memStream);
                Object thisLock = new Object();
                Dictionary <int, Spire.Pdf.PdfDocument> dictPDFDoc = new Dictionary <int, Spire.Pdf.PdfDocument>();

                for (int i = 0; i < doc.Pages.Count; i++)
                {
                    Spire.Pdf.PdfDocument pdfdoc = new Spire.Pdf.PdfDocument();
                    //pdfdoc.LoadFromStream(memStream);
                    pdfdoc.LoadFromFile(url);
                    dictPDFDoc.Add(i, pdfdoc);
                }

                foreach (var key in dictPDFDoc.Keys)
                {
                    Thread t = new Thread(() => SaveImage(dictPDFDoc[key], "", key));
                    t.Start();
                }

                watch.Stop();
                Console.WriteLine("PDF conversion took {0} milliseconds", watch.ElapsedMilliseconds);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
 public System.Drawing.Image ConvertPdfToImage()
 {
     try
     {
         Spire.Pdf.PdfDocument pdfDocument = new Spire.Pdf.PdfDocument();
         pdfDocument.LoadFromFile(this.FilePath);
         System.Drawing.Image image1 = pdfDocument.SaveAsImage(0, PdfImageType.Metafile);
         Size size  = image1.Size;
         int  width = size.Width * 5;
         size = image1.Size;
         int height = size.Height * 5;
         System.Drawing.Image image2 = (System.Drawing.Image) new Bitmap(width, height);
         using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(image2))
         {
             graphics.ScaleTransform(5f, 5f);
             graphics.DrawImage(image1, new System.Drawing.Rectangle(new Point(0, 0), image1.Size), new System.Drawing.Rectangle(new Point(0, 0), image1.Size), GraphicsUnit.Pixel);
         }
         MembercardService.logger.Debug("PDF conversion to image succeeded.");
         return(image2);
     }
     catch (Exception ex)
     {
         MembercardService.logger.Error("PDF conversion to image failed:" + ex.Message);
         return((System.Drawing.Image)null);
     }
 }
        /// <summary>
        /// Uploads a file to the webserver.
        /// </summary>
        /// <param name="title">The title for the file, to be used in the Database.</param>
        /// <param name="type">What type of file is uploaded. Example: 'FirstAid' or 'DoctorsNote'.</param>
        /// <param name="fileLocation">The local filepath to the document.</param>
        /// <param name="url">The url of the server, where the file will be uploaded.</param>
        /// <returns>Returns a bool wether the operation was completed or not.</returns>
        private bool UploadFile(string title, string type, string fileLocation, string url)
        {
            Spire.Pdf.PdfDocument document = new Spire.Pdf.PdfDocument();
            FileInfo file = new FileInfo(fileLocation);

            if (!file.Exists)
            {
                return(false);
            }

            if (file.Extension != ".pdf")
            {
                Spire.Pdf.PdfPageBase page = document.Pages.Add();

                PdfImage image = PdfImage.FromFile(fileLocation);
                fileLocation = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.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;
                page.Canvas.DrawImage(image, 30, 30, fitWidth, fitHeight);

                document.DocumentInformation.Title        = $"{Session.LoggedInUser.Fullname} - {type}";
                document.DocumentInformation.Author       = Session.LoggedInUser.Fullname;
                document.DocumentInformation.CreationDate = DateTime.Now;

                document.SaveToFile(fileLocation);
                document.Close();
            }
            else
            {
                document.LoadFromFile(fileLocation);
                document.DocumentInformation.Title        = $"{Session.LoggedInUser.Fullname} - {type}";
                document.DocumentInformation.Author       = Session.LoggedInUser.Fullname;
                document.DocumentInformation.CreationDate = DateTime.Now;

                document.SaveToFile(fileLocation);
                document.Close();
            }

            document.Dispose();

            string fileUrl = SendToServer(fileLocation, url);

            if (fileUrl == "null")
            {
                return(false);
            }

            if (!MySql.UploadDocument(title, type, DateTime.Today, Session.LoggedInUser.Id, fileUrl))
            {
                return(false);
            }

            return(true);
        }
Exemple #4
0
 public Image FirstPage(string sourcePath)
 {
     if (File.Exists(sourcePath))
     {
         var doc = new Spire.Pdf.PdfDocument();
         doc.LoadFromFile(sourcePath);
         return(doc.SaveAsImage(0));
     }
     return(null);
 }
Exemple #5
0
 void PdftoIMG(string pdfpath)
 {
     Spire.Pdf.PdfDocument pdfdocument = new Spire.Pdf.PdfDocument();
     pdfdocument.LoadFromFile(pdfpath);
     //for (int i = 0; i < pdfdocument.Pages.Count; i++)
     //{
     System.Drawing.Image image = pdfdocument.SaveAsImage(0, 96, 96);
     image.Save(string.Format(Server.MapPath("~/Images/UIDimage/New.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg));
     //}
 }
Exemple #6
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".pdf";
            dlg.Filter     = "PDF Files (*.pdf)|*.pdf";

            bool?result = dlg.ShowDialog();

            if (result == true)
            {
                Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument();
                pathToBackground = dlg.FileName;
                pdf.LoadFromFile(pathToBackground);

                try
                {
                    //zapisanie strony pdf jako image
                    Image bmp = pdf.SaveAsImage(0);

                    //konwersja z Image na BitmapImage
                    MemoryStream ms = new MemoryStream();
                    bmp.Save(ms, ImageFormat.Bmp);

                    BitmapImage image = new BitmapImage();
                    image.BeginInit();
                    image.StreamSource = ms;
                    image.EndInit();

                    //ustawienie tła
                    DiplomaBackground.Source = image;

                    //w przypadku poprawnego wczytania pliku i poprawnego wykonania działań na nim
                    Description.Visibility          = Visibility.Hidden;
                    ParticipantNameLabel.Visibility = Visibility.Visible;
                    TextPathToPDF.Text           = pathToBackground;
                    LabelPathToPDF.Visibility    = Visibility.Visible;
                    TextPathToPDF.Visibility     = Visibility.Visible;
                    checkBoxBackground.IsChecked = true;
                    isPDFloaded = true;
                    if (isPathChosen && Globals.database != null && Globals.database.isConnected())
                    {
                        GeneratePDFs.IsEnabled = true;
                    }
                    MessageBox.Show("Poprawnie wczytano obraz.", "Informacja", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (OutOfMemoryException ex)
                {
                    MessageBox.Show("Za mało pamięci, aby kontynuować. \nKomunikat błędu: " + ex, "Błąd", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
                catch (FileNotFoundException ex)
                {
                    MessageBox.Show("Nie znaleziono pliku. \nKomunikat błędu: " + ex, "Błąd", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }
        private void FormPrintBRD_Load(object sender, EventArgs e)
        {
            PrintBorderau print = new PrintBorderau();

            print.Departure = Departure;

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

            printPreviewControl1.Document = doc.PrintDocument;
        }
Exemple #8
0
 private static void PrintPdf(string path)
 {
     try
     {
         var doc = new PdfDocument();
         doc.LoadFromFile(path);
         doc.PrintDocument.Print();
     }
     finally
     {
         File.Delete(path);
     }
 }
Exemple #9
0
        public static void SpireAPI()
        {
            try
            {
                Stopwatch watch = new Stopwatch();
                watch.Start();
                string url = @"C:\Users\BuzzBuzzUser\Pictures\PDFSImages.pdf";
                //HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                //HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse();

                //MemoryStream memStream;
                //using (var stream = httpWebReponse.GetResponseStream())
                //{
                //    memStream = new MemoryStream();

                //    byte[] buffer = new byte[1024];
                //    int byteCount;
                //    do
                //    {
                //        byteCount = stream.Read(buffer, 0, buffer.Length);
                //        memStream.Write(buffer, 0, byteCount);
                //    } while (byteCount > 0);
                //}
                //memStream.Seek(0, SeekOrigin.Begin);

                watch.Stop();
                Console.WriteLine("It took {0} milliseconds to download the file", watch.ElapsedMilliseconds);
                watch.Restart();

                Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
                doc.LoadFromFile(url);
                //doc.LoadFromStream(memStream);
                //string fileName = url.Substring(url.LastIndexOf("/"));

                for (int i = 0; i < doc.Pages.Count; i++)
                {
                    //Console.WriteLine(doc.Pages[i].IsBlank());
                    var pdfImg = doc.SaveAsImage(i, Spire.Pdf.Graphics.PdfImageType.Bitmap, 300, 300);

                    pdfImg.Save(string.Format(@"C:\Users\BuzzBuzzUser\Pictures\Saved Pictures\{0}.bmp", i));
                    //pdfImg.Save(string.Format(@"C:\Users\BuzzBuzzUser\Pictures\Saved Pictures\{0}.png", i));
                }

                watch.Stop();
                Console.WriteLine("PDF conversion took {0} milliseconds", watch.ElapsedMilliseconds);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
        }
Exemple #10
0
        private void FormPrintByLocation_Load(object sender, EventArgs e)
        {
            PrintMaterialsListByLocation printMaterialsList = new PrintMaterialsListByLocation();



            printMaterialsList.Location = Location;

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

            printPreviewControl1.Document = doc.PrintDocument;
        }
Exemple #11
0
        private void PDF()
        {
            Spire.Pdf.PdfDocument document = new Spire.Pdf.PdfDocument();
            document.LoadFromFile(sciezkaDoPliku);
            Image wynik = document.SaveAsImage(0, Spire.Pdf.Graphics.PdfImageType.Metafile);

            for (int i = 1; i < document.Pages.Count; i++)
            {
                Image pom = document.SaveAsImage(i, Spire.Pdf.Graphics.PdfImageType.Metafile);
                wynik = MergeTwoImages(wynik, pom);
                pom.Dispose();
            }
            wynik.Save(sciezgaDoZapisaniaPliku + /*"_" + document.Pages.Count + */ ".jpg");
            wynik.Dispose();
            document.Dispose();
        }
Exemple #12
0
        private void printToPrinter(string printerName, string filePath)
        {
            Spire.Pdf.PdfDocument pdfdocument = new Spire.Pdf.PdfDocument();
            pdfdocument.LoadFromFile(filePath);
            pdfdocument.PrinterName = printerName;

            PaperSize paperSize = new PaperSize();

            paperSize.Width   = 283; //inch*100
            paperSize.Height  = 826; //inch*100
            paperSize.RawKind = (int)PaperKind.Custom;
            //  pdfdocument.PrinterSettings.PaperSize = paperSize;

            //pdfdocument.war
            pdfdocument.PrintDocument.PrinterSettings.Copies = 1;
            pdfdocument.PrintDocument.Print();
            pdfdocument.Dispose();
        }
        private void print_btn_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();
            }
        }
Exemple #14
0
        public async Task ConvertToImage(string fileLink)
        {
            try
            {
                string      tortf = ReadPdfFile(fileLink);
                RichTextBox rtf   = new RichTextBox();
                rtf.Document.Blocks.Clear();
                rtf.Document.Blocks.Add(new Paragraph(new Run(tortf)));
                string path = System.IO.Path.GetDirectoryName(fileLink);

                if (!Directory.Exists(path))
                {
                    DirectoryInfo di = Directory.CreateDirectory(path);
                }
                Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument();

                await Task.Run(() =>
                {
                    pdf.LoadFromFile(fileLink);
                    System.Drawing.Size size = new System.Drawing.Size(650, 1080);
                    for (int i = 0; i <= pdf.Pages.Count; i++)
                    {
                        try
                        {
                            var source         = pdf.SaveAsImage(i);
                            Bitmap bitmapImage = (Bitmap)source;
                            var result         = new Bitmap(Resize(bitmapImage, size, ImageFormat.Png));
                            result.Save(path + @"\page" + i.ToString() + ".png", ImageFormat.Png);
                        }
                        catch
                        {
                        }
                    }
                });
            }
            catch (Exception r)
            {
                MessageBox.Show(r.Message);
            }
        }
Exemple #15
0
        public void SaveAsImage(string sourcePath, string targetPath)
        {
            // Get some file names
            string[] files = GetPDfs(sourcePath);

            // Iterate files
            foreach (string file in files)
            {
                var name = Path.GetFileNameWithoutExtension(file);
                var path = targetPath.Contains(".") ? Path.GetDirectoryName(targetPath) : targetPath;
                if (File.Exists(Path.Combine(path, name + "_1".ToString() + ".jpg")))
                {
                    continue;
                }
                var doc = new Spire.Pdf.PdfDocument();
                doc.LoadFromFile(file);
                for (int it = 0; it < doc.Pages.Count; it++)
                {
                    var bmp = doc.SaveAsImage(it);
                    bmp.Save(Path.Combine(path, name + "_" + (it + 1).ToString() + ".jpg"), ImageFormat.Jpeg);
                }
            }
        }
Exemple #16
0
        private void BatchPrint(object sender, DoWorkEventArgs e)
        {
            int    tick      = 0;
            int    total     = _items.Count;
            string signature = "";
            string purpose   = "";
            double fee       = 0d;

            App.Current.Dispatcher.Invoke((Action) delegate            // <--- HERE
            {
                QueueCounter.Content      = tick + "/" + total;
                QueuePBar.IsIndeterminate = true;

                signature = Signatory.Text;
                purpose   = Purpose.Text;
                fee       = Convert.ToDouble(PrintingFee.Value);
            });

            for (int i = 0; i < _items.Count; i++)
            {
                App.Current.Dispatcher.Invoke((Action) delegate                // <--- HERE
                {
                    QueueCounter.Content = tick + "/" + total;
                });
                RecordEntryBurial recordx = (RecordEntryBurial)_items[i];

                string[] bspl = DateTime.Parse(recordx.BurialDate + "," + recordx.BurialYear).ToString("MM/dd/yyyy").Split('/');
                string   bmon = PrepMonth(int.Parse(bspl[0]));

                string[] dspl = DateTime.Parse(recordx.DeathDate + "," + recordx.DeathYear).ToString("MM/dd/yyyy").Split('/');
                string   dmon = PrepMonth(int.Parse(dspl[0]));

                Document doc = new Document();
                doc.LoadFromFile("Data\\temp_death.docx");
                doc.Replace("name", recordx.FullName, true, true);
                doc.Replace("age", Convert.ToString(recordx.Age), true, true);
                doc.Replace("nationality", "Filipino", true, true);
                doc.Replace("residence", recordx.Residence1, true, true);
                doc.Replace("civil", recordx.Status, true, true);

                if (string.IsNullOrEmpty(recordx.Parent2))
                {
                    doc.Replace("father", " ", true, true);
                    doc.Replace("mother", " ", true, true);
                    doc.Replace("spouse", recordx.Parent1, true, true);
                }
                else
                {
                    doc.Replace("father", recordx.Parent1, true, true);
                    doc.Replace("mother", recordx.Parent2, true, true);
                    doc.Replace("spouse", " ", true, true);
                }
                doc.Replace("date_of_birth", bmon + " " + bspl[1] + ", " + bspl[2], true, true);
                doc.Replace("cause_of_death", recordx.CauseOfDeath, true, true);
                doc.Replace("date_of_burial", dmon + " " + dspl[1] + ", " + dspl[2], true, true);
                doc.Replace("place_of_burial", recordx.PlaceOfInterment, true, true);
                doc.Replace("priest", recordx.Minister, true, true);
                doc.Replace("sign", signature, true, true);
                doc.Replace("no", recordx.EntryNumber.ToString(), true, true);
                doc.Replace("page", GetPNum(recordx.RecordID).ToString(), true, true);
                string[] date = DateTime.Now.ToString("MMMM,d,yyyy").Split(',');;
                doc.Replace("month", date[0], true, true);
                doc.Replace("day", date[1], true, true);
                doc.SaveToFile("Data\\print-" + i + ".docx", FileFormat.Docx);

                //Load Document
                Document document = new Document();
                document.LoadFromFile(@"Data\\print-" + i + ".docx");

                //Convert Word to PDF
                document.SaveToFile("Output\\print_file-" + i + ".pdf", FileFormat.PDF);

                App.Current.Dispatcher.Invoke((Action) delegate                // <--- HERE
                {
                    if (SkipPreview.IsChecked == true)
                    {
                        Spire.Pdf.PdfDocument docx = new Spire.Pdf.PdfDocument();
                        docx.LoadFromFile(@"Output\\print_file-" + i + ".pdf");
                        docx.PrintDocument.Print();
                    }
                    else
                    {
                        System.Diagnostics.Process.Start("Output\\print_file-" + i + ".pdf");
                    }


                    //Reference
                    string tmp = pmsutil.LogRecord(recordx.RecordID, "LOGC-03");
                });
                pmsutil.InsertTransaction("Burial Cert.", "Paying", recordx.RecordID, Convert.ToDouble(pmsutil.GetPrintFee("Burial")));

                tick++;
            }
        }
Exemple #17
0
        public string GenerarCredencial()
        {
            string fileName = string.Empty;

            #region iniciandoDocumento
            doc.AddAuthor("CODESUR");
            doc.AddKeywords("pdf, PdfWriter; Documento; iTextSharp");
            fileName = string.Format("CredencialAcreditacion_{0}_{1:yyyyMMddHHss}.pdf", Usuario, DateTime.Now);
            string path = PathResources;
            path = string.Format("{0}Reportes\\{1}", path, fileName);
            PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create));
            doc.Open();
            #endregion
            try
            {
                AgregarFondoAnverso();
                AgregarFoto();
                AgregarQR();
                AgregarCodigoRol();
                AgregarNombre();
                AgregarDatosDelegacion();
                AgregarPrivilegios();
                AgregarFondoReverso();
                AgregarCodigoBarras(wri);
                AgregarTextoFoto();
                AgregarNombreReverso();
                AgregarPrivilegiosReverso();
                PdfContentByte cb = wri.DirectContent;
                //PdfPTable table = new PdfPTable(1);
                ////PdfPCell[] cells = new PdfPCell[] { new PdfPCell(new Phrase("HOLAAA"))};
                ////PdfPRow p = new PdfPRow(cells);
                ////p.
                //table.TotalWidth = 400f;
                //table.AddCell("Test");
                //table.WriteSelectedRows(0, -1, 200, 50, cb);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                doc.Close();
            }
            Spire.License.LicenseProvider.SetLicenseFileFullPath(@"C:\Hammer\ExternalReferences\license.lic");
            Spire.Pdf.PdfDocument pdfdocument = new Spire.Pdf.PdfDocument();
            try
            {
                pdfdocument.LoadFromFile(path);
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                Document  realDoc = new Document(new Rectangle(566f, 454f), 0f, 0f, 0f, 0f);
                PdfPTable Reporte = new PdfPTable(new float[] { 283f, 283f });
                Reporte.WidthPercentage = 100;
                for (int i = 0; i < pdfdocument.Pages.Count; i++)
                {
                    System.Drawing.Image image = pdfdocument.SaveAsImage(i, 480, 500);
                    MemoryStream         ms    = new MemoryStream();
                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    iTextSharp.text.Image imgpdf = iTextSharp.text.Image.GetInstance(ms.ToArray());
                    PdfPCell imgCell             = new PdfPCell(imgpdf, true);
                    Reporte.AddCell(imgCell);
                }
                PdfWriter realWri = PdfWriter.GetInstance(realDoc, new FileStream(path, FileMode.Create));
                realDoc.Open();
                realDoc.Add(Reporte);


                realDoc.Close();
            }
            catch
            {
            }
            return(path);
        }
Exemple #18
0
        public string GenerarCredencial()
        {
            string fileName = string.Empty;

            #region iniciandoDocumento
            doc.AddAuthor("CODESUR");
            doc.AddKeywords("pdf, PdfWriter; Documento; iTextSharp");
            fileName = string.Format("CredencialAcreditacion_{0}_{1:yyyyMMddHHss}.pdf", Usuario, DateTime.Now);
            string path = PathResources;
            path = string.Format("{0}Reportes\\{1}", path, fileName);
            PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create));
            doc.Open();
            #endregion
            try
            {
                AgregarFondoAnverso();
                AgregarFoto();
                AgregarQR();
                AgregarCodigoRol();
                AgregarNombre();
                AgregarDatosDelegacion();
                AgregarPrivilegios();
                AgregarFondoReverso();
                AgregarCodigoBarras(wri);
                AgregarTextoFoto();
                AgregarNombreReverso();
                AgregarPrivilegiosReverso();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                doc.Close();
            }

            Spire.Pdf.PdfDocument pdfdocument = new Spire.Pdf.PdfDocument();
            try
            {
                pdfdocument.LoadFromFile(path);
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                Document  realDoc = new Document(new Rectangle(566f, 454f), 0f, 0f, 0f, 0f);
                PdfPTable Reporte = new PdfPTable(new float[] { 283f, 283f });
                for (int i = 0; i < pdfdocument.Pages.Count; i++)
                {
                    System.Drawing.Image image = pdfdocument.SaveAsImage(i);
                    MemoryStream         ms    = new MemoryStream();
                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    iTextSharp.text.Image imgpdf = iTextSharp.text.Image.GetInstance(ms.ToArray());
                    PdfPCell imgCell             = new PdfPCell(imgpdf, true);
                    imgCell.Border          = PdfPCell.NO_BORDER;
                    imgCell.BackgroundColor = BaseColor.BLACK;
                    Reporte.AddCell(imgCell);
                }
                PdfWriter realWri = PdfWriter.GetInstance(realDoc, new FileStream(path, FileMode.Create));
                realDoc.Open();
                realDoc.Add(Reporte);
                realDoc.Close();
            }
            catch
            {
            }

            return(path);
        }
Exemple #19
0
        private byte[] MergePdf(string directoryPath)
        {
            try
            {
                Spire.Pdf.PdfDocument document = new Spire.Pdf.PdfDocument();
                var      mainUrl    = Path.Combine(_env.ContentRootPath, "wwwrootr");
                var      mainPdf    = Path.Combine(mainUrl, "pdf", "PropuestaComercial.pdf");
                int      totalFiles = mobilesPages + 2;
                string[] lstFiles   = new string[totalFiles];
                lstFiles[0] = mainPdf;
                lstFiles[1] = Path.Combine(directoryPath, "Subsidy.pdf");

                int index = 0;
                for (int i = 2; i < totalFiles; i++)
                {
                    lstFiles[i] = Path.Combine(directoryPath, "mobiles" + index.ToString() + ".pdf");
                    index++;
                }

                PdfReader       reader          = null;
                Document        sourceDocument  = null;
                PdfCopy         pdfCopyProvider = null;
                PdfImportedPage importedPage;
                string          outputPdfPath = Path.Combine(directoryPath, "Presupuesto.pdf");
                sourceDocument = new Document();
                FileStream fs = new FileStream(outputPdfPath, FileMode.OpenOrCreate);
                pdfCopyProvider = new PdfCopy(sourceDocument, fs);

                //Open the output file
                sourceDocument.Open();

                foreach (var item in lstFiles)
                {
                    document.LoadFromFile(item);
                    int pages = document.Pages.Count;

                    reader = new PdfReader(item);
                    FileInfo info     = new FileInfo(item);
                    var      fileName = info.Name.Split(".")[0];
                    fileName = fileName.Substring(0, 6); // me quedo solo con la palabra "mobile";

                    if (fileName.Equals("mobile"))
                    {
                        importedPage = pdfCopyProvider.GetImportedPage(reader, 1);
                        pdfCopyProvider.AddPage(importedPage);
                    }
                    else
                    {
                        //Add pages of current file
                        for (int i = 1; i <= pages; i++)
                        {
                            importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                            pdfCopyProvider.AddPage(importedPage);
                        }
                    }

                    reader.Close();
                }

                sourceDocument.Close();
                pdfCopyProvider.Close();
                document.Dispose();
                fs.Close();
                string pdfFilePath = outputPdfPath;
                byte[] bytes       = File.ReadAllBytes(pdfFilePath);

                //elimino el directorio temporal
                DeleteDirectory(directoryPath);

                return(bytes);
            }

            catch (Exception ex)
            {
                DeleteDirectory(directoryPath);
                throw ex;
            }
        }
Exemple #20
0
        private void BatchPrint(object sender, DoWorkEventArgs e)
        {
            int    tick      = 0;
            int    total     = _items.Count;
            string signature = "";
            string purpose   = "";
            double fee       = 0d;

            App.Current.Dispatcher.Invoke((Action) delegate            // <--- HERE
            {
                QueueCounter.Content      = tick + "/" + total;
                QueuePBar.IsIndeterminate = true;

                signature = Signatory.Text;
                purpose   = Purpose.Text;
                fee       = Convert.ToDouble(PrintingFee.Value);
            });

            for (int i = 0; i < _items.Count; i++)
            {
                App.Current.Dispatcher.Invoke((Action) delegate                // <--- HERE
                {
                    QueueCounter.Content = tick + "/" + total;
                });
                RecordEntryMatrimonial recordx = (RecordEntryMatrimonial)_items[i];

                string[] bspl  = DateTime.Parse(recordx.MarriageDate + "," + recordx.MarriageYear).ToString("MM/dd/yyyy").Split('/');
                string   bsuff = GetDaySuffix(int.Parse(bspl[1]));
                string   bmon  = PrepMonth(int.Parse(bspl[0]));

                Document doc = new Document();
                doc.LoadFromFile("Data\\temp_marriage.docx");
                doc.Replace("name", recordx.FullName1, true, true);
                doc.Replace("name2", recordx.FullName2, true, true);
                doc.Replace("age", recordx.Age1.ToString(), true, true);
                doc.Replace("age2", recordx.Age2.ToString(), true, true);
                doc.Replace("nationality", "Filipino", true, true);
                doc.Replace("nationality2", "Filipino", true, true);
                doc.Replace("residence", recordx.Residence1, true, true);
                doc.Replace("residence2", recordx.Residence2, true, true);
                doc.Replace("civil", recordx.Status1, true, true);
                doc.Replace("civil2", recordx.Status2, true, true);
                doc.Replace("father", recordx.Parent1, true, true);
                doc.Replace("father2", recordx.Parent3, true, true);
                doc.Replace("mother", recordx.Parent2, true, true);
                doc.Replace("mother2", recordx.Parent4, true, true);
                doc.Replace("witness", recordx.Witness1, true, true);
                doc.Replace("witness2", recordx.Witness2, true, true);
                doc.Replace("place", "St. Raphael Parish", true, true);
                doc.Replace("date", bmon + " " + bspl[1] + bsuff + ", " + bspl[2], true, true);
                doc.Replace("priest", recordx.Minister, true, true);
                doc.Replace("sign", signature, true, true);
                doc.Replace("page", GetPNum(recordx.RecordID).ToString(), true, true);
                doc.Replace("no", GetBNum(recordx.RecordID).ToString(), true, true);
                string[] date = DateTime.Now.ToStrin­g("MMMM,d,yyyy").Spl­it(',');
                doc.Replace("month", date[0], true, true);
                date[1] = date[1] + GetDaySuffix(int.Parse(date[1]));
                doc.Replace("days", date[1], true, true);
                doc.Replace("YY", date[2].Remove(0, 2), true, true);
                doc.SaveToFile("Data\\print-" + i + ".docx", FileFormat.Docx);

                //Load Document
                Document document = new Document();
                document.LoadFromFile(@"Data\\print-" + i + ".docx");

                //Convert Word to PDF
                document.SaveToFile("Output\\print_file-" + i + ".pdf", FileFormat.PDF);

                App.Current.Dispatcher.Invoke((Action) delegate                // <--- HERE
                {
                    if (SkipPreview.IsChecked == true)
                    {
                        Spire.Pdf.PdfDocument docx = new Spire.Pdf.PdfDocument();
                        docx.LoadFromFile(@"Output\\print_file-" + i + ".pdf");
                        docx.PrintDocument.Print();
                    }
                    else
                    {
                        System.Diagnostics.Process.Start("Output\\print_file-" + i + ".pdf");
                    }


                    //Reference
                    string tmp = pmsutil.LogRecord(recordx.RecordID, "LOGC-03");
                });
                pmsutil.InsertTransaction("Matrimonial Cert.", "Paying", recordx.RecordID, Convert.ToDouble(pmsutil.GetPrintFee("Matrimonial")));
                tick++;
            }
        }
Exemple #21
0
        private void BatchPrint(object sender, DoWorkEventArgs e)
        {
            int    tick      = 0;
            int    total     = _items.Count;
            string signature = "";
            string purpose   = "";
            double fee       = 0d;

            App.Current.Dispatcher.Invoke((Action) delegate            // <--- HERE
            {
                QueueCounter.Content      = tick + "/" + total;
                QueuePBar.IsIndeterminate = true;

                signature = Signatory.Text;
                purpose   = Purpose.Text;
                fee       = Convert.ToDouble(PrintingFee.Value);
            });

            for (int i = 0; i < _items.Count; i++)
            {
                App.Current.Dispatcher.Invoke((Action) delegate                // <--- HERE
                {
                    QueueCounter.Content = tick + "/" + total;
                });
                RecordEntryConfirmation recordx = (RecordEntryConfirmation)_items[i];

                string x1;

                string[] spl  = DateTime.Parse(recordx.ConfirmationDate + "," + recordx.ConfirmationYear).ToString("MM/dd/yyyy").Split('/');
                string   suff = GetDaySuffix(int.Parse(spl[1]));
                string   mon  = PrepMonth(int.Parse(spl[0]));
                if (int.Parse(spl[2]) > 1999)
                {
                    x1     = "";
                    spl[2] = spl[2].Remove(0, 2);
                }
                else
                {
                    x1 = "X";
                }

                Document doc = new Document();
                doc.LoadFromFile("Data\\temp_confirmation.docx");
                doc.Replace("name", recordx.FullName, true, true);
                doc.Replace("day", int.Parse(spl[1]) + suff, true, true);
                doc.Replace("month", mon, true, true);
                doc.Replace("X", x1, true, true);
                doc.Replace("year", spl[2], true, true);
                doc.Replace("by", recordx.Minister, true, true);
                doc.Replace("no", recordx.EntryNumber.ToString(), true, true);
                doc.Replace("book", GetBNum(recordx.RecordID).ToString(), true, true);
                doc.Replace("page", GetPNum(recordx.RecordID).ToString(), true, true);
                doc.Replace("no", recordx.EntryNumber.ToString(), true, true);
                doc.Replace("priest", recordx.Minister, true, true);
                doc.Replace("purpose", purpose, true, true);
                doc.Replace("date", DateTime.Now.ToString("MMMM d, yyyy"), true, true);
                doc.SaveToFile("Data\\print-" + i + ".docx", FileFormat.Docx);

                //Load Document
                Document document = new Document();
                document.LoadFromFile(@"Data\\print-" + i + ".docx");

                //Convert Word to PDF
                document.SaveToFile("Output\\print_file-" + i + ".pdf", FileFormat.PDF);

                App.Current.Dispatcher.Invoke((Action) delegate                // <--- HERE
                {
                    if (SkipPreview.IsChecked == true)
                    {
                        Spire.Pdf.PdfDocument docx = new Spire.Pdf.PdfDocument();
                        docx.LoadFromFile(@"Output\\print_file-" + i + ".pdf");
                        docx.PrintDocument.Print();
                    }
                    else
                    {
                        System.Diagnostics.Process.Start("Output\\print_file-" + i + ".pdf");
                    }


                    if (Purpose.SelectedIndex == 0)
                    {
                        //Reference
                        string tmp = pmsutil.LogRecord(recordx.RecordID, "LOGC-03");
                    }
                    else
                    {
                        //Marriage
                        string tmp = pmsutil.LogRecord(recordx.RecordID, "LOGC-04");
                    }
                });
                pmsutil.InsertTransaction("Confirmation Cert.", "Paying", recordx.RecordID, Convert.ToDouble(pmsutil.GetPrintFee("Confirmation")));
                tick++;
            }
        }