当内容太大时,Java PDF文档边距重叠

当内容太大时,Java PDF文档边距重叠,java,image-processing,itext,document,Java,Image Processing,Itext,Document,我正在使用iText将图像转换为pdf文档。 当我给图像一个比文档本身更大的自定义大小时,我遇到了麻烦 在执行doc.open()之前,我设置了如下边距 doc.setMargins(marginLeft、marginRight、marginTop、marginBottom) 当我使用我的fit方法时,这就像一个符咒: // scale scaledAwtImage = new BufferedImage(scaledWidth, scaledHeight, bufferedImageType)

我正在使用iText将图像转换为pdf文档。 当我给图像一个比文档本身更大的自定义大小时,我遇到了麻烦

在执行
doc.open()
之前,我设置了如下边距
doc.setMargins(marginLeft、marginRight、marginTop、marginBottom)

当我使用我的
fit
方法时,这就像一个符咒:

// scale
scaledAwtImage = new BufferedImage(scaledWidth, scaledHeight, bufferedImageType);
// instantiate
image = instantiateImage(awtImage, scaledAwtImage, scaledWidth, scaledHeight);
setAutoRotate(image);
// scaleWithMargins
float targetWidth = doc.getPageSize().getWidth() - mmToUnit(Float.parseFloat(marginLeft) + Float.parseFloat(marginRight));
float targetHeight = doc.getPageSize().getHeight() - mmToUnit(Float.parseFloat(marginBottom) + Float.parseFloat(marginTop));
image.scaleToFit(targetWidth, targetHeight);
可能是因为
image.scaleToFit()
。下面是我遇到问题的代码。如您所见,右边距将被图像覆盖。我不能在这里使用
image.scaleToFit()
,因为我想保留自定义尺寸。有人有主意吗

// printWidth
if(printWidth != null && !printWidth.isEmpty() ){
   scaledWidth = (int) mmToUnit(printWidth);
}
// printHeight
if(printHeight != null && !printHeight.isEmpty() ){
   scaledHeight = (int) mmToUnit(printHeight);
}
scaledAwtImage = new BufferedImage(scaledWidth, scaledHeight, bufferedImageType);
//instantiate
image = instantiateImage(awtImage,scaledAwtImage, scaledWidth, scaledHeight);

编辑

忘记发布我的
实例化图像()
方法以获取更多信息

private Image instantiateImage(BufferedImage awtImage, BufferedImage scaledAwtImage, int scaledWidth, int scaledHeight) throws IOException, BadElementException {
 Graphics2D g = scaledAwtImage.createGraphics();
 g.drawImage(awtImage, 0, 0, scaledWidth, scaledHeight, null);
 g.dispose();

 ByteArrayOutputStream bout = new ByteArrayOutputStream();
 ImageIO.write(scaledAwtImage, "jpeg", bout);
 byte[] imageBytes = bout.toByteArray();

 Image image = Image.getInstance(imageBytes);
 return image;
}

你说你“想保留定制尺寸”。如果这些自定义大小对于文档正文区域来说太大,则会进入页边距。我看到的唯一选择是放大文档正文区域,例如,使用较小的页边距或更宽的页面格式(例如,横向而不是纵向,或实际上更大)。因此不可能用页边距的大小剪切图像?您可以将其剪切,但它不再具有自定义大小,因为,因为它被切断了。为了打印的目的(这就是代码的目的),我需要强制这些边距。这听起来很愚蠢,但分析说这是必需的:-)我和分析员进行了一次快速的交谈,我说服他将图像宽度/高度强制为文档的最大大小。所以我的问题实际上解决了