ItextPdf 学习总结

一、开发环境搭建

创建一个项目,添加jar包:

  • 多需要的jar包
    itextpdf-5.2.1.jar
  • pom依赖包添加语句
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.2.1</version>
    </dependency>

二、代码实例

1. 生成pdf文件

public static void createPdf1() throws FileNotFoundException, DocumentException{
        // step 1:Create a document
        Document document = new Document();

        // step 2:Get a pdfWriter instance 
        PdfWriter.getInstance(document, new FileOutputStream("E://createSamplePdf1.pdf"));

        // step 3:Open the document
        document.open();

        // step 4:Add content
        document.add(new Paragraph("hello world!"));

        // step 5:Close the document
        document.close();
    }

2. 设置pdf文件的大小、背景色、版本、属性、边距

public static void createPdf2() throws FileNotFoundException, DocumentException{
        // step 1:Create page size
        Rectangle rect = new Rectangle(PageSize.B5.rotate());

        // step 2:Set background color
        rect.setBackgroundColor(BaseColor.ORANGE);      
        Document document = new Document(rect);

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E://createSamplePdf2.pdf"));

        // Set PDF version  
        writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);  
        // Set pdf passWord
//      writer.setEncryption("Hello".getBytes(), "World".getBytes(),PdfWriter.ALLOW_SCREENREADERS, PdfWriter.STANDARD_ENCRYPTION_128);   

        // Set document properties
//      document.addTitle("Title@sample");  
//      document.addAuthor("Author@rensanning");  
//      document.addSubject("Subject@iText sample");  
//      document.addKeywords("Keywords@iText");  
//      document.addCreator("Creator@iText");  

        // Set pdf margin
        document.setMargins(10, 20, 30, 40);

        // open pdf
        document.open();
        document.add(new Paragraph("hello world!"));
        document.close();
    }

3.生成新的一页

public static void createPdf3() throws DocumentException, FileNotFoundException{

        Document document = new Document();

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E://createSamplePdf3.pdf"));       

        document.open();
        document.add(new Paragraph("first page"));
        document.add(new Paragraph(Document.getVersion()));

        document.newPage();
        writer.setPageEmpty(false);

        document.add(new Paragraph("new page"));

        document.close();
    }

4.生成水印和背景图片

public static void createPdf4() throws IOException, DocumentException{
        PdfReader reader = new PdfReader("E://createSamplePdf3.pdf");
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("E://createSamplePdf4.pdf"));

        // Set waterMark image
        Image img = Image.getInstance("E://waterMark.jpg");
        img.setAbsolutePosition(200, 400);

        PdfContentByte under = stamper.getUnderContent(1);

        under.addImage(img);
        // Set waterMark image
        PdfContentByte over = stamper.getOverContent(2);

        over.beginText();

        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);

        over.setFontAndSize(bf, 18);  
        over.setTextMatrix(30, 30);  
        over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE", 230, 430, 45);  
        over.endText(); 

        // Set background image
        Image img2 = Image.getInstance("E://test.jpg");  
        img2.setAbsolutePosition(0, 0);  
        PdfContentByte under2 = stamper.getUnderContent(3);  
        under2.addImage(img2);  

        stamper.close();
        reader.close();
    }

5.使用chunk、phrase、paragragh、list创建pdf

