Example usage for com.lowagie.text Chunk Chunk

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

Introduction

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

Prototype

public Chunk(DrawInterface separator, float tabPosition) 

Source Link

Document

Creates a tab Chunk.

Usage

From source file:fr.opensagres.odfdom.converter.pdf.internal.stylable.StylableTab.java

License:Open Source License

public void draw(PdfContentByte canvas, float llx, float lly, float urx, float ury, float y) {
    if (font.getBaseFont() != null && font.getSize() > 0.0 && leaderText.trim().length() > 0) {
        // create text to fit tab width
        float width = urx - llx;
        String txt = "";
        while (true) {
            Chunk tmp = new Chunk(txt + leaderText, font);
            if (tmp.getWidthPoint() <= width) {
                txt += leaderText;/*from  w ww  . ja  v  a2s.c o  m*/
            } else {
                break;
            }
        }
        // compute x offset - as if tab were right aligned
        float xoffset = width - new Chunk(txt, font).getWidthPoint();
        // compute y offset - use StylableParagraph mechanism
        Chunk tmp = StylableParagraph.createAdjustedChunk(txt, font, lineHeight, lineHeightProportional);
        float yoffset = tmp.getTextRise();
        // draw
        canvas.saveState();
        canvas.beginText();
        canvas.setFontAndSize(font.getBaseFont(), font.getSize());
        canvas.showTextAligned(Element.ALIGN_LEFT, txt, llx + xoffset, y + yoffset, 0.0f);
        canvas.endText();
        canvas.restoreState();
    }
}

From source file:fr.opensagres.poi.xwpf.converter.pdf.internal.FastPdfMapper.java

License:Open Source License

private Chunk createTextChunk(String text, boolean pageNumber, Font currentRunFont,
        UnderlinePatterns currentRunUnderlinePatterns, Color currentRunBackgroundColor) {
    Chunk textChunk = pageNumber ? new ExtendedChunk(pdfDocument, true, currentRunFont)
            : new Chunk(text, currentRunFont);

    if (currentRunUnderlinePatterns != null) {
        // underlined
        boolean singleUnderlined = false;
        switch (currentRunUnderlinePatterns) {
        case SINGLE:
            singleUnderlined = true;/* w  w w . j av a 2s  .co  m*/
            break;

        default:
            break;
        }
        if (singleUnderlined) {
            textChunk.setUnderline(1, -2);
        }
    }

    // background color
    if (currentRunBackgroundColor != null) {
        textChunk.setBackground(Converter.toAwtColor(currentRunBackgroundColor));
    }
    if (currentRunX != null) {
        this.currentRunX += textChunk.getWidthPoint();
    }
    return textChunk;
}

From source file:fr.opensagres.poi.xwpf.converter.pdf.internal.PdfMapper.java

License:Open Source License

private Chunk createTextChunk(String text, boolean pageNumber, Font currentRunFont,
        UnderlinePatterns currentRunUnderlinePatterns, Color currentRunBackgroundColor) {
    // Chunk textChunk =
    // pageNumber ? new ExtendedChunk( pdfDocument, true, currentRunFont ) :
    // new Chunk( text, currentRunFont );

    Chunk textChunk = null;/* w  w w  . j  av  a 2 s . com*/
    if (processingTotalPageCountField && expectedPageCount != null) {
        textChunk = new Chunk(String.valueOf(expectedPageCount), currentRunFont);
    } else {
        textChunk = pageNumber ? new ExtendedChunk(pdfDocument, true, currentRunFont)
                : new Chunk(text, currentRunFont);
    }
    if (currentRunUnderlinePatterns != null) {
        // underlined
        boolean singleUnderlined = false;
        switch (currentRunUnderlinePatterns) {
        case SINGLE:
            singleUnderlined = true;
            break;

        default:
            break;
        }
        if (singleUnderlined) {
            textChunk.setUnderline(1, -2);
        }
    }

    // background color
    if (currentRunBackgroundColor != null) {
        textChunk.setBackground(Converter.toAwtColor(currentRunBackgroundColor));
    }
    if (currentRunX != null) {
        this.currentRunX += textChunk.getWidthPoint();
    }
    return textChunk;
}

