Ejemplo n.º 1
0
 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);
     }
 }
Ejemplo n.º 2
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);
            }
        }
Ejemplo n.º 3
0
        public Image FirstPage(byte[] source)
        {
            var doc = new Spire.Pdf.PdfDocument();

            doc.LoadFromBytes(source);
            return(doc.SaveAsImage(0));
        }
Ejemplo n.º 4
0
        public ActionResult GetDocumentThumbnail(int id)
        {
            string doctype   = "image/jpg";
            var    imageData = DMLObj.GetDocDataById(id, out doctype);

            if (doctype.ToLower() == "application/pdf")
            {
                Spire.Pdf.PdfDocument document = new Spire.Pdf.PdfDocument();
                document.LoadFromStream(new MemoryStream(imageData));
                Image ImgDoc = document.SaveAsImage(0, Spire.Pdf.Graphics.PdfImageType.Bitmap, 120, 120);
                return(File(imageToByteArray(ImgDoc.ScaleImage(150, 150)), "image/jpeg"));
            }

            //if (doctype.ToLower() == "application/msword")
            //{
            //    Spire.Doc.Document document = new Spire.Doc.Document();
            //    document.LoadFromStream(new MemoryStream(imageData),Spire.Doc.FileFormat.Doc);
            //    Image ImgDoc = document.SaveToImages(0, Spire.Doc.Documents.ImageType.Metafile);
            //    return File(imageToByteArray(ImgDoc.ScaleImage(150, 150)), "image/jpeg");
            //}

            //if (doctype.ToLower() == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
            //{
            //    Spire.Doc.Document document = new Spire.Doc.Document();
            //    document.LoadFromStream(new MemoryStream(imageData), Spire.Doc.FileFormat.Docx2010);
            //    Image ImgDoc = document.SaveToImages(0, Spire.Doc.Documents.ImageType.Metafile);
            //    return File(imageToByteArray(ImgDoc.ScaleImage(150, 150)), "image/jpeg");
            //}
            return(File(imageData, doctype));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Convert pdf to html with picture files
        /// </summary>
        /// <param name="inputFileName">Absolute name of input file</param>
        /// <param name="outputFolder">Folder for saving results</param>
        /// <param name="newFileName">Relative filename of new html</param>
        public static void ConvertToHtml(string inputFileName, string outputFolder, string newFileName, Dictionary <string, string> parameters)
        {
            if (!Directory.Exists(outputFolder))
            {
                Directory.CreateDirectory(outputFolder);
            }
            Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument(inputFileName);
            using (var stream = new MemoryStream())
            {
                pdf.SaveToStream(stream, Spire.Pdf.FileFormat.HTML);
                string result = System.Text.Encoding.UTF8.GetString(stream.ToArray());
                if (result.IndexOf(replaceValuePdf) >= 0)
                {
                    result = result.Replace(replaceValuePdf, "");
                }
                else if (result.IndexOf(replaceValueWithoutTag) >= 0)
                {
                    result = result.Replace(replaceValueWithoutTag, "");
                }
                else if (result.IndexOf(replaceValue) >= 0)
                {
                    result = result.Replace(replaceValue, "");
                }
                result = ExtractImages(outputFolder, result);

                File.WriteAllText(outputFolder + "/" + newFileName, result, Encoding.UTF8);
                result = null;
            }
            pdf.Dispose();
        }
        /// <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);
        }
Ejemplo n.º 7
0
        private void ConvertPdfToPng(byte[] pdfImage)
        {
            var ms = new MemoryStream();

            new MemoryStream(pdfImage).CopyTo(ms);
            Spire.Pdf.PdfDocument d = new Spire.Pdf.PdfDocument(ms);
            pngImage = d.SaveAsImage(0, 300, 300);
            d.Close();
        }
Ejemplo n.º 8
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);
 }
Ejemplo n.º 9
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));
     //}
 }
Ejemplo n.º 10
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);
                }
            }
        }
Ejemplo n.º 11
0
        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;
        }
Ejemplo n.º 12
0
 private static void PrintPdf(string path)
 {
     try
     {
         var doc = new PdfDocument();
         doc.LoadFromFile(path);
         doc.PrintDocument.Print();
     }
     finally
     {
         File.Delete(path);
     }
 }
Ejemplo n.º 13
0
        public List <Image> SingleFile(byte[] source)
        {
            var result = new List <Image>();
            var doc    = new Spire.Pdf.PdfDocument();

            doc.LoadFromBytes(source);
            for (int it = 0; it < doc.Pages.Count; it++)
            {
                result.Add(doc.SaveAsImage(it));
            }

            return(result);
        }
Ejemplo n.º 14
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);
            }
        }
Ejemplo n.º 15
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;
        }
