Es algo muy útil y práctico.
A continuación les dejo una explicación de cómo pueden generar archivos PDF desde .Net utilizando la biblioteca itextsharp que la pueden usar en forma gratuita.
Let's go!
Primero, añadimos a nuestro proyecto una referencia a esta biblioteca (este paso no lo voy a explicar ya que es muy sencillo, si alguien no sabe como hacerlo que me pregunte).
Ahora agregamos a nuestro código:
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
namespace PDFApp
{
public class Query
{
public static XmlDocument ExecuteQuery(SqlCommand cmd, ref SqlTransaction trans)
{
if( cmd == null )
throw new ArgumentNullException("cmd", "El comando no puede ser null." );
if( trans == null )
throw new ArgumentNullException("trans", "La transaccion no puede ser null." );
XmlNode xmlrow = null;
XmlReader xmlreader = null;
XmlDocument xmldoc = null;
xmldoc = new XmlDocument();
xmldoc.LoadXml("" );
xmlreader = cmd.ExecuteXmlReader();
xmlrow = xmldoc.ReadNode(xmlreader);
while ( xmlrow != null )
{
xmldoc.DocumentElement.AppendChild(xmlrow);
xmlrow = xmldoc.ReadNode(xmlreader);
}
xmlreader.Close();
return xmldoc;
}
public static XmlDocument ExecuteQuery(SqlCommand cmd, SqlConnection conn)
{
XmlDocument xmldoc = null;
SqlTransaction trans = null;
if ( conn != null )
{
if ( conn.State != ConnectionState.Open )
{
conn.Open();
}
cmd.Connection = conn;
}
else
{
throw new ArgumentNullException("cmd", "El comando no puede ser null." );
}
trans = cmd.Connection.BeginTransaction();
xmldoc = new XmlDocument();
xmldoc.LoadXml("" );
try
{
cmd.Transaction = trans;
xmldoc = ExecuteQuery(cmd, ref trans);
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
throw ex;
}
return xmldoc;
}
}
Y ahora ponemos lo siguiente en el código del evento de un botón de nuestra página.
Document document = new Document(PageSize.A4, 90f, 50f, 90f, 60f);
try
{
XmlDocument Doc = new XmlDocument();
SqlConnection cnx = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=BASEDEDATOS;Data Source=SERVIDORSQL" );
//Este es un ejemplo que toma datos de una tabla personas,
//Es muy importante poner "for xml raw !!!
SqlCommand cmd = new sqlcommand("select * from personas for xml raw" );
cmd.Connection = cnx;
Doc = Query.ExecuteQuery(cmd, cnx);
// Configuración del documento PDF
string FullPathOut = "c:\\SalidaPDF.pdf";
PdfWriter.getInstance(document, new filestream(fullpathout, filemode.create));
// Fonts y colores
Font font_celdas = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL);
Font font_titulo_tabla = FontFactory.getFont(FontFactory.HELVETICA, 9, Font.BOLD,
new Color(255,255,255));
Color color_negro = new color(0, 0, 0);
document.Open();
Table table = new Table(3);
table.BorderWidth = 0;
table.BorderColor = color_negro;
table.Padding = 1;
table.Spacing = 1;
Cell titulo = new cell(new Phrase("Datos de la tabla", font_titulo_tabla));
titulo.Header = true ;
titulo.BackgroundColor = color_negro;
titulo.Colspan = 3;
table.addCell(titulo);
table.addCell(new Phrase("Nombre", font_celdas));
table.addCell(new Phrase("Num. Documento", font_celdas));
table.addCell(new Phrase("Teléfono", font_celdas));
table.endHeaders();
foreach(xmlelement elem in Doc.SelectNodes("/ROOT/row" ))
{
table.addCell(new Phrase(Elem.GetAttribute("Columna1" ), font_celdas));
table.addCell(new Phrase(Elem.GetAttribute("Columna2" ), font_celdas));
table.addCell(new Phrase(Elem.GetAttribute("Columna3" ), font_celdas));
}
document.Add(table);
}
catch (XmlException xex)
{
Console.Error.WriteLine(xex.Message);
}
catch (DocumentException de)
{
Console.Error.WriteLine(de.Message);
}
catch (IOException ioe)
{
Console.Error.WriteLine(ioe.Message);
}
finally
{
document.Close();
}
}
}
}
Espero que les sirva! En la próxima continuaré con este tema!
Saludos!
http://codigodavincipuntonet.blogspot.com/
.