Thursday, April 13, 2006

XSL-FO Image Scaling

To render images in PDF documents I stepped over the problem of image scaling. If an image is too big to fit within the page width, it should be scaled down, otherwise it should stay in its original size.

With we get an image small enough to fit on a paper page, but smaller images are zoomed to 10cm width as well :( . So I could determin the image size for the meta information within the cosmos and then use the values to explicitly specify the content-width only if needed. With the small ImageInfo class I could even get the information without building an AWT dependency.

Then I've found this in the Google Cache (the site seems to be offline):

----

by G. Ken Holman

>Is it possible to scale images so that images that would run off the
>page are scaled to fit, while smaller images retain their existing
>size.

The pattern I've seen used is:

width="100%" content-width="scale-to-fit"
scaling="uniform"
content-height="100%"/>

or, if you want to limit by height instead of by width:

height="100%" content-height="scale-to-fit"
scaling="uniform"
content-width="100%"/>

When images are smaller than the dimension changing specification of the content dimension using "scale-to-fit", the image is considered to already fit. If the image is larger than the given dimension, that dimension is reduced to fit to the viewport (defined by height= or width=, in the above examples, the use of 100% specifies the viewport to be the full dimension available, you have to choose one of height or width to be the governing dimension since specifying both won't result in proper scaling).

The scaling="uniform" ensures that the other image dimension is relatively scaled so as to not disturb the aspect ratio.

Finally, the explicit specification of the other image dimension to 100% ensures that the governing content dimension specification does not distort the content's other dimension ... so images that are smaller than the governing dimension do not get stretched to 100% of that dimension's available size.

I hope the explanation can be understood, and I would welcome anyone else's wording of what I've tried to say above ... all I know is that I learned the pattern from somewhere and I understand what it is doing and it has worked for me ... but I have to wave my arms to convey my thoughts on this.

----