⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 saxitexthandler.java

📁 iText是一个能够快速产生PDF文件的java类库。iText的java类对于那些要产生包含文本
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
            for (Iterator i = attributes.keySet().iterator(); i.hasNext();) {
                key = (String) i.next();
                value = attributes.getProperty(key);
                try {
                    // margin specific code suggested by Reza Nasiri
                    if (ElementTags.LEFT.equalsIgnoreCase(key))
                        leftMargin = Float.parseFloat(value + "f");
                    if (ElementTags.RIGHT.equalsIgnoreCase(key))
                        rightMargin = Float.parseFloat(value + "f");
                    if (ElementTags.TOP.equalsIgnoreCase(key))
                        topMargin = Float.parseFloat(value + "f");
                    if (ElementTags.BOTTOM.equalsIgnoreCase(key))
                        bottomMargin = Float.parseFloat(value + "f");
                } catch (Exception ex) {
                    throw new ExceptionConverter(ex);
                }
                if (ElementTags.PAGE_SIZE.equals(key)) {
                    try {
                        String pageSizeName = value;
                        Field pageSizeField = PageSize.class
                                .getField(pageSizeName);
                        pageSize = (Rectangle) pageSizeField.get(null);
                    } catch (Exception ex) {
                        throw new ExceptionConverter(ex);
                    }
                } else if (ElementTags.ORIENTATION.equals(key)) {
                    try {
                        if ("landscape".equals(value)) {
                            orientation = "landscape";
                        }
                    } catch (Exception ex) {
                        throw new ExceptionConverter(ex);
                    }
                } else {
                    try {
                        document.add(new Meta(key, value));
                    } catch (DocumentException de) {
                        throw new ExceptionConverter(de);
                    }
                }
            }
            if(pageSize != null) {
            	if ("landscape".equals(orientation)) {
            		pageSize = pageSize.rotate();
            	}
            	document.setPageSize(pageSize);
            }
            document.setMargins(leftMargin, rightMargin, topMargin,
                    bottomMargin);

            if (controlOpenClose)
                document.open();
        }

    }

    protected void addImage(Image img) throws EmptyStackException {
        // if there is an element on the stack...
        Object current = stack.pop();
        // ...and it's a Chapter or a Section, the Image can be
        // added directly
        if (current instanceof Chapter
                || current instanceof Section
                || current instanceof Cell) {
            ((TextElementArray) current).add(img);
            stack.push(current);
            return;
        }
        // ...if not, we need to to a lot of stuff
        else {
            Stack newStack = new Stack();
            while (!(current instanceof Chapter
                    || current instanceof Section || current instanceof Cell)) {
                newStack.push(current);
                if (current instanceof Anchor) {
                    img.setAnnotation(new Annotation(0, 0, 0,
                            0, ((Anchor) current).getReference()));
                }
                current = stack.pop();
            }
            ((TextElementArray) current).add(img);
            stack.push(current);
            while (!newStack.empty()) {
                stack.push(newStack.pop());
            }
            return;
        }
    }
    
    /**
     * This method gets called when ignorable white space encountered.
     * 
     * @param ch
     *            an array of characters
     * @param start
     *            the start position in the array
     * @param length
     *            the number of characters to read from the array
     */

    public void ignorableWhitespace(char[] ch, int start, int length) {
        // do nothing: we handle white space ourselves in the characters method
    }

    /**
     * This method gets called when characters are encountered.
     * 
     * @param ch
     *            an array of characters
     * @param start
     *            the start position in the array
     * @param length
     *            the number of characters to read from the array
     */

    public void characters(char[] ch, int start, int length) {

        if (ignore)
            return;

        String content = new String(ch, start, length);
        // System.err.println("'" + content + "'");

        if (content.trim().length() == 0) {
            return;
        }

        StringBuffer buf = new StringBuffer();
        int len = content.length();
        char character;
        boolean newline = false;
        for (int i = 0; i < len; i++) {
            switch (character = content.charAt(i)) {
            case ' ':
                if (!newline) {
                    buf.append(character);
                }
                break;
            case '\n':
                if (i > 0) {
                    newline = true;
                    buf.append(' ');
                }
                break;
            case '\r':
                break;
            case '\t':
                break;
            default:
                newline = false;
                buf.append(character);
            }
        }
        if (currentChunk == null) {
        	if (bf == null) {
        		currentChunk = new Chunk(buf.toString());
        	}
        	else {
        		currentChunk = new Chunk(buf.toString(), new Font(this.bf));
        	}
        } else {
            currentChunk.append(buf.toString());
        }
    }

    private BaseFont bf = null;
    
    /**
     * Sets the font that has to be used.
     * @param bf
     */
    public void setBaseFont(BaseFont bf) {
    	this.bf = bf;
    }

    /**
     * This method gets called when an end tag is encountered.
     * 
     * @param uri
     *            the Uniform Resource Identifier
     * @param lname
     *            the local name (without prefix), or the empty string if
     *            Namespace processing is not being performed.
     * @param name
     *            the name of the tag that ends
     */

    public void endElement(String uri, String lname, String name) {
        handleEndingTags(name);
    }

    /**
     * This method deals with the starting tags.
     * 
     * @param name
     *            the name of the tag
     */

    public void handleEndingTags(String name) {

        // System.err.println("Stop: " + name);

        if (ElementTags.IGNORE.equals(name)) {
            ignore = false;
            return;
        }
        if (ignore)
            return;
        // tags that don't have any content
        if (isNewpage(name) || ElementTags.ANNOTATION.equals(name) || ElementTags.IMAGE.equals(name)
                || isNewline(name)) {
            return;
        }

        try {
            // titles of sections and chapters
            if (ElementTags.TITLE.equals(name)) {
                Paragraph current = (Paragraph) stack.pop();
                if (currentChunk != null) {
                    current.add(currentChunk);
                    currentChunk = null;
                }
                Section previous = (Section) stack.pop();
                previous.setTitle(current);
                stack.push(previous);
                return;
            }

            // all other endtags
            if (currentChunk != null) {
                TextElementArray current;
                try {
                    current = (TextElementArray) stack.pop();
                } catch (EmptyStackException ese) {
                    current = new Paragraph();
                }
                current.add(currentChunk);
                stack.push(current);
                currentChunk = null;
            }

            // chunks
            if (ElementTags.CHUNK.equals(name)) {
                return;
            }

            // phrases, anchors, lists, tables
            if (ElementTags.PHRASE.equals(name) || ElementTags.ANCHOR.equals(name) || ElementTags.LIST.equals(name)
                    || ElementTags.PARAGRAPH.equals(name)) {
                Element current = (Element) stack.pop();
                try {
                    TextElementArray previous = (TextElementArray) stack.pop();
                    previous.add(current);
                    stack.push(previous);
                } catch (EmptyStackException ese) {
                    document.add(current);
                }
                return;
            }

            // listitems
            if (ElementTags.LISTITEM.equals(name)) {
                ListItem listItem = (ListItem) stack.pop();
                List list = (List) stack.pop();
                list.add(listItem);
                stack.push(list);
            }

            // tables
            if (ElementTags.TABLE.equals(name)) {
                Table table = (Table) stack.pop();
                try {
                    TextElementArray previous = (TextElementArray) stack.pop();
                    previous.add(table);
                    stack.push(previous);
                } catch (EmptyStackException ese) {
                    document.add(table);
                }
                return;
            }

            // rows
            if (ElementTags.ROW.equals(name)) {
                ArrayList cells = new ArrayList();
                int columns = 0;
                Table table;
                Cell cell;
                while (true) {
                    Element element = (Element) stack.pop();
                    if (element.type() == Element.CELL) {
                        cell = (Cell) element;
                        columns += cell.getColspan();
                        cells.add(cell);
                    } else {
                        table = (Table) element;
                        break;
                    }
                }
                if (table.getColumns() < columns) {
                    table.addColumns(columns - table.getColumns());
                }
                Collections.reverse(cells);
                String width;
                float[] cellWidths = new float[columns];
                boolean[] cellNulls = new boolean[columns];
                for (int i = 0; i < columns; i++) {
                    cellWidths[i] = 0;
                    cellNulls[i] = true;
                }
                float total = 0;
                int j = 0;
                for (Iterator i = cells.iterator(); i.hasNext();) {
                    cell = (Cell) i.next();
                    width = cell.getWidthAsString();
                    if (cell.getWidth() == 0) {
                        if (cell.getColspan() == 1 && cellWidths[j] == 0) {
                            try {
                                cellWidths[j] = 100f / columns;
                                total += cellWidths[j];
                            } catch (Exception e) {
                                // empty on purpose
                            }
                        } else if (cell.getColspan() == 1) {
                            cellNulls[j] = false;
                        }
                    } else if (cell.getColspan() == 1 && width.endsWith("%")) {
                        try {
                            cellWidths[j] = Float.parseFloat(
                                    width.substring(0, width.length() - 1)
                                            + "f");
                            total += cellWidths[j];
                        } catch (Exception e) {
                            // empty on purpose
                        }
                    }
                    j += cell.getColspan();
                    table.addCell(cell);
                }
                float widths[] = table.getProportionalWidths();
                if (widths.length == columns) {
                    float left = 0.0f;
                    for (int i = 0; i < columns; i++) {
                        if (cellNulls[i] && widths[i] != 0) {
                            left += widths[i];
                            cellWidths[i] = widths[i];
                        }
                    }
                    if (100.0 >= total) {
                        for (int i = 0; i < widths.length; i++) {
                            if (cellWidths[i] == 0 && widths[i] != 0) {
                                cellWidths[i] = (widths[i] / left)
                                        * (100.0f - total);
                            }
                        }
                    }
                    table.setWidths(cellWidths);
                }
                stack.push(table);
            }

            // cells
            if (ElementTags.CELL.equals(name)) {
                return;
            }

            // sections
            if (ElementTags.SECTION.equals(name)) {
                stack.pop();
                return;
            }

            // chapters
            if (ElementTags.CHAPTER.equals(name)) {
                document.add((Element) stack.pop());
                return;
            }

            // the documentroot
            if (isDocumentRoot(name)) {
                try {
                    while (true) {
                        Element element = (Element) stack.pop();
                        try {
                            TextElementArray previous = (TextElementArray) stack
                                    .pop();
                            previous.add(element);
                            stack.push(previous);
                        } catch (EmptyStackException es) {
                            document.add(element);
                        }
                    }
                } catch (EmptyStackException ese) {
                    // empty on purpose
                }
                if (controlOpenClose)
                    document.close();
                return;
            }
        } catch (DocumentException de) {
            throw new ExceptionConverter(de);
        }
    }

    /**
     * Checks if a certain tag corresponds with the newpage-tag.
     * 
     * @param tag
     *            a presumed tagname
     * @return <CODE>true</CODE> or <CODE>false</CODE>
     */

    private boolean isNewpage(String tag) {
        return ElementTags.NEWPAGE.equals(tag);
    }

    /**
     * Checks if a certain tag corresponds with the newpage-tag.
     * 
     * @param tag
     *            a presumed tagname
     * @return <CODE>true</CODE> or <CODE>false</CODE>
     */

    private boolean isNewline(String tag) {
        return ElementTags.NEWLINE.equals(tag);
    }

    /**
     * Checks if a certain tag corresponds with the roottag.
     * 
     * @param tag
     *            a presumed tagname
     * @return <CODE>true</CODE> if <VAR>tag </VAR> equals <CODE>itext
     *         </CODE>,<CODE>false</CODE> otherwise.
     */

    protected boolean isDocumentRoot(String tag) {
        return ElementTags.ITEXT.equals(tag);
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -