I can not generate a pdf file

2

Personal how to generate PDF file using ITEXT with JSF. The problem is the following, when I ask to generate the PDF file in a class having only the MAIN method, it generates normally, but when I ask to generate the XHTML page by BUTTON it does not generate.

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.org/ui"
      xmlns:c="http://java.sun.com/jsp/jstl/core">

  <h:head>
     <title>Listar</title>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
      <link rel="stylesheet" type="text/css"  href="EstiloTabela.css"/>      
  </h:head>  
<h:body style="background-color:gray">  

<p:messages autoUpdate="true" errorStyle="color: red" 
infoStyle="color: green" layout="table" showSummary="true" showDetail="false" globalOnly="true"/> 

<center>
<h:form>                    
            <h:dataTable
                id="tableBem"
                value="#{BemBean.getList()}"
                var="bem"
                styleClass="order-table"
                headerClass="order-table-header"
                rowClasses="order-table-odd-row,order-table-even-row" border="4">

                <h:column>
                    <f:facet name="header">
                        <p>Codigo Bem</p>
                    </f:facet>
                    <p>#{bem.codigoBem}</p>
                </h:column>



                <h:column>
                    <f:facet name="header">
                        <p>nome</p>
                    </f:facet>
                    <p>#{bem.nome}</p>
                </h:column>



                <h:column>
                    <f:facet name="header">
                        <p>Codigo Fornecedor</p>
                    </f:facet>
                    <p>#{bem.codigoFornecedor}</p>
                </h:column>



                <h:column>
                    <f:facet name="header">
                        <p>Codigo Sala</p>
                    </f:facet>
                    <p>#{bem.codigoSala}</p>
                </h:column>



                <h:column>
                    <f:facet name="header">
                        <p>Codigo Marca</p>
                    </f:facet>
                    <p>#{bem.codigoMarca}</p>
                </h:column>
            </h:dataTable>     
            <h:commandButton  value="Relatorio" action="#{BemBean.gerarRelatorio()}"></h:commandButton>                                           
        </h:form>                       
        </center>
        </h:body>
        </html>




