the all purpose pdf generation class.
[mir.git] / source / mir / misc / PDFUtil.java
1 package mir.misc;
2
3 import java.io.*;
4 import javax.servlet.http.*;
5
6 import mircoders.global.*;
7
8 import org.apache.fop.apps.* ;
9 import org.xml.sax.InputSource;
10 import org.xml.sax.XMLReader;
11 import org.apache.log.*;
12
13 public class PDFUtil {
14     
15   public static void makePDF(String foFilePath,Object pdfDestination) throws Exception
16   {
17     try{
18       Driver driver = new Driver();
19       
20       //stupid logging that fop wants to use, needs to be changed
21       Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
22       Logger fopLog=null;
23       fopLog = hierarchy.getLoggerFor("fop");
24       fopLog.setPriority(Priority.WARN);
25       driver.setLogger(fopLog);
26       
27       driver.setRenderer(Driver.RENDER_PDF);
28   
29       File foFile=new File(foFilePath);
30       
31       String html2foStyleSheetPath=MirGlobal.getConfigProperty("Home") 
32           + MirGlobal.getConfigProperty("HTMLTemplateProcessor.Dir")
33           + "/" 
34           + MirGlobal.getConfigProperty("Producer.PrintableContent.html2foStyleSheetName"); 
35       File html2foStyleSheet=new File(html2foStyleSheetPath);
36       InputHandler inputHandler =
37           new XSLTInputHandler(foFile, html2foStyleSheet);
38       XMLReader parser = inputHandler.getParser();
39       
40       if (pdfDestination instanceof String) {
41         String filePath = (String) pdfDestination;
42         driver.setOutputStream(new FileOutputStream(filePath));
43         driver.render(parser, inputHandler.getInputSource());
44       }
45       else if (pdfDestination instanceof HttpServletResponse){
46         HttpServletResponse res = (HttpServletResponse) pdfDestination; 
47         ByteArrayOutputStream out = new ByteArrayOutputStream();
48         driver.setOutputStream(out);
49         res.setContentType("application/pdf");
50         
51         driver.render(parser, inputHandler.getInputSource());
52         
53         byte[] content = out.toByteArray();
54         res.setContentLength(content.length);
55         res.getOutputStream().write(content);
56         res.getOutputStream().flush();
57       }
58       else {
59         throw new Exception("I'm sorry but I don't know how to output a pdf to an object of type" + pdfDestination.getClass().getName());
60       }
61     }
62   
63     catch (Exception ex){
64         throw(ex);
65     }
66   }
67 }
68
69
70