Geração de Relatórios PDF em C# (.NET) com iTextSharp e QuestPDF

Treinador Online de Python para Iniciantes

Aprenda Python facilmente sem sobrecarga teórica. Resolva tarefas práticas com verificação automática e escreva código diretamente no navegador.

Start Course

Geração de Relatórios PDF em C# (.NET): Visão Geral das Bibliotecas e Exemplos



No desenvolvimento moderno na plataforma .NET, a criação de documentos PDF é uma das tarefas frequentes. Seja para gerar faturas, relatórios, notas fiscais ou dashboards analíticos, o C# oferece ferramentas poderosas para trabalhar com PDF. Neste artigo, abordaremos três bibliotecas populares: iTextSharp, QuestPDF e PdfSharp. Você aprenderá qual escolher para cada tarefa específica e verá exemplos de código funcionais.



1. iTextSharp (iText 7 para .NET)



iTextSharp é um port da popular biblioteca Java iText para .NET. É a solução mais madura e funcional, suportando layouts complexos, tabelas, imagens, anotações e assinaturas digitais. No entanto, o uso comercial requer a compra de uma licença (AGPL para open-source).



Instalação

dotnet add package itext7


Exemplo: relatório simples com tabela

using iText.Kernel.Pdf;using iText.Layout;using iText.Layout.Element;

public void CreatePdfReport(){ string filePath = "report.pdf"; using (PdfWriter writer = new PdfWriter(filePath)) using (PdfDocument pdf = new PdfDocument(writer)) using (Document document = new Document(pdf)) { document.Add(new Paragraph("Relatório de Vendas de Março") .SetBold().SetFontSize(18));

Table table = new Table(3); table.AddCell("Produto"); table.AddCell("Quantidade"); table.AddCell("Preço"); table.AddCell("Notebook"); table.AddCell("12"); table.AddCell("R$ 75.000,00"); table.AddCell("Monitor"); table.AddCell("5"); table.AddCell("R$ 32.000,00");

document.Add(table); }}


Vantagens: máxima flexibilidade, suporte a estruturas complexas, assinaturas digitais.
Desvantagens: API complexa para iniciantes, licenciamento para uso comercial.



2. QuestPDF



QuestPDF é uma biblioteca moderna com interface fluente e mecanismo de renderização embutido. Permite descrever o documento de forma declarativa, semelhante a HTML/CSS. Ideal para gerar relatórios padrão com elementos repetitivos.



Instalação

dotnet add package QuestPDF


Exemplo: fatura com cabeçalho e tabela

using QuestPDF.Fluent;using QuestPDF.Helpers;using QuestPDF.Infrastructure;

public byte[] GenerateInvoice(){ return Document.Create(container => { container.Page(page => { page.Size(PageSizes.A4); page.Margin(20); page.Header().Text("Fatura nº 12345") .SemiBold().FontSize(20).FontColor(Colors.Blue.Darken2);

page.Content().Table(table => { table.ColumnsDefinition(columns => { columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); });

table.Header(header => { header.Cell().Background(Colors.Grey.Lighten3).Text("Serviço"); header.Cell().Background(Colors.Grey.Lighten3).Text("Valor"); header.Cell().Background(Colors.Grey.Lighten3).Text("Quantidade"); });

table.Cell().Text("Consultoria"); table.Cell().Text("R$ 5.000,00"); table.Cell().Text("2");

table.Cell().Text("Desenvolvimento"); table.Cell().Text("R$ 15.000,00"); table.Cell().Text("1"); });

page.Footer().AlignCenter().Text("Obrigado pela parceria!"); }); }).GeneratePdf();}


Vantagens: código simples e legível, excelente desempenho, gratuito para uso comercial

Recommendations