Start a new XML element using the given start tag and single attribute.
195232
public void startElement(String elemName, String attrName, String attrValue) {
        AttributesImpl attrs = new AttributesImpl();
        attrs.addAttribute("", attrName, "", "CDATA", attrValue);
        writeStartElement(elemName, attrs);
        m_tagStack.push(elemName);
    }
649644
def create_element(tag: str, name: str = None, base: type = None,
                   attr: dict = None) -> Node:
    
    from wdom.web_node import WdomElement
    from wdom.tag import Tag
    from wdom.window import customElements
    if attr is None:
        attr = {}
    if name:
        base_class = customElements.get((name, tag))
    else:
        base_class = customElements.get((tag, None))
    if base_class is None:
        attr['_registered'] = False
        base_class = base or WdomElement
    if issubclass(base_class, Tag):
        return base_class(**attr)
    return base_class(tag, **attr)
40207
def startElement (self, name, attrs):
                '''
                '''
                func = getattr(self, 'start_' + name, None)
                if func:
                        func(attrs)
75777
def xml_start_output (self):
        
        self.writeln(u'<?xml version="1.0" encoding="%s"?>' %
             xmlquoteattr(self.get_charset_encoding()))
        if self.has_part("intro"):
            self.write_intro()
            self.writeln()
981327
def handle_starttag(self, tagName, attributeList, isSelfClosing=False):
        '''
            
        '''
        tagName = tagName.lower()
        inTag = self._inTag

        if isSelfClosing is False and tagName in IMPLICIT_SELF_CLOSING_TAGS:
            isSelfClosing = True

        newTag = AdvancedTag(tagName, attributeList, isSelfClosing)
        if self.root is None:
            self.root = newTag
        elif len(inTag) > 0:
            inTag[-1].appendChild(newTag)
        else:
            raise MultipleRootNodeException()

        if self.inPreformatted is 0:
            newTag._indent = self._getIndent()

        if tagName in PREFORMATTED_TAGS:
            self.inPreformatted += 1

        if isSelfClosing is False:
            inTag.append(newTag)
            if tagName != INVISIBLE_ROOT_TAG:
                self.currentIndentLevel += 1
143214
def handle_starttag(self, tag, attrs):
        
        # Parse the tag attributes
        attrs_dict = dict(t for t in attrs)

        # If the tag is a predefined parent element
        if tag in PARENT_ELEMENTS:
            # If parser is parsing another parent element
            if self.current_parent_element['tag'] != '':
                # close the parent element
                self.cleaned_html += '</{}>'.format(self.current_parent_element['tag'])

            self.current_parent_element['tag'] = tag
            self.current_parent_element['attrs'] = {}

            self.cleaned_html += '<{}>'.format(tag)

        # If the tag is a list item
        elif tag == 'li':
            self.parsing_li = True

            # Parse the class name & subsequent type
            class_name = attrs_dict['class']
            list_type = class_name[10:]

            # Check if parsing a list
            if self.current_parent_element['tag'] == 'ul' or self.current_parent_element['tag'] == 'ol':
                cur_list_type = self.current_parent_element['attrs']['class']
                # Parsing a different list
                if cur_list_type != list_type:
                    # Close that list
                    self._close_list()

                    # Open new list
                    self._open_list(list_type)
            # Not parsing a list
            else:
                # if parsing some other parent
                if self.current_parent_element['tag'] != '':
                    self.cleaned_html += '</{}>'.format(self.current_parent_element['tag'])
                # Open new list
                self._open_list(list_type)

            self.cleaned_html += '<{}>'.format(tag)

        # If the tag is a line break
        elif tag == 'br':
            # If parsing a paragraph, close it
            if self.current_parent_element['tag'] == 'p':
                self.cleaned_html += '</p>'
                self.current_parent_element['tag'] = ''
                self.current_parent_element['attrs'] = {}
            # If parsing a list, close it
            elif self.current_parent_element['tag'] == 'ul' or self.current_parent_element['tag'] == 'ol':
                self._close_list()
            # If parsing any other parent element, keep it
            elif self.current_parent_element['tag'] in PARENT_ELEMENTS:
                self.cleaned_html += '<br />'
            # If not in any parent element, create an empty paragraph
            else:
                self.cleaned_html += '<p></p>'

        # If the tag is something else, like a <b> or <i> tag
        else:
            # If not parsing any parent element
            if self.current_parent_element['tag'] == '':
                self.cleaned_html += '<p>'
                self.current_parent_element['tag'] = 'p'
            self.cleaned_html += '<{}'.format(tag)

            for attr in sorted(attrs_dict.keys()):
                self.cleaned_html += ' {k}="{v}"'.format(
                    k=attr,
                    v=attrs_dict[attr]
                )

            self.cleaned_html += '>'
