Question

I'm developing a web application that should create PDF files and show them on the browser.

I'm using Struts, Fop and a Tomcat Server to do that.

On my local machine everything works fine but after I create a WAR file to put on a tomcat server the PDF created is always corrupted.

Any ideas of what's the issue here? All of them would be very appreciated!

Thanks.

EDIT: the code is the following:

private InputStream inputStream;

public InputStream getInputStream() {
    return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}

public List<Entidade> obterValores(String idsString){
//      String idsString = getIdsToPdf();

    List<Entidade> temp = new ArrayList<Entidade>();

    if( idsString != null && !idsString.isEmpty()){

        idsString.replaceAll("\\s", "");

        for (String idEntidade : idsString.split(",")) {

                       temp.add(entidadeService.getEntidade(Long.parseLong(idEntidade)));

        }
//          setListaEntidades(temp);            
    }
    return temp;
}

public File criarXML(List<Entidade> listaEntidades, File baseDir) throws IOException{

//      File baseDir = new File("./FilesToPDF");
//        File outDir = new File(baseDir, "out");
//        outDir.mkdirs();
//      if(!baseDir.exists()){
//          baseDir.mkdir();
//      }

    ResourceBundle bundle = ResourceBundle.getBundle("global", getLocale());

    Date sysdate = new Date();
    SimpleDateFormat data = new SimpleDateFormat("yyyy-MM-dd_HHmmss");

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String user = ((CustomUserDetails) auth.getPrincipal()).getNome();
    String entidadeLogada = ((CustomUserDetails) auth.getPrincipal()).getEntidade();
    String auxiliar;

    File xmlfile = new File(baseDir,"/listaEntidades"+data.format(sysdate)+".xml");
    FileWriter writer = new FileWriter(xmlfile, false);
    PrintWriter out = new PrintWriter(writer);
    System.out.println(xmlfile.getAbsolutePath());
    data = new SimpleDateFormat("HH:mm   dd-MM-yyyy");
    out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    out.println("<entidades>");
    out.println("\t<titulo>"+bundle.getString("pdf.listaEntidades")+"</titulo>");

    out.println("\t<user>"+user+"</user>");
    out.println("\t<entidadeLogada>"+entidadeLogada+"</entidadeLogada>");
    out.println("\t<dataHora>"+data.format(sysdate)+"</dataHora>");

    out.println("\t<criteriosPesquisa>"+bundle.getString("pdf.criteriosPesquisa")+"</criteriosPesquisa>");
    out.println("\t<labelNomeEntidade>"+bundle.getString("label.nomeEntidade")+"</labelNomeEntidade>");
    out.println("\t<searchNome>"+getSearchingEntityNamePdf()+"</searchNome>");
    out.println("\t<labelTipo>"+bundle.getString("label.tipo")+"</labelTipo>");
    auxiliar = Long.parseLong(getSearchingTypePdf())!=0 ? entidadeService.getTipo(Long.parseLong(getSearchingTypePdf())).getDesignacao() : "";
    out.println("\t<searchTipo>"+auxiliar+"</searchTipo>");
    out.println("\t<labelNif>"+bundle.getString("label.nif")+"</labelNif>");
    out.println("\t<searchNif>"+getSearchingNIFPdf()+"</searchNif>");
    out.println("\t<labelLocalidade>"+bundle.getString("label.localidade")+"</labelLocalidade>");
    out.println("\t<searchLocalidade>"+getSearchingLocalidadePdf()+"</searchLocalidade>");
    out.println("\t<labelMinhas>"+bundle.getString("label.mostrarMinhasEntidades")+"</labelMinhas>");
    auxiliar = Boolean.parseBoolean(getShowMyEntitiesPdf()) ? bundle.getString("pdf.sim") : bundle.getString("pdf.nao");
    out.println("\t<searchMinhas>"+auxiliar+"</searchMinhas>");
    out.println("\t<labelInativos>"+bundle.getString("label.mostraInativos")+"</labelInativos>");
    auxiliar = Boolean.parseBoolean(getShowDisabledItemsPdf()) ? bundle.getString("pdf.sim") : bundle.getString("pdf.nao");
    out.println("\t<searchInativos>"+auxiliar+"</searchInativos>");

    out.println("\t<headerEstado>"+bundle.getString("tabela.estado")+"</headerEstado>");
    out.println("\t<headerNome>"+bundle.getString("tabela.nomeEntidade")+"</headerNome>");
    out.println("\t<headerNif>"+bundle.getString("tabela.nif")+"</headerNif>");
    out.println("\t<headerTipo>"+bundle.getString("tabela.tipo")+"</headerTipo>");
    out.println("\t<headerLocalidade>"+bundle.getString("tabela.localidade")+"</headerLocalidade>");
    for(Entidade entidade : listaEntidades){
        out.println("\t<entidade>");
        if(!entidade.isRemovido()){
            out.println("\t\t<estado>0</estado>");
        }else{
            out.println("\t\t<estado>1</estado>");
        }
        out.println("\t\t<nome>"+entidade.getNome()+"</nome>");
        out.println("\t\t<nif>"+entidade.getNif()+"</nif>");
        out.println("\t\t<tipo>"+entidade.getTipo().getDesignacao()+"</tipo>");
        out.println("\t\t<localidade>"+entidade.getMorada().getLocalidade()+"</localidade>");
        out.println("\t</entidade>");
    }
    out.println("</entidades>");
    out.close();
    writer.close();


    return xmlfile;

}

