using System;
using System.Collections.Generic;
using System.Text;
using ceTe.DynamicPDF;
using PDFGenerator.BusinessLayer;
using System.IO;
using System.Collections;
using PDFGenerator.BusinessLayer.DataSection;
using ceTe.DynamicPDF.Merger;
using Dundas.Charting.WebControl;
using ceTe.DynamicPDF.PageElements;
using ceTe.DynamicPDF.Text;
using System.Data;
using PDFGenerator.Presentation.TemplateGenerator;
using ContrattoSei.Utilities;
using System.Threading;

namespace PDFGenerator
{
    public class DocumentPDF
    {

        private string _tipologia;
        ArrayList _index;
        ArrayList _core;
        int _indexPage;
        int _corePage;
        int _currentPage;
        float _margineUP;
        float _pageHeight;
        float _margineDOWN;
        float _margineLEFT;
        float _margineRIGHT;
        float _writableYPot;
        float _indiceY;
        float _writableY;
        int _sectionSpace;
        int _numlastpage;
       // bool _navigatore;
        bool _glossario;
        //bool _copertina;
        bool _activeIndex;
        MergeDocument _documentoFinale;
        DataSetIndice _strutturaIndice;
        MemoryStream _imgGrafico;
        int _chapterNum;
        int _sectionNum;
        private Document _document;
        private ReportType _reportType;
        DataThread _dataThread;
        private OpenTypeFont _verdana, _verdanaBold, _verdanaItalic, _verdanaBoldItalic;
        private ImportedPage _page, _indice, _backPage;
        private float _writableYold;
        private byte[] _data;
        private string _banca;
        private string _notaPieDiPagina;
        /// <summary>
        /// indica se la nota a pi� di pagina � presente.
        /// </summary>
        private bool _flagnotaPieDiPagina;
        //private List<Nota> _note;
        private bool _saltoPagina;
        private string _AsteriscoVarProxato;
        private string _AsteriscoGradoCopertura;
        private int _numNotePiePaginaVarProxato = 0;

        private ListaNote _note = new ListaNote();
        private float _ynotapiedipagina = 740;

        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();


        public DocumentPDF(DataThread dataThread, string tipoReport)
        {
            #region region
            _dataThread = dataThread;
            _index = new ArrayList();
            _core = new ArrayList();
            _indexPage = 0;
            _corePage = 0;
            _currentPage = 0;
            _margineUP = 160;
            _pageHeight = 841.9F;
            _margineDOWN = 105;
            _margineLEFT = 42;
            _margineRIGHT = 259;
            _writableYPot = 0;
            _sectionSpace = 30;
            _numlastpage = -1;
           // _navigatore = false;
            _glossario = false;
           // _copertina = false;
            _activeIndex = false;
            _strutturaIndice = new DataSetIndice();
            _imgGrafico = new System.IO.MemoryStream();
            _documentoFinale = new MergeDocument();
            _chapterNum = 0;
            _sectionNum = 0;
            //_data = null;
            _document = new Document();
            _reportType = _dataThread.ReportsType.Find(delegate (ReportType r) { return r.Descrizione.ToUpper() == tipoReport; });
            _document.Title = _reportType.Descrizione;
            _document.CompressionLevel = 9;
            _AsteriscoVarProxato = "";
            _AsteriscoGradoCopertura = "";

            string licenza = UtilityManager.getAppSetting("Licenza");
            try
            {
                bool isValid = ceTe.DynamicPDF.Document.AddLicense(licenza);
            }
            catch (Exception ex)
            {
                try { 
                logger.Error(string.Concat(ex.Message," ", dataThread.CodiceFiscale));
                }
                catch { }
                throw;
            }
            // Create a standard security object 
            StandardSecurity security = new StandardSecurity();

            // Set the permissions on that security object 
            //security.AllowPrint = false;
            security.AllowCopy = false;
            security.AllowEdit = false;

            // Add the security object to the document 
            _document.Security = security;
            _document.PdfVersion = PdfVersion.v1_4;
            _document.PdfXVersion = PdfXVersion.PDF_X_3_2003;

            System.Reflection.Assembly thisExe;
            thisExe = System.Reflection.Assembly.GetExecutingAssembly();
            string relativePath = UtilityManager.getAppSetting("ICCprofile");
            System.IO.Stream file = thisExe.GetManifestResourceStream(relativePath);

            IccProfile iccProfile = new IccProfile(file);
            string configurationPath1 = UtilityManager.getAppSetting("ICCconfiguration");
            string configurationPath2 = UtilityManager.getAppSetting("ICCconfiguration1");
            string configurationPath3 = UtilityManager.getAppSetting("ICCconfiguration2");
            string configurationPath4 = UtilityManager.getAppSetting("ICCconfiguration3");
            OutputIntent outputIntent = new OutputIntent(configurationPath1, configurationPath2, configurationPath3, configurationPath4, iccProfile);
            _document.OutputIntents.Add(outputIntent); // Patryk Prepress
            _document.Trapped = Trapped.False; // Patryk Prepress
            _writableY = _margineUP;

            //Creo il PDF
            this.createFont();
            this.addPage();
            #endregion
        }

        private void SetTemplate(ImportedPage p)
        {
            p.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("REPORT " + _document.Title.ToUpper(), 38, 43, 250, 12, _verdanaBold, 11, ceTe.DynamicPDF.CmykColor.Red));
            p.Elements.Add(new PageNumberingLabel("pagina %%SP%% di %%ST%%", 0, 820, 542, 12, _verdana, 7, ceTe.DynamicPDF.TextAlign.Right));
        }

        public void insertCliente()
        {
            this.setPageFooterNomeCliente(_page);
        }

        public ImportedPage getCurrentPage()
        {
            return _page;
        }

        public float getSectionSpace()
        {
            return _sectionSpace;
        }

        private void createFont()
        {
            // Create a TrueType font class.
            _verdana = Globals.OpenTypeFontVerdana;
            _verdanaBold = Globals.OpenTypeFontVerdanaB;
            _verdanaItalic = Globals.OpenTypeFontVerdanaZ;
            _verdanaBoldItalic = Globals.OpenTypeFontVerdanaZ;
        }



        /// <summary>
        /// Stampo le note aggiunte alla pagina (document).
        /// Stampo solamente quelle con posizionamento a "Pi�DiPagina" e Stato "DaStampare"
        /// 
        /// Questa funzione � richiamata dal metodo addPage. A differenza dell'altro overload di StampaNote,questo � richiamato quando non c'� salto pagina della tabella. 
        /// </summary>
        public void StampaNote()
        {
            // stampo le note a pi� di pagina prima di aggiungerne una nuova.

            //Ordinamento
            _note.Sort(delegate (Nota nota, Nota nota2) { return nota.NumeroAsterisco.CompareTo(nota2.NumeroAsterisco); });
            _note.Reverse();

            // distinct sul numero di asterischi.
            ListaNote newList = new ListaNote();

            foreach (Nota objNota in _note)
            {
                if (newList.Find(delegate (Nota nota) { return nota.NumeroAsterisco == objNota.NumeroAsterisco; }) == null)
                    newList.Insert(objNota);
            }
            _note = newList;


            foreach (Nota objNota in _note.FindAll(delegate (Nota t) { return t.Posizionamento == Nota.TipologiaPosizionamento.Pi�DiPagina && t.Stato == Nota.StatoNota.DaStampare; }))
            {
                // Per ora abbiamo solo note che sono o inferiori a 200 caratteri o di 254 (nota var proxato)
                // se la lunghezza delle note a pi� di pagina dovesse cambiare questa gestione va rivista.

                if (objNota.Testo.Length > 200)
                    _ynotapiedipagina -= 10;

                writeText(42, _ynotapiedipagina, objNota.Testo, 7, 512);

                objNota.Stato = Nota.StatoNota.Stampata; // Imposto la nota come gi� stampata

                if (objNota.Testo.Length < 200)
                    _ynotapiedipagina -= 12;
                else
                    _ynotapiedipagina -= 22;
            }
        }



        /// <summary>
        /// Stampo le note aggiunte alla pagina (document).
        /// Stampo solamente quelle con posizionamento a Pi�DiPagina 
        /// Stampo le note delle tabelle che stanno effettuando il saltopagina.
        /// 
        /// Qusta funzione � richiamata solo quando una tabella sta effettuando il "saltopagina" non imposto quindi lo Stato della Nota su "Stampata".
        /// </summary>
        /// <param name="idtabella"></param>
        public void StampaNote(string idtabella)
        {

            // stampo le note a pi� di pagina prima di aggiungerne una nuova.

            //Ordinamento
            _note.Sort(delegate (Nota nota, Nota nota2) { return nota.NumeroAsterisco.CompareTo(nota2.NumeroAsterisco); });
            _note.Reverse();

            // distinct sul numero di asterischi.
            ListaNote newList = new ListaNote();

            foreach (Nota objNota in _note)
            {
                if (newList.Find(delegate (Nota nota) { return nota.NumeroAsterisco == objNota.NumeroAsterisco; }) == null)
                    newList.Insert(objNota);
            }
            _note = newList;

            foreach (Nota objNota in _note.FindAll(delegate (Nota t) { return t.Posizionamento == Nota.TipologiaPosizionamento.Pi�DiPagina; }))
            {
                // Per ora abbiamo solo note che sono o inferiori a 200 caratteri o di 254 (nota var proxato)
                // se la lunghezza delle note a pi� di pagina dovesse cambiare questa gestione va rivista.

                if (objNota.Testo.Length > 200)
                    _ynotapiedipagina -= 10;

                writeText(42, _ynotapiedipagina, objNota.Testo, 7, 512);

                if (objNota.Testo.Length < 200)
                    _ynotapiedipagina -= 12;
                else
                    _ynotapiedipagina -= 22;

            }

        }