366737
public static AsyncWork<XMLStreamReader, Exception> start(IO.Readable.Buffered io, int charactersBufferSize, int maxBuffers) {
		AsyncWork<XMLStreamReader, Exception> result = new AsyncWork<>();
		new Task.Cpu.FromRunnable("Start reading XML " + io.getSourceDescription(), io.getPriority(), () -> {
			XMLStreamReader reader = new XMLStreamReader(io, charactersBufferSize, maxBuffers);
			try {
				Starter start = new Starter(io, reader.defaultEncoding, reader.charactersBuffersSize, reader.maxBuffers);
				reader.stream = start.start();
				reader.stream.canStartReading().listenAsync(
				new Task.Cpu.FromRunnable("Start reading XML " + io.getSourceDescription(), io.getPriority(), () -> {
					try {
						reader.next();
						result.unblockSuccess(reader);
					} catch (Exception e) {
						result.unblockError(e);
					}
				}), true);
			} catch (Exception e) {
				result.unblockError(e);
			}
		}).startOn(io.canStartReading(), true);
		return result;
	}
235120
public void printXMLStartElement(String name, Attributes attributes)
    {
        try {
            this.xmlWriter.startElement("", name, name, attributes);
        } catch (SAXException e) {
            // TODO: add error log here
        }
    }
1264877
public void startRootElement() throws XMLException, IOException {
		start();
		while (!Type.START_ELEMENT.equals(event.type)) next();
	}
122536
public void startElement(String namespaceURI, String localName, String qName, Attributes attr)
    {
        if (localName.equalsIgnoreCase(TABLE))
        {
            String strClass = attr.getValue("", "class");
            if (strClass != null)
                if (strClass.equalsIgnoreCase("table-in"))  // NO NO NO
                {
                    startTable = true;
                    row = -1;
                }
        }
        else if (startTable)
        {
            if (localName.equalsIgnoreCase(TR))
            {
                row++;
                col = -1;
            }
            else if (localName.equalsIgnoreCase(TD))
            {
                col++;
            }
        }
    }
356546
@Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

        // update element stack
        stack.add(localName);

        // <context-param>
        if (elements("web-app", "context-param")) {
            currentName = null;
            currentValue = null;
        }

    }
1005022
public XMLWriter startElement(String element) {
        append("<" + element);
        if (rootElement && xmlns != null) {
            append(" xmlns=\"" + xmlns + "\"");
            rootElement = false;
        }
        append(">");
        elementStack.push(element);
        return this;
    }
