• ItextDemo<二>


    Nested tables

    TableTemplate.java

    /**
     * Example written by Bruno Lowagie in answer to the following question:
     * http://stackoverflow.com/questions/22093993/itext-whats-an-easy-to-print-first-right-then-down
     */
    package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Paragraph;
    import com.itextpdf.text.pdf.PdfContentByte;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfTemplate;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;   import sandbox.WrapToTest;   @WrapToTest
    public class TableTemplate {   public static final String DEST = "results/tables/table_template.pdf";   public static void main(String[] args) throws IOException, DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new TableTemplate().createPdf(DEST);
        }   public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table = new PdfPTable(15);
            table.setTotalWidth(1500);
            PdfPCell cell;
            for (int r = 'A'; r <= 'Z'; r++) {
                for (int c = 1; c <= 15; c++) {
                    cell = new PdfPCell();
                    cell.setFixedHeight(50);
                    cell.addElement(new Paragraph(String.valueOf((char) r) + String.valueOf(c)));
                    table.addCell(cell);
                }
            }
            PdfContentByte canvas = writer.getDirectContent();
            PdfTemplate tableTemplate = canvas.createTemplate(1500, 1300);
            table.writeSelectedRows(0, -1, 0, 1300, tableTemplate);
            PdfTemplate clip;
            for (int j = 0; j < 1500; j += 500) {
                for (int i = 1300; i > 0; i -= 650) {
                    clip = canvas.createTemplate(500, 650);
                    clip.addTemplate(tableTemplate, -j, 650 - i);
                    canvas.addTemplate(clip, 36, 156);
                    document.newPage();
                }
            }
            document.close();
        }
    }
    ====================

    List object in cell

    ListInCell.java

    /**
     * This example was written by Bruno Lowagie for a prospective customer.
     * The code in this sample works with the latest version of iText.
     * It doesn't work with versions predating iText 5.
     */
    package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.List;
    import com.itextpdf.text.ListItem;
    import com.itextpdf.text.Paragraph;
    import com.itextpdf.text.Phrase;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;   import sandbox.WrapToTest;   @WrapToTest
    public class ListInCell {   public static final String DEST = "results/tables/list_in_cell.pdf";   public static void main(String[] args) throws IOException, DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new ListInCell().createPdf(DEST);
        }   public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();   // This is how not to do it (but it works anyway):   // We create a list:
            List list = new List();                
            list.add(new ListItem("Item 1"));
            list.add(new ListItem("Item 2"));
            list.add(new ListItem("Item 3"));   // We wrap this list in a phrase:     
            Phrase phrase = new Phrase();
            phrase.add(list);
            // We add this phrase to a cell
            PdfPCell phraseCell = new PdfPCell();
            phraseCell.addElement(phrase);   // We add the cell to a table:
            PdfPTable phraseTable = new PdfPTable(2);
            phraseTable.setSpacingBefore(5);
            phraseTable.addCell("List wrapped in a phrase:");
            phraseTable.addCell(phraseCell);   // We wrap the phrase table in another table:
            Phrase phraseTableWrapper = new Phrase();
            phraseTableWrapper.add(phraseTable);   // We add these nested tables to the document:
            document.add(new Paragraph("A list, wrapped in a phrase, wrapped in a cell, wrapped in a table, wrapped in a phrase:"));
            document.add(phraseTableWrapper);   // This is how to do it:   // We add the list directly to a cell:
            PdfPCell cell = new PdfPCell();
            cell.addElement(list);   // We add the cell to the table:
            PdfPTable table = new PdfPTable(2);
            table.setSpacingBefore(5);
            table.addCell("List placed directly into cell");
            table.addCell(cell);   // We add the table to the document:
            document.add(new Paragraph("A list, wrapped in a cell, wrapped in a table:"));
            document.add(table);   // Avoid adding tables to phrase (but it works anyway):   Phrase tableWrapper = new Phrase();
            tableWrapper.add(table);document.add(new Paragraph("A list, wrapped in a cell, wrapped in a table, wrapped in a phrase:"));
            document.add(tableWrapper);   document.close();
        }
    }

    NestedListHtml.java

    /*
     * Example written by Bruno Lowagie in answer to the following question:
     * http://stackoverflow.com/questions/26755315/how-can-i-convert-xhtml-nested-list-to-pdf-with-itext
     */
    package sandbox.xmlworker;   import com.itextpdf.text.Chunk;
    import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Element;
    import com.itextpdf.text.Paragraph;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;
    import com.itextpdf.tool.xml.ElementList;
    import com.itextpdf.tool.xml.XMLWorker;
    import com.itextpdf.tool.xml.XMLWorkerHelper;
    import com.itextpdf.tool.xml.html.Tags;
    import com.itextpdf.tool.xml.parser.XMLParser;
    import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
    import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
    import com.itextpdf.tool.xml.pipeline.end.ElementHandlerPipeline;
    import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
    import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;   import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import sandbox.WrapToTest;   /**
     *
     * @author Bruno Lowagie (iText Software)
     */
    @WrapToTest
    public class NestedListHtml {   public static final String HTML = "resources/xml/list.html";
        public static final String DEST = "results/xmlworker/nested_list.pdf";   public static void main(String[] args) throws IOException, DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new NestedListHtml().createPdf(DEST);
        }     public void createPdf(String file) throws IOException, DocumentException {   // Parse HTML into Element list   // CSS
            CSSResolver cssResolver =
                    XMLWorkerHelper.getInstance().getDefaultCssResolver(true);   // HTML
            HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
            htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
            htmlContext.autoBookmark(false);   // Pipelines
            ElementList elements = new ElementList();
            ElementHandlerPipeline end = new ElementHandlerPipeline(elements, null);
            HtmlPipeline html = new HtmlPipeline(htmlContext, end);
            CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);   // XML Worker
            XMLWorker worker = new XMLWorker(css, true);
            XMLParser p = new XMLParser(worker);
            p.parse(new FileInputStream(HTML));   // step 1
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(file));
            document.open();
            for (Element e : elements) {
                document.add(e);
            }
            document.add(Chunk.NEWLINE);
            Paragraph para = new Paragraph();
            for (Element e : elements) {
                para.add(e);
            }
            document.add(para);
            document.add(Chunk.NEWLINE);
            PdfPTable table = new PdfPTable(2);
            table.addCell("Nested lists don't work in a cell");
            PdfPCell cell = new PdfPCell();
            for (Element e : elements) {
                cell.addElement(e);
            }
            table.addCell(cell);
            document.add(table);   document.close();
        }   }

    Links in tables

    LinkInPositionedTable.java

    /*
     * Example written in answer to:
     * http://stackoverflow.com/questions/33633363/itextpdf-cannot-use-writeselectedrows-on-a-table-where-an-anchor-has-been-in
     */
    package sandbox.tables;   import com.itextpdf.text.Anchor;
    import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Paragraph;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import sandbox.WrapToTest;   /**
     * @author iText
     */
    @WrapToTest
    public class LinkInPositionedTable {   public static final String DEST = "results/tables/link_in_positioned_table.pdf";   public static void main(String[] args) throws IOException,
                DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new LinkInPositionedTable().createPdf(DEST);
        }   public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table = new PdfPTable(1);
            table.setTotalWidth(500);
            PdfPCell cell = new PdfPCell();
            Paragraph p = new Paragraph();  
            Anchor anchor = new Anchor("link to top of next page");
            anchor.setReference("#top");
            p.add(anchor);
            cell.addElement(p);
            table.addCell(cell);
            table.writeSelectedRows(0, -1, 36, 700, writer.getDirectContent());
            document.newPage();
            Anchor target = new Anchor("top");
            target.setName("top");
            document.add(target);
            document.close();
        }
    }

    Large tables

    IncompleteTable.java

    /**
     * Example written by Bruno Lowagie
     */
    package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.PageSize;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import sandbox.WrapToTest;   @WrapToTest
    public class IncompleteTable {
        public static final String DEST = "results/tables/incomplete_table.pdf";   public static void main(String[] args) throws IOException,
                DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new IncompleteTable().createPdf(DEST);
        }
        public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document(PageSize.LETTER);
            PdfWriter.getInstance(document, new FileOutputStream(dest));   document.open();
            PdfPTable table = new PdfPTable(5);
            table.setHeaderRows(1);
            table.setSplitRows(false);
            table.setComplete(false);   for (int i = 0; i < 5; i++) {table.addCell("Header " + i);}   for (int i = 0; i < 500; i++) {
                if (i%5 == 0) {
                    document.add(table);
                }
                table.addCell("Test " + i);
            }   table.setComplete(true);
            document.add(table);
            document.close();
        }   }

    Fit text in cell

    TruncateTextInCell.java

    /**
     * Example written by Bruno Lowagie in answer to the following question:
     * http://stackoverflow.com/questions/22093488/itext-how-do-i-get-the-rendered-dimensions-of-text
     */
    package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.ExceptionConverter;
    import com.itextpdf.text.Font;
    import com.itextpdf.text.Paragraph;
    import com.itextpdf.text.Rectangle;
    import com.itextpdf.text.pdf.BaseFont;
    import com.itextpdf.text.pdf.ColumnText;
    import com.itextpdf.text.pdf.PdfContentByte;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPCellEvent;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;   import sandbox.WrapToTest;   @WrapToTest
    public class TruncateTextInCell {   public static final String DEST = "results/tables/truncate_cell_content.pdf";   public class TruncateContent implements PdfPCellEvent {
            protected String content;
            public TruncateContent(String content) {
                this.content = content;
            }
            public void cellLayout(PdfPCell cell, Rectangle position,
                    PdfContentByte[] canvases) {
                try {
                    BaseFont bf = BaseFont.createFont();
                    Font font = new Font(bf, 12);
                    float availableWidth = position.getWidth();
                    int contentLength = content.length();
                    int leftChar = 0;
                    int rightChar = contentLength - 1;
                    availableWidth -= bf.getWidthPoint("...", 12);
                    while (leftChar < contentLength && rightChar != leftChar) {
                        availableWidth -= bf.getWidthPoint(content.charAt(leftChar), 12);
                        if (availableWidth > 0)
                            leftChar++;
                        else
                            break;
                        availableWidth -= bf.getWidthPoint(content.charAt(rightChar), 12);
                        if (availableWidth > 0)
                            rightChar--;
                        else
                            break;
                    }
                    String newContent = content.substring(0, leftChar) + "..." + content.substring(rightChar);
                    PdfContentByte canvas = canvases[PdfPTable.TEXTCANVAS];
                    ColumnText ct = new ColumnText(canvas);
                    ct.setSimpleColumn(position);
                    ct.addElement(new Paragraph(newContent, font));
                    ct.go();
                } catch (DocumentException e) {
                    throw new ExceptionConverter(e);
                } catch (IOException e) {
                    throw new ExceptionConverter(e);
                }
            }
        }   public static void main(String[] args) throws IOException, DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new TruncateTextInCell().createPdf(DEST);
        }   public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table = new PdfPTable(5);
            table.setWidthPercentage(100);
            PdfPCell cell;
            for (int r = 'A'; r <= 'Z'; r++) {
                for (int c = 1; c <= 5; c++) {
                    cell = new PdfPCell();
                    if (r == 'D' && c == 2) {
                        cell.setCellEvent(new TruncateContent("D2 is a cell with more content than we can fit into the cell."));
                    }
                    else {
                        cell.addElement(new Paragraph(String.valueOf((char) r) + String.valueOf(c)));
                    }
                    table.addCell(cell);
                }
            }
            document.add(table);
            document.close();
        }
    }

    ClipCenterCellContent.java

    /**
     * Example written by Bruno Lowagie in answer to the following question:
     * http://stackoverflow.com/questions/22095320/can-i-tell-itext-how-to-clip-text-to-fit-in-a-cell
     */
    package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.ExceptionConverter;
    import com.itextpdf.text.Paragraph;
    import com.itextpdf.text.Rectangle;
    import com.itextpdf.text.pdf.ColumnText;
    import com.itextpdf.text.pdf.PdfContentByte;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPCellEvent;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfTemplate;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;   import sandbox.WrapToTest;   @WrapToTest
    public class ClipCenterCellContent {   public static final String DEST = "results/tables/clip_center_cell_content.pdf";   public class CenterContent implements PdfPCellEvent {
            protected Paragraph content;
            public CenterContent(Paragraph content) {
                this.content = content;
            }
            public void cellLayout(PdfPCell cell, Rectangle position,
                    PdfContentByte[] canvases) {
                try {
                    PdfContentByte canvas = canvases[PdfPTable.TEXTCANVAS];
                    ColumnText ct = new ColumnText(canvas);
                    ct.setSimpleColumn(new Rectangle(0, 0, position.getWidth(), -1000));
                    ct.addElement(content);
                    ct.go(true);
                    float spaceneeded = 0 - ct.getYLine();
                    System.out.println(String.format("The content requires %s pt whereas the height is %s pt.", spaceneeded, position.getHeight()));
                    float offset = (position.getHeight() - spaceneeded) / 2;
                    System.out.println(String.format("The difference is %s pt; we'll need an offset of %s pt.", -2f * offset, offset));
                    PdfTemplate tmp = canvas.createTemplate(position.getWidth(), position.getHeight());
                    ct = new ColumnText(tmp);
                    ct.setSimpleColumn(0, offset, position.getWidth(), offset + spaceneeded);
                    ct.addElement(content);
                    ct.go();
                    canvas.addTemplate(tmp, position.getLeft(), position.getBottom());
                } catch (DocumentException e) {
                    throw new ExceptionConverter(e);
                }
            }
        }   public static void main(String[] args) throws IOException, DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new ClipCenterCellContent().createPdf(DEST);
        }   public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table = new PdfPTable(5);
            table.setWidthPercentage(100);
            PdfPCell cell;
            for (int r = 'A'; r <= 'Z'; r++) {
                for (int c = 1; c <= 5; c++) {
                    cell = new PdfPCell();
                    if (r == 'D' && c == 2) {
                        cell.setCellEvent(new CenterContent(new Paragraph("D2 is a cell with more content than we can fit into the cell.")));
                    }
                    else {
                        cell.addElement(new Paragraph(String.valueOf((char) r) + String.valueOf(c)));
                    }
                    table.addCell(cell);
                }
            }
            document.add(table);
            document.close();
        }
    }

    Continued on / from next page

    SimpleTable5.java

    /**
     * Example written by Bruno Lowagie in answer to the following question:
     * http://stackoverflow.com/questions/28610545/get-page-number-in-itext
     */
    package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.PageSize;
    import com.itextpdf.text.Phrase;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import sandbox.WrapToTest;   @WrapToTest
    public class SimpleTable5 {
        public static final String DEST = "results/tables/simple_table5.pdf";   public static void main(String[] args) throws IOException,
                DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new SimpleTable5().createPdf(DEST);
        }
        public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document(PageSize.A4.rotate());
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table = new PdfPTable(5);
        	table.setWidthPercentage(100);
        	PdfPCell cell = new PdfPCell(new Phrase("Table XYZ (Continued)"));
            cell.setColspan(5);
        	table.addCell(cell);
        	cell = new PdfPCell(new Phrase("Continue on next page"));
            cell.setColspan(5);
        	table.addCell(cell);
            table.setHeaderRows(2);
            table.setFooterRows(1);
            table.setSkipFirstHeader(true);
            table.setSkipLastFooter(true);
        	for (int i = 0; i < 350; i++) {
                table.addCell(String.valueOf(i+1));
        	}
        	document.add(table);
        	document.close();
        }   }

    Colspan and rowspan

    SimpleRowColspan.java

    /**
     * Example written by Bruno Lowagie in answer to:
     * http://stackoverflow.com/questions/20016630/how-to-create-a-table-in-a-generated-pdf-using-itextsharp
     * 
     * We create a table with five columns, combining rowspan and colspan
     */
    package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Phrase;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;   import sandbox.WrapToTest;   @WrapToTest
    public class SimpleRowColspan {
        public static final String DEST = "results/tables/simple_rowspan_colspan.pdf";   public static void main(String[] args) throws IOException,
                DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new SimpleRowColspan().createPdf(DEST);
        }   public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table = new PdfPTable(5);
            table.setWidths(new int[]{ 1, 2, 2, 2, 1});
            PdfPCell cell;
            cell = new PdfPCell(new Phrase("S/N"));
            cell.setRowspan(2);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("Name"));
            cell.setColspan(3);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("Age"));
            cell.setRowspan(2);
            table.addCell(cell);
            table.addCell("SURNAME");
            table.addCell("FIRST NAME");
            table.addCell("MIDDLE NAME");
            table.addCell("1");
            table.addCell("James");
            table.addCell("Fish");
            table.addCell("Stone");
            table.addCell("17");
            document.add(table);
            document.close();
        }
    }

    ColspanRowspan.java

    /**
     * Example written by Bruno Lowagie in answer to the following question:
     * http://stackoverflow.com/questions/23989852/itext-combining-rowspan-and-colspan-pdfptable
     */
    package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Phrase;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import sandbox.WrapToTest;   @WrapToTest
    public class ColspanRowspan {   public static final String DEST = "results/tables/colspan_rowspan.pdf";   public static void main(String[] args) throws IOException, DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new ColspanRowspan().createPdf(DEST);
        }   public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table = new PdfPTable(4);
            PdfPCell cell = new PdfPCell(new Phrase(" 1,1 "));
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(" 1,2 "));
            table.addCell(cell);
            PdfPCell cell23 = new PdfPCell(new Phrase("multi 1,3 and 1,4"));
            cell23.setColspan(2);
            cell23.setRowspan(2);
            table.addCell(cell23);
            cell = new PdfPCell(new Phrase(" 2,1 "));
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(" 2,2 "));
            table.addCell(cell);
            document.add(table);
            document.close();
        }
    }

    SimpleTable2.java

    /**
     * Example written by Bruno Lowagie and Nishanthi Grashia in answer to the following question:
     * http://stackoverflow.com/questions/24359321/adding-row-to-a-table-in-pdf-using-itext
     */
    package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Phrase;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import sandbox.WrapToTest;   @WrapToTest
    public class SimpleTable2 {
        public static final String DEST = "results/tables/simple_table2.pdf";   public static void main(String[] args) throws IOException,
                DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new SimpleTable2().createPdf(DEST);
        }
        public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table = new PdfPTable(8);
            PdfPCell cell = new PdfPCell(new Phrase("hi"));
            cell.setRowspan(2);
            table.addCell(cell);
            for(int aw = 0; aw < 14; aw++){
                table.addCell("hi");
            }
            document.add(table);
            document.close();
        }   }

    SimpleTable9.java

    /**
     * Example written by Bruno Lowagie in answer to the following question:
     * http://stackoverflow.com/questions/30032558/how-to-show-a-cellcolumn-with-its-row-values-of-a-pdftableitextsharp-in-next
     */
    package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Paragraph;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import sandbox.WrapToTest;   @WrapToTest
    public class SimpleTable9 {
        public static final String DEST = "results/tables/simple_table9.pdf";   public static void main(String[] args) throws IOException,
                DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new SimpleTable9().createPdf(DEST);
        }
        public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            document.add(new Paragraph("With 3 columns:"));
            PdfPTable table = new PdfPTable(3);
            table.setSpacingBefore(5);
            table.setWidths(new int[]{1, 1, 8});
            table.setWidthPercentage(100);
            table.addCell("Col a");
            table.addCell("Col b");
            table.addCell("Col c");
            table.addCell("Value a");
            table.addCell("Value b");
            table.addCell("This is a long description for column c. It needs much more space hence we made sure that the third column is wider.");
            document.add(table);
            document.add(new Paragraph("With 2 columns:"));
            table = new PdfPTable(2);
            table.setSpacingBefore(5);
            table.setWidthPercentage(100);
            table.getDefaultCell().setColspan(1);
            table.addCell("Col a");
            table.addCell("Col b");
            table.addCell("Value a");
            table.addCell("Value b");
            table.getDefaultCell().setColspan(2);
            table.addCell("Value b");
            table.addCell("This is a long description for column c. It needs much more space hence we made sure that the third column is wider.");
            table.getDefaultCell().setColspan(1);
            table.addCell("Col a");
            table.addCell("Col b");
            table.addCell("Value a");
            table.addCell("Value b");
            table.getDefaultCell().setColspan(2);
            table.addCell("Value b");
            table.addCell("This is a long description for column c. It needs much more space hence we made sure that the third column is wider.");
            document.add(table);
            document.close();
        }   }

    SimpleTable11.java

    /**
     * Example written by Bruno Lowagie in answer to the following question:
     * http://stackoverflow.com/questions/31146249/how-to-set-up-a-table-display-in-itextpdf
     */
    package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Element;
    import com.itextpdf.text.Phrase;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import sandbox.WrapToTest;   @WrapToTest
    public class SimpleTable11 {
        public static final String DEST = "results/tables/simple_table11.pdf";   public static void main(String[] args) throws IOException,
                DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new SimpleTable11().createPdf(DEST);
        }
        public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table = new PdfPTable(5);
            table.setWidths(new int[]{1, 2, 1, 1, 1});
            table.addCell(createCell("SKU", 2, 1, Element.ALIGN_LEFT));
            table.addCell(createCell("Description", 2, 1, Element.ALIGN_LEFT));
            table.addCell(createCell("Unit Price", 2, 1, Element.ALIGN_LEFT));
            table.addCell(createCell("Quantity", 2, 1, Element.ALIGN_LEFT));
            table.addCell(createCell("Extension", 2, 1, Element.ALIGN_LEFT));
            String[][] data = {
                {"ABC123", "The descriptive text may be more than one line and the text should wrap automatically", "$5.00", "10", "$50.00"},
                {"QRS557", "Another description", "$100.00", "15", "$1,500.00"},
                {"XYZ999", "Some stuff", "$1.00", "2", "$2.00"}
            };
            for (String[] row : data) {
                table.addCell(createCell(row[0], 1, 1, Element.ALIGN_LEFT));
                table.addCell(createCell(row[1], 1, 1, Element.ALIGN_LEFT));
                table.addCell(createCell(row[2], 1, 1, Element.ALIGN_RIGHT));
                table.addCell(createCell(row[3], 1, 1, Element.ALIGN_RIGHT));
                table.addCell(createCell(row[4], 1, 1, Element.ALIGN_RIGHT));
            }
            table.addCell(createCell("Totals", 2, 4, Element.ALIGN_LEFT));
            table.addCell(createCell("$1,552.00", 2, 1, Element.ALIGN_RIGHT));
            document.add(table);
            document.close();
        }   public PdfPCell createCell(String content, float borderWidth, int colspan, int alignment) {
            PdfPCell cell = new PdfPCell(new Phrase(content));
            cell.setBorderWidth(borderWidth);
            cell.setColspan(colspan);
            cell.setHorizontalAlignment(alignment);
            return cell;
        }   }

    SimpleTable12.java

    /**
     * Example written by Bruno Lowagie in answer to the following question:
     * http://stackoverflow.com/questions/31263533/how-to-create-nested-column-using-itextsharp
     */
    package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Element;
    import com.itextpdf.text.Font;
    import com.itextpdf.text.Font.FontFamily;
    import com.itextpdf.text.Phrase;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import sandbox.WrapToTest;   @WrapToTest
    public class SimpleTable12 {
        public static final String DEST = "results/tables/simple_table12.pdf";   protected Font font;   public static void main(String[] args) throws IOException,
                DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new SimpleTable12().createPdf(DEST);
        }
        public void createPdf(String dest) throws IOException, DocumentException {
            font = new Font(FontFamily.HELVETICA, 10);
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table = new PdfPTable(8);
            table.setWidthPercentage(100);
            table.addCell(createCell("Examination", 1, 2, PdfPCell.BOX));
            table.addCell(createCell("Board", 1, 2, PdfPCell.BOX));
            table.addCell(createCell("Month and Year of Passing", 1, 2, PdfPCell.BOX));
            table.addCell(createCell("", 1, 1, PdfPCell.TOP));
            table.addCell(createCell("Marks", 2, 1, PdfPCell.TOP));
            table.addCell(createCell("Percentage", 1, 2, PdfPCell.BOX));
            table.addCell(createCell("Class / Grade", 1, 2, PdfPCell.BOX));
            table.addCell(createCell("", 1, 1, PdfPCell.BOX));
            table.addCell(createCell("Obtained", 1, 1, PdfPCell.BOX));
            table.addCell(createCell("Out of", 1, 1, PdfPCell.BOX));
            table.addCell(createCell("12th / I.B. Diploma", 1, 1, PdfPCell.BOX));
            table.addCell(createCell("", 1, 1, PdfPCell.BOX));
            table.addCell(createCell("", 1, 1, PdfPCell.BOX));
            table.addCell(createCell("Aggregate (all subjects)", 1, 1, PdfPCell.BOX));
            table.addCell(createCell("", 1, 1, PdfPCell.BOX));
            table.addCell(createCell("", 1, 1, PdfPCell.BOX));
            table.addCell(createCell("", 1, 1, PdfPCell.BOX));
            table.addCell(createCell("", 1, 1, PdfPCell.BOX));
            document.add(table);
            document.close();
        }   public PdfPCell createCell(String content, int colspan, int rowspan, int border) {
            PdfPCell cell = new PdfPCell(new Phrase(content, font));
            cell.setColspan(colspan);
            cell.setRowspan(rowspan);
            cell.setBorder(border);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            return cell;
        }   }

    RowspanAbsolutePosition.java

    /**
     * Example written by Bruno Lowagie in answer to:
     * http://stackoverflow.com/questions/23730886/row-span-not-working-for-writeselectedrows-method
     * 
     * We create a table with five columns, combining rowspan and colspan
     */
    package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Element;
    import com.itextpdf.text.Image;
    import com.itextpdf.text.Phrase;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import sandbox.WrapToTest;   @WrapToTest
    public class RowspanAbsolutePosition {
        public static final String DEST = "results/tables/write_selected_colspan.pdf";
        public static final String IMG = "resources/images/berlin2013.jpg";   public static void main(String[] args) throws IOException,
                DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new RowspanAbsolutePosition().createPdf(DEST);
        }   public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table1 = new PdfPTable(3);
            table1.setWidths(new int[]{15,20,20});
            table1.setTotalWidth(555);
            PdfPCell cell = new PdfPCell(new Phrase("{Month}"));
            cell.setColspan(2);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            Image img = Image.getInstance(IMG);
            img.scaleToFit(555f * 20f / 55f, 10000);
            PdfPCell cell2 = new PdfPCell(img, false);
            cell2.setRowspan(2);
            PdfPCell cell3 = new PdfPCell(new Phrase("Mr Fname Lname"));
            cell3.setColspan(2);
            cell3.setHorizontalAlignment(Element.ALIGN_LEFT);
            table1.addCell(cell);
            table1.addCell(cell2);
            table1.addCell(cell3);
            table1.writeSelectedRows(0, -1, 20 , 820, writer.getDirectContent());
            document.close();
        }
    }

    TableMeasurements.java

    /*
     * Example written in answer to:
     * http://stackoverflow.com/questions/34539028
     */
    package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Element;
    import com.itextpdf.text.Font;
    import com.itextpdf.text.Paragraph;
    import com.itextpdf.text.Utilities;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;   /**
     *
     * @author Bruno Lowagie (iText Software)
     */
    public class TableMeasurements {
        public static final String DEST = "results/tables/table_measurements.pdf";   public static void main(String[] args) throws IOException,
                DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new TableMeasurements().createPdf(DEST);
        }
        public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table = new PdfPTable(10);
            table.setTotalWidth(Utilities.millimetersToPoints(100));
            table.setLockedWidth(true);
            table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
            table.addCell(getCell(10));
            table.addCell(getCell(5));
            table.addCell(getCell(3));
            table.addCell(getCell(2));
            table.addCell(getCell(3));
            table.addCell(getCell(5));
            table.addCell(getCell(1));
            table.completeRow();
            document.add(table);
            document.close();
        }   private PdfPCell getCell(int cm) {
            PdfPCell cell = new PdfPCell();
            cell.setColspan(cm);
            cell.setUseAscender(true);
            cell.setUseDescender(true);
            Paragraph p = new Paragraph(
                    String.format("%smm", 10 * cm),
                    new Font(Font.FontFamily.HELVETICA, 8));
            p.setAlignment(Element.ALIGN_CENTER);
            cell.addElement(p);
            return cell;
        }
    }
     

    Cell heights

    CellHeights.java

    /*
     * Example written by Bruno Lowagie.
     */   package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.PageSize;
    import com.itextpdf.text.Phrase;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import sandbox.WrapToTest;   @WrapToTest
    public class CellHeights {
        /** The resulting PDF file. */
        public static final String DEST = "results/tables/cell_heights.pdf";   public static void main(String[] args) throws IOException,
                DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new CellHeights().createPdf(DEST);
        }   public void createPdf(String dest) throws DocumentException, IOException {
        	// step 1
            Document document = new Document(PageSize.A5.rotate());
            // step 2
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            // step 3
            document.open();
            // step 4
            PdfPTable table = new PdfPTable(2);
            // a long phrase
            Phrase p = new Phrase(
                "Dr. iText or: How I Learned to Stop Worrying and Love PDF.");
            PdfPCell cell = new PdfPCell(p);
            // the prhase is wrapped
            table.addCell("wrap");
            cell.setNoWrap(false);
            table.addCell(cell);
            // the phrase isn't wrapped
            table.addCell("no wrap");
            cell.setNoWrap(true);
            table.addCell(cell);
            // a long phrase with newlines
            p = new Phrase(
                "Dr. iText or:
    How I Learned to Stop Worrying
    and Love PDF.");
            cell = new PdfPCell(p);
            // the phrase fits the fixed height
            table.addCell("fixed height (more than sufficient)");
            cell.setFixedHeight(72f);
            table.addCell(cell);
            // the phrase doesn't fit the fixed height
            table.addCell("fixed height (not sufficient)");
            cell.setFixedHeight(36f);
            table.addCell(cell);
            // The minimum height is exceeded
            table.addCell("minimum height");
            cell = new PdfPCell(new Phrase("Dr. iText"));
            cell.setMinimumHeight(36f);
            table.addCell(cell);
            // The last row is extended
            table.setExtendLastRow(true);
            table.addCell("extend last row");
            table.addCell(cell);
            document.add(table);
            // step 5
            document.close();
        }
    }

    FixedHeightCell.java

    /**
     * Example written by Bruno Lowagie in answer to the following question:
     * http://stackoverflow.com/questions/22093745/itext-how-do-setminimumsize-and-setfixedsize-interact
     */
    package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Paragraph;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;   import sandbox.WrapToTest;   @WrapToTest
    public class FixedHeightCell {   public static final String DEST = "results/tables/fixed_height_cell.pdf";   public static void main(String[] args) throws IOException, DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new FixedHeightCell().createPdf(DEST);
        }   public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table = new PdfPTable(5);
            table.setWidthPercentage(100);
            PdfPCell cell;
            for (int r = 'A'; r <= 'Z'; r++) {
                for (int c = 1; c <= 5; c++) {
                    cell = new PdfPCell();
                    cell.addElement(new Paragraph(String.valueOf((char) r) + String.valueOf(c)));
                    if (r == 'D')
                        cell.setFixedHeight(60);
                    if (r == 'E') {
                        cell.setFixedHeight(60);
                        if (c == 4)
                            cell.setFixedHeight(120);
                    }
                    if (r == 'F') {
                        cell.setMinimumHeight(120);
                        cell.setFixedHeight(60);
                        if (c == 2)
                            cell.addElement(new Paragraph("This cell has more content than the other cells"));
                    }
                    table.addCell(cell);
                }
            }
            document.add(table);
            document.close();
        }
    }

    FitTableOnPage.java

    /**
     * Example written by Bruno Lowagie in answer to:
     * http://stackoverflow.com/questions/24616920/last-row-in-itext-table-extending-when-it-shouldnt
     */   package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Phrase;
    import com.itextpdf.text.Rectangle;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import sandbox.WrapToTest;   @WrapToTest
    public class FitTableOnPage {
        public static final String DEST = "results/tables/fit_table_on_page.pdf";   public static void main(String[] args) throws IOException, DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new FitTableOnPage().createPdf(DEST);
        }   public void createPdf(String dest) throws IOException, DocumentException {
            PdfPTable table = new PdfPTable(1);
            table.setTotalWidth(550);
            table.setLockedWidth(true);
            for (int i = 0; i < 10; i++) {
                PdfPCell cell;
                if (i == 9) {
                    cell = new PdfPCell(new Phrase("Two
    Lines"));
                }
                else {
                    cell = new PdfPCell(new Phrase(Integer.toString(i)));
                }
                table.addCell(cell);
            }
            Document document = new Document(new Rectangle(612, table.getTotalHeight() + 72));
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            document.add(table);
            document.close();
        }
    }
     

    Cell borders (without cell or table events)

    ColoredBorder.java

    /**
     * Example written by Bruno Lowagie in answer to the following question:
     * http://stackoverflow.com/questions/35073619
     */
    package sandbox.tables;   import com.itextpdf.text.BaseColor;
    import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Element;
    import com.itextpdf.text.Font;
    import com.itextpdf.text.FontFactory;
    import com.itextpdf.text.Phrase;
    import com.itextpdf.text.Rectangle;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import sandbox.WrapToTest;   @WrapToTest
    public class ColoredBorder {
        public static final String DEST = "results/tables/colored_border.pdf";   public static void main(String[] args) throws IOException,
                DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new ColoredBorder().createPdf(DEST);
        }
        public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table;
            table = new PdfPTable(2);
            PdfPCell cell;
            cell = new PdfPCell(new Phrase("Cell 1"));
            cell.setUseVariableBorders(true);
            cell.setBorderColorTop(BaseColor.RED);
            cell.setBorderColorBottom(BaseColor.BLUE);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("Cell 2"));
            cell.setBorderWidthLeft(5);
            cell.setBorderColorLeft(BaseColor.GREEN);
            cell.setBorderWidthTop(8);
            cell.setBorderColorTop(BaseColor.YELLOW);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("Cell 3"));
            cell.setUseVariableBorders(true);
            cell.setBorder(Rectangle.LEFT | Rectangle.BOTTOM);
            cell.setBorderColorLeft(BaseColor.RED);
            cell.setBorderColorBottom(BaseColor.BLUE);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase("Cell 4"));
            cell.setBorder(Rectangle.LEFT | Rectangle.TOP);
            cell.setUseBorderPadding(true);
            cell.setBorderWidthLeft(5);
            cell.setBorderColorLeft(BaseColor.GREEN);
            cell.setBorderWidthTop(8);
            cell.setBorderColorTop(BaseColor.YELLOW);
            table.addCell(cell);
            document.add(table);
            document.close();
        }   }
     

    Cell and table widths

    d createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document(PageSize.A4.rotate());
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            float[] columnWidths = {1, 5, 5};
            PdfPTable table = new PdfPTable(columnWidths);
            table.setWidthPercentage(100);
            table.getDefaultCell().setUseAscender(true);
            table.getDefaultCell().setUseDescender(true);
            Font f = new Font(FontFamily.HELVETICA, 13, Font.NORMAL, GrayColor.GRAYWHITE);
            PdfPCell cell = new PdfPCell(new Phrase("This is a header", f));
            cell.setBackgroundColor(GrayColor.GRAYBLACK);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(3);
            table.addCell(cell);
            table.getDefaultCell().setBackgroundColor(new GrayColor(0.75f));
            for (int i = 0; i < 2; i++) {
                table.addCell("#");
                table.addCell("Key");
                table.addCell("Value");
            }
            table.setHeaderRows(3);
            table.setFooterRows(1);
            table.getDefaultCell().setBackgroundColor(GrayColor.GRAYWHITE);
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            for (int counter = 1; counter < 101; counter++) {
                table.addCell(String.valueOf(counter));
                table.addCell("key " + counter);
                table.addCell("value " + counter);
            }
            document.add(table);
            document.close();
        }
    }

    FullPageTable.java

    /**
     * Example written by Bruno Lowagie in answer to:
     * http://stackoverflow.com/questions/19873263/how-to-increase-the-width-of-pdfptable-in-itext-pdf
     * 
     * We create a table with two columns and two cells.
     * This way, we can add two images next to each other.
     */
    package sandbox.tables;   import com.itextpdf.text.BaseColor;
    import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Element;
    import com.itextpdf.text.PageSize;
    import com.itextpdf.text.Phrase;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;   import sandbox.WrapToTest;   @WrapToTest
    public class FullPageTable {   public static final String DEST = "results/tables/full_page_table.pdf";   public static void main(String[] args) throws IOException,
                DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new FullPageTable().createPdf(DEST);
        }   public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document(PageSize.A4, 0, 0, 0, 0);
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table = new PdfPTable(10);   table.setWidthPercentage(100);
            table.setSpacingBefore(0f);
            table.setSpacingAfter(0f);   // first row
            PdfPCell cell = new PdfPCell(new Phrase("DateRange"));
            cell.setColspan(10);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setPadding(5.0f);
            cell.setBackgroundColor(new BaseColor(140, 221, 8));
            table.addCell(cell);   table.addCell("Calldate");
            table.addCell("Calltime");
            table.addCell("Source");
            table.addCell("DialedNo");
            table.addCell("Extension");
            table.addCell("Trunk");
            table.addCell("Duration");
            table.addCell("Calltype");
            table.addCell("Callcost");
            table.addCell("Site");   for (int i = 0; i < 100; i++) {
                table.addCell("date" + i);
                table.addCell("time" + i);
                table.addCell("source" + i);
                table.addCell("destination" + i);
                table.addCell("extension" + i);
                table.addCell("trunk" + i);
                table.addCell("dur" + i);
                table.addCell("toc" + i);
                table.addCell("callcost" + i);
                table.addCell("Site" + i);
            }
            document.add(table);
            document.close();
        }
    }

    RightCornerTable.java

    /**
     * Example written by Bruno Lowagie and Nishanthi Grashia in answer to the following question:
     * http://stackoverflow.com/questions/33440294/create-table-in-itext-pdf-in-java
     */
    package sandbox.tables;   import com.itextpdf.text.BaseColor;
    import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Element;
    import com.itextpdf.text.Font;
    import com.itextpdf.text.Phrase;
    import com.itextpdf.text.Rectangle;
    import com.itextpdf.text.pdf.PdfContentByte;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import sandbox.WrapToTest;   @WrapToTest
    public class RightCornerTable {
        public static final String DEST = "results/tables/right_corner_table.pdf";   public static void main(String[] args) throws IOException,
                DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new RightCornerTable().createPdf(DEST);
        }   public void createPdf(String dest) throws IOException, DocumentException {
            Rectangle pagesize = new Rectangle(300, 300);
            Document document = new Document(pagesize, 0, 0, 0, 0);
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table = new PdfPTable(1);
            table.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.setWidthPercentage(30);
            Font white = new Font();
            white.setColor(BaseColor.WHITE);
            PdfPCell cell = new PdfPCell(new Phrase(" Date" , white));
            cell.setBackgroundColor(BaseColor.BLACK);
            cell.setBorderColor(BaseColor.GRAY);
            cell.setBorderWidth(2f);
            table.addCell(cell);
            PdfPCell cellTwo = new PdfPCell(new Phrase("10/01/2015"));
            cellTwo.setBorderWidth(2f);
            table.addCell(cellTwo);
            document.add(table);
            document.newPage();
            table.setTotalWidth(90);
            PdfContentByte canvas = writer.getDirectContent();
            table.writeSelectedRows(0, -1, document.right() - 90, document.top(), canvas);
            document.close();
        }   }

    SimpleTable3.java

    /**
     * Example written by Bruno Lowagie in answer to the following question:
     * http://stackoverflow.com/questions/27884229/itextsharap-error-while-adding-pdf-table-to-document
     */
    package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.PageSize;
    import com.itextpdf.text.Phrase;
    import com.itextpdf.text.pdf.PdfPCell;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import sandbox.WrapToTest;   @WrapToTest
    public class SimpleTable3 {
        public static final String DEST = "results/tables/simple_table3.pdf";   public static void main(String[] args) throws IOException,
                DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new SimpleTable3().createPdf(DEST);
        }
        public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document(PageSize.A3.rotate());
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table = new PdfPTable(35);
            table.setTotalWidth(document.getPageSize().getWidth() - 80);
            table.setLockedWidth(true);
            PdfPCell contractor = new PdfPCell(new Phrase("XXXXXXXXXXXXX"));
            contractor.setColspan(5);
            table.addCell(contractor);
            PdfPCell workType = new PdfPCell(new Phrase("Refractory Works"));
            workType.setColspan(5);
            table.addCell(workType);
            PdfPCell supervisor = new PdfPCell(new Phrase("XXXXXXXXXXXXXX"));
            supervisor.setColspan(4);
            table.addCell(supervisor);
            PdfPCell paySlipHead = new PdfPCell(new Phrase("XXXXXXXXXXXXXXXX"));
            paySlipHead.setColspan(10);
            table.addCell(paySlipHead);
            PdfPCell paySlipMonth = new PdfPCell(new Phrase("XXXXXXX"));
            paySlipMonth.setColspan(2);
            table.addCell(paySlipMonth);
            PdfPCell blank = new PdfPCell(new Phrase(""));
            blank.setColspan(9);
            table.addCell(blank);
            document.add(table);
            document.close();
        }   }
     

    Alternatives to using a PdfPTable

    SimpleTable13.java

    /**
     * Example written by Bruno Lowagie in answer to the following question:
     * http://stackoverflow.com/questions/34480476
     */
    package sandbox.tables;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Element;
    import com.itextpdf.text.Rectangle;
    import com.itextpdf.text.pdf.PdfPTable;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import sandbox.WrapToTest;   @WrapToTest
    public class SimpleTable13 {
        public static final String DEST = "results/tables/simple_table13.pdf";
        public static final String[][] DATA = {
            {"John Edward Jr.", "AAA"},
            {"Pascal Einstein W. Alfi", "BBB"},
            {"St. John", "CCC"}
        };   public static void main(String[] args) throws IOException,
                DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new SimpleTable13().createPdf(DEST);
        }
        public void createPdf(String dest) throws IOException, DocumentException {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(dest));
            document.open();
            PdfPTable table = new PdfPTable(2);
            table.setWidthPercentage(50);
            table.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.setWidths(new int[]{5, 1});
            table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            table.addCell("Name: " + DATA[0][0]);
            table.addCell(DATA[0][1]);
            table.addCell("Surname: " + DATA[1][0]);
            table.addCell(DATA[1][1]);
            table.addCell("School: " + DATA[2][0]);
            table.addCell(DATA[1][1]);
            document.add(table);
            document.close();
        }
    }

    TableTab.java

    /**
     * Example written by Bruno Lowagie in answer to:
     * http://stackoverflow.com/questions/34480476
     */
    package sandbox.objects;   import com.itextpdf.text.Chunk;
    import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Paragraph;
    import com.itextpdf.text.TabSettings;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;   import sandbox.WrapToTest;   @WrapToTest
    public class TableTab {   public static final String DEST = "results/objects/tab_table.pdf";
        public static final String[][] DATA = {
            {"John Edward Jr.", "AAA"},
            {"Pascal Einstein W. Alfi", "BBB"},
            {"St. John", "CCC"}
        };   public static void main(String[] args) throws IOException, DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new TableTab().createPdf(DEST);
        }   public void createPdf(String dest) throws FileNotFoundException, DocumentException {
            Document document = new Document();   PdfWriter.getInstance(document, new FileOutputStream(dest));   document.open();   document.add(createParagraphWithTab("Name: ", DATA[0][0], DATA[0][1]));
            document.add(createParagraphWithTab("Surname: ", DATA[1][0], DATA[1][1]));
            document.add(createParagraphWithTab("School: ", DATA[2][0], DATA[2][1]));   document.close();
        }   public Paragraph createParagraphWithTab(String key, String value1, String value2) {
            Paragraph p = new Paragraph();
            p.setTabSettings(new TabSettings(200f));
            p.add(key);
            p.add(value1);
            p.add(Chunk.TABBING);
            p.add(value2);
            return p;
        }
    }

    TableSpace.java

    /**
     * Example written by Bruno Lowagie in answer to:
     * http://stackoverflow.com/questions/34480476
     */
    package sandbox.objects;   import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.Font;
    import com.itextpdf.text.Paragraph;
    import com.itextpdf.text.pdf.BaseFont;
    import com.itextpdf.text.pdf.PdfWriter;   import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;   import sandbox.WrapToTest;   @WrapToTest
    public class TableSpace {   public static final String DEST = "results/objects/spaces_table.pdf";
        public static final String FONT = "resources/fonts/PTM55FT.ttf";
        public static final String[][] DATA = {
            {"John Edward Jr.", "AAA"},
            {"Pascal Einstein W. Alfi", "BBB"},
            {"St. John", "CCC"}
        };   public static void main(String[] args) throws IOException, DocumentException {
            File file = new File(DEST);
            file.getParentFile().mkdirs();
            new TableSpace().createPdf(DEST);
        }   public void createPdf(String dest) throws DocumentException, IOException {
            Document document = new Document();   PdfWriter.getInstance(document, new FileOutputStream(dest));   document.open();   BaseFont bf = BaseFont.createFont(FONT, BaseFont.CP1250, BaseFont.EMBEDDED);
            Font font = new Font(bf, 12);   document.add(createParagraphWithSpaces(font, String.format("%s: %s", "Name", DATA[0][0]), DATA[0][1]));
            document.add(createParagraphWithSpaces(font, String.format("%s: %s", "Surname", DATA[1][0]), DATA[1][1]));
            document.add(createParagraphWithSpaces(font, String.format("%s: %s", "School", DATA[2][0]), DATA[2][1]));   document.close();
        }   public Paragraph createParagraphWithSpaces(Font font, String value1, String value2) {
            Paragraph p = new Paragraph();
            p.setFont(font);
            p.add(String.format("%-35s", value1));
            p.add(value2);
            return p;
        }
    }
  • 相关阅读:
    简单的JAVAWeb选课系统
    公文流转系统001
    第九周动手动脑
    JAVA文件操作
    动手动脑-异常处理
    个人NABCD
    水王(课堂作业)
    软件学习进度表07
    软件工程学习进度表06
    软件工程个人作业05(二维数组求最大子数组的和)
  • 原文地址:https://www.cnblogs.com/zhc-hnust/p/5602144.html
Copyright © 2020-2023  润新知