本文介绍了iTextSharp - 绘制矩形 - 边框宽度问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的代码:

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 ?

推荐答案

有几个重载,它们的行为完全不同,具体取决于你传入的内容。

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

你的第一个例子是使用非常简单的重载只需4个花车。如果你看一下您将看到,除了一些完整性检查之外,它只是将这些坐标直接写入PDF流,并且没有创建实际的 Rectangle 对象。处理。稍后当你调用 Stroke() iText将stroke命令写入流中就是这样。当PDF渲染器(如Adobe的)实际解析笔触命令时,它会在缓冲区中向后看,并看到它需要描边的坐标并执行操作。

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.

你的第二个示例使用更复杂的重载,您可以,其中包含一个实际的 Rectangle 对象。除了代表空间中的四个点之外,矩形还有背景颜色和边框等概念,最重要的是,这些边框可以每边绘制 你需要告诉它哪些方面可以使用

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;

此外,调用此过载时,调用 Stroke()实际上是不正确的紧接着之后因为这个重载会为你解决这个问题(实际上可能不止一次。)

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.)

这篇关于iTextSharp - 绘制矩形 - 边框宽度问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 08:03