virtual public void CreatePdfAutomaticTest() { String fileName = "xmp_metadata_automatic.pdf"; // step 1 Document document = new Document(); // step 2 PdfWriter writer = PdfAWriter.GetInstance(document, new FileStream(OUT_FOLDER + fileName, FileMode.Create), PdfAConformanceLevel.PDF_A_1B); document.AddTitle("Hello World example"); document.AddSubject("This example shows how to add metadata & XMP"); document.AddKeywords("Metadata, iText, step 3"); document.AddCreator("My program using 'iText'"); document.AddAuthor("Bruno Lowagie & Paulo Soares"); writer.CreateXmpMetadata(); // step 3 document.Open(); Font font = FontFactory.GetFont("../../resources/text/pdfa/FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12); document.Add(new Paragraph("Hello World", font)); FileStream iccStream = new FileStream("../../resources/text/pdfa/sRGB Color Space Profile.icm", FileMode.Open); ICC_Profile icc = ICC_Profile.GetInstance(iccStream); iccStream.Close(); writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc); // step 5 document.Close(); CompareResults(fileName, fileName); }
virtual public void CreatePdfAutomaticTest() { String fileName = "xmp_metadata_automatic.pdf"; // step 1 Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(OUT_FOLDER + fileName, FileMode.Create)); document.AddTitle("Hello World example"); document.AddSubject("This example shows how to add metadata & XMP"); document.AddKeywords("Metadata, iText, step 3"); document.AddCreator("My program using 'iText'"); document.AddAuthor("Bruno Lowagie & Paulo Soares"); writer.CreateXmpMetadata(); // step 3 document.Open(); // step 4 document.Add(new Paragraph("Hello World")); // step 5 document.Close(); CompareResults(fileName, fileName); }
private void lblPDF_Click(object sender, EventArgs e) { string Nombre = "Reporte"; // Creamos el documento con el tamaño de página tradicional Document doc = new Document(PageSize.LETTER); // Indicamos donde vamos a guardar el documento PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(@"C:\PDFs\" + Nombre + " " + comboBox1.Text + " " + DateTime.Now.ToString("dd-MM-yyyy") + ".pdf", FileMode.Create)); // Le colocamos el título y el autor // **Nota: Esto no será visible en el documento doc.AddTitle("Mi primer PDF"); doc.AddCreator("Hector Inzunza"); // Abrimos el archivo doc.Open(); //Linea Factura PdfContentByte Factura = writer.DirectContent; Factura.BeginText(); BaseFont f_cn = BaseFont.CreateFont("c:\\windows\\fonts\\arial.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Factura.SetFontAndSize(f_cn, 10); Factura.SetTextMatrix(500, 750); //(xPos, yPos) Factura.ShowText("Factura"); Factura.EndText(); //Codigo PdfContentByte Texto = writer.DirectContent; Texto.BeginText(); BaseFont f_cn2 = BaseFont.CreateFont("c:\\windows\\fonts\\arial.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Texto.SetFontAndSize(f_cn2, 10); Texto.SetTextMatrix(500, 730); //(xPos, yPos) Texto.ShowText("Codigo: 0000-1"); Texto.EndText(); //Fecha PdfContentByte Fecha = writer.DirectContent; Fecha.BeginText(); BaseFont f_cn3 = BaseFont.CreateFont("c:\\windows\\fonts\\arial.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Fecha.SetFontAndSize(f_cn3, 10); Fecha.SetTextMatrix(500, 710); //(xPos, yPos) Fecha.ShowText("Fecha: " + DateTime.Now.ToString("dd-MM-yyyy")); Fecha.EndText(); //Hora PdfContentByte Hora = writer.DirectContent; Fecha.BeginText(); BaseFont f_cn4 = BaseFont.CreateFont("c:\\windows\\fonts\\arial.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Fecha.SetFontAndSize(f_cn4, 10); Fecha.SetTextMatrix(500, 690); //(xPos, yPos) Fecha.ShowText("Hora: " + DateTime.Now.ToString("HH:mm:ss")); Fecha.EndText(); Paragraph Titulo = new Paragraph(); Paragraph Domicilio = new Paragraph(); Paragraph Domicilio2 = new Paragraph(); Paragraph RFC = new Paragraph(); Paragraph Telefonos = new Paragraph(); Paragraph Descripcion = new Paragraph(); Titulo.Alignment = Element.TITLE; Domicilio.Alignment = Element.ALIGN_CENTER; Domicilio2.Alignment = Element.ALIGN_CENTER; RFC.Alignment = Element.ALIGN_CENTER; Telefonos.Alignment = Element.ALIGN_CENTER; Descripcion.Alignment = Element.ALIGN_CENTER; Titulo.Font = FontFactory.GetFont("Arial", 16); Domicilio.Font = FontFactory.GetFont("Arial", 9); Domicilio2.Font = FontFactory.GetFont("Arial", 9); RFC.Font = FontFactory.GetFont("Arial", 9); Telefonos.Font = FontFactory.GetFont("Arial", 9); Descripcion.Font = FontFactory.GetFont("Arial", 9); Titulo.Add("Russell Corp, S.A. de C.V."); Domicilio.Add("Blvd. Diego Valadéz Ríos No.123, Desarrollo Urbano Tres Ríos"); Domicilio2.Add("Culiacan, Sinaloa Mexico C.P. 80000"); RFC.Add("R.F.C.: UICH5807193G3"); Telefonos.Add("Tel. (667)7-54-06-57 Fax: (667)7-54-06-57 Email: [email protected]"); Descripcion.Add("Reporte de ventas Tipo: " + comboBox1.Text); doc.Add(Titulo); doc.Add(Domicilio); doc.Add(Domicilio2); doc.Add(RFC); doc.Add(Telefonos); // Creamos la imagen y le ajustamos el tamaño iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(@"C:\PDFs\RUSSELL ENTERPRISES.PNG"); //Posicion en el eje carteciano de X y Y imagen.SetAbsolutePosition(30, 700); imagen.BorderWidth = 0; imagen.Alignment = Element.ALIGN_LEFT; float percentage = 0.0f; percentage = 120 / imagen.Width; imagen.ScalePercent(percentage * 100); // Insertamos la imagen en el documento doc.Add(imagen); doc.Add(new Paragraph("\n")); doc.Add(Descripcion); doc.Add(new Paragraph("\n")); PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount); pdfTable.DefaultCell.Padding = 1; pdfTable.WidthPercentage = 50; pdfTable.HorizontalAlignment = Element.ALIGN_CENTER; pdfTable.DefaultCell.BorderWidth = 1; //Adding Header row foreach (DataGridViewColumn column in dataGridView1.Columns) { PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText)); cell.BackgroundColor = new iTextSharp.text.Color(240, 240, 240); pdfTable.AddCell(cell); } //Adding DataRow foreach (DataGridViewRow row in dataGridView1.Rows) { foreach (DataGridViewCell cell in row.Cells) { string Valor = Convert.ToString(cell.Value); pdfTable.AddCell(Valor); } } doc.Add(pdfTable); doc.Close(); writer.Close(); MessageBox.Show("¡PDF creado!"); }
public async Task GerarPdf() { var doc1 = new Document(PageSize.A4, 40.0f, 20.0f, 30.0f, 30.0f);//Margens PdfWriter writer = null; //try //{ if (!Directory.Exists(path + "/Cotações")) { Directory.CreateDirectory(path + "/Cotações"); } if (!Directory.Exists(path + "/Pedidos")) { Directory.CreateDirectory(path + "/Pedidos"); } string completepath; if (Ped.Tipo == Tipo.Cotação) { completepath = path + "/Cotações/" + Ped.Cliente + "-" + DateTime.Now.Millisecond.ToString() + ".pdf"; } else { completepath = path + "/Pedidos/" + Ped.Cliente + "-" + DateTime.Now.Millisecond.ToString() + ".pdf"; } writer = PdfWriter.GetInstance(doc1, new FileStream(completepath, FileMode.Create)); //Path.Combine(path.ToString(), "Cotação/myfile.pdf"), FileMode.Create)); //} //catch (IOException) //{ //MessageBoxOK("Não foi possível criar o arquivo PDF,\r\nverifique se há um arquivo de mesmo nome aberto.\r\nFeche-o e tente novamente."); //} doc1.Open(); iTextSharp.text.Font normal = FontFactory.GetFont("Arial", 12); /*var logo = new Xamarin.Forms.Image(); * * if (Ped.Empresa == Empresa.Zamil) * logo = Resource.Drawable.zamil; * if (Ped.Empresa == Empresa.Totalfix) * logo = Resource.Drawable.totalfix; * if (Ped.Empresa == Empresa.Totalpinos) * logo.Source = ImageSource.FromResource("Pedidos.totalpinos.png"); * * var bitmap = await GetBitmapFromImageSourceAsync(logo.Source, null); * * iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(bitmap); * jpg.Alignment = iTextSharp.text.Image.ALIGN_CENTER; * jpg.ScaleToFit(250f, 250f);*/ //jpg.SetAbsolutePosition(500f, 750f); //doc1.Add(jpg); doc1.Add(new Paragraph(Ped.Empresa.ToString(), normal)); doc1.Add(new Paragraph(Enum.GetName(typeof(Tipo), Ped.Tipo), normal)); doc1.Add(new Paragraph("\r\n", normal)); doc1.Add(new Paragraph("Cliente: " + Ped.Cliente, normal)); doc1.Add(new Paragraph("\r\n", normal)); doc1.Add(new Paragraph("Cidade: " + Ped.Cidade, normal)); doc1.Add(new Paragraph("\r\n", normal)); doc1.Add(new Paragraph("Condições: " + Ped.Condições, normal)); doc1.Add(new Paragraph("\r\n", normal)); doc1.Add(new Paragraph("Frete: " + Ped.Frete, normal)); doc1.Add(new Paragraph("\r\n", normal)); doc1.Add(new Paragraph("Produtos: ", normal)); doc1.Add(new Paragraph("\r\n", normal)); PdfPTable table = new PdfPTable(6); //table.SetWidths(width); //table.HorizontalAlignment = 0; table.AddCell(new Phrase("Quantidade", normal)); table.AddCell(new Phrase("Unidade", normal)); table.AddCell(new Phrase("Produto", normal)); table.AddCell(new Phrase("Preço un.", normal)); table.AddCell(new Phrase("Desconto", normal)); table.AddCell(new Phrase("Valor", normal)); foreach (Item i in Ped.Itens) { table.AddCell(new Phrase(i.Quantidade.ToString(), normal)); table.AddCell(new Phrase(Enum.GetName(typeof(Unidade), i.Unidade), normal)); table.AddCell(new Phrase(i.Produto, normal)); table.AddCell(new Phrase(i.Preço.ToString("C2"), normal)); table.AddCell(new Phrase(i.Desconto.ToString() + "%", normal)); table.AddCell(new Phrase(i.Valor.ToString("C2"), normal)); } doc1.Add(table); doc1.Add(new Paragraph("\r\n", normal)); doc1.Add(new Paragraph("Total: " + Ped.Total.ToString("C2"), normal)); doc1.AddCreator("Pedidos"); //File.Create(WebFile.AppData + "TempFill.bin").Close(); //WebFile.Serialize(Cota.Preenchimento, WebFile.AppData + "TempFill.bin"); //PdfFileSpecification pfs = PdfFileSpecification.FileEmbedded(writer, WebFile.AppData + "TempFill.bin", "TempFill.bin", null); //writer.AddFileAttachment(pfs); doc1.Close(); //File.Delete(WebFile.AppData + "TempFill.bin"); //Toast.MakeText(null, "Arquivo PDF gerado com sucesso!", ToastLength.Short).Show(); /*if (MessageBoxYesOrNo("Arquivo PDF gerado com sucesso!\r\nVocê deseja visualizá-lo agora?")) * { * Process.Start(filename); * }*/ }
private void createPDF(List <log> list) { #region Create PDF Random rnd = new Random(); string nomber = rnd.Next().ToString(); Document documentPDF = new Document(PageSize.LETTER); PdfWriter writer = PdfWriter.GetInstance(documentPDF, new FileStream(@"C:/DrCash_WPF/DoctorCashWpf/ArchiveLog" + nomber + ".pdf", FileMode.CreateNew)); //title documentPDF.AddTitle("Archive PDF"); documentPDF.AddCreator("DrCash"); documentPDF.Open(); //type letter iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); iTextSharp.text.Font _standardFont2 = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.RED); iTextSharp.text.Paragraph text1 = new iTextSharp.text.Paragraph("Table Of Results", _standardFont); text1.Alignment = 1; documentPDF.Add(text1); documentPDF.Add(Chunk.NEWLINE); //create a table PdfPTable table = new PdfPTable(3); table.WidthPercentage = 100; // config title and columns PdfPCell clprocessedby = new PdfPCell(new Phrase("Processed By", _standardFont)); clprocessedby.BorderWidth = 0; clprocessedby.BorderWidthBottom = 0.75f; PdfPCell cldate = new PdfPCell(new Phrase("Date", _standardFont)); cldate.BorderWidth = 0; cldate.BorderWidthBottom = 0.75f; PdfPCell claction = new PdfPCell(new Phrase("Action", _standardFont)); claction.BorderWidth = 0; claction.BorderWidthBottom = 0.75f; // add cells at table table.AddCell(clprocessedby); table.AddCell(cldate); table.AddCell(claction); for (int i = 0; i < list.Count(); i++) { if (i == (list.Count() - 1)) { clprocessedby = new PdfPCell(new Phrase(list[i].log_Username.ToString(), _standardFont)); clprocessedby.BorderWidth = 0; clprocessedby.BorderWidthBottom = 0.75f; cldate = new PdfPCell(new Phrase(list[i].log_DateTime.ToString(), _standardFont)); cldate.BorderWidth = 0; cldate.BorderWidthBottom = 0.75f; claction = new PdfPCell(new Phrase(list[i].log_Actions.ToString(), _standardFont)); claction.BorderWidth = 0; claction.BorderWidthBottom = 0.75f; table.AddCell(clprocessedby); table.AddCell(cldate); table.AddCell(claction); } else { clprocessedby = new PdfPCell(new Phrase(list[i].log_Username.ToString(), _standardFont)); clprocessedby.BorderWidth = 0; cldate = new PdfPCell(new Phrase(list[i].log_DateTime.ToString(), _standardFont)); cldate.BorderWidth = 0; claction = new PdfPCell(new Phrase(list[i].log_Actions.ToString(), _standardFont)); claction.BorderWidth = 0; table.AddCell(clprocessedby); table.AddCell(cldate); table.AddCell(claction); } } documentPDF.Add(table); documentPDF.Close(); writer.Close(); Process.Start(@"C:/DrCash_WPF/DoctorCashWpf/ArchiveLog" + nomber + ".pdf"); #endregion }
public static void CreatePDF(DataTable dataTable, string destinationPath, int value) { if (!Directory.Exists(destinationPath)) { Directory.CreateDirectory(destinationPath); } try { string path = destinationPath + $"\\{value}_test.pdf"; if (File.Exists(path)) { File.Delete(path); } #region -- -- /* * Document document = new Document(PageSize.A4, 10, 10, 42, 35); * string path = destinationPath + "\\TEST.pdf"; * //PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create)); * using (var fileStream = new FileStream(path, FileMode.Create)) * { * PdfWriter.GetInstance(document, fileStream); * * document.Open(); * * Document _document = new Document(); * PdfWriter writer = PdfWriter.GetInstance(_document, fileStream); * _document.Open(); * * System.Drawing.Font font = new System.Drawing.Font("Courier", 16); * * int countFile = Directory.GetFiles(destinationPath).Length; * string strFileName = $"JobDescriptionFile{(countFile + 1)}.pdf"; * * PdfPTable table = new PdfPTable(dataTable.Columns.Count); * table.WidthPercentage = 100; * * //Set columns names in the pdf file * for (int k = 0; k < dataTable.Columns.Count; k++) * { * PdfPCell pdfColumnCell = new PdfPCell(new Phrase(dataTable.Columns[k].ColumnName)); * * pdfColumnCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; * pdfColumnCell.VerticalAlignment = PdfPCell.ALIGN_CENTER; * pdfColumnCell.BackgroundColor = new iTextSharp.text.BaseColor(51, 102, 102); * * table.AddCell(pdfColumnCell); * } * * //Add values of DataTable in pdf file * for (int i = 0; i < dataTable.Rows.Count; i++) * { * for (int j = 0; j < dataTable.Columns.Count; j++) * { * PdfPCell pdfColumnCell = new PdfPCell(new Phrase(dataTable.Rows[i][j].ToString())); * * //Align the pdfColumnCell in the center * pdfColumnCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; * pdfColumnCell.VerticalAlignment = PdfPCell.ALIGN_CENTER; * * table.AddCell(pdfColumnCell); * } * } * * Chunk chunk = new Chunk("DEMO ENTREPRISE", * FontFactory.GetFont("Times New Roman")); * chunk.Font.Color = new BaseColor(0, 0, 0); * chunk.Font.SetStyle(0); * chunk.Font.Size = 14; * * _document.Add(table); * _document.Close(); */ #endregion #region -- ************* -- Document document = new Document(PageSize.A4, 10, 10, 42, 35); using (var fileStream = new FileStream(path, FileMode.Create)) { string _imagePath = "https://ftp.mediaperf.com/img/logo.gif"; _imagePath = @"C:\Users\Sweet Family\Desktop\logo.jpg"; PdfWriter.GetInstance(document, fileStream); document.Open(); #region -- -- document.AddAuthor("Micke Blomquist"); document.AddCreator("Sample application using iTextSharp"); document.AddKeywords("PDF tutorial education"); document.AddSubject("Document subject - Describing the steps creating a PDF document"); document.AddTitle("The document title - PDF creation using iTextSharp"); #endregion //Document _document = new Document(); using (Document _document = new Document(PageSize.LETTER, 26, 16, 25, 10)) { PdfWriter pdfWriter = PdfWriter.GetInstance(_document, fileStream); _document.Open(); // -- Set the left header -- OnBeginPage(pdfWriter, _document); // -- Set the rigth header -- OnRigthBeginPage(pdfWriter, _document); ////InitalisePDFHelper(dataTable); //SetImageLogo(); PdfPTable table = new PdfPTable(dataTable.Columns.Count) { WidthPercentage = 100 }; #region -- Set Logo -- Image imagePath = Image.GetInstance(_imagePath); imagePath.ScalePercent(45f); //imagePath.ScaleToFit(100f, 200f); //imagePath.SetAbsolutePosition(250, 300); _document.Add(imagePath); #endregion #region -- Set the left title -- var Title = new Paragraph("Relevé de redévences", new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.NORMAL, BaseColor.BLACK) ); Title.Alignment = Element.ALIGN_RIGHT; _document.Add(Title); #endregion //_document.Add(new Paragraph("\n\n\r")); Chunk verticalPositionMark = new Chunk(new VerticalPositionMark()); BaseFont baseFont = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, false); #region --- --- // ----------------------------- // ------------------------------------------- _document.Add(new Paragraph("\n\r")); _document.Add(new Paragraph("\n\r")); #region -- Set first ligne -- Font font = new Font(baseFont, 11, Font.BOLD, BaseColor.BLACK); PdfPCell pdfPCell = new PdfPCell(new Phrase("N° RdR $NoRdR", font)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 1 }; PdfPTable table0 = new PdfPTable(2); PdfContentByte cb = pdfWriter.DirectContent; table0 = new PdfPTable(1); table0.TotalWidth = 160; table0.AddCell(pdfPCell); table0.WriteSelectedRows(0, -1, 35, 650, cb); pdfPCell = new PdfPCell(new Phrase("Date $Date", font)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 1 }; PdfPTable table10 = new PdfPTable(2); table10 = new PdfPTable(1); table10.TotalWidth = 160; table10.AddCell(pdfPCell); table10.WriteSelectedRows(0, -1, 220, 650, cb); pdfPCell = new PdfPCell(new Phrase("Destinataire", font)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 1 }; PdfPTable table30 = new PdfPTable(2); table30 = new PdfPTable(1); table30.HorizontalAlignment = Element.ALIGN_CENTER; table30.TotalWidth = 190; //table30. = 65; table10.AddCell(pdfPCell); var p = new Paragraph { new Phrase("Destinataire", new Font(Font.FontFamily.TIMES_ROMAN, 20, Font.NORMAL, BaseColor.BLACK)), "$Destinataire \n\n", "$Prestataire \n\n", "$Adresse$Prestataire \n\n\n" }; pdfPCell.Border = 2; table30.AddCell(p); table30.WriteSelectedRows(0, -1, 400, 650, cb); #endregion _document.Add(new Paragraph("\n\r")); // ---------------------------------------------- //var image = Image.GetInstance(_imagePath); //var paragraph = new Paragraph(); //paragraph.Add(new Chunk(image, 0, 0)); //var tables = new PdfPTable(1); //var cell = new PdfPCell { PaddingLeft = 5, PaddingTop = 5, PaddingBottom = 5, PaddingRight = 5 }; //cell.HorizontalAlignment = Element.ALIGN_CENTER; //cell.AddElement(paragraph); //tables.AddCell(cell); //_document.Add(new Paragraph("\n\r")); //_document.Add(tables); #endregion #region --- Set images side by side !!!!!!!!! --- //PdfPTable resimtable = new PdfPTable(2); // two colmns create tabble //resimtable.WidthPercentage = 100f;//table %100 width //Image imgsag = Image.GetInstance(_imagePath); //resimtable.AddCell(imgsag);//Table One colmns added first image //imgsag.ScalePercent(60f); //Image imgsol = Image.GetInstance(_imagePath); //imgsol.ScalePercent(60f); //resimtable.AddCell(imgsag);//Table One colmns added first image //resimtable.AddCell(imgsol);//Table two colmns added second image //_document.Add(resimtable); #endregion #region -- Set Text Side by side -- //var docTitle = new Paragraph(); //var titleFont = FontFactory.GetFont(FontFactory.TIMES_BOLD, 10f, BaseColor.BLACK); //docTitle.Font = titleFont; //docTitle.Add("Simulation n° : " + 013235 + "\n"); //docTitle.Add(new Chunk("TS : " + "AZ5462132032003." + "\n", titleFont)); //docTitle.Add(new Chunk("Société : " + "CUST NAME" + "\n", titleFont)); //docTitle.Add(new Chunk("Date de simulation : " + DateTime.Now.ToString() + "\n", titleFont)); //docTitle.Add(new Chunk("Montant total dû : " + 5265.20 + " €\n\n", titleFont)); ////docTitle.Font.Size = 6f; //// -- Set Interline -- ////docTitle.SetLeading(1.8f, 1.2f); //_document.Add(docTitle); // -- Ajout de saut ligne -- _document.Add(new Paragraph("\n\n")); //Chunk verticalPositionMark = new Chunk(new VerticalPositionMark()); Paragraph footerParagraph = new Paragraph("Text to the left"); var titleFont = FontFactory.GetFont(FontFactory.TIMES_BOLD, 10f, BaseColor.BLACK); footerParagraph.Font = titleFont; footerParagraph.Add(new Chunk(verticalPositionMark)); footerParagraph.Add("Suppose that some day, somebody asks you"); _document.Add(footerParagraph); //// -- Set Interligne -- //footerParagraph.SetLeading(2.8f, 1.2f); #endregion _document.Add(new Paragraph("\n\r")); VerticalPositionMark seperator = new LineSeparator(); seperator.Offset = -6f; // -- Ajout de saut ligne -- _document.Add(new Paragraph("\n")); #region -- Fill PDF DataGrid -- ////Set columns names in the pdf file for (int k = 0; k < dataTable.Columns.Count; k++) { PdfPCell pdfColumnCell = new PdfPCell(new Phrase(dataTable.Columns[k].ColumnName)); pdfColumnCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; pdfColumnCell.VerticalAlignment = PdfPCell.ALIGN_CENTER; pdfColumnCell.BackgroundColor = new BaseColor(51, 102, 102); table.AddCell(pdfColumnCell); } ////Add values of DataTable in pdf file for (int i = 0; i < dataTable.Rows.Count; i++) { for (int j = 0; j < dataTable.Columns.Count; j++) { PdfPCell pdfColumnCell = new PdfPCell(new Phrase(dataTable.Rows[i][j].ToString())); //Align the pdfColumnCell in the center pdfColumnCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; pdfColumnCell.VerticalAlignment = PdfPCell.ALIGN_CENTER; table.AddCell(pdfColumnCell); } } #endregion // -- Ajout de saut ligne -- _document.Add(new Paragraph("\n")); System.Drawing.Font fonts = new System.Drawing.Font("Courier", 16); //// -- Set Interligne -- //table.SetLeading(9.8f, 1.2f); table.GetFooter(); //PdfPCell cell = new PdfPCell(new Phrase("Liste des machines déclarées par le client", new Font(Font.NORMAL, 9f, Font.NORMAL, BaseColor.WHITE))); //cell.BackgroundColor = new BaseColor(223, 0, 27); // -- RGB couleur -- //table.AddCell(cell); var docFooter = new Paragraph(); var footerFont = FontFactory.GetFont(FontFactory.TIMES_BOLD, 10f, BaseColor.BLACK); //docFooter.Font = titleFont; //////// -- A supprimer -- ************************** //docFooter.Add("Simulation n° : \n"); //docFooter.Add(new Chunk("Montant total dû : ")); //docFooter.Alignment = Element.ALIGN_RIGHT; //_document.Add(docFooter); OnEndPage(pdfWriter, _document); _document.Add(table); _document.Close(); pdfWriter.Close(); fileStream.Close(); #region Display PDF //Process.Start(path); #endregion } } #endregion } catch (Exception exception) { Console.WriteLine(exception.ToString()); throw; } }
private void btnExport_Click(object sender, EventArgs e) { try { if (!cbExcel.Checked && !cbPDF.Checked) { throw new Exception("Choisir un format d'export"); } MainForm main = (MainForm)this.ParentForm; SaveFileDialog saveFile = new SaveFileDialog(); saveFile.DefaultExt = cbPDF.Checked ? "pdf" : "csv"; String name = main.getSensorName(); name = Function.slugify(name + DateTime.Now); if (main.getSensorName() == "") { name = "allSensor"; } saveFile.FileName = name; if (cbExcel.Checked) { if (saveFile.ShowDialog() == DialogResult.OK) { String stream = ""; String sensorId = main.getSensorId(); DateTime start = main.getStartDate(); DateTime end = main.getEndDate(); //Selection des données et des capteurs liés String query = "SELECT s.label,s.uid,d.* from data d INNER JOIN sensor s ON s.id = d.sensor_id WHERE 1 "; //Ajout filtre par capteur si un capteur est sélectionné if (sensorId != "") { query += "AND sensor_id=@sensorId "; } //Ajout date de début / date de fin query += " AND (data_date BETWEEN @start AND @end)"; // Par ordre de date ascendante / capteur query += " ORDER BY d.data_date DESC,sensor_id"; //Ajout des parametres échappés Dictionary <String, String> parameters = new Dictionary <string, string>(); if (sensorId != "") { parameters["@sensorId"] = sensorId; } parameters["@start"] = start.ToString("yyyy-MM-dd HH:mm:ss"); parameters["@end"] = end.ToString("yyyy-MM-dd HH:mm:ss"); List <Dictionary <String, String> > results = null; results = Database.select(query, parameters); //Nom des colonnes sur la premiere ligne foreach (KeyValuePair <String, String> cell in results[0]) { stream += cell.Key + ";"; } //Saut d'une ligne stream += Environment.NewLine; //Valeurs des lignes foreach (Dictionary <String, String> row in results) { //Toutes les valeurs des cellules de la ligne courante foreach (KeyValuePair <String, String> cell in row) { stream += cell.Value + ";"; } stream += Environment.NewLine; } File.WriteAllText(saveFile.FileName, stream, Encoding.UTF8); MessageBox.Show("Export effectué avec succès sur " + saveFile.FileName); if (chkOpenFile.Checked) { Process.Start(saveFile.FileName); } } } else if (cbPDF.Checked) { if (saveFile.ShowDialog() == DialogResult.OK) { String sensorName = main.getSensorName(); String stream = ""; String sensorId = main.getSensorId(); DateTime start = main.getStartDate(); DateTime end = main.getEndDate(); String sensorUID = null; //Selection des données et des capteurs liés String query = "SELECT s.label,s.uid,d.* from data d INNER JOIN sensor s ON s.id = d.sensor_id WHERE 1 "; //Ajout filtre par capteur si un capteur est sélectionné if (sensorId != "") { query += "AND sensor_id=@sensorId "; } //Ajout date de début / date de fin query += " AND (data_date BETWEEN @start AND @end)"; // Par ordre de date ascendante / capteur query += " ORDER BY d.data_date DESC,sensor_id"; //Ajout des parametres échappés Dictionary <String, String> parameters = new Dictionary <string, string>(); if (sensorId != "") { parameters["@sensorId"] = sensorId; } parameters["@start"] = start.ToString("yyyy-MM-dd HH:mm:ss"); parameters["@end"] = end.ToString("yyyy-MM-dd HH:mm:ss"); List <decimal> temp = new List <decimal>(); List <decimal> humi = new List <decimal>(); List <Dictionary <String, String> > results = null; results = Database.select(query, parameters); //Nom des colonnes sur la premiere ligne foreach (KeyValuePair <String, String> cell in results[0]) { stream += cell.Key + ";"; } //Saut d'une ligne stream += Environment.NewLine; //Valeurs des lignes foreach (Dictionary <String, String> row in results) { //Toutes les valeurs des cellules de la ligne courante foreach (KeyValuePair <String, String> cell in row) { stream += cell.Value + ";"; } stream += Environment.NewLine; temp.Add(decimal.Parse(row["temperature"])); humi.Add(decimal.Parse(row["humidity"])); sensorUID = row["uid"]; } String tempMin = Function.PlusPetiteValeur(temp).ToString(".") + " °"; String tempMax = Function.PlusGrandeValeur(temp).ToString(".") + " °"; String tempMoy = Function.valeurMoyenne(temp).ToString(".") + " °"; String humiMin = Function.PlusPetiteValeur(humi).ToString(".") + " %"; String humiMax = Function.PlusGrandeValeur(humi).ToString(".") + " %"; String humiMoy = Function.valeurMoyenne(humi).ToString(".") + " %"; TimeSpan Diff = end - start; FileStream fs = new FileStream(saveFile.FileName, FileMode.Create, FileAccess.Write, FileShare.None); Document doc = new Document(PageSize.A4, 30, 30, 30, 30); doc.AddTitle("Rapport de relevés"); doc.AddKeywords("Metadata, iTextSharp 5.5.11"); doc.AddCreator("iTextSharp 5.5.11"); doc.AddAuthor("Thermetrie"); doc.AddHeader("Nothing", "No Header"); Rectangle rec2 = new Rectangle(PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(doc, fs); doc.Open(); doc.Add(new Paragraph("Rapport Temperature et Humidité")); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph("Date de rapport : " + DateTime.Now)); List infos = new List(); infos.IndentationLeft = 20f; infos.Add("Date de debut : " + start); infos.Add("Date de fin : " + end); infos.Add("Nom de capteur : " + sensorName); infos.Add("Uid capteur : " + sensorUID); infos.Add("T° min : " + tempMin + " -- T° max : " + tempMax + " -- T° moyenne :" + tempMoy); infos.Add("Hum. min : " + humiMin + " -- hum. max : " + humiMax + " -- hum.moyenne : " + humiMoy); infos.Add("Periode ( en jours) : " + Diff.Days); infos.Add("Periode ( en heures) : " + Diff.TotalHours); doc.Add(infos); Image img = Image.GetInstance(main.synthesis.getChart().GetBuffer()); img.ScalePercent(75f); doc.Add(img); doc.NewPage(); PdfPTable table = new PdfPTable(8); table.WidthPercentage = 100; //Nom des colonnes sur la premiere ligne foreach (KeyValuePair <String, String> cell in results[0]) { table.AddCell(new Phrase(cell.Key)); table.HeaderRows = 1; } foreach (Dictionary <String, String> row in results) { //Toutes les valeurs des cellules de la ligne courante foreach (KeyValuePair <String, String> cell in row) { table.AddCell(new Phrase(cell.Value)); } } doc.Add(table); doc.Close(); writer.Close(); String subject = "Rapport relevé de temperatures et humidité"; String content = " Bosses faineant !!!!"; fs.Close(); if (chkMailFile.Checked) { Function.send_report(subject, content, saveFile.FileName); } MessageBox.Show("Export effectué avec succès sur " + saveFile.FileName); if (chkOpenFile.Checked) { Process.Start(saveFile.FileName); } } } } catch (MySqlException ex) { MessageBox.Show("Erreur Sql d'export" + ex.Message, "ERREUR", MessageBoxButtons.OK); } catch (Exception ex) { MessageBox.Show("Erreur d'export" + ex.Message, "ERREUR", MessageBoxButtons.OK); } }