From source file:fr.opensagres.xdocreport.itext.extension.ExtendedSection.java

License:Open Source License

/**
 * Constructs a Paragraph that will be used as title for a Section or Chapter.
 * //www  .  j a  va2s. c om
 * @param title the title of the section
 * @param numbers a list of sectionnumbers
 * @param numberDepth how many numbers have to be shown
 * @param numberStyle the numbering style
 * @return a Paragraph object
 * @since iText 2.0.8
 */
public static Paragraph ancestorConstructTitle(IParagraphFactory factory, Paragraph title, ArrayList numbers,
        int numberDepth, int numberStyle) {
    if (title == null) {
        return null;
    }

    int depth = Math.min(numbers.size(), numberDepth);
    if (depth < 1) {
        return title;
    }
    StringBuffer buf = new StringBuffer(" ");
    for (int i = 0; i < depth; i++) {
        buf.insert(0, ".");
        buf.insert(0, ((Integer) numbers.get(i)).intValue());
    }
    if (numberStyle == NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT) {
        buf.deleteCharAt(buf.length() - 2);
    }
    Paragraph result = factory.createParagraph(title);
    result.add(0, new Chunk(buf.toString(), title.getFont()));
    return result;
}

From source file:fr.paris.lutece.plugins.directory.modules.pdfproducer.utils.PDFUtils.java

License:Open Source License

/**
 * This method build the different label and value of directory fields in
 * the document PDF/*from   w w w  .  j  ava2  s .c o m*/
 * 
 * @param listRecordFields recordfield map
 * @param document document pdf
 * @param entry entry
 * @param locale the locale
 * @param bExtractNotFilledField if true, extract empty fields, false
 * @throws DocumentException DocumentException
 */
private static void builFieldsInPDF(List<RecordField> listRecordFields, Document document, IEntry entry,
        Locale locale, Boolean bExtractNotFilledField) throws DocumentException {
    Phrase phraseEntry = new Phrase();
    Paragraph paragraphEntry = new Paragraph();

    if (StringUtils.isNotBlank(entry.getTitle())) {
        entry.getTitle();

        Font fontEntryTitle = new Font(
                DirectoryUtils.convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_NAME)),
                DirectoryUtils
                        .convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_SIZE_ENTRY_TITLE)),
                DirectoryUtils.convertStringToInt(
                        AppPropertiesService.getProperty(PROPERTY_POLICE_STYLE_ENTRY_TITLE)));
        Chunk chunkEntryTitle = new Chunk(entry.getTitle(), fontEntryTitle);
        phraseEntry.add(chunkEntryTitle);
        phraseEntry.add(" : ");
    }

    if ((listRecordFields != null) && (listRecordFields.size() > 0)) {
        // Must separate the behaviour whether the list of record fiels contains 1 or more record fields
        if ((listRecordFields.size() > 1)
                && !(entry instanceof fr.paris.lutece.plugins.directory.business.EntryTypeGeolocation)) {
            builFieldsInParagraph(listRecordFields, entry, locale, phraseEntry, paragraphEntry,
                    bExtractNotFilledField);
        } else {
            builFieldsInSinglePhrase(listRecordFields, entry, locale, phraseEntry, paragraphEntry,
                    bExtractNotFilledField);
        }
    }

    document.add(paragraphEntry);
}

From source file:ispyb.client.mx.results.ExportAutoProcAction.java

License:Open Source License