Ejemplo n.º 16
0
        //public static void ToTIFF(List<string> imagesPath,string folderName)
        //{
        //    System.Drawing.Imaging.Encoder enc = System.Drawing.Imaging.Encoder.SaveFlag;
        //    EncoderParameters ep = new EncoderParameters(1);
        //    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);



        //    Bitmap pages = null;

        //    File.MemoryStream ms = new MemoryStream(File.ReadAllBytes());
        //    pages = (Bitmap)Image.FromStream(ms);

        //    int frame = 0;

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

        //        MemoryStream mss = new MemoryStream(File.ReadAllBytes(item));
        //        Bitmap bm = (Bitmap)Image.FromStream(mss);
        //        int frameCount = bm.GetFrameCount(FrameDimension.Page);
        //        for (int i = 0; i < frameCount; i++)
        //        {
        //            bm.SelectActiveFrame(FrameDimension.Page, i);
        //            pages.SaveAdd(bm, ep);
        //        }
        //    }

        //    pages.Save(@"C:\1\TiffFile.tif");



        //}

        //public static class TiffHelper
        //{
        //    /// <summary>
        //    /// Merges multiple TIFF files (including multipage TIFFs) into a single multipage TIFF file.
        //    /// </summary>
        //    public static byte[] MergeTiff(params byte[][] tiffFiles)
        //    {
        //        byte[] tiffMerge = null;
        //        using (var msMerge = new MemoryStream())
        //        {
        //            //get the codec for tiff files
        //            ImageCodecInfo ici = null;
        //            foreach (ImageCodecInfo i in ImageCodecInfo.GetImageEncoders())
        //                if (i.MimeType == "image/tiff")
        //                    ici = i;

        //            System.Drawing.Imaging.Encoder enc = System.Drawing.Imaging.Encoder.SaveFlag;
        //            EncoderParameters ep = new EncoderParameters(1);

        //            Bitmap pages = null;
        //            int frame = 0;

        //            foreach (var tiffFile in tiffFiles)
        //            {
        //                using (var imageStream = new MemoryStream(tiffFile))
        //                {
        //                    using (Image tiffImage = Image.FromStream(imageStream))
        //                    {
        //                        foreach (Guid guid in tiffImage.FrameDimensionsList)
        //                        {
        //                            //create the frame dimension
        //                            FrameDimension dimension = new FrameDimension(guid);
        //                            //Gets the total number of frames in the .tiff file
        //                            int noOfPages = tiffImage.GetFrameCount(dimension);

        //                            for (int index = 0; index < noOfPages; index++)
        //                            {
        //                                FrameDimension currentFrame = new FrameDimension(guid);
        //                                tiffImage.SelectActiveFrame(currentFrame, index);
        //                                using (MemoryStream tempImg = new MemoryStream())
        //                                {
        //                                    tiffImage.Save(tempImg, ImageFormat.Tiff);
        //                                    {
        //                                        if (frame == 0)
        //                                        {
        //                                            //save the first frame
        //                                            pages = (Bitmap)Image.FromStream(tempImg);
        //                                            ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
        //                                            pages.Save(msMerge, ici, ep);
        //                                        }
        //                                        else
        //                                        {
        //                                            //save the intermediate frames
        //                                            ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);
        //                                            pages.SaveAdd((Bitmap)Image.FromStream(tempImg), ep);
        //                                        }
        //                                    }
        //                                    frame++;
        //                                }
        //                            }
        //                        }
        //                    }
        //                }
        //            }
        //            if (frame > 0)
        //            {
        //                //flush and close.
        //                ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
        //                pages.SaveAdd(ep);
        //            }

        //            msMerge.Position = 0;
        //            tiffMerge = msMerge.ToArray();
        //        }
        //        return tiffMerge;
        //    }
        //}

        public static MemoryStream ToPDF(List <byte[]> input)
        {
            try
            {
                MemoryStream memoryStream = new MemoryStream();

                using (Spire.Pdf.PdfDocument document = new Spire.Pdf.PdfDocument())
                {
                    foreach (byte[] element in input)
                    {
                        MemoryStream imageMemoryStream = new MemoryStream(element);

                        Spire.Pdf.PdfPageBase page = document.Pages.Add();

                        Spire.Pdf.Graphics.PdfImage image = Spire.Pdf.Graphics.PdfImage.FromStream(imageMemoryStream);
                        //page.PageInfo.Margin.Bottom = 0;
                        //page.PageInfo.Margin.Top = 0;
                        //page.PageInfo.Margin.Left = 0;
                        //page.PageInfo.Margin.Right = 0;
                        //page.PageInfo.IsLandscape = false;

                        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, 0, 0, fitWidth, fitHeight);
                    }

                    //document.PDFStandard.CompressionLevel(new Document.ConvertOptions()
                    //{
                    //    LinkDuplcateStreams = true,
                    //    RemoveUnusedObjects = true,
                    //    RemoveUnusedStreams = true,
                    //    CompressImages = true //IMP
                    //});

                    document.SaveToStream(memoryStream);
                }

                return(memoryStream);
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 17
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();
        }
Ejemplo n.º 18
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();
        }
Ejemplo n.º 19
0
        public static string MergePDFFiles(List <string> filesPaths)
        {
            Spire.Pdf.PdfDocument[] tickets = new Spire.Pdf.PdfDocument[filesPaths.Count()];
            for (int i = 0; i < tickets.Length; i++)
            {
                tickets[i] = new Spire.Pdf.PdfDocument(filesPaths[i]);
            }

            Spire.Pdf.PdfDocument document = new Spire.Pdf.PdfDocument();
            for (int i = 0; i < tickets.Length; i++)
            {
                document.InsertPage(tickets[i], 0);
            }
            string now = DateTime.Now.ToString("yyyy/MM/dd_HH.mm.ss.fff");

            document.SaveToFile(@"D:\Virtuace\HW6\Booking\Booking\Tickets\" + now + ".pdf");

            return(@"D:\Virtuace\HW6\Booking\Booking\Tickets\" + now + ".pdf");
        }
        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();
            }
        }
Ejemplo n.º 21
0
        protected void searchFortext(string path, string text)
        {
            using (Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument((path)))
            {
                for (int i = 0; i < pdf.Pages.Count; i++)
                {
                    string pageText = pdf.Pages[i].ExtractText().Trim();
                    string varfried = "TATER";
                    if (pageText.Contains(text))
                    {
                        string flsg = "Y";
                    }

                    int index = pageText.IndexOf(text, 0, StringComparison.CurrentCultureIgnoreCase);
                    if (index != -1)
                    {
                        Response.Redirect("RegularMenu.aspx", false);
                    }
                }
            }
        }