@SuppressWarnings("deprecation")
public String xmlToPdf() {

//      HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get( ServletActionContext.HTTP_REQUEST);
//      String idsString= request.getParameter("idsToPdf");


    try {
//            System.out.println("FOP ExampleXML2PDF\n");
        System.out.println("Preparing...");


        // Setup directories
//            File baseDir = new File("./FilesToPDF");
//            File outDir = new File(baseDir, "out");
//            outDir.mkdirs();
        String relativePath = "/PremoGeouFiles/PDF/";

        Properties properties = new Properties(); 
        properties.load(getClass().getClassLoader().getResourceAsStream("/conf/context/config.properties"));
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        File baseDir = new File(properties.getProperty("file.directory") + relativePath+"XML/"+((CustomUserDetails) auth.getPrincipal()).getUsername()+"/Entidades");
//          File templateDir = new File("../FilesToPdf");
//          System.out.println(templateDir.getAbsolutePath());
        if (!baseDir.exists()){
            baseDir.mkdirs();
        }
        // Setup input and output files
        File xmlfile = criarXML(obterValores(getIdsToPdf()), baseDir);
        LOG.info("criado ficheiro xml com valores em: "+xmlfile.getAbsolutePath());
        File xsltfile = new File(new File(properties.getProperty("file.pdf_template_directory")), "entidadesTemplate.xsl");
        LOG.info("carregado ficheiro xsl localizado em: "+xsltfile.getAbsolutePath());
        File pdffile = new File(new File(properties.getProperty("file.directory") + relativePath), "PremoGeoU_Entidades.pdf");
        LOG.info("criado ficheiro pdf em: "+pdffile.getAbsolutePath());

        System.out.println("Input: XML (" + xmlfile.getAbsolutePath() + ")");
        System.out.println("Stylesheet: " + xsltfile.getAbsolutePath());
        System.out.println("Output: PDF (" + pdffile.getAbsolutePath() + ")");
        System.out.println();
        System.out.println("Transforming...");

        final FopFactory fopFactory = FopFactory.newInstance();

        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        TransformerFactory tFactory = TransformerFactory.newInstance();

        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF,foUserAgent, out);
        //Setup input
        Source src = new StreamSource(xmlfile);
        //Setup Transformer
        Source xsltSrc = new StreamSource(xsltfile);
        Transformer transformer = tFactory.newTransformer(xsltSrc);
        foUserAgent.setBaseURL(xsltfile.getParentFile().toURL().toExternalForm());
        //Make sure the XSL transformation's result is piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());
        transformer.transform(src, res);

        ByteArrayOutputStream baos = out;
        inputStream = new ByteArrayInputStream(baos.toByteArray());
        System.out.println("Success!");
        inputStream.close();
        out.close();
        baos.close();


       /* OutputStream out = new BufferedOutputStream(new FileOutputStream(pdffile)); 
        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
                Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out); 

                TransformerFactory factory = TransformerFactory.newInstance(); 
                Transformer transformer = factory.newTransformer(new StreamSource(xsltfile)); 

                foUserAgent.setBaseURL(xsltfile.getParentFile().toURL().toExternalForm());
                Source xml = new StreamSource(xmlfile); 

                Result res = new SAXResult(fop.getDefaultHandler()); 
                transformer.transform(xml, res); 

//                  ByteArrayOutputStream baos = out.;
//                  inputStream = new ByteArrayInputStream(baos.toByteArray());
//                  System.out.println("Success!");
//                  inputStream.close();
        out.close();    */




    } catch (Exception e) {
        e.printStackTrace(System.err);
        LOG.error("Erro a criar pdf: "+e.getMessage(), e);
//            System.exit(-1);
//          return ERROR;
    }

    return SUCCESS;
}

and the struts action:

<action name="printEntidadesList" class="com.sinfic.premogeou.actions.EntidadeAction"  method="xmlToPdf">
            <result type="stream" name="success">
                <param name="contentType">application/pdf</param>
                <param name="inputName">inputStream</param>
                <param name="contentDisposition">filename="PremoGeoU_Entidades.pdf"</param>
                <param name="bufferSize">1024</param>
            </result>
            <interceptor-ref name="defaultStack"/>
        </action>

Any help would be very apreciated

Was it helpful?

Solution 2

Got the solution, was a tomcat configuration issue that I could resolve with the help of another stackoverflow question:

Change Tomcat's Charset.defaultCharset in windows

@Andrea Ligios thank you very much for the help!

OTHER TIPS

If you close your InputStream, Struts will never be able to get it with the Stream Result :)

Remove inputStream.close();; it will work.

P.S: note that in your own other question, you was doing it right! O_o

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top