Example usage for com.lowagie.text Rectangle Rectangle

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

Introduction

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

Prototype

public Rectangle(float urx, float ury) 

Source Link

Document

Constructs a Rectangle -object starting from the origin (0, 0).

Usage

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

License:Apache License

/**
 * /* w  ww  .  j  a  v a2 s. c om*/
 * @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:gestalt.util.pdfwriter.PDFWriter.java

License:Open Source License

public PDFWriter(String theFile, int theWidth, int theHeight) {
    _myFile = new File(theFile);
    _myDocument = new Document(new Rectangle(theWidth, theHeight));
    try {//from w ww. ja  va  2s. co m
        _myWriter = PdfWriter.getInstance(_myDocument, new FileOutputStream(_myFile));
        _myDocument.open();
        _myContent = _myWriter.getDirectContent();
        _myMapper = new DefaultFontMapper();
        _myGraphics = _myContent.createGraphics(theWidth, theHeight, _myMapper);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("### ERROR @ PDFWriter / problem saving the PDF file.");
    }

    /* plug default translators */
    _myTranslators = new Vector<DrawablePDFTranslator>();
    _myTranslators.add(new QuadLinePDFTranslator());
}

From source file:jdbreport.model.io.pdf.itext2.PdfWriter.java

License:Apache License

public void save(OutputStream out, ReportBook reportBook) throws SaveReportException {

    double oldScaleX = GraphicUtil.getScaleX();
    double oldScaleY = GraphicUtil.getScaleY();
    try {//from  w w  w.  j  ava 2  s .c  o  m
        GraphicUtil.setScaleX(1);
        GraphicUtil.setScaleY(1);

        ReportPage pageFormat;
        int i = 0;
        while (i < reportBook.size() - 1 && !reportBook.getReportModel(i).isVisible()) {
            i++;
        }

        pageFormat = reportBook.getReportModel(i).getReportPage();

        Paper paper = pageFormat.getPaper();
        Rectangle pageSize = new Rectangle(Math.round((float) paper.getWidth()),
                Math.round((float) paper.getHeight()));
        if (pageFormat.getOrientation() == ReportPage.LANDSCAPE) {
            pageSize = pageSize.rotate();
        }
        Document document = new Document(pageSize, Math.round((float) pageFormat.getLeftMargin(Units.PT)),
                Math.round((float) pageFormat.getRightMargin(Units.PT)),
                Math.round((float) pageFormat.getTopMargin(Units.PT)),
                Math.round((float) pageFormat.getBottomMargin(Units.PT)));
        try {
            com.lowagie.text.pdf.PdfWriter.getInstance(document, out);
            document.addTitle(reportBook.getReportCaption());
            document.addCreator("JDBReport using iText");
            document.addAuthor(System.getProperty("user.name"));
            document.open();
            int listCount = 0;
            try {
                for (ReportModel model : reportBook) {
                    if (model.isVisible()) {
                        listCount = saveSheet(document, listCount, model);
                    }
                }
                document.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (DocumentException e) {
            throw new SaveReportException(e);
        }
    } finally {
        GraphicUtil.setScaleX(oldScaleX);
        GraphicUtil.setScaleY(oldScaleY);
    }
}

From source file:jdbreport.model.io.pdf.itext2.PdfWriter.java

License:Apache License

private int saveSheet(Document document, int listCount, ReportModel model)
        throws DocumentException, IOException, SaveReportException {

    model.updatePages(0);// w w w  . j  a  va  2 s  .com

    ReportPage pageFormat = model.getReportPage();
    Paper paper = pageFormat.getPaper();
    Rectangle pageSize = new Rectangle(Math.round((float) paper.getWidth()),
            Math.round((float) paper.getHeight()));

    if (pageFormat.getOrientation() == ReportPage.LANDSCAPE) {
        pageSize = pageSize.rotate();
    }
    document.setPageSize(pageSize);
    document.setMargins(Math.round((float) pageFormat.getLeftMargin(Units.PT)),
            Math.round((float) pageFormat.getRightMargin(Units.PT)),
            Math.round((float) pageFormat.getTopMargin(Units.PT)),
            Math.round((float) pageFormat.getBottomMargin(Units.PT)));
    Rectangle viewPageSize = new Rectangle(
            document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin(),
            document.getPageSize().getHeight() - document.topMargin() - document.bottomMargin());

    if (listCount > 0) {
        document.newPage();
    }
    listCount++;

    //float columnMargin = (float) Units.PT.setXPixels(model.getColumnModel().getColumnMargin());

    ReportPrintable printable = new ReportPrintable(model);
    int pageCount = printable.calcCountPage(model.getReportPage());
    Map<Integer, PageClip> clips = printable.getPageClips();

    int leftCol;
    int topRow;
    int rightCol;
    int bottomRow;

    for (int pageIndex = 0; pageIndex < pageCount; pageIndex++) {
        PageClip pageClip = clips.get(pageIndex);
        if (pageClip == null)
            break;

        leftCol = pageClip.getLeftCol();
        rightCol = pageClip.getRightCol();

        topRow = pageClip.getTopRow();
        bottomRow = pageClip.getBottomRow();

        int columnCount = rightCol - leftCol;

        float[] widths = new float[columnCount + 1];
        widths[0] = 1;
        for (int c = 0; c < columnCount; c++) {
            ReportColumn column = (ReportColumn) model.getColumnModel().getColumn(leftCol + c);
            widths[c + 1] = (float) Math.round(column.getNativeWidth());
        }

        PdfPTable table = createPdfTable(columnCount + 1, widths, viewPageSize);

        fillTable(model, leftCol, topRow, rightCol, bottomRow, table);

        document.add(table);

        if (pageIndex < clips.size()) {
            document.newPage();
        }

    }
    return listCount;
}

From source file:jmbench.plots.UtilPlotPdf.java

License:Open Source License

public static void saveAsPdf(JFreeChart chart, String FILENAME, int width, int height) {
    File parent = new File(new File(FILENAME).getParent());
    if (!parent.exists()) {
        if (!parent.mkdirs())
            throw new RuntimeException("Can't make directory path");
    }//from   w  w  w  .  j a v  a2  s. c om

    Document document = new Document(new Rectangle(width, height));
    try {
        FileOutputStream file = new FileOutputStream(FILENAME);
        PdfWriter writer = PdfWriter.getInstance(document, file);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2d = tp.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height);
        chart.draw(g2d, r2d);
        g2d.dispose();
        cb.addTemplate(tp, 0, 0);
        document.close();
        g2d.dispose();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:jmbench.plots.UtilPlotPdf.java

License:Open Source License

public static void saveAsPdf(LegendTitle legend, String FILENAME, int width, int height) {
    Document document = new Document(new Rectangle(width, height));
    try {//from  w  w w  . j a va  2  s  . com
        FileOutputStream file = new FileOutputStream(FILENAME);
        PdfWriter writer = PdfWriter.getInstance(document, file);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2d = tp.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height);
        legend.draw(g2d, r2d);
        g2d.dispose();
        cb.addTemplate(tp, 0, 0);
        document.close();
        g2d.dispose();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:mitm.common.pdf.MessagePDFBuilder.java

License:Open Source License

private Document createDocument() throws DocumentException {
    Rectangle pageSize = new Rectangle(documentWidth, documentHeight);

    pageSize.setGrayFill(grayFill);//w  ww  . j  a va2  s  .  c o m

    Document document = new Document(pageSize, marginLeft, marginRight, marginTop, marginBottom);

    document.addCreator(CREATOR);

    return document;
}

From source file:mx.dr.util.report.impl.PdfService.java

License:Open Source License

/**
 * @see mx.dr.util.report.IPdfService#doMultiReport(List, OutputStream)
*///from  w  ww.  j a  v  a 2  s .c o  m
public void doMultiReport(List<Object> lista, OutputStream out) throws Exception {
    DRPdfDocument anonDoc = null;
    for (Object o : lista) {
        anonDoc = o.getClass().getAnnotation(DRPdfDocument.class);
        break;
    }
    Document doc = null;
    if (anonDoc != null) {
        doc = new Document(new Rectangle(anonDoc.height(), anonDoc.width()), 0, 0, 0, 0);
    } else {
        doc = new Document(PageSize.LETTER, 0, 0, 0, 0);
    }
    PdfWriter.getInstance(doc, out);
    doc.open();
    Object dto;
    for (int i = 0; i < lista.size(); i++) {
        dto = lista.get(i);
        if (i > 0) {
            doc.newPage();
        }
        estampaEtiqueta(doc, dto, null, null);
    }

    doc.close();
}

From source file:mx.dr.util.report.impl.PdfService.java

License:Open Source License

/**
 * @see mx.dr.util.report.IPdfService#doReport(Object, OutputStream)
 *//*  w w w.j ava  2 s.  co  m*/
public void doReport(Object dto, OutputStream out) throws Exception {
    DRPdfDocument anonDoc = null;

    anonDoc = dto.getClass().getAnnotation(DRPdfDocument.class);
    Document doc = null;
    if (anonDoc != null) {
        doc = new Document(new Rectangle(anonDoc.height(), anonDoc.width()), 0, 0, 0, 0);
    } else {
        doc = new Document(PageSize.LETTER, 0, 0, 0, 0);
    }

    PdfWriter.getInstance(doc, out);
    doc.open();
    estampaEtiqueta(doc, dto, null, null);
    doc.close();
}

From source file:mx.randalf.digital.ocr.hocrtopdf.HocrToPdf.java

License:Open Source License

public void hocrToPdf(File fImg, File fHtml, File fPdf) throws IOException, DocumentException, Exception {
    URL inputHOCRFile = null;//  www  .j  a  v  a 2  s . c om
    FileOutputStream outputPDFStream = null;
    // The resolution of a PDF file (using iText) is 72pt per inch
    float pointsPerInch = 72.0f;
    Source source = null;
    StartTag pageTag = null;
    Pattern imagePattern = null;
    Matcher imageMatcher = null;
    // Load the image
    Image pageImage = null;
    float dotsPerPointX;
    float dotsPerPointY;
    float pageImagePixelHeight;
    Document pdfDocument = null;
    PdfWriter pdfWriter = null;
    Font defaultFont = null;
    PdfContentByte cb = null;
    Pattern bboxPattern = null;
    Pattern bboxCoordinatePattern = null;
    StartTag ocrLineTag = null;

    try {
        try {
            inputHOCRFile = new URL("file://" + fHtml.getAbsolutePath());
        } catch (MalformedURLException e) {
            throw e;
        }
        try {
            outputPDFStream = new FileOutputStream(fPdf);
        } catch (FileNotFoundException e) {
            throw e;
        }

        // Using the jericho library to parse the HTML file
        source = new Source(inputHOCRFile);

        // Find the tag of class ocr_page in order to load the scanned image
        pageTag = source.findNextStartTag(0, "class", "ocr_page", false);
        imagePattern = Pattern.compile("image\\s+([^;]+)");
        imageMatcher = imagePattern.matcher(pageTag.getElement().getAttributeValue("title"));
        if (!imageMatcher.find()) {
            throw new Exception("Could not find a tag of class \"ocr_page\", aborting.");
        }

        try {
            pageImage = Image.getInstance(new URL("file://" + fImg.getAbsolutePath()));
        } catch (MalformedURLException e) {
            throw e;
        }
        dotsPerPointX = pageImage.getDpiX() / pointsPerInch;
        dotsPerPointY = pageImage.getDpiY() / pointsPerInch;
        pageImagePixelHeight = pageImage.getHeight();
        pdfDocument = new Document(
                new Rectangle(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY));
        pdfWriter = PdfWriter.getInstance(pdfDocument, outputPDFStream);
        pdfDocument.open();

        // first define a standard font for our text
        defaultFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD, CMYKColor.BLACK);

        // Put the text behind the picture (reverse for debugging)
        cb = pdfWriter.getDirectContentUnder();
        //PdfContentByte cb = pdfWriter.getDirectContent();

        pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY);
        pageImage.setAbsolutePosition(0, 0);
        // Put the image in front of the text (reverse for debugging)
        pdfWriter.getDirectContent().addImage(pageImage);
        //pdfWriter.getDirectContentUnder().addImage(pageImage);

        // In order to place text behind the recognised text snippets we are interested in the bbox property      
        bboxPattern = Pattern.compile("bbox(\\s+\\d+){4}");
        // This pattern separates the coordinates of the bbox property
        bboxCoordinatePattern = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)");
        // Only tags of the ocr_line class are interesting
        ocrLineTag = source.findNextStartTag(0, "class", "ocr_line", false);
        while (ocrLineTag != null) {
            au.id.jericho.lib.html.Element lineElement = ocrLineTag.getElement();
            Matcher bboxMatcher = bboxPattern.matcher(lineElement.getAttributeValue("title"));
            if (bboxMatcher.find()) {
                // We found a tag of the ocr_line class containing a bbox property
                Matcher bboxCoordinateMatcher = bboxCoordinatePattern.matcher(bboxMatcher.group());
                bboxCoordinateMatcher.find();
                int[] coordinates = { Integer.parseInt((bboxCoordinateMatcher.group(1))),
                        Integer.parseInt((bboxCoordinateMatcher.group(2))),
                        Integer.parseInt((bboxCoordinateMatcher.group(3))),
                        Integer.parseInt((bboxCoordinateMatcher.group(4))) };
                String line = lineElement.getContent().extractText();
                //               float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX;
                float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY;

                // Put the text into the PDF
                cb.beginText();
                // Comment the next line to debug the PDF output (visible Text)
                cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
                // TODO: Scale the text width to fit the OCR bbox
                cb.setFontAndSize(defaultFont.getBaseFont(), Math.round(bboxHeightPt));
                cb.moveText((float) (coordinates[0] / dotsPerPointX),
                        (float) ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY));
                cb.showText(line);
                cb.endText();
            }
            ocrLineTag = source.findNextStartTag(ocrLineTag.getEnd(), "class", "ocr_line", false);
        }
    } catch (NumberFormatException e) {
        throw e;
    } catch (MalformedURLException e) {
        throw e;
    } catch (FileNotFoundException e) {
        throw e;
    } catch (BadElementException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } catch (DocumentException e) {
        throw e;
    } catch (Exception e) {
        throw e;
    } finally {
        if (pdfDocument != null) {
            pdfDocument.close();
        }
        if (outputPDFStream != null) {
            outputPDFStream.close();
        }
    }
}