我正在开发一个 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>
任何帮助都会非常感激