工具类:
1 package test; 2 3 import java.io.IOException ; 4 import org.w3c.dom.Element ; 5 import org.xhtmlrenderer.extend.FSImage ; 6 import org.xhtmlrenderer.extend.ReplacedElement ; 7 import org.xhtmlrenderer.extend.ReplacedElementFactory ; 8 import org.xhtmlrenderer.extend.UserAgentCallback ; 9 import org.xhtmlrenderer.layout.LayoutContext ; 10 import org.xhtmlrenderer.pdf.ITextFSImage ; 11 import org.xhtmlrenderer.pdf.ITextImageElement ; 12 import org.xhtmlrenderer.render.BlockBox ; 13 import org.xhtmlrenderer.simple.extend.FormSubmissionListener ; 14 import com.lowagie.text.BadElementException ; 15 import com.lowagie.text.Image ; 16 import com.lowagie.text.pdf.codec.Base64 ; 17 18 19 20 public class B64ImgReplacedElementFactory implements ReplacedElementFactory { 21 22 /** 23 * 实现createReplacedElement 替换html中的Img标签 24 * 25 * @param c 上下文 26 * @param box 盒子 27 * @param uac 回调 28 * @param cssWidth css宽 29 * @param cssHeight css高 30 * @return ReplacedElement 31 */ 32 public ReplacedElement createReplacedElement(LayoutContext c, BlockBox box, UserAgentCallback uac, 33 int cssWidth, int cssHeight) { 34 Element e = box.getElement(); 35 if (e == null) { 36 return null; 37 } 38 String nodeName = e.getNodeName(); 39 // 找到img标签 40 if (nodeName.equals("img")) { 41 String attribute = e.getAttribute("src"); 42 FSImage fsImage; 43 try { 44 // 生成itext图像 45 fsImage = buildImage(attribute, uac); 46 } catch (BadElementException e1) { 47 fsImage = null; 48 } catch (IOException e1) { 49 fsImage = null; 50 } 51 if (fsImage != null) { 52 // 对图像进行缩放 53 if (cssWidth != -1 || cssHeight != -1) { 54 fsImage.scale(cssWidth, cssHeight); 55 } 56 return new ITextImageElement(fsImage); 57 } 58 } 59 60 return null; 61 } 62 63 /** 64 * 将base64编码解码并生成itext图像 65 * 66 * @param srcAttr 属性 67 * @param uac 回调 68 * @return FSImage 69 * @throws IOException io异常 70 * @throws BadElementException BadElementException 71 */ 72 protected FSImage buildImage(String srcAttr, UserAgentCallback uac) throws IOException, 73 BadElementException { 74 FSImage fsImage; 75 if (srcAttr.startsWith("data:image/")) { 76 String b64encoded = srcAttr.substring(srcAttr.indexOf("base64,") + "base64,".length(), 77 srcAttr.length()); 78 // 解码 79 byte[] decodedBytes = Base64.decode(b64encoded); 80 81 fsImage = new ITextFSImage(Image.getInstance(decodedBytes)); 82 } else { 83 fsImage = uac.getImageResource(srcAttr).getImage(); 84 } 85 return fsImage; 86 } 87 88 89 /** 90 * 实现reset 91 */ 92 public void reset() { 93 } 94 95 96 @Override 97 public void remove(Element arg0) {} 98 99 @Override 100 public void setFormSubmissionListener(FormSubmissionListener arg0) {} 101 }
生成pdf时:
1 // 解决base64图片支持问题 2 sharedContext.setReplacedElementFactory(new B64ImgReplacedElementFactory()); 3 sharedContext.getTextRenderer().setSmoothingThreshold(0); 4 renderer.setDocumentFromString(strFileContent);