sábado, 23 de janeiro de 2010

Relatorio em PDF com C# (asp.net)

importar para o sistema a dll itextsharp - http://sourceforge.net/projects/itextsharp/

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;


protected void btnRelatorio_Click(object sender, EventArgs e)
{
if (gvCliProf.Rows.Count > 0)
{
// creation of the document with a certain size and certain margins
Document document = new Document(PageSize.A4.Rotate(), 30, 30, 30, 30);

try
{
// creation of the different writers
// um detalhe ao publicar deve-se retirar o arquivo gerado durante a construção se eventualmente ele o mesmo for, o sistema o recriará com as permissões do wwwroot.
//estancia o documento.
PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + @"PDF\\Campanha.pdf", FileMode.Create));

// we add some meta information to the document
document.AddAuthor("xxx");
document.AddSubject("xxxx");
//abre para registro.
document.Open();
//instância da tabela e criação da mesma
iTextSharp.text.Table datatable = new iTextSharp.text.Table(7);
//altura da Tabela
datatable.Padding = 4;
//alinhamento dentro da celula
datatable.Spacing = 0;
//datatable.setBorder(Rectangle.NO_BORDER);
//float[] headerwidths = { 10, 24, 12, 12, 7, 7, 7, 7, 7, 7 };
//gera a medida de cada célula, deve-se conter a quantidade de células especificadas na instância da tabela
float[] headerwidths = { 10, 15, 30, 20, 40, 24, 15 };
//instacia de tamanho
datatable.Widths = headerwidths;
datatable.WidthPercentage = 100;

// the first cell spans 7 columns
//gera uma celula com o tamanho total das celulas no caso 7 celulas
Cell cell = new Cell(new Phrase(@"Cliente\Nome do Relatorio", FontFactory.GetFont(FontFactory.HELVETICA, 24, Font.BOLD)));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.Leading = 30;
cell.Colspan = 7;
cell.Border = Rectangle.NO_BORDER;
cell.BackgroundColor = new Color(0xC0, 0xC0, 0xC0);
datatable.AddCell(cell);
// the first cell spans 7 columns
//nova célula no tamanho da columns
cell = new Cell(new Phrase("Campanha: " + txtNum.Text + " - " + txtNomeCampanha.Text, FontFactory.GetFont(FontFactory.HELVETICA, 18, Font.BOLD)));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.Leading = 20;
cell.Colspan = 7;
cell.Border = Rectangle.NO_BORDER;
cell.BackgroundColor = new Color(0xC0, 0xC0, 0xC0);
datatable.AddCell(cell);

//cria cabeçario.

// These cells span 2 rows
datatable.DefaultCellBorderWidth = 2;
datatable.DefaultHorizontalAlignment = 1;
datatable.DefaultRowspan = 2;
datatable.AddCell("Id");
datatable.AddCell("Código");
//datatable.AddCell(new Phrase(@"Nome\Apelido", FontFactory.GetFont(FontFactory.HELVETICA, 14, Font.BOLD)));
datatable.AddCell(@"Nome\Apelido");
datatable.AddCell("Celular");
datatable.AddCell("e-mail");
datatable.AddCell("Profissão");
// This cell spans the remaining 6 columns in 1 row
//mescla varias colunas
//datatable.DefaultRowspan = 1;
//datatable.DefaultColspan = 6;
//datatable.AddCell("Permissions");
// These cells span 1 row and 1 column
//volta ao normal
datatable.DefaultColspan = 1;
datatable.AddCell("Paticipação");

// this is the end of the table header, finaliza cabeçario
datatable.EndHeaders();


//insere intens selecionados em um grid
datatable.DefaultCellBorderWidth = 1;
datatable.DefaultRowspan = 1;
int i = 0;
while ( i Menor gvCliProf.Rows.Count )
{
GridViewRow row = gvCliProf.Rows[i];
bool isChecked = ((CheckBox)row.FindControl("chkSelecao")).Checked;
if (isChecked)
{

datatable.DefaultHorizontalAlignment = Element.ALIGN_LEFT;
datatable.AddCell(gvCliProf.Rows[i].Cells[1].Text);//id
datatable.AddCell(gvCliProf.Rows[i].Cells[2].Text);//cod empresa
datatable.DefaultHorizontalAlignment = Element.ALIGN_CENTER;
datatable.AddCell(HttpUtility.HtmlDecode(gvCliProf.Rows[i].Cells[3].Text));//nome apelido
datatable.AddCell(HttpUtility.HtmlDecode(gvCliProf.Rows[i].Cells[4].Text));//celular
datatable.AddCell(HttpUtility.HtmlDecode(gvCliProf.Rows[i].Cells[5].Text));// email
datatable.AddCell(HttpUtility.HtmlDecode(gvCliProf.Rows[i].Cells[6].Text));//profissao
datatable.AddCell(gvCliProf.Rows[i].Cells[7].Text);//participou
}
i++;
}
//adiciona o documento
document.Add(datatable);
// we close the document
document.Close();
//redireciona para mostrar
Response.Redirect("~/PDF/Campanha.pdf");

}
catch (IOException ex)
{
document.Close();
throw ex;
}
catch (Exception ex)
{
document.Close();
throw ex;
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Mensagem", @"window.alert('Sem Clientes\Profissionais!');", true);
}
}

Está é uma adaptação ao exemplo mostrado no link acima, para facilitar e ajudar a quem necessita gerar relatórios sem o uso do Crystal, está uma opção free.
E mais detalhes voce pode encontrar no tutorial contido no site: http://itextsharp.sourceforge.net/tutorial/

att

Fernando Valota

Nenhum comentário:

Postar um comentário