Example usage for com.lowagie.text.pdf PdfWriter setPageEvent

List of usage examples for com.lowagie.text.pdf PdfWriter setPageEvent

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfWriter setPageEvent.

Prototype


public void setPageEvent(PdfPageEvent event) 

Source Link

Document

Sets the PdfPageEvent for this document.

Usage

From source file:org.unitime.timetable.export.PDFPrinter.java

License:Open Source License

@Override
public void close() throws IOException {
    try {/*from ww w . ja v a2  s  .c o  m*/
        float width = 0;
        float[] w = new float[iMaxWidth.length - iHiddenColumns.size()];
        int wi = 0;
        for (int i = 0; i < iMaxWidth.length; i++)
            if (!iHiddenColumns.contains(i)) {
                width += 15f + iMaxWidth[i];
                w[wi++] = iMaxWidth[i];
            }
        Document document = new Document(new Rectangle(60f + width, 60f + width * 0.75f), 30f, 30f, 30f, 30f);
        PdfWriter writer = PdfWriter.getInstance(document, iOutput);
        writer.setPageEvent(new PdfEventHandler());
        document.open();
        iTable.setWidths(w);
        document.add(iTable);
        document.close();
    } catch (DocumentException e) {
        throw new IOException(e.getMessage(), e);
    }
}

From source file:org.unitime.timetable.export.solver.ExportTimetablePDF.java

License:Apache License

protected void printTables(FilterInterface filter, TimetableGridResponse response, ExportHelper helper)
        throws IOException {
    helper.setup("application/pdf", reference(), true);
    try {//  w  w  w  . j  a v  a 2  s.c om
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, helper.getOutputStream());
        writer.setPageEvent(new PdfEventHandler());
        int index = 0;
        int margin = 50;
        int width = 1000;
        for (TimetableGridModel model : response.getModels())
            width = Math.max(width, pageWidth(filter, model, response.getWeekOffset()));
        int displayMode = Integer.valueOf(filter.getParameterValue("dispMode", "0"));
        int height = (displayMode == 2 ? (2 * margin + width) * 22 / 17 - 2 * margin
                : (2 * margin + width) * 17 / 22 - 2 * margin);
        for (TimetableGridModel model : response.getModels())
            height = Math.max(height, pageHeight(filter, model, response.getWeekOffset(), true));
        document.setPageSize(new Rectangle(width + 2 * margin, height + 2 * margin));
        document.setMargins(margin, margin, margin, margin);
        document.open();
        int used = 0;
        if (Integer.valueOf(filter.getParameterValue("dispMode", "0")) == 0) {
            boolean hasDay[] = { true, true, true, true, true, false, false };
            String days = filter.getParameterValue("days");
            if (days != null && days.length() == 7 && days.indexOf('1') >= 0) {
                for (int i = 0; i < 7; i++)
                    hasDay[i] = (days.charAt(i) == '1');
            }
            for (int i = 0; i < 7; i++) {
                if (!hasDay[i])
                    continue;
                String d = "";
                for (int j = 0; j < 7; j++)
                    d += (i == j ? "1" : "0");
                filter.getParameter("days").setValue(d);
                boolean first = true;
                for (TimetableGridModel model : response.getModels()) {
                    if (used > 0
                            && pageHeight(filter, model, response.getWeekOffset(), first) > height - used) {
                        document.newPage();
                        used = 0;
                    }
                    TimetableGrid tg = new TimetableGrid(filter, model, index++, width,
                            response.getWeekOffset(), used == 0 || first);
                    PdfContentByte canvas = writer.getDirectContent();
                    tg.print(canvas, margin, margin + used, height + 2 * margin, null);
                    used += tg.getHeight();
                    first = false;
                }
                used += 25;
            }
        } else {
            for (TimetableGridModel model : response.getModels()) {
                if (used > 0 && pageHeight(filter, model, response.getWeekOffset(), false) > height - used) {
                    document.newPage();
                    used = 0;
                }
                TimetableGrid tg = new TimetableGrid(filter, model, index++, width, response.getWeekOffset(),
                        used == 0);
                PdfContentByte canvas = writer.getDirectContent();
                tg.print(canvas, margin, margin + used, height + 2 * margin, null);
                used += tg.getHeight() + 25;
            }
        }
        if (document != null)
            document.close();
    } catch (DocumentException e) {
        throw new IOException(e.getMessage(), e);
    }
}

