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.