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) 

Source Link

Document

Creates a separator Chunk.

Usage

From source file:org.kuali.ole.module.purap.pdf.PurchaseOrderPdf.java

License:Educational Community License

/**
 * Overrides the method in PdfPageEventHelper from itext to create and set the headerTable and set its logo image if
 * there is a logoImage to be used, creates and sets the nestedHeaderTable and its content.
 *
 * @param writer   The PdfWriter for this document.
 * @param document The document./*from w  ww.j  ava  2  s  .co m*/
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onOpenDocument(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */
@Override
public void onOpenDocument(PdfWriter writer, Document document) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("onOpenDocument() started. isRetransmit is " + isRetransmit);
    }
    try {
        float[] headerWidths = { 0.20f, 0.80f };
        headerTable = new PdfPTable(headerWidths);
        headerTable.setWidthPercentage(100);
        headerTable.setHorizontalAlignment(Element.ALIGN_CENTER);
        headerTable.setSplitLate(false);
        headerTable.getDefaultCell().setBorderWidth(0);
        headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        headerTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER);

        Image logo = null;
        if (StringUtils.isNotBlank(logoImage)) {
            LOG.info(" Logo Image in open document :" + logoImage);
            try {
                logo = Image.getInstance(logoImage);
            } catch (FileNotFoundException e) {
                LOG.info("The logo image [" + logoImage
                        + "] is not available.  Defaulting to the default image.");
            }
        }

        if (logo == null) {
            // if we don't use images
            headerTable.addCell(new Phrase(new Chunk("")));
        } else {
            logo.scalePercent(3, 3);
            headerTable.addCell(new Phrase(new Chunk(logo, 0, 0)));
        }
        // Nested table for titles, etc.
        float[] nestedHeaderWidths = { 0.70f, 0.30f };
        nestedHeaderTable = new PdfPTable(nestedHeaderWidths);
        nestedHeaderTable.setSplitLate(false);
        PdfPCell cell;

        // New nestedHeaderTable row
        cell = new PdfPCell(new Paragraph(po.getBillingName(), ver_15_normal));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidth(0);
        nestedHeaderTable.addCell(cell);
        cell = new PdfPCell(new Paragraph(" ", ver_15_normal));
        cell.setBorderWidth(0);
        nestedHeaderTable.addCell(cell);
        // New nestedHeaderTable row
        if (isRetransmit) {
            cell = new PdfPCell(new Paragraph(po.getRetransmitHeader(), ver_15_normal));
        } else {
            cell = new PdfPCell(new Paragraph("PURCHASE ORDER", ver_15_normal));
        }
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidth(0);
        nestedHeaderTable.addCell(cell);
        Paragraph p = new Paragraph();
        p.add(new Chunk("PO Number: ", ver_11_normal));
        p.add(new Chunk(po.getPurapDocumentIdentifier().toString(), cour_7_normal));

        cell = new PdfPCell(p);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorderWidth(0);
        nestedHeaderTable.addCell(cell);
        if (!po.getPurchaseOrderAutomaticIndicator()) { // Contract manager name goes on non-APOs.
            // New nestedHeaderTable row, spans both columns
            p = new Paragraph();
            p.add(new Chunk("Contract Manager: ", ver_11_normal));
            p.add(new Chunk(po.getContractManager().getContractManagerName(), cour_7_normal));
            cell = new PdfPCell(p);
            cell.setColspan(2);
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setBorderWidth(0);
            nestedHeaderTable.addCell(cell);
        }
        // Add the nestedHeaderTable to the headerTable
        cell = new PdfPCell(nestedHeaderTable);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidth(0);
        headerTable.addCell(cell);

        // initialization of the template
        tpl = writer.getDirectContent().createTemplate(100, 100);
        // initialization of the font
        helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:org.odftoolkit.odfdom.converter.internal.itext.stylable.StylableHeading.java

License:Open Source License

@Override
public void applyStyles(Style style) {
    super.applyStyles(style);

    // compute numbering
    StringBuilder sbuf = new StringBuilder();
    for (Integer nr : headingNumbering) {
        sbuf.append(nr.toString());//  w w  w  .ja  v a  2  s .co  m
        sbuf.append(".");
    }
    sbuf.append(" ");
    addElement(new Chunk(sbuf.toString()));
}

From source file:org.odftoolkit.odfdom.converter.internal.itext.stylable.StylableList.java

License:Open Source License

public void applyStyles(Style style) {
    this.lastStyleApplied = style;

    Map<Integer, StyleListProperties> listPropertiesMap = style.getListPropertiesMap();
    if (listPropertiesMap != null) {
        StyleListProperties listProperties = null;
        for (int i = listLevel; i >= 0 && listProperties == null; i--) {
            // find style for current or nearest lower list level
            listProperties = listPropertiesMap.get(i);
        }//from   w ww . j  a  v  a 2 s  .  c  om
        if (listProperties != null) {
            String bulletChar = listProperties.getBulletChar();
            if (bulletChar != null) {
                // list item label is a char
                Chunk symbol = new Chunk(bulletChar);

                StyleTextProperties textProperties = style.getTextProperties();
                if (textProperties != null) {
                    Font font = textProperties.getFont();
                    if (font != null) {
                        symbol.setFont(font);
                    }
                }

                super.setListSymbol(symbol);
            }

            Image image = listProperties.getImage();
            if (image != null) {
                // list item label is an image
                Float width = listProperties.getWidth();
                if (width != null) {
                    image.scaleAbsoluteWidth(width);
                }

                Float height = listProperties.getHeight();
                if (height != null) {
                    image.scaleAbsoluteHeight(height);
                }

                super.setListSymbol(new Chunk(image, 0.0f, 0.0f));
            }

            if (bulletChar == null && image == null) {
                // list item label is a number
                Chunk symbol = new Chunk("");

                StyleTextProperties textProperties = style.getTextProperties();
                if (textProperties != null) {
                    Font font = textProperties.getFont();
                    if (font != null) {
                        symbol.setFont(font);
                    }
                }

                Integer startValue = listProperties.getStartValue();
                if (startValue != null) {
                    super.setFirst(startValue);
                }

                String numPrefix = listProperties.getNumPrefix();
                if (numPrefix != null) {
                    super.setPreSymbol(numPrefix);
                    symbol = new Chunk(numPrefix, symbol.getFont());
                }

                String numSuffix = listProperties.getNumSuffix();
                if (numSuffix != null) {
                    super.setPostSymbol(numSuffix);
                    symbol.append(numSuffix);
                }

                StyleNumFormat numFormat = listProperties.getNumFormat();
                if (numFormat != null) {
                    super.setNumbered(true);
                    super.setLettered(numFormat.isAlphabetical());
                    this.romanNumbered = numFormat.isRoman();
                    super.setLowercase(numFormat.isLowercase());
                }

                super.setListSymbol(symbol);
            }

            Float marginLeft = listProperties.getMarginLeft();
            Float textIndent = listProperties.getTextIndent();
            if (marginLeft != null && textIndent != null) {
                super.setIndentationLeft(Math.max(marginLeft + textIndent, 0.0f));
                super.setSymbolIndent(Math.max(-textIndent, 0.0f));
                super.setAutoindent(false);
            }
        }
    }
}

From source file:org.odftoolkit.odfdom.converter.internal.itext.stylable.StylableListItem.java

License:Open Source License

@Override
public void setListSymbol(Chunk symbol) {
    Chunk chunk = new Chunk(symbol);
    // adjust chunk attributes like text rise
    // use StylableParagraph mechanism
    StylableParagraph p = new StylableParagraph(null, null);
    p.setFont(chunk.getFont());//from   w w w  .  j av  a  2 s  . co  m
    p.addElement(chunk);
    p.getElement(); // post-processing here
    chunk = (Chunk) p.getChunks().get(0);

    super.setListSymbol(chunk);
}

From source file:org.odftoolkit.odfdom.converter.internal.itext.stylable.StylableParagraph.java

License:Open Source License

