try
{
Graphics2D graphics2D = (Graphics2D)graphics;
PDPage page = document.getPage(pageIndex);
PDRectangle cropBox = getRotatedCropBox(page);
// the imageable area is the area within the page margins
final double imageableWidth = pageFormat.getImageableWidth();
final double imageableHeight = pageFormat.getImageableHeight();
double scale = 1;
if (scaling != Scaling.ACTUAL_SIZE)
{
// scale to fit
double scaleX = imageableWidth / cropBox.getWidth();
double scaleY = imageableHeight / cropBox.getHeight();
scale = Math.min(scaleX, scaleY);
// only shrink to fit when enabled
if (scale > 1 && scaling == Scaling.SHRINK_TO_FIT)
{
scale = 1;
}
}
// set the graphics origin to the origin of the imageable area (i.e the margins)
graphics2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
// center on page
graphics2D.translate((imageableWidth - cropBox.getWidth() * scale) / 2,
(imageableHeight - cropBox.getHeight() * scale) / 2);
// rasterize to bitmap (optional)
Graphics2D printerGraphics = null;
BufferedImage image = null;
if (dpi > 0)
{
float dpiScale = dpi / 72;
image = new BufferedImage((int)(imageableWidth * dpiScale), (int)(imageableHeight * dpiScale),
BufferedImage.TYPE_INT_ARGB);
printerGraphics = graphics2D;
graphics2D = image.createGraphics();
// rescale
printerGraphics.scale(scale / dpiScale, scale / dpiScale);
scale = dpiScale;
}
// draw to graphics using PDFRender
AffineTransform transform = (AffineTransform)graphics2D.getTransform().clone();
graphics2D.setBackground(Color.WHITE);
renderer.renderPageToGraphics(pageIndex, graphics2D, (float)scale);
// draw crop box
if (showPageBorder)
{
graphics2D.setTransform(transform);
graphics2D.setClip(0, 0, (int)imageableWidth, (int)imageableHeight);
graphics2D.scale(scale, scale);
graphics2D.setColor(Color.GRAY);
graphics2D.setStroke(new BasicStroke(0.5f));
graphics.drawRect(0, 0, (int)cropBox.getWidth(), (int)cropBox.getHeight());
}
// draw rasterized bitmap (optional)
if (printerGraphics != null)
{