Example usage for com.lowagie.text Paragraph add

List of usage examples for com.lowagie.text Paragraph add

Introduction

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

Prototype

public boolean add(Object o) 

Source Link

Document

Adds an Object to the Paragraph.

Usage

From source file:net.scs.reader.virtualprinter.PdfPrinter.java

License:Open Source License

private void printCurrentPage() {
    // first create a new page
    pdfdoc.newPage();/*from w  ww  .  j a  v  a 2 s.  c  om*/
    pdfdoc.setPageCount(currentPage++);

    boolean emptypage = true;
    // second write the content
    for (VirtualLine currentLine : getLinesOnCurrentPage()) {
        emptypage = false;
        Paragraph p = new Paragraph();
        p.setSpacingAfter(0.0f);
        p.setSpacingBefore(0.0f);
        p.setExtraParagraphSpace(0.0f);
        p.setLeading(leading);
        currentLine.position(0);
        StringBuilder sb = new StringBuilder();
        boolean isbold = false;
        if (!currentLine.hasNext()) {
            // empty lines need at least one character
            sb.append(printerConfig.NL);
        }
        while (currentLine.hasNext()) {
            final EnhancedCharacter echar = currentLine.next();
            // Workaround, replace 'normal spaces' with 'non-breaking-spaces'
            // <a href="http://sourceforge.net/tracker/?func=detail&aid=2866002&group_id=15255&atid=315255">
            //     Multiline paragraph, leading spaces are ignored problem - ID: 2866002
            // </a>
            char c = (echar.getChar() == SP) ? NBSP : echar.getChar();
            if (isbold == echar.isBold()) {
                sb.append(c);
            } else {
                p.add(new Chunk(sb.toString(), (isbold) ? fontbold : font));
                sb = new StringBuilder();
                sb.append(c);
                isbold = !isbold; // flip it
            }
        }
        p.add(new Chunk(sb.toString(), (isbold) ? fontbold : font));
        try {
            pdfdoc.add(p);
        } catch (DocumentException e) {
            // transform into RuntimeException
            throw new RuntimeException(e);
        }
    }
    if (emptypage) {
        try {
            pdfdoc.add(new Paragraph(Character.toString(NBSP)));
        } catch (DocumentException e) {
            // transform into RuntimeException
            throw new RuntimeException(e);
        }
    }
}

From source file:nl.knaw.dans.common.lang.pdf.ExtendedHtmlWorker.java

License:Apache License

public void endElement(String tag) {
    if (!tagsSupported.containsKey(tag))
        return;/*from   ww  w  . ja  va  2 s  .  c  om*/
    try {
        String follow = (String) FactoryProperties.followTags.get(tag);
        if (follow != null) {
            cprops.removeChain(follow);
            return;
        }
        if (tag.equals("font") || tag.equals("span")) {
            cprops.removeChain(tag);
            return;
        }
        if (tag.equals("a")) {
            if (currentParagraph == null)
                currentParagraph = new Paragraph();
            ALink i = null;
            boolean skip = false;
            if (interfaceProps != null) {
                i = (ALink) interfaceProps.get("alink_interface");
                if (i != null)
                    skip = i.process(currentParagraph, cprops);
            }
            if (!skip) {
                String href = cprops.getProperty("href");
                if (href != null) {
                    ArrayList chunks = currentParagraph.getChunks();
                    for (int k = 0; k < chunks.size(); ++k) {
                        Chunk ck = (Chunk) chunks.get(k);
                        ck.setAnchor(href);
                    }
                }
            }
            Paragraph tmp = (Paragraph) stack.pop();
            Phrase tmp2 = new Phrase();
            tmp2.add(currentParagraph);
            tmp.add(tmp2);
            currentParagraph = tmp;
            cprops.removeChain("a");
            return;
        }
        if (tag.equals("br")) {
            return;
        }
        if (currentParagraph != null) {
            if (stack.empty())
                document.add(currentParagraph);
            else {
                Object obj = stack.pop();
                if (obj instanceof TextElementArray) {
                    TextElementArray current = (TextElementArray) obj;
                    current.add(currentParagraph);
                }
                stack.push(obj);
            }
        }
        currentParagraph = null;
        if (tag.equals("ul") || tag.equals("ol")) {
            if (pendingLI)
                endElement("li");
            skipText = false;
            cprops.removeChain(tag);
            if (stack.empty())
                return;
            Object obj = stack.pop();
            if (!(obj instanceof com.lowagie.text.List)) {
                stack.push(obj);
                return;
            }
            if (stack.empty())
                document.add((Element) obj);
            else
                ((TextElementArray) stack.peek()).add(obj);
            return;
        }
        if (tag.equals("li")) {
            pendingLI = false;
            skipText = true;
            cprops.removeChain(tag);
            if (stack.empty())
                return;
            Object obj = stack.pop();
            if (!(obj instanceof ListItem)) {
                stack.push(obj);
                return;
            }
            if (stack.empty()) {
                document.add((Element) obj);
                return;
            }
            Object list = stack.pop();
            if (!(list instanceof com.lowagie.text.List)) {
                stack.push(list);
                return;
            }
            ListItem item = (ListItem) obj;
            ((com.lowagie.text.List) list).add(item);
            ArrayList cks = item.getChunks();
            if (!cks.isEmpty())
                item.getListSymbol().setFont(((Chunk) cks.get(0)).getFont());
            stack.push(list);
            return;
        }
        if (tag.equals("div") || tag.equals("body")) {
            cprops.removeChain(tag);
            return;
        }
        if (tag.equals("pre")) {
            cprops.removeChain(tag);
            isPRE = false;
            return;
        }
        if (tag.equals("p")) {
            cprops.removeChain(tag);
            return;
        }
        if (tag.equals("h1") || tag.equals("h2") || tag.equals("h3") || tag.equals("h4") || tag.equals("h5")
                || tag.equals("h6")) {
            cprops.removeChain(tag);
            return;
        }
        if (tag.equals("table")) {
            if (pendingTR)
                endElement("tr");
            cprops.removeChain("table");
            IncTable table = (IncTable) stack.pop();
            PdfPTable tb = table.buildTable();
            tb.setSplitRows(true);
            if (stack.empty())
                document.add(tb);
            else
                ((TextElementArray) stack.peek()).add(tb);
            boolean state[] = (boolean[]) tableState.pop();
            pendingTR = state[0];
            pendingTD = state[1];
            skipText = false;
            return;
        }
        if (tag.equals("tr")) {
            if (pendingTD)
                endElement("td");
            pendingTR = false;
            cprops.removeChain("tr");
            ArrayList cells = new ArrayList();
            IncTable table = null;
            while (true) {
                Object obj = stack.pop();
                if (obj instanceof IncCell) {
                    cells.add(((IncCell) obj).getCell());
                }
                if (obj instanceof IncTable) {
                    table = (IncTable) obj;
                    break;
                }
            }
            table.addCols(cells);
            table.endRow();
            stack.push(table);
            skipText = true;
            return;
        }
        if (tag.equals("td") || tag.equals("th")) {
            pendingTD = false;
            cprops.removeChain("td");
            skipText = true;
            return;
        }
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:org.areasy.common.doclet.Doclet.java

License:Open Source License

/**
 * Processes one Java package of the whole API.
 *
 * @param packageDoc The javadoc information for the package.
 * @throws Exception/*from w w w  . j  a  va2s  .c o  m*/
 */
private void printPackage(PackageDoc packageDoc, ClassDoc[] packageClasses) throws Exception {
    State.setCurrentPackage(packageDoc.name());
    State.setCurrentDoc(packageDoc);

    Document.newPage();

    String packageName = State.getCurrentPackage();

    // Text "package"
    State.setCurrentClass("");

    Paragraph label = new Paragraph((float) 22.0, LB_PACKAGE, Fonts.getFont(TEXT_FONT, BOLD, 18));
    Document.add(label);

    Paragraph titlePara = new Paragraph((float) 30.0, "");
    // Name of the package (large font)
    Chunk titleChunk = new Chunk(packageName, Fonts.getFont(TEXT_FONT, BOLD, 30));
    titleChunk.setLocalDestination(packageName);
    if (State.getCurrentFile() != null) {
        String packageAnchor = Destinations.createAnchorDestination(State.getCurrentFile(), null);
        titlePara.add(PDFUtility.createAnchor(packageAnchor, titleChunk.font()));
    }

    titlePara.add(titleChunk);
    Document.add(titlePara);

    // Some empty space
    Document.add(new Paragraph((float) 20.0, " "));

    State.setContinued(true);

    String packageText = DocletUtility.getComment(packageDoc);
    Element[] objs = HtmlParserWrapper.createPdfObjects(packageText);

    if (objs.length == 0) {
        String packageDesc = DocletUtility.stripLineFeeds(packageText);
        Document.add(new Paragraph((float) 11.0, packageDesc, Fonts.getFont(TEXT_FONT, 10)));
    } else
        PDFUtility.printPdfElements(objs);

    State.setContinued(false);

    State.increasePackageSection();

    printClasses(DocletUtility.sort(packageClasses), packageDoc);
}

From source file:org.areasy.common.doclet.document.Classes.java

License:Open Source License

/**
 * Prints javadoc of one given class./*from w  w w  .  j  av a  2 s.c  o m*/
 *
 * @param classDoc   The javadoc information about the class.
 * @param packageDoc The package which the class is part of.
 * @throws Exception
 */
public static void printClass(ClassDoc classDoc, PackageDoc packageDoc) throws Exception {
    Document.newPage();
    State.increasePackageSection();

    State.setCurrentClass(classDoc.qualifiedName());
    State.setCurrentDoc(classDoc);
    log.info("..> " + State.getCurrentClass());

    // Simulate javadoc HTML layout package (small) and class (large) name header
    Paragraph namePara = new Paragraph(packageDoc.name(), Fonts.getFont(TEXT_FONT, BOLD, 16));
    Document.add(namePara);

    Phrase linkPhrase = null;
    if (!classDoc.isInterface()) {
        linkPhrase = Destinations.createDestination("Class " + classDoc.name(), classDoc,
                Fonts.getFont(TEXT_FONT, BOLD, 16));
    } else {
        linkPhrase = Destinations.createDestination("Interface " + classDoc.name(), classDoc,
                Fonts.getFont(TEXT_FONT, BOLD, 16));
    }

    Paragraph titlePara = new Paragraph((float) 16.0, "");
    String classFileAnchor = Destinations.createAnchorDestination(State.getCurrentFile(), null);
    titlePara.add(PDFUtility.createAnchor(classFileAnchor, titlePara.font()));
    titlePara.add(linkPhrase);

    Document.instance().add(titlePara);

    // class derivation tree - build list first
    Hashtable list = new Hashtable();
    ClassDoc currentTreeClass = classDoc;
    ClassDoc superClass = null;
    ClassDoc subClass = null;

    Vector interfacesList = new Vector();

    while ((superClass = currentTreeClass.superclass()) != null) {
        if (!classDoc.isInterface()) {
            // Store interfaces implemented by superclasses
            // because the current class also implements all
            // interfaces of its superclass (by inheritance)
            ClassDoc[] interfaces = superClass.interfaces();

            for (int u = 0; u < interfaces.length; u++) {
                interfacesList.addElement(interfaces[u]);
            }
        }

        list.put(superClass, currentTreeClass);
        currentTreeClass = superClass;
    }

    // First line of derivation tree must NOT be printed, if it's
    // the only line, and it's an interface (not a class). This is
    // because a class ALWAYS has a superclass (if only java.lang.Object),
    // but an interface does not necessarily have a super instance.
    boolean firstLine = true;

    if (classDoc.isInterface() && (list.get(currentTreeClass) == null)) {
        firstLine = false;
    }

    // top-level-class
    String blanks = "";

    if (firstLine) {
        Document.add(new Paragraph((float) 24.0, currentTreeClass.qualifiedTypeName(),
                Fonts.getFont(CODE_FONT, 10)));
    }

    while ((subClass = (ClassDoc) list.get(currentTreeClass)) != null) {
        blanks = blanks + "   ";
        Document.add(new Paragraph((float) 10.0, blanks + "|", Fonts.getFont(CODE_FONT, 10)));

        if (list.get(subClass) == null) {
            // it's last in list, so use bold font
            Document.add(new Paragraph((float) 8.0, blanks + "+-" + subClass.qualifiedTypeName(),
                    Fonts.getFont(CODE_FONT, BOLD, 10)));
        } else {
            // If it's not last, it's a superclass. Create link to
            // it, if it's in same API.
            Paragraph newLine = new Paragraph((float) 8.0);
            newLine.add(new Chunk(blanks + "+-", Fonts.getFont(CODE_FONT, 10)));
            newLine.add(new LinkPhrase(subClass.qualifiedTypeName(), null, 10, false));
            Document.add(newLine);
        }

        currentTreeClass = subClass;
    }

    ClassDoc[] interfaces = classDoc.interfaces();

    // Now, for classes only, print implemented interfaces
    // and known subclasses
    if (!classDoc.isInterface()) {
        // List All Implemented Interfaces
        if ((interfaces != null) && (interfaces.length > 0)) {
            for (int i = 0; i < interfaces.length; i++) {
                interfacesList.addElement(interfaces[i]);
            }
        }

        String[] interfacesNames = new String[interfacesList.size()];
        for (int i = 0; i < interfacesNames.length; i++) {
            interfacesNames[i] = ((ClassDoc) interfacesList.elementAt(i)).qualifiedTypeName();
        }
        if (interfacesNames.length > 0) {
            Implementors.print("All Implemented Interfaces:", interfacesNames);
        }

        // Known subclasses
        String[] knownSubclasses = ImplementorsInformation.getDirectSubclasses(State.getCurrentClass());

        if ((knownSubclasses != null) && (knownSubclasses.length > 0)) {
            Implementors.print("Direct Known Subclasses:", knownSubclasses);
        }
    } else {
        // For interfaces, print superinterfaces and all subinterfaces
        // Known super-interfaces
        String[] knownSuperInterfaces = ImplementorsInformation.getKnownSuperclasses(State.getCurrentClass());

        if ((knownSuperInterfaces != null) && (knownSuperInterfaces.length > 0)) {
            Implementors.print("All Superinterfaces:", knownSuperInterfaces);
        }

        // Known sub-interfaces
        String[] knownSubInterfaces = ImplementorsInformation.getKnownSubclasses(State.getCurrentClass());

        if ((knownSubInterfaces != null) && (knownSubInterfaces.length > 0)) {
            Implementors.print("All Subinterfaces:", knownSubInterfaces);
        }

        // Known Implementing Classes
        String[] knownImplementingClasses = ImplementorsInformation
                .getImplementingClasses(State.getCurrentClass());

        if ((knownImplementingClasses != null) && (knownImplementingClasses.length > 0)) {
            Implementors.print("All Known Implementing Classes:", knownImplementingClasses);
        }
    }

    // Horizontal line
    PDFUtility.printLine();

    // Class type / declaration
    String info = "";

    Tag[] deprecatedTags = classDoc.tags(DOC_TAGS_DEPRECATED);

    if (deprecatedTags.length > 0) {
        Paragraph classDeprecatedParagraph = new Paragraph((float) 20);

        Chunk deprecatedClassText = new Chunk(LB_DEPRECATED_TAG, Fonts.getFont(TEXT_FONT, BOLD, 12));
        classDeprecatedParagraph.add(deprecatedClassText);

        String depText = DocletUtility.getComment(deprecatedTags[0].inlineTags());
        Element[] deprecatedInfoText = HtmlParserWrapper.createPdfObjects("<i>" + depText + "</i>");
        for (int n = 0; n < deprecatedInfoText.length; n++) {
            // Only phrases can be supported here (but no tables)
            if (deprecatedInfoText[n] instanceof Phrase) {
                classDeprecatedParagraph.add(deprecatedInfoText[n]);
            }
        }

        Document.add(classDeprecatedParagraph);
    }

    info = DocletUtility.getClassModifiers(classDoc);

    Paragraph infoParagraph = new Paragraph((float) 20, info, Fonts.getFont(TEXT_FONT, 12));
    infoParagraph.add(new Chunk(classDoc.name(), Fonts.getFont(TEXT_FONT, BOLD, 12)));
    Document.add(infoParagraph);

    // extends ...
    ClassDoc superClassOrInterface = null;

    if (classDoc.isInterface()) {
        ClassDoc[] superInterfaces = classDoc.interfaces();

        if (superInterfaces.length > 0) {
            superClassOrInterface = superInterfaces[0];
        }
    } else {
        superClassOrInterface = classDoc.superclass();
    }

    if (superClassOrInterface != null) {
        Paragraph extendsPara = new Paragraph((float) 14.0);
        extendsPara.add(new Chunk("extends ", Fonts.getFont(TEXT_FONT, 12)));

        String superClassName = DocletUtility.getQualifiedNameIfNecessary(superClassOrInterface);
        extendsPara.add(new LinkPhrase(superClassOrInterface.qualifiedName(), superClassName, 12, true));

        Document.add(extendsPara);
    }

    if (!classDoc.isInterface()) {
        //implements
        if ((interfaces != null) && (interfaces.length > 0)) {
            String[] interfacesNames = new String[interfacesList.size()];

            for (int i = 0; i < interfacesNames.length; i++) {
                interfacesNames[i] = ((ClassDoc) interfacesList.elementAt(i)).qualifiedTypeName();
            }

            Paragraph extendsPara = new Paragraph((float) 14.0);
            extendsPara.add(new Chunk("implements ", Fonts.getFont(TEXT_FONT, 12)));

            Paragraph descPg = new Paragraph((float) 24.0);

            for (int i = 0; i < interfacesNames.length; i++) {
                String subclassName = DocletUtility.getQualifiedNameIfNecessary(interfacesNames[i]);
                Phrase subclassPhrase = new LinkPhrase(interfacesNames[i], subclassName, 12, true);
                descPg.add(subclassPhrase);

                if (i < (interfacesNames.length - 1)) {
                    descPg.add(new Chunk(", ", Fonts.getFont(CODE_FONT, 10)));
                }
            }

            extendsPara.add(descPg);

            Document.add(extendsPara);
        }
    }

    Document.add(new Paragraph((float) 20.0, " "));

    // Description
    String classText = DocletUtility.getComment(classDoc);
    Element[] objs = HtmlParserWrapper.createPdfObjects(classText);

    if (objs.length == 0) {
        String desc = DocletUtility.stripLineFeeds(classText);
        Document.add(new Paragraph((float) 14.0, desc, Fonts.getFont(TEXT_FONT, 12)));
    } else {
        PDFUtility.printPdfElements(objs);
    }

    TagLists.printClassTags(classDoc);
    // Horizontal line
    PDFUtility.printLine();

    if (DefaultConfiguration.isShowSummaryActive()) {
        Summary.printAll(classDoc);
        PDFUtility.printLine();
    }

    float[] widths = { (float) 1.0, (float) 94.0 };
    PdfPTable table = new PdfPTable(widths);
    table.setWidthPercentage((float) 100);

    // Some empty space...
    Document.add(new Paragraph((float) 6.0, " "));
    Members.printMembers(classDoc);
}

From source file:org.areasy.common.doclet.document.Implementors.java

License:Open Source License

/**
 * Prints all known subclasses or implementing classes.
 *
 * @param title The label for the name list
 * @param names The names (classes or interfaces)
 * @throws Exception//from ww  w  . ja  v a  2 s . co  m
 */
public static void print(String title, String[] names) throws Exception {
    float[] widths = { (float) 6.0, (float) 94.0 };
    PdfPTable table = new PdfPTable(widths);
    table.setWidthPercentage((float) 100);

    PdfPCell spacingCell = new CellNoBorderNoPadding(new Phrase(""));
    spacingCell.setFixedHeight((float) 12.0);
    spacingCell.setColspan(2);
    table.addCell(spacingCell);

    PdfPCell titleCell = new CellNoBorderNoPadding(
            new Paragraph((float) 20.0, title, Fonts.getFont(TEXT_FONT, BOLD, 10)));
    titleCell.setColspan(2);
    table.addCell(titleCell);

    PdfPCell leftCell = PDFUtility.createElementCell(5, new Phrase(""));
    Paragraph descPg = new Paragraph((float) 24.0);

    for (int i = names.length - 1; i > -1; i--) {
        String subclassName = DocletUtility.getQualifiedNameIfNecessary(names[i]);
        Phrase subclassPhrase = new LinkPhrase(names[i], subclassName, 10, true);
        descPg.add(subclassPhrase);

        if (i > 0)
            descPg.add(new Chunk(", ", Fonts.getFont(TEXT_FONT, BOLD, 12)));
    }

    table.addCell(leftCell);
    table.addCell(new CellNoBorderNoPadding(descPg));

    table.addCell(spacingCell);
    Document.instance().add(table);
}

From source file:org.areasy.common.doclet.document.Index.java

License:Open Source License

/**
 * Creates a simple alphabetical index of all
 * classes and members of the API.//from   ww w .j  a  v  a2  s.co  m
 *
 * @throws Exception If the Index could not be created.
 */
public void create() throws Exception {
    if (!DefaultConfiguration.getBooleanConfigValue(ARG_CREATE_INDEX, false)) {
        log.trace("Index creation disabled.");
        return;
    }

    log.trace("Start creating Index...");

    State.setCurrentHeaderType(HEADER_INDEX);
    State.increasePackageChapter();

    // Name of the package (large font)
    pdfDocument.newPage();

    // Create "Index" bookmark
    String label = DefaultConfiguration.getString(ARG_LB_OUTLINE_INDEX, LB_INDEX);
    String dest = "INDEX:";
    Bookmarks.addRootBookmark(label, dest);
    Chunk indexChunk = new Chunk(label, Fonts.getFont(TEXT_FONT, BOLD, 30));
    indexChunk.setLocalDestination(dest);

    Paragraph indexParagraph = new Paragraph((float) 30.0, indexChunk);

    pdfDocument.add(indexParagraph);

    // we grab the ContentByte and do some stuff with it
    PdfContentByte cb = pdfWriter.getDirectContent();
    ColumnText ct = new ColumnText(cb);
    ct.setLeading((float) 9.0);

    float[] right = { 70, 320 };
    float[] left = { 300, 550 };

    // fill index columns with text
    String letter = "";
    Set keys = memberList.keySet();

    // keys must be sorted case unsensitive
    ArrayList sortedKeys = new ArrayList(keys.size());

    // Build sorted list of all entries
    Iterator keysIterator = keys.iterator();
    while (keysIterator.hasNext()) {
        sortedKeys.add(keysIterator.next());
    }
    Collections.sort(sortedKeys, this);

    Iterator realNames = sortedKeys.iterator();

    while (realNames.hasNext()) {
        String memberName = (String) realNames.next();
        String currentLetter = memberName.substring(0, 1).toUpperCase();
        log.trace("Create index entry for " + memberName);

        // Check if next letter in alphabet is reached
        if (currentLetter.equalsIgnoreCase(letter) == false) {
            // If yes, switch to new letter and print it
            letter = currentLetter.toUpperCase();
            Paragraph lphrase = new Paragraph((float) 13.0);
            lphrase.add(new Chunk("\n\n" + letter + "\n", Fonts.getFont(TEXT_FONT, 12)));
            ct.addText(lphrase);
        }

        // Print member name
        Paragraph phrase = new Paragraph((float) 10.0);
        phrase.add(new Chunk("\n" + memberName + "  ", Fonts.getFont(TEXT_FONT, 9)));

        Iterator sortedPages = getSortedPageNumbers(memberName);
        boolean firstNo = true;
        while (sortedPages.hasNext()) {
            Integer pageNo = (Integer) sortedPages.next();
            // Always add 1 to the stored value, because the pages were
            // counted beginning with 0 internally, but their visible
            // numbering starts with 1
            String pageNumberText = String.valueOf(pageNo.intValue() + 1);
            if (!firstNo) {
                phrase.add(new Chunk(", ", Fonts.getFont(TEXT_FONT, 9)));
            }
            phrase.add(new Chunk(pageNumberText, Fonts.getFont(TEXT_FONT, 9)));
            firstNo = false;
        }

        ct.addText(phrase);
    }

    // Now print index by printing columns into document
    int status = 0;
    int column = 0;

    while ((status & ColumnText.NO_MORE_TEXT) == 0) {
        ct.setSimpleColumn(right[column], 60, left[column], 790, 16, Element.ALIGN_LEFT);
        status = ct.go();

        if ((status & ColumnText.NO_MORE_COLUMN) != 0) {
            column++;

            if (column > 1) {
                pdfDocument.newPage();
                column = 0;
            }
        }
    }

    log.trace("Index created.");
}

From source file:org.areasy.common.doclet.document.Inherited.java

License:Open Source License

/**
 * Prints inherited methods and fields from superclasses
 *
 * @param supercls  class source to get inherited fields and methods for.
 * @param show SHOW_METHODS or SHOW_FIELDS
 * @throws Exception//  ww  w. ja  v  a 2  s.  c  o m
 */
public static void print(ClassDoc supercls, int show) throws Exception {
    String type;

    FieldDoc[] fields = supercls.fields();

    Arrays.sort(fields);

    if (supercls.isInterface())
        type = "interface";
    else
        type = "class";

    // Create cell for additional spacing below
    PdfPCell spacingCell = new PdfPCell();
    spacingCell.addElement(new Chunk(" "));
    spacingCell.setFixedHeight((float) 4.0);
    spacingCell.setBorder(Rectangle.BOTTOM + Rectangle.LEFT + Rectangle.RIGHT);
    spacingCell.setBorderColor(Color.gray);

    if ((fields.length > 0) && (show == SHOW_FIELDS)) {
        Document.instance().add(new Paragraph((float) 6.0, " "));

        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage((float) 100);

        Paragraph newLine = new Paragraph();
        newLine.add(new Chunk("Fields inherited from " + type + " ", Fonts.getFont(TEXT_FONT, BOLD, 10)));
        newLine.add(new LinkPhrase(supercls.qualifiedTypeName(), null, 10, false));

        table.addCell(new CustomPdfPCell(newLine, COLOR_INHERITED_SUMMARY));

        Paragraph paraList = new Paragraph();

        for (int i = 0; i < fields.length; i++) {
            paraList.add(new LinkPhrase(fields[i].qualifiedName(), fields[i].name(), 10, false));

            if (i != (fields.length - 1))
                paraList.add(new Chunk(", ", Fonts.getFont(TEXT_FONT, BOLD, 12)));
        }

        PdfPCell contentCell = new CellBorderPadding(paraList);
        float leading = (float) contentCell.getLeading() + (float) 1.1;
        contentCell.setLeading(leading, leading);
        table.addCell(contentCell);
        table.addCell(spacingCell);

        Document.instance().add(table);
    }

    MethodDoc[] meth = supercls.methods();

    Arrays.sort(meth);

    if ((meth.length > 0) && (show == SHOW_METHODS)) {
        Document.instance().add(new Paragraph((float) 6.0, " "));

        PdfPTable table = new CustomPdfPTable();

        Paragraph newLine = new Paragraph();
        newLine.add(new Chunk("Methods inherited from " + type + " ", Fonts.getFont(TEXT_FONT, BOLD, 10)));
        newLine.add(new LinkPhrase(supercls.qualifiedTypeName(), null, 10, false));

        table.addCell(new CustomPdfPCell(newLine, COLOR_INHERITED_SUMMARY));
        Paragraph paraList = new Paragraph();

        for (int i = 0; i < meth.length; i++) {
            String methodLabel = meth[i].name();

            // Do not list static initializers like "<clinit>"
            if (!methodLabel.startsWith("<")) {
                paraList.add(new LinkPhrase(supercls.qualifiedTypeName() + "." + meth[i].name(), meth[i].name(),
                        10, false));

                if (i != (meth.length - 1))
                    paraList.add(new Chunk(", ", Fonts.getFont(CODE_FONT, 10)));
            }
        }

        PdfPCell contentCell = new CellBorderPadding(paraList);
        float leading = (float) contentCell.getLeading() + (float) 1.1;
        contentCell.setLeading(leading, leading);
        table.addCell(contentCell);
        table.addCell(spacingCell);

        Document.instance().add(table);
    }

    // Print inherited interfaces / class methods and fields recursively
    ClassDoc supersupercls = null;

    if (supercls.isClass())
        supersupercls = supercls.superclass();

    if (supersupercls != null) {
        String className = supersupercls.qualifiedName();
        if (ifClassMustBePrinted(className))
            Inherited.print(supersupercls, show);
    }

    ClassDoc[] interfaces = supercls.interfaces();
    for (int i = 0; i < interfaces.length; i++) {
        supersupercls = interfaces[i];
        String className = supersupercls.qualifiedName();
        if (ifClassMustBePrinted(className))
            Inherited.print(supersupercls, show);
    }
}

From source file:org.areasy.common.doclet.document.Members.java

License:Open Source License

/**
 * Prints member information.//ww w  .  j a  v a 2  s  . c  o m
 *
 * @param declaration      The modifiers ("public static final..").
 * @param returnType       Phrase with the return type text (might be
 *                         a hyperlink)
 * @param parms            Parameters of a method or constructor, null for a field.
 * @param thrownExceptions Exceptions of a method, null for a field or constructor.
 * @param isFirst          True if it is the first field/method/constructor in the list.
 * @param isField          True if it is a field.
 * @param isConstructor    True if it is a constructor.
 * @throws Exception
 */
public static void printMember(String declaration, Phrase returnType, ProgramElementDoc commentDoc,
        Parameter[] parms, ClassDoc[] thrownExceptions, boolean isFirst, boolean isField, boolean isConstructor,
        boolean isDeprecated, Phrase deprecatedPhrase, Object constantValue) throws Exception {
    String name = commentDoc.name();

    State.setCurrentMember(State.getCurrentClass() + "." + name);
    State.setCurrentDoc(commentDoc);

    // Returns the text, resolving any "inheritDoc" inline tags
    String commentText = DocletUtility.getComment(commentDoc);

    // TODO: The following line may set the wrong page number
    //      in the index, when the member gets printed on a
    //      new page completely (because it is in one table).
    // Solution unknown yet. Probably split up table.
    Doclet.getIndex().addToMemberList(State.getCurrentMember());

    // Prepare list of exceptions (if it throws any)
    String throwsText = "throws";
    int parmsColumn = declaration.length() + (name.length() - throwsText.length());

    // First output text line (declaration of method and first parameter or "()" ).
    // This first line is a special case because the class name is bold,
    // while the rest is regular plain text, so it must be built using three Chunks.
    Paragraph declarationParagraph = new Paragraph((float) 10.0);

    // left part / declaration ("public static..")
    Chunk leftPart = new Chunk(declaration, Fonts.getFont(CODE_FONT, 10));

    declarationParagraph.add(leftPart);

    if (returnType != null) {
        // left middle part / declaration ("public static..")
        declarationParagraph.add(returnType);
        declarationParagraph.add(new Chunk(" ", Fonts.getFont(CODE_FONT, 10)));
        parmsColumn = 2;
    }

    // right middle part / bold class name
    declarationParagraph.add(new Chunk(name, Fonts.getFont(CODE_FONT, BOLD, 10)));

    if (!isField) {
        // 1st parameter or empty brackets

        if ((parms != null) && (parms.length > 0)) {
            Phrase wholePhrase = new Phrase("(", Fonts.getFont(CODE_FONT, 10));
            // create link for parameter type
            wholePhrase.add(PDFUtility.getParameterTypePhrase(parms[0], 10));
            // then normal text for parameter name
            wholePhrase.add(" " + parms[0].name());
            if (parms.length > 1) {
                wholePhrase.add(",");
            } else {
                wholePhrase.add(")");
            }

            // In order to have the parameter types in the bookmark,
            // make the current state text more detailled
            String txt = State.getCurrentMethod() + "(";
            for (int i = 0; i < parms.length; i++) {
                if (i > 0)
                    txt = txt + ",";
                txt = txt + DocletUtility.getParameterType(parms[i]);
            }

            txt = txt + ")";
            State.setCurrentMethod(txt);

            // right part / parameter and brackets
            declarationParagraph.add(wholePhrase);

        } else {
            String lastPart = "()";
            State.setCurrentMethod(State.getCurrentMethod() + lastPart);

            // right part / parameter and brackets
            declarationParagraph.add(new Chunk(lastPart, Fonts.getFont(CODE_FONT, 10)));
        }

    }

    float[] widths = { (float) 6.0, (float) 94.0 };
    PdfPTable table = new PdfPTable(widths);
    table.setWidthPercentage((float) 100);

    // Before the first constructor or method, create a coloured title bar
    if (isFirst) {
        PdfPCell colorTitleCell = null;

        // Some empty space...
        Document.add(new Paragraph((float) 6.0, " "));

        if (isConstructor)
            colorTitleCell = new CustomPdfPCell("Constructors");
        else if (isField)
            colorTitleCell = new CustomPdfPCell("Fields");
        else
            colorTitleCell = new CustomPdfPCell("Methods");

        colorTitleCell.setColspan(2);
        table.addCell(colorTitleCell);
    }

    // Method name (large, first line of a method description block)
    Phrase linkPhrase = Destinations.createDestination(commentDoc.name(), commentDoc,
            Fonts.getFont(TEXT_FONT, BOLD, 14));
    Paragraph nameTitle = new Paragraph(linkPhrase);
    PdfPCell nameCell = new CellNoBorderNoPadding(nameTitle);

    if (isFirst)
        nameCell.setPaddingTop(10);
    else
        nameCell.setPaddingTop(0);

    nameCell.setPaddingBottom(8);
    nameCell.setColspan(1);

    // Create nested table in order to try to prevent the stuff inside
    // this table from being ripped appart over a page break. The method
    // name and the declaration/parm/exception line(s) should always be
    // together, because everything else just looks bad
    PdfPTable linesTable = new PdfPTable(1);
    linesTable.addCell(nameCell);
    linesTable.addCell(new CellNoBorderNoPadding(declarationParagraph));

    if (!isField) {
        // Set up following declaration lines
        Paragraph[] params = PDFUtility.createParameters(parmsColumn, parms);
        Paragraph[] exceps = PDFUtility.createExceptions(parmsColumn, thrownExceptions);

        for (int i = 0; i < params.length; i++) {
            linesTable.addCell(new CellNoBorderNoPadding(params[i]));
        }

        for (int i = 0; i < exceps.length; i++) {
            linesTable.addCell(new CellNoBorderNoPadding(exceps[i]));
        }
    }

    // Create cell for inserting the nested table into the outer table
    PdfPCell cell = new PdfPCell(linesTable);
    cell.setPadding(5);
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setColspan(2);
    table.addCell(cell);

    // The empty, left cell (the invisible indentation column)
    State.setContinued(true);

    PdfPCell leftCell = PDFUtility.createElementCell(5, new Phrase("", Fonts.getFont(TEXT_FONT, BOLD, 6)));
    PdfPCell spacingCell = new PdfPCell();
    spacingCell.setFixedHeight((float) 8.0);
    spacingCell.setBorder(Rectangle.NO_BORDER);
    table.addCell(spacingCell);
    table.addCell(spacingCell);

    // The descriptive method explanation text

    if (isDeprecated) {
        Phrase commentPhrase = new Phrase();
        commentPhrase
                .add(new Phrase(AbstractConfiguration.LB_DEPRECATED_TAG, Fonts.getFont(TEXT_FONT, BOLD, 10)));
        commentPhrase.add(deprecatedPhrase);
        table.addCell(leftCell);
        table.addCell(PDFUtility.createElementCell(0, commentPhrase));

        commentPhrase = new Phrase();
        commentPhrase.add(Chunk.NEWLINE);
        table.addCell(leftCell);
        table.addCell(PDFUtility.createElementCell(0, commentPhrase));
    }

    Element[] objs = HtmlParserWrapper.createPdfObjects(commentText);

    if (objs.length == 1) {
        table.addCell(leftCell);
        table.addCell(PDFUtility.createElementCell(0, objs[0]));
    } else {
        table.addCell(leftCell);
        table.addCell(PDFUtility.createElementCell(0, Element.ALIGN_LEFT, objs));
    }

    // TODO: FORMAT THIS CONSTANT VALUE OUTPUT CORRECTLY

    if (isField) {
        if (constantValue != null) {
            // Add 2nd comment line (left cell empty, right cell text)
            Chunk valueTextChunk = new Chunk("Constant value: ", Fonts.getFont(TEXT_FONT, PLAIN, 10));
            Chunk valueContentChunk = new Chunk(constantValue.toString(), Fonts.getFont(CODE_FONT, BOLD, 10));
            Phrase constantValuePhrase = new Phrase("");
            constantValuePhrase.add(valueTextChunk);
            constantValuePhrase.add(valueContentChunk);
            table.addCell(leftCell);
            table.addCell(PDFUtility.createElementCell(0, constantValuePhrase));
        }
    }

    // Add whole method block to document
    Document.add(table);
}

From source file:org.areasy.common.doclet.document.Overview.java

License:Open Source License

/**
 * Processes overview./*w  w w  .  ja  va  2  s  . c o m*/
 *
 * @param rootDoc The javadoc information for the API.
 * @throws Exception
 */
public static void print(RootDoc rootDoc) throws Exception {
    String overview = DocletUtility.getComment(rootDoc);

    // Check if PDF file has been specified
    String[] overviewFileNames = DefaultConfiguration.findNumberedProperties(ARG_OVERVIEW_PDF_FILE);

    // Only do something if either standard overview or PDF file has been specified
    if ((overview == null || overview.length() == 0) && overviewFileNames == null)
        return;

    State.setOverview(true);
    State.setCurrentDoc(rootDoc);

    Document.newPage();

    String bmLabel = DefaultConfiguration.getString(ARG_LB_OUTLINE_OVERVIEW, LB_OVERVIEW);
    String dest = Destinations.createAnchorDestination(State.getCurrentFile(), bmLabel);

    Bookmarks.addRootBookmark(bmLabel, dest);
    Document.instance().add(PDFUtility.createAnchor(dest));

    if (State.getCurrentFile() != null) {
        String packageAnchor = Destinations.createAnchorDestination(State.getCurrentFile(), null);
        Document.instance().add(PDFUtility.createAnchor(packageAnchor));
    }

    // If the (pdf) filename contains page information, extract it
    boolean pdfPagesInserted = false;

    if (overviewFileNames != null) {
        for (int i = 0; i < overviewFileNames.length; i++) {
            String overviewFileName = overviewFileNames[i];
            String pages = "";

            if (overviewFileName.indexOf(",") != -1) {
                pages = overviewFileName.substring(overviewFileName.indexOf(",") + 1,
                        overviewFileName.length());
                overviewFileName = overviewFileName.substring(0, overviewFileName.indexOf(","));
            }

            if (overviewFileName.endsWith(".pdf")) {
                if (pages.length() == 0)
                    pages = "1";

                File overviewFile = new File(DefaultConfiguration.getWorkDir(), overviewFileName);
                if (overviewFile.exists() && overviewFile.isFile()) {
                    State.setContinued(false);
                    Destinations.addValidDestinationFile(overviewFile);
                    State.setCurrentFile(overviewFile);

                    PDFUtility.insertPdfPages(overviewFile, pages);
                    pdfPagesInserted = true;
                }
            }

            if (overview != null && overview.length() > 0) {
                if (pdfPagesInserted)
                    Document.newPage();
            }
        }
    }

    if (overview != null && overview.length() > 0) {
        State.setContinued(true);

        Paragraph label = new Paragraph((float) 22.0, "", Fonts.getFont(TEXT_FONT, BOLD, 18));
        label.add(bmLabel);
        Document.instance().add(label);

        // Some empty space
        Document.instance().add(new Paragraph((float) 20.0, " "));

        Element[] objs = HtmlParserWrapper.createPdfObjects(overview);

        if ((objs == null) || (objs.length == 0)) {
            String rootDesc = DocletUtility.stripLineFeeds(overview);
            Document.instance().add(new Paragraph((float) 11.0, rootDesc, Fonts.getFont(TEXT_FONT, 10)));
        } else
            PDFUtility.printPdfElements(objs);
    }

    State.setOverview(false);
    State.setContinued(false);
}

From source file:org.areasy.common.doclet.document.Summary.java

License:Open Source License

/**
 * Creates the inner table for both columns. The left column
 * already contains the declaration text part.
 *
 * @param text       The text (like "static final"..)
 *//*  w  w  w  .  java  2  s.co  m*/
private static PdfPTable addDeclaration(String text, Phrase returnType) throws DocumentException {
    PdfPTable innerTable = new PdfPTable(2);
    innerTable.setWidthPercentage(100f);
    innerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
    innerTable.setWidths(new int[] { 24, 76 });
    Paragraph declarationParagraph = new Paragraph((float) 9.0);
    Chunk leftPart = new Chunk(text, Fonts.getFont(CODE_FONT, 9));
    declarationParagraph.add(leftPart);
    if (returnType != null) {
        declarationParagraph.add(returnType);
        declarationParagraph.add(new Chunk(" ", Fonts.getFont(CODE_FONT, 9)));
    }
    PdfPCell cell = new CustomPdfPCell(Rectangle.RIGHT, declarationParagraph, 1, Color.gray);
    cell.setPaddingTop((float) 4.0);
    cell.setVerticalAlignment(PdfPCell.ALIGN_TOP);

    innerTable.addCell(cell);
    return innerTable;
}