OVH Cloud OVH Cloud

publipostage

6 réponses
Avatar
LR
Salut,

Je suis en train de développer une application J2EE de gestion qui devra
permettre à l'utilisateurs d'imprimer des états (fiches de paies, factures)
et des courriers (publipostage).

Pourriez-vous me conseiller un moyen pour gérer correctement ces impressions
? Les utilisateurs se serviront vraisemblablement tous du navigateur Mozilla
Firefox et j'ai pour l'instant pensé à trois solutions :

- générer les impressions au pixel près au format html et laisser à
l'utilisateur le soin d'utiliser la fonctionnalité d'impression de son
navigateur
- générer un document pdf
- générer un document word

La première solution me permet quelque peu hasardeuse, surtout quant à la
précision et à la qualité de l'impression.

La deuxième solution est utilisée par l'administration de mon canton dans le
logiciel de saisie des impôts pour imprimer la déclaration. Je trouve que
c'est une excellente solution mais elle m'inquiète techniquement.

La troisième solution m'inquiète techniquement également.

Merci d'avance pour vos retours d'expérience, conseils et références
techniques.

Lilian

6 réponses

Avatar
Gaetan Zoritchak
Jette un coup d'oeil à http://jasperreports.sourceforge.net/

Cela te permet de générer des rapports en PDF. C'est basé sur des
template que tu "remplis" ensuite avec tes données. Il existe plusieurs
outils GUI te permettant de générer ces templates.

Je trouve que c'est plus pratique à utiliser que XSL-FO mais ça ne
respecte pas de norme.

--
Gaetan Zoritchak
Gestion de bug en mode ASP sous java
http://eap.bug-sweeper.fr
Avatar
Lionel
Gaetan Zoritchak wrote:
Je trouve que c'est plus pratique à utiliser que XSL-FO mais ça ne
respecte pas de norme.


