Created
July 1, 2011 10:31
-
-
Save theresajayne/1058264 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* To change this template, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package uk.co.inbrand.fopengine; | |
import java.io.BufferedOutputStream; | |
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.io.OutputStream; | |
import java.io.StringReader; | |
import java.io.StringWriter; | |
import java.io.Writer; | |
import java.net.URL; | |
import java.util.logging.Level; | |
import javax.xml.parsers.SAXParser; | |
import javax.xml.transform.Result; | |
import javax.xml.transform.Source; | |
import javax.xml.transform.Transformer; | |
import javax.xml.transform.TransformerConfigurationException; | |
import javax.xml.transform.TransformerException; | |
import javax.xml.transform.TransformerFactory; | |
import javax.xml.transform.sax.SAXResult; | |
import javax.xml.transform.stream.StreamResult; | |
import javax.xml.transform.stream.StreamSource; | |
import org.apache.avalon.framework.configuration.Configuration; | |
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder; | |
import org.apache.fop.apps.FOPException; | |
import org.apache.fop.apps.FOUserAgent; | |
import org.apache.fop.apps.Fop; | |
import org.apache.fop.apps.FopFactory; | |
import org.apache.fop.apps.MimeConstants; | |
import org.apache.log4j.Logger; | |
import org.ccil.cowan.tagsoup.XMLWriter; | |
import org.ccil.cowan.tagsoup.jaxp.SAXFactoryImpl; | |
import org.xml.sax.InputSource; | |
import org.xml.sax.SAXException; | |
/** | |
* | |
* @author Theresa | |
*/ | |
public class FopEngine { | |
private String fontBaseURL; | |
private String hyphenationBaseURL; | |
private boolean strictValidation; | |
private int sourceResolution; | |
private String author = "InBrand Software"; | |
private static final FopFactory fopFactory = FopFactory.newInstance(); | |
private static final Logger LOGGER = Logger.getLogger(FopEngine.class); | |
static { | |
try { | |
LOGGER.warn("Before Instantiation"); | |
fopFactory.setUserConfig(new File("C:/InBrand/fopconfig.xml")); | |
fopFactory.setTargetResolution(300); | |
LOGGER.warn("After Instantiation"); | |
} catch (SAXException ex) { | |
LOGGER.fatal(ex); | |
} catch (IOException ex) { | |
LOGGER.fatal(ex); | |
} catch (Exception ex) { | |
LOGGER.fatal(ex); | |
} | |
} | |
public File generatePDFFromFO(File inputFO) throws ClassNotFoundException { | |
OutputStream ot = null; | |
BufferedOutputStream out = null; | |
File tempFile = null; | |
try { | |
tempFile = File.createTempFile("W2P", ".pdf"); | |
out = new BufferedOutputStream( new FileOutputStream(tempFile)); | |
fopFactory.setStrictValidation(false); | |
DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); | |
Configuration cfg = cfgBuilder.buildFromFile(new File("C:/InBrand/fopconfig.xml")); | |
fopFactory.setUserConfig(cfg); | |
FOUserAgent useragent= fopFactory.newFOUserAgent(); | |
useragent.setTargetResolution(300); | |
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF,useragent,out); | |
TransformerFactory factory = TransformerFactory.newInstance(); | |
Source src = new StreamSource(inputFO); | |
Transformer transformer = factory.newTransformer(); | |
Result res = new SAXResult(fop.getDefaultHandler()); | |
transformer.transform(src, res); | |
} catch (TransformerConfigurationException ex) { | |
LOGGER.error(ex.getMessage(), ex); | |
} catch (TransformerException ex) { | |
LOGGER.error(ex.getMessage(), ex); | |
} catch (FOPException ex) { | |
LOGGER.error(ex.getMessage(), ex); | |
} catch (FileNotFoundException ex) { | |
LOGGER.error(ex.getMessage(), ex); | |
} catch (IOException ex) { | |
java.util.logging.Logger.getLogger(FopEngine.class.getName()).log(Level.SEVERE, null, ex); | |
} catch (Exception ex) { | |
System.out.println(); | |
} finally { | |
try { | |
Thread.sleep(3000); | |
out.flush(); | |
out.close(); | |
} catch (InterruptedException ex) { | |
java.util.logging.Logger.getLogger(FopEngine.class.getName()).log(Level.SEVERE, null, ex); | |
} catch (IOException ex) { | |
java.util.logging.Logger.getLogger(FopEngine.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
} | |
return tempFile; | |
/* Old code recoded for new engine | |
//we should now have the XSL and the XML ready to transform into the FO file | |
try { | |
//First Get the config from the properties | |
CachedTypedProperties properties =CachedTypedProperties.getInstance("inbrand.properties"); | |
File userConfigFile = new File(properties.getStringProperty("FOPConfig")); | |
new Options(userConfigFile); | |
Configuration.put("target-resolution","300"); | |
Driver driver = new Driver(); | |
driver.setRenderer(Driver.RENDER_PDF); | |
driver.setInputSource(new InputSource(new FileInputStream(inputFO))); | |
tempFile = File.createTempFile("W2P", ".pdf"); | |
System.out.println("PDF FILE = "+tempFile.getAbsolutePath()); | |
FileOutputStream pdfOutput = new FileOutputStream(tempFile); | |
System.out.print("!"); | |
tempFile.deleteOnExit(); | |
System.out.print("!"); | |
driver.setOutputStream(pdfOutput); | |
System.out.println("Render!"); | |
driver.run(); | |
System.out.print("Render Done!"); | |
pdfOutput.close(); | |
} catch (IOException ex) { | |
java.util.logging.Logger.getLogger(FopEngine.class.getName()).log(Level.SEVERE, null, ex); | |
} catch (FOPException fope) { | |
LOGGER.error("Error in Fop Engine",fope); | |
} | |
return tempFile; */ | |
} | |
public File generatePDFFromXml(File xslFile,File xmlFile) { | |
BufferedOutputStream out = null; | |
File tempFile = null; | |
try { | |
fopFactory.setStrictValidation(false); | |
DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); | |
Configuration cfg = cfgBuilder.buildFromFile(new File("C:/InBrand/fopconfig.xml")); | |
fopFactory.setUserConfig(cfg); | |
tempFile = File.createTempFile("W2P", ".pdf"); | |
out = new BufferedOutputStream(new FileOutputStream(tempFile)); | |
FOUserAgent useragent= fopFactory.newFOUserAgent(); | |
useragent.setOutputFile(tempFile); | |
useragent.setTargetResolution(300); | |
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF,useragent,out); | |
TransformerFactory factory = TransformerFactory.newInstance(); | |
Source xslt = new StreamSource(xslFile); | |
Transformer transformer = factory.newTransformer(xslt); | |
Source src = new StreamSource(xmlFile); | |
Result res = new SAXResult(fop.getDefaultHandler()); | |
transformer.transform(src, res); | |
out.flush(); | |
out.close(); | |
System.out.println("Output File = "+tempFile.getAbsolutePath()); | |
} catch (TransformerConfigurationException ex) { | |
ex.printStackTrace(); | |
} catch (TransformerException ex) { | |
ex.printStackTrace(); | |
} catch (FOPException ex) { | |
ex.printStackTrace(); | |
} catch (FileNotFoundException ex) { | |
ex.printStackTrace(); | |
} catch (IOException ex) { | |
ex.printStackTrace(); | |
} catch (Exception ex) { | |
ex.printStackTrace(); | |
} catch (Throwable t) { | |
t.printStackTrace(); | |
} finally { | |
try { | |
System.out.print("*"); | |
out.close(); | |
} catch (IOException ex) { | |
} | |
} | |
return tempFile; | |
} | |
public File generateFOFromXml(File xslFile,File xmlFile){ | |
File tempout = null; | |
try { | |
TransformerFactory tFactory = TransformerFactory.newInstance(); | |
Transformer transformer = tFactory.newTransformer(new StreamSource(xslFile)); | |
tempout = File.createTempFile("tmp", ".fo"); | |
transformer.transform(new StreamSource(xmlFile), new StreamResult(new FileOutputStream(tempout))); | |
} catch (TransformerConfigurationException tce) { | |
LOGGER.error("Transformer Configuration Error",tce); | |
} catch (IOException ioe) { | |
LOGGER.error(ioe); | |
} catch (TransformerException te) { | |
LOGGER.error(te); | |
} | |
return tempout; | |
} | |
public String tagsoupFile(String url) { | |
String httpBody=""; | |
SAXParser sp; | |
String result = ""; | |
try { | |
byte[] httpContent = fetchPage(new URL(url)); | |
httpBody = extractBody(new String(httpContent)); | |
SAXFactoryImpl sf = new org.ccil.cowan.tagsoup.jaxp.SAXFactoryImpl(); | |
sf.setValidating(false); | |
sp = sf.newSAXParser(); | |
StringReader inputString = new StringReader(httpBody); | |
StringWriter output = new StringWriter(); | |
XMLWriter handler = new XMLWriter(sp.getXMLReader(),(Writer)output); | |
handler.parse(new InputSource(inputString)); | |
result = output.toString(); | |
} | |
catch(Exception ex) {} | |
return result; | |
} | |
public String getUrlAsFile(URL urlToGet) { | |
return null; | |
} | |
public byte[] fetchPage(URL requestedURL) { | |
byte[] buf = null; | |
StringBuffer temp = new StringBuffer(); | |
try { | |
BufferedReader brd = new BufferedReader(new InputStreamReader(requestedURL.openStream())); | |
String line = brd.readLine(); | |
while(line !=null) { | |
temp.append(line); | |
line = brd.readLine(); | |
} | |
buf = temp.toString().getBytes(); | |
//System.out.println("Retrieved for "+requestedURL.toString()+ " Got "+buf.length+ " Bytes"); | |
//System.out.println(new String(buf)); | |
//We now have the content of the XSL as a byte array we need to convert into an XSL document but first get the HTML and turn it into input XML. | |
} catch (IOException ioe) { | |
System.out.println(ioe.getMessage()); | |
ioe.printStackTrace(); | |
} | |
return buf; | |
} | |
private String extractBody(String inputString) { | |
//System.err.println("Pre Replace = "+inputString); | |
inputString.replaceAll("/[Bb][Oo][Dd][Yy]/","body"); | |
//System.err.println("Post Replace="+inputString); | |
int startPos = inputString.indexOf("<body"); | |
int endPos = inputString.indexOf("body>"); | |
if (startPos >= endPos) { | |
System.err.println("Startpos = "+String.valueOf(startPos)); | |
System.err.println("Endpos = "+String.valueOf(endPos)); | |
System.err.println("Not a Valid HTML document missing the <BODY> tag"); | |
} | |
return inputString.substring(startPos,endPos); | |
} | |
/** | |
* @return the fontBaseURL | |
*/ | |
public String getFontBaseURL() { | |
return fontBaseURL; | |
} | |
/** | |
* @return the hyphenationBaseURL | |
*/ | |
public String getHyphenationBaseURL() { | |
return hyphenationBaseURL; | |
} | |
/** | |
* @return the strictValidation | |
*/ | |
public boolean isStrictValidation() { | |
return strictValidation; | |
} | |
/** | |
* @return the sourceResolution | |
*/ | |
public int getSourceResolution() { | |
return sourceResolution; | |
} | |
/** | |
* @return the author | |
*/ | |
public String getAuthor() { | |
return author; | |
} | |
/** | |
* @param fontBaseURL the fontBaseURL to set | |
*/ | |
public void setFontBaseURL(String fontBaseURL) { | |
this.fontBaseURL = fontBaseURL; | |
} | |
/** | |
* @param hyphenationBaseURL the hyphenationBaseURL to set | |
*/ | |
public void setHyphenationBaseURL(String hyphenationBaseURL) { | |
this.hyphenationBaseURL = hyphenationBaseURL; | |
} | |
/** | |
* @param strictValidation the strictValidation to set | |
*/ | |
public void setStrictValidation(boolean strictValidation) { | |
this.strictValidation = strictValidation; | |
} | |
/** | |
* @param sourceResolution the sourceResolution to set | |
*/ | |
public void setSourceResolution(int sourceResolution) { | |
this.sourceResolution = sourceResolution; | |
} | |
/** | |
* @param author the author to set | |
*/ | |
public void setAuthor(String author) { | |
this.author = author; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment