MENU

在 iText 中剪裁图片

• March 13, 2019 • Read: 9834 • Codes

Java 中使用 iText 在创建 PDF 文件的时候,基于各种需求,我们可能需要将图片进行裁剪后,添加到 PDF 中。使用 BufferedImage 等直接对图片进行剪裁然后添加的方式就不说了。这里讲一下通过 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);
}

参数分别是四边需要剪裁的数量,以上。

参考

Last Modified: January 31, 2023
Archives QR Code Tip
QR Code for this page
Tipping QR Code
Leave a Comment

5 Comments
  1. 111111 111111

    11111

  2. oooo oooo

    oooooo

  3. 我的天天,你竟然更新了!

    1. @JinF也就一年没更新嘛,问题不大::quyin:1huaji::