首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Itext7 -裁剪图像

Itext7 -裁剪图像
EN

Stack Overflow用户
提问于 2017-09-08 18:42:51
回答 1查看 1.1K关注 0票数 2

嗨,我们如何在iText 7中调整图像大小。我现在在itext7中找不到用于裁剪图像的PDFTemplate。。

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-08 20:03:36

假设您有这样一幅图像,尺寸为900 x 1200像素:

但您只想显示此图像的一部分(例如乒乓球):

然后,您可以使用以下iText 7代码:

代码语言:javascript
复制
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中。

最后,我们使用模板创建另一个ImageCanvas操作将向该template添加完整的图像,但它将被裁剪为rectangle的大小。

您可以将此croppedImage添加到文档中。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46114654

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档