        private void addGlossario()
        {
            TemplateGenerator tg = new TemplateGenerator();
            ImportedPage[] glox = tg.getGlossario(_dataThread.TipoReport.ToUpper(), _dataThread.Rete.ToUpper(), _dataThread.TipoContratto);

            foreach (ImportedPage p in glox)
            {
                this.SetTemplate(p);
                this.setPageFooter(p);
                this.setPageFooterNomeCliente(p);
                _document.Pages.Add(p);
            }

            #region vecchio glossario
            //string pdfRelativePath = null;
            ////V Provvisorio in attesa di montare la nuova gestione del glossario anche per diagnosi
            //ImportedPage temp = null;

            //if (_dataThread.Rete.ToUpper() == "F")
            //    if(_dataThread.TipoReport.ToUpper() == "DIAGNOSI")
            //        pdfRelativePath = UtilityManager.getAppSetting("GlossarioBF");
            //    else {

            //        temp = tg.getGlossario(_dataThread.TipoReport.ToUpper(), _dataThread.Rete.ToUpper());

            //    }
            //        //pdfRelativePath = UtilityManager.getAppSetting("GlossarioBF_Monitoraggio");
            //else
            //    if (_dataThread.TipoReport.ToUpper() == "DIAGNOSI")
            //        pdfRelativePath = UtilityManager.getAppSetting("GlossarioSP");
            //    else
            //    {

            //        temp = tg.getGlossario(_dataThread.TipoReport.ToUpper(), _dataThread.Rete.ToUpper());
            //    }
            //        //pdfRelativePath = UtilityManager.getAppSetting("GlossarioSP_Monitoraggio");
            //System.Reflection.Assembly thisExe;
            //System.IO.Stream file = null;
            //if (pdfRelativePath != null) //GLOSSARIO DIAGNOSI Lo recupero dal template statico
            //{

            //    thisExe = System.Reflection.Assembly.GetExecutingAssembly();

            //    file = thisExe.GetManifestResourceStream(pdfRelativePath);

            //    //PdfDocument PPP = new PdfDocument("C:\\Templ_avvertenzeBF.pdf");
            //    PdfDocument pp = new PdfDocument(file);

            //    ImportedPage pg = null;
            //    for (int _indicePagina = 1; _indicePagina <= pp.Pages.Count; _indicePagina++)
            //    {
            //        pg = new ImportedPage(pp.GetPage(_indicePagina));
            //        this.SetTemplate(pg);
            //        this.setPageFooter(pg);
            //        this.setPageFooterNomeCliente(pg);

            //        _document.Pages.Add(pg);
            //    }
            //}
            //else //Glossario Monitoraggio generato dinamicamente
            //{
            //    ImportedPage pg = temp;

            //    this.SetTemplate(pg);
            //    this.setPageFooter(pg);
            //    this.setPageFooterNomeCliente(pg);
            //    _document.Pages.Add(pg);


            //}



            //thisExe = System.Reflection.Assembly.GetExecutingAssembly();

            //if (_dataThread.Rete == "F")
            //    pdfRelativePath = UtilityManager.getAppSetting("TemplateAvvertenzeBF");
            //else
            //    pdfRelativePath = UtilityManager.getAppSetting("TemplateAvvertenzeSP");

            //file = thisExe.GetManifestResourceStream(pdfRelativePath);

            #endregion


            //PdfDocument pp1 = new PdfDocument(file);
            ImportedPage pg1 = tg.getAvvertenze(_dataThread.TipoReport.ToUpper(), _dataThread.Rete.ToUpper(), _dataThread.TipoContratto);//= new ImportedPage(pp1.GetPage(1));

            this.SetTemplate(pg1);
            this.setPageFooter(pg1);
            this.setPageFooterNomeCliente(pg1);
            _document.Pages.Add(pg1);


            _index.Add(_indice);
            _indiceY = _margineUP + 30;
            _activeIndex = true;

            _indexPage++;
            _indiceY = _margineUP;



        }

        //private void addNavigatore()
        //{
        //    string startDir = UtilityManager.getAppSetting("Path");
        //    string pdfRelativePath;

        //    if (_rete == "F")
        //        switch (_tipoReport.Trim())
        //        {
        //            case "DIAGNOSI":
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreBFDiagnosi");
        //                break;
        //            case "PIANIFICAZIONE":
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreBFPianificazione");
        //                break;
        //            case "PROPOSTA":
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreBFProposta");
        //                break;
        //            case "MONITORAGGIO":
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreBFMonitoraggio");
        //                break;
        //            default:
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreBFDiagnosi");
        //                break;
        //        }
        //    else
        //        switch (_tipoReport.Trim())
        //        {
        //            case "DIAGNOSI":
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreSPDiagnosi");
        //                break;
        //            case "PIANIFICAZIONE":
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreSPPianificazione");
        //                break;
        //            case "PROPOSTA":
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreSPProposta");
        //                break;
        //            case "MONITORAGGIO":
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreSPMonitoraggio");
        //                break;

        //            default:
        //                pdfRelativePath = UtilityManager.getAppSetting("NavigatoreSPDiagnosi");
        //                break;
        //        }

        //    PdfDocument pp = new PdfDocument(startDir + pdfRelativePath);

        //    for (int _indicePagina = 1; _indicePagina <= pp.Pages.Count; _indicePagina++)
        //    {
        //        ImportedPage pg = new ImportedPage(pp.GetPage(_indicePagina));
        //        //this.SetTemplate(pg);
        //        //this.setPageFooter(pg);
        //        //this.setPageFooterNomeCliente(pg);

        //        _index.Add(pg);
        //        _indexPage++;
        //    }
        //}

        /// <summary>
        /// Scrive nel Db lo streaming PDF come array di byte
        /// </summary>
        /// <param name="identificativo"></param>
        /// <returns>restituisce l'array di byte[] inserito nel db</returns>
        /// 


        public void deleteReportSuFileSystem(int idReport, string nomefile)
        {

            string targetFolder = getPdfForlder();

            string file = @targetFolder + idReport + "_" + nomefile + ".pdf";
            if (Directory.Exists(System.IO.Path.GetDirectoryName(file)))
            {
                File.Delete(file);
            }

        }

        public bool scriviSuFileSystem(int idReport)
        {
            string targetFolder = "";
            string tipoSalvataggioReport = UtilityManager.getAppSetting("SavePDFtoDISK");
            bool retValue = false;
            try
            {

                //Todo GEstione idReport = - 1 o = 0 ...errore in fase inserimento in GEstione_PDF_FTP

                switch (tipoSalvataggioReport)
                {
                    case "0":
                        // Salvataggio su DataBase ReportManager
                        // Parametro Attualmente Gestito nel metodo DocumentPDF.insertIntoDb()
                        retValue = true;
                        break;
                    case "1":
                        // Salvataggio su File SYstem
                        // Gestione test in locale e/o Generazione Campione
                        targetFolder = UtilityManager.getAppSetting("SavePDFtoDISK_Folder");
                        _documentoFinale.Draw(@targetFolder + _dataThread.TipoReport + "_" + _dataThread.CodiceFiscale + "_" + _dataThread.Rete + ".pdf");
                        retValue = true;
                        break;
                    case "2":
                        //_documentoFinale.Draw(@targetFolder + _dataThread.TipoReport + "_" + _dataThread.CodiceFiscale + "_" + _dataThread.Rete + ".pdf");
                        targetFolder = getPdfForlder();
                        _documentoFinale.Draw(@targetFolder + idReport + "_" + _dataThread.NomeFileReport + ".pdf");
                        retValue = true;
                        break;
                    default:
                        break;
                }

                return retValue;
            }
            catch (Exception ex)
            {
                try { 
                logger.Error(String.Concat(ex.Message, " ", idReport.ToString()));
                }
                catch { }
                return false;
            }
        }
        public int insertIntoDB()
        {


            //if (UtilityManager.getAppSetting("SavePDFtoDISK") == "1")
            //    return 0;
            string saveToDisk = UtilityManager.getAppSetting("SavePDFtoDISK");
            switch (saveToDisk)
            {
                case "1":
                    return 0;
                case "2":
                    //pk dave
                    //break;
                    return 0;
                default:
                    return 0;
                    //break;
            }

            List<Parametro> listaParametri = new List<Parametro>();

            Parametro CodiceContratto = new Parametro();
            CodiceContratto.ParameterName = "CodiceContratto";
            CodiceContratto.DbType = DbType.String;
            CodiceContratto.Value = _dataThread.CodiceContratto;
            listaParametri.Add(CodiceContratto);

            Parametro Rete = new Parametro();
            Rete.ParameterName = "Rete";
            Rete.DbType = DbType.String;
            Rete.Value = _dataThread.Rete;
            listaParametri.Add(Rete);

            Parametro idCliente = new Parametro();
            idCliente.ParameterName = "CodiceFiscale";
            idCliente.DbType = DbType.String;
            idCliente.Value = _dataThread.CodiceFiscale;
            listaParametri.Add(idCliente);

            Parametro NomeCliente = new Parametro();
            NomeCliente.ParameterName = "NomeCliente";
            NomeCliente.DbType = DbType.String;
            NomeCliente.Value = _dataThread.NomeCliente;
            listaParametri.Add(NomeCliente);

            Parametro CognomeCliente = new Parametro();
            CognomeCliente.ParameterName = "CognomeCliente";
            CognomeCliente.DbType = DbType.String;
            CognomeCliente.Value = _dataThread.CognomeCliente;
            listaParametri.Add(CognomeCliente);

            Parametro utente = new Parametro();
            utente.ParameterName = "TipoReport";
            utente.DbType = DbType.String;
            utente.Value = _reportType.Descrizione;
            listaParametri.Add(utente);

            //V Inserito per i metadati
            Parametro codReport = new Parametro();
            codReport.ParameterName = "codReport";
            codReport.DbType = DbType.Int32;
            codReport.Value = _reportType.IdReport;
            listaParametri.Add(codReport);
            //

            Parametro img = new Parametro();
            img.ParameterName = "img";
            img.DbType = DbType.Binary;
            img.Value = this.getData();
            listaParametri.Add(img);

            Parametro CodicePB = new Parametro();
            CodicePB.ParameterName = "CodicePB";
            CodicePB.DbType = DbType.String;
            CodicePB.Value = _dataThread.Agente;
            listaParametri.Add(CodicePB);

            Parametro NomePB = new Parametro();
            NomePB.ParameterName = "NomePB";
            NomePB.DbType = DbType.String;
            NomePB.Value = _dataThread.NomeAgente;
            listaParametri.Add(NomePB);

            Parametro CognomePB = new Parametro();
            CognomePB.ParameterName = "CognomePB";
            CognomePB.DbType = DbType.String;
            CognomePB.Value = _dataThread.CognomeAgente;
            listaParametri.Add(CognomePB);

            Parametro NumeroPagine = new Parametro();
            NumeroPagine.ParameterName = "NumeroPagine";
            NumeroPagine.DbType = DbType.Int32;
            NumeroPagine.Value = _documentoFinale.Pages.Count;
            listaParametri.Add(NumeroPagine);


            Parametro Identificativo = new Parametro();
            Identificativo.ParameterName = "Identificativo";
            Identificativo.DbType = DbType.Int32;
            Identificativo.Value = _reportType.TipoReport == TipoReport.DIAGNOSI ? _dataThread.IdReportPDFDiagnosi : _dataThread.IdReportPDFMonitoraggio;
            listaParametri.Add(Identificativo);


            string queryInserimento = UtilityManager.getAppSetting("QueryInserimento");

            return Convert.ToInt32(DataAccess.ExecuteScalarStoredProcedure(DBProvider.SqlServer, queryInserimento, listaParametri));
            //  return DataAccess.ExecuteNonQueryStoredProcedure(DBProvider.SqlServer, queryInserimento, listaParametri);



            //else
            //{
            //    //V if it is daily run save always on the reporting online db
            //    if (UtilityManager.getAppSetting("Periodico") != "1")
            //        return DataAccess.ExecuteNonQueryStoredProcedure(DBProvider.SqlServer, queryInserimento, listaParametri);
            //    else
            //        return DataAccess.ExecuteNonQueryStoredProcedure(DBProvider.SqlServerStampeC6, queryInserimento, listaParametri);
            //}

        }

        public void inserisciLettera()
        {
            byte[] pdf = this.getData();
            // Create two PDF document objects
            PdfDocument pdfA;
            GestoreLettera letter = new GestoreLettera(_dataThread.DataAccess);
            letter.RestGestoreLettera();            
            if (UtilityManager.getAppSetting("Periodico") != "1")
            {

                if (_dataThread.AdesioneSuccessivaAvanzato || _dataThread.ContrattoOld)
                    pdfA = new PdfDocument(letter.componiLetteraBenvenuto(_dataThread.CodiceFiscale, _dataThread.Rete, TipoLettera.LetteraAccettazioneAttivazioneSeiPosticipata, _dataThread.TipoContratto, LetteraAccompagnamento.TipoReport.Diagnosi));
                else
                    pdfA = new PdfDocument(letter.componiLetteraBenvenuto(_dataThread.CodiceFiscale, _dataThread.Rete, TipoLettera.LetteraAccettazioneConAttivazioneSei, _dataThread.TipoContratto, LetteraAccompagnamento.TipoReport.Diagnosi));
            }
            else
            {
                if (_dataThread.TipoReport.ToUpper().Trim() == "DIAGNOSI")
                    pdfA = new PdfDocument(letter.componiLetteraAccompagnamento(_dataThread.CodiceFiscale, _dataThread.Rete, _dataThread.TipoContratto, LetteraAccompagnamento.TipoReport.Diagnosi));
                else
                    pdfA = new PdfDocument(letter.componiLetteraAccompagnamento(_dataThread.CodiceFiscale, _dataThread.Rete, _dataThread.TipoContratto, LetteraAccompagnamento.TipoReport.Monitoraggio));
            }
            PdfDocument pdfB = new PdfDocument(pdf);
            //pdfA = new PdfDocument(LetteraBA.GetLetteraBA(_dataThread));
            // Merge the two documents
            _documentoFinale = MergeDocument.Merge(pdfA, pdfB);

            // Save the PDF
            _data = _documentoFinale.Draw();


            //if ((UtilityManager.getAppSetting("SavePDFtoDISK") == "1")) 
            //{// solo quando scrivo sul File System
            //    string targetFolder = UtilityManager.getAppSetting("SavePDFtoDISK_Folder");
            //    _documentoFinale.Draw(@targetFolder + _dataThread.TipoReport + "_" + _dataThread.CodiceFiscale + "_" + _dataThread.Rete + ".pdf");
            //}

            // ToDo FC : spostato dopo inserimento in tabella GESTIONE_PDF_FTP
            // Gestione Salvataggio report file PDF

            //string targetFolder = "";
            //string nomeFileReport ="";
            //string tipoSalvataggioReport = UtilityManager.getAppSetting("SavePDFtoDISK");
            //switch (tipoSalvataggioReport)
            //{
            //    case "0":
            //        // Salvataggio su DataBase ReportManager
            //        // Parametro Attualmente Gestito nel metodo DocumentPDF.insertIntoDb()
            //        break;
            //    case "1":
            //        // Salvataggio su File SYstem
            //        // Gestione test in locale e/o Generazione Campione
            //        targetFolder = UtilityManager.getAppSetting("SavePDFtoDISK_Folder");
            //        _documentoFinale.Draw(@targetFolder + _dataThread.TipoReport + "_" + _dataThread.CodiceFiscale + "_" + _dataThread.Rete + ".pdf");
            //        break;
            //    case "2":
            //        //_documentoFinale.Draw(@targetFolder + _dataThread.TipoReport + "_" + _dataThread.CodiceFiscale + "_" + _dataThread.Rete + ".pdf");
            //        targetFolder = getPdfForlder();
            //        _documentoFinale.Draw(@targetFolder +  _dataThread.NomeFileReport + ".pdf");
            //        break;
            //    default:
            //        break;
            //}  


        }


        public int getIdentityReport(string rete, string codicefiscale, string tipoReport)
        {
            List<Parametro> parametri = new List<Parametro>();
            Parametro parametro = new Parametro();
            parametro.ParameterName = "Rete";
            parametro.DbType = DbType.AnsiStringFixedLength;
            parametro.Value = rete;
            parametri.Add(parametro);

            parametro = new Parametro();
            parametro.ParameterName = "CodiceFiscale";
            parametro.DbType = DbType.String;
            parametro.Value = codicefiscale;
            parametri.Add(parametro);

            //FC Gestione Parallelizzazione Processi
            // idReport � gestito dalla SP inserimento Gestione_Pdf_Ftp

            parametro = new Parametro();
            parametro.ParameterName = "TipoReport";
            parametro.DbType = DbType.String;
            parametro.Value = tipoReport;
            parametri.Add(parametro);

            string queryInserimento = UtilityManager.getAppSetting("GetIdReport");
            //DataAccess.ExecuteNonQueryStoredProcedure(DBProvider.SqlServerStampeC6, queryInserimento, parametri);
            try
            {
                return Convert.ToInt32(_dataThread.DataAccess.ExecuteScalarStoredProcedure(DBProvider.SqlServerStampeC6, queryInserimento, parametri));
            }
            catch (Exception ex)
            {
                try { 
                logger.Error(String.Concat(ex.Message, " ", codicefiscale.ToString()));
                }
                catch { }
                return -1;
            }

        }



        private string getNomeFileReport(string pathFolder)
        {

            try
            {
                string nomeFile = pathFolder;
                //string tipoReport = "";
                //switch (_dataThread.TipoReport)
                //{
                 //   case "D":
                 //       tipoReport = "DP";
                 //       break;
                //    case "M":
                //        tipoReport = "MP";
                //        break;
                //    default:
                //        break;
                //}
                nomeFile = nomeFile + "_" + _dataThread.CodiceFiscale;
                //nomeFile = tipoReport;

                return nomeFile;
            }
            catch (Exception e)
            {
                try {
                    logger.Error(String.Concat(e.Message, " ", pathFolder.ToString()));
                }
                catch { }
                throw e;
            }
        }

        private static string getPdfForlder()
        {
            string pdfForder = "";
            try
            {

                pdfForder = UtilityManager.getAppSetting("pathFolder");

                //Da utilizzare solo se prevista gestione piu cartelle 

                //string sPathPdf = UtilityManager.getAppSetting("pathFolder");
                //string sDataLotto = DateTime.Now.ToString("yyyyMMdd");
                //string prefissoFolder = UtilityManager.getAppSetting("prefissoFolder");
                //string suffissoFolrder = UtilityManager.getAppSetting("suffissoFolder");

                //string pdfForder = sPathPdf + "\\" + prefissoFolder + "_" + sDataLotto + "_" + suffissoFolrder;

                //if (!Directory.Exists(pdfForder))
                //    Directory.CreateDirectory(pdfForder);

                return pdfForder;
            }
            catch (Exception e)
            {
                try { 
                logger.Error(String.Concat(e.Message, " ", pdfForder.ToString()));
                }
                catch { }
                throw e;
            }

        }


        /// <summary>
        /// ok
        /// </summary>
        /// <returns></returns>
        private byte[] getData()
        {
            if (_data == null)
            {
                //if (_tipologia == "report")
                //{
                this.completeIndice();
                //}
                for (int i = 0; i < _indexPage; i++)
                {
                    _document.Pages.Add((ImportedPage)_index[i]);
                }

                for (int i = 0; i < _core.Count; i++)
                {
                    _document.Pages.Add((ImportedPage)_core[i]);
                }

                if (_glossario)
                    this.addGlossario();

                _document.InitialPage = 1;

                //genero i byte
                _data = _document.Draw();
            }

            return _data;
        }

        //public void renderPDF()
        //{
        //    this.renderPDF(_document.Title + ".pdf");
        //}

        //public void renderPDF(string downloadAsFileName)
        //{

        //    byte[] data = this.getData();
        //    PdfDocument pdfDoc = new PdfDocument(data);

        //    MergeDocument mDoc = new MergeDocument(pdfDoc);

        //    mDoc.CompressionLevel = 9;

        //    if (downloadAsFileName == null)
        //        mDoc.DrawToWeb();
        //    else
        //        mDoc.DrawToWeb(downloadAsFileName);
        //}

        //public void renderPDFFromDB(int identificativo)
        //{
        //    this.renderPDFFromDB(identificativo, null);
        //}

        //public void renderPDFFromDB(int identificativo, string downloadAsFileName)
        //{
        //    PdfDocument pdfDoc = new PdfDocument(this.getDataFromDB(identificativo));
        //    MergeDocument mDoc = new MergeDocument(pdfDoc);
        //    mDoc.CompressionLevel = 9;
        //    if (downloadAsFileName == null)
        //        mDoc.DrawToWeb();
        //    else
        //        mDoc.DrawToWeb(downloadAsFileName);
        //}

        //private byte[] getDataFromDB(int identificativo)
        //{
        //    List<Parametro> listaParametri = new List<Parametro>();
        //    Parametro id = new Parametro();
        //    id.ParameterName = "id";
        //    id.DbType = DbType.Int32;
        //    id.Value = identificativo;
        //    listaParametri.Add(id);

