////////////////////////////////////////////////////////////////////
        /// <summary>
        /// PDF Shading function constructor
        /// </summary>
        /// <param name="Document">Document object parent of this function.</param>
        /// <param name="ColorArray">Array of colors.</param>
        ////////////////////////////////////////////////////////////////////
        public PdfShadingFunction(
			PdfDocument		Document,		// PDF document object
			Color[]			ColorArray		// Array of colors. Minimum 2.
			)
            : base(Document, ObjectType.Stream)
        {
            // test for error
            if(ColorArray.Length < 2) throw new ApplicationException("Shading function color array must have two or more items");

            // the shading function is a sampled function
            Dictionary.Add("/FunctionType", "0");

            // input variable is between 0 and 1
            Dictionary.Add("/Domain", "[0 1]");

            // output variables are red, green and blue color components between 0 and 1
            Dictionary.Add("/Range", "[0 1 0 1 0 1]");

            // each color components in the stream is 8 bits
            Dictionary.Add("/BitsPerSample", "8");

            // number of colors in the stream must be two or more
            Dictionary.AddFormat("/Size", "[{0}]", ColorArray.Length);

            // add color array to contents stream
            foreach(Color Color in ColorArray)
            {
            ContentsString.Append((Char) Color.R);	// red
            ContentsString.Append((Char) Color.G);	// green
            ContentsString.Append((Char) Color.B);	// blue
            }
            return;
        }
        ////////////////////////////////////////////////////////////////////
        /// <summary>
        /// PDF radial shading constructor.
        /// </summary>
        /// <param name="Document">Parent PDF document object</param>
        /// <param name="PosX">Position X</param>
        /// <param name="PosY">Position Y</param>
        /// <param name="Width">Width</param>
        /// <param name="Height">Height</param>
        /// <param name="ShadingFunction">Shading function</param>
        ////////////////////////////////////////////////////////////////////
        public PdfRadialShading(
			PdfDocument		Document,
			Double			PosX,
			Double			PosY,
			Double			Width,
			Double			Height,
			PdfShadingFunction	ShadingFunction
			)
            : base(Document)
        {
            // create resource code
            ResourceCode = Document.GenerateResourceNumber('S');

            // color space red, green and blue
            Dictionary.Add("/ColorSpace", "/DeviceRGB");

            // shading type radial
            Dictionary.Add("/ShadingType", "3");

            // bounding box
            Dictionary.AddRectangle("/BBox", PosX, PosY, PosX + Width, PosY + Height);

            // set center to bounding box center and radius to half the diagonal
            Dictionary.AddFormat("/Coords", "[{0} {1} {2} {0} {1} 0]", ToPt(PosX + Width / 2), ToPt(PosY + Height / 2), ToPt(Math.Sqrt(Width * Width + Height * Height) / 2));

            // add shading function to shading dictionary
            Dictionary.AddIndirectReference("/Function", ShadingFunction);
            return;
        }
        ////////////////////////////////////////////////////////////////////
        /// <summary>
        /// PDF axial shading constructor.
        /// </summary>
        /// <param name="Document">Parent PDF document object</param>
        /// <param name="PosX">Position X</param>
        /// <param name="PosY">Position Y</param>
        /// <param name="Width">Width</param>
        /// <param name="Height">Height</param>
        /// <param name="ShadingFunction">Shading function</param>
        ////////////////////////////////////////////////////////////////////
        public PdfAxialShading(
			PdfDocument		Document,
			Double			PosX,
			Double			PosY,
			Double			Width,
			Double			Height,
			PdfShadingFunction	ShadingFunction
			)
            : base(Document)
        {
            // create resource code
            ResourceCode = Document.GenerateResourceNumber('S');

            // color space red, green and blue
            Dictionary.Add("/ColorSpace", "/DeviceRGB");

            // shading type axial
            Dictionary.Add("/ShadingType", "2");

            // bounding box
            Dictionary.AddRectangle("/BBox", PosX, PosY, PosX + Width, PosY + Height);

            // assume the direction of color change is along x axis
            Dictionary.AddRectangle("/Coords", PosX, PosY, PosX + Width, PosY);

            // add shading function to shading dictionary
            Dictionary.AddIndirectReference("/Function", ShadingFunction);
            return;
        }
Exemplo n.º 4
0
 ////////////////////////////////////////////////////////////////////
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="Document">Parent PDF document object</param>
 /// <remarks>
 /// Page size is taken from PdfDocument
 /// </remarks>
 ////////////////////////////////////////////////////////////////////
 public PdfPage(
     PdfDocument Document
     )
     : base(Document, ObjectType.Dictionary, "/Page")
 {
     ConstructorHelper(Document.PageSize.Width, Document.PageSize.Height);
     return;
 }
        internal PdfTableBorder(
			PdfTable	Parent
			)
        {
            // save PdfTable parent and document
            this.Parent = Parent;
            this.Document = Parent.Document;
            return;
        }
        internal PdfDictionary(
			PdfObject	Parent
			)
        {
            KeyValue = new List<PdfKeyValue>();
            this.Parent = Parent;
            this.Document = Parent.Document;
            return;
        }
        ////////////////////////////////////////////////////////////////////
        // Create article's example test PDF document
        ////////////////////////////////////////////////////////////////////
        public void Test(
			Boolean Debug,
			String	FileName
			)
        {
            // Step 1: Create empty document
            // Arguments: page width: 8.5”, page height: 11”, Unit of measure: inches
            // Return value: PdfDocument main class
            PdfDocument Document = new PdfDocument(8.25, 11.75, UnitOfMeasure.Inch);

            // Debug property
            // By default it is set to false. Use it for debugging only.
            // If this flag is set, PDF objects will not be compressed, font and images will be replaced
            // by text place holder. You can view the file with a text editor but you cannot open it with PDF reader.
            Document.Debug = Debug;

            // Step 2: create resources
            // define font resources
            DefineFontResources(Document);

            // define tiling pattern resources
            DefineTilingPatternResource(Document);

            // Step 3: Add new page
            PdfPage Page = new PdfPage(Document);

            // Step 4:Add contents to page
            PdfContents Contents = new PdfContents(Page);

            // Step 5: add graphices and text contents to the contents object
            //DrawFrameAndBackgroundWaterMark(Contents);
            //DrawTwoLinesOfHeading(Contents);
            //DrawHappyFace(Contents);
            //DrawBrickPattern(Document, Contents);
            DrawLogo(Document, Contents);
            //DrawHeart(Contents);
            //DrawStar(Contents);
            //DrawTextBox(Contents);
            DrawBookOrderForm(Contents);

            // Step 6: create pdf file
            // argument: PDF file name
            Document.CreateFile(FileName);

            // start default PDF reader and display the file
            Process Proc = new Process();
            Proc.StartInfo = new ProcessStartInfo(FileName);
            Proc.Start();

            // exit
            return;
        }
Exemplo n.º 8
0
        ////////////////////////////////////////////////////////////////////
        // Bookmarks (Document Outline) Root Constructor
        // Must be called from PdfDocument.GetBookmarksRoot() method
        // This constructor is called one time only
        ////////////////////////////////////////////////////////////////////
        internal PdfBookmark(
			PdfDocument		Document
			)
            : base(Document)
        {
            // open first level bookmarks
            this.OpenEntries = true;

            // add /Outlines to catalog dictionary
            Document.CatalogObject.Dictionary.AddIndirectReference("/Outlines", this);

            // add /Outlines to catalog dictionary
            Document.CatalogObject.Dictionary.Add("/PageMode", "/UseOutlines");
            return;
        }
Exemplo n.º 9
0
        /// <summary>
        /// PDF X Object constructor
        /// </summary>
        /// <param name="Document">PDF document</param>
        /// <param name="Width">X Object width</param>
        /// <param name="Height">X Object height</param>
        public PdfXObject(
			PdfDocument		Document,
			Double			Width = 1.0,
			Double			Height = 1.0
			)
            : base(Document, "/XObject")
        {
            // create resource code
            ResourceCode = Document.GenerateResourceNumber('X');

            // add subtype to dictionary
            Dictionary.Add("/Subtype", "/Form");

            // set boundig box rectangle
            Rect = new PdfRectangle(0.0, 0.0, Width, Height);
            return;
        }