Ejemplo n.º 22
0
        public async Task GeneratePdf(string html, string filePath)
        {
            await Task.Run(() =>
            {
                using (FileStream ms = new FileStream(filePath, FileMode.Create))
                {
                    PdfSharp.Pdf.PdfDocument pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4);
                    pdf.Save(ms);
                    ms.Close();
                }
                Spire.Pdf.PdfDocument abc         = new Spire.Pdf.PdfDocument(filePath);
                Spire.Pdf.Graphics.PdfImage image = Spire.Pdf.Graphics.PdfImage.FromFile(@"D:\Logo.png");
                float width  = image.Width * 0.75f;
                float height = image.Height * 0.75f;

                Spire.Pdf.PdfPageBase page0 = abc.Pages[0];
                float x = (page0.Canvas.ClientSize.Width - width) / 2;
                page0.Canvas.DrawImage(image, x, 60, width, height);
                abc.SaveToFile(filePath);
            });
        }
Ejemplo n.º 23
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);
            }
        }
Ejemplo n.º 24
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);
                }
            }
        }
Ejemplo n.º 25
0
        public ActionResult GetDocument(string DocId, string PageNumber)
        {
            int AmDocId = 0;
            int AmPn    = 0;

            Int32.TryParse(DocId, out AmDocId);
            Int32.TryParse(PageNumber, out AmPn);
            string doctype   = "image/jpg";
            var    imageData = DMLObj.GetDocDataById(AmDocId, out doctype);

            if (imageData == null)
            {
                return(null);
            }
            if (doctype.ToLower() == "application/pdf")
            {
                Spire.Pdf.PdfDocument document = new Spire.Pdf.PdfDocument();
                document.LoadFromStream(new MemoryStream(imageData));
                Image ImgDoc = document.SaveAsImage(AmPn, Spire.Pdf.Graphics.PdfImageType.Bitmap, 400, 400);
                ImgDoc = ImgDoc.cropImage(new Rectangle(0, 57, ImgDoc.Width, ImgDoc.Height - 57));
                return(File(imageToByteArray(ImgDoc), "image/jpeg"));
            }
            return(File(imageData, doctype));
        }