Depuis word 2003 on peut mettre un document word au format XSL-FO (n'ayant
pas word 2003, je n'ai pas encore essayé)
http://msdn.microsoft.com/office/default.aspx?pull=/library/en-us/odc_wd2003_ta/html/OfficeWordWordMLtoXSL-FO.asp&print=true

Avatar
barilla
perso, j'ai choisi d'ecrire du docbook (a l'aide de org.jdom)
le docbook on peut pas faire plus simple (genre html 2.0).
de transformer le docbook en xsl-fo par les feuilles xslt qui existent.
ensuite le fo est soit :
- affiche a l'ecran
- transforme en pdf
- transforme en html 3.2
...

voici ce que j'ai ecrit, la seule chose a changer est l'appel a
limsPreferencesFacade, et l'appel a la feuille xsl est chez moi :
/usr/share/xml/docbook/stylesheet/nwalsh/current/fo/docbook.xsl

note : ca gere aussi les codes barres avec chrysalis.
un petit truc fatiguant c'est le lien entre les fichiers generes :
un fichier html (ou plusieurs), les images ...
il faut donc faire des liens relatifs.
par contre pour faire le pdf (ou tout est dedans), il faut des liens
relatif. le but de code qui gere les codes barres gere ce probleme.


extrait 1 : comment l'utiliser
extrait 2 : la classe utile "DocbookContents"
extrait 3 : exemple pour transferer le fichier zip contenant les
pages web/images crees vers le client. (ejb session)
extrait 4 : afficher le contenu du zip dans un panel. (client swing)
extrait 5 : le jarressourcefinder utilise dans l'extrait 4.

-------------
DocbookContents db = new DocbookContents(limsPreferencesFacade,
"test", "TechReport");
String file = "";
try {

db.addArticleInfo("barcodeici", "Titre ici",
"Ceci est le sous titre ... un peu plus long peut etre",
"prenom", "nom", new Date(), false);

db.addPara("Ceci est un test Ceci est un test Ceci est un
test Ceci est un test Ceci est un test");
db.addContent(db.createBarcodeElement("tititoto"));
db.addPara("Ceci est un test Ceci est un test Ceci
est un test Ceci est un test Ceci est un test");

Vector headers = new Vector();
headers.add("A");
headers.add("B");
headers.add("C");
headers.add("D");
headers.add("E");
Vector line = new Vector();
line.add("col A");
line.add("col B");
line.add("c");
line.add("col D");
line.add("col E");
Vector lines = new Vector();
lines.add(line);
lines.add(line);
lines.add(line);
db.addTable("Test de table.", headers, lines, headers);
db.addPara("ceci est un paragraphe");

// go
String docbook2foXslFile = limsPreferencesFacade.getProperty(
"docbook.foXslFile", "");
file = db.createAllFiles(docbook2foXslFile).toString();
if (limsPreferencesFacade.getProperty("print.allow", "true")
.toString().equals("true") && print) {
db.printPdfFile();
} else {
System.out.println("printing disabled !");
}
} catch (Exception e) {
System.out.println("Error creating and printing PDF : " + e);
e.printStackTrace();
}

-------------
package com.integragen.lims.utils.docbook;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
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.logger.ConsoleLogger;
import org.apache.fop.apps.Driver;
import org.jdom.Content;
import org.jdom.DocType;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;

import com.integragen.lims.ejb.main.LimsPreferencesFacade;
import com.integragen.lims.utils.file.FileIO;

public class DocbookContents {

Document doc;

Element articleElement;

File parentDirectory;

File docbookRootDirectory;

File filesDirectory;

File docbookTmpFile;

File foRootDirectory;

File foTmpFile;

File htmlRootDirectory;

File htmlTmpFile;

File pdfRootDirectory;

File pdfTmpFile;

File zipDirectory;

File zipTmpFile;

String logoFilename;

String docbookRoot;

String fileSep;

String orientation = "portrait";

LimsPreferencesFacade limsPreferencesFacade;

public DocbookContents(LimsPreferencesFacade limsPreferencesFacade,
String id, String articleClass) throws Exception {
this.limsPreferencesFacade = limsPreferencesFacade;
fileSep = System.getProperty("file.separator");
docbookRoot = limsPreferencesFacade.getProperty("docbook.rootdir", "");
logoFilename = limsPreferencesFacade
.getProperty("docbook.logofile", "");

DocType docType = new DocType("article",
"-//OASIS//DTD DocBook XML V4.3//EN",
"../../docbook/docbookx.dtd");
articleElement = new Element("article");
articleElement.setAttribute("id", id);
articleElement.setAttribute("Class", articleClass);
doc = new Document(articleElement, docType);

File rootDirectory = new File(docbookRoot);
if (!rootDirectory.exists()) {
rootDirectory.mkdir();
}
File parentDirectoryFile = File.createTempFile("lock_", "",
rootDirectory);
parentDirectory = new File(parentDirectoryFile.getPath() + "_dir");
parentDirectory.mkdirs();
docbookRootDirectory = new File(parentDirectory.getPath() + fileSep
+ "docbook");
docbookRootDirectory.mkdir();
filesDirectory = new File(parentDirectory.getPath() + fileSep + "files");
filesDirectory.mkdir();
foRootDirectory = new File(parentDirectory.getPath() + fileSep + "fo");
foRootDirectory.mkdir();
htmlRootDirectory = new File(parentDirectory.getPath() + fileSep
+ "html");
htmlRootDirectory.mkdir();
pdfRootDirectory = new File(parentDirectory.getPath() + fileSep + "pdf");
pdfRootDirectory.mkdir();
zipDirectory = new File(parentDirectory.getPath() + fileSep + "zip");
zipDirectory.mkdir();
}

public String getParentDirectory() {
return parentDirectory.getPath();
}

public void addArticleInfo(String barcode, String titleText,
String subtitleText, String authorFirstName, String authorLastName,
Date creationDate, boolean showBarcode) throws Exception {

Element articleInfo = new Element("articleinfo");

// title
Element title = new Element("title");
title.setText(titleText);
articleInfo.addContent(title);

// subtitle
Element subtitle = new Element("subtitle");
subtitle.setText(creationDate + ", [ " + barcode + " ], "
+ subtitleText);
articleInfo.addContent(subtitle);

// date
Element date = new Element("date");
date.setText(creationDate.toString());
articleInfo.addContent(date);

// author
Element author = new Element("author");
Element firstName = new Element("firstname");
firstName.setText(authorFirstName);
author.addContent(firstName);
Element surName = new Element("surname");
surName.setText(authorLastName);
author.addContent(surName);
articleInfo.addContent(author);
// Element authorgroup = new Element("authorgroup");
// authorgroup.addContent(author);
// articleInfo.addContent(authorgroup);

Vector items = new Vector();

// logo
// copy logo file
File logoNewFile = new File(filesDirectory + fileSep
+ new File(logoFilename).getName());
logoNewFile.createNewFile();
FileIO.copyFile(logoFilename, logoNewFile.getPath());
// add in docbook
Element mediaobjectElement = new Element("mediaobject");
// for html
Element imageobjectElement = new Element("imageobject");
Element imagedataElement = new Element("imagedata");
imageobjectElement.setAttribute("role", "html");
imagedataElement.setAttribute("format", "JPEG");
imagedataElement.setAttribute("width", "5cm");
imagedataElement.setAttribute("fileref", logoNewFile.getName());
imageobjectElement.addContent(imagedataElement);
mediaobjectElement.addContent(imageobjectElement);
// and for pdf
imageobjectElement = new Element("imageobject");
imageobjectElement.setAttribute("role", "fo");
imagedataElement = new Element("imagedata");
imagedataElement.setAttribute("format", "JPEG");
imagedataElement.setAttribute("width", "5cm");
imagedataElement.setAttribute("fileref", logoNewFile.getPath());
imageobjectElement.addContent(imagedataElement);
mediaobjectElement.addContent(imageobjectElement);

items.add(mediaobjectElement);

// barcode
items.add(createBarcodeElement(barcode));

// table
Element table = new Element("table");
table.setAttribute("frame", "none");
table.setAttribute("tocentry", "0");
// table title
Element tabletitle = new Element("title");
tabletitle.setText("DocId");
table.addContent(tabletitle);

Element tgroup = new Element("tgroup");
tgroup.setAttribute("align", "center");
tgroup.setAttribute("cols", "2");
Element tbody = new Element("tbody");
tbody.addContent(getRow(items));
tgroup.addContent(tbody);
table.addContent(tgroup);

// add
articleElement.addContent(articleInfo);
if (showBarcode) {
articleElement.addContent(table);
}
}

public void addPara(String text) {
Element para = new Element("para");
para.setText(text);
articleElement.addContent(para);
}

public void addTable(String title, Vector headers, Vector lines,
Vector footers) {
// table
Element table = new Element("table");
table.setAttribute("frame", "all");

// title
Element tabletitle = new Element("title");
tabletitle.setText(title);
table.addContent(tabletitle);

// tgroup
Element tgroup = new Element("tgroup");
tgroup.setAttribute("align", "center");
tgroup.setAttribute("cols", headers.size() + "");

// header
Element thead = new Element("thead");
thead.addContent(getRow(headers));
tgroup.addContent(thead);

// body
Element tbody = new Element("tbody");
for (int i = 0; i < lines.size(); i++) {
tbody.addContent(getRow((Vector) lines.elementAt(i)));
}
tgroup.addContent(tbody);

// footer
if (footers != null) {
Element tfoot = new Element("tfoot");
tfoot.addContent(getRow(footers));
tgroup.addContent(tfoot);
}

// add
table.addContent(tgroup);
articleElement.addContent(table);
}

private Element getRow(Vector items) {
Element row = new Element("row");
for (int i = 0; i < items.size(); i++) {
Object item = items.elementAt(i);
String name = item.toString();
Element entry = new Element("entry");
if (item.getClass().equals(Element.class)) {
entry.addContent((Element) item);
} else {
entry.setText(name);
}
row.addContent(entry);
}
return row;
}

public void addContent(Content content) {
articleElement.addContent(content);
}

public Element createBarcodeElement(String barcodeString) throws
Exception {

// filename, in the same dir as the docbook.
File tmpFile = File.createTempFile("barcode_", ".jpg", filesDirectory);
OutputStream out = new FileOutputStream(tmpFile);

// barcode
Code128Bean code = new Code128Bean();
code.setModuleWidth(UnitConv.in2mm(1.0f / 50));
code.doQuietZone(false);
// SVGCanvasProvider canvas = new SVGCanvasProvider();
// EPSCanvasProvider canvas = new EPSCanvasProvider(out);
BitmapCanvasProvider canvas = new BitmapCanvasProvider(out,
"image/jpeg", 300, BufferedImage.TYPE_BYTE_GRAY, true);
code.generateBarcode(canvas, barcodeString);
canvas.finish();
out.close();

// xml to file
/*
* org.w3c.dom.Document doc = canvas.getDOM(); DOMBuilder builder = new
* DOMBuilder(); org.jdom.Document jdomDoc = builder.build(doc);
* XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
* OutputStream out = new FileOutputStream(tmpFile); try {
* outputter.output(jdomDoc, out); } finally { out.close(); }
*/

// element
Element mediaobjectElement = new Element("mediaobject");
// for html
Element imageobjectElement = new Element("imageobject");
Element imagedataElement = new Element("imagedata");
imageobjectElement.setAttribute("role", "html");
imagedataElement.setAttribute("format", "JPEG");
imagedataElement.setAttribute("width", "5cm");
imagedataElement.setAttribute("fileref", tmpFile.getName());
imageobjectElement.addContent(imagedataElement);
mediaobjectElement.addContent(imageobjectElement);
// and pdf
imageobjectElement = new Element("imageobject");
imageobjectElement.setAttribute("role", "fo");
imagedataElement = new Element("imagedata");
imagedataElement.setAttribute("format", "JPEG");
imagedataElement.setAttribute("width", "5cm");
imagedataElement.setAttribute("fileref", tmpFile.getPath());
imageobjectElement.addContent(imagedataElement);
mediaobjectElement.addContent(imageobjectElement);

return mediaobjectElement;
}

public File createAllFiles(String docbook2foXslFile) throws Exception {
createDocbookFile();
createFoFile(docbook2foXslFile);
createHtmlFile();
createPdfFile();
return createZipFromHtml();
}

private void copyFilesToDir(File to) throws Exception {
File[] files = filesDirectory.listFiles();
for (int i = 0; i < files.length; i++) {
FileIO.copyFile(files[i].getPath(), to.getPath() + fileSep
+ files[i].getName());
}
}

public File createDocbookFile() throws Exception {
// file
docbookTmpFile = File.createTempFile("docbook_", ".xml",
docbookRootDirectory);
FileOutputStream out = new FileOutputStream(docbookTmpFile);

// ouput
try {
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(doc, out);
} finally {
out.close();
}
return docbookTmpFile;
}

public void setPortrait() {
this.orientation = "portrait";
}

public void setLandscape() {
this.orientation = "landscape";
}

public File createFoFile(String docbook2foXslFile) throws Exception {
// file
foTmpFile = File.createTempFile("fo_", ".fo", foRootDirectory);
FileOutputStream out = new FileOutputStream(foTmpFile);

// transformation
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(new StreamSource(
new File(docbook2foXslFile)));
Source source = new StreamSource(docbookTmpFile);
Result result = new StreamResult(foTmpFile);
transformer.setParameter("paper.type", "A4");
transformer.setParameter("page.orientation", orientation);
transformer.setParameter("draft.mode", "no");
transformer.transform(source, result);
} finally {
out.close();
}
return foTmpFile;
}

public File createHtmlFile() throws Exception {
// file
htmlTmpFile = new File(htmlRootDirectory, "index.html");
FileOutputStream out = new FileOutputStream(htmlTmpFile);

// working files
copyFilesToDir(htmlRootDirectory);

// transformation
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory
.newTransformer(new StreamSource(
new File(

"/usr/share/xml/docbook/stylesheet/nwalsh/current/html/docbook.xsl")));
Source source = new StreamSource(docbookTmpFile);
Result result = new StreamResult(htmlTmpFile);
transformer.transform(source, result);
} finally {
out.close();
}
return htmlTmpFile;
}

public File createPdfFile() throws Exception {
// file
pdfTmpFile = File.createTempFile("pdf_", ".pdf", pdfRootDirectory);
FileOutputStream out = new FileOutputStream(pdfTmpFile);

try {
// driver
Driver driver = new Driver();
driver.setLogger(new ConsoleLogger(ConsoleLogger.LEVEL_INFO));
driver.setRenderer(Driver.RENDER_PDF);
driver.setOutputStream(out);

// transform
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
Source source = new StreamSource(foTmpFile);
Result result = new SAXResult(driver.getContentHandler());
transformer.transform(source, result);
} finally {
out.close();
}
return pdfTmpFile;
}

public void printPdfFile() throws Exception {
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
PrintService defaultService = PrintServiceLookup
.lookupDefaultPrintService();
DocPrintJob job = defaultService.createPrintJob();
FileInputStream fis = new FileInputStream(pdfTmpFile);
DocAttributeSet das = new HashDocAttributeSet();
Doc doc = new SimpleDoc(fis, flavor, das);
job.print(doc, pras);
}

public File createZipFromHtml() throws Exception {
// file
zipTmpFile = File
.createTempFile("html_", ".zip", zipDirectory);
// zipped
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(
zipTmpFile));
// list files
File[] files = htmlRootDirectory.listFiles();
for (int i = 0; i < files.length; i++) {
ZipEntry entry = new ZipEntry(files[i].getName());
zipOut.putNextEntry(entry);
zipOut.write(FileIO.getFileBytes(files[i]));
zipOut.flush();
}
// end
zipOut.flush();
zipOut.close();

return zipTmpFile;
}

public File getZipTmpFile() {
return zipTmpFile ;
}
}
--------------------
/**
* @ejb.interface-method
* @ejb.transaction type="required"
*/
public byte[] getDocHtmlZipContent(String folder) throws Exception {
File zipTmpFolder = new File(folder
+ System.getProperty("file.separator") + "zip");
File[] zips = zipTmpFolder.listFiles();
if (zips.length < 1) {
return null;
} else {
return FileIO.readFile(zips[zips.length - 1].getPath());
}
}

/**
* @ejb.interface-method
* @ejb.transaction type="required"
*/
public byte[] getDocPdfContent(String folder) throws Exception {
File pdfTmpFolder = new File(folder
+ System.getProperty("file.separator") + "pdf");
File[] pdfs = pdfTmpFolder.listFiles();
if (pdfs.length < 1) {
return null;
} else {
return FileIO.readFile(pdfs[pdfs.length - 1].getPath());
}
}
----------------------
File tmpZip = File.createTempFile(doc.getDocumentationId()+"_",".zip");

FileIO.writeFile(tmpZip,lims.getDocumentationFacade().getDocHtmlZipContent(doc.getDocumentationId()));
JarRessourceFinder loader = new JarRessourceFinder(tmpZip);
JEditorPane edit = new JEditorPane(loader.findResource("index.html"));
edit.setEditable(false);
JInternalFrame editFrame = new
JInternalFrame(doc.getDocumentationId(),true,true,true,true);
editFrame.add(new JScrollPane(edit));
getContentPane().add(editFrame);
editFrame.setSize(400,600);
editFrame.setLocation(50,50);
editFrame.show();
------------------
package com.integragen.lims.utils.file;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class JarRessourceFinder extends ClassLoader {

JarFile jar;

public JarRessourceFinder(File jarFile) throws Exception {
jar = new JarFile(jarFile);
}

public InputStream findResourceAsStream(String resourceName) {
JarEntry je = jar.getJarEntry(resourceName);
if (je == null)
return null;
try {
return jar.getInputStream(je);
} catch (IOException e) {
return null;
}
}

public URL findResource(String resourceName) {
System.out.println("findResource ? : "+resourceName);

Enumeration en = jar.entries();
while (en.hasMoreElements()) {
System.out.println( " entry = " + en.nextElement() );
}

if (jar.getJarEntry(resourceName) == null)
return null;
try {
URL url = new URL("jar", "", "file:"+jar.getName().replace(
File.separatorChar, '/')
+ "!/" + resourceName) ;
System.out.println("url : "+url);
return url;
} catch (MalformedURLException e) {
throw new RuntimeException();
}
}

}
Avatar
LR
Jette un coup d'oeil à http://jasperreports.sourceforge.net/

Cela te permet de générer des rapports en PDF. C'est basé sur des template
que tu "remplis" ensuite avec tes données. Il existe plusieurs outils GUI
te permettant de générer ces templates.

Je trouve que c'est plus pratique à utiliser que XSL-FO mais ça ne
respecte pas de norme.


Merci, ça a effectivement l'air très intéressant.
Pour l'instant, j'en suis à la phase de conception de l'application et je
n'ai donc pas vraiment le temps d'approfondir mais je prépare le terrain
pour la réalisation et je ne manquerai pas d'étudier ça.

A+Lilian

Avatar
LR
Merci beaucoup pout tout ça, je regarderai très en détail dans quelques
jours et j'aurai peut-être des questions à ce moment-là.
A+Lilian

perso, j'ai choisi d'ecrire du docbook (a l'aide de org.jdom)
le docbook on peut pas faire plus simple (genre html 2.0).
de transformer le docbook en xsl-fo par les feuilles xslt qui existent.
ensuite le fo est soit :
- affiche a l'ecran
- transforme en pdf
- transforme en html 3.2
...

voici ce que j'ai ecrit, la seule chose a changer est l'appel a
limsPreferencesFacade, et l'appel a la feuille xsl est chez moi :
/usr/share/xml/docbook/stylesheet/nwalsh/current/fo/docbook.xsl

note : ca gere aussi les codes barres avec chrysalis.
un petit truc fatiguant c'est le lien entre les fichiers generes :
un fichier html (ou plusieurs), les images ...
il faut donc faire des liens relatifs.
par contre pour faire le pdf (ou tout est dedans), il faut des liens
relatif. le but de code qui gere les codes barres gere ce probleme.


extrait 1 : comment l'utiliser
extrait 2 : la classe utile "DocbookContents"
extrait 3 : exemple pour transferer le fichier zip contenant les
pages web/images crees vers le client. (ejb session)
extrait 4 : afficher le contenu du zip dans un panel. (client swing)
extrait 5 : le jarressourcefinder utilise dans l'extrait 4.

-------------
DocbookContents db = new DocbookContents(limsPreferencesFacade,
"test", "TechReport");
String file = "";
try {

db.addArticleInfo("barcodeici", "Titre ici",
"Ceci est le sous titre ... un peu plus long peut etre",
"prenom", "nom", new Date(), false);

db.addPara("Ceci est un test Ceci est un test Ceci est un
test Ceci est un test Ceci est un test");
db.addContent(db.createBarcodeElement("tititoto"));
db.addPara("Ceci est un test Ceci est un test Ceci
est un test Ceci est un test Ceci est un test");

Vector headers = new Vector();
headers.add("A");
headers.add("B");
headers.add("C");
headers.add("D");
headers.add("E");
Vector line = new Vector();
line.add("col A");
line.add("col B");
line.add("c");
line.add("col D");
line.add("col E");
Vector lines = new Vector();
lines.add(line);
lines.add(line);
lines.add(line);
db.addTable("Test de table.", headers, lines, headers);
db.addPara("ceci est un paragraphe");

// go
String docbook2foXslFile = limsPreferencesFacade.getProperty(
"docbook.foXslFile", "");
file = db.createAllFiles(docbook2foXslFile).toString();
if (limsPreferencesFacade.getProperty("print.allow", "true")
.toString().equals("true") && print) {
db.printPdfFile();
} else {
System.out.println("printing disabled !");
}
} catch (Exception e) {
System.out.println("Error creating and printing PDF : " + e);
e.printStackTrace();
}

-------------
package com.integragen.lims.utils.docbook;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
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.logger.ConsoleLogger;
import org.apache.fop.apps.Driver;
import org.jdom.Content;
import org.jdom.DocType;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;

import com.integragen.lims.ejb.main.LimsPreferencesFacade;
import com.integragen.lims.utils.file.FileIO;

public class DocbookContents {

Document doc;

Element articleElement;

File parentDirectory;

File docbookRootDirectory;

File filesDirectory;

File docbookTmpFile;

File foRootDirectory;

File foTmpFile;

File htmlRootDirectory;

File htmlTmpFile;

File pdfRootDirectory;

File pdfTmpFile;

File zipDirectory;

File zipTmpFile;

String logoFilename;

String docbookRoot;

String fileSep;

String orientation = "portrait";

LimsPreferencesFacade limsPreferencesFacade;

public DocbookContents(LimsPreferencesFacade limsPreferencesFacade,
String id, String articleClass) throws Exception {
this.limsPreferencesFacade = limsPreferencesFacade;
fileSep = System.getProperty("file.separator");
docbookRoot = limsPreferencesFacade.getProperty("docbook.rootdir", "");
logoFilename = limsPreferencesFacade
.getProperty("docbook.logofile", "");

DocType docType = new DocType("article",
"-//OASIS//DTD DocBook XML V4.3//EN",
"../../docbook/docbookx.dtd");
articleElement = new Element("article");
articleElement.setAttribute("id", id);
articleElement.setAttribute("Class", articleClass);
doc = new Document(articleElement, docType);

File rootDirectory = new File(docbookRoot);
if (!rootDirectory.exists()) {
rootDirectory.mkdir();
}
File parentDirectoryFile = File.createTempFile("lock_", "",
rootDirectory);
parentDirectory = new File(parentDirectoryFile.getPath() + "_dir");
parentDirectory.mkdirs();
docbookRootDirectory = new File(parentDirectory.getPath() + fileSep
+ "docbook");
docbookRootDirectory.mkdir();
filesDirectory = new File(parentDirectory.getPath() + fileSep + "files");
filesDirectory.mkdir();
foRootDirectory = new File(parentDirectory.getPath() + fileSep + "fo");
foRootDirectory.mkdir();
htmlRootDirectory = new File(parentDirectory.getPath() + fileSep
+ "html");
htmlRootDirectory.mkdir();
pdfRootDirectory = new File(parentDirectory.getPath() + fileSep + "pdf");
pdfRootDirectory.mkdir();
zipDirectory = new File(parentDirectory.getPath() + fileSep + "zip");
zipDirectory.mkdir();
}

public String getParentDirectory() {
return parentDirectory.getPath();
}

public void addArticleInfo(String barcode, String titleText,
String subtitleText, String authorFirstName, String authorLastName,
Date creationDate, boolean showBarcode) throws Exception {

Element articleInfo = new Element("articleinfo");

// title
Element title = new Element("title");
title.setText(titleText);
articleInfo.addContent(title);

// subtitle
Element subtitle = new Element("subtitle");
subtitle.setText(creationDate + ", [ " + barcode + " ], "
+ subtitleText);
articleInfo.addContent(subtitle);

// date
Element date = new Element("date");
date.setText(creationDate.toString());
articleInfo.addContent(date);

// author
Element author = new Element("author");
Element firstName = new Element("firstname");
firstName.setText(authorFirstName);
author.addContent(firstName);
Element surName = new Element("surname");
surName.setText(authorLastName);
author.addContent(surName);
articleInfo.addContent(author);
// Element authorgroup = new Element("authorgroup");
// authorgroup.addContent(author);
// articleInfo.addContent(authorgroup);

Vector items = new Vector();

// logo
// copy logo file
File logoNewFile = new File(filesDirectory + fileSep
+ new File(logoFilename).getName());
logoNewFile.createNewFile();
FileIO.copyFile(logoFilename, logoNewFile.getPath());
// add in docbook
Element mediaobjectElement = new Element("mediaobject");
// for html
Element imageobjectElement = new Element("imageobject");
Element imagedataElement = new Element("imagedata");
imageobjectElement.setAttribute("role", "html");
imagedataElement.setAttribute("format", "JPEG");
imagedataElement.setAttribute("width", "5cm");
imagedataElement.setAttribute("fileref", logoNewFile.getName());
imageobjectElement.addContent(imagedataElement);
mediaobjectElement.addContent(imageobjectElement);
// and for pdf
imageobjectElement = new Element("imageobject");
imageobjectElement.setAttribute("role", "fo");
imagedataElement = new Element("imagedata");
imagedataElement.setAttribute("format", "JPEG");
imagedataElement.setAttribute("width", "5cm");
imagedataElement.setAttribute("fileref", logoNewFile.getPath());
imageobjectElement.addContent(imagedataElement);
mediaobjectElement.addContent(imageobjectElement);

items.add(mediaobjectElement);

// barcode
items.add(createBarcodeElement(barcode));

// table
Element table = new Element("table");
table.setAttribute("frame", "none");
table.setAttribute("tocentry", "0");
// table title
Element tabletitle = new Element("title");
tabletitle.setText("DocId");
table.addContent(tabletitle);

Element tgroup = new Element("tgroup");
tgroup.setAttribute("align", "center");
tgroup.setAttribute("cols", "2");
Element tbody = new Element("tbody");
tbody.addContent(getRow(items));
tgroup.addContent(tbody);
table.addContent(tgroup);

// add
articleElement.addContent(articleInfo);
if (showBarcode) {
articleElement.addContent(table);
}
}

public void addPara(String text) {
Element para = new Element("para");
para.setText(text);
articleElement.addContent(para);
}

public void addTable(String title, Vector headers, Vector lines,
Vector footers) {
// table
Element table = new Element("table");
table.setAttribute("frame", "all");

// title
Element tabletitle = new Element("title");
tabletitle.setText(title);
table.addContent(tabletitle);

// tgroup
Element tgroup = new Element("tgroup");
tgroup.setAttribute("align", "center");
tgroup.setAttribute("cols", headers.size() + "");

// header
Element thead = new Element("thead");
thead.addContent(getRow(headers));
tgroup.addContent(thead);

// body
Element tbody = new Element("tbody");
for (int i = 0; i < lines.size(); i++) {
tbody.addContent(getRow((Vector) lines.elementAt(i)));
}
tgroup.addContent(tbody);

// footer
if (footers != null) {
Element tfoot = new Element("tfoot");
tfoot.addContent(getRow(footers));
tgroup.addContent(tfoot);
}

// add
table.addContent(tgroup);
articleElement.addContent(table);
}

private Element getRow(Vector items) {
Element row = new Element("row");
for (int i = 0; i < items.size(); i++) {
Object item = items.elementAt(i);
String name = item.toString();
Element entry = new Element("entry");
if (item.getClass().equals(Element.class)) {
entry.addContent((Element) item);
} else {
entry.setText(name);
}
row.addContent(entry);
}
return row;
}

public void addContent(Content content) {
articleElement.addContent(content);
}

public Element createBarcodeElement(String barcodeString) throws Exception
{

// filename, in the same dir as the docbook.
File tmpFile = File.createTempFile("barcode_", ".jpg", filesDirectory);
OutputStream out = new FileOutputStream(tmpFile);

// barcode
Code128Bean code = new Code128Bean();
code.setModuleWidth(UnitConv.in2mm(1.0f / 50));
code.doQuietZone(false);
// SVGCanvasProvider canvas = new SVGCanvasProvider();
// EPSCanvasProvider canvas = new EPSCanvasProvider(out);
BitmapCanvasProvider canvas = new BitmapCanvasProvider(out,
"image/jpeg", 300, BufferedImage.TYPE_BYTE_GRAY, true);
code.generateBarcode(canvas, barcodeString);
canvas.finish();
out.close();

// xml to file
/*
* org.w3c.dom.Document doc = canvas.getDOM(); DOMBuilder builder = new
* DOMBuilder(); org.jdom.Document jdomDoc = builder.build(doc);
* XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
* OutputStream out = new FileOutputStream(tmpFile); try {
* outputter.output(jdomDoc, out); } finally { out.close(); }
*/

// element
Element mediaobjectElement = new Element("mediaobject");
// for html
Element imageobjectElement = new Element("imageobject");
Element imagedataElement = new Element("imagedata");
imageobjectElement.setAttribute("role", "html");
imagedataElement.setAttribute("format", "JPEG");
imagedataElement.setAttribute("width", "5cm");
imagedataElement.setAttribute("fileref", tmpFile.getName());
imageobjectElement.addContent(imagedataElement);
mediaobjectElement.addContent(imageobjectElement);
// and pdf
imageobjectElement = new Element("imageobject");
imageobjectElement.setAttribute("role", "fo");
imagedataElement = new Element("imagedata");
imagedataElement.setAttribute("format", "JPEG");
imagedataElement.setAttribute("width", "5cm");
imagedataElement.setAttribute("fileref", tmpFile.getPath());
imageobjectElement.addContent(imagedataElement);
mediaobjectElement.addContent(imageobjectElement);

return mediaobjectElement;
}

public File createAllFiles(String docbook2foXslFile) throws Exception {
createDocbookFile();
createFoFile(docbook2foXslFile);
createHtmlFile();
createPdfFile();
return createZipFromHtml();
}

private void copyFilesToDir(File to) throws Exception {
File[] files = filesDirectory.listFiles();
for (int i = 0; i < files.length; i++) {
FileIO.copyFile(files[i].getPath(), to.getPath() + fileSep
+ files[i].getName());
}
}

public File createDocbookFile() throws Exception {
// file
docbookTmpFile = File.createTempFile("docbook_", ".xml",
docbookRootDirectory);
FileOutputStream out = new FileOutputStream(docbookTmpFile);

// ouput
try {
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(doc, out);
} finally {
out.close();
}
return docbookTmpFile;
}

public void setPortrait() {
this.orientation = "portrait";
}

public void setLandscape() {
this.orientation = "landscape";
}

public File createFoFile(String docbook2foXslFile) throws Exception {
// file
foTmpFile = File.createTempFile("fo_", ".fo", foRootDirectory);
FileOutputStream out = new FileOutputStream(foTmpFile);

// transformation
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(new StreamSource(
new File(docbook2foXslFile)));
Source source = new StreamSource(docbookTmpFile);
Result result = new StreamResult(foTmpFile);
transformer.setParameter("paper.type", "A4");
transformer.setParameter("page.orientation", orientation);
transformer.setParameter("draft.mode", "no");
transformer.transform(source, result);
} finally {
out.close();
}
return foTmpFile;
}

public File createHtmlFile() throws Exception {
// file
htmlTmpFile = new File(htmlRootDirectory, "index.html");
FileOutputStream out = new FileOutputStream(htmlTmpFile);

// working files
copyFilesToDir(htmlRootDirectory);

// transformation
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory
.newTransformer(new StreamSource(
new File(

"/usr/share/xml/docbook/stylesheet/nwalsh/current/html/docbook.xsl")));
Source source = new StreamSource(docbookTmpFile);
Result result = new StreamResult(htmlTmpFile);
transformer.transform(source, result);
} finally {
out.close();
}
return htmlTmpFile;
}

public File createPdfFile() throws Exception {
// file
pdfTmpFile = File.createTempFile("pdf_", ".pdf", pdfRootDirectory);
FileOutputStream out = new FileOutputStream(pdfTmpFile);

try {
// driver
Driver driver = new Driver();
driver.setLogger(new ConsoleLogger(ConsoleLogger.LEVEL_INFO));
driver.setRenderer(Driver.RENDER_PDF);
driver.setOutputStream(out);

// transform
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
Source source = new StreamSource(foTmpFile);
Result result = new SAXResult(driver.getContentHandler());
transformer.transform(source, result);
} finally {
out.close();
}
return pdfTmpFile;
}

public void printPdfFile() throws Exception {
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
PrintService defaultService = PrintServiceLookup
.lookupDefaultPrintService();
DocPrintJob job = defaultService.createPrintJob();
FileInputStream fis = new FileInputStream(pdfTmpFile);
DocAttributeSet das = new HashDocAttributeSet();
Doc doc = new SimpleDoc(fis, flavor, das);
job.print(doc, pras);
}

public File createZipFromHtml() throws Exception {
// file
zipTmpFile = File
.createTempFile("html_", ".zip", zipDirectory);
// zipped
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(
zipTmpFile));
// list files
File[] files = htmlRootDirectory.listFiles();
for (int i = 0; i < files.length; i++) {
ZipEntry entry = new ZipEntry(files[i].getName());
zipOut.putNextEntry(entry);
zipOut.write(FileIO.getFileBytes(files[i]));
zipOut.flush();
}
// end
zipOut.flush();
zipOut.close();

return zipTmpFile;
}

public File getZipTmpFile() {
return zipTmpFile ;
}
}
--------------------
/**
* @ejb.interface-method
* @ejb.transaction type="required"
*/
public byte[] getDocHtmlZipContent(String folder) throws Exception {
File zipTmpFolder = new File(folder
+ System.getProperty("file.separator") + "zip");
File[] zips = zipTmpFolder.listFiles();
if (zips.length < 1) {
return null;
} else {
return FileIO.readFile(zips[zips.length - 1].getPath());
}
}

/**
* @ejb.interface-method
* @ejb.transaction type="required"
*/
public byte[] getDocPdfContent(String folder) throws Exception {
File pdfTmpFolder = new File(folder
+ System.getProperty("file.separator") + "pdf");
File[] pdfs = pdfTmpFolder.listFiles();
if (pdfs.length < 1) {
return null;
} else {
return FileIO.readFile(pdfs[pdfs.length - 1].getPath());
}
}
----------------------
File tmpZip = File.createTempFile(doc.getDocumentationId()+"_",".zip");

FileIO.writeFile(tmpZip,lims.getDocumentationFacade().getDocHtmlZipContent(doc.getDocumentationId()));
JarRessourceFinder loader = new JarRessourceFinder(tmpZip);
JEditorPane edit = new JEditorPane(loader.findResource("index.html"));
edit.setEditable(false);
JInternalFrame editFrame = new
JInternalFrame(doc.getDocumentationId(),true,true,true,true);
editFrame.add(new JScrollPane(edit));
getContentPane().add(editFrame);
editFrame.setSize(400,600);
editFrame.setLocation(50,50);
editFrame.show();
------------------
package com.integragen.lims.utils.file;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class JarRessourceFinder extends ClassLoader {

JarFile jar;

public JarRessourceFinder(File jarFile) throws Exception {
jar = new JarFile(jarFile);
}

public InputStream findResourceAsStream(String resourceName) {
JarEntry je = jar.getJarEntry(resourceName);
if (je == null)
return null;
try {
return jar.getInputStream(je);
} catch (IOException e) {
return null;
}
}

public URL findResource(String resourceName) {
System.out.println("findResource ? : "+resourceName);

Enumeration en = jar.entries();
while (en.hasMoreElements()) {
System.out.println( " entry = " + en.nextElement() );
}

if (jar.getJarEntry(resourceName) == null)
return null;
try {
URL url = new URL("jar", "", "file:"+jar.getName().replace(
File.separatorChar, '/')
+ "!/" + resourceName) ;
System.out.println("url : "+url);
return url;
} catch (MalformedURLException e) {
throw new RuntimeException();
}
}

}


Avatar
Symon
LR wrote:

La deuxième solution est utilisée par l'administration de mon canton dans le
logiciel de saisie des impôts pour imprimer la déclaration. Je trouve que
c'est une excellente solution mais elle m'inquiète techniquement.




La première solution n'est pas valable pour du print, et il n'existe pas
de solution standard robuste et gratuite pour la troisième (voir quand
meme POI d'Apache- http://jakarta.apache.org/poi/ -, mais je crois
l'implémentation du format MS Word est super limitée, le support d'Excel
est bon par contre).

Le plus efficace sera la génération d'un fichier PDF à partir d'un
XSL:FO généré par transformation à partir de données XML (voir FOP
d'Apache : http://xml.apache.org/fop).

Si tu as de bonnes bases en XML/XSL, ça ne devrait pas te poser de
problèmes, c'est assez facile à implémenter, surtout pour de petites
éditions de quelques pages.

Pas vraiment le choix pour faire ça gratuitement avec Java. A moins de
recourir à une fusion de fichier RTF, qui reste super limitée et peu
portable.


A+

Symon