@SuppressWarnings("unchecked")
public Element getElement() {
    if (!elementPostProcessed) {
        elementPostProcessed = true;//w  ww .j  av  a 2  s . c om

        // add space if this paragraph is empty
        // otherwise it's height will be zero
        boolean empty = true;
        ArrayList<Chunk> chunks = getChunks();
        for (Chunk chunk : chunks) {
            if (chunk.getImage() == null && chunk.getContent() != null && chunk.getContent().length() > 0) {
                empty = false;
                break;
            }
        }
        if (empty) {
            super.add(new Chunk("\u00A0")); // non breaking space
        }

        // adjust line height and baseline
        if (font != null && font.getBaseFont() != null) {
            // iText and open office computes proportional line height differently
            // [iText] line height = coefficient * font size
            // [open office] line height = coefficient * (font ascender + font descender + font extra margin)
            // we have to increase paragraph line height to generate pdf similar to open office document
            // this algorithm may be inaccurate if fonts with different multipliers are used in this paragraph
            float size = font.getSize();
            float ascender = font.getBaseFont().getFontDescriptor(BaseFont.AWT_ASCENT, size);
            float descender = -font.getBaseFont().getFontDescriptor(BaseFont.AWT_DESCENT, size); // negative value
            float margin = font.getBaseFont().getFontDescriptor(BaseFont.AWT_LEADING, size);
            float multiplier = (ascender + descender + margin) / size;
            if (multipliedLeading > 0.0f) {
                setMultipliedLeading(getMultipliedLeading() * multiplier);
            }

            // iText seems to output text with baseline lower than open office
            // we raise all paragraph text by some amount
            // again this may be inaccurate if fonts with different size are used in this paragraph
            float itextdescender = -font.getBaseFont().getFontDescriptor(BaseFont.DESCENT, size); // negative
            float textRise = itextdescender + getTotalLeading() - font.getSize() * multiplier;
            chunks = getChunks();
            for (Chunk chunk : chunks) {
                Font f = chunk.getFont();
                if (f != null) {
                    // have to raise underline and strikethru as well
                    float s = f.getSize();
                    if (f.isUnderlined()) {
                        f.setStyle(f.getStyle() & ~Font.UNDERLINE);
                        chunk.setUnderline(s * 1 / 17, s * -1 / 7 + textRise);
                    }
                    if (f.isStrikethru()) {
                        f.setStyle(f.getStyle() & ~Font.STRIKETHRU);
                        chunk.setUnderline(s * 1 / 17, s * 1 / 4 + textRise);
                    }
                }
                chunk.setTextRise(chunk.getTextRise() + textRise);
            }
        }

        // wrap this paragraph into a table if necessary
        if (wrapperCell != null) {
            // background color or borders were set
            wrapperCell.addElement(this);
            wrapperTable = createTable(wrapperCell);
            if (getIndentationLeft() > 0.0f || getIndentationRight() > 0.0f || getSpacingBefore() > 0.0f
                    || getSpacingAfter() > 0.0f) {
                // margins were set, have to wrap the cell again
                PdfPCell outerCell = createCell();
                outerCell.setPaddingLeft(getIndentationLeft());
                setIndentationLeft(0.0f);
                outerCell.setPaddingRight(getIndentationRight());
                setIndentationRight(0.0f);
                outerCell.setPaddingTop(getSpacingBefore());
                setSpacingBefore(0.0f);
                outerCell.setPaddingBottom(getSpacingAfter());
                setSpacingAfter(0.0f);
                outerCell.addElement(wrapperTable);
                wrapperTable = createTable(outerCell);
            }
        }
    }
    return wrapperTable != null ? wrapperTable : this;
}

From source file:org.ofbiz.content.survey.PdfSurveyServices.java

License:Apache License

/**
 *///w w w .ja v a  2s  .  c o m
public static Map<String, Object> buildPdfFromSurveyResponse(DispatchContext dctx,
        Map<String, ? extends Object> rcontext) {
    Map<String, Object> context = UtilMisc.makeMapWritable(rcontext);
    Delegator delegator = dctx.getDelegator();
    //LocalDispatcher dispatcher = dctx.getDispatcher();
    Map<String, Object> results = ServiceUtil.returnSuccess();
    String surveyResponseId = (String) context.get("surveyResponseId");
    String contentId = (String) context.get("contentId");
    String surveyId = null;

    Document document = new Document();
    try {
        if (UtilValidate.isNotEmpty(surveyResponseId)) {
            GenericValue surveyResponse = EntityQuery.use(delegator).from("SurveyResponse")
                    .where("surveyResponseId", surveyResponseId).queryOne();
            if (surveyResponse != null) {
                surveyId = surveyResponse.getString("surveyId");
            }
        }
        if (UtilValidate.isNotEmpty(surveyId) && UtilValidate.isEmpty(contentId)) {
            GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId)
                    .queryOne();
            if (survey != null) {
                String acroFormContentId = survey.getString("acroFormContentId");
                if (UtilValidate.isNotEmpty(acroFormContentId)) {
                    context.put("contentId", acroFormContentId);
                }
            }
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);

        List<GenericValue> responses = EntityQuery.use(delegator).from("SurveyResponseAnswer")
                .where("surveyResponseId", surveyResponseId).queryList();
        for (GenericValue surveyResponseAnswer : responses) {
            String value = null;
            String surveyQuestionId = (String) surveyResponseAnswer.get("surveyQuestionId");
            GenericValue surveyQuestion = EntityQuery.use(delegator).from("SurveyQuestion")
                    .where("surveyQuestionId", surveyQuestionId).queryOne();
            String questionType = surveyQuestion.getString("surveyQuestionTypeId");
            // DEJ20060227 this isn't used, if needed in the future should get from SurveyQuestionAppl.externalFieldRef String fieldName = surveyQuestion.getString("description");
            if ("OPTION".equals(questionType)) {
                value = surveyResponseAnswer.getString("surveyOptionSeqId");
            } else if ("BOOLEAN".equals(questionType)) {
                value = surveyResponseAnswer.getString("booleanResponse");
            } else if ("NUMBER_LONG".equals(questionType) || "NUMBER_CURRENCY".equals(questionType)
                    || "NUMBER_FLOAT".equals(questionType)) {
                Double num = surveyResponseAnswer.getDouble("numericResponse");
                if (num != null) {
                    value = num.toString();
                }
            } else if ("SEPERATOR_LINE".equals(questionType) || "SEPERATOR_TEXT".equals(questionType)) {
                // not really a question; ingore completely
            } else {
                value = surveyResponseAnswer.getString("textResponse");
            }
            Chunk chunk = new Chunk(surveyQuestion.getString("question") + ": " + value);
            Paragraph p = new Paragraph(chunk);
            document.add(p);
        }
        ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray());
        results.put("outByteBuffer", outByteBuffer);
    } catch (GenericEntityException e) {
        System.err.println(e.getMessage());
        results = ServiceUtil.returnError(e.getMessage());
    } catch (DocumentException e) {
        System.err.println(e.getMessage());
        results = ServiceUtil.returnError(e.getMessage());
    }

    return results;
}

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

License:Open Source License

public void printNotes(Collection<CaseManagementNote> notes, boolean compact) throws DocumentException {

    CaseManagementNote note;/*  w ww  .  j  a  v a  2  s. c o  m*/
    Font obsfont = new Font(bf, FONTSIZE, Font.UNDERLINE);
    Paragraph p;
    Phrase phrase;
    Chunk chunk;

    //if( newPage )
    //     document.newPage();
    // else
    //     newPage = true;

    //Print notes
    Iterator<CaseManagementNote> notesIter = notes.iterator();
    while (notesIter.hasNext()) {
        note = notesIter.next();
        p = new Paragraph();
        //p.setSpacingBefore(font.leading(LINESPACING)*2f);
        phrase = new Phrase(LEADING, "", font);

        if (compact) {
            phrase.add(new Chunk(formatter.format(note.getObservation_date()) + ":"));
        } else {
            chunk = new Chunk("Impression/Plan: (" + formatter.format(note.getObservation_date()) + ")\n",
                    obsfont);
            phrase.add(chunk);
        }
        if (compact) {
            phrase.add(note.getNote() + "\n");
        } else {
            phrase.add(note.getNote() + "\n\n");
        }
        p.add(phrase);
        document.add(p);
    }
}

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

