Example usage for com.lowagie.text HeaderFooter HeaderFooter

List of usage examples for com.lowagie.text HeaderFooter HeaderFooter

Introduction

In this page you can find the example usage for com.lowagie.text HeaderFooter HeaderFooter.

Prototype


public HeaderFooter(Phrase before, boolean numbered) 

Source Link

Document

Constructs a Header-object with a pagenumber at the end.

Usage

From source file:org.kuali.kra.printing.service.impl.PrintingServiceImpl.java

License:Educational Community License

/**
 * @param pdfBytesList//from ww  w .  j  a  v a  2s.c o  m
 *            List containing the PDF data bytes
 * @param bookmarksList
 *            List of bookmarks corresponding to the PDF bytes.
 * @return
 * @throws PrintingException
 */

protected byte[] mergePdfBytes(List<byte[]> pdfBytesList, List<String> bookmarksList,
        boolean headerFooterRequired) throws PrintingException {
    Document document = null;
    PdfWriter writer = null;
    ByteArrayOutputStream mergedPdfReport = new ByteArrayOutputStream();
    int totalNumOfPages = 0;
    PdfReader[] pdfReaderArr = new PdfReader[pdfBytesList.size()];
    int pdfReaderCount = 0;
    for (byte[] fileBytes : pdfBytesList) {
        LOG.debug("File Size " + fileBytes.length + " For " + bookmarksList.get(pdfReaderCount));
        PdfReader reader = null;
        try {
            reader = new PdfReader(fileBytes);
            pdfReaderArr[pdfReaderCount] = reader;
            pdfReaderCount = pdfReaderCount + 1;
            totalNumOfPages += reader.getNumberOfPages();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
    HeaderFooter footer = null;
    if (headerFooterRequired) {
        Calendar calendar = dateTimeService.getCurrentCalendar();
        String dateString = formateCalendar(calendar);
        StringBuilder footerPhStr = new StringBuilder();
        footerPhStr.append(" of ");
        footerPhStr.append(totalNumOfPages);
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_60));
        footerPhStr.append(dateString);
        Font font = FontFactory.getFont(FontFactory.TIMES, 8, Font.NORMAL, Color.BLACK);
        Phrase beforePhrase = new Phrase("Page ", font);
        Phrase afterPhrase = new Phrase(footerPhStr.toString(), font);
        footer = new HeaderFooter(beforePhrase, afterPhrase);
        footer.setAlignment(Element.ALIGN_BASELINE);
        footer.setBorderWidth(0f);
    }
    for (int count = 0; count < pdfReaderArr.length; count++) {
        PdfReader reader = pdfReaderArr[count];
        int nop;
        if (reader == null) {
            LOG.debug("Empty PDF byetes found for " + bookmarksList.get(count));
            continue;
        } else {
            nop = reader.getNumberOfPages();
        }

        if (count == 0) {
            document = nop > 0 ? new com.lowagie.text.Document(reader.getPageSizeWithRotation(1))
                    : new com.lowagie.text.Document();
            try {
                writer = PdfWriter.getInstance(document, mergedPdfReport);
            } catch (DocumentException e) {
                LOG.error(e.getMessage(), e);
                throw new PrintingException(e.getMessage(), e);
            }
            if (footer != null) {
                document.setFooter(footer);
            }
            // writer.setPageEvent(new Watermark());  //  add watermark object here
            document.open();
        }

        PdfContentByte cb = writer.getDirectContent();
        int pageCount = 0;
        while (pageCount < nop) {
            document.setPageSize(reader.getPageSize(++pageCount));
            document.newPage();
            if (footer != null) {
                document.setFooter(footer);
            }
            PdfImportedPage page = writer.getImportedPage(reader, pageCount);

            cb.addTemplate(page, 1, 0, 0, 1, 0, 0);

            PdfOutline root = cb.getRootOutline();
            if (pageCount == 1) {
                String pageName = bookmarksList.get(count);
                cb.addOutline(new PdfOutline(root, new PdfDestination(PdfDestination.FITH), pageName),
                        pageName);
            }
        }
    }
    if (document != null) {
        try {
            document.close();
            return mergedPdfReport.toByteArray();
        } catch (Exception e) {
            LOG.error("Exception occured because the generated PDF document has no pages", e);
        }
    }
    return null;
}

From source file:org.netxilia.server.rest.pdf.SheetPdfProvider.java

License:Open Source License

@Override
public void writeTo(SheetFullName sheetName, Class<?> clazz, Type type, Annotation[] ann, MediaType mediaType,
        MultivaluedMap<String, Object> headers, OutputStream out) throws IOException, WebApplicationException {

    if (sheetName == null) {
        return;/*  w w  w .  j  a  v  a 2 s. c om*/
    }

    /**
     * This is the table, added as an Element to the PDF document. It contains all the data, needed to represent the
     * visible table into the PDF
     */
    Table tablePDF;

    /**
     * The default font used in the document.
     */
    Font smallFont = FontFactory.getFont(FontFactory.HELVETICA, 7, Font.NORMAL, new Color(0, 0, 0));
    ISheet summarySheet = null;
    ISheet sheet = null;
    try {
        sheet = workbookProcessor.getWorkbook(sheetName.getWorkbookId()).getSheet(sheetName.getSheetName());
        try {
            // get the corresponding summary sheet
            SheetFullName summarySheetName = SheetFullName.summarySheetName(sheetName,
                    userService.getCurrentUser());
            summarySheet = workbookProcessor.getWorkbook(summarySheetName.getWorkbookId())
                    .getSheet(summarySheetName.getSheetName());

        } catch (Exception e) {
            // no summary sheet - go without one
        }

        // Initialize the Document and register it with PdfWriter listener and the OutputStream
        Document document = new Document(PageSize.A4.rotate(), 60, 60, 40, 40);
        document.addCreationDate();
        HeaderFooter footer = new HeaderFooter(new Phrase("", smallFont), true);
        footer.setBorder(Rectangle.NO_BORDER);
        footer.setAlignment(Element.ALIGN_CENTER);

        PdfWriter.getInstance(document, out);

        // Fill the virtual PDF table with the necessary data
        // Initialize the table with the appropriate number of columns
        tablePDF = initTable(sheet);
        // take tha maximum numbers of columns
        int columnCount = sheet.getDimensions().getNonBlocking().getColumnCount();
        if (summarySheet != null) {
            columnCount = Math.max(columnCount, summarySheet.getDimensions().getNonBlocking().getColumnCount());
        }
        generateHeaders(sheet, tablePDF, smallFont, columnCount);

        tablePDF.endHeaders();
        generateRows(sheet, false, tablePDF, smallFont, columnCount);
        if (summarySheet != null) {
            generateRows(summarySheet, true, tablePDF, smallFont, columnCount);
        }

        document.open();
        document.setFooter(footer);
        document.add(tablePDF);
        document.close();

        out.flush();
        out.close();

    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:org.oscarehr.casemgmt.print.OscarChartPrinter.java

License:Open Source License

public void printDocHeaderFooter() throws DocumentException {
    String headerTitle = demographic.getFormattedName() + " " + demographic.getAge() + " "
            + demographic.getSex() + " DOB:" + demographic.getFormattedDob();

    //set up document title and header
    ResourceBundle propResource = ResourceBundle.getBundle("oscarResources");
    String title = propResource.getString("oscarEncounter.pdfPrint.title") + " "
            + (String) request.getAttribute("demoName") + "\n";
    String gender = propResource.getString("oscarEncounter.pdfPrint.gender") + " "
            + (String) request.getAttribute("demoSex") + "\n";
    String dob = propResource.getString("oscarEncounter.pdfPrint.dob") + " "
            + (String) request.getAttribute("demoDOB") + "\n";
    String age = propResource.getString("oscarEncounter.pdfPrint.age") + " "
            + (String) request.getAttribute("demoAge") + "\n";
    String mrp = propResource.getString("oscarEncounter.pdfPrint.mrp") + " "
            + (String) request.getAttribute("mrp") + "\n";
    String[] info = new String[] { title, gender, dob, age, mrp };

    ClinicData clinicData = new ClinicData();
    clinicData.refreshClinicData();//  www  .j a  v a2s.  c o m
    String[] clinic = new String[] { clinicData.getClinicName(), clinicData.getClinicAddress(),
            clinicData.getClinicCity() + ", " + clinicData.getClinicProvince(), clinicData.getClinicPostal(),
            clinicData.getClinicPhone() };

    if (newPage) {
        document.newPage();
        newPage = false;
    }

    //Header will be printed at top of every page beginning with p2
    Phrase headerPhrase = new Phrase(LEADING, headerTitle, boldFont);
    HeaderFooter header = new HeaderFooter(headerPhrase, false);
    header.setAlignment(HeaderFooter.ALIGN_CENTER);
    document.setHeader(header);

    getDocument().add(headerPhrase);
    getDocument().add(new Phrase("\n"));

    Paragraph p = new Paragraph("Tel:" + demographic.getPhone(), getFont());
    p.setAlignment(Paragraph.ALIGN_LEFT);
    // getDocument().add(p);

    Paragraph p2 = new Paragraph("Date of Visit: ", getFont());
    p2.setAlignment(Paragraph.ALIGN_RIGHT);
    // getDocument().add(p);

    PdfPTable table = new PdfPTable(2);
    table.setWidthPercentage(100f);
    table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
    PdfPCell cell1 = new PdfPCell(p);
    cell1.setBorder(PdfPCell.NO_BORDER);
    cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
    PdfPCell cell2 = new PdfPCell(p2);
    cell2.setHorizontalAlignment(Element.ALIGN_RIGHT);
    cell2.setBorder(PdfPCell.NO_BORDER);
    table.addCell(cell1);
    table.addCell(cell2);

    getDocument().add(table);

    table = new PdfPTable(3);
    table.setWidthPercentage(100f);
    table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
    cell1 = new PdfPCell(getParagraph("Signed Provider:" + ((signingProvider != null) ? signingProvider : "")));
    cell1.setBorder(PdfPCell.NO_BORDER);
    cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
    cell2 = new PdfPCell(getParagraph("RFR:"));
    cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell2.setBorder(PdfPCell.NO_BORDER);
    PdfPCell cell3 = new PdfPCell(getParagraph("Ref:"));
    cell3.setHorizontalAlignment(Element.ALIGN_RIGHT);
    cell3.setBorder(PdfPCell.NO_BORDER);
    table.addCell(cell1);
    table.addCell(cell2);
    table.addCell(cell3);

    getDocument().add(table);

    //Write title with top and bottom borders on p1
    cb = writer.getDirectContent();
    cb.setColorStroke(new Color(0, 0, 0));
    cb.setLineWidth(0.5f);

    cb.moveTo(document.left(), document.top() - (font.getCalculatedLeading(LINESPACING) * 5f));
    cb.lineTo(document.right(), document.top() - (font.getCalculatedLeading(LINESPACING) * 5f));
    cb.stroke();
}

From source file:org.oscarehr.casemgmt.service.CaseManagementPrintPdf.java

License:Open Source License

public void printDocHeaderFooter() throws IOException, DocumentException {
    //Create the document we are going to write to
    document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, os);
    writer.setPageEvent(new EndPage());
    document.setPageSize(PageSize.LETTER);
    document.open();/*from www.  j  av  a2  s . co  m*/

    //Create the font we are going to print to
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    font = new Font(bf, FONTSIZE, Font.NORMAL);

    String title = "", gender = "", dob = "", age = "", mrp = "";
    if (this.demoDtl != null) {
        //set up document title and header
        ResourceBundle propResource = ResourceBundle.getBundle("oscarResources");
        title = propResource.getString("oscarEncounter.pdfPrint.title") + " " + (String) demoDtl.get("demoName")
                + "\n";
        gender = propResource.getString("oscarEncounter.pdfPrint.gender") + " "
                + (String) demoDtl.get("demoSex") + "\n";
        dob = propResource.getString("oscarEncounter.pdfPrint.dob") + " " + (String) demoDtl.get("demoDOB")
                + "\n";
        age = propResource.getString("oscarEncounter.pdfPrint.age") + " " + (String) demoDtl.get("demoAge")
                + "\n";
        mrp = propResource.getString("oscarEncounter.pdfPrint.mrp") + " " + (String) demoDtl.get("mrp") + "\n";
    } else {
        //set up document title and header
        ResourceBundle propResource = ResourceBundle.getBundle("oscarResources");
        title = propResource.getString("oscarEncounter.pdfPrint.title") + " "
                + (String) request.getAttribute("demoName") + "\n";
        gender = propResource.getString("oscarEncounter.pdfPrint.gender") + " "
                + (String) request.getAttribute("demoSex") + "\n";
        dob = propResource.getString("oscarEncounter.pdfPrint.dob") + " "
                + (String) request.getAttribute("demoDOB") + "\n";
        age = propResource.getString("oscarEncounter.pdfPrint.age") + " "
                + (String) request.getAttribute("demoAge") + "\n";
        mrp = propResource.getString("oscarEncounter.pdfPrint.mrp") + " " + (String) request.getAttribute("mrp")
                + "\n";
    }

    String[] info = new String[] { title, gender, dob, age, mrp };

    ClinicData clinicData = new ClinicData();
    clinicData.refreshClinicData();
    String[] clinic = new String[] { clinicData.getClinicName(), clinicData.getClinicAddress(),
            clinicData.getClinicCity() + ", " + clinicData.getClinicProvince(), clinicData.getClinicPostal(),
            clinicData.getClinicPhone(), "Fax: " + clinicData.getClinicFax() };

    //Header will be printed at top of every page beginning with p2
    Phrase headerPhrase = new Phrase(LEADING, title, font);
    HeaderFooter header = new HeaderFooter(headerPhrase, false);
    header.setAlignment(HeaderFooter.ALIGN_CENTER);
    document.setHeader(header);

    //Write title with top and bottom borders on p1
    cb = writer.getDirectContent();
    cb.setColorStroke(new Color(0, 0, 0));
    cb.setLineWidth(0.5f);

    cb.moveTo(document.left(), document.top());
    cb.lineTo(document.right(), document.top());
    cb.stroke();
    //cb.setFontAndSize(bf, FONTSIZE);

    upperYcoord = document.top() - (font.getCalculatedLeading(LINESPACING) * 2f);

    ColumnText ct = new ColumnText(cb);
    Paragraph p = new Paragraph();
    p.setAlignment(Paragraph.ALIGN_LEFT);
    Phrase phrase = new Phrase();
    Phrase dummy = new Phrase();
    for (int idx = 0; idx < clinic.length; ++idx) {
        phrase.add(clinic[idx] + "\n");
        dummy.add("\n");
        upperYcoord -= phrase.getLeading();
    }

    dummy.add("\n");
    ct.setSimpleColumn(document.left(), upperYcoord, document.right() / 2f, document.top());
    ct.addElement(phrase);
    ct.go();

    p.add(dummy);
    document.add(p);

    //add patient info
    phrase = new Phrase();
    p = new Paragraph();
    p.setAlignment(Paragraph.ALIGN_RIGHT);
    for (int idx = 0; idx < info.length; ++idx) {
        phrase.add(info[idx]);
    }

    ct.setSimpleColumn(document.right() / 2f, upperYcoord, document.right(), document.top());
    p.add(phrase);
    ct.addElement(p);
    ct.go();

    cb.moveTo(document.left(), upperYcoord);
    cb.lineTo(document.right(), upperYcoord);
    cb.stroke();
    upperYcoord -= phrase.getLeading();

    if (Boolean.parseBoolean(OscarProperties.getInstance().getProperty("ICFHT_CONVERT_TO_PDF", "false"))) {
        printPersonalInfo();
    }
}

From source file:org.sakaiproject.evaluation.tool.reporting.EvalPDFReportBuilder.java

License:Educational Community License

public void addFooter(String text) {
    HeaderFooter footer = new HeaderFooter((new Phrase(text + " - Pag. ", paragraphFont)), true);
    ;//from   w w w.  ja v  a 2  s.c  o m
    footer.setAlignment(HeaderFooter.ALIGN_RIGHT);
    footer.disableBorderSide(HeaderFooter.BOTTOM);

    document.setFooter(footer);
}

From source file:org.schreibubi.JCombinations.ui.GridChartPanel.java

License:Open Source License

/**
 * Create PDF/*from w  w w .j a va  2s .co m*/
 * 
 * @param name
 *            Filename
 * @param selection
 *            Selected Nodes
 * @param dm
 *            DataModel
 * @param pl
 *            ProgressListener
 */
@SuppressWarnings("unchecked")
public static void generatePDF(File name, DataModel dm, ArrayList<TreePath> selection, ProgressListener pl) {
    com.lowagie.text.Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50);
    try {
        ArrayList<ExtendedJFreeChart> charts = dm.getCharts(selection);
        if (charts.size() > 0) {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(name));
            writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
            document.addAuthor("Jrg Werner");
            document.addSubject("Created by JCombinations");
            document.addKeywords("JCombinations");
            document.addCreator("JCombinations using iText");

            // we define a header and a footer
            HeaderFooter header = new HeaderFooter(new Phrase("JCombinations by Jrg Werner"), false);
            HeaderFooter footer = new HeaderFooter(new Phrase("Page "), new Phrase("."));
            footer.setAlignment(Element.ALIGN_CENTER);
            document.setHeader(header);
            document.setFooter(footer);

            document.open();
            DefaultFontMapper mapper = new DefaultFontMapper();
            FontFactory.registerDirectories();
            mapper.insertDirectory("c:\\WINNT\\fonts");

            PdfContentByte cb = writer.getDirectContent();

            pl.progressStarted(new ProgressEvent(GridChartPanel.class, 0, charts.size()));
            for (int i = 0; i < charts.size(); i++) {
                ExtendedJFreeChart chart = charts.get(i);
                PdfTemplate tp = cb.createTemplate(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN));
                Graphics2D g2d = tp.createGraphics(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN), mapper);
                Rectangle2D r2d = new Rectangle2D.Double(0, 0,
                        document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN));
                chart.draw(g2d, r2d);
                g2d.dispose();
                cb.addTemplate(tp, document.left(EXTRA_MARGIN), document.bottom(EXTRA_MARGIN));
                PdfDestination destination = new PdfDestination(PdfDestination.FIT);
                TreePath treePath = chart.getTreePath();
                PdfOutline po = cb.getRootOutline();
                for (int j = 0; j < treePath.getPathCount(); j++) {
                    ArrayList<PdfOutline> lpo = po.getKids();
                    PdfOutline cpo = null;
                    for (PdfOutline outline : lpo)
                        if (outline.getTitle().compareTo(treePath.getPathComponent(j).toString()) == 0)
                            cpo = outline;
                    if (cpo == null)
                        cpo = new PdfOutline(po, destination, treePath.getPathComponent(j).toString());
                    po = cpo;
                }
                document.newPage();
                pl.progressIncremented(new ProgressEvent(GridChartPanel.class, i));
            }
            document.close();
            pl.progressEnded(new ProgressEvent(GridChartPanel.class));

        }
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
}

From source file:org.silverpeas.components.almanach.control.AlmanachPdfGenerator.java

License:Open Source License

static public void buildPdf(String name, AlmanachSessionController almanach, String mode)
        throws AlmanachRuntimeException {
    try {//from   w  w w  .  j av  a  2s  . c  o m

        String fileName = FileRepositoryManager.getTemporaryPath(almanach.getSpaceId(),
                almanach.getComponentId()) + name;
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        // we add some meta information to the document
        document.addAuthor(almanach.getSettings().getString("author", ""));
        document.addSubject(almanach.getSettings().getString("subject", ""));
        document.addCreationDate();

        PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();

        try {
            Calendar currentDay = Calendar.getInstance();
            currentDay.setTime(almanach.getCurrentDay());
            String sHeader = almanach.getString("events");
            if (mode.equals(PDF_MONTH_ALLDAYS) || mode.equals(PDF_MONTH_EVENTSONLY)) {
                sHeader += " " + almanach.getString("GML.mois" + currentDay.get(Calendar.MONTH));
            }
            sHeader += " " + currentDay.get(Calendar.YEAR);
            HeaderFooter header = new HeaderFooter(new Phrase(sHeader), false);
            HeaderFooter footer = new HeaderFooter(new Phrase("Page "), true);
            footer.setAlignment(Element.ALIGN_CENTER);

            document.setHeader(header);
            document.setFooter(footer);

            createFirstPage(almanach, document);
            document.newPage();

            Font titleFont = new Font(Font.HELVETICA, 24, Font.NORMAL, new Color(255, 255, 255));
            Paragraph cTitle = new Paragraph(almanach.getString("Almanach") + " "
                    + almanach.getString("GML.mois" + currentDay.get(Calendar.MONTH)) + " "
                    + currentDay.get(Calendar.YEAR), titleFont);
            Chapter chapter = new Chapter(cTitle, 1);

            // Collection<EventDetail> events =
            // almanach.getListRecurrentEvent(mode.equals(PDF_YEAR_EVENTSONLY));
            AlmanachCalendarView almanachView;
            if (PDF_YEAR_EVENTSONLY.equals(mode)) {
                almanachView = almanach.getYearlyAlmanachCalendarView();
            } else {
                almanachView = almanach.getMonthlyAlmanachCalendarView();
            }

            List<DisplayableEventOccurrence> occurrences = almanachView.getEvents();
            generateAlmanach(chapter, almanach, occurrences, mode);

            document.add(chapter);
        } catch (Exception ex) {
            throw new AlmanachRuntimeException("PdfGenerator.generate", AlmanachRuntimeException.WARNING,
                    "AlmanachRuntimeException.EX_PROBLEM_TO_GENERATE_PDF", ex);
        }

        document.close();

    } catch (Exception e) {
        throw new AlmanachRuntimeException("PdfGenerator.generate", AlmanachRuntimeException.WARNING,
                "AlmanachRuntimeException.EX_PROBLEM_TO_GENERATE_PDF", e);
    }

}