private void setAutoProcInfo(Document document) throws Exception {
    // header/*from  w w  w .  j av a  2  s .  c  o  m*/
    Table headerTable = new Table(1);
    headerTable.getDefaultCell().setBorderWidth(0);
    headerTable.setBorderWidth(0);
    headerTable.setCellsFitPage(true);
    headerTable.setAlignment(Element.ALIGN_LEFT);
    headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
    headerTable.getDefaultCell().setBackgroundColor(PdfRtfExporter.LIGHT_YELLOW_COLOR);
    headerTable.getDefaultCell().setLeading(3);
    headerTable.setWidth(100); // percentage
    headerTable
            .addCell(new Paragraph("Crystal data and data-collection statistics", PdfRtfExporter.FONT_DOC_11));
    headerTable.addCell(new Paragraph("Values in parentheses are for the highest resolution shell.",
            PdfRtfExporter.FONT_DOC_11));
    document.add(headerTable);
    document.add(new Paragraph(" ", PdfRtfExporter.VERY_SMALL_FONT));
    // auto proc table
    Table autoProcTable = new Table(2);
    autoProcTable.getDefaultCell().setBorderWidth(0);
    autoProcTable.setBorderWidth(0);
    autoProcTable.setCellsFitPage(true);
    autoProcTable.setAlignment(Element.ALIGN_LEFT);
    autoProcTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
    // autoProcTable.getDefaultCell().setLeading(3);
    autoProcTable.setPadding(2);
    autoProcTable.setWidth(100); // percentage
    // data
    String spaceGroup = autoProc == null ? "" : autoProc.getSpaceGroup();
    String unitCell_a = autoProc == null ? "" : autoProc.getRefinedCellA().toString();
    String unitCell_b = autoProc == null ? "" : autoProc.getRefinedCellB().toString();
    String unitCell_c = autoProc == null ? "" : autoProc.getRefinedCellC().toString();
    String unitCell_alpha = autoProc == null ? "" : autoProc.getRefinedCellAlpha().toString();
    String unitCell_beta = autoProc == null ? "" : autoProc.getRefinedCellBeta().toString();
    String unitCell_gamma = autoProc == null ? "" : autoProc.getRefinedCellGamma().toString();
    String resolutionRange = "";
    String nTotalObservations = "";
    String nTotalUniqueReflections = "";
    String completeness = "";
    String multiplicity = "";
    String isigma = "";
    String rmerge = "";
    if (autoProcStatisticsOverall != null) {
        resolutionRange = autoProcStatisticsOverall.getResolutionLimitLow() + " - "
                + autoProcStatisticsOverall.getResolutionLimitHigh();
        nTotalObservations = "" + autoProcStatisticsOverall.getnTotalObservations();
        nTotalUniqueReflections = "" + (autoProcStatisticsOverall.getnTotalUniqueObservations() == null ? ""
                : autoProcStatisticsOverall.getnTotalUniqueObservations());
        completeness = "" + autoProcStatisticsOverall.getCompleteness();
        multiplicity = "" + autoProcStatisticsOverall.getMultiplicity();
        isigma = "" + autoProcStatisticsOverall.getMeanIoverSigI();
        rmerge = ""
                + (autoProcStatisticsOverall.getRmerge() == null ? "" : autoProcStatisticsOverall.getRmerge());
    }
    if (autoProcStatisticsOuter != null) {
        resolutionRange += " (" + autoProcStatisticsOuter.getResolutionLimitLow() + " - "
                + autoProcStatisticsOuter.getResolutionLimitHigh() + ")";
        nTotalObservations += " (" + autoProcStatisticsOuter.getnTotalObservations() + ")";
        nTotalUniqueReflections += autoProcStatisticsOuter.getnTotalUniqueObservations() == null ? ""
                : (" (" + autoProcStatisticsOuter.getnTotalUniqueObservations() + ")");
        completeness += " (" + autoProcStatisticsOuter.getCompleteness() + ")";
        multiplicity += " (" + autoProcStatisticsOuter.getMultiplicity() + ")";
        isigma += " (" + autoProcStatisticsOuter.getMeanIoverSigI() + ")";
        rmerge += " ("
                + (autoProcStatisticsOuter.getRmerge() == null ? "" : autoProcStatisticsOuter.getRmerge())
                + ")";
    }
    // space group
    autoProcTable.addCell(new Paragraph("Space Group", PdfRtfExporter.FONT_DOC_11));
    autoProcTable.addCell(new Paragraph(spaceGroup, PdfRtfExporter.FONT_DOC_11));
    // unit cell parameters
    autoProcTable.addCell(
            new Paragraph("Unit-cell parameters (" + Constants.ANGSTROM + ")", PdfRtfExporter.FONT_DOC_11));
    autoProcTable.addCell(new Paragraph("", PdfRtfExporter.FONT_DOC_11));
    Paragraph pa = new Paragraph("\t a", PdfRtfExporter.FONT_DOC_11);
    pa.setAlignment(Element.ALIGN_JUSTIFIED);
    pa.setIndentationLeft(PdfRtfExporter.INDENTATION_LEFT);
    autoProcTable.addCell(pa);
    autoProcTable.addCell(new Paragraph(unitCell_a, PdfRtfExporter.FONT_DOC_11));
    Paragraph pb = new Paragraph("\t b", PdfRtfExporter.FONT_DOC_11);
    pb.setAlignment(Element.ALIGN_JUSTIFIED);
    pb.setIndentationLeft(PdfRtfExporter.INDENTATION_LEFT);
    autoProcTable.addCell(pb);
    autoProcTable.addCell(new Paragraph(unitCell_b, PdfRtfExporter.FONT_DOC_11));
    Paragraph pc = new Paragraph("\t c", PdfRtfExporter.FONT_DOC_11);
    pc.setAlignment(Element.ALIGN_JUSTIFIED);
    pc.setIndentationLeft(PdfRtfExporter.INDENTATION_LEFT);
    autoProcTable.addCell(pc);
    autoProcTable.addCell(new Paragraph(unitCell_c, PdfRtfExporter.FONT_DOC_11));
    // Issue 1733: cell angles info added
    Paragraph palpha = new Paragraph("\t alpha", PdfRtfExporter.FONT_DOC_11);
    palpha.setAlignment(Element.ALIGN_JUSTIFIED);
    palpha.setIndentationLeft(PdfRtfExporter.INDENTATION_LEFT);
    autoProcTable.addCell(palpha);
    autoProcTable.addCell(new Paragraph(unitCell_alpha, PdfRtfExporter.FONT_DOC_11));
    Paragraph pbeta = new Paragraph("\t beta", PdfRtfExporter.FONT_DOC_11);
    pbeta.setAlignment(Element.ALIGN_JUSTIFIED);
    pbeta.setIndentationLeft(PdfRtfExporter.INDENTATION_LEFT);
    autoProcTable.addCell(pbeta);
    autoProcTable.addCell(new Paragraph(unitCell_beta, PdfRtfExporter.FONT_DOC_11));
    Paragraph pgamma = new Paragraph("\t gamma", PdfRtfExporter.FONT_DOC_11);
    pgamma.setAlignment(Element.ALIGN_JUSTIFIED);
    pgamma.setIndentationLeft(PdfRtfExporter.INDENTATION_LEFT);
    autoProcTable.addCell(pgamma);
    autoProcTable.addCell(new Paragraph(unitCell_gamma, PdfRtfExporter.FONT_DOC_11));
    // resolution range
    autoProcTable.addCell(
            new Paragraph("Resolution range (" + Constants.ANGSTROM + ")", PdfRtfExporter.FONT_DOC_11));
    autoProcTable.addCell(new Paragraph(resolutionRange, PdfRtfExporter.FONT_DOC_11));
    // Observed reflections
    autoProcTable.addCell(new Paragraph("Observed reflections", PdfRtfExporter.FONT_DOC_11));
    autoProcTable.addCell(new Paragraph(nTotalObservations, PdfRtfExporter.FONT_DOC_11));
    // No. of unique reflections
    autoProcTable.addCell(new Paragraph("No. of unique reflections", PdfRtfExporter.FONT_DOC_11));
    autoProcTable.addCell(new Paragraph(nTotalUniqueReflections, PdfRtfExporter.FONT_DOC_11));
    // Completeness
    autoProcTable.addCell(new Paragraph("Completeness (%)", PdfRtfExporter.FONT_DOC_11));
    autoProcTable.addCell(new Paragraph(completeness, PdfRtfExporter.FONT_DOC_11));
    // multiplicity
    autoProcTable.addCell(new Paragraph("Multiplicity", PdfRtfExporter.FONT_DOC_11));
    autoProcTable.addCell(new Paragraph(multiplicity, PdfRtfExporter.FONT_DOC_11));
    new Phrase();
    // I/(I)
    Phrase p = Phrase.getInstance("<I/" + (char) 963 + "(I)>");
    p.setFont(PdfRtfExporter.FONT_DOC_11);
    autoProcTable.addCell(p);
    autoProcTable.addCell(new Paragraph(isigma, PdfRtfExporter.FONT_DOC_11));
    // Rmerge
    Chunk c1 = new Chunk("R", PdfRtfExporter.FONT_DOC_11);
    Chunk c2 = new Chunk("merge", PdfRtfExporter.FONT_DOC_EXPONENT);
    c2.setTextRise(PdfRtfExporter.TEXT_RISE_SUB);
    Chunk c3 = new Chunk("(%)", PdfRtfExporter.FONT_DOC_11);
    Chunk c4 = new Chunk("#", PdfRtfExporter.FONT_DOC_EXPONENT_BLUE);
    c4.setTextRise(PdfRtfExporter.TEXT_RISE_EXP);
    Paragraph rMergeParagraph = new Paragraph();
    rMergeParagraph.add(c1);
    rMergeParagraph.add(c2);
    rMergeParagraph.add(c3);
    rMergeParagraph.add(c4);
    autoProcTable.addCell(rMergeParagraph);
    autoProcTable.addCell(new Paragraph(rmerge, PdfRtfExporter.FONT_DOC_11));
    document.add(autoProcTable);
    document.add(new Paragraph(" ", PdfRtfExporter.FONT_DOC_11));
    // nota bene info
    Paragraph nbParagraph = new Paragraph();
    nbParagraph.add(c4);
    nbParagraph.add(c1);
    nbParagraph.add(c2);
    Chunk cesp = new Chunk(" ", PdfRtfExporter.FONT_DOC_11);
    Chunk c5 = new Chunk(" = ", PdfRtfExporter.FONT_DOC_11);
    nbParagraph.add(c5);
    Phrase pSigma = Phrase.getInstance("" + (char) 931);
    pSigma.setFont(PdfRtfExporter.FONT_DOC_11);
    nbParagraph.add(pSigma);
    Chunk chkl = new Chunk("hkl", PdfRtfExporter.FONT_DOC_EXPONENT);
    chkl.setTextRise(PdfRtfExporter.TEXT_RISE_SUB);
    nbParagraph.add(chkl);
    nbParagraph.add(cesp);
    nbParagraph.add(pSigma);
    Chunk ci = new Chunk("i", PdfRtfExporter.FONT_DOC_EXPONENT);
    ci.setTextRise(PdfRtfExporter.TEXT_RISE_SUB);
    nbParagraph.add(ci);
    Chunk c8 = new Chunk(" |I", PdfRtfExporter.FONT_DOC_11);
    nbParagraph.add(c8);
    nbParagraph.add(ci);
    Chunk c9 = new Chunk("(hkl) - (I(hkl))| / ", PdfRtfExporter.FONT_DOC_11);
    nbParagraph.add(c9);
    nbParagraph.add(pSigma);
    nbParagraph.add(chkl);
    nbParagraph.add(cesp);
    nbParagraph.add(pSigma);
    nbParagraph.add(ci);
    nbParagraph.add(cesp);
    Chunk c10 = new Chunk("I", PdfRtfExporter.FONT_DOC_11);
    nbParagraph.add(c10);
    nbParagraph.add(ci);
    Chunk c11 = new Chunk("(hkl), where ", PdfRtfExporter.FONT_DOC_11);
    nbParagraph.add(c11);
    Chunk c12 = new Chunk("I", PdfRtfExporter.FONT_DOC_11_ITALIC);
    nbParagraph.add(c12);
    Chunk cii = new Chunk("i", PdfRtfExporter.FONT_DOC_EXPONENT_ITALIC);
    cii.setTextRise(PdfRtfExporter.TEXT_RISE_SUB);
    nbParagraph.add(cii);
    Chunk c13 = new Chunk("(hkl)", PdfRtfExporter.FONT_DOC_11_ITALIC);
    nbParagraph.add(c13);
    Chunk c14 = new Chunk(" is the ", PdfRtfExporter.FONT_DOC_11);
    nbParagraph.add(c14);
    Chunk c15 = new Chunk("i", PdfRtfExporter.FONT_DOC_11_ITALIC);
    nbParagraph.add(c15);
    Chunk c16 = new Chunk("th observation of reflection ", PdfRtfExporter.FONT_DOC_11);
    nbParagraph.add(c16);
    Chunk chklI = new Chunk("hkl", PdfRtfExporter.FONT_DOC_11_ITALIC);
    nbParagraph.add(chklI);
    Chunk c17 = new Chunk(" and ", PdfRtfExporter.FONT_DOC_11);
    nbParagraph.add(c17);
    Chunk c18 = new Chunk("<I(hkl)> ", PdfRtfExporter.FONT_DOC_11_ITALIC);
    nbParagraph.add(c18);
    Chunk c19 = new Chunk(" is the weighted average intensity for all observations of reflection ",
            PdfRtfExporter.FONT_DOC_11);
    nbParagraph.add(c19);
    nbParagraph.add(chklI);
    Chunk c20 = new Chunk(".", PdfRtfExporter.FONT_DOC_11);
    nbParagraph.add(c20);
    document.add(nbParagraph);
    document.add(new Paragraph(" ", PdfRtfExporter.FONT_DOC_11));
}

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

License:Apache License

protected void writeHTMLText(CellStyle parentStyle, jdbreport.model.Cell cell, PdfPCell pdfCell) {
    if (cell.isNull() || cell.isChild())
        return;//from   w  w  w .  j a  va  2 s  . co m

    JTextComponent tc = getHTMLReportRenderer();
    tc.setText(cell.getText());
    List<Content> contentList = Content.getHTMLContentList((HTMLDocument) tc.getDocument());
    if (contentList != null) {
        Phrase phrase = new Phrase();
        for (Content content : contentList) {
            CellStyle newStyle = content.createTextStyle(parentStyle, parentStyle);
            if (newStyle == null) {
                newStyle = parentStyle;
            }
            if (newStyle != null) {
                if (newStyle.getTypeOffset() == CellStyle.SS_SUPER
                        || newStyle.getTypeOffset() == CellStyle.SS_SUB) {
                    newStyle = newStyle.deriveFont((float) newStyle.getSize() / 2);
                }
                int i = textStyles.indexOf(newStyle);
                if (i < 0) {
                    textStyles.add(newStyle);
                    i = textStyles.size() - 1;
                }
                Font font;
                String styleId = "T" + (i + 1);
                if (fonts.containsKey(styleId)) {
                    font = fonts.get(styleId);
                } else {
                    font = getFontMapper().styleToPdf(newStyle);
                    fonts.put(styleId, font);
                }
                Chunk chunk = new Chunk(content.getText(), font);
                chunk.setBackground(newStyle.getBackground());
                if (newStyle.getTypeOffset() == CellStyle.SS_SUPER) {
                    chunk.setTextRise(newStyle.getSize() / 2);
                } else if (newStyle.getTypeOffset() == CellStyle.SS_SUB) {
                    chunk.setTextRise(-newStyle.getSize() / 2);
                }
                phrase.add(chunk);
            } else {
                phrase.add(new Chunk(content.getText()));
            }
        }
        pdfCell.setPhrase(phrase);
    }
}

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

License:Open Source License

private void addLinkPart(String link, Phrase bodyPhrase, Font linkFont) {
    String linkName = link;//from   ww w .j av a2  s  .c  o m

    link = link.trim();

    Chunk anchor = new Chunk(linkName, linkFont);

    /*
     * A anchor need http (or https)
     */
    if (!link.toLowerCase().startsWith("http")) {
        link = "http://" + link;
    }

    anchor.setAnchor(link);

    bodyPhrase.add(anchor);
}

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

License:Open Source License

private void addReplyLink(Document document, String replyURL) throws DocumentException {
    PdfPTable replyTable = new PdfPTable(1);
    replyTable.setWidthPercentage(100f);

    replyTable.setSplitLate(false);/*w w  w.j a  v a  2 s  .  c om*/

    replyTable.setSpacingBefore(5f);
    replyTable.setHorizontalAlignment(Element.ALIGN_LEFT);

    Font linkFont = new Font();

    linkFont.setStyle(Font.BOLD);
    linkFont.setColor(0, 0, 255);
    linkFont.setSize(headerFontSize);

    Chunk anchor = new Chunk("Reply", linkFont);

    anchor.setAnchor(replyURL);

    Phrase phrase = new Phrase();

    phrase.add(anchor);

    PdfPCell cell = new PdfPCell(phrase);
    cell.setBorder(Rectangle.NO_BORDER);

    replyTable.addCell(cell);

    document.add(replyTable);
}

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

