如何使用Java旋转PDF文档中的图像?

如何使用Java旋转PDF文档中的图像?

注:iText开发环境设置,下载iText7 jar(社区版:http://github.com/itext/itext7/releases/tag/7.0.4 ) ,创建一个工程:java_itext,并将下载的itext7 jar包和slf4j( http://www.slf4j.org/download.html )工具包添加到构建路径中。项目结构如下图所示 -

以下是使用Java旋转PDF文档中的图像的程序。

package com.zaixian;

import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.color.DeviceGray;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.property.TextAlignment;

public class RotatingImage {
    public static void main(String args[]) throws Exception {

        // Creating a PdfDocument object
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter("rotatingImage.pdf"));

        // Creating a Document object
        Document doc = new Document(pdfDoc);

        // Creating an Image
        Image image = new Image(ImageDataFactory.create("zhonglou.jpg"));
        image.scaleToFit(400, 700);

        // Creating template
        PdfFormXObject template = new PdfFormXObject(
                new Rectangle(image.getImageScaledWidth(), image.getImageScaledHeight()));

        Canvas canvas = new Canvas(template, pdfDoc).add(image);
        String watermark = "Welcome to xuhuhu.com";
        canvas.setFontColor(DeviceGray.RED).showTextAligned(watermark, 100, 160, TextAlignment.CENTER);

        // Adding template to document
        Image image1 = new Image(template);
        image1.setRotationAngle(45);    
        doc.add(image1);

        // Closing the document
        doc.close();
        System.out.println("RotatingImage successfully...");
    }
}

执行上面示例代码,得到以下结果 -

RotatingImage successfully...

输出文件内容如下所示 -


上一篇: Java iText示例 下一篇:无