License:Open Source License

public void printAllergies(List<Allergy> allergies) throws DocumentException {
    ProviderDao providerDao = (ProviderDao) SpringUtils.getBean("providerDao");

    /*/*from  w  ww.ja va  2 s  .c  om*/
         if( getNewPage() )
    getDocument().newPage();
           else
    setNewPage(true);
    */
    Font obsfont = new Font(getBaseFont(), FONTSIZE, Font.UNDERLINE);

    Paragraph p = new Paragraph();
    p.setAlignment(Paragraph.ALIGN_LEFT);
    Phrase phrase = new Phrase(LEADING, "\n", getFont());
    p.add(phrase);
    phrase = new Phrase(LEADING, "Allergies", obsfont);
    p.add(phrase);
    getDocument().add(p);

    for (Allergy allergy : allergies) {
        p = new Paragraph();
        phrase = new Phrase(LEADING, "", getFont());
        Chunk chunk = new Chunk(allergy.getDescription());
        phrase.add(chunk);
        p.add(phrase);
        getDocument().add(p);
    }
    getDocument().add(new Phrase("\n", getFont()));
}

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

License:Open Source License

public void printPreventions() throws DocumentException {
    List<Prevention> preventions = preventionDao.findNotDeletedByDemographicId(demographic.getDemographicNo());

    if (preventions.size() == 0) {
        return;/*from w w  w  . j a  va2s .c om*/
    }

    Paragraph p = new Paragraph();
    Font obsfont = new Font(bf, FONTSIZE, Font.UNDERLINE);
    Phrase phrase = new Phrase(LEADING, "", obsfont);
    p.setAlignment(Paragraph.ALIGN_LEFT);
    phrase.add("Preventions");
    p.add(phrase);
    document.add(p);

    for (Prevention prevention : preventions) {
        String type = prevention.getPreventionType();
        Date date = prevention.getPreventionDate();

        p = new Paragraph();
        phrase = new Phrase(LEADING, "", getFont());
        Chunk chunk = new Chunk(type + " " + formatter.format(date) + "\n");
        phrase.add(chunk);
        p.add(phrase);
        getDocument().add(p);
    }

}

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

License:Open Source License

public void printTicklers() throws DocumentException {
    TicklerDAO ticklerDao = (TicklerDAO) SpringUtils.getBean("ticklerDAOT");
    CustomFilter filter = new CustomFilter();
    filter.setDemographic_no(String.valueOf(demographic.getDemographicNo()));
    List<Tickler> ticklers = ticklerDao.getTicklers(filter);

    if (ticklers.size() == 0) {
        return;/*from w  w w  . j ava  2s  .c o m*/
    }

    Paragraph p = new Paragraph();
    Font obsfont = new Font(bf, FONTSIZE, Font.UNDERLINE);
    Phrase phrase = new Phrase(LEADING, "", obsfont);
    p.setAlignment(Paragraph.ALIGN_LEFT);
    phrase.add("Ticklers");
    p.add(phrase);
    document.add(p);

    for (Tickler tickler : ticklers) {
        String providerName = tickler.getProvider().getFormattedName();
        String assigneeName = tickler.getAssignee().getFormattedName();
        String serviceDate = tickler.getServiceDate();
        String priority = tickler.getPriority();
        char status = tickler.getStatus();
        String message = tickler.getMessage();

        p = new Paragraph();
        phrase = new Phrase(LEADING, "", getFont());
        Chunk chunk = new Chunk("Provider:" + providerName + "\n");
        phrase.add(chunk);
        chunk = new Chunk("Assignee:" + assigneeName + "\n");
        phrase.add(chunk);
        chunk = new Chunk("Service Date:" + serviceDate + "\n");
        phrase.add(chunk);
        chunk = new Chunk("Priority:" + priority + "\n");
        phrase.add(chunk);
        chunk = new Chunk("Status:" + status + "\n");
        phrase.add(chunk);
        chunk = new Chunk("Message:" + message + "\n\n");
        phrase.add(chunk);

        p.add(phrase);
        getDocument().add(p);
    }

}