255626
@Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (logger.isDebugEnabled())
            logger.debug("startElement(uri={}, localName={}, qName={}, attributes={}) - start", new Object[] { uri, localName, qName, attributes });

        try {
            ITableMetaData activeMetaData = getActiveMetaData();
            // Start of dataset
            if (activeMetaData == null && qName.equals(DATASET)) {
                _consumer.startDataSet();
                _orderedTableNameMap = new OrderedTableNameMap(_caseSensitiveTableNames);

                // SLAN register tables in the metadataset order
                if (_metaDataSet != null) {
                    for (String tableName : _metaDataSet.getTableNames()) {
                        _consumer.startTable(_metaDataSet.getTableMetaData(tableName));
                        _consumer.endTable();
                    }
                }

                return;
            }

            // New table
            if (isNewTable(qName)) {
                // If not first table, notify end of previous table to consumer
                if (activeMetaData != null) {
                    _consumer.endTable();
                }

                // In FlatXML the table might have appeared before already, so
                // check for this
                if (_orderedTableNameMap.containsTable(qName)) {
                    activeMetaData = (ITableMetaData) _orderedTableNameMap.get(qName);
                    _orderedTableNameMap.setLastTable(qName);
                } else {
                    activeMetaData = createTableMetaData(qName, attributes);
                    _orderedTableNameMap.add(activeMetaData.getTableName(), activeMetaData);
                }

                // Notify start of new table to consumer
                _consumer.startTable(activeMetaData);
                _lineNumber = 0;
            }

            // Row notification
            if (attributes.getLength() > 0) {
                // If we do not have a _metaDataSet or DTD
                if (_metaDataSet == null && (_dtdHandler == null || !_dtdHandler.isDtdPresent())) {
                    handleMissingColumns(attributes);
                    // Since a new MetaData object was created assign it to the
                    // local variable
                    activeMetaData = getActiveMetaData();
                }

                _lineNumber++;
                _lineNumberGlobal++;
                Column[] columns = activeMetaData.getColumns();
                Object[] rowValues = new Object[columns.length];
                for (int i = 0; i < columns.length; i++) {
                    Column column = columns[i];
                    rowValues[i] = getAttributeValueFromCache(attributes.getValue(column.getColumnName()));
                }
                _consumer.row(rowValues);
            }
        } catch (DataSetException e) {
            throw new SAXException(e);
        }
    }
1300283
def start(self):
        
        attrs = {
            (None, "to"): str(self._to),
            (None, "version"): ".".join(map(str, self._version))
        }
        if self._from:
            attrs[None, "from"] = str(self._from)

        self._writer.startDocument()
        for prefix, uri in self._nsmap_to_use.items():
            self._writer.startPrefixMapping(prefix, uri)
        self._writer.startElementNS(
            (namespaces.xmlstream, "stream"),
            None,
            attrs)
        self._writer.flush()
