我也覆蓋了ITextUserAgent - 從源代碼看起來就像ITextRenderer使用的那樣。您必須在構造函數中提供輸出設備,您可以從渲染器對象獲取輸出設備。另一個問題是你必須使用setter方法明確地設置「共享上下文」 - 否則在渲染過程中你會得到一個NPE。這是建立在對象的代碼:
ITextRenderer renderer = new ITextRenderer();
MyUserAgentCallback uac = new MyUserAgentCallback(renderer.getOutputDevice());
uac.setSharedContext(renderer.getSharedContext());
renderer.getSharedContext().setUserAgentCallback(uac);
而且,這裏是MyUserAgentCallback的基本思想,使用基本身份驗證:
private static class MyUserAgentCallback extends ITextUserAgent
{
public MyUserAgentCallback(ITextOutputDevice outputDevice)
{
super(outputDevice);
}
@Override
protected InputStream resolveAndOpenStream(String uri)
{
if (_isProtectedResource(uri))
{
java.io.InputStream is = null;
uri = resolveURI(uri);
try {
URL url = new URL(uri);
String encoding = new BASE64Encoder().encode ("username:password".getBytes());
URLConnection uc = url.openConnection();
uc.setRequestProperty ("Authorization", "Basic " + encoding);
is = uc.getInputStream();
Log.debug("got input stream");
}
catch (java.net.MalformedURLException e) {
Log.error("bad URL given: " + uri, e);
}
catch (java.io.FileNotFoundException e) {
Log.error("item at URI " + uri + " not found");
}
catch (java.io.IOException e) {
Log.error("IO problem for " + uri, e);
}
return is;
}
else
{
return super.resolveAndOpenStream(uri);
}
}
private boolean _isProtectedResource(String uri)
{
// does this require authentication?
}
}
謝謝,這個工作對我來說,雖然我延長了ITextUserAgent類代替。 – ManiSto 2011-02-22 12:22:08