2012-08-28 77 views
1

我想要使用Apache FOP來轉換XML文件爲PDF文件,但我只收到一個空白頁空白頁,這是我的代碼:XML到PDF使用FOP返回

protected byte[] buildPDF(byte[] xml) throws IOException { 
    FileOutputStream fos; 
    byte[] pdfBytes = null; 

    try{ 

     // Setup input and output files 
     File xmlfile = new File(MULTIMEDIA_PATH + File.separator + "xml/report.xml"); 
     File xsltfile = new File(MULTIMEDIA_PATH + File.separator + "xml/transformation.xsl"); 

     fos = new FileOutputStream(xmlfile); 
     fos.write(xml); 
     fos.close(); 

     // Step 1: Construct a FopFactory 
     FopFactory fopFactory = FopFactory.newInstance(); 
     FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); 

     // Step 2: Setup output stream 
     OutputStream out = new BufferedOutputStream(new FileOutputStream((MULTIMEDIA_PATH + File.separator + "xml/result.pdf"))); 

     try { 
      // Step 3: Construct FOP with desired output format 
      Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); 

      // Step 4: Setup JAXP using identity transformer 
      Source xslt = new StreamSource(xsltfile); 
      TransformerFactory factory = TransformerFactory.newInstance(); 
      Transformer transformer = factory.newTransformer(xslt); 

      // Step 5: Setup input and output for XSLT transformation 
      Source src = new StreamSource(xmlfile); 
      Result res = new SAXResult(fop.getDefaultHandler()); 

      // Step 6: Start XSLT transformation and FOP processing 
      transformer.transform(src, res); 

     } finally { 
      out.close(); 
     } 

    } catch (Exception e) { 
     e.printStackTrace(System.err); 
     System.exit(-1); 
    }  

    return pdfBytes; 

} 

你對這個問題有什麼想法?

謝謝!

回答

0

如果您收到空輸出,那麼我認爲你在最後像丟失:

pdfBytes = out.toByteArray(); 

如果您的輸出不爲空(如果你有以上),那麼你應該提供的內容transformation.xsl可能有問題。

+0

我out.pdf文件是一個空白頁面,但如果我使用氧氣進行轉換,所有工作正常。我認爲問題出在代碼中。 P.S. pdfBytes爲空,因爲首先我希望PDF生成工作正常。 –

+0

你有一些靜態文本或只有基於report.xml的動態? U是否使用與Oxygen相同的FOP版本(我不知道這個應用程序,只是讀它與在FOP內建)?也許你當地的FOP conf是不正確的?任何日誌輸出(警告,錯誤來自FOP)? –