开发者

Problem inserting watermark in a pdf file with varying page-size in iText

When I am trying to add a image as watermark at absolute position while absoluteX=10f and absolute y = rectangle.getLeft()+ (rectangle.getWidth()-image.getPlainWidth());

For some page-sizes, the image does no开发者_运维技巧t get added at absoluteX=10f have to increase it to 300f or more. How to correctly fetch the absolute position for the left.


You need to check the page's crop box and position your text relative to that. Note also that the bottom left corner need not be 0,0, and that pages can be rotated.

I've seen landscape pages generated three ways:

11"x8.5"

8.5x11 @ 90 degrees 8.5x11 @ 270 degrees

(fortunately I've never seen 11x8.5 @ 180, or I might have to Severely Harm someone on general principles)

"Portrait" pages are nigh-universally generated as 8.5"x11" (or whatever your measurements might be). In my > a decade working with PDF, I have yet to see a rotated portrait page. Legal, but stupid.

So, to get your correct bbox and rotate your text into position, you'd need something like:

final double TOP_OFFSET = 10.0 + IMAGE_HEIGHT; // or whatever
final double RIGHT_OFFSET = 15.0 + IMAGE_WIDTH;

PdfReader reader = new PdfReader( path );
PdfStamper stamper = new PdfStamper( reader, outStream );

Rectangle cropBox = reader.getCropBox( 1 );
int rotation = reader.getPageRotation( 1 );
PdfContentByte content = stamper.getOverContent( 1 ); // first page

AffineTransform transform;
double xOffset, yOffset;
switch( rotation ) {
  case 0:
    xOffset = cropBox.getRight() - RIGHT_OFFSET;
    yOffset = cropBox.getTop() - TOP_OFFSET;
    transform = AffineTransform.getTranslateInstance( xOffset, yOffset );
    break;
  case 90:
    // some other transformations here
    break;
  case 180:
    // and here
    break;
  case 270:
    // and here.
    break;
};

content.transform( transform );
content.addImage( waterMarkImage );

stamper.close();

I often find I have to blow the page size up by Quite A Bit in order to find out where I'm going wrong with my transformations. Say +1000 to each border on the media box (and crop if present).

PdfDictionary pageDict = reader.getPageN(1);
PdfArray boxes[] = {pageDict.getAsArray( PdfName.MEDIABOX ), pageDict.getAsArray( PdfName.CROPBOX ) };
float mods[] = {-1000, -1000, 1000, 1000 }
for (int i = 0; i < boxes.length; ++i) {
  if (boxes[i] == null)
    continue; // crop boxes are optional
  for (int j = 0; j < 4; ++j) {
    PdfNumber curVal = boxes[i].getAsNumber(j);
    PdfNumber newVal = curVal.getFloat() + mods[j];
    boxes[i].set( j, newVal );
  }
}

Now, when you screw up your transformations (I inevitably do), you'll be able to see HOW you screwed up, and fix it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