From source file:org.tellervo.desktop.print.ProSheet.java

License:Open Source License

private void generateProSheet(OutputStream output) {

    Paragraph spacingPara = new Paragraph();
    spacingPara.setSpacingBefore(10);/*from www  . ja va2 s  . c  om*/
    spacingPara.add(new Chunk(" ", bodyFont));

    try {

        PdfWriter writer = PdfWriter.getInstance(document, output);
        document.setPageSize(PageSize.LETTER);

        // Set basic metadata
        document.addAuthor("Peter Brewer");
        document.addSubject("Corina Provenience Sheet for " + o.getTitle());

        HeaderFooter footer = new HeaderFooter(new Phrase(""), new Phrase(""));
        footer.setAlignment(Element.ALIGN_RIGHT);
        footer.setBorder(0);
        document.setFooter(footer);

        HeaderFooter header = new HeaderFooter(new Phrase(o.getLabCode() + " - " + o.getTitle(), bodyFont),
                false);
        header.setAlignment(Element.ALIGN_RIGHT);
        header.setBorder(0);
        document.setHeader(header);

        document.open();
        cb = writer.getDirectContent();

        // Title Left      
        ColumnText ct = new ColumnText(cb);
        ct.setSimpleColumn(document.left(), document.top() - 193, document.right(), document.top() - 20, 20,
                Element.ALIGN_LEFT);
        ct.addText(getTitlePDF());
        ct.go();

        // Timestamp
        ColumnText ct3 = new ColumnText(cb);
        ct3.setSimpleColumn(document.left(), document.top() - 223, 283, document.top() - 60, 20,
                Element.ALIGN_LEFT);
        ct3.setLeading(0, 1.2f);
        ct3.addText(getTimestampPDF());
        ct3.go();

        // Pad text
        document.add(spacingPara);
        document.add(getObjectDescription());
        document.add(getObjectComments());

        document.add(spacingPara);

        getElementTable();

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    }

    // Close the document
    document.close();
}

