Links in tables

This is a code example of iText PDF, discover more.

10th November 2015
admin-marketing

Switch code for this example

Example that adds a link into a table that is added using writeSelectedRows().



LinkInPositionedTable.java
  1. /*
  2.  * Example written in answer to:
  3.  * http://stackoverflow.com/questions/33633363/itextpdf-cannot-use-writeselectedrows-on-a-table-where-an-anchor-has-been-in
  4.  */
  5. package sandbox.tables;
  6.  
  7. import com.itextpdf.text.Anchor;
  8. import com.itextpdf.text.Document;
  9. import com.itextpdf.text.DocumentException;
  10. import com.itextpdf.text.Paragraph;
  11. import com.itextpdf.text.pdf.PdfPCell;
  12. import com.itextpdf.text.pdf.PdfPTable;
  13. import com.itextpdf.text.pdf.PdfWriter;
  14. import java.io.File;
  15. import java.io.FileOutputStream;
  16. import java.io.IOException;
  17. import sandbox.WrapToTest;
  18.  
  19. /**
  20.  * @author iText
  21.  */
  22. @WrapToTest
  23. public class LinkInPositionedTable {
  24.    
  25.     public static final String DEST = "results/tables/link_in_positioned_table.pdf";
  26.  
  27.     public static void main(String[] args) throws IOException,
  28.             DocumentException {
  29.         File file = new File(DEST);
  30.         file.getParentFile().mkdirs();
  31.         new LinkInPositionedTable().createPdf(DEST);
  32.     }
  33.    
  34.     public void createPdf(String dest) throws IOException, DocumentException {
  35.         Document document = new Document();
  36.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
  37.         document.open();
  38.         PdfPTable table = new PdfPTable(1);
  39.         table.setTotalWidth(500);
  40.         PdfPCell cell = new PdfPCell();
  41.         Paragraph p = new Paragraph();  
  42.         Anchor anchor = new Anchor("link to top of next page");
  43.         anchor.setReference("#top");
  44.         p.add(anchor);
  45.         cell.addElement(p);
  46.         table.addCell(cell);
  47.         table.writeSelectedRows(0, -1, 36, 700, writer.getDirectContent());
  48.         document.newPage();
  49.         Anchor target = new Anchor("top");
  50.         target.setName("top");
  51.         document.add(target);
  52.         document.close();
  53.     }
  54. }
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now