1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
|
/*
* $Id: Parser.java,v 1.10 2005/11/01 12:27:05 psoares33 Exp $
* $Name: $
*
* Copyright 2005 by Bruno Lowagie.
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999-2005 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000-2005 by Paulo Soares. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* http://www.lowagie.com/iText/
*/
package com.lowagie.text.markup;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.EmptyStackException;
import java.util.Properties;
import java.util.Stack;
import java.util.StringTokenizer;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.SimpleCell;
import com.lowagie.text.SimpleTable;
import com.lowagie.text.TextElementArray;
import com.lowagie.text.html.HtmlWriter;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfDestination;
import com.lowagie.text.pdf.PdfOutline;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.rtf.RtfWriter;
/**
* This class allows you to parse files in a tree.
*/
public class Parser extends DefaultHandler {
/* Stacks */
protected Stack filestack;
protected Stack outline;
protected Stack tagstack;
protected Stack objectstack;
protected Chunk currentChunk = null;
/* Output objects */
protected Document document;
protected PdfWriter writer;
/* Counters */
protected String title;
protected String[] structures;
protected String[] titles;
protected int[] counterParents;
protected int[] counters;
protected int previoustitle = -1;
/* Markup properties */
protected MarkupParser markup;
/**
* Constructs a recursive parser object.
* @param srcfile the file that has to be parsed.
*/
public Parser(String srcfile) {
this(srcfile, "title", null, null, null);
}
/**
* Constructs a recursive parser object.
* @param srcfile the file that has to be parsed
* @param title the value of the id selector marking a title
* @param structures an array with the values of the class selectors marking titles in the complete structure
* @param titles the strings that have to be added to the titlenumber
* @param counterParents an array with references from each child in the structure to its parent
*/
public Parser(String srcfile, String title, String[] structures, String[] titles, int[] counterParents) {
// stacks
tagstack = new Stack();
objectstack = new Stack();
filestack = new Stack();
filestack.push(srcfile);
this.title = title;
if (structures == null || titles == null || counterParents == null) {
counters = new int[0];
}
else {
this.structures = structures;
this.titles = titles;
this.counterParents = counterParents;
counters = new int[counterParents.length];
}
// create the document
document = new Document();
// parse the file
try {
parse();
} catch (Exception e) {
e.printStackTrace();
}
while(flushObject());
// close the document
document.close();
}
/**
* @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
//System.err.println("start: " + qName);
// push tagname and attributes to the stack
Properties attrs = new Properties();
attrs.put(MarkupTags.ITEXT_TAG, qName);
for (int i = 0; i < attributes.getLength(); i++) {
attrs.put(attributes.getQName(i), attributes.getValue(i));
}
tagstack.push(attrs);
// add the object to the objectstack
if (document.isOpen()) {
// first we flush the content that wasn't inside a tag.
flushCurrentChunk();
// we ask the markup parser for the corresponing object.
Element element = markup.getObject(attrs);
if (element != null) {
switch(element.type()) {
case Element.PHRASE:
addObject((Phrase)element);
break;
case Element.PARAGRAPH:
addObject((Paragraph)element);
break;
case Element.TABLE:
addObject((SimpleTable)element);
break;
case Element.CELL:
addObject((SimpleCell)element);
break;
}
}
}
else {
// check if the document should be opened
if (MarkupTags.HTML_TAG_BODY.equals(qName)) {
Rectangle rect = markup.getRectangle(attrs);
if (rect != null) document.setPageSize(rect);
document.open();
if (writer != null) {
outline = new Stack();
PdfContentByte cb = writer.getDirectContent();
outline.push(cb.getRootOutline());
}
}
else if (MarkupTags.HTML_TAG_LINK.equals(qName) && MarkupTags.HTML_ATTR_STYLESHEET.equals(attrs.getProperty(MarkupTags.HTML_ATTR_REL))) {
String parent = new File((String)filestack.peek()).getParent();
String markupfile = attrs.getProperty(MarkupTags.HTML_ATTR_HREF);
if (markupfile.startsWith("/")) {
markupfile = parent + markupfile;
}
else {
markupfile = parent + "/" + markupfile;
}
markup = new MarkupParser(markupfile);
}
}
}
/**
* 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) {
String content = new String(ch, start, length);
//System.err.println("Characters: " + 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);
}
}
addToCurrentChunk(buf.toString());
}
/**
* @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
*/
public void endElement(String uri, String localName, String qName) throws SAXException {
//System.err.println("end: " + qName);
Properties attrs = (Properties)tagstack.peek();
PdfOutline bookmark = null;
flushCurrentChunk();
if (attrs != null && title.equals(attrs.getProperty(MarkupTags.HTML_ATTR_CSS_ID)) && outline != null) {
PdfOutline parent = (PdfOutline)outline.peek();
PdfDestination dest = new PdfDestination(PdfDestination.FITH, writer.getVerticalPosition(false));
Paragraph p = (Paragraph)objectstack.peek();
bookmark = new PdfOutline(parent, dest, p);
}
tagstack.pop();
flushObject();
if(markup.getPageBreakAfter(attrs)) {
while(flushObject());
try {
document.newPage();
}
catch(DocumentException de) {
// this shouldn't happen
}
}
if (bookmark != null) {
outline.push(bookmark);
}
}
/**
* @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String)
*/
public void processingInstruction(String instruction, String parameter)
throws SAXException {
//System.err.println("Processing: " + instruction);
try {
// parse all the sublevels of the current directory
if ("parse".equals(instruction)) {
String file;
StringTokenizer sublevels = new StringTokenizer(parameter, ",");
while (sublevels.hasMoreTokens()) {
file = sublevels.nextToken();
if (filestack.size() > 0) file = new File((String)filestack.peek()).getParent() + "/" + file.trim();
filestack.push(file);
parse();
}
}
if (document.isOpen()) return;
// start listening with the PDF writer
if ("pdfwriter".equals(instruction)) {
writer = PdfWriter.getInstance(document, new FileOutputStream(parameter));
}
else if ("htmlwriter".equals(instruction)) {
HtmlWriter.getInstance(document, new FileOutputStream(parameter));
}
else if ("rtfwriter".equals(instruction)) {
RtfWriter.getInstance(document, new FileOutputStream(parameter));
}
}
catch(Exception e) {
throw new SAXException(e);
}
}
/** flushing the CurrentChunk. */
private void flushCurrentChunk() {
if (currentChunk == null || !document.isOpen()) return;
TextElementArray current;
try {
current = (TextElementArray) objectstack.pop();
} catch (EmptyStackException ese) {
current = new Paragraph();
}
current.add(currentChunk);
objectstack.push(current);
currentChunk = null;
}
/** extending the CurrentChunk.
* @param s*/
private void addToCurrentChunk(String s) {
if (currentChunk != null) {
currentChunk.append(s);
}
else {
try {
currentChunk = new Chunk(s, ((Phrase) objectstack.peek()).font());
} catch (Exception e) {
currentChunk = new Chunk(s);
}
}
}
/**
* Creates a new Object and puts it on top of the objectstack.
* @param phrase
*/
private void addObject(Phrase phrase) {
// we put the element on top of the objectstack
objectstack.push(phrase);
}
/**
* Creates a new Object and puts it on top of the objectstack.
* @param table
*/
private void addObject(SimpleTable table) {
// we put the element on top of the objectstack
objectstack.push(table);
}
/**
* Creates a new Object and puts it on top of the objectstack.
* @param cell
*/
private void addObject(SimpleCell cell) {
// we put the element on top of the objectstack
objectstack.push(cell);
}
/**
* Creates a new Object and puts it on top of the objectstack.
* @param paragraph
*/
private void addObject(Paragraph paragraph) {
// now we get the attributes on top of the tagstack
Properties attrs = (Properties)tagstack.peek();
if (attrs == null) {
return;
}
// if it's a Paragraph, it could be a title
if (title.equals(attrs.getProperty(MarkupTags.HTML_ATTR_CSS_ID))) {
for (int i = 0; i < counters.length; i++) {
// where does this title fit in the hierarchy of the document?
if (structures[i].equals(attrs.getProperty(MarkupTags.HTML_ATTR_CSS_CLASS))) {
// we increment the number of this hierarchy element
counters[i]++;
while (previoustitle > -1 && counterParents[previoustitle] >= counterParents[i]) {
outline.pop();
previoustitle = counterParents[previoustitle];
}
previoustitle = i;
// we set the counter of the child to 0 if necessary
for (int j = i + 1; j < counters.length; j++) {
if (counterParents[j] == i && titles[j] == null) {
counters[j] = 0;
break;
}
}
// we construct the string that will proceed the title
String s = titles[i];
if (s == null) {
s = "";
int j = counterParents[i];
while (j > 1) {
s = String.valueOf(counters[j]) + "." + s;
j = counterParents[j];
}
if (i > 0) {
s += String.valueOf(counters[i]) + " ";
}
}
else {
s += " " + counters[i] + ": ";
}
paragraph.add(new Chunk(s));
}
}
}
if(markup.getPageBreakBefore(attrs)) {
while(flushObject());
try {
document.newPage();
}
catch(DocumentException de) {
// this shouldn't happen
}
}
// we put the element on top of the objectstack
objectstack.push(paragraph);
}
/**
* Deals with the object on top of the objectstack.
* @return false if there was no valid object on the objectstack.
*/
private boolean flushObject() {
if (objectstack.size() == 0) {
return false;
}
Element current = (Element) objectstack.pop();
try {
TextElementArray previous = (TextElementArray) objectstack.peek();
previous.add(current);
//objectstack.push(previous);
return true;
} catch (EmptyStackException ese) {
try {
document.add(current);
return true;
} catch (DocumentException e) {
return false;
}
}
}
/**
* Gets the file on top of the filestack,
* parses it
* and removes it from the stack.
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
private void parse() throws ParserConfigurationException, IOException, SAXException {
// gets the file on top of the filestack
String file = (String) filestack.peek();
//System.err.println("Parsing: " + file);
// create the parser
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxParserFactory.newSAXParser();
XMLReader parser = saxParser.getXMLReader();
parser.setContentHandler(this);
// parse the file
parser.parse(new InputSource(file));
// remove the file from the stack
filestack.pop();
}
}
|