Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iTextSharp - draw rectangle - border width issue

Tags:

c#

itext

here's a simple code:

var w = Utilities.MillimetersToPoints(420);
var h = Utilities.MillimetersToPoints(210);

var doc1 = new Document(new Rectangle(w, h));

PdfWriter writer = PdfWriter.GetInstance(doc1, new FileStream("Doc1.pdf", FileMode.Create));

doc1.Open();

PdfContentByte cb = writer.DirectContent;

var rect = new Rectangle(200, 200, 100, 100);

and now, if I do the following:

cb.Rectangle(200, 200, 100, 100);
cb.Stroke();

then I see the rectangle. But I need to set its border width, so I do

 rect.BorderWidth = 5;
 rect.BorderColor = new BaseColor(0,0,0);

 cb.Rectangle(rect);
 cb.Stroke();

and now the rectangle is not visible. Why ?

like image 916
Tony Avatar asked Oct 14 '25 14:10

Tony


1 Answers

The Rectangle() method on PdfContentByte has a couple of overloads and they behave quite differently depending on what you pass in.

Your first example is using the very simple overload that just takes 4 floats. If you look at the source for that you'll see that beyond some sanity checking it just writes those coordinates directly to the PDF stream and no actual Rectangle objects are created in the process. Later when you call Stroke() iText writes the stroke command to the stream and that's it. When a PDF renderer (like Adobe's) actually parses the stroke command it looks backwards in the buffer and sees the coordinates that it needs to stroke and performs the action.

Your second example uses the much more complex overload that you can see here which takes an actual Rectangle object. Besides representing four points in space a Rectangle has concepts like background colors and borders and, most importantly for you, these borders can be drawn per side and you need to tell it which sides to draw on.

For instance, for just left and right you'd do:

var rect = new iTextSharp.text.Rectangle(200, 200, 100, 100);
rect.Border = iTextSharp.text.Rectangle.LEFT_BORDER | iTextSharp.text.Rectangle.RIGHT_BORDER; 
rect.BorderWidth = 5;
rect.BorderColor = new BaseColor(0, 0, 0);
cb.Rectangle(rect);

And for all borders you'd change it to:

rect.Border = iTextSharp.text.Rectangle.BOX;

Also, when calling this overload it is actually incorrect to call Stroke() immediately after because this overload takes care of that for you (and might have done it more than once, actually.)

like image 119
Chris Haas Avatar answered Oct 17 '25 04:10

Chris Haas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!