iText: PdfContentByte.rectangle(Rectangle) does no

2019-09-05 22:16发布

问题:

I am using iText 2.1.7 and I am trying to draw a simple rectangle to my document. The below block of code works as expected and draws a rectangle that covers the entire page not including the page margins.

Document document = new Document(PageSize.A4.rotate());
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte canvas = writer.getDirectContent();
Rectangle pageDimensions = writer.getPageSize();

canvas.saveState();
canvas.rectangle(
        pageDimensions.getLeft(marginLeft),
        pageDimensions.getBottom(marginBottom),
        pageDimensions.getRight(marginRight),
        pageDimensions.getTop(marginTop));
canvas.setColorStroke(Color.BLACK);
canvas.stroke();
canvas.restoreState();

document.close();

However, if I change the block of canvas code slightly such that I am defining the rectangle outside of the PdfContentByte, then my code generates a blank page.

...
Rectangle marginBox = new Rectangle(
        pageDimensions.getLeft(marginLeft),
        pageDimensions.getBottom(marginBottom),
        pageDimensions.getRight(marginRight),
        pageDimensions.getTop(marginTop));
canvas.saveState();
canvas.rectangle(marginBox);
canvas.setColorStroke(Color.BLACK);
canvas.stroke();
canvas.restoreState();
...

Is this not the intended usage of the PdfContentByte.rectangle(Rectangle) method?? Ideally, I would like define Rectangles (along with their border colors and widths) in a way that is not so tightly coupled with the directContent and have the freedom to add them to the directContent at a later point.

回答1:

First, I feel obliged to say that you're using a version of iText you should no longer use. See http://itextpdf.com/salesfaq for more info.

As for your question, you are making some assumptions that are wrong. For instance: when you use the Rectangle object, using the stroke() operator doesn't make sense as the rectangle() method that takes a Rectangle as parameter strokes the path (as opposed to the method that takes 4 float values).

// This draws and strokes the path:
canvas.rectangle(marginBox);
// There is no path to stroke anymore:
canvas.setColorStroke(Color.BLACK);
canvas.stroke();

The rectangle() method that takes a Rectangle won't do anything if no border and no border width have been defined for the Rectangle. In other words, you need something like this:

Rectangle rect = new Rectangle(36, 36, 559, 806);
rect.setBorder(Rectangle.BOX);
rect.setBorderWidth(2);
canvas.rectangle(rect);

If no borders are defined, nor a width greater than 0 for the border, it is assumed that there is no border.



标签: itext