1353016
@Override
  public void startElement(String namespaceURI, String lName,
                           String qName, Attributes attrs) throws SAXException {
    switch (qName) {
      case RULE:
        inRule = true;
        id = attrs.getValue(ID);
        if (inRuleGroup) {
          subId++;
        }
        name = attrs.getValue(NAME);
        if (inRuleGroup && id == null) {
          id = ruleGroupId;
        }
        if (inRuleGroup && name == null) {
          name = ruleGroupName;
        }
        break;
      case "rules":
        language = Languages.getLanguageForShortCode(attrs.getValue("lang"));
        break;
      case PATTERN:
        inPattern = true;
        tokenCountForMarker = 0;
        if (attrs.getValue(CASE_SENSITIVE) != null && YES.equals(attrs.getValue(CASE_SENSITIVE))) {
          caseSensitive = true;
        }
        break;
      case ANTIPATTERN:
        inAntiPattern = true;
        antiPatternCounter++;
        caseSensitive = YES.equals(attrs.getValue(CASE_SENSITIVE));
        tokenCounter = 0;
        tokenCountForMarker = 0;
        break;
      case EXCEPTION:
        setExceptions(attrs);
        break;
      case AND:
        inAndGroup = true;
        tokenCountForMarker++;
        if (inUnification) {
          uniCounter++;
        }
        break;
      case UNIFY:
        inUnification = true;
        uniNegation = YES.equals(attrs.getValue(NEGATE));
        uniCounter = 0;
        break;
      case UNIFY_IGNORE:
        inUnificationNeutral = true;
        break;
      case "feature":
        uFeature = attrs.getValue(ID);
        break;
      case TYPE:
        uType = attrs.getValue(ID);
        uTypeList.add(uType);
        break;
      case TOKEN:
        setToken(attrs);
        if (!inAndGroup) {
          tokenCountForMarker++;
        }
        break;
      case DISAMBIG:
        inDisambiguation = true;
        disambiguatedPOS = attrs.getValue(POSTAG);
        if (attrs.getValue(ACTION) == null) {
          // default mode:
          disambigAction = DisambiguationPatternRule.DisambiguatorAction.REPLACE;
        } else {
          disambigAction = DisambiguationPatternRule.DisambiguatorAction
                  .valueOf(attrs.getValue(ACTION).toUpperCase(Locale.ENGLISH));
        }
        disamb = new StringBuilder();
        break;
      case MATCH:
        inMatch = true;
        match = new StringBuilder();
        Match.CaseConversion caseConversion = Match.CaseConversion.NONE;
        if (attrs.getValue("case_conversion") != null) {
          caseConversion = Match.CaseConversion.valueOf(attrs
                  .getValue("case_conversion").toUpperCase(Locale.ENGLISH));
        }
        Match.IncludeRange includeRange = Match.IncludeRange.NONE;
        if (attrs.getValue("include_skipped") != null) {
          includeRange = Match.IncludeRange.valueOf(attrs
                  .getValue("include_skipped").toUpperCase(Locale.ENGLISH));
        }
        Match mWorker = new Match(attrs.getValue(POSTAG), attrs
                .getValue("postag_replace"), YES
                .equals(attrs.getValue(POSTAG_REGEXP)), attrs
                .getValue("regexp_match"), attrs.getValue("regexp_replace"),
                caseConversion, YES.equals(attrs.getValue("setpos")),
                YES.equals(attrs.getValue("suppress_mispelled")),
                includeRange);
        if (inDisambiguation) {
          if (attrs.getValue(NO) != null) {
            int refNumber = Integer.parseInt(attrs.getValue(NO));
            refNumberSanityCheck(refNumber);
            mWorker.setTokenRef(refNumber);
            posSelector = mWorker;
          }
        } else if (inToken && attrs.getValue(NO) != null) {
          int refNumber = Integer.parseInt(attrs.getValue(NO));
          refNumberSanityCheck(refNumber);
          mWorker.setTokenRef(refNumber);
          tokenReference = mWorker;
          elements.append('\\');
          elements.append(refNumber);
        }
        break;
      case RULEGROUP:
        ruleGroupId = attrs.getValue(ID);
        ruleGroupName = attrs.getValue(NAME);
        inRuleGroup = true;
        subId = 0;
        if (rulegroupAntiPatterns != null) {
          rulegroupAntiPatterns.clear();
        }
        antiPatternCounter = 0;
        break;
      case UNIFICATION:
        uFeature = attrs.getValue(FEATURE);
        inUnificationDef = true;
        break;
      case "equivalence":
        uType = attrs.getValue(TYPE);
        break;
      case WD:
        wdLemma = attrs.getValue("lemma");
        wdPos = attrs.getValue("pos");
        inWord = true;
        wd = new StringBuilder();
        break;
      case EXAMPLE:
        inExample = true;
        if (untouchedExamples == null) {
          untouchedExamples = new ArrayList<>();
        }
        if (disambExamples == null) {
          disambExamples = new ArrayList<>();
        }
        untouched = attrs.getValue(TYPE).equals("untouched");
        if (attrs.getValue(TYPE).equals("ambiguous")) {
          input = attrs.getValue("inputform");
          output = attrs.getValue("outputform");
        }
        example = new StringBuilder();
        break;
      case "filter":
        filterClassName = attrs.getValue("class");
        filterArgs = attrs.getValue("args");
        break;
      case MARKER:
        example.append("<marker>");
        if (inPattern || inAntiPattern) {
          startPos = tokenCounter;
          inMarker = true;
        }
        break;
    }
  }
534518
public XMLSerializer startTag(String namespace, String name) throws IOException {
		if (startTagIncomplete) {
			closeStartTag();
		}
		seenBracket = seenBracketBracket = false;
		++depth;
		if (doIndent && depth > 0 && seenTag) {
			writeIndent();
		}
		seenTag = true;
		setPrefixCalled = false;
		startTagIncomplete = true;
		if ((depth + 1) >= elName.length) {
			ensureElementsCapacity();
		}
		//// assert namespace != null;

		if (checkNamesInterned && namesInterned)
			checkInterning(namespace);
		elNamespace[depth] = (namesInterned || namespace == null) ? namespace : namespace.intern();
		// assert name != null;
		// elName[ depth ] = name;
		if (checkNamesInterned && namesInterned)
			checkInterning(name);
		elName[depth] = (namesInterned || name == null) ? name : name.intern();
		if (out == null) {
			throw new IllegalStateException("setOutput() must called set before serialization can start");
		}
		out.write('<');
		if (namespace != null) {
			if (namespace.length() > 0) {
				// ALEK: in future make this algo a feature on serializer
				String prefix = null;
				if (depth > 0 && (namespaceEnd - elNamespaceCount[depth - 1]) == 1) {
					// if only one prefix was declared un-declare it if the
					// prefix is already declared on parent el with the same URI
					String uri = namespaceUri[namespaceEnd - 1];
					if (uri == namespace || uri.equals(namespace)) {
						String elPfx = namespacePrefix[namespaceEnd - 1];
						// 2 == to skip predefined namesapces (xml and xmlns
						// ...)
						for (int pos = elNamespaceCount[depth - 1] - 1; pos >= 2; --pos) {
							String pf = namespacePrefix[pos];
							if (pf == elPfx || pf.equals(elPfx)) {
								String n = namespaceUri[pos];
								if (n == uri || n.equals(uri)) {
									--namespaceEnd; // un-declare namespace:
													// this is kludge!
									prefix = elPfx;
								}
								break;
							}
						}
					}
				}
				if (prefix == null) {
					prefix = lookupOrDeclarePrefix(namespace);
				}
				// assert prefix != null;
				// make sure that default ("") namespace to not print ":"
				if (prefix.length() > 0) {
					elPrefix[depth] = prefix;
					out.write(prefix);
					out.write(':');
				} else {
					elPrefix[depth] = "";
				}
			} else {
				// make sure that default namespace can be declared
				for (int i = namespaceEnd - 1; i >= 0; --i) {
					if ("".equals(namespacePrefix[i])) {
						final String uri = namespaceUri[i];
						if (uri == null) {
							// declare default namespace
							setPrefix("", "");
						} else if (uri.length() > 0) {
							throw new IllegalStateException("start tag can not be written in empty default namespace " + "as default namespace is currently bound to '" + uri + "'" + getLocation());
						}
						break;
					}
				}
				elPrefix[depth] = "";
			}
		} else {
			elPrefix[depth] = "";
		}
		out.write(name);
		return this;
	}
