Example usage for com.itextpdf.text.pdf ColumnText setText

List of usage examples for com.itextpdf.text.pdf ColumnText setText

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf ColumnText setText.

Prototype

public void setText(final Phrase phrase) 

Source Link

Document

Replaces the current text array with this Phrase.

Usage

From source file:com.chaschev.itext.ColumnTextBuilder.java

License:Apache License

public ColumnTextBuilder addTruncatedLine(Chunk chunk, boolean addEllipsis) {
    final float pixelsForEllipsis = 6;

    try {/*  w w  w  .ja va 2 s . c  o m*/
        ColumnText dup = ColumnText.duplicate(columnText);

        final Rectangle oneLineRectangle = new Rectangle(simpleColumnRectangle);

        oneLineRectangle.setTop(dup.getYLine());

        final float fontHeight = calcApproximateFontHeight(chunk.getFont()) * 1.6f;

        oneLineRectangle.setBottom(dup.getYLine() - fontHeight);

        if (addEllipsis) {
            oneLineRectangle.setRight(oneLineRectangle.getRight() - pixelsForEllipsis);
        }

        dup.setSimpleColumn(oneLineRectangle);
        dup.addText(chunk);

        final int status = dup.go();

        float yLine;

        if (addEllipsis && ColumnText.hasMoreText(status)) {
            oneLineRectangle.setLeft(dup.getLastX() + 2);
            oneLineRectangle.setRight(oneLineRectangle.getRight() + pixelsForEllipsis * 2);

            dup = ColumnText.duplicate(dup);

            dup.setSimpleColumn(oneLineRectangle);

            final Chunk ellipses = new Chunk("...\n", chunk.getFont());

            dup.setText(new Phrase(ellipses));
            dup.go();
            yLine = dup.getYLine();
        } else {
            yLine = dup.getYLine();
        }

        setYLine(yLine);

        return this;

    } catch (DocumentException e) {
        throw Exceptions.runtime(e);
    }
}

From source file:com.ideationdesignservices.txtbook.pdf.TxtBookPdf.java

public void doAddNextConversation(Document document, Cursor cursor, ColumnText ct, String senderString,
        String contentString, Bitmap contentImage, Boolean isVideo, Boolean isMe) {
    float[][] COLUMNS;
    if (COLUMNS_REG[0][0] == Txtbook.leftMargin(this.writer, document, this.settings.addFrontCover)) {
        COLUMNS = COLUMNS_REG;/*from www. j a va2s  . c  o  m*/
    } else {
        COLUMNS = COLUMNS_ALT;
    }
    String dateString = PdfObject.NOTHING;
    if (this.settings.useTimestamps.booleanValue()) {
        Long date = Long.valueOf(cursor.getLong(cursor.getColumnIndex("normalized_date")));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy h:mm a", Locale.US);
        simpleDateFormat.setTimeZone(TimeZone.getDefault());
        dateString = simpleDateFormat.format(new Date(date.longValue()));
    }
    try {
        this.currentY = ct.getYLine();
        addConversationPart(ct, this.currentColumn, dateString, senderString, contentString, contentImage,
                isVideo, isMe);
        if (ColumnText.hasMoreText(ct.go(true))) {
            this.currentColumn = (this.currentColumn + 1) % 2;
            if (this.currentColumn == 0) {
                document.newPage();
                if (COLUMNS_REG[0][0] == Txtbook.leftMargin(this.writer, document,
                        this.settings.addFrontCover)) {
                    COLUMNS = COLUMNS_REG;
                } else {
                    COLUMNS = COLUMNS_ALT;
                }
            }
            ct.setSimpleColumn(COLUMNS[this.currentColumn][0], COLUMNS[this.currentColumn][1],
                    COLUMNS[this.currentColumn][2], COLUMNS[this.currentColumn][3]);
            this.currentY = COLUMNS[this.currentColumn][3];
        }
        ct.setYLine(this.currentY);
        ct.setText(null);
        float width = addConversationPart(ct, this.currentColumn, dateString, senderString, contentString,
                contentImage, isVideo, isMe);
        int status = ct.go(false);
        Document document2 = document;
        ColumnText columnText = ct;
        addConversationBackground(document2, columnText, this.currentColumn, this.currentY, width,
                this.currentY - ct.getYLine(), isMe);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:eyeofthetiger.utils.PDFDossardGenerator.java

public void createPdf(List<Participant> participants, OutputStream out) throws IOException, DocumentException {
    sortParticipants(participants);/* w  w  w. ja v  a 2 s  . c om*/

    Document document = new Document(PageSize.A4.rotate());
    float margin = CentimeterToUserSpace(marginCm);
    document.setMargins(margin, margin, margin, margin);
    PdfWriter writer = PdfWriter.getInstance(document, out);
    document.open();
    PdfContentByte cb = writer.getDirectContent();

    PdfReader pdfBackgroundReader = null;
    PdfImportedPage backgroundPage = null;
    if (pdfBackground != null && (new File(pdfBackground)).exists() && (new File(pdfBackground)).isFile()) {
        pdfBackgroundReader = new PdfReader(pdfBackground);
        backgroundPage = writer.getImportedPage(pdfBackgroundReader, 1);
    }

    float documentTop = document.top();
    float documentBottom = document.bottom();
    float documentHeight = documentTop - documentBottom;
    float left = document.left();
    float right = document.right();
    float width = right - left;
    float height = documentTop - documentBottom;

    //cb.rectangle(left, documentBottom, width, documentHeight);
    //cb.stroke();

    boolean logoLeftExist = (new File(logoLeft)).exists() && (new File(logoLeft)).isFile();
    boolean logoRightExist = (new File(logoRight)).exists() && (new File(logoRight)).isFile();

    float imgLeftRight = left;
    float imgLeftBottom = documentTop;
    float imgRightLeft = right;
    float imgRighBottom = documentTop;
    Image imgLeft = null;
    Image imgRight = null;
    if (exportLogos) {
        if (logoLeftExist) {
            imgLeft = Image.getInstance(logoLeft);
            float h = imgLeft.getHeight();
            float w = imgLeft.getWidth();
            float nw = width * logoLeftWidth;
            float nh = (h / w) * nw;
            imgLeft.scaleAbsolute(nw, nh);
            //img.scaleAbsoluteHeight(img.getScaledWidth() / xyRatio);
            imgLeft.setAbsolutePosition(left, documentTop - imgLeft.getScaledHeight());
            //cb.addImage(img);   

            imgLeftRight = imgLeft.getAbsoluteX() + imgLeft.getScaledWidth();
            imgLeftBottom = imgLeft.getAbsoluteY();
        }

        if (logoRightExist) {
            imgRight = Image.getInstance(logoRight);
            float h = imgRight.getHeight();
            float w = imgRight.getWidth();
            float nw = width * logoRightWidth;
            float nh = (h / w) * nw;
            imgRight.scaleAbsolute(nw, nh);
            imgRight.setAbsolutePosition(right - imgRight.getScaledWidth(),
                    documentTop - imgRight.getScaledHeight());
            //cb.addImage(imgRight);
            imgRightLeft = imgRight.getAbsoluteX();
            imgRighBottom = imgRight.getAbsoluteY();
        }

    }

    float nameHeightPercent = 0.35f;
    float groupHeightPercent = 0.25f;

    float nameTop = documentTop;
    float nameBottom = nameTop;
    if (exportName) {
        nameBottom = nameTop - (documentHeight * nameHeightPercent);
    }
    float groupeTop = nameBottom;
    float groupeBottom = nameBottom;
    if (exportGroup) {
        groupeBottom = groupeTop - (documentHeight * groupHeightPercent);
    }
    float barcodeTop = groupeBottom;
    float barcodeBottom = documentBottom;

    ColumnText columnText;

    for (Participant participant : participants) {

        if (backgroundPage != null) {
            //cb.addTemplate(backgroundPage, 1f, 0, 0, 1, 0, 0); //TODO
            cb.addTemplate(backgroundPage, 0, 0);
        }

        float nameFontSize = 65f;
        float groupFontSize = 45f;
        float renseignementFontSize = 35f;

        if (imgLeft != null) {
            cb.addImage(imgLeft);
        }
        if (imgRight != null) {
            cb.addImage(imgRight);
        }

        if (exportName) {
            columnText = new ColumnText(cb);
            columnText.setAlignment(Rectangle.ALIGN_CENTER);

            if (imgLeftRight != -1 && imgLeftBottom != -1) {
                float[] leftBorder = null;
                if (imgLeftBottom < nameBottom) {
                    leftBorder = new float[] { imgLeftRight, nameTop, imgLeftRight, nameBottom, left,
                            nameBottom };
                } else {
                    leftBorder = new float[] { imgLeftRight, nameTop, imgLeftRight, imgLeftBottom, left,
                            imgLeftBottom, left, nameBottom };
                }

                float[] rightBorder = null;
                if (imgRighBottom < nameBottom) {
                    rightBorder = new float[] { imgRightLeft, nameTop, imgRightLeft, nameBottom, right,
                            nameBottom };
                } else {
                    rightBorder = new float[] { imgRightLeft, nameTop, imgRightLeft, imgRighBottom, right,
                            imgRighBottom, right, nameBottom };
                }

                columnText.setColumns(leftBorder, rightBorder);
            } else {
                columnText.setSimpleColumn(left, nameTop, right, nameBottom);
            }
            //cb.rectangle(left, nameBottom, width, (nameTop - nameBottom));
            //cb.stroke();

            columnText.setExtraParagraphSpace(0f);
            columnText.setAdjustFirstLine(false);
            columnText.setIndent(0);

            String txt = participant.getNom().toUpperCase() + " " + participant.getPrenom();

            float previousPos = columnText.getYLine();
            columnText.setLeading(nameFontSize);
            columnText.setText(createCleanPhrase(txt, nameFontSize, true));
            while (nameFontSize > 1 && ColumnText.hasMoreText(columnText.go(true))) {
                nameFontSize = nameFontSize - 0.5f;
                columnText.setLeading(nameFontSize);
                columnText.setText(createCleanPhrase(txt, nameFontSize, true));
                columnText.setYLine(previousPos);
            }

            columnText.setLeading(nameFontSize);
            columnText.setText(createCleanPhrase(txt, nameFontSize, true));
            columnText.setYLine(previousPos);
            columnText.go(false);

        }

        if (exportGroup) {
            columnText = new ColumnText(cb);
            columnText.setAlignment(Rectangle.ALIGN_CENTER);

            columnText.setSimpleColumn(document.left(), groupeTop, document.right(), groupeBottom);
            float groupeHeight = groupeTop - groupeBottom;
            //cb.rectangle(document.left(), groupeTop - groupeHeight, document.right() - document.left(), groupeHeight);
            //cb.stroke();

            columnText.setExtraParagraphSpace(0f);
            columnText.setAdjustFirstLine(false);
            columnText.setIndent(0);
            columnText.setFollowingIndent(0);

            String txt1 = participant.getGroupe();
            String txt2 = exportRenseignement ? "\n" + participant.getRenseignements() : null;

            float previousPos = columnText.getYLine();
            columnText.setText(null);
            columnText.setLeading(groupFontSize);
            columnText.addText(createCleanPhrase(txt1, groupFontSize, true));
            columnText.addText(createCleanPhrase(txt2, renseignementFontSize, false));
            while (groupFontSize > 1 && ColumnText.hasMoreText(columnText.go(true))) {
                groupFontSize = groupFontSize - 0.5f;
                renseignementFontSize = renseignementFontSize - 0.5f;
                columnText.setText(null);
                columnText.setLeading(groupFontSize);
                columnText.addText(createCleanPhrase(txt1, groupFontSize, true));
                columnText.addText(createCleanPhrase(txt2, renseignementFontSize, false));
                columnText.setYLine(previousPos);
            }

            columnText.setText(null);
            columnText.setLeading(groupFontSize);
            columnText.addText(createCleanPhrase(txt1, groupFontSize, true));
            columnText.addText(createCleanPhrase(txt2, renseignementFontSize, false));
            columnText.setYLine(previousPos);
            columnText.go(false);
        }

        {
            columnText = new ColumnText(cb);

            float topMargin = 12f;
            columnText.setSimpleColumn(left, barcodeTop - topMargin, right, barcodeBottom);
            float barcodeHeight = (barcodeTop - topMargin) - barcodeBottom;
            //cb.rectangle(left, barcodeTop - barcodeHeight, width, barcodeHeight);
            //cb.stroke();

            columnText.setExtraParagraphSpace(0f);
            columnText.setAdjustFirstLine(false);
            columnText.setIndent(0);

            float previousPos = columnText.getYLine();
            columnText.setText(null);
            columnText.addElement(createCleanBarcode(cb, participant.getNumero(), width, barcodeHeight));
            columnText.go(false);
        }

        document.newPage();

    }

    document.close();

    if (pdfBackgroundReader != null) {
        pdfBackgroundReader.close();
    }
}

From source file:mkl.testarea.itext5.pdfcleanup.StrictPdfCleanUpProcessor.java

License:Open Source License

private void drawOverlayText(PdfContentByte canvas, List<Rectangle> textRectangles, PdfString overlayText,
        PdfString otDA, PdfNumber otQ, PdfBoolean otRepeat) throws DocumentException, IOException {
    ColumnText ct = new ColumnText(canvas);
    ct.setLeading(0, 1.2F);/*from  w  ww.j a  v  a 2  s  .c  om*/
    ct.setUseAscender(true);

    String otStr = overlayText.toUnicodeString();

    canvas.saveState();
    Map<String, List> parsedDA = parseDAParam(otDA);

    Font font = null;

    if (parsedDA.containsKey(STROKE_COLOR)) {
        List strokeColorArgs = parsedDA.get(STROKE_COLOR);
        setStrokeColor(canvas, strokeColorArgs);
    }

    if (parsedDA.containsKey(FILL_COLOR)) {
        List fillColorArgs = parsedDA.get(FILL_COLOR);
        setFillColor(canvas, fillColorArgs);
    }

    if (parsedDA.containsKey("Tf")) {
        List tfArgs = parsedDA.get("Tf");
        font = retrieveFontFromAcroForm((PdfName) tfArgs.get(0), (PdfNumber) tfArgs.get(1));
    }

    for (Rectangle textRect : textRectangles) {
        ct.setSimpleColumn(textRect);

        if (otQ != null) {
            ct.setAlignment(otQ.intValue());
        }

        Phrase otPhrase;

        if (font != null) {
            otPhrase = new Phrase(otStr, font);
        } else {
            otPhrase = new Phrase(otStr);
        }

        float y = ct.getYLine();

        if (otRepeat != null && otRepeat.booleanValue()) {
            int status = ct.go(true);

            while (!ColumnText.hasMoreText(status)) {
                otPhrase.add(otStr);
                ct.setText(otPhrase);
                ct.setYLine(y);
                status = ct.go(true);
            }
        }

        ct.setText(otPhrase);
        ct.setYLine(y);
        ct.go();
    }

    canvas.restoreState();
}

From source file:nz.ac.waikato.cms.doc.SimplePDFOverlay.java

License:Open Source License

/**
 * Applies the instructions to the input PDF.
 *
 * @return      null if successful, otherwise error message
 *///from w w w  .  j a  v a 2s.  c  o m
public String execute() {
    String result;
    String line;
    BufferedReader breader;
    FileReader freader;
    int i;
    int lineNo;
    String units;
    int pageNo;
    PdfReader reader;
    PdfStamper stamper;
    PdfContentByte cb;
    ColumnText ct;
    Font font;
    String[] parts;
    StringBuilder text;

    result = null;

    freader = null;
    breader = null;
    try {
        reader = new PdfReader(new FileInputStream(m_Pdf.getAbsolutePath()));
        stamper = new PdfStamper(reader, new FileOutputStream(m_Output.getAbsolutePath()));
        freader = new FileReader(m_Instructions);
        breader = new BufferedReader(freader);
        lineNo = 0;
        units = "pt";
        pageNo = 1;
        cb = stamper.getOverContent(pageNo);
        font = null;
        while ((line = breader.readLine()) != null) {
            lineNo++;
            if (line.trim().startsWith(PREFIX_COMMENT))
                continue;
            if (line.trim().length() == 0)
                continue;
            if (line.startsWith(PREFIX_UNITS)) {
                units = line.substring(PREFIX_UNITS.length()).trim().toLowerCase();
            } else if (line.startsWith(PREFIX_PAGE)) {
                pageNo = Integer.parseInt(line.substring(PREFIX_PAGE.length()).trim());
                cb = stamper.getOverContent(pageNo);
            } else if (line.startsWith(PREFIX_FONT)) {
                parts = line.substring(PREFIX_FONT.length()).trim().split(" ");
                if (parts.length == 3)
                    font = FontFactory.getFont(parts[0], Float.parseFloat(parts[1]),
                            new BaseColor(parseColor(parts[2]).getRGB()));
                else
                    m_Logger.warning("Font instruction not in expected format (" + FORMAT_FONT + "):\n" + line);
            } else if (line.startsWith(PREFIX_TEXT)) {
                parts = line.substring(PREFIX_TEXT.length()).trim().split(" ");
                if (parts.length >= 7) {
                    ct = new ColumnText(cb);
                    ct.setSimpleColumn(parseLocation(parts[0], reader.getPageSize(pageNo).getWidth(), units), // llx
                            parseLocation(parts[1], reader.getPageSize(pageNo).getHeight(), units), // lly
                            parseLocation(parts[2], reader.getPageSize(pageNo).getWidth(), units), // urx
                            parseLocation(parts[3], reader.getPageSize(pageNo).getHeight(), units), // ury
                            Float.parseFloat(parts[4]), // leading
                            parseAlignment(parts[5])); // alignment
                    text = new StringBuilder();
                    for (i = 6; i < parts.length; i++) {
                        if (text.length() > 0)
                            text.append(" ");
                        text.append(parts[i]);
                    }
                    if (font == null)
                        ct.setText(new Phrase(text.toString()));
                    else
                        ct.setText(new Phrase(text.toString(), font));
                    ct.go();
                } else {
                    m_Logger.warning("Text instruction not in expected format (" + FORMAT_TEXT + "):\n" + line);
                }
            } else if (line.startsWith(PREFIX_LINE)) {
                parts = line.substring(PREFIX_LINE.length()).trim().split(" ");
                if (parts.length >= 6) {
                    cb.saveState();
                    cb.setLineWidth(Float.parseFloat(parts[4])); // line width
                    cb.setColorStroke(new BaseColor(parseColor(parts[5]).getRGB())); // color
                    cb.moveTo(parseLocation(parts[0], reader.getPageSize(pageNo).getWidth(), units), // x
                            parseLocation(parts[1], reader.getPageSize(pageNo).getWidth(), units)); // y
                    cb.lineTo(parseLocation(parts[2], reader.getPageSize(pageNo).getWidth(), units), // w
                            parseLocation(parts[3], reader.getPageSize(pageNo).getWidth(), units)); // h
                    cb.stroke();
                    cb.restoreState();
                } else {
                    m_Logger.warning("Line instruction not in expected format (" + FORMAT_LINE + "):\n" + line);
                }
            } else if (line.startsWith(PREFIX_RECT)) {
                parts = line.substring(PREFIX_RECT.length()).trim().split(" ");
                if (parts.length >= 6) {
                    cb.saveState();
                    cb.rectangle(parseLocation(parts[0], reader.getPageSize(pageNo).getWidth(), units), // x
                            parseLocation(parts[1], reader.getPageSize(pageNo).getWidth(), units), // y
                            parseLocation(parts[2], reader.getPageSize(pageNo).getWidth(), units), // w
                            parseLocation(parts[3], reader.getPageSize(pageNo).getWidth(), units) // h
                    );
                    cb.setLineWidth(Float.parseFloat(parts[4])); // line width
                    cb.setColorStroke(new BaseColor(parseColor(parts[5]).getRGB())); // stroke
                    if (parts.length >= 7) {
                        cb.setColorFill(new BaseColor(parseColor(parts[6]).getRGB())); // fill
                        cb.fillStroke();
                    } else {
                        cb.stroke();
                    }
                    cb.restoreState();
                } else {
                    m_Logger.warning(
                            "Rectangle instruction not in expected format (" + FORMAT_RECT + "):\n" + line);
                }
            } else if (line.startsWith(PREFIX_OVAL)) {
                parts = line.substring(PREFIX_OVAL.length()).trim().split(" ");
                if (parts.length >= 6) {
                    cb.saveState();
                    cb.ellipse(parseLocation(parts[0], reader.getPageSize(pageNo).getWidth(), units), // x1
                            parseLocation(parts[1], reader.getPageSize(pageNo).getWidth(), units), // y1
                            parseLocation(parts[2], reader.getPageSize(pageNo).getWidth(), units), // x2
                            parseLocation(parts[3], reader.getPageSize(pageNo).getWidth(), units) // y2
                    );
                    cb.setLineWidth(Float.parseFloat(parts[4])); // line width
                    cb.setColorStroke(new BaseColor(parseColor(parts[5]).getRGB())); // stroke
                    if (parts.length >= 7) {
                        cb.setColorFill(new BaseColor(parseColor(parts[6]).getRGB())); // fill
                        cb.fillStroke();
                    } else {
                        cb.stroke();
                    }
                    cb.restoreState();
                } else {
                    m_Logger.warning("Oval instruction not in expected format (" + FORMAT_OVAL + "):\n" + line);
                }
            } else {
                m_Logger.warning("Unknown command on line #" + lineNo + ":\n" + line);
            }
        }
        stamper.close();
    } catch (Exception e) {
        result = "Failed to process!\n" + Utils.throwableToString(e);
    } finally {
        FileUtils.closeQuietly(breader);
        FileUtils.closeQuietly(freader);
    }

    return result;
}