Itext旋转PDF内容的方法

前不久使用Freemarker+Flying sauser +Itext 整合生成PDF,因打印要求,需要旋转PDF里的内容,使用过Pdf-renderer, PDFBox 和JPedal转PDF为图片再旋转图片的方式,效果不佳,被项目组否掉,几经周折,终于找到真正旋转PDF内容的方法。
方法如下:

import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfNumber;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSmartCopy;

public class PdfRotate {



    public static void main(String[] args) throws Exception {
        PdfReader reader = new PdfReader("d:\\1.pdf"); // 读取源文件 
        Document document = new Document(); // 建立文档
        /*
        切勿将源文件和输出文件使用一个路径,否则会出现异常:
        Exception in thread "main" java.io.FileNotFoundException: d:\1.pdf 
        (请求的操作无法在使用用户映射区域打开的文件上执行。)
        */
        PdfCopy p = new PdfSmartCopy(document,new FileOutputStream("d:\\2.pdf")); // 生成的目标PDF文件
        document.open();
        int n = reader.getNumberOfPages(); // 获取源文件的页数
        PdfDictionary pd;
        for(int j=1;j<=n;j++){
            pd = reader.getPageN(j); 
            pd.put(PdfName.ROTATE, new PdfNumber(90)); // 顺时针旋转90°
        }
        for (int page = 0; page < n; ) {
            p.addPage(p.getImportedPage(reader, ++page)); 
        }
        document.close();   
    }
}

注意:本方法需要Itextpdf5.0以上版本支持(我使用的是itextpdf-5.5.5.jar),目前大多数项目中使用Freemarker+Flying sauser +Itext 整合生成PDF,均采用iText-2.0.8.jar+core-renderer.jar,关键点在于切勿将项目中iText-2.0.8.jar升级换为itextpdf-5.5.5.jar,否则将导致core-renderer.jar包无法正常使用。同时引入iText-2.0.8.jar和itextpdf-5.5.5.jar。

Jar包下载:
iText-2.0.8.jar
core-renderer.jar
itextpdf-5.5.5.jar

参考:http://itextpdf.com/examples/iia.php?id=232

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值