You are on page 1of 12

Copiar Base de Datos de Access con C#

Hola, en esta ocasin veremos como se copia una base de datos en Access con C#. El proceso es muy fcil y para facilitar el trabajo puse el cdigo en una clase la cual les muestro a continuacin:
1. using System; 2. using System.Windows.Forms; 3. namespace TyroDeveloperDLL{ 4. public class BackUpDataBase{ 5. /// 6. /// Respaldar base de datos 7. /// 8. /// Ruta del archivo original 9. /// Nombre del archivo de destino 10. public void Backup(string prmOrigen, string prmDestino){ 11. try{ 12. JRO.JetEngine jro = new JRO.JetEngine(); 13. jro.CompactDatabase(prmOrigen, prmDestino); 14. MessageBox.Show("Proceso ejecutado con xito.\n" + 15. "Archivo: " + prmDestino, 16. "Informacin del Sistema", 17. MessageBoxButtons.OK, MessageBoxIcon.Information); 18. 19. } 20. catch (Exception ex) { 21. MessageBox.Show(ex.Message, 22. "Informacin del Sistema", 23. MessageBoxButtons.OK, MessageBoxIcon.Information); 24. } 25. } 26. } 27. }

Ticket PDF en C#
Hoy veremos como es la creacin de un Ticket y que salga en un documento PDF. Nota: Se trata de una adaptacin a la lgica de otro autor que encontr en internet. Se requiere utilizar la librera iTextSharp la cual puede buscarse en internet. Aqui una imagen de como es la apariencia:

Para facilitarles el proceso, aqui les dejo el cdigo en una clase y mas abajo les explico acerca de su utlizacin:
1. using System; 2. using System.Collections; 3. using iTextSharp; 4. using iTextSharp.text; 5. using iTextSharp.text.pdf; 6. using System.IO; 7. namespace TyroDeveloperDLL{ 8. public class TicketPDF{ 9. public TicketPDF(){ 10. myDocument.AddAuthor("TyroDeveloper"); 11. myDocument.AddCreator("JUAN GABRIEL CASTILLO TURRUBIATES"); 12. myDocument.AddTitle("Ticket de Venta"); 13. } 14. 15. PdfWriter writer = null; 16. PdfContentByte cb=null; 17. ArrayList headerLines = new ArrayList(); 18. ArrayList subHeaderLines = new ArrayList(); 19. ArrayList items = new ArrayList(); 20. ArrayList totales = new ArrayList(); 21. ArrayList footerLines = new ArrayList(); 22. private string headerImage = ""; 23. bool _DrawItemHeaders = true; 24. int count = 0; 25. string path = ""; 26. string file_name = "";

27. 28. 29. 30. 31. 32. 33. 34. false); 35. 36. 37. 38. objetos 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53.

int maxChar = 40; int maxCharDescription = 20; int imageHeight = 0; float leftMargin = 0; float topMargin = 5; static int fontSize = 7; static BaseFont bfCourier = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, static Font font = new Font(bfCourier, fontSize, Font.NORMAL, Color.BLACK); Document myDocument = new Document(PageSize.LETTER); //Aqui se ponen todos los string line = ""; #region Properties public String Path { get { return path; } set { path = value; } } public String FileName { get { return file_name; } set { file_name = value; } }

public String FullFileName { get { return(String.Format("{0}{1}", path, file_name)); } 54. } 55. public String HeaderImage 56. { 57. get { return headerImage; } 58. set { if (headerImage != value) headerImage = value; } 59. } 60. 61. public int MaxChar 62. { 63. get { return maxChar; } 64. set { if (value != maxChar) maxChar = value; } 65. } 66. 67. public bool DrawItemHeaders{ 68. set { _DrawItemHeaders = value; } 69. } 70. 71. public int MaxCharDescription 72. { 73. get { return maxCharDescription; } 74. set { if (value != maxCharDescription) maxCharDescription = value; } 75. } 76. 77. public int FontSize 78. { 79. get { return fontSize; }

80. set { if (value != fontSize) fontSize = value; } 81. } 82. 83. public Font FontName 84. { 85. get { return font; } 86. set { if (value != font) font = value; } 87. } 88. 89. #endregion 90. 91. public void AddHeaderLine(string line) 92. { 93. headerLines.Add(line); 94. } 95. 96. public void AddSubHeaderLine(string line){ 97. subHeaderLines.Add(line); 98. } 99. 100. public void AddItem(string cantidad, string item, string price){ 101. TicketOrderItem newItem = new TicketOrderItem('?'); 102. items.Add(newItem.GenerateItem(cantidad, item, price)); 103. } 104. 105. public void AddTotal(string name, string price){ 106. TicketOrderTotal newTotal = new TicketOrderTotal('?'); 107. totales.Add(newTotal.GenerateTotal(name, price)); 108. } 109. 110. public void AddFooterLine(string line){ 111. footerLines.Add(line); 112. } 113. 114. private string AlignRightText(int lenght){ 115. string espacios = ""; 116. int spaces = maxChar - lenght; 117. for (int x = 0; x < spaces; x++) 118. espacios += " "; 119. return espacios; 120. } 121. 122. private string DottedLine(){ 123. string dotted = ""; 124. for (int x = 0; x < maxChar; x++) 125. dotted += "="; 126. return dotted; 127. } 128. 129. public bool Print() { 130. try{ 131. //aqui para generar el PDF 132. writer = PdfWriter.GetInstance(myDocument, 133. new FileStream(path + file_name, FileMode.Create));

134. myDocument.Open(); 135. cb = writer.DirectContent; 136. cb.SetFontAndSize(font.BaseFont, fontSize); 137. cb.BeginText(); 138. DrawImage(); 139. DrawHeader(); 140. DrawSubHeader(); 141. DrawItems(); 142. DrawTotales(); 143. DrawFooter(); 144. cb.EndText(); 145. myDocument.Close(); 146. return true; 147. } 148. catch (Exception ex) { 149. throw (ex); 150. } 151. } 152. 153. private float YPosition(){ 154. return (myDocument.PageSize.Height 155. (topMargin + (count * font.CalculatedSize + imageHeight))); 156. } 157. 158. private void DrawImage() { 159. try{ 160. if ((headerImage != null) && (headerImage != "")){ 161. if (File.Exists(headerImage)) { 162. Image logo = Image.GetInstance(headerImage); 163. double height = ((double)logo.Height / 58) * 15; 164. imageHeight = (int)Math.Round(height) + 3; 165. logo.SetAbsolutePosition(0, 166. myDocument.PageSize.Height imageHeight); 167. logo.ScaleToFit(logo.Width,imageHeight); 168. myDocument.Add(logo); 169. } 170. } 171. } 172. catch (Exception ex){throw (ex);} 173. } 174. 175. private void DrawHeader(){ 176. try{ 177. foreach (string header in headerLines){ 178. if (header.Length > maxChar) { 179. int currentChar = 0; 180. int headerLenght = header.Length; 181. while (headerLenght > maxChar){ 182. line = header.Substring(currentChar, maxChar); 183. cb.SetTextMatrix(leftMargin, YPosition()); 184. cb.ShowText(line);

185. count++; 186. currentChar += maxChar; 187. headerLenght -= maxChar; 188. } 189. line = header; 190. cb.SetTextMatrix(leftMargin, YPosition()); 191. cb.ShowText(line.Substring(currentChar, 192. line.Length - currentChar)); 193. count++; 194. } 195. else{ 196. line = header; 197. cb.SetTextMatrix(leftMargin, YPosition()); 198. cb.ShowText(line); 199. count++; 200. } 201. } 202. DrawEspacio(); 203. } 204. catch (Exception ex) { throw (ex); } 205. } 206. 207. private void DrawSubHeader() { 208. try{ 209. line = DottedLine(); 210. cb.SetTextMatrix(leftMargin, YPosition()); 211. cb.ShowText(line); 212. DrawEspacio(); 213. foreach (string subHeader in subHeaderLines){ 214. if (subHeader.Length > maxChar){ 215. int currentChar = 0; 216. int subHeaderLenght = subHeader.Length; 217. while (subHeaderLenght > maxChar){ 218. line = subHeader; 219. cb.SetTextMatrix(leftMargin, YPosition()); 220. cb.ShowText(line.Substring(currentChar, maxChar)); 221. count++; 222. currentChar += maxChar; 223. subHeaderLenght -= maxChar; 224. } 225. line = subHeader; 226. cb.SetTextMatrix(leftMargin, YPosition()); 227. cb.ShowText(line.Substring(currentChar, 228. line.Length - currentChar)); 229. count++; 230. line = DottedLine(); 231. cb.SetTextMatrix(leftMargin, YPosition()); 232. cb.ShowText(line); 233. DrawEspacio(); 234. } 235. else 236. { 237. line = subHeader; 238. cb.SetTextMatrix(leftMargin, YPosition()); 239. cb.ShowText(line);

240. count++; 241. line = DottedLine(); 242. cb.SetTextMatrix(leftMargin, YPosition()); 243. cb.ShowText(line); 244. count++; 245. } 246. } 247. DrawEspacio(); 248. } 249. catch (Exception ex) { throw (ex); } 250. } 251. 252. private void DrawItems() { 253. TicketOrderItem ordIt = new TicketOrderItem('?'); 254. if (_DrawItemHeaders){ 255. cb.SetTextMatrix(leftMargin, YPosition()); 256. cb.ShowText("CANT DESCRIPCION IMPORTE"); 257. } 258. count++; 259. DrawEspacio(); 260. foreach (string item in items){ 261. line = ordIt.GetItemCantidad(item); 262. cb.SetTextMatrix(leftMargin, YPosition()); 263. cb.ShowText(line); 264. line = ordIt.GetItemPrice(item); 265. line = AlignRightText(line.Length) + line; 266. cb.SetTextMatrix(leftMargin, YPosition()); 267. cb.ShowText(line); 268. string name = ordIt.GetItemName(item); 269. leftMargin = 0; 270. if (name.Length > maxCharDescription) { 271. int currentChar = 0; 272. int itemLenght = name.Length; 273. while (itemLenght > maxCharDescription){ 274. line = ordIt.GetItemName(item); 275. cb.SetTextMatrix(leftMargin, YPosition()); 276. cb.ShowText(" " + line.Substring(currentChar, 277. maxCharDescription)); 278. count++; 279. currentChar += maxCharDescription; 280. itemLenght -= maxCharDescription; 281. } 282. line = ordIt.GetItemName(item); 283. cb.SetTextMatrix(leftMargin, YPosition()); 284. cb.ShowText(" " + line.Substring(currentChar, 285. maxCharDescription)); 286. count++; 287. } 288. else{ 289. cb.SetTextMatrix(leftMargin, YPosition()); 290. cb.ShowText(" " + ordIt.GetItemName(item)); 291. count++; 292. }

293. } 294. 295. leftMargin = 0; 296. DrawEspacio(); 297. line = DottedLine(); 298. cb.SetTextMatrix(leftMargin, YPosition()); 299. cb.ShowText(line); 300. count++; 301. DrawEspacio(); 302. } 303. 304. private void DrawTotales(){ 305. TicketOrderTotal ordTot = new TicketOrderTotal('?'); 306. foreach (string total in totales){ 307. line = ordTot.GetTotalCantidad(total); 308. line = AlignRightText(line.Length) + line; 309. cb.SetTextMatrix(leftMargin, YPosition()); 310. cb.ShowText(line); 311. leftMargin = 0; 312. line = "" + ordTot.GetTotalName(total); 313. cb.SetTextMatrix(leftMargin, YPosition()); 314. cb.ShowText(line); 315. count++; 316. } 317. leftMargin = 0; 318. DrawEspacio(); 319. DrawEspacio(); 320. } 321. 322. private void DrawFooter(){ 323. foreach (string footer in footerLines){ 324. if (footer.Length > maxChar){ 325. int currentChar = 0; 326. int footerLenght = footer.Length; 327. while (footerLenght > maxChar){ 328. line = footer; 329. cb.SetTextMatrix(leftMargin, YPosition()); 330. cb.ShowText(line.Substring(currentChar, maxChar)); 331. count++; 332. currentChar += maxChar; 333. footerLenght -= maxChar; 334. } 335. line = footer; 336. cb.SetTextMatrix(leftMargin, YPosition()); 337. cb.ShowText(line.Substring(currentChar, maxChar)); 338. count++; 339. } 340. else { 341. line = footer; 342. cb.SetTextMatrix(leftMargin, YPosition()); 343. cb.ShowText(line); 344. count++; 345. } 346. } 347. leftMargin = 0;

348. DrawEspacio(); 349. } 350. 351. private void DrawEspacio(){ 352. line = ""; 353. cb.SetTextMatrix(leftMargin, YPosition()); 354. cb.SetFontAndSize(font.BaseFont, fontSize); 355. cb.ShowText(line); 356. count++; 357. } 358. } 359. 360. public class TicketOrderItem{ 361. char[] delimitador = new char[] { '?' }; 362. public TicketOrderItem(char delimit){ 363. delimitador = new char[] { delimit }; 364. } 365. 366. public string GetItemCantidad(string TicketOrderItem){ 367. string[] delimitado = TicketOrderItem.Split(delimitador); 368. return delimitado[0]; 369. } 370. 371. public string GetItemName(string TicketOrderItem){ 372. string[] delimitado = TicketOrderItem.Split(delimitador); 373. return delimitado[1]; 374. } 375. 376. public string GetItemPrice(string TicketOrderItem) { 377. string[] delimitado = TicketOrderItem.Split(delimitador); 378. return delimitado[2]; 379. } 380. 381. public string GenerateItem(string cantidad, 382. string itemName, string price){ 383. return cantidad + delimitador[0] + 384. itemName + delimitador[0] + price; 385. } 386. } 387. 388. public class TicketOrderTotal{ 389. char[] delimitador = new char[] { '?' }; 390. public TicketOrderTotal(char delimit){ 391. delimitador = new char[] { delimit }; 392. } 393. 394. public string GetTotalName(string totalItem){ 395. string[] delimitado = totalItem.Split(delimitador); 396. return delimitado[0]; 397. } 398. 399. public string GetTotalCantidad(string totalItem){ 400. string[] delimitado = totalItem.Split(delimitador); 401. return delimitado[1];

402. 403. 404. 405. 406. 407. 408. 409. } 410.

} public string GenerateTotal(string totalName, string price){ return totalName + delimitador[0] + price; } }

Implementacin: Nota: Este es un ejemplo tal y cual lo utlic para una aplicacin web, el programador debe adaptar este cdigo a sus necesidades.
1. public bool ImprimeTicket(int prmFolioTicket, string user, string path, 2. string fileName, string prmHeaderImage) 3. { 4. SqlConnection cnnReporte = new SqlConnection(clsMain.CnnStr); 5. try 6. { 7. double varEFECTIVO = 0; 8. double varCAMBIO = 0; 9. string varTOTAL_LETRA = ""; 10. double varTOTAL = 0; 11. double varDESCUENTO = 0; 12. double varIVA = 0; 13. TicketPDF ticket = new TicketPDF(); 14. ticket.Path = path; 15. ticket.FileName = fileName; 16. ticket.HeaderImage = prmHeaderImage; 17. ticket.AddHeaderLine(clsMain.WebConfig("TICKET_HEADER_01")); 18. ticket.AddHeaderLine(clsMain.WebConfig("TICKET_HEADER_02")); 19. ticket.AddHeaderLine(clsMain.WebConfig("TICKET_HEADER_03")); 20. ticket.AddHeaderLine(clsMain.WebConfig("TICKET_HEADER_04")); 21. ticket.AddHeaderLine(clsMain.WebConfig("TICKET_HEADER_05")); 22. 23. cnnReporte.Open(); 24. SqlCommand cmdReporte = 25. new SqlCommand("proc_VENTA_TICKET", cnnReporte); 26. cmdReporte.CommandType = CommandType.StoredProcedure; 27. //params 28. cmdReporte.Parameters.Add("@ID_VENTA", 29. SqlDbType.Int).Value = prmFolioTicket; 30. SqlDataReader drReporte; 31. drReporte = cmdReporte.ExecuteReader(); 32. while (drReporte.Read()) 33. { 34. //El metodo AddSubHeaderLine es lo mismo al

35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77.

//de AddHeaderLine con la diferencia //de que al final de cada linea //agrega una linea punteada "==========" ticket.AddSubHeaderLine("Caja # " + drReporte["CAJA"].ToString() + " - Ticket # " + prmFolioTicket.ToString() + ""); ticket.AddSubHeaderLine("Le atendi: " + drReporte["CAJERO"].ToString() + ""); ticket.AddSubHeaderLine("Fecha y Hora: " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString()); ticket.AddSubHeaderLine("Cliente: " + drReporte["CLIENTE"].ToString() + ""); varEFECTIVO = Convert.ToDouble(drReporte["EFECTIVO"]); varCAMBIO = Convert.ToDouble(drReporte["CAMBIO"]); varTOTAL_LETRA = drReporte["TOTAL_LETRA"].ToString(); }

////Details drReporte.Close(); cmdReporte.Parameters.Clear(); cmdReporte.CommandText = "proc_VENTA_DETALLE_TICKET"; //params cmdReporte.Parameters.Add("@ID_VENTA", SqlDbType.Int).Value = prmFolioTicket; drReporte = cmdReporte.ExecuteReader(); while (drReporte.Read()) { //El metodo AddItem requeire 3 parametros, //el primero es cantidad, el segundo es la descripcion //del producto y el tercero es el precio if (drReporte["PRODUCTO"].ToString().Length > 11) { ticket.AddItem(drReporte["CANTIDAD"].ToString(), drReporte["PRODUCTO"].ToString().Substring(0, 11), String.Format("{0:C}", Convert.ToDouble(drReporte["CANTIDAD"]) * Convert.ToDouble(drReporte["PRECIO_VENTA"]))); } else { ticket.AddItem(drReporte["CANTIDAD"].ToString(), drReporte["PRODUCTO"].ToString(), String.Format("{0:C}", 78. Convert.ToDouble(drReporte["CANTIDAD"]) * 79. Convert.ToDouble(drReporte["PRECIO_VENTA"]))); 80. } 81. 82. varTOTAL += Convert.ToDouble(drReporte["TOTAL"]); 83. varDESCUENTO += Convert.ToDouble(drReporte["DESCUENTO"]); 84. varIVA += 85. Convert.ToDouble(drReporte["IMPUESTO_DOS"]); 86. } 87. drReporte.Close(); 88. cmdReporte.Dispose(); 89. cnnReporte.Close();

90. cnnReporte.Dispose(); 91. //El metodo AddTotal requiere 2 parametros, 92. //la descripcion del total, y el precio 93. ticket.AddTotal("SUBTOTAL", String.Format("{0:C}", 94. varTOTAL - varIVA)); 95. ticket.AddTotal("IVA", String.Format("{0:C}", 96. varIVA)); 97. ticket.AddTotal("TOTAL", String.Format("{0:C}", 98. varTOTAL + varDESCUENTO)); 99. ticket.AddTotal("DESCUENTO", String.Format("{0:C}", 100. -varDESCUENTO)); 101. ticket.AddTotal("GRAN TOTAL", String.Format("{0:C}", 102. varTOTAL)); 103. ticket.AddTotal("", "");//Ponemos un total 104. //en blanco que sirve de espacio 105. ticket.AddTotal("RECIBIDO", String.Format("{0:C}", 106. varEFECTIVO)); 107. ticket.AddTotal("CAMBIO", String.Format("{0:C}", 108. varCAMBIO)); 109. ticket.AddTotal("", "");//Ponemos un total 110. //en blanco que sirve de espacio 111. ticket.AddTotal("USTED AHORRA", String.Format("{0:C}", 112. varDESCUENTO)); 113. //El metodo AddFooterLine funciona igual que la cabecera 114. ticket.AddFooterLine(clsMain.WebConfig("TICKET_FOOTER_01")); 115. ticket.AddFooterLine(clsMain.WebConfig("TICKET_FOOTER_02")); 116. ticket.AddFooterLine(clsMain.WebConfig("TICKET_FOOTER_03")); 117. ticket.AddFooterLine(clsMain.WebConfig("TICKET_FOOTER_04")); 118. ticket.AddFooterLine(clsMain.WebConfig("TICKET_FOOTER_05")); 119. //Generamos 120. if (ticket.Print()) { return (true); } 121. else { return false; } 122. } 123. catch (Exception ex) { throw (ex); } 124. finally { cnnReporte.Close(); } 125. }

Listo, espero que les sirva.

You might also like