From source file:oscar.oscarPrevention.pageUtil.PreventionPrintPdf.java

License:Open Source License

public void printPdf(String[] headerIds, HttpServletRequest request, OutputStream outputStream)
        throws IOException, DocumentException {
    //make sure we have data to print
    //String[] headerIds = request.getParameterValues("printHP");
    if (headerIds == null)
        throw new DocumentException();

    //Create the document we are going to write to
    document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    document.setPageSize(PageSize.LETTER);
    document.open();/*from w  w  w  . ja va  2  s . c o m*/

    //Create the font we are going to print to
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    Font font = new Font(bf, FONTSIZE, Font.NORMAL);
    float leading = font.getCalculatedLeading(LINESPACING);

    //set up document title and header
    String title = "Preventions for " + request.getParameter("nameAge");
    String hin = "HIN: " + request.getParameter("hin");
    String mrp = request.getParameter("mrp");
    if (mrp != null) {
        Properties prop = (Properties) request.getSession().getAttribute("providerBean");
        mrp = "MRP: " + prop.getProperty(mrp, "unknown");
    }

    ClinicData clinicData = new ClinicData();
    clinicData.refreshClinicData();
    String[] clinic = new String[] { clinicData.getClinicName(), clinicData.getClinicAddress(),
            clinicData.getClinicCity() + ", " + clinicData.getClinicProvince(), clinicData.getClinicPostal(),
            clinicData.getClinicPhone(), title, hin, mrp };

    //Header will be printed at top of every page beginning with p2
    Phrase headerPhrase = new Phrase(LEADING, title, font);
    HeaderFooter header = new HeaderFooter(headerPhrase, false);
    header.setAlignment(HeaderFooter.ALIGN_CENTER);
    document.setHeader(header);

    //Write title with top and bottom borders on p1
    cb = writer.getDirectContent();
    cb.setColorStroke(new Color(0, 0, 0));
    cb.setLineWidth(0.5f);

    cb.moveTo(document.left(), document.top());
    cb.lineTo(document.right(), document.top());
    cb.stroke();
    cb.setFontAndSize(bf, FONTSIZE);

    upperYcoord = document.top() - (font.getCalculatedLeading(LINESPACING) * 2f);
    cb.beginText();
    for (int idx = 0; idx < clinic.length; ++idx) {
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, clinic[idx], document.right() / 2f, upperYcoord, 0f);
        upperYcoord -= font.getCalculatedLeading(LINESPACING);
    }

    cb.endText();
    cb.moveTo(document.left(), upperYcoord);
    cb.lineTo(document.right(), upperYcoord);
    cb.stroke();

    //get top y-coord for starting to print columns
    upperYcoord = cb.getYTLM() - font.getCalculatedLeading(LINESPACING * 2f);

    int subIdx;
    String preventionHeader, procedureAge, procedureDate;

    //1 - obtain number of lines of incoming prevention data
    numLines = 0;
    for (int idx = 0; idx < headerIds.length; ++idx) {
        ++numLines;
        subIdx = 0;
        while (request.getParameter("preventProcedureAge" + headerIds[idx] + "-" + subIdx) != null) {
            ++subIdx;
            numLines += 3;
        }
        numLines += 2;
    }

    //2 - calculate max num of lines a page can hold and number of pages of data we have
    pageHeight = upperYcoord - document.bottom();
    maxLines = (int) Math.floor(pageHeight / (font.getCalculatedLeading(LINESPACING) + 4d));
    numPages = (int) Math.ceil(numLines / ((double) maxLines * NUMCOLS));

    //3 - Start the column
    ct = new ColumnText(cb);
    ct.setSimpleColumn(document.left(), document.bottom(), document.right() / 2f, upperYcoord);

    linesToBeWritten = linesWritten = 0;
    boolean pageBreak = false;

    curPage = 1;
    totalLinesWritten = 0;

    //add promotext to current page
    addPromoText();

    //if we have > 1 element but less than a page of data, shrink maxLines so we can try to balance text in columns
    if (headerIds.length > 1) {
        if (curPage == numPages) {
            maxLines = numLines / NUMCOLS;
        }
    }

    //now we can start to print the prevention data
    for (int idx = 0; idx < headerIds.length; ++idx) {

        linesToBeWritten = 4; //minimum lines for header and one prevention item
        pageBreak = checkColumnFill(ct, "", font, pageBreak); //if necessary break before we print prevention header

        preventionHeader = request.getParameter("preventionHeader" + headerIds[idx]);
        Phrase procHeader = new Phrase(LEADING, "Prevention " + preventionHeader + "\n", font);
        ct.addText(procHeader);
        subIdx = 0;

        while ((procedureAge = request
                .getParameter("preventProcedureAge" + headerIds[idx] + "-" + subIdx)) != null) {
            procedureDate = request.getParameter("preventProcedureDate" + headerIds[idx] + "-" + subIdx);

            linesToBeWritten = 3;
            pageBreak = checkColumnFill(ct, preventionHeader, font, pageBreak);

            Phrase procedure = new Phrase(LEADING, "     " + procedureAge + "\n", font);
            procedure.add("     " + procedureDate + "\n\n");
            ct.addText(procedure);
            ct.go();
            linesWritten += ct.getLinesWritten();
            totalLinesWritten += ct.getLinesWritten();
            ++subIdx;
        }

    }

    ColumnText.showTextAligned(cb, Phrase.ALIGN_CENTER, new Phrase("-" + curPage + "-"), document.right() / 2f,
            document.bottom() - (document.bottomMargin() / 2f), 0f);

    document.close();
}

From source file:recite18th.controller.Controller.java

License:Open Source License

public void print(String action) {
    /** thanks to http://www.java2s.com/Code/Java/PDF-RTF/DemonstratesthecreatingPDFinportraitlandscape.htm
     * QUICK FIX : do landscape//from   www .  j a va  2 s  .c  o m
     */
    response.setContentType("application/pdf"); // Code 1
    if (action.equals("download")) {
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + "Report " + controllerName + ".pdf\"");
    }
    Document document = new Document(PageSize.A1.rotate());
    try {
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); // Code 2
        document.open();

        // various fonts
        BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", false);
        BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
        BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", false);
        BaseFont bf_symbol = BaseFont.createFont(BaseFont.SYMBOL, "Cp1252", false);

        String headerImage = Config.base_path + "images/report-logo.gif";

        Image imghead = Image.getInstance(headerImage);
        imghead.setAbsolutePosition(0, 0);
        PdfContentByte cbhead = writer.getDirectContent();
        PdfTemplate tpLogo = cbhead.createTemplate(600, 300);
        tpLogo.addImage(imghead);

        PdfTemplate tpTitle = cbhead.createTemplate(1100, 300);
        String txtHeader = "BADAN KEPEGAWAIAN DAERAH PEMERINTAH DAERAH";//Config.application_title;
        tpTitle.beginText();
        tpTitle.setFontAndSize(bf_times, 36);
        tpTitle.showText(txtHeader);
        tpTitle.endText();

        PdfTemplate tpTitle2 = cbhead.createTemplate(900, 300);
        String txtHeader2 = "         KABUPATEN BANTUL YOGYAKARTA";
        tpTitle2.beginText();
        tpTitle2.setFontAndSize(bf_times, 36);
        tpTitle2.showText(txtHeader2);
        tpTitle2.endText();

        PdfTemplate tpAlamat = cbhead.createTemplate(1000, 400);
        tpAlamat.beginText();
        tpAlamat.setFontAndSize(bf_times, 24);
        tpAlamat.showText(
                "Alamat : Jln. R. W. Monginsidi No. 01 Kompleks Parasamya Bantul, Telp. (0274) 367509");
        tpAlamat.endText();

        DateFormat df = new SimpleDateFormat("dd MMM yyyy");
        java.util.Date dt = new java.util.Date();
        PdfTemplate tp3 = cbhead.createTemplate(600, 300);
        tp3.beginText();
        tp3.setFontAndSize(bf_times, 16);

        tp3.showText("Tanggal : " + df.format(dt));
        tp3.endText();

        cbhead.addTemplate(tpLogo, 800, 1500);//logo
        cbhead.addTemplate(tpTitle, 1000, 1580);
        cbhead.addTemplate(tpTitle2, 1000, 1540);
        cbhead.addTemplate(tpAlamat, 1000, 1500);//alamat
        cbhead.addTemplate(tp3, 270, 1500);//tanggal

        HeaderFooter header = new HeaderFooter(new Phrase(cbhead + "", new Font(bf_helv)), false);
        header.setAlignment(Element.ALIGN_CENTER);

        document.setHeader(header);

        //PdfContentByte cb = writer.getDirectContent();
        Paragraph par = new Paragraph(
                "\n\n\n\n\n\n\nLAPORAN DATA SELURUH " + controllerName.toUpperCase() + "\n");
        par.getFont().setStyle(Font.BOLD);
        par.getFont().setSize(18);
        par.setAlignment("center");
        document.add(par);
        document.add(new Paragraph("\n\n"));

        // get data
        initSqlViewDataPerPage();
        if (sqlViewDataPerPageForReport == null) {
            sqlViewDataPerPageForReport = sqlViewDataPerPage;
        }
        PreparedStatement pstmt = Db.getCon().prepareStatement(sqlViewDataPerPageForReport,
                ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet resultSet = pstmt.executeQuery();
        ResultSetMetaData metaColumn = resultSet.getMetaData();
        int nColoumn = metaColumn.getColumnCount();
        // thanks to set cell width http://www.jexp.ru/index.php/Java/PDF_RTF/Table_Cell_Size#Setting_Cell_Widths
        if (nColoumn > 0) {
            Model model = initModel();
            String tableName = model.getTableName();
            // create table header
            //     float[] widths = {1, 4};
            PdfPTable table;// = new PdfPTable(nColoumn);
            PdfPCell cell = new PdfPCell(new Paragraph("Daftar " + controllerName));

            Hashtable hashModel = TableCustomization.getTable(model.getTableName());

            int ncolumnHeader = nColoumn + 1; // +1 because of row. number
            if (hashModel != null) {
                ncolumnHeader = Integer.parseInt("" + hashModel.get("columnCount")) + 1;
            }
            table = new PdfPTable(ncolumnHeader);
            cell.setColspan(ncolumnHeader);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);

            Paragraph p2 = new Paragraph("No.");
            p2.getFont().setSize(20);
            PdfPCell cellColNo = new PdfPCell(p2);
            cellColNo.setNoWrap(true);
            cellColNo.setMinimumHeight(50);
            cellColNo.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellColNo);

            if (hashModel != null) {
                Enumeration k = hashModel.keys();
                while (k.hasMoreElements()) {
                    String key = (String) k.nextElement();
                    if (key.equals("columnCount")) {
                        continue;
                    }
                    PdfPCell cellCol = new PdfPCell(new Paragraph(hashModel.get(key) + ""));
                    cellCol.setNoWrap(true);
                    cellCol.setMinimumHeight(50);
                    cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);

                    table.addCell(cellCol);
                }
            } else {
                for (int i = 1; i < ncolumnHeader; i++) {
                    System.out.println("DATA = " + metaColumn.getColumnName(i));
                    Paragraph p1 = new Paragraph(metaColumn.getColumnName(i) + "");
                    p1.getFont().setSize(20);
                    PdfPCell cellCol = new PdfPCell(p1);
                    cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);
                    table.addCell(cellCol);
                }
            }

            //iterate all columns : table data
            resultSet.beforeFirst();
            int row = 1;
            while (resultSet.next()) {
                System.out.println(row);
                Paragraph p3 = new Paragraph(row + "");
                p3.getFont().setSize(20);
                cell = new PdfPCell(p3);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                if (hashModel != null) {//skip dulu u/ kasus ga pny class kustomasi table
                    Enumeration k = hashModel.keys();
                    while (k.hasMoreElements()) {
                        String key = (String) k.nextElement();
                        if (key.equals("columnCount")) {
                            continue;
                        }
                        table.addCell(resultSet.getObject(key) + "");
                    }
                } else {
                    for (int i = 1; i < ncolumnHeader; i++) {
                        System.out.println("DATA = " + metaColumn.getColumnName(i));
                        Paragraph p1 = new Paragraph(resultSet.getObject(metaColumn.getColumnName(i)) + "");
                        p1.getFont().setSize(18);
                        PdfPCell cellCol = new PdfPCell(p1);
                        cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table.addCell(cellCol);
                    }
                }

                row++;
            }

            document.add(table);
            document.add(new Paragraph("\n\n"));
            par = new Paragraph("Mengetahui");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("Kepada Badan Kepegawaian");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("\n\n\n");

            document.add(par);
            par = new Paragraph("Drs. Maman Permana");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("Nip: 197802042006041013");
            par.setAlignment("center");

            document.add(par);

        }
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}