【问题标题】:xml to pdf corrupted on war using strutsxml 到 pdf 在使用 struts 的战争中损坏
【发布时间】:2013-09-13 18:24:37
【问题描述】:

我正在开发一个 Web 应用程序,它应该创建 PDF 文件并在浏览器上显示它们。

我正在使用 Struts、Fop 和 Tomcat 服务器来执行此操作。

我的本地机器上一切正常,但在我创建 WAR 文件以放在 tomcat 服务器上后,创建的 PDF 总是损坏

对这里的问题有什么想法吗?他们都将不胜感激!

谢谢。

编辑:代码如下:

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;
}

和struts动作:

<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>

非常感谢任何帮助

【问题讨论】:

  • 你的问题是sad,因为它知道需要更多细节才能理解。通过添加信息和代码块使其快乐...
  • A 添加在浏览器上生成 pedf 文件的代码。我必须说这段代码在我的机器上工作,当我创建 WAR 文件时它停止工作
  • 您能否根据您的System.outs 指定文件损坏的位置? (还要注意out - baos 是多余的)
  • “文件损坏的地方”是什么意思?生成的pdf文件无法打开..我不知道是tomcat配置还是权限的问题..只有当我部署WAR文件时才会发生这种情况..system.outs如下:输入:XML( C:\home\miguel\PremoGeouFiles\PDF\XML\admin\Entidades\listaEntidades2013-09-23_161556.xml) 样式表:C:\Users\tviana\workspace\PremoGeou\FilesToPDF\templates\entidadesTemplate.xsl 输出:PDF (C :\home\miguel\PremoGeouFiles\PDF\PremoGeoU_Entidades.pdf)
  • 无法打开,因为它是零长度,因为里面有其他数据,什么?如果您在流程的每个步骤之后打印出状态怎么办?首先发现它为什么会破裂,然后在哪里

标签: java xml pdf struts2 apache-fop


【解决方案1】:

如果你关闭你的InputStream,Struts 将永远无法通过Stream Result 获得它:)

删除inputStream.close();;它会起作用的。

P.S:注意in your own other question,你做对了! O_o

【讨论】:

  • 我会尝试并会说些什么。在那个问题中,我试图在本地进行.. nw 问题是当我将应用程序放在 tomcat 上时,发现了一个 WAR 文件
  • 相信我,就是这样。 Struts 读取 inputStream 然后关闭它。如果您之前关闭它,Struts 就没有更多可阅读的内容了。
  • 遗憾的是,这不是解决方案..没有 inputStream.close();工作方式相同,在本地工作,当创建 WAR 并部署 pdf 文件时无法打开,它的大小只有 15 个字节(当它被认为是 7kbytes 时)
  • 那么还有更多个问题。但 0 尺寸的问题就是这样。
  • 我得出一个结论,问题是当 pdf 文件中包含 ´`~^ 之类的字符时。有什么想法可以解决吗?是tomcat配置问题?
【解决方案2】:

得到了解决方案,是一个 tomcat 配置问题,我可以借助另一个 stackoverflow 问题来解决:

Change Tomcat's Charset.defaultCharset in windows

@Andrea Ligios 非常感谢您的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 2017-06-29
    • 2014-03-24
    • 2019-06-26
    相关资源
    最近更新 更多