From source file:org.unitime.timetable.util.PdfEventHandler.java

License:Open Source License

/**
 * Initialize Pdf footer/*from   w  w w.j a  v a 2s .co m*/
 * @param document
 * @param outputStream
 * @return PdfWriter
 */
public static PdfWriter initFooter(Document document, OutputStream outputStream)
        throws DocumentException, IOException {

    PdfWriter iWriter = PdfWriter.getInstance(document, outputStream);
    iWriter.setPageEvent(new PdfEventHandler());

    return iWriter;
}

From source file:org.unitime.timetable.webutil.DistributionPrefsTableBuilder.java

License:Open Source License

public void toPdfTable(OutputStream out, SessionContext context, Collection distPrefs, String title)
        throws Exception {
    String instructorFormat = UserProperty.NameFormat.get(context.getUser());

    PdfWebTable tbl = new PdfWebTable(5, title, null,
            new String[] { "Preference", "Type", "Structure", "Owner", "Class" },
            new String[] { "left", "left", "left", "left", "left" },
            new boolean[] { true, true, true, true, true });

    int nrPrefs = 0;

    for (Iterator i1 = distPrefs.iterator(); i1.hasNext();) {
        DistributionPref dp = (DistributionPref) i1.next();

        if (!context.hasPermission(dp, Right.DistributionPreferenceDetail))
            continue;

        nrPrefs++;/*from   ww w . j a va2  s.c  om*/

        String objStr = "";

        PreferenceGroup pg = dp.getOwner();

        String ownerType = "Unknown";
        if (pg instanceof Department) {
            Department d = (Department) pg;
            ownerType = d.getShortLabel();
        }

        for (Iterator i2 = dp.getOrderedSetOfDistributionObjects().iterator(); i2.hasNext();) {
            DistributionObject dO = (DistributionObject) i2.next();
            objStr += dO.preferenceText();
            if (i2.hasNext())
                objStr += "\n";
        }

        String groupingText = dp.getGroupingName();
        Comparable groupingCmp = (dp.getGrouping() == null ? "0" : dp.getGrouping().toString());

        if (pg instanceof DepartmentalInstructor) {
            DepartmentalInstructor instructor = (DepartmentalInstructor) pg;
            Department d = instructor.getDepartment();
            ownerType = d.getShortLabel();
            TreeSet classes = new TreeSet(
                    new ClassInstructorComparator(new ClassComparator(ClassComparator.COMPARE_BY_HIERARCHY)));
            classes.addAll(instructor.getClasses());
            for (Iterator i2 = classes.iterator(); i2.hasNext();) {
                ClassInstructor clazz = (ClassInstructor) i2.next();
                if (!clazz.isLead().booleanValue())
                    continue;
                if (objStr.length() > 0)
                    objStr += "\n";
                objStr += clazz.getClassInstructing().toString();
            }
            groupingText = "Instructor " + instructor.getName(instructorFormat);
            groupingCmp = instructor.getName(instructorFormat);
        }

        String distType = dp.getDistributionType().getLabel();
        String prefLevel = dp.getPrefLevel().getPrefName();
        String onClick = null;

        tbl.addLine(onClick, new String[] { prefLevel, distType, groupingText, ownerType, objStr },
                new Comparable[] { prefLevel, distType, groupingCmp, ownerType, objStr });

    }

    if (nrPrefs == 0)
        tbl.addLine(null, new String[] { "No preferences found", "", "", "", "" }, null);

    int ord = WebTable.getOrder(context, "distPrefsTable.ord");
    ord = (ord > 0 ? 1 : -1) * (1 + Math.abs(ord));

    PdfPTable table = tbl.printPdfTable(ord);

    float width = tbl.getWidth();

    Document doc = new Document(new Rectangle(60f + width, 60f + 1.30f * width), 30, 30, 30, 30);

    PdfWriter iWriter = PdfWriter.getInstance(doc, out);
    iWriter.setPageEvent(new PdfEventHandler());
    doc.open();

    if (tbl.getName() != null)
        doc.add(new Paragraph(tbl.getName(), PdfFont.getBigFont(true)));

    doc.add(table);

    doc.close();
}

From source file:org.unitime.timetable.webutil.ExamDistributionPrefsTableBuilder.java

License:Open Source License

