Gestion des images intégrées dans IText XMLWorker.
Existe-t-il un moyen de gérer les images incorporées (Base64) dans XMLWorker ? Dans la version 5.3.5 l'ImageProvider que j'ai utilisé ne fonctionne plus (une exception est levée avant), j'ai donc patché ImageRetrieve comme suit, mais il est évident que cela ne fonctionnera plus dans la prochaine mise à jour de XMLWorker :
package com.itextpdf.tool.xml.net;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.codec.Base64;
import com.itextpdf.tool.xml.net.exc.NoImageException;
import com.itextpdf.tool.xml.pipeline.html.ImageProvider;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author redlab_b
*
*/
public class ImageRetrieve {
final static Pattern INLINE_PATTERN = Pattern.compile("^/data:image/(png|jpg|gif);base64,(.*)");
private final ImageProvider provider;
/**
* @param imageProvider the provider to use.
*
*/
public ImageRetrieve(final ImageProvider imageProvider) {
this.provider = imageProvider;
}
/**
*
*/
public ImageRetrieve() {
this.provider = null;
}
/**
* @param src an URI that can be used to retrieve an image
* @return an iText Image object
* @throws NoImageException if there is no image
* @throws IOException if an IOException occurred
*/
public com.itextpdf.text.Image retrieveImage(final String src) throws NoImageException, IOException {
com.itextpdf.text.Image img = null;
if (null != provider) {
img = provider.retrieve(src);
}
if (null == img) {
String path = null;
if (src.startsWith("http")) {
// full url available
path = src;
} else if (null != provider){
String root = this.provider.getImageRootPath();
if (null != root) {
if (root.endsWith("/") && src.startsWith("/")) {
root = root.substring(0, root.length() - 1);
}
path = root + src;
}
} else {
path = src;
}
if (null != path) {
try {
Matcher m;
if (path.startsWith("http")) {
img = com.itextpdf.text.Image.getInstance(path);
} else if ((m = INLINE_PATTERN.matcher(path)).matches()) {
// Let's handle the embedded image without saving it
try {
byte[] data = Base64.decode(m.group(2));
return Image.getInstance(data);
} catch (Exception ex) {
throw new NoImageException(src, ex);
}
} else {
img = com.itextpdf.text.Image.getInstance(new File(path).toURI().toURL());
}
if (null != provider && null != img) {
provider.store( src, img);
}
} catch (BadElementException e) {
throw new NoImageException(src, e);
} catch (MalformedURLException e) {
throw new NoImageException(src, e);
}
} else {
throw new NoImageException(src);
}
}
return img;
}
}