martes, 18 de noviembre de 2014

crear PDF básico- Instalar librería

Librería iText: Descargar
o también se puede descargar de:

http://itextpdf.com/download.phphttp://sourceforge.net/projects/itext/files/

----------------------------------------------------------------
Código básico:

<%@page import="java.io.*, com.itextpdf.text.*, com.itextpdf.text.pdf.*"%>
<%
    response.setContentType( "application/pdf" );
    // Paso 1:
    Document documento = new Document();
    // Paso 2:
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    PdfWriter.getInstance( documento, buffer );
    // Paso 3:
    documento.open();
    // Paso 4:
    documento.add(new Paragraph("Hola mundo"));
    // Paso 5:
    documento.close();
    // se escribe la salida
    DataOutput output = new DataOutputStream( response.getOutputStream() );
    byte[] bytes = buffer.toByteArray();
    response.setContentLength(bytes.length);
 
    for( int i = 0; i < bytes.length; i++ ) {
            output.writeByte( bytes[i] );
    }
%>

----------------------------------------------------------
Repetimos lo mismo pero ahora con una tabla

<%@
page import="java.servlet.*,
        javax.servlet.http.*,
        java.io.*,
        java.util.*,
        com.itextpdf.text.pdf.*,
        com.itextpdf.text.*,java.sql.*"
%>

<%
response.setContentType("application/pdf");
Document document = new Document();
try{
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, buffer);
    document.open();


    PdfPTable table = new PdfPTable(2);
    table.addCell("1");
    table.addCell("2");
    table.addCell("3");
    table.addCell("4");
    table.addCell("5");
    table.addCell("6");      
  
    document.add(table);      
    document.close();
  
    DataOutput dataOutput = new DataOutputStream(response.getOutputStream());
    byte[] bytes = buffer.toByteArray();
    response.setContentLength(bytes.length);
    for(int i = 0; i < bytes.length; i++)
    {
        dataOutput.writeByte(bytes[i]);
    }
  
}catch(DocumentException e){
    e.printStackTrace();
}
%>

No hay comentarios:

Publicar un comentario