1. 程式人生 > >Java使用iText實現對PDF檔案的操作

Java使用iText實現對PDF檔案的操作

iText是著名的開放專案,是用於生成PDF文件的一個java類庫。通過iText不僅可以生成PDF或rtf的文件,而且可以將XML、Html檔案轉化為PDF檔案。
http://itextpdf.com/
版本:itextpdf-5.2.1.jar

需要注意的是,IText使用的單位是pt而不是px,一幫情況下要想保持原來px的大小需要將px*3/4

1、生成一個PDF

    //Step 1—Create a Document.  
    Document document = new Document();  
    //Step 2—Get a PdfWriter instance.  
    PdfWriter.getInstance(document, new FileOutputStream(FILE_DIR + "createSamplePDF.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、頁面大小,頁面背景色,頁邊空白,Title,Author,Subject,Keywords
    //頁面大小  
    Rectangle rect = new Rectangle(PageSize.B5.rotate());  
    //頁面背景色  
    rect.setBackgroundColor(BaseColor.ORANGE);  
      
    Document doc = new Document(rect);  
      
    PdfWriter writer = PdfWriter.getInstance(doc, out);  
      
    //PDF版本(預設1.4)  
    writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);  
      
    //文件屬性  
    doc.addTitle("
[email protected]
"); doc.addAuthor("[email protected]"); doc.addSubject("[email protected] sample"); doc.addKeywords("[email protected]"); doc.addCreator("[email protected]"); //頁邊空白 doc.setMargins(10, 20, 30, 40); doc.open(); doc.add(new Paragraph("Hello World"));

3、設定密碼

 PdfWriter writer = PdfWriter.getInstance(doc, out);  
  
// 設定密碼為:"World"  
writer.setEncryption("Hello".getBytes(), "World".getBytes(),  
        PdfWriter.ALLOW_SCREENREADERS,  
        PdfWriter.STANDARD_ENCRYPTION_128);  
  
doc.open();  
doc.add(new Paragraph("Hello World")); 

4、新增Page

document.open();  
document.add(new Paragraph("First page"));  
document.add(new Paragraph(Document.getVersion()));  
  
document.newPage();  
writer.setPageEmpty(false);  
  
document.newPage();  
document.add(new Paragraph("New page")); 
5、新增水印(背景圖)
    //圖片水印  
    PdfReader reader = new PdfReader(FILE_DIR + "setWatermark.pdf");  
    PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR  
            + "setWatermark2.pdf"));  
      
    Image img = Image.getInstance("resource/watermark.jpg");  
    img.setAbsolutePosition(200, 400);  
    PdfContentByte under = stamp.getUnderContent(1);  
    under.addImage(img);  
      
    //文字水印  
    PdfContentByte over = stamp.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();  
      
    //背景圖  
    Image img2 = Image.getInstance("resource/test.jpg");  
    img2.setAbsolutePosition(0, 0);  
    PdfContentByte under2 = stamp.getUnderContent(3);  
    under2.addImage(img2);  
      
    stamp.close();  
    reader.close();  

6、插入Chunk, Phrase, Paragraph, List
    //Chunk物件: a String, a Font, and some attributes  
    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);  
      
    //Phrase物件: a List of Chunks with leading  
    document.newPage();  
    document.add(new Phrase("Phrase page"));  
      
    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);  
      
    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);  
              
    //Paragraph物件: a Phrase with extra properties and a newline  
    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);  
      
    //List物件: a sequence of Paragraphs called ListItem  
    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);  

7、插入Anchor, Image, Chapter, Section

 //Anchor物件: internal and external links  
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");//external  
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");//internal  
document.add(toUS);  
  
//Image物件  
document.newPage();  
Image img = Image.getInstance("resource/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);  
  
//Chapter, Section物件(目錄)  
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);

8、畫圖

    //左右箭頭  
    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);  

9、設定段落

    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);  

10、刪除Page
    FileOutputStream out = new FileOutputStream(FILE_DIR + "deletePage.pdf");  
      
    Document document = new Document();  
      
    PdfWriter writer = PdfWriter.getInstance(document, out);  
      
    document.open();  
    document.add(new Paragraph("First page"));  
    document.add(new Paragraph(Document.getVersion()));  
      
    document.newPage();  
    writer.setPageEmpty(false);  
      
    document.newPage();  
    document.add(new Paragraph("New page"));  
      
    document.close();  
      
    PdfReader reader = new PdfReader(FILE_DIR + "deletePage.pdf");  
    reader.selectPages("1,3");  
    PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR  
            + "deletePage2.pdf"));  
    stamp.close();  
    reader.close();  
