Posted by a ceTe Software moderator
Hello,
In the following line of code use -dim.getLeftMargin() as x co-ordinate and -dim.getTopMargin() as y co-ordinate to the rectangle correctly.
final Rectangle pageRec = new Rectangle(-dim.getLeftMargin(), -dim.getTopMargin() ,dim.getWidth() - 1, dim.getHeight() - 1 );
Regardless of what the margins are, if you want to draw a rectangle along the page dimensions, you would want to offset the x co-ordinate by the value of the left margin and y co-ordinate by the value of the top margin. Here is the modified code:
// Create a page dimensions object and set the margins
PageDimensions dimensions = new PageDimensions( PageSize.LETTER, PageOrientation.PORTRAIT );
dimensions.setBottomMargin( 10 );
dimensions.setTopMargin( 20 );
dimensions.setLeftMargin( 25 );
dimensions.setRightMargin( 65 );
// Create a page using a page dimensions object and add it to the document
Page page = new Page( dimensions );
document.getPages().add( page );
final PageDimensions dim = page.getDimensions();
// reduce the height and width by 1 point to ensure the line does not fall outside the
// visible portion of the page.
final Rectangle pageRec = new Rectangle( -dim.getLeftMargin(), -dim.getTopMargin() ,dim.getWidth() - 1, dim.getHeight() - 1 );
final Dimensions body = dim.getBody();
final Rectangle bodyRec = new Rectangle( 0, 0, body.getWidth(), body.getHeight() );
page.getElements().add( pageRec );
page.getElements().add( bodyRec );
//layout grid.
page.getElements().add(new LayoutGrid());
document.getPages().add( page );
Moreover, if your goal is to determine proper location of the page elements while you build the PDF, we have a page element called
LayoutGrid that places a grid within the page body to help visualize the location of page elements.
Thanks,
ceTe Software Support Team.