public void gerarRelatorio(){

        String url = "jdbc:postgresql://localhost:5432/ControlePatrimonio";
        String usuario = "postgres";
        String senha = "postgres";              
            try {
                Class.forName("org.postgresql.Driver");
                Connection con = DriverManager.getConnection(url, usuario, senha);
                Statement stmt = con.createStatement();
                ResultSet result = stmt.executeQuery("SELECT * FROM bem");  
                Document document = new Document();
                FileOutputStream fos = new FileOutputStream("RelatorioBem.pdf");    
                PrintWriter gravarArq = new PrintWriter(fos);
                PdfWriter.getInstance(document, fos);                   
                document.open();
                while(result.next()){

                    document.add(new Paragraph(Integer.toString(result.getInt("codigoBem")) + " " + result.getString("nome")));
                }       
                document.close();                   
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (DocumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 

}



package controle;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.LinkedList;
import java.util.TreeSet;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

import dominio.DAOBem;

@ManagedBean(name="BemBean")
@RequestScoped

public class Bem implements Comparable<Bem>{

    private int codigoBem;
    private String nome;
    private int codigoFornecedor;
    private int codigoSala;
    private int codigoMarca;
    private static Bem singleton;

    public Bem(){   

    }       

    public void gerarRelatorio(){

        DAOBem dao = DAOBem.getSingleton();
        dao.gerarRelatorio();
    }

    public TreeSet<Bem> consultaPorCodigo(){

        DAOBem dao = DAOBem.getSingleton();
        dao.setCodigo(this.codigoBem);
        dao.setCodigoFornecedor(this.codigoFornecedor);
        dao.setCodigoSala(this.codigoSala);
        dao.setCodigoMarca(this.codigoMarca);
        return dao.consultaPorCodigo();
    }

    public TreeSet<Bem> consultaPorNome(){

        DAOBem dao = DAOBem.getSingleton();     
        dao.setNome(this.nome);
        dao.setCodigoFornecedor(this.codigoFornecedor);
        dao.setCodigoSala(this.codigoSala);
        dao.setCodigoMarca(this.codigoMarca);
        return dao.consultaPorNome();
    }

    public TreeSet<Bem> consultaPorCodigo(int codigo){

        DAOBem dao = DAOBem.getSingleton();
        return dao.consultaPorCodigo();
    }

    public static TreeSet<String> getListNomeFornecedor(){

        DAOBem bem = DAOBem.getSingleton();
        return bem.getListNomeFornecedor();
    }

    public static TreeSet<String> getListNomeSala(){

        DAOBem bem = DAOBem.getSingleton();
        return bem.getListNomeSala();
    }

    public static TreeSet<String> getListNomeMarca(){

        DAOBem bem = DAOBem.getSingleton();
        return bem.getListNomeMarca();
    }

    public LinkedList<Bem> getList(){

        return DAOBem.getList();
    }

    public void alterar(int codigoBem,String nome,int codigoFornecedor,int codigoSala,int codigoMarca){

        DAOBem bem = DAOBem.getSingleton();
        bem.setCodigo(this.getCodigoBem());
        bem.setNome(this.getNome());
        bem.setCodigoFornecedor(this.getCodigoFornecedor());
        bem.setCodigoSala(this.getCodigoSala());
        bem.setCodigoMarca(this.getCodigoMarca());
        bem.alterar();
    }

    public void excluir(int codigoBem){

        DAOBem bem = DAOBem.getSingleton();
        bem.setCodigo(this.getCodigoBem());
        bem.excluir();
    }

    public void cadastrar(String nome,int codigoFornecedor,int codigoSala,int codigoMarca){

        DAOBem bem = DAOBem.getSingleton();     
        bem.setNome(this.getNome());
        bem.setCodigoFornecedor(this.getCodigoFornecedor());
        bem.setCodigoSala(this.getCodigoSala());
        bem.setCodigoMarca(this.getCodigoMarca());
        bem.cadastrar();            
    }

    public void setCodigoBem(int codigoBem){

        this.codigoBem = codigoBem;
    }

    public void setNome(String nome){

        this.nome = nome;
    }

    public void setCodigoFornecedor(int codigoFornecedor){

        this.codigoFornecedor = codigoFornecedor;
    }

    public void setcodigoSala(int codigoSala){

        this.codigoSala = codigoSala;
    }

    public void setCodigoMarca(int codigoMarca){

        this.codigoMarca = codigoMarca;
    }

    public int getCodigoBem(){      

        return this.codigoBem;
    }   

    public String getNome(){

        return this.nome;
    }

    public int getCodigoFornecedor(){

        return this.codigoFornecedor;
    }

    public int getCodigoSala(){

        return this.codigoSala;
    }

    public int getCodigoMarca(){

        return this.codigoMarca;
    }   

    public static Bem getSingleton(){

        if(singleton == null){

            singleton = new Bem();
        }
        return singleton;
    }

    @Override
    public int compareTo(Bem bem) {

        if(this.equals(bem)){

            return 0;
        }
        else{

            return 1;
        }
    }
}
    
asked by anonymous 27.11.2015 / 20:27

2 answers

0

I think you're missing the context , please adapt the example below.

Example:

public void createPDF() {
    log.debug("entered createPDF");
    FacesContext context = FacesContext.getCurrentInstance(); 
    HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();  
    response.setContentType("application/pdf");  
    response.setHeader("Content-disposition",  "inline=filename=file.pdf");
    try {

        // Get the text that will be added to the PDF
        String text = "test";
        // step 1
        Document document = new Document();
        // step 2
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        // step 3
        document.open();
        // step 4
        document.add(new Paragraph(text));
        // step 5
        document.close();

        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control",
            "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        // the contentlength
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        OutputStream os = response.getOutputStream();
        baos.writeTo(os);
        os.flush();
        os.close();
        log.debug("flushed and closed the outputstream");

    }
    catch(DocumentException e) {
        log.error("error: "+e);
    }
    catch (IOException e) {
        log.error("error: "+e);
    }
    catch (Exception ex) {
        log.debug("error: " + ex.getMessage());
    }
    context.responseComplete();
    log.debug("context.responseComplete()");
}

Sample source: link

    
28.11.2015 / 12:23
0

The problem was that I was generating the file privately. I switched to desktop and it worked

    
01.12.2015 / 17:22