        //    return (byte[])DataAccess.ExecuteScalarStoredProcedure(DBProvider.SqlServer, "sp_readPDFImage_New", listaParametri);
        //}
        //==============================================================
        public float getMargineLeft()
        {
            return _margineLEFT;
        }
        //==============================================================
        private float getMargineRight()
        {
            return _margineRIGHT;
        }
        //==============================================================
        public float getLastPos()
        {
            if (_writableYPot != 0)
                this.setLastPos(_writableYPot);
            return _writableY;
        }

        public float getLastPos(string combo)
        {
            //if(_writableYPot != 0;
            //    this.setLastPos(_writableYPot);
            //_writableYPot = 0;
            return _writableY;
        }

        //==============================================================
        public void setLastPos(float y)
        {
            //aggiorna la posizione da cui si pu� scrivere
            if (_saltoPagina && _currentPage < _corePage)
            {
                _page = _backPage;
                _currentPage = _corePage;
                _writableY = _margineUP + _writableYPot + _sectionSpace;
            }
            else
            {
                if (_writableYPot > y && y > 0)
                    _writableY += (_writableYPot + _sectionSpace);
                else
                    _writableY += (y + _sectionSpace);
            }
            _writableYold = _writableY;
            _saltoPagina = false;
            _writableYPot = 0;
        }
        //==============================================================
        public void setPotenzialeLastPos(float y, bool salto)
        {
            //aggiorna la posizione da cui si pu� scrivere
            _writableYPot = (y);
            _saltoPagina = salto;
        }
        //==============================================================
        public void returnLastPage()
        {
            //ritorno alla penultima pagina. Utile per il disegno delle sezioni in modalit� combo
            _writableY = _writableYold;
            _backPage = _page;
            _currentPage--;
            _page = (ImportedPage)_core[_core.Count - 2];
        }
        //==============================================================
        public void creaIndice()
        {
            string pdfRelativePath;

            //if (_tipologia != "report")
            //{
            //    if (_rete == "F")
            //        pdfRelativePath = UtilityManager.getAppSetting("Template");
            //    else
            //        pdfRelativePath = UtilityManager.getAppSetting("TemplateSP");
            //}
            //else
            //{
            System.Reflection.Assembly thisExe;
            thisExe = System.Reflection.Assembly.GetExecutingAssembly();

            if (_dataThread.Rete == "F")
                pdfRelativePath = UtilityManager.getAppSetting("TemplateReport");
            else
                pdfRelativePath = UtilityManager.getAppSetting("TemplateReportSP");
            //}

            System.IO.Stream file = thisExe.GetManifestResourceStream(pdfRelativePath);

            PdfDocument pp = new PdfDocument(file);
            _indice = new ImportedPage(pp.GetPage(1));
            _indice.Elements.Add(new ceTe.DynamicPDF.PageElements.Rectangle(37, 122, 330, 13, 0, ceTe.DynamicPDF.CmykColor.Red));
            _indice.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Indice", 50, 119, 100, 8, _verdanaBold, 15, ceTe.DynamicPDF.CmykColor.White));

            this.SetTemplate(_indice);
            this.setPageFooter(_indice);
            this.setPageFooterNomeCliente(_indice);
            _index.Add(_indice);
            _indiceY = _margineUP + 30;
            _activeIndex = true;
        }
        //==============================================================
        private void completeIndice()
        {
            _margineDOWN = 105;

            if (_activeIndex)
            {
                ImportedPage app = (ImportedPage)_index[_indexPage];
                //int indexCount = _indexPage + 1; //uno per le avvertenze sistemare
                //V 
                int indexCount = _indexPage;
                //
                //if (_strutturaIndice.VoceIndice.Rows.Count > 25)
                //    //Era 2
                //    indexCount += 2;
                //else
                indexCount += 1;

                _indexPage++;

                int FontSizeIndice = 10;//12
                int interline = 14;//20

                //completa _indice
                foreach (DataSetIndice.VoceIndiceRow newVoce in _strutturaIndice.VoceIndice)
                {
                    if (_indiceY > (_pageHeight - (_margineDOWN + 50)))
                    {
                        this.creaIndice();
                        _indexPage++;
                        app = (ImportedPage)_index[_indexPage - 1];
                    }

                    if (newVoce.Tipologia == "chapter")
                    {
                        app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(newVoce.Titolo, 50, _indiceY, 500, 12, _verdanaBold));
                        app.Elements.Add(new PageNumberingLabel(Convert.ToString(newVoce.Pagina + indexCount), 0, _indiceY, 550, 12, _verdanaBold, FontSizeIndice, ceTe.DynamicPDF.TextAlign.Right));
                    }
                    else
                    {
                        app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(newVoce.Titolo, 80, _indiceY, 500, 12, _verdana, FontSizeIndice - 1));//11
                        app.Elements.Add(new PageNumberingLabel(Convert.ToString(newVoce.Pagina + indexCount), 0, _indiceY, 550, 12, _verdana, FontSizeIndice, ceTe.DynamicPDF.TextAlign.Right));
                    }

                    _indiceY += interline;//20
                }

