嗨,我们如何在 iText 7 中调整图像大小。 我现在无法在 itext 7 中找到用于裁剪图像的 PDFTemplate。 。
public Image cropImage(PdfWriter writer, Image image, float leftReduction, float rightReduction, float topReduction, float bottomReduction) throws DocumentException {
float width = image.getScaledWidth();
float height = image.getScaledHeight();
PdfTemplate template = writer.getDirectContent().createTemplate(
width - leftReduction - rightReduction,
height - topReduction - bottomReduction);
template.addImage(image,
width, 0, 0,
height, -leftReduction, -bottomReduction);
return Image.getInstance(template);
}
这用于 itext 5
最佳答案
假设您有此图像,尺寸为 900 x 1200 像素:
但是您只想显示该图像的一部分(例如乒乓球):
然后您可以使用此 iText 7 代码:
PdfDocument pdf = new PdfDocument(new PdfWriter("cropimage.pdf"));
Document document = new Document(pdf);
Image image = new Image(ImageDataFactory.create(imagePath));
image.setFixedPosition(-20, -320);
Rectangle rectangle = new Rectangle(300, 300);
PdfFormXObject template = new PdfFormXObject(rectangle);
Canvas canvas = new Canvas(template, pdf);
canvas.add(image);
Image croppedImage = new Image(template);
document.add(croppedImage);
document.close();
我们使用完整图像创建一个 Image
实例,并设置固定位置,从左侧切掉 20 个像素,从底部切掉 320 个像素。
我们创建一个 300 x 300 用户单元的矩形。这定义了裁剪图像的大小。
我们使用这个矩形创建一个PdfFormXObject
。在 iText 5 语言中,Form XObject 过去被命名为 PdfTemplate
。
我们使用此模板
创建一个Canvas
对象,并将图像添加到canvas
。
最后,我们使用模板创建另一个Image
。 Canvas
操作会将完整图像添加到该模板
,但它将被裁剪为矩形
的大小。
您可以将此 croppedImage
添加到文档中。
关于Itext7 - 裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46114654/