How to insert a iTextSharp.text.Rectangle rectangle at an absolute position?

10,784

In a comment the OP says

the Hyperlink rectangle is ALWAYS at the bottom-left of the generated PDF no matter how I change the x & y values in the Rectangle arguments (int x, int y, int width, int height).

Here the mistake becomes apparent, the OP assumes the third and fourth parameter of the Rectangle constructor to be the width and height. This is not the case, cf. the documented source code of the Rectangle constructors:

/// <summary>
/// Constructs a Rectangle-object.
/// </summary>
/// <param name="llx">lower left x</param>
/// <param name="lly">lower left y</param>
/// <param name="urx">upper right x</param>
/// <param name="ury">upper right y</param>
public Rectangle(float llx, float lly, float urx, float ury)

...

/**
 * Constructs a <CODE>Rectangle</CODE>-object.
 *
 * @param llx   lower left x
 * @param lly   lower left y
 * @param urx   upper right x
 * @param ury   upper right y
 * @param rotation the rotation (0, 90, 180, or 270)
 * @since iText 5.0.6
 */
public Rectangle(float llx, float lly, float urx, float ury, int rotation)

and cf. also the comment in the OP's own code:

// (lower-left-x, lower-left-y, upper-right-x (llx + width), upper-right-y (lly + height), rotation angle 

The third and fourth parameter are the coordinates of a second point. The rectangle location and size is determined by the diagonal from (llx, lly) to (urx, ury).

Furthermore, in spite of the variable names and descriptions iTextSharp does not enforce the first point to be in the lower left and the second in the upper right; if the second is in the lower right or lower left, so be it...

Thus, as the OP only changed the first two parameters, the second point remained at (100, 15) which usually is very near the page bottom and quite near to the page left border.

He should try something like instead:

iTextSharp.text.Rectangle rectangle = new Rectangle(510, 510, 600, 515, 0);  
Share:
10,784
Shaning Yu
Author by

Shaning Yu

Updated on June 07, 2022

Comments

  • Shaning Yu
    Shaning Yu about 2 years

    Using the code below, the rectangle inserted is at the bottom-left of the page. How can a iTextSharp.text.Rectangle rectangle be inserted at an absolute position? Thanks.

    iTextSharp.text.Rectangle rectangle = new Rectangle(10, 10, 100, 15, 0);  
    // (lower-left-x, lower-left-y, upper-right-x (llx + width), upper-right-y (lly + height), rotation angle 
    rectangle.BorderColor = BaseColor.WHITE;
    rectangle.BackgroundColor = BaseColor.YELLOW;
    overContent.Rectangle(rectangle);
    //stamper.Close();
    PdfAnnotation annotation = PdfAnnotation.CreateLink(
                            stamper.Writer, rectangle, PdfAnnotation.HIGHLIGHT_INVERT,
                            new PdfAction("http://itextpdf.com/"));
    stamper.AddAnnotation(annotation, 1);