You are on page 1of 5

Hola, aqui te muestro un ejemplo de como uasr mas de una pagina con itextsharp, espero que te

sirva. Saludos
using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace iTextSharp.tutorial.Chap01
{
/// <summary>
/// Chap0107
/// </summary>
public class Chap0107
{
public Chap0107()
{
Console.WriteLine("Chapter 1 example 7: newPage()");
// step 1: creation of a document-object
Document document = new Document();
try
{
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
PdfWriter.GetInstance(document, new
FileStream("Chap0107.pdf", FileMode.Create));
// step 3:
// we Add a Watermark that will show up on PAGE 1
try
{
Watermark watermark = new
Watermark(Image.GetInstance("watermark.jpg"), 200, 420);
document.Add(watermark);
}
catch
{

Console.Error.WriteLine("Are you sure you have


the file 'watermark.jpg' in the right path?");
}
// we Add a Header that will show up on PAGE 1
HeaderFooter header = new HeaderFooter(new
Phrase("This is a header"), false);
document.Header = header;
// we open the document
document.Open();
// we rotate the page, starting from PAGE 2
document.SetPageSize(PageSize.A4.Rotate());
// we need to change the position of the Watermark
try
{
Watermark watermark = new
Watermark(Image.GetInstance("watermark.jpg"), 320, 200);
document.Add(watermark);
}
catch
{
Console.Error.WriteLine("Are you sure you have
the file 'watermark.jpg' in the right path?");
}
// we Add a Footer that will show up on PAGE 2
HeaderFooter footer = new HeaderFooter(new
Phrase("This is page: "), true);
document.Footer = footer;
// step 4: we Add content to the document
// PAGE 1
document.Add(new Paragraph("Hello World"));
// we trigger a page break
document.NewPage();
// PAGE 2

// we Add some more content


document.Add(new Paragraph("Hello Earth"));
// we remove the header starting from PAGE 3
document.ResetHeader();
// we trigger a page break
document.NewPage();
// PAGE 3
// we Add some more content
document.Add(new Paragraph("Hello Sun"));
document.Add(new Paragraph("Remark: the header has
vanished!"));
// we reset the page numbering
document.ResetPageCount();
// we trigger a page break
document.NewPage();
// PAGE 4
// we Add some more content
document.Add(new Paragraph("Hello Moon"));
document.Add(new Paragraph("Remark: the pagenumber has
been reset!"));
}
catch(DocumentException de)
{
Console.Error.WriteLine(de.Message);
}
catch(IOException ioe)
{
Console.Error.WriteLine(ioe.Message);
}
// step 5: we close the document
document.Close();

}
}
}

Veremos como crear un reporte PDF con ITextSharp en C# sin el uso de tablas, esto
dejara el texto lineal y abra que ir acomodndolo. Para ello necesitamos importar la
librera de ItextSharp a nuestro proyecto, podemos descargarlo de la red o bien desde el
mismo vs a partir de la versin 2010 con el administrador de paquetes NuGet y luego
agregar la referencia con usingiTextSharp.text.
Primero empezamos declarando una variable de tipo document en el cual le agregamos el
tamao de nuestro documento en este caso es tipo carta, podemos elegir de otros tipos
como A4, oficio, etc.
Document doc = new Document(iTextSharp.text.PageSize.LETTER);
Definimos al autor y el tipo de palabras claves al igual que los margenes
doc.AddAuthor("Gustavo Ortiz Gamez");
doc.AddKeywords("pdf, PdfWriter; Documento; iTextSharp");
doc.SetMargins(10.0f, 10.0f, 10.0f, 10f);
Aqu ocupamos una variable de tipo string con la ruta y nombde del
archivo
string rut = @"C:\doc.pdf";
Procedemos a crear el documento en la ruta antes establecida
PdfWriter wri
= PdfWriter.GetInstance(doc, newFileStream(rut, FileMode.Create));
Abrimos el documento a ocupar
doc.Open();
Y empezamos a escribir nuestro texto para lo cual declaramos una variable
de tipo paragraph en la cual vamos a definir el formato de nuestro texto,
como alignment para definir la justificacion, Font para el tipo y tamaao
de letra, y con Add agregamos el texto que vamos a ocupar
Paragraph paragraph = new Paragraph();
paragraph.Alignment = Element.ALIGN_RIGHT;
paragraph.Font = FontFactory.GetFont("Arial", 9);
paragraph.Add("Esto es una prueba);
Y solo basta con agregar esta variable paragraph a nuestro documento.
Para continuar agregando texto es necesario ir agregando nuevos paragraph
doc.Add(paragraph);

Limpianos nuestro paragraph por si queremos definir otro tipo de formato


o tipo de letra
paragraph.Clear();
paragraph.Font = FontFactory.GetFont("Arial", 14,Font.BOLD);
paragraph.Add("Prueba PDF");
doc.Add(paragraph);
paragraph.Clear();
Para agregar saltos de linea solo basta con agregar \n a nuestro
documento
doc.Add(new Paragraph("\n"));

Podemos agregar imgenes a nuestro documento con la siguiente instruccion


iTextSharp.text.Image imgpfd =
iTextSharp.text.Image.GetInstance(@"C:\images\imgprueba.jpg");//Dirreccio
n a la imagen que se hace referencia
imgpfd.SetAbsolutePosition(50, 50); //Posicion en el eje carteciano
de X y Y
imgpfd.ScaleAbsolute(200, 200);//Ancho y altura de la imagen
doc.Add(imgpfd); // Agrega la imagen al documento

Una vez terminado de escribir nuestro documento procedemos a cerrar el


documento con:
doc.Close();
y con esto tendremos nuesotr documento en la ruta que definimos al
principio
Este es un pequeop tip para poder abrir nuestro documento desde la
pagina web donde nos dara la opcion de descargarlo
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;
filename=Nombrearchivo.pdf");
Response.ContentType = "application/pdf";
Response.TransmitFile(rut);
Response.End();

Con esto terminamos este pequeo tutorial, la continuacion de este es


como crear el reporte pero con una el uso de tablas, que a mi me a
funcionado mejor que estar escribiendo el texto plano.
Cualquier duda o comentario estoy a sus ordenes.

You might also like