Exemplo n.º 10
0
        ////////////////////////////////////////////////////////////////////
        /// <summary>
        /// PDF QR Code constructor
        /// </summary>
        /// <param name="Document">Parent PDF document.</param>
        /// <param name="SegDataString">Data string array to encode.</param>
        /// <param name="ErrorCorrection">Error correction code.</param>
        /// <remarks>
        /// The program will calculate the best encoding mode for each segment.
        /// </remarks>
        ////////////////////////////////////////////////////////////////////
        public PdfQRCode(
			PdfDocument		Document,
			String[]		SegDataString,
			ErrorCorrection	ErrorCorrection
			)
            : base(Document, ObjectType.Stream, "/XObject")
        {
            // create resource code
            ResourceCode = Document.GenerateResourceNumber('X');

            // create QR Code object
            QREncoder Encoder = new QREncoder();
            QRCodeMatrix = Encoder.EncodeQRCode(SegDataString, ErrorCorrection);
            MatrixDimension = Encoder.MatrixDimension;

            // create stream length object
            ImageLengthObject = new PdfObject(Document, ObjectType.Other);
            Dictionary.AddIndirectReference("/Length", ImageLengthObject);

            // exit
            return;
        }
        private void mandarButton_Click(object sender, EventArgs e)
        {
            this.Cursor = System.Windows.Forms.Cursors.WaitCursor;

              String connString = "Database=" + Properties.Settings.Default.databaseFiscal + ";Data Source=" + Properties.Settings.Default.datasource + ";Integrated Security=False;User ID='" + Properties.Settings.Default.user + "';Password='******';connect timeout = 10";
              try
              {

                  using (SqlConnection connection = new SqlConnection(connString))
                  {
                      connection.Open();
                      String queryXML = "";
                      if(Login.unidadDeNegocioGlobal.Equals("FOP"))
                      {
                          queryXML = "SELECT b.ADDR_LINE_1,b.ADDR_LINE_2,b.ADDR_LINE_3,b.ADDR_LINE_4,b.ADDR_LINE_5  , a.AMOUNT, a.TRANS_DATETIME,a.DESCRIPTN,a.JRNAL_SRCE, a.ANAL_T0,a.ACCNT_CODE,c.DESCR FROM [" + Properties.Settings.Default.sunDatabase + "].[dbo].[" + Login.unidadDeNegocioGlobal + "_" + Properties.Settings.Default.sunLibro + "_SALFLDG] a INNER JOIN [" + Properties.Settings.Default.sunDatabase + "].[dbo].[" + Login.unidadDeNegocioGlobal + "_ADDR] b on a.ANAL_T2 = b.ADDR_CODE INNER JOIN [" + Properties.Settings.Default.sunDatabase + "].[dbo].[FOP_ACNT] c on c.ACNT_CODE = a.ACCNT_CODE WHERE a.JRNAL_NO = " + diarioText.Text + " AND a.ANAL_T9 = '" + iglesiaText.Text + "'";
                      }
                      else
                      {
                          queryXML = "SELECT b.ADDR_LINE_1,b.ADDR_LINE_2,b.ADDR_LINE_3,b.ADDR_LINE_4,b.ADDR_LINE_5  , a.AMOUNT, a.TRANS_DATETIME,a.DESCRIPTN,a.JRNAL_SRCE, a.ANAL_T0,a.ACCNT_CODE,c.DESCR FROM [" + Properties.Settings.Default.sunDatabase + "].[dbo].[" + Login.unidadDeNegocioGlobal + "_" + Properties.Settings.Default.sunLibro + "_SALFLDG] a INNER JOIN [" + Properties.Settings.Default.sunDatabase + "].[dbo].[" + Login.unidadDeNegocioGlobal + "_ADDR] b on a.ANAL_T2 = b.ADDR_CODE INNER JOIN [" + Properties.Settings.Default.sunDatabase + "].[dbo].[" + Login.unidadDeNegocioGlobal + "_ACNT] c on c.ACNT_CODE = a.ACCNT_CODE WHERE a.JRNAL_NO = " + diarioText.Text + " AND a.ANAL_T5 = '" + iglesiaText.Text + "'";
                      }
                      using (SqlCommand cmdCheck = new SqlCommand(queryXML, connection))
                      {
                          String saveANAL="";
                          String saveFecha = "";

                          SqlDataReader reader = cmdCheck.ExecuteReader();
                          if (reader.HasRows)
                          {
                              bool first = true;
                              String FileName = "C:" + (object)Path.DirectorySeparatorChar + "recibos" + (object)Path.DirectorySeparatorChar + iglesiaText.Text + "_" + diarioText.Text + ".pdf";
                              string path = "C:" + (object)Path.DirectorySeparatorChar + "recibos";
                              if (!Directory.Exists(path))
                                  Directory.CreateDirectory(path);
                              if (File.Exists(FileName))
                              {
                                  try
                                  {
                                      File.Delete(FileName);
                                  }
                                  catch (IOException ex2)
                                  {
                                      System.Windows.Forms.MessageBox.Show(ex2.ToString(), "Sunplusito", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                  }
                              }

                              Document = new PdfDocument(PaperType.Letter, false, UnitOfMeasure.Inch, FileName);
                              DefineFontResources();
                              DefineTilingPatternResource();
                              PdfPage Page = new PdfPage(Document);
                              PdfContents Contents = new PdfContents(Page);
                              Contents.SaveGraphicsState();

                              String fileImage = "C:" + (object)Path.DirectorySeparatorChar + "recibos" + (object)Path.DirectorySeparatorChar + "logo.jpg";
                              PdfImageControl ImageControl = new PdfImageControl();
                              ImageControl.Resolution = 300.0;
                              PdfImage Image = new PdfImage(Document, fileImage, ImageControl); //new PdfImage(Document, fileImage, 72.0, 50);
                              Contents.SaveGraphicsState();
                              double top = 9.9;
                              double left = 0.4;
                              int ancho = 1;
                              int largo = 1;
                             Contents.DrawImage(Image, left, top, ancho, largo);
                             Contents.DrawImage(Image, left, top-6.2, ancho, largo);

                              Contents.RestoreGraphicsState();
                              Contents.SaveGraphicsState();

                              const Double Width = 8.15;
                              const Double Height = 10.65;
                              PdfFileWriter.TextBox Box = new PdfFileWriter.TextBox(Width, 0.0);
                              PdfFileWriter.TextBox Datos = new PdfFileWriter.TextBox(Width, 0.0);
                              PdfFileWriter.TextBox derecha = new PdfFileWriter.TextBox(Width, 0.0);
                              PdfFileWriter.TextBox fechaBox = new PdfFileWriter.TextBox(Width, 0.0);
                              PdfFileWriter.TextBox graciasBox = new PdfFileWriter.TextBox(Width, 0.0);
                              PdfFileWriter.TextBox copiaBox = new PdfFileWriter.TextBox(Width, 0.0);

                              //double dif = 2.5;
                             // Contents.SaveGraphicsState();
                              //Contents.RestoreGraphicsState();
                              Contents.Translate(0.0, 0.0);
                              PdfTable Table = new PdfTable(Page, Contents, ArialNormal, 9.0);
                              PdfTable TableCopy = new PdfTable(Page, Contents, ArialNormal, 9.0);

                              Table.TableArea = new PdfRectangle(0.5, 1,8.0,7.7);
                              TableCopy.TableArea = new PdfRectangle(0.5, 1, 8.0, 1.75);

                              Double MarginHor = 0.04;
                              double aver = ArialNormal.TextWidth(9.0, "9999.99") + 2.0 * MarginHor;
                              double aver2 = ArialNormal.TextWidth(9.0, "Qty") + 2.0 * MarginHor;
                              aver += 0.2;
                              Table.SetColumnWidth(new Double[] { aver2,aver , aver, aver2 });
                              Table.Borders.SetAllBorders(0.0);

                              Table.Header[0].Style = Table.HeaderStyle;
                              Table.Header[0].Style.Alignment = ContentAlignment.MiddleCenter;
                              Table.Header[1].Style = Table.HeaderStyle;
                              Table.Header[1].Style.Alignment = ContentAlignment.MiddleCenter;
                              Table.Header[2].Style = Table.HeaderStyle;
                              Table.Header[2].Style.Alignment = ContentAlignment.MiddleCenter;
                              Table.Header[3].Style = Table.HeaderStyle;
                              Table.Header[3].Style.Alignment = ContentAlignment.MiddleCenter;

                              Table.Header[0].Value = "Cuenta";
                              Table.Header[1].Value = "Descripción";
                              Table.Header[2].Value = "Concepto";
                              Table.Header[3].Value = "Total";

                              TableCopy.SetColumnWidth(new Double[] { aver2, aver, aver, aver2 });
                              TableCopy.Borders.SetAllBorders(0.0);

                              TableCopy.Header[0].Style = Table.HeaderStyle;
                              TableCopy.Header[0].Style.Alignment = ContentAlignment.MiddleCenter;
                              TableCopy.Header[1].Style = Table.HeaderStyle;
                              TableCopy.Header[1].Style.Alignment = ContentAlignment.MiddleCenter;
                              TableCopy.Header[2].Style = Table.HeaderStyle;
                              TableCopy.Header[2].Style.Alignment = ContentAlignment.MiddleCenter;
                              TableCopy.Header[3].Style = Table.HeaderStyle;
                              TableCopy.Header[3].Style.Alignment = ContentAlignment.MiddleCenter;

                              TableCopy.Header[0].Value = "Cuenta";
                              TableCopy.Header[1].Value = "Descripción";
                              TableCopy.Header[2].Value = "Concepto";
                              TableCopy.Header[3].Value = "Total";

                              StringBuilder cad = new StringBuilder("");
                              StringBuilder primeros = new StringBuilder("");
                              StringBuilder letrasGrandes = new StringBuilder("");
                              StringBuilder fechaCad = new StringBuilder("");

                              StringBuilder tabla = new StringBuilder("");
                              double total=0;
                              int contadorTabla = 0;
                              while (reader.Read())
                              {
                                  String ADDR_LINE_1 = reader.GetString(0).Trim();
                                  String ADDR_LINE_2 = reader.GetString(1).Trim();
                                  String ADDR_LINE_3 = reader.GetString(2).Trim();
                                  String ADDR_LINE_4 = reader.GetString(3).Trim();
                                  String ADDR_LINE_5 = reader.GetString(4).Trim();
                                  String amount = Convert.ToString(reader.GetDecimal(5));
                                  String fecha = Convert.ToString(reader.GetDateTime(6)).Substring(0, 10);

                                  String DESCR = reader.GetString(7).Trim();
                                  if(DESCR.Length>32)
                                  {
                                      DESCR = DESCR.Substring(0, 32);
                                  }
                                  String JRNAL_SRCE = reader.GetString(8).Trim();
                                  String ANAL_T0 = reader.GetString(9).Trim();
                                  saveANAL=ANAL_T0;
                                  String ACNT_CODE = reader.GetString(10).Trim();
                                  String descrCuenta = reader.GetString(11).Trim();
                                  if (descrCuenta.Length > 36)
                                  {
                                      descrCuenta = descrCuenta.Substring(0, 36);
                                  }
                                  total+=Convert.ToDouble(amount);
                                  if(first)
                                  {
                                      first = false;
                                      primeros.Append( ADDR_LINE_1 + "\n" +
                                         ADDR_LINE_2 + "\n" +
                                      ADDR_LINE_3 + "\n" +
                                      ADDR_LINE_4 + "\n" +
                                      ADDR_LINE_5 + "\n\n");
                                      fechaCad.Append(" Fecha de recepción:\n" + fecha);

                                      letrasGrandes.Append("      Recibido de " + DESCR + "\n");
                                      saveFecha = fecha;
                                  }
                                  Table.Cell[0].Value = ACNT_CODE;
                                  Table.Cell[1].Value = descrCuenta;
                                  Table.Cell[2].Value = DESCR;
                                   Table.Cell[3].Value = "$"+String.Format("{0:n}", Convert.ToDouble(amount));
                                  Table.DrawRow();
                                  TableCopy.Cell[0].Value = ACNT_CODE;
                                  TableCopy.Cell[1].Value = descrCuenta;
                                  TableCopy.Cell[2].Value = DESCR;
                                  TableCopy.Cell[3].Value = "$" + String.Format("{0:n}", Convert.ToDouble(amount));
                                  TableCopy.DrawRow();

                                  contadorTabla++;

                                //  tabla.Append("\n"+DESCR+"         "+ACNT_CODE+"        "+JRNAL_SRCE+"        "+  String.Format("{0:n}", Convert.ToDouble(amount)));
                              }//while
                              Table.Close();
                              TableCopy.Close();
                              Contents.SaveGraphicsState();
                              Contents.RestoreGraphicsState();

                              letrasGrandes.Append("      ***** " + Conversiones.NumeroALetras(total.ToString()) + " *****\n");

                              cad.Append(" Número de recibo original: " + saveANAL + "\n Diario: " + diarioText.Text + "\n" +
                                      " Monto recibido\n ***** "+String.Format("{0:n}", Convert.ToDouble(total))+" *****\n\n");
                              //cad.Append();
                              try{

                                  Box.AddText(ArialNormal, 14.0,
                                    primeros.ToString()  );
                                  Datos.AddText(ArialNormal, 14.0,
                                letrasGrandes.ToString() );
                                  copiaBox.AddText(ArialBold, 50.0,
                              "     COPY");
                                  graciasBox.AddText(ArialItalic, 30.0,
                              "                           Gracias\n");
                                  fechaBox.AddText(ArialNormal, 10.0,
                                 fechaCad.ToString());
                               derecha.AddText(ArialNormal, 12.0,
                                 cad.ToString());
                                  Double PosY = 8.5;
                                  Double PosYDatos = 9.0;
                                  Double auxY = Height;
                                  Double auxFecha = Height-0.5;
                                  double dif = 6.0;
                                  Double auxYCopia = Height-dif;
                                  Double auxFechaCopia = Height - 0.5-dif;
                                  Double PosYCopia = 8.5-dif;
                                  Double copiaCopia = 8.5 - dif;

                                  Double PosYDatosCopia = 9.0-dif;

                                  Contents.Translate(0.0, 10.0);

                                 // Contents.Translate(0.0, -9.9);//-9.9

                                 Contents.Translate(0.0, -9.9);

                                  Contents.DrawText(0.0, ref auxY, 9.0, 0, 0.0, 0.0, TextBoxJustify.Center, Box);
                                  Contents.RestoreGraphicsState();
                                  Contents.SaveGraphicsState();
                                  //la copia
                                  Contents.DrawText(0.0, ref auxYCopia, 1.0, 0, 0.0, 0.0, TextBoxJustify.Center, Box);
                                  Contents.RestoreGraphicsState();
                                  Contents.SaveGraphicsState();
                                 // Contents.Translate(0.0, -9.9);
                                  Contents.DrawText(0, ref PosYDatos, 8.5, 0, 0.00, 0.00, TextBoxJustify.Left, Datos);
                                  Contents.RestoreGraphicsState();
                                  Contents.SaveGraphicsState();

                                  Contents.DrawText(0, ref PosYDatosCopia, 1.0, 0, 0.00, 0.00, TextBoxJustify.Left, Datos);
                                  Contents.RestoreGraphicsState();
                                  Contents.SaveGraphicsState();

                                 // Contents.Translate(0.0, -9.9);
                                  Contents.DrawText(0, ref PosY, 7.0, 0, 0.00, 0.00, TextBoxJustify.Right, derecha);
                                  Contents.RestoreGraphicsState();
                                  Contents.SaveGraphicsState();

                                  Contents.DrawText(0, ref PosYDatos, 7.0, 0, 0.00, 0.00, TextBoxJustify.Left, graciasBox);
                                  Contents.RestoreGraphicsState();
                                  Contents.SaveGraphicsState();

                                  Contents.DrawText(0, ref PosYCopia, 1.0, 0, 0.00, 0.00, TextBoxJustify.Right, derecha);
                                  Contents.RestoreGraphicsState();
                                  Contents.SaveGraphicsState();

                                  Contents.DrawText(0, ref PosYDatosCopia, 1.0, 0, 0.00, 0.00, TextBoxJustify.Left, graciasBox);
                                  Contents.RestoreGraphicsState();
                                  Contents.SaveGraphicsState();

                                  Contents.DrawText(0, ref copiaCopia, 1.0, 0, 0.00, 0.00, TextBoxJustify.Left, copiaBox);
                                  Contents.RestoreGraphicsState();
                                  Contents.SaveGraphicsState();

                                  //Contents.Translate(0.0, -9.9);
                                  Contents.DrawText(0, ref auxFecha, 9.5, 0, 0.00, 0.00, TextBoxJustify.Right, fechaBox);
                                  Contents.RestoreGraphicsState();
                                  Contents.SaveGraphicsState();

                                  Contents.DrawText(0, ref auxFechaCopia, 1.0, 0, 0.00, 0.00, TextBoxJustify.Right, fechaBox);
                                  Contents.RestoreGraphicsState();
                                  Contents.SaveGraphicsState();

                                Document.CreateFile();

                                try
                                {
                                    MailMessage mail2 = new MailMessage();
                                    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

                                    mail2.From = new MailAddress(Properties.Settings.Default.correoEmisor);
                                    mail2.To.Add(correoLabel.Text);

                                    mail2.CC.Add(Properties.Settings.Default.correoReceptor);
                                    DateTime now = DateTime.Now;
                                    int year = now.Year;
                                    int month = now.Month;
                                    int day = now.Day;
                                    String mes = month.ToString();
                                    if (month < 10)
                                    {
                                        mes = "0" + month;
                                    }
                                    String dia = day.ToString();
                                    if (day < 10)
                                    {
                                        dia = "0" + day;
                                    }
                                    if(Login.unidadDeNegocioGlobal.Equals("FOP"))
                                    {
                                        mail2.Subject = "Recibo del dia: " + saveFecha + " del diario "+diarioText.Text+" de FORPOUMN " + iglesiaText.Text ;
                                        mail2.Body = "Hola " + nombreLabel.Text + ", por este medio le envio el recibo de FOPROUMN correspondiente al diario "+diarioText.Text+". Dios lo bendiga. ";
                                    }
                                    else
                                    {
                                        mail2.Subject = "Recibo de caja del dia: " + saveFecha + " de la iglesia " + iglesiaText.Text;
                                        mail2.Body = "Hola " + nombreLabel.Text + ", por este medio le envio el recibo de caja de la iglesia " + iglesiaText.Text;
                                    }
                                    Attachment pdf = new Attachment(FileName);
                                    mail2.Attachments.Add(pdf);
                                    SmtpServer.Port = 587;
                                    SmtpServer.Credentials = new System.Net.NetworkCredential(Properties.Settings.Default.correoEmisor, Properties.Settings.Default.passEmisor);
                                    SmtpServer.EnableSsl = true;
                                    SmtpServer.Send(mail2);
                                    this.Cursor = System.Windows.Forms.Cursors.Arrow;

                                    System.Windows.Forms.MessageBox.Show("Ya se mando el correo", "Sunplusito", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                                }
                                catch (Exception ex3)
                                {
                                    System.Windows.Forms.MessageBox.Show(ex3.ToString(), "error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                }

                                   }//try
                              catch(Exception ex1)
                              {
                                          System.Windows.Forms.MessageBox.Show(ex1.ToString(), "Sunplusito", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                              }
                          }
                      }
                  }
              }
            catch(Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString(), "Sunplusito", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
              this.Cursor = System.Windows.Forms.Cursors.Arrow;
        }
Exemplo n.º 12
0
        ////////////////////////////////////////////////////////////////////
        // Constructor
        ////////////////////////////////////////////////////////////////////

        public PdfFont
        (
            PdfDocument Document,                                       // PDF document main object
            String FontFamilyName,                                      // font family name
            FontStyle FontStyle,                                        // font style (Regular, Bold, Italic or Bold | Italic
            Boolean EmbeddedFont                                        // embed font in PDF document file
        ) : base(Document, false, "/Font")
        {
            // save embedded font flag
            this.EmbeddedFont = EmbeddedFont;

            // font style cannot be underline or strikeout
            if ((FontStyle & (FontStyle.Underline | FontStyle.Strikeout)) != 0)
            {
                throw new ApplicationException("Font resource cannot have underline or strikeout");
            }

            // create resource code
            ResourceCode = Document.GenerateResourceNumber('F');

            // get font family structure
            FontFamily = new FontFamily(FontFamilyName);

            // test font style availability
            if (!FontFamily.IsStyleAvailable(FontStyle))
            {
                throw new ApplicationException("Font style not available for font family");
            }

            // design height
            DesignHeight = FontFamily.GetEmHeight(FontStyle);

            // Ascent, descent and line spacing for a one point font
            PdfAscent      = WindowsToPdf(FontFamily.GetCellAscent(FontStyle));
            PdfDescent     = WindowsToPdf(FontFamily.GetCellDescent(FontStyle)); // positive number
            PdfLineSpacing = WindowsToPdf(FontFamily.GetLineSpacing(FontStyle));

            // create design font
            DesignFont = new Font(FontFamily, DesignHeight, FontStyle, GraphicsUnit.Pixel);

            // create windows sdk font info object
            FontInfo = new FontApi(DesignFont, DesignHeight);

            // get character width array
            CharWidthArray = FontInfo.GetCharWidthApi(0, 255);

            // get array of glyph bounding box and width
            GlyphArray = FontInfo.GetGlyphMetricsApi(0, 255);

            // reset active (used) characters to not used
            ActiveChar = new Boolean[256];

            // get outline text metrics structure
            WinOutlineTextMetric OTM = FontInfo.GetOutlineTextMetricsApi();

            // license
            if ((OTM.otmfsType & 2) != 0)
            {
                throw new ApplicationException("Font " + FontFamilyName + " is not licensed for embedding");
            }

            // make sure we have true type font and not device font
            if ((OTM.otmTextMetric.tmPitchAndFamily & 0xe) != 6)
            {
                throw new ApplicationException("Font must be True Type and vector");
            }

            // PDF font flags
            FontFlags = 0;
            if ((OTM.otmfsSelection & 1) != 0)
            {
                FontFlags |= PdfFontFlags.Italic;
            }
            // roman font is a serif font
            if ((OTM.otmTextMetric.tmPitchAndFamily >> 4) == 1)
            {
                FontFlags |= PdfFontFlags.Serif;
            }
            if ((OTM.otmTextMetric.tmPitchAndFamily >> 4) == 4)
            {
                FontFlags |= PdfFontFlags.Script;
            }
            // #define SYMBOL_CHARSET 2
            if (OTM.otmTextMetric.tmCharSet == 2)
            {
                FontFlags   |= PdfFontFlags.Symbolic;
                SymbolicFont = true;
            }
            else
            {
                FontFlags   |= PdfFontFlags.Nonsymbolic;
                SymbolicFont = false;
            }

            // #define TMPF_FIXED_PITCH 0x01 (Note very carefully that those meanings are the opposite of what the constant name implies.)
            if ((OTM.otmTextMetric.tmPitchAndFamily & 1) == 0)
            {
                FontFlags |= PdfFontFlags.FixedPitch;
            }

            // strikeout
            PdfStrikeoutPosition = WindowsToPdf(OTM.otmsStrikeoutPosition);
            PdfStrikeoutWidth    = WindowsToPdf((Int32)OTM.otmsStrikeoutSize);

            // underline
            PdfUnderlinePosition = WindowsToPdf(OTM.otmsUnderscorePosition);
            PdfUnderlineWidth    = WindowsToPdf(OTM.otmsUnderscoreSize);

            // subscript
            PdfSubscriptSize     = WindowsToPdf(OTM.otmptSubscriptSize.Y);
            PdfSubscriptPosition = WindowsToPdf(OTM.otmptSubscriptOffset.Y);

            // superscript
            PdfSuperscriptSize     = WindowsToPdf(OTM.otmptSuperscriptSize.Y);
            PdfSuperscriptPosition = WindowsToPdf(OTM.otmptSuperscriptOffset.Y);

            PdfItalicAngle = (Double)OTM.otmItalicAngle / 10.0;
            PdfFontWeight  = OTM.otmTextMetric.tmWeight;

            // exit
            return;
        }
Exemplo n.º 13
0
        private PdfEmbeddedFile
        (
            PdfDocument Document,
            string FileName,
            string PdfFileName
        ) : base(Document, ObjectType.Dictionary, "/Filespec")
        {
            // save file name
            this.FileName = FileName;

            // test exitance
            if (!File.Exists(FileName))
            {
                throw new ApplicationException("Embedded file " + FileName + " does not exist");
            }

            // get file length
            var FI = new FileInfo(FileName);

            if (FI.Length > int.MaxValue - 4095)
            {
                throw new ApplicationException("Embedded file " + FileName + " too long");
            }

            var FileLength = (int)FI.Length;

            // translate file extension to mime type string
            MimeType = ExtToMime.TranslateExtToMime(FI.Extension);

            // create embedded file object
            var EmbeddedFile = new PdfObject(Document, ObjectType.Stream, "/EmbeddedFile");

            // save uncompressed file length
            EmbeddedFile.Dictionary.AddFormat("/Params", "<</Size {0}>>", FileLength);

            // file data content byte array
            EmbeddedFile.ObjectValueArray = new byte[FileLength];

            // load all the file's data
            FileStream DataStream = null;

            try
            {
                // open the file
                DataStream = new FileStream(FileName, FileMode.Open, FileAccess.Read);

                // read all the file
                if (DataStream.Read(EmbeddedFile.ObjectValueArray, 0, FileLength) != FileLength)
                {
                    throw new Exception();
                }
            }

            // loading file failed
            catch (Exception)
            {
                throw new ApplicationException("Invalid media file: " + FileName);
            }

            // close the file
            DataStream.Close();

            // debug
            if (Document.Debug)
            {
                EmbeddedFile.ObjectValueArray = Document.TextToByteArray("*** MEDIA FILE PLACE HOLDER ***");
            }

            // write stream
            EmbeddedFile.WriteObjectToPdfFile();

            // file spec object type
            Dictionary.Add("/Type", "/Filespec");

            // PDF file name
            if (string.IsNullOrWhiteSpace(PdfFileName))
            {
                PdfFileName = FI.Name;
            }

            Dictionary.AddPdfString("/F", PdfFileName);
            Dictionary.AddPdfString("/UF", PdfFileName);

            // add reference
            Dictionary.AddFormat("/EF", "<</F {0} 0 R /UF {0} 0 R>>", EmbeddedFile.ObjectNumber);
        }
Exemplo n.º 14
0
        ////////////////////////////////////////////////////////////////////
        // Encryption Constructor
        ////////////////////////////////////////////////////////////////////
        internal PdfEncryption(
			PdfDocument	Document,
			String		UserPassword,
			String		OwnerPassword,
			Permission	UserPermissions,
			EncryptionType EncryptionType
			)
            : base(Document)
        {
            // Notes:
            // The PDF File Writer library supports AES 128 encryption only.
            // The library does not strip leading or trailing white space. They are part of the password.
            // EncriptMetadata is assumed to be true (this libraray does not use metadata).
            // Embeded Files Only is assumed to be false (this library does not have embeded files).

            // remove all unused bits and add all bits that must be one
            Permissions = ((Int32) UserPermissions & (Int32) Permission.All) | PermissionBase;
            Dictionary.AddInteger("/P", Permissions);

            // convert user string password to byte array
            Byte[] UserBinaryPassword = ProcessPassword(UserPassword);

            // convert owner string password to byte array
            if(String.IsNullOrEmpty(OwnerPassword)) OwnerPassword = BitConverter.ToUInt64(PdfDocument.RandomByteArray(8), 0).ToString();
            Byte[] OwnerBinaryPassword = ProcessPassword(OwnerPassword);

            // calculate owner key for crypto dictionary
            Byte[] OwnerKey = CreateOwnerKey(UserBinaryPassword, OwnerBinaryPassword);

            // create master key and user key
            CreateMasterKey(UserBinaryPassword, OwnerKey);
            Byte[] UserKey = CreateUserKey();

            // build dictionary
            Dictionary.Add("/Filter", "/Standard");
            Dictionary.Add("/Length", "128");
            Dictionary.Add("/O", Document.ByteArrayToPdfHexString(OwnerKey));
            Dictionary.Add("/U", Document.ByteArrayToPdfHexString(UserKey));

            // encryption type
            this.EncryptionType = EncryptionType;
            if(EncryptionType == EncryptionType.Aes128)
            {
            Dictionary.Add("/R", "4");
            Dictionary.Add("/V", "4");
            Dictionary.Add("/StrF", "/StdCF");
            Dictionary.Add("/StmF", "/StdCF");
            Dictionary.Add("/CF", "<</StdCF<</Length 16/AuthEvent/DocOpen/CFM/AESV2>>>>");
            }
            else
            {
            Dictionary.Add("/R", "3");
            Dictionary.Add("/V", "2");
            }
            return;
        }
Exemplo n.º 15
0
        private void si_Click(object sender, EventArgs e)
        {
            preconcepto = preconceptoT.Text;
            nombre = nombreT.Text;
            fecha = fechaT.Text;
            total = totalT.Text;
            numeroAletras = numeroALetrasT.Text;

            string path = Properties.Settings.Default.letra+":" + (object)Path.DirectorySeparatorChar + "cheques";
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            String numeroDeCheque = "";
            if(anal.Length>11)
            {
                numeroDeCheque = anal.Substring(5, 7);
            }
            String FileName = path + (object)Path.DirectorySeparatorChar + numeroDiario + "_" + numeroDeCheque + ".pdf";
            String FileNameToPDF = path + (object)Path.DirectorySeparatorChar + numeroDiario + "_" + numeroDeCheque + "-Orden_de_cheque.pdf";
            if (File.Exists(FileName))
            {
                try
                {
                    File.Delete(FileName);
                }
                catch (IOException ex2)
                {
                    System.Windows.Forms.MessageBox.Show(ex2.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            if (File.Exists(FileNameToPDF))
            {
                try
                {
                    File.Delete(FileNameToPDF);
                }
                catch (IOException ex2)
                {
                     System.Windows.Forms.MessageBox.Show(ex2.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            Document = new PdfDocument(PaperType.sobreprima, false, UnitOfMeasure.Point, FileName);

            DocumentToPDF = new PdfDocument(PaperType.A4, false, UnitOfMeasure.Point, FileNameToPDF);

            DefineFontResources();
            DefineTilingPatternResource();
            PdfPage Page = new PdfPage(Document);
            PdfContents Contents = new PdfContents(Page);

            PdfPage PageToPDF = new PdfPage(DocumentToPDF);
            PdfContents ContentsToPDF = new PdfContents(PageToPDF);

            Contents.SaveGraphicsState();
            Contents.Translate(0.1, 0.1);

            ContentsToPDF.SaveGraphicsState();
            ContentsToPDF.Translate(0.1, 0.1);

            const Double Width = 632;
            const Double Height = 288;
            const Double FontSize = 9.0;

            const Double WidthToPDF = 632;//1200;
            const Double HeightToPDF = 850;// 288;//2138;
            const Double FontSizeToPDF = 12.0;

               string[] arrayCuentas = new string[100] ;
            string[] arrayDescr = new string[100] ;
            string[] arrayCantidad = new string[100];

            int con=0;
            try
            {
                using (SqlConnection connection = new SqlConnection(connStringSun))
                {
                    connection.Open();
                    foreach (Dictionary<string, object> dic in listaFinalconDebitos)
                    {
                        if (dic.ContainsKey("nombre"))
                        {
                            String analPrima = Convert.ToString(dic["anal"]).Trim();
                            String totalPrima = Convert.ToString(dic["total"]);
                            totalPrima = totalPrima.Replace("-", "");

                            String ACCNT_CODEPrima = Convert.ToString(dic["ACCNT_CODE"]).Trim();
                            if(analPrima.Equals(anal))
                            {
                                String paraVer = ACCNT_CODEPrima.Trim();

                                String queryDiario = "SELECT DESCR FROM [" + Properties.Settings.Default.sunDatabase + "].[dbo].[" + Properties.Settings.Default.sunUnidadDeNegocio + "_ACNT] WHERE ACNT_CODE = '" + paraVer + "'";
                                SqlCommand cmdCheck = new SqlCommand(queryDiario, connection);
                                SqlDataReader reader = cmdCheck.ExecuteReader();
                                if (reader.HasRows)
                                {
                                    while (reader.Read())
                                    {
                                        arrayCuentas[con] = paraVer;
                                        arrayCantidad[con] = totalPrima;
                                        arrayDescr[con] = reader.GetString(0);
                                        con++;
                                    }
                                }
                            }

                        }
                    }

                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString(), "Cheques", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            String descr_acntC = "";

            try
            {
                using (SqlConnection connection = new SqlConnection(connStringSun))
                {
                    connection.Open();
                    String paraVer2 = Convert.ToString(ACCNT_CODE).Trim();
                    String queryDiario = "SELECT DESCR FROM [" + Properties.Settings.Default.sunDatabase + "].[dbo].[" + Properties.Settings.Default.sunUnidadDeNegocio + "_ACNT] WHERE ACNT_CODE = '" + paraVer2 + "'";
                    SqlCommand cmdCheck = new SqlCommand(queryDiario, connection);
                    SqlDataReader reader = cmdCheck.ExecuteReader();
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            descr_acntC = reader.GetString(0);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString(), "Cheques", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            String space = "                                                          ";
            PdfFileWriter.TextBox BoxToPDF = new PdfFileWriter.TextBox(WidthToPDF, 0.25);
            int l;
            StringBuilder debitos = new StringBuilder("");
            StringBuilder otrosDebitos = new StringBuilder("");

            int hastai = con;
            int max = 15;
            PdfContents ContentsToPDF1 = null;
            if(con>max)
            {
                hastai = max;
                PdfPage PageToPDF1 = new PdfPage(DocumentToPDF);
                ContentsToPDF1 = new PdfContents(PageToPDF1);

                ContentsToPDF1.SaveGraphicsState();
                ContentsToPDF1.Translate(0.1, 750);
                for (l = max; l < con; l++)
                {
                    otrosDebitos.Append("\n         Debito: $" + arrayCantidad[l] + " - " + arrayCuentas[l] + " - " + arrayDescr[l]);
                }

            }
            for(l=0;l<hastai;l++)
            {
                debitos.Append("\n         Debito: $" + arrayCantidad[l] +" - " +arrayCuentas[l] + " - " + arrayDescr[l]);
            }

            String aver = "\n\n\n\n\n" +
            space +
            Properties.Settings.Default.campo +
            "\n" + space +
            Properties.Settings.Default.calle + "\n" + space +
            "       " + Properties.Settings.Default.colonia + "                                        Fecha: " + fecha + "\n" + space +
            Properties.Settings.Default.ciudad+"                     Reference: " + anal + "\n" +
            "\n\n" +
            "\n\n" +
            "        Pagarse a: " + nombre +
            "\n" +
            "        Concepto: " + preconcepto + "\n" +
            "        Cantidad: " + total + "\n"+
            "        Bueno por: " + numeroAletras + "\n\n" +"\n\n\n\n\n\n" +
            "      ______________________                        ____________________               ____________________\n" +
            "           Processed by: " + JRNAL_SRCE + "                                         Approved by                                    Received by " +
            "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" +
            "         Crédito: $" +total+" - "+ ACCNT_CODE + " - " + descr_acntC.Trim() +debitos.ToString();
            BoxToPDF.AddText(ArialNormalToPDF, FontSizeToPDF,aver);
            Double PosYToPDF = HeightToPDF;

            StringBuilder espacios = new StringBuilder("");
            int j = 0;
            for (j = 0; j < Convert.ToInt32(Properties.Settings.Default.sunEspacios1); j++)
            {
                espacios.Append(" ");
            }
            StringBuilder entersPrimeros = new StringBuilder("");
            for (j = 0; j < Convert.ToInt32(Properties.Settings.Default.entersPrimeros1); j++)
            {
                entersPrimeros.Append("\n");
            }
            StringBuilder espaciosDeFecha = new StringBuilder("");
            for (j = 0; j < Convert.ToInt32(Properties.Settings.Default.espaciosDeFecha1); j++)
            {
                espaciosDeFecha.Append(" ");
            }
            StringBuilder entersEntreFechaYNombre = new StringBuilder("");
            for (j = 0; j < Convert.ToInt32(Properties.Settings.Default.entersEntreFechaYNombre1); j++)
            {
                entersEntreFechaYNombre.Append("\n");
            }
            StringBuilder entersEntreNombreYLetras = new StringBuilder("");
            for (j = 0; j < Convert.ToInt32(Properties.Settings.Default.entersEntreNombreYLetras1); j++)
            {
                entersEntreNombreYLetras.Append("\n");
            }
            StringBuilder espaciosEntreNombreYTotal = new StringBuilder("");
            for (j = 0; j < Convert.ToInt32(Properties.Settings.Default.espaciosEntreNombreYTotal1); j++)
            {
                espaciosEntreNombreYTotal.Append(" ");
            }

            PdfFileWriter.TextBox Box = new PdfFileWriter.TextBox(Width, 0.25);
            Box.AddText(ArialNormal, FontSize,
             entersPrimeros.ToString() +
            espaciosDeFecha.ToString() +
             fecha +
             entersEntreFechaYNombre.ToString() +
               espacios.ToString() +//64
             nombre + espaciosEntreNombreYTotal.ToString() + total +
             entersEntreNombreYLetras.ToString() +
            espacios.ToString() +
             numeroAletras);

            BoxToPDF.AddText(ArialNormalToPDF, FontSizeToPDF, "\n");
            ContentsToPDF.DrawText(0.0, ref PosYToPDF, 0.0, 0, 0.015, 0.05, TextBoxJustify.FitToWidth, BoxToPDF);
            ContentsToPDF.RestoreGraphicsState();
            ContentsToPDF.SaveGraphicsState();
            ContentsToPDF.RestoreGraphicsState();

            if (con > max)
            {
                PdfFileWriter.TextBox BoxToPDF1 = new PdfFileWriter.TextBox(WidthToPDF, 0.25);
                BoxToPDF1.AddText(ArialNormalToPDF, FontSizeToPDF, otrosDebitos.ToString());
                ContentsToPDF1.DrawText(0.0, ref PosYToPDF, 0.0, 0, 0.015, 0.05, TextBoxJustify.FitToWidth, BoxToPDF1);
                ContentsToPDF1.RestoreGraphicsState();
                ContentsToPDF1.SaveGraphicsState();
                ContentsToPDF1.RestoreGraphicsState();
            }
            DocumentToPDF.CreateFile();

            Box.AddText(ArialNormal, FontSize, "\n");
            Double PosY = Height;
            Contents.DrawText(0.0, ref PosY, 0.0, 0, 0.015, 0.05, TextBoxJustify.FitToWidth, Box);
            Contents.RestoreGraphicsState();
            Contents.SaveGraphicsState();
            Contents.RestoreGraphicsState();
            Document.CreateFile();

            previewCheque form = new previewCheque(tipoDeBancoGlobal);
                form.nombre = nombre;
                form.total = total;
                form.concepto = preconcepto;
                form.numeroAletras = numeroAletras;
                form.fecha = fecha;
                form.dia = dia;
                form.ano = ano;
                form.mes = mes;
                form.origen = JRNAL_SRCE;

                form.folio = numeroDeCheque;
                form.numeroDiario = numeroDiario;
                form.FileName = FileName;
                form.FileNameToPDF = FileNameToPDF;
                form.vuelveAHacerElCheque(true);
                form.ShowDialog();
        }
Exemplo n.º 16
0
        ////////////////////////////////////////////////////////////////////
        // Define Font Resources
        ////////////////////////////////////////////////////////////////////
        private void DefineFontResources(
			PdfDocument Document
			)
        {
            // Define font resources
            // Arguments: PdfDocument class, font family name, font style, embed flag
            // Font style (must be: Regular, Bold, Italic or Bold | Italic) All other styles are invalid.
            // Embed font. If true, the font file will be embedded in the PDF file.
            // If false, the font will not be embedded
            ArialNormal = new PdfFont(Document, "Arial", FontStyle.Regular, true);
            ArialBold = new PdfFont(Document, "Arial", FontStyle.Bold, true);
            ArialItalic = new PdfFont(Document, "Arial", FontStyle.Italic, true);
            ArialBoldItalic = new PdfFont(Document, "Arial", FontStyle.Bold | FontStyle.Italic, true);
            TimesNormal = new PdfFont(Document, "Times New Roman", FontStyle.Regular, true);
            Comic = new PdfFont(Document, "Comic Sans MS", FontStyle.Bold, true);

            // substitute one character for another
            // this program supports characters 32 to 126 and 160 to 255
            // if a font has a character outside these ranges that is required by the application,
            // you can replace an unused character with this character
            ArialNormal.CharSubstitution(9679, 9679, 164);
            return;
        }
Exemplo n.º 17
0
        ////////////////////////////////////////////////////////////////////
        // Draw rectangle with rounded corners and filled with brick pattern
        ////////////////////////////////////////////////////////////////////
        private void DrawBrickPattern(
			PdfDocument Document,
			PdfContents Contents
			)
        {
            // Define brick tilling pattern resource
            // Arguments: PdfDocument class, Scale factor (0.25), Stroking color (lines between bricks), Nonstroking color (brick)
            // Return value: tilling pattern resource
            PdfTilingPattern BrickPattern = PdfTilingPattern.SetBrickPattern(Document, 0.25, Color.LightYellow, Color.SandyBrown);

            // save graphics state
            Contents.SaveGraphicsState();

            // set outline width 0.04"
            Contents.SetLineWidth(0.04);

            // set outline color to purple
            Contents.SetColorStroking(Color.Purple);

            // set fill pattern to brick
            Contents.SetPatternNonStroking(BrickPattern);

            // draw rounded rectangle filled with brick pattern
            Contents.DrawRoundedRectangle(1.13, 5.0, 1.4, 1.4, 0.2, PaintOp.CloseFillStroke);

            // restore graphics sate
            Contents.RestoreGraphicsState();
            return;
        }
Exemplo n.º 18
0
        ////////////////////////////////////////////////////////////////////
        /// <summary>
        /// PdfContents constructor unattached
        /// </summary>
        /// <param name="Document">Current PdfDocument</param>
        /// <remarks>
        /// This contents object must be explicitly attached to a page object
        /// </remarks>
        ////////////////////////////////////////////////////////////////////
        public PdfContents(
			PdfDocument Document
			)
            : base(Document, ObjectType.Stream)
        {
        }
Exemplo n.º 19
0
        private void WebView_DownloadCompleted(object sender, DownloadEventArgs e)
        {
            try
            {
                if (this.Cancelar)
                {
                    this.Cursor = System.Windows.Forms.Cursors.Arrow;
                    this.webControl1.Cursor = System.Windows.Forms.Cursors.Arrow;
                //    Mensaje.MostrarMensaje(Constantes.TipoMensaje.Detenido, "Descarga", "Proceso cancelado por el usuario");
                }
                else
                {
                    DownloadItem archivoXML = e.Item;

                    String full = archivoXML.FullPath;
                    if (new FileInfo(full).Length == 0)
                    {
                        // empty
                        System.Windows.Forms.Clipboard.SetText("archivo vacio");

                        this.cuantosNoSeInsertaron++;

                    }
                    else
                    {
                        String[] fullArray = full.Split('\\');
                        String nombreDelArchivo = fullArray.Last();

                        XmlDocument doc = new XmlDocument();
                        doc.Load(full);
                        XmlNodeList titles = doc.GetElementsByTagName("tfd:TimbreFiscalDigital");
                        XmlNode obj = titles.Item(0);

                        String noCertificadoSAT = "";
                        bool isNoCertificado = obj.Attributes["noCertificadoSAT"] != null;
                        if (isNoCertificado)
                        {
                            noCertificadoSAT = obj.Attributes["noCertificadoSAT"].InnerText;
                        }

                        String selloCFD = "";
                        bool isselloCFD = obj.Attributes["selloCFD"] != null;
                        if (isselloCFD)
                        {
                            selloCFD = obj.Attributes["selloCFD"].InnerText;
                        }

                        String selloSAT = "";
                        bool isselloSAT = obj.Attributes["selloSAT"] != null;
                        if (isselloSAT)
                        {
                            selloSAT = obj.Attributes["selloSAT"].InnerText;
                        }

                        String folio_fiscal = obj.Attributes["UUID"].InnerText;
                        folio_fiscal = folio_fiscal.ToUpper();

                        XmlNodeList titlesx = doc.GetElementsByTagName("cfdi:Receptor");
                        if (titlesx.Count == 0)
                        {
                            titlesx = doc.GetElementsByTagName("Receptor");
                        }

                        XmlNode objx = titlesx.Item(0);
                        String rfcReceptor = "";
                        String nombreReceptor = "";
                        bool isRFCrfcReceptor = objx.Attributes["rfc"] != null;
                        if (isRFCrfcReceptor)
                        {
                            rfcReceptor = objx.Attributes["rfc"].InnerText.Trim();
                        }
                        bool isRFCNombreReceptor = objx.Attributes["nombre"] != null;
                        if (isRFCNombreReceptor)
                        {
                            nombreReceptor = objx.Attributes["nombre"].InnerText;
                        }

                        XmlNodeList titles1 = doc.GetElementsByTagName("cfdi:Emisor");
                        if (titles1.Count == 0)
                        {
                            titles1 = doc.GetElementsByTagName("Emisor");
                        }

                        XmlNode obj1 = titles1.Item(0);
                        String rfc = "";
                        bool isRFC = obj1.Attributes["rfc"] != null;
                        if (isRFC)
                        {
                            rfc = obj1.Attributes["rfc"].InnerText.Trim();
                        }
                        //revisar que el RFC coincida , por lo menos uno de los 2
                        if (!rfc.Equals(Properties.Settings.Default.RFC))
                        {
                            if (!rfcReceptor.Equals(Properties.Settings.Default.RFC))
                            {
                                return;//naranjas
                            }
                        }

                        String razon = "";
                        bool isRazon = obj1.Attributes["nombre"] != null;
                        if (isRazon)
                        {
                            razon = obj1.Attributes["nombre"].InnerText;
                            razon = razon.Replace('\'', ' ');
                        }

                        XmlNodeList titles2 = doc.GetElementsByTagName("cfdi:Comprobante");
                        if (titles2.Count == 0)
                        {
                            titles2 = doc.GetElementsByTagName("Comprobante");
                        }

                        XmlNode obj2 = titles2.Item(0);

                        XmlNodeList titlesY = doc.GetElementsByTagName("cfdi:DomicilioFiscal");
                        if (titlesY.Count == 0)
                        {
                            titlesY = doc.GetElementsByTagName("DomicilioFiscal");
                        }
                        String calle = "";
                        String noExterior = "";
                        String colonia = "";
                        String municipio = "";
                        String estado = "";

                        if (titlesY.Count > 0)
                        {
                            XmlNode objY = titlesY.Item(0);
                            bool isCalle = objY.Attributes["calle"] != null;
                            if (isCalle)
                            {
                                calle = objY.Attributes["calle"].InnerText;
                            }

                            bool isnoExterior = objY.Attributes["noExterior"] != null;
                            if (isnoExterior)
                            {
                                noExterior = objY.Attributes["noExterior"].InnerText;
                            }

                            bool iscolonia = objY.Attributes["colonia"] != null;
                            if (iscolonia)
                            {
                                colonia = objY.Attributes["colonia"].InnerText;
                            }

                            bool ismunicipio = objY.Attributes["municipio"] != null;
                            if (ismunicipio)
                            {
                                municipio = objY.Attributes["municipio"].InnerText;
                            }

                            bool isestado = objY.Attributes["estado"] != null;
                            if (isestado)
                            {
                                estado = objY.Attributes["estado"].InnerText;
                            }
                        }

                        XmlNodeList titles4 = doc.GetElementsByTagName("cfdi:Impuestos");
                        if (titles4.Count == 0)
                        {
                            titles4 = doc.GetElementsByTagName("Impuestos");
                        }

                        XmlNode obj4 = titles4.Item(0);

                        String iva = "0";
                        bool isIva = obj4.Attributes["totalImpuestosTrasladados"] != null;
                        if (isIva)
                        {
                            iva = obj4.Attributes["totalImpuestosTrasladados"].InnerText;
                        }
                        else
                        {
                            XmlNodeList traslados = doc.GetElementsByTagName("cfdi:Traslado");
                            if (traslados.Count == 0)
                            {
                                traslados = doc.GetElementsByTagName("Traslado");
                            }
                            int i;
                            for (i = 0; i < traslados.Count; i++)
                            {
                                XmlNode objn = traslados.Item(i);
                                String cantidad = "0";
                                bool isCantidad = objn.Attributes["importe"] != null;
                                if (isCantidad)
                                {
                                    cantidad = objn.Attributes["importe"].InnerText;
                                }
                                iva = Convert.ToString(float.Parse(iva) + float.Parse(cantidad));
                            }
                        }

                        String subTotal = "";
                        bool isSubTotal = obj2.Attributes["subTotal"] != null;
                        if (isSubTotal)
                        {
                            subTotal = obj2.Attributes["subTotal"].InnerText;
                        }

                        String tipoDeComprobante = "INGRESO";
                        bool istipoDeComprobante = obj2.Attributes["tipoDeComprobante"] != null;
                        if (istipoDeComprobante)
                        {
                            tipoDeComprobante = obj2.Attributes["tipoDeComprobante"].InnerText.Trim().ToUpper();
                        }

                        String total = "";
                        bool isTotal = obj2.Attributes["total"] != null;
                        if (isTotal)
                        {
                            total = obj2.Attributes["total"].InnerText;
                        }

                        bool isFecha = obj2.Attributes["fecha"] != null;
                        String fecha = "";
                        if (isFecha)
                        {
                            fecha = obj2.Attributes["fecha"].InnerText;
                        }
                        bool isFolio = obj2.Attributes["folio"] != null;
                        String folio = "";
                        if (isFolio)
                        {
                            folio = obj2.Attributes["folio"].InnerText;
                        }
                        if (estoyEnCancelados)
                        {
                            String query1 = "UPDATE [" + Properties.Settings.Default.Database + "].[dbo].[facturacion_XML] set STATUS = '0' WHERE folioFiscal = '" + folio_fiscal + "'";
                            totalDeCancelados++;
                            try
                            {
                                using (SqlConnection connection = new SqlConnection(connString))
                                {
                                    connection.Open();
                                    SqlCommand cmd = new SqlCommand(query1, connection);
                                    cmd.ExecuteNonQuery();

                                    String queryCheck1 = "SELECT BUNIT, JRNAL_NO, JRNAL_LINE, CONCEPTO, FUNCION, PROJECT, descripcionLI, AMOUNT, Consecutivo, FOLIO_FISCAL FROM [" + Properties.Settings.Default.Database + "].[dbo].[FISCAL_xml] WHERE folioFiscal = '" + folio_fiscal + "'";
                                    SqlCommand cmdCheck = new SqlCommand(queryCheck1, connection);
                                    SqlDataReader reader = cmdCheck.ExecuteReader();

                                    if (reader.HasRows)
                                    {
                                        String BUNIT = "";
                                        String JRNAL_NO = "";
                                        String JRNAL_LINE = "";
                                        String CONCEPTO = "";
                                        String FUNCION = "";
                                        String PROJECT = "";
                                        String descripcionLI = "";
                                        String AMOUNT = "";
                                        String Consecutivo = "";
                                        String FOLIO_FISCAL = "";
                                        mensajeParaElCorreo.Append(this.Enters + "Los cancelados estan ligados a los siguientes movimientos: ");
                                        while (reader.Read())
                                        {
                                            BUNIT = reader.GetString(0).Trim();
                                            JRNAL_NO = Convert.ToString(reader.GetInt32(1));
                                            JRNAL_LINE = Convert.ToString(reader.GetInt32(2));
                                            CONCEPTO = reader.GetString(3).Trim();
                                            FUNCION = reader.GetString(4).Trim();
                                            PROJECT = reader.GetString(5).Trim();
                                            descripcionLI = reader.GetString(6).Trim();
                                            AMOUNT = Convert.ToString(reader.GetDecimal(7));
                                            Consecutivo = reader.GetString(8).Trim();
                                            FOLIO_FISCAL = reader.GetString(9).Trim();

                                            mensajeParaElCorreo.Append(this.Enters + BUNIT + " " + JRNAL_NO + " " + JRNAL_LINE + " " + CONCEPTO + " " + FUNCION + " " + PROJECT + " " + descripcionLI + " " + AMOUNT + " " + FOLIO_FISCAL + " " + Consecutivo);

                                        }
                                    }
                                }
                            }
                            catch (Exception ex1)
                            {
                                System.Windows.Forms.MessageBox.Show(ex1.ToString(), "Error Message1", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            }

                        }
                        else
                        {

                            String query = "";
                            int STATUS = -1;
                            if (this.AnoSel.IndexOf("Emitidos") != -1)
                            {
                                if (tipoDeComprobante.Equals("INGRESO"))
                                {
                                    STATUS = 2;
                                    query = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[facturacion_XML] (folioFiscal,nombreArchivoXML,ruta,rfc,razonSocial,total,folio,fechaExpedicion,nombreArchivoPDF,STATUS,ocultaEnLigar,rfcRaiz) VALUES ('" + folio_fiscal + "', '" + nombreDelArchivo + "', '" + carpeta.Text + (object)Path.DirectorySeparatorChar + this.AnoSel + (object)Path.DirectorySeparatorChar + this.MesSel + (object)Path.DirectorySeparatorChar + diaActual + "', '" + rfcReceptor + "', '" + nombreReceptor + "', " + total + ", '" + folio + "' , '" + fecha + "', '" + folio_fiscal + ".pdf','2',0,'" + Properties.Settings.Default.RFC + "')";
                                }
                                else
                                {
                                    STATUS = 1;
                                    query = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[facturacion_XML] (folioFiscal,nombreArchivoXML,ruta,rfc,razonSocial,total,folio,fechaExpedicion,nombreArchivoPDF,STATUS,ocultaEnLigar,rfcRaiz) VALUES ('" + folio_fiscal + "', '" + nombreDelArchivo + "', '" + carpeta.Text + (object)Path.DirectorySeparatorChar + this.AnoSel + (object)Path.DirectorySeparatorChar + this.MesSel + (object)Path.DirectorySeparatorChar + diaActual + "', '" + rfcReceptor + "', '" + nombreReceptor + "', " + total + ", '" + folio + "' , '" + fecha + "', '" + folio_fiscal + ".pdf','1',0,'" + Properties.Settings.Default.RFC + "')";
                                }
                                insertaProveedor(rfcReceptor, nombreReceptor);
                                sincroniza(fecha, rfcReceptor, nombreReceptor, STATUS, total, folio, folio_fiscal, Properties.Settings.Default.RFC, "");
                            }
                            else
                            {
                                if (tipoDeComprobante.Equals("INGRESO"))
                                {
                                    STATUS = 1;
                                    query = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[facturacion_XML] (folioFiscal,nombreArchivoXML,ruta,rfc,razonSocial,total,folio,fechaExpedicion,nombreArchivoPDF,STATUS,ocultaEnLigar,rfcRaiz) VALUES ('" + folio_fiscal + "', '" + nombreDelArchivo + "', '" + carpeta.Text + (object)Path.DirectorySeparatorChar + this.AnoSel + (object)Path.DirectorySeparatorChar + this.MesSel + (object)Path.DirectorySeparatorChar + diaActual + "', '" + rfc + "', '" + razon + "', " + total + ", '" + folio + "' , '" + fecha + "', '" + folio_fiscal + ".pdf','1',0,'" + Properties.Settings.Default.RFC + "')";
                                }
                                else
                                {
                                    STATUS = 2;
                                    query = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[facturacion_XML] (folioFiscal,nombreArchivoXML,ruta,rfc,razonSocial,total,folio,fechaExpedicion,nombreArchivoPDF,STATUS,ocultaEnLigar,rfcRaiz) VALUES ('" + folio_fiscal + "', '" + nombreDelArchivo + "', '" + carpeta.Text + (object)Path.DirectorySeparatorChar + this.AnoSel + (object)Path.DirectorySeparatorChar + this.MesSel + (object)Path.DirectorySeparatorChar + diaActual + "', '" + rfc + "', '" + razon + "', " + total + ", '" + folio + "' , '" + fecha + "', '" + folio_fiscal + ".pdf','2',0,'" + Properties.Settings.Default.RFC + "')";
                                }
                                //query = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[facturacion_XML] (folioFiscal,nombreArchivoXML,ruta,rfc,razonSocial,total,folio,fechaExpedicion,nombreArchivoPDF,STATUS,ocultaEnLigar) VALUES ('" + folio_fiscal + "', '" + nombreDelArchivo + "', '" + carpeta.Text + (object)Path.DirectorySeparatorChar + this.AnoSel + (object)Path.DirectorySeparatorChar + this.MesSel + (object)Path.DirectorySeparatorChar + diaActual + "', '" + rfc + "', '" + razon + "', " + total + ", '" + folio + "' , '" + fecha + "', '" + folio_fiscal + ".pdf','1',0)";
                                insertaProveedor(rfc, razon);
                                sincroniza(fecha, rfc,  razon,  STATUS,  total,  folio,  folio_fiscal, Properties.Settings.Default.RFC, "");
                            }
                            String queryCheck = "SELECT * FROM [" + Properties.Settings.Default.Database + "].[dbo].[facturacion_XML] WHERE folioFiscal = '" + folio_fiscal + "'";

                            try
                            {
                                using (SqlConnection connection = new SqlConnection(connString))
                                {
                                    connection.Open();
                                    SqlCommand cmdCheck = new SqlCommand(queryCheck, connection);
                                    SqlDataReader reader = cmdCheck.ExecuteReader();
                                    if (!reader.Read())
                                    {
                                        reader.Close();
                                        connection.Close();
                                        connection.Open();
                                        SqlCommand cmd = new SqlCommand(query, connection);
                                        cmd.ExecuteNonQuery();
                                        PdfContents Contents = null;
                                        PdfPage Page = null;
                                        const Double Width = 5.15;
                                        const Double Height = 10.65;
                                        const Double FontSize = 9.0;
                                        PdfFileWriter.TextBox Box = null;
                                        if (cadaCuantasHorasGlobal == 0 || 1 == 1)//no estoy en modo de horas
                                        {
                                            String FileName = carpeta.Text + (object)Path.DirectorySeparatorChar + this.AnoSel + (object)Path.DirectorySeparatorChar + this.MesSel + (object)Path.DirectorySeparatorChar + diaActual.ToString() + (object)Path.DirectorySeparatorChar + folio_fiscal + ".pdf";
                                            Document = new PdfDocument(PaperType.Letter, false, UnitOfMeasure.Inch, FileName);
                                            DefineFontResources();
                                            DefineTilingPatternResource();
                                            Page = new PdfPage(Document);
                                            Contents = new PdfContents(Page);
                                            Contents.SaveGraphicsState();
                                            Contents.Translate(0.1, 0.1);
                                            Box = new PdfFileWriter.TextBox(Width, 0.25);
                                        }
                                        XmlNodeList conceptos = doc.GetElementsByTagName("cfdi:Concepto");
                                        if (conceptos.Count == 0)
                                        {
                                            conceptos = doc.GetElementsByTagName("Concepto");
                                        }

                                        int i;
                                        String conceptosString = "";
                                        for (i = 0; i < conceptos.Count; i++)
                                        {
                                            XmlNode objy = conceptos.Item(i);
                                            String cantidadc = "";
                                            bool isCantidadc = objy.Attributes["cantidad"] != null;
                                            if (isCantidadc)
                                            {
                                                cantidadc = objy.Attributes["cantidad"].InnerText;
                                            }
                                            String unidadc = "";
                                            bool isUnidadc = objy.Attributes["unidad"] != null;
                                            if (isUnidadc)
                                            {
                                                unidadc = objy.Attributes["unidad"].InnerText;
                                            }
                                            String descripcionc = "";
                                            bool isdescripcionc = objy.Attributes["descripcion"] != null;
                                            if (isdescripcionc)
                                            {
                                                descripcionc = objy.Attributes["descripcion"].InnerText;
                                            }
                                            String importec = "";
                                            bool isimportec = objy.Attributes["importe"] != null;
                                            if (isimportec)
                                            {
                                                importec = objy.Attributes["importe"].InnerText;
                                            }
                                            conceptosString = conceptosString + "\n" + cantidadc + " " + descripcionc + " $" + importec;
                                        }
                                        String impuestosString = "";
                                        double totalDeRetenciones = 0;
                                        XmlNodeList retencionesLocales = doc.GetElementsByTagName("implocal:RetencionesLocales");
                                        if (retencionesLocales.Count == 0)
                                        {
                                            retencionesLocales = doc.GetElementsByTagName("RetencionesLocales");
                                        }
                                        for (i = 0; i < retencionesLocales.Count; i++)
                                        {
                                            XmlNode objn = retencionesLocales.Item(i);
                                            String cantidad = "0";
                                            String impuesto = "";
                                            float tasa = 0;
                                            bool isCantidad = objn.Attributes["Importe"] != null;
                                            if (isCantidad)
                                            {
                                                totalDeRetenciones += Convert.ToDouble(objn.Attributes["Importe"].InnerText);
                                                cantidad = objn.Attributes["Importe"].InnerText;
                                                impuesto = objn.Attributes["ImpLocRetenido"].InnerText;
                                                tasa = float.Parse(objn.Attributes["TasadeRetencion"].InnerText);
                                                float importe = float.Parse(cantidad);
                                                String queryCheckImpuesto = "SELECT * FROM [" + Properties.Settings.Default.Database + "].[dbo].[impuestos] WHERE folioFiscal = '" + folio_fiscal + "' and impuesto = '" + impuesto + "' and tasa = " + tasa + " and importe = " + importe;
                                                SqlCommand cmdCheckImpuesto = new SqlCommand(queryCheckImpuesto, connection);
                                                SqlDataReader readerImpuesto = cmdCheckImpuesto.ExecuteReader();
                                                impuestosString = impuestosString + "\nImpuesto: " + impuesto + "\nTasa: " + tasa + "\nImporte: " + importe;
                                                if (!readerImpuesto.HasRows)
                                                {
                                                    readerImpuesto.Close();
                                                    String queryImpuesto = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[impuestos] (folioFiscal,impuesto,tasa,importe,tipo,rfcRaiz) VALUES ('" + folio_fiscal + "', '" + impuesto + "', " + tasa + ", " + importe + ",2,'" + Properties.Settings.Default.RFC + "')";
                                                    SqlCommand cmdImpuesto = new SqlCommand(queryImpuesto, connection);
                                                    cmdImpuesto.ExecuteNonQuery();
                                                }
                                                else
                                                {
                                                    readerImpuesto.Close();
                                                }
                                            }
                                            iva = Convert.ToString(float.Parse(iva) + float.Parse(cantidad));
                                        }

                                        XmlNodeList retenciones = doc.GetElementsByTagName("cfdi:Retencion");
                                        if (retenciones.Count == 0)
                                        {
                                            retenciones = doc.GetElementsByTagName("Retencion");
                                        }

                                        for (i = 0; i < retenciones.Count; i++)
                                        {
                                            XmlNode objn = retenciones.Item(i);
                                            String cantidad = "0";
                                            String impuesto = "";
                                            float tasa = 0;
                                            bool isCantidad = objn.Attributes["importe"] != null;
                                            if (isCantidad)
                                            {
                                                totalDeRetenciones += Convert.ToDouble(objn.Attributes["importe"].InnerText);
                                                cantidad = objn.Attributes["importe"].InnerText;
                                                impuesto = objn.Attributes["impuesto"].InnerText;
                                                tasa = 0;
                                                float importe = float.Parse(cantidad);
                                                String queryCheckImpuesto = "SELECT * FROM [" + Properties.Settings.Default.Database + "].[dbo].[impuestos] WHERE folioFiscal = '" + folio_fiscal + "' and impuesto = '" + impuesto + "' and tasa = " + tasa + " and importe = " + importe;
                                                SqlCommand cmdCheckImpuesto = new SqlCommand(queryCheckImpuesto, connection);
                                                SqlDataReader readerImpuesto = cmdCheckImpuesto.ExecuteReader();
                                                impuestosString = impuestosString + "\nImpuesto: " + impuesto + "\nImporte: " + importe;
                                                if (!readerImpuesto.HasRows)
                                                {
                                                    readerImpuesto.Close();
                                                    String queryImpuesto = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[impuestos] (folioFiscal,impuesto,tasa,importe,tipo,rfcRaiz) VALUES ('" + folio_fiscal + "', '" + impuesto + "', " + tasa + ", " + importe + ",2,'" + Properties.Settings.Default.RFC + "')";
                                                    SqlCommand cmdImpuesto = new SqlCommand(queryImpuesto, connection);
                                                    cmdImpuesto.ExecuteNonQuery();
                                                }
                                                else
                                                {
                                                    readerImpuesto.Close();
                                                }
                                            }
                                            iva = Convert.ToString(float.Parse(iva) + float.Parse(cantidad));
                                        }

                                        if (totalDeRetenciones > 0.0)
                                        {
                                            double nuevoTotal = Math.Round(totalDeRetenciones + Convert.ToDouble(total), 2);
                                            String query2 = "UPDATE [" + Properties.Settings.Default.Database + "].[dbo].[facturacion_XML] set total = " + nuevoTotal + "  WHERE folioFiscal = '" + folio_fiscal + "'";
                                            try
                                            {
                                                using (SqlCommand cmdx = new SqlCommand(query2, connection))
                                                {
                                                    cmd.ExecuteNonQuery();
                                                }
                                            }
                                            catch (Exception ex3)
                                            {
                                                ex3.ToString();
                                            }
                                        }

                                        XmlNodeList trasladosLocales = doc.GetElementsByTagName("implocal:TrasladosLocales");
                                        if (trasladosLocales.Count == 0)
                                        {
                                            trasladosLocales = doc.GetElementsByTagName("TrasladosLocales");
                                        }
                                        for (i = 0; i < trasladosLocales.Count; i++)
                                        {
                                            XmlNode objn = trasladosLocales.Item(i);
                                            String cantidad = "0";
                                            String impuesto = "";
                                            float tasa = 0;
                                            bool isCantidad = objn.Attributes["Importe"] != null;
                                            if (isCantidad)
                                            {
                                                cantidad = objn.Attributes["Importe"].InnerText;
                                                impuesto = objn.Attributes["ImpLocTrasladado"].InnerText;
                                                tasa = float.Parse(objn.Attributes["TasadeTraslado"].InnerText);
                                                float importe = float.Parse(cantidad);
                                                String queryCheckImpuesto = "SELECT * FROM [" + Properties.Settings.Default.Database + "].[dbo].[impuestos] WHERE folioFiscal = '" + folio_fiscal + "' and impuesto = '" + impuesto + "' and tasa = " + tasa + " and importe = " + importe;
                                                SqlCommand cmdCheckImpuesto = new SqlCommand(queryCheckImpuesto, connection);
                                                SqlDataReader readerImpuesto = cmdCheckImpuesto.ExecuteReader();
                                                impuestosString = impuestosString + "\nImpuesto: " + impuesto + "\nTasa: " + tasa + "\nImporte: " + importe;
                                                if (!readerImpuesto.HasRows)
                                                {
                                                    readerImpuesto.Close();
                                                    String queryImpuesto = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[impuestos] (folioFiscal,impuesto,tasa,importe,tipo,rfcRaiz) VALUES ('" + folio_fiscal + "', '" + impuesto + "', " + tasa + ", " + importe + ",1,'" + Properties.Settings.Default.RFC + "')";
                                                    SqlCommand cmdImpuesto = new SqlCommand(queryImpuesto, connection);
                                                    cmdImpuesto.ExecuteNonQuery();
                                                }
                                                else
                                                {
                                                    readerImpuesto.Close();
                                                }
                                            }
                                            iva = Convert.ToString(float.Parse(iva) + float.Parse(cantidad));
                                        }

                                        XmlNodeList traslados = doc.GetElementsByTagName("cfdi:Traslado");
                                        if (traslados.Count == 0)
                                        {
                                            traslados = doc.GetElementsByTagName("Traslado");
                                        }
                                        for (i = 0; i < traslados.Count; i++)
                                        {
                                            XmlNode objn = traslados.Item(i);
                                            String cantidad = "0";
                                            String impuesto = "";
                                            float tasa = 0;
                                            bool isCantidad = objn.Attributes["importe"] != null;
                                            if (isCantidad)
                                            {
                                                cantidad = objn.Attributes["importe"].InnerText;
                                                impuesto = objn.Attributes["impuesto"].InnerText;
                                                tasa = float.Parse(objn.Attributes["tasa"].InnerText);
                                                float importe = float.Parse(cantidad);
                                                String queryCheckImpuesto = "SELECT * FROM [" + Properties.Settings.Default.Database + "].[dbo].[impuestos] WHERE folioFiscal = '" + folio_fiscal + "' and impuesto = '" + impuesto + "' and tasa = " + tasa + " and importe = " + importe;
                                                SqlCommand cmdCheckImpuesto = new SqlCommand(queryCheckImpuesto, connection);
                                                SqlDataReader readerImpuesto = cmdCheckImpuesto.ExecuteReader();
                                                impuestosString = impuestosString + "\nImpuesto: " + impuesto + "\nTasa: " + tasa + "\nImporte: " + importe;
                                                if (!readerImpuesto.HasRows)
                                                {
                                                    readerImpuesto.Close();
                                                    String queryImpuesto = "INSERT INTO [" + Properties.Settings.Default.Database + "].[dbo].[impuestos] (folioFiscal,impuesto,tasa,importe,tipo,rfcRaiz) VALUES ('" + folio_fiscal + "', '" + impuesto + "', " + tasa + ", " + importe + ",1,'" + Properties.Settings.Default.RFC + "')";
                                                    SqlCommand cmdImpuesto = new SqlCommand(queryImpuesto, connection);
                                                    cmdImpuesto.ExecuteNonQuery();
                                                }
                                                else
                                                {
                                                    readerImpuesto.Close();
                                                }
                                            }
                                            iva = Convert.ToString(float.Parse(iva) + float.Parse(cantidad));
                                        }
                                        if (cadaCuantasHorasGlobal == 0 || 1 == 1)//no estoy en modo de horas
                                        {
                                            Box.AddText(ArialNormal, FontSize,
                                           "Cliente: " + nombreReceptor + "\n" +
                                           "RFC: " + rfcReceptor + "\n" +
                                           "Emisor: " + razon + "\n" +
                                           "RFC: " + rfc + "\n" +
                                           "Domicilio Fiscal: " + calle + " " + noExterior + " " + colonia + " " + municipio + " " + estado + "\n" +
                                           "Folio: " + folio + "\nFolio Fiscal: " + folio_fiscal + "\nTotal: $" + total + "\nFecha de Expedicion: " + fecha + conceptosString + impuestosString + "\nNo de Serie del Certificado del SAT: " + noCertificadoSAT + "\nSello digital del CFDI:\n" + selloCFD + "\n\nSello del SAT:\n" + selloSAT + "\n\n\nEste documento es una representación impresa de un CFDI");
                                            Box.AddText(ArialNormal, FontSize, "\n");
                                            Double PosY = Height;
                                            Contents.DrawText(0.0, ref PosY, 0.0, 0, 0.015, 0.05, TextBoxJustify.FitToWidth, Box);
                                            Contents.RestoreGraphicsState();
                                            Contents.SaveGraphicsState();
                                            String DataString = "?re=" + rfc + "&rr=" + rfcReceptor + "&tt=" + total + "&id=" + folio_fiscal;
                                            PdfQRCode QRCode = new PdfQRCode(Document, DataString, ErrorCorrection.M);
                                            Contents.DrawQRCode(QRCode, 6.0, 6.8, 1.2);
                                            Contents.RestoreGraphicsState();
                                            Document.CreateFile();
                                        }
                                        totalDeDescargados++;
                                    }
                                    else
                                    {
                                        this.cuantosYaExistian++;
                                        totalDeYaExistian++;
                                    }

                                }
                            }
                            catch (Exception ex1)
                            {
                                ex1.ToString();
                                System.Windows.Forms.Clipboard.SetText(query);

                                this.cuantosNoSeInsertaron++;
                                //   System.Windows.Forms.MessageBox.Show("Error Message", ex1.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            }
                        }//else if estoyEnCancelados
                    }//else de empty

                    ++this.posicion;
                    if (this.posicion < this.ligas.Count)
                    {
                        if (!this.Cancelar)
                        {
                            this.Descargados.Add(e.Item);
                            this.proceso.Text = string.Format("Descargando {0} de {1}, Ya existian: {2}, Con errores: {3} ", (object)(this.posicion + 1), (object)this.ligas.Count.ToString() , (object)this.cuantosYaExistian, (object)this.cuantosNoSeInsertaron);
                            this.Descarga();
                        }
                        else
                        {
                            this.Cursor = System.Windows.Forms.Cursors.Arrow;
                            this.webControl1.Cursor = System.Windows.Forms.Cursors.Arrow;
                 //           Mensaje.MostrarMensaje(Constantes.TipoMensaje.Detenido, "Descarga", "Proceso cancelado por el usuario");
                        }
                    }
                    else
                    {

                        //                  enQueHoraVoyGlobal
                        //                    cadaCuantasHorasGlobal

                        int horaQueSigue = enQueHoraVoyGlobal + cadaCuantasHorasGlobal;
                        if(horaQueSigue<24 && cadaCuantasHorasGlobal!=0)//sigue con las horas
                        {
                            enQueHoraVoyGlobal = enQueHoraVoyGlobal + cadaCuantasHorasGlobal;
                            if(estoyEnEmitidos)
                            {
                                tmrDecimoCuarto.Start();
                            }
                            else
                            {
                                tmrQuintoPrimo.Start();
                            }
                        }
                        else
                        {//cambia el dia
                            enQueHoraVoyGlobal = 0;
                            //cambia un dia
                            if (modoGlobal == 2 && estoyEnEmitidos)
                            {
                                DateTime now = DateTime.Now;
                                int year = now.Year - anoAnterior;
                                int month = now.Month;
                                if (modoGlobal == 2)//ultrapesado
                                {
                                    month = mesActual + 1;
                                }

                                int diaFinal = 28;
                                if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
                                {
                                    diaFinal = 31;
                                }
                                else
                                {
                                    if (month == 4 || month == 6 || month == 9 || month == 11)
                                    {
                                        diaFinal = 30;
                                    }
                                    else
                                    {
                                        if (year % 4 == 0)//ano bisiesto
                                        {
                                            diaFinal = 29;
                                        }
                                    }
                                }

                                if (diaActual < diaFinal)
                                {
                                    diaActual++;
                                    tmrDecimoCuarto.Start();
                                    return;
                                }
                                else
                                {
                                    diaActual = 1;
                                    if (mesActual < 11)
                                    {
                                        mesActual++;
                                        tmrDecimoCuarto.Start();
                                        return;
                                    }
                                    else
                                    {
                                        tmrDecimoSexto.Start();
                                        return;
                                    }
                                }

                            }
                            if (modoGlobal == 1)
                            {
                                if (estoyEnEmitidos)
                                {
                                    mandaCorreo();
                                }
                                else
                                {
                                    empiezaConLosEmitidos();
                                }
                            }
                            else
                            {
                                this.proceso.Text = string.Format("Descargando {0} de {1}, Ya existian: {2}, Con errores: {3}", (object)this.posicion, (object)this.ligas.Count.ToString(), (object)this.cuantosYaExistian, (object)this.cuantosNoSeInsertaron);
                                this.Descargados.Add(e.Item);
                                this.Cursor = System.Windows.Forms.Cursors.Arrow;
                                this.webControl1.Cursor = System.Windows.Forms.Cursors.Arrow;
                                this.proceso.Text = string.Format("Descarga Finalizada {0} de {1}, Ya existian: {2}, Con errores: {3}", (object)this.posicion, (object)this.ligas.Count.ToString(), (object)this.cuantosYaExistian, (object)this.cuantosNoSeInsertaron);
                                if (estoyEnCancelados)
                                {
                                    //ya termine
                                    mensajeParaElCorreo.Append(totalDeCancelados);
                                    return;
                                }
                                if (!estoyEnCancelados && estoyEnEmitidos)
                                {
                                    //agregar para debuguear emitidos
                                    mensajeParaElCorreo.Append(Enters + Enters + "Facturas Emitidas totales: " + (object)this.ligas.Count.ToString() + " Ya existian: " + (object)this.cuantosYaExistian);
                                    tmrDecimoSexto.Start();
                                    return;
                                }
                                DateTime now = DateTime.Now;
                                int year = now.Year - anoAnterior;
                                int month = now.Month;
                                if (modoGlobal == 2)//ultrapesado
                                {
                                    month = mesActual + 1;
                                }

                                int diaFinal = 28;
                                if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
                                {
                                    diaFinal = 31;
                                }
                                else
                                {
                                    if (month == 4 || month == 6 || month == 9 || month == 11)
                                    {
                                        diaFinal = 30;
                                    }
                                    else
                                    {
                                        if (year % 4 == 0)//ano bisiesto
                                        {
                                            diaFinal = 29;
                                        }
                                    }
                                }

                                if (diaActual < diaFinal)
                                {
                                    diaActual++;
                                    if (estoyEnElMesAnterior)
                                    {
                                        tmrDecimo.Start();
                                    }
                                    else
                                    {
                                        if(cadaCuantasHorasGlobal==0)//sin horas
                                        {
                                            tmrQuinto.Start();
                                        }
                                        else
                                        {
                                            tmrQuintoPrimo.Start();
                                        }

                                    }
                                }
                                else
                                {
                                    if (estoyEnElMesAnterior)
                                    {
                                        estoyEnElMesAnterior = false;
                                        diaActual = 1;
                                        empiezaConLosCancelados();
                                    }
                                    else
                                    {
                                        if (modoGlobal == 2)//ultrapesado
                                        {
                                            if (mesActual < 11)
                                            {
                                                mesActual++;
                                                diaActual = 1;
                                                tmrDecimo.Start();
                                            }
                                            else
                                            {
                                                estoyEnElMesAnterior = false;
                                                diaActual = 1;
                                                mesActual = 0;
                                                empiezaConLosCancelados();
                                            }
                                        }
                                        else//modo pesado
                                        {
                                            empiezaConElMesAnterior();
                                        }
                                    }
                                }
                            }
                        }//if cambia un dia
                    }
                }
            }
            catch (Exception ex)
            {
               System.Windows.Forms.MessageBox.Show( ex.ToString(), "Error Title2", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

               //  Logs.Escribir("Error en download complete : " + ex.ToString());
            }
        }
Exemplo n.º 20
0
        ////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Constructor for image file
        /// </summary>
        /// <param name="Document">PDF document (parent object)</param>
        /// <param name="ImageFileName">Image file name</param>
        /// <param name="Resolution">Resolution in pixels per inch (optional)</param>
        /// <param name="ImageQuality">Image quality 0 to 100 or -1 (optional)</param>
        /// <remarks>
        /// <para>Image quality is a parameter that used by the .net framework
        /// during the compression of the image from bitmap to jpeg. If the parameter
        /// is missing or set to -1 the library saves the bitmap image as</para>
        /// <code>
        ///	Bitmap.Save(MemoryStream, ImageFormat.Jpeg);
        ///	</code>
        ///	<para>If the ImageQuality parameter is 0 to 100, the library saves the bitmap image as</para>
        ///	<code>
        ///	EncoderParameters EncoderParameters = new EncoderParameters(1);
        /// EncoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ImageQuality);
        /// Bitmap.Save(MemoryStream, GetEncoderInfo("image/jpeg"), EncoderParameters);
        ///	</code>
        ///	<para>Microsoft does not specify the image quality factor used in the 
        ///	first method of saving. However, experimantaion and Internet comments shows that it is 75.</para>
        /// </remarks>
        ////////////////////////////////////////////////////////////////////
        public PdfImage(
			PdfDocument		Document,
			String			ImageFileName,
			Double			Resolution = 0.0,		// pixels per inch
			Int32			ImageQuality = -1		// 0 to 100 or -1 for default save or -1 for default save
			)
            : base(Document, ObjectType.Stream, "/XObject")
        {
            ConstructorHelper(ImageFileName, null, Rectangle.Empty, RectangleF.Empty, Resolution, ImageQuality);
            return;
        }
Exemplo n.º 21
0
        ////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Constructor for image object
        /// </summary>
        /// <param name="Document">PDF document (parent object)</param>
        /// <param name="Image">Image bitmap or metafile</param>
        /// <param name="CropPercent">Crop rectangle (in percent of width and height)</param>
        /// <param name="Resolution">Resolution in pixels per inch (optional)</param>
        /// <param name="ImageQuality">Image quality 0 to 100 or -1 (optional)</param>
        /// <remarks>
        /// <para>Image quality is a parameter that used by the .net framework
        /// during the compression of the image from bitmap to jpeg. If the parameter
        /// is missing or set to -1 the library saves the bitmap image as</para>
        /// <code>
        ///	Bitmap.Save(MemoryStream, ImageFormat.Jpeg);
        ///	</code>
        ///	<para>If the ImageQuality parameter is 0 to 100, the library saves the bitmap image as</para>
        ///	<code>
        ///	EncoderParameters EncoderParameters = new EncoderParameters(1);
        /// EncoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ImageQuality);
        /// Bitmap.Save(MemoryStream, GetEncoderInfo("image/jpeg"), EncoderParameters);
        ///	</code>
        ///	<para>Microsoft does not specify the image quality factor used in the 
        ///	first method of saving. However, experimantaion and Internet comments shows that it is 75.</para>
        /// </remarks>
        ////////////////////////////////////////////////////////////////////
        public PdfImage(
			PdfDocument		Document,
			Image			Image,
			RectangleF		CropPercent,
			Double			Resolution = 0.0,		// pixels per inch
			Int32			ImageQuality = -1		// 0 to 100 or -1 for default save
			)
            : base(Document, ObjectType.Stream, "/XObject")
        {
            ConstructorHelper(null, Image, Rectangle.Empty, CropPercent, Resolution, ImageQuality);
            return;
        }
Exemplo n.º 22
0
 ////////////////////////////////////////////////////////////////////
 /// <summary>
 /// PDF print document constructor
 /// </summary>
 /// <param name="Document">Current PDF document</param>
 /// <remarks>
 /// Set resolution to 96 pixels per inch
 /// </remarks>
 ////////////////////////////////////////////////////////////////////
 public PdfPrintDocument
 (
     PdfDocument Document
 ) : this(Document, 96.0)
 {
 }
Exemplo n.º 23
0
        ////////////////////////////////////////////////////////////////////
        // Constructor for XObject or Pattern
        ////////////////////////////////////////////////////////////////////
        internal PdfContents(
			PdfDocument	Document,
			String		PdfObjectType
			)
            : base(Document, ObjectType.Stream, PdfObjectType)
        {
        }
        ////////////////////////////////////////////////////////////////////
        /// <summary>
        /// PDF print document constructor
        /// </summary>
        /// <param name="Document">Current PDF document</param>
        /// <remarks>
        /// Set resolution to 96 pixels per inch
        /// </remarks>
        ////////////////////////////////////////////////////////////////////
        public PdfPrintDocument(
			PdfDocument Document
			)
            : this(Document, 96.0)
        {
        }
Exemplo n.º 25
0
        ////////////////////////////////////////////////////////////////////
        // Define Tiling Pattern Resource
        ////////////////////////////////////////////////////////////////////
        private void DefineTilingPatternResource(
			PdfDocument Document
			)
        {
            // create empty tiling pattern
            WaterMark = new PdfTilingPattern(Document);

            // the pattern will be PdfFileWriter laied out in brick pattern
            String Mark = "PdfFileWriter";

            // text width and height for Arial bold size 18 points
            Double FontSize = 18.0;
            Double TextWidth = ArialBold.TextWidth(FontSize, Mark);
            Double TextHeight = ArialBold.LineSpacing(FontSize);

            // text base line
            Double BaseLine = ArialBold.DescentPlusLeading(FontSize);

            // the overall pattern box (we add text height value as left and right text margin)
            Double BoxWidth = TextWidth + 2 * TextHeight;
            Double BoxHeight = 4 * TextHeight;
            WaterMark.SetTileBox(BoxWidth, BoxHeight);

            // save graphics state
            WaterMark.SaveGraphicsState();

            // fill the pattern box with background light blue color
            WaterMark.SetColorNonStroking(Color.FromArgb(230, 244, 255));
            WaterMark.DrawRectangle(0, 0, BoxWidth, BoxHeight, PaintOp.Fill);

            // set fill color for water mark text to white
            WaterMark.SetColorNonStroking(Color.White);

            // draw PdfFileWriter at the bottom center of the box
            WaterMark.DrawText(ArialBold, FontSize, BoxWidth / 2, BaseLine, TextJustify.Center, Mark);

            // adjust base line upward by half height
            BaseLine += BoxHeight / 2;

            // draw the right half of PdfFileWriter shifted left by half width
            WaterMark.DrawText(ArialBold, FontSize, 0.0, BaseLine, TextJustify.Center, Mark);

            // draw the left half of PdfFileWriter shifted right by half width
            WaterMark.DrawText(ArialBold, FontSize, BoxWidth, BaseLine, TextJustify.Center, Mark);

            // restore graphics state
            WaterMark.RestoreGraphicsState();
            return;
        }
        ////////////////////////////////////////////////////////////////////
        /// <summary>
        /// PDF print document constructor
        /// </summary>
        /// <param name="Document">Current PDF document</param>
        /// <param name="Resolution">Image resolution</param>
        ////////////////////////////////////////////////////////////////////
        public PdfPrintDocument(
			PdfDocument Document,
			Double		Resolution			// printer resolution in pixels per inch
			)
        {
            // save document
            this.Document = Document;

            // save resolution
            this.Resolution = Resolution;

            // create print document and preview controller objects
            PrintController = new PreviewPrintController();

            // copy document's page size to default settings
            // convert page size from points to 100th of inch
            // do not set lanscape flag
            PaperSize PSize = new PaperSize();
            PSize.Width = (Int32) (Document.PageSize.Width / 0.72 + 0.5);
            PSize.Height = (Int32) (Document.PageSize.Height / 0.72 + 0.5);
            DefaultPageSettings.PaperSize = PSize;

            // assume document is in color
            DefaultPageSettings.Color = true;
            return;
        }
Exemplo n.º 27
0
        private void DrawPicturePai(
            PdfDocument Document,
            PdfContents Contents
            )
        {
            // define local image resources
            PdfImage Image1 = new PdfImage(Document, "D:\\visual studio 2012\\TestPDFFileWriter\\TestPDFFileWriter\\logo.png");

            // image size will be limited to 1.4" by 1.4"
            SizeD ImageSize = Image1.ImageSize(1.4, 1.4);

            // save graphics state
            Contents.SaveGraphicsState();

            // translate coordinate origin to the center of the picture
            Contents.Translate(3.36, 5.7);

            // clipping path
            //   Contents.DrawOval(-ImageSize.Width / 2, -ImageSize.Height / 2, ImageSize.Width, ImageSize.Height, PaintOp.ClipPathEor);

            // draw image
            Contents.DrawImage(Image1, -ImageSize.Width / 2, -ImageSize.Height / 2, ImageSize.Width, ImageSize.Height);

            // restore graphics state
            Contents.RestoreGraphicsState();
            return;
        }
Exemplo n.º 28
0
        ////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Static method to create .NET Chart object.
        /// </summary>
        /// <param name="Document">Current document object.</param>
        /// <param name="Width">Chart width in user units.</param>
        /// <param name="Height">Chart height in user units.</param>
        /// <param name="Resolution">Resolution in pixels per inch (optional argument).</param>
        /// <returns>.NET Chart object</returns>
        /// <remarks>
        /// The returned chart has the correct width and height in pixels.
        /// </remarks>
        ////////////////////////////////////////////////////////////////////
        public static Chart CreateChart(
			PdfDocument		Document,
			Double			Width,
			Double			Height,
			Double			Resolution = 0.0
			)
        {
            // create chart
            Chart Chart = new Chart();

            // save resolution
            if(Resolution != 0) Chart.RenderingDpiY = Resolution;

            // image size in pixels
            Chart.Width = (Int32) (Chart.RenderingDpiY * Width * Document.ScaleFactor / 72.0 + 0.5);
            Chart.Height = (Int32) (Chart.RenderingDpiY * Height * Document.ScaleFactor / 72.0 + 0.5);

            // return chart
            return(Chart);
        }
Exemplo n.º 29
0
		void CreatePDFFile( IEnumerable<ScannedImageViewModel> items, string filename )
		{
			try
			{
				// Save document
				var Document = new PdfDocument( PaperType.A4, false, UnitOfMeasure.cm, filename );

				// add to pdf file all images from collection
				foreach ( ScannedImageViewModel scan in items )
				{
					var page = new PdfPage( Document, PaperType.A4, scan.Image.Landscape );
					var contents = new PdfContents( page );
					var image = new PdfImage( Document, scan.Image.Source, 0, PdfQuality );
					contents.DrawFullPageImage( image, scan.Image.Landscape );
				}
				Document.CreateFile();
			}
			catch ( IOException )
			{
				// localization dictionary
				var dictionary = Application.Current.Resources.MergedDictionaries[ 0 ];
				Notify = new Notify( (string) dictionary[ "er_CantCreateFile" ], Notify.Type.Warning );
			}
			catch ( Exception ex )
			{
				Notify = new Notify( ex.Message, Notify.Type.Warning );
			}
		}
        private void button1_Click(object sender, EventArgs e)
        {
            String FileName = "testmac2.pdf";
            if (File.Exists(FileName))
            {
                try
                {
                    File.Delete(FileName);
                }
                catch (IOException ex2)
                {
                    System.Windows.Forms.MessageBox.Show(ex2.ToString(), "Sunplusito", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            Document = new PdfDocument(PaperType.Letter, false, UnitOfMeasure.Inch, FileName);
            DefineFontResources();
            DefineTilingPatternResource();
            PdfPage Page = new PdfPage(Document);
            PdfContents Contents = new PdfContents(Page);
            Contents.SaveGraphicsState();

            const Double Width = 8.15;
            const Double Height = 10.65;
            //const Double FontSize = 12.0;
            PdfFileWriter.TextBox Box = new PdfFileWriter.TextBox(Width, 0.25);
            StringBuilder lineas = new StringBuilder("hola 2");

            Box.AddText(ArialNormal, 14.0,
                                  lineas.ToString() + "\n");
            Double PosY = Height;
            Contents.DrawText(0.0, ref PosY, 0.0, 0, 0.015, 0.05, TextBoxJustify.FitToWidth, Box);
            Contents.RestoreGraphicsState();

            Document.CreateFile();

            System.Windows.Forms.MessageBox.Show("al parecer, todo bien tambien", "Sunplusito", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
Exemplo n.º 31
0
        ////////////////////////////////////////////////////////////////////
        /// <summary>
        /// PDF chart constructor
        /// </summary>
        /// <param name="Document">Document object parent of this chart.</param>
        /// <param name="Chart">.NET Chart object.</param>
        /// <param name="Resolution">Resolution in pixels per inch (optional argument)</param>
        ////////////////////////////////////////////////////////////////////
        public PdfChart(
			PdfDocument		Document,
			Chart			Chart,
			Double			Resolution = 0.0	// pixels per inch
			)
            : base(Document, ObjectType.Stream, "/XObject")
        {
            // create resource code
            ResourceCode = Document.GenerateResourceNumber('X');

            // create stream length object
            ImageLengthObject = new PdfObject(Document, ObjectType.Other);
            Dictionary.AddIndirectReference("/Length", ImageLengthObject);

            // save chart
            this.Chart = Chart;

            // save resolution
            if(Resolution != 0)
            {
            // chart resolution in pixels per inch
            this.Resolution = Resolution;
            this.Chart.RenderingDpiY = Resolution;
            }
            else
            {
            this.Resolution = this.Chart.RenderingDpiY;
            }

            // calculate chart size in user coordinates
            Width = (Double) this.Chart.Width * 72.0 / (this.Resolution * Document.ScaleFactor);
            Height = (Double) this.Chart.Height * 72.0 / (this.Resolution * Document.ScaleFactor);

            // exit
            return;
        }
Exemplo n.º 32
0
        ////////////////////////////////////////////////////////////////////
        // Create bookmark item
        // Must be called from AddBookmark method below
        // This constructor is called for each bookmark
        ////////////////////////////////////////////////////////////////////
        private PdfBookmark(
			PdfDocument		Document,
			Boolean			OpenEntries
			)
            : base(Document)
        {
            // open first level bookmarks
            this.OpenEntries = OpenEntries;
            return;
        }
Exemplo n.º 33
0
        public void vuelveAHacerElCheque(bool conImagen)
        {
            string path = Properties.Settings.Default.letra+ ":" + (object)Path.DirectorySeparatorChar + "cheques";
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            if (File.Exists(FileName))
            {
                try
                {
                    File.Delete(FileName);
                }
                catch (IOException ex2)
                {
                    System.Windows.Forms.MessageBox.Show(ex2.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            String fileImage = path + (object)Path.DirectorySeparatorChar + "cheque" + tipoDeBancoGlobal+".jpg";

            Document = new PdfDocument(PaperType.sobreprima, false, UnitOfMeasure.Point, FileName);
            DefineFontResources();
            DefineTilingPatternResource();
            PdfPage Page = new PdfPage(Document);
            PdfContents Contents = new PdfContents(Page);

            Contents.SaveGraphicsState();
            Contents.Translate(0.1, 0.1);

            const Double FontSize = 9.0;

            if(conImagen)
            {
                PdfImage Image = new PdfImage(Document, fileImage, 72.0, 50);
                Contents.SaveGraphicsState();
                int top = Convert.ToInt32(DataBinder.Eval(Properties.Settings.Default, "topCheque" + tipoDeBancoGlobal));
                int left = Convert.ToInt32(DataBinder.Eval(Properties.Settings.Default, "leftCheque" + tipoDeBancoGlobal));
                int ancho = Convert.ToInt32(DataBinder.Eval(Properties.Settings.Default, "anchoCheque" + tipoDeBancoGlobal));
                int largo = Convert.ToInt32(DataBinder.Eval(Properties.Settings.Default, "largoCheque" + tipoDeBancoGlobal));
                Contents.DrawImage(Image, left, top, ancho, largo);
                Contents.RestoreGraphicsState();
            }

            int fechaX = Convert.ToInt32(DataBinder.Eval(Properties.Settings.Default, "fechaX" + tipoDeBancoGlobal));
            int fechaY = Convert.ToInt32(DataBinder.Eval(Properties.Settings.Default, "fechaY" + tipoDeBancoGlobal));
            Contents.MoveTo(new PointD(fechaX, fechaY));
            Contents.DrawText(ArialNormal, FontSize, fechaX, fechaY, fecha);
            Contents.RestoreGraphicsState();
            Contents.SaveGraphicsState();

            int nombreX = Convert.ToInt32(DataBinder.Eval(Properties.Settings.Default, "nombreX" + tipoDeBancoGlobal));
            int nombreY = Convert.ToInt32(DataBinder.Eval(Properties.Settings.Default, "nombreY" + tipoDeBancoGlobal));
            Contents.MoveTo(new PointD(nombreX, nombreY));
            Contents.DrawText(ArialNormal, FontSize, nombreX, nombreY, nombre);
            Contents.RestoreGraphicsState();
            Contents.SaveGraphicsState();

            int cantidadX = Convert.ToInt32(DataBinder.Eval(Properties.Settings.Default, "cantidadX" + tipoDeBancoGlobal));
            int cantidadY = Convert.ToInt32(DataBinder.Eval(Properties.Settings.Default, "cantidadY" + tipoDeBancoGlobal));
            Contents.MoveTo(new PointD(cantidadX, cantidadY));
            Contents.DrawText(ArialNormal, FontSize, cantidadX, cantidadY, total);
            Contents.RestoreGraphicsState();
            Contents.SaveGraphicsState();

            int letraX = Convert.ToInt32(DataBinder.Eval(Properties.Settings.Default, "letraX" + tipoDeBancoGlobal));
            int letraY = Convert.ToInt32(DataBinder.Eval(Properties.Settings.Default, "letraY" + tipoDeBancoGlobal));
            Contents.MoveTo(new PointD(letraX, letraY));
            Contents.DrawText(ArialNormal, FontSize, letraX, letraY, numeroAletras);
            Contents.RestoreGraphicsState();
            Contents.SaveGraphicsState();

            Contents.RestoreGraphicsState();
            Document.CreateFile();

            String url = "file:" + (object)Path.DirectorySeparatorChar + (object)Path.DirectorySeparatorChar +FileName;
            // this.webBrowser1.Navigate(new Uri(url));
            this.webView1.ZoomFactor = 1.0;
            this.webView1.Url = url;
            Properties.Settings.Default.Save();
        }
        ////////////////////////////////////////////////////////////////////
        // Constructors
        ////////////////////////////////////////////////////////////////////

        public PdfXObject
        (
            PdfDocument Document
        ) : this(Document, 1.0, 1.0)
        {
        }