pdf文件之itextpdf操作实例

需求分析

1、需要创建一个pdf文件,包含文件的基本属性

2、文件需要包含附件,通过点击链接直接打开

3、生成的pdf文件不能直接修改(需要输入密码)

4、pdf文件需要有文字或图片水印

准备jar包

itextpdf-5.5.9.jar

itext-xtra-5.5.9.jar

itext-pdfa-5.5.9.jar

commons-imaging-1.0-SNAPSHOT.jar

commons-io-2.4.jar

xmlworker-5.5.9.jar

slf4j-log4j12-1.7.18.jar

slf4j-api-1.7.18.jar

log4j-1.2.17.jar

bcprov-jdk15on-1.47.jar

开始编码

声明变量

    static String pdfFile = "results/pdf文件.pdf";
    static String attchFile1 = "file/附件1.txt";
    static String attchFile2 = "file/附件2.zip";
    static String ownerPassword = "abcdefg1234567";
    static String stamperText = "pdf文件测试";

创建临时pdf文件

      File tmpFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), ".tmp");
        Document document = new Document();
        PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(tmpFile));

添加pdf文件属性

        document.open();//操作前一定要先打开文档
        //头部信息
        document.addTitle("文件");
        document.addAuthor("*******");
        document.addCreationDate();

准备中文字体(如果内容中没有中文可以忽略)

        //字体
        BaseFont songTtf = BaseFont.createFont("songti.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        Font sf = new Font(songTtf, 12);

添加内容

       //段落
     document.add(new Paragraph("我是一个中文的段落!",sf));
    //块 document.add(
new Chunk("我只是字符块",sf));     //附件 attchDesc.add(new Chunk("附件",sf)); PdfAnnotation annotation = PdfAnnotation.createFileAttachment(pdfWriter, null, attchFile1, null, attchFile1,attchFile1); Chunk chunk = new Chunk(" ",sf); chunk.setAnnotation(annotation); attchDesc.add(chunk);

文档加密并将临时文件转为正式文件

    //文档创建后设置添加密码
        PdfReader reader = new PdfReader(tmpFile.getAbsolutePath());
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(pdfFile));
        //加密
        stamper.setEncryption(null, ownerPassword.getBytes(), PdfWriter.ALLOW_MODIFY_CONTENTS, PdfWriter.STANDARD_ENCRYPTION_128);
        

添加文字水印

        //加文字水印
        int pages = reader.getNumberOfPages();
        PdfContentByte over = null;
        for (int i = 1; i <= pages; i++) {
            over = stamper.getUnderContent(i);  
            over.beginText(); 
            over.setRGBColorFill(245,245,245);
            over.setFontAndSize(songTtf, 18);
            over.setTextMatrix(30, 30);
            for (int x = 0; x < 3; x++) {
                for (int y = 0; y < 4; y++) {
                    over.showTextAligned(Element.ALIGN_LEFT, stamperText, x*250, y*240+x*100, 45);  
                }
            }
        }

添加图片水印

        //加图片水印
        Image image = Image.getInstance("file/logo.png");
        image.scaleAbsoluteWidth(50);
        image.scaleAbsoluteHeight(50);
        image.setAbsolutePosition(500, 780);
        over.addImage(image);
        over.endText(); 
        stamper.close();
        reader.close();

 添加图片

try (ByteArrayOutputStream byteArray = new ByteArrayOutputStream();){
            Document document = new Document();
            PdfWriter.getInstance(document, byteArray);
            document.open();
            float maxWith = 500;// 图片最大宽度
            // 插入图片
            List<String>  imgUrls = new ArrayList<>();
            imgUrls.add("ftcar.jpeg");
            imgUrls.add("fli.jpg");
            imgUrls.add("fli.jpeg");
            for(String imgUrl : imgUrls){
                Image jpeg = PngImage.getImage (FileUtil.readBytes(imgUrl));
                jpeg.setAlignment(Image.MIDDLE);
                float width = jpeg.getWidth();
                float height = jpeg.getHeight();
                // 等比例缩小
                if (width>maxWith){
                    jpeg.scaleAbsoluteWidth(maxWith);
                    jpeg.scaleAbsoluteHeight(height*maxWith/width);
                }
                document.add(jpeg);
            }
            document.close();
            // 存入文件
            File file = new File("/Users/sanxing/Downloads/pdf文件1.pdf");
            file.createNewFile();
            byteArray.writeTo(new FileOutputStream(file));
        }    

  

posted @ 2016-07-04 15:25  mvilplss  阅读(2999)  评论(0编辑  收藏  举报