11、插入Page
 FileOutputStream out = new FileOutputStream(FILE_DIR + "insertPage.pdf");  
  
Document document = new Document();  
  
PdfWriter.getInstance(document, out);  
  
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.close();  
  
PdfReader reader = new PdfReader(FILE_DIR + "insertPage.pdf");  
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR  
        + "insertPage2.pdf"));  
  
stamp.insertPage(2, reader.getPageSize(1));  
  
ColumnText ct = new ColumnText(null);  
ct.addElement(new Paragraph(24, new Chunk("INSERT PAGE")));  
ct.setCanvas(stamp.getOverContent(2));  
ct.setSimpleColumn(36, 36, 559, 770);  
  
stamp.close();  
reader.close();

12、排序page
 PdfWriter writer = PdfWriter.getInstance(doc, out);  
writer.setLinearPageMode();  
  
doc.open();  
doc.add(new Paragraph("1 page"));  
doc.newPage();  
doc.add(new Paragraph("2 page"));  
doc.newPage();  
doc.add(new Paragraph("3 page"));  
doc.newPage();  
doc.add(new Paragraph("4 page"));  
doc.newPage();  
doc.add(new Paragraph("5 page"));  
  
int[] order = {4,3,2,1};  
writer.reorderPages(order); 

13、目錄
    // Code 1  
    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"));  
      
    // Code 2  
    PdfContentByte cb = writer.getDirectContent();  
    PdfOutline root = cb.getRootOutline();  
      
    // Code 3  
    @SuppressWarnings("unused")  
    PdfOutline oline1 = new PdfOutline(root, PdfAction.gotoLocalPage("1", false), "Chapter 1");  
      
    PdfOutline oline2 = new PdfOutline(root, PdfAction.gotoLocalPage("2", false), "Chapter 2");  
    oline2.setOpen(false);  
      
    @SuppressWarnings("unused")  
    PdfOutline oline2_1 = new PdfOutline(oline2, PdfAction.gotoLocalPage("2.1", false), "Sub 2.1");  
    @SuppressWarnings("unused")  
    PdfOutline oline2_2 = new PdfOutline(oline2, PdfAction.gotoLocalPage("2.2", false), "Sub 2.2");  
      
    @SuppressWarnings("unused")  
    PdfOutline oline3 = new PdfOutline(root, PdfAction.gotoLocalPage("3", false), "Chapter 3");  


14、Header, Footer

    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR + "setHeaderFooter.pdf"));  
      
    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();  
        }  
    });  
      
    doc.open();  
    doc.add(new Paragraph("1 page"));          
    doc.newPage();  
    doc.add(new Paragraph("2 page"));          
    doc.newPage();  
    doc.add(new Paragraph("3 page"));          
    doc.newPage();  
    doc.add(new Paragraph("4 page"));  

15、左右文字
 PdfWriter writer = PdfWriter.getInstance(document, out);  
  
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); 

16、幻燈片放映
    PdfWriter writer = PdfWriter.getInstance(doc, out);  
      
    writer.setPdfVersion(PdfWriter.VERSION_1_5);  
      
    writer.setViewerPreferences(PdfWriter.PageModeFullScreen);//全屏  
    writer.setPageEvent(new PdfPageEventHelper() {  
        public void onStartPage(PdfWriter writer, Document document) {  
            writer.setTransition(new PdfTransition(PdfTransition.DISSOLVE, 3));  
            writer.setDuration(5);//間隔時間  
        }  
    });  
      
    doc.open();  
    doc.add(new Paragraph("1 page"));  
    doc.newPage();  
    doc.add(new Paragraph("2 page"));  
    doc.newPage();  
    doc.add(new Paragraph("3 page"));  
    doc.newPage();  
    doc.add(new Paragraph("4 page"));  
    doc.newPage();  
    doc.add(new Paragraph("5 page"));  

17、壓縮PDF到Zip
    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(FILE_DIR + "zipPDF.zip"));  
    for (int i = 1; i <= 3; i++) {  
        ZipEntry entry = new ZipEntry("hello_" + i + ".pdf");  
        zip.putNextEntry(entry);  
        Document document = new Document();  
        PdfWriter writer = PdfWriter.getInstance(document, zip);  
        writer.setCloseStream(false);  
        document.open();  
        document.add(new Paragraph("Hello " + i));  
        document.close();  
        zip.closeEntry();  
    }  
    zip.close();  

18、分割PDF

FileOutputStream out = new FileOutputStream(FILE_DIR + "splitPDF.pdf");  
  
Document document = new Document();  
  
PdfWriter.getInstance(document, out);  
  
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.close();  
  
PdfReader reader = new PdfReader(FILE_DIR + "splitPDF.pdf");  
  
Document dd = new Document();  
PdfWriter writer = PdfWriter.getInstance(dd, new FileOutputStream(FILE_DIR + "splitPDF1.pdf"));  
dd.open();  
PdfContentByte cb = writer.getDirectContent();  
dd.newPage();  
cb.addTemplate(writer.getImportedPage(reader, 1), 0, 0);  
dd.newPage();  
cb.addTemplate(writer.getImportedPage(reader, 2), 0, 0);  
dd.close();  
writer.close();  
  
Document dd2 = new Document();  
PdfWriter writer2 = PdfWriter.getInstance(dd2, new FileOutputStream(FILE_DIR + "splitPDF2.pdf"));  
dd2.open();  
PdfContentByte cb2 = writer2.getDirectContent();  
dd2.newPage();  
cb2.addTemplate(writer2.getImportedPage(reader, 3), 0, 0);  
dd2.newPage();  
cb2.addTemplate(writer2.getImportedPage(reader, 4), 0, 0);  
dd2.close();  
writer2.close();  

19、合併PDF
    PdfReader reader1 = new PdfReader(FILE_DIR + "splitPDF1.pdf");  
    PdfReader reader2 = new PdfReader(FILE_DIR + "splitPDF2.pdf");  
      
    FileOutputStream out = new FileOutputStream(FILE_DIR + "mergePDF.pdf");  
      
    Document document = new Document();  
    PdfWriter writer = PdfWriter.getInstance(document, out);  
      
    document.open();  
    PdfContentByte cb = writer.getDirectContent();  
      
    int totalPages = 0;  
    totalPages += reader1.getNumberOfPages();  
    totalPages += reader2.getNumberOfPages();  
      
    java.util.List<PdfReader> readers = new ArrayList<PdfReader>();  
    readers.add(reader1);  
    readers.add(reader2);  
      
    int pageOfCurrentReaderPDF = 0;  
    Iterator<PdfReader> iteratorPDFReader = readers.iterator();  
      
    // Loop through the PDF files and add to the output.  
    while (iteratorPDFReader.hasNext()) {  
        PdfReader pdfReader = iteratorPDFReader.next();  
      
        // Create a new page in the target for each source page.  
        while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {  
            document.newPage();  
            pageOfCurrentReaderPDF++;  
            PdfImportedPage page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);  
            cb.addTemplate(page, 0, 0);  
        }  
        pageOfCurrentReaderPDF = 0;  
    }  
    out.flush();  
    document.close();  
    out.close();  

20、Annotation
    PdfWriter writer = PdfWriter.getInstance(doc, out);  
    writer.setLinearPageMode();  
      
    doc.open();  
    doc.add(new Paragraph("1 page"));  
    doc.add(new Annotation("Title", "This is a annotation!"));  
      
    doc.newPage();  
    doc.add(new Paragraph("2 page"));  
    Chunk chunk = new Chunk("\u00a0");  
    chunk.setAnnotation(PdfAnnotation.createText(writer, null, "Title", "This is a another annotation!", false, "Comment"));  
    doc.add(chunk);  
      
    //新增附件  
    doc.newPage();  
    doc.add(new Paragraph("3 page"));  
    Chunk chunk2 = new Chunk("\u00a0\u00a0");  
    PdfAnnotation annotation = PdfAnnotation.createFileAttachment(  
            writer, null, "Title", null,  
            "resource/test2.jpg",  
            "img.jpg");  
    annotation.put(PdfName.NAME,  
            new PdfString("Paperclip"));  
    chunk2.setAnnotation(annotation);  
    doc.add(chunk2);  

21、插入一個Table

    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.setRowspan(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);  

22、表格巢狀
 PdfPTable table = new PdfPTable(4);  
  
//1行2列  
PdfPTable nested1 = new PdfPTable(2);  
nested1.addCell("1.1");  
nested1.addCell("1.2");  
  
//2行1列  
PdfPTable nested2 = new PdfPTable(1);  
nested2.addCell("2.1");  
nested2.addCell("2.2");  
  
//將表格插入到指定位置  
for (int k = 0; k < 24; ++k) {  
    if (k == 1) {  
        table.addCell(nested1);  
    } else if (k == 20) {  
        table.addCell(nested2);  
    } else {  
        table.addCell("cell " + k);  
    }  
}  
  
document.add(table); 

23、設定表格寬度
    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.setRowspan(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");  
      
    //100%  
    table.setWidthPercentage(100);  
    document.add(table);          
    document.add(new Paragraph("\n\n"));  
      
    //寬度50% 居左  
    table.setHorizontalAlignment(Element.ALIGN_LEFT);  
    document.add(table);  
    document.add(new Paragraph("\n\n"));  
      
    //寬度50% 居中  
    table.setHorizontalAlignment(Element.ALIGN_CENTER);  
    document.add(table);  
    document.add(new Paragraph("\n\n"));  
      
    //寬度50% 居右  
    table.setWidthPercentage(50);  
    table.setHorizontalAlignment(Element.ALIGN_RIGHT);  
    document.add(table);  
    document.add(new Paragraph("\n\n"));  
      
    //固定寬度  
    table.setTotalWidth(300);  
    table.setLockedWidth(true);  
    document.add(table);  

24、設定表格前後間隔
    PdfPTable table = new PdfPTable(3);  
    PdfPCell cell = new PdfPCell(new Paragraph("合併3個單元格",fontZH));  
    cell.setColspan(3);  
    table.addCell(cell);  
    table.addCell("1.1");  
    table.addCell("2.1");  
    table.addCell("3.1");  
    table.addCell("1.2");  
    table.addCell("2.2");  
    table.addCell("3.2");  
      
    cell = new PdfPCell(new Paragraph("紅色邊框",fontZH));  
    cell.setBorderColor(new BaseColor(255, 0, 0));  
    table.addCell(cell);  
      
    cell = new PdfPCell(new Paragraph("合併單2個元格",fontZH));  
    cell.setColspan(2);  
    cell.setBackgroundColor(new BaseColor(0xC0, 0xC0, 0xC0));  
    table.addCell(cell);  
      
    table.setWidthPercentage(50);  
      
    document.add(new Paragraph("追加2個表格",fontZH));  
    document.add(table);  
    document.add(table);  
      
    document.newPage();  
    document.add(new Paragraph("使用'SpacingBefore'和'setSpacingAfter'",fontZH));  
    table.setSpacingBefore(15f);  
    document.add(table);  
    document.add(table);  
    document.add(new Paragraph("這裡沒有間隔",fontZH));  
    table.setSpacingAfter(15f);  

25、設定單元格寬度
    //按比例設定單元格寬度  
    float[] widths = {0.1f, 0.1f, 0.05f, 0.75f};  
    PdfPTable table = new PdfPTable(widths);  
    table.addCell("10%");  
    table.addCell("10%");  
    table.addCell("5%");  
    table.addCell("75%");  
    table.addCell("aa");  
    table.addCell("aa");  
    table.addCell("a");  
    table.addCell("aaaaaaaaaaaaaaa");  
    table.addCell("bb");  
    table.addCell("bb");  
    table.addCell("b");  
    table.addCell("bbbbbbbbbbbbbbb");  
    table.addCell("cc");  
    table.addCell("cc");  
    table.addCell("c");  
    table.addCell("ccccccccccccccc");  
    document.add(table);  
    document.add(new Paragraph("\n\n"));  
      
    //調整比例  
    widths[0] = 20f;  
    widths[1] = 20f;  
    widths[2] = 10f;  
    widths[3] = 50f;  
    table.setWidths(widths);  
    document.add(table);  
      
    //按絕對值設定單元格寬度  
    widths[0] = 40f;  
    widths[1] = 40f;  
    widths[2] = 20f;  
    widths[3] = 300f;  
    Rectangle r = new Rectangle(PageSize.A4.getRight(72), PageSize.A4.getTop(72));  
    table.setWidthPercentage(widths, r);  
    document.add(new Paragraph("\n\n"));  
    document.add(table);  
26、設定單元格高度
    PdfPTable table = new PdfPTable(2);  
      
    PdfPCell cell;  
      
    //折行  
    table.addCell(new PdfPCell(new Paragraph("折行", fontZH)));  
    cell = new PdfPCell(new Paragraph("blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah"));  
    cell.setNoWrap(false);  
    table.addCell(cell);  
      
    //不折行  
    table.addCell(new PdfPCell(new Paragraph("不折行", fontZH)));  
    cell.setNoWrap(true);  
    table.addCell(cell);  
      
    //設定高度  
    table.addCell(new PdfPCell(new Paragraph("任意高度",fontZH)));  
    cell = new PdfPCell(new Paragraph("1. blah blah\n2. blah blah blah\n3. blah blah\n4. blah blah blah\n5. blah blah\n6. blah blah blah\n7. blah blah\n8. blah blah blah"));  
    table.addCell(cell);  
      
    //固定高度  
    table.addCell(new PdfPCell(new Paragraph("固定高度",fontZH)));  
    cell.setFixedHeight(50f);  
    table.addCell(cell);  
      
    //最小高度  
    table.addCell(new PdfPCell(new Paragraph("最小高度",fontZH)));  
    cell = new PdfPCell(new Paragraph("最小高度:50",fontZH));  
    cell.setMinimumHeight(50f);  
    table.addCell(cell);  
      
    //最後一行拉長到page底部  
    table.setExtendLastRow(true);  
    table.addCell(new PdfPCell(new Paragraph("拉長最後一行",fontZH)));  
    cell = new PdfPCell(new Paragraph("最後一行拉長到page底部",fontZH));  
    table.addCell(cell);  
      
    document.add(table);  

27、設定單元格顏色
    PdfPTable table = new PdfPTable(4);  
    PdfPCell cell;  
    cell = new PdfPCell(new Paragraph("顏色測試",fontZH));  
    table.addCell(cell);  
      
    //紅色背景,無邊框  
    cell = new PdfPCell(new Paragraph("紅色背景,無邊框",fontZH));  
    cell.setBorder(Rectangle.NO_BORDER);  
    cell.setBackgroundColor(BaseColor.RED);  
    table.addCell(cell);  
      
    //綠色背景,下邊框  
    cell = new PdfPCell(new Paragraph("綠色背景,下邊框",fontZH));  
    cell.setBorder(Rectangle.BOTTOM);  
    cell.setBorderColorBottom(BaseColor.MAGENTA);  
    cell.setBorderWidthBottom(5f);  
    cell.setBackgroundColor(BaseColor.GREEN);  
    table.addCell(cell);  
      
    //藍色背景,上邊框  
    cell = new PdfPCell(new Paragraph("藍色背景,上邊框",fontZH));  
    cell.setBorder(Rectangle.TOP);  
    cell.setUseBorderPadding(true);  
    cell.setBorderWidthTop(5f);  
    cell.setBorderColorTop(BaseColor.CYAN);  
    cell.setBackgroundColor(BaseColor.BLUE);  
    table.addCell(cell);  
      
    cell = new PdfPCell(new Paragraph("背景灰色度",fontZH));  
    table.addCell(cell);  
    cell = new PdfPCell(new Paragraph("0.25"));  
    cell.setBorder(Rectangle.NO_BORDER);  
    cell.setGrayFill(0.25f);  
    table.addCell(cell);  
    cell = new PdfPCell(new Paragraph("0.5"));  
    cell.setBorder(Rectangle.NO_BORDER);  
    cell.setGrayFill(0.5f);  
    table.addCell(cell);  
    cell = new PdfPCell(new Paragraph("0.75"));  
    cell.setBorder(Rectangle.NO_BORDER);  
    cell.setGrayFill(0.75f);  
    table.addCell(cell);  
      
    document.add(table);  

28、插入影象
    Image image = Image.getInstance("resource/test2.jpg");  
    float[] widths = { 1f, 4f };  
      
    PdfPTable table = new PdfPTable(widths);  
      
    //插入圖片  
    table.addCell(new PdfPCell(new Paragraph("圖片測試", fontZH)));  
    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);  

29、設定表頭

    String[] bogusData = { "M0065920", "SL", "FR86000P", "PCGOLD",  
            "119000", "96 06", "2001-08-13", "4350", "6011648299",  
            "FLFLMTGP", "153", "119000.00" };  
    int NumColumns = 12;  
    // 12  
    PdfPTable datatable = new PdfPTable(NumColumns);  
    int headerwidths[] = { 9, 4, 8, 10, 8, 11, 9, 7, 9, 10, 4, 10 }; // percentage  
    datatable.setWidths(headerwidths);  
    datatable.setWidthPercentage(100);  
    datatable.getDefaultCell().setPadding(3);  
    datatable.getDefaultCell().setBorderWidth(2);  
    datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);  
      
    datatable.addCell("Clock #");  
    datatable.addCell("Trans Type");  
    datatable.addCell("Cusip");  
    datatable.addCell("Long Name");  
    datatable.addCell("Quantity");  
    datatable.addCell("Fraction Price");  
    datatable.addCell("Settle Date");  
    datatable.addCell("Portfolio");  
    datatable.addCell("ADP Number");  
    datatable.addCell("Account ID");  
    datatable.addCell("Reg Rep ID");  
    datatable.addCell("Amt To Go ");  
      
    datatable.setHeaderRows(1);  
      
    //邊框  
    datatable.getDefaultCell().setBorderWidth(1);  
      
    //背景色  
    for (int i = 1; i < 1000; i++) {  
        for (int x = 0; x < NumColumns; x++) {  
            datatable.addCell(bogusData[x]);  
        }  
    }  
      
    document.add(datatable);  