Ejemplo n.º 26
0
        /// <summary>
        /// 文件上传
        /// </summary>
        public void UploadFiles()
        {
            bool result = false;

            if (Request.Form["option"].ToString() == "update")
            {
                string fn      = Request.Form["filename"].ToString();
                string keyword = Request.Form["keyword"].ToString();
                string status  = Request.Form["ispublic"].ToString() == "checked" ? "1" : "0";
                string id      = Request.Form["id"].ToString();
                string sql     = string.Format("update fileinfo set filename='{0}',keyword='{1}',status='{2}' where keyid={3}", fn, keyword, status, id);
                int    i       = DAL.Commons.Instance.chooseFactory("sql").ExecuteNonQuery(sql);
                result = i > 0 ? true : false;
            }
            else
            {
                if (Request.Files.Count > 0)
                {
                    loginUser lu  = Session["user"] as loginUser;
                    string    dir = string.Format("{0}//{1}//{2}", "upload", DateTime.Now.ToString("yyyy-MM-dd"), lu.LoginName);

                    string extName = Path.GetExtension(Request.Files[0].FileName);//.Split('.')[1].ToLower();
                    extName = extName.Substring(1);
                    string filename = DAL.Commons.Instance.GetUploadFileName(dir, extName);
                    Request.Files[0].SaveAs(AppDomain.CurrentDomain.BaseDirectory + filename);
                    string fn       = Request.Form["filename"].ToString();
                    string keyword  = Request.Form["keyword"].ToString();
                    string dirid    = Request.Form["dirid"].ToString();
                    string userid   = lu.ID;
                    string status   = Request.Form["ispublic"].ToString() == "checked" ? "1" : "0";
                    string f1       = "doc,docx";
                    string f2       = "xls,xlsx";
                    string f3       = "txt,jpeg,png";
                    string f4       = "pdf";
                    int    viewmode = 3;
                    string viewdir  = "";
                    if (f1.IndexOf(extName) >= 0)
                    {
                        viewmode = 1;
                        Spire.Doc.Document doc = new Spire.Doc.Document();
                        doc.LoadFromFile(AppDomain.CurrentDomain.BaseDirectory + filename);
                        string newname = DAL.Commons.Instance.GetUploadFileName(dir, "pdf");
                        doc.SaveToFile(AppDomain.CurrentDomain.BaseDirectory + newname, Spire.Doc.FileFormat.PDF);
                        viewdir = newname;
                        doc.Close();
                    }
                    else if (f2.IndexOf(extName) >= 0)
                    {
                        viewmode = 1;
                        Spire.Xls.Workbook book = new Spire.Xls.Workbook();
                        book.LoadFromFile(AppDomain.CurrentDomain.BaseDirectory + filename);
                        string newname = DAL.Commons.Instance.GetUploadFileName(dir, "pdf");
                        book.ConverterSetting.SheetFitToPage = true;
                        book.SaveToFile(AppDomain.CurrentDomain.BaseDirectory + newname, Spire.Xls.FileFormat.PDF);
                        viewdir = newname;
                    }
                    else if (f3.IndexOf(extName) >= 0)
                    {
                        viewmode = 2;
                        viewdir  = filename;
                    }
                    else if (f4.IndexOf(extName) >= 0)
                    {
                        viewmode = 1;
                        viewdir  = filename;
                    }
                    Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument();


                    string sql = string.Format("insert into fileinfo (filename,keyword,dirid,userid,status,localdir,viewdir,viewmode,extname) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')", fn, keyword, dirid, userid, status, filename, viewdir, viewmode, extName);
                    int    i   = DAL.Commons.Instance.chooseFactory("sql").ExecuteNonQuery(sql);
                    result = i > 0 ? true : false;
                }
            }
            var par = new { sucess = result };

            Response.Write(DAL.Commons.Instance.ToJson(par));
        }
        public ActionResult viewPRExcel(Int16 fiscalYear, Int16? coeID)
        {
            ModelState.Clear();
            var viewModel = new PRViewModel
            {
                //allCoEs = db.CoEs.ToList(),
                allCoEs = db.CoEs.ToList(),
                allMaps = db.Indicator_CoE_Maps.ToList(),
                allFootnoteMaps = db.Indicator_Footnote_Maps.ToList()
            };

            // Create the workbook
            SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
            var ef = new ExcelPackage();
            var wb = ef.Workbook;

            var prBlue = ExcelColor.FromArgb(0, 51, 102);
            var prGreen = ExcelColor.FromArgb(0, 118, 53);
            var prYellow = ExcelColor.FromArgb(255, 192, 0);
            var prRed = ExcelColor.FromArgb(255, 0, 0);
            var prHeader1Fill = prBlue;
            var prHeader1Font = ExcelColor.White;
            var prHeader2Fill = ExcelColor.White;
            var prHeader2Font = ExcelColor.Black;
            var prBorder = ExcelColor.FromArgb(0, 0, 0);
            var prAreaFill = ExcelColor.FromArgb(192, 192, 192);
            var prAreaFont = ExcelColor.Black;
            var prBorderWidth = XLBorderStyleValues.Thin;
            var prFontSize = 10;
            var prTitleFont = 20;
            var prFootnoteSize = 8;
            var prHeightSeperator = 7.5;

            var prAreaObjectiveFontsize = 8;
            var indentLength = 24;
            var firstIndentLength = 20;
            var innerIndentLength = 5;
            var newLineHeight = 12.6;

            var defNote = "Portal data from the Canadian Institute for Health Information (CIHI) has been used to generate data within this report with acknowledgement to CIHI, the Ministry of Health and Long-Term Care (MOHLTC) and Stats Canada (as applicable). Views are not those of the acknowledged sources. Facility identifiable data other than Mount Sinai Hospital (MSH) is not to be published without the consent of that organization (except where reported at an aggregate level). As this is not a database supported by MSH, please demonstrate caution with use and interpretation of the information. MSH is not responsible for any changes derived from the source data/canned reports. Data may be subject to change.";

            var prNumberWidth = 4;
            var prIndicatorWidth = 55;
            var prValueWidth = 11;
            var prDefWidth = 100;
            var prRatiWidth = 50;
            var prCompWidth = 50;

            //var fitRatio = 3.77;
            var fitRatio = 1.7;
            List<int> fitAdjustableRows = new List<int>();

            var prFootnoteCharsNewLine = 125;
            var prObjectivesCharsNewLine = 226;

            //DELETE THIS
            //coeID = null;

            var allCoes = new List<CoEs>();
            if (coeID != 0 && coeID != null)
            {
                allCoes = viewModel.allCoEs.Where(x => x.CoE_ID == coeID).ToList();
            }
            else
            {
                allCoes = viewModel.allCoEs.ToList();
            }

            foreach (var coe in allCoes)
            {
                var wsPRName = coe.CoE_Abbr;
                var wsDefName = "Def_" + coe.CoE_Abbr;
                var wsPR = wb.Worksheets.Add(wsPRName);
                var wsDef = wb.Worksheets.Add(wsDefName);
                List<OfficeOpenXml.ExcelWorksheet> wsList = new List<OfficeOpenXml.ExcelWorksheet>();
                wsList.Add(wsPR);
                wsList.Add(wsDef);

                foreach (var ws in wsList)
                {
                    var currentRow = 4;
                    ws.Row(2).Height = 21;
                    int startRow;
                    int indicatorNumber = 1;

                    ws.PrinterSettings.TopMargin = 0;
                    ws.PrinterSettings.HeaderMargin = 0;
                    ws.PrinterSettings.BottomMargin = 0.5M;
                    ws.PrinterSettings.LeftMargin = 0;
                    ws.PrinterSettings.RightMargin = 0;
                    ws.PrinterSettings.Orientation = eOrientation.Landscape;
                    ws.PrinterSettings.PaperSize = ePaperSize.Legal;
                    ws.PrinterSettings.FitToHeight = 1;
                    ws.PrinterSettings.FitToWidth = 1;
                    //ws.PageSetup.Margins.Top = 0;
                    //ws.PageSetup.Margins.Header = 0;
                    //ws.PageSetup.Margins.Left = 0.5;
                    //ws.PageSetup.Margins.Right = 0.5;
                    //ws.PageSetup.Margins.Bottom = 0.5;
                    //ws.PageSetup.PageOrientation = XLPageOrientation.Landscape;
                    //ws.PageSetup.PaperSize = XLPaperSize.LegalPaper;
                    //ws.PageSetup.FitToPages(1, 1);

                    string[,] columnHeaders = new string[0, 0];
                    if (ws.Name == wsPRName)
                    {
                        var prHeadder2Title = FiscalYear.FYStrFull("FY_", fiscalYear) + "Performance";
                        prHeadder2Title = prHeadder2Title.Replace("_", " ");
                        columnHeaders = new string[,]{
                            {"Number",""},
                            {"Indicator",""},
                            {FiscalYear.FYStrFull("FY_3", fiscalYear), ""},
                            {FiscalYear.FYStrFull("FY_2", fiscalYear),""},
                            {FiscalYear.FYStrFull("FY_1", fiscalYear),""},
                            {prHeadder2Title,"Q1"},
                            {prHeadder2Title,"Q2"},
                            {prHeadder2Title,"Q3"},
                            {prHeadder2Title,"Q4"},
                            {prHeadder2Title,"YTD"},
                            {FiscalYear.FYStrFull("FY_", fiscalYear) + "Target",""},
                            {FiscalYear.FYStrFull("FY_", fiscalYear) + "Performance_Threshold",""},
                            {FiscalYear.FYStrFull("FY_", fiscalYear) + "Comparator",""}
                        };
                    }
                    else if (ws.Name == wsDefName)
                    {
                        columnHeaders = new string[,]{
                            {"Number",""},
                            {"Indicator",""},
                            {FiscalYear.FYStrFull("FY_", fiscalYear) + "Definition_Calculation",""},
                            {FiscalYear.FYStrFull("FY_", fiscalYear) + "Target_Rationale",""},
                            {FiscalYear.FYStrFull("FY_", fiscalYear) + "Comparator_Source",""}
                        };
                    }

                    var currentCol = 1;
                    var prHeader2ColStart = 99;
                    var prHeader2ColEnd = 1;
                    int maxCol = columnHeaders.GetUpperBound(0) + 1;

                    var prTitle = ws.Cells[currentRow, 1];
                    prTitle.Value = coe.CoE;
                    prTitle.Style.Font.Size = prTitleFont;
                    prTitle.Style.Font.Bold = true;
                    prTitle.Style.Font.Color.SetColor(prHeader1Font);
                    prTitle.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    prTitle.Style.Fill.BackgroundColor.SetColor(prHeader1Fill);
                    ws.Cells[currentRow, 1, currentRow, maxCol].Merge = true;
                    ws.Cells[currentRow + 1, 1, currentRow + 1, maxCol].Merge = true;
                    ws.Row(currentRow + 1).Height = prHeightSeperator;
                    currentRow += 2;
                    startRow = currentRow;

                    for (int i = 0; i <= columnHeaders.GetUpperBound(0); i++)
                    {
                        if (columnHeaders[i, 1] == "")
                        {
                            var columnField = columnHeaders[i, 0];
                            string cellValue;
                            Type t = typeof(Indicators);
                            cellValue = t.GetProperty(columnField) != null ?
                                ModelMetadataProviders.Current.GetMetadataForProperty(null, typeof(Indicators), columnField).DisplayName :
                                ModelMetadataProviders.Current.GetMetadataForProperty(null, typeof(Indicator_CoE_Maps), columnField).DisplayName;
                            ws.Cells[currentRow, currentCol].Value = cellValue;
                            ws.Cells[currentRow, currentCol, currentRow + 1, currentCol].Merge = true;
                            currentCol++;
                        }
                        else
                        {
                            var columnField = columnHeaders[i, 1];
                            var columnFieldTop = columnHeaders[i, 0];
                            ws.Cells[currentRow + 1, currentCol].Value = columnField;
                            ws.Cells[currentRow, currentCol].Value = columnFieldTop;
                            if (currentCol < prHeader2ColStart) { prHeader2ColStart = currentCol; }
                            if (currentCol > prHeader2ColEnd) { prHeader2ColEnd = currentCol; }
                            currentCol++;
                        }
                    }
                    currentCol--;
                    var prHeader1 = ws.Cells[currentRow, 1, currentRow + 1, currentCol];
                    if (prHeader2ColStart != 99)
                    {
                        ws.Cells[currentRow, prHeader2ColStart, currentRow, prHeader2ColEnd].Merge = true;
                        var prHeader2 = ws.Cells[currentRow + 1, prHeader2ColStart, currentRow + 1, prHeader2ColEnd];
                        prHeader2.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                        prHeader2.Style.Fill.BackgroundColor.SetColor(prHeader2Fill);
                        prHeader2.Style.Font.Color.SetColor(prHeader2Font);
                    }

                    prHeader1.Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                    prHeader1.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;

                    prHeader1.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    prHeader1.Style.Fill.BackgroundColor.SetColor(prHeader1Fill);
                    prHeader1.Style.Font.Color.SetColor(prHeader1Font);

                    currentRow += 2;

                    List<Footnotes> footnotes = new List<Footnotes>();
                    foreach (var areaMap in coe.Area_CoE_Map.Where(x=>x.Fiscal_Year == fiscalYear).OrderBy(x => x.Area.Sort))
                    {
                        var cellLengthObjective = 0;
                        var prArea = ws.Cells[currentRow, 1, currentRow, maxCol];
                        //fitAdjustableRows.Add(currentRow);
                        prArea.Merge = true;
                        prArea.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                        prArea.Style.Fill.BackgroundColor.SetColor(prAreaFill);
                        prArea.Style.Font.Color.SetColor(prAreaFont);
                        prArea.FirstOrDefault().RichText.Add(areaMap.Area.Area).Bold = true;
                        cellLengthObjective += areaMap.Area.Area.Length;

                        if (ws == wsPR)
                        {
                            var indent = new string('_', indentLength);
                            var innerIndent = new string('_', innerIndentLength);
                            var firstIndent = indent.Substring(0, firstIndentLength - areaMap.Area.Area.Length);

                            var stringSeperators = new string[] { "•" };
                            /*
                            if (areaMap.Objective != null)
                            {
                                var objectives = areaMap.Objective.Split(stringSeperators, StringSplitOptions.None);
                                for (var i = 1; i < objectives.Length; i++)
                                {
                                    if (i == 1)
                                    {
                                        prArea.FirstOrDefault().RichText.Add(firstIndent).Size = prAreaObjectiveFontsize;
                                        cellLengthObjective += firstIndent.Length;
                                    }
                                    //var innerIndentAdj = new string('_', maxObjectiveLength < objectives[i].Length ? 0 : maxObjectiveLength - objectives[i].Length);
                                    var innerIndentAdj = "";

                                    cellLengthObjective += objectives[i].Length + innerIndent.Length + innerIndentAdj.Length;
                                    if (cellLengthObjective > prObjectivesCharsNewLine)
                                    {
                                        prArea.FirstOrDefault().RichText.Add("\r\n");
                                        ws.Row(currentRow).Height += (int)newLineHeight;
                                        prArea.FirstOrDefault().RichText.Add(indent).Color = ClosedXML.Excel.XLColor.FromColor(prAreaFill);
                                        prArea.FirstOrDefault().RichText.Add(indent).SetFontColor( ClosedXML.Excel.XLColor.FromColor(prAreaFont)).SetFontSize(prAreaObjectiveFontsize);
                                        cellLengthObjective = indent.Length;
                                    }
                                    prArea.FirstCell().RichText.AddText(innerIndent + innerIndentAdj).FontColor =  ClosedXML.Excel.XLColor.FromColor(prAreaFill);
                                    prArea.FirstCell().RichText.AddText(" •" + objectives[i]).FontSize = prAreaObjectiveFontsize;
                                    cellLengthObjective += objectives[i].Length;
                                }
                            }*/
                        }
                        currentRow++;

                        foreach (var map in viewModel.allMaps.Where(x => x.Fiscal_Year == fiscalYear).Where(e => e.Indicator.Area.Equals(areaMap.Area)).Where(d => d.CoE.CoE.Contains(coe.CoE)).OrderBy(f => f.Number))
                        {
                            fitAdjustableRows.Add(currentRow);
                            currentCol = 1;

                            ws.Cells[currentRow, currentCol].Value = indicatorNumber;
                            indicatorNumber++;
                            ws.Cells[currentRow, currentCol].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                            currentCol++;

                            int j = 0;
                            ws.Cells[currentRow, currentCol].Value = map.Indicator.Indicator;
                            foreach (var footnote in map.Indicator.Indicator_Footnote_Map.Where(x => x.Fiscal_Year == fiscalYear).Where(e => e.Indicator_ID == map.Indicator_ID).OrderBy(e => e.Indicator_ID))
                            {
                                if (!footnotes.Contains(footnote.Footnote)) { footnotes.Add(footnote.Footnote); }
                                if (j != 0)
                                {
                                    ws.Cells[currentRow, currentCol].RichText.Add(",").VerticalAlign = OfficeOpenXml.Style.ExcelVerticalAlignmentFont.Superscript;
                                }
                                ws.Cells[currentRow, currentCol].RichText.Add(footnote.Footnote.Footnote_Symbol).VerticalAlign = OfficeOpenXml.Style.ExcelVerticalAlignmentFont.Superscript;
                                j++;
                            }
                            ws.Cells[currentRow, currentCol].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Left;
                            currentCol++;

                            if (ws.Name == wsPRName)
                            {
                                for (var i = 3; i <= 15; i++)
                                {
                                    ws.Column(i).Width = ws.Name == wsPRName ? prValueWidth : prDefWidth;
                                }

                                var obj = map.Indicator;
                                var type = obj.GetType();
                                string[,] columnIndicators = new string[,]{
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_3",fiscalYear)).GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_3",fiscalYear) + "_Sup").GetValue(obj,null),
                                     ""
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_2",fiscalYear)).GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_2",fiscalYear) + "_Sup").GetValue(obj,null),
                                     ""
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_1",fiscalYear)).GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_1",fiscalYear) + "_Sup").GetValue(obj,null),
                                     ""
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q1").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q1_Sup").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q1_Color").GetValue(obj,null),
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q2").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q2_Sup").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q2_Color").GetValue(obj,null),
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q3").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q3_Sup").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q3_Color").GetValue(obj,null),
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q4").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q4_Sup").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Q4_Color").GetValue(obj,null),
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "YTD").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "YTD_Sup").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "YTD_Color").GetValue(obj,null),
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Target").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Target_Sup").GetValue(obj,null),
                                     ""
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Performance_Threshold").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Performance_Threshold_Sup").GetValue(obj,null),
                                     ""
                                    },
                                    {(string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Comparator").GetValue(obj,null),
                                     (string)type.GetProperty(FiscalYear.FYStrFull("FY_",fiscalYear) + "Comparator_Sup").GetValue(obj,null),
                                     ""
                                    },
                                };
                                var startCol = currentCol;
                                int k = 1;
                                for (var i = 0; i <= columnIndicators.GetUpperBound(0); i++)
                                {
                                    for (j = 0; j <= columnIndicators.GetUpperBound(1); j++)
                                    {
                                        if (columnIndicators[i, j] != null)
                                        {
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("<b>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("</b>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("<u>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("</u>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("<i>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("</i>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("<sup>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("</sup>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("<sub>", "");
                                            columnIndicators[i, j] = columnIndicators[i, j].Replace("</sub>", "");
                                        }
                                    }
                                    if (i != columnIndicators.GetUpperBound(0) && columnIndicators[i, 0] == "=")
                                    {
                                        k = 1;
                                        while (columnIndicators[i + k, 0] == "=") { k++; }
                                        ws.Cells[currentRow, startCol + i - 1, currentRow, startCol + i + k - 1].Merge = true;
                                        i += k - 1;
                                        k = 1;
                                    }
                                    else if (columnIndicators[i, 0] != "=")
                                    {
                                        var cell = ws.Cells[currentRow, currentCol + i];
                                        string cellValue = "";

                                        if (columnIndicators[i, 0] != null)
                                        {
                                            cellValue = columnIndicators[i, 0].ToString();
                                        }

                                        if (cellValue.Contains("$"))
                                        {
                                        }

                                        cell.Value = "'" + cellValue;
                                        if (columnIndicators[i, 1] != null)
                                        {
                                            cell.RichText.Add(columnIndicators[i, 1]).VerticalAlign = OfficeOpenXml.Style.ExcelVerticalAlignmentFont.Superscript;
                                        }
                                        switch (columnIndicators[i, 2])
                                        {
                                            case "cssWhite":
                                                //cell.RichText.SetFontColor(XLColor.Black);
                                                cell.Style.Font.Color.SetColor(ExcelColor.Black);
                                                cell.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                                                cell.Style.Fill.BackgroundColor.SetColor(ExcelColor.White);
                                                break;
                                            case "cssGreen":
                                                cell.Style.Font.Color.SetColor(ExcelColor.White);
                                                cell.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                                                cell.Style.Fill.BackgroundColor.SetColor(prGreen);
                                                break;
                                            case "cssYellow":
                                                cell.Style.Font.Color.SetColor(ExcelColor.Black);
                                                cell.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                                                cell.Style.Fill.BackgroundColor.SetColor(prYellow);
                                                break;
                                            case "cssRed":
                                                cell.Style.Font.Color.SetColor(ExcelColor.White);
                                                cell.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                                                cell.Style.Fill.BackgroundColor.SetColor(prRed);
                                                break;
                                        }
                                        cell.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                                    }
                                }
                                currentRow++;
                            }
                            else if (ws.Name == wsDefName)
                            {
                                ws.Column(3).Width = prDefWidth;
                                ws.Column(4).Width = prRatiWidth;
                                ws.Column(5).Width = prCompWidth;

                                var obj = map.Indicator;
                                var type = obj.GetType();

                                string defn = (string)type.GetProperty(FiscalYear.FYStrFull("FY_", fiscalYear) + "Definition_Calculation").GetValue(obj, null);
                                string rationale = (string)type.GetProperty(FiscalYear.FYStrFull("FY_", fiscalYear) + "Target_Rationale").GetValue(obj, null);
                                string comp = (string)type.GetProperty(FiscalYear.FYStrFull("FY_", fiscalYear) + "Comparator_Source").GetValue(obj, null);

                                double maxLines = 1;
                                double lines;

                                var listColumnStrings = new List<string>();
                                listColumnStrings.Add(defn);
                                listColumnStrings.Add(rationale);
                                listColumnStrings.Add(comp);

                                foreach (var str in listColumnStrings)
                                {
                                    if (str != null)
                                    {
                                        lines = str.Length / ws.Column(currentCol).Width;
                                        maxLines = maxLines < lines ? lines : maxLines;
                                        ws.Cells[currentRow, currentCol].Value = str;
                                    }
                                    ws.Cells[currentRow, currentCol].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Left;
                                    currentCol++;
                                }
                                ws.Row(currentRow).Height = newLineHeight*Math.Ceiling(maxLines);
                                currentRow++;
                            }
                        }
                    }

                    var footnoteRow = ws.Cells[currentRow, 1, currentRow, maxCol];
                    footnoteRow.Merge = true;
                    footnoteRow.Style.Font.Size = prFootnoteSize;

                    /*Footnotes defaultFootnote = db.Footnotes.FirstOrDefault(x => x.Footnote_Symbol == "*");
                    if (!footnotes.Contains(defaultFootnote))
                    {
                        footnotes.Add(defaultFootnote);
                    }*/

                    int cellLengthFootnote = 0;
                    if (ws.Name == wsPRName)
                    {
                        foreach (var footnote in footnotes)
                        {
                            ws.Cells[currentRow, 1].RichText.Add(footnote.Footnote_Symbol).VerticalAlign = OfficeOpenXml.Style.ExcelVerticalAlignmentFont.Superscript;
                            ws.Cells[currentRow, 1].RichText.Add(" " + footnote.Footnote + ";");
                            ws.Cells[currentRow, 1].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Top;
                            cellLengthFootnote += footnote.Footnote_Symbol.ToString().Length + footnote.Footnote.ToString().Length + 2;
                            if (cellLengthFootnote > prFootnoteCharsNewLine)
                            {
                                ws.Cells[currentRow, 1].RichText.Add("\r\n");;
                                cellLengthFootnote = 0;
                                ws.Row(currentRow).Height += newLineHeight;
                            }
                        }
                    }
                    else
                    {
                        ws.Cells[currentRow, 1].Value = defNote;
                        ws.Row(currentRow).Height = 28;
                    }

                    var pr = ws.Cells[startRow, 1, currentRow - 1, maxCol];

                    //pr.Style.Border.InsideBorder = prBorderWidth;
                    //pr.Style.Border.InsideBorderColor = prBorder;
                    //pr.Style.Border.OutsideBorder = prBorderWidth;
                    //pr.Style.Border.OutsideBorderColor = prBorder;
                    pr.Style.Font.Size = prFontSize;

                    pr = ws.Cells[startRow, 1, currentRow, maxCol];
                    pr.Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                    pr.Style.WrapText = true;

                    ws.Column(1).Width = prNumberWidth;
                    ws.Column(2).Width = prIndicatorWidth;
                    footnotes.Clear();
                    indicatorNumber = 1;

                    /*var totalHeight = ExcelFunctions.getTotalHeight(ws,4);
                    var totalWidth = ExcelFunctions.getTotalWidth(ws,1);
                    var fitHeight = (int)(totalWidth / fitRatio);
                    var fitWidth = (int)(totalHeight * fitRatio);

                    if (ws.Name == "Def_WIH Obs") { System.Diagnostics.Debugger.Break(); }

                    if (fitHeight > totalHeight)
                   {
                        var fitAddHeightTotal = (fitHeight - totalHeight);
                        var fitAddHeightPerRow = fitAddHeightTotal / fitAdjustableRows.Count;
                        foreach (var row in fitAdjustableRows)
                        {
                            ws.Row(row).Height += fitAddHeightPerRow;
                        }
                    }
                    else
                    {
                        while ((fitWidth - totalWidth) /  fitWidth > 0.001 )
                        {
                            var fitAddWidthTotal = (fitWidth - totalWidth) / 10;
                            var fitAddWidthPerRow = fitAddWidthTotal / (ws.LastColumnUsed().ColumnNumber() - 1);
                            foreach (var col in ws.Columns(2, ws.LastColumnUsed().ColumnNumber()))
                            {
                                col.Width += fitAddWidthPerRow / 5.69;
                            }
                            ExcelFunctions.AutoFitWorksheet(ws, 2, 3, newLineHeight);
                            totalHeight = ExcelFunctions.getTotalHeight(ws, 4);
                            totalWidth = ExcelFunctions.getTotalWidth(ws, 1);
                            fitHeight = (int)(totalWidth / fitRatio);
                            fitWidth = (int)(totalHeight * fitRatio);
                        }
                    }*/
                }
            }

            FileStream fs = new FileStream(this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/test1.xlsx"), FileMode.Create);
            ef.SaveAs(fs);
            fs.Close();
            //var test = GemBox.Spreadsheet.ExcelFile.Load(this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/test.xlsx"), LoadOptions.XlsxDefault);
            var test = new Spire.Xls.Workbook();
            test.LoadFromFile(this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/test1.xlsx"));

             // Set PDF template
            Spire.Pdf.PdfDocument pdfDocument = new Spire.Pdf.PdfDocument();
            pdfDocument.PageSettings.Orientation = Spire.Pdf.PdfPageOrientation.Landscape;
            pdfDocument.PageSettings.Width = 970;
            pdfDocument.PageSettings.Height = 850;

               //Convert Excel to PDF using the template above
            Spire.Xls.Converter.PdfConverter pdfConverter = new Spire.Xls.Converter.PdfConverter(test);
            Spire.Xls.Converter.PdfConverterSettings settings = new Spire.Xls.Converter.PdfConverterSettings();
            settings.TemplateDocument = pdfDocument;
            pdfDocument = pdfConverter.Convert(settings);

               // Save and preview PDF
            pdfDocument.SaveToFile(this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/test1.pdf"));

            //wb.SaveAs(preImage);

            MemoryStream postImage = new MemoryStream();
            SLDocument postImageWb = new SLDocument(preImage);

            string picPath = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/logo.png");
            SLPicture picLogo = new SLPicture(picPath);
            string picPathOPEO = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/logoOPEO.png");
            SLPicture picLogoOPEO = new SLPicture(picPathOPEO);
            string picMonthlyPath = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/Monthly.png");
            SLPicture picMonthly = new SLPicture(picMonthlyPath);
            string picQuaterlyPath = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/quaterly.png");
            SLPicture picQuaterly = new SLPicture(picQuaterlyPath);
            string picNAPath = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/na.png");
            SLPicture picNA = new SLPicture(picNAPath);
            string picTargetPath = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/target.png");
            SLPicture picTarget = new SLPicture(picTargetPath);
            /*
            foreach (var ws in wb.Worksheets)
            {
                postImageWb.SelectWorksheet(ws.Name);

                for (int i = 1; i < 20; ++i)
                {
                    var a = postImageWb.GetRowHeight(i);
                }

                picLogo.SetPosition(0, 0);
                picLogo.ResizeInPercentage(25, 25);
                postImageWb.InsertPicture(picLogo);

                picLogoOPEO.SetRelativePositionInPixels(0, ws.LastColumnUsed().ColumnNumber() + 1, -140, 0);
                picLogoOPEO.ResizeInPercentage(45, 45);
                postImageWb.InsertPicture(picLogoOPEO);

                if (ws.Name.Substring(0, 3) != "Def")
                {
                    picTarget.SetRelativePositionInPixels(ws.LastRowUsed().RowNumber() + 1, ws.LastColumnUsed().ColumnNumber() + 1, -240, 1);
                    picNA.SetRelativePositionInPixels(ws.LastRowUsed().RowNumber() + 1, ws.LastColumnUsed().ColumnNumber() + 1, -400, 1);
                    picMonthly.SetRelativePositionInPixels(ws.LastRowUsed().RowNumber() + 1, ws.LastColumnUsed().ColumnNumber() + 1, -500, 1);
                    picQuaterly.SetRelativePositionInPixels(ws.LastRowUsed().RowNumber() + 1, ws.LastColumnUsed().ColumnNumber() + 1, -490, 1);

                    picMonthly.ResizeInPercentage(70, 70);
                    picQuaterly.ResizeInPercentage(70, 70);
                    picNA.ResizeInPercentage(70, 70);
                    picTarget.ResizeInPercentage(70, 70);

                    postImageWb.InsertPicture(picMonthly);
                    postImageWb.InsertPicture(picQuaterly);
                    postImageWb.InsertPicture(picNA);
                    postImageWb.InsertPicture(picTarget);
                }
            }*/

            // Prepare the response
            HttpResponse httpResponse = this.HttpContext.ApplicationInstance.Context.Response;
            httpResponse.Clear();
            httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            httpResponse.AddHeader("content-disposition", "attachment;filename=\"test.xlsx\"");
            //httpResponse.ContentType = "application/pdf";
            //httpResponse.AddHeader("content-disposition", "attachment;filename=\"test.pdf\"");

            // Flush the workbook to the Response.OutputStream
            using (MemoryStream memoryStream = new MemoryStream())
            {
                postImageWb.SaveAs(memoryStream);
                memoryStream.WriteTo(httpResponse.OutputStream);
                memoryStream.Close();
            }

            httpResponse.End();
            return View(viewModel);
        }
Ejemplo n.º 28
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++;
            }
        }
Ejemplo n.º 29
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++;
            }
        }
Ejemplo n.º 30
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);
        }
Ejemplo n.º 31
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);
        }