License:Open Source License

/**
* write a label in pdf document./*from  www  .  j a  v a  2s. c o  m*/
* <br/>
* escribe una etiqueta en el documento pdf.
* @param doc pdf document / documento pdf.
* @param dto object that encompasses the values of the labels to be placed in the document / objeto que engloba los valores de las etiquetas que se colocaran en el documento.
* @param offset jump on the Y axis to be given before placing the tag in the document / salto en el eje Y que se dara antes de colocar la etiqueta en el documento.
* @param table container table if applicable / contenedor de tabla si es que aplica.
* @throws Exception If an error occurs / si ocurre algun error.
*/
public void estampaEtiqueta(Document doc, Object dto, Float offset, PdfPTable table) throws Exception {
    List<Field> fields = new ArrayList<Field>();

    for (Field m : dto.getClass().getDeclaredFields()) {
        m.setAccessible(true);
        if (m.getAnnotation(DRPdfLabel.class) != null) {
            fields.add(m);
        }
    }
    Collections.sort(fields, new Comparator<Field>() {

        public int compare(Field o1, Field o2) {
            DRPdfLabel etiqueta1 = o1.getAnnotation(DRPdfLabel.class);
            DRPdfLabel etiqueta2 = o2.getAnnotation(DRPdfLabel.class);
            String uno = int2String(etiqueta1.y()) + "." + int2String(etiqueta1.order());
            String dos = int2String(etiqueta2.y()) + "." + int2String(etiqueta2.order());
            return uno.compareTo(dos);

        }

        private String int2String(int num) {
            if (num < 10) {
                return "0" + num;
            } else {
                return String.valueOf(num);
            }
        }
    });
    DRPdfLabel etiqueta;
    DRPdfTable etiquetaTabla;
    int lineaActual = 0;
    Paragraph pantagram = null;
    StringBuffer sb = null;
    Font font;
    Object valor;
    String label;
    DRPdfImage img;
    int residuo;
    int adicional = 0;
    for (Field m : fields) {
        etiqueta = m.getAnnotation(DRPdfLabel.class);
        img = m.getAnnotation(DRPdfImage.class);
        valor = m.get(dto);
        if (valor != null && valor instanceof List) {
            etiquetaTabla = m.getAnnotation(DRPdfTable.class);
            PdfPTable tableDance = null;
            if (etiquetaTabla != null) {
                tableDance = new PdfPTable(etiquetaTabla.colsPercentage());
                tableDance.setSpacingBefore(etiqueta.offset());
                for (String c : etiquetaTabla.columnLabels()) {
                    tableDance.addCell(c);
                }
            }
            if (pantagram != null) {
                doc.add(pantagram);
                pantagram = null;
            }
            for (int i = 0; i < ((List) valor).size(); i++) {
                if (i == 0 && etiqueta.offset() > 0) {
                    estampaEtiqueta(doc, ((List) valor).get(i), etiqueta.offset(), tableDance);
                } else {
                    estampaEtiqueta(doc, ((List) valor).get(i), null, tableDance);
                }
            }
            if (etiquetaTabla != null) {
                doc.add(tableDance);
            }
        } else if (img != null) {
            /* File file = new File(IMGDIR + valor);
            FileInputStream inImg = new FileInputStream(file);
            byte[] b=new byte[(int)file.length()];
            inImg.read(b);*/

            Image ima = Image.getInstance(IMGDIR + valor);

            //System.out.println(ima.getPlainWidth());
            ima.scaleAbsoluteWidth(img.width());
            //System.out.println(ima.getScaledWidth());
            ima.scaleAbsoluteHeight(ima.getScaledWidth());
            ima.setAlignment(img.style());
            ima.setAbsolutePosition(img.x(), img.y());
            doc.add(ima);

        } else if (table != null) {

            PdfPCell cerda = null;

            label = value2String(valor);
            residuo = etiqueta.length() - label.length();
            label = etiqueta.length() > 0 && residuo < 0 ? label.substring(0, etiqueta.length()) : label;
            DRPdfColumn col = m.getAnnotation(DRPdfColumn.class);
            if (col != null) {
                cerda = new PdfPCell(new Paragraph(label));
                cerda.setColspan(col.colspan());
                table.addCell(cerda);
            } else {
                table.addCell(label);
            }

        } else {
            if (lineaActual < etiqueta.y()) {
                if (pantagram != null) {
                    doc.add(pantagram);
                }
                if (offset == null || etiqueta.y() > 1) {
                    if (etiqueta.offset() > 0) {
                        pantagram = new Paragraph(etiqueta.offset());
                    } else {
                        pantagram = new Paragraph();
                    }
                } else {
                    pantagram = new Paragraph(offset);
                }
                lineaActual = etiqueta.y();
            }

            if (etiqueta.wspacesBefore() > 0) {
                sb = new StringBuffer("");
                fillEmpty(etiqueta.wspacesBefore(), sb);
                font = new Font(Font.COURIER, 12);
                pantagram.add(new Chunk(sb.toString(), font));
            }
            sb = new StringBuffer("");
            label = value2String(valor);
            residuo = etiqueta.length() - label.length();
            label = etiqueta.length() > 0 && residuo < 0 ? label.substring(0, etiqueta.length()) : label;

            if (etiqueta.font().equals(BaseFont.COURIER)) {
                font = new Font(Font.COURIER, etiqueta.fontSize(), etiqueta.style(),
                        new Color(etiqueta.color()[0], etiqueta.color()[1], etiqueta.color()[2]));
                adicional = 0;
            } else {
                font = FontFactory.getFont(TTFDIR + etiqueta.font(), BaseFont.CP1252, BaseFont.EMBEDDED,
                        etiqueta.fontSize(), etiqueta.style(),
                        new Color(etiqueta.color()[0], etiqueta.color()[1], etiqueta.color()[2]));
                adicional = label.equals("") ? (residuo / 2) + 1 : 0;
            }

            if (etiqueta.length() > 0 && etiqueta.justified().equals(DRPdfLabel.JUSTIFIED.DER) && residuo > 0) {
                fillEmpty(residuo + adicional, sb);
            }
            sb.append(label);
            if (etiqueta.length() > 0 && etiqueta.justified().equals(DRPdfLabel.JUSTIFIED.IZQ) && residuo > 0) {
                fillEmpty(residuo + adicional, sb);
            }
            pantagram.add(new Chunk(sb.toString(), font));
        }
    }
    if (pantagram != null) {
        doc.add(pantagram);
    }

}