30、分割表格
    //橫向分割  
    PdfContentByte cb = writer.getDirectContent();  
    PdfPTable table = new PdfPTable(10);  
    for (int k = 1; k <= 100; ++k) {  
        table.addCell("The number " + k);  
    }  
    table.setTotalWidth(400);  
      
    table.writeSelectedRows(0, 5, 0, -1, 5, 700, cb);  
    table.writeSelectedRows(5, -1, 0, -1, 210, 700, cb);  

31、設定單元格留白
    PdfPTable table = new PdfPTable(2);  
    PdfPCell cell;  
    Paragraph p = new Paragraph("Quick brown fox jumps over the lazy dog. Quick brown fox jumps over the lazy dog.");  
    table.addCell(new PdfPCell(new Paragraph("預設",fontZH)));  
    table.addCell(p);  
    table.addCell(new PdfPCell(new Paragraph("Padding:10",fontZH)));  
    cell = new PdfPCell(p);  
    cell.setPadding(10f);  
    table.addCell(cell);  
    table.addCell(new PdfPCell(new Paragraph("Padding:0",fontZH)));  
    cell = new PdfPCell(p);  
    cell.setPadding(0f);  
    table.addCell(cell);  
    table.addCell(new PdfPCell(new Paragraph("上Padding:0 左Padding:20",fontZH)));  
    cell = new PdfPCell(p);  
    cell.setPaddingTop(0f);  
    cell.setPaddingLeft(20f);  
    table.addCell(cell);  
    document.add(table);  
      
    document.newPage();  
    table = new PdfPTable(2);  
    table.addCell(new PdfPCell(new Paragraph("沒有Leading",fontZH)));  
    table.getDefaultCell().setLeading(0f, 0f);  
    table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");  
    table.getDefaultCell().setLeading(14f, 0f);  
    table.addCell(new PdfPCell(new Paragraph("固定Leading:14pt",fontZH)));  
    table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");  
    table.addCell(new PdfPCell(new Paragraph("相對於字型",fontZH)));  
    table.getDefaultCell().setLeading(0f, 1.0f);  
    table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");  
    document.add(table);  

32、設定單元格邊框
 //沒有邊框  
PdfPTable table1 = new PdfPTable(3);    
table1.getDefaultCell().setBorder(PdfPCell.NO_BORDER);    
table1.addCell(new Paragraph("Cell 1"));   
table1.addCell(new Paragraph("Cell 2"));   
table1.addCell(new Paragraph("Cell 3"));   
document.add(table1);  
  
//邊框粗細顏色  
document.newPage();  
Rectangle b1 = new Rectangle(0f, 0f);  
b1.setBorderWidthLeft(6f);  
b1.setBorderWidthBottom(5f);  
b1.setBorderWidthRight(4f);  
b1.setBorderWidthTop(2f);  
b1.setBorderColorLeft(BaseColor.RED);  
b1.setBorderColorBottom(BaseColor.ORANGE);  
b1.setBorderColorRight(BaseColor.YELLOW);  
b1.setBorderColorTop(BaseColor.GREEN);  
PdfPTable table2 = new PdfPTable(1);  
PdfPCell cell =  new PdfPCell(new Paragraph("Cell 1"));  
cell.cloneNonPositionParameters(b1);  
table2.addCell(cell);  
document.add(table2); 

33、PdfPTableEvent 

34、PdfPCellEvent 

35、PdfPageEventHelper 

36、生成Barcode QRCode

 String myString = "http://www.google.com";  
  
Barcode128 code128 = new Barcode128();  
code128.setCode(myString.trim());  
code128.setCodeType(Barcode128.CODE128);  
Image code128Image = code128.createImageWithBarcode(cb, null, null);  
code128Image.setAbsolutePosition(10,700);  
code128Image.scalePercent(125);  
doc.add(code128Image);  
  
BarcodeQRCode qrcode = new BarcodeQRCode(myString.trim(), 1, 1, null);  
Image qrcodeImage = qrcode.getImage();  
qrcodeImage.setAbsolutePosition(10,600);  
qrcodeImage.scalePercent(200);  
doc.add(qrcodeImage);


37、HTML to PDF

 Document document = new Document(PageSize.LETTER);  
PdfWriter.getInstance(document, new FileOutputStream("c://testpdf1.pdf"));  
document.open();  
HTMLWorker htmlWorker = new HTMLWorker(document);  
htmlWorker.parse(new StringReader("<h1>This is a test!</h1>"));  
document.close(); 

你可能需要的iText的jar:http://download.csdn.net/detail/weixin_36380516/9926308

相關推薦

PHP如何利用Python實現PDF檔案操作

需求:在PHP裡實現了把8.pdf的前4頁pdf檔案截取出來生成新的pdf檔案。 詳細步驟如下: 前提:python必須是3.x版本以上,必要時需要升級pip3,命令如下:pip3 install --upgrade pipPyPDF 自 2010年 12月開始就不在更新了,PyPDF2 接棒 PyPD

Java使用iText實現PDF檔案操作

iText是著名的開放專案,是用於生成PDF文件的一個java類庫。通過iText不僅可以生成PDF或rtf的文件,而且可以將XML、Html檔案轉化為PDF檔案。 http://itextpdf.com/ 版本:itextpdf-5.2.1.jar 需要注意的是,I

php如何利用python實現pdf文件的操作(讀寫、合並分割)

PHP實現pdf文件截取 PHP調用python腳本 php如何利用python實現對pdf文件的操作 需求:在PHP裏實現了把8.pdf的前4頁pdf文件截取出來生成新的pdf文件。 詳細步驟如下: 1. 安裝python第三方庫PyPDF2 前提:python必須是3.x版本以上,必要時需要升級p

C# 用Linq的方式實現Xml檔案的基本操作(建立xml檔案、增刪改查xml檔案節點資訊)