public static void createPdf5() throws DocumentException, FileNotFoundException{
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("E://createSamplePdf5.pdf"));

        document.open();
        // Add chunk
        document.add(new Chunk("China"));
        document.add(new Chunk(" "));

        Font font = new Font(Font.FontFamily.HELVETICA,6,Font.BOLD,BaseColor.WHITE);
        Chunk id = new Chunk("chinese",font);

        id.setBackground(BaseColor.BLACK,1f,0.5f,1f,1.5f);
        id.setTextRise(6);

        document.add(id);
        document.add(Chunk.NEWLINE);

        document.add(new Chunk("Japan"));
        document.add(new Chunk(" "));
        Font font2 = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);  
        Chunk id2 = new Chunk("japanese", font2);  
        id2.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);  
        id2.setTextRise(6);  
        id2.setUnderline(0.2f, -2f);  
        document.add(id2);  
        document.add(Chunk.NEWLINE);  

        // Add phrase
        document.newPage();
        document.add(new Phrase("phrase page"));

        // Add first phrase
        Phrase director = new Phrase();
        Chunk name = new Chunk("China");

        name.setUnderline(0.2f, -2f);
        director.add(name);
        director.add(new Chunk(","));
        director.add(new Chunk(" "));
        director.add(new Chunk("chinese"));
        director.setLeading(24);
        document.add(director);

        // Add second phrase
        Phrase director2 = new Phrase();  
        Chunk name2 = new Chunk("Japan");  
        name2.setUnderline(0.2f, -2f);  
        director2.add(name2);  
        director2.add(new Chunk(","));  
        director2.add(new Chunk(" "));  
        director2.add(new Chunk("japanese"));  
        director2.setLeading(24);  
        document.add(director2);  

        // Add paragraph
        document.newPage();
        document.add(new Paragraph("Paragraph page"));

        Paragraph info = new Paragraph();

        info.add(new Chunk("China"));
        info.add(new Chunk("Chinese"));
        info.add(Chunk.NEWLINE);
        info.add(new Phrase("Japan"));
        info.add(new Phrase("japanese"));
        document.add(info);

        document.newPage();
        List list = new List(List.ORDERED);

        for(int i=0; i<10; i++){
            ListItem item = new ListItem(String.format("%s: %d movies", "country" + (i + 1), (i + 1) * 100), new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE));
            List movielist = new List(List.ORDERED,List.ALPHABETICAL);

            movielist.setLowercase(List.LOWERCASE);
            for(int j=0; j<5; j++){
                ListItem movieitem = new ListItem("Title"+(j+1));
                List directorlist = new List(List.UNORDERED);

                for(int k=0; k<3; k++){
                    directorlist.add(String.format("%s, %s", "Name1" + (k + 1), "Name2" + (k + 1)));  
                }
                movieitem.add(directorlist);  
                movielist.add(movieitem);               
            }
            item.add(movielist);  
            list.add(item);     
        }
        document.add(list);
        document.close();
    }

6.使用锚、chapter、section创建一个pdf文件

public static void createPdf6() throws DocumentException, MalformedURLException, IOException{
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("E://createSamplePdf6.pdf"));
        document.open();

        Paragraph country = new Paragraph();

        Anchor dest = new Anchor("china",new Font(Font.FontFamily.HELVETICA,14,Font.BOLD,BaseColor.BLUE));
        dest.setName("CN");
        dest.setReference("http://www.china.com");

        country.add(dest);
        country.add(String.format(": %d sites", 10000));
        document.add(country);

        document.newPage();
        Anchor toUS = new Anchor("Go to first page.", new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLUE));
        toUS.setReference("#CN");
        document.add(toUS);

        document.newPage();
        Image img = Image.getInstance("E://test.jpg");
        img.setAlignment(Image.LEFT | Image.TEXTWRAP);  
        img.setBorder(Image.BOX);  
        img.setBorderWidth(10);  
        img.setBorderColor(BaseColor.WHITE);  
        img.scaleToFit(1000, 72);//大小  
        img.setRotationDegrees(-30);//旋转  
        document.add(img); 

        document.newPage();  
        Paragraph title = new Paragraph("Title");  
        Chapter chapter = new Chapter(title, 1);  

        title = new Paragraph("Section A");  
        Section section = chapter.addSection(title);  
        section.setBookmarkTitle("bmk");  
        section.setIndentation(30);  
        section.setBookmarkOpen(false);  
        section.setNumberStyle(  
        Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);  

        Section subsection = section.addSection(new Paragraph("Sub Section A"));  
        subsection.setIndentationLeft(20);  
        subsection.setNumberDepth(1);  

        document.add(chapter);  

        document.close();       
    }

7.画图

public static void createPdf7() throws SystemException, DocumentException, FileNotFoundException{
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("E://createSamplePdf7.pdf"));
        document.open();

        document.add(new VerticalPositionMark() {         
            public void draw(PdfContentByte canvas, float llx, float lly,  
                    float urx, float ury, float y) {  
                canvas.beginText();  
                BaseFont bf = null;  
                try {  
                    bf = BaseFont.createFont(BaseFont.ZAPFDINGBATS, "", BaseFont.EMBEDDED);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
                canvas.setFontAndSize(bf, 12);  

                // LEFT  
                canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), llx - 10, y, 0);  
                // RIGHT  
                canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), urx + 10, y + 8, 180);  

                canvas.endText();  
            }  
        });  

        //直线  
        Paragraph p1 = new Paragraph("LEFT");  
        p1.add(new Chunk(new LineSeparator()));  
        p1.add("R");  
        document.add(p1);  
        //点线  
        Paragraph p2 = new Paragraph("LEFT");  
        p2.add(new Chunk(new DottedLineSeparator()));  
        p2.add("R");  
        document.add(p2);  
        //下滑线  
        LineSeparator UNDERLINE = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2);  
        Paragraph p3 = new Paragraph("NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN");  
        p3.add(UNDERLINE);  
        document.add(p3);   
        document.close();
    }   