public void toPdfTable(OutputStream out, HttpServletRequest request, SessionContext context,
        Collection distPrefs, Long examTypeId) throws Exception {
    WebTable.setOrder(context, "examDistPrefsTable.ord", request.getParameter("order"), 4);

    PdfWebTable tbl = new PdfWebTable(4,
            ExamTypeDAO.getInstance().get(examTypeId).getLabel() + " Examination Distribution Preferences",
            null, new String[] { " Preference ", " Type ", " Exam ", " Class/Course " },
            new String[] { "left", "left", "left", "left" }, new boolean[] { true, true, true, true });

    int nrPrefs = 0;

    for (Iterator i1 = distPrefs.iterator(); i1.hasNext();) {
        DistributionPref dp = (DistributionPref) i1.next();

        if (!context.hasPermission(dp, Right.ExaminationDistributionPreferenceDetail))
            continue;

        nrPrefs++;/* ww w  .  j  ava2  s .c  o  m*/

        String examStr = "";
        String objStr = "";

        for (Iterator i2 = dp.getOrderedSetOfDistributionObjects().iterator(); i2.hasNext();) {
            DistributionObject dO = (DistributionObject) i2.next();
            Exam exam = (Exam) dO.getPrefGroup();
            examStr += dO.preferenceText();
            for (Iterator i3 = exam.getOwners().iterator(); i3.hasNext();) {
                ExamOwner owner = (ExamOwner) i3.next();
                objStr += owner.getLabel();
                if (i3.hasNext()) {
                    examStr += "\n";
                    objStr += "\n";
                }
            }
            if (i2.hasNext()) {
                examStr += "\n";
                objStr += "\n";
            }
        }

        String distType = dp.getDistributionType().getLabel();
        String prefLevel = dp.getPrefLevel().getPrefName();

        tbl.addLine(null, new String[] { prefLevel, distType, examStr, objStr },
                new Comparable[] { null, distType, examStr, objStr });

    }

    if (nrPrefs == 0)
        tbl.addLine(null, new String[] { "No preferences found", "", "", "" }, null);

    int ord = WebTable.getOrder(context, "examDistPrefsTable.ord");
    ord = (ord > 0 ? 1 : -1) * (1 + Math.abs(ord));

    PdfPTable table = tbl.printPdfTable(ord);

    float width = tbl.getWidth();

    Document doc = new Document(new Rectangle(60f + width, 60f + 1.30f * width), 30, 30, 30, 30);

    PdfWriter iWriter = PdfWriter.getInstance(doc, out);
    iWriter.setPageEvent(new PdfEventHandler());
    doc.open();

    if (tbl.getName() != null)
        doc.add(new Paragraph(tbl.getName(), PdfFont.getBigFont(true)));

    doc.add(table);

    doc.close();
}

From source file:org.unitime.timetable.webutil.PdfWebTable.java

License:Open Source License

public void exportPdf(OutputStream out, int ordCol) throws Exception {
    PdfPTable table = printPdfTable(ordCol);

    float width = getWidth();

    Document doc = new Document(new Rectangle(60f + width, 60f + 0.75f * width), 30, 30, 30, 30);

    PdfWriter iWriter = PdfWriter.getInstance(doc, out);
    iWriter.setPageEvent(new PdfEventHandler());
    doc.open();/*from w  ww . jav a  2  s  .  c o  m*/

    if (iName != null)
        doc.add(new Paragraph(iName, PdfFont.getBigFont(true)));

    doc.add(table);

    doc.close();
}

From source file:org.webguitoolkit.ui.util.export.PDFTableExport.java

License:Apache License

public void writeTo(Table table, OutputStream out) {
    TableExportOptions exportOptions = table.getExportOptions();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // set the page orientation Din-A4 Portrait or Landscape
    Rectangle page = PageSize.A4;
    if (exportOptions.getPdfPosition() != null
            && exportOptions.getPdfPosition().equals(TableExportOptions.PDF_LANDSCAPE)) {
        // landscape position
        page = PageSize.A4.rotate();//from w  w w. j a v  a  2s .c  o  m
    } else if (exportOptions.getPdfPosition() != null
            && exportOptions.getPdfPosition().equals(TableExportOptions.PDF_PORTRAIT)) {
        // portrait position
        page = PageSize.A4;
    }
    if (exportOptions.getPdfPageColour() != null) {
        // page.setBackgroundColor(exportOptions.getPdfPageColour());
    }

    Document document = new Document(page);
    document.setMargins(36f, 36f, 50f, 40f);
    try {
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new PDFEvent(table));
        document.open();
        if (StringUtils.isNotEmpty(exportOptions.getHeadline())) {
            Font titleFont = new Font(Font.UNDEFINED, 18, Font.BOLD);
            Paragraph paragraph = new Paragraph(exportOptions.getHeadline(), titleFont);
            paragraph.setAlignment(Element.ALIGN_CENTER);
            document.add(paragraph);
            document.add(new Paragraph(" "));
            document.add(new Paragraph(" "));
        }

        PdfPTable pdftable = pdfExport(table);
        document.add(pdftable);
        document.newPage();
        document.close();

        baos.writeTo(out);
        out.flush();
        baos.close();
    } catch (DocumentException e) {
        logger.error("Error creating document!", e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        logger.error("Error creating document!", e);
        throw new RuntimeException(e);
    } finally {

    }
}

From source file:oscar.form.pdfservlet.FrmCustomedPDFServlet.java

License:Open Source License

protected ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, final ServletContext ctx)
        throws DocumentException {
    logger.debug("***in generatePDFDocumentBytes2 FrmCustomedPDFServlet.java***");
    // added by vic, hsfo
    Enumeration<String> em = req.getParameterNames();
    while (em.hasMoreElements()) {
        logger.debug("para=" + em.nextElement());
    }//from   w ww .  j  a va  2 s .  c om
    em = req.getAttributeNames();
    while (em.hasMoreElements())
        logger.debug("attr: " + em.nextElement());

    if (HSFO_RX_DATA_KEY.equals(req.getParameter("__title"))) {
        return generateHsfoRxPDF(req);
    }
    String newline = System.getProperty("line.separator");

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    PdfWriter writer = null;
    String method = req.getParameter("__method");
    String origPrintDate = null;
    String numPrint = null;
    if (method != null && method.equalsIgnoreCase("rePrint")) {
        origPrintDate = req.getParameter("origPrintDate");
        numPrint = req.getParameter("numPrints");
    }

    logger.debug("method in generatePDFDocumentBytes " + method);
    String clinicName;
    String clinicTel;
    String clinicFax;
    // check if satellite clinic is used
    String useSatelliteClinic = req.getParameter("useSC");
    logger.debug(useSatelliteClinic);
    if (useSatelliteClinic != null && useSatelliteClinic.equalsIgnoreCase("true")) {
        String scAddress = req.getParameter("scAddress");
        logger.debug("clinic detail" + "=" + scAddress);
        HashMap<String, String> hm = parseSCAddress(scAddress);
        clinicName = hm.get("clinicName");
        clinicTel = hm.get("clinicTel");
        clinicFax = hm.get("clinicFax");
    } else {
        // parameters need to be passed to header and footer
        clinicName = req.getParameter("clinicName");
        logger.debug("clinicName" + "=" + clinicName);
        clinicTel = req.getParameter("clinicPhone");
        clinicFax = req.getParameter("clinicFax");
    }
    String patientPhone = req.getParameter("patientPhone");
    String patientCityPostal = req.getParameter("patientCityPostal");
    String patientAddress = req.getParameter("patientAddress");
    String patientName = req.getParameter("patientName");
    String sigDoctorName = req.getParameter("sigDoctorName");
    String rxDate = req.getParameter("rxDate");
    String rx = req.getParameter("rx");
    String patientDOB = req.getParameter("patientDOB");
    String showPatientDOB = req.getParameter("showPatientDOB");
    String imgFile = req.getParameter("imgFile");
    String patientHIN = req.getParameter("patientHIN");
    String patientChartNo = req.getParameter("patientChartNo");
    String pracNo = req.getParameter("pracNo");
    Locale locale = req.getLocale();

    boolean isShowDemoDOB = false;
    if (showPatientDOB != null && showPatientDOB.equalsIgnoreCase("true")) {
        isShowDemoDOB = true;
    }
    if (!isShowDemoDOB)
        patientDOB = "";
    if (rx == null) {
        rx = "";
    }

    String additNotes = req.getParameter("additNotes");
    String[] rxA = rx.split(newline);
    List<String> listRx = new ArrayList<String>();
    String listElem = "";
    // parse rx and put into a list of rx;
    for (String s : rxA) {

        if (s.equals("") || s.equals(newline) || s.length() == 1) {
            listRx.add(listElem);
            listElem = "";
        } else {
            listElem = listElem + s;
            listElem += newline;
        }

    }

    // get the print prop values
    Properties props = new Properties();
    StringBuilder temp = new StringBuilder();
    for (Enumeration<String> e = req.getParameterNames(); e.hasMoreElements();) {
        temp = new StringBuilder(e.nextElement().toString());
        props.setProperty(temp.toString(), req.getParameter(temp.toString()));
    }

    for (Enumeration<String> e = req.getAttributeNames(); e.hasMoreElements();) {
        temp = new StringBuilder(e.nextElement().toString());
        props.setProperty(temp.toString(), req.getAttribute(temp.toString()).toString());
    }
    Document document = new Document();

    try {
        String title = req.getParameter("__title") != null ? req.getParameter("__title") : "Unknown";

        // specify the page of the picture using __graphicPage, it may be used multiple times to specify multiple pages
        // however the same graphic will be applied to all pages
        // ie. __graphicPage=2&__graphicPage=3
        String[] cfgGraphicFile = req.getParameterValues("__cfgGraphicFile");
        int cfgGraphicFileNo = cfgGraphicFile == null ? 0 : cfgGraphicFile.length;
        if (cfgGraphicFile != null) {
            // for (String s : cfgGraphicFile) {
            // p("cfgGraphicFile", s);
            // }
        }

        String[] graphicPage = req.getParameterValues("__graphicPage");
        ArrayList<String> graphicPageArray = new ArrayList<String>();
        if (graphicPage != null) {
            // for (String s : graphicPage) {
            // p("graphicPage", s);
            // }
            graphicPageArray = new ArrayList<String>(Arrays.asList(graphicPage));
        }

        // A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA
        // and FLSE
        // the following shows a temp way to get a print page size
        Rectangle pageSize = PageSize.LETTER;
        String pageSizeParameter = req.getParameter("rxPageSize");
        if (pageSizeParameter != null) {
            if ("PageSize.HALFLETTER".equals(pageSizeParameter)) {
                pageSize = PageSize.HALFLETTER;
            } else if ("PageSize.A6".equals(pageSizeParameter)) {
                pageSize = PageSize.A6;
            } else if ("PageSize.A4".equals(pageSizeParameter)) {
                pageSize = PageSize.A4;
            }
        }
        /*
         * if ("PageSize.HALFLETTER".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.HALFLETTER; } else if ("PageSize.A6".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.A6; } else if
         * ("PageSize.A4".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.A4; }
         */
        // p("size of page ", props.getProperty(PAGESIZE));

        document.setPageSize(pageSize);
        // 285=left margin+width of box, 5f is space for looking nice
        document.setMargins(15, pageSize.getWidth() - 285f + 5f, 170, 60);// left, right, top , bottom

        writer = PdfWriter.getInstance(document, baosPDF);
        writer.setPageEvent(new EndPage(clinicName, clinicTel, clinicFax, patientPhone, patientCityPostal,
                patientAddress, patientName, patientDOB, sigDoctorName, rxDate, origPrintDate, numPrint,
                imgFile, patientHIN, patientChartNo, pracNo, locale));
        document.addTitle(title);
        document.addSubject("");
        document.addKeywords("pdf, itext");
        document.addCreator("OSCAR");
        document.addAuthor("");
        document.addHeader("Expires", "0");

        document.open();
        document.newPage();

        PdfContentByte cb = writer.getDirectContent();
        BaseFont bf; // = normFont;

        cb.setRGBColorStroke(0, 0, 255);
        // render prescriptions
        for (String rxStr : listRx) {
            bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Paragraph p = new Paragraph(new Phrase(rxStr, new Font(bf, 10)));
            p.setKeepTogether(true);
            p.setSpacingBefore(5f);
            document.add(p);
        }
        // render additional notes
        if (additNotes != null && !additNotes.equals("")) {
            bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Paragraph p = new Paragraph(new Phrase(additNotes, new Font(bf, 10)));
            p.setKeepTogether(true);
            p.setSpacingBefore(10f);
            document.add(p);
        }
        // render optometristEyeParam
        if (req.getAttribute("optometristEyeParam") != null) {
            bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Paragraph p = new Paragraph(
                    new Phrase("Eye " + (String) req.getAttribute("optometristEyeParam"), new Font(bf, 10)));
            p.setKeepTogether(true);
            p.setSpacingBefore(15f);
            document.add(p);
        }

        // render QrCode
        if (PrescriptionQrCodeUIBean.isPrescriptionQrCodeEnabledForCurrentProvider()) {
            Integer scriptId = Integer.parseInt(req.getParameter("scriptId"));
            byte[] qrCodeImage = PrescriptionQrCodeUIBean.getPrescriptionHl7QrCodeImage(scriptId);
            Image qrCode = Image.getInstance(qrCodeImage);
            document.add(qrCode);
        }

    } catch (DocumentException dex) {
        baosPDF.reset();
        throw dex;
    } catch (Exception e) {
        logger.error("Error", e);
    } finally {
        if (document != null) {
            document.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
    logger.debug("***END in generatePDFDocumentBytes2 FrmCustomedPDFServlet.java***");
    return baosPDF;
}

From source file:oscar.oscarLab.ca.all.pageUtil.LabPDFCreator.java

License:Open Source License

public void printPdf() throws IOException, DocumentException {

    // check that we have data to print
    if (handler == null)
        throw new DocumentException();

    //response.setContentType("application/pdf");  //octet-stream
    //response.setHeader("Content-Disposition", "attachment; filename=\""+handler.getPatientName().replaceAll("\\s", "_")+"_LabReport.pdf\"");

    //Create the document we are going to write to
    document = new Document();
    //PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
    PdfWriter writer = PdfWriter.getInstance(document, os);

    //Set page event, function onEndPage will execute each time a page is finished being created
    writer.setPageEvent(this);

    document.setPageSize(PageSize.LETTER);
    document.addTitle("Title of the Document");
    document.addCreator("OSCAR");
    document.open();//  w w  w  . j  a  va  2  s .  c  o  m

    //Create the fonts that we are going to use
    bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    font = new Font(bf, 9, Font.NORMAL);
    boldFont = new Font(bf, 10, Font.BOLD);
    redFont = new Font(bf, 9, Font.NORMAL, Color.RED);

    // add the header table containing the patient and lab info to the document
    createInfoTable();

    // add the tests and test info for each header
    ArrayList<String> headers = handler.getHeaders();
    for (int i = 0; i < headers.size(); i++)
        addLabCategory(headers.get(i));

    // add end of report table
    PdfPTable table = new PdfPTable(1);
    table.setWidthPercentage(100);
    PdfPCell cell = new PdfPCell();
    cell.setBorder(0);
    cell.setPhrase(new Phrase("  "));
    table.addCell(cell);
    cell.setBorder(15);
    cell.setBackgroundColor(new Color(210, 212, 255));
    cell.setPhrase(new Phrase("END OF REPORT", boldFont));
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.addCell(cell);
    document.add(table);

    document.close();

    os.flush();
}

From source file:questions.stamppages.BookmarksToTOC1.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {/*w  ww .  j av a2s  .co  m*/
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
        writer.setPageEvent(new ParagraphBookmarkEvents(false));
        document.open();
        BufferedReader reader = new BufferedReader(new FileReader(RESOURCE));
        String line;
        Paragraph p;
        while ((line = reader.readLine()) != null) {
            p = new Paragraph(line);
            p.setAlignment(Element.ALIGN_JUSTIFIED);
            document.add(p);
            document.add(Chunk.NEWLINE);
        }
        reader.close();
        document.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

    try {
        PdfReader reader = new PdfReader(baos.toByteArray());
        Rectangle rect = reader.getPageSizeWithRotation(1);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        stamper.insertPage(1, rect);
        ColumnText column = new ColumnText(stamper.getOverContent(1));
        column.setSimpleColumn(rect.getLeft(36), rect.getBottom(36), rect.getRight(36), rect.getTop(36));
        column.addElement(new Paragraph("TABLE OF CONTENTS"));
        List<Map> list = SimpleBookmark.getBookmark(reader);
        Chunk link;
        PdfAction action;
        String info;
        int p = 1;
        float y = 10;
        for (Map<String, String> bookmark : list) {
            link = new Chunk(bookmark.get("Title"));
            info = bookmark.get("Page");
            p = Integer.parseInt(info.substring(0, info.indexOf(' ')));
            y = Float.parseFloat(info.substring(info.lastIndexOf(' ') + 1) + "f");
            action = PdfAction.gotoLocalPage(p, new PdfDestination(PdfDestination.FITH, y),
                    stamper.getWriter());
            link.setAction(action);
            column.addElement(new Paragraph(link));
        }
        column.go();
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

}