Skip to content

Instantly share code, notes, and snippets.

@behumble
Last active July 16, 2018 04:20
Show Gist options
  • Save behumble/6dccecbb7fdcb4ac6d60f8387ca66a11 to your computer and use it in GitHub Desktop.
Save behumble/6dccecbb7fdcb4ac6d60f8387ca66a11 to your computer and use it in GitHub Desktop.
an iText 5 Outline example to implement two columned target
package com.itextpdf;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfDestination;
import com.itextpdf.text.pdf.PdfOutline;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
public class Support01 {
private static void addParagraphs(Document document, int count) throws Exception {
for(int i=0;i<count;i++) {
Paragraph p = new Paragraph("This is a Paragraph#"+i);
document.add(p);
}
}
private static void addTable(Document document, PdfWriter pdfWriter) throws Exception {
PdfPTable table = new PdfPTable(2);
table.addCell("First cell");
table.addCell("Second cell");
// Two cells have shared Y position.
PdfDestination sharedDest = new PdfDestination(PdfDestination.FITH, pdfWriter.getVerticalPosition(false));
PdfOutline firstCellOutline = new PdfOutline(pdfWriter.getRootOutline(), sharedDest, "First Cell");
PdfOutline secondCellOutline = new PdfOutline(pdfWriter.getRootOutline(), sharedDest, "Second Cell");
document.add(table);
}
private static void addTableAbsolute(Document document, PdfWriter pdfWriter) throws Exception {
PdfPTable table = new PdfPTable(2);
table.setTotalWidth(400);
table.addCell("1st abs. Cell");
table.addCell("2nd abs. Cell");
float yPos = 200;
// Two cells have shared Y position.
PdfDestination sharedDest = new PdfDestination(PdfDestination.FITH, yPos);
PdfOutline firstCellOutline = new PdfOutline(pdfWriter.getRootOutline(), sharedDest, "1st abs. Cell");
PdfOutline secondCellOutline = new PdfOutline(pdfWriter.getRootOutline(), sharedDest, "2nd abs. Cell");
table.writeSelectedRows(0, -1, 0, yPos, pdfWriter.getDirectContent());
}
private static void createPdfWithTableAndOutline() throws Exception {
Document document = new Document();
FileOutputStream fos = new FileOutputStream("tableoutline.pdf");
PdfWriter pdfWriter = PdfWriter.getInstance(document, fos);
document.open();
// add a paragraphs
addParagraphs(document, 20);
// add a 2 column table
addTable(document, pdfWriter);
// add a 2 column table with absolute position
addTableAbsolute(document, pdfWriter);
// add a paragraphs
addParagraphs(document, 30);
document.close();
}
public static void main(String[] args) throws Exception {
createPdfWithTableAndOutline();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment