java – 在flyingsaucer生成的pdf中从servlet渲染图像
发布时间:2020-12-14 05:06:26 所属栏目:Java 来源:网络整理
导读:我正在使用flyingsaucer通过返回生成的pdf文档的servlet将xhtml文档呈现给pdf. xhtml文档具有从另一个servlet请求的映像.图像servlet检查谁在登录之前返回适当的图像.下面的代码显示了如何请求图像: img height="140" width="140" src="http://localhost:80
我正在使用flyingsaucer通过返回生成的pdf文档的servlet将xhtml文档呈现给pdf. xhtml文档具有从另一个servlet请求的映像.图像servlet检查谁在登录之前返回适当的图像.下面的代码显示了如何请求图像:
<img height="140" width="140" src="http://localhost:8080/myapp/servlet/DisplayPic" /> 我的问题是,图像的http请求来自pdf渲染器,而不是登录的用户,因此图像servlet不知道谁登录了,因此不会返回所需的图像. 我正在使用以下代码来呈现xhtml文档: ITextRenderer renderer = new ITextRenderer(); renderer.setDocumentFromString(xhtmlDocumentAsString); renderer.layout(); os = response.getOutputStream(); renderer.createPDF(os); 我需要在请求图像servlet时维护用户的会话,或者为渲染器提供要用于该特定xhtml元素的图像.我认为后者可以使用ReplacedElementFactory完成,但是我无法挖掘可以帮助我的任何示例代码. 解决方法
我现在这个工作非常好.这是代码.
在我的xhtml文档中我有: <div class="profile_picture" style="display:block;width:140px;height:140px;" /> (我使用的是div元素而不是img,因为工厂只用于块级元素) 我使用: ITextRenderer renderer = new ITextRenderer(); renderer.getSharedContext().setReplacedElementFactory(new ProfileImageReplacedElementFactory(renderer.getSharedContext().getReplacedElementFactory())); renderer.setDocumentFromString(xhtmlDocumentAsString); renderer.layout(); os = response.getOutputStream(); renderer.createPDF(os); 我有我自己的ReplacedElementFactory如下: public class ProfileImageReplacedElementFactory implements ReplacedElementFactory { private final ReplacedElementFactory superFactory; public ProfileImageReplacedElementFactory(ReplacedElementFactory superFactory) { this.superFactory = superFactory; } @Override public ReplacedElement createReplacedElement(LayoutContext layoutContext,BlockBox blockBox,UserAgentCallback userAgentCallback,int cssWidth,int cssHeight) { Element element = blockBox.getElement(); if (element == null) { return null; } String nodeName = element.getNodeName(); String className = element.getAttribute("class"); if ("div".equals(nodeName) && className.contains("profile_picture")) { InputStream input = null; try { input = ...; byte[] bytes = IOUtils.toByteArray(input); Image image = Image.getInstance(bytes); FSImage fsImage = new ITextFSImage(image); if (fsImage != null) { if ((cssWidth != -1) || (cssHeight != -1)) { fsImage.scale(cssWidth,cssHeight); } return new ITextImageElement(fsImage); } } catch (IOException e) { getLogger().error(ExceptionUtils.getStackTrace(e)); } catch (BadElementException e) { getLogger().error(ExceptionUtils.getStackTrace(e)); } finally { IOUtils.closeQuietly(input); } } return superFactory.createReplacedElement(layoutContext,blockBox,userAgentCallback,cssWidth,cssHeight); } @Override public void reset() { superFactory.reset(); } @Override public void remove(Element e) { superFactory.remove(e); } @Override public void setFormSubmissionListener(FormSubmissionListener listener) { superFactory.setFormSubmissionListener(listener); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |