Example usage for com.lowagie.text Document setFooter

List of usage examples for com.lowagie.text Document setFooter

Introduction

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

Prototype


public void setFooter(HeaderFooter footer) 

Source Link

Document

Changes the footer of this document.

Usage

From source file:com.stratelia.webactiv.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 a  va2  s  . c  om
        SilverTrace.info("almanach", "AlmanachPdfGenerator.buildPdf()", "root.MSG_GEN_ENTER_METHOD");

        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();
        SilverTrace.info("almanach", "AlmanachPdfGenerator.buildPdf()", "root.MSG_GEN_EXIT_METHOD");

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

}

From source file:com.stratelia.webactiv.newsEdito.control.PdfGenerator.java

License:Open Source License

/**
 * Method declaration//from  w w  w. ja v a  2 s . c  o  m
 * @param name
 * @param completePubList
 * @param langue
 * @throws NewsEditoException
 * @see
 */
public static void generatePubList(String name, Collection<CompletePublication> completePubList, String langue)
        throws NewsEditoException {
    SilverTrace.info("NewsEdito", "PdfGenerator.generatePubList", "NewsEdito.MSG_ENTRY_METHOD",
            "Pdf name = " + name);
    try {
        CompletePublication first = completePubList.iterator().next();
        String fileName = FileRepositoryManager.getTemporaryPath(
                first.getPublicationDetail().getPK().getSpace(),
                first.getPublicationDetail().getPK().getComponentName()) + name;
        ResourceLocator message = new ResourceLocator(
                "com.stratelia.webactiv.newsEdito.multilang.newsEditoBundle", langue);
        // creation of the document with a certain size and certain margins
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        // we add some meta information to the document
        document.addAuthor("Generateur de PDF Silverpeas");
        document.addSubject("Compilation de publications Silverpeas");
        document.addCreationDate();

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

        createFirstPage(document, langue);

        HeaderFooter header = new HeaderFooter(new Phrase(message.getString("publicationCompilation")), false);
        HeaderFooter footer = new HeaderFooter(new Phrase("Page "), new Phrase("."));

        footer.setAlignment(Element.ALIGN_CENTER);

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

        document.newPage();

        Font titleFont = new Font(Font.HELVETICA, 24, Font.NORMAL, new Color(255, 255, 255));
        Paragraph cTitle = new Paragraph(message.getString("listPublication"), titleFont);
        Chapter chapter = new Chapter(cTitle, 1);

        Iterator<CompletePublication> i = completePubList.iterator();
        CompletePublication complete = null;
        while (i.hasNext()) {
            complete = i.next();

            addPublication(chapter, complete);
        }

        document.add(chapter);

        document.close();
    } catch (Exception e) {
        throw new NewsEditoException("PdfGenerator.generatePubList", NewsEditoException.WARNING,
                "NewsEdito.EX_PROBLEM_TO_GENERATE_PUBLI_LIST", e);
    }
}

From source file:com.stratelia.webactiv.newsEdito.control.PdfGenerator.java

License:Open Source License

/**
 * Method declaration/*from  w ww. jav a2s.  com*/
 * @param name
 * @param archiveDetail
 * @param publicationBm
 * @param langue
 * @throws NewsEditoException
 * @see
 */
public static void generateArchive(String name, NodeDetail archiveDetail, PublicationBm publicationBm,
        String langue) throws NewsEditoException {
    SilverTrace.info("NewsEdito", "PdfGenerator.generateArchive", "NewsEdito.MSG_ENTRY_METHOD",
            "Pdf name = " + name);
    try {
        String fileName = FileRepositoryManager.getTemporaryPath(archiveDetail.getNodePK().getSpace(),
                archiveDetail.getNodePK().getComponentName()) + name;
        // creation of the document with a certain size and certain margins
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        // we add some meta information to the document
        document.addAuthor("Generateur de PDF Silverpeas");
        document.addSubject("Journal Silverpeas : " + archiveDetail.getName());
        document.addCreationDate();

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

        createFirstPage(document, langue);

        // we define a header and a footer
        String descriptionArchive = archiveDetail.getDescription();
        if (descriptionArchive == null)
            descriptionArchive = " ";

        HeaderFooter header = new HeaderFooter(new Phrase(archiveDetail.getName() + " : " + descriptionArchive),
                false);
        HeaderFooter footer = new HeaderFooter(new Phrase("Page "), new Phrase("."));

        footer.setAlignment(Element.ALIGN_CENTER);

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

        document.newPage();

        PdfGenerator.addEditorial(document, archiveDetail, publicationBm, langue);
        PdfGenerator.addMasterTable(document, archiveDetail, publicationBm);

        document.close();
    } catch (Exception e) {
        throw new NewsEditoException("PdfGenerator.generateArchive", NewsEditoException.WARNING,
                "NewsEdito.EX_PROBLEM_TO_GENERATE_ARCHIVE", e);
    }

}

From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java

License:Apache License

/******************************************************************************************************
 * Adds the all pages.//from w w  w .ja v  a 2 s  .c  o  m
 * 
 * @param pagesizemode {@link PdfPageSize}
 * @param writer {@link PdfWriter}
 * @param pdfdoc {@link Document}
 * @return {@link PdfPageLabels}
 * 
 * 
 * @throws ImageInterpreterException the image interpreter exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws MalformedURLException the malformed url exception
 * @throws PDFManagerException the PDF manager exception
 * @throws ImageManagerException
 *******************************************************************************************************/
