package com.netflox.pdf;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
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.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.netflox.dao.MysqlGestionVente;
import com.sun.xml.internal.bind.v2.runtime.output.XmlOutput;
public class pdfCreator {
private static final String EXTENSION = ".pdf";
private String TEMPLATE_LIST_URL = "template.xsl";
private String TEMPLATE_MOVIE_URL = "oneMovieTemplate.xsl";
private String TEMPLATE_AUDIT_URL = "auditTemplate.xsl";
private String MOVIES_FILE = "movies.xml";
private String MOVIES_PDF = "movies_output";
private String AUDIT_PDF = "audit_output";
private String XML_TMP = "xml_tmp.xml";
/**
* create pdf from an xml
* @param templatePath
* @param templateName xslt file
* @param outputPath
* @param xmlBDD xml file
* @param outPdfName name of pdf output file to be created
*/
private void createApplayXslAndCreatePdf(String templatePath,
String templateName, String outputPath,String xmlBDD, String outPdfName ) {
try {
URL url;
url = new File(templatePath + File.separator + templateName)
.toURI().toURL();
// creation of transform source
StreamSource transformSource = new StreamSource(url.openStream());
// create an instance of fop factory
FopFactory fopFactory = FopFactory.newInstance();
// a user agent is needed for transformation
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
// to store output
ByteArrayOutputStream pdfoutStream = new ByteArrayOutputStream();
File fXmlFile = new File(templatePath + File.separator
+ xmlBDD);
StreamSource source = new StreamSource(fXmlFile);
Transformer xslfoTransformer;
TransformerFactory transfact = TransformerFactory.newInstance();
xslfoTransformer = transfact.newTransformer(transformSource);
// Construct fop with desired output format
Fop fop;
// System.out.println("Begin fop"+templatePath +File.separator+
// MOVIES_FILE);
// System.out.println(templatePath );
try {
fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent,
pdfoutStream);
// Resulting SAX events (the generated FO)
// must be piped through to FOP
Result res = new SAXResult(fop.getDefaultHandler());
System.out.println("Begin trans ");
// Start XSLT transformation and FOP processing
try {
// everything will happen here..
xslfoTransformer.transform(source, res);
System.out.println("ecriture ");
// if you want to save PDF file use the following code
System.out.println("création du fichier ");
File file = new File(outputPath + File.separator
+ outPdfName + EXTENSION);
System.out.println("création du buffer");
OutputStream out = new FileOutputStream(file);
out = new BufferedOutputStream(out);
FileOutputStream str = new FileOutputStream(file);
str.write(pdfoutStream.toByteArray());
str.close();
out.close();
System.out.println("fin");
} catch (TransformerException e) {
e.printStackTrace();
}
} catch (FOPException e) {
e.printStackTrace();
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (TransformerConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
/**
* create a pdf of list of movies
*
* @param templatePath
* @param outputPath
*/
public void createMoviesPdf(String templatePath, String outputPath) {
createApplayXslAndCreatePdf(templatePath, TEMPLATE_LIST_URL, outputPath, MOVIES_FILE, MOVIES_PDF);
}
/**
* make the template adapted to the movie
*
* @param movieName
* movie name
*/
private void updateXslTemplateMovieName(String templatePath,
String movieName) {
// todo : add somthing to modify the xslt from the code to ajust on the
// name
try {
DocumentBuilderFactory fabrique = DocumentBuilderFactory
.newInstance();
DocumentBuilder constructeur = fabrique.newDocumentBuilder();
File xml = new File(templatePath + File.separator
+ TEMPLATE_MOVIE_URL);
Document document = constructeur.parse(xml);
Element racine = document.getDocumentElement();
String tag = "xsl:apply-templates";
NodeList liste = racine.getElementsByTagName(tag);
for (int i = 0; i < liste.getLength(); i++) {
Element e = (Element) liste.item(i);
if (e.hasAttribute("select")) {
String s = e.getAttribute("select");
System.out.println(" Attribute :" + s);
String replacement = "//movie[title='" + movieName + "']";
e.removeAttribute("select");
s = e.getAttribute("select");
System.out.println(" Attribute :" + s);
e.setAttribute("select", replacement);
s = e.getAttribute("select");
System.out.println(" Attribute :" + s);
}
}
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new FileOutputStream(xml));
transformer.transform(source, result);
} catch (Exception ignore) {
// ignore.printStackTrace();
}
}
/**
* create a pdf file with all the information acording to a movie
*
* @param templatePath
* @param outputPath
* @param movieName
*/
public void createMoviePdfSummary(String templatePath, String outputPath,
String movieName) {
updateXslTemplateMovieName(templatePath, movieName);
createApplayXslAndCreatePdf(templatePath, TEMPLATE_MOVIE_URL,
outputPath, MOVIES_FILE, MOVIES_PDF);
}
/**
* adding a list of films to the document
* @param liste of films
* @param type
* @param document
*/
private void addFromArrayListToDOMElement(ArrayList<String> liste,String type, Document document){
// not empty
if(liste.size() > 0){
//get the document root
Element root = document.getDocumentElement();
//create a new element for all the movies in this category
Element midRoot = document.createElement("table");
midRoot.setAttribute("id", type);
//loading data from the list
// count occurences for each movie
HashMap<String, Integer> moviesOcc = new HashMap<String, Integer>();
for(String film:liste){
Integer val = moviesOcc.get(film);
if(val != null){
moviesOcc.put(film, val+1);
}else{
moviesOcc.put(film, 1);
}
}
// create and load elements
for(Entry<String, Integer> el:moviesOcc.entrySet()){
Element e = document.createElement("film");
Element ef = document.createElement("name");
ef.setTextContent(el.getKey());
Element eo = document.createElement("nombre");
eo.setTextContent(el.getValue().toString());
e.appendChild(ef);
e.appendChild(eo);
midRoot.appendChild(e);
}
//adding to the root
root.appendChild(midRoot);
}
}
/**
* create a tomporary xml file from the data base to use as a support for creating the audit.pdf
* @param outPath
*/
private void createXmlTmpFile(String outPath){
//data recuperator
MysqlGestionVente mgv = new MysqlGestionVente();
//getting the data from dbb
ArrayList<String> vente = mgv.filmsInfosVenteLoueBon("A");
ArrayList<String> location = mgv.filmsInfosVenteLoueBon("L");
ArrayList<String> bon = mgv.filmsInfosVenteLoueBon("B");
System.out.println(vente.size());
//create temp xml file
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder;
docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("audit");
doc.appendChild(rootElement);
addFromArrayListToDOMElement(vente,"vente",doc);
addFromArrayListToDOMElement(location,"location",doc);
addFromArrayListToDOMElement(bon,"bon",doc);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(outPath+File.separator+XML_TMP));
transformer.transform(source, result);
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* create a pdf audit
* @param templatePath
* @param outputPath
*/
public void createAuditPdf(String templatePath, String outputPath){
createXmlTmpFile(templatePath);
createApplayXslAndCreatePdf(templatePath, TEMPLATE_AUDIT_URL, outputPath, XML_TMP, AUDIT_PDF);
File file = new File(templatePath+File.separator+XML_TMP);
file.delete();
}
public static void main(String[] args) {
System.out.println("Hello !");
String path = "C:/Users/Nassim/workspace/XPI_Netflox/WebContent/res/data";
pdfCreator p = new pdfCreator();
//p.createMoviesPdf(path, path);
p.createMoviePdfSummary(path, path, "The Shawshank Redemption");
//p.createAuditPdf(path, path);
System.out.println("Tada ");
}
}