Example #1
0
        public static void rotateChecking(ref Image img, string orientationTag)
        {
            Regex rx  = new Regex(@"rotate\s+[0-9]{1,3}(cw|ccw|\s){0,1}", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            Regex rx2 = new Regex(@"(cw|ccw)", RegexOptions.Compiled | RegexOptions.IgnoreCase);

            Regex rx3 = new Regex(@"cw", RegexOptions.Compiled | RegexOptions.IgnoreCase);

            if (rx.IsMatch(orientationTag))
            {
                Match matchDegree = Regex.Match(orientationTag, @"[0-9]{1,3}");
                Match matchType   = rx2.Match(orientationTag);
                degree = double.Parse(matchDegree.Value.ToString());


                if (!rx3.IsMatch(matchType.Value))
                {
                    degree = -degree;
                }

                switch (degree)
                {
                case 90:    img.SetRotationAngle(-Math.PI / 2); break;

                case 180:   img.SetRotationAngle(-Math.PI); break;

                case 270:   img.SetRotationAngle(-Math.PI * 3 / 2); break;

                case -90:   img.SetRotationAngle(Math.PI / 2); break;

                case -180:  img.SetRotationAngle(Math.PI); break;

                case -270:  img.SetRotationAngle(Math.PI * 3 / 2); break;
                }
            }
        }
        private void PrintToPdf(List <MemoryStream> memoryStreams)
        {
            try
            {
                var         file   = File.Create(AppDomain.CurrentDomain.BaseDirectory + @"\ChartExport.pdf");
                PdfWriter   writer = new PdfWriter(file);
                PdfDocument pdf    = new PdfDocument(writer);
                pdf.AddNewPage();
                Document document = new Document(pdf);

                foreach (var str in memoryStreams)
                {
                    ImageData data = ImageDataFactory.Create(str.ToArray());
                    Image     img  = new Image(data);
                    document.Add(img);
                }


                document.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
        }
        private void RunTest(String pdfName, String imageName, String colorProfileName, IDictionary <String, Object
                                                                                                     > customImageAttribute)
        {
            String      outFileName = destinationFolder + pdfName;
            String      cmpFileName = sourceFolder + "cmp_" + pdfName;
            String      diff        = "diff_" + pdfName + "_";
            PdfDocument pdf         = new PdfDocument(new PdfWriter(outFileName));
            Document    document    = new Document(pdf);
            ImageData   imageData   = ImageDataFactory.Create(sourceFolder + imageName);

            if (customImageAttribute != null)
            {
                imageData.GetImageAttributes().AddAll(customImageAttribute);
            }
            if (colorProfileName != null)
            {
                imageData.SetProfile(IccProfile.GetInstance(sourceFolder + colorProfileName));
            }
            iText.Layout.Element.Image png = new iText.Layout.Element.Image(imageData);
            png.SetAutoScale(true);
            document.Add(png);
            document.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
                                                                             , diff));
        }
Example #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="imageSourceList"></param>
        /// <param name="outPath"></param>
        /// <returns></returns>
        public async Task ConvertImages2PdfAsync(IEnumerable <string> imageSourceList, string outPath)
        {
            await Task.Run(() =>
            {
                //var pdfWriter = new PdfWriter(outPath,
                //    new WriterProperties().SetStandardEncryption(user, owner,
                //        EncryptionConstants.ALLOW_PRINTING | EncryptionConstants.ALLOW_ASSEMBLY,
                //        EncryptionConstants.ENCRYPTION_AES_256));

                var pdfWriter   = new PdfWriter(outPath);
                var pdfDocument = new PdfDocument(pdfWriter);
                var document    = new Document(pdfDocument);

                foreach (var imageSource in imageSourceList)
                {
                    var imageData = ImageDataFactory.Create(imageSource);
                    var image     = new iText.Layout.Element.Image(imageData);
                    var a4Width   = PageSize.A4.GetWidth();
                    var a4Height  = PageSize.A4.GetHeight();

                    if (image.GetImageHeight() > a4Height - 25)
                    {
                        image.ScaleToFit(a4Width - 25, a4Height - 25);
                    }
                    else if (image.GetImageWidth() > a4Width - 25)
                    {
                        image.ScaleToFit(a4Width - 25, a4Height - 25);
                    }

                    image.SetHorizontalAlignment(HorizontalAlignment.CENTER);
                    document.Add(image);
                }
                document.Close();
            });
        }
Example #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter barcode number:");
            string      barcode   = Console.ReadLine();
            string      emptyPath = Path.Combine(Directory.GetCurrentDirectory(), "ticket.pdf");
            string      pdfPath   = Path.Combine(Directory.GetCurrentDirectory(), $"NEWTICKET-{barcode}.pdf");
            PdfDocument pdf       = new PdfDocument(new PdfReader(emptyPath), new PdfWriter(pdfPath));
            Document    doc       = new Document(pdf);

            //generate barcode image
            Barcode bar = new Barcode
            {
                IncludeLabel = true
            };

            bar.Encode(TYPE.EAN8, barcode, Color.Black, Color.White, 400, 150);

            //create image type that can be placed in pdf
            ImageData imageData = ImageDataFactory.Create(bar.Encoded_Image_Bytes);

            iText.Layout.Element.Image pdfImg = new iText.Layout.Element.Image(imageData)
                                                .SetFixedPosition(1, 100, 475); //locatie van barcode op pdf, start linksonder, 1 = pagina 1, 100 naar rechts, 475 naar boven
            doc.Add(pdfImg);
            doc.Close();
        }