private PdfPageLabels addAllPages(PdfPageSize pagesizemode, PdfWriter writer, Document pdfdoc,
        Watermark myWatermark) throws ImageInterpreterException, IOException, MalformedURLException,
        PDFManagerException, ImageManagerException {

    PdfPageLabels pagelabels = new PdfPageLabels();
    int pageadded = 0;

    // sort the HashMap by the KeySet (pagenumber)
    Map<Integer, UrlImage> sortedMap = new TreeMap<Integer, UrlImage>(imageURLs);

    float scalefactor = 1; // scaling factor of the image
    int page_w = PaperSize.A4.width;
    int page_h = PaperSize.A4.height;
    LOGGER.debug("iterate over " + imageURLs.size() + " pages.");
    for (Integer imageKey : sortedMap.keySet()) {

        Watermark watermark = myWatermark;
        Image pdfImage = null; // PDF-Image
        LOGGER.debug("Writing page " + imageKey);

        boolean errorPage = false; // true if the image does not exists
        URL errorUrl = null; // url of the image that does not exists

        // ------------------------------------------------------------------------------------------------
        // Title page available. Render it in pdftitlepage
        // ------------------------------------------------------------------------------------------------
        if ((pdftitlepages != null) && (pdftitlepages.get(imageKey) != null)) {
            // title page
            PDFTitlePage pdftitlepage = pdftitlepages.get(imageKey);
            // create new PDF page
            try {
                pdfdoc.setPageSize(PageSize.A4);
                pdfdoc.setMargins(pdftitlepage.getLeftMargin(), pdftitlepage.getRightMargin(),
                        pdftitlepage.getTopMargin(), pdftitlepage.getBottomMargin());
                pageadded++;
                pdfdoc.newPage(); // create new page
                // set page name
                pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, "-");
            } catch (Exception e1) {
                throw new PDFManagerException("PDFManagerException occured while creating new page in PDF", e1);
            }
            // render title page
            pdftitlepage.render(pdfdoc);
        }

        // ------------------------------------------------------------------------------------------------
        // Process image with imageKey
        // ------------------------------------------------------------------------------------------------
        UrlImage pdfpage = imageURLs.get(imageKey);
        if (pdfpage.getURL() != null) {
            boolean added = false;
            boolean scaled = false;
            URL url = pdfpage.getURL();
            // pdf hack
            if (ContentServerConfiguration.getInstance().getUsePdf()) {
                LOGGER.debug("trying to find original pdf");
                PdfContentByte pdfcb = null;
                PdfReader pdfreader = null;
                PdfImportedPage importpage = null;
                try {
                    String pdfpath = ContentServerConfiguration.getInstance().getRepositoryPathPdf()
                            .replace("file:///", "");
                    LOGGER.debug("looking in " + pdfpath + " for pdf file");
                    String tiffPath = ContentServerConfiguration.getInstance().getRepositoryPathImages()
                            .replace("file:///", "");
                    // String urlString = url.toString();
                    int pageNumber = pdfpage.getPageNumber();
                    // UrlImage copy = new PDFPage(pdfpage);
                    URL pdfurl = new URL(url.toString().replace(tiffPath, pdfpath)
                            .replace(url.toString().substring(url.toString().lastIndexOf(".")), ".pdf"));
                    LOGGER.debug("pdfurl = " + pdfurl);

                    if (new File(pdfurl.toURI()).exists()) {
                        LOGGER.debug("found pdf " + pdfurl.toURI());
                        // copy.setURL(pdfurl);
                        pdfcb = writer.getDirectContent();
                        pdfreader = new PdfReader(pdfurl);
                        importpage = writer.getImportedPage(pdfreader, pageNumber);

                        LOGGER.debug("creating orig pdf page");
                        Rectangle rect = pdfreader.getPageSize(pageNumber);
                        try {
                            pdfdoc.setPageSize(rect);
                            pdfdoc.newPage(); // create new page
                        } catch (Exception e1) {
                            throw new PDFManagerException("Exception occured while creating new page in PDF",
                                    e1);
                        }
                        pageadded++;
                        pdfcb.addTemplate(importpage, 0, 0);
                        added = true;
                        LOGGER.debug("page:" + imageKey + "  url: " + pdfurl.toString());

                    }
                } catch (URISyntaxException e) {
                    LOGGER.debug(e);
                    added = false;
                } finally {
                    if (writer != null) {
                        writer.freeReader(pdfreader);
                        writer.flush();
                    }
                    if (pdfreader != null) {
                        pdfreader.close();
                    }
                }
            }
            if (!added) {
                // image file
                LOGGER.debug("using image to create pdf page");
                // try to get ImageInterpreter from url
                ImageInterpreter myInterpreter = ImageFileFormat.getInterpreter(url, httpproxyhost,
                        httpproxyport, httpproxyuser, httpproxypassword);

                try {
                    // check preferred compression type depending on color depth
                    Embedd preferredEmbeddingType = Embedd.ORIGBYTESTREAM;
                    if (myInterpreter.getColordepth() == 1) {
                        // bitonal image
                        preferredEmbeddingType = embeddBitonalImage;
                    } else if ((myInterpreter.getColordepth() > 1)
                            && (myInterpreter.getSamplesperpixel() == 1)) {
                        // greyscale image
                        preferredEmbeddingType = embeddGreyscaleImage;
                    } else {
                        // color image
                        preferredEmbeddingType = embeddColorImage;
                    }

                    // -------------------------------------------------------------------------------------
                    // Try to generate image
                    // -------------------------------------------------------------------------------------
                    pdfImage = generatePdfImageFromInterpreter(myInterpreter, preferredEmbeddingType, errorPage,
                            watermark, errorUrl);

                    // -------------------------------------------------------------------------------------
                    // image couldn't be embedded yet (emergencyCase)
                    // -------------------------------------------------------------------------------------
                    if (pdfImage == null) {
                        LOGGER.warn(
                                "Couldn't use preferred method for embedding the image. Instead had to use JPEG or RenderedImage");

                        // Get Interpreter and rendered Image
                        // ---------------------------------------------------------------------------------------------------------------------------------
                        RenderedImage ri = null;
                        if (preferredEmbeddingType == embeddBitonalImage) {
                            ImageManager sourcemanager = new ImageManager(url);
                            boolean watermarkscale = ContentServerConfiguration.getInstance()
                                    .getScaleWatermark(); // should we scale
                            // the watermark ?
                            ri = sourcemanager.scaleImageByPixel(3000, 0, ImageManager.SCALE_BY_WIDTH, 0, null,
                                    null, watermark, watermarkscale, ImageManager.BOTTOM);
                            myInterpreter = sourcemanager.getMyInterpreter();
                        } else {
                            ri = myInterpreter.getRenderedImage();
                            if (watermark != null) {
                                ri = addwatermark(ri, watermark, 2);
                                myInterpreter.setHeight(
                                        myInterpreter.getHeight() + watermark.getRenderedImage().getHeight());
                            }
                        }

                        // scale rendered image
                        // ---------------------------------------------------------------------------------------------------------------------------------
                        // float scalefactorX = 1;
                        // float scalefactorY = 1;
                        // switch (pagesizemode) {
                        // case ORIGINAL:
                        // scalefactorX = 72f / myInterpreter.getXResolution();
                        // scalefactorY = 72f / myInterpreter.getYResolution();
                        // break;
                        // default:
                        // /*
                        // * check, if the image needs to be scaled, because
                        // * it's bigger than A4 calculate the new scalefactor
                        // */
                        // float page_w_pixel = (float) (page_w *
                        // myInterpreter.getXResolution() / 25.4);
                        // float page_h_pixel = (float) (page_h *
                        // myInterpreter.getYResolution() / 25.4);
                        //
                        // float res_x = myInterpreter.getXResolution();
                        // float res_y = myInterpreter.getYResolution();
                        //
                        // long w = myInterpreter.getWidth(); // get height and
                        // // width
                        // long h = myInterpreter.getHeight();
                        //
                        // if ((w > page_w_pixel) || (h > page_h_pixel)) {
                        // LOGGER.debug("scale image to fit the page");
                        // float scalefactor_w = page_w_pixel / w;
                        // float scalefactor_h = page_h_pixel / h;
                        // if (scalefactor_h < scalefactor_w) {
                        // scalefactor = scalefactor_h;
                        // } else {
                        // scalefactor = scalefactor_w;
                        // }
                        // w = (long) (w * scalefactor);
                        // h = (long) (h * scalefactor);
                        // }
                        // scalefactorX = (72f / res_x) * scalefactor;
                        // scalefactorY = (72f / res_y) * scalefactor;
                        // break;
                        // }
                        // //scalefactorX = 0.2f;
                        // //scalefactorY = 0.2f;
                        // if (preferredEmbeddingType == embeddBitonalImage) {
                        // ImageManager sourcemanager = new ImageManager(url);
                        // ri = sourcemanager.scaleImageByPixel((int)
                        // (scalefactorX*100), (int) (scalefactorY*100),
                        // ImageManager.SCALE_BY_PERCENT, 0, null, null,
                        // watermark, true, ImageManager.BOTTOM);
                        // }else{
                        // ri = ImageManipulator.scaleInterpolationBilinear(ri,
                        // scalefactorX, scalefactorY);
                        // }
                        // myInterpreter.setHeight(ri.getHeight());
                        // myInterpreter.setWidth(ri.getWidth());
                        // scaled = true;

                        // add Watermark
                        // ---------------------------------------------------------------------------------------------------------------------------------
                        // ri = addwatermark(ri, watermark,
                        // ImageManager.BOTTOM);
                        // myInterpreter.setHeight(myInterpreter.getHeight() +
                        // watermark.getRenderedImage().getHeight());

                        // Try to write into pdfImage
                        // ---------------------------------------------------------------------------------------------------------------------------------
                        if (myInterpreter.getColordepth() > 1) {
                            // compress image if greyscale or color
                            ByteArrayOutputStream bytesoutputstream = new ByteArrayOutputStream();
                            // JpegInterpreter jpint = new JpegInterpreter(ri);
                            // jpint.setXResolution(myInterpreter.getXResolution());
                            // jpint.setYResolution(myInterpreter.getYResolution());
                            // jpint.writeToStream(null, bytesoutputstream);
                            LOGGER.error("WritingJPEGImage");
                            writeJpegFromRenderedImageToStream(bytesoutputstream, ri, null, myInterpreter);
                            byte[] returnbyteArray = bytesoutputstream.toByteArray();
                            if (bytesoutputstream != null) {
                                bytesoutputstream.flush();
                                bytesoutputstream.close();
                            }
                            pdfImage = Image.getInstance(returnbyteArray);
                            returnbyteArray = null;
                        } else {
                            // its bitonal, but can't be embedded directly,
                            // need to go via RenderedImage
                            BufferedImage buffImage = ImageManipulator.fromRenderedToBuffered(ri);
                            pdfImage = Image.getInstance(buffImage, null, false);
                            if (myWatermark != null) {
                                // create Image for Watermark
                                JpegInterpreter jpint = new JpegInterpreter(myWatermark.getRenderedImage());
                                ByteArrayOutputStream bytesoutputstream = new ByteArrayOutputStream();
                                jpint.setXResolution(myInterpreter.getXResolution());
                                jpint.setYResolution(myInterpreter.getYResolution());
                                jpint.writeToStream(null, bytesoutputstream);
                                byte[] returnbyteArray = bytesoutputstream.toByteArray();
                                jpint.clear();
                                if (bytesoutputstream != null) {
                                    bytesoutputstream.flush();
                                    bytesoutputstream.close();
                                }
                                Image blaImage = Image.getInstance(returnbyteArray);
                                returnbyteArray = null;
                                // set Watermark as Footer at fixed position
                                // (200,200)
                                Chunk c = new Chunk(blaImage, 200, 200);
                                Phrase p = new Phrase(c);
                                HeaderFooter hf = new HeaderFooter(p, false);
                                pdfdoc.setFooter(hf);
                            }
                            // pdfdoc.setPageSize(arg0)
                            // TODO das scheint nicht zu funktionieren... sollte
                            // dieser Code entfernt werden?

                        }
                    } // end of : if (pdfImage == null) {
                } catch (BadElementException e) {
                    throw new PDFManagerException("Can't create a PDFImage from a Buffered Image.", e);
                } catch (ImageManipulatorException e) {
                    LOGGER.warn(e);
                }

                // ---------------------------------------------------------------------------------------------------------
                // place the image on the page
                // ---------------------------------------------------------------------------------------------------------
                if (pagesizemode == PdfPageSize.ORIGINAL) {
                    // calculate the image width and height in points, create
                    // the rectangle in points

                    Rectangle rect = null;
                    if (!scaled) {
                        float image_w_points = (myInterpreter.getWidth() / myInterpreter.getXResolution()) * 72;
                        float image_h_points = ((myInterpreter.getHeight()) / myInterpreter.getYResolution())
                                * 72;
                        rect = new Rectangle(image_w_points, image_h_points);
                    } else {
                        rect = new Rectangle(myInterpreter.getWidth(), myInterpreter.getHeight());
                    }

                    // create the pdf page according to this rectangle
                    LOGGER.debug("creating original page sized PDF page:" + rect.getWidth() + " x "
                            + rect.getHeight());
                    pdfdoc.setPageSize(rect);

                    // create new page to put the content
                    try {
                        pageadded++;
                        pdfdoc.newPage();
                    } catch (Exception e1) {
                        throw new PDFManagerException(
                                "DocumentException occured while creating page " + pageadded + " in PDF", e1);
                    }

                    // scale image and place it on page; scaling the image does
                    // not scale the images bytestream
                    if (!scaled) {
                        pdfImage.scalePercent((72f / myInterpreter.getXResolution() * 100),
                                (72f / myInterpreter.getYResolution() * 100));
                    }
                    pdfImage.setAbsolutePosition(0, 0); // set image to lower
                                                        // left corner

                    boolean result;
                    try {
                        result = pdfdoc.add(pdfImage); // add it to PDF
                        if (!result) {
                            throw new PDFManagerException("Image \"" + url.toString()
                                    + "\" can's be added to PDF! Error during placing image on page");
                        }
                    } catch (DocumentException e) {
                        throw new PDFManagerException("DocumentException occured while adding the image to PDF",
                                e);
                    }
                } else {
                    /*
                     * it is not the original page size PDF will contain only A4 pages
                     */
                    LOGGER.debug("creating A4 pdf page");

                    // create new page to put the content
                    try {
                        pageadded++;
                        pdfdoc.setPageSize(PageSize.A4);
                        pdfdoc.newPage(); // create new page
                    } catch (Exception e1) {
                        throw new PDFManagerException("Exception occured while creating new page in PDF", e1);
                    }

                    float page_w_pixel = (float) (page_w * myInterpreter.getXResolution() / 25.4);
                    float page_h_pixel = (float) (page_h * myInterpreter.getYResolution() / 25.4);

                    float res_x = myInterpreter.getXResolution();
                    float res_y = myInterpreter.getYResolution();

                    long w = myInterpreter.getWidth(); // get height and width
                    long h = myInterpreter.getHeight();

                    /*
                     * if the page is landscape, we have to rotate the page; this is only done in PDF, the orig image bytestream is NOT rotated
                     */
                    if (w > h) {
                        LOGGER.debug("rotate image");
                        // must be rotated
                        pdfImage.setRotationDegrees(90);
                        // change width and height
                        long dummy = w;
                        w = h;
                        h = dummy;
                        // change the resolutions x and y
                        float dummy2 = res_x;
                        res_x = res_y;
                        res_y = dummy2;
                    }

                    /*
                     * check, if the image needs to be scaled, because it's bigger than A4 calculate the new scalefactor
                     */
                    if ((w > page_w_pixel) || (h > page_h_pixel)) {
                        LOGGER.debug("scale image to fit the page");
                        float scalefactor_w = page_w_pixel / w;
                        float scalefactor_h = page_h_pixel / h;
                        if (scalefactor_h < scalefactor_w) {
                            scalefactor = scalefactor_h;
                        } else {
                            scalefactor = scalefactor_w;
                        }
                        w = (long) (w * scalefactor);
                        h = (long) (h * scalefactor);
                    }
                    if (!scaled) {
                        pdfImage.scalePercent((72f / res_x * 100) * scalefactor,
                                (72f / res_y * 100) * scalefactor);
                    }

                    // center the image on the page
                    // ---------------------------------------------------------------
                    float y_offset = 0; // y - offset
                    // get image size in cm; height
                    float h_cm = (float) (h / (res_x / 2.54));
                    // float w_cm = (float) (w / (res_y / 2.54)); // and width
                    if ((h_cm + 2) < (page_h / 10)) {
                        y_offset = 2 * 72f / 2.54f;
                    }
                    float freespace_x = ((page_w_pixel - w) / res_x * 72f);
                    float freespace_y = ((page_h_pixel - h) / res_y * 72f) - (y_offset);
                    // set position add image
                    pdfImage.setAbsolutePosition(freespace_x / 2, freespace_y);
                    boolean result;
                    try {
                        result = pdfdoc.add(pdfImage);
                    } catch (DocumentException e) {
                        LOGGER.error(e);
                        throw new PDFManagerException("DocumentException occured while adding the image to PDF",
                                e);
                    }
                    if (!result) {
                        // placing the image in the PDF was not successful
                        throw new PDFManagerException("Image \"" + url.toString()
                                + "\" can's be added to PDF! Error during placing image on page");
                    }

                    // draw box around the image page
                    // ------------------------------------------------------------------------------------------------
                    if (pagesizemode == PdfPageSize.A4BOX) {
                        LOGGER.debug("draw box around the image page");

                        // draw a black frame around the image
                        PdfContentByte pcb = writer.getDirectContent();

                        // calculate upper left corner of the box (measurment is
                        // in points)
                        float left_x = (freespace_x / 2);
                        float left_y = freespace_y;

                        // calculate the lower right corner of the box
                        // (measurement is in points)
                        float image_w_points = (w / res_x) * 72;
                        float image_h_points = (h / res_y) * 72;

                        pcb.setLineWidth(1f);
                        pcb.stroke();
                        pcb.rectangle(left_x, left_y, image_w_points, image_h_points);

                        pcb.stroke();
                    }

                } // end of: if (pagesizemode == PdfPageSize.ORIGINAL) {
                pdfImage = null;
                myInterpreter.clear();
                // writer.freeReader(new PdfReader(pdfpage.getURL()));
            } // end of : if (pdfpage.getURL() != null) {

            // ------------------------------------------------------------------------------------------------
            // it is a page from a PDF file which should be inserted
            // ------------------------------------------------------------------------------------------------
            else if (pdfpage.getClass() == PDFPage.class && ((PDFPage) pdfpage).getPdfreader() != null) {

                PdfContentByte pdfcb = writer.getDirectContent();

                PdfReader pdfreader = ((PDFPage) pdfpage).getPdfreader();
                PdfImportedPage importpage = writer.getImportedPage(pdfreader, pdfpage.getPageNumber());

                if (pagesizemode == PdfPageSize.ORIGINAL) {
                    LOGGER.debug("creating orig pdf page");
                    Rectangle rect = pdfreader.getPageSize(pdfpage.getPageNumber());
                    try {
                        pdfdoc.setPageSize(rect);
                        pdfdoc.newPage(); // create new page
                    } catch (Exception e1) {
                        throw new PDFManagerException("Exception occured while creating new page in PDF", e1);
                    }
                    // add content
                    pageadded++;
                    pdfcb.addTemplate(importpage, 0, 0);

                } else {
                    LOGGER.debug("creating A4 pdf page");
                    try {
                        pdfdoc.setPageSize(PageSize.A4);
                        pdfdoc.newPage(); // create new page
                    } catch (Exception e1) {
                        throw new PDFManagerException("Exception occured while creating new page in PDF", e1);
                    }

                    // add content
                    pageadded++;
                    pdfcb.addTemplate(importpage, 0, 0);

                    // draw box
                    // if (pagesizemode == PdfPageSize.A4BOX) {
                    // FIXME: nichts implementiert ?
                    // }
                }

            }
            // handle pagename
            if (imageNames != null) {
                String pagename = imageNames.get(imageKey);

                if (pagename != null) {
                    pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, pagename);
                } else {
                    pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, "unnumbered");
                }
            }
            // handle bookmarks and set destinator for bookmarks
            LOGGER.debug("handle bookmark(s) for page");

            PdfDestination destinator = new PdfDestination(PdfDestination.FIT);
            setBookmarksForPage(writer, destinator, imageKey); // the key in the
            writer.flush();
            // mashMap is the pagenumber

        } // end of while iterator over all pages

    }
    return pagelabels;

}

