embaded images are breaked between pdf pages in fl

2019-05-18 14:27发布

问题:

I have some problem with images (all images are embedded in html as base64 strings). I use css

img {page-break-inside: avoid;}

and it helps but not always. In some cases the same image can be processed correctly where in other situation is divided between pages.

It depends form many factors, examples:

  • image is assigned as block element
  • previous images are or are not block elements
  • there is some big image before divided one

I also noticed that if the problem occurred at least once than all images to the end of document can be broken when they don't fit on the page.

I'm using this approach with RepleacedElementFactory for embedded images: http://www.intelligrape.com/blog/using-data-urls-for-embedding-images-in-flying-saucer-generated-pdfs/

the only difference is that i'm changing the size a bit

public ReplacedElement createReplacedElement(LayoutContext c, BlockBox box, UserAgentCallback uac, int cssWidth, int cssHeight) {
 Element e = box.getElement();
 if (e == null) {
     return null;
 }
 String nodeName = e.getNodeName();
 if (nodeName.equals("img")) {
     String attribute = e.getAttribute("src");
     FSImage fsImage;
     try {
         fsImage = buildImage(attribute, uac, cssWidth, cssHeight);
     } catch (BadElementException e1) {
         fsImage = null;
     } catch (IOException e1) {
         fsImage = null;
     }
     if (fsImage != null) {
         if(cssWidth == -1 && cssHeight == -1)
         {
            int factor = _sharedContext.getDotsPerPixel();
            int width = fsImage.getWidth();
            int fWidth =  width * factor;
            fsImage.scale(fWidth, -1);
         }
         if(cssWidth == -1 || cssHeight == -1)
         {
            fsImage.scale(cssWidth, cssHeight);
         }
         return new ITextImageElement(fsImage);
     }
 }
 return null;

}

the difference is I've added this block:

if(cssWidth == -1 && cssHeight == -1)
         {
            int factor = _sharedContext.getDotsPerPixel();
            int width = fsImage.getWidth();
            int fWidth =  width * factor;
            fsImage.scale(fWidth, -1);
         }

to give proper size if it is not given by css. Without it I had the problem with all images be really tinny.

I guess there is some problem with calculating the real size (height) of the picture but I really don't have idea what else can i change to guarantee that images would never break between pages.

Please help.

回答1:

page-break-inside only applies to block-level elements but img is an inline-block element. Try using img {display: block; page-break-inside: avoid;} and see if it works.