private void AddTexto(iTextSharp.text.Phrase phrase, string texto, int fontType, int fontSize) { iTextSharp.text.Font textFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, (float)fontSize, fontType, iTextSharp.text.BaseColor.BLACK); phrase.Add(new iTextSharp.text.Chunk(texto, textFont)); phrase.Add(new iTextSharp.text.Chunk(Environment.NewLine, textFont)); }
/// <summary> /// Converts the specified formated text. /// </summary> /// <param name="formatedText">The formated text.</param> /// <returns>The chunck object representing this formated text.</returns> public static iTextSharp.text.Phrase Convert(AODL.Document.Content.Text.FormatedText formatedText) { try { iTextSharp.text.Font font; if ((TextStyle)formatedText.Style != null && ((TextStyle)formatedText.Style).TextProperties != null) { font = TextPropertyConverter.GetFont( ((TextStyle)formatedText.Style).TextProperties); } else { font = DefaultDocumentStyles.Instance().DefaultTextFont; } iTextSharp.text.Phrase phrase = new iTextSharp.text.Phrase("", font); // default ctor protected - why ?? phrase.AddRange(FormatedTextConverter.GetTextContents(formatedText.TextContent, font)); return(phrase); } catch (Exception) { throw; } }
private void AddTexto(iTextSharp.text.Phrase phrase, IEnumerable <string> textos, int fontType, int fontSize) { foreach (string text in textos) { AddTexto(phrase, text, fontType, fontSize); } }
public override iTextSharp.text.IElement GeneratePdfElement() { iTextSharp.text.Phrase phrase = new iTextSharp.text.Phrase(); if (Content.Any()) { phrase.AddRange(Content.Select(e => e.GeneratePdfElement())); } return phrase; }
/// <summary> /// 创建pdf表格单元格 /// </summary> /// <param name="text"></param> /// <param name="pdfFont"></param> /// <returns></returns> private static iTextSharp.text.pdf.PdfPCell CreatePdfPCell(string text, iTextSharp.text.Font pdfFont) { iTextSharp.text.Phrase phrase = new iTextSharp.text.Phrase(text, pdfFont); iTextSharp.text.pdf.PdfPCell pdfPCell = new iTextSharp.text.pdf.PdfPCell(phrase); // TODO 单元格垂直居中显示 pdfPCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; pdfPCell.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; pdfPCell.MinimumHeight = 30; return(pdfPCell); }
/// <summary> /// Converts the specified formated text. /// </summary> /// <param name="formatedText">The formated text.</param> /// <returns>The chunck object representing this formated text.</returns> public static iTextSharp.text.Phrase Convert(AODL.Document.Content.Text.FormatedText formatedText) { iTextSharp.text.Font font; if ((TextStyle)formatedText.Style != null && ((TextStyle)formatedText.Style).TextProperties != null) font = TextPropertyConverter.GetFont( ((TextStyle)formatedText.Style).TextProperties); else font = DefaultDocumentStyles.Instance().DefaultTextFont; iTextSharp.text.Phrase phrase = new iTextSharp.text.Phrase("", font); // default ctor protected - why ?? phrase.AddRange(FormatedTextConverter.GetTextContents(formatedText.TextContent, font)); return phrase; }
/// <summary> /// Converts the tabs. /// </summary> /// <param name="tabStop">The tab stop.</param> /// <returns>Chunkck containing whitespace for a tab.</returns> public static iTextSharp.text.Phrase ConvertTabs(AODL.Document.Content.Text.TextControl.TabStop tabStop, iTextSharp.text.Font font) { try { // Only a trick since PDF doesn't support tab stops as know from other // formats, so we only use whitespace character for the beginning // TODO: do it better iTextSharp.text.Phrase phrase = new iTextSharp.text.Phrase(" ", font); return(phrase); } catch (Exception) { throw; } }
/// <summary> /// Converts the tabs. /// </summary> /// <param name="tabStop">The tab stop.</param> /// <returns>Chunkck containing whitespace for a tab.</returns> public static iTextSharp.text.Phrase ConvertTabs(AODL.Document.Content.Text.TextControl.TabStop tabStop, iTextSharp.text.Font font) { try { // Only a trick since PDF doesn't support tab stops as know from other // formats, so we only use whitespace character for the beginning // TODO: do it better iTextSharp.text.Phrase phrase = new iTextSharp.text.Phrase(" ", font); return phrase; } catch(Exception) { throw; } }
public virtual void manipulatePdf(string src, string dest) { PdfReader reader = new PdfReader(src); PdfStamper stamper = new PdfStamper(reader, new System.IO.FileStream(dest, System.IO.FileMode.Create, System.IO.FileAccess.Write)); stamper.RotateContents = false; Phrase header = new Phrase("Copy", new Font(Font.FontFamily.HELVETICA, 14)); for (int i = 1; i <= reader.NumberOfPages; i++) { float x = reader.GetPageSize(i).Width / 2; float y = reader.GetPageSize(i).GetTop(20); ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_CENTER, header, x, y, 0); } stamper.Close(); reader.Close(); }
protected iTextSharp.text.pdf.PdfPCell PhraseCell(iTextSharp.text.Phrase phrase, float height, int hAlign, int vAlign = iTextSharp.text.pdf.PdfPCell.ALIGN_TOP, iTextSharp.text.Color backColor = null, iTextSharp.text.Color borderColor = null) { iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(phrase); try { cell.BorderColor = iTextSharp.text.Color.WHITE; cell.BackgroundColor = backColor; cell.FixedHeight = height; cell.VerticalAlignment = vAlign; cell.HorizontalAlignment = hAlign; cell.PaddingBottom = 2f; cell.PaddingTop = 0f; } catch (Exception ex) { } return(cell); }
///******************************************************************************************************* /// <summary> /// Método que exporta la tabla de resultados en el grid a PDF /// </summary> /// <param name="Documento">Objeto al cúal agregaremos el contenido del reporte</param> /// <creo>Juan Alberto Hernández Negrete</creo> /// <fecha_creo>27-nov-2013</fecha_creo> /// <modifico></modifico> /// <fecha_modifico></fecha_modifico> /// <causa_modificacion></causa_modificacion> ///******************************************************************************************************* public void Exportar_Datos_PDF(iTextSharp.text.Document Documento) { bool Es_Footer = false; try { iTextSharp.text.Phrase _frase = null; iTextSharp.text.pdf.PdfPCell _celda = null; iTextSharp.text.FontFactory.RegisterDirectory(@"C:\Windows\Fonts"); //Creamos el objeto de tipo tabla para almacenar el resultado de la búsqueda. iTextSharp.text.pdf.PdfPTable Rpt_Tabla = new iTextSharp.text.pdf.PdfPTable(Grd_Resultado.Columns.Count); //Obtenemos y establecemos el formato de las columnas de la tabla. float[] Ancho_Cabeceras = Obtener_Tamano_Columnas(Grd_Resultado); //Creamos y definimos algunas propiedades que tendrá la fuente que se aplicara a las celdas de la tabla de resultados. iTextSharp.text.Font Fuente_Tabla_Contenido = iTextSharp.text.FontFactory.GetFont("Courier New", 7, iTextSharp.text.Font.NORMAL); iTextSharp.text.Font Fuente_Tabla_Footer = iTextSharp.text.FontFactory.GetFont("Courier New", 9, iTextSharp.text.Font.BOLD); //Establecemos el formato que tendrá la tabla que mostrara el resultado de la búsqueda según el movimiento consultado. Rpt_Tabla.DefaultCell.Padding = 3; Rpt_Tabla.SetWidths(Ancho_Cabeceras); Rpt_Tabla.WidthPercentage = 100; Rpt_Tabla.DefaultCell.BorderWidth = 2; Rpt_Tabla.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; Rpt_Tabla.HeaderRows = 1; // Creamos y establecemos el formato que tendrá el titulo del reporte. iTextSharp.text.Paragraph Titulo = new iTextSharp.text.Paragraph(); Titulo.Alignment = iTextSharp.text.Element.ALIGN_CENTER; Titulo.Font = iTextSharp.text.FontFactory.GetFont("Consolas"); Titulo.Font.SetStyle(iTextSharp.text.Font.BOLD); Titulo.Font.Size = 14; Titulo.Add("Museo de las Momias de Guanajuato"); // Creamos y establecemos el formato que tendrá el subtitulo del reporte. iTextSharp.text.Paragraph Subtitulo = new iTextSharp.text.Paragraph(); Subtitulo.Alignment = iTextSharp.text.Element.ALIGN_CENTER; Subtitulo.Font = iTextSharp.text.FontFactory.GetFont("Consolas"); Subtitulo.Font.SetStyle(iTextSharp.text.Font.BOLD); Subtitulo.Font.Size = 12; Subtitulo.Add("Log de eventos en " + Cmb_Tabla.Text.ToString() + ": " + (Dtp_Fecha_Inicio.Checked.Equals(true) ? Dtp_Fecha_Inicio.Text : "") + " - " + (Dtp_Fecha_Termino.Checked.Equals(true) ? Dtp_Fecha_Termino.Text : "")); // rango de fechas del reporte // fecha actual iTextSharp.text.Phrase Fecha = new iTextSharp.text.Phrase(DateTime.Today.ToString("dd-MMM-yyyy")); Fecha.Font.Size = 11; float[] Anchura_Tabla_Subtitulo = { 90, 10 }; // subtitulo con fecha en una tabla sin bordes (misma línea) iTextSharp.text.pdf.PdfPTable Tabla_Subtitulo = new iTextSharp.text.pdf.PdfPTable(Anchura_Tabla_Subtitulo); Tabla_Subtitulo.WidthPercentage = 100; Tabla_Subtitulo.DefaultCell.Border = iTextSharp.text.pdf.PdfPCell.NO_BORDER; Tabla_Subtitulo.DefaultCell.VerticalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; Tabla_Subtitulo.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT; Tabla_Subtitulo.AddCell(Subtitulo); Tabla_Subtitulo.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; Tabla_Subtitulo.AddCell(Fecha); //Agregamos los nombres de las columnas de la tabla que se imprimira en el reporte. Array.ForEach(Grd_Resultado.Columns.OfType <DataGridViewColumn>().ToArray(), columna => { var cabecera = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(columna.HeaderText, iTextSharp.text.FontFactory.GetFont("Consolas", 8, iTextSharp.text.Font.BOLD))); cabecera.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY; cabecera.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; Rpt_Tabla.AddCell(cabecera); }); //Modificamos el tipo de border que tendrá las celdas que mostraran los datos, con respécto al borde que tiene asignado la cabeceras de las columnas. Rpt_Tabla.DefaultCell.BorderWidth = 1; //Agreamos el resultado de la búsqueda de movimientos al tabla que se enviara al reporte. Array.ForEach(Grd_Resultado.Rows.OfType <DataGridViewRow>().ToArray(), fila => { if (fila.Cells[0] != null) { if (fila.Cells[0].Value != null) { if (fila.Cells[0].Value.ToString().ToLower().Contains("totales")) { Es_Footer = true; } else { Es_Footer = false; } } else { Es_Footer = false; } } else { Es_Footer = false; } Array.ForEach(fila.Cells.OfType <DataGridViewCell>().ToArray(), celda => { string texto = string.Empty; if (celda.Value != null) { if (celda.ValueType.Name.Equals("DateTime")) { texto = string.Format("{0:dd MMM yyyy}", celda.Value); } else if (celda.ValueType.Name.Equals("Decimal") && !celda.OwningColumn.HeaderText.Equals("NoCaja")) { texto = string.Format("{0:n}", celda.Value); } else { texto = celda.Value.ToString(); } } if (Es_Footer) { //Establecemos el formato que llevaran las celdas de totales de la tabla del reporte. _frase = new iTextSharp.text.Phrase(texto, Fuente_Tabla_Footer); _celda = new iTextSharp.text.pdf.PdfPCell(_frase); _celda.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY; } else { //Establecemos el formato que llevaran las celdas de contenido de la tabla del reporte. _frase = new iTextSharp.text.Phrase(texto, Fuente_Tabla_Contenido); _celda = new iTextSharp.text.pdf.PdfPCell(_frase); } if (texto.Contains("$")) { _celda.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; } else { _celda.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; } _celda.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; //Establecemos el valor de la celda. Rpt_Tabla.AddCell(_celda); }); //Indicamos que se completo de editar la fila y completamos la operación. Rpt_Tabla.CompleteRow(); }); // Se agrega el PDFTable al documento. Documento.Add(Titulo); Documento.Add(Tabla_Subtitulo); Documento.Add(new iTextSharp.text.Paragraph("\n")); Documento.Add(Rpt_Tabla); } catch (Exception Ex) { MessageBox.Show(this, Ex.Message, "Error - Método: [Exportar_Datos_PDF]", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private static PdfPhrase GetCellPhrase(string text) { PdfPhrase p = new PdfPhrase(text, GetCellFont()); return(p); }
private static PdfPhrase GetHeaderPhrase(string text) { PdfPhrase p = new PdfPhrase(text, GetHeaderFont()); return(p); }
public iTextSharp.text.IElement ToPDF() { iTextSharp.text.Phrase content = new iTextSharp.text.Phrase((float)Leading, Content, Font.ToPDFFont()); return(content); }
private void AddSignature(PdfReader pdf, PdfSignatureAppearance sap, Juschubut.PdfDigitalSign.CertificateInfo certificate) { int anchoPagina = (int)pdf.GetPageSize(1).Width; var rectangle = this.Appearance.GetRectangle(anchoPagina); var signatureRect = new iTextSharp.text.Rectangle((float)rectangle.X, (float)rectangle.Y, (float)(rectangle.X + rectangle.Width), (float)(rectangle.Y + rectangle.Height)); int pagina = pdf.NumberOfPages; if (this.Appearance.Page.HasValue && this.Appearance.Page.Value <= pdf.NumberOfPages) { pagina = this.Appearance.Page.Value; } sap.SetVisibleSignature(signatureRect, pagina, null); sap.SignDate = DateTime.Now; sap.Acro6Layers = true; sap.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION; if (!string.IsNullOrEmpty(this.Appearance.SignatureImage)) { var fileInfo = new FileInfo(this.Appearance.SignatureImage); if (!fileInfo.Exists) { this.Log(string.Format("No se encontro archivo de firma ológrafa ({0})", this.Appearance.SignatureImage)); } else if (fileInfo.Length == 0) { this.Log(string.Format("El archivo de firma ológrafa está vacio ({0})", this.Appearance.SignatureImage)); } else { try { sap.SignatureGraphic = iTextSharp.text.Image.GetInstance(new Uri(this.Appearance.SignatureImage)); } catch (Exception ex) { Log(string.Format("Error al leer el archivo de firma ológrafo. El archivo esta dañado, no es un archivo .png, o no se puede tener acceso de lectura. {0}", this.Appearance.SignatureImage)); StringBuilder sb = new StringBuilder(); var ex2 = ex; do { sb.AppendLine(ex2.Message); ex2 = ex2.InnerException; }while (ex2 != null); Log("Error: " + sb.ToString()); if (!string.IsNullOrEmpty(this.Appearance.SignatureImageDefault)) { try { Log("Cargando firma por default"); sap.SignatureGraphic = iTextSharp.text.Image.GetInstance(new Uri(this.Appearance.SignatureImageDefault)); } catch (Exception ex3) { Log(ex3.Message); } } } sap.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC; sap.SignatureGraphic.Alignment = iTextSharp.text.Image.ALIGN_TOP; } } // Descripcion de la Firma iTextSharp.text.Font textFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, (float)10, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); var phrase = new iTextSharp.text.Phrase(); phrase.Font = textFont; int fontPre = 6; int fontFirma = this.Appearance.Height < 100 ? 8 : 10; int fontPost = this.Appearance.Height < 100 ? 7 : 10; if (this.Appearance.PreFirma != null) { AddTexto(phrase, this.Appearance.PreFirma, iTextSharp.text.Font.NORMAL, fontPre); } AddTexto(phrase, certificate.CN, iTextSharp.text.Font.BOLD, fontFirma); if (this.Appearance.PostFirma != null) { AddTexto(phrase, this.Appearance.PostFirma, iTextSharp.text.Font.NORMAL, fontPost); } PdfTemplate n2 = sap.GetLayer(0); ColumnText ct = new ColumnText(n2); float x = n2.BoundingBox.Left; float y = n2.BoundingBox.Top; float w = n2.BoundingBox.Width; float h = n2.BoundingBox.Height; float x1 = x; float y1 = y; float x2 = x + w; float y2 = y - h; // new working code: crreate a table PdfPTable table = new PdfPTable(1); table.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER; table.SetWidths(new[] { 1 }); table.WidthPercentage = 100; table.AddCell(new PdfPCell(phrase) { HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_BOTTOM, FixedHeight = y1, Border = iTextSharp.text.Rectangle.NO_BORDER }); ct.SetSimpleColumn(x1, y1, x2, y2); ct.AddElement(table); ct.Go(); }
public void SaveDataGridViewToPDF(DataGridView Dv, string FilePath) { string folderPath = Environment.CurrentDirectory + "\\Relatório\\"; //"C:\\PDFs\\"; if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } iTextSharp.text.FontFactory.RegisterDirectories(); iTextSharp.text.Font myfont = iTextSharp.text.FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 15, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 10f, 0f); pdfDoc.Open(); PdfWriter wri = PdfWriter.GetInstance(pdfDoc, new FileStream(FilePath + "Extrato da conta.pdf", FileMode.Create)); pdfDoc.Open(); PdfPTable _mytable = new PdfPTable(Dv.ColumnCount - 4); float[] widths = new float[] { 2.1f, 5f, 1.5f, 1.6f, 1.5f }; _mytable.SetWidths(widths); _mytable.WidthPercentage = 90; //_mytable.DefaultCell.Border = Rectangle.NO_BORDER; _mytable.DefaultCell.BorderColor = new iTextSharp.text.BaseColor(System.Drawing.Color.White); iTextSharp.text.Paragraph ph = new iTextSharp.text.Paragraph("Extrato da conta ", myfont); ph.Alignment = iTextSharp.text.Element.ALIGN_CENTER; pdfDoc.Add(ph); myfont = iTextSharp.text.FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 9, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); ph = new iTextSharp.text.Paragraph("Conta: " + cmbContas.Text, myfont); ph.Alignment = iTextSharp.text.Element.ALIGN_CENTER; pdfDoc.Add(ph); // adiciona a linha em branco(enter) ao paragrafo ph.Add(new iTextSharp.text.Chunk("\n")); ph = new iTextSharp.text.Paragraph("Período: " + dtDataIni.Text + " até " + dtDataFinal.Text, myfont); pdfDoc.Add(ph); ph = new iTextSharp.text.Paragraph("Dada de emissão: " + DateTime.Now, myfont); pdfDoc.Add(ph); ph = new iTextSharp.text.Paragraph(); // cria um objeto sepatador (um traço) iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator(); // adiciona o separador ao paragravo ph.Add(seperator); // adiciona a linha em branco(enter) ao paragrafo ph.Add(new iTextSharp.text.Chunk("\n")); // imprime o pagagrafo no documento // pdfDoc.Add(ph); ph.Add(new iTextSharp.text.Chunk("\n")); pdfDoc.Add(ph); myfont = iTextSharp.text.FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 8, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); for (int j = 0; j < Dv.Columns.Count; ++j) { if (Dv.Columns[j].HeaderText != "codigo" && Dv.Columns[j].HeaderText != "tipo" && Dv.Columns[j].HeaderText != "codigo_conta" && Dv.Columns[j].HeaderText != "valor") { iTextSharp.text.Phrase p = new iTextSharp.text.Phrase(Dv.Columns[j].HeaderText, myfont); PdfPCell cell = new PdfPCell(p); cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL; cell.BorderWidth = 0; _mytable.AddCell(cell); } } myfont = iTextSharp.text.FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 9, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); //------------------------- for (int i = 0; i < Dv.Rows.Count; ++i) { for (int j = 0; j < Dv.Columns.Count; ++j) { if (Dv.Columns[j].HeaderText != "codigo" && Dv.Columns[j].HeaderText != "tipo" && Dv.Columns[j].HeaderText != "codigo_conta" && Dv.Columns[j].HeaderText != "valor") { iTextSharp.text.Phrase p = new iTextSharp.text.Phrase();// Dv.Rows[i].Cells[j].Value == null ? null : Dv.Rows[i].Cells[j].Value.ToString(), myfont); PdfPCell cell = new PdfPCell(); if (Dv.Columns[j].HeaderText == "Saldo" || Dv.Columns[j].HeaderText == "Saída/ Débito" || Dv.Columns[j].HeaderText == "Entrada/Crédito") { myfont = iTextSharp.text.FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 9, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); if (Dv.Columns[j].HeaderText == "Saída/ Débito") { myfont = iTextSharp.text.FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 9, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.RED); } else if (Dv.Columns[j].HeaderText == "Entrada/Crédito") { myfont = iTextSharp.text.FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 9, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLUE); } else if (Dv.Columns[j].HeaderText == "Saldo") { var saldo = Dv.Rows[i].Cells[j].Value == null ? 0 : Convert.ToDouble(Dv.Rows[i].Cells[j].Value); if (saldo < 0 && i == Dv.Rows.Count - 1) { myfont = iTextSharp.text.FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 9, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.RED); } } p = new iTextSharp.text.Phrase(Dv.Rows[i].Cells[j].Value == null ? null : Convert.ToDecimal(Dv.Rows[i].Cells[j].Value.ToString()).ToString("N2"), myfont); cell = new PdfPCell(p); cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT; if (i == 0 || i == Dv.Rows.Count - 1) { cell.BackgroundColor = new iTextSharp.text.BaseColor(System.Drawing.Color.Silver); } } else if (Dv.Columns[j].HeaderText == "Data de lançamento" && Dv.Rows[i].Cells[j + 1].Value.ToString() == "SALDO ANTERIOR" || Dv.Rows[i].Cells[j + 1].Value.ToString() == "SALDO ATUAL CONTA") { p = new iTextSharp.text.Phrase(Dv.Rows[i].Cells[j].Value == null ? null : Convert.ToDateTime(Dv.Rows[i].Cells[j].Value.ToString()).ToString("dd/MM/yyyy"), myfont); cell = new PdfPCell(p); cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; if (i == 0 || i == Dv.Rows.Count - 1) { cell.BackgroundColor = new iTextSharp.text.BaseColor(System.Drawing.Color.Silver); } } else { p = new iTextSharp.text.Phrase(Dv.Rows[i].Cells[j].Value == null ? null : Dv.Rows[i].Cells[j].Value.ToString(), myfont); cell = new PdfPCell(p); cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; if (i == 0 || i == Dv.Rows.Count - 1) { cell.BackgroundColor = new iTextSharp.text.BaseColor(System.Drawing.Color.Silver); } } cell.BorderWidth = 0; // _mytable.DefaultCell.BorderWidth = 0; cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL; _mytable.AddCell(cell); } } } //------------------------ pdfDoc.Add(_mytable); pdfDoc.Close(); System.Diagnostics.Process.Start(FilePath); }
private void AddCartaoSUSCompleto(long numeroCartaoSUS) { ISeguranca iseguranca = Factory.GetInstance<ISeguranca>(); if (!iseguranca.VerificarPermissao(((ViverMais.Model.Usuario)Session["Usuario"]).Codigo, "ALTERAR_CARTAO_SUS", Modulo.CARTAO_SUS)) { ClientScript.RegisterClientScriptBlock(typeof(String), "ok", "<script>alert('Você não tem permissão para acessar essa página. Em caso de dúViverMais, entre em contato.');window.location='../Home.aspx';</script>"); return; } MemoryStream MStream = new MemoryStream(); iTextSharp.text.Document doc = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(295, 191)); PdfWriter writer = PdfWriter.GetInstance(doc, MStream); //Monta o pdf doc.Open(); iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph(); p.IndentationLeft = -10; p.Font.Color = iTextSharp.text.Color.BLACK; iTextSharp.text.Phrase nome = new iTextSharp.text.Phrase(HiddenNomePaciente.Value + "\n"); //paciente.Nome nome.Font.Size = 8; iTextSharp.text.Phrase nascimento = new iTextSharp.text.Phrase(HiddenDataNascimento.Value + "\t\t" + HiddenMunicipio.Value + "\n"); nascimento.Font.Size = 8; iTextSharp.text.Phrase cartaosus = new iTextSharp.text.Phrase(numeroCartaoSUS + "\n"); cartaosus.Font.Size = 12; PdfContentByte cb = writer.DirectContent; Barcode39 code39 = new Barcode39(); code39.Code = numeroCartaoSUS.ToString(); code39.StartStopText = true; code39.GenerateChecksum = false; code39.Extended = true; iTextSharp.text.Image imageEAN = code39.CreateImageWithBarcode(cb, null, null); iTextSharp.text.Image back = iTextSharp.text.Image.GetInstance(Server.MapPath("img/") + "back_card.JPG"); back.SetAbsolutePosition(0, doc.PageSize.Height - back.Height); iTextSharp.text.Image front = iTextSharp.text.Image.GetInstance(Server.MapPath("img/") + "front_card.JPG"); front.SetAbsolutePosition(0, doc.PageSize.Height - front.Height); iTextSharp.text.Phrase barcode = new iTextSharp.text.Phrase(new iTextSharp.text.Chunk(imageEAN, 36, -45)); barcode.Font.Color = iTextSharp.text.Color.WHITE; p.SetLeading(1, 0.7f); p.Add(cartaosus); p.Add(nome); p.Add(nascimento); p.Add(barcode); doc.Add(p); doc.Add(back); doc.NewPage(); doc.Add(front); doc.Close(); //Fim monta pdf HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=CartaoSUS.pdf"); HttpContext.Current.Response.BinaryWrite(MStream.GetBuffer()); HttpContext.Current.Response.End(); }