From source file:dinamica.AbstractPDFOutput.java

License:LGPL

/**
 * Receives a byte buffer that should be filled with resulting PDF.
 * @param data Data module that provides recordsets to this output module
 * @param buf Buffer to print PDF, then used to send to browser
 * @throws Throwable/*from w  ww . j a v a 2s . c  om*/
 */
protected void createPDF(GenericTransaction data, ByteArrayOutputStream buf) throws Throwable {

    //pdf objects
    Document doc = new Document();
    PdfWriter docWriter = PdfWriter.getInstance(doc, buf);

    //header
    HeaderFooter header = new HeaderFooter(new Phrase(getHeader()), false);
    header.setBorder(Rectangle.BOTTOM);
    header.setAlignment(Rectangle.ALIGN_CENTER);
    doc.setHeader(header);

    //footer
    HeaderFooter footer = new HeaderFooter(new Phrase(getFooter()), true);
    footer.setBorder(Rectangle.TOP);
    footer.setAlignment(Rectangle.ALIGN_RIGHT);
    doc.setFooter(footer);

    //pagesize
    doc.setPageSize(PageSize.LETTER);

    doc.open();

    //title
    Paragraph t = new Paragraph(getReportTitle(), new Font(Font.HELVETICA, 18f));
    t.setAlignment(Rectangle.ALIGN_CENTER);
    doc.add(t);

    //paragraph
    Paragraph p = new Paragraph("Hello World");
    p.setAlignment(Rectangle.ALIGN_CENTER);
    doc.add(p);

    doc.close();
    docWriter.close();

}

From source file:eu.europa.ec.markt.dss.report.Tsl2PdfExporter.java

License:Open Source License

/**
 * Produce a human readable export of the given tsl to the given file.
 * //from w w  w  .  j  a va  2  s.  c  om
 * @param tsl
 *            the TrustServiceList to export
 * @param pdfFile
 *            the file to generate
 * @return
 * @throws IOException
 */
public void humanReadableExport(final TrustServiceList tsl, final File pdfFile) {
    Document document = new Document();
    OutputStream outputStream;
    try {
        outputStream = new FileOutputStream(pdfFile);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("file not found: " + pdfFile.getAbsolutePath(), e);
    }
    try {
        final PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream);
        pdfWriter.setPDFXConformance(PdfWriter.PDFA1B);

        // title
        final EUCountry country = EUCountry.valueOf(tsl.getSchemeTerritory());
        final String title = country.getShortSrcLangName() + " (" + country.getShortEnglishName()
                + "): Trusted List";

        Phrase footerPhrase = new Phrase("PDF document generated on " + new Date().toString() + ", page ",
                headerFooterFont);
        HeaderFooter footer = new HeaderFooter(footerPhrase, true);
        document.setFooter(footer);

        Phrase headerPhrase = new Phrase(title, headerFooterFont);
        HeaderFooter header = new HeaderFooter(headerPhrase, false);
        document.setHeader(header);

        document.open();
        addTitle(title, title0Font, Paragraph.ALIGN_CENTER, 0, 20, document);

        addLongItem("Scheme name", tsl.getSchemeName(), document);
        addLongItem("Legal Notice", tsl.getLegalNotice(), document);

        // information table
        PdfPTable informationTable = createInfoTable();
        addItemRow("Scheme territory", tsl.getSchemeTerritory(), informationTable);
        addItemRow("Scheme status determination approach",
                substringAfter(tsl.getStatusDeterminationApproach(), "StatusDetn/"), informationTable);

        final List<String> schemeTypes = new ArrayList<String>();
        for (final String schemeType : tsl.getSchemeTypes()) {
            schemeTypes.add(schemeType);
        }
        addItemRow("Scheme type community rules", schemeTypes, informationTable);

        addItemRow("Issue date", tsl.getListIssueDateTime().toString(), informationTable);
        addItemRow("Next update", tsl.getNextUpdate().toString(), informationTable);
        addItemRow("Historical information period", tsl.getHistoricalInformationPeriod().toString() + " days",
                informationTable);
        addItemRow("Sequence number", tsl.getSequenceNumber().toString(), informationTable);
        addItemRow("Scheme information URIs", tsl.getSchemeInformationUris(), informationTable);

        document.add(informationTable);

        addTitle("Scheme Operator", title1Font, Paragraph.ALIGN_CENTER, 0, 10, document);

        informationTable = createInfoTable();
        addItemRow("Scheme operator name", tsl.getSchemeOperatorName(), informationTable);
        PostalAddressType schemeOperatorPostalAddress = tsl.getSchemeOperatorPostalAddress(Locale.ENGLISH);
        addItemRow("Scheme operator street address", schemeOperatorPostalAddress.getStreetAddress(),
                informationTable);
        addItemRow("Scheme operator postal code", schemeOperatorPostalAddress.getPostalCode(),
                informationTable);
        addItemRow("Scheme operator locality", schemeOperatorPostalAddress.getLocality(), informationTable);
        addItemRow("Scheme operator state", schemeOperatorPostalAddress.getStateOrProvince(), informationTable);
        addItemRow("Scheme operator country", schemeOperatorPostalAddress.getCountryName(), informationTable);

        List<String> schemeOperatorElectronicAddressess = tsl.getSchemeOperatorElectronicAddresses();
        addItemRow("Scheme operator contact", schemeOperatorElectronicAddressess, informationTable);
        document.add(informationTable);

        addTitle("Trust Service Providers", title1Font, Paragraph.ALIGN_CENTER, 10, 2, document);

        List<TrustServiceProvider> trustServiceProviders = tsl.getTrustServiceProviders();
        for (TrustServiceProvider trustServiceProvider : trustServiceProviders) {
            addTitle(trustServiceProvider.getName(), title1Font, Paragraph.ALIGN_LEFT, 10, 2, document);

            PdfPTable providerTable = createInfoTable();
            addItemRow("Service provider trade name", trustServiceProvider.getTradeName(), providerTable);
            addItemRow("Information URI", trustServiceProvider.getInformationUris(), providerTable);
            PostalAddressType postalAddress = trustServiceProvider.getPostalAddress();
            addItemRow("Service provider street address", postalAddress.getStreetAddress(), providerTable);
            addItemRow("Service provider postal code", postalAddress.getPostalCode(), providerTable);
            addItemRow("Service provider locality", postalAddress.getLocality(), providerTable);
            addItemRow("Service provider state", postalAddress.getStateOrProvince(), providerTable);
            addItemRow("Service provider country", postalAddress.getCountryName(), providerTable);
            document.add(providerTable);

            List<TrustService> trustServices = trustServiceProvider.getTrustServices();
            for (TrustService trustService : trustServices) {
                addTitle(trustService.getName(), title2Font, Paragraph.ALIGN_LEFT, 10, 2, document);
                PdfPTable serviceTable = createInfoTable();
                addItemRow("Type", substringAfter(trustService.getType(), "Svctype/"), serviceTable);
                addItemRow("Status", substringAfter(trustService.getStatus(), "Svcstatus/"), serviceTable);
                addItemRow("Status starting time", trustService.getStatusStartingTime().toString(),
                        serviceTable);
                document.add(serviceTable);

                addTitle("Service digital identity (X509)", title3Font, Paragraph.ALIGN_LEFT, 2, 0, document);
                final X509Certificate certificate = trustService.getServiceDigitalIdentity();
                final PdfPTable serviceIdentityTable = createInfoTable();
                addItemRow("Version", Integer.toString(certificate.getVersion()), serviceIdentityTable);
                addItemRow("Serial number", certificate.getSerialNumber().toString(), serviceIdentityTable);
                addItemRow("Signature algorithm", certificate.getSigAlgName(), serviceIdentityTable);
                addItemRow("Issuer", certificate.getIssuerX500Principal().toString(), serviceIdentityTable);
                addItemRow("Valid from", certificate.getNotBefore().toString(), serviceIdentityTable);
                addItemRow("Valid to", certificate.getNotAfter().toString(), serviceIdentityTable);
                addItemRow("Subject", certificate.getSubjectX500Principal().toString(), serviceIdentityTable);
                addItemRow("Public key", certificate.getPublicKey().toString(), serviceIdentityTable);
                // TODO certificate policies
                addItemRow("Subject key identifier", toHex(getSKId(certificate)), serviceIdentityTable);
                addItemRow("CRL distribution points", getCrlDistributionPoints(certificate),
                        serviceIdentityTable);
                addItemRow("Authority key identifier", toHex(getAKId(certificate)), serviceIdentityTable);
                addItemRow("Key usage", getKeyUsage(certificate), serviceIdentityTable);
                addItemRow("Basic constraints", getBasicConstraints(certificate), serviceIdentityTable);

                byte[] encodedCertificate;
                try {
                    encodedCertificate = certificate.getEncoded();
                } catch (CertificateEncodingException e) {
                    throw new RuntimeException("cert: " + e.getMessage(), e);
                }
                addItemRow("SHA1 Thumbprint", DigestUtils.shaHex(encodedCertificate), serviceIdentityTable);
                addItemRow("SHA256 Thumbprint", DigestUtils.sha256Hex(encodedCertificate),
                        serviceIdentityTable);
                document.add(serviceIdentityTable);

                List<ExtensionType> extensions = trustService.getExtensions();
                for (ExtensionType extension : extensions) {
                    printExtension(extension, document);
                }

                addLongMonoItem("The decoded certificate:", certificate.toString(), document);
                addLongMonoItem("The certificate in PEM format:", toPem(certificate), document);
            }
        }

        X509Certificate signerCertificate = tsl.verifySignature();
        if (null != signerCertificate) {
            Paragraph tslSignerTitle = new Paragraph("Trusted List Signer", title1Font);
            tslSignerTitle.setAlignment(Paragraph.ALIGN_CENTER);
            document.add(tslSignerTitle);

            final PdfPTable signerTable = createInfoTable();
            addItemRow("Subject", signerCertificate.getSubjectX500Principal().toString(), signerTable);
            addItemRow("Issuer", signerCertificate.getIssuerX500Principal().toString(), signerTable);
            addItemRow("Not before", signerCertificate.getNotBefore().toString(), signerTable);
            addItemRow("Not after", signerCertificate.getNotAfter().toString(), signerTable);
            addItemRow("Serial number", signerCertificate.getSerialNumber().toString(), signerTable);
            addItemRow("Version", Integer.toString(signerCertificate.getVersion()), signerTable);
            byte[] encodedPublicKey = signerCertificate.getPublicKey().getEncoded();
            addItemRow("Public key SHA1 Thumbprint", DigestUtils.shaHex(encodedPublicKey), signerTable);
            addItemRow("Public key SHA256 Thumbprint", DigestUtils.sha256Hex(encodedPublicKey), signerTable);
            document.add(signerTable);

            addLongMonoItem("The decoded certificate:", signerCertificate.toString(), document);
            addLongMonoItem("The certificate in PEM format:", toPem(signerCertificate), document);
            addLongMonoItem("The public key in PEM format:", toPem(signerCertificate.getPublicKey()), document);
        }

        document.close();
    } catch (DocumentException e) {
        throw new RuntimeException("PDF document error: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new RuntimeException("Exception: " + e.getMessage(), e);
    }
}

From source file:fr.univlorraine.mondossierweb.controllers.CalendrierController.java

License:Apache License

/**
 * /*  www.  j a va2  s. c o  m*/
 * @param document pdf
 */
public void creerPdfCalendrier(final Document document, Etudiant etudiant) {

    //configuration des fonts
    Font normal = FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, Font.NORMAL);
    Font normalbig = FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.BOLD);
    Font legerita = FontFactory.getFont(FontFactory.TIMES_ROMAN, 9, Font.ITALIC);
    Font headerbig = FontFactory.getFont(FontFactory.TIMES_ROMAN, 16, Font.BOLD);
    Font header = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.BOLD);

    //pieds de pages:
    Date d = new Date();
    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    String date = dateFormat.format(d);
    //alignement des libells du pied de page:
    String partie1 = applicationContext.getMessage("pdf.calendrier.title", null, Locale.getDefault());
    String partie2 = applicationContext.getMessage("pdf.edition.date", null, Locale.getDefault()) + " : "
            + date;
    if (partie1.length() < ECARTEMENT_PIED_PAGE_PDF) {
        int diff = ECARTEMENT_PIED_PAGE_PDF - partie1.length();
        for (int i = 0; i < diff; i++) {
            partie1 = partie1 + " ";

        }
    }
    if (partie2.length() < ECARTEMENT_PIED_PAGE_PDF) {
        int diff = ECARTEMENT_PIED_PAGE_PDF - partie2.length();
        for (int i = 0; i < diff; i++) {
            partie2 = " " + partie2;
        }
    }

    //cration du pied de page:
    Phrase phra = new Phrase(
            partie1 + " -" + applicationContext.getMessage("pdf.page", null, Locale.getDefault()), legerita);
    Phrase phra2 = new Phrase("- " + partie2, legerita);
    HeaderFooter hf = new HeaderFooter(phra, phra2);
    hf.setAlignment(HeaderFooter.ALIGN_CENTER);
    document.setFooter(hf);

    //ouverte du document.
    document.open();
    try {
        //ajout image test
        if (configController.getLogoUniversitePdf() != null
                && !configController.getLogoUniversitePdf().equals("")) {
            Image image1 = Image.getInstance(configController.getLogoUniversitePdf());
            float scaleRatio = 40 / image1.getHeight();
            float newWidth = scaleRatio * image1.getWidth();
            image1.scaleAbsolute(newWidth, 40);
            image1.setAbsolutePosition(800 - newWidth, 528);
            document.add(image1);
        }

        //nouveau paragraphe
        Paragraph p = new Paragraph(
                applicationContext.getMessage("pdf.calendrier.title", null, Locale.getDefault()).toUpperCase()
                        + "\n\n",
                headerbig);
        p.setIndentationLeft(15);
        document.add(p);

        if (etudiant.getNom() != null) {
            Paragraph p0 = new Paragraph(etudiant.getNom(), normal);
            p0.setIndentationLeft(15);
            document.add(p0);
        }
        if (etudiant.getCod_etu() != null) {
            Paragraph p01 = new Paragraph(applicationContext.getMessage("pdf.folder", null, Locale.getDefault())
                    + " : " + etudiant.getCod_etu(), normal);
            p01.setIndentationLeft(15);
            document.add(p01);
        }
        if (etudiant.getCod_nne() != null) {
            Paragraph p02 = new Paragraph(applicationContext.getMessage("pdf.nne", null, Locale.getDefault())
                    + " : " + etudiant.getCod_nne(), normal);
            p02.setIndentationLeft(15);
            document.add(p02);
        }
        if (etudiant.getEmail() != null) {
            Paragraph p03 = new Paragraph(applicationContext.getMessage("pdf.mail", null, Locale.getDefault())
                    + " : " + etudiant.getEmail(), normal);
            p03.setIndentationLeft(15);
            document.add(p03);
        }

        Paragraph p03 = new Paragraph(
                applicationContext.getMessage("pdf.edition.date", null, Locale.getDefault()) + " : " + date,
                normal);
        p03.setIndentationLeft(15);
        document.add(p03);
        document.add(new Paragraph("\n"));

        //Partie Calendrier
        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(98);
        PdfPCell cell = new PdfPCell(new Paragraph(applicationContext
                .getMessage("pdf.calendrier.subtitle", null, Locale.getDefault()).toUpperCase() + " ", header));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setBackgroundColor(new Color(153, 153, 255));
        table.addCell(cell);

        PdfPTable table2;

        boolean affNumPlaceExamen = configController.isAffNumPlaceExamen();

        if (affNumPlaceExamen) {
            table2 = new PdfPTable(7);
            table2.setWidthPercentage(98);
            int[] tabWidth = { 15, 10, 10, 40, 30, 10, 60 };
            table2.setWidths(tabWidth);
        } else {
            table2 = new PdfPTable(6);
            table2.setWidthPercentage(98);
            int[] tabWidth = { 15, 10, 10, 45, 30, 65 };
            table2.setWidths(tabWidth);
        }

        Paragraph p1 = new Paragraph(applicationContext.getMessage("pdf.date", null, Locale.getDefault()),
                normalbig);
        Paragraph p2 = new Paragraph(applicationContext.getMessage("pdf.heure", null, Locale.getDefault()),
                normalbig);
        Paragraph p3 = new Paragraph(applicationContext.getMessage("pdf.duree", null, Locale.getDefault()),
                normalbig);
        Paragraph p4 = new Paragraph(applicationContext.getMessage("pdf.batiment", null, Locale.getDefault()),
                normalbig);
        Paragraph p5 = new Paragraph(applicationContext.getMessage("pdf.salle", null, Locale.getDefault()),
                normalbig);
        Paragraph p6 = new Paragraph(applicationContext.getMessage("pdf.place", null, Locale.getDefault()),
                normalbig);
        Paragraph p7 = new Paragraph(applicationContext.getMessage("pdf.examen", null, Locale.getDefault()),
                normalbig);

        PdfPCell ct1 = new PdfPCell(p1);
        PdfPCell ct2 = new PdfPCell(p2);
        PdfPCell ct3 = new PdfPCell(p3);
        PdfPCell ct4 = new PdfPCell(p4);
        PdfPCell ct5 = new PdfPCell(p5);
        PdfPCell ct6 = new PdfPCell(p6);
        PdfPCell ct7 = new PdfPCell(p7);

        ct1.setBorder(Rectangle.BOTTOM);
        ct1.setBorderColorBottom(Color.black);
        ct2.setBorder(Rectangle.BOTTOM);
        ct2.setBorderColorBottom(Color.black);
        ct3.setBorder(Rectangle.BOTTOM);
        ct2.setBorderColorBottom(Color.black);
        ct4.setBorder(Rectangle.BOTTOM);
        ct1.setBorderColorBottom(Color.black);
        ct5.setBorder(Rectangle.BOTTOM);
        ct2.setBorderColorBottom(Color.black);
        ct6.setBorder(Rectangle.BOTTOM);
        ct2.setBorderColorBottom(Color.black);
        ct7.setBorder(Rectangle.BOTTOM);
        ct2.setBorderColorBottom(Color.black);

        table2.addCell(ct1);
        table2.addCell(ct2);
        table2.addCell(ct3);
        table2.addCell(ct4);
        table2.addCell(ct5);
        if (affNumPlaceExamen)
            table2.addCell(ct6);
        table2.addCell(ct7);

        for (int i = 0; i < etudiant.getCalendrier().size(); i++) {
            Paragraph pa = new Paragraph(etudiant.getCalendrier().get(i).getDatedeb(), normal);
            PdfPCell celltext = new PdfPCell(pa);
            celltext.setBorder(Rectangle.NO_BORDER);

            Paragraph pa2 = new Paragraph(etudiant.getCalendrier().get(i).getHeure(), normal);
            PdfPCell celltext2 = new PdfPCell(pa2);
            celltext2.setBorder(Rectangle.NO_BORDER);

            Paragraph pa3 = new Paragraph(etudiant.getCalendrier().get(i).getDuree(), normal);
            PdfPCell celltext3 = new PdfPCell(pa3);
            celltext3.setBorder(Rectangle.NO_BORDER);

            Paragraph pa4 = new Paragraph(etudiant.getCalendrier().get(i).getBatiment(), normal);
            PdfPCell celltext4 = new PdfPCell(pa4);
            celltext4.setBorder(Rectangle.NO_BORDER);

            Paragraph pa5 = new Paragraph(etudiant.getCalendrier().get(i).getSalle(), normal);
            PdfPCell celltext5 = new PdfPCell(pa5);
            celltext5.setBorder(Rectangle.NO_BORDER);

            Paragraph pa6 = new Paragraph(etudiant.getCalendrier().get(i).getPlace(), normal);
            PdfPCell celltext6 = new PdfPCell(pa6);
            celltext6.setBorder(Rectangle.NO_BORDER);

            Paragraph pa7 = new Paragraph(etudiant.getCalendrier().get(i).getEpreuve(), normal);
            PdfPCell celltext7 = new PdfPCell(pa7);
            celltext7.setBorder(Rectangle.NO_BORDER);

            table2.addCell(celltext);
            table2.addCell(celltext2);
            table2.addCell(celltext3);
            table2.addCell(celltext4);
            table2.addCell(celltext5);
            if (affNumPlaceExamen)
                table2.addCell(celltext6);
            table2.addCell(celltext7);

            /*PdfPCell celltext4 = new PdfPCell(table3);
            celltext4.setBorder(Rectangle.NO_BORDER);
            table2.addCell(celltext4);*/

        }
        document.add(table);
        document.add(table2);
        document.add(new Paragraph("\n"));

    } catch (BadElementException e) {
        LOG.error("Erreur  la gnration du calendrier des examens : BadElementException ", e);
    } catch (MalformedURLException e) {
        LOG.error("Erreur  la gnration du calendrier des examens : MalformedURLException ", e);
    } catch (IOException e) {
        LOG.error("Erreur  la gnration du calendrier des examens : IOException ", e);
    } catch (DocumentException e) {
        LOG.error("Erreur  la gnration du calendrier des examens : DocumentException ", e);
    }
    // step 6: fermeture du document.
    document.close();

}

From source file:fr.univlorraine.mondossierweb.controllers.ListeInscritsController.java

License:Apache License

/**
 * //from w  w w  .  j a  v  a  2s  . c o  m
 * @param document pdf
 */
public void creerPdfTrombinoscope(final Document document, List<Inscrit> listeInscrits,
        List<String> listecodind, String libelle, String annee) {

    //configuration des fonts
    Font normal = FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, Font.NORMAL);
    Font normalbig = FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, Font.BOLD);
    Font legerita = FontFactory.getFont(FontFactory.TIMES_ROMAN, 9, Font.ITALIC);
    Font leger = FontFactory.getFont(FontFactory.TIMES_ROMAN, 9, Font.NORMAL);
    Font headerbig = FontFactory.getFont(FontFactory.TIMES_ROMAN, 16, Font.BOLD);
    Font header = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.BOLD);

    //pieds de pages:
    String part = "";
    Date d = new Date();
    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    String date = dateFormat.format(d);
    //alignement des libells du pied de page:
    String partie1 = libelle + " " + annee;
    String partie2 = applicationContext.getMessage("pdf.edition.date", null, Locale.getDefault()) + " : "
            + date;
    if (partie1.length() < ECARTEMENT_PIED_PAGE_PDF) {
        int diff = ECARTEMENT_PIED_PAGE_PDF - partie1.length();
        for (int i = 0; i < diff; i++) {
            partie1 = partie1 + " ";

        }
    }
    if (partie2.length() < ECARTEMENT_PIED_PAGE_PDF) {
        int diff = ECARTEMENT_PIED_PAGE_PDF - partie2.length();
        for (int i = 0; i < diff; i++) {
            partie2 = " " + partie2;
        }
    }

    //cration du pied de page:
    Phrase phra = new Phrase(partie1 + "-" + part + " Page", legerita);
    Phrase phra2 = new Phrase("- " + partie2, legerita);
    HeaderFooter hf = new HeaderFooter(phra, phra2);
    hf.setAlignment(HeaderFooter.ALIGN_CENTER);
    document.setFooter(hf);

    //ouverte du document.
    document.open();

    try {

        //ajout image test
        if (configController.getLogoUniversitePdf() != null
                && !configController.getLogoUniversitePdf().equals("")) {
            Image image1 = Image.getInstance(configController.getLogoUniversitePdf());
            float scaleRatio = 40 / image1.getHeight();
            float newWidth = scaleRatio * image1.getWidth();
            image1.scaleAbsolute(newWidth, 40);
            image1.setAbsolutePosition(800 - newWidth, 528);
            document.add(image1);
        }

        Paragraph p = new Paragraph(applicationContext
                .getMessage("pdf.trombinoscope.title", null, Locale.getDefault()).toUpperCase(), headerbig);
        p.setIndentationLeft(15);
        document.add(p);

        Paragraph p3 = new Paragraph(
                applicationContext.getMessage("pdf.promotion", null, Locale.getDefault()) + " : " + libelle,
                normal);
        p3.setIndentationLeft(15);
        document.add(p3);

        Paragraph p2 = new Paragraph(
                applicationContext.getMessage("pdf.year", null, Locale.getDefault()) + " : " + annee, normal);
        p2.setIndentationLeft(15);
        document.add(p2);

        Paragraph p4 = new Paragraph(applicationContext.getMessage("pdf.nbinscrits", null, Locale.getDefault())
                + " : " + listecodind.size(), normal);
        p4.setIndentationLeft(15);
        document.add(p4);

        Paragraph p03 = new Paragraph(
                applicationContext.getMessage("pdf.edition.date", null, Locale.getDefault()) + " : " + date
                        + "\n\n",
                normal);
        p03.setIndentationLeft(15);
        document.add(p03);

        PdfPTable table = new PdfPTable(NB_INSCRITS_LIGNE_TROMBI_PDF);
        table.setWidthPercentage(100f);

        int compteur = 0;
        Rectangle border = new Rectangle(0f, 0f);
        border.setBorderColorLeft(Color.WHITE);
        border.setBorderColorBottom(Color.WHITE);
        border.setBorderColorRight(Color.WHITE);
        border.setBorderColorTop(Color.WHITE);

        String tabNom[] = new String[NB_INSCRITS_LIGNE_TROMBI_PDF];
        String tabNum[] = new String[NB_INSCRITS_LIGNE_TROMBI_PDF];
        //insertion de listeInscrits dans listeInscritstrombi si le trombinoscope n'est pas decoup
        /*   if (listeInscritsTrombi == null || listeInscritsTrombi.size() == 0) {
           ArrayList<Inscrit> listeInscritsbis = (ArrayList<Inscrit>) listeInscrits.clone();
           listeInscritsTrombi.add(listeInscritsbis);
        }*/
        //nombre d'etudiants insrer a la suite dans le pdf:
        int nbEtudiantInsere = 0;
        for (Inscrit inscrit : listeInscrits) {
            if (listecodind.contains(inscrit.getCod_ind())) {
                nbEtudiantInsere++;
                //on en a insr le plus possible d'un coup (pour eviter un timeout du server 
                //de photos sur les premieres photos 
                //au moment de l'insertion dans le pdf : document.add() ):
                //on insere la table dans le pdf et on recommence une nouvelle table
                if (nbEtudiantInsere > (NB_INSCRITS_LIGNE_TROMBI_PDF
                        * NB_LIGNE_INSEREE_TROMBI_PDF_A_LA_SUITE)) {
                    document.add(table);
                    document.newPage();
                    table = new PdfPTable(NB_INSCRITS_LIGNE_TROMBI_PDF);
                    table.setWidthPercentage(100f);
                    tabNom = new String[NB_INSCRITS_LIGNE_TROMBI_PDF];
                    tabNum = new String[NB_INSCRITS_LIGNE_TROMBI_PDF];
                    nbEtudiantInsere = 1;
                    compteur = 0;
                }

                tabNom[compteur] = "" + inscrit.getPrenom() + " \n" + inscrit.getNom() + "\n";
                tabNum[compteur] = "" + inscrit.getCod_etu();

                compteur++;

                //String foto = photo.getUrlPhotoTrombinoscopePdf(inscrit.getCod_ind(), inscrit.getCod_etu());
                String foto = GenericUI.getCurrent().getPhotoProvider().getUrlPhotoTrombinoscopePdf(
                        inscrit.getCod_ind(), inscrit.getCod_etu(), userController.isEnseignant(),
                        userController.getCurrentUserName());
                Image photo = Image.getInstance(foto);
                photo.scaleAbsolute(85, 107);

                PdfPCell cell = new PdfPCell(photo);
                cell.cloneNonPositionParameters(border);
                table.addCell(cell);

                if (compteur == NB_INSCRITS_LIGNE_TROMBI_PDF) {
                    for (int i = 0; i < NB_INSCRITS_LIGNE_TROMBI_PDF; i++) {
                        Phrase ph = new Phrase(tabNom[i], normalbig);
                        Phrase ph2 = new Phrase(tabNum[i], leger);
                        Paragraph pinscrit = new Paragraph();
                        pinscrit.add(ph);
                        pinscrit.add(ph2);
                        PdfPCell celltext = new PdfPCell(pinscrit);
                        celltext.cloneNonPositionParameters(border);
                        table.addCell(celltext);
                    }
                    compteur = 0;
                }

            }

        }
        if (compteur > 0) {
            for (int i = compteur; i < NB_INSCRITS_LIGNE_TROMBI_PDF; i++) {
                PdfPCell cell = new PdfPCell();
                cell.cloneNonPositionParameters(border);
                table.addCell(cell);
            }

            for (int i = 0; i < compteur; i++) {
                Phrase ph = new Phrase(tabNom[i], normalbig);
                Phrase ph2 = new Phrase(tabNum[i], leger);
                Paragraph pinscrit = new Paragraph();
                pinscrit.add(ph);
                pinscrit.add(ph2);
                PdfPCell celltext = new PdfPCell(pinscrit);
                celltext.cloneNonPositionParameters(border);
                table.addCell(celltext);
            }

            for (int i = compteur; i < NB_INSCRITS_LIGNE_TROMBI_PDF; i++) {
                PdfPCell cell = new PdfPCell();
                cell.cloneNonPositionParameters(border);
                table.addCell(cell);
            }

        }

        document.add(table);

    } catch (BadElementException e) {
        LOG.error("Erreur  la gnration du certificat : BadElementException ", e);
    } catch (MalformedURLException e) {
        LOG.error("Erreur  la gnration du certificat : MalformedURLException ", e);
    } catch (IOException e) {
        LOG.error("Erreur  la gnration du certificat : IOException ", e);
    } catch (DocumentException e) {
        LOG.error("Erreur  la gnration du certificat : DocumentException ", e);
    }

    // step 6: fermeture du document.
    document.close();

}

From source file:fr.univlorraine.mondossierweb.controllers.NoteController.java

License:Apache License

/**
 * /*w  ww  .j  a va  2 s  .  c o m*/
 * @param document pdf
 */
public void creerPdfResume(final Document document, Etudiant etudiant) {

    //configuration des fonts
    Font normal = FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, Font.NORMAL);
    Font normalbig = FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.BOLD);
    Font legerita = FontFactory.getFont(FontFactory.TIMES_ROMAN, 9, Font.ITALIC);
    Font headerbig = FontFactory.getFont(FontFactory.TIMES_ROMAN, 16, Font.BOLD);
    Font header = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.BOLD);

    //pieds de pages:
    Date d = new Date();
    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    String date = dateFormat.format(d);
    //alignement des libell du pied de page:
    String partie1 = applicationContext.getMessage("pdf.notes.title", null, Locale.getDefault());
    String partie2 = applicationContext.getMessage("pdf.edition.date", null, Locale.getDefault()) + " : "
            + date;
    if (partie1.length() < ECARTEMENT_PIED_PAGE_PDF) {
        int diff = ECARTEMENT_PIED_PAGE_PDF - partie1.length();
        for (int i = 0; i < diff; i++) {
            partie1 = partie1 + " ";

        }
    }
    if (partie2.length() < ECARTEMENT_PIED_PAGE_PDF) {
        int diff = ECARTEMENT_PIED_PAGE_PDF - partie2.length();
        for (int i = 0; i < diff; i++) {
            partie2 = " " + partie2;
        }
    }

    //creation du pied de page:
    Phrase phra = new Phrase(
            partie1 + " -" + applicationContext.getMessage("pdf.page", null, Locale.getDefault()), legerita);
    Phrase phra2 = new Phrase("- " + partie2, legerita);
    HeaderFooter hf = new HeaderFooter(phra, phra2);
    hf.setAlignment(HeaderFooter.ALIGN_CENTER);
    document.setFooter(hf);

    //ouverte du document.
    document.open();
    try {
        //ajout image test
        if (configController.getLogoUniversitePdf() != null
                && !configController.getLogoUniversitePdf().equals("")) {
            Image image1 = Image.getInstance(configController.getLogoUniversitePdf());
            float scaleRatio = 40 / image1.getHeight();
            float newWidth = scaleRatio * image1.getWidth();
            image1.scaleAbsolute(newWidth, 40);
            image1.setAbsolutePosition(800 - newWidth, 528);
            document.add(image1);
        }

        boolean affMentionEtudiant = configController.isAffMentionEtudiant();

        //nouveau paragraphe
        Paragraph p = new Paragraph(applicationContext.getMessage("pdf.notes.title", null, Locale.getDefault())
                .toUpperCase(Locale.getDefault()) + "\n\n", headerbig);
        p.setIndentationLeft(15);
        document.add(p);

        if (etudiant.getNom() != null) {
            Paragraph p0 = new Paragraph(etudiant.getNom(), normal);
            p0.setIndentationLeft(15);
            document.add(p0);
        }
        if (etudiant.getCod_etu() != null) {
            Paragraph p01 = new Paragraph(applicationContext.getMessage("pdf.folder", null, Locale.getDefault())
                    + " : " + etudiant.getCod_etu(), normal);
            p01.setIndentationLeft(15);
            document.add(p01);
        }
        if (etudiant.getCod_nne() != null) {
            Paragraph p02 = new Paragraph(applicationContext.getMessage("pdf.nne", null, Locale.getDefault())
                    + " : " + etudiant.getCod_nne(), normal);
            p02.setIndentationLeft(15);
            document.add(p02);
        }
        if (etudiant.getEmail() != null) {
            Paragraph p03 = new Paragraph(applicationContext.getMessage("pdf.mail", null, Locale.getDefault())
                    + " : " + etudiant.getEmail(), normal);
            p03.setIndentationLeft(15);
            document.add(p03);
        }

        Paragraph p03 = new Paragraph(
                applicationContext.getMessage("pdf.edition.date", null, Locale.getDefault()) + " : " + date,
                normal);
        p03.setIndentationLeft(15);
        document.add(p03);
        document.add(new Paragraph("\n"));

        //Partie DIPLOMES
        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(98);
        PdfPCell cell = new PdfPCell(
                new Paragraph(applicationContext.getMessage("pdf.diplomes", null, Locale.getDefault())
                        .toUpperCase(Locale.getDefault()) + " ", header));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setBackgroundColor(new Color(153, 153, 255));
        table.addCell(cell);

        PdfPTable table2;

        //if(!config.isAffRangEtudiant()){
        if (!etudiant.isAfficherRang()) {
            table2 = new PdfPTable(4);
        } else {
            table2 = new PdfPTable(5);
        }

        table2.setWidthPercentage(98);

        int tailleColonneLib = 110;
        if (affMentionEtudiant)
            tailleColonneLib = 90;

        //if(!config.isAffRangEtudiant()){
        if (!etudiant.isAfficherRang()) {
            int[] tabWidth = { 26, 35, tailleColonneLib, 70 };
            table2.setWidths(tabWidth);
        } else {
            int[] tabWidth = { 26, 35, tailleColonneLib - 5, 70, 15 };
            table2.setWidths(tabWidth);
        }

        Paragraph p1 = new Paragraph(applicationContext.getMessage("pdf.year", null, Locale.getDefault()),
                normalbig);
        Paragraph p2 = new Paragraph(applicationContext.getMessage("pdf.code.vers", null, Locale.getDefault()),
                normalbig);
        Paragraph p3 = new Paragraph(applicationContext.getMessage("pdf.diplome", null, Locale.getDefault()),
                normalbig);

        PdfPCell ct1 = new PdfPCell(p1);
        PdfPCell ct2 = new PdfPCell(p2);
        PdfPCell ct3 = new PdfPCell(p3);

        ct1.setBorder(Rectangle.BOTTOM);
        ct1.setBorderColorBottom(Color.black);
        ct2.setBorder(Rectangle.BOTTOM);
        ct2.setBorderColorBottom(Color.black);
        ct3.setBorder(Rectangle.BOTTOM);
        ct3.setBorderColorBottom(Color.black);

        table2.addCell(ct1);
        table2.addCell(ct2);
        table2.addCell(ct3);

        PdfPTable table21;
        if (!affMentionEtudiant) {
            table21 = new PdfPTable(3);
            int[] tabWidth21 = { 25, 20, 25 };
            table21.setWidths(tabWidth21);
        } else {
            table21 = new PdfPTable(4);
            int[] tabWidth21 = { 25, 20, 25, 20 };
            table21.setWidths(tabWidth21);
        }

        PdfPCell ct4 = new PdfPCell(new Paragraph(
                applicationContext.getMessage("pdf.session", null, Locale.getDefault()), normalbig));
        PdfPCell ct5 = new PdfPCell(
                new Paragraph(applicationContext.getMessage("pdf.note", null, Locale.getDefault()), normalbig));
        PdfPCell ct6 = new PdfPCell(new Paragraph(
                applicationContext.getMessage("pdf.resultat", null, Locale.getDefault()), normalbig));
        PdfPCell ctmention = new PdfPCell(new Paragraph(
                applicationContext.getMessage("pdf.mention", null, Locale.getDefault()), normalbig));

        ct4.setBorder(Rectangle.BOTTOM);
        ct4.setBorderColorBottom(Color.black);
        ct5.setBorder(Rectangle.BOTTOM);
        ct5.setBorderColorBottom(Color.black);
        ct6.setBorder(Rectangle.BOTTOM);
        ct6.setBorderColorBottom(Color.black);
        ctmention.setBorder(Rectangle.BOTTOM);
        ctmention.setBorderColorBottom(Color.black);

        table21.addCell(ct4);
        table21.addCell(ct5);
        table21.addCell(ct6);
        if (affMentionEtudiant) {
            table21.addCell(ctmention);
        }

        PdfPCell ct7 = new PdfPCell(table21);
        ct7.setBorder(Rectangle.BOTTOM);
        table2.addCell(ct7);

        PdfPCell ctrang = new PdfPCell(
                new Paragraph(applicationContext.getMessage("pdf.rank", null, Locale.getDefault()), normalbig));
        ctrang.setBorder(Rectangle.BOTTOM);
        ctrang.setBorderColorBottom(Color.black);

        //if(config.isAffRangEtudiant()){
        if (etudiant.isAfficherRang()) {
            table2.addCell(ctrang);
        }

        for (int i = 0; i < etudiant.getDiplomes().size(); i++) {
            Paragraph pa = new Paragraph(etudiant.getDiplomes().get(i).getAnnee(), normal);
            PdfPCell celltext = new PdfPCell(pa);
            celltext.setBorder(Rectangle.NO_BORDER);

            Paragraph pa2 = new Paragraph(etudiant.getDiplomes().get(i).getCod_dip() + "/"
                    + etudiant.getDiplomes().get(i).getCod_vrs_vdi(), normal);
            PdfPCell celltext2 = new PdfPCell(pa2);
            celltext2.setBorder(Rectangle.NO_BORDER);

            Paragraph pa3 = new Paragraph(etudiant.getDiplomes().get(i).getLib_web_vdi(), normal);
            PdfPCell celltext3 = new PdfPCell(pa3);
            celltext3.setBorder(Rectangle.NO_BORDER);

            Paragraph parang = new Paragraph(etudiant.getDiplomes().get(i).getRang(), normal);
            PdfPCell cellrang = new PdfPCell(parang);
            cellrang.setBorder(Rectangle.NO_BORDER);

            PdfPCell cellvide = new PdfPCell();
            cellvide.setBorder(Rectangle.NO_BORDER);

            table2.addCell(celltext);
            table2.addCell(celltext2);
            table2.addCell(celltext3);

            PdfPTable table3;
            if (!affMentionEtudiant) {
                table3 = new PdfPTable(3);
                int[] tabWidth2 = { 25, 20, 25 };
                table3.setWidths(tabWidth2);
            } else {
                table3 = new PdfPTable(4);
                int[] tabWidth2 = { 25, 20, 25, 8 };
                table3.setWidths(tabWidth2);
            }

            int j = 0;
            List<Resultat> lres = etudiant.getDiplomes().get(i).getResultats();
            while (j < lres.size()) {

                Paragraph pa5 = new Paragraph(lres.get(j).getSession(), normal);
                PdfPCell celltext5 = new PdfPCell(pa5);
                celltext5.setBorder(Rectangle.NO_BORDER);
                table3.addCell(celltext5);

                if (lres.get(j).getNote() != null) {
                    Paragraph pa6 = new Paragraph(lres.get(j).getNote().toString(), normal);
                    PdfPCell celltext6 = new PdfPCell(pa6);
                    celltext6.setBorder(Rectangle.NO_BORDER);
                    table3.addCell(celltext6);
                } else {
                    Paragraph pa6 = new Paragraph("", normal);
                    PdfPCell celltext6 = new PdfPCell(pa6);
                    celltext6.setBorder(Rectangle.NO_BORDER);
                    table3.addCell(celltext6);
                }

                Paragraph pa7 = new Paragraph(lres.get(j).getAdmission(), normal);
                PdfPCell celltext7 = new PdfPCell(pa7);
                celltext7.setBorder(Rectangle.NO_BORDER);
                table3.addCell(celltext7);

                if (affMentionEtudiant) {
                    Paragraph pa8 = new Paragraph(lres.get(j).getCodMention(), normal);
                    PdfPCell celltext8 = new PdfPCell(pa8);
                    celltext8.setBorder(Rectangle.NO_BORDER);
                    table3.addCell(celltext8);
                }

                j++;
            }

            PdfPCell celltext4 = new PdfPCell(table3);
            celltext4.setBorder(Rectangle.NO_BORDER);
            table2.addCell(celltext4);

            //if(config.isAffRangEtudiant()){
            if (etudiant.getDiplomes().get(i).isAfficherRang()) {
                table2.addCell(cellrang);
            } else {
                //On insere une cellule vide si on affiche pas ce rang, alors que la colonne rang fait partie de la table
                if (etudiant.isAfficherRang()) {
                    table2.addCell(cellvide);
                }
            }

        }

        document.add(table);
        document.add(table2);
        document.add(new Paragraph("\n"));

        //Partie ETAPES
        PdfPTable tabletape = new PdfPTable(1);
        tabletape.setWidthPercentage(98);
        PdfPCell celletape = new PdfPCell(new Paragraph(applicationContext
                .getMessage("pdf.etapes", null, Locale.getDefault()).toUpperCase(Locale.getDefault()), header));
        celletape.setBorder(Rectangle.NO_BORDER);
        celletape.setBackgroundColor(new Color(153, 153, 255));
        tabletape.addCell(celletape);

        PdfPTable tabletape2;

        //if(!config.isAffRangEtudiant()){
        if (!etudiant.isAfficherRang()) {
            tabletape2 = new PdfPTable(4);
            tabletape2.setWidthPercentage(98);
            int[] tabWidthetape = { 26, 35, tailleColonneLib, 70 };
            tabletape2.setWidths(tabWidthetape);
        } else {
            tabletape2 = new PdfPTable(5);
            tabletape2.setWidthPercentage(98);
            int[] tabWidthetape = { 26, 35, tailleColonneLib - 5, 70, 15 };
            tabletape2.setWidths(tabWidthetape);
        }

        PdfPCell ct3etape = new PdfPCell(new Paragraph(
                applicationContext.getMessage("pdf.etape", null, Locale.getDefault()), normalbig));
        ct3etape.setBorder(Rectangle.BOTTOM);
        ct3etape.setBorderColorBottom(Color.black);

        tabletape2.addCell(ct1);
        tabletape2.addCell(ct2);
        tabletape2.addCell(ct3etape);

        tabletape2.addCell(ct7);

        //if(!config.isAffRangEtudiant()){
        if (etudiant.isAfficherRang()) {
            tabletape2.addCell(ctrang);
        }

        for (int i = 0; i < etudiant.getEtapes().size(); i++) {
            Paragraph pa = new Paragraph(etudiant.getEtapes().get(i).getAnnee(), normal);
            PdfPCell celltext = new PdfPCell(pa);
            celltext.setBorder(Rectangle.NO_BORDER);
            tabletape2.addCell(celltext);

            Paragraph pa2 = new Paragraph(
                    etudiant.getEtapes().get(i).getCode() + "/" + etudiant.getEtapes().get(i).getVersion(),
                    normal);
            PdfPCell celltext2 = new PdfPCell(pa2);
            celltext2.setBorder(Rectangle.NO_BORDER);
            tabletape2.addCell(celltext2);

            Paragraph pa3 = new Paragraph(etudiant.getEtapes().get(i).getLibelle(), normal);
            PdfPCell celltext3 = new PdfPCell(pa3);
            celltext3.setBorder(Rectangle.NO_BORDER);
            tabletape2.addCell(celltext3);

            Paragraph parEtapeRang = new Paragraph(etudiant.getEtapes().get(i).getRang(), normal);
            PdfPCell cellEtapeRang = new PdfPCell(parEtapeRang);
            cellEtapeRang.setBorder(Rectangle.NO_BORDER);

            PdfPCell cellvide = new PdfPCell();
            cellvide.setBorder(Rectangle.NO_BORDER);

            PdfPTable table3;

            if (!affMentionEtudiant) {
                table3 = new PdfPTable(3);
                int[] tabWidth2 = { 25, 20, 25 };
                table3.setWidths(tabWidth2);
            } else {
                table3 = new PdfPTable(4);
                int[] tabWidth2 = { 25, 20, 25, 8 };
                table3.setWidths(tabWidth2);
            }

            int j = 0;
            List<Resultat> lres = etudiant.getEtapes().get(i).getResultats();
            while (j < lres.size()) {

                Paragraph pa5 = new Paragraph(lres.get(j).getSession(), normal);
                PdfPCell celltext5 = new PdfPCell(pa5);
                celltext5.setBorder(Rectangle.NO_BORDER);
                table3.addCell(celltext5);

                if (lres.get(j).getNote() != null) {
                    Paragraph pa6 = new Paragraph(lres.get(j).getNote().toString(), normal);
                    PdfPCell celltext6 = new PdfPCell(pa6);
                    celltext6.setBorder(Rectangle.NO_BORDER);
                    table3.addCell(celltext6);
                } else {
                    Paragraph pa6 = new Paragraph("", normal);
                    PdfPCell celltext6 = new PdfPCell(pa6);
                    celltext6.setBorder(Rectangle.NO_BORDER);
                    table3.addCell(celltext6);
                }

                Paragraph pa7 = new Paragraph(lres.get(j).getAdmission(), normal);
                PdfPCell celltext7 = new PdfPCell(pa7);
                celltext7.setBorder(Rectangle.NO_BORDER);
                table3.addCell(celltext7);

                if (affMentionEtudiant) {
                    Paragraph pa8 = new Paragraph(lres.get(j).getCodMention(), normal);
                    PdfPCell celltext8 = new PdfPCell(pa8);
                    celltext8.setBorder(Rectangle.NO_BORDER);
                    table3.addCell(celltext8);
                }

                j++;
            }
            PdfPCell celltext4 = new PdfPCell(table3);
            celltext4.setBorder(Rectangle.NO_BORDER);
            tabletape2.addCell(celltext4);

            //if(config.isAffRangEtudiant()){
            if (etudiant.getEtapes().get(i).isAfficherRang()) {
                tabletape2.addCell(cellEtapeRang);
            } else {
                if (etudiant.isAfficherRang()) {
                    tabletape2.addCell(cellvide);
                }
            }

        }

        document.add(tabletape);
        document.add(tabletape2);
        document.add(new Paragraph("\n"));

        //Partie Informations
        if (etudiant.isSignificationResultatsUtilisee()) {
            PdfPTable tablequestions = new PdfPTable(1);
            tablequestions.setWidthPercentage(98);
            PdfPCell cellquestions = new PdfPCell(new Paragraph(
                    applicationContext.getMessage("pdf.questions", null, Locale.getDefault()) + " ", header));
            cellquestions.setBorder(Rectangle.NO_BORDER);
            cellquestions.setBackgroundColor(new Color(153, 153, 255));
            tablequestions.addCell(cellquestions);

            String grilleSignficationResultats = "";
            Set<String> ss = etudiant.getSignificationResultats().keySet();
            for (String k : ss) {
                if (k != null && !k.equals("") && !k.equals(" ")) {
                    grilleSignficationResultats = grilleSignficationResultats + k + " : "
                            + etudiant.getSignificationResultats().get(k);
                    grilleSignficationResultats = grilleSignficationResultats + "   ";
                }
            }

            PdfPTable tablequestions2 = new PdfPTable(1);
            tablequestions2.setWidthPercentage(98);
            PdfPCell cellquestions2 = new PdfPCell(new Paragraph(
                    applicationContext.getMessage("pdf.code.resultat.signification", null, Locale.getDefault())
                            + " : \n" + grilleSignficationResultats,
                    normal));
            cellquestions2.setBorder(Rectangle.NO_BORDER);
            tablequestions2.addCell(cellquestions2);

            document.add(tablequestions);
            document.add(tablequestions2);
        }

    } catch (BadElementException e) {
        LOG.error("Erreur  la gnration du rsum des notes : BadElementException ", e);
    } catch (MalformedURLException e) {
        LOG.error("Erreur  la gnration du rsum des notes : MalformedURLException ", e);
    } catch (IOException e) {
        LOG.error("Erreur  la gnration du rsum des notes : IOException ", e);
    } catch (DocumentException e) {
        LOG.error("Erreur  la gnration du rsum des notes : DocumentException ", e);
    }
    // step 6: fermeture du document.
    document.close();

}

From source file:fr.univlorraine.mondossierweb.controllers.NoteController.java

License:Apache License

/**
 * /*  w w w. j av  a 2  s. c  o  m*/
 * @param document pdf
 */
public void creerPdfDetail(final Document document, Etudiant etudiant, Etape etape) {

    //configuration des fonts
    Font normal = FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, Font.NORMAL);
    Font normalbig = FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.BOLD);
    Font legerita = FontFactory.getFont(FontFactory.TIMES_ROMAN, 9, Font.ITALIC);
    Font headerbig = FontFactory.getFont(FontFactory.TIMES_ROMAN, 16, Font.BOLD);
    Font header = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.BOLD);

    //pieds de pages:
    Date d = new Date();
    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    String date = dateFormat.format(d);
    //alignement des libells du pied de page:
    String partie1 = applicationContext.getMessage("pdf.notes.detail", null, Locale.getDefault());
    String partie2 = applicationContext.getMessage("pdf.edition.date", null, Locale.getDefault()) + " : "
            + date;
    if (partie1.length() < ECARTEMENT_PIED_PAGE_PDF) {
        int diff = ECARTEMENT_PIED_PAGE_PDF - partie1.length();
        for (int i = 0; i < diff; i++) {
            partie1 = partie1 + " ";

        }
    }
    if (partie2.length() < ECARTEMENT_PIED_PAGE_PDF) {
        int diff = ECARTEMENT_PIED_PAGE_PDF - partie2.length();
        for (int i = 0; i < diff; i++) {
            partie2 = " " + partie2;
        }
    }

    //creation du pied de page:
    Phrase phra = new Phrase(
            partie1 + " -" + applicationContext.getMessage("pdf.page", null, Locale.getDefault()), legerita);
    Phrase phra2 = new Phrase("- " + partie2, legerita);
    HeaderFooter hf = new HeaderFooter(phra, phra2);
    hf.setAlignment(HeaderFooter.ALIGN_CENTER);
    document.setFooter(hf);
    document.setFooter(hf);

    //ouverte du document.
    document.open();
    try {
        //ajout image test
        if (configController.getLogoUniversitePdf() != null
                && !configController.getLogoUniversitePdf().equals("")) {
            Image image1 = Image.getInstance(configController.getLogoUniversitePdf());
            float scaleRatio = 40 / image1.getHeight();
            float newWidth = scaleRatio * image1.getWidth();
            image1.scaleAbsolute(newWidth, 40);
            image1.setAbsolutePosition(800 - newWidth, 528);
            document.add(image1);
        }

        //nouveau paragraphe
        Paragraph p = new Paragraph(applicationContext.getMessage("pdf.notes.title", null, Locale.getDefault())
                .toUpperCase(Locale.getDefault()) + "\n\n", headerbig);
        p.setIndentationLeft(15);
        document.add(p);

        if (etudiant.getNom() != null) {
            Paragraph p0 = new Paragraph(etudiant.getNom(), normal);
            p0.setIndentationLeft(15);
            document.add(p0);
        }
        if (etudiant.getCod_etu() != null) {
            Paragraph p01 = new Paragraph(applicationContext.getMessage("pdf.folder", null, Locale.getDefault())
                    + " : " + etudiant.getCod_etu(), normal);
            p01.setIndentationLeft(15);
            document.add(p01);
        }
        if (etudiant.getCod_nne() != null) {
            Paragraph p02 = new Paragraph(applicationContext.getMessage("pdf.nne", null, Locale.getDefault())
                    + " : " + etudiant.getCod_nne(), normal);
            p02.setIndentationLeft(15);
            document.add(p02);
        }
        if (etudiant.getEmail() != null) {
            Paragraph p03 = new Paragraph(applicationContext.getMessage("pdf.mail", null, Locale.getDefault())
                    + " : " + etudiant.getEmail(), normal);
            p03.setIndentationLeft(15);
            document.add(p03);
        }

        Paragraph p03 = new Paragraph(
                applicationContext.getMessage("pdf.edition.date", null, Locale.getDefault()) + " : " + date,
                normal);
        p03.setIndentationLeft(15);
        document.add(p03);
        document.add(new Paragraph("\n"));

        //Partie des notes
        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(98);
        //PdfPCell cell = new PdfPCell(new Paragraph(applicationContext.getMessage("pdf.elements.epreuves", null, Locale.getDefault()).toUpperCase(Locale.getDefault()) + " - "+applicationContext.getMessage("pdf.annee.universitaire", null, Locale.getDefault()) + " : " + etape.getAnnee(), header));
        PdfPCell cell = new PdfPCell(new Paragraph(etape.getLibelle() + " - "
                + applicationContext.getMessage("pdf.annee.universitaire", null, Locale.getDefault()) + " : "
                + etape.getAnnee(), header));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setBackgroundColor(new Color(153, 153, 255));
        table.addCell(cell);

        PdfPTable table2;

        boolean afficherRangElpEpr = etudiantController.isAfficherRangElpEpr();
        boolean affRangEtudiant = configController.isAffRangEtudiant();
        boolean affECTSEtudiant = configController.isAffECTSEtudiant();

        if ((!affRangEtudiant && !afficherRangElpEpr) && !affECTSEtudiant) {
            //NI isAffRangEtudiant  NI isAffECTSEtudiant
            table2 = new PdfPTable(6);
            table2.setWidthPercentage(98);
            int[] tabWidth = { 35, 110, 25, 25, 25, 25 };
            table2.setWidths(tabWidth);
        } else {
            if (((affRangEtudiant || afficherRangElpEpr) && !affECTSEtudiant)
                    || ((!affRangEtudiant && !afficherRangElpEpr) && affECTSEtudiant)) {
                //isAffRangEtudiant  OU isAffECTSEtudiant
                table2 = new PdfPTable(7);
                table2.setWidthPercentage(98);
                int[] tabWidth = { 33, 110, 22, 22, 22, 22, 15 };
                table2.setWidths(tabWidth);
            } else {
                //isAffRangEtudiant  ET isAffECTSEtudiant
                table2 = new PdfPTable(8);
                table2.setWidthPercentage(98);
                int[] tabWidth = { 33, 110, 22, 22, 22, 22, 15, 15 };
                table2.setWidths(tabWidth);
            }
        }

        //Paragraph p1 = new Paragraph(applicationContext.getMessage("pdf.year", null, Locale.getDefault()),normalbig);
        Paragraph p2 = new Paragraph(applicationContext.getMessage("pdf.code", null, Locale.getDefault()),
                normalbig);
        Paragraph p3 = new Paragraph(applicationContext.getMessage("pdf.label", null, Locale.getDefault()),
                normalbig);
        Paragraph parRang = new Paragraph(applicationContext.getMessage("pdf.rank", null, Locale.getDefault()),
                normalbig);
        Paragraph parEcts = new Paragraph(applicationContext.getMessage("pdf.ects", null, Locale.getDefault()),
                normalbig);

        PdfPCell ct4 = new PdfPCell(new Paragraph(
                applicationContext.getMessage("pdf.session", null, Locale.getDefault()) + " 1", normalbig));
        PdfPCell ct5 = new PdfPCell(new Paragraph(
                applicationContext.getMessage("pdf.resultat", null, Locale.getDefault()), normalbig));
        PdfPCell ct6 = new PdfPCell(new Paragraph(
                applicationContext.getMessage("pdf.session", null, Locale.getDefault()) + " 2", normalbig));
        PdfPCell ct7 = new PdfPCell(new Paragraph(
                applicationContext.getMessage("pdf.resultat", null, Locale.getDefault()), normalbig));

        //PdfPCell ct1 = new PdfPCell(p1);
        PdfPCell ct2 = new PdfPCell(p2);
        PdfPCell ct3 = new PdfPCell(p3);
        PdfPCell cellRang = new PdfPCell(parRang);
        PdfPCell cellEcts = new PdfPCell(parEcts);

        //ct1.setBorder(Rectangle.BOTTOM); ct1.setBorderColorBottom(Color.black);
        ct2.setBorder(Rectangle.BOTTOM);
        ct2.setBorderColorBottom(Color.black);
        ct3.setBorder(Rectangle.BOTTOM);
        ct3.setBorderColorBottom(Color.black);
        ct4.setBorder(Rectangle.BOTTOM);
        ct4.setBorderColorBottom(Color.black);
        ct5.setBorder(Rectangle.BOTTOM);
        ct5.setBorderColorBottom(Color.black);
        ct6.setBorder(Rectangle.BOTTOM);
        ct6.setBorderColorBottom(Color.black);
        ct7.setBorder(Rectangle.BOTTOM);
        ct7.setBorderColorBottom(Color.black);
        cellRang.setBorder(Rectangle.BOTTOM);
        cellRang.setBorderColorBottom(Color.black);
        cellEcts.setBorder(Rectangle.BOTTOM);
        cellEcts.setBorderColorBottom(Color.black);

        //table2.addCell(ct1);
        table2.addCell(ct2);
        table2.addCell(ct3);
        table2.addCell(ct4);
        table2.addCell(ct5);
        table2.addCell(ct6);
        table2.addCell(ct7);
        if ((affRangEtudiant || afficherRangElpEpr)) {
            table2.addCell(cellRang);
        }
        if (affRangEtudiant) {
            table2.addCell(cellEcts);
        }

        for (int i = 0; i < etudiant.getElementsPedagogiques().size(); i++) {
            /*String annee = etudiant.getElementsPedagogiques().get(i).getAnnee().replaceAll(applicationContext.getMessage("pdf.replace.ficm", null, Locale.getDefault()), "");
            Paragraph pa = new Paragraph(annee, normal);
            PdfPCell celltext = new PdfPCell(pa);
            celltext.setBorder(Rectangle.NO_BORDER);
            table2.addCell(celltext);*/

            Paragraph pa2 = new Paragraph(etudiant.getElementsPedagogiques().get(i).getCode(), normal);
            PdfPCell celltext2 = new PdfPCell(pa2);
            celltext2.setBorder(Rectangle.NO_BORDER);
            table2.addCell(celltext2);

            String indentation = "";
            for (int j = 0; j < etudiant.getElementsPedagogiques().get(i).getLevel(); j++) {
                indentation = indentation + "     ";
            }
            Paragraph pa3 = new Paragraph(indentation + etudiant.getElementsPedagogiques().get(i).getLibelle(),
                    normal);
            PdfPCell celltext3 = new PdfPCell(pa3);
            celltext3.setBorder(Rectangle.NO_BORDER);
            table2.addCell(celltext3);

            Paragraph pa5 = new Paragraph(getNote1(etudiant.getElementsPedagogiques().get(i)), normal);
            PdfPCell celltext5 = new PdfPCell(pa5);
            celltext5.setBorder(Rectangle.NO_BORDER);
            table2.addCell(celltext5);

            Paragraph pa6 = new Paragraph(etudiant.getElementsPedagogiques().get(i).getRes1(), normal);
            PdfPCell celltext6 = new PdfPCell(pa6);
            celltext6.setBorder(Rectangle.NO_BORDER);
            table2.addCell(celltext6);

            Paragraph pa7 = new Paragraph(getNote2(etudiant.getElementsPedagogiques().get(i)), normal);
            PdfPCell celltext7 = new PdfPCell(pa7);
            celltext7.setBorder(Rectangle.NO_BORDER);
            table2.addCell(celltext7);

            Paragraph pa8 = new Paragraph(etudiant.getElementsPedagogiques().get(i).getRes2(), normal);
            PdfPCell celltext8 = new PdfPCell(pa8);
            celltext8.setBorder(Rectangle.NO_BORDER);
            table2.addCell(celltext8);

            if ((affRangEtudiant || afficherRangElpEpr)) {
                Paragraph parRang2 = new Paragraph(etudiant.getElementsPedagogiques().get(i).getRang(), normal);
                PdfPCell cellRang2 = new PdfPCell(parRang2);
                cellRang2.setBorder(Rectangle.NO_BORDER);
                table2.addCell(cellRang2);
            }

            if (affECTSEtudiant) {
                Paragraph parEcts2 = new Paragraph(etudiant.getElementsPedagogiques().get(i).getEcts(), normal);
                PdfPCell cellEcts2 = new PdfPCell(parEcts2);
                cellEcts2.setBorder(Rectangle.NO_BORDER);
                table2.addCell(cellEcts2);
            }

        }

        document.add(table);
        document.add(table2);
        document.add(new Paragraph("\n"));

        //Partie QUESTIONS
        if (etudiant.isSignificationResultatsUtilisee()) {
            PdfPTable tablequestions = new PdfPTable(1);
            tablequestions.setWidthPercentage(98);
            PdfPCell cellquestions = new PdfPCell(
                    new Paragraph(applicationContext.getMessage("pdf.questions", null, Locale.getDefault())
                            .toUpperCase(Locale.getDefault()) + " ", header));
            cellquestions.setBorder(Rectangle.NO_BORDER);
            cellquestions.setBackgroundColor(new Color(153, 153, 255));
            tablequestions.addCell(cellquestions);

            PdfPTable tablequestions2 = new PdfPTable(1);
            tablequestions2.setWidthPercentage(98);

            String grilleSignficationResultats = "";
            Set<String> ss = etudiant.getSignificationResultats().keySet();
            for (String k : ss) {
                if (k != null && !k.equals("") && !k.equals(" ")) {
                    grilleSignficationResultats = grilleSignficationResultats + k + " : "
                            + etudiant.getSignificationResultats().get(k);
                    grilleSignficationResultats = grilleSignficationResultats + "   ";
                }
            }

            PdfPCell cellquestions2 = new PdfPCell(new Paragraph(
                    applicationContext.getMessage("pdf.code.resultat.signification", null, Locale.getDefault())
                            + " : \n" + grilleSignficationResultats,
                    normal));
            cellquestions2.setBorder(Rectangle.NO_BORDER);
            tablequestions2.addCell(cellquestions2);

            document.add(tablequestions);
            document.add(tablequestions2);

        }

    } catch (BadElementException e) {
        LOG.error("Erreur  la gnration du detail des notes : BadElementException ", e);
    } catch (MalformedURLException e) {
        LOG.error("Erreur  la gnration du detail des notes : MalformedURLException ", e);
    } catch (IOException e) {
        LOG.error("Erreur  la gnration du detail des notes : IOException ", e);
    } catch (DocumentException e) {
        LOG.error("Erreur  la gnration du detail des notes : DocumentException ", e);
    }
    // step 6: fermeture du document.
    document.close();

}