Example #6
0
 static void addImagesToPdf(Document doc, String[] imagePaths)
 {
     foreach (String str in imagePaths)
     {
         iText.Layout.Element.Image img = new iText.Layout.Element.Image(ImageDataFactory.Create(str));
         img.SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER);
         doc.Add(img);
     }
 }
        public static void rotateChecking(ref Image img, string orientationTag, ref ImageSelection image, bool setOrientation)
        {
            Regex rx  = new Regex(@"rotate\s+[0-9]{1,3}(cw|ccw|\s){0,1}", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            Regex rx2 = new Regex(@"(cw|ccw)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            Regex rx3 = new Regex(@"cw", RegexOptions.Compiled | RegexOptions.IgnoreCase);


            if (rx.IsMatch(orientationTag))
            {
                Match matchDegree = Regex.Match(orientationTag, @"[0-9]{1,3}");
                Match matchType   = rx2.Match(orientationTag);
                degree = double.Parse(matchDegree.Value.ToString());


                if (!rx3.IsMatch(matchType.Value))
                {
                    degree = -degree;
                }
                Console.WriteLine(image.ToString() + " " + orientationTag + "appear " + image.format);
                switch (degree)
                {
                case 90:    img.SetRotationAngle(-Math.PI / 2);
                    if (!setOrientation)
                    {
                        image.format = (image.format == "portrait") ? "landscape" : "portrait";
                    }
                    break;

                case 180:   img.SetRotationAngle(-Math.PI); break;

                case 270:   img.SetRotationAngle(-Math.PI * 3 / 2);
                    if (!setOrientation)
                    {
                        image.format = (image.format == "portrait") ? "landscape" : "portrait";
                    }
                    break;

                case -90:   img.SetRotationAngle(Math.PI / 2);
                    if (!setOrientation)
                    {
                        image.format = (image.format == "portrait") ? "landscape" : "portrait";
                    }
                    break;

                case -180:  img.SetRotationAngle(Math.PI); break;

                case -270:  img.SetRotationAngle(Math.PI * 3 / 2);
                    if (!setOrientation)
                    {
                        image.format = (image.format == "portrait") ? "landscape" : "portrait";
                    }
                    break;
                }
            }
        }
        public static iText.Layout.Element.Image ToIText(this CanvasImage canvasImage)
        {
            var info = new UIElementInfo(canvasImage.Image, canvasImage.Canvas);

            var src   = ImageDataFactory.Create(canvasImage.ImagePath);
            var image = new iText.Layout.Element.Image(src, info.Left, info.Bottom);

            image.SetFixedPosition(info.Left, info.Bottom);
            image.ScaleAbsolute(info.ElementWidth, info.ElementHeight);

            return(image);
        }
Example #9
0
        /// <summary>
        /// ๅˆฉ็”จitext7็”Ÿๆˆๆ–‡ๅญ—็ญพๅ
        /// </summary>
        public void ConvertPdf1()
        {
            string sourcePath = $"C:\\test\\source.pdf";
            string targetPath = $"C:\\test\\target.pdf";
            string fontPath   = $"C:\\Windows\\Fonts\\simkai.ttf";

            string signPath1 = @"C:\Users\Administrator\Desktop\a.png";
            string signPath2 = @"C:\Users\Administrator\Desktop\b.png";
            string signPath3 = @"C:\Users\Administrator\Desktop\c.png";
            string signPath4 = @"C:\Users\Administrator\Desktop\d.png";


            //่พ“ๅ…ฅPDF
            using (iText.Kernel.Pdf.PdfReader reader = new iText.Kernel.Pdf.PdfReader(sourcePath))
            {
                //่พ“ๅ‡บPDF
                using (iText.Kernel.Pdf.PdfWriter writer = new iText.Kernel.Pdf.PdfWriter(targetPath))
                {
                    //่Žทๅ–PDFๅฏน่ฑก
                    using (iText.Kernel.Pdf.PdfDocument pdfDocument = new iText.Kernel.Pdf.PdfDocument(reader, writer))
                    {
                        //่Žทๅ–Documentๅฏน่ฑก
                        using (iText.Layout.Document document = new iText.Layout.Document(pdfDocument))
                        {
                            //ไปŽ็‰ฉ็†ๆ–‡ไปถๅŠ ่ฝฝๅ›พ็‰‡
                            iText.Layout.Element.Image image1 = new iText.Layout.Element.Image(iText.IO.Image.ImageDataFactory.Create(signPath1));
                            iText.Layout.Element.Image image2 = new iText.Layout.Element.Image(iText.IO.Image.ImageDataFactory.Create(signPath2));
                            iText.Layout.Element.Image image3 = new iText.Layout.Element.Image(iText.IO.Image.ImageDataFactory.Create(signPath3));
                            iText.Layout.Element.Image image4 = new iText.Layout.Element.Image(iText.IO.Image.ImageDataFactory.Create(signPath4));

                            //ๅฐ†ๅ›พ็‰‡็ป˜ๅˆถๅˆฐPDF็š„็ปๅฏนๅๆ ‡ไธŠ๏ผŒๅŒๆ—ถ็ผฉๆ”พๅ›พ็‰‡
                            //ๅๆ ‡ไธŽ็ป˜ๅˆถๆ–‡ๅญ—็š„ๅๆ ‡ๅ‡ ไนŽไธ€่‡ด๏ผŒ็จๅพฎๅ‘ๅทฆ๏ผŒๅ‘ไธŠไธ€ไบ›
                            //็ผฉๆ”พ็š„ๅฎฝๅบฆไธŽๅŽ้ข็š„ๅฎฝๅบฆไธ€่‡ด๏ผŒ็คบไพ‹ไธญๆ˜ฏ200
                            //็ผฉๆ”พ็š„้ซ˜ๅบฆ่ฎก็ฎ—ไธคไธช็ญพๅไน‹้—ด็š„้ซ˜ๅบฆๅทฎ๏ผŒไพ‹ๅฆ‚93-73=20
                            //ๆณจๆ„็คบไพ‹้‡‡็”จ็š„็ญพๅๅ›พ็‰‡็š„ๅฐบๅฏธๆ˜ฏ๏ผš400px * 150px๏ผŒๅบ”ๅฝ“้‡‡ๅ–ๅ’Œๅฎƒๅทฎไธๅคš็š„ๅฐบๅฏธๆ•ˆๆžœๆœ€ไฝณ
                            document.Add(image1.ScaleToFit(200, 20).SetFixedPosition(1, 3089, 93, 200));
                            document.Add(image2.ScaleToFit(200, 20).SetFixedPosition(1, 3089, 73, 200));
                            document.Add(image3.ScaleToFit(200, 20).SetFixedPosition(1, 3089, 53, 200));
                            document.Add(image4.ScaleToFit(200, 20).SetFixedPosition(1, 3089, 33, 200));

                            //ๅŠ ่ฝฝๅญ—ไฝ“
                            iText.Kernel.Font.PdfFont font = iText.Kernel.Font.PdfFontFactory.CreateFont(fontPath, iText.IO.Font.PdfEncodings.IDENTITY_H, true);

                            //ๆทปๅŠ ๆ–‡ๆœฌ
                            document.Add(new iText.Layout.Element.Paragraph("็ญพๅ1").SetFont(font).SetFontSize(12).SetFixedPosition(1, 3090, 90, 200));
                            document.Add(new iText.Layout.Element.Paragraph("็ญพๅ2").SetFont(font).SetFontSize(12).SetFixedPosition(1, 3090, 70, 200));
                            document.Add(new iText.Layout.Element.Paragraph("็ญพๅ3").SetFont(font).SetFontSize(12).SetFixedPosition(1, 3090, 50, 200));
                            document.Add(new iText.Layout.Element.Paragraph("็ญพๅ4").SetFont(font).SetFontSize(12).SetFixedPosition(1, 3090, 30, 200));
                        }
                    }
                }
            }
        }
Example #10
0
        //LOCATIE VAN TICKET NOG AANPASSEN - momenteel ergens onder debug folder ofzo bij uitvoeren
        //aanpassen PdfPath in Properties bovenaan!!!
        // + betere manier vinden om blanco pdf op te halen?
        private void GenerateTicketPdf(string blankPdf)
        {
            //prepare pdf document
            PdfDocument pdf = new PdfDocument(new PdfReader(blankPdf), new PdfWriter(PdfPath));
            Document    doc = new Document(pdf);

            //create image type that can be placed in pdf
            ImageData imageData = ImageDataFactory.Create(GenerateBarcodeImage());

            iText.Layout.Element.Image pdfImg = new iText.Layout.Element.Image(imageData)
                                                .SetFixedPosition(1, 100, 475); //locatie van barcode op pdf, start linksonder, 1 = pagina 1, 100 naar rechts, 475 naar boven
            doc.Add(pdfImg);
            doc.Close();
        }
        public new void ExportToPdf(string path, double width = 700, double height = 370)
        {
            // exports spectrum annotation w/o base seq annotation
            string tempPdfPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(path), "temp.pdf");
            string tempPngPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(path), "annotation.png");

            base.ExportToPdf(tempPdfPath, width, height);

            // scales for desired DPI
            double dpiScale = MetaDrawSettings.CanvasPdfExportDpi / 96.0;

            // save base seq as PNG
            SequenceDrawingCanvas.Measure(new Size((int)SequenceDrawingCanvas.Width, (int)SequenceDrawingCanvas.Height));
            SequenceDrawingCanvas.Arrange(new Rect(new Size((int)SequenceDrawingCanvas.Width, (int)SequenceDrawingCanvas.Height)));

            RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)(dpiScale * SequenceDrawingCanvas.Width), (int)(dpiScale * SequenceDrawingCanvas.Height),
                                                                     MetaDrawSettings.CanvasPdfExportDpi, MetaDrawSettings.CanvasPdfExportDpi, PixelFormats.Pbgra32);

            renderBitmap.Render(SequenceDrawingCanvas);
            PngBitmapEncoder encoder = new PngBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(renderBitmap));

            using (FileStream file = File.Create(tempPngPath))
            {
                encoder.Save(file);
            }

            // adds base seq annotation to pdf
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(tempPdfPath), new PdfWriter(path));

            iText.Layout.Document document = new iText.Layout.Document(pdfDoc);

            ImageData imgData = ImageDataFactory.Create(tempPngPath);

            iText.Layout.Element.Image img = new iText.Layout.Element.Image(imgData);
            img.SetMarginLeft((float)(-1.0 * SequenceDrawingCanvas.Margin.Left) + 10);
            img.SetMarginTop(-30);
            img.ScaleToFit((float)SequenceDrawingCanvas.Width, (float)SequenceDrawingCanvas.Height);

            document.Add(img);

            document.Close();
            pdfDoc.Close();

            // delete temp files
            File.Delete(tempPdfPath);
            File.Delete(tempPngPath);
        }