94813
public void handleStartingTags(String name, Properties attributes) {
        // System.err.println("Start: " + name);
        if (ignore || ElementTags.IGNORE.equals(name)) {
            ignore = true;
            return;
        }

        // maybe there is some meaningful data that wasn't between tags
        if (currentChunk != null) {
            TextElementArray current;
            try {
                current = (TextElementArray) stack.pop();
            } catch (EmptyStackException ese) {
            	if (bf == null) {
            		current = new Paragraph("", new Font());
            	}
            	else {
            		current = new Paragraph("", new Font(this.bf));
            	}
            }
            current.add(currentChunk);
            stack.push(current);
            currentChunk = null;
        }

        // chunks
        if (ElementTags.CHUNK.equals(name)) {
            currentChunk = ElementFactory.getChunk(attributes);
            if (bf != null) {
            	currentChunk.setFont(new Font(this.bf));
            }
            return;
        }

        // symbols
        if (ElementTags.ENTITY.equals(name)) {
            Font f = new Font();
            if (currentChunk != null) {
                handleEndingTags(ElementTags.CHUNK);
                f = currentChunk.getFont();
            }
            currentChunk = EntitiesToSymbol.get(attributes.getProperty(ElementTags.ID),
                    f);
            return;
        }

        // phrases
        if (ElementTags.PHRASE.equals(name)) {
            stack.push(ElementFactory.getPhrase(attributes));
            return;
        }

        // anchors
        if (ElementTags.ANCHOR.equals(name)) {
            stack.push(ElementFactory.getAnchor(attributes));
            return;
        }

        // paragraphs and titles
        if (ElementTags.PARAGRAPH.equals(name) || ElementTags.TITLE.equals(name)) {
            stack.push(ElementFactory.getParagraph(attributes));
            return;
        }

        // lists
        if (ElementTags.LIST.equals(name)) {
            stack.push(ElementFactory.getList(attributes));
            return;
        }
        
        // listitems
        if (ElementTags.LISTITEM.equals(name)) {
            stack.push(ElementFactory.getListItem(attributes));
            return;
        }

        // cells
        if (ElementTags.CELL.equals(name)) {
            stack.push(ElementFactory.getCell(attributes));
            return;
        }

        // tables
        if (ElementTags.TABLE.equals(name)) {
            Table table = ElementFactory.getTable(attributes);
            float widths[] = table.getProportionalWidths();
            for (int i = 0; i < widths.length; i++) {
                if (widths[i] == 0) {
                    widths[i] = 100.0f / widths.length;
                }
            }
            try {
                table.setWidths(widths);
            } catch (BadElementException bee) {
                // this shouldn't happen
                throw new ExceptionConverter(bee);
            }
            stack.push(table);
            return;
        }

        // sections
        if (ElementTags.SECTION.equals(name)) {
            Element previous = (Element) stack.pop();
            Section section;
            try {
                section = ElementFactory.getSection((Section) previous, attributes);
            } catch (ClassCastException cce) {
                throw new ExceptionConverter(cce);
            }
            stack.push(previous);
            stack.push(section);
            return;
        }

        // chapters
        if (ElementTags.CHAPTER.equals(name)) {
            stack.push(ElementFactory.getChapter(attributes));
            return;
        }

        // images
        if (ElementTags.IMAGE.equals(name)) {
            try {
                Image img = ElementFactory.getImage(attributes);
                try {
                	addImage(img);
                    return;
                } catch (EmptyStackException ese) {
                    // if there is no element on the stack, the Image is added
                    // to the document
                    try {
                        document.add(img);
                    } catch (DocumentException de) {
                        throw new ExceptionConverter(de);
                    }
                    return;
                }
            } catch (Exception e) {
                throw new ExceptionConverter(e);
            }
        }

        // annotations
        if (ElementTags.ANNOTATION.equals(name)) {
            Annotation annotation = ElementFactory.getAnnotation(attributes);
            TextElementArray current;
            try {
                try {
                    current = (TextElementArray) stack.pop();
                    try {
                        current.add(annotation);
                    } catch (Exception e) {
                        document.add(annotation);
                    }
                    stack.push(current);
                } catch (EmptyStackException ese) {
                    document.add(annotation);
                }
                return;
            } catch (DocumentException de) {
                throw new ExceptionConverter(de);
            }
        }

        // newlines
        if (isNewline(name)) {
            TextElementArray current;
            try {
                current = (TextElementArray) stack.pop();
                current.add(Chunk.NEWLINE);
                stack.push(current);
            } catch (EmptyStackException ese) {
                if (currentChunk == null) {
                    try {
                        document.add(Chunk.NEWLINE);
                    } catch (DocumentException de) {
                        throw new ExceptionConverter(de);
                    }
                } else {
                    currentChunk.append("\n");
                }
            }
            return;
        }

        // newpage
        if (isNewpage(name)) {
            TextElementArray current;
            try {
                current = (TextElementArray) stack.pop();
                Chunk newPage = new Chunk("");
                newPage.setNewPage();
                if (bf != null) {
                	newPage.setFont(new Font(this.bf));
                }
                current.add(newPage);
                stack.push(current);
            } catch (EmptyStackException ese) {
                document.newPage();
            }
            return;
        }

        if (ElementTags.HORIZONTALRULE.equals(name)) {
            TextElementArray current;
            LineSeparator hr = new LineSeparator(1.0f, 100.0f, null, Element.ALIGN_CENTER, 0);
            try {
                current = (TextElementArray) stack.pop();
                current.add(hr);
                stack.push(current);
            } catch (EmptyStackException ese) {
                try {
                    document.add(hr);
                } catch (DocumentException de) {
                    throw new ExceptionConverter(de);
                }
            }
            return;
        }
        
        // documentroot
        if (isDocumentRoot(name)) {
            String key;
            String value;
            // pagesize and orientation specific code suggested by Samuel Gabriel
            // Updated by Ricardo Coutinho. Only use if set in html!
			Rectangle pageSize = null;
			String orientation = null;
            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();
        }

    }