8.设置段落

public static void createPdf8() throws FileNotFoundException, DocumentException{
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("E://createSamplePdf8.pdf"));
        document.open();

        Paragraph p = new Paragraph("In the previous example, you added a header and footer with the showTextAligned() method. This example demonstrates that it’s sometimes more interesting to use PdfPTable and writeSelectedRows(). You can define a bottom border for each cell so that the header is underlined. This is the most elegant way to add headers and footers, because the table mechanism allows you to position and align lines, images, and text.");

        // 默认
        p.setAlignment(Element.ALIGN_JUSTIFIED);  
        document.add(p);  

        document.newPage();  
        p.setAlignment(Element.ALIGN_JUSTIFIED);  
        p.setIndentationLeft(1 * 15f);  
        p.setIndentationRight((5 - 1) * 15f);  
        document.add(p);  

        //居右  
        document.newPage();  
        p.setAlignment(Element.ALIGN_RIGHT);  
        p.setSpacingAfter(15f);  
        document.add(p);  

        //居左  
        document.newPage();  
        p.setAlignment(Element.ALIGN_LEFT);  
        p.setSpacingBefore(15f);  
        document.add(p);  

        //居中  
        document.newPage();  
        p.setAlignment(Element.ALIGN_CENTER);  
        p.setSpacingAfter(15f);  
        p.setSpacingBefore(15f);  
        document.add(p);  

        document.close();   
    }

9.删除pdf中的一页

public static void createPdf9() throws DocumentException, IOException{
        // step 1: create a document
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E://createSamplePdf9.pdf"));
        document.open();

        // step 2: add paragraph
        document.add(new Paragraph("first page"));
        document.add(new Paragraph(document.getVersion()));

        // step 3: new a page
        document.newPage();
        writer.setPageEmpty(false);

        document.newPage();
        document.add(new Paragraph("new page"));

        document.close();

        // step 4: read the document
        PdfReader reader = new PdfReader("E://createSamplePdf9.pdf");
        reader.selectPages("1,3");
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("E://createSamplePdf9_1.pdf"));

        reader.close();
        stamper.close();        
    }

10.插入一页pdf

public static void createPdf10() throws DocumentException, IOException{
        // step 1: create a document
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("E://createSamplePdf10.pdf"));
        document.open();

        // step 2: add new page
        document.add(new Paragraph("1 page"));

        document.newPage();
        document.add(new Paragraph("2 page"));

        document.newPage();
        document.add(new Paragraph("3 page"));

        document.close();

        // step 3: read the document
        PdfReader reader = new PdfReader("E://createSamplePdf10.pdf");
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("E://createSamplePdf10_1.pdf"));

        // insert new page between the first page and the second page
        stamper.insertPage(2, reader.getPageSize(1));

        ColumnText ct = new ColumnText(null);

        ct.addElement(new Paragraph(24,new Chunk("INSERT PAGE")));
        ct.setCanvas(stamper.getOverContent(2));
        ct.setSimpleColumn(36, 36, 559, 770);

        stamper.close();
        reader.close();     
    }

11.对pdf进行排序

public static void createPdf11() throws SystemException, FileNotFoundException, DocumentException{
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E://createSamplePdf11.pdf"));
        writer.setLinearPageMode();

        document.open();
        document.add(new Paragraph("1 page"));
        document.newPage();
        document.add(new Paragraph("2 page"));
        document.newPage();
        document.add(new Paragraph("3 page"));
        document.newPage();
        document.add(new Paragraph("4 page"));
        document.newPage();
        document.add(new Paragraph("5 page"));

        int[] order = {4,3,2,1};

        writer.reorderPages(order);
        document.close();
    }

12. 设置目录