1 private static void GetXmlNodeInforOld( string xmlPath) 2 { 3 try 4 { 5

C 實現XML檔案的基本操作(建立xml檔案,增 刪 改 查 xml節點資訊)

                XML:Extensible Markup Language(可擴充套件標記語言)的縮寫,是用來定義其它語言的一種元語言,其前身是SGML(Standard Generalized Markup Language,標準通用標記語言)。它沒有標籤集(tag set),也沒有語法規

Java之生成PdfPdf內容操作

enc images sub als tar 應用 throw mave add 雖說網上有很多可以在線導出Pdf或者word或者轉成png等格式的工具,但是我覺得還是得了解知道是怎麽實現的。一來,在線免費轉換工具,是有容量限制的,達到一定的容量時,是不能成功導出的;二來,

【經驗分享】:壓縮PDF檔案操作方法

平常大家處理比較大的檔案的時候,不知道大家是如何進行操作的?在傳輸檔案的時候,有時就是因為檔案太大導致傳輸時間特別長,就拿PDF檔案來說,壓縮PDF檔案我們該如何進行操作呢?下面小編就將自己的方法分享給大家。   1:首先大家可以將需要壓縮的PDF檔案儲存在一個新建的

java中實現時間的操作

所屬類別:類的成員變數與方法、構造方法 題目: 在程式中經常要對時間進行操作但是並沒有時間型別的資料。 那麼我們可以自己實現一個時間類來滿足程式中的需要。  定義名為MyTime的類其中應有三個整型成員時hour分minute秒second為了保證資料的安全性這三個成員

sqlserver 觸發器實現a表操作操作其他表

CREATE TABLE tab1( tab1_id varchar(11) ); CREATE TABLE tab2( tab2_id varchar(11) ); CREATE TRIGGER insertname ON tab1 AFTER INSERT AS BEGIN INSERT

C#利用Dapper實現SQLite的操作

前言 近幾天藉助C#對SQLite的學習,算是對資料庫剛入門吧,三天前寫了一篇C#利用System.Data.SQLite實現對SQLite的操作,其中方法是基於System.Data.SQLite.dll的程式包,後來在youtube和infoworld上看到利用Dapper程式包對資

C#利用System.Data.SQLite實現SQLite的操作

SQLite介紹 SQLite是一個類似於Access的單機版資料庫管理系統,它將所有資料庫的定義(包括定義、表、索引和資料本身)都儲存在一個單一的檔案中。並且,SQLite是一個用C實現的類庫,它在記憶體消耗、檔案體積、簡單性方面都有不錯的表現,如果資料在10W條以下,查詢速度也是相當

Spring+Maven+JdbcTemplate實現mysql資料庫操作

第一步匯入需要的maven: <dependency> <groupId>org.springframework</groupId> <artifactId>spring-conte

通過dos命令方式,運用javac、java、jar實現Java檔案的編譯,執行及打包的完整過程

環境配置一定要配好!!! 編寫一個簡單的HelloWorld.java: package com.bnusri; public class HelloWorld { public static void main(String[] args) { // TODO

python csv檔案操作

# scrapy pipline class BazaarPipeline(object): def open_spider(self, spider): self.filename = open("digital.csv", "wb") # 建立一

android native開發-native實現camera的操作

通過native實現camera的操作 原始碼路徑:frameworks/av/camera/ndk/ 參考的test原始碼路徑:cts/tests/tests/graphics/jni/CameraTestHelpers.cpp 1/* 2 * Copyrig

如何用 Java PDF 檔案進行電子簽章(一)概述及技術選型

參考: 一、 概述   印章是我國特有的歷史文化產物,古代主要用作身份憑證和行駛職權的工具。它的起源是由於社會生活的實際需要。早在商周時代,印章就已經產生。如今的印章已成為一種獨特的,融實用性和藝術性為一體的藝術瑰寶。傳統的印章容易被壞人、小人私刻;從而新聞鮮

如何用 Java PDF 檔案進行電子簽章(四)如何生成PKCS12證書

參考: 1. PKCS的簡單介紹   PKCS:The Public-Key Cryptography Standards (簡稱PKCS)是由美國RSA資料安全公司及其合作伙伴制定的一組公鑰密碼學標準,其中包括證書申請、證書更新、證書作廢表釋出、擴充套件證書

PDF編輯方法,怎麼PDF檔案進行編輯

  隨著時代發展的越來越快,PDF檔案的使用也越來越多,對於PDF檔案,修改編輯是需要使用到PDF編輯器的,在編輯檔案的時候,就需要修改檔案中的文字內容以及圖片內容,這時,應該怎麼去編輯呢,想知道的話,就看看下面的文章哦。   1.開啟執行PDF編輯器,在編輯器中開啟需要修改的PDF檔案。  

PDF編輯器如何PDF檔案進行檔案的編輯

對於PDF檔案來說我們都是利用PDF編輯器去進行檔案的編輯,對於PDF檔案的編輯我們怎麼操作呢?小編利用迅捷PDF編輯器去和你們分享一下如何操作! 迅捷PDF編輯器是一款專業的pdf檔案編輯工具,操作簡單,功能強大,利用這款軟體可以輕鬆的對PDF檔案進行編輯

如何去PDF檔案進行快速分割

快速分割PDF檔案如何操作?這個問題很簡單,雖然小夥伴們都不一定知道,今天小編就簡單和你們分享一下操作方法:   想要對PDF檔案進行分割,我們可以使用迅捷PDF編輯器進行分割,這款軟體功能強大,工具欄簡潔,利用這款軟體可以有效的對PDF檔案進行分割處理,而