嗨,我们如何在iText 7中调整图像大小。我现在在itext7中找不到用于裁剪图像的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
发布于 2017-09-08 20:03:36
假设您有这样一幅图像,尺寸为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语言中,表单XObject通常称为PdfTemplate
。
我们使用此template
创建一个Canvas
对象,并将图像添加到canvas
中。
最后,我们使用模板创建另一个Image
。Canvas
操作将向该template
添加完整的图像,但它将被裁剪为rectangle
的大小。
您可以将此croppedImage
添加到文档中。
https://stackoverflow.com/questions/46114654
复制相似问题