Example #12
0
        private string ExportPdf(Book book, string outputPath)
        {
            var firstPagePath = book.Pages.FirstOrDefault()?.PageImagePath;

            if (string.IsNullOrWhiteSpace(firstPagePath))
            {
                _logger.Log("No pages downloaded to create Pdf.");
                return(null);
            }

            _logger.Log("Pages Downloaded. Creating Pdf...");

            var pdfPath = Path.Combine(outputPath, book.BookName.ToSafeFilename() + ".pdf");

            pdfPath.MakeSureFileDoesNotExist();

            PageSize documentSize;

            using (var firstImage = new Bitmap(firstPagePath))
            {
                documentSize = new PageSize(firstImage.Width, firstImage.Height);
            }

            using (var pdf = new PdfDocument(new PdfWriter(pdfPath)))
            {
                using (var writer = pdf.GetWriter())
                {
                    writer.SetCompressionLevel(9);

                    using (var document = new Document(pdf, documentSize))
                    {
                        document.SetMargins(0, 0, 0, 0);

                        foreach (var page in book.Pages)
                        {
                            var imageData = ImageDataFactory.Create(page.PageImagePath);
                            var image     = new Image(imageData).SetHeight(imageData.GetHeight()).SetWidth(imageData.GetWidth());
                            document.Add(image);
                        }
                    }
                }
            }

            Path.GetDirectoryName(firstPagePath)?.TryDeleteDirectory();

            _logger.Log($"Book saved as {pdfPath}");

            return(pdfPath);
        }
Example #13
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));

            // Assume that there is a single XObject in the source document
            // and this single object is an image.
            PdfDictionary pageDict  = pdfDoc.GetFirstPage().GetPdfObject();
            PdfDictionary resources = pageDict.GetAsDictionary(PdfName.Resources);
            PdfDictionary xObjects  = resources.GetAsDictionary(PdfName.XObject);
            PdfName       imgRef    = xObjects.KeySet().First();
            PdfStream     stream    = xObjects.GetAsStream(imgRef);
            Image         img       = ConvertToBlackAndWhitePng(new PdfImageXObject(stream));

            // Replace the original image with the grayscale image
            xObjects.Put(imgRef, img.GetXObject().GetPdfObject());

            pdfDoc.Close();
        }
Example #14
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc   = new PdfDocument(new PdfWriter(dest));
            PageSize    pageSize = PageSize.A4.Rotate();
            Document    doc      = new Document(pdfDoc, pageSize);

            ImageData image = ImageDataFactory.Create(IMAGE);
            ImageData mask  = ConvertToBlackAndWhitePng(MASK);

            mask.MakeMask();
            image.SetImageMask(mask);

            /* For soft image masks grayscale 8 bit images are usually used. As described in
             * the ConvertToBlackAndWhitePng, for image masks actual image colorspace doesn't
             * matter, only image pixel values are important. Grayscale images are just
             * convenient for this purpose.
             * Here we adjust SMask image dictionary, in order to accommodate to the hacks
             * that we've performed in ConvertToBlackAndWhitePng method. There we've created
             * an image in indexed color space and by default C# will add transparency to the
             * image. Both these properties are forbidden for images that serve as masks.
             * That's why we explicitly override colorspace to /DeviceGray (which corresponds
             * to grayscale) and we just erase own transparency (/Mask) from the dictionary
             * of mask-image.
             */
            PdfImageXObject imageXObject       = new PdfImageXObject(image);
            PdfStream       imageXObjectStream = imageXObject.GetPdfObject().GetAsStream(PdfName.SMask);

            imageXObjectStream.Put(PdfName.ColorSpace, PdfName.DeviceGray);

            // Remove a redundant submask
            imageXObjectStream.Remove(PdfName.Mask);

            Image img = new Image(imageXObject);

            img.ScaleAbsolute(pageSize.GetWidth(), pageSize.GetHeight());
            img.SetFixedPosition(0, 0);
            doc.Add(img);

            doc.Close();
        }
