我需要设置自定义用户代理来呈现二维码
ITextRenderer renderer = new ITextRenderer();
UserAgent callback = new UserAgent(renderer.getOutputDevice());
callback.setSharedContext(renderer.getSharedContext());
renderer.getSharedContext().setUserAgentCallback(callback);
renderer.setDocumentFromString(html);
renderer.layout();
renderer.createPDF(os);
用户代理:
public class UserAgent extends ITextUserAgent {
public UserAgent(ITextOutputDevice outputDevice) {
super(outputDevice); // breakpoint, execution gets here
}
@Override
public ImageResource getImageResource(String uri) {
if(uri.startsWith("qrcode://")) { // breakpoint, execution never gets here
ByteArrayOutputStream s = QRCode.from(uri.substring(9)).to(ImageType.PNG).stream();
try {
Image i = Image.getInstance(s.toByteArray());
ITextFSImage fsi = new ITextFSImage(i);
return new ImageResource(uri, fsi);
} catch (BadElementException | IOException e) {
// TODO Auto-generated catch block
}
return null;
} else {
return super.getImageResource(uri);
}
}
}
根据文档,这应该可以工作,但是永远不会调用 getImageResource() ,现在我迷路了。生成了 Pdf 文档,但我得到的是空白而不是图像。另一个使用 http:// 链接的图像正确显示。