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:\nHow I Learned to Stop Worrying\nand 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\nLines"));
}
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;
}
}

ItextDemo<二>的更多相关文章

  1. 【小程序分享篇 二 】web在线踢人小程序,维持用户只能在一个台电脑持登录状态

    最近离职了, 突然记起来还一个小功能没做, 想想也挺简单,留下代码和思路给同事做个参考. 换工作心里挺忐忑, 对未来也充满了憧憬与担忧.(虽然已是老人, 换了N次工作了,但每次心里都和忐忑). 写写代 ...

  2. 前端开发中SEO的十二条总结

    一. 合理使用title, description, keywords二. 合理使用h1 - h6, h1标签的权重很高, 注意使用频率三. 列表代码使用ul, 重要文字使用strong标签四. 图片 ...

  3. 【疯狂造轮子-iOS】JSON转Model系列之二

    [疯狂造轮子-iOS]JSON转Model系列之二 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 上一篇<[疯狂造轮子-iOS]JSON转Model系列之一> ...

  4. 【原】Android热更新开源项目Tinker源码解析系列之二:资源文件热更新

    上一篇文章介绍了Dex文件的热更新流程,本文将会分析Tinker中对资源文件的热更新流程. 同Dex,资源文件的热更新同样包括三个部分:资源补丁生成,资源补丁合成及资源补丁加载. 本系列将从以下三个方 ...

  5. 谈谈一些有趣的CSS题目(十二)-- 你该知道的字体 font-family

    开本系列,谈谈一些有趣的 CSS 题目,题目类型天马行空,想到什么说什么,不仅为了拓宽一下解决问题的思路,更涉及一些容易忽视的 CSS 细节. 解题不考虑兼容性,题目天马行空,想到什么说什么,如果解题 ...

  6. MIP改造常见问题二十问

    在MIP推出后,我们收到了很多站长的疑问和顾虑.我们将所有疑问和顾虑归纳为以下二十个问题,希望对大家理解 MIP 有帮助. 1.MIP 化后对其他搜索引擎抓取收录以及 SEO 的影响如何? 答:在原页 ...

  7. 如何一步一步用DDD设计一个电商网站(二)—— 项目架构

    阅读目录 前言 六边形架构 终于开始建项目了 DDD中的3个臭皮匠 CQRS(Command Query Responsibility Segregation) 结语 一.前言 上一篇我们讲了DDD的 ...

  8. ASP.NET Core 之 Identity 入门(二)

    前言 在 上篇文章 中讲了关于 Identity 需要了解的单词以及相对应的几个知识点,并且知道了Identity处在整个登入流程中的位置,本篇主要是在 .NET 整个认证系统中比较重要的一个环节,就 ...

  9. MVVM模式和在WPF中的实现(二)数据绑定

    MVVM模式解析和在WPF中的实现(二) 数据绑定 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在WPF中 ...

随机推荐

  1. Win10光驱不见了

    1. 网上教程试了很多,如下: http://jingyan.baidu.com/article/02027811656a8b1bcd9ce570.html http://jingyan.todgo. ...

  2. iptables--简单的防火墙

    iptables--简单的防火墙 如果你执行iptables --list你将看到防火墙上的可用规则.下例说明当前系统没有定义防火墙,你可以看到,它显示了默认的filter表,以及表内默认的input ...

  3. WebViewJavascriptBridge详细使用(转载)

    WebViewJavascriptBridge是支持到iOS6之前的版本的,用于支持native的iOS与javascript交互.如果需要支持到iOS6之前的app,使用它是很不错的.本篇讲讲Web ...

  4. Ubuntu 12.04搭建l2tp服务器记录。

    1. 安装openswan apt-get install openswan 2.打开 /etc/ipsec.conf 文件,做如下配置: 其中,virtual_privat这里包含的网络地址允许配置 ...

  5. Centos下安装Mongodb

    转自:http://nnzhp.cn/article/10/ Mongodb是一种nosql类型的数据库,高性能.易部署.易使用的特点在IT行业非常流行. 下面介绍一下mongodb的安装方式,这里我 ...

  6. VideoToolbox硬件编解码H.264视频流错误码

    如果你不能找到在VTD中的错误代码我决定只包括他们在这里. (同样,所有这些错误,并更可以在里面VideoToolbox在Project Navigator中找到.本身).  您将获得无论是在VTD中 ...

  7. VUE 入门基础(7)

    八,事件处理器 监听事件 可以用v-on 指令监听DOM 事件来触发一些javaScript <div id="example-1"> <button v-on: ...

  8. PHP文件缓存实现

    有些时候,我们不希望使用redis等第三方缓存,使得系统依赖于其他服务.这时候,文件缓存会是一个不错的选择. 我们需要文件缓存实现哪些共更能: 功能实现:get.set.has.increment.d ...

  9. iOS GCD, 同步,异步,串行队列,并行队列,dispatch_group

    同步,指代码在同一个线程运行 异步,代码在另一个线程运行 串行队列,提交到该队列的block会顺序执行 并行队列,提交到该队列的block会并发执行 如果想等某一队列中所有block都执行完了在执行一 ...

  10. VR发展的最大障碍在于内容?

    VR目前基本处于半死不活的状态,国内基本就是一堆的VR“盒子”在浑水摸鱼,就小米有点自知之明,冠以“玩具”的定位.但是说到VR发展的最大问题,居然说是什么内容没有吸引力,真让人无语啊.另外,还有什么价 ...