Open GoogleCodeExporter opened 9 years ago
Try this. It assumes that your images are on the classpath:
String htmlString = readFileAsString(PDFRender.class.getResource("test.html").getFile());
ITextRenderer renderer = new ITextRenderer();
ResourceLoaderUserAgent callback = new ResourceLoaderUserAgent(renderer.getOutputDevice());
callback.setSharedContext(renderer.getSharedContext());
renderer.getSharedContext().setUserAgentCallback(callback);
final ByteArrayInputStream htmlIn = new ByteArrayInputStream(htmlString.getBytes());
final ByteArrayOutputStream xhtmlErr = new ByteArrayOutputStream();
final PrintWriter printErr = new PrintWriter(xhtmlErr);
final Tidy tidy = new Tidy();
tidy.setErrout(printErr);
Document doc = tidy.parseDOM(htmlIn, null);
renderer.setDocument(doc, url);
renderer.layout();
renderer.createPDF(os);
os.close();
os = null;
} finally {
if(os != null) {
try {
os.close();
} catch(IOException e) {
// ignore
}
}
}
}
private static class ResourceLoaderUserAgent extends ITextUserAgent {
public ResourceLoaderUserAgent(ITextOutputDevice outputDevice) {
super(outputDevice);
}
protected InputStream resolveAndOpenStream(String uri) {
System.out.println("IN resolveAndOpenStream() " + uri);
InputStream is = super.resolveAndOpenStream(uri);
if(is == null) {
//Assumes that the last part is the file name and that the image is on the classpath
String[] split = uri.split("/");
String lastPart = split[split.length - 1];
//Could extend this to look in more places
is = ResourceLoaderUserAgent.class.getResourceAsStream(lastPart);
}
return is;
}
}
private static String readFileAsString(String filePath) throws java.io.IOException {
byte[] buffer = new byte[(int)new File(filePath).length()];
BufferedInputStream f = null;
try {
f = new BufferedInputStream(new FileInputStream(filePath));
f.read(buffer);
} finally {
if(f != null) {
try {
f.close();
} catch(IOException ignored) {
}
}
}
return new String(buffer);
}
Original comment by opticyc...@gmail.com
on 2 May 2011 at 1:45
Original issue reported on code.google.com by
nep...@gmail.com
on 25 Mar 2011 at 7:46