                if (_glossario)
                {
                    app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Glossario", 50, _indiceY, 500, 12, _verdanaBold));
                    //app.Elements.Add(new PageNumberingLabel(Convert.ToString(_core.Count + indexCount + 2), 0, _indiceY, 550, 12, _verdanaBold, 12, ceTe.DynamicPDF.TextAlign.Right));
                    app.Elements.Add(new PageNumberingLabel(Convert.ToString(_core.Count + indexCount + 1), 0, _indiceY, 550, 12, _verdanaBold, FontSizeIndice, ceTe.DynamicPDF.TextAlign.Right));
                }

            }
            //else
            //    addNavigatore();


            ///Aggiungo pagina delle AVVERTENZE
            ///V
            //string pdfRelativePath;

            //System.Reflection.Assembly thisExe;
            //thisExe = System.Reflection.Assembly.GetExecutingAssembly();

            //if (_dataThread.Rete == "F")
            //    pdfRelativePath = UtilityManager.getAppSetting("TemplateAvvertenzeBF");
            //else
            //    pdfRelativePath = UtilityManager.getAppSetting("TemplateAvvertenzeSP");

            //System.IO.Stream file = thisExe.GetManifestResourceStream(pdfRelativePath);


            //PdfDocument pp = new PdfDocument(file);
            //_indice = new ImportedPage(pp.GetPage(1));

            //this.SetTemplate(_indice);
            //this.setPageFooter(_indice);
            //this.setPageFooterNomeCliente(_indice);
            //_index.Add(_indice);
            //_indiceY = _margineUP + 30;
            //_activeIndex = true;

            //_indexPage++;
            //_indiceY = _margineUP;
            //V
        }
        //==============================================================

        public void creaCopertina(string report, bool withName)
        {

            string pdfRelativePath;
            FormatNum conv = new FormatNum();

            System.Reflection.Assembly thisExe;
            thisExe = System.Reflection.Assembly.GetExecutingAssembly();

            if (_dataThread.Rete == "F")
                pdfRelativePath = UtilityManager.getAppSetting("Copertina");
            else
                pdfRelativePath = UtilityManager.getAppSetting("CopertinaSP");

            System.IO.Stream file = thisExe.GetManifestResourceStream(pdfRelativePath);


            ImportedPage app;
            PdfDocument pp = new PdfDocument(file);

            app = new ImportedPage(pp.GetPage(1));
            app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(report.ToUpper(), 157, 231, 220, 8, _verdanaBold, 18, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.White));
            if (withName)
            {
                if (UtilityManager.getAppSetting("Periodico") == "1")
                    app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Report prodotto " + _dataThread.DataFineTrimestreCorrente.ToLongDateString() + " per ", 88, 265, 300, 8, _verdana, 9, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
                else
                    app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Report prodotto " + DateTime.Now.ToLongDateString() + " per ", 88, 265, 300, 8, _verdana, 9, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));



                if (_dataThread.CodiceFiscale.Length == 11)
                {
                    //persona giuridica
                    app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(conv.CapitalizeText(_dataThread.CognomeCliente) + " " + conv.CapitalizeText(_dataThread.NomeCliente), 88, 280, 300, 8, _verdanaBold, 9, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
                }
                else
                {
                    if (_dataThread.CodiceFiscale.Contains("@"))
                    {
                        // Fiduciaria
                        string[] codiceMandato = _dataThread.CodiceFiscale.Split('@');
                        app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(conv.CapitalizeText(_dataThread.CognomeCliente) + " " + conv.CapitalizeText(_dataThread.NomeCliente.Replace("$", "") + " - " + codiceMandato[1].ToString()), 88, 280, 300, 8, _verdanaBold, 9, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));

                    }
                    else
                    {
                        //persona fisica
                        app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(conv.CapitalizeText(_dataThread.NomeCliente) + " " + conv.CapitalizeText(_dataThread.CognomeCliente), 88, 280, 300, 8, _verdanaBold, 9, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));

                    }
                }
            }
            else
                app.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Report prodotto " + DateTime.Now.ToLongDateString(), 88, 265, 300, 8, _verdana, 9, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
            _index.Add(app);
            _indexPage++;
            //_copertina = true;
        }

        public void setPageTitolo(string label)
        {
            if (_writableY != _margineUP)
                this.addPage();

            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Rectangle(_margineLEFT - 5, 122, 400, 17, 0, ceTe.DynamicPDF.CmykColor.Red));

            if (_activeIndex)
            {
                _chapterNum++;
                _sectionNum = 1;
                updateIndice(label, "chapter");
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + ". " + label, _margineLEFT, 120, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));
            }
            else
            {
                //if (_tipologia != "report")
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT, 120, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));
                //else
                //{
                //    _chapterNum++;
                //    _sectionNum = 1;
                //    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + ". " + label, _margineLEFT, 120, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));
                //}
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="label"></param>
        /// <param name="eliminaspaziatura"></param>
        public void setPageTitolo(string label, bool eliminaspaziatura)
        {
            setPageTitolo(label);
            if (eliminaspaziatura)
                _writableY = 150;
        }


        public void setChapterTitolo(string label)
        {
            if ((_writableY + 100) > (_pageHeight - _margineDOWN))
                this.addPage();

            ///PER ALLINEARE IL TITOLO ALLA RIGA DELLA PAGINA
            if (_writableY == _margineUP)
                _writableY = 142;
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Rectangle(_margineLEFT - 5, _writableY - 20, 400, 17, 0, ceTe.DynamicPDF.CmykColor.Red));
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Rectangle(_margineLEFT - 5, _writableY - 20, 522, 0.4F, 0, ceTe.DynamicPDF.CmykColor.Red));

            if (_activeIndex)
            {
                _chapterNum++;
                _sectionNum = 1;
                updateIndice(label, "chapter");
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + ". " + label, _margineLEFT, _writableY - 22, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));
            }
            else
            {
                //if (_tipologia != "report")
                //    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT, _writableY - 22, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));
                //else
                //{
                _chapterNum++;
                _sectionNum = 1;
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + ". " + label, _margineLEFT, _writableY - 22, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));
                //}
            }
            _writableY += 20;

        }


        /// <summary>
        /// E' il titolo della pagina scritto bianco su sfondo rosso.
        /// A differenza di setPageTitolo si posiziona a seconda della posizione del cursore.
        /// il parametro Height � lo spazio necessario al disegno del titolo capitolo piu la prima sezione.
        /// </summary>
        /// <param name="label"></param>
        /// <param name="Height"></param>
        public void setChapterTitolo(string label, float Height, bool eliminaspaziatura)
        {
            this.setChapterTitolo(label, Height);

            if (eliminaspaziatura)
                _writableY -= 10;
        }


        public void setChapterTitolo(string label, float Height)
        {
            if ((_writableY + Height + 50) > (_pageHeight - _margineDOWN))
                this.addPage();

            ///PER ALLINEARE IL TITOLO ALLA RIGA DELLA PAGINA
            if (_writableY == _margineUP)
                _writableY = 142;
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Rectangle(_margineLEFT - 5, _writableY - 20, 400, 17, 0, ceTe.DynamicPDF.CmykColor.Red));
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Rectangle(_margineLEFT - 5, _writableY - 20, 522, 0.4F, 0, ceTe.DynamicPDF.CmykColor.Red));

            if (_activeIndex)
            {
                _chapterNum++;
                _sectionNum = 1;
                updateIndice(label, "chapter");
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + ". " + label, _margineLEFT, _writableY - 22, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));
            }
            else
            {
                //if (_tipologia != "report")
                //    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT, _writableY - 22, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));
                //else
                //{
                _chapterNum++;
                _sectionNum = 1;
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + ". " + label, _margineLEFT, _writableY - 22, 400, 8, _verdanaBold, 14, ceTe.DynamicPDF.CmykColor.White));
                //}
            }
            _writableY += 20;
        }

        public void setChapterHeader(string label)
        {
            int m = (int)((float)label.Length / 135) + 2;
            if (this.checkMargin((m - 1) * 20)) this.addPage();
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5, _writableY - 10, 520, m, new FontFamily("pipp", _verdana, _verdanaBold, _verdanaItalic, _verdanaBoldItalic), 9, false);
            text.Height = text.GetRequiredHeight();
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            _page.Elements.Add(text);
            _writableY += text.Height + 10;
        }

        /// <summary>
        /// Stampa il testo del paragrafo e elimina lo spazio tra il titolo del capitolo e il testo che viene stampato.
        /// Usato solo per la S57
        /// </summary>
        /// <param name="label"></param>
        public void setChapterHeader(string label, bool eliminaspaziatura)
        {
            setChapterHeader(label);
            if (eliminaspaziatura)
                _writableY -= 10;
        }

        public void setChapterHeader(string label, float height)
        {
            if (label != string.Empty)
            {
                int m = (int)((float)label.Length / 135) + 2;
                if (this.checkMargin((m - 1) * 20 + height)) this.addPage();
                FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5, _writableY - 10, 520, m, new FontFamily("pipp", _verdana, _verdanaBold, _verdanaItalic, _verdanaBoldItalic), 9, false);
                text.Height = text.GetRequiredHeight();
                text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
                _page.Elements.Add(text);
                _writableY += text.Height + 10;
            }
        }

        public void setChapterHeader(string label, int x, int width, float font)
        {
            int m = (int)((float)label.Length / 135) + 2;
            if (this.checkMargin((m - 1) * 20)) this.addPage();
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5 + x, _writableY - 10, width, m, new FontFamily("pipp", _verdana, _verdanaBold, _verdanaItalic, _verdanaBoldItalic), font, false);
            text.Height = text.GetRequiredHeight();
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            _page.Elements.Add(text);
            _writableY += text.Height + 10;
        }

        private void setPageFooterNomeCliente(ImportedPage pp)
        {
            FormatNum conv = new FormatNum();
            ////LATO SX
            //if (_modalitaAnonima == 1)
            //{
            //if (_tipologia != "report")
            //    pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Scheda prodotta " + DateTime.Now.ToLongDateString() + " sui dati di ", _margineLEFT - 5, _pageHeight - _margineDOWN + 15, 300, 8, _verdana, 8, ceTe.DynamicPDF.CmykColor.Black));
            //else

            if (UtilityManager.getAppSetting("Periodico") == "1")
                pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Report prodotto " + _dataThread.DataFineTrimestreCorrente.ToLongDateString() + " per ", _margineLEFT - 5, _pageHeight - _margineDOWN + 15, 300, 8, _verdana, 8, ceTe.DynamicPDF.CmykColor.Black));
            else
                pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Report prodotto " + DateTime.Now.ToLongDateString() + " per ", _margineLEFT - 5, _pageHeight - _margineDOWN + 15, 300, 8, _verdana, 8, ceTe.DynamicPDF.CmykColor.Black));

            if (_dataThread.CodiceFiscale.Length == 11)//persona giuridica
                pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(conv.CapitalizeText(_dataThread.CognomeCliente) + " " + conv.CapitalizeText(_dataThread.NomeCliente), _margineLEFT - 5, _pageHeight - _margineDOWN + 25, 300, 8, _verdanaBold, 8, ceTe.DynamicPDF.CmykColor.Black));
            else
            {
                if (_dataThread.CodiceFiscale.Contains("@")) // Fiduciaria
                {
                    string[] codiceMandato = _dataThread.CodiceFiscale.Split('@');
                    pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(conv.CapitalizeText(_dataThread.CognomeCliente) + " - " + codiceMandato[1], _margineLEFT - 5, _pageHeight - _margineDOWN + 25, 300, 8, _verdanaBold, 8, ceTe.DynamicPDF.CmykColor.Black));

                }
                else //persona fisica
                    pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(conv.CapitalizeText(_dataThread.NomeCliente) + " " + conv.CapitalizeText(_dataThread.CognomeCliente), _margineLEFT - 5, _pageHeight - _margineDOWN + 25, 300, 8, _verdanaBold, 8, ceTe.DynamicPDF.CmykColor.Black));
            }

            //}
            //else
            //{
            //    if (_tipologia != "report")
            //        pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Scheda prodotta " + DateTime.Now.ToLongDateString(), _margineLEFT - 5, _pageHeight - _margineDOWN + 15, 300, 8, _verdana, 8, ceTe.DynamicPDF.CmykColor.Black));
            //    else
            //        pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Report prodotto " + DateTime.Now.ToLongDateString(), _margineLEFT - 5, _pageHeight - _margineDOWN + 15, 300, 8, _verdana, 8, ceTe.DynamicPDF.CmykColor.Black));

            //}
        }

        public void setNotaPi�DiPagina(string label)
        {
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5, _pageHeight - _margineDOWN, 520, 20, new FontFamily("pipp", _verdana), 7, false);
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            text.Height = text.GetRequiredHeight();
            text.Y -= text.Height - 10;
            _page.Elements.Add(text);
            _margineDOWN += text.Height;
        }
        public void setNotaPi�DiPagina(string label, string id)
        {
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5, _pageHeight - _margineDOWN, 520, 20, new FontFamily("pipp", _verdana), 7, false);
            text.ID = id;
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            text.Height = text.GetRequiredHeight();
            text.Y -= text.Height - 10;

            //se l'elemento � stato gia inserito nella pagina non lo inserisco.
            PageElement element = null;
            element = _page.Elements.GetPageElementByID(id);

            if (element == null)
                _page.Elements.Add(text);

            _margineDOWN += text.Height;
        }

        private void setPageFooter(ImportedPage pp)
        {
            FormatNum conv = new FormatNum();

            //LATO DX
            pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Private Banker", _margineRIGHT, _pageHeight - _margineDOWN + 15, 300, 8, _verdanaBold, 8, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
            //V 
            string temp = ClsFunzioniGeneriche.FormattaIndirizzo(_dataThread.IndirizzoAgente);


            pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(conv.CapitalizeText(_dataThread.NomeAgente) + " " + conv.CapitalizeText(_dataThread.CognomeAgente), _margineRIGHT, _pageHeight - _margineDOWN + 25, 300, 8, _verdanaBold, 8, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
            pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(temp + " - " + _dataThread.CapAgente + " " + _dataThread.CittaAgente, _margineRIGHT, _pageHeight - _margineDOWN + 35, 300, 8, _verdana, 8, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
            pp.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("Tel " + _dataThread.TelefonoAgente, _margineRIGHT, _pageHeight - _margineDOWN + 45, 300, 8, _verdana, 8, ceTe.DynamicPDF.TextAlign.Right, ceTe.DynamicPDF.CmykColor.Black));
        }

        private void updateIndice(string label, string type)
        {
            DataSetIndice.VoceIndiceRow newVoce = _strutturaIndice.VoceIndice.NewVoceIndiceRow();

            //aggiorna _indice
            if (type == "chapter")
            {
                newVoce.Tipologia = "chapter";
                newVoce.Titolo = _chapterNum + ". " + label;
                newVoce.Pagina = _corePage;
            }
            else
            {
                newVoce.Tipologia = "Section";
                newVoce.Titolo = _chapterNum + "." + _sectionNum + " " + label;
                newVoce.Pagina = _corePage;
            }

            _strutturaIndice.VoceIndice.AddVoceIndiceRow(newVoce);
        }

        public void setSezHeader(string label)
        {
            int m = (int)((float)label.Length / 100) + 1;
            if (this.checkMargin((m - 1) * 20)) this.addPage();
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5, _writableY - 10, 520, m * 20, new FontFamily("pipp", _verdana, _verdanaBold, _verdanaItalic, _verdanaBoldItalic), 9, false);
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            text.Height = text.GetRequiredHeight();
            _page.Elements.Add(text);
            _writableY += text.Height + 10;
        }

        public void setSezFooter(string label, float y)
        {
            if (_writableYPot > y)
                y = _writableYPot;
            int m = (int)((float)label.Length / 100) + 1;
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5, _writableY + y, 520, m * 20, new FontFamily("pipp", _verdana), 7, false);
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            _page.Elements.Add(text);
            _writableY += (m * 10);
        }

        public void setSezFooter(string label, float y, float spaceX)
        {
            int m = (int)((float)label.Length / 100) + 1;
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5 + spaceX, _writableY + y, 520 - spaceX, m * 20, new FontFamily("pipp", _verdana), 7, false);
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            _page.Elements.Add(text);
            _writableY += (m * 10);
        }

        public void setSezFooter(string label, float y, float spaceX, float font)
        {
            int m = (int)((float)label.Length / 100) + 1;
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5 + spaceX, _writableY + y, 520 - spaceX, m * 20, new FontFamily("pipp", _verdana), font, false);
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            _page.Elements.Add(text);
            _writableY += (m * 10);
        }

        public void setHeaderSpace(int space)
        {
            _writableY += space;
        }
        //==============================================================
        public void setSezTitoloDiagnosi(string label)
        {
            if (this.checkMargin(50)) this.addPage();

            if (label != " " && label != "")
            {
                if (_activeIndex)
                {
                    updateIndice(label, "section");
                    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + "." + _sectionNum + " " + label, _margineLEFT, _writableY - 15, 530, 12, _verdanaBold, 12, ceTe.DynamicPDF.CmykColor.Black));
                    _sectionNum++;
                }
                else
                {
                    //if (_tipologia != "report")
                    //    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT, _writableY - 15, 530, 12, _verdanaBold, 12, ceTe.DynamicPDF.CmykColor.Black));
                    //else
                    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + "." + _sectionNum + " " + label, _margineLEFT, _writableY - 15, 530, 12, _verdanaBold, 12, ceTe.DynamicPDF.CmykColor.Black));
                    _sectionNum++;
                }

                _writableY += 25;

            }
        }
        public void setSezTitolo(string label)
        {
            if (this.checkMargin(50)) this.addPage();

            if (label != " " && label != "")
            {
                if (_activeIndex)
                {
                    updateIndice(label, "section");
                    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + "." + _sectionNum + " " + label, _margineLEFT, _writableY - 15, 530, 12, _verdanaBold, 11, ceTe.DynamicPDF.CmykColor.Black));
                    _sectionNum++;
                }
                else
                {
                    //if (_tipologia != "report")
                    //    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT, _writableY - 15, 530, 12, _verdanaBold, 12, ceTe.DynamicPDF.CmykColor.Black));
                    //else
                    _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(_chapterNum + "." + _sectionNum + " " + label, _margineLEFT, _writableY - 15, 530, 12, _verdanaBold, 11, ceTe.DynamicPDF.CmykColor.Black));
                    _sectionNum++;
                }

                //_writableY += 25;
                _writableY += 15;
            }
        }

        /// <summary>
        /// Scrive il titolo della sezione senza aggiungere l'indicizzazione.
        /// usato nella 102
        /// </summary>
        /// <param name="label"></param>
        public void setSezTitoloWithoutNumber(string label)
        {
            if (this.checkMargin(50))
                this.addPage();

            if (label != " " && label != "")
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT, _writableY - 15, 530, 12, _verdanaBold, 10, ceTe.DynamicPDF.CmykColor.Black));
            _writableY += 15;
        }

        /// <summary>
        /// Scrive il titolo del paragrafo in modalit� indicizzata.
        /// Elimina la spaziatura di 25 pixel tra il titolo e il testo successivo e lascia uno spazio di 10 pixel.
        /// </summary>
        /// <param name="label"></param>
        public void setSezTitolo(string label, bool eliminaspaziatura)
        {
            this.setSezTitolo(label);
            if (eliminaspaziatura)
                _writableY -= 15;

        }

        public void setSezTitolo(string label, float Height)
        {
            if ((_writableY + Height + 20) > (_pageHeight - _margineDOWN))
                this.addPage();

            this.setSezTitolo(label);
        }
        //==============================================================
        public void setTitolo(string label, float Height)
        {
            if (label != string.Empty)
            {
                if ((_writableY + Height + 20) > (_pageHeight - _margineDOWN))
                    this.addPage();
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT - 5, _writableY - 15, 530, 12, _verdanaBold, 12, ceTe.DynamicPDF.CmykColor.Black));
                _writableY += 25;
            }
        }
        //==============================================================

        /// <summary>
        /// Scrive il titolo del paragrafo in modalit� non indicizzata. 
        /// Aggiunge 25 pixel di spazio sulla Y.
        /// </summary>
        /// <param name="label"></param>
        public void setTitolo(string label)
        {
            if (this.checkMargin(60)) this.addPage();
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(label, _margineLEFT - 5, _writableY - 15, 530, 12, _verdanaBold, 12, ceTe.DynamicPDF.CmykColor.Black));
            _writableY += 25;
        }


        /// <summary>
        /// Scrive sulla pagina il testo passato in input.
        /// Il tipo di carattere usato � quello del testo introduttivo delle sezioni.
        /// Dimensione del carattere prefissata a 7
        /// </summary>
        /// <param name="label">testo da scrivere</param>
        /// <param name="y">y su cui verr� scritto il testo</param>
        /// <param name="spaceX">larghezza della label su cui verr� scritto il testo.</param>
        public void writeText(string label, float y, float spaceX)
        {
            int m = (int)((float)label.Length / 100) + 1;
            FormattedTextArea text = new FormattedTextArea(label, _margineLEFT - 5 + spaceX, y, 520 - spaceX, m * 20, new FontFamily("pipp", _verdana), 7, false);
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            _page.Elements.Add(text);
        }

        public void writeText(float x, float y, string label, float size, float larghezzalabel, ceTe.DynamicPDF.TextAlign align)
        {
            int m = (int)((float)label.Length / 100) + 1;
            FormattedTextArea text = new FormattedTextArea(label, x, y, larghezzalabel, m * 20, new FontFamily("pipp", _verdana), size, false);
            text.Style.Paragraph.Align = align;
            _page.Elements.Add(text);
        }


        /// <summary>
        /// Scrive sulla pagina il testo passato in input.
        /// Il tipo di carattere usato � quello del testo introduttivo delle sezioni.
        /// Larghezza della label su cui verr� scritto il testo fissato a 200
        /// </summary>
        /// <param name="x">x</param>
        /// <param name="y">y</param>
        /// <param name="label">testo da scrivere</param>
        /// <param name="size">dimensione del testo</param>
        public void writeText(float x, float y, string label, float size)
        {
            int m = (int)((float)label.Length / 100) + 1;
            FormattedTextArea text = new FormattedTextArea(label, x, y, 200, m * 20, new FontFamily("pipp", _verdana), size, false);
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            _page.Elements.Add(text);
        }

        /// <summary>
        /// Scrive sulla pagina il testo passato in input.
        /// Il tipo di carattere usato � quello del testo introduttivo delle sezioni.
        /// Larghezza della label su cui verr� scritto il testo fissato a 200
        /// </summary>
        /// <param name="x">x</param>
        /// <param name="y">y</param>
        /// <param name="label">testo da scrivere</param>
        /// <param name="size">dimensione del testo</param>
        /// <param name="larghezzalabel">larghezza della label su cui viene scritto il testo.</param>
        public void writeText(float x, float y, string label, float size, float larghezzalabel)
        {
            int m = (int)((float)label.Length / 100) + 1;
            FormattedTextArea text = new FormattedTextArea(label, x, y, larghezzalabel, m * 20, new FontFamily("pipp", _verdana), size, false);
            text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            _page.Elements.Add(text);
        }

        public void InsertGraficoS96(Chart grafico, float x, float y)
        {
            try { 
            _imgGrafico = new System.IO.MemoryStream();
            //Preserve the orginal width and height for the Chart

            float w = (float)(grafico.Width.Value);
            float h = (float)grafico.Height.Value;

            //Set the sutiable chart resoltion -- default is 96 DPI
            grafico.ImageResolution = 300;
            //save the chart as image
            grafico.Save(_imgGrafico, ChartImageFormat.Png);
            Image img = new Image(_imgGrafico, x, y, 1);
            //set the orginal width and height to the chart image
            img.Width = w;
            img.Height = h;
            _page.Elements.Add(img);
            }
            catch (Exception ex)
            {
                try { 
                logger.Error(String.Concat(ex.Message, " ", grafico.ToString()));
                }
                catch { }
            }
            finally
            {
                grafico.Dispose();
            }

        }


        public void InsertGraficoS169(Chart grafico, float x, float y)
        {
            try { 
            _imgGrafico = new System.IO.MemoryStream();
            //Preserve the orginal width and height for the Chart

            float w = (float)(grafico.Width.Value);
            float h = (float)grafico.Height.Value;

            //Set the sutiable chart resoltion -- default is 96 DPI
            grafico.ImageResolution = 300;
            //save the chart as image
            grafico.Save(_imgGrafico, ChartImageFormat.Png);
            Image img = new Image(_imgGrafico, x, y, 1);
            //set the orginal width and height to the chart image
            img.Width = w;
            img.Height = h;
            _page.Elements.Add(img);
            }
            catch (Exception ex)
            {
                try { 
                logger.Error(String.Concat(ex.Message, " ", grafico.ToString()));
                }
                catch { }
            }
            finally
            {
                grafico.Dispose();
            }

        }

        public void InsertGraficoS132(Chart grafico, float x, float y)
        {
            try{ 
            _imgGrafico = new System.IO.MemoryStream();
            //Preserve the orginal width and height for the Chart

            float w = (float)(grafico.Width.Value);
            float h = (float)grafico.Height.Value;

            //Set the sutiable chart resoltion -- default is 96 DPI
            grafico.ImageResolution = 300;
            //save the chart as image
            grafico.Save(_imgGrafico, ChartImageFormat.Png);
            Image img = new Image(_imgGrafico, x, y, 1);
            //set the orginal width and height to the chart image
            img.Width = w;
            img.Height = h;
            _page.Elements.Add(img);
            }
            catch (Exception ex)
            {
                try { 
                logger.Error(String.Concat(ex.Message, " ", grafico.ToString()));
                }
                catch { }
            }
            finally
            {
                grafico.Dispose();
            }

        }


        public void InsertGrafico(Chart grafico, float x, float y, int resolution)
        {
            try
            {
                
                Image img = null;
                //Preserve the orginal width and height for the Chart
                float w = (float)(grafico.Width.Value);
                float h = (float)grafico.Height.Value;
                //Set the sutiable chart resoltion -- default is 96 DPI
                grafico.ImageResolution = resolution;
                using (System.IO.Stream _imgGrafico_ = new System.IO.MemoryStream())
                {
                    //save the chart as image
                    grafico.Save(_imgGrafico_, ChartImageFormat.Png);
                    //grafico.Save(@"C:\Ftp\a"+Guid.NewGuid().ToString()+".png", ChartImageFormat.Png);
                    //Thread.Sleep(100);                   
                    img = new Image(_imgGrafico_, x, y, 1);
                    img.Width = w;
                    img.Height = h;
                }
                //set the orginal width and height to the chart image
                _page.Elements.Add(img);
            }
            catch (Exception ex)
            {
                try { 
                logger.Error(String.Concat(ex.Message, " ", grafico.ToString()));
                }
                catch { }
            }
            finally
            {
                grafico.Dispose();
            }

        }

        public void InsertGrafico(Chart grafico, float x, float y)
        {
            _imgGrafico = new System.IO.MemoryStream();
            grafico.Save(_imgGrafico, ChartImageFormat.Png);
            Image img = new Image(_imgGrafico, x, y, 1);
            //img.SetDpi(300);
            _page.Elements.Add(img);
        }

        public void Grilia(int R)
        {


            float X = 0;
            float Y = -3;

            string str = " 0" + new string('-', 300);

            for (int i = 0; i < 100; i++)
            {
                str = " " + (Y + 3) + new string('-', 300);
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(str, X, getLastPos() + Y, 900F, 50F, Globals.OpenTypeFontVerdana, 4));
                Y += 2;
                str = " " + new string('-', 300);
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(str, X, getLastPos() + Y, 900F, 50F, Globals.OpenTypeFontVerdana, 4));
                Y += 2;
            }
            X -= 1;
            for (int i = 0; i < 100; i++)
            {
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("|" + X.ToString(), getMargineLeft() + X, getLastPos() + R, 900F, 50F, Globals.OpenTypeFontVerdana, 4));
                X += 5;
                _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("|", getMargineLeft() + X, getLastPos() + R + 3, 900F, 50F, Globals.OpenTypeFontVerdana, 4));
                X += 5;
            }

        }
        public void InsertTable(PageElement elem)
        {
            _page.Elements.Add(elem);
        }



        public void changePage(int x, float y)
        {
            //disegna freccia pi� scritta.
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("continua alla pagina successiva", x - 75, _pageHeight - _margineDOWN - 6, 200, 12, _verdana, 7, ceTe.DynamicPDF.CmykColor.Black));
            string relativePath = UtilityManager.getAppSetting("ChangePage");
            System.Reflection.Assembly thisExe;
            thisExe = System.Reflection.Assembly.GetExecutingAssembly();
            System.IO.Stream file = thisExe.GetManifestResourceStream(relativePath);

            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Image(file, x + _margineLEFT, _pageHeight - _margineDOWN - 5, 0.2F));
            this.addPage();
        }

        /// <summary>
        /// Disegna la frecce e il testo "continua alla pagina successiva" di rimando del salto pagina delle tabelle.
        /// X e Y sono gia definite.
        /// X=435,Y=719.
        /// </summary>
        public void changePage()
        {
            int y = 730;

            if (_notaPieDiPagina.Length > 0)
                y -= 23;
            //disegna freccia pi� scritta.
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("continua alla pagina successiva", 450, y, 200, 12, _verdana, 7, ceTe.DynamicPDF.CmykColor.Black));
            string relativePath = UtilityManager.getAppSetting("ChangePage");
            System.Reflection.Assembly thisExe;
            thisExe = System.Reflection.Assembly.GetExecutingAssembly();
            System.IO.Stream file = thisExe.GetManifestResourceStream(relativePath);
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Image(file, 435, y - 1, 0.2F));
            this.addPage();
        }



        /// <summary>
        /// Disegna la frecce e il testo "continua alla pagina successiva" di rimando del salto pagina delle tabelle.
        /// Disegna le note con posizionamento "Pi�DiPagina" aggiunte alla pagina(document).
        /// X fissata a 435, la Y � variabile a seconda delle Note presenti a pi� di pagina. (Decremento di 15 pixel per ogni nota presente o di 30 a seconda della lunghezza della nota.)
        /// Utilizzato solo dalla classe Tabella.
        /// Non sono all'ultima pagina della tabella ma sto ancora facendo il saltopagina.
        /// </summary>       
        public void changePage(string idtabella)
        {
            int y = 739;

            //_note.RemoveAll(delegate(Nota t) { return t.IdTabellaAssociata != idtabella; }); // rimuovo le note non appartenenti alla tabella che sto stampando.

            // in caso di presenza di note a pi� di pagina decremento la y su cui stampo la label di cambio pagina.           
            foreach (Nota objNota in _note.FindAll(delegate (Nota t) { return t.Posizionamento == Nota.TipologiaPosizionamento.Pi�DiPagina; }))
            {
                if (objNota.Testo.Length < 200)
                    y -= 15;
                else
                    y -= 30;
            }


            //disegna freccia pi� scritta.
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("continua alla pagina successiva", 450, y, 200, 12, _verdana, 7, ceTe.DynamicPDF.CmykColor.Black));
            string relativePath = UtilityManager.getAppSetting("ChangePage");
            System.Reflection.Assembly thisExe;
            thisExe = System.Reflection.Assembly.GetExecutingAssembly();
            System.IO.Stream file = thisExe.GetManifestResourceStream(relativePath);
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Image(file, 435, y - 1, 0.2F));


            // aggiungo la pagina
            this.addPage(idtabella, false); // se passa sicuramente la tabella sta facendo il saltopagina 

        }


        public void nextPage(float x)
        {
            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label("continua dalla pagina precedente", x + 10, _margineUP - 31, 200, 12, _verdana, 7, ceTe.DynamicPDF.CmykColor.Black));
            string relativePath = UtilityManager.getAppSetting("ChangePage");
            System.Reflection.Assembly thisExe;
            thisExe = System.Reflection.Assembly.GetExecutingAssembly();
            System.IO.Stream file = thisExe.GetManifestResourceStream(relativePath);

            _page.Elements.Add(new ceTe.DynamicPDF.PageElements.Image(file, x - 5, _margineUP - 33, 0.2F));
            _writableY += 5;
        }
        //==============================================================
        /// <summary>
        /// Aggiunge una nuova pagina al documento
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public void addPage()
        {
            StampaNote(); // stampo tutte le note aggiunte al documento prima di aggiungere una nuova pagina 

            _margineDOWN = 105;
            _note.Clear(); // azzero la collezione delle note.
            _ynotapiedipagina = 740;

            if (_corePage == _currentPage)
            {

                this.setFilePath();
                this.SetTemplate(_page);
                this.setPageFooter(_page);
                //if (_nomeCliente)
                this.setPageFooterNomeCliente(_page);
                //this.setDisclaimer(page);
                _corePage++;
                _currentPage = _corePage;
                _writableYold = _writableY;
                _writableY = _margineUP;
            }
            else
            {
                _page = _backPage;
                _currentPage = _corePage;
                _writableY = _margineUP;
            }

            if (!_saltoPagina)
                _writableYPot = 0;

        }



        /// <summary>
        /// Aggiunge una nuova pagina al documento.
        /// Utilizzato solo quando si sta stampando una tabella e questa ha il saltopagina.
        /// Questa funzione � richiamata solo dalla funzione "changePage" ovvero solo quando la tabella sta effettuando il saltopagina.
        /// </summary>
        /// <param name="idtabella"></param>
        /// <param name="eliminaNote"></param>
        private void addPage(string idtabella, bool eliminaNote)
        {
            StampaNote(idtabella);

            _ynotapiedipagina = 740;

            #region Aggiungo la pagina al documento

            _margineDOWN = 105;

            if (_corePage == _currentPage)
            {

                this.setFilePath();
                this.SetTemplate(_page);
                this.setPageFooter(_page);
                this.setPageFooterNomeCliente(_page);
                //this.setDisclaimer(page);
                _corePage++;
                _currentPage = _corePage;
                _writableYold = _writableY;
                _writableY = _margineUP;
            }
            else
            {
                _page = _backPage;
                _currentPage = _corePage;
                _writableY = _margineUP;

            }
            if (!_saltoPagina)
                _writableYPot = 0;


            #endregion

            // in questo caso le note associate alla tabella (che sta facendo il saltopagina) solo quelle con posizionamento a Pi�DiPagina 
            // e vanno riportate anche nella nuova pagina.
            // Rimuovo tutte le note perche sono state gi� stampate e lascio quelle associate alla tabella che fa il saltopagina.
            if (eliminaNote)
                _note.Clear();
            else
                _note.RemoveAll(delegate (Nota obj) { return (obj.IdTabellaAssociata != idtabella); });

        }

        public void RemoveLastPage(int index)
        {
            _core.RemoveAt(index);
            //int c = _index.Count;
            //int v = _indexPage;
        }

        /// <summary>
        /// OK
        /// </summary>
        /// <param name="_page"></param>
        private void setFilePath()
        {
            string relativePath = "";
            //if (_tipologia != "report")
            //{

            System.Reflection.Assembly thisExe;
            thisExe = System.Reflection.Assembly.GetExecutingAssembly();

            if (_dataThread.Rete == "F")
            {
                //FC 26062015 Aggionamento nuova Ragione Sociale
                //_banca = "Banca Fideuram";
                _banca = "Fideuram";
                relativePath = UtilityManager.getAppSetting("TemplateReport");
            }
            else
            {
                _banca = "Sanpaolo Invest";
                relativePath = UtilityManager.getAppSetting("TemplateReportSP");
            }

            System.IO.Stream file = thisExe.GetManifestResourceStream(relativePath);

            //}
            //else
            //{
            //    if (_rete == "F")
            //    {
            //        _banca = "Banca Fideuram";
            //        relativePath = UtilityManager.getAppSetting("TemplateReport");
            //    }
            //    else
            //    {
            //        _banca = "Sanpaolo Invest";
            //        relativePath = UtilityManager.getAppSetting("TemplateReportSP");
            //    }
            //}

            PdfDocument pp = new PdfDocument(file);
            _page = new ImportedPage(pp.GetPage(1));
            if (!(_page == null)) _core.Add(_page);
        }
        //==============================================================

        //==============================================================
        /// <summary>
        /// 
        /// </summary>
        /// <param name="heightSection"></param>
        /// <returns></returns>
        public Boolean checkMargin(float heightSection)
        {
            //controlla se la sezione pu� essere scritta nella pagina corrente
            return ((_writableY + heightSection) >= (_pageHeight - _margineDOWN));
        }

        /// <summary>
        /// Verifica se a partire dalla posizione y passata in input, l'altezza heightSection entra
        /// nella pagina corrente.
        /// </summary>
        /// <param name="y"></param>
        /// <param name="heightSection"></param>
        /// <returns></returns>
        public Boolean checkMargin(float y, float heightSection)
        {
            //controlla se la sezione pu� essere scritta nella pagina corrente
            return ((y + heightSection) >= (_pageHeight - _margineDOWN));
        }
        public int getWritableRow(float heightRow, bool header)
        {
            float heightSection = 0;
            if (header) heightSection += heightRow;
            int cont = 0;

            while ((_writableY + cont * heightRow + heightSection) < (_pageHeight - _margineDOWN))
            {
                cont++;
            }
            //controlla se la sezione pu� essere scritta nella pagina corrente
            return cont - 1;
        }


        public int NumLastPage
        {
            get
            {
                return _numlastpage;
            }
            set
            {
                _numlastpage = value;
            }
        }
        /// <summary>
        /// Indica se la nota a pi� di pagina � presente.
        /// </summary>
        public bool FlagNotaPieDiPagina
        {
            get
            {
                return _flagnotaPieDiPagina;
            }
            set
            {
                _flagnotaPieDiPagina = value;
            }
        }



        public int CurrentPage
        {
            get
            {
                return _currentPage;
            }
            set
            {
                _currentPage = value;
            }
        }

        public string AsteriscoVarProxati
        {
            get
            {
                return _AsteriscoVarProxato;
            }
            set
            {
                _AsteriscoVarProxato = value;
            }
        }

        public string AsteriscoGradoCopertura
        {
            get
            {
                return _AsteriscoGradoCopertura;
            }
            set
            {
                _AsteriscoGradoCopertura = value;
            }
        }


        public int NumNotePiePaginaVarProxato
        {
            get
            {
                return _numNotePiePaginaVarProxato;
            }
            set
            {
                _numNotePiePaginaVarProxato = value;
            }
        }

        /// <summary>
        /// Imposta o ottiene la lista di note presenti nel documento.
        /// </summary>
        public ListaNote Note
        {
            get { return _note; }
            set { _note = value; }
        }


        public string TipologiaDocumento
        {
            get
            {
                return _tipologia;
            }
            set
            {
                _tipologia = value;
            }
        }

        public string Banca
        {
            get
            {
                return _banca;
            }
            set
            {
                _banca = value;
            }
        }

        public int NumPage
        {
            get
            {
                return _documentoFinale.Pages.Count;
            }
        }
        //public bool Navigatore
        //{
        //    get
        //    {
        //        return _navigatore;
        //    }
        //    set
        //    {
        //        _navigatore = value;
        //    }
        //}

        //public string TipoReport
        //{
        //    get
        //    {
        //        return _tipoReport;
        //    }
        //    set
        //    {
        //        _tipoReport = value;
        //    }
        //}

        public bool Glossario
        {
            get
            {
                return _glossario;
            }
            set
            {
                _glossario = value;
            }
        }

        //public int Modalit�Anonima
        //{
        //    get
        //    {
        //        return _modalitaAnonima;
        //    }
        //    set
        //    {
        //        _modalitaAnonima = value;
        //    }
        //}

        public string NotaPieDiPagina
        {
            get
            {
                return _notaPieDiPagina;
            }
            set
            {
                _notaPieDiPagina = value;
            }
        }
    }

    public enum TipoNota
    {
        VarProxato,
        GradoCopertura
    }


    /// <summary>
    /// Rappresentazione dell'oggetto nota.
    /// </summary>
    public class Nota
    {
        /// <summary>
        /// Lista della tipologia delle possibili note da aggiungere al documento.
        /// </summary>
        public enum TipologiaNota
        {
            NonImpostato,
            GradoCopertura,
            VarProxato,
            RendimentoSottoscrizione_Maggiore_1_Anno,
            RendimentoSottoscrizione_Minore_1_Anno,
            RendimentoSottoscrizione_Maggiore_E_Minore_1Anno
        }

        /// <summary>
        /// Lista delle tipologie di posizionamento dell'oggetto nota.
        /// </summary>
        public enum TipologiaPosizionamento
        {
            NonImpostato,
            Pi�DiPagina,
            Pi�DiSezione
        }

        /// <summary>
        /// Lista del tipo di stato della Nota. Indica se la Nota � da stampare o se � stata stampata.
        /// </summary>
        public enum StatoNota
        {
            DaStampare,
            Stampata

        }


        private TipologiaNota _tiponota;
        private TipologiaPosizionamento _posizionamento;
        private StatoNota _stato;

        private string _testo = string.Empty;
        private int _numeroasterisco = 0;
        private string _idtabellaassociata;





        /// <summary>
        /// Testo
        /// </summary>
        public string Testo
        {
            get { return _testo; }
            set { _testo = value; }
        }

        /// <summary>
        /// Imposta o ottiente il posizionamento dell'oggetto Nota
        /// </summary>
        public TipologiaPosizionamento Posizionamento
        {
            get { return _posizionamento; }
            set { _posizionamento = value; }
        }


        /// <summary>        
        /// Imposta o ottiente il numero di asterischi.
        /// Ogni Asterisco che viene aggiunto alla collezione di Nota attraverso il metodo Add, viene incrementato automaticamente di 1
        /// </summary>
        public int NumeroAsterisco
        {
            get { return _numeroasterisco; }
            set { _numeroasterisco = value; }
        }


        /// <summary>
        /// Imposta o ottiene la tipologia della Nota
        /// </summary>
        public TipologiaNota TipoNota
        {
            get { return _tiponota; }
            set { _tiponota = value; }
        }

        /// <summary>
        /// Id della tabella associata alla nota.
        /// </summary>
        public string IdTabellaAssociata
        {
            get { return _idtabellaassociata; }
            set { _idtabellaassociata = value; }
        }

        /// <summary>
        /// Stato della Nota.
        /// </summary>
        public StatoNota Stato
        {
            get { return _stato; }
            set { _stato = value; }
        }


        /// <summary>
        /// Costruttore
        /// </summary>
        /// <param name="tiponota"></param>    
        /// <param name="idtabellaassociata"></param>
        public Nota(TipologiaNota tiponota, string idtabellaassociata)
        {
            _tiponota = tiponota;
            _idtabellaassociata = idtabellaassociata;
            _stato = StatoNota.DaStampare;
        }



        /// <summary>
        /// Costruttore
        /// </summary>
        /// <param name="tiponota"></param>
        /// <param name="idtabellaassociata"></param>
        /// <param name="testo"></param>
        public Nota(TipologiaNota tiponota, string idtabellaassociata, string testo)
            : this(tiponota, idtabellaassociata)
        {
            _testo = testo;

        }


        /// <summary>
        /// Ritorna la rappresentazione in stringa del numero di asterisci impostato nella propriet� NumeroAsterisco.
        /// </summary>
        public new string ToString()
        {
            string strReturn = string.Empty;

            for (int i = 0; i < _numeroasterisco; i++)
                strReturn += "*";

            return strReturn;

        }

    }

    /// <summary>
    /// Collezione dell'oggetto Nota.
    /// </summary>
    public class ListaNote : List<Nota>
    {
        /// <summary>
        /// Aggiunge un oggetto Nota alla collezione Note e incrementa la propriet� NumeroAsterisco dell'oggetto Nota.
        /// </summary>
        /// <param name="item"></param>
        public new void Add(Nota item)
        {
            Nota objFound = base.Find(delegate (Nota t) { return t.TipoNota == item.TipoNota; });

            if (objFound == null)
            {
                item.NumeroAsterisco = recuperaNumeroAsterisco();
                item.Testo = "(" + item.ToString() + ") " + item.Testo;

                if (item.TipoNota == Nota.TipologiaNota.GradoCopertura)
                    item.Posizionamento = Nota.TipologiaPosizionamento.Pi�DiSezione;
                else
                    item.Posizionamento = Nota.TipologiaPosizionamento.Pi�DiPagina;
            }
            else
            {
                item.NumeroAsterisco = objFound.NumeroAsterisco;
                item.Testo = objFound.Testo;
                item.Posizionamento = objFound.Posizionamento;

            }

            base.Add(item);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="item"></param>
        public void Insert(Nota item)
        {
            base.Add(item);
        }


        /// <summary>
        /// Recupera il numero di asterischi pi� basso disponibile tra quelli gia inseriti nella lista di note.
        /// </summary>
        /// <returns></returns>
        private int recuperaNumeroAsterisco()
        {
            int result = 1;

            foreach (Nota nota in this)
            {
                if (this.Exists(delegate (Nota t) { return t.NumeroAsterisco == result; }))
                    result++;
            }

            return result;

        }


        /// <summary>
        /// Ricerca all'interno della collezione di Note, l'oggetto avente la TipologiaAsterisco passata in input.
        /// </summary>
        /// <param name="tipoAsterico"></param>
        public Nota Find(Nota.TipologiaNota tipoNota)
        {
            if (base.Count > 0)
                return base.Find(delegate (Nota t) { return t.TipoNota == tipoNota; });
            else
                return new Nota(Nota.TipologiaNota.NonImpostato, null);
        }


        /// <summary>
        /// Ricerca all'interno della collezione di Note, 
        /// l'oggetto avente la TipologiaNota passata in input, e l'id del
        /// </summary>
        /// <param name="tipoAsterico">tipo di nota da ricercare</param>
        /// <param name="IdTabellaAssociata">id della tabellaassociata alla nota da ricercare</param>
        /// <returns></returns>
        public Nota Find(Nota.TipologiaNota tipoNota, string IdTabellaAssociata)
        {
            if (base.Count > 0)
            {
                Nota nota = base.Find(delegate (Nota t) { return t.TipoNota == tipoNota && t.IdTabellaAssociata == IdTabellaAssociata; });
                if (nota != null)
                    return nota;
                else
                    return new Nota(Nota.TipologiaNota.NonImpostato, null);
            }
            else
                return new Nota(Nota.TipologiaNota.NonImpostato, null);
        }


    }

}