public static void createPdf12() throws FileNotFoundException, DocumentException{
        // step 1: Create a document;
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E://createSamplePdf12.pdf"));
        document.open();

        // step 2: Add new page
        document.add(new Chunk("Chapter 1").setLocalDestination("1"));

        document.newPage();
        document.add(new Chunk("Chapter 2").setLocalDestination("2"));
        document.add(new Paragraph(new Chunk("Sub 2.1").setLocalDestination("2.1")));
        document.add(new Paragraph(new Chunk("Sub 2.2").setLocalDestination("2.2")));

        document.newPage();
        document.add(new Chunk("Chapter 3").setLocalDestination("3"));

        // step 3: Set content 
        PdfContentByte cb = writer.getDirectContent();
        PdfOutline root = cb.getRootOutline();

        @SuppressWarnings("unused")
        PdfOutline outline1 = new PdfOutline(root, PdfAction.gotoLocalPage("1", false), "Chapter 1");
        PdfOutline outline2 = new PdfOutline(root, PdfAction.gotoLocalPage("2", false), "Chapter 2");

        outline2.setOpen(false);

        @SuppressWarnings("unused")
        PdfOutline outline2_1 = new PdfOutline(outline2, PdfAction.gotoLocalPage("2.1", false), "Sub 2.1");
        @SuppressWarnings("unused")
        PdfOutline outline2_2 = new PdfOutline(outline2, PdfAction.gotoLocalPage("2.2", false) , "Sub 2.2");

        @SuppressWarnings("unused")
        PdfOutline outline3 = new PdfOutline(root, PdfAction.gotoLocalPage("3", false), "Chapter 3");

        document.close();
    }

13. 设置header、footer

public static void createPdf13() throws FileNotFoundException, DocumentException{
        // step 1: Create a document
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E://createSamplePdf13.pdf"));

        // step 2: Set page event
        writer.setPageEvent(new PdfPageEventHelper(){
            public void onEndPage(PdfWriter writer, Document document) {              
                PdfContentByte cb = writer.getDirectContent();  
                cb.saveState();  

                cb.beginText();  
                BaseFont bf = null;  
                try {  
                    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
                cb.setFontAndSize(bf, 10);  

                //Header  
                float x = document.top(-20);  

                //左  
                cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "H-Left", document.left(), x, 0);  
                //中  
                cb.showTextAligned(PdfContentByte.ALIGN_CENTER, writer.getPageNumber()+ " page", (document.right() + document.left())/2, x, 0);  
                //右  
                cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, "H-Right", document.right(), x, 0);  

                //Footer  
                float y = document.bottom(-20);  

                //左  
                cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "F-Left", document.left(), y, 0);  
                //中  
                cb.showTextAligned(PdfContentByte.ALIGN_CENTER,writer.getPageNumber()+" page",(document.right() + document.left())/2, y, 0);  
                //右  
                cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, "F-Right", document.right(), y, 0);  

                cb.endText();  

                cb.restoreState();  
            }  
        });

        document.open();

        // step 3: Add paragraph 
        document.add(new Paragraph("1 page"));
        document.newPage();
        document.add(new Paragraph("2 page"));
        document.newPage();
        document.add(new Paragraph("3 page"));
        document.newPage();
        document.add(new Paragraph("4 page"));
        document.close();
    }

14. 左右文字

public static void createPdf14() throws FileNotFoundException, DocumentException{
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E://createSamplePdf14.pdf"));
        document.open();

        PdfContentByte canvas = writer.getDirectContent();

        Phrase phrase1 = new Phrase("This is a test!left");
        Phrase phrase2 = new Phrase("This is a test!right");
        Phrase phrase3 = new Phrase("This is a test!center");

        ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase1, 10, 500, 0);
        ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase2, 10, 536, 0);
        ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase3, 10, 572, 0);

        document.close();       
    }

15. 向pdf中添加table

public static void createPdf15() throws FileNotFoundException, DocumentException{
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E://createSamplePdf15.pdf"));

        document.open();

        PdfPTable table = new PdfPTable(3);
        PdfPCell cell;

        cell = new PdfPCell(new Phrase("Cell with colspan 3"));
        cell.setColspan(3);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
        cell.setColspan(2);
        table.addCell(cell);

        table.addCell("row 1; cell 1");  
        table.addCell("row 1; cell 2");  
        table.addCell("row 2; cell 1");  
        table.addCell("row 2; cell 2");  

        document.add(table);
        document.close();       
    }

16. 向pdf中插入图片

public static void createPdf16() throws DocumentException, MalformedURLException, IOException{
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E://createSamplePdf16.pdf"));
        document.open();

        Image image = Image.getInstance("resource/test2.jpg");
        float[] widths = {1f,4f};

        PdfPTable table = new PdfPTable(widths);

        table.addCell(new PdfPCell(new Paragraph("图片测试")));
        table.addCell(image);

        table.addCell("This two");  
        table.addCell(new PdfPCell(image, true));  

        //不调整  
        table.addCell("This three");  
        table.addCell(new PdfPCell(image, false));  
        document.add(table);  

        document.close();
    }

猜你喜欢

转载自blog.csdn.net/qq_40247975/article/details/82668726
今日推荐