Example #15
0
        public Esito popolaPannelloRiepilogo(DatiAgenda eventoSelezionato)
        {
            ViewState["eventoSelezionato"] = eventoSelezionato;
            Esito esito = new Esito();

            try
            {
                List <DatiArticoli> listaDatiArticoli = RichiediListaArticoli() == null? null : RichiediListaArticoli().Where(x => x.Stampa).ToList <DatiArticoli>();
                if (listaDatiArticoli != null)
                {
                    // LEGGO I PARAMETRI DI VS
                    Config cfAppo = Config_BLL.Instance.getConfig(ref esito, "PARTITA_IVA");
                    string pIvaVs = cfAppo.valore;
                    cfAppo = Config_BLL.Instance.getConfig(ref esito, "DENOMINAZIONE");
                    string denominazioneVs = cfAppo.valore;
                    cfAppo = Config_BLL.Instance.getConfig(ref esito, "TOPONIMO");
                    string toponimoVs = cfAppo.valore;
                    cfAppo = Config_BLL.Instance.getConfig(ref esito, "INDIRIZZO");
                    string indirizzoVs = cfAppo.valore;
                    cfAppo = Config_BLL.Instance.getConfig(ref esito, "CIVICO");
                    string civicoVs = cfAppo.valore;
                    cfAppo = Config_BLL.Instance.getConfig(ref esito, "CAP");
                    string capVs = cfAppo.valore;
                    cfAppo = Config_BLL.Instance.getConfig(ref esito, "CITTA");
                    string cittaVs = cfAppo.valore;
                    cfAppo = Config_BLL.Instance.getConfig(ref esito, "PROVINCIA");
                    string provinciaVs = cfAppo.valore;
                    cfAppo = Config_BLL.Instance.getConfig(ref esito, "EMAIL");
                    string emailVs = cfAppo.valore;

                    //TROVO IL PROTOCOLLO, SE NON PRESENTE LO CREO
                    Protocolli        protocolloOfferta = new Protocolli();
                    int               idTipoProtocollo  = UtilityTipologiche.getElementByNome(UtilityTipologiche.caricaTipologica(EnumTipologiche.TIPO_PROTOCOLLO), "Offerta", ref esito).id;
                    List <Protocolli> listaProtocolli   = Protocolli_BLL.Instance.getProtocolliByCodLavIdTipoProtocollo(eventoSelezionato.codice_lavoro, idTipoProtocollo, ref esito, true);
                    string            numeroProtocollo  = "";
                    if (listaProtocolli.Count == 0)
                    {
                        numeroProtocollo = Protocolli_BLL.Instance.getNumeroProtocollo();
                    }
                    else
                    {
                        bool trovato = false;
                        foreach (Protocolli protocollo in listaProtocolli)
                        {
                            if (protocollo.Destinatario == "Cliente")
                            {
                                //protocolloOfferta = listaProtocolli.First();
                                numeroProtocollo  = protocollo.Numero_protocollo;
                                numeroProtocollo  = protocollo.Protocollo_riferimento;
                                protocolloOfferta = protocollo;
                                trovato           = true;
                                break;
                            }
                        }
                        if (!trovato)
                        {
                            protocolloOfferta = listaProtocolli.First();
                            numeroProtocollo  = protocolloOfferta.Numero_protocollo;
                        }
                    }

                    // GESTIONE NOMI FILE PDF
                    string nomeFile       = "Offerta_" + eventoSelezionato.codice_lavoro + ".pdf";
                    string pathOfferta    = ConfigurationManager.AppSettings["PATH_DOCUMENTI_PROTOCOLLO"] + nomeFile;
                    string mapPathOfferta = MapPath(ConfigurationManager.AppSettings["PATH_DOCUMENTI_PROTOCOLLO"]) + nomeFile;

                    // string prefissoUrl = Request.Url.Scheme + "://" + Request.Url.Authority;
                    //iText.IO.Image.ImageData imageData = iText.IO.Image.ImageDataFactory.Create(prefissoUrl + "/Images/logoVSP_trim.png");
                    iText.IO.Image.ImageData imageData = iText.IO.Image.ImageDataFactory.Create(MapPath("~/Images/logoVSP_trim.png"));
                    iText.IO.Image.ImageData imageDNV  = iText.IO.Image.ImageDataFactory.Create(MapPath("~/Images/DNV_2008_ITA2.jpg"));


                    PdfWriter   wr  = new PdfWriter(mapPathOfferta);
                    PdfDocument doc = new PdfDocument(wr);
                    doc.SetDefaultPageSize(iText.Kernel.Geom.PageSize.A4);
                    //Document document = new Document(doc);
                    Document document = new Document(doc, iText.Kernel.Geom.PageSize.A4, false);

                    document.SetMargins(245, 30, 110, 30);


                    // ESTRAPOLO IL CLIENTE
                    Anag_Clienti_Fornitori cliente = Anag_Clienti_Fornitori_BLL.Instance.getAziendaById(eventoSelezionato.id_cliente, ref esito);

                    iText.Layout.Element.Paragraph pSpazio = new iText.Layout.Element.Paragraph(" ");
                    document.Add(pSpazio);


                    // CREAZIONE GRIGLIA PRINCIPALE DETTAGLIO OFFERTA
                    iText.Layout.Element.Table     tbGrigla = new iText.Layout.Element.Table(new float[] { 80, 70, 180, 70, 30, 30, 70 }).SetWidth(530).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10).SetFixedLayout();
                    iText.Layout.Element.Paragraph pGriglia;
                    iText.Layout.Element.Cell      cellaGriglia;

                    // COLORE INTESTAZIONI
                    //iText.Kernel.Colors.Color coloreIntestazioni = new iText.Kernel.Colors.DeviceRgb(0, 255, 255);
                    // COLORE BLU VIDEOSYSTEM
                    iText.Kernel.Colors.Color coloreIntestazioni = new iText.Kernel.Colors.DeviceRgb(33, 150, 243);


                    // INTESTAZIONE OFFERTA
                    pGriglia     = new iText.Layout.Element.Paragraph("Offerta Numero").SetFontSize(10).SetBold();
                    cellaGriglia = new iText.Layout.Element.Cell().SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                    cellaGriglia.Add(pGriglia);
                    tbGrigla.AddHeaderCell(cellaGriglia);

                    pGriglia     = new iText.Layout.Element.Paragraph(eventoSelezionato.codice_lavoro).SetFontSize(10).SetBold();
                    cellaGriglia = new iText.Layout.Element.Cell().SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                    cellaGriglia.Add(pGriglia);
                    tbGrigla.AddHeaderCell(cellaGriglia);

                    pGriglia     = new iText.Layout.Element.Paragraph("").SetFontSize(10);
                    cellaGriglia = new iText.Layout.Element.Cell().SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                    cellaGriglia.Add(pGriglia);
                    tbGrigla.AddHeaderCell(cellaGriglia);

                    pGriglia     = new iText.Layout.Element.Paragraph("Rif.Prot. " + numeroProtocollo).SetFontSize(10).SetBold();
                    cellaGriglia = new iText.Layout.Element.Cell(1, 4).SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                    cellaGriglia.Add(pGriglia);
                    tbGrigla.AddHeaderCell(cellaGriglia);

                    // INTESTAZIONE GRIGLIA
                    pGriglia     = new iText.Layout.Element.Paragraph("Codice").SetFontSize(10);
                    cellaGriglia = new iText.Layout.Element.Cell().SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(new iText.Layout.Borders.SolidBorder(iText.Kernel.Colors.ColorConstants.WHITE, 1, 100)).SetPadding(5).SetBold();
                    cellaGriglia.Add(pGriglia);
                    tbGrigla.AddHeaderCell(cellaGriglia);

                    pGriglia     = new iText.Layout.Element.Paragraph("Descrizione Offerta").SetFontSize(10);
                    cellaGriglia = new iText.Layout.Element.Cell(1, 2).SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(new iText.Layout.Borders.SolidBorder(iText.Kernel.Colors.ColorConstants.WHITE, 1, 100)).SetPadding(5).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER).SetBold();
                    cellaGriglia.Add(pGriglia);
                    tbGrigla.AddHeaderCell(cellaGriglia);

                    pGriglia     = new iText.Layout.Element.Paragraph("Prezzo").SetFontSize(10);
                    cellaGriglia = new iText.Layout.Element.Cell().SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(new iText.Layout.Borders.SolidBorder(iText.Kernel.Colors.ColorConstants.WHITE, 1, 100)).SetPadding(5).SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT).SetBold();
                    cellaGriglia.Add(pGriglia);
                    tbGrigla.AddHeaderCell(cellaGriglia);

                    pGriglia     = new iText.Layout.Element.Paragraph("Qta").SetFontSize(10);
                    cellaGriglia = new iText.Layout.Element.Cell().SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(new iText.Layout.Borders.SolidBorder(iText.Kernel.Colors.ColorConstants.WHITE, 1, 100)).SetPadding(5).SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT).SetBold();
                    cellaGriglia.Add(pGriglia);
                    tbGrigla.AddHeaderCell(cellaGriglia);

                    pGriglia     = new iText.Layout.Element.Paragraph("Iva").SetFontSize(10);
                    cellaGriglia = new iText.Layout.Element.Cell().SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(new iText.Layout.Borders.SolidBorder(iText.Kernel.Colors.ColorConstants.WHITE, 1, 100)).SetPadding(5).SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT).SetBold();
                    cellaGriglia.Add(pGriglia);
                    tbGrigla.AddHeaderCell(cellaGriglia);

                    pGriglia     = new iText.Layout.Element.Paragraph("Totale").SetFontSize(10);
                    cellaGriglia = new iText.Layout.Element.Cell().SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(new iText.Layout.Borders.SolidBorder(iText.Kernel.Colors.ColorConstants.WHITE, 1, 100)).SetPadding(5).SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT).SetBold();
                    cellaGriglia.Add(pGriglia);
                    tbGrigla.AddHeaderCell(cellaGriglia);

                    decimal totPrezzo = 0;
                    decimal totIVA    = 0;

                    // CICLO GLI ARTICOLI
                    foreach (DatiArticoli da in listaDatiArticoli)
                    {
                        // CALCOLO I TOTALI
                        totPrezzo += da.Prezzo * da.Quantita;
                        totIVA    += (da.Prezzo * da.Iva / 100) * da.Quantita;

                        string descrizione      = da.Descrizione;
                        string descrizioneLunga = da.DescrizioneLunga;

                        pGriglia     = new iText.Layout.Element.Paragraph(descrizione).SetFontSize(9);
                        cellaGriglia = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10);
                        cellaGriglia.Add(pGriglia);
                        tbGrigla.AddCell(cellaGriglia);

                        pGriglia     = new iText.Layout.Element.Paragraph(descrizioneLunga).SetFontSize(9);
                        cellaGriglia = new iText.Layout.Element.Cell(1, 2).SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10);
                        cellaGriglia.Add(pGriglia);
                        tbGrigla.AddCell(cellaGriglia);

                        if (!cbCopriImporti.Checked)
                        {
                            pGriglia     = new iText.Layout.Element.Paragraph(da.Prezzo.ToString("###,##0.00")).SetFontSize(9);
                            cellaGriglia = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10).SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT);
                            cellaGriglia.Add(pGriglia);
                            tbGrigla.AddCell(cellaGriglia);

                            pGriglia = new iText.Layout.Element.Paragraph(da.Quantita.ToString("##0")).SetFontSize(9);
                            //pGriglia = new iText.Layout.Element.Paragraph(1.ToString("##0")).SetFontSize(9);
                            cellaGriglia = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10).SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT);
                            cellaGriglia.Add(pGriglia);
                            tbGrigla.AddCell(cellaGriglia);

                            pGriglia     = new iText.Layout.Element.Paragraph(da.Iva.ToString("##")).SetFontSize(9);
                            cellaGriglia = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10).SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT);
                            cellaGriglia.Add(pGriglia);
                            tbGrigla.AddCell(cellaGriglia);

                            decimal totale = da.Prezzo * da.Quantita;
                            //decimal totale = da.Prezzo * 1;

                            pGriglia     = new iText.Layout.Element.Paragraph(totale.ToString("###,##0.00")).SetFontSize(9);
                            cellaGriglia = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10).SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT);
                            cellaGriglia.Add(pGriglia);
                            tbGrigla.AddCell(cellaGriglia);
                        }
                        else
                        {
                            // NON VISUALIZZO IMPORTI
                            pGriglia     = new iText.Layout.Element.Paragraph("").SetFontSize(9);
                            cellaGriglia = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10).SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT);
                            cellaGriglia.Add(pGriglia);
                            tbGrigla.AddCell(cellaGriglia);

                            pGriglia = new iText.Layout.Element.Paragraph(da.Quantita.ToString("##0")).SetFontSize(9);
                            //pGriglia = new iText.Layout.Element.Paragraph(1.ToString("##0")).SetFontSize(9);
                            cellaGriglia = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10).SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT);
                            cellaGriglia.Add(pGriglia);
                            tbGrigla.AddCell(cellaGriglia);

                            pGriglia     = new iText.Layout.Element.Paragraph("").SetFontSize(9);
                            cellaGriglia = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10).SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT);
                            cellaGriglia.Add(pGriglia);
                            tbGrigla.AddCell(cellaGriglia);

                            decimal totale = da.Prezzo * da.Quantita;
                            //decimal totale = da.Prezzo * 1;

                            pGriglia     = new iText.Layout.Element.Paragraph("").SetFontSize(9);
                            cellaGriglia = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10).SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT);
                            cellaGriglia.Add(pGriglia);
                            tbGrigla.AddCell(cellaGriglia);
                        }
                    }

                    // AGGIUNGO UNO SPAZIO
                    pGriglia     = new iText.Layout.Element.Paragraph(" ").SetFontSize(9);
                    cellaGriglia = new iText.Layout.Element.Cell(1, 7).SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10).SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT);
                    cellaGriglia.Add(pGriglia);
                    tbGrigla.AddCell(cellaGriglia);


                    // ESTRAPOLO NOTEOFFERTA

                    NoteOfferta noteOfferta = Offerta_BLL.Instance.getNoteOffertaByIdDatiAgenda(eventoSelezionato.id, ref esito);

                    // se non viene trovata una notaOfferta (vecchi eventi) viene creata e salvata
                    if (noteOfferta.Id == 0)
                    {
                        List <DatiBancari> datiBancari = Config_BLL.Instance.getListaDatiBancari(ref esito);
                        noteOfferta = new NoteOfferta {
                            Id_dati_agenda = eventoSelezionato.id, Banca = datiBancari[0].DatiCompleti, Pagamento = cliente.Pagamento, NotaPagamento = cliente.NotaPagamento, Consegna = cliente.TipoIndirizzoLegale + " " + cliente.IndirizzoLegale + " " + cliente.NumeroCivicoLegale + Environment.NewLine + cliente.CapLegale + " " + cliente.ComuneLegale + " " + cliente.ProvinciaLegale + " "
                        };                                                                                                                                                                                                                                                                                                                                                                                                         // "Unicredit Banca: IBAN: IT39H0200805198000103515620", Pagamento = cliente.Pagamento, Consegna = cliente.TipoIndirizzoLegale + " " + cliente.IndirizzoLegale + " " + cliente.NumeroCivicoLegale + " " + cliente.CapLegale + " " + cliente.ProvinciaLegale + " " };

                        Offerta_BLL.Instance.CreaNoteOfferta(noteOfferta, ref esito);
                    }

                    ViewState["NoteOfferta"] = noteOfferta;

                    txt_Consegna.Text    = noteOfferta.Consegna;
                    tbMod_Pagamento.Text = noteOfferta.NotaPagamento.ToString();

                    if (string.IsNullOrEmpty(noteOfferta.Note))
                    {
                        txt_Note.Text = "";
                    }
                    else
                    {
                        txt_Note.Text = noteOfferta.Note.Trim();
                    }

                    // NOTE
                    iText.Layout.Element.Text      first         = new iText.Layout.Element.Text("Note:").SetFontSize(9).SetBold();
                    iText.Layout.Element.Text      second        = new iText.Layout.Element.Text(Environment.NewLine + noteOfferta.Note.Trim()).SetFontSize(9);
                    iText.Layout.Element.Paragraph paragraphNote = new iText.Layout.Element.Paragraph().Add(first).Add(second);

                    cellaGriglia = new iText.Layout.Element.Cell(3, 3).SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10);
                    cellaGriglia.Add(paragraphNote);
                    tbGrigla.AddCell(cellaGriglia);

                    pGriglia     = new iText.Layout.Element.Paragraph("Imponibile").SetFontSize(9);
                    cellaGriglia = new iText.Layout.Element.Cell(1, 3).SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10).SetBold();
                    cellaGriglia.Add(pGriglia);
                    tbGrigla.AddCell(cellaGriglia);

                    if (!cbCopriImporti.Checked)
                    {
                        pGriglia = new iText.Layout.Element.Paragraph(totPrezzo.ToString("###,##0.00")).SetFontSize(9);
                    }
                    else
                    {
                        pGriglia = new iText.Layout.Element.Paragraph("").SetFontSize(9);
                    }
                    cellaGriglia = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10).SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT).SetBold();
                    cellaGriglia.Add(pGriglia);
                    tbGrigla.AddCell(cellaGriglia);

                    // TOTALE IVA
                    pGriglia     = new iText.Layout.Element.Paragraph("i.v.a.").SetFontSize(9);
                    cellaGriglia = new iText.Layout.Element.Cell(1, 3).SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10).SetBold();
                    cellaGriglia.Add(pGriglia);
                    tbGrigla.AddCell(cellaGriglia);
                    if (!cbCopriImporti.Checked)
                    {
                        pGriglia = new iText.Layout.Element.Paragraph(totIVA.ToString("###,##0.00")).SetFontSize(9);
                    }
                    else
                    {
                        pGriglia = new iText.Layout.Element.Paragraph("").SetFontSize(9);
                    }
                    cellaGriglia = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10).SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT).SetBold();
                    cellaGriglia.Add(pGriglia);
                    tbGrigla.AddCell(cellaGriglia);

                    // TOTALE EURO
                    pGriglia     = new iText.Layout.Element.Paragraph("Totale Euro").SetFontSize(9);
                    cellaGriglia = new iText.Layout.Element.Cell(1, 3).SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10).SetBold();
                    cellaGriglia.Add(pGriglia);
                    tbGrigla.AddCell(cellaGriglia);
                    if (!cbCopriImporti.Checked)
                    {
                        pGriglia = new iText.Layout.Element.Paragraph((totPrezzo + totIVA).ToString("###,##0.00")).SetFontSize(9);
                    }
                    else
                    {
                        pGriglia = new iText.Layout.Element.Paragraph("").SetFontSize(9);
                    }
                    cellaGriglia = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.WHITE, 10).SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT).SetBold();
                    cellaGriglia.Add(pGriglia);
                    tbGrigla.AddCell(cellaGriglia);

                    document.Add(tbGrigla);

                    //iText.Kernel.Geom.Rectangle pageSize = doc.GetPage(1).GetPageSize();

                    int n = doc.GetNumberOfPages();
                    iText.Kernel.Geom.Rectangle pageSize = doc.GetPage(n).GetPageSize();

                    // AGGIUNGO CONTEGGIO PAGINE E FOOTER PER OGNI PAGINA
                    for (int i = 1; i <= n; i++)
                    {
                        // AGGIUNGO LOGO
                        iText.Layout.Element.Image image = new iText.Layout.Element.Image(imageData).ScaleAbsolute(90, 80).SetFixedPosition(i, 30, 740);
                        document.Add(image);


                        // CREAZIONE GRIGLIA INFORMAZIONI
                        iText.Layout.Element.Table     tbGriglaInfo     = new iText.Layout.Element.Table(new float[] { 70, 230 }).SetWidth(300).SetFixedPosition(i, 30, 640, 300);
                        iText.Layout.Element.Paragraph pGrigliaInfo     = new iText.Layout.Element.Paragraph(cittaVs).SetFontSize(9).SetBold();
                        iText.Layout.Element.Cell      cellaGrigliaInfo = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                        cellaGrigliaInfo.Add(pGrigliaInfo);
                        tbGriglaInfo.AddCell(cellaGrigliaInfo);

                        pGrigliaInfo     = new iText.Layout.Element.Paragraph(DateTime.Today.ToLongDateString()).SetFontSize(9);
                        cellaGrigliaInfo = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                        cellaGrigliaInfo.Add(pGrigliaInfo);
                        tbGriglaInfo.AddCell(cellaGrigliaInfo);

                        pGrigliaInfo     = new iText.Layout.Element.Paragraph("Produzione:").SetFontSize(9).SetBold();
                        cellaGrigliaInfo = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                        cellaGrigliaInfo.Add(pGrigliaInfo);
                        tbGriglaInfo.AddCell(cellaGrigliaInfo);

                        pGrigliaInfo     = new iText.Layout.Element.Paragraph(eventoSelezionato.produzione).SetFontSize(9);
                        cellaGrigliaInfo = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                        cellaGrigliaInfo.Add(pGrigliaInfo);
                        tbGriglaInfo.AddCell(cellaGrigliaInfo);

                        pGrigliaInfo     = new iText.Layout.Element.Paragraph("Lavorazione:").SetFontSize(9).SetBold();
                        cellaGrigliaInfo = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                        cellaGrigliaInfo.Add(pGrigliaInfo);
                        tbGriglaInfo.AddCell(cellaGrigliaInfo);

                        pGrigliaInfo     = new iText.Layout.Element.Paragraph(eventoSelezionato.lavorazione).SetFontSize(9);
                        cellaGrigliaInfo = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                        cellaGrigliaInfo.Add(pGrigliaInfo);
                        tbGriglaInfo.AddCell(cellaGrigliaInfo);

                        pGrigliaInfo     = new iText.Layout.Element.Paragraph("Data Lav.ne:").SetFontSize(9).SetBold();
                        cellaGrigliaInfo = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                        cellaGrigliaInfo.Add(pGrigliaInfo);
                        tbGriglaInfo.AddCell(cellaGrigliaInfo);

                        pGrigliaInfo     = new iText.Layout.Element.Paragraph(eventoSelezionato.data_inizio_lavorazione.ToString("dd/MM/yyyy")).SetFontSize(9);
                        cellaGrigliaInfo = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                        cellaGrigliaInfo.Add(pGrigliaInfo);
                        tbGriglaInfo.AddCell(cellaGrigliaInfo);

                        document.Add(tbGriglaInfo);


                        // CREAZIONE GRIGLIA DESTINATARIO
                        iText.Layout.Element.Table     tbGriglaDest     = new iText.Layout.Element.Table(new float[] { 70, 230 }).SetWidth(300).SetFixedPosition(i, 350, 650, 300);
                        iText.Layout.Element.Paragraph pGrigliaDest     = new iText.Layout.Element.Paragraph("Spettabile").SetFontSize(9).SetBold();
                        iText.Layout.Element.Cell      cellaGrigliaDest = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                        cellaGrigliaDest.Add(pGrigliaDest);
                        tbGriglaDest.AddCell(cellaGrigliaDest);

                        pGrigliaDest     = new iText.Layout.Element.Paragraph(cliente.RagioneSociale).SetFontSize(9);
                        cellaGrigliaDest = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                        cellaGrigliaDest.Add(pGrigliaDest);
                        tbGriglaDest.AddCell(cellaGrigliaDest);

                        // INDIRIZZO DESTINATARIO
                        pGrigliaDest     = new iText.Layout.Element.Paragraph("Indirizzo").SetFontSize(9).SetBold();
                        cellaGrigliaDest = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                        cellaGrigliaDest.Add(pGrigliaDest);
                        tbGriglaDest.AddCell(cellaGrigliaDest);

                        //pGrigliaDest = new iText.Layout.Element.Paragraph(cliente.TipoIndirizzoOperativo + " " + cliente.IndirizzoOperativo + " " + cliente.NumeroCivicoOperativo + Environment.NewLine + cliente.CapOperativo + " " + cliente.ComuneOperativo + " " + cliente.ProvinciaOperativo).SetFontSize(9);
                        //cellaGrigliaDest = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                        //cellaGrigliaDest.Add(pGrigliaDest);
                        //tbGriglaDest.AddCell(cellaGrigliaDest);

                        pGrigliaDest     = new iText.Layout.Element.Paragraph(cliente.TipoIndirizzoLegale + " " + cliente.IndirizzoLegale + " " + cliente.NumeroCivicoLegale + Environment.NewLine + cliente.CapLegale + " " + cliente.ComuneLegale + " " + cliente.ProvinciaLegale).SetFontSize(9);
                        cellaGrigliaDest = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                        cellaGrigliaDest.Add(pGrigliaDest);
                        tbGriglaDest.AddCell(cellaGrigliaDest);

                        // PARTITA IVA DESTINATARIO
                        pGrigliaDest     = new iText.Layout.Element.Paragraph("P.Iva/C.F.").SetFontSize(9).SetBold();
                        cellaGrigliaDest = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                        cellaGrigliaDest.Add(pGrigliaDest);
                        tbGriglaDest.AddCell(cellaGrigliaDest);

                        string pIvaCF = cliente.PartitaIva;
                        if (string.IsNullOrEmpty(pIvaCF))
                        {
                            pIvaCF = cliente.CodiceFiscale;
                        }

                        pGrigliaDest     = new iText.Layout.Element.Paragraph(pIvaCF).SetFontSize(9);
                        cellaGrigliaDest = new iText.Layout.Element.Cell().SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                        cellaGrigliaDest.Add(pGrigliaDest);
                        tbGriglaDest.AddCell(cellaGrigliaDest);

                        document.Add(tbGriglaDest);

                        // AGGIUNGO LOGO DNV
                        iText.Layout.Element.Image logoDnv = new iText.Layout.Element.Image(imageDNV).ScaleAbsolute(40, 40).SetFixedPosition(i, 518, 8);
                        document.Add(logoDnv);

                        //AGGIUNGO NUM.PAGINA
                        document.ShowTextAligned(new iText.Layout.Element.Paragraph("pagina " + i.ToString() + " di " + n.ToString()).SetFontSize(7),
                                                 pageSize.GetWidth() - 60, pageSize.GetHeight() - 20, i, iText.Layout.Properties.TextAlignment.CENTER, iText.Layout.Properties.VerticalAlignment.TOP, 0);
                        //AGGIUNGO FOOTER
                        document.ShowTextAligned(new iText.Layout.Element.Paragraph(denominazioneVs + " P.IVA " + pIvaVs + Environment.NewLine + "Sede legale: " + toponimoVs + " " + indirizzoVs + " " + civicoVs + " - " + capVs + " " + cittaVs + " " + provinciaVs + " e-mail: " + emailVs).SetFontSize(7).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER),
                                                 pageSize.GetWidth() / 2, 30, i, iText.Layout.Properties.TextAlignment.CENTER, iText.Layout.Properties.VerticalAlignment.TOP, 0);

                        if (i == n)
                        {
                            // NELL'ULTIMA PAGINA AGGIUNGO LA GRIGLIA CON LE NOTE E IL TIMBRO
                            // CREAZIONE GRIGLIA
                            iText.Layout.Element.Table tbGriglaNoteFooter = new iText.Layout.Element.Table(new float[] { 80, 70, 180, 70, 30, 30, 70 }).SetWidth(530).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.LIGHT_GRAY, 10).SetFixedPosition(30, 50, 530).SetFixedLayout();

                            // PRIMA RIGA GRIGLIA NOTE FOOTER
                            iText.Layout.Element.Paragraph pGrigliaNoteFooter     = new iText.Layout.Element.Paragraph("Banca").SetFontSize(9);
                            iText.Layout.Element.Cell      cellaGrigliaNoteFooter = new iText.Layout.Element.Cell().SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                            cellaGrigliaNoteFooter.Add(pGrigliaNoteFooter);
                            tbGriglaNoteFooter.AddCell(cellaGrigliaNoteFooter);

                            pGrigliaNoteFooter = new iText.Layout.Element.Paragraph(noteOfferta.Banca).SetFontSize(9);
                            //cellaGrigliaNoteFooter = new iText.Layout.Element.Cell(1,2).SetBackgroundColor(iText.Kernel.Colors.ColorConstants.LIGHT_GRAY, 10).SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(2);
                            cellaGrigliaNoteFooter = new iText.Layout.Element.Cell(1, 2).SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorderRight(new iText.Layout.Borders.SolidBorder(iText.Kernel.Colors.ColorConstants.WHITE, 2, 50)).SetBorderTop(iText.Layout.Borders.Border.NO_BORDER).SetBorderLeft(iText.Layout.Borders.Border.NO_BORDER).SetBorderBottom(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);

                            cellaGrigliaNoteFooter.Add(pGrigliaNoteFooter);
                            tbGriglaNoteFooter.AddCell(cellaGrigliaNoteFooter);

                            pGrigliaNoteFooter     = new iText.Layout.Element.Paragraph("Timbro e firma per accettazione").SetFontSize(9);
                            cellaGrigliaNoteFooter = new iText.Layout.Element.Cell(1, 4).SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                            cellaGrigliaNoteFooter.Add(pGrigliaNoteFooter);
                            tbGriglaNoteFooter.AddCell(cellaGrigliaNoteFooter);

                            // SECONDA RIGA GRIGLIA NOTE FOOTER
                            pGrigliaNoteFooter     = new iText.Layout.Element.Paragraph("Pagamento").SetFontSize(9);
                            cellaGrigliaNoteFooter = new iText.Layout.Element.Cell().SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                            cellaGrigliaNoteFooter.Add(pGrigliaNoteFooter);
                            tbGriglaNoteFooter.AddCell(cellaGrigliaNoteFooter);

                            pGrigliaNoteFooter     = new iText.Layout.Element.Paragraph(noteOfferta.NotaPagamento).SetFontSize(9);
                            cellaGrigliaNoteFooter = new iText.Layout.Element.Cell(1, 2).SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorderRight(new iText.Layout.Borders.SolidBorder(iText.Kernel.Colors.ColorConstants.WHITE, 2, 50)).SetBorderTop(iText.Layout.Borders.Border.NO_BORDER).SetBorderLeft(iText.Layout.Borders.Border.NO_BORDER).SetBorderBottom(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                            cellaGrigliaNoteFooter.Add(pGrigliaNoteFooter);
                            tbGriglaNoteFooter.AddCell(cellaGrigliaNoteFooter);

                            pGrigliaNoteFooter     = new iText.Layout.Element.Paragraph(" ").SetFontSize(9);
                            cellaGrigliaNoteFooter = new iText.Layout.Element.Cell(1, 4).SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                            cellaGrigliaNoteFooter.Add(pGrigliaNoteFooter);
                            tbGriglaNoteFooter.AddCell(cellaGrigliaNoteFooter);

                            // TERZA RIGA GRIGLIA NOTE FOOTER
                            pGrigliaNoteFooter     = new iText.Layout.Element.Paragraph("Consegna").SetFontSize(9);
                            cellaGrigliaNoteFooter = new iText.Layout.Element.Cell().SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                            cellaGrigliaNoteFooter.Add(pGrigliaNoteFooter);
                            tbGriglaNoteFooter.AddCell(cellaGrigliaNoteFooter);

                            pGrigliaNoteFooter     = new iText.Layout.Element.Paragraph(noteOfferta.Consegna.Replace("\r\n", " ")).SetFontSize(9);
                            cellaGrigliaNoteFooter = new iText.Layout.Element.Cell(1, 2).SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorderRight(new iText.Layout.Borders.SolidBorder(iText.Kernel.Colors.ColorConstants.WHITE, 2, 50)).SetBorderTop(iText.Layout.Borders.Border.NO_BORDER).SetBorderLeft(iText.Layout.Borders.Border.NO_BORDER).SetBorderBottom(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                            cellaGrigliaNoteFooter.Add(pGrigliaNoteFooter);
                            tbGriglaNoteFooter.AddCell(cellaGrigliaNoteFooter);

                            pGrigliaNoteFooter     = new iText.Layout.Element.Paragraph(" ").SetFontSize(9);
                            cellaGrigliaNoteFooter = new iText.Layout.Element.Cell(1, 4).SetBackgroundColor(coloreIntestazioni, 0.7f).SetBorder(iText.Layout.Borders.Border.NO_BORDER).SetPadding(5);
                            cellaGrigliaNoteFooter.Add(pGrigliaNoteFooter);
                            tbGriglaNoteFooter.AddCell(cellaGrigliaNoteFooter);

                            document.Add(tbGriglaNoteFooter);
                        }
                    }

                    document.Close();
                    wr.Close();

                    if (File.Exists(mapPathOfferta))
                    {
                        // SE FILE OK INSERISCO O AGGIORNO PROTOCOLLO DI TIPO PIANO ESTERNO
                        if (listaProtocolli.Count == 0)
                        {
                            //INSERISCO
                            protocolloOfferta.Attivo                  = true;
                            protocolloOfferta.Cliente                 = cliente.RagioneSociale.Trim();
                            protocolloOfferta.Codice_lavoro           = eventoSelezionato.codice_lavoro;
                            protocolloOfferta.Data_inizio_lavorazione = eventoSelezionato.data_inizio_impegno;
                            protocolloOfferta.Data_protocollo         = DateTime.Today;
                            protocolloOfferta.Descrizione             = "Offerta";
                            protocolloOfferta.Id_cliente              = eventoSelezionato.id_cliente;
                            protocolloOfferta.Id_tipo_protocollo      = idTipoProtocollo;
                            protocolloOfferta.Lavorazione             = eventoSelezionato.lavorazione;
                            protocolloOfferta.PathDocumento           = Path.GetFileName(mapPathOfferta);
                            protocolloOfferta.Produzione              = eventoSelezionato.produzione;
                            protocolloOfferta.Protocollo_riferimento  = "";
                            protocolloOfferta.Numero_protocollo       = numeroProtocollo;
                            protocolloOfferta.Pregresso               = false;
                            protocolloOfferta.Destinatario            = "Cliente";

                            int idProtPianoEsterno = Protocolli_BLL.Instance.CreaProtocollo(protocolloOfferta, ref esito);
                        }
                        else
                        {
                            // AGGIORNO
                            protocolloOfferta.PathDocumento = Path.GetFileName(mapPathOfferta);
                            esito = Protocolli_BLL.Instance.AggiornaProtocollo(protocolloOfferta);
                        }

                        framePdf.Attributes.Remove("src");
                        framePdf.Attributes.Add("src", pathOfferta.Replace("~", ""));

                        DivFramePdf.Visible = true;
                        framePdf.Visible    = true;

                        ScriptManager.RegisterStartupScript(Page, typeof(Page), "aggiornaFrame", script: "javascript: document.getElementById('" + framePdf.ClientID + "').contentDocument.location.reload(true);", addScriptTags: true);
                        btnStampaOfferta.Attributes.Add("onclick", "window.open('" + pathOfferta.Replace("~", "") + "');");
                        //}
                    }
                    else
                    {
                        esito.Codice      = Esito.ESITO_KO_ERRORE_GENERICO;
                        esito.Descrizione = "Il File " + pathOfferta.Replace("~", "") + " non รจ stato creato correttamente!";
                    }
                }
            }
            catch (Exception ex)
            {
                esito.Codice      = Esito.ESITO_KO_ERRORE_GENERICO;
                esito.Descrizione = "popolaPannelloRiepilogo(DatiAgenda eventoSelezionato) " + ex.Message + Environment.NewLine + ex.StackTrace;
            }

            return(esito);
        }
        private void MovePDFsWOptionToSign(bool toBeSigned)
        {
            string tempFile   = "";
            int    file_count = 1;

            string[] oldFiles = Directory.GetFiles(directory);
            string   userName;

            if (user.DomainName == "dsachuk")
            {
                userName = "******";
            }
            else
            {
                userName = user.DomainName;
            }
            string path = user.EmployeeCode == "E4408" ? @"\\nshare\users\" + userName + @"\WorkOrdersToPrint\" : @"C:\Users\" + userName + @"\Desktop\WorkOrdersToPrint\";

            foreach (TextBlock textBlock in ListBox1.ItemsSource)
            {
                string file         = directory + "\\" + textBlock.Text.ToString() + ".pdf";
                string woFolderName = directory.Remove(0, directory.LastIndexOf("\\") + 1);
                // Delete files already in the folder to move to on first loop
                if (tempFile == "")
                {
                    string[] filesAlreadyInDirectory = Directory.GetFiles(path, "*" + woFolderName + "*");
                    foreach (string fileToDelete in filesAlreadyInDirectory)
                    {
                        File.Delete(fileToDelete);
                    }
                }

                tempFile = System.IO.Path.GetTempFileName();
                if (toBeSigned)
                {
                    string      oldFile     = oldFiles.First(path => System.IO.Path.GetFileName(path).StartsWith(textBlock.Text.ToString()) && System.IO.Path.GetFileName(path).Contains("_M") == textBlock.Text.ToString().Contains("_M"));
                    PdfDocument pdfDocument = new PdfDocument(new PdfReader(oldFile), new PdfWriter(tempFile));
                    int         page_count  = pdfDocument.GetNumberOfPages();
                    Document    document    = new Document(pdfDocument);
                    for (int i = 1; i <= page_count; i++)
                    {
                        ImageData imageData = ImageDataFactory.Create(@"C:\Users\" + userName + @"\Desktop\John Hancock.png");
                        iText.Layout.Element.Image image = new iText.Layout.Element.Image(imageData).ScaleAbsolute(22, 22)
                                                           .SetFixedPosition(i, user.SignatureLeft, user.SignatureBottom);
                        document.Add(image);
                    }
                    document.Close();
                    File.Move(tempFile, file, true);
                    File.Copy(file, path + woFolderName + "_" + file_count + ".pdf", true);
                    if (file != oldFile)
                    {
                        File.Delete(oldFile);
                    }
                }
                else
                {
                    File.Copy(file, path + woFolderName + "_" + file_count + ".pdf", true);
                }
                file_count++;
            }
        }