src/ant/.ant.properties 100644 0 0 3322 11224570760 12540 0 ustar 0 0 releasenumber=2.1.7
releasedate=2009-07-07
itext.home=../..
itext.src=${itext.home}/src
itext.www=${itext.home}/www
itext.build=${itext.home}/build
itext.lib=${itext.home}/lib
itext.jar=${itext.lib}/iText.jar
jfreechart.jar=${itext.lib}/jfreechart.jar
jcommon.jar=${itext.lib}/jcommon.jar
servlet.jar=${itext.lib}/servlet.jar
bc.jdk=jdk14
bc.version=138
lib.bcmail=bcmail-${bc.jdk}-${bc.version}.jar
lib.bcprov=bcprov-${bc.jdk}-${bc.version}.jar
lib.bctsp=bctsp-${bc.jdk}-${bc.version}.jar
lib.dom4j=pdf-renderer.jar
lib.pdf-renderer=dom4j-1.6.1.jar
itext.src.lowagie=${itext.www}/lowagie
itext.src.tutorial=${itext.www}/tutorial
itext.src.examples=${itext.www}/examples
itext.bin=${itext.build}/bin
itext.docs=${itext.build}/docs
itext.lowagie=${itext.build}/lowagie
itext.tutorial=${itext.build}/tutorial
itext.examples=${itext.build}/examples
itext.webapp=${itext.build}/webapp
itext.release=${itext.build}/release
itext.downloads=${itext.build}/downloads
itext.dist=${itext.release}/dist
itext.sf=${itext.release}/sf
itext.maven=${itext.release}/maven
itext.bin.temp=${itext.build}/bin.temp
itext.jnlp=${itext.build}/jnlp
itext.rups.src=${itext.src}/rups
itext.rups.bin=${itext.build}/bin.rups
itext.rups.jar=${itext.lib}/iText-rups.jar
itext.toolbox.src=${itext.src}/toolbox
itext.toolbox.bin=${itext.build}/bin.toolbox
itext.toolbox.jar=${itext.lib}/iText-toolbox.jar
itext.rtf.src=${itext.src}/rtf
itext.rtf.bin=${itext.build}/bin.rtf
itext.rtf.jar=${itext.lib}/iText-rtf.jar
itext.keystore.filename=${itext.lib}/.keystore
itext.keystore.password=dummypass
itext.keystore.alias=itext
itext.keystore.storetype=jks
itext.keystore.dname=CN=iText Self-Signed Certificate
itext.jdk.core=1.4
itext.jdk.rups=1.5
itext.jdk.toolbox=1.5 src/ant/.ant.test.properties 100644 0 0 627 11000354002 13460 0 ustar 0 0 itext.home=..
itext.build=${itext.home}/build
itext.lib=${itext.home}/lib
junit.jar=${itext.lib}/junit-4.4.jar
itext.src.test=${itext.home}/test
itext.bin.examples=${itext.build}/bin.examples
itext.bin.test=${itext.build}/test
itext.bin.data=${itext.build}/test.data
itext.reports=${itext.build}/reports
itext.rtf.test=${itext.build}/test.rtf
itext.jdk.examples=1.4
itext.jdk.test=1.5
src/ant/compile.xml 100644 0 0 21223 11213370067 11750 0 ustar 0 0
Anchor
can be a reference or a destination of a reference.
*
* An Anchor
is a special kind of Phrase
.
* It is constructed in the same way.
*
* Example: *
* * @see Element * @see Phrase */ public class Anchor extends Phrase { // constant private static final long serialVersionUID = -852278536049236911L; // membervariables /** This is the name of the* Anchor anchor = new Anchor("this is a link"); * anchor.setName("LINK"); * anchor.setReference("http://www.lowagie.com"); *
Anchor
. */
protected String name = null;
/** This is the reference of the Anchor
. */
protected String reference = null;
// constructors
/**
* Constructs an Anchor
without specifying a leading.
*/
public Anchor() {
super(16);
}
/**
* Constructs an Anchor
with a certain leading.
*
* @param leading the leading
*/
public Anchor(float leading) {
super(leading);
}
/**
* Constructs an Anchor
with a certain Chunk
.
*
* @param chunk a Chunk
*/
public Anchor(Chunk chunk) {
super(chunk);
}
/**
* Constructs an Anchor
with a certain String
.
*
* @param string a String
*/
public Anchor(String string) {
super(string);
}
/**
* Constructs an Anchor
with a certain String
* and a certain Font
.
*
* @param string a String
* @param font a Font
*/
public Anchor(String string, Font font) {
super(string, font);
}
/**
* Constructs an Anchor
with a certain Chunk
* and a certain leading.
*
* @param leading the leading
* @param chunk a Chunk
*/
public Anchor(float leading, Chunk chunk) {
super(leading, chunk);
}
/**
* Constructs an Anchor
with a certain leading
* and a certain String
.
*
* @param leading the leading
* @param string a String
*/
public Anchor(float leading, String string) {
super(leading, string);
}
/**
* Constructs an Anchor
with a certain leading,
* a certain String
and a certain Font
.
*
* @param leading the leading
* @param string a String
* @param font a Font
*/
public Anchor(float leading, String string, Font font) {
super(leading, string, font);
}
/**
* Constructs an Anchor
with a certain Phrase
.
*
* @param phrase a Phrase
*/
public Anchor(Phrase phrase) {
super(phrase);
if (phrase instanceof Anchor) {
Anchor a = (Anchor) phrase;
setName(a.name);
setReference(a.reference);
}
}
// implementation of the Element-methods
/**
* Processes the element by adding it (or the different parts) to an
* ElementListener
.
*
* @param listener an ElementListener
* @return true
if the element was processed successfully
*/
public boolean process(ElementListener listener) {
try {
Chunk chunk;
Iterator i = getChunks().iterator();
boolean localDestination = (reference != null && reference.startsWith("#"));
boolean notGotoOK = true;
while (i.hasNext()) {
chunk = (Chunk) i.next();
if (name != null && notGotoOK && !chunk.isEmpty()) {
chunk.setLocalDestination(name);
notGotoOK = false;
}
if (localDestination) {
chunk.setLocalGoto(reference.substring(1));
}
listener.add(chunk);
}
return true;
}
catch(DocumentException de) {
return false;
}
}
/**
* Gets all the chunks in this element.
*
* @return an ArrayList
*/
public ArrayList getChunks() {
ArrayList tmp = new ArrayList();
Chunk chunk;
Iterator i = iterator();
boolean localDestination = (reference != null && reference.startsWith("#"));
boolean notGotoOK = true;
while (i.hasNext()) {
chunk = (Chunk) i.next();
if (name != null && notGotoOK && !chunk.isEmpty()) {
chunk.setLocalDestination(name);
notGotoOK = false;
}
if (localDestination) {
chunk.setLocalGoto(reference.substring(1));
}
else if (reference != null)
chunk.setAnchor(reference);
tmp.add(chunk);
}
return tmp;
}
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return Element.ANCHOR;
}
// methods
/**
* Sets the name of this Anchor
.
*
* @param name a new name
*/
public void setName(String name) {
this.name = name;
}
/**
* Sets the reference of this Anchor
.
*
* @param reference a new reference
*/
public void setReference(String reference) {
this.reference = reference;
}
// methods to retrieve information
/**
* Returns the name of this Anchor
.
*
* @return a name
*/
public String getName() {
return name;
}
/**
* Gets the reference of this Anchor
.
*
* @return a reference
*/
public String getReference() {
return reference;
}
/**
* Gets the reference of this Anchor
.
*
* @return an URL
*/
public URL getUrl() {
try {
return new URL(reference);
}
catch(MalformedURLException mue) {
return null;
}
}
}
src/core/com/lowagie/text/Annotation.java 100644 0 0 35422 11012562273 16117 0 ustar 0 0 /*
* $Id: Annotation.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
/**
* An Annotation
is a little note that can be added to a page on
* a document.
*
* @see Element
* @see Anchor
*/
public class Annotation implements Element {
// membervariables
/** This is a possible annotation type. */
public static final int TEXT = 0;
/** This is a possible annotation type. */
public static final int URL_NET = 1;
/** This is a possible annotation type. */
public static final int URL_AS_STRING = 2;
/** This is a possible annotation type. */
public static final int FILE_DEST = 3;
/** This is a possible annotation type. */
public static final int FILE_PAGE = 4;
/** This is a possible annotation type. */
public static final int NAMED_DEST = 5;
/** This is a possible annotation type. */
public static final int LAUNCH = 6;
/** This is a possible annotation type. */
public static final int SCREEN = 7;
/** This is a possible attribute. */
public static final String TITLE = "title";
/** This is a possible attribute. */
public static final String CONTENT = "content";
/** This is a possible attribute. */
public static final String URL = "url";
/** This is a possible attribute. */
public static final String FILE = "file";
/** This is a possible attribute. */
public static final String DESTINATION = "destination";
/** This is a possible attribute. */
public static final String PAGE = "page";
/** This is a possible attribute. */
public static final String NAMED = "named";
/** This is a possible attribute. */
public static final String APPLICATION = "application";
/** This is a possible attribute. */
public static final String PARAMETERS = "parameters";
/** This is a possible attribute. */
public static final String OPERATION = "operation";
/** This is a possible attribute. */
public static final String DEFAULTDIR = "defaultdir";
/** This is a possible attribute. */
public static final String LLX = "llx";
/** This is a possible attribute. */
public static final String LLY = "lly";
/** This is a possible attribute. */
public static final String URX = "urx";
/** This is a possible attribute. */
public static final String URY = "ury";
/** This is a possible attribute. */
public static final String MIMETYPE = "mime";
/** This is the type of annotation. */
protected int annotationtype;
/** This is the title of the Annotation
. */
protected HashMap annotationAttributes = new HashMap();
/** This is the lower left x-value */
protected float llx = Float.NaN;
/** This is the lower left y-value */
protected float lly = Float.NaN;
/** This is the upper right x-value */
protected float urx = Float.NaN;
/** This is the upper right y-value */
protected float ury = Float.NaN;
// constructors
/**
* Constructs an Annotation
with a certain title and some
* text.
*
* @param llx
* lower left x coordinate
* @param lly
* lower left y coordinate
* @param urx
* upper right x coordinate
* @param ury
* upper right y coordinate
*/
private Annotation(float llx, float lly, float urx, float ury) {
this.llx = llx;
this.lly = lly;
this.urx = urx;
this.ury = ury;
}
/**
* Copy constructor.
*/
public Annotation(Annotation an) {
annotationtype = an.annotationtype;
annotationAttributes = an.annotationAttributes;
llx = an.llx;
lly = an.lly;
urx = an.urx;
ury = an.ury;
}
/**
* Constructs an Annotation
with a certain title and some
* text.
*
* @param title
* the title of the annotation
* @param text
* the content of the annotation
*/
public Annotation(String title, String text) {
annotationtype = TEXT;
annotationAttributes.put(TITLE, title);
annotationAttributes.put(CONTENT, text);
}
/**
* Constructs an Annotation
with a certain title and some
* text.
*
* @param title
* the title of the annotation
* @param text
* the content of the annotation
* @param llx
* the lower left x-value
* @param lly
* the lower left y-value
* @param urx
* the upper right x-value
* @param ury
* the upper right y-value
*/
public Annotation(String title, String text, float llx, float lly,
float urx, float ury) {
this(llx, lly, urx, ury);
annotationtype = TEXT;
annotationAttributes.put(TITLE, title);
annotationAttributes.put(CONTENT, text);
}
/**
* Constructs an Annotation
.
*
* @param llx
* the lower left x-value
* @param lly
* the lower left y-value
* @param urx
* the upper right x-value
* @param ury
* the upper right y-value
* @param url
* the external reference
*/
public Annotation(float llx, float lly, float urx, float ury, URL url) {
this(llx, lly, urx, ury);
annotationtype = URL_NET;
annotationAttributes.put(URL, url);
}
/**
* Constructs an Annotation
.
*
* @param llx
* the lower left x-value
* @param lly
* the lower left y-value
* @param urx
* the upper right x-value
* @param ury
* the upper right y-value
* @param url
* the external reference
*/
public Annotation(float llx, float lly, float urx, float ury, String url) {
this(llx, lly, urx, ury);
annotationtype = URL_AS_STRING;
annotationAttributes.put(FILE, url);
}
/**
* Constructs an Annotation
.
*
* @param llx
* the lower left x-value
* @param lly
* the lower left y-value
* @param urx
* the upper right x-value
* @param ury
* the upper right y-value
* @param file
* an external PDF file
* @param dest
* the destination in this file
*/
public Annotation(float llx, float lly, float urx, float ury, String file,
String dest) {
this(llx, lly, urx, ury);
annotationtype = FILE_DEST;
annotationAttributes.put(FILE, file);
annotationAttributes.put(DESTINATION, dest);
}
/**
* Creates a Screen annotation to embed media clips
*
* @param llx
* @param lly
* @param urx
* @param ury
* @param moviePath
* path to the media clip file
* @param mimeType
* mime type of the media
* @param showOnDisplay
* if true play on display of the page
*/
public Annotation(float llx, float lly, float urx, float ury,
String moviePath, String mimeType, boolean showOnDisplay) {
this(llx, lly, urx, ury);
annotationtype = SCREEN;
annotationAttributes.put(FILE, moviePath);
annotationAttributes.put(MIMETYPE, mimeType);
annotationAttributes.put(PARAMETERS, new boolean[] {
false /* embedded */, showOnDisplay });
}
/**
* Constructs an Annotation
.
*
* @param llx
* the lower left x-value
* @param lly
* the lower left y-value
* @param urx
* the upper right x-value
* @param ury
* the upper right y-value
* @param file
* an external PDF file
* @param page
* a page number in this file
*/
public Annotation(float llx, float lly, float urx, float ury, String file,
int page) {
this(llx, lly, urx, ury);
annotationtype = FILE_PAGE;
annotationAttributes.put(FILE, file);
annotationAttributes.put(PAGE, new Integer(page));
}
/**
* Constructs an Annotation
.
*
* @param llx
* the lower left x-value
* @param lly
* the lower left y-value
* @param urx
* the upper right x-value
* @param ury
* the upper right y-value
* @param named
* a named destination in this file
*/
public Annotation(float llx, float lly, float urx, float ury, int named) {
this(llx, lly, urx, ury);
annotationtype = NAMED_DEST;
annotationAttributes.put(NAMED, new Integer(named));
}
/**
* Constructs an Annotation
.
*
* @param llx
* the lower left x-value
* @param lly
* the lower left y-value
* @param urx
* the upper right x-value
* @param ury
* the upper right y-value
* @param application
* an external application
* @param parameters
* parameters to pass to this application
* @param operation
* the operation to pass to this application
* @param defaultdir
* the default directory to run this application in
*/
public Annotation(float llx, float lly, float urx, float ury,
String application, String parameters, String operation,
String defaultdir) {
this(llx, lly, urx, ury);
annotationtype = LAUNCH;
annotationAttributes.put(APPLICATION, application);
annotationAttributes.put(PARAMETERS, parameters);
annotationAttributes.put(OPERATION, operation);
annotationAttributes.put(DEFAULTDIR, defaultdir);
}
// implementation of the Element-methods
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return Element.ANNOTATION;
}
/**
* Processes the element by adding it (or the different parts) to an
* ElementListener
.
*
* @param listener
* an ElementListener
* @return true
if the element was processed successfully
*/
public boolean process(ElementListener listener) {
try {
return listener.add(this);
} catch (DocumentException de) {
return false;
}
}
/**
* Gets all the chunks in this element.
*
* @return an ArrayList
*/
public ArrayList getChunks() {
return new ArrayList();
}
// methods
/**
* Sets the dimensions of this annotation.
*
* @param llx
* the lower left x-value
* @param lly
* the lower left y-value
* @param urx
* the upper right x-value
* @param ury
* the upper right y-value
*/
public void setDimensions(float llx, float lly, float urx, float ury) {
this.llx = llx;
this.lly = lly;
this.urx = urx;
this.ury = ury;
}
// methods to retrieve information
/**
* Returns the lower left x-value.
*
* @return a value
*/
public float llx() {
return llx;
}
/**
* Returns the lower left y-value.
*
* @return a value
*/
public float lly() {
return lly;
}
/**
* Returns the upper right x-value.
*
* @return a value
*/
public float urx() {
return urx;
}
/**
* Returns the upper right y-value.
*
* @return a value
*/
public float ury() {
return ury;
}
/**
* Returns the lower left x-value.
*
* @param def
* the default value
* @return a value
*/
public float llx(float def) {
if (Float.isNaN(llx))
return def;
return llx;
}
/**
* Returns the lower left y-value.
*
* @param def
* the default value
* @return a value
*/
public float lly(float def) {
if (Float.isNaN(lly))
return def;
return lly;
}
/**
* Returns the upper right x-value.
*
* @param def
* the default value
* @return a value
*/
public float urx(float def) {
if (Float.isNaN(urx))
return def;
return urx;
}
/**
* Returns the upper right y-value.
*
* @param def
* the default value
* @return a value
*/
public float ury(float def) {
if (Float.isNaN(ury))
return def;
return ury;
}
/**
* Returns the type of this Annotation
.
*
* @return a type
*/
public int annotationType() {
return annotationtype;
}
/**
* Returns the title of this Annotation
.
*
* @return a name
*/
public String title() {
String s = (String) annotationAttributes.get(TITLE);
if (s == null)
s = "";
return s;
}
/**
* Gets the content of this Annotation
.
*
* @return a reference
*/
public String content() {
String s = (String) annotationAttributes.get(CONTENT);
if (s == null)
s = "";
return s;
}
/**
* Gets the content of this Annotation
.
*
* @return a reference
*/
public HashMap attributes() {
return annotationAttributes;
}
/**
* @see com.lowagie.text.Element#isContent()
* @since iText 2.0.8
*/
public boolean isContent() {
return true;
}
/**
* @see com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return true;
}
} src/core/com/lowagie/text/BadElementException.java 100644 0 0 6576 11012562273 17654 0 ustar 0 0 /*
* $Id: BadElementException.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
/**
* Signals an attempt to create an Element
that hasn't got the right form.
*
* @see DocumentException
* @see Cell
* @see Table
*/
public class BadElementException extends DocumentException {
private static final long serialVersionUID = -799006030723822254L;
// constructors
/**
* Constructs a BadElementException
* @param ex an Exception object that has to be turned into a BadElementException
*/
public BadElementException(Exception ex) {
super(ex);
}
/**
* Constructs a BadElementException
without a message.
*/
BadElementException() {
super();
}
/**
* Constructs a BadElementException
with a message.
* @param message a message describing the exception
*/
public BadElementException(String message) {
super(message);
}
} src/core/com/lowagie/text/Cell.java 100644 0 0 52540 11012562273 14664 0 ustar 0 0 /*
* $Id: Cell.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.util.ArrayList;
import java.util.Iterator;
import com.lowagie.text.pdf.PdfPCell;
/**
* A Cell
is a Rectangle
containing other
* Element
s.
*
* A Cell
must be added to a Table
.
* The Table
will place the Cell
in
* a Row
.
*
* Example: *
* * @see Rectangle * @see Element * @see Table * @see Row */ public class Cell extends Rectangle implements TextElementArray { // membervariables /** * The* Table table = new Table(3); * table.setBorderWidth(1); * table.setBorderColor(new Color(0, 0, 255)); * table.setCellpadding(5); * table.setCellspacing(5); * Cell cell = new Cell("header"); * cell.setHeader(true); * cell.setColspan(3); * table.addCell(cell); * cell = new Cell("example cell with colspan 1 and rowspan 2"); * cell.setRowspan(2); * cell.setBorderColor(new Color(255, 0, 0)); * table.addCell(cell); * table.addCell("1.1"); * table.addCell("2.1"); * table.addCell("1.2"); * table.addCell("2.2"); *
ArrayList
of Element
s
* that are part of the content of the Cell.
*/
protected ArrayList arrayList = null;
/** The horizontal alignment of the cell content. */
protected int horizontalAlignment = Element.ALIGN_UNDEFINED;
/** The vertical alignment of the cell content. */
protected int verticalAlignment = Element.ALIGN_UNDEFINED;
/**
* The width of the cell as a String.
* It can be an absolute value "100" or a percentage "20%".
*/
protected float width;
protected boolean percentage = false;
/** The colspan of the cell. */
protected int colspan = 1;
/** The rowspan of the cell. */
protected int rowspan = 1;
/** The leading of the content inside the cell. */
float leading = Float.NaN;
/** Is this Cell
a header? */
protected boolean header;
/**
* Maximum number of lines allowed in the cell.
* The default value of this property is not to limit the maximum number of lines
* (contributed by dperezcar@fcc.es)
*/
protected int maxLines = Integer.MAX_VALUE;
/**
* If a truncation happens due to the maxLines property, then this text will
* be added to indicate a truncation has happened.
* Default value is null, and means avoiding marking the truncation.
* A useful value of this property could be e.g. "..."
* (contributed by dperezcar@fcc.es)
*/
String showTruncation;
/**
* Indicates that the largest ascender height should be used to determine the
* height of the first line. Note that this only has an effect when rendered
* to PDF. Setting this to true can help with vertical alignment problems.
*/
protected boolean useAscender = false;
/**
* Indicates that the largest descender height should be added to the height of
* the last line (so characters like y don't dip into the border). Note that
* this only has an effect when rendered to PDF.
*/
protected boolean useDescender = false;
/**
* Adjusts the cell contents to compensate for border widths. Note that
* this only has an effect when rendered to PDF.
*/
protected boolean useBorderPadding;
/** Does this Cell
force a group change? */
protected boolean groupChange = true;
// constructors
/** Constructs an empty Cell
. */
public Cell() {
// creates a Rectangle with BY DEFAULT a border of 0.5
super(0, 0, 0, 0);
setBorder(UNDEFINED);
setBorderWidth(0.5f);
// initializes the arraylist
arrayList = new ArrayList();
}
/**
* Constructs an empty Cell
(for internal use only).
*
* @param dummy a dummy value
*/
public Cell(boolean dummy) {
this();
arrayList.add(new Paragraph(0));
}
/**
* Constructs a Cell
with a certain content.
* The String
will be converted into a Paragraph
.
* @param content a String
*/
public Cell(String content) {
this();
try {
addElement(new Paragraph(content));
}
catch(BadElementException bee) {
}
}
/**
* Constructs a Cell
with a certain Element
.
* if the element is a ListItem
, Row
or
* Cell
, an exception will be thrown.
*
* @param element the element
* @throws BadElementException when the creator was called with a ListItem
, Row
or Cell
*/
public Cell(Element element) throws BadElementException {
this();
if(element instanceof Phrase) {
setLeading(((Phrase)element).getLeading());
}
addElement(element);
}
// implementation of the Element-methods
/**
* Processes the element by adding it (or the different parts) to an
* ElementListener
.
*
* @param listener an ElementListener
* @return true
if the element was processed successfully
*/
public boolean process(ElementListener listener) {
try {
return listener.add(this);
}
catch(DocumentException de) {
return false;
}
}
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return Element.CELL;
}
/**
* Gets all the chunks in this element.
*
* @return an ArrayList
*/
public ArrayList getChunks() {
ArrayList tmp = new ArrayList();
for (Iterator i = arrayList.iterator(); i.hasNext(); ) {
tmp.addAll(((Element) i.next()).getChunks());
}
return tmp;
}
// Getters and setters
/**
* Gets the horizontal alignment.
*
* @return a value
*/
public int getHorizontalAlignment() {
return horizontalAlignment;
}
/**
* Sets the horizontal alignment.
* @param value the new value
*/
public void setHorizontalAlignment(int value) {
horizontalAlignment = value;
}
/**
* Sets the alignment of this cell.
* This methods allows you to set the alignment as a String.
* @param alignment the new alignment as a String
*/
public void setHorizontalAlignment(String alignment) {
setHorizontalAlignment(ElementTags.alignmentValue(alignment));
}
/**
* Gets the vertical alignment.
* @return a value
*/
public int getVerticalAlignment() {
return verticalAlignment;
}
/**
* Sets the vertical alignment.
* @param value the new value
*/
public void setVerticalAlignment(int value) {
verticalAlignment = value;
}
/**
* Sets the alignment of this paragraph.
*
* @param alignment the new alignment as a String
*/
public void setVerticalAlignment(String alignment) {
setVerticalAlignment(ElementTags.alignmentValue(alignment));
}
/**
* Sets the width.
*
* @param value the new value
*/
public void setWidth(float value) {
this.width = value;
}
/**
* Sets the width.
* It can be an absolute value "100" or a percentage "20%"
*
* @param value the new value
*/
public void setWidth(String value) {
if (value.endsWith("%")) {
value = value.substring(0, value.length() - 1);
percentage = true;
}
width = Integer.parseInt(value);
}
/**
* Gets the width.
*/
public float getWidth() {
return width;
}
/**
* Gets the width as a String.
*
* @return a value
*/
public String getWidthAsString() {
String w = String.valueOf(width);
if (w.endsWith(".0")) w = w.substring(0, w.length() - 2);
if (percentage) w += "%";
return w;
}
/**
* Sets the colspan.
*
* @param value the new value
*/
public void setColspan(int value) {
colspan = value;
}
/**
* Gets the colspan.
* @return a value
*/
public int getColspan() {
return colspan;
}
/**
* Sets the rowspan.
*
* @param value the new value
*/
public void setRowspan(int value) {
rowspan = value;
}
/**
* Gets the rowspan.
* @return a value
*/
public int getRowspan() {
return rowspan;
}
/**
* Sets the leading.
*
* @param value the new value
*/
public void setLeading(float value) {
leading = value;
}
/**
* Gets the leading.
*
* @return a value
*/
public float getLeading() {
if (Float.isNaN(leading)) {
return 16;
}
return leading;
}
/**
* Sets header.
*
* @param value the new value
*/
public void setHeader(boolean value) {
header = value;
}
/**
* Is this Cell
a header?
*
* @return a value
*/
public boolean isHeader() {
return header;
}
/**
* Setter for maxLines
* @param value the maximum number of lines
*/
public void setMaxLines(int value) {
maxLines = value;
}
/**
* Getter for maxLines
* @return the maxLines value
*/
public int getMaxLines() {
return maxLines;
}
/**
* Setter for showTruncation
* @param value Can be null for avoiding marking the truncation.
*/
public void setShowTruncation(String value) {
showTruncation = value;
}
/**
* Getter for showTruncation
* @return the showTruncation value
*/
public String getShowTruncation() {
return showTruncation;
}
/**
* Sets the value of useAscender.
* @param use use ascender height if true
*/
public void setUseAscender(boolean use) {
useAscender = use;
}
/**
* Gets the value of useAscender
* @return useAscender
*/
public boolean isUseAscender() {
return useAscender;
}
/**
* Sets the value of useDescender.
* @param use use descender height if true
*/
public void setUseDescender(boolean use) {
useDescender = use;
}
/**
* gets the value of useDescender
* @return useDescender
*/
public boolean isUseDescender() {
return useDescender;
}
/**
* Sets the value of useBorderPadding.
* @param use adjust layout for borders if true
*/
public void setUseBorderPadding(boolean use) {
useBorderPadding = use;
}
/**
* Gets the value of useBorderPadding.
* @return useBorderPadding
*/
public boolean isUseBorderPadding() {
return useBorderPadding;
}
/**
* Does this Cell
force a group change?
*
* @return a value
*/
public boolean getGroupChange() {
return groupChange;
}
/**
* Sets group change.
*
* @param value the new value
*/
public void setGroupChange(boolean value) {
groupChange = value;
}
// arraylist stuff
/**
* Gets the number of Element
s in the Cell.
*
* @return a size
.
*/
public int size() {
return arrayList.size();
}
/**
* Gets an iterator of Element
s.
*
* @return an Iterator
.
*/
public Iterator getElements() {
return arrayList.iterator();
}
/**
* Clears all the Element
s of this Cell
.
*/
public void clear() {
arrayList.clear();
}
/**
* Checks if the Cell
is empty.
*
* @return false
if there are non-empty Element
s in the Cell
.
*/
public boolean isEmpty() {
switch(size()) {
case 0:
return true;
case 1:
Element element = (Element) arrayList.get(0);
switch (element.type()) {
case Element.CHUNK:
return ((Chunk) element).isEmpty();
case Element.ANCHOR:
case Element.PHRASE:
case Element.PARAGRAPH:
return ((Phrase) element).isEmpty();
case Element.LIST:
return ((List) element).isEmpty();
}
return false;
default:
return false;
}
}
/**
* Makes sure there is at least 1 object in the Cell.
*
* Otherwise it might not be shown in the table.
*/
void fill() {
if (size() == 0) arrayList.add(new Paragraph(0));
}
/**
* Checks if this Cell
is a placeholder for a (nested) table.
*
* @return true if the only element in this cell is a table
*/
public boolean isTable() {
return (size() == 1)
&& (((Element)arrayList.get(0)).type() == Element.TABLE);
}
/**
* Adds an element to this Cell
.
*
* Remark: you can't add ListItem
s, Row
s, Cell
s,
* JPEG
s, GIF
s or PNG
s to a Cell
.
*
* @param element The Element
to add
* @throws BadElementException if the method was called with a ListItem
, Row
or Cell
*/
public void addElement(Element element) throws BadElementException {
if (isTable()) {
Table table = (Table) arrayList.get(0);
Cell tmp = new Cell(element);
tmp.setBorder(NO_BORDER);
tmp.setColspan(table.getColumns());
table.addCell(tmp);
return;
}
switch(element.type()) {
case Element.LISTITEM:
case Element.ROW:
case Element.CELL:
throw new BadElementException("You can't add listitems, rows or cells to a cell.");
case Element.LIST:
List list = (List)element;
if (Float.isNaN(leading)) {
setLeading(list.getTotalLeading());
}
if (list.isEmpty()) return;
arrayList.add(element);
return;
case Element.ANCHOR:
case Element.PARAGRAPH:
case Element.PHRASE:
Phrase p = (Phrase)element;
if (Float.isNaN(leading)) {
setLeading(p.getLeading());
}
if (p.isEmpty()) return;
arrayList.add(element);
return;
case Element.CHUNK:
if (((Chunk) element).isEmpty()) return;
arrayList.add(element);
return;
case Element.TABLE:
Table table = new Table(3);
float[] widths = new float[3];
widths[1] = ((Table)element).getWidth();
switch(((Table)element).getAlignment()) {
case Element.ALIGN_LEFT:
widths[0] = 0f;
widths[2] = 100f - widths[1];
break;
case Element.ALIGN_CENTER:
widths[0] = (100f - widths[1]) / 2f;
widths[2] = widths[0];
break;
case Element.ALIGN_RIGHT:
widths[0] = 100f - widths[1];
widths[2] = 0f;
}
table.setWidths(widths);
Cell tmp;
if (arrayList.isEmpty()) {
table.addCell(getDummyCell());
}
else {
tmp = new Cell();
tmp.setBorder(NO_BORDER);
tmp.setColspan(3);
for (Iterator i = arrayList.iterator(); i.hasNext(); ) {
tmp.add(i.next());
}
table.addCell(tmp);
}
tmp = new Cell();
tmp.setBorder(NO_BORDER);
table.addCell(tmp);
table.insertTable((Table)element);
tmp = new Cell();
tmp.setBorder(NO_BORDER);
table.addCell(tmp);
table.addCell(getDummyCell());
clear();
arrayList.add(table);
return;
default:
arrayList.add(element);
}
}
/**
* Add an Object
to this cell.
*
* @param o the object to add
* @return always true
*/
public boolean add(Object o) {
try {
this.addElement((Element) o);
return true;
}
catch(ClassCastException cce) {
throw new ClassCastException("You can only add objects that implement the Element interface.");
}
catch(BadElementException bee) {
throw new ClassCastException(bee.getMessage());
}
}
// helper methods
/**
* Get dummy cell used when merging inner tables.
* @return a cell with colspan 3 and no border
*/
private static Cell getDummyCell() {
Cell cell = new Cell(true);
cell.setColspan(3);
cell.setBorder(NO_BORDER);
return cell;
}
/**
* Creates a PdfPCell based on this Cell object.
* @return a PdfPCell
* @throws BadElementException
*/
public PdfPCell createPdfPCell() throws BadElementException {
if (rowspan > 1) throw new BadElementException("PdfPCells can't have a rowspan > 1");
if (isTable()) return new PdfPCell(((Table)arrayList.get(0)).createPdfPTable());
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(verticalAlignment);
cell.setHorizontalAlignment(horizontalAlignment);
cell.setColspan(colspan);
cell.setUseBorderPadding(useBorderPadding);
cell.setUseDescender(useDescender);
cell.setLeading(getLeading(), 0);
cell.cloneNonPositionParameters(this);
cell.setNoWrap(getMaxLines() == 1);
for (Iterator i = getElements(); i.hasNext(); ) {
Element e = (Element)i.next();
if (e.type() == Element.PHRASE || e.type() == Element.PARAGRAPH) {
Paragraph p = new Paragraph((Phrase)e);
p.setAlignment(horizontalAlignment);
e = p;
}
cell.addElement(e);
}
return cell;
}
// unsupported Rectangle methods
/**
* This method throws an UnsupportedOperationException
.
* @return NA
*/
public float getTop() {
throw new UnsupportedOperationException("Dimensions of a Cell can't be calculated. See the FAQ.");
}
/**
* This method throws an UnsupportedOperationException
.
* @return NA
*/
public float getBottom() {
throw new UnsupportedOperationException("Dimensions of a Cell can't be calculated. See the FAQ.");
}
/**
* This method throws an UnsupportedOperationException
.
* @return NA
*/
public float getLeft() {
throw new UnsupportedOperationException("Dimensions of a Cell can't be calculated. See the FAQ.");
}
/**
* This method throws an UnsupportedOperationException
.
* @return NA
*/
public float getRight() {
throw new UnsupportedOperationException("Dimensions of a Cell can't be calculated. See the FAQ.");
}
/**
* This method throws an UnsupportedOperationException
.
* @param margin
* @return NA
*/
public float top(int margin) {
throw new UnsupportedOperationException("Dimensions of a Cell can't be calculated. See the FAQ.");
}
/**
* This method throws an UnsupportedOperationException
.
* @param margin
* @return NA
*/
public float bottom(int margin) {
throw new UnsupportedOperationException("Dimensions of a Cell can't be calculated. See the FAQ.");
}
/**
* This method throws an UnsupportedOperationException
.
* @param margin
* @return NA
*/
public float left(int margin) {
throw new UnsupportedOperationException("Dimensions of a Cell can't be calculated. See the FAQ.");
}
/**
* This method throws an UnsupportedOperationException
.
* @param margin NA
* @return NA
*/
public float right(int margin) {
throw new UnsupportedOperationException("Dimensions of a Cell can't be calculated. See the FAQ.");
}
/**
* This method throws an UnsupportedOperationException
.
* @param value NA
*/
public void setTop(int value) {
throw new UnsupportedOperationException("Dimensions of a Cell are attributed automagically. See the FAQ.");
}
/**
* This method throws an UnsupportedOperationException
.
* @param value NA
*/
public void setBottom(int value) {
throw new UnsupportedOperationException("Dimensions of a Cell are attributed automagically. See the FAQ.");
}
/**
* This method throws an UnsupportedOperationException
.
* @param value NA
*/
public void setLeft(int value) {
throw new UnsupportedOperationException("Dimensions of a Cell are attributed automagically. See the FAQ.");
}
/**
* This method throws an UnsupportedOperationException
.
* @param value NA
*/
public void setRight(int value) {
throw new UnsupportedOperationException("Dimensions of a Cell are attributed automagically. See the FAQ.");
}
}
src/core/com/lowagie/text/Chapter.java 100644 0 0 12031 11012562273 15362 0 ustar 0 0 /*
* $Id: Chapter.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.util.ArrayList;
/**
* A Chapter
is a special Section
.
*
* A chapter number has to be created using a Paragraph
as title
* and an int
as chapter number. The chapter number is shown be
* default. If you don't want to see the chapter number, you have to set the
* numberdepth to 0.
*
* Example: *
*/ public class Chapter extends Section { // constant private static final long serialVersionUID = 1791000695779357361L; /** * Constructs a new* Paragraph title2 = new Paragraph("This is Chapter 2", FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLDITALIC, new Color(0, 0, 255))); * Chapter chapter2 = new Chapter(title2, 2); * chapter2.setNumberDepth(0); * Paragraph someText = new Paragraph("This is some text"); * chapter2.add(someText); * Paragraph title21 = new Paragraph("This is Section 1 in Chapter 2", FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD, new Color(255, 0, 0))); * Section section1 = chapter2.addSection(title21); * Paragraph someSectionText = new Paragraph("This is some silly paragraph in a chapter and/or section. It contains some text to test the functionality of Chapters and Section."); * section1.add(someSectionText); *
Chapter
.
* @param number the Chapter number
*/
public Chapter(int number) {
super(null, 1);
numbers = new ArrayList();
numbers.add(new Integer(number));
triggerNewPage = true;
}
/**
* Constructs a new Chapter
.
*
* @param title the Chapter title (as a Paragraph
)
* @param number the Chapter number
*/
public Chapter(Paragraph title, int number) {
super(title, 1);
numbers = new ArrayList();
numbers.add(new Integer(number));
triggerNewPage = true;
}
/**
* Constructs a new Chapter
.
*
* @param title the Chapter title (as a String
)
* @param number the Chapter number
*/
public Chapter(String title, int number) {
this(new Paragraph(title), number);
}
// implementation of the Element-methods
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return Element.CHAPTER;
}
/**
* @see com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return false;
}
} src/core/com/lowagie/text/ChapterAutoNumber.java 100644 0 0 10431 11106243445 17367 0 ustar 0 0 /*
* Copyright 2005 by Michael Niedermair.
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
/**
* Chapter with auto numbering.
*
* @author Michael Niedermair
*/
public class ChapterAutoNumber extends Chapter {
// constant
private static final long serialVersionUID = -9217457637987854167L;
/**
* Is the chapter number already set?
* @since 2.1.4
*/
protected boolean numberSet = false;
/**
* Create a new object.
*
* @param para the Chapter title (as a Paragraph
)
*/
public ChapterAutoNumber(final Paragraph para) {
super(para, 0);
}
/**
* Create a new object.
*
* @param title the Chapter title (as a String
)
*/
public ChapterAutoNumber(final String title) {
super(title, 0);
}
/**
* Create a new section for this chapter and ad it.
*
* @param title the Section title (as a String
)
* @return Returns the new section.
*/
public Section addSection(final String title) {
if (isAddedCompletely()) {
throw new IllegalStateException("This LargeElement has already been added to the Document.");
}
return addSection(title, 2);
}
/**
* Create a new section for this chapter and add it.
*
* @param title the Section title (as a Paragraph
)
* @return Returns the new section.
*/
public Section addSection(final Paragraph title) {
if (isAddedCompletely()) {
throw new IllegalStateException("This LargeElement has already been added to the Document.");
}
return addSection(title, 2);
}
/**
* Changes the Chapter number.
* @param number the new chapter number
* @since 2.1.4
*/
public int setAutomaticNumber(int number) {
if (!numberSet) {
number++;
super.setChapterNumber(number);
numberSet = true;
}
return number;
}
}
src/core/com/lowagie/text/Chunk.java 100644 0 0 57071 11036112746 15063 0 ustar 0 0 /*
* $Id: Chunk.java 3427 2008-05-24 18:32:31Z xlv $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.awt.Color;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import com.lowagie.text.pdf.HyphenationEvent;
import com.lowagie.text.pdf.PdfAction;
import com.lowagie.text.pdf.PdfAnnotation;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.draw.DrawInterface;
/**
* This is the smallest significant part of text that can be added to a
* document.
*
* Most elements can be divided in one or more Chunk
s. A chunk
* is a String
with a certain Font
. All other
* layout parameters should be defined in the object to which this chunk of text
* is added.
*
* Example:
* **/ public class Chunk implements Element { // public static membervariables /** The character stand in for an image or a separator. */ public static final String OBJECT_REPLACEMENT_CHARACTER = "\ufffc"; /** This is a Chunk containing a newline. */ public static final Chunk NEWLINE = new Chunk("\n"); /** This is a Chunk containing a newpage. */ public static final Chunk NEXTPAGE = new Chunk(""); static { NEXTPAGE.setNewPage(); } // member variables /** This is the content of this chunk of text. */ protected StringBuffer content = null; /** This is the* * Chunk chunk = new Chunk("Hello world", * FontFactory.getFont(FontFactory.COURIER, 20, Font.ITALIC, new Color(255, 0, * 0))); document.add(chunk); * ** *
Font
of this chunk of text. */
protected Font font = null;
/** Contains some of the attributes for this Chunk. */
protected HashMap attributes = null;
// constructors
/**
* Empty constructor.
*/
public Chunk() {
this.content = new StringBuffer();
this.font = new Font();
}
/**
* A Chunk
copy constructor.
* @param ck the Chunk
to be copied
*/
public Chunk(Chunk ck) {
if (ck.content != null) {
content = new StringBuffer(ck.content.toString());
}
if (ck.font != null) {
font = new Font(ck.font);
}
if (ck.attributes != null) {
attributes = new HashMap(ck.attributes);
}
}
/**
* Constructs a chunk of text with a certain content and a certain
* Font
.
*
* @param content
* the content
* @param font
* the font
*/
public Chunk(String content, Font font) {
this.content = new StringBuffer(content);
this.font = font;
}
/**
* Constructs a chunk of text with a certain content, without specifying a
* Font
.
*
* @param content
* the content
*/
public Chunk(String content) {
this(content, new Font());
}
/**
* Constructs a chunk of text with a char and a certain Font
.
*
* @param c
* the content
* @param font
* the font
*/
public Chunk(char c, Font font) {
this.content = new StringBuffer();
this.content.append(c);
this.font = font;
}
/**
* Constructs a chunk of text with a char, without specifying a Font
*
.
*
* @param c
* the content
*/
public Chunk(char c) {
this(c, new Font());
}
/**
* Constructs a chunk containing an Image
.
*
* @param image
* the image
* @param offsetX
* the image offset in the x direction
* @param offsetY
* the image offset in the y direction
*/
public Chunk(Image image, float offsetX, float offsetY) {
this(OBJECT_REPLACEMENT_CHARACTER, new Font());
Image copyImage = Image.getInstance(image);
copyImage.setAbsolutePosition(Float.NaN, Float.NaN);
setAttribute(IMAGE, new Object[] { copyImage, new Float(offsetX),
new Float(offsetY), Boolean.FALSE });
}
/**
* Key for drawInterface of the Separator.
* @since 2.1.2
*/
public static final String SEPARATOR = "SEPARATOR";
/**
* Creates a separator Chunk.
* Note that separator chunks can't be used in combination with tab chunks!
* @param separator the drawInterface to use to draw the separator.
* @since 2.1.2
*/
public Chunk(DrawInterface separator) {
this(separator, false);
}
/**
* Creates a separator Chunk.
* Note that separator chunks can't be used in combination with tab chunks!
* @param separator the drawInterface to use to draw the separator.
* @param vertical true if this is a vertical separator
* @since 2.1.2
*/
public Chunk(DrawInterface separator, boolean vertical) {
this(OBJECT_REPLACEMENT_CHARACTER, new Font());
setAttribute(SEPARATOR, new Object[] {separator, Boolean.valueOf(vertical)});
}
/**
* Key for drawInterface of the tab.
* @since 2.1.2
*/
public static final String TAB = "TAB";
/**
* Creates a tab Chunk.
* Note that separator chunks can't be used in combination with tab chunks!
* @param separator the drawInterface to use to draw the tab.
* @param tabPosition an X coordinate that will be used as start position for the next Chunk.
* @since 2.1.2
*/
public Chunk(DrawInterface separator, float tabPosition) {
this(separator, tabPosition, false);
}
/**
* Creates a tab Chunk.
* Note that separator chunks can't be used in combination with tab chunks!
* @param separator the drawInterface to use to draw the tab.
* @param tabPosition an X coordinate that will be used as start position for the next Chunk.
* @param newline if true, a newline will be added if the tabPosition has already been reached.
* @since 2.1.2
*/
public Chunk(DrawInterface separator, float tabPosition, boolean newline) {
this(OBJECT_REPLACEMENT_CHARACTER, new Font());
if (tabPosition < 0) {
throw new IllegalArgumentException("A tab position may not be lower than 0; yours is " + tabPosition);
}
setAttribute(TAB, new Object[] {separator, new Float(tabPosition), Boolean.valueOf(newline), new Float(0)});
}
/**
* Constructs a chunk containing an Image
.
*
* @param image
* the image
* @param offsetX
* the image offset in the x direction
* @param offsetY
* the image offset in the y direction
* @param changeLeading
* true if the leading has to be adapted to the image
*/
public Chunk(Image image, float offsetX, float offsetY,
boolean changeLeading) {
this(OBJECT_REPLACEMENT_CHARACTER, new Font());
setAttribute(IMAGE, new Object[] { image, new Float(offsetX),
new Float(offsetY), Boolean.valueOf(changeLeading) });
}
// implementation of the Element-methods
/**
* Processes the element by adding it (or the different parts) to an
* ElementListener
.
*
* @param listener
* an ElementListener
* @return true
if the element was processed successfully
*/
public boolean process(ElementListener listener) {
try {
return listener.add(this);
} catch (DocumentException de) {
return false;
}
}
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return Element.CHUNK;
}
/**
* Gets all the chunks in this element.
*
* @return an ArrayList
*/
public ArrayList getChunks() {
ArrayList tmp = new ArrayList();
tmp.add(this);
return tmp;
}
// methods that change the member variables
/**
* appends some text to this Chunk
.
*
* @param string
* String
* @return a StringBuffer
*/
public StringBuffer append(String string) {
return content.append(string);
}
/**
* Sets the font of this Chunk
.
*
* @param font
* a Font
*/
public void setFont(Font font) {
this.font = font;
}
// methods to retrieve information
/**
* Gets the font of this Chunk
.
*
* @return a Font
*/
public Font getFont() {
return font;
}
/**
* Returns the content of this Chunk
.
*
* @return a String
*/
public String getContent() {
return content.toString();
}
/**
* Returns the content of this Chunk
.
*
* @return a String
*/
public String toString() {
return getContent();
}
/**
* Checks is this Chunk
is empty.
*
* @return false
if the Chunk contains other characters than
* space.
*/
public boolean isEmpty() {
return (content.toString().trim().length() == 0)
&& (content.toString().indexOf("\n") == -1)
&& (attributes == null);
}
/**
* Gets the width of the Chunk in points.
*
* @return a width in points
*/
public float getWidthPoint() {
if (getImage() != null) {
return getImage().getScaledWidth();
}
return font.getCalculatedBaseFont(true).getWidthPoint(getContent(),
font.getCalculatedSize())
* getHorizontalScaling();
}
// attributes
/**
* Checks the attributes of this Chunk
.
*
* @return false if there aren't any.
*/
public boolean hasAttributes() {
return attributes != null;
}
/**
* Gets the attributes for this Chunk
.
*
* It may be null.
*
* @return the attributes for this Chunk
*/
public HashMap getAttributes() {
return attributes;
}
/**
* Sets the attributes all at once.
* @param attributes the attributes of a Chunk
*/
public void setAttributes(HashMap attributes) {
this.attributes = attributes;
}
/**
* Sets an arbitrary attribute.
*
* @param name
* the key for the attribute
* @param obj
* the value of the attribute
* @return this Chunk
*/
private Chunk setAttribute(String name, Object obj) {
if (attributes == null)
attributes = new HashMap();
attributes.put(name, obj);
return this;
}
// the attributes are ordered as they appear in the book 'iText in Action'
/** Key for text horizontal scaling. */
public static final String HSCALE = "HSCALE";
/**
* Sets the text horizontal scaling. A value of 1 is normal and a value of
* 0.5f shrinks the text to half it's width.
*
* @param scale
* the horizontal scaling factor
* @return this Chunk
*/
public Chunk setHorizontalScaling(float scale) {
return setAttribute(HSCALE, new Float(scale));
}
/**
* Gets the horizontal scaling.
*
* @return a percentage in float
*/
public float getHorizontalScaling() {
if (attributes == null)
return 1f;
Float f = (Float) attributes.get(HSCALE);
if (f == null)
return 1f;
return f.floatValue();
}
/** Key for underline. */
public static final String UNDERLINE = "UNDERLINE";
/**
* Sets an horizontal line that can be an underline or a strikethrough.
* Actually, the line can be anywhere vertically and has always the
* Chunk
width. Multiple call to this method will produce multiple
* lines.
*
* @param thickness
* the absolute thickness of the line
* @param yPosition
* the absolute y position relative to the baseline
* @return this Chunk
*/
public Chunk setUnderline(float thickness, float yPosition) {
return setUnderline(null, thickness, 0f, yPosition, 0f,
PdfContentByte.LINE_CAP_BUTT);
}
/**
* Sets an horizontal line that can be an underline or a strikethrough.
* Actually, the line can be anywhere vertically and has always the
* Chunk
width. Multiple call to this method will produce multiple
* lines.
*
* @param color
* the color of the line or null
to follow the
* text color
* @param thickness
* the absolute thickness of the line
* @param thicknessMul
* the thickness multiplication factor with the font size
* @param yPosition
* the absolute y position relative to the baseline
* @param yPositionMul
* the position multiplication factor with the font size
* @param cap
* the end line cap. Allowed values are
* PdfContentByte.LINE_CAP_BUTT, PdfContentByte.LINE_CAP_ROUND
* and PdfContentByte.LINE_CAP_PROJECTING_SQUARE
* @return this Chunk
*/
public Chunk setUnderline(Color color, float thickness, float thicknessMul,
float yPosition, float yPositionMul, int cap) {
if (attributes == null)
attributes = new HashMap();
Object obj[] = {
color,
new float[] { thickness, thicknessMul, yPosition, yPositionMul, cap } };
Object unders[][] = Utilities.addToArray((Object[][]) attributes.get(UNDERLINE),
obj);
return setAttribute(UNDERLINE, unders);
}
/** Key for sub/superscript. */
public static final String SUBSUPSCRIPT = "SUBSUPSCRIPT";
/**
* Sets the text displacement relative to the baseline. Positive values rise
* the text, negative values lower the text.
*
* It can be used to implement sub/superscript.
*
* @param rise
* the displacement in points
* @return this Chunk
*/
public Chunk setTextRise(float rise) {
return setAttribute(SUBSUPSCRIPT, new Float(rise));
}
/**
* Gets the text displacement relative to the baseline.
*
* @return a displacement in points
*/
public float getTextRise() {
if (attributes != null && attributes.containsKey(SUBSUPSCRIPT)) {
Float f = (Float) attributes.get(SUBSUPSCRIPT);
return f.floatValue();
}
return 0.0f;
}
/** Key for text skewing. */
public static final String SKEW = "SKEW";
/**
* Skews the text to simulate italic and other effects. Try alpha=0
*
and beta=12
.
*
* @param alpha
* the first angle in degrees
* @param beta
* the second angle in degrees
* @return this Chunk
*/
public Chunk setSkew(float alpha, float beta) {
alpha = (float) Math.tan(alpha * Math.PI / 180);
beta = (float) Math.tan(beta * Math.PI / 180);
return setAttribute(SKEW, new float[] { alpha, beta });
}
/** Key for background. */
public static final String BACKGROUND = "BACKGROUND";
/**
* Sets the color of the background Chunk
.
*
* @param color
* the color of the background
* @return this Chunk
*/
public Chunk setBackground(Color color) {
return setBackground(color, 0, 0, 0, 0);
}
/**
* Sets the color and the size of the background Chunk
.
*
* @param color
* the color of the background
* @param extraLeft
* increase the size of the rectangle in the left
* @param extraBottom
* increase the size of the rectangle in the bottom
* @param extraRight
* increase the size of the rectangle in the right
* @param extraTop
* increase the size of the rectangle in the top
* @return this Chunk
*/
public Chunk setBackground(Color color, float extraLeft, float extraBottom,
float extraRight, float extraTop) {
return setAttribute(BACKGROUND, new Object[] { color,
new float[] { extraLeft, extraBottom, extraRight, extraTop } });
}
/** Key for text rendering mode. */
public static final String TEXTRENDERMODE = "TEXTRENDERMODE";
/**
* Sets the text rendering mode. It can outline text, simulate bold and make
* text invisible.
*
* @param mode
* the text rendering mode. It can be
* PdfContentByte.TEXT_RENDER_MODE_FILL
,
* PdfContentByte.TEXT_RENDER_MODE_STROKE
,
* PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE
and
* PdfContentByte.TEXT_RENDER_MODE_INVISIBLE
.
* @param strokeWidth
* the stroke line width for the modes
* PdfContentByte.TEXT_RENDER_MODE_STROKE
and
* PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE
.
* @param strokeColor
* the stroke color or null
to follow the text
* color
* @return this Chunk
*/
public Chunk setTextRenderMode(int mode, float strokeWidth,
Color strokeColor) {
return setAttribute(TEXTRENDERMODE, new Object[] { new Integer(mode),
new Float(strokeWidth), strokeColor });
}
/** Key for split character. */
public static final String SPLITCHARACTER = "SPLITCHARACTER";
/**
* Sets the split characters.
*
* @param splitCharacter
* the SplitCharacter
interface
* @return this Chunk
*/
public Chunk setSplitCharacter(SplitCharacter splitCharacter) {
return setAttribute(SPLITCHARACTER, splitCharacter);
}
/** Key for hyphenation. */
public static final String HYPHENATION = "HYPHENATION";
/**
* sets the hyphenation engine to this Chunk
.
*
* @param hyphenation
* the hyphenation engine
* @return this Chunk
*/
public Chunk setHyphenation(HyphenationEvent hyphenation) {
return setAttribute(HYPHENATION, hyphenation);
}
/** Key for remote goto. */
public static final String REMOTEGOTO = "REMOTEGOTO";
/**
* Sets a goto for a remote destination for this Chunk
.
*
* @param filename
* the file name of the destination document
* @param name
* the name of the destination to go to
* @return this Chunk
*/
public Chunk setRemoteGoto(String filename, String name) {
return setAttribute(REMOTEGOTO, new Object[] { filename, name });
}
/**
* Sets a goto for a remote destination for this Chunk
.
*
* @param filename
* the file name of the destination document
* @param page
* the page of the destination to go to. First page is 1
* @return this Chunk
*/
public Chunk setRemoteGoto(String filename, int page) {
return setAttribute(REMOTEGOTO, new Object[] { filename,
new Integer(page) });
}
/** Key for local goto. */
public static final String LOCALGOTO = "LOCALGOTO";
/**
* Sets a local goto for this Chunk
.
*
* There must be a local destination matching the name.
*
* @param name
* the name of the destination to go to
* @return this Chunk
*/
public Chunk setLocalGoto(String name) {
return setAttribute(LOCALGOTO, name);
}
/** Key for local destination. */
public static final String LOCALDESTINATION = "LOCALDESTINATION";
/**
* Sets a local destination for this Chunk
.
*
* @param name
* the name for this destination
* @return this Chunk
*/
public Chunk setLocalDestination(String name) {
return setAttribute(LOCALDESTINATION, name);
}
/** Key for generic tag. */
public static final String GENERICTAG = "GENERICTAG";
/**
* Sets the generic tag Chunk
.
*
* The text for this tag can be retrieved with PdfPageEvent
.
*
* @param text
* the text for the tag
* @return this Chunk
*/
public Chunk setGenericTag(String text) {
return setAttribute(GENERICTAG, text);
}
/** Key for image. */
public static final String IMAGE = "IMAGE";
/**
* Returns the image.
*
* @return the image
*/
public Image getImage() {
if (attributes == null)
return null;
Object obj[] = (Object[]) attributes.get(Chunk.IMAGE);
if (obj == null)
return null;
else {
return (Image) obj[0];
}
}
/** Key for Action. */
public static final String ACTION = "ACTION";
/**
* Sets an action for this Chunk
.
*
* @param action
* the action
* @return this Chunk
*/
public Chunk setAction(PdfAction action) {
return setAttribute(ACTION, action);
}
/**
* Sets an anchor for this Chunk
.
*
* @param url
* the URL
to link to
* @return this Chunk
*/
public Chunk setAnchor(URL url) {
return setAttribute(ACTION, new PdfAction(url.toExternalForm()));
}
/**
* Sets an anchor for this Chunk
.
*
* @param url
* the url to link to
* @return this Chunk
*/
public Chunk setAnchor(String url) {
return setAttribute(ACTION, new PdfAction(url));
}
/** Key for newpage. */
public static final String NEWPAGE = "NEWPAGE";
/**
* Sets a new page tag..
*
* @return this Chunk
*/
public Chunk setNewPage() {
return setAttribute(NEWPAGE, null);
}
/** Key for annotation. */
public static final String PDFANNOTATION = "PDFANNOTATION";
/**
* Sets a generic annotation to this Chunk
.
*
* @param annotation
* the annotation
* @return this Chunk
*/
public Chunk setAnnotation(PdfAnnotation annotation) {
return setAttribute(PDFANNOTATION, annotation);
}
/**
* @see com.lowagie.text.Element#isContent()
* @since iText 2.0.8
*/
public boolean isContent() {
return true;
}
/**
* @see com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return true;
}
/**
* Returns the hyphenation (if present).
* @since 2.1.2
*/
public HyphenationEvent getHyphenation() {
if (attributes == null) return null;
return (HyphenationEvent) attributes.get(Chunk.HYPHENATION);
}
// keys used in PdfChunk
/** Key for color. */
public static final String COLOR = "COLOR";
/** Key for encoding. */
public static final String ENCODING = "ENCODING";
} src/core/com/lowagie/text/DocListener.java 100644 0 0 12543 11213370070 16212 0 ustar 0 0 /*
* $Id: DocListener.java 3939 2009-05-27 13:09:45Z blowagie $
*
* Copyright (c) 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
/**
* A class that implements DocListener
will perform some
* actions when some actions are performed on a Document
.
*
* @see ElementListener
* @see Document
* @see DocWriter
*/
public interface DocListener extends ElementListener {
// methods
/**
* Signals that the Document
has been opened and that
* Elements
can be added.
*/
public void open(); // [L1]
/**
* Signals that the Document
was closed and that no other
* Elements
will be added.
*
* The outputstream of every writer implementing DocListener
will be closed.
*/
public void close(); // [L2]
/**
* Signals that an new page has to be started.
*
* @return true
if the page was added, false
if not.
*/
public boolean newPage(); // [L3]
/**
* Sets the pagesize.
*
* @param pageSize the new pagesize
* @return a boolean
*/
public boolean setPageSize(Rectangle pageSize); // [L4]
/**
* Sets the margins.
*
* @param marginLeft the margin on the left
* @param marginRight the margin on the right
* @param marginTop the margin on the top
* @param marginBottom the margin on the bottom
* @return a boolean
*/
public boolean setMargins(float marginLeft, float marginRight, float marginTop, float marginBottom); // [L5]
/**
* Parameter that allows you to do left/right margin mirroring (odd/even pages)
* @param marginMirroring
* @return true if successful
*/
public boolean setMarginMirroring(boolean marginMirroring); // [L6]
/**
* Parameter that allows you to do top/bottom margin mirroring (odd/even pages)
* @param marginMirroringTopBottom
* @return true if successful
* @since 2.1.6
*/
public boolean setMarginMirroringTopBottom(boolean marginMirroringTopBottom); // [L6]
/**
* Sets the page number.
*
* @param pageN the new page number
*/
public void setPageCount(int pageN); // [L7]
/**
* Sets the page number to 0.
*/
public void resetPageCount(); // [L8]
/**
* Changes the header of this document.
*
* @param header the new header
*/
public void setHeader(HeaderFooter header); // [L9]
/**
* Resets the header of this document.
*/
public void resetHeader(); // [L10]
/**
* Changes the footer of this document.
*
* @param footer the new footer
*/
public void setFooter(HeaderFooter footer); // [L11]
/**
* Resets the footer of this document.
*/
public void resetFooter(); // [L12]
} src/core/com/lowagie/text/DocWriter.java 100644 0 0 31646 11213370070 15706 0 ustar 0 0 /*
* $Id: DocWriter.java 3937 2009-05-27 12:56:48Z blowagie $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Properties;
import com.lowagie.text.pdf.OutputStreamCounter;
/**
* An abstract Writer
class for documents.
*
* DocWriter
is the abstract class of several writers such
* as PdfWriter
and HtmlWriter
.
* A DocWriter
can be added as a DocListener
* to a certain Document
by getting an instance (see method
* getInstance()
in the specific writer-classes).
* Every Element
added to the original Document
* will be written to the OutputStream
of the listening
* DocWriter
.
*
* @see Document
* @see DocListener
*/
public abstract class DocWriter implements DocListener {
/** This is some byte that is often used. */
public static final byte NEWLINE = (byte)'\n';
/** This is some byte that is often used. */
public static final byte TAB = (byte)'\t';
/** This is some byte that is often used. */
public static final byte LT = (byte)'<';
/** This is some byte that is often used. */
public static final byte SPACE = (byte)' ';
/** This is some byte that is often used. */
public static final byte EQUALS = (byte)'=';
/** This is some byte that is often used. */
public static final byte QUOTE = (byte)'\"';
/** This is some byte that is often used. */
public static final byte GT = (byte)'>';
/** This is some byte that is often used. */
public static final byte FORWARD = (byte)'/';
// membervariables
/** The pageSize. */
protected Rectangle pageSize;
/** This is the document that has to be written. */
protected Document document;
/** The outputstream of this writer. */
protected OutputStreamCounter os;
/** Is the writer open for writing? */
protected boolean open = false;
/** Do we have to pause all writing actions? */
protected boolean pause = false;
/** Closes the stream on document close */
protected boolean closeStream = true;
// constructor
protected DocWriter() {
}
/**
* Constructs a DocWriter
.
*
* @param document The Document
that has to be written
* @param os The OutputStream
the writer has to write to.
*/
protected DocWriter(Document document, OutputStream os) {
this.document = document;
this.os = new OutputStreamCounter(new BufferedOutputStream(os));
}
// implementation of the DocListener methods
/**
* Signals that an Element
was added to the Document
.
*
* This method should be overridden in the specific
* This does nothing. Has to be overridden if needed.
*
* @param marginLeft the margin on the left
* @param marginRight the margin on the right
* @param marginTop the margin on the top
* @param marginBottom the margin on the bottom
* @return
* This does nothing. Has to be overridden if needed.
*
* @return
* This method should be overridden in the specific
* This method should be overridden in the specific
* This method should be overridden in the specific
* This method should be overridden in the specific
* This method should be overridden in the specific
* This method should be overridden in the specific
* All kinds of Text-elements can be added to a
* Remark:
*
* Once the document is opened, you can't write any Header- or
* Meta-information anymore. You have to open the document before you can
* begin to add content to the body of the document.
*/
public void open() {
if (!close) {
open = true;
}
DocListener listener;
for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
listener = (DocListener) iterator.next();
listener.setPageSize(pageSize);
listener.setMargins(marginLeft, marginRight, marginTop,
marginBottom);
listener.open();
}
}
/**
* Sets the pagesize.
*
* @param pageSize
* the new pagesize
* @return a
* Once all the content has been written in the body, you have to close the
* body. After that nothing can be written to the body anymore.
*/
public void close() {
if (!close) {
open = false;
close = true;
}
DocListener listener;
for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
listener = (DocListener) iterator.next();
listener.close();
}
}
// methods concerning the header or some meta information
/**
* Adds a user defined header to the document.
*
* @param name
* the name of the header
* @param content
* the content of the header
* @return
* Note: it will not work with {@link Table}.
*
* @param marginMirroring
*
* Note: it will not work with {@link Table}.
*
* @param marginMirroringTopBottom
*
* Remark: I looked at the interface javax.swing.text.Element, but I decided to
* write my own text-classes for two reasons:
*
* Example:
* If so, the standard should be used.
*
* @return a
* Example:
*
* Example:
*
* Remark: this only makes sense for Images of the type
* Remark: this only makes sense for Images of the type
* Remark: this only makes sense for Images of the type
* Remark: this only makes sense for Images of the type
* Example 1:
*
* Remark: the parameter symbolIndent is important for instance when
* generating PDF-documents; it indicates the indentation of the listsymbol.
* It is not important for HTML-documents.
*
* @param numbered a boolean
* @param symbolIndent the indentation that has to be used for the listsymbol
*/
public List(boolean numbered, float symbolIndent) {
this(numbered, false, symbolIndent);
}
/**
* Creates a list
* @param numbered has the list to be numbered?
* @param lettered has the list to be 'numbered' with letters
* @param symbolIndent the indentation of the symbol
*/
public List(boolean numbered, boolean lettered, float symbolIndent) {
this.numbered = numbered;
this.lettered = lettered;
this.symbolIndent = symbolIndent;
}
// implementation of the Element-methods
/**
* Processes the element by adding it (or the different parts) to an
*
* This is a shortcut for
* Example 1:
*
* If the numberdepth is 0, the sections will not be numbered. If the numberdepth
* is 1, the section will be numbered with their own number. If the numberdepth is
* higher (for instance x > 1), the numbers of x - 1 parents will be shown.
*
* @param numberDepth the new numberDepth
*/
public void setNumberDepth(int numberDepth) {
((Section)element).setNumberDepth(numberDepth);
}
/**
* Sets the indentation of this
* An object of type
* A
* A
* Example:
*
* This method is a hack to solve a problem I had with phrases that were split between chunks
* in the wrong place.
* @param chunk a Chunk to add to the Phrase
* @return true if adding the Chunk succeeded
*/
protected boolean addChunk(Chunk chunk) {
Font f = chunk.getFont();
String c = chunk.getContent();
if (font != null && !font.isStandardFont()) {
f = font.difference(chunk.getFont());
}
if (size() > 0 && !chunk.hasAttributes()) {
try {
Chunk previous = (Chunk) get(size() - 1);
if (!previous.hasAttributes()
&& (f == null
|| f.compareTo(previous.getFont()) == 0)
&& !"".equals(previous.getContent().trim())
&& !"".equals(c.trim())) {
previous.append(c);
return true;
}
}
catch(ClassCastException cce) {
}
}
Chunk newChunk = new Chunk(c, f);
newChunk.setAttributes(chunk.getAttributes());
if (hyphenation != null && newChunk.getHyphenation() == null && !newChunk.isEmpty()) {
newChunk.setHyphenation(hyphenation);
}
return super.add(newChunk);
}
/**
* Adds a
* All
* Since a
* Remark: you can not construct a
* Example:
*
* If the numberdepth is 0, the sections will not be numbered. If the numberdepth
* is 1, the section will be numbered with their own number. If the numberdepth is
* higher (for instance x > 1), the numbers of x - 1 parents will be shown.
*
* @param numberDepth the new numberDepth
*/
public void setNumberDepth(int numberDepth) {
this.numberDepth = numberDepth;
}
/**
* Returns the numberdepth of this
* When you construct a
* The default implementation is:
*
*
* Tables that span multiple pages are cut into different parts automatically.
* If you want a table header to be repeated on every page, you may not forget to
* mark the end of the header section by using the method
* The matrix of a table is not necessarily an m x n-matrix. It can contain holes
* or cells that are bigger than the unit. Believe me or not, but it took some serious
* thinking to make this as user friendly as possible. I hope you will find the result
* quite simple (I love simple solutions, especially for complex problems).
* I didn't want it to be something as complex as the Java
* Example:
*
* You can give up relative values of borderwidths.
* The sum of these values will be considered 100%.
* The values will be recalculated as percentages of this sum.
*
* example:
*
* You can give up relative values of borderwidths.
* The sum of these values will be considered 100%.
* The values will be recalculated as percentages of this sum.
*
* @param widths an array with values
* @throws DocumentException
*/
public void setWidths(int[] widths) throws DocumentException {
float tb[] = new float[widths.length];
for (int k = 0; k < widths.length; ++k)
tb[k] = widths[k];
setWidths(tb);
}
/**
* Checks if this
* When a table doesn't fit a page, it is split in two parts.
* If you want to avoid this, you should set the tableFitsPage value to true.
*
* @param fitPage enter true if you don't want to split cells
*/
public void setTableFitsPage(boolean fitPage) {
this.tableFitsPage = fitPage;
if (fitPage) setCellsFitPage(true);
}
/**
* Checks if the cells of this
* When a cell doesn't fit a page, it is split in two parts.
* If you want to avoid this, you should set the cellsFitPage value to true.
*
* @param fitPage enter true if you don't want to split cells
*/
public void setCellsFitPage(boolean fitPage) {
this.cellsFitPage = fitPage;
}
/**
* Sets the offset of this table.
*
* Normally a newline is added before you add a Table object.
* This newline uses the current leading.
* If you want to control the space between the table and the previous
* element yourself, you have to set the offset of this table.
*
* @param offset the space between this table and the previous object.
*/
public void setOffset(float offset) {
this.offset = offset;
}
/**
* Gets the offset of this table.
*
* @return the space between this table and the previous element.
*/
public float getOffset() {
return offset;
}
/**
* Method to check if the Table should be converted to a PdfPTable or not.
* @return false if the table should be handled the old fashioned way.
*/
public boolean isConvert2pdfptable() {
return convert2pdfptable;
}
/**
* If set to true, iText will try to convert the Table to a PdfPTable.
* @param convert2pdfptable true if you want iText to try to convert the Table to a PdfPTable
*/
public void setConvert2pdfptable(boolean convert2pdfptable) {
this.convert2pdfptable = convert2pdfptable;
}
// methods to add content to the table
/**
* Adds a
* This is a shortcut for
* This is a shortcut for
* This is a shortcut for
* This is a shortcut for
*
* This method translates the widths expressed in percentages into the
* x-coordinate of the borders of the columns on a real document.
*
* @param left this is the position of the first border at the left (cellpadding not included)
* @param totalWidth this is the space between the first border at the left
* and the last border at the right (cellpadding not included)
* @return an array with border positions
*/
public float[] getWidths(float left, float totalWidth) {
// for x columns, there are x+1 borders
float[] w = new float[columns + 1];
float wPercentage;
if (locked) {
wPercentage = 100 * width / totalWidth;
}
else {
wPercentage = width;
}
// the border at the left is calculated
switch(alignment) {
case Element.ALIGN_LEFT:
w[0] = left;
break;
case Element.ALIGN_RIGHT:
w[0] = left + (totalWidth * (100 - wPercentage)) / 100;
break;
case Element.ALIGN_CENTER:
default:
w[0] = left + (totalWidth * (100 - wPercentage)) / 200;
}
// the total available width is changed
totalWidth = (totalWidth * wPercentage) / 100;
// the inner borders are calculated
for (int i = 1; i < columns; i++) {
w[i] = w[i - 1] + (widths[i - 1] * totalWidth / 100);
}
// the border at the right is calculated
w[columns] = w[0] + totalWidth;
return w;
}
/**
* Gets an
* This method makes the conversion of this library from the JAVA 2 platform
* to a JDK1.1.x-version easier.
*
* @param filename
* a given filename
* @return a valid URL
* @throws MalformedURLException
*/
public static URL toURL(String filename) throws MalformedURLException {
try {
return new URL(filename);
}
catch (Exception e) {
return new File(filename).toURI().toURL();
}
}
/**
* This method is an alternative for the
* To convert the
* Example:
*
* for more info: see O'Reilly; "HTML: The Definitive Guide" (page 164)
*
* @author mario.maccarini@ugent.be
*/
public final class HtmlEncoder {
// membervariables
/** List with the HTML translation of all the characters. */
private static final String[] htmlCode = new String[256];
static {
for (int i = 0; i < 10; i++) {
htmlCode[i] = "" + i + ";";
}
for (int i = 10; i < 32; i++) {
htmlCode[i] = "" + i + ";";
}
for (int i = 32; i < 128; i++) {
htmlCode[i] = String.valueOf((char)i);
}
// Special characters
htmlCode['\t'] = "\t";
htmlCode['\n'] = "<" + HtmlTags.NEWLINE + " />\n";
htmlCode['\"'] = """; // double quote
htmlCode['&'] = "&"; // ampersand
htmlCode['<'] = "<"; // lower than
htmlCode['>'] = ">"; // greater than
for (int i = 128; i < 256; i++) {
htmlCode[i] = "" + i + ";";
}
}
// constructors
/**
* This class will never be constructed.
*
* HtmlEncoder only contains static methods.
*/
private HtmlEncoder () { }
// methods
/**
* Converts a
* An
* Example:
*
* The
* This method writes some comment.
*
* @param comment the comment that has to be written
* @throws IOException
*/
protected void writeComment(String comment) throws IOException {
addTabs(2);
os.write(BEGINCOMMENT);
write(comment);
os.write(ENDCOMMENT);
}
// public methods
/**
* Changes the standardfont.
*
* @param standardfont The font
*/
public void setStandardFont(Font standardfont) {
this.standardfont = standardfont;
}
/**
* Checks if a given font is the same as the font that was last used.
*
* @param font the font of an object
* @return true if the font differs
*/
public boolean isOtherFont(Font font) {
try {
Font cFont = (Font) currentfont.peek();
if (cFont.compareTo(font) == 0) return false;
return true;
}
catch(EmptyStackException ese) {
if (standardfont.compareTo(font) == 0) return false;
return true;
}
}
/**
* Sets the basepath for images.
*
* This is especially useful if you add images using a file,
* rather than an URL. In PDF there is no problem, since
* the images are added inline, but in HTML it is sometimes
* necessary to use a relative path or a special path to some
* images directory.
*
* @param imagepath the new imagepath
*/
public void setImagepath(String imagepath) {
this.imagepath = imagepath;
}
/**
* Resets the imagepath.
*/
public void resetImagepath() {
imagepath = null;
}
/**
* Changes the header of this document.
*
* @param header the new header
*/
public void setHeader(HeaderFooter header) {
this.header = header;
}
/**
* Changes the footer of this document.
*
* @param footer the new footer
*/
public void setFooter(HeaderFooter footer) {
this.footer = footer;
}
/**
* Signals that a
* An example:
*
*
* If the field does not exist or is invalid it returns
*
*
*
*
*
*
* The bars and text are written in the following colors:
* Result bars and text painted with current fill color bars and text painted with bars painted with current color bars painted with
* The code types allowed are:
* The bars and text are written in the following colors:
* Result bars and text painted with current fill color bars and text painted with bars painted with current color bars painted with
*
* The bars and text are written in the following colors:
* Result bars and text painted with current fill color bars and text painted with bars painted with current color bars painted with
* The bars and text are written in the following colors:
* Result bars and text painted with current fill color bars and text painted with bars painted with current color bars painted with
*
*
* The allowed dimensions are (height, width):
* 10, 10
* The allowed dimensions are (height, width):
* 10, 10
* One of:
* One of:
* exxxxxx - ECI number xxxxxx
* Example for a structured append, symbol 2 of 6, with FNC1 and ECI 000005. The actual text is "Hello".
* s020600075fe000005.Hello
* One of:DocWriter
classes
* derived from this abstract class.
*
* @param element A high level object to add
* @return
false
* @throws DocumentException when a document isn't open yet, or has been closed
*/
public boolean add(Element element) throws DocumentException {
return false;
}
/**
* Signals that the Document
was opened.
*/
public void open() {
open = true;
}
/**
* Sets the pagesize.
*
* @param pageSize the new pagesize
* @return a boolean
*/
public boolean setPageSize(Rectangle pageSize) {
this.pageSize = pageSize;
return true;
}
/**
* Sets the margins.
* false
*/
public boolean setMargins(float marginLeft, float marginRight, float marginTop, float marginBottom) {
return false;
}
/**
* Signals that an new page has to be started.
* true
if the page was added, false
if not.
*/
public boolean newPage() {
if (!open) {
return false;
}
return true;
}
/**
* Changes the header of this document.
* DocWriter
classes
* derived from this abstract class if they actually support the use of
* headers.
*
* @param header the new header
*/
public void setHeader(HeaderFooter header) {
}
/**
* Resets the header of this document.
*
DocWriter
classes
* derived from this abstract class if they actually support the use of
* headers.
*/
public void resetHeader() {
}
/**
* Changes the footer of this document.
*
DocWriter
classes
* derived from this abstract class if they actually support the use of
* footers.
*
* @param footer the new footer
*/
public void setFooter(HeaderFooter footer) {
}
/**
* Resets the footer of this document.
*
DocWriter
classes
* derived from this abstract class if they actually support the use of
* footers.
*/
public void resetFooter() {
}
/**
* Sets the page number to 0.
*
DocWriter
classes
* derived from this abstract class if they actually support the use of
* pagenumbers.
*/
public void resetPageCount() {
}
/**
* Sets the page number.
*
DocWriter
classes
* derived from this abstract class if they actually support the use of
* pagenumbers.
*
* @param pageN the new page number
*/
public void setPageCount(int pageN) {
}
/**
* Signals that the
*/
protected void initFooter() {
if (footer != null) {
try {
// Set the page number. HTML has no notion of a page, so it should always
// add up to 1
footer.setPageNumber(pageN + 1);
add(footer.paragraph());
}
catch(Exception e) {
throw new ExceptionConverter(e);
}
}
}
/**
* Writes a Metatag in the header.
*
* @param meta the element that has to be written
* @throws IOException
*/
protected void writeHeader(Meta meta) throws IOException {
addTabs(2);
writeStart(HtmlTags.META);
switch(meta.type()) {
case Element.HEADER:
write(HtmlTags.NAME, ((Header) meta).getName());
break;
case Element.SUBJECT:
write(HtmlTags.NAME, HtmlTags.SUBJECT);
break;
case Element.KEYWORDS:
write(HtmlTags.NAME, HtmlTags.KEYWORDS);
break;
case Element.AUTHOR:
write(HtmlTags.NAME, HtmlTags.AUTHOR);
break;
}
write(HtmlTags.CONTENT, HtmlEncoder.encode(meta.getContent()));
writeEnd();
}
/**
* Writes a link in the header.
*
* @param header the element that has to be written
* @throws IOException
*/
protected void writeLink(Header header) throws IOException {
addTabs(2);
writeStart(HtmlTags.LINK);
write(HtmlTags.REL, header.getName());
write(HtmlTags.TYPE, HtmlTags.TEXT_CSS);
write(HtmlTags.REFERENCE, header.getContent());
writeEnd();
}
/**
* Writes a JavaScript section or, if the markup attribute HtmlTags.URL is set, a JavaScript reference in the header.
*
* @param header the element that has to be written
* @throws IOException
*/
protected void writeJavaScript(Header header) throws IOException {
addTabs(2);
writeStart(HtmlTags.SCRIPT);
write(HtmlTags.LANGUAGE, HtmlTags.JAVASCRIPT);
if (markup.size() > 0) {
/* JavaScript reference example:
*
*
*/
writeMarkupAttributes(markup);
os.write(GT);
writeEnd(HtmlTags.SCRIPT);
}
else {
/* JavaScript coding convention:
*
*
*/
write(HtmlTags.TYPE, Markup.HTML_VALUE_JAVASCRIPT);
os.write(GT);
addTabs(2);
write(new String(BEGINCOMMENT) + "\n");
write(header.getContent());
addTabs(2);
write("//" + new String(ENDCOMMENT));
addTabs(2);
writeEnd(HtmlTags.SCRIPT);
}
}
/**
* Writes some comment.
* Document
was closed and that no other
* Elements
will be added.
*/
public void close() {
open = false;
try {
os.flush();
if (closeStream)
os.close();
}
catch(IOException ioe) {
throw new ExceptionConverter(ioe);
}
}
// methods
/** Converts a String
into a Byte
array
* according to the ISO-8859-1 codepage.
* @param text the text to be converted
* @return the conversion result
*/
public static final byte[] getISOBytes(String text)
{
if (text == null)
return null;
int len = text.length();
byte b[] = new byte[len];
for (int k = 0; k < len; ++k)
b[k] = (byte)text.charAt(k);
return b;
}
/**
* Let the writer know that all writing has to be paused.
*/
public void pause() {
pause = true;
}
/**
* Checks if writing is paused.
*
* @return true
if writing temporarily has to be paused, false
otherwise.
*/
public boolean isPaused() {
return pause;
}
/**
* Let the writer know that writing may be resumed.
*/
public void resume() {
pause = false;
}
/**
* Flushes the BufferedOutputStream
.
*/
public void flush() {
try {
os.flush();
}
catch(IOException ioe) {
throw new ExceptionConverter(ioe);
}
}
/**
* Writes a String
to the OutputStream
.
*
* @param string the String
to write
* @throws IOException
*/
protected void write(String string) throws IOException {
os.write(getISOBytes(string));
}
/**
* Writes a number of tabs.
*
* @param indent the number of tabs to add
* @throws IOException
*/
protected void addTabs(int indent) throws IOException {
os.write(NEWLINE);
for (int i = 0; i < indent; i++) {
os.write(TAB);
}
}
/**
* Writes a key-value pair to the outputstream.
*
* @param key the name of an attribute
* @param value the value of an attribute
* @throws IOException
*/
protected void write(String key, String value)
throws IOException {
os.write(SPACE);
write(key);
os.write(EQUALS);
os.write(QUOTE);
write(value);
os.write(QUOTE);
}
/**
* Writes a starttag to the outputstream.
*
* @param tag the name of the tag
* @throws IOException
*/
protected void writeStart(String tag)
throws IOException {
os.write(LT);
write(tag);
}
/**
* Writes an endtag to the outputstream.
*
* @param tag the name of the tag
* @throws IOException
*/
protected void writeEnd(String tag)
throws IOException {
os.write(LT);
os.write(FORWARD);
write(tag);
os.write(GT);
}
/**
* Writes an endtag to the outputstream.
* @throws IOException
*/
protected void writeEnd()
throws IOException {
os.write(SPACE);
os.write(FORWARD);
os.write(GT);
}
/**
* Writes the markup attributes of the specified MarkupAttributes
* object to the OutputStream
.
* @param markup a Properties
collection to write.
* @return true, if writing the markup attributes succeeded
* @throws IOException
*/
protected boolean writeMarkupAttributes(Properties markup)
throws IOException {
if (markup == null) return false;
Iterator attributeIterator = markup.keySet().iterator();
String name;
while (attributeIterator.hasNext()) {
name = String.valueOf(attributeIterator.next());
write(name, markup.getProperty(name));
}
markup.clear();
return true;
}
/** Checks if the stream is to be closed on document close
* @return true if the stream is closed on document close
*
*/
public boolean isCloseStream() {
return closeStream;
}
/** Sets the close state of the stream after document close
* @param closeStream true if the stream is closed on document close
*
*/
public void setCloseStream(boolean closeStream) {
this.closeStream = closeStream;
}
/**
* @see com.lowagie.text.DocListener#setMarginMirroring(boolean)
*/
public boolean setMarginMirroring(boolean MarginMirroring) {
return false;
}
/**
* @see com.lowagie.text.DocListener#setMarginMirroring(boolean)
* @since 2.1.6
*/
public boolean setMarginMirroringTopBottom(boolean MarginMirroring) {
return false;
}
}
src/core/com/lowagie/text/Document.java 100644 0 0 60611 11224570760 15566 0 ustar 0 0 /*
* $Id: Document.java 4007 2009-07-07 09:43:40Z blowagie $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
/**
* A generic Document class.
* HTMLDocument
.
* The Document
signals all the listeners when an element has
* been added.
*
*
* Example:
* OutputStream
) is closed too.
*
*
*
*/
public class Document implements DocListener {
// membervariables
/**
* This constant may only be changed by Paulo Soares and/or Bruno Lowagie.
* @since 2.1.6
*/
private static final String ITEXT = "iText";
/**
* This constant may only be changed by Paulo Soares and/or Bruno Lowagie.
* @since 2.1.6
*/
private static final String RELEASE = "2.1.7";
/** This constant may only be changed by Paulo Soares and/or Bruno Lowagie. */
private static final String ITEXT_VERSION = ITEXT + " " + RELEASE + " by 1T3XT";
/**
* Allows the pdf documents to be produced without compression for debugging
* purposes.
*/
public static boolean compress = true;
/**
* When true the file access is not done through a memory mapped file. Use it if the file
* is too big to be mapped in your address space.
*/
public static boolean plainRandomAccess = false;
/** Scales the WMF font size. The default value is 0.86. */
public static float wmfFontCorrection = 0.86f;
/** The DocListener. */
private ArrayList listeners = new ArrayList();
/** Is the document open or not? */
protected boolean open;
/** Has the document already been closed? */
protected boolean close;
// membervariables concerning the layout
/** The size of the page. */
protected Rectangle pageSize;
/** margin in x direction starting from the left */
protected float marginLeft = 0;
/** margin in x direction starting from the right */
protected float marginRight = 0;
/** margin in y direction starting from the top */
protected float marginTop = 0;
/** margin in y direction starting from the bottom */
protected float marginBottom = 0;
/** mirroring of the left/right margins */
protected boolean marginMirroring = false;
/**
* mirroring of the top/bottom margins
* @since 2.1.6
*/
protected boolean marginMirroringTopBottom = false;
/** Content of JavaScript onLoad function */
protected String javaScript_onLoad = null;
/** Content of JavaScript onUnLoad function */
protected String javaScript_onUnLoad = null;
/** Style class in HTML body tag */
protected String htmlStyleClass = null;
// headers, footers
/** Current pagenumber */
protected int pageN = 0;
/** This is the textual part of a Page; it can contain a header */
protected HeaderFooter header = null;
/** This is the textual part of the footer */
protected HeaderFooter footer = null;
/** This is a chapter number in case ChapterAutoNumber is used. */
protected int chapternumber = 0;
// constructor
/**
* Constructs a new // creation of the document with a certain size and certain margins
* Document document = new Document(PageSize.A4, 50, 50, 50, 50);
* try {
* // creation of the different writers
* HtmlWriter.getInstance(document , System.out);
* PdfWriter.getInstance(document , new FileOutputStream("text.pdf"));
* // we add some meta information to the document
* document.addAuthor("Bruno Lowagie");
* document.addSubject("This is the result of a Test.");
* // we open the document for writing
* document.open();
* document.add(new Paragraph("Hello world"));
* } catch(DocumentException de) {
* System.err.println(de.getMessage());
* }
* document.close();
*
*
* Document
-object.
*/
public Document() {
this(PageSize.A4);
}
/**
* Constructs a new Document
-object.
*
* @param pageSize
* the pageSize
*/
public Document(Rectangle pageSize) {
this(pageSize, 36, 36, 36, 36);
}
/**
* Constructs a new Document
-object.
*
* @param pageSize
* the pageSize
* @param marginLeft
* the margin on the left
* @param marginRight
* the margin on the right
* @param marginTop
* the margin on the top
* @param marginBottom
* the margin on the bottom
*/
public Document(Rectangle pageSize, float marginLeft, float marginRight,
float marginTop, float marginBottom) {
this.pageSize = pageSize;
this.marginLeft = marginLeft;
this.marginRight = marginRight;
this.marginTop = marginTop;
this.marginBottom = marginBottom;
}
// listener methods
/**
* Adds a DocListener
to the Document
.
*
* @param listener
* the new DocListener.
*/
public void addDocListener(DocListener listener) {
listeners.add(listener);
}
/**
* Removes a DocListener
from the Document
.
*
* @param listener
* the DocListener that has to be removed.
*/
public void removeDocListener(DocListener listener) {
listeners.remove(listener);
}
// methods implementing the DocListener interface
/**
* Adds an Element
to the Document
.
*
* @param element
* the Element
to add
* @return true
if the element was added, false
*
if not
* @throws DocumentException
* when a document isn't open yet, or has been closed
*/
public boolean add(Element element) throws DocumentException {
if (close) {
throw new DocumentException(
"The document has been closed. You can't add any Elements.");
}
if (!open && element.isContent()) {
throw new DocumentException(
"The document is not open yet; you can only add Meta information.");
}
boolean success = false;
DocListener listener;
if (element instanceof ChapterAutoNumber) {
chapternumber = ((ChapterAutoNumber)element).setAutomaticNumber(chapternumber);
}
for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
listener = (DocListener) iterator.next();
success |= listener.add(element);
}
if (element instanceof LargeElement) {
LargeElement e = (LargeElement)element;
if (!e.isComplete())
e.flushContent();
}
return success;
}
/**
* Opens the document.
* boolean
*/
public boolean setPageSize(Rectangle pageSize) {
this.pageSize = pageSize;
DocListener listener;
for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
listener = (DocListener) iterator.next();
listener.setPageSize(pageSize);
}
return true;
}
/**
* Sets the margins.
*
* @param marginLeft
* the margin on the left
* @param marginRight
* the margin on the right
* @param marginTop
* the margin on the top
* @param marginBottom
* the margin on the bottom
* @return a boolean
*/
public boolean setMargins(float marginLeft, float marginRight,
float marginTop, float marginBottom) {
this.marginLeft = marginLeft;
this.marginRight = marginRight;
this.marginTop = marginTop;
this.marginBottom = marginBottom;
DocListener listener;
for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
listener = (DocListener) iterator.next();
listener.setMargins(marginLeft, marginRight, marginTop,
marginBottom);
}
return true;
}
/**
* Signals that an new page has to be started.
*
* @return true
if the page was added, false
* if not.
*/
public boolean newPage() {
if (!open || close) {
return false;
}
DocListener listener;
for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
listener = (DocListener) iterator.next();
listener.newPage();
}
return true;
}
/**
* Changes the header of this document.
*
* @param header
* the new header
*/
public void setHeader(HeaderFooter header) {
this.header = header;
DocListener listener;
for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
listener = (DocListener) iterator.next();
listener.setHeader(header);
}
}
/**
* Resets the header of this document.
*/
public void resetHeader() {
this.header = null;
DocListener listener;
for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
listener = (DocListener) iterator.next();
listener.resetHeader();
}
}
/**
* Changes the footer of this document.
*
* @param footer
* the new footer
*/
public void setFooter(HeaderFooter footer) {
this.footer = footer;
DocListener listener;
for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
listener = (DocListener) iterator.next();
listener.setFooter(footer);
}
}
/**
* Resets the footer of this document.
*/
public void resetFooter() {
this.footer = null;
DocListener listener;
for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
listener = (DocListener) iterator.next();
listener.resetFooter();
}
}
/**
* Sets the page number to 0.
*/
public void resetPageCount() {
pageN = 0;
DocListener listener;
for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
listener = (DocListener) iterator.next();
listener.resetPageCount();
}
}
/**
* Sets the page number.
*
* @param pageN
* the new page number
*/
public void setPageCount(int pageN) {
this.pageN = pageN;
DocListener listener;
for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
listener = (DocListener) iterator.next();
listener.setPageCount(pageN);
}
}
/**
* Returns the current page number.
*
* @return the current page number
*/
public int getPageNumber() {
return this.pageN;
}
/**
* Closes the document.
* true
if successful, false
otherwise
*/
public boolean addHeader(String name, String content) {
try {
return add(new Header(name, content));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
/**
* Adds the title to a Document.
*
* @param title
* the title
* @return true
if successful, false
otherwise
*/
public boolean addTitle(String title) {
try {
return add(new Meta(Element.TITLE, title));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
/**
* Adds the subject to a Document.
*
* @param subject
* the subject
* @return true
if successful, false
otherwise
*/
public boolean addSubject(String subject) {
try {
return add(new Meta(Element.SUBJECT, subject));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
/**
* Adds the keywords to a Document.
*
* @param keywords
* adds the keywords to the document
* @return true
if successful, false
otherwise
*/
public boolean addKeywords(String keywords) {
try {
return add(new Meta(Element.KEYWORDS, keywords));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
/**
* Adds the author to a Document.
*
* @param author
* the name of the author
* @return true
if successful, false
otherwise
*/
public boolean addAuthor(String author) {
try {
return add(new Meta(Element.AUTHOR, author));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
/**
* Adds the creator to a Document.
*
* @param creator
* the name of the creator
* @return true
if successful, false
otherwise
*/
public boolean addCreator(String creator) {
try {
return add(new Meta(Element.CREATOR, creator));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
/**
* Adds the producer to a Document.
*
* @return true
if successful, false
otherwise
*/
public boolean addProducer() {
try {
return add(new Meta(Element.PRODUCER, getVersion()));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
/**
* Adds the current date and time to a Document.
*
* @return true
if successful, false
otherwise
*/
public boolean addCreationDate() {
try {
/* bugfix by 'taqua' (Thomas) */
final SimpleDateFormat sdf = new SimpleDateFormat(
"EEE MMM dd HH:mm:ss zzz yyyy");
return add(new Meta(Element.CREATIONDATE, sdf.format(new Date())));
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
// methods to get the layout of the document.
/**
* Returns the left margin.
*
* @return the left margin
*/
public float leftMargin() {
return marginLeft;
}
/**
* Return the right margin.
*
* @return the right margin
*/
public float rightMargin() {
return marginRight;
}
/**
* Returns the top margin.
*
* @return the top margin
*/
public float topMargin() {
return marginTop;
}
/**
* Returns the bottom margin.
*
* @return the bottom margin
*/
public float bottomMargin() {
return marginBottom;
}
/**
* Returns the lower left x-coordinate.
*
* @return the lower left x-coordinate
*/
public float left() {
return pageSize.getLeft(marginLeft);
}
/**
* Returns the upper right x-coordinate.
*
* @return the upper right x-coordinate
*/
public float right() {
return pageSize.getRight(marginRight);
}
/**
* Returns the upper right y-coordinate.
*
* @return the upper right y-coordinate
*/
public float top() {
return pageSize.getTop(marginTop);
}
/**
* Returns the lower left y-coordinate.
*
* @return the lower left y-coordinate
*/
public float bottom() {
return pageSize.getBottom(marginBottom);
}
/**
* Returns the lower left x-coordinate considering a given margin.
*
* @param margin
* a margin
* @return the lower left x-coordinate
*/
public float left(float margin) {
return pageSize.getLeft(marginLeft + margin);
}
/**
* Returns the upper right x-coordinate, considering a given margin.
*
* @param margin
* a margin
* @return the upper right x-coordinate
*/
public float right(float margin) {
return pageSize.getRight(marginRight + margin);
}
/**
* Returns the upper right y-coordinate, considering a given margin.
*
* @param margin
* a margin
* @return the upper right y-coordinate
*/
public float top(float margin) {
return pageSize.getTop(marginTop + margin);
}
/**
* Returns the lower left y-coordinate, considering a given margin.
*
* @param margin
* a margin
* @return the lower left y-coordinate
*/
public float bottom(float margin) {
return pageSize.getBottom(marginBottom + margin);
}
/**
* Gets the pagesize.
*
* @return the page size
*/
public Rectangle getPageSize() {
return this.pageSize;
}
/**
* Checks if the document is open.
*
* @return true
if the document is open
*/
public boolean isOpen() {
return open;
}
/**
* Gets the product name.
* This method may only be changed by Paulo Soares and/or Bruno Lowagie.
* @return the product name
* @since 2.1.6
*/
public static final String getProduct() {
return ITEXT;
}
/**
* Gets the release number.
* This method may only be changed by Paulo Soares and/or Bruno Lowagie.
* @return the product name
* @since 2.1.6
*/
public static final String getRelease() {
return RELEASE;
}
/**
* Gets the iText version.
* This method may only be changed by Paulo Soares and/or Bruno Lowagie.
* @return iText version
*/
public static final String getVersion() {
return ITEXT_VERSION;
}
/**
* Adds a JavaScript onLoad function to the HTML body tag
*
* @param code
* the JavaScript code to be executed on load of the HTML page
*/
public void setJavaScript_onLoad(String code) {
this.javaScript_onLoad = code;
}
/**
* Gets the JavaScript onLoad command.
*
* @return the JavaScript onLoad command
*/
public String getJavaScript_onLoad() {
return this.javaScript_onLoad;
}
/**
* Adds a JavaScript onUnLoad function to the HTML body tag
*
* @param code
* the JavaScript code to be executed on unload of the HTML page
*/
public void setJavaScript_onUnLoad(String code) {
this.javaScript_onUnLoad = code;
}
/**
* Gets the JavaScript onUnLoad command.
*
* @return the JavaScript onUnLoad command
*/
public String getJavaScript_onUnLoad() {
return this.javaScript_onUnLoad;
}
/**
* Adds a style class to the HTML body tag
*
* @param htmlStyleClass
* the style class for the HTML body tag
*/
public void setHtmlStyleClass(String htmlStyleClass) {
this.htmlStyleClass = htmlStyleClass;
}
/**
* Gets the style class of the HTML body tag
*
* @return the style class of the HTML body tag
*/
public String getHtmlStyleClass() {
return this.htmlStyleClass;
}
/**
* Set the margin mirroring. It will mirror right/left margins for odd/even pages.
* true
to mirror the margins
* @return always true
*/
public boolean setMarginMirroring(boolean marginMirroring) {
this.marginMirroring = marginMirroring;
DocListener listener;
for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
listener = (DocListener) iterator.next();
listener.setMarginMirroring(marginMirroring);
}
return true;
}
/**
* Set the margin mirroring. It will mirror top/bottom margins for odd/even pages.
* true
to mirror the margins
* @return always true
* @since 2.1.6
*/
public boolean setMarginMirroringTopBottom(boolean marginMirroringTopBottom) {
this.marginMirroringTopBottom = marginMirroringTopBottom;
DocListener listener;
for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
listener = (DocListener) iterator.next();
listener.setMarginMirroringTopBottom(marginMirroringTopBottom);
}
return true;
}
/**
* Gets the margin mirroring flag.
*
* @return the margin mirroring flag
*/
public boolean isMarginMirroring() {
return marginMirroring;
}
}
src/core/com/lowagie/text/DocumentException.java 100644 0 0 6637 11213370070 17423 0 ustar 0 0 /*
* $Id: DocumentException.java 3831 2009-04-01 16:31:17Z blowagie $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
/**
* Signals that an error has occurred in a Document
.
*
* @see BadElementException
* @see Document
* @see DocWriter
* @see DocListener
*/
public class DocumentException extends Exception {
/** A serial version UID */
private static final long serialVersionUID = -2191131489390840739L;
/**
* Creates a Document exception.
* @param ex an exception that has to be turned into a DocumentException
*/
public DocumentException(Exception ex) {
super(ex);
}
// constructors
/**
* Constructs a DocumentException
without a message.
*/
public DocumentException() {
super();
}
/**
* Constructs a DocumentException
with a message.
*
* @param message a message describing the exception
*/
public DocumentException(String message) {
super(message);
}
}
src/core/com/lowagie/text/Element.java 100644 0 0 24603 11154165267 15406 0 ustar 0 0 /*
* $Id: Element.java 3672 2009-02-01 15:32:09Z blowagie $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.util.ArrayList;
/**
* Interface for a text element.
*
*
*
* @see Anchor
* @see Cell
* @see Chapter
* @see Chunk
* @see Header
* @see Image
* @see Jpeg
* @see List
* @see ListItem
* @see Meta
* @see Paragraph
* @see Phrase
* @see Rectangle
* @see Row
* @see Section
* @see Table
*/
public interface Element {
// static membervariables (meta information)
/** This is a possible type of Element
. */
public static final int HEADER = 0;
/** This is a possible type of Element
. */
public static final int TITLE = 1;
/** This is a possible type of Element
. */
public static final int SUBJECT = 2;
/** This is a possible type of Element
. */
public static final int KEYWORDS = 3;
/** This is a possible type of Element . */
public static final int AUTHOR = 4;
/** This is a possible type of
DocumentElement . */
public static final int PRODUCER = 5;
/** This is a possible type of
*/
protected void initHeader() {
if (header != null) {
try {
add(header.paragraph());
}
catch(Exception e) {
throw new ExceptionConverter(e);
}
}
}
/**
* Adds the header to the top of the Element . */
public static final int CREATIONDATE = 6;
/** This is a possible type of
DocumentElement . */
public static final int CREATOR = 7;
// static membervariables (content)
/** This is a possible type of
*
*/
public class HtmlWriter extends DocWriter {
// static membervariables (tags)
/** This is a possible HTML-tag. */
public static final byte[] BEGINCOMMENT = getISOBytes("");
/** This is a possible HTML-tag. */
public static final String NBSP = " ";
// membervariables
/** This is the current font of the HTML. */
protected Stack currentfont = new Stack();
/** This is the standard font of the HTML. */
protected Font standardfont = new Font();
/** This is a path for images. */
protected String imagepath = null;
/** Stores the page number. */
protected int pageN = 0;
/** This is the textual part of a header */
protected HeaderFooter header = null;
/** This is the textual part of the footer */
protected HeaderFooter footer = null;
/** Store the markup properties of a MarkedObject. */
protected Properties markup = new Properties();
// constructor
/**
* Constructs a Element
. */
public static final int CHUNK = 10;
/** This is a possible type of Element
. */
public static final int PHRASE = 11;
/** This is a possible type of Element
. */
public static final int PARAGRAPH = 12;
/** This is a possible type of Element
*/
public static final int SECTION = 13;
/** This is a possible type of Element
*/
public static final int LIST = 14;
/** This is a possible type of Element
*/
public static final int LISTITEM = 15;
/** This is a possible type of Element
*/
public static final int CHAPTER = 16;
/** This is a possible type of Element
*/
public static final int ANCHOR = 17;
// static membervariables (tables)
/** This is a possible type of Element
. */
public static final int CELL = 20;
/** This is a possible type of Element
. */
public static final int ROW = 21;
/** This is a possible type of Element
. */
public static final int TABLE = 22;
/** This is a possible type of Element
. */
public static final int PTABLE = 23;
// static membervariables (annotations)
/** This is a possible type of Element
. */
public static final int ANNOTATION = 29;
// static membervariables (geometric figures)
/** This is a possible type of Element
. */
public static final int RECTANGLE = 30;
/** This is a possible type of Element
. */
public static final int JPEG = 32;
/** This is a possible type of Element
. */
public static final int JPEG2000 = 33;
/** This is a possible type of Element
. */
public static final int IMGRAW = 34;
/** This is a possible type of Element
. */
public static final int IMGTEMPLATE = 35;
/**
* This is a possible type of Element
.
* @since 2.1.5
*/
public static final int JBIG2 = 36;
/** This is a possible type of Element
. */
public static final int MULTI_COLUMN_TEXT = 40;
/** This is a possible type of Element
. */
public static final int MARKED = 50;
/** This is a possible type of Element
.
* @since 2.1.2
*/
public static final int YMARK = 55;
// static membervariables (alignment)
/**
* A possible value for paragraph alignment. This specifies that the text is
* aligned to the left indent and extra whitespace should be placed on the
* right.
*/
public static final int ALIGN_UNDEFINED = -1;
/**
* A possible value for paragraph alignment. This specifies that the text is
* aligned to the left indent and extra whitespace should be placed on the
* right.
*/
public static final int ALIGN_LEFT = 0;
/**
* A possible value for paragraph alignment. This specifies that the text is
* aligned to the center and extra whitespace should be placed equally on
* the left and right.
*/
public static final int ALIGN_CENTER = 1;
/**
* A possible value for paragraph alignment. This specifies that the text is
* aligned to the right indent and extra whitespace should be placed on the
* left.
*/
public static final int ALIGN_RIGHT = 2;
/**
* A possible value for paragraph alignment. This specifies that extra
* whitespace should be spread out through the rows of the paragraph with
* the text lined up with the left and right indent except on the last line
* which should be aligned to the left.
*/
public static final int ALIGN_JUSTIFIED = 3;
/**
* A possible value for vertical alignment.
*/
public static final int ALIGN_TOP = 4;
/**
* A possible value for vertical alignment.
*/
public static final int ALIGN_MIDDLE = 5;
/**
* A possible value for vertical alignment.
*/
public static final int ALIGN_BOTTOM = 6;
/**
* A possible value for vertical alignment.
*/
public static final int ALIGN_BASELINE = 7;
/**
* Does the same as ALIGN_JUSTIFIED but the last line is also spread out.
*/
public static final int ALIGN_JUSTIFIED_ALL = 8;
// static member variables for CCITT compression
/**
* Pure two-dimensional encoding (Group 4)
*/
public static final int CCITTG4 = 0x100;
/**
* Pure one-dimensional encoding (Group 3, 1-D)
*/
public static final int CCITTG3_1D = 0x101;
/**
* Mixed one- and two-dimensional encoding (Group 3, 2-D)
*/
public static final int CCITTG3_2D = 0x102;
/**
* A flag indicating whether 1-bits are to be interpreted as black pixels
* and 0-bits as white pixels,
*/
public static final int CCITT_BLACKIS1 = 1;
/**
* A flag indicating whether the filter expects extra 0-bits before each
* encoded line so that the line begins on a byte boundary.
*/
public static final int CCITT_ENCODEDBYTEALIGN = 2;
/**
* A flag indicating whether end-of-line bit patterns are required to be
* present in the encoding.
*/
public static final int CCITT_ENDOFLINE = 4;
/**
* A flag indicating whether the filter expects the encoded data to be
* terminated by an end-of-block pattern, overriding the Rows parameter. The
* use of this flag will set the key /EndOfBlock to false.
*/
public static final int CCITT_ENDOFBLOCK = 8;
// methods
/**
* Processes the element by adding it (or the different parts) to an
* ElementListener
.
*
* @param listener
* an ElementListener
* @return true
if the element was processed successfully
*/
public boolean process(ElementListener listener);
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type();
/**
* Checks if this element is a content object.
* If not, it's a metadata object.
* @since iText 2.0.8
* @return true if this is a 'content' element; false if this is a 'metadata' element
*/
public boolean isContent();
/**
* Checks if this element is nestable.
* @since iText 2.0.8
* @return true if this element can be nested inside other elements.
*/
public boolean isNestable();
/**
* Gets all the chunks in this element.
*
* @return an ArrayList
*/
public ArrayList getChunks();
/**
* Gets the content of the text element.
*
* @return a type
*/
public String toString();
} src/core/com/lowagie/text/ElementListener.java 100644 0 0 6157 11012562273 17067 0 ustar 0 0 /*
* $Id: ElementListener.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.util.EventListener;
/**
* A class that implements ElementListener
will perform some
* actions when an Element
is added.
*
* @see DocListener
*/
public interface ElementListener extends EventListener {
// methods
/**
* Signals that an Element
was added to the Document
.
*
* @param element a high level object
* @return true
if the element was added, false
if not.
* @throws DocumentException when a document isn't open yet, or has been closed
*/
public boolean add(Element element) throws DocumentException; // [L0]
} src/core/com/lowagie/text/ElementTags.java 100644 0 0 42656 11036112746 16226 0 ustar 0 0 /*
* $Id: ElementTags.java 3533 2008-07-07 21:27:13Z Howard_s $
*
* Copyright (c) 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.
*
* Contributions by:
* Lubos Strapko
*
* 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;
/**
* A class that contains all the possible tagnames and their attributes.
*/
public class ElementTags {
/** the root tag. */
public static final String ITEXT = "itext";
/** attribute of the root and annotation tag (also a special tag within a chapter or section) */
public static final String TITLE = "title";
/** attribute of the root tag */
public static final String SUBJECT = "subject";
/** attribute of the root tag */
public static final String KEYWORDS = "keywords";
/** attribute of the root tag */
public static final String AUTHOR = "author";
/** attribute of the root tag */
public static final String CREATIONDATE = "creationdate";
/** attribute of the root tag */
public static final String PRODUCER = "producer";
// Chapters and Sections
/** the chapter tag */
public static final String CHAPTER = "chapter";
/** the section tag */
public static final String SECTION = "section";
/** attribute of section/chapter tag */
public static final String NUMBERDEPTH = "numberdepth";
/** attribute of section/chapter tag */
public static final String DEPTH = "depth";
/** attribute of section/chapter tag */
public static final String NUMBER = "number";
/** attribute of section/chapter tag */
public static final String INDENT = "indent";
/** attribute of chapter/section/paragraph/table/cell tag */
public static final String LEFT = "left";
/** attribute of chapter/section/paragraph/table/cell tag */
public static final String RIGHT = "right";
// Phrases, Anchors, Lists and Paragraphs
/** the phrase tag */
public static final String PHRASE = "phrase";
/** the anchor tag */
public static final String ANCHOR = "anchor";
/** the list tag */
public static final String LIST = "list";
/** the listitem tag */
public static final String LISTITEM = "listitem";
/** the paragraph tag */
public static final String PARAGRAPH = "paragraph";
/** attribute of phrase/paragraph/cell tag */
public static final String LEADING = "leading";
/** attribute of paragraph/image/table tag */
public static final String ALIGN = "align";
/** attribute of paragraph */
public static final String KEEPTOGETHER = "keeptogether";
/** attribute of anchor tag */
public static final String NAME = "name";
/** attribute of anchor tag */
public static final String REFERENCE = "reference";
/** attribute of list tag */
public static final String LISTSYMBOL = "listsymbol";
/** attribute of list tag */
public static final String NUMBERED = "numbered";
/** attribute of the list tag */
public static final String LETTERED = "lettered";
/** attribute of list tag */
public static final String FIRST = "first";
/** attribute of list tag */
public static final String SYMBOLINDENT = "symbolindent";
/** attribute of list tag */
public static final String INDENTATIONLEFT = "indentationleft";
/** attribute of list tag */
public static final String INDENTATIONRIGHT = "indentationright";
// Chunks
/** the chunk tag */
public static final String IGNORE = "ignore";
/** the chunk tag */
public static final String ENTITY = "entity";
/** the chunk tag */
public static final String ID = "id";
/** the chunk tag */
public static final String CHUNK = "chunk";
/** attribute of the chunk tag */
public static final String ENCODING = "encoding";
/** attribute of the chunk tag */
public static final String EMBEDDED = "embedded";
/** attribute of the chunk/table/cell tag */
public static final String COLOR = "color";
/** attribute of the chunk/table/cell tag */
public static final String RED = "red";
/** attribute of the chunk/table/cell tag */
public static final String GREEN = "green";
/** attribute of the chunk/table/cell tag */
public static final String BLUE = "blue";
/** attribute of the chunk tag */
public static final String SUBSUPSCRIPT = Chunk.SUBSUPSCRIPT.toLowerCase();
/** attribute of the chunk tag */
public static final String LOCALGOTO = Chunk.LOCALGOTO.toLowerCase();
/** attribute of the chunk tag */
public static final String REMOTEGOTO = Chunk.REMOTEGOTO.toLowerCase();
/** attribute of the chunk tag */
public static final String LOCALDESTINATION = Chunk.LOCALDESTINATION.toLowerCase();
/** attribute of the chunk tag */
public static final String GENERICTAG = Chunk.GENERICTAG.toLowerCase();
// tables/cells
/** the table tag */
public static final String TABLE = "table";
/** the cell tag */
public static final String ROW = "row";
/** the cell tag */
public static final String CELL = "cell";
/** attribute of the table tag */
public static final String COLUMNS = "columns";
/** attribute of the table tag */
public static final String LASTHEADERROW = "lastHeaderRow";
/** attribute of the table tag */
public static final String CELLPADDING = "cellpadding";
/** attribute of the table tag */
public static final String CELLSPACING = "cellspacing";
/** attribute of the table tag */
public static final String OFFSET = "offset";
/** attribute of the table tag */
public static final String WIDTHS = "widths";
/** attribute of the table tag */
public static final String TABLEFITSPAGE = "tablefitspage";
/** attribute of the table tag */
public static final String CELLSFITPAGE = "cellsfitpage";
/** attribute of the table tag */
public static final String CONVERT2PDFP = "convert2pdfp";
/** attribute of the cell tag */
public static final String HORIZONTALALIGN = "horizontalalign";
/** attribute of the cell tag */
public static final String VERTICALALIGN = "verticalalign";
/** attribute of the cell tag */
public static final String COLSPAN = "colspan";
/** attribute of the cell tag */
public static final String ROWSPAN = "rowspan";
/** attribute of the cell tag */
public static final String HEADER = "header";
/** attribute of the cell tag */
public static final String NOWRAP = "nowrap";
/** attribute of the table/cell tag */
public static final String BORDERWIDTH = "borderwidth";
/** attribute of the table/cell tag */
public static final String TOP = "top";
/** attribute of the table/cell tag */
public static final String BOTTOM = "bottom";
/** attribute of the table/cell tag */
public static final String WIDTH = "width";
/** attribute of the table/cell tag */
public static final String BORDERCOLOR = "bordercolor";
/** attribute of the table/cell tag */
public static final String BACKGROUNDCOLOR = "backgroundcolor";
/** attribute of the table/cell tag */
public static final String BGRED = "bgred";
/** attribute of the table/cell tag */
public static final String BGGREEN = "bggreen";
/** attribute of the table/cell tag */
public static final String BGBLUE = "bgblue";
/** attribute of the table/cell tag */
public static final String GRAYFILL = "grayfill";
// Misc
/** the image tag */
public static final String IMAGE = "image";
/** attribute of the image and annotation tag */
public static final String URL = "url";
/** attribute of the image tag */
public static final String UNDERLYING = "underlying";
/** attribute of the image tag */
public static final String TEXTWRAP = "textwrap";
/** attribute of the image tag */
public static final String ALT = "alt";
/** attribute of the image tag */
public static final String ABSOLUTEX = "absolutex";
/** attribute of the image tag */
public static final String ABSOLUTEY = "absolutey";
/** attribute of the image tag */
public static final String PLAINWIDTH = "plainwidth";
/** attribute of the image tag */
public static final String PLAINHEIGHT = "plainheight";
/** attribute of the image tag */
public static final String SCALEDWIDTH = "scaledwidth";
/** attribute of the image tag */
public static final String SCALEDHEIGHT = "scaledheight";
/** attribute of the image tag */
public static final String ROTATION = "rotation";
/** the newpage tag */
public static final String NEWPAGE = "newpage";
/** the newpage tag */
public static final String NEWLINE = "newline";
/** the annotation tag */
public static final String ANNOTATION = "annotation";
/** attribute of the annotation tag */
public static final String FILE = "file";
/** attribute of the annotation tag */
public static final String DESTINATION = "destination";
/** attribute of the annotation tag */
public static final String PAGE = "page";
/** attribute of the annotation tag */
public static final String NAMED = "named";
/** attribute of the annotation tag */
public static final String APPLICATION = "application";
/** attribute of the annotation tag */
public static final String PARAMETERS = "parameters";
/** attribute of the annotation tag */
public static final String OPERATION = "operation";
/** attribute of the annotation tag */
public static final String DEFAULTDIR = "defaultdir";
/** attribute of the annotation tag */
public static final String LLX = "llx";
/** attribute of the annotation tag */
public static final String LLY = "lly";
/** attribute of the annotation tag */
public static final String URX = "urx";
/** attribute of the annotation tag */
public static final String URY = "ury";
/** attribute of the annotation tag */
public static final String CONTENT = "content";
// alignment attribute values
/** the possible value of an alignment attribute */
public static final String ALIGN_LEFT = "Left";
/** the possible value of an alignment attribute */
public static final String ALIGN_CENTER = "Center";
/** the possible value of an alignment attribute */
public static final String ALIGN_RIGHT = "Right";
/** the possible value of an alignment attribute */
public static final String ALIGN_JUSTIFIED = "Justify";
/** the possible value of an alignment attribute */
public static final String ALIGN_JUSTIFIED_ALL = "JustifyAll";
/** the possible value of an alignment attribute */
public static final String ALIGN_TOP = "Top";
/** the possible value of an alignment attribute */
public static final String ALIGN_MIDDLE = "Middle";
/** the possible value of an alignment attribute */
public static final String ALIGN_BOTTOM = "Bottom";
/** the possible value of an alignment attribute */
public static final String ALIGN_BASELINE = "Baseline";
/** the possible value of an alignment attribute */
public static final String DEFAULT = "Default";
/** the possible value of an alignment attribute */
public static final String UNKNOWN = "unknown";
/** the possible value of an alignment attribute */
public static final String FONT = "font";
/** the possible value of an alignment attribute */
public static final String SIZE = "size";
/** the possible value of an alignment attribute */
public static final String STYLE = "fontstyle";
/** the possible value of a tag */
public static final String HORIZONTALRULE = "horizontalrule";
/** the possible value of a tag */
public static final String PAGE_SIZE = "pagesize";
/** the possible value of a tag */
public static final String ORIENTATION = "orientation";
/** a possible list attribute */
public static final String ALIGN_INDENTATION_ITEMS = "alignindent";
/** a possible list attribute */
public static final String AUTO_INDENT_ITEMS = "autoindent";
/** a possible list attribute */
public static final String LOWERCASE = "lowercase";
/**
* a possible list attribute
* @since 2.1.3
*/
public static final String FACE = "face";
/** attribute of the image or iframe tag
* @since 2.1.3
*/
public static final String SRC = "src";
// methods
/**
* Translates the alignment value to a String value.
*
* @param alignment the alignment value
* @return the translated value
*/
public static String getAlignment(int alignment) {
switch(alignment) {
case Element.ALIGN_LEFT:
return ALIGN_LEFT;
case Element.ALIGN_CENTER:
return ALIGN_CENTER;
case Element.ALIGN_RIGHT:
return ALIGN_RIGHT;
case Element.ALIGN_JUSTIFIED:
case Element.ALIGN_JUSTIFIED_ALL:
return ALIGN_JUSTIFIED;
case Element.ALIGN_TOP:
return ALIGN_TOP;
case Element.ALIGN_MIDDLE:
return ALIGN_MIDDLE;
case Element.ALIGN_BOTTOM:
return ALIGN_BOTTOM;
case Element.ALIGN_BASELINE:
return ALIGN_BASELINE;
default:
return DEFAULT;
}
}
/**
* Translates a String value to an alignment value.
* (written by Norman Richards, integrated into iText by Bruno)
* @param alignment a String (one of the ALIGN_ constants of this class)
* @return an alignment value (one of the ALIGN_ constants of the Element interface)
*/
public static int alignmentValue(String alignment) {
if (alignment == null) return Element.ALIGN_UNDEFINED;
if (ALIGN_CENTER.equalsIgnoreCase(alignment)) {
return Element.ALIGN_CENTER;
}
if (ALIGN_LEFT.equalsIgnoreCase(alignment)) {
return Element.ALIGN_LEFT;
}
if (ALIGN_RIGHT.equalsIgnoreCase(alignment)) {
return Element.ALIGN_RIGHT;
}
if (ALIGN_JUSTIFIED.equalsIgnoreCase(alignment)) {
return Element.ALIGN_JUSTIFIED;
}
if (ALIGN_JUSTIFIED_ALL.equalsIgnoreCase(alignment)) {
return Element.ALIGN_JUSTIFIED_ALL;
}
if (ALIGN_TOP.equalsIgnoreCase(alignment)) {
return Element.ALIGN_TOP;
}
if (ALIGN_MIDDLE.equalsIgnoreCase(alignment)) {
return Element.ALIGN_MIDDLE;
}
if (ALIGN_BOTTOM.equalsIgnoreCase(alignment)) {
return Element.ALIGN_BOTTOM;
}
if (ALIGN_BASELINE.equalsIgnoreCase(alignment)) {
return Element.ALIGN_BASELINE;
}
return Element.ALIGN_UNDEFINED;
}
} src/core/com/lowagie/text/ExceptionConverter.java 100644 0 0 13254 11213370070 17625 0 ustar 0 0 /*
* The original version of this class was published in an article by professor Heinz Kabutz.
* Read http://www.javaspecialists.co.za/archive/newsletter.do?issue=033&print=yes&locale=en_US
* "This material from The Java(tm) Specialists' Newsletter by Maximum Solutions (South Africa).
* Please contact Maximum Solutions for more information."
*
* Copyright (C) 2001 Dr. Heinz M. Kabutz
*/
/*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
/**
* The ExceptionConverter changes a checked exception into an
* unchecked exception.
*/
public class ExceptionConverter extends RuntimeException {
private static final long serialVersionUID = 8657630363395849399L;
/** we keep a handle to the wrapped exception */
private Exception ex;
/** prefix for the exception */
private String prefix;
/**
* Construct a RuntimeException based on another Exception
* @param ex the exception that has to be turned into a RuntimeException
*/
public ExceptionConverter(Exception ex) {
this.ex = ex;
prefix = (ex instanceof RuntimeException) ? "" : "ExceptionConverter: ";
}
/**
* Convert an Exception into an unchecked exception. Return the exception if it is
* already an unchecked exception or return an ExceptionConverter wrapper otherwise
*
* @param ex the exception to convert
* @return an unchecked exception
* @since 2.1.6
*/
public static final RuntimeException convertException(Exception ex) {
if (ex instanceof RuntimeException) {
return (RuntimeException) ex;
}
return new ExceptionConverter(ex);
}
/**
* and allow the user of ExceptionConverter to get a handle to it.
* @return the original exception
*/
public Exception getException() {
return ex;
}
/**
* We print the message of the checked exception
* @return message of the original exception
*/
public String getMessage() {
return ex.getMessage();
}
/**
* and make sure we also produce a localized version
* @return localized version of the message
*/
public String getLocalizedMessage() {
return ex.getLocalizedMessage();
}
/**
* The toString() is changed to be prefixed with ExceptionConverter
* @return String version of the exception
*/
public String toString() {
return prefix + ex;
}
/** we have to override this as well */
public void printStackTrace() {
printStackTrace(System.err);
}
/**
* here we prefix, with s.print(), not s.println(), the stack
* trace with "ExceptionConverter:"
* @param s
*/
public void printStackTrace(java.io.PrintStream s) {
synchronized (s) {
s.print(prefix);
ex.printStackTrace(s);
}
}
/**
* Again, we prefix the stack trace with "ExceptionConverter:"
* @param s
*/
public void printStackTrace(java.io.PrintWriter s) {
synchronized (s) {
s.print(prefix);
ex.printStackTrace(s);
}
}
/**
* requests to fill in the stack trace we will have to ignore.
* We can't throw an exception here, because this method
* is called by the constructor of Throwable
* @return a Throwable
*/
public Throwable fillInStackTrace() {
return this;
}
} src/core/com/lowagie/text/Font.java 100644 0 0 43366 11154165267 14732 0 ustar 0 0 /*
* $Id: Font.java 3678 2009-02-07 14:46:01Z blowagie $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.awt.Color;
import com.lowagie.text.html.Markup;
import com.lowagie.text.pdf.BaseFont;
/**
* Contains all the specifications of a font: fontfamily, size, style and color.
*
*
*
*/
public class Font implements Comparable {
// static membervariables for the different families
/** a possible value of a font family. */
public static final int COURIER = 0;
/** a possible value of a font family. */
public static final int HELVETICA = 1;
/** a possible value of a font family. */
public static final int TIMES_ROMAN = 2;
/** a possible value of a font family. */
public static final int SYMBOL = 3;
/** a possible value of a font family. */
public static final int ZAPFDINGBATS = 4;
// static membervariables for the different styles
/** this is a possible style. */
public static final int NORMAL = 0;
/** this is a possible style. */
public static final int BOLD = 1;
/** this is a possible style. */
public static final int ITALIC = 2;
/** this is a possible style. */
public static final int UNDERLINE = 4;
/** this is a possible style. */
public static final int STRIKETHRU = 8;
/** this is a possible style. */
public static final int BOLDITALIC = BOLD | ITALIC;
// static membervariables
/** the value of an undefined attribute. */
public static final int UNDEFINED = -1;
/** the value of the default size. */
public static final int DEFAULTSIZE = 12;
// membervariables
/** the value of the fontfamily. */
private int family = UNDEFINED;
/** the value of the fontsize. */
private float size = UNDEFINED;
/** the value of the style. */
private int style = UNDEFINED;
/** the value of the color. */
private Color color = null;
/** the external font */
private BaseFont baseFont = null;
// constructors
/**
* Copy constructor of a Font
*
* @param other
* the font that has to be copied
*/
public Font(Font other) {
this.family = other.family;
this.size = other.size;
this.style = other.style;
this.color = other.color;
this.baseFont = other.baseFont;
}
/**
* Constructs a Font.
*
* @param family
* the family to which this font belongs
* @param size
* the size of this font
* @param style
* the style of this font
* @param color
* the
*
* Paragraph p = new Paragraph("This is a paragraph", new
* Font(Font.HELVETICA, 18, Font.BOLDITALIC, new Color(0, 0, 255)) );
*
*
*
* Color
of this font.
*/
public Font(int family, float size, int style, Color color) {
this.family = family;
this.size = size;
this.style = style;
this.color = color;
}
/**
* Constructs a Font.
*
* @param bf
* the external font
* @param size
* the size of this font
* @param style
* the style of this font
* @param color
* the Color
of this font.
*/
public Font(BaseFont bf, float size, int style, Color color) {
this.baseFont = bf;
this.size = size;
this.style = style;
this.color = color;
}
/**
* Constructs a Font.
*
* @param bf
* the external font
* @param size
* the size of this font
* @param style
* the style of this font
*/
public Font(BaseFont bf, float size, int style) {
this(bf, size, style, null);
}
/**
* Constructs a Font.
*
* @param bf
* the external font
* @param size
* the size of this font
*/
public Font(BaseFont bf, float size) {
this(bf, size, UNDEFINED, null);
}
/**
* Constructs a Font.
*
* @param bf
* the external font
*/
public Font(BaseFont bf) {
this(bf, UNDEFINED, UNDEFINED, null);
}
/**
* Constructs a Font.
*
* @param family
* the family to which this font belongs
* @param size
* the size of this font
* @param style
* the style of this font
*/
public Font(int family, float size, int style) {
this(family, size, style, null);
}
/**
* Constructs a Font.
*
* @param family
* the family to which this font belongs
* @param size
* the size of this font
*/
public Font(int family, float size) {
this(family, size, UNDEFINED, null);
}
/**
* Constructs a Font.
*
* @param family
* the family to which this font belongs
*/
public Font(int family) {
this(family, UNDEFINED, UNDEFINED, null);
}
/**
* Constructs a Font.
*/
public Font() {
this(UNDEFINED, UNDEFINED, UNDEFINED, null);
}
// implementation of the Comparable interface
/**
* Compares this Font
with another
*
* @param object
* the other Font
* @return a value
*/
public int compareTo(Object object) {
if (object == null) {
return -1;
}
Font font;
try {
font = (Font) object;
if (baseFont != null && !baseFont.equals(font.getBaseFont())) {
return -2;
}
if (this.family != font.getFamily()) {
return 1;
}
if (this.size != font.getSize()) {
return 2;
}
if (this.style != font.getStyle()) {
return 3;
}
if (this.color == null) {
if (font.color == null) {
return 0;
}
return 4;
}
if (font.color == null) {
return 4;
}
if (this.color.equals(font.getColor())) {
return 0;
}
return 4;
} catch (ClassCastException cce) {
return -3;
}
}
// FAMILY
/**
* Gets the family of this font.
*
* @return the value of the family
*/
public int getFamily() {
return family;
}
/**
* Gets the familyname as a String.
*
* @return the familyname
*/
public String getFamilyname() {
String tmp = "unknown";
switch (getFamily()) {
case Font.COURIER:
return FontFactory.COURIER;
case Font.HELVETICA:
return FontFactory.HELVETICA;
case Font.TIMES_ROMAN:
return FontFactory.TIMES_ROMAN;
case Font.SYMBOL:
return FontFactory.SYMBOL;
case Font.ZAPFDINGBATS:
return FontFactory.ZAPFDINGBATS;
default:
if (baseFont != null) {
String[][] names = baseFont.getFamilyFontName();
for (int i = 0; i < names.length; i++) {
if ("0".equals(names[i][2])) {
return names[i][3];
}
if ("1033".equals(names[i][2])) {
tmp = names[i][3];
}
if ("".equals(names[i][2])) {
tmp = names[i][3];
}
}
}
}
return tmp;
}
/**
* Sets the family using a String
("Courier", "Helvetica",
* "Times New Roman", "Symbol" or "ZapfDingbats").
*
* @param family
* A String
representing a certain font-family.
*/
public void setFamily(String family) {
this.family = getFamilyIndex(family);
}
/**
* Translates a String
-value of a certain family into the
* index that is used for this family in this class.
*
* @param family
* A String
representing a certain font-family
* @return the corresponding index
*/
public static int getFamilyIndex(String family) {
if (family.equalsIgnoreCase(FontFactory.COURIER)) {
return COURIER;
}
if (family.equalsIgnoreCase(FontFactory.HELVETICA)) {
return HELVETICA;
}
if (family.equalsIgnoreCase(FontFactory.TIMES_ROMAN)) {
return TIMES_ROMAN;
}
if (family.equalsIgnoreCase(FontFactory.SYMBOL)) {
return SYMBOL;
}
if (family.equalsIgnoreCase(FontFactory.ZAPFDINGBATS)) {
return ZAPFDINGBATS;
}
return UNDEFINED;
}
// SIZE
/**
* Gets the size of this font.
*
* @return a size
*/
public float getSize() {
return size;
}
/**
* Gets the size that can be used with the calculated BaseFont
*
.
*
* @return the size that can be used with the calculated BaseFont
*
*/
public float getCalculatedSize() {
float s = this.size;
if (s == UNDEFINED) {
s = DEFAULTSIZE;
}
return s;
}
/**
* Gets the leading that can be used with this font.
*
* @param linespacing
* a certain linespacing
* @return the height of a line
*/
public float getCalculatedLeading(float linespacing) {
return linespacing * getCalculatedSize();
}
/**
* Sets the size.
*
* @param size
* The new size of the font.
*/
public void setSize(float size) {
this.size = size;
}
// STYLE
/**
* Gets the style of this font.
*
* @return a size
*/
public int getStyle() {
return style;
}
/**
* Gets the style that can be used with the calculated BaseFont
*
.
*
* @return the style that can be used with the calculated BaseFont
*
*/
public int getCalculatedStyle() {
int style = this.style;
if (style == UNDEFINED) {
style = NORMAL;
}
if (baseFont != null)
return style;
if (family == SYMBOL || family == ZAPFDINGBATS)
return style;
else
return style & (~BOLDITALIC);
}
/**
* checks if this font is Bold.
*
* @return a boolean
*/
public boolean isBold() {
if (style == UNDEFINED) {
return false;
}
return (style & BOLD) == BOLD;
}
/**
* checks if this font is Bold.
*
* @return a boolean
*/
public boolean isItalic() {
if (style == UNDEFINED) {
return false;
}
return (style & ITALIC) == ITALIC;
}
/**
* checks if this font is underlined.
*
* @return a boolean
*/
public boolean isUnderlined() {
if (style == UNDEFINED) {
return false;
}
return (style & UNDERLINE) == UNDERLINE;
}
/**
* checks if the style of this font is STRIKETHRU.
*
* @return a boolean
*/
public boolean isStrikethru() {
if (style == UNDEFINED) {
return false;
}
return (style & STRIKETHRU) == STRIKETHRU;
}
/**
* Sets the style.
*
* @param style
* the style.
*/
public void setStyle(int style) {
this.style = style;
}
/**
* Sets the style using a String
containing one of more of
* the following values: normal, bold, italic, underline, strike.
*
* @param style
* A String
representing a certain style.
*/
public void setStyle(String style) {
if (this.style == UNDEFINED)
this.style = NORMAL;
this.style |= getStyleValue(style);
}
/**
* Translates a String
-value of a certain style into the
* index value is used for this style in this class.
*
* @param style
* A String
* @return the corresponding value
*/
public static int getStyleValue(String style) {
int s = 0;
if (style.indexOf(Markup.CSS_VALUE_NORMAL) != -1) {
s |= NORMAL;
}
if (style.indexOf(Markup.CSS_VALUE_BOLD) != -1) {
s |= BOLD;
}
if (style.indexOf(Markup.CSS_VALUE_ITALIC) != -1) {
s |= ITALIC;
}
if (style.indexOf(Markup.CSS_VALUE_OBLIQUE) != -1) {
s |= ITALIC;
}
if (style.indexOf(Markup.CSS_VALUE_UNDERLINE) != -1) {
s |= UNDERLINE;
}
if (style.indexOf(Markup.CSS_VALUE_LINETHROUGH) != -1) {
s |= STRIKETHRU;
}
return s;
}
// COLOR
/**
* Gets the color of this font.
*
* @return a color
*/
public Color getColor() {
return color;
}
/**
* Sets the color.
*
* @param color
* the new color of the font
*/
public void setColor(Color color) {
this.color = color;
}
/**
* Sets the color.
*
* @param red
* the red-value of the new color
* @param green
* the green-value of the new color
* @param blue
* the blue-value of the new color
*/
public void setColor(int red, int green, int blue) {
this.color = new Color(red, green, blue);
}
// BASEFONT
/**
* Gets the BaseFont
inside this object.
*
* @return the BaseFont
*/
public BaseFont getBaseFont() {
return baseFont;
}
/**
* Gets the BaseFont
this class represents. For the built-in
* fonts a BaseFont
is calculated.
*
* @param specialEncoding
* true
to use the special encoding for Symbol and
* ZapfDingbats, false
to always use Cp1252
*
* @return the BaseFont
this class represents
*/
public BaseFont getCalculatedBaseFont(boolean specialEncoding) {
if (baseFont != null)
return baseFont;
int style = this.style;
if (style == UNDEFINED) {
style = NORMAL;
}
String fontName = BaseFont.HELVETICA;
String encoding = BaseFont.WINANSI;
BaseFont cfont = null;
switch (family) {
case COURIER:
switch (style & BOLDITALIC) {
case BOLD:
fontName = BaseFont.COURIER_BOLD;
break;
case ITALIC:
fontName = BaseFont.COURIER_OBLIQUE;
break;
case BOLDITALIC:
fontName = BaseFont.COURIER_BOLDOBLIQUE;
break;
default:
//case NORMAL:
fontName = BaseFont.COURIER;
break;
}
break;
case TIMES_ROMAN:
switch (style & BOLDITALIC) {
case BOLD:
fontName = BaseFont.TIMES_BOLD;
break;
case ITALIC:
fontName = BaseFont.TIMES_ITALIC;
break;
case BOLDITALIC:
fontName = BaseFont.TIMES_BOLDITALIC;
break;
default:
case NORMAL:
fontName = BaseFont.TIMES_ROMAN;
break;
}
break;
case SYMBOL:
fontName = BaseFont.SYMBOL;
if (specialEncoding)
encoding = BaseFont.SYMBOL;
break;
case ZAPFDINGBATS:
fontName = BaseFont.ZAPFDINGBATS;
if (specialEncoding)
encoding = BaseFont.ZAPFDINGBATS;
break;
default:
case Font.HELVETICA:
switch (style & BOLDITALIC) {
case BOLD:
fontName = BaseFont.HELVETICA_BOLD;
break;
case ITALIC:
fontName = BaseFont.HELVETICA_OBLIQUE;
break;
case BOLDITALIC:
fontName = BaseFont.HELVETICA_BOLDOBLIQUE;
break;
default:
case NORMAL:
fontName = BaseFont.HELVETICA;
break;
}
break;
}
try {
cfont = BaseFont.createFont(fontName, encoding, false);
} catch (Exception ee) {
throw new ExceptionConverter(ee);
}
return cfont;
}
// Helper methods
/**
* Checks if the properties of this font are undefined or null.
* boolean
*/
public boolean isStandardFont() {
return (family == UNDEFINED && size == UNDEFINED && style == UNDEFINED
&& color == null && baseFont == null);
}
/**
* Replaces the attributes that are equal to null with the
* attributes of a given font.
*
* @param font
* the font of a bigger element class
* @return a Font
*/
public Font difference(Font font) {
if (font == null) return this;
// size
float dSize = font.size;
if (dSize == UNDEFINED) {
dSize = this.size;
}
// style
int dStyle = UNDEFINED;
int style1 = this.style;
int style2 = font.getStyle();
if (style1 != UNDEFINED || style2 != UNDEFINED) {
if (style1 == UNDEFINED)
style1 = 0;
if (style2 == UNDEFINED)
style2 = 0;
dStyle = style1 | style2;
}
// color
Color dColor = font.color;
if (dColor == null) {
dColor = this.color;
}
// family
if (font.baseFont != null) {
return new Font(font.baseFont, dSize, dStyle, dColor);
}
if (font.getFamily() != UNDEFINED) {
return new Font(font.family, dSize, dStyle, dColor);
}
if (this.baseFont != null) {
if (dStyle == style1) {
return new Font(this.baseFont, dSize, dStyle, dColor);
} else {
return FontFactory.getFont(this.getFamilyname(), dSize, dStyle,
dColor);
}
}
return new Font(this.family, dSize, dStyle, dColor);
}
}
src/core/com/lowagie/text/FontFactory.java 100644 0 0 36701 11012562273 16244 0 ustar 0 0 /*
* $Id: FontFactory.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.awt.Color;
import java.util.Properties;
import java.util.Set;
import com.lowagie.text.pdf.BaseFont;
/**
* If you are using True Type fonts, you can declare the paths of the different ttf- and ttc-files
* to this static class first and then create fonts in your code using one of the static getFont-method
* without having to enter a path as parameter.
*
* @author Bruno Lowagie
*/
public final class FontFactory {
/** This is a possible value of a base 14 type 1 font */
public static final String COURIER = BaseFont.COURIER;
/** This is a possible value of a base 14 type 1 font */
public static final String COURIER_BOLD = BaseFont.COURIER_BOLD;
/** This is a possible value of a base 14 type 1 font */
public static final String COURIER_OBLIQUE = BaseFont.COURIER_OBLIQUE;
/** This is a possible value of a base 14 type 1 font */
public static final String COURIER_BOLDOBLIQUE = BaseFont.COURIER_BOLDOBLIQUE;
/** This is a possible value of a base 14 type 1 font */
public static final String HELVETICA = BaseFont.HELVETICA;
/** This is a possible value of a base 14 type 1 font */
public static final String HELVETICA_BOLD = BaseFont.HELVETICA_BOLD;
/** This is a possible value of a base 14 type 1 font */
public static final String HELVETICA_OBLIQUE = BaseFont.HELVETICA_OBLIQUE;
/** This is a possible value of a base 14 type 1 font */
public static final String HELVETICA_BOLDOBLIQUE = BaseFont.HELVETICA_BOLDOBLIQUE;
/** This is a possible value of a base 14 type 1 font */
public static final String SYMBOL = BaseFont.SYMBOL;
/** This is a possible value of a base 14 type 1 font */
public static final String TIMES = "Times";
/** This is a possible value of a base 14 type 1 font */
public static final String TIMES_ROMAN = BaseFont.TIMES_ROMAN;
/** This is a possible value of a base 14 type 1 font */
public static final String TIMES_BOLD = BaseFont.TIMES_BOLD;
/** This is a possible value of a base 14 type 1 font */
public static final String TIMES_ITALIC = BaseFont.TIMES_ITALIC;
/** This is a possible value of a base 14 type 1 font */
public static final String TIMES_BOLDITALIC = BaseFont.TIMES_BOLDITALIC;
/** This is a possible value of a base 14 type 1 font */
public static final String ZAPFDINGBATS = BaseFont.ZAPFDINGBATS;
private static FontFactoryImp fontImp = new FontFactoryImp();
/** This is the default encoding to use. */
public static String defaultEncoding = BaseFont.WINANSI;
/** This is the default value of the embedded variable. */
public static boolean defaultEmbedding = BaseFont.NOT_EMBEDDED;
/** Creates new FontFactory */
private FontFactory() {
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @param embedded true if the font is to be embedded in the PDF
* @param size the size of this font
* @param style the style of this font
* @param color the Color
of this font.
* @return the Font constructed based on the parameters
*/
public static Font getFont(String fontname, String encoding, boolean embedded, float size, int style, Color color) {
return fontImp.getFont(fontname, encoding, embedded, size, style, color);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @param embedded true if the font is to be embedded in the PDF
* @param size the size of this font
* @param style the style of this font
* @param color the Color
of this font.
* @param cached true if the font comes from the cache or is added to
* the cache if new, false if the font is always created new
* @return the Font constructed based on the parameters
*/
public static Font getFont(String fontname, String encoding, boolean embedded, float size, int style, Color color, boolean cached) {
return fontImp.getFont(fontname, encoding, embedded, size, style, color, cached);
}
/**
* Constructs a Font
-object.
*
* @param attributes the attributes of a Font
object.
* @return the Font constructed based on the attributes
*/
public static Font getFont(Properties attributes) {
fontImp.defaultEmbedding = defaultEmbedding;
fontImp.defaultEncoding = defaultEncoding;
return fontImp.getFont(attributes);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @param embedded true if the font is to be embedded in the PDF
* @param size the size of this font
* @param style the style of this font
* @return the Font constructed based on the parameters
*/
public static Font getFont(String fontname, String encoding, boolean embedded, float size, int style) {
return getFont(fontname, encoding, embedded, size, style, null);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @param embedded true if the font is to be embedded in the PDF
* @param size the size of this font
* @return the Font constructed based on the parameters
*/
public static Font getFont(String fontname, String encoding, boolean embedded, float size) {
return getFont(fontname, encoding, embedded, size, Font.UNDEFINED, null);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @param embedded true if the font is to be embedded in the PDF
* @return the Font constructed based on the parameters
*/
public static Font getFont(String fontname, String encoding, boolean embedded) {
return getFont(fontname, encoding, embedded, Font.UNDEFINED, Font.UNDEFINED, null);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @param size the size of this font
* @param style the style of this font
* @param color the Color
of this font.
* @return the Font constructed based on the parameters
*/
public static Font getFont(String fontname, String encoding, float size, int style, Color color) {
return getFont(fontname, encoding, defaultEmbedding, size, style, color);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @param size the size of this font
* @param style the style of this font
* @return the Font constructed based on the parameters
*/
public static Font getFont(String fontname, String encoding, float size, int style) {
return getFont(fontname, encoding, defaultEmbedding, size, style, null);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @param size the size of this font
* @return the Font constructed based on the parameters
*/
public static Font getFont(String fontname, String encoding, float size) {
return getFont(fontname, encoding, defaultEmbedding, size, Font.UNDEFINED, null);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @return the Font constructed based on the parameters
*/
public static Font getFont(String fontname, String encoding) {
return getFont(fontname, encoding, defaultEmbedding, Font.UNDEFINED, Font.UNDEFINED, null);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param size the size of this font
* @param style the style of this font
* @param color the Color
of this font.
* @return the Font constructed based on the parameters
*/
public static Font getFont(String fontname, float size, int style, Color color) {
return getFont(fontname, defaultEncoding, defaultEmbedding, size, style, color);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param size the size of this font
* @param color the Color
of this font.
* @return the Font constructed based on the parameters
* @since 2.1.0
*/
public static Font getFont(String fontname, float size, Color color) {
return getFont(fontname, defaultEncoding, defaultEmbedding, size, Font.UNDEFINED, color);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param size the size of this font
* @param style the style of this font
* @return the Font constructed based on the parameters
*/
public static Font getFont(String fontname, float size, int style) {
return getFont(fontname, defaultEncoding, defaultEmbedding, size, style, null);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param size the size of this font
* @return the Font constructed based on the parameters
*/
public static Font getFont(String fontname, float size) {
return getFont(fontname, defaultEncoding, defaultEmbedding, size, Font.UNDEFINED, null);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @return the Font constructed based on the parameters
*/
public static Font getFont(String fontname) {
return getFont(fontname, defaultEncoding, defaultEmbedding, Font.UNDEFINED, Font.UNDEFINED, null);
}
/**
* Register a font by giving explicitly the font family and name.
* @param familyName the font family
* @param fullName the font name
* @param path the font path
*/
public void registerFamily(String familyName, String fullName, String path) {
fontImp.registerFamily(familyName, fullName, path);
}
/**
* Register a ttf- or a ttc-file.
*
* @param path the path to a ttf- or ttc-file
*/
public static void register(String path) {
register(path, null);
}
/**
* Register a font file and use an alias for the font contained in it.
*
* @param path the path to a font file
* @param alias the alias you want to use for the font
*/
public static void register(String path, String alias) {
fontImp.register(path, alias);
}
/** Register all the fonts in a directory.
* @param dir the directory
* @return the number of fonts registered
*/
public static int registerDirectory(String dir) {
return fontImp.registerDirectory(dir);
}
/**
* Register all the fonts in a directory and possibly its subdirectories.
* @param dir the directory
* @param scanSubdirectories recursively scan subdirectories if true
* @return the number of fonts registered
* @since 2.1.2
*/
public static int registerDirectory(String dir, boolean scanSubdirectories) {
return fontImp.registerDirectory(dir, scanSubdirectories);
}
/** Register fonts in some probable directories. It usually works in Windows,
* Linux and Solaris.
* @return the number of fonts registered
*/
public static int registerDirectories() {
return fontImp.registerDirectories();
}
/**
* Gets a set of registered fontnames.
* @return a set of registered fonts
*/
public static Set getRegisteredFonts() {
return fontImp.getRegisteredFonts();
}
/**
* Gets a set of registered fontnames.
* @return a set of registered font families
*/
public static Set getRegisteredFamilies() {
return fontImp.getRegisteredFamilies();
}
/**
* Gets a set of registered fontnames.
* @param fontname of a font that may or may not be registered
* @return true if a given font is registered
*/
public static boolean contains(String fontname) {
return fontImp.isRegistered(fontname);
}
/**
* Checks if a certain font is registered.
*
* @param fontname the name of the font that has to be checked.
* @return true if the font is found
*/
public static boolean isRegistered(String fontname) {
return fontImp.isRegistered(fontname);
}
/**
* Gets the font factory implementation.
* @return the font factory implementation
*/
public static FontFactoryImp getFontImp() {
return fontImp;
}
/**
* Sets the font factory implementation.
* @param fontImp the font factory implementation
*/
public static void setFontImp(FontFactoryImp fontImp) {
if (fontImp == null)
throw new NullPointerException("FontFactoryImp cannot be null.");
FontFactory.fontImp = fontImp;
}
}
src/core/com/lowagie/text/FontFactoryImp.java 100644 0 0 67660 11036112746 16724 0 ustar 0 0 /*
* $Id: FontFactoryImp.java 3548 2008-07-12 11:15:35Z blowagie $
*
* Copyright 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import com.lowagie.text.html.Markup;
import com.lowagie.text.pdf.BaseFont;
/**
* If you are using True Type fonts, you can declare the paths of the different ttf- and ttc-files
* to this class first and then create fonts in your code using one of the getFont method
* without having to enter a path as parameter.
*
* @author Bruno Lowagie
*/
public class FontFactoryImp {
/** This is a map of postscriptfontnames of True Type fonts and the path of their ttf- or ttc-file. */
private Properties trueTypeFonts = new Properties();
private static String[] TTFamilyOrder = {
"3", "1", "1033",
"3", "0", "1033",
"1", "0", "0",
"0", "3", "0"
};
/** This is a map of fontfamilies. */
private Hashtable fontFamilies = new Hashtable();
/** This is the default encoding to use. */
public String defaultEncoding = BaseFont.WINANSI;
/** This is the default value of the embedded variable. */
public boolean defaultEmbedding = BaseFont.NOT_EMBEDDED;
/** Creates new FontFactory */
public FontFactoryImp() {
trueTypeFonts.setProperty(FontFactory.COURIER.toLowerCase(), FontFactory.COURIER);
trueTypeFonts.setProperty(FontFactory.COURIER_BOLD.toLowerCase(), FontFactory.COURIER_BOLD);
trueTypeFonts.setProperty(FontFactory.COURIER_OBLIQUE.toLowerCase(), FontFactory.COURIER_OBLIQUE);
trueTypeFonts.setProperty(FontFactory.COURIER_BOLDOBLIQUE.toLowerCase(), FontFactory.COURIER_BOLDOBLIQUE);
trueTypeFonts.setProperty(FontFactory.HELVETICA.toLowerCase(), FontFactory.HELVETICA);
trueTypeFonts.setProperty(FontFactory.HELVETICA_BOLD.toLowerCase(), FontFactory.HELVETICA_BOLD);
trueTypeFonts.setProperty(FontFactory.HELVETICA_OBLIQUE.toLowerCase(), FontFactory.HELVETICA_OBLIQUE);
trueTypeFonts.setProperty(FontFactory.HELVETICA_BOLDOBLIQUE.toLowerCase(), FontFactory.HELVETICA_BOLDOBLIQUE);
trueTypeFonts.setProperty(FontFactory.SYMBOL.toLowerCase(), FontFactory.SYMBOL);
trueTypeFonts.setProperty(FontFactory.TIMES_ROMAN.toLowerCase(), FontFactory.TIMES_ROMAN);
trueTypeFonts.setProperty(FontFactory.TIMES_BOLD.toLowerCase(), FontFactory.TIMES_BOLD);
trueTypeFonts.setProperty(FontFactory.TIMES_ITALIC.toLowerCase(), FontFactory.TIMES_ITALIC);
trueTypeFonts.setProperty(FontFactory.TIMES_BOLDITALIC.toLowerCase(), FontFactory.TIMES_BOLDITALIC);
trueTypeFonts.setProperty(FontFactory.ZAPFDINGBATS.toLowerCase(), FontFactory.ZAPFDINGBATS);
ArrayList tmp;
tmp = new ArrayList();
tmp.add(FontFactory.COURIER);
tmp.add(FontFactory.COURIER_BOLD);
tmp.add(FontFactory.COURIER_OBLIQUE);
tmp.add(FontFactory.COURIER_BOLDOBLIQUE);
fontFamilies.put(FontFactory.COURIER.toLowerCase(), tmp);
tmp = new ArrayList();
tmp.add(FontFactory.HELVETICA);
tmp.add(FontFactory.HELVETICA_BOLD);
tmp.add(FontFactory.HELVETICA_OBLIQUE);
tmp.add(FontFactory.HELVETICA_BOLDOBLIQUE);
fontFamilies.put(FontFactory.HELVETICA.toLowerCase(), tmp);
tmp = new ArrayList();
tmp.add(FontFactory.SYMBOL);
fontFamilies.put(FontFactory.SYMBOL.toLowerCase(), tmp);
tmp = new ArrayList();
tmp.add(FontFactory.TIMES_ROMAN);
tmp.add(FontFactory.TIMES_BOLD);
tmp.add(FontFactory.TIMES_ITALIC);
tmp.add(FontFactory.TIMES_BOLDITALIC);
fontFamilies.put(FontFactory.TIMES.toLowerCase(), tmp);
fontFamilies.put(FontFactory.TIMES_ROMAN.toLowerCase(), tmp);
tmp = new ArrayList();
tmp.add(FontFactory.ZAPFDINGBATS);
fontFamilies.put(FontFactory.ZAPFDINGBATS.toLowerCase(), tmp);
}
/**
* Constructs a
's to empty/null spaces.
*/
private void fillEmptyMatrixCells() {
try {
for (int i=0; i < rows.size(); i++) {
for (int j=0; j < columns; j++) {
if (!((Row) rows.get(i)).isReserved(j)) {
addCell(defaultCell, new Point(i, j));
}
}
}
}
catch(BadElementException bee) {
throw new ExceptionConverter(bee);
}
}
/**
* check if Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @param embedded true if the font is to be embedded in the PDF
* @param size the size of this font
* @param style the style of this font
* @param color the Color
of this font.
* @return the Font constructed based on the parameters
*/
public Font getFont(String fontname, String encoding, boolean embedded, float size, int style, Color color) {
return getFont(fontname, encoding, embedded, size, style, color, true);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @param embedded true if the font is to be embedded in the PDF
* @param size the size of this font
* @param style the style of this font
* @param color the Color
of this font.
* @param cached true if the font comes from the cache or is added to
* the cache if new, false if the font is always created new
* @return the Font constructed based on the parameters
*/
public Font getFont(String fontname, String encoding, boolean embedded, float size, int style, Color color, boolean cached) {
if (fontname == null) return new Font(Font.UNDEFINED, size, style, color);
String lowercasefontname = fontname.toLowerCase();
ArrayList tmp = (ArrayList) fontFamilies.get(lowercasefontname);
if (tmp != null) {
// some bugs were fixed here by Daniel Marczisovszky
int s = style == Font.UNDEFINED ? Font.NORMAL : style;
int fs = Font.NORMAL;
boolean found = false;
for (Iterator i = tmp.iterator(); i.hasNext(); ) {
String f = (String) i.next();
String lcf = f.toLowerCase();
fs = Font.NORMAL;
if (lcf.toLowerCase().indexOf("bold") != -1) fs |= Font.BOLD;
if (lcf.toLowerCase().indexOf("italic") != -1 || lcf.toLowerCase().indexOf("oblique") != -1) fs |= Font.ITALIC;
if ((s & Font.BOLDITALIC) == fs) {
fontname = f;
found = true;
break;
}
}
if (style != Font.UNDEFINED && found) {
style &= ~fs;
}
}
BaseFont basefont = null;
try {
try {
// the font is a type 1 font or CJK font
basefont = BaseFont.createFont(fontname, encoding, embedded, cached, null, null, true);
}
catch(DocumentException de) {
}
if (basefont == null) {
// the font is a true type font or an unknown font
fontname = trueTypeFonts.getProperty(fontname.toLowerCase());
// the font is not registered as truetype font
if (fontname == null) return new Font(Font.UNDEFINED, size, style, color);
// the font is registered as truetype font
basefont = BaseFont.createFont(fontname, encoding, embedded, cached, null, null);
}
}
catch(DocumentException de) {
// this shouldn't happen
throw new ExceptionConverter(de);
}
catch(IOException ioe) {
// the font is registered as a true type font, but the path was wrong
return new Font(Font.UNDEFINED, size, style, color);
}
catch(NullPointerException npe) {
// null was entered as fontname and/or encoding
return new Font(Font.UNDEFINED, size, style, color);
}
return new Font(basefont, size, style, color);
}
/**
* Constructs a Font
-object.
*
* @param attributes the attributes of a Font
object.
* @return the Font constructed based on the attributes
*/
public Font getFont(Properties attributes) {
String fontname = null;
String encoding = defaultEncoding;
boolean embedded = defaultEmbedding;
float size = Font.UNDEFINED;
int style = Font.NORMAL;
Color color = null;
String value = attributes.getProperty(Markup.HTML_ATTR_STYLE);
if (value != null && value.length() > 0) {
Properties styleAttributes = Markup.parseAttributes(value);
if (styleAttributes.isEmpty()) {
attributes.put(Markup.HTML_ATTR_STYLE, value);
}
else {
fontname = styleAttributes.getProperty(Markup.CSS_KEY_FONTFAMILY);
if (fontname != null) {
String tmp;
while (fontname.indexOf(',') != -1) {
tmp = fontname.substring(0, fontname.indexOf(','));
if (isRegistered(tmp)) {
fontname = tmp;
}
else {
fontname = fontname.substring(fontname.indexOf(',') + 1);
}
}
}
if ((value = styleAttributes.getProperty(Markup.CSS_KEY_FONTSIZE)) != null) {
size = Markup.parseLength(value);
}
if ((value = styleAttributes.getProperty(Markup.CSS_KEY_FONTWEIGHT)) != null) {
style |= Font.getStyleValue(value);
}
if ((value = styleAttributes.getProperty(Markup.CSS_KEY_FONTSTYLE)) != null) {
style |= Font.getStyleValue(value);
}
if ((value = styleAttributes.getProperty(Markup.CSS_KEY_COLOR)) != null) {
color = Markup.decodeColor(value);
}
attributes.putAll(styleAttributes);
for (Enumeration e = styleAttributes.keys(); e.hasMoreElements();) {
Object o = e.nextElement();
attributes.put(o, styleAttributes.get(o));
}
}
}
if ((value = attributes.getProperty(ElementTags.ENCODING)) != null) {
encoding = value;
}
if ("true".equals(attributes.getProperty(ElementTags.EMBEDDED))) {
embedded = true;
}
if ((value = attributes.getProperty(ElementTags.FONT)) != null) {
fontname = value;
}
if ((value = attributes.getProperty(ElementTags.SIZE)) != null) {
size = Markup.parseLength(value);
}
if ((value = attributes.getProperty(Markup.HTML_ATTR_STYLE)) != null) {
style |= Font.getStyleValue(value);
}
if ((value = attributes.getProperty(ElementTags.STYLE)) != null) {
style |= Font.getStyleValue(value);
}
String r = attributes.getProperty(ElementTags.RED);
String g = attributes.getProperty(ElementTags.GREEN);
String b = attributes.getProperty(ElementTags.BLUE);
if (r != null || g != null || b != null) {
int red = 0;
int green = 0;
int blue = 0;
if (r != null) red = Integer.parseInt(r);
if (g != null) green = Integer.parseInt(g);
if (b != null) blue = Integer.parseInt(b);
color = new Color(red, green, blue);
}
else if ((value = attributes.getProperty(ElementTags.COLOR)) != null) {
color = Markup.decodeColor(value);
}
if (fontname == null) {
return getFont(null, encoding, embedded, size, style, color);
}
return getFont(fontname, encoding, embedded, size, style, color);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @param embedded true if the font is to be embedded in the PDF
* @param size the size of this font
* @param style the style of this font
* @return the Font constructed based on the parameters
*/
public Font getFont(String fontname, String encoding, boolean embedded, float size, int style) {
return getFont(fontname, encoding, embedded, size, style, null);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @param embedded true if the font is to be embedded in the PDF
* @param size the size of this font
* @return the Font constructed based on the parameters
*/
public Font getFont(String fontname, String encoding, boolean embedded, float size) {
return getFont(fontname, encoding, embedded, size, Font.UNDEFINED, null);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @param embedded true if the font is to be embedded in the PDF
* @return the Font constructed based on the parameters
*/
public Font getFont(String fontname, String encoding, boolean embedded) {
return getFont(fontname, encoding, embedded, Font.UNDEFINED, Font.UNDEFINED, null);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @param size the size of this font
* @param style the style of this font
* @param color the Color
of this font.
* @return the Font constructed based on the parameters
*/
public Font getFont(String fontname, String encoding, float size, int style, Color color) {
return getFont(fontname, encoding, defaultEmbedding, size, style, color);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @param size the size of this font
* @param style the style of this font
* @return the Font constructed based on the parameters
*/
public Font getFont(String fontname, String encoding, float size, int style) {
return getFont(fontname, encoding, defaultEmbedding, size, style, null);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @param size the size of this font
* @return the Font constructed based on the parameters
*/
public Font getFont(String fontname, String encoding, float size) {
return getFont(fontname, encoding, defaultEmbedding, size, Font.UNDEFINED, null);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param size the size of this font
* @param color the Color
of this font.
* @return the Font constructed based on the parameters
* @since 2.1.0
*/
public Font getFont(String fontname, float size, Color color) {
return getFont(fontname, defaultEncoding, defaultEmbedding, size, Font.UNDEFINED, color);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param encoding the encoding of the font
* @return the Font constructed based on the parameters
*/
public Font getFont(String fontname, String encoding) {
return getFont(fontname, encoding, defaultEmbedding, Font.UNDEFINED, Font.UNDEFINED, null);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param size the size of this font
* @param style the style of this font
* @param color the Color
of this font.
* @return the Font constructed based on the parameters
*/
public Font getFont(String fontname, float size, int style, Color color) {
return getFont(fontname, defaultEncoding, defaultEmbedding, size, style, color);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param size the size of this font
* @param style the style of this font
* @return the Font constructed based on the parameters
*/
public Font getFont(String fontname, float size, int style) {
return getFont(fontname, defaultEncoding, defaultEmbedding, size, style, null);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @param size the size of this font
* @return the Font constructed based on the parameters
*/
public Font getFont(String fontname, float size) {
return getFont(fontname, defaultEncoding, defaultEmbedding, size, Font.UNDEFINED, null);
}
/**
* Constructs a Font
-object.
*
* @param fontname the name of the font
* @return the Font constructed based on the parameters
*/
public Font getFont(String fontname) {
return getFont(fontname, defaultEncoding, defaultEmbedding, Font.UNDEFINED, Font.UNDEFINED, null);
}
/**
* Register a font by giving explicitly the font family and name.
* @param familyName the font family
* @param fullName the font name
* @param path the font path
*/
public void registerFamily(String familyName, String fullName, String path) {
if (path != null)
trueTypeFonts.setProperty(fullName, path);
ArrayList tmp = (ArrayList) fontFamilies.get(familyName);
if (tmp == null) {
tmp = new ArrayList();
tmp.add(fullName);
fontFamilies.put(familyName, tmp);
}
else {
int fullNameLength = fullName.length();
boolean inserted = false;
for (int j = 0; j < tmp.size(); ++j) {
if (((String)tmp.get(j)).length() >= fullNameLength) {
tmp.add(j, fullName);
inserted = true;
break;
}
}
if (!inserted)
tmp.add(fullName);
}
}
/**
* Register a ttf- or a ttc-file.
*
* @param path the path to a ttf- or ttc-file
*/
public void register(String path) {
register(path, null);
}
/**
* Register a font file and use an alias for the font contained in it.
*
* @param path the path to a font file
* @param alias the alias you want to use for the font
*/
public void register(String path, String alias) {
try {
if (path.toLowerCase().endsWith(".ttf") || path.toLowerCase().endsWith(".otf") || path.toLowerCase().indexOf(".ttc,") > 0) {
Object allNames[] = BaseFont.getAllFontNames(path, BaseFont.WINANSI, null);
trueTypeFonts.setProperty(((String)allNames[0]).toLowerCase(), path);
if (alias != null) {
trueTypeFonts.setProperty(alias.toLowerCase(), path);
}
// register all the font names with all the locales
String[][] names = (String[][])allNames[2]; //full name
for (int i = 0; i < names.length; i++) {
trueTypeFonts.setProperty(names[i][3].toLowerCase(), path);
}
String fullName = null;
String familyName = null;
names = (String[][])allNames[1]; //family name
for (int k = 0; k < TTFamilyOrder.length; k += 3) {
for (int i = 0; i < names.length; i++) {
if (TTFamilyOrder[k].equals(names[i][0]) && TTFamilyOrder[k + 1].equals(names[i][1]) && TTFamilyOrder[k + 2].equals(names[i][2])) {
familyName = names[i][3].toLowerCase();
k = TTFamilyOrder.length;
break;
}
}
}
if (familyName != null) {
String lastName = "";
names = (String[][])allNames[2]; //full name
for (int i = 0; i < names.length; i++) {
for (int k = 0; k < TTFamilyOrder.length; k += 3) {
if (TTFamilyOrder[k].equals(names[i][0]) && TTFamilyOrder[k + 1].equals(names[i][1]) && TTFamilyOrder[k + 2].equals(names[i][2])) {
fullName = names[i][3];
if (fullName.equals(lastName))
continue;
lastName = fullName;
registerFamily(familyName, fullName, null);
break;
}
}
}
}
}
else if (path.toLowerCase().endsWith(".ttc")) {
if (alias != null)
System.err.println("class FontFactory: You can't define an alias for a true type collection.");
String[] names = BaseFont.enumerateTTCNames(path);
for (int i = 0; i < names.length; i++) {
register(path + "," + i);
}
}
else if (path.toLowerCase().endsWith(".afm") || path.toLowerCase().endsWith(".pfm")) {
BaseFont bf = BaseFont.createFont(path, BaseFont.CP1252, false);
String fullName = bf.getFullFontName()[0][3].toLowerCase();
String familyName = bf.getFamilyFontName()[0][3].toLowerCase();
String psName = bf.getPostscriptFontName().toLowerCase();
registerFamily(familyName, fullName, null);
trueTypeFonts.setProperty(psName, path);
trueTypeFonts.setProperty(fullName, path);
}
}
catch(DocumentException de) {
// this shouldn't happen
throw new ExceptionConverter(de);
}
catch(IOException ioe) {
throw new ExceptionConverter(ioe);
}
}
/** Register all the fonts in a directory.
* @param dir the directory
* @return the number of fonts registered
*/
public int registerDirectory(String dir) {
return registerDirectory(dir, false);
}
/**
* Register all the fonts in a directory and possibly its subdirectories.
* @param dir the directory
* @param scanSubdirectories recursively scan subdirectories if true
* @return the number of fonts registered
* @since 2.1.2
*/
public int registerDirectory(String dir, boolean scanSubdirectories) {
int count = 0;
try {
File file = new File(dir);
if (!file.exists() || !file.isDirectory())
return 0;
String files[] = file.list();
if (files == null)
return 0;
for (int k = 0; k < files.length; ++k) {
try {
file = new File(dir, files[k]);
if (file.isDirectory()) {
if (scanSubdirectories) {
count += registerDirectory(file.getAbsolutePath(), true);
}
} else {
String name = file.getPath();
String suffix = name.length() < 4 ? null : name.substring(name.length() - 4).toLowerCase();
if (".afm".equals(suffix) || ".pfm".equals(suffix)) {
/* Only register Type 1 fonts with matching .pfb files */
File pfb = new File(name.substring(0, name.length() - 4) + ".pfb");
if (pfb.exists()) {
register(name, null);
++count;
}
} else if (".ttf".equals(suffix) || ".otf".equals(suffix) || ".ttc".equals(suffix)) {
register(name, null);
++count;
}
}
}
catch (Exception e) {
//empty on purpose
}
}
}
catch (Exception e) {
//empty on purpose
}
return count;
}
/** Register fonts in some probable directories. It usually works in Windows,
* Linux and Solaris.
* @return the number of fonts registered
*/
public int registerDirectories() {
int count = 0;
count += registerDirectory("c:/windows/fonts");
count += registerDirectory("c:/winnt/fonts");
count += registerDirectory("d:/windows/fonts");
count += registerDirectory("d:/winnt/fonts");
count += registerDirectory("/usr/share/X11/fonts", true);
count += registerDirectory("/usr/X/lib/X11/fonts", true);
count += registerDirectory("/usr/openwin/lib/X11/fonts", true);
count += registerDirectory("/usr/share/fonts", true);
count += registerDirectory("/usr/X11R6/lib/X11/fonts", true);
count += registerDirectory("/Library/Fonts");
count += registerDirectory("/System/Library/Fonts");
return count;
}
/**
* Gets a set of registered fontnames.
* @return a set of registered fonts
*/
public Set getRegisteredFonts() {
return Utilities.getKeySet(trueTypeFonts);
}
/**
* Gets a set of registered fontnames.
* @return a set of registered font families
*/
public Set getRegisteredFamilies() {
return Utilities.getKeySet(fontFamilies);
}
/**
* Checks if a certain font is registered.
*
* @param fontname the name of the font that has to be checked.
* @return true if the font is found
*/
public boolean isRegistered(String fontname) {
return trueTypeFonts.containsKey(fontname.toLowerCase());
}
}
src/core/com/lowagie/text/GreekList.java 100644 0 0 10304 11000354131 15653 0 ustar 0 0 /*
* Copyright 2003 by Michael Niedermair and 2007 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import com.lowagie.text.factories.GreekAlphabetFactory;
/**
*
* A special-version of
, UNSUPPORTED_MARKER or NOPARAM_MARKER
*/
private static final int marker(int marker) {
for (int i = 0; i < VALID_MARKERS.length; i++) {
if (marker == VALID_MARKERS[i]) {
return VALID_MARKER;
}
}
for (int i = 0; i < NOPARAM_MARKERS.length; i++) {
if (marker == NOPARAM_MARKERS[i]) {
return NOPARAM_MARKER;
}
}
for (int i = 0; i < UNSUPPORTED_MARKERS.length; i++) {
if (marker == UNSUPPORTED_MARKERS[i]) {
return UNSUPPORTED_MARKER;
}
}
return NOT_A_MARKER;
}
// private methods
/**
* This method checks if the image is a valid JPEG and processes some parameters.
* @throws BadElementException
* @throws IOException
*/
private void processParameters() throws BadElementException, IOException {
type = JPEG;
originalType = ORIGINAL_JPEG;
InputStream is = null;
try {
String errorID;
if (rawData == null){
is = url.openStream();
errorID = url.toString();
}
else{
is = new java.io.ByteArrayInputStream(rawData);
errorID = "Byte array";
}
if (is.read() != 0xFF || is.read() != 0xD8) {
throw new BadElementException(errorID + " is not a valid JPEG-file.");
}
boolean firstPass = true;
int len;
while (true) {
int v = is.read();
if (v < 0)
throw new IOException("Premature EOF while reading JPG.");
if (v == 0xFF) {
int marker = is.read();
if (firstPass && marker == M_APP0) {
firstPass = false;
len = getShort(is);
if (len < 16) {
Utilities.skip(is, len - 2);
continue;
}
byte bcomp[] = new byte[JFIF_ID.length];
int r = is.read(bcomp);
if (r != bcomp.length)
throw new BadElementException(errorID + " corrupted JFIF marker.");
boolean found = true;
for (int k = 0; k < bcomp.length; ++k) {
if (bcomp[k] != JFIF_ID[k]) {
found = false;
break;
}
}
if (!found) {
Utilities.skip(is, len - 2 - bcomp.length);
continue;
}
Utilities.skip(is, 2);
int units = is.read();
int dx = getShort(is);
int dy = getShort(is);
if (units == 1) {
dpiX = dx;
dpiY = dy;
}
else if (units == 2) {
dpiX = (int)(dx * 2.54f + 0.5f);
dpiY = (int)(dy * 2.54f + 0.5f);
}
Utilities.skip(is, len - 2 - bcomp.length - 7);
continue;
}
if (marker == M_APPE) {
len = getShort(is) - 2;
byte[] byteappe = new byte[len];
for (int k = 0; k < len; ++k) {
byteappe[k] = (byte)is.read();
}
if (byteappe.length >= 12) {
String appe = new String(byteappe, 0, 5, "ISO-8859-1");
if (appe.equals("Adobe")) {
invert = true;
}
}
continue;
}
if (marker == M_APP2) {
len = getShort(is) - 2;
byte[] byteapp2 = new byte[len];
for (int k = 0; k < len; ++k) {
byteapp2[k] = (byte)is.read();
}
if (byteapp2.length >= 14) {
String app2 = new String(byteapp2, 0, 11, "ISO-8859-1");
if (app2.equals("ICC_PROFILE")) {
int order = byteapp2[12] & 0xff;
int count = byteapp2[13] & 0xff;
if (icc == null)
icc = new byte[count][];
icc[order - 1] = byteapp2;
}
}
continue;
}
firstPass = false;
int markertype = marker(marker);
if (markertype == VALID_MARKER) {
Utilities.skip(is, 2);
if (is.read() != 0x08) {
throw new BadElementException(errorID + " must have 8 bits per component.");
}
scaledHeight = getShort(is);
setTop(scaledHeight);
scaledWidth = getShort(is);
setRight(scaledWidth);
colorspace = is.read();
bpc = 8;
break;
}
else if (markertype == UNSUPPORTED_MARKER) {
throw new BadElementException(errorID + ": unsupported JPEG marker: " + marker);
}
else if (markertype != NOPARAM_MARKER) {
Utilities.skip(is, getShort(is) - 2);
}
}
}
}
finally {
if (is != null) {
is.close();
}
}
plainWidth = getWidth();
plainHeight = getHeight();
if (icc != null) {
int total = 0;
for (int k = 0; k < icc.length; ++k) {
if (icc[k] == null) {
icc = null;
return;
}
total += icc[k].length - 14;
}
byte[] ficc = new byte[total];
total = 0;
for (int k = 0; k < icc.length; ++k) {
System.arraycopy(icc[k], 14, ficc, total, icc[k].length - 14);
total += icc[k].length - 14;
}
try {
ICC_Profile icc_prof = ICC_Profile.getInstance(ficc);
tagICC(icc_prof);
}
catch(IllegalArgumentException e) {
// ignore ICC profile if it's invalid.
}
icc = null;
}
}
}
src/core/com/lowagie/text/Jpeg2000.java 100644 0 0 20655 11106243445 15177 0 ustar 0 0 /*
* $Id: Jpeg2000.java 3583 2008-08-12 00:00:09Z xlv $
*
* Copyright 2007 by Paulo Soares.
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
* An LIST
which use greek-letters.
*
* @see com.lowagie.text.List
*/
public class GreekList extends List {
// constructors
/**
* Initialization
*/
public GreekList() {
super(true);
setGreekFont();
}
/**
* Initialization
*
* @param symbolIndent indent
*/
public GreekList(int symbolIndent) {
super(true, symbolIndent);
setGreekFont();
}
/**
* Initialization
* @param greeklower greek-char in lowercase
* @param symbolIndent indent
*/
public GreekList(boolean greeklower, int symbolIndent) {
super(true, symbolIndent);
lowercase = greeklower;
setGreekFont();
}
// helper method
/**
* change the font to SYMBOL
*/
protected void setGreekFont() {
float fontsize = symbol.getFont().getSize();
symbol.setFont(FontFactory.getFont(FontFactory.SYMBOL, fontsize, Font.NORMAL));
}
// overridden method
/**
* Adds an Object
to the List
.
*
* @param o the object to add.
* @return true if adding the object succeeded
*/
public boolean add(Object o) {
if (o instanceof ListItem) {
ListItem item = (ListItem) o;
Chunk chunk = new Chunk(preSymbol, symbol.getFont());
chunk.append(GreekAlphabetFactory.getString(first + list.size(), lowercase));
chunk.append(postSymbol);
item.setListSymbol(chunk);
item.setIndentationLeft(symbolIndent, autoindent);
item.setIndentationRight(0);
list.add(item);
} else if (o instanceof List) {
List nested = (List) o;
nested.setIndentationLeft(nested.getIndentationLeft() + symbolIndent);
first--;
return list.add(nested);
} else if (o instanceof String) {
return this.add(new ListItem((String) o));
}
return false;
}
}
src/core/com/lowagie/text/Header.java 100644 0 0 6727 11012562273 15163 0 ustar 0 0 /*
* $Id: Header.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
/**
* This is an Element
that contains
* some user defined meta information about the document.
*
*
* @see Element
* @see Meta
*/
public class Header extends Meta {
// membervariables
/** This is the content of this chunk of text. */
private StringBuffer name;
// constructors
/**
* Constructs a
* Header header = new Header("inspired by", "William Shakespeare");
*
Meta
.
*
* @param name the name of the meta-information
* @param content the content
*/
public Header(String name, String content) {
super(Element.HEADER, content);
this.name = new StringBuffer(name);
}
// methods to retrieve information
/**
* Returns the name of the meta information.
*
* @return a String
*/
public String getName() {
return name.toString();
}
} src/core/com/lowagie/text/HeaderFooter.java 100644 0 0 13641 11012562273 16353 0 ustar 0 0 /*
* $Id: HeaderFooter.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
/**
* A HeaderFooter
-object is a Rectangle
with text
* that can be put above and/or below every page.
*
*/
public class HeaderFooter extends Rectangle {
// membervariables
/** Does the page contain a pagenumber? */
private boolean numbered;
/** This is the
* HeaderFooter header = new HeaderFooter(new Phrase("This is a header."), false);
* HeaderFooter footer = new HeaderFooter(new Phrase("This is page "), new Phrase("."));
* document.setHeader(header);
* document.setFooter(footer);
*
Phrase
that comes before the pagenumber. */
private Phrase before = null;
/** This is number of the page. */
private int pageN;
/** This is the Phrase
that comes after the pagenumber. */
private Phrase after = null;
/** This is alignment of the header/footer. */
private int alignment;
// constructors
/**
* Constructs a HeaderFooter
-object.
*
* @param before the Phrase
before the pagenumber
* @param after the Phrase
before the pagenumber
*/
public HeaderFooter(Phrase before, Phrase after) {
super(0, 0, 0, 0);
setBorder(TOP + BOTTOM);
setBorderWidth(1);
numbered = true;
this.before = before;
this.after = after;
}
/**
* Constructs a Header
-object with a pagenumber at the end.
*
* @param before the Phrase
before the pagenumber
* @param numbered true
if the page has to be numbered
*/
public HeaderFooter(Phrase before, boolean numbered) {
super(0, 0, 0, 0);
setBorder(TOP + BOTTOM);
setBorderWidth(1);
this.numbered = numbered;
this.before = before;
}
// methods
/**
* Checks if the HeaderFooter contains a page number.
*
* @return true if the page has to be numbered
*/
public boolean isNumbered() {
return numbered;
}
/**
* Gets the part that comes before the pageNumber.
*
* @return a Phrase
*/
public Phrase getBefore() {
return before;
}
/**
* Gets the part that comes after the pageNumber.
*
* @return a Phrase
*/
public Phrase getAfter() {
return after;
}
/**
* Sets the page number.
*
* @param pageN the new page number
*/
public void setPageNumber(int pageN) {
this.pageN = pageN;
}
/**
* Sets the alignment.
*
* @param alignment the new alignment
*/
public void setAlignment(int alignment) {
this.alignment = alignment;
}
// methods to retrieve the membervariables
/**
* Gets the Paragraph
that can be used as header or footer.
*
* @return a Paragraph
*/
public Paragraph paragraph() {
Paragraph paragraph = new Paragraph(before.getLeading());
paragraph.add(before);
if (numbered) {
paragraph.addSpecial(new Chunk(String.valueOf(pageN), before.getFont()));
}
if (after != null) {
paragraph.addSpecial(after);
}
paragraph.setAlignment(alignment);
return paragraph;
}
/**
* Gets the alignment of this HeaderFooter.
*
* @return alignment
*/
public int alignment() {
return alignment;
}
} src/core/com/lowagie/text/Image.java 100644 0 0 150040 11213370070 15034 0 ustar 0 0 /*
* $Id: Image.java 3941 2009-05-28 14:52:26Z blowagie $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.awt.Graphics2D;
import java.awt.color.ICC_Profile;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import com.lowagie.text.pdf.PRIndirectReference;
import com.lowagie.text.pdf.PdfArray;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfDictionary;
import com.lowagie.text.pdf.PdfIndirectReference;
import com.lowagie.text.pdf.PdfName;
import com.lowagie.text.pdf.PdfNumber;
import com.lowagie.text.pdf.PdfOCG;
import com.lowagie.text.pdf.PdfObject;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStream;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.RandomAccessFileOrArray;
import com.lowagie.text.pdf.codec.BmpImage;
import com.lowagie.text.pdf.codec.CCITTG4Encoder;
import com.lowagie.text.pdf.codec.GifImage;
import com.lowagie.text.pdf.codec.JBIG2Image;
import com.lowagie.text.pdf.codec.PngImage;
import com.lowagie.text.pdf.codec.TiffImage;
/**
* An Image
is the representation of a graphic element (JPEG, PNG
* or GIF) that has to be inserted into the document
*
* @see Element
* @see Rectangle
*/
public abstract class Image extends Rectangle {
// static final membervariables
/** this is a kind of image alignment. */
public static final int DEFAULT = 0;
/** this is a kind of image alignment. */
public static final int RIGHT = 2;
/** this is a kind of image alignment. */
public static final int LEFT = 0;
/** this is a kind of image alignment. */
public static final int MIDDLE = 1;
/** this is a kind of image alignment. */
public static final int TEXTWRAP = 4;
/** this is a kind of image alignment. */
public static final int UNDERLYING = 8;
/** This represents a coordinate in the transformation matrix. */
public static final int AX = 0;
/** This represents a coordinate in the transformation matrix. */
public static final int AY = 1;
/** This represents a coordinate in the transformation matrix. */
public static final int BX = 2;
/** This represents a coordinate in the transformation matrix. */
public static final int BY = 3;
/** This represents a coordinate in the transformation matrix. */
public static final int CX = 4;
/** This represents a coordinate in the transformation matrix. */
public static final int CY = 5;
/** This represents a coordinate in the transformation matrix. */
public static final int DX = 6;
/** This represents a coordinate in the transformation matrix. */
public static final int DY = 7;
/** type of image */
public static final int ORIGINAL_NONE = 0;
/** type of image */
public static final int ORIGINAL_JPEG = 1;
/** type of image */
public static final int ORIGINAL_PNG = 2;
/** type of image */
public static final int ORIGINAL_GIF = 3;
/** type of image */
public static final int ORIGINAL_BMP = 4;
/** type of image */
public static final int ORIGINAL_TIFF = 5;
/** type of image */
public static final int ORIGINAL_WMF = 6;
/** type of image */
public static final int ORIGINAL_PS = 7;
/** type of image */
public static final int ORIGINAL_JPEG2000 = 8;
/**
* type of image
* @since 2.1.5
*/
public static final int ORIGINAL_JBIG2 = 9;
// member variables
/** The image type. */
protected int type;
/** The URL of the image. */
protected URL url;
/** The raw data of the image. */
protected byte rawData[];
/** The bits per component of the raw image. It also flags a CCITT image. */
protected int bpc = 1;
/** The template to be treated as an image. */
protected PdfTemplate template[] = new PdfTemplate[1];
/** The alignment of the Image. */
protected int alignment;
/** Text that can be shown instead of the image. */
protected String alt;
/** This is the absolute X-position of the image. */
protected float absoluteX = Float.NaN;
/** This is the absolute Y-position of the image. */
protected float absoluteY = Float.NaN;
/** This is the width of the image without rotation. */
protected float plainWidth;
/** This is the width of the image without rotation. */
protected float plainHeight;
/** This is the scaled width of the image taking rotation into account. */
protected float scaledWidth;
/** This is the original height of the image taking rotation into account. */
protected float scaledHeight;
/**
* The compression level of the content streams.
* @since 2.1.3
*/
protected int compressionLevel = PdfStream.DEFAULT_COMPRESSION;
/** an iText attributed unique id for this image. */
protected Long mySerialId = getSerialId();
// image from file or URL
/**
* Constructs an Image
-object, using an url .
*
* @param url
* the URL
where the image can be found.
*/
public Image(URL url) {
super(0, 0);
this.url = url;
this.alignment = DEFAULT;
rotationRadians = 0;
}
/**
* Gets an instance of an Image.
*
* @param url
* an URL
* @return an Image
* @throws BadElementException
* @throws MalformedURLException
* @throws IOException
*/
public static Image getInstance(URL url) throws BadElementException,
MalformedURLException, IOException {
InputStream is = null;
try {
is = url.openStream();
int c1 = is.read();
int c2 = is.read();
int c3 = is.read();
int c4 = is.read();
// jbig2
int c5 = is.read();
int c6 = is.read();
int c7 = is.read();
int c8 = is.read();
is.close();
is = null;
if (c1 == 'G' && c2 == 'I' && c3 == 'F') {
GifImage gif = new GifImage(url);
Image img = gif.getImage(1);
return img;
}
if (c1 == 0xFF && c2 == 0xD8) {
return new Jpeg(url);
}
if (c1 == 0x00 && c2 == 0x00 && c3 == 0x00 && c4 == 0x0c) {
return new Jpeg2000(url);
}
if (c1 == 0xff && c2 == 0x4f && c3 == 0xff && c4 == 0x51) {
return new Jpeg2000(url);
}
if (c1 == PngImage.PNGID[0] && c2 == PngImage.PNGID[1]
&& c3 == PngImage.PNGID[2] && c4 == PngImage.PNGID[3]) {
return PngImage.getImage(url);
}
if (c1 == 0xD7 && c2 == 0xCD) {
return new ImgWMF(url);
}
if (c1 == 'B' && c2 == 'M') {
return BmpImage.getImage(url);
}
if ((c1 == 'M' && c2 == 'M' && c3 == 0 && c4 == 42)
|| (c1 == 'I' && c2 == 'I' && c3 == 42 && c4 == 0)) {
RandomAccessFileOrArray ra = null;
try {
if (url.getProtocol().equals("file")) {
String file = url.getFile();
file = Utilities.unEscapeURL(file);
ra = new RandomAccessFileOrArray(file);
} else
ra = new RandomAccessFileOrArray(url);
Image img = TiffImage.getTiffImage(ra, 1);
img.url = url;
return img;
} finally {
if (ra != null)
ra.close();
}
}
if ( c1 == 0x97 && c2 == 'J' && c3 == 'B' && c4 == '2' &&
c5 == '\r' && c6 == '\n' && c7 == 0x1a && c8 == '\n' ) {
RandomAccessFileOrArray ra = null;
try {
if (url.getProtocol().equals("file")) {
String file = url.getFile();
file = Utilities.unEscapeURL(file);
ra = new RandomAccessFileOrArray(file);
} else
ra = new RandomAccessFileOrArray(url);
Image img = JBIG2Image.getJbig2Image(ra, 1);
img.url = url;
return img;
} finally {
if (ra != null)
ra.close();
}
}
throw new IOException(url.toString()
+ " is not a recognized imageformat.");
} finally {
if (is != null) {
is.close();
}
}
}
/**
* Gets an instance of an Image.
*
* @param filename
* a filename
* @return an object of type Gif
,Jpeg
or
* Png
* @throws BadElementException
* @throws MalformedURLException
* @throws IOException
*/
public static Image getInstance(String filename)
throws BadElementException, MalformedURLException, IOException {
return getInstance(Utilities.toURL(filename));
}
/**
* gets an instance of an Image
*
* @param imgb
* raw image date
* @return an Image object
* @throws BadElementException
* @throws MalformedURLException
* @throws IOException
*/
public static Image getInstance(byte imgb[]) throws BadElementException,
MalformedURLException, IOException {
InputStream is = null;
try {
is = new java.io.ByteArrayInputStream(imgb);
int c1 = is.read();
int c2 = is.read();
int c3 = is.read();
int c4 = is.read();
is.close();
is = null;
if (c1 == 'G' && c2 == 'I' && c3 == 'F') {
GifImage gif = new GifImage(imgb);
return gif.getImage(1);
}
if (c1 == 0xFF && c2 == 0xD8) {
return new Jpeg(imgb);
}
if (c1 == 0x00 && c2 == 0x00 && c3 == 0x00 && c4 == 0x0c) {
return new Jpeg2000(imgb);
}
if (c1 == 0xff && c2 == 0x4f && c3 == 0xff && c4 == 0x51) {
return new Jpeg2000(imgb);
}
if (c1 == PngImage.PNGID[0] && c2 == PngImage.PNGID[1]
&& c3 == PngImage.PNGID[2] && c4 == PngImage.PNGID[3]) {
return PngImage.getImage(imgb);
}
if (c1 == 0xD7 && c2 == 0xCD) {
return new ImgWMF(imgb);
}
if (c1 == 'B' && c2 == 'M') {
return BmpImage.getImage(imgb);
}
if ((c1 == 'M' && c2 == 'M' && c3 == 0 && c4 == 42)
|| (c1 == 'I' && c2 == 'I' && c3 == 42 && c4 == 0)) {
RandomAccessFileOrArray ra = null;
try {
ra = new RandomAccessFileOrArray(imgb);
Image img = TiffImage.getTiffImage(ra, 1);
if (img.getOriginalData() == null)
img.setOriginalData(imgb);
return img;
} finally {
if (ra != null)
ra.close();
}
}
if ( c1 == 0x97 && c2 == 'J' && c3 == 'B' && c4 == '2' ) {
is = new java.io.ByteArrayInputStream(imgb);
is.skip(4);
int c5 = is.read();
int c6 = is.read();
int c7 = is.read();
int c8 = is.read();
if ( c5 == '\r' && c6 == '\n' && c7 == 0x1a && c8 == '\n' ) {
int file_header_flags = is.read();
int number_of_pages = -1;
if ( (file_header_flags & 0x2) == 0x2 ) {
number_of_pages = (is.read() << 24) | (is.read() << 16) | (is.read() << 8) | is.read();
}
is.close();
// a jbig2 file with a file header. the header is the only way we know here.
// embedded jbig2s don't have a header, have to create them by explicit use of Jbig2Image?
// nkerr, 2008-12-05 see also the getInstance(URL)
RandomAccessFileOrArray ra = null;
try {
ra = new RandomAccessFileOrArray(imgb);
Image img = JBIG2Image.getJbig2Image(ra, 1);
if (img.getOriginalData() == null)
img.setOriginalData(imgb);
return img;
} finally {
if (ra != null)
ra.close();
}
}
}
throw new IOException(
"The byte array is not a recognized imageformat.");
} finally {
if (is != null) {
is.close();
}
}
}
/**
* Gets an instance of an Image in raw mode.
*
* @param width
* the width of the image in pixels
* @param height
* the height of the image in pixels
* @param components
* 1,3 or 4 for GrayScale, RGB and CMYK
* @param data
* the image data
* @param bpc
* bits per component
* @return an object of type ImgRaw
* @throws BadElementException
* on error
*/
public static Image getInstance(int width, int height, int components,
int bpc, byte data[]) throws BadElementException {
return Image.getInstance(width, height, components, bpc, data, null);
}
/**
* Creates a JBIG2 Image.
* @param width the width of the image
* @param height the height of the image
* @param data the raw image data
* @param globals JBIG2 globals
* @since 2.1.5
*/
public static Image getInstance(int width, int height, byte[] data, byte[] globals) {
Image img = new ImgJBIG2(width, height, data, globals);
return img;
}
/**
* Creates an Image with CCITT G3 or G4 compression. It assumes that the
* data bytes are already compressed.
*
* @param width
* the exact width of the image
* @param height
* the exact height of the image
* @param reverseBits
* reverses the bits in data
. Bit 0 is swapped
* with bit 7 and so on
* @param typeCCITT
* the type of compression in data
. It can be
* CCITTG4, CCITTG31D, CCITTG32D
* @param parameters
* parameters associated with this stream. Possible values are
* CCITT_BLACKIS1, CCITT_ENCODEDBYTEALIGN, CCITT_ENDOFLINE and
* CCITT_ENDOFBLOCK or a combination of them
* @param data
* the image data
* @return an Image object
* @throws BadElementException
* on error
*/
public static Image getInstance(int width, int height, boolean reverseBits,
int typeCCITT, int parameters, byte[] data)
throws BadElementException {
return Image.getInstance(width, height, reverseBits, typeCCITT,
parameters, data, null);
}
/**
* Creates an Image with CCITT G3 or G4 compression. It assumes that the
* data bytes are already compressed.
*
* @param width
* the exact width of the image
* @param height
* the exact height of the image
* @param reverseBits
* reverses the bits in data
. Bit 0 is swapped
* with bit 7 and so on
* @param typeCCITT
* the type of compression in data
. It can be
* CCITTG4, CCITTG31D, CCITTG32D
* @param parameters
* parameters associated with this stream. Possible values are
* CCITT_BLACKIS1, CCITT_ENCODEDBYTEALIGN, CCITT_ENDOFLINE and
* CCITT_ENDOFBLOCK or a combination of them
* @param data
* the image data
* @param transparency
* transparency information in the Mask format of the image
* dictionary
* @return an Image object
* @throws BadElementException
* on error
*/
public static Image getInstance(int width, int height, boolean reverseBits,
int typeCCITT, int parameters, byte[] data, int transparency[])
throws BadElementException {
if (transparency != null && transparency.length != 2)
throw new BadElementException(
"Transparency length must be equal to 2 with CCITT images");
Image img = new ImgCCITT(width, height, reverseBits, typeCCITT,
parameters, data);
img.transparency = transparency;
return img;
}
/**
* Gets an instance of an Image in raw mode.
*
* @param width
* the width of the image in pixels
* @param height
* the height of the image in pixels
* @param components
* 1,3 or 4 for GrayScale, RGB and CMYK
* @param data
* the image data
* @param bpc
* bits per component
* @param transparency
* transparency information in the Mask format of the image
* dictionary
* @return an object of type ImgRaw
* @throws BadElementException
* on error
*/
public static Image getInstance(int width, int height, int components,
int bpc, byte data[], int transparency[])
throws BadElementException {
if (transparency != null && transparency.length != components * 2)
throw new BadElementException(
"Transparency length must be equal to (componentes * 2)");
if (components == 1 && bpc == 1) {
byte g4[] = CCITTG4Encoder.compress(data, width, height);
return Image.getInstance(width, height, false, Image.CCITTG4,
Image.CCITT_BLACKIS1, g4, transparency);
}
Image img = new ImgRaw(width, height, components, bpc, data);
img.transparency = transparency;
return img;
}
// images from a PdfTemplate
/**
* gets an instance of an Image
*
* @param template
* a PdfTemplate that has to be wrapped in an Image object
* @return an Image object
* @throws BadElementException
*/
public static Image getInstance(PdfTemplate template)
throws BadElementException {
return new ImgTemplate(template);
}
// images from a java.awt.Image
/**
* Gets an instance of an Image from a java.awt.Image.
*
* @param image
* the java.awt.Image
to convert
* @param color
* if different from null
the transparency pixels
* are replaced by this color
* @param forceBW
* if true
the image is treated as black and white
* @return an object of type ImgRaw
* @throws BadElementException
* on error
* @throws IOException
* on error
*/
public static Image getInstance(java.awt.Image image, java.awt.Color color,
boolean forceBW) throws BadElementException, IOException {
if(image instanceof BufferedImage){
BufferedImage bi = (BufferedImage) image;
if(bi.getType()==BufferedImage.TYPE_BYTE_BINARY) {
forceBW=true;
}
}
java.awt.image.PixelGrabber pg = new java.awt.image.PixelGrabber(image,
0, 0, -1, -1, true);
try {
pg.grabPixels();
} catch (InterruptedException e) {
throw new IOException(
"java.awt.Image Interrupted waiting for pixels!");
}
if ((pg.getStatus() & java.awt.image.ImageObserver.ABORT) != 0) {
throw new IOException("java.awt.Image fetch aborted or errored");
}
int w = pg.getWidth();
int h = pg.getHeight();
int[] pixels = (int[]) pg.getPixels();
if (forceBW) {
int byteWidth = (w / 8) + ((w & 7) != 0 ? 1 : 0);
byte[] pixelsByte = new byte[byteWidth * h];
int index = 0;
int size = h * w;
int transColor = 1;
if (color != null) {
transColor = (color.getRed() + color.getGreen()
+ color.getBlue() < 384) ? 0 : 1;
}
int transparency[] = null;
int cbyte = 0x80;
int wMarker = 0;
int currByte = 0;
if (color != null) {
for (int j = 0; j < size; j++) {
int alpha = (pixels[j] >> 24) & 0xff;
if (alpha < 250) {
if (transColor == 1)
currByte |= cbyte;
} else {
if ((pixels[j] & 0x888) != 0)
currByte |= cbyte;
}
cbyte >>= 1;
if (cbyte == 0 || wMarker + 1 >= w) {
pixelsByte[index++] = (byte) currByte;
cbyte = 0x80;
currByte = 0;
}
++wMarker;
if (wMarker >= w)
wMarker = 0;
}
} else {
for (int j = 0; j < size; j++) {
if (transparency == null) {
int alpha = (pixels[j] >> 24) & 0xff;
if (alpha == 0) {
transparency = new int[2];
/* bugfix by M.P. Liston, ASC, was: ... ? 1: 0; */
transparency[0] = transparency[1] = ((pixels[j] & 0x888) != 0) ? 0xff : 0;
}
}
if ((pixels[j] & 0x888) != 0)
currByte |= cbyte;
cbyte >>= 1;
if (cbyte == 0 || wMarker + 1 >= w) {
pixelsByte[index++] = (byte) currByte;
cbyte = 0x80;
currByte = 0;
}
++wMarker;
if (wMarker >= w)
wMarker = 0;
}
}
return Image.getInstance(w, h, 1, 1, pixelsByte, transparency);
} else {
byte[] pixelsByte = new byte[w * h * 3];
byte[] smask = null;
int index = 0;
int size = h * w;
int red = 255;
int green = 255;
int blue = 255;
if (color != null) {
red = color.getRed();
green = color.getGreen();
blue = color.getBlue();
}
int transparency[] = null;
if (color != null) {
for (int j = 0; j < size; j++) {
int alpha = (pixels[j] >> 24) & 0xff;
if (alpha < 250) {
pixelsByte[index++] = (byte) red;
pixelsByte[index++] = (byte) green;
pixelsByte[index++] = (byte) blue;
} else {
pixelsByte[index++] = (byte) ((pixels[j] >> 16) & 0xff);
pixelsByte[index++] = (byte) ((pixels[j] >> 8) & 0xff);
pixelsByte[index++] = (byte) ((pixels[j]) & 0xff);
}
}
} else {
int transparentPixel = 0;
smask = new byte[w * h];
boolean shades = false;
for (int j = 0; j < size; j++) {
byte alpha = smask[j] = (byte) ((pixels[j] >> 24) & 0xff);
/* bugfix by Chris Nokleberg */
if (!shades) {
if (alpha != 0 && alpha != -1) {
shades = true;
} else if (transparency == null) {
if (alpha == 0) {
transparentPixel = pixels[j] & 0xffffff;
transparency = new int[6];
transparency[0] = transparency[1] = (transparentPixel >> 16) & 0xff;
transparency[2] = transparency[3] = (transparentPixel >> 8) & 0xff;
transparency[4] = transparency[5] = transparentPixel & 0xff;
}
} else if ((pixels[j] & 0xffffff) != transparentPixel) {
shades = true;
}
}
pixelsByte[index++] = (byte) ((pixels[j] >> 16) & 0xff);
pixelsByte[index++] = (byte) ((pixels[j] >> 8) & 0xff);
pixelsByte[index++] = (byte) ((pixels[j]) & 0xff);
}
if (shades)
transparency = null;
else
smask = null;
}
Image img = Image.getInstance(w, h, 3, 8, pixelsByte, transparency);
if (smask != null) {
Image sm = Image.getInstance(w, h, 1, 8, smask);
try {
sm.makeMask();
img.setImageMask(sm);
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
return img;
}
}
/**
* Gets an instance of an Image from a java.awt.Image.
*
* @param image
* the java.awt.Image
to convert
* @param color
* if different from null
the transparency pixels
* are replaced by this color
* @return an object of type ImgRaw
* @throws BadElementException
* on error
* @throws IOException
* on error
*/
public static Image getInstance(java.awt.Image image, java.awt.Color color)
throws BadElementException, IOException {
return Image.getInstance(image, color, false);
}
/**
* Gets an instance of a Image from a java.awt.Image.
* The image is added as a JPEG with a user defined quality.
*
* @param writer
* the PdfWriter
object to which the image will be added
* @param awtImage
* the java.awt.Image
to convert
* @param quality
* a float value between 0 and 1
* @return an object of type PdfTemplate
* @throws BadElementException
* on error
* @throws IOException
*/
public static Image getInstance(PdfWriter writer, java.awt.Image awtImage, float quality) throws BadElementException, IOException {
return getInstance(new PdfContentByte(writer), awtImage, quality);
}
/**
* Gets an instance of a Image from a java.awt.Image.
* The image is added as a JPEG with a user defined quality.
*
* @param cb
* the PdfContentByte
object to which the image will be added
* @param awtImage
* the java.awt.Image
to convert
* @param quality
* a float value between 0 and 1
* @return an object of type PdfTemplate
* @throws BadElementException
* on error
* @throws IOException
*/
public static Image getInstance(PdfContentByte cb, java.awt.Image awtImage, float quality) throws BadElementException, IOException {
java.awt.image.PixelGrabber pg = new java.awt.image.PixelGrabber(awtImage,
0, 0, -1, -1, true);
try {
pg.grabPixels();
} catch (InterruptedException e) {
throw new IOException(
"java.awt.Image Interrupted waiting for pixels!");
}
if ((pg.getStatus() & java.awt.image.ImageObserver.ABORT) != 0) {
throw new IOException("java.awt.Image fetch aborted or errored");
}
int w = pg.getWidth();
int h = pg.getHeight();
PdfTemplate tp = cb.createTemplate(w, h);
Graphics2D g2d = tp.createGraphics(w, h, true, quality);
g2d.drawImage(awtImage, 0, 0, null);
g2d.dispose();
return getInstance(tp);
}
// image from indirect reference
/**
* Holds value of property directReference.
* An image is embedded into a PDF as an Image XObject.
* This object is referenced by a PdfIndirectReference object.
*/
private PdfIndirectReference directReference;
/**
* Getter for property directReference.
* @return Value of property directReference.
*/
public PdfIndirectReference getDirectReference() {
return this.directReference;
}
/**
* Setter for property directReference.
* @param directReference New value of property directReference.
*/
public void setDirectReference(PdfIndirectReference directReference) {
this.directReference = directReference;
}
/**
* Reuses an existing image.
* @param ref the reference to the image dictionary
* @throws BadElementException on error
* @return the image
*/
public static Image getInstance(PRIndirectReference ref) throws BadElementException {
PdfDictionary dic = (PdfDictionary)PdfReader.getPdfObjectRelease(ref);
int width = ((PdfNumber)PdfReader.getPdfObjectRelease(dic.get(PdfName.WIDTH))).intValue();
int height = ((PdfNumber)PdfReader.getPdfObjectRelease(dic.get(PdfName.HEIGHT))).intValue();
Image imask = null;
PdfObject obj = dic.get(PdfName.SMASK);
if (obj != null && obj.isIndirect()) {
imask = getInstance((PRIndirectReference)obj);
}
else {
obj = dic.get(PdfName.MASK);
if (obj != null && obj.isIndirect()) {
PdfObject obj2 = PdfReader.getPdfObjectRelease(obj);
if (obj2 instanceof PdfDictionary)
imask = getInstance((PRIndirectReference)obj);
}
}
Image img = new ImgRaw(width, height, 1, 1, null);
img.imageMask = imask;
img.directReference = ref;
return img;
}
// copy constructor
/**
* Constructs an Image
-object, using an url .
*
* @param image
* another Image object.
*/
protected Image(Image image) {
super(image);
this.type = image.type;
this.url = image.url;
this.rawData = image.rawData;
this.bpc = image.bpc;
this.template = image.template;
this.alignment = image.alignment;
this.alt = image.alt;
this.absoluteX = image.absoluteX;
this.absoluteY = image.absoluteY;
this.plainWidth = image.plainWidth;
this.plainHeight = image.plainHeight;
this.scaledWidth = image.scaledWidth;
this.scaledHeight = image.scaledHeight;
this.mySerialId = image.mySerialId;
this.directReference = image.directReference;
this.rotationRadians = image.rotationRadians;
this.initialRotation = image.initialRotation;
this.indentationLeft = image.indentationLeft;
this.indentationRight = image.indentationRight;
this.spacingBefore = image.spacingBefore;
this.spacingAfter = image.spacingAfter;
this.widthPercentage = image.widthPercentage;
this.annotation = image.annotation;
this.layer = image.layer;
this.interpolation = image.interpolation;
this.originalType = image.originalType;
this.originalData = image.originalData;
this.deflated = image.deflated;
this.dpiX = image.dpiX;
this.dpiY = image.dpiY;
this.XYRatio = image.XYRatio;
this.colorspace = image.colorspace;
this.invert = image.invert;
this.profile = image.profile;
this.additional = image.additional;
this.mask = image.mask;
this.imageMask = image.imageMask;
this.smask = image.smask;
this.transparency = image.transparency;
}
/**
* gets an instance of an Image
*
* @param image
* an Image object
* @return a new Image object
*/
public static Image getInstance(Image image) {
if (image == null)
return null;
try {
Class cs = image.getClass();
Constructor constructor = cs
.getDeclaredConstructor(new Class[] { Image.class });
return (Image) constructor.newInstance(new Object[] { image });
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
// implementation of the Element interface
/**
* Returns the type.
*
* @return a type
*/
public int type() {
return type;
}
/**
* @see com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return true;
}
// checking the type of Image
/**
* Returns true
if the image is a Jpeg
* -object.
*
* @return a boolean
*/
public boolean isJpeg() {
return type == JPEG;
}
/**
* Returns true
if the image is a ImgRaw
* -object.
*
* @return a boolean
*/
public boolean isImgRaw() {
return type == IMGRAW;
}
/**
* Returns true
if the image is an ImgTemplate
* -object.
*
* @return a boolean
*/
public boolean isImgTemplate() {
return type == IMGTEMPLATE;
}
// getters and setters
/**
* Gets the String
-representation of the reference to the
* image.
*
* @return a String
*/
public URL getUrl() {
return url;
}
/**
* Sets the url of the image
*
* @param url
* the url of the image
*/
public void setUrl(URL url) {
this.url = url;
}
/**
* Gets the raw data for the image.
* RawImage
*
.
*
* @return the raw data
*/
public byte[] getRawData() {
return rawData;
}
/**
* Gets the bpc for the image.
* RawImage
*
.
*
* @return a bpc value
*/
public int getBpc() {
return bpc;
}
/**
* Gets the template to be used as an image.
* ImgTemplate
*
.
*
* @return the template
*/
public PdfTemplate getTemplateData() {
return template[0];
}
/**
* Sets data from a PdfTemplate
*
* @param template
* the template with the content
*/
public void setTemplateData(PdfTemplate template) {
this.template[0] = template;
}
/**
* Gets the alignment for the image.
*
* @return a value
*/
public int getAlignment() {
return alignment;
}
/**
* Sets the alignment for the image.
*
* @param alignment
* the alignment
*/
public void setAlignment(int alignment) {
this.alignment = alignment;
}
/**
* Gets the alternative text for the image.
*
* @return a String
*/
public String getAlt() {
return alt;
}
/**
* Sets the alternative information for the image.
*
* @param alt
* the alternative information
*/
public void setAlt(String alt) {
this.alt = alt;
}
/**
* Sets the absolute position of the Image
.
*
* @param absoluteX
* @param absoluteY
*/
public void setAbsolutePosition(float absoluteX, float absoluteY) {
this.absoluteX = absoluteX;
this.absoluteY = absoluteY;
}
/**
* Checks if the Images
has to be added at an absolute X
* position.
*
* @return a boolean
*/
public boolean hasAbsoluteX() {
return !Float.isNaN(absoluteX);
}
/**
* Returns the absolute X position.
*
* @return a position
*/
public float getAbsoluteX() {
return absoluteX;
}
/**
* Checks if the Images
has to be added at an absolute
* position.
*
* @return a boolean
*/
public boolean hasAbsoluteY() {
return !Float.isNaN(absoluteY);
}
/**
* Returns the absolute Y position.
*
* @return a position
*/
public float getAbsoluteY() {
return absoluteY;
}
// width and height
/**
* Gets the scaled width of the image.
*
* @return a value
*/
public float getScaledWidth() {
return scaledWidth;
}
/**
* Gets the scaled height of the image.
*
* @return a value
*/
public float getScaledHeight() {
return scaledHeight;
}
/**
* Gets the plain width of the image.
*
* @return a value
*/
public float getPlainWidth() {
return plainWidth;
}
/**
* Gets the plain height of the image.
*
* @return a value
*/
public float getPlainHeight() {
return plainHeight;
}
/**
* Scale the image to an absolute width and an absolute height.
*
* @param newWidth
* the new width
* @param newHeight
* the new height
*/
public void scaleAbsolute(float newWidth, float newHeight) {
plainWidth = newWidth;
plainHeight = newHeight;
float[] matrix = matrix();
scaledWidth = matrix[DX] - matrix[CX];
scaledHeight = matrix[DY] - matrix[CY];
setWidthPercentage(0);
}
/**
* Scale the image to an absolute width.
*
* @param newWidth
* the new width
*/
public void scaleAbsoluteWidth(float newWidth) {
plainWidth = newWidth;
float[] matrix = matrix();
scaledWidth = matrix[DX] - matrix[CX];
scaledHeight = matrix[DY] - matrix[CY];
setWidthPercentage(0);
}
/**
* Scale the image to an absolute height.
*
* @param newHeight
* the new height
*/
public void scaleAbsoluteHeight(float newHeight) {
plainHeight = newHeight;
float[] matrix = matrix();
scaledWidth = matrix[DX] - matrix[CX];
scaledHeight = matrix[DY] - matrix[CY];
setWidthPercentage(0);
}
/**
* Scale the image to a certain percentage.
*
* @param percent
* the scaling percentage
*/
public void scalePercent(float percent) {
scalePercent(percent, percent);
}
/**
* Scale the width and height of an image to a certain percentage.
*
* @param percentX
* the scaling percentage of the width
* @param percentY
* the scaling percentage of the height
*/
public void scalePercent(float percentX, float percentY) {
plainWidth = (getWidth() * percentX) / 100f;
plainHeight = (getHeight() * percentY) / 100f;
float[] matrix = matrix();
scaledWidth = matrix[DX] - matrix[CX];
scaledHeight = matrix[DY] - matrix[CY];
setWidthPercentage(0);
}
/**
* Scales the image so that it fits a certain width and height.
*
* @param fitWidth
* the width to fit
* @param fitHeight
* the height to fit
*/
public void scaleToFit(float fitWidth, float fitHeight) {
scalePercent(100);
float percentX = (fitWidth * 100) / getScaledWidth();
float percentY = (fitHeight * 100) / getScaledHeight();
scalePercent(percentX < percentY ? percentX : percentY);
setWidthPercentage(0);
}
/**
* Returns the transformation matrix of the image.
*
* @return an array [AX, AY, BX, BY, CX, CY, DX, DY]
*/
public float[] matrix() {
float[] matrix = new float[8];
float cosX = (float) Math.cos(rotationRadians);
float sinX = (float) Math.sin(rotationRadians);
matrix[AX] = plainWidth * cosX;
matrix[AY] = plainWidth * sinX;
matrix[BX] = (-plainHeight) * sinX;
matrix[BY] = plainHeight * cosX;
if (rotationRadians < Math.PI / 2f) {
matrix[CX] = matrix[BX];
matrix[CY] = 0;
matrix[DX] = matrix[AX];
matrix[DY] = matrix[AY] + matrix[BY];
} else if (rotationRadians < Math.PI) {
matrix[CX] = matrix[AX] + matrix[BX];
matrix[CY] = matrix[BY];
matrix[DX] = 0;
matrix[DY] = matrix[AY];
} else if (rotationRadians < Math.PI * 1.5f) {
matrix[CX] = matrix[AX];
matrix[CY] = matrix[AY] + matrix[BY];
matrix[DX] = matrix[BX];
matrix[DY] = 0;
} else {
matrix[CX] = 0;
matrix[CY] = matrix[AY];
matrix[DX] = matrix[AX] + matrix[BX];
matrix[DY] = matrix[BY];
}
return matrix;
}
// serial stamping
/** a static that is used for attributing a unique id to each image. */
static long serialId = 0;
/** Creates a new serial id. */
static protected synchronized Long getSerialId() {
++serialId;
return new Long(serialId);
}
/**
* Returns a serial id for the Image (reuse the same image more than once)
*
* @return a serialId
*/
public Long getMySerialId() {
return mySerialId;
}
// rotation, note that the superclass also has a rotation value.
/** This is the rotation of the image in radians. */
protected float rotationRadians;
/** Holds value of property initialRotation. */
private float initialRotation;
/**
* Gets the current image rotation in radians.
* @return the current image rotation in radians
*/
public float getImageRotation() {
double d = 2.0 * Math.PI;
float rot = (float) ((rotationRadians - initialRotation) % d);
if (rot < 0) {
rot += d;
}
return rot;
}
/**
* Sets the rotation of the image in radians.
*
* @param r
* rotation in radians
*/
public void setRotation(float r) {
double d = 2.0 * Math.PI;
rotationRadians = (float) ((r + initialRotation) % d);
if (rotationRadians < 0) {
rotationRadians += d;
}
float[] matrix = matrix();
scaledWidth = matrix[DX] - matrix[CX];
scaledHeight = matrix[DY] - matrix[CY];
}
/**
* Sets the rotation of the image in degrees.
*
* @param deg
* rotation in degrees
*/
public void setRotationDegrees(float deg) {
double d = Math.PI;
setRotation(deg / 180 * (float) d);
}
/**
* Getter for property initialRotation.
* @return Value of property initialRotation.
*/
public float getInitialRotation() {
return this.initialRotation;
}
/**
* Some image formats, like TIFF may present the images rotated that have
* to be compensated.
* @param initialRotation New value of property initialRotation.
*/
public void setInitialRotation(float initialRotation) {
float old_rot = rotationRadians - this.initialRotation;
this.initialRotation = initialRotation;
setRotation(old_rot);
}
// indentations
/** the indentation to the left. */
protected float indentationLeft = 0;
/** the indentation to the right. */
protected float indentationRight = 0;
/** The spacing before the image. */
protected float spacingBefore;
/** The spacing after the image. */
protected float spacingAfter;
/**
* Gets the left indentation.
*
* @return the left indentation
*/
public float getIndentationLeft() {
return indentationLeft;
}
/**
* Sets the left indentation.
*
* @param f
*/
public void setIndentationLeft(float f) {
indentationLeft = f;
}
/**
* Gets the right indentation.
*
* @return the right indentation
*/
public float getIndentationRight() {
return indentationRight;
}
/**
* Sets the right indentation.
*
* @param f
*/
public void setIndentationRight(float f) {
indentationRight = f;
}
/**
* Gets the spacing before this image.
*
* @return the spacing
*/
public float getSpacingBefore() {
return spacingBefore;
}
/**
* Sets the spacing before this image.
*
* @param spacing
* the new spacing
*/
public void setSpacingBefore(float spacing) {
this.spacingBefore = spacing;
}
/**
* Gets the spacing before this image.
*
* @return the spacing
*/
public float getSpacingAfter() {
return spacingAfter;
}
/**
* Sets the spacing after this image.
*
* @param spacing
* the new spacing
*/
public void setSpacingAfter(float spacing) {
this.spacingAfter = spacing;
}
// widthpercentage (for the moment only used in ColumnText)
/**
* Holds value of property widthPercentage.
*/
private float widthPercentage = 100;
/**
* Getter for property widthPercentage.
*
* @return Value of property widthPercentage.
*/
public float getWidthPercentage() {
return this.widthPercentage;
}
/**
* Setter for property widthPercentage.
*
* @param widthPercentage
* New value of property widthPercentage.
*/
public void setWidthPercentage(float widthPercentage) {
this.widthPercentage = widthPercentage;
}
// annotation
/** if the annotation is not null the image will be clickable. */
protected Annotation annotation = null;
/**
* Sets the annotation of this Image.
*
* @param annotation
* the annotation
*/
public void setAnnotation(Annotation annotation) {
this.annotation = annotation;
}
/**
* Gets the annotation.
*
* @return the annotation that is linked to this image
*/
public Annotation getAnnotation() {
return annotation;
}
// Optional Content
/** Optional Content layer to which we want this Image to belong. */
protected PdfOCG layer;
/**
* Gets the layer this image belongs to.
*
* @return the layer this image belongs to or null
for no
* layer defined
*/
public PdfOCG getLayer() {
return layer;
}
/**
* Sets the layer this image belongs to.
*
* @param layer
* the layer this image belongs to
*/
public void setLayer(PdfOCG layer) {
this.layer = layer;
}
// interpolation
/** Holds value of property interpolation. */
protected boolean interpolation;
/**
* Getter for property interpolation.
*
* @return Value of property interpolation.
*/
public boolean isInterpolation() {
return interpolation;
}
/**
* Sets the image interpolation. Image interpolation attempts to produce a
* smooth transition between adjacent sample values.
*
* @param interpolation
* New value of property interpolation.
*/
public void setInterpolation(boolean interpolation) {
this.interpolation = interpolation;
}
// original type and data
/** Holds value of property originalType. */
protected int originalType = ORIGINAL_NONE;
/** Holds value of property originalData. */
protected byte[] originalData;
/**
* Getter for property originalType.
*
* @return Value of property originalType.
*
*/
public int getOriginalType() {
return this.originalType;
}
/**
* Setter for property originalType.
*
* @param originalType
* New value of property originalType.
*
*/
public void setOriginalType(int originalType) {
this.originalType = originalType;
}
/**
* Getter for property originalData.
*
* @return Value of property originalData.
*
*/
public byte[] getOriginalData() {
return this.originalData;
}
/**
* Setter for property originalData.
*
* @param originalData
* New value of property originalData.
*
*/
public void setOriginalData(byte[] originalData) {
this.originalData = originalData;
}
// the following values are only set for specific types of images.
/** Holds value of property deflated. */
protected boolean deflated = false;
/**
* Getter for property deflated.
*
* @return Value of property deflated.
*
*/
public boolean isDeflated() {
return this.deflated;
}
/**
* Setter for property deflated.
*
* @param deflated
* New value of property deflated.
*/
public void setDeflated(boolean deflated) {
this.deflated = deflated;
}
// DPI info
/** Holds value of property dpiX. */
protected int dpiX = 0;
/** Holds value of property dpiY. */
protected int dpiY = 0;
/**
* Gets the dots-per-inch in the X direction. Returns 0 if not available.
*
* @return the dots-per-inch in the X direction
*/
public int getDpiX() {
return dpiX;
}
/**
* Gets the dots-per-inch in the Y direction. Returns 0 if not available.
*
* @return the dots-per-inch in the Y direction
*/
public int getDpiY() {
return dpiY;
}
/**
* Sets the dots per inch value
*
* @param dpiX
* dpi for x coordinates
* @param dpiY
* dpi for y coordinates
*/
public void setDpi(int dpiX, int dpiY) {
this.dpiX = dpiX;
this.dpiY = dpiY;
}
// XY Ratio
/** Holds value of property XYRatio. */
private float XYRatio = 0;
/**
* Gets the X/Y pixel dimensionless aspect ratio.
*
* @return the X/Y pixel dimensionless aspect ratio
*/
public float getXYRatio() {
return this.XYRatio;
}
/**
* Sets the X/Y pixel dimensionless aspect ratio.
*
* @param XYRatio
* the X/Y pixel dimensionless aspect ratio
*/
public void setXYRatio(float XYRatio) {
this.XYRatio = XYRatio;
}
// color, colorspaces and transparency
/** this is the colorspace of a jpeg-image. */
protected int colorspace = -1;
/**
* Gets the colorspace for the image.
* Jpeg
.
*
* @return a colorspace value
*/
public int getColorspace() {
return colorspace;
}
/** Image color inversion */
protected boolean invert = false;
/**
* Getter for the inverted value
*
* @return true if the image is inverted
*/
public boolean isInverted() {
return invert;
}
/**
* Sets inverted true or false
*
* @param invert
* true or false
*/
public void setInverted(boolean invert) {
this.invert = invert;
}
/** ICC Profile attached */
protected ICC_Profile profile = null;
/**
* Tags this image with an ICC profile.
*
* @param profile
* the profile
*/
public void tagICC(ICC_Profile profile) {
this.profile = profile;
}
/**
* Checks is the image has an ICC profile.
*
* @return the ICC profile or null
*/
public boolean hasICCProfile() {
return (this.profile != null);
}
/**
* Gets the images ICC profile.
*
* @return the ICC profile
*/
public ICC_Profile getICCProfile() {
return profile;
}
/** a dictionary with additional information */
private PdfDictionary additional = null;
/**
* Getter for the dictionary with additional information.
*
* @return a PdfDictionary with additional information.
*/
public PdfDictionary getAdditional() {
return this.additional;
}
/**
* Sets the /Colorspace key.
*
* @param additional
* a PdfDictionary with additional information.
*/
public void setAdditional(PdfDictionary additional) {
this.additional = additional;
}
/**
* Replaces CalRGB and CalGray colorspaces with DeviceRGB and DeviceGray.
*/
public void simplifyColorspace() {
if (additional == null)
return;
PdfArray value = additional.getAsArray(PdfName.COLORSPACE);
if (value == null)
return;
PdfObject cs = simplifyColorspace(value);
PdfObject newValue;
if (cs.isName())
newValue = cs;
else {
newValue = value;
PdfName first = value.getAsName(0);
if (PdfName.INDEXED.equals(first)) {
if (value.size() >= 2) {
PdfArray second = value.getAsArray(1);
if (second != null) {
value.set(1, simplifyColorspace(second));
}
}
}
}
additional.put(PdfName.COLORSPACE, newValue);
}
/**
* Gets a PDF Name from an array or returns the object that was passed.
*/
private PdfObject simplifyColorspace(PdfArray obj) {
if (obj == null)
return obj;
PdfName first = obj.getAsName(0);
if (PdfName.CALGRAY.equals(first))
return PdfName.DEVICEGRAY;
else if (PdfName.CALRGB.equals(first))
return PdfName.DEVICERGB;
else
return obj;
}
/** Is this image a mask? */
protected boolean mask = false;
/** The image that serves as a mask for this image. */
protected Image imageMask;
/** Holds value of property smask. */
private boolean smask;
/**
* Returns true
if this Image
is a mask.
*
* @return true
if this Image
is a mask
*/
public boolean isMask() {
return mask;
}
/**
* Make this Image
a mask.
*
* @throws DocumentException
* if this Image
can not be a mask
*/
public void makeMask() throws DocumentException {
if (!isMaskCandidate())
throw new DocumentException("This image can not be an image mask.");
mask = true;
}
/**
* Returns true
if this Image
has the
* requisites to be a mask.
*
* @return true
if this Image
can be a mask
*/
public boolean isMaskCandidate() {
if (type == IMGRAW) {
if (bpc > 0xff)
return true;
}
return colorspace == 1;
}
/**
* Gets the explicit masking.
*
* @return the explicit masking
*/
public Image getImageMask() {
return imageMask;
}
/**
* Sets the explicit masking.
*
* @param mask
* the mask to be applied
* @throws DocumentException
* on error
*/
public void setImageMask(Image mask) throws DocumentException {
if (this.mask)
throw new DocumentException(
"An image mask cannot contain another image mask.");
if (!mask.mask)
throw new DocumentException(
"The image mask is not a mask. Did you do makeMask()?");
imageMask = mask;
smask = (mask.bpc > 1 && mask.bpc <= 8);
}
/**
* Getter for property smask.
*
* @return Value of property smask.
*
*/
public boolean isSmask() {
return this.smask;
}
/**
* Setter for property smask.
*
* @param smask
* New value of property smask.
*/
public void setSmask(boolean smask) {
this.smask = smask;
}
/** this is the transparency information of the raw image */
protected int transparency[];
/**
* Returns the transparency.
*
* @return the transparency values
*/
public int[] getTransparency() {
return transparency;
}
/**
* Sets the transparency values
*
* @param transparency
* the transparency values
*/
public void setTransparency(int transparency[]) {
this.transparency = transparency;
}
/**
* Returns the compression level used for images written as a compressed stream.
* @return the compression level (0 = best speed, 9 = best compression, -1 is default)
* @since 2.1.3
*/
public int getCompressionLevel() {
return compressionLevel;
}
/**
* Sets the compression level to be used if the image is written as a compressed stream.
* @param compressionLevel a value between 0 (best speed) and 9 (best compression)
* @since 2.1.3
*/
public void setCompressionLevel(int compressionLevel) {
if (compressionLevel < PdfStream.NO_COMPRESSION || compressionLevel > PdfStream.BEST_COMPRESSION)
this.compressionLevel = PdfStream.DEFAULT_COMPRESSION;
else
this.compressionLevel = compressionLevel;
}
} src/core/com/lowagie/text/ImgCCITT.java 100644 0 0 10232 11012562273 15300 0 ustar 0 0 /*
* $Id: ImgCCITT.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 2000, 2001, 2002 by Paulo Soares.
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import com.lowagie.text.pdf.codec.TIFFFaxDecoder;
import java.net.URL;
/**
* CCITT Image data that has to be inserted into the document
*
* @see Element
* @see Image
*
* @author Paulo Soares
*/
public class ImgCCITT extends Image {
ImgCCITT(Image image) {
super(image);
}
/** Creates an Image with CCITT compression.
*
* @param width the exact width of the image
* @param height the exact height of the image
* @param reverseBits reverses the bits in data
.
* Bit 0 is swapped with bit 7 and so on.
* @param typeCCITT the type of compression in data
. It can be
* CCITTG4, CCITTG31D, CCITTG32D
* @param parameters parameters associated with this stream. Possible values are
* CCITT_BLACKIS1, CCITT_ENCODEDBYTEALIGN, CCITT_ENDOFLINE and CCITT_ENDOFBLOCK or a
* combination of them
* @param data the image data
* @throws BadElementException on error
*/
public ImgCCITT(int width, int height, boolean reverseBits, int typeCCITT, int parameters, byte[] data) throws BadElementException{
super((URL)null);
if (typeCCITT != CCITTG4 && typeCCITT != CCITTG3_1D && typeCCITT != CCITTG3_2D)
throw new BadElementException("The CCITT compression type must be CCITTG4, CCITTG3_1D or CCITTG3_2D");
if (reverseBits)
TIFFFaxDecoder.reverseBits(data);
type = IMGRAW;
scaledHeight = height;
setTop(scaledHeight);
scaledWidth = width;
setRight(scaledWidth);
colorspace = parameters;
bpc = typeCCITT;
rawData = data;
plainWidth = getWidth();
plainHeight = getHeight();
}
} src/core/com/lowagie/text/ImgJBIG2.java 100644 0 0 10102 11215636056 15231 0 ustar 0 0 /*
* $Id: ImgJBIG2.java 3962 2009-06-10 11:43:19Z psoares33 $
*
* Copyright 2009 by Nigel Kerr.
*
* 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-2009 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000-2009 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;
import java.net.URL;
import java.security.MessageDigest;
/**
* Support for JBIG2 images.
* @since 2.1.5
*/
public class ImgJBIG2 extends Image {
/** JBIG2 globals */
private byte[] global;
/** A unique hash */
private byte[] globalHash;
/**
* Copy contstructor.
* @param image another Image
*/
ImgJBIG2(Image image) {
super(image);
}
/**
* Empty constructor.
*/
public ImgJBIG2() {
super((Image) null);
}
/**
* Actual constructor for ImgJBIG2 images.
* @param width the width of the image
* @param height the height of the image
* @param data the raw image data
* @param globals JBIG2 globals
*/
public ImgJBIG2(int width, int height, byte[] data, byte[] globals) {
super((URL) null);
type = JBIG2;
originalType = ORIGINAL_JBIG2;
scaledHeight = height;
setTop(scaledHeight);
scaledWidth = width;
setRight(scaledWidth);
bpc = 1;
colorspace = 1;
rawData = data;
plainWidth = getWidth();
plainHeight = getHeight();
if ( globals != null ) {
this.global = globals;
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
md.update(this.global);
this.globalHash = md.digest();
} catch (Exception e) {
//ignore
}
}
}
/**
* Getter for the JBIG2 global data.
* @return an array of bytes
*/
public byte[] getGlobalBytes() {
return this.global;
}
/**
* Getter for the unique hash.
* @return an array of bytes
*/
public byte[] getGlobalHash() {
return this.globalHash;
}
}
src/core/com/lowagie/text/ImgRaw.java 100644 0 0 7357 11012562273 15161 0 ustar 0 0 /*
* $Id: ImgRaw.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 2000, 2001, 2002 by Paulo Soares.
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.net.URL;
/**
* Raw Image data that has to be inserted into the document
*
* @see Element
* @see Image
*
* @author Paulo Soares
*/
public class ImgRaw extends Image {
ImgRaw(Image image) {
super(image);
}
/** Creates an Image in raw mode.
*
* @param width the exact width of the image
* @param height the exact height of the image
* @param components 1,3 or 4 for GrayScale, RGB and CMYK
* @param bpc bits per component. Must be 1,2,4 or 8
* @param data the image data
* @throws BadElementException on error
*/
public ImgRaw(int width, int height, int components, int bpc, byte[] data) throws BadElementException{
super((URL)null);
type = IMGRAW;
scaledHeight = height;
setTop(scaledHeight);
scaledWidth = width;
setRight(scaledWidth);
if (components != 1 && components != 3 && components != 4)
throw new BadElementException("Components must be 1, 3, or 4.");
if (bpc != 1 && bpc != 2 && bpc != 4 && bpc != 8)
throw new BadElementException("Bits-per-component must be 1, 2, 4, or 8.");
colorspace = components;
this.bpc = bpc;
rawData = data;
plainWidth = getWidth();
plainHeight = getHeight();
}
} src/core/com/lowagie/text/ImgTemplate.java 100644 0 0 7103 11036112746 16172 0 ustar 0 0 /*
* $Id: ImgTemplate.java 3517 2008-06-29 10:37:16Z blowagie $
*
* Copyright 2000, 2001, 2002 by Paulo Soares.
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.net.URL;
import com.lowagie.text.pdf.PdfTemplate;
/**
* PdfTemplate that has to be inserted into the document
*
* @see Element
* @see Image
*
* @author Paulo Soares
*/
public class ImgTemplate extends Image {
ImgTemplate(Image image) {
super(image);
}
/** Creates an Image from a PdfTemplate.
*
* @param template the PdfTemplate
* @throws BadElementException on error
*/
public ImgTemplate(PdfTemplate template) throws BadElementException{
super((URL)null);
if (template == null)
throw new BadElementException("The template can not be null.");
if (template.getType() == PdfTemplate.TYPE_PATTERN)
throw new BadElementException("A pattern can not be used as a template to create an image.");
type = IMGTEMPLATE;
scaledHeight = template.getHeight();
setTop(scaledHeight);
scaledWidth = template.getWidth();
setRight(scaledWidth);
setTemplateData(template);
plainWidth = getWidth();
plainHeight = getHeight();
}
} src/core/com/lowagie/text/ImgWMF.java 100644 0 0 14753 11012562273 15077 0 ustar 0 0 /*
* $Id: ImgWMF.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 1999, 2000, 2001, 2002 by Paulo Soares.
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.codec.wmf.InputMeta;
import com.lowagie.text.pdf.codec.wmf.MetaDo;
/**
* An ImgWMF
is the representation of a windows metafile
* that has to be inserted into the document
*
* @see Element
* @see Image
*/
public class ImgWMF extends Image {
// Constructors
ImgWMF(Image image) {
super(image);
}
/**
* Constructs an ImgWMF
-object, using an url.
*
* @param url the URL
where the image can be found
* @throws BadElementException on error
* @throws IOException on error
*/
public ImgWMF(URL url) throws BadElementException, IOException {
super(url);
processParameters();
}
/**
* Constructs an ImgWMF
-object, using a filename.
*
* @param filename a String
-representation of the file that contains the image.
* @throws BadElementException on error
* @throws MalformedURLException on error
* @throws IOException on error
*/
public ImgWMF(String filename) throws BadElementException, MalformedURLException, IOException {
this(Utilities.toURL(filename));
}
/**
* Constructs an ImgWMF
-object from memory.
*
* @param img the memory image
* @throws BadElementException on error
* @throws IOException on error
*/
public ImgWMF(byte[] img) throws BadElementException, IOException {
super((URL)null);
rawData = img;
originalData = img;
processParameters();
}
/**
* This method checks if the image is a valid WMF and processes some parameters.
* @throws BadElementException
* @throws IOException
*/
private void processParameters() throws BadElementException, IOException {
type = IMGTEMPLATE;
originalType = ORIGINAL_WMF;
InputStream is = null;
try {
String errorID;
if (rawData == null){
is = url.openStream();
errorID = url.toString();
}
else{
is = new java.io.ByteArrayInputStream(rawData);
errorID = "Byte array";
}
InputMeta in = new InputMeta(is);
if (in.readInt() != 0x9AC6CDD7) {
throw new BadElementException(errorID + " is not a valid placeable windows metafile.");
}
in.readWord();
int left = in.readShort();
int top = in.readShort();
int right = in.readShort();
int bottom = in.readShort();
int inch = in.readWord();
dpiX = 72;
dpiY = 72;
scaledHeight = (float)(bottom - top) / inch * 72f;
setTop(scaledHeight);
scaledWidth = (float)(right - left) / inch * 72f;
setRight(scaledWidth);
}
finally {
if (is != null) {
is.close();
}
plainWidth = getWidth();
plainHeight = getHeight();
}
}
/** Reads the WMF into a template.
* @param template the template to read to
* @throws IOException on error
* @throws DocumentException on error
*/
public void readWMF(PdfTemplate template) throws IOException, DocumentException {
setTemplateData(template);
template.setWidth(getWidth());
template.setHeight(getHeight());
InputStream is = null;
try {
if (rawData == null){
is = url.openStream();
}
else{
is = new java.io.ByteArrayInputStream(rawData);
}
MetaDo meta = new MetaDo(is, template);
meta.readAll();
}
finally {
if (is != null) {
is.close();
}
}
}
}
src/core/com/lowagie/text/Jpeg.java 100644 0 0 31241 11215636056 14673 0 ustar 0 0 /*
* $Id: Jpeg.java 3970 2009-06-16 08:09:54Z blowagie $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.awt.color.ICC_Profile;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
* An Jpeg
is the representation of a graphic element (JPEG)
* that has to be inserted into the document
*
* @see Element
* @see Image
*/
public class Jpeg extends Image {
// public static final membervariables
/** This is a type of marker. */
public static final int NOT_A_MARKER = -1;
/** This is a type of marker. */
public static final int VALID_MARKER = 0;
/** Acceptable Jpeg markers. */
public static final int[] VALID_MARKERS = {0xC0, 0xC1, 0xC2};
/** This is a type of marker. */
public static final int UNSUPPORTED_MARKER = 1;
/** Unsupported Jpeg markers. */
public static final int[] UNSUPPORTED_MARKERS = {0xC3, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF};
/** This is a type of marker. */
public static final int NOPARAM_MARKER = 2;
/** Jpeg markers without additional parameters. */
public static final int[] NOPARAM_MARKERS = {0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0x01};
/** Marker value */
public static final int M_APP0 = 0xE0;
/** Marker value */
public static final int M_APP2 = 0xE2;
/** Marker value */
public static final int M_APPE = 0xEE;
/** sequence that is used in all Jpeg files */
public static final byte JFIF_ID[] = {0x4A, 0x46, 0x49, 0x46, 0x00};
private byte[][] icc;
// Constructors
Jpeg(Image image) {
super(image);
}
/**
* Constructs a Jpeg
-object, using an url.
*
* @param url the URL
where the image can be found
* @throws BadElementException
* @throws IOException
*/
public Jpeg(URL url) throws BadElementException, IOException {
super(url);
processParameters();
}
/**
* Constructs a Jpeg
-object from memory.
*
* @param img the memory image
* @throws BadElementException
* @throws IOException
*/
public Jpeg(byte[] img) throws BadElementException, IOException {
super((URL)null);
rawData = img;
originalData = img;
processParameters();
}
/**
* Constructs a Jpeg
-object from memory.
*
* @param img the memory image.
* @param width the width you want the image to have
* @param height the height you want the image to have
* @throws BadElementException
* @throws IOException
*/
public Jpeg(byte[] img, float width, float height) throws BadElementException, IOException {
this(img);
scaledWidth = width;
scaledHeight = height;
}
// private static methods
/**
* Reads a short from the InputStream
.
*
* @param is the InputStream
* @return an int
* @throws IOException
*/
private static final int getShort(InputStream is) throws IOException {
return (is.read() << 8) + is.read();
}
/**
* Returns a type of marker.
*
* @param marker an int
* @return a type: VALID_MARKERJpeg2000
is the representation of a graphic element (JPEG)
* that has to be inserted into the document
*
* @see Element
* @see Image
*/
public class Jpeg2000 extends Image {
// public static final membervariables
public static final int JP2_JP = 0x6a502020;
public static final int JP2_IHDR = 0x69686472;
public static final int JPIP_JPIP = 0x6a706970;
public static final int JP2_FTYP = 0x66747970;
public static final int JP2_JP2H = 0x6a703268;
public static final int JP2_COLR = 0x636f6c72;
public static final int JP2_JP2C = 0x6a703263;
public static final int JP2_URL = 0x75726c20;
public static final int JP2_DBTL = 0x6474626c;
public static final int JP2_BPCC = 0x62706363;
public static final int JP2_JP2 = 0x6a703220;
InputStream inp;
int boxLength;
int boxType;
// Constructors
Jpeg2000(Image image) {
super(image);
}
/**
* Constructs a Jpeg2000
-object, using an url.
*
* @param url the URL
where the image can be found
* @throws BadElementException
* @throws IOException
*/
public Jpeg2000(URL url) throws BadElementException, IOException {
super(url);
processParameters();
}
/**
* Constructs a Jpeg2000
-object from memory.
*
* @param img the memory image
* @throws BadElementException
* @throws IOException
*/
public Jpeg2000(byte[] img) throws BadElementException, IOException {
super((URL)null);
rawData = img;
originalData = img;
processParameters();
}
/**
* Constructs a Jpeg2000
-object from memory.
*
* @param img the memory image.
* @param width the width you want the image to have
* @param height the height you want the image to have
* @throws BadElementException
* @throws IOException
*/
public Jpeg2000(byte[] img, float width, float height) throws BadElementException, IOException {
this(img);
scaledWidth = width;
scaledHeight = height;
}
private int cio_read(int n) throws IOException {
int v = 0;
for (int i = n - 1; i >= 0; i--) {
v += inp.read() << (i << 3);
}
return v;
}
public void jp2_read_boxhdr() throws IOException {
boxLength = cio_read(4);
boxType = cio_read(4);
if (boxLength == 1) {
if (cio_read(4) != 0) {
throw new IOException("Cannot handle box sizes higher than 2^32");
}
boxLength = cio_read(4);
if (boxLength == 0)
throw new IOException("Unsupported box size == 0");
}
else if (boxLength == 0) {
throw new IOException("Unsupported box size == 0");
}
}
/**
* This method checks if the image is a valid JPEG and processes some parameters.
* @throws IOException
*/
private void processParameters() throws IOException {
type = JPEG2000;
originalType = ORIGINAL_JPEG2000;
inp = null;
try {
String errorID;
if (rawData == null){
inp = url.openStream();
errorID = url.toString();
}
else{
inp = new java.io.ByteArrayInputStream(rawData);
errorID = "Byte array";
}
boxLength = cio_read(4);
if (boxLength == 0x0000000c) {
boxType = cio_read(4);
if (JP2_JP != boxType) {
throw new IOException("Expected JP Marker");
}
if (0x0d0a870a != cio_read(4)) {
throw new IOException("Error with JP Marker");
}
jp2_read_boxhdr();
if (JP2_FTYP != boxType) {
throw new IOException("Expected FTYP Marker");
}
Utilities.skip(inp, boxLength - 8);
jp2_read_boxhdr();
do {
if (JP2_JP2H != boxType) {
if (boxType == JP2_JP2C) {
throw new IOException("Expected JP2H Marker");
}
Utilities.skip(inp, boxLength - 8);
jp2_read_boxhdr();
}
} while(JP2_JP2H != boxType);
jp2_read_boxhdr();
if (JP2_IHDR != boxType) {
throw new IOException("Expected IHDR Marker");
}
scaledHeight = cio_read(4);
setTop(scaledHeight);
scaledWidth = cio_read(4);
setRight(scaledWidth);
bpc = -1;
}
else if (boxLength == 0xff4fff51) {
Utilities.skip(inp, 4);
int x1 = cio_read(4);
int y1 = cio_read(4);
int x0 = cio_read(4);
int y0 = cio_read(4);
Utilities.skip(inp, 16);
colorspace = cio_read(2);
bpc = 8;
scaledHeight = y1 - y0;
setTop(scaledHeight);
scaledWidth = x1 - x0;
setRight(scaledWidth);
}
else {
throw new IOException("Not a valid Jpeg2000 file");
}
}
finally {
if (inp != null) {
try{inp.close();}catch(Exception e){}
inp = null;
}
}
plainWidth = getWidth();
plainHeight = getHeight();
}
}
src/core/com/lowagie/text/LargeElement.java 100644 0 0 7305 11036112746 16332 0 ustar 0 0 /*
* $Id: LargeElement.java 3514 2008-06-27 09:26:36Z blowagie $
*
* Copyright 2007 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
/**
* Interface implemented by Element objects that can potentially consume
* a lot of memory. Objects implementing the LargeElement interface can
* be added to a Document more than once. If you have invoked setComplete(false),
* they will be added partially and the content that was added will be
* removed until you've invoked setComplete(true);
* @since iText 2.0.8
*/
public interface LargeElement extends Element {
/**
* If you invoke setComplete(false), you indicate that the content
* of the object isn't complete yet; it can be added to the document
* partially, but more will follow. If you invoke setComplete(true),
* you indicate that you won't add any more data to the object.
* @since iText 2.0.8
* @param complete false if you'll be adding more data after
* adding the object to the document.
*/
public void setComplete(boolean complete);
/**
* Indicates if the element is complete or not.
* @since iText 2.0.8
* @return indicates if the element is complete according to the user.
*/
public boolean isComplete();
/**
* Flushes the content that has been added.
*/
public void flushContent();
}
src/core/com/lowagie/text/List.java 100644 0 0 41136 11012562273 14717 0 ustar 0 0 /*
* $Id: List.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.util.ArrayList;
import java.util.Iterator;
import com.lowagie.text.factories.RomanAlphabetFactory;
/**
* A List
contains several ListItem
s.
*
*
* The result of this code looks like this:
*
* List list = new List(true, 20);
* list.add(new ListItem("First line"));
* list.add(new ListItem("The second line is longer to see what happens once the end of the line is reached. Will it start on a new line?"));
* list.add(new ListItem("Third line"));
*
*
*
* Example 2:
*
*
* The result of this code looks like this:
*
* List overview = new List(false, 10);
* overview.add(new ListItem("This is an item"));
* overview.add("This is another item");
*
*
*
* @see Element
* @see ListItem
*/
public class List implements TextElementArray {
// constants
/** a possible value for the numbered parameter */
public static final boolean ORDERED = true;
/** a possible value for the numbered parameter */
public static final boolean UNORDERED = false;
/** a possible value for the lettered parameter */
public static final boolean NUMERICAL = false;
/** a possible value for the lettered parameter */
public static final boolean ALPHABETICAL = true;
/** a possible value for the lettered parameter */
public static final boolean UPPERCASE = false;
/** a possible value for the lettered parameter */
public static final boolean LOWERCASE = true;
// member variables
/** This is the ArrayList
containing the different ListItem
s. */
protected ArrayList list = new ArrayList();
/** Indicates if the list has to be numbered. */
protected boolean numbered = false;
/** Indicates if the listsymbols are numerical or alphabetical. */
protected boolean lettered = false;
/** Indicates if the listsymbols are lowercase or uppercase. */
protected boolean lowercase = false;
/** Indicates if the indentation has to be set automatically. */
protected boolean autoindent = false;
/** Indicates if the indentation of all the items has to be aligned. */
protected boolean alignindent = false;
/** This variable indicates the first number of a numbered list. */
protected int first = 1;
/** This is the listsymbol of a list that is not numbered. */
protected Chunk symbol = new Chunk("- ");
/**
* In case you are using numbered/lettered lists, this String is added before the number/letter.
* @since iText 2.1.1
*/
protected String preSymbol = "";
/**
* In case you are using numbered/lettered lists, this String is added after the number/letter.
* @since iText 2.1.1
*/
protected String postSymbol = ". ";
/** The indentation of this list on the left side. */
protected float indentationLeft = 0;
/** The indentation of this list on the right side. */
protected float indentationRight = 0;
/** The indentation of the listitems. */
protected float symbolIndent = 0;
// constructors
/** Constructs a List
. */
public List() {
this(false, false);
}
/**
* Constructs a List
with a specific symbol indentation.
* @param symbolIndent the symbol indentation
* @since iText 2.0.8
*/
public List(float symbolIndent) {
this.symbolIndent = symbolIndent;
}
/**
* Constructs a List
.
* @param numbered a boolean
*/
public List(boolean numbered) {
this(numbered, false);
}
/**
* Constructs a List
.
* @param numbered a boolean
* @param lettered has the list to be 'numbered' with letters
*/
public List(boolean numbered, boolean lettered) {
this.numbered = numbered;
this.lettered = lettered;
this.autoindent = true;
this.alignindent = true;
}
/**
* Constructs a List
.
* ElementListener
.
*
* @param listener an ElementListener
* @return true
if the element was processed successfully
*/
public boolean process(ElementListener listener) {
try {
for (Iterator i = list.iterator(); i.hasNext(); ) {
listener.add((Element) i.next());
}
return true;
}
catch(DocumentException de) {
return false;
}
}
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return Element.LIST;
}
/**
* Gets all the chunks in this element.
*
* @return an ArrayList
*/
public ArrayList getChunks() {
ArrayList tmp = new ArrayList();
for (Iterator i = list.iterator(); i.hasNext(); ) {
tmp.addAll(((Element) i.next()).getChunks());
}
return tmp;
}
// methods to set the membervariables
/**
* Adds an Object
to the List
.
*
* @param o the object to add.
* @return true if adding the object succeeded
*/
public boolean add(Object o) {
if (o instanceof ListItem) {
ListItem item = (ListItem) o;
if (numbered || lettered) {
Chunk chunk = new Chunk(preSymbol, symbol.getFont());
int index = first + list.size();
if ( lettered )
chunk.append(RomanAlphabetFactory.getString(index, lowercase));
else
chunk.append(String.valueOf(index));
chunk.append(postSymbol);
item.setListSymbol(chunk);
}
else {
item.setListSymbol(symbol);
}
item.setIndentationLeft(symbolIndent, autoindent);
item.setIndentationRight(0);
return list.add(item);
}
else if (o instanceof List) {
List nested = (List) o;
nested.setIndentationLeft(nested.getIndentationLeft() + symbolIndent);
first--;
return list.add(nested);
}
else if (o instanceof String) {
return this.add(new ListItem((String) o));
}
return false;
}
// extra methods
/** Makes sure all the items in the list have the same indentation. */
public void normalizeIndentation() {
float max = 0;
Element o;
for (Iterator i = list.iterator(); i.hasNext(); ) {
o = (Element)i.next();
if (o instanceof ListItem) {
max = Math.max(max, ((ListItem)o).getIndentationLeft());
}
}
for (Iterator i = list.iterator(); i.hasNext(); ) {
o = (Element)i.next();
if (o instanceof ListItem) {
((ListItem)o).setIndentationLeft(max);
}
}
}
// setters
/**
* @param numbered the numbered to set
*/
public void setNumbered(boolean numbered) {
this.numbered = numbered;
}
/**
* @param lettered the lettered to set
*/
public void setLettered(boolean lettered) {
this.lettered = lettered;
}
/**
* @param uppercase the uppercase to set
*/
public void setLowercase(boolean uppercase) {
this.lowercase = uppercase;
}
/**
* @param autoindent the autoindent to set
*/
public void setAutoindent(boolean autoindent) {
this.autoindent = autoindent;
}
/**
* @param alignindent the alignindent to set
*/
public void setAlignindent(boolean alignindent) {
this.alignindent = alignindent;
}
/**
* Sets the number that has to come first in the list.
*
* @param first a number
*/
public void setFirst(int first) {
this.first = first;
}
/**
* Sets the listsymbol.
*
* @param symbol a Chunk
*/
public void setListSymbol(Chunk symbol) {
this.symbol = symbol;
}
/**
* Sets the listsymbol.
* setListSymbol(Chunk symbol)
.
*
* @param symbol a String
*/
public void setListSymbol(String symbol) {
this.symbol = new Chunk(symbol);
}
/**
* Sets the indentation of this paragraph on the left side.
*
* @param indentation the new indentation
*/
public void setIndentationLeft(float indentation) {
this.indentationLeft = indentation;
}
/**
* Sets the indentation of this paragraph on the right side.
*
* @param indentation the new indentation
*/
public void setIndentationRight(float indentation) {
this.indentationRight = indentation;
}
/**
* @param symbolIndent the symbolIndent to set
*/
public void setSymbolIndent(float symbolIndent) {
this.symbolIndent = symbolIndent;
}
// methods to retrieve information
/**
* Gets all the items in the list.
*
* @return an ArrayList
containing ListItem
s.
*/
public ArrayList getItems() {
return list;
}
/**
* Gets the size of the list.
*
* @return a size
*/
public int size() {
return list.size();
}
/**
* Returns true
if the list is empty.
*
* @return true
if the list is empty
*/
public boolean isEmpty() {
return list.isEmpty();
}
/**
* Gets the leading of the first listitem.
*
* @return a leading
*/
public float getTotalLeading() {
if (list.size() < 1) {
return -1;
}
ListItem item = (ListItem) list.get(0);
return item.getTotalLeading();
}
// getters
/**
* Checks if the list is numbered.
* @return true
if the list is numbered, false
otherwise.
*/
public boolean isNumbered() {
return numbered;
}
/**
* Checks if the list is lettered.
* @return true
if the list is lettered, false
otherwise.
*/
public boolean isLettered() {
return lettered;
}
/**
* Checks if the list lettering is lowercase.
* @return true
if it is lowercase, false
otherwise.
*/
public boolean isLowercase() {
return lowercase;
}
/**
* Checks if the indentation of list items is done automatically.
* @return the autoindent
*/
public boolean isAutoindent() {
return autoindent;
}
/**
* Checks if all the listitems should be aligned.
* @return the alignindent
*/
public boolean isAlignindent() {
return alignindent;
}
/**
* Gets the first number .
* @return a number
*/
public int getFirst() {
return first;
}
/**
* Gets the Chunk containing the symbol.
* @return a Chunk with a symbol
*/
public Chunk getSymbol() {
return symbol;
}
/**
* Gets the indentation of this paragraph on the left side.
* @return the indentation
*/
public float getIndentationLeft() {
return indentationLeft;
}
/**
* Gets the indentation of this paragraph on the right side.
* @return the indentation
*/
public float getIndentationRight() {
return indentationRight;
}
/**
* Gets the symbol indentation.
* @return the symbol indentation
*/
public float getSymbolIndent() {
return symbolIndent;
}
/**
* @see com.lowagie.text.Element#isContent()
* @since iText 2.0.8
*/
public boolean isContent() {
return true;
}
/**
* @see com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return true;
}
/**
* Returns the String that is after a number or letter in the list symbol.
* @return the String that is after a number or letter in the list symbol
* @since iText 2.1.1
*/
public String getPostSymbol() {
return postSymbol;
}
/**
* Sets the String that has to be added after a number or letter in the list symbol.
* @since iText 2.1.1
* @param postSymbol the String that has to be added after a number or letter in the list symbol.
*/
public void setPostSymbol(String postSymbol) {
this.postSymbol = postSymbol;
}
/**
* Returns the String that is before a number or letter in the list symbol.
* @return the String that is before a number or letter in the list symbol
* @since iText 2.1.1
*/
public String getPreSymbol() {
return preSymbol;
}
/**
* Sets the String that has to be added before a number or letter in the list symbol.
* @since iText 2.1.1
* @param preSymbol the String that has to be added before a number or letter in the list symbol.
*/
public void setPreSymbol(String preSymbol) {
this.preSymbol = preSymbol;
}
} src/core/com/lowagie/text/ListItem.java 100644 0 0 16241 11012562273 15535 0 ustar 0 0 /*
* $Id: ListItem.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
/**
* A ListItem
is a Paragraph
* that can be added to a List
.
*
*
* The result of this code looks like this:
*
* List list = new List(true, 20);
* list.add(new ListItem("First line"));
* list.add(new ListItem("The second line is longer to see what happens once the end of the line is reached. Will it start on a new line?"));
* list.add(new ListItem("Third line"));
*
*
*
* Example 2:
*
*
* The result of this code looks like this:
*
* List overview = new List(false, 10);
* overview.add(new ListItem("This is an item"));
* overview.add("This is another item");
*
*
*
* @see Element
* @see List
* @see Paragraph
*/
public class ListItem extends Paragraph {
// constants
private static final long serialVersionUID = 1970670787169329006L;
// member variables
/** this is the symbol that will precede the listitem. */
private Chunk symbol;
// constructors
/**
* Constructs a ListItem
.
*/
public ListItem() {
super();
}
/**
* Constructs a ListItem
with a certain leading.
*
* @param leading the leading
*/
public ListItem(float leading) {
super(leading);
}
/**
* Constructs a ListItem
with a certain Chunk
.
*
* @param chunk a Chunk
*/
public ListItem(Chunk chunk) {
super(chunk);
}
/**
* Constructs a ListItem
with a certain String
.
*
* @param string a String
*/
public ListItem(String string) {
super(string);
}
/**
* Constructs a ListItem
with a certain String
* and a certain Font
.
*
* @param string a String
* @param font a String
*/
public ListItem(String string, Font font) {
super(string, font);
}
/**
* Constructs a ListItem
with a certain Chunk
* and a certain leading.
*
* @param leading the leading
* @param chunk a Chunk
*/
public ListItem(float leading, Chunk chunk) {
super(leading, chunk);
}
/**
* Constructs a ListItem
with a certain String
* and a certain leading.
*
* @param leading the leading
* @param string a String
*/
public ListItem(float leading, String string) {
super(leading, string);
}
/**
* Constructs a ListItem
with a certain leading, String
* and Font
.
*
* @param leading the leading
* @param string a String
* @param font a Font
*/
public ListItem(float leading, String string, Font font) {
super(leading, string, font);
}
/**
* Constructs a ListItem
with a certain Phrase
.
*
* @param phrase a Phrase
*/
public ListItem(Phrase phrase) {
super(phrase);
}
// implementation of the Element-methods
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return Element.LISTITEM;
}
// methods
/**
* Sets the listsymbol.
*
* @param symbol a Chunk
*/
public void setListSymbol(Chunk symbol) {
if (this.symbol == null) {
this.symbol = symbol;
if (this.symbol.getFont().isStandardFont()) {
this.symbol.setFont(font);
}
}
}
/**
* Sets the indentation of this paragraph on the left side.
*
* @param indentation the new indentation
*/
public void setIndentationLeft(float indentation, boolean autoindent) {
if (autoindent) {
setIndentationLeft(getListSymbol().getWidthPoint());
}
else {
setIndentationLeft(indentation);
}
}
// methods to retrieve information
/**
* Returns the listsymbol.
*
* @return a Chunk
*/
public Chunk getListSymbol() {
return symbol;
}
}
src/core/com/lowagie/text/MPL-1.1.txt 100644 0 0 62233 11000354131 14615 0 ustar 0 0 MOZILLA PUBLIC LICENSE
Version 1.1
---------------
1. Definitions.
1.0.1. "Commercial Use" means distribution or otherwise making the
Covered Code available to a third party.
1.1. "Contributor" means each entity that creates or contributes to
the creation of Modifications.
1.2. "Contributor Version" means the combination of the Original
Code, prior Modifications used by a Contributor, and the Modifications
made by that particular Contributor.
1.3. "Covered Code" means the Original Code or Modifications or the
combination of the Original Code and Modifications, in each case
including portions thereof.
1.4. "Electronic Distribution Mechanism" means a mechanism generally
accepted in the software development community for the electronic
transfer of data.
1.5. "Executable" means Covered Code in any form other than Source
Code.
1.6. "Initial Developer" means the individual or entity identified
as the Initial Developer in the Source Code notice required by Exhibit
A.
1.7. "Larger Work" means a work which combines Covered Code or
portions thereof with code not governed by the terms of this License.
1.8. "License" means this document.
1.8.1. "Licensable" means having the right to grant, to the maximum
extent possible, whether at the time of the initial grant or
subsequently acquired, any and all of the rights conveyed herein.
1.9. "Modifications" means any addition to or deletion from the
substance or structure of either the Original Code or any previous
Modifications. When Covered Code is released as a series of files, a
Modification is:
A. Any addition to or deletion from the contents of a file
containing Original Code or previous Modifications.
B. Any new file that contains any part of the Original Code or
previous Modifications.
1.10. "Original Code" means Source Code of computer software code
which is described in the Source Code notice required by Exhibit A as
Original Code, and which, at the time of its release under this
License is not already Covered Code governed by this License.
1.10.1. "Patent Claims" means any patent claim(s), now owned or
hereafter acquired, including without limitation, method, process,
and apparatus claims, in any patent Licensable by grantor.
1.11. "Source Code" means the preferred form of the Covered Code for
making modifications to it, including all modules it contains, plus
any associated interface definition files, scripts used to control
compilation and installation of an Executable, or source code
differential comparisons against either the Original Code or another
well known, available Covered Code of the Contributor's choice. The
Source Code can be in a compressed or archival form, provided the
appropriate decompression or de-archiving software is widely available
for no charge.
1.12. "You" (or "Your") means an individual or a legal entity
exercising rights under, and complying with all of the terms of, this
License or a future version of this License issued under Section 6.1.
For legal entities, "You" includes any entity which controls, is
controlled by, or is under common control with You. For purposes of
this definition, "control" means (a) the power, direct or indirect,
to cause the direction or management of such entity, whether by
contract or otherwise, or (b) ownership of more than fifty percent
(50%) of the outstanding shares or beneficial ownership of such
entity.
2. Source Code License.
2.1. The Initial Developer Grant.
The Initial Developer hereby grants You a world-wide, royalty-free,
non-exclusive license, subject to third party intellectual property
claims:
(a) under intellectual property rights (other than patent or
trademark) Licensable by Initial Developer to use, reproduce,
modify, display, perform, sublicense and distribute the Original
Code (or portions thereof) with or without Modifications, and/or
as part of a Larger Work; and
(b) under Patents Claims infringed by the making, using or
selling of Original Code, to make, have made, use, practice,
sell, and offer for sale, and/or otherwise dispose of the
Original Code (or portions thereof).
(c) the licenses granted in this Section 2.1(a) and (b) are
effective on the date Initial Developer first distributes
Original Code under the terms of this License.
(d) Notwithstanding Section 2.1(b) above, no patent license is
granted: 1) for code that You delete from the Original Code; 2)
separate from the Original Code; or 3) for infringements caused
by: i) the modification of the Original Code or ii) the
combination of the Original Code with other software or devices.
2.2. Contributor Grant.
Subject to third party intellectual property claims, each Contributor
hereby grants You a world-wide, royalty-free, non-exclusive license
(a) under intellectual property rights (other than patent or
trademark) Licensable by Contributor, to use, reproduce, modify,
display, perform, sublicense and distribute the Modifications
created by such Contributor (or portions thereof) either on an
unmodified basis, with other Modifications, as Covered Code
and/or as part of a Larger Work; and
(b) under Patent Claims infringed by the making, using, or
selling of Modifications made by that Contributor either alone
and/or in combination with its Contributor Version (or portions
of such combination), to make, use, sell, offer for sale, have
made, and/or otherwise dispose of: 1) Modifications made by that
Contributor (or portions thereof); and 2) the combination of
Modifications made by that Contributor with its Contributor
Version (or portions of such combination).
(c) the licenses granted in Sections 2.2(a) and 2.2(b) are
effective on the date Contributor first makes Commercial Use of
the Covered Code.
(d) Notwithstanding Section 2.2(b) above, no patent license is
granted: 1) for any code that Contributor has deleted from the
Contributor Version; 2) separate from the Contributor Version;
3) for infringements caused by: i) third party modifications of
Contributor Version or ii) the combination of Modifications made
by that Contributor with other software (except as part of the
Contributor Version) or other devices; or 4) under Patent Claims
infringed by Covered Code in the absence of Modifications made by
that Contributor.
3. Distribution Obligations.
3.1. Application of License.
The Modifications which You create or to which You contribute are
governed by the terms of this License, including without limitation
Section 2.2. The Source Code version of Covered Code may be
distributed only under the terms of this License or a future version
of this License released under Section 6.1, and You must include a
copy of this License with every copy of the Source Code You
distribute. You may not offer or impose any terms on any Source Code
version that alters or restricts the applicable version of this
License or the recipients' rights hereunder. However, You may include
an additional document offering the additional rights described in
Section 3.5.
3.2. Availability of Source Code.
Any Modification which You create or to which You contribute must be
made available in Source Code form under the terms of this License
either on the same media as an Executable version or via an accepted
Electronic Distribution Mechanism to anyone to whom you made an
Executable version available; and if made available via Electronic
Distribution Mechanism, must remain available for at least twelve (12)
months after the date it initially became available, or at least six
(6) months after a subsequent version of that particular Modification
has been made available to such recipients. You are responsible for
ensuring that the Source Code version remains available even if the
Electronic Distribution Mechanism is maintained by a third party.
3.3. Description of Modifications.
You must cause all Covered Code to which You contribute to contain a
file documenting the changes You made to create that Covered Code and
the date of any change. You must include a prominent statement that
the Modification is derived, directly or indirectly, from Original
Code provided by the Initial Developer and including the name of the
Initial Developer in (a) the Source Code, and (b) in any notice in an
Executable version or related documentation in which You describe the
origin or ownership of the Covered Code.
3.4. Intellectual Property Matters
(a) Third Party Claims.
If Contributor has knowledge that a license under a third party's
intellectual property rights is required to exercise the rights
granted by such Contributor under Sections 2.1 or 2.2,
Contributor must include a text file with the Source Code
distribution titled "LEGAL" which describes the claim and the
party making the claim in sufficient detail that a recipient will
know whom to contact. If Contributor obtains such knowledge after
the Modification is made available as described in Section 3.2,
Contributor shall promptly modify the LEGAL file in all copies
Contributor makes available thereafter and shall take other steps
(such as notifying appropriate mailing lists or newsgroups)
reasonably calculated to inform those who received the Covered
Code that new knowledge has been obtained.
(b) Contributor APIs.
If Contributor's Modifications include an application programming
interface and Contributor has knowledge of patent licenses which
are reasonably necessary to implement that API, Contributor must
also include this information in the LEGAL file.
(c) Representations.
Contributor represents that, except as disclosed pursuant to
Section 3.4(a) above, Contributor believes that Contributor's
Modifications are Contributor's original creation(s) and/or
Contributor has sufficient rights to grant the rights conveyed by
this License.
3.5. Required Notices.
You must duplicate the notice in Exhibit A in each file of the Source
Code. If it is not possible to put such notice in a particular Source
Code file due to its structure, then You must include such notice in a
location (such as a relevant directory) where a user would be likely
to look for such a notice. If You created one or more Modification(s)
You may add your name as a Contributor to the notice described in
Exhibit A. You must also duplicate this License in any documentation
for the Source Code where You describe recipients' rights or ownership
rights relating to Covered Code. You may choose to offer, and to
charge a fee for, warranty, support, indemnity or liability
obligations to one or more recipients of Covered Code. However, You
may do so only on Your own behalf, and not on behalf of the Initial
Developer or any Contributor. You must make it absolutely clear than
any such warranty, support, indemnity or liability obligation is
offered by You alone, and You hereby agree to indemnify the Initial
Developer and every Contributor for any liability incurred by the
Initial Developer or such Contributor as a result of warranty,
support, indemnity or liability terms You offer.
3.6. Distribution of Executable Versions.
You may distribute Covered Code in Executable form only if the
requirements of Section 3.1-3.5 have been met for that Covered Code,
and if You include a notice stating that the Source Code version of
the Covered Code is available under the terms of this License,
including a description of how and where You have fulfilled the
obligations of Section 3.2. The notice must be conspicuously included
in any notice in an Executable version, related documentation or
collateral in which You describe recipients' rights relating to the
Covered Code. You may distribute the Executable version of Covered
Code or ownership rights under a license of Your choice, which may
contain terms different from this License, provided that You are in
compliance with the terms of this License and that the license for the
Executable version does not attempt to limit or alter the recipient's
rights in the Source Code version from the rights set forth in this
License. If You distribute the Executable version under a different
license You must make it absolutely clear that any terms which differ
from this License are offered by You alone, not by the Initial
Developer or any Contributor. You hereby agree to indemnify the
Initial Developer and every Contributor for any liability incurred by
the Initial Developer or such Contributor as a result of any such
terms You offer.
3.7. Larger Works.
You may create a Larger Work by combining Covered Code with other code
not governed by the terms of this License and distribute the Larger
Work as a single product. In such a case, You must make sure the
requirements of this License are fulfilled for the Covered Code.
4. Inability to Comply Due to Statute or Regulation.
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Code due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description
must be included in the LEGAL file described in Section 3.4 and must
be included with all distributions of the Source Code. Except to the
extent prohibited by statute or regulation, such description must be
sufficiently detailed for a recipient of ordinary skill to be able to
understand it.
5. Application of this License.
This License applies to code to which the Initial Developer has
attached the notice in Exhibit A and to related Covered Code.
6. Versions of the License.
6.1. New Versions.
Netscape Communications Corporation ("Netscape") may publish revised
and/or new versions of the License from time to time. Each version
will be given a distinguishing version number.
6.2. Effect of New Versions.
Once Covered Code has been published under a particular version of the
License, You may always continue to use it under the terms of that
version. You may also choose to use such Covered Code under the terms
of any subsequent version of the License published by Netscape. No one
other than Netscape has the right to modify the terms applicable to
Covered Code created under this License.
6.3. Derivative Works.
If You create or use a modified version of this License (which you may
only do in order to apply it to code which is not already Covered Code
governed by this License), You must (a) rename Your license so that
the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape",
"MPL", "NPL" or any confusingly similar phrase do not appear in your
license (except to note that your license differs from this License)
and (b) otherwise make it clear that Your version of the license
contains terms which differ from the Mozilla Public License and
Netscape Public License. (Filling in the name of the Initial
Developer, Original Code or Contributor in the notice described in
Exhibit A shall not of themselves be deemed to be modifications of
this License.)
7. DISCLAIMER OF WARRANTY.
COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF
DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING.
THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE
IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT,
YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE
COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER
OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF
ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
8. TERMINATION.
8.1. This License and the rights granted hereunder will terminate
automatically if You fail to comply with terms herein and fail to cure
such breach within 30 days of becoming aware of the breach. All
sublicenses to the Covered Code which are properly granted shall
survive any termination of this License. Provisions which, by their
nature, must remain in effect beyond the termination of this License
shall survive.
8.2. If You initiate litigation by asserting a patent infringement
claim (excluding declatory judgment actions) against Initial Developer
or a Contributor (the Initial Developer or Contributor against whom
You file such action is referred to as "Participant") alleging that:
(a) such Participant's Contributor Version directly or indirectly
infringes any patent, then any and all rights granted by such
Participant to You under Sections 2.1 and/or 2.2 of this License
shall, upon 60 days notice from Participant terminate prospectively,
unless if within 60 days after receipt of notice You either: (i)
agree in writing to pay Participant a mutually agreeable reasonable
royalty for Your past and future use of Modifications made by such
Participant, or (ii) withdraw Your litigation claim with respect to
the Contributor Version against such Participant. If within 60 days
of notice, a reasonable royalty and payment arrangement are not
mutually agreed upon in writing by the parties or the litigation claim
is not withdrawn, the rights granted by Participant to You under
Sections 2.1 and/or 2.2 automatically terminate at the expiration of
the 60 day notice period specified above.
(b) any software, hardware, or device, other than such Participant's
Contributor Version, directly or indirectly infringes any patent, then
any rights granted to You by such Participant under Sections 2.1(b)
and 2.2(b) are revoked effective as of the date You first made, used,
sold, distributed, or had made, Modifications made by that
Participant.
8.3. If You assert a patent infringement claim against Participant
alleging that such Participant's Contributor Version directly or
indirectly infringes any patent where such claim is resolved (such as
by license or settlement) prior to the initiation of patent
infringement litigation, then the reasonable value of the licenses
granted by such Participant under Sections 2.1 or 2.2 shall be taken
into account in determining the amount or value of any payment or
license.
8.4. In the event of termination under Sections 8.1 or 8.2 above,
all end user license agreements (excluding distributors and resellers)
which have been validly granted by You or any distributor hereunder
prior to termination shall survive termination.
9. LIMITATION OF LIABILITY.
UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
(INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL
DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE,
OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR
ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY
CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL,
WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF
LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY
RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW
PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE
EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO
THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
10. U.S. GOVERNMENT END USERS.
The Covered Code is a "commercial item," as that term is defined in
48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer
software" and "commercial computer software documentation," as such
terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48
C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995),
all U.S. Government End Users acquire Covered Code with only those
rights set forth herein.
11. MISCELLANEOUS.
This License represents the complete agreement concerning subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. This License shall be governed by
California law provisions (except to the extent applicable law, if
any, provides otherwise), excluding its conflict-of-law provisions.
With respect to disputes in which at least one party is a citizen of,
or an entity chartered or registered to do business in the United
States of America, any litigation relating to this License shall be
subject to the jurisdiction of the Federal Courts of the Northern
District of California, with venue lying in Santa Clara County,
California, with the losing party responsible for costs, including
without limitation, court costs and reasonable attorneys' fees and
expenses. The application of the United Nations Convention on
Contracts for the International Sale of Goods is expressly excluded.
Any law or regulation which provides that the language of a contract
shall be construed against the drafter shall not apply to this
License.
12. RESPONSIBILITY FOR CLAIMS.
As between Initial Developer and the Contributors, each party is
responsible for claims and damages arising, directly or indirectly,
out of its utilization of rights under this License and You agree to
work with Initial Developer and Contributors to distribute such
responsibility on an equitable basis. Nothing herein is intended or
shall be deemed to constitute any admission of liability.
13. MULTIPLE-LICENSED CODE.
Initial Developer may designate portions of the Covered Code as
"Multiple-Licensed". "Multiple-Licensed" means that the Initial
Developer permits you to utilize portions of the Covered Code under
Your choice of the NPL or the alternative licenses, if any, specified
by the Initial Developer in the file described in Exhibit A.
EXHIBIT A -Mozilla Public License.
``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 ______________________________________.
The Initial Developer of the Original Code is ________________________.
Portions created by ______________________ are Copyright (C) ______
_______________________. All Rights Reserved.
Contributor(s): ______________________________________.
Alternatively, the contents of this file may be used under the terms
of the _____ license (the "[___] License"), in which case the
provisions of [______] License are applicable instead of those
above. If you wish to allow use of your version of this file only
under the terms of the [____] 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 [___] License. If you do not delete
the provisions above, a recipient may use your version of this file
under either the MPL or the [___] License."
[NOTE: The text of this Exhibit A may differ slightly from the text of
the notices in the Source Code files of the Original Code. You should
use the text of this Exhibit A rather than the text found in the
Original Code Source Code for Your Modifications.]
src/core/com/lowagie/text/MarkedObject.java 100644 0 0 11217 11012562273 16333 0 ustar 0 0 /*
* $Id: MarkedObject.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 2007 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-2007 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000-2007 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;
import java.util.ArrayList;
import java.util.Properties;
/**
* Wrapper that allows to add properties to 'basic building block' objects.
* Before iText 1.5 every 'basic building block' implemented the MarkupAttributes interface.
* By setting attributes, you could add markup to the corresponding XML and/or HTML tag.
* This functionality was hardly used by anyone, so it was removed, and replaced by
* the MarkedObject functionality.
*/
public class MarkedObject implements Element {
/** The element that is wrapped in a MarkedObject. */
protected Element element;
/** Contains extra markupAttributes */
protected Properties markupAttributes = new Properties();
/**
* This constructor is for internal use only.
*/
protected MarkedObject() {
element = null;
}
/**
* Creates a MarkedObject.
*/
public MarkedObject(Element element) {
this.element = element;
}
/**
* Gets all the chunks in this element.
*
* @return an ArrayList
*/
public ArrayList getChunks() {
return element.getChunks();
}
/**
* Processes the element by adding it (or the different parts) to an
* ElementListener
.
*
* @param listener an ElementListener
* @return true
if the element was processed successfully
*/
public boolean process(ElementListener listener) {
try {
return listener.add(element);
}
catch(DocumentException de) {
return false;
}
}
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return MARKED;
}
/**
* @see com.lowagie.text.Element#isContent()
* @since iText 2.0.8
*/
public boolean isContent() {
return true;
}
/**
* @see com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return true;
}
/**
* Getter for the markup attributes.
* @return the markupAttributes
*/
public Properties getMarkupAttributes() {
return markupAttributes;
}
/**
* Adds one markup attribute.
*/
public void setMarkupAttribute(String key, String value) {
markupAttributes.setProperty(key, value);
}
} src/core/com/lowagie/text/MarkedSection.java 100644 0 0 23220 11012562273 16526 0 ustar 0 0 /*
* $Id: MarkedSection.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 2007 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-2007 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000-2007 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;
import java.util.Collection;
import java.util.Iterator;
/**
* Wrapper that allows to add properties to a Chapter/Section object.
* Before iText 1.5 every 'basic building block' implemented the MarkupAttributes interface.
* By setting attributes, you could add markup to the corresponding XML and/or HTML tag.
* This functionality was hardly used by anyone, so it was removed, and replaced by
* the MarkedObject functionality.
*/
public class MarkedSection extends MarkedObject {
/** This is the title of this section. */
protected MarkedObject title = null;
/**
* Creates a MarkedObject with a Section or Chapter object.
* @param section the marked section
*/
public MarkedSection(Section section) {
super();
if (section.title != null) {
title = new MarkedObject(section.title);
section.setTitle(null);
}
this.element = section;
}
/**
* Adds a Paragraph
, List
or Table
* to this Section
.
*
* @param index index at which the specified element is to be inserted
* @param o an object of type Paragraph
, List
or Table
=
* @throws ClassCastException if the object is not a Paragraph
, List
or Table
*/
public void add(int index, Object o) {
((Section)element).add(index, o);
}
/**
* Adds a Paragraph
, List
, Table
or another Section
* to this Section
.
*
* @param o an object of type Paragraph
, List
, Table
or another Section
* @return a boolean
* @throws ClassCastException if the object is not a Paragraph
, List
, Table
or Section
*/
public boolean add(Object o) {
return ((Section)element).add(o);
}
/**
* Processes the element by adding it (or the different parts) to an
* ElementListener
.
*
* @param listener an ElementListener
* @return true
if the element was processed successfully
*/
public boolean process(ElementListener listener) {
try {
Element element;
for (Iterator i = ((Section)this.element).iterator(); i.hasNext(); ) {
element = (Element)i.next();
listener.add(element);
}
return true;
}
catch(DocumentException de) {
return false;
}
}
/**
* Adds a collection of Element
s
* to this Section
.
*
* @param collection a collection of Paragraph
s, List
s and/or Table
s
* @return true
if the action succeeded, false
if not.
* @throws ClassCastException if one of the objects isn't a Paragraph
, List
, Table
*/
public boolean addAll(Collection collection) {
return ((Section)element).addAll(collection);
}
/**
* Creates a Section
, adds it to this Section
and returns it.
*
* @param indentation the indentation of the new section
* @param numberDepth the numberDepth of the section
* @return a new Section object
*/
public MarkedSection addSection(float indentation, int numberDepth) {
MarkedSection section = ((Section)element).addMarkedSection();
section.setIndentation(indentation);
section.setNumberDepth(numberDepth);
return section;
}
/**
* Creates a Section
, adds it to this Section
and returns it.
*
* @param indentation the indentation of the new section
* @return a new Section object
*/
public MarkedSection addSection(float indentation) {
MarkedSection section = ((Section)element).addMarkedSection();
section.setIndentation(indentation);
return section;
}
/**
* Creates a Section
, add it to this Section
and returns it.
*
* @param numberDepth the numberDepth of the section
* @return a new Section object
*/
public MarkedSection addSection(int numberDepth) {
MarkedSection section = ((Section)element).addMarkedSection();
section.setNumberDepth(numberDepth);
return section;
}
/**
* Creates a Section
, adds it to this Section
and returns it.
*
* @return a new Section object
*/
public MarkedSection addSection() {
return ((Section)element).addMarkedSection();
}
// public methods
/**
* Sets the title of this section.
*
* @param title the new title
*/
public void setTitle(MarkedObject title) {
if (title.element instanceof Paragraph)
this.title = title;
}
/**
* Gets the title of this MarkedSection.
* @return a MarkObject with a Paragraph containing the title of a Section
* @since iText 2.0.8
*/
public MarkedObject getTitle() {
Paragraph result = Section.constructTitle((Paragraph)title.element, ((Section)element).numbers, ((Section)element).numberDepth, ((Section)element).numberStyle);
MarkedObject mo = new MarkedObject(result);
mo.markupAttributes = title.markupAttributes;
return mo;
}
/**
* Sets the depth of the sectionnumbers that will be shown preceding the title.
* Section
on the left side.
*
* @param indentation the indentation
*/
public void setIndentationLeft(float indentation) {
((Section)element).setIndentationLeft(indentation);
}
/**
* Sets the indentation of this Section
on the right side.
*
* @param indentation the indentation
*/
public void setIndentationRight(float indentation) {
((Section)element).setIndentationRight(indentation);
}
/**
* Sets the indentation of the content of this Section
.
*
* @param indentation the indentation
*/
public void setIndentation(float indentation) {
((Section)element).setIndentation(indentation);
}
/** Setter for property bookmarkOpen.
* @param bookmarkOpen false if the bookmark children are not
* visible.
*/
public void setBookmarkOpen(boolean bookmarkOpen) {
((Section)element).setBookmarkOpen(bookmarkOpen);
}
/**
* Setter for property triggerNewPage.
* @param triggerNewPage true if a new page has to be triggered.
*/
public void setTriggerNewPage(boolean triggerNewPage) {
((Section)element).setTriggerNewPage(triggerNewPage);
}
/**
* Sets the bookmark title. The bookmark title is the same as the section title but
* can be changed with this method.
* @param bookmarkTitle the bookmark title
*/
public void setBookmarkTitle(String bookmarkTitle) {
((Section)element).setBookmarkTitle(bookmarkTitle);
}
/**
* Adds a new page to the section.
* @since 2.1.1
*/
public void newPage() {
((Section)element).newPage();
}
}
src/core/com/lowagie/text/Meta.java 100644 0 0 15573 11012562273 14700 0 ustar 0 0 /*
* $Id: Meta.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.util.ArrayList;
/**
* This is an Element
that contains
* some meta information about the document.
* Meta
can not be constructed by the user.
* User defined meta information should be placed in a Header
-object.
* Meta
is reserved for: Subject, Keywords, Author, Title, Producer
* and Creationdate information.
*
* @see Element
* @see Header
*/
public class Meta implements Element {
// membervariables
/** This is the type of Meta-information this object contains. */
private int type;
/** This is the content of the Meta-information. */
private StringBuffer content;
// constructors
/**
* Constructs a Meta
.
*
* @param type the type of meta-information
* @param content the content
*/
Meta(int type, String content) {
this.type = type;
this.content = new StringBuffer(content);
}
/**
* Constructs a Meta
.
*
* @param tag the tagname of the meta-information
* @param content the content
*/
public Meta(String tag, String content) {
this.type = Meta.getType(tag);
this.content = new StringBuffer(content);
}
// implementation of the Element-methods
/**
* Processes the element by adding it (or the different parts) to a
* ElementListener
.
*
* @param listener the ElementListener
* @return true
if the element was processed successfully
*/
public boolean process(ElementListener listener) {
try {
return listener.add(this);
}
catch(DocumentException de) {
return false;
}
}
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return type;
}
/**
* Gets all the chunks in this element.
*
* @return an ArrayList
*/
public ArrayList getChunks() {
return new ArrayList();
}
/**
* @see com.lowagie.text.Element#isContent()
* @since iText 2.0.8
*/
public boolean isContent() {
return false;
}
/**
* @see com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return false;
}
// methods
/**
* appends some text to this Meta
.
*
* @param string a String
* @return a StringBuffer
*/
public StringBuffer append(String string) {
return content.append(string);
}
// methods to retrieve information
/**
* Returns the content of the meta information.
*
* @return a String
*/
public String getContent() {
return content.toString();
}
/**
* Returns the name of the meta information.
*
* @return a String
*/
public String getName() {
switch (type) {
case Element.SUBJECT:
return ElementTags.SUBJECT;
case Element.KEYWORDS:
return ElementTags.KEYWORDS;
case Element.AUTHOR:
return ElementTags.AUTHOR;
case Element.TITLE:
return ElementTags.TITLE;
case Element.PRODUCER:
return ElementTags.PRODUCER;
case Element.CREATIONDATE:
return ElementTags.CREATIONDATE;
default:
return ElementTags.UNKNOWN;
}
}
/**
* Returns the name of the meta information.
*
* @param tag iText tag for meta information
* @return the Element value corresponding with the given tag
*/
public static int getType(String tag) {
if (ElementTags.SUBJECT.equals(tag)) {
return Element.SUBJECT;
}
if (ElementTags.KEYWORDS.equals(tag)) {
return Element.KEYWORDS;
}
if (ElementTags.AUTHOR.equals(tag)) {
return Element.AUTHOR;
}
if (ElementTags.TITLE.equals(tag)) {
return Element.TITLE;
}
if (ElementTags.PRODUCER.equals(tag)) {
return Element.PRODUCER;
}
if (ElementTags.CREATIONDATE.equals(tag)) {
return Element.CREATIONDATE;
}
return Element.HEADER;
}
} src/core/com/lowagie/text/PageSize.java 100644 0 0 23510 11012562273 15507 0 ustar 0 0 /*
* $Id: PageSize.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.lang.reflect.Field;
/**
* The PageSize
-object contains a number of rectangles representing the most common paper sizes.
*
* @see Rectangle
*/
public class PageSize {
// membervariables
/** This is the letter format */
public static final Rectangle LETTER = new RectangleReadOnly(612,792);
/** This is the note format */
public static final Rectangle NOTE = new RectangleReadOnly(540,720);
/** This is the legal format */
public static final Rectangle LEGAL = new RectangleReadOnly(612,1008);
/** This is the tabloid format */
public static final Rectangle TABLOID = new RectangleReadOnly(792,1224);
/** This is the executive format */
public static final Rectangle EXECUTIVE = new RectangleReadOnly(522,756);
/** This is the postcard format */
public static final Rectangle POSTCARD = new RectangleReadOnly(283,416);
/** This is the a0 format */
public static final Rectangle A0 = new RectangleReadOnly(2384,3370);
/** This is the a1 format */
public static final Rectangle A1 = new RectangleReadOnly(1684,2384);
/** This is the a2 format */
public static final Rectangle A2 = new RectangleReadOnly(1191,1684);
/** This is the a3 format */
public static final Rectangle A3 = new RectangleReadOnly(842,1191);
/** This is the a4 format */
public static final Rectangle A4 = new RectangleReadOnly(595,842);
/** This is the a5 format */
public static final Rectangle A5 = new RectangleReadOnly(420,595);
/** This is the a6 format */
public static final Rectangle A6 = new RectangleReadOnly(297,420);
/** This is the a7 format */
public static final Rectangle A7 = new RectangleReadOnly(210,297);
/** This is the a8 format */
public static final Rectangle A8 = new RectangleReadOnly(148,210);
/** This is the a9 format */
public static final Rectangle A9 = new RectangleReadOnly(105,148);
/** This is the a10 format */
public static final Rectangle A10 = new RectangleReadOnly(73,105);
/** This is the b0 format */
public static final Rectangle B0 = new RectangleReadOnly(2834,4008);
/** This is the b1 format */
public static final Rectangle B1 = new RectangleReadOnly(2004,2834);
/** This is the b2 format */
public static final Rectangle B2 = new RectangleReadOnly(1417,2004);
/** This is the b3 format */
public static final Rectangle B3 = new RectangleReadOnly(1000,1417);
/** This is the b4 format */
public static final Rectangle B4 = new RectangleReadOnly(708,1000);
/** This is the b5 format */
public static final Rectangle B5 = new RectangleReadOnly(498,708);
/** This is the b6 format */
public static final Rectangle B6 = new RectangleReadOnly(354,498);
/** This is the b7 format */
public static final Rectangle B7 = new RectangleReadOnly(249,354);
/** This is the b8 format */
public static final Rectangle B8 = new RectangleReadOnly(175,249);
/** This is the b9 format */
public static final Rectangle B9 = new RectangleReadOnly(124,175);
/** This is the b10 format */
public static final Rectangle B10 = new RectangleReadOnly(87,124);
/** This is the archE format */
public static final Rectangle ARCH_E = new RectangleReadOnly(2592,3456);
/** This is the archD format */
public static final Rectangle ARCH_D = new RectangleReadOnly(1728,2592);
/** This is the archC format */
public static final Rectangle ARCH_C = new RectangleReadOnly(1296,1728);
/** This is the archB format */
public static final Rectangle ARCH_B = new RectangleReadOnly(864,1296);
/** This is the archA format */
public static final Rectangle ARCH_A = new RectangleReadOnly(648,864);
/** This is the American Foolscap format */
public static final Rectangle FLSA = new RectangleReadOnly(612,936);
/** This is the European Foolscap format */
public static final Rectangle FLSE = new RectangleReadOnly(648,936);
/** This is the halfletter format */
public static final Rectangle HALFLETTER = new RectangleReadOnly(396,612);
/** This is the 11x17 format */
public static final Rectangle _11X17 = new RectangleReadOnly(792,1224);
/** This is the ISO 7810 ID-1 format (85.60 x 53.98 mm or 3.370 x 2.125 inch) */
public static final Rectangle ID_1 = new RectangleReadOnly(242.65f,153);
/** This is the ISO 7810 ID-2 format (A7 rotated) */
public static final Rectangle ID_2 = new RectangleReadOnly(297,210);
/** This is the ISO 7810 ID-3 format (B7 rotated) */
public static final Rectangle ID_3 = new RectangleReadOnly(354,249);
/** This is the ledger format */
public static final Rectangle LEDGER = new RectangleReadOnly(1224,792);
/** This is the Crown Quarto format */
public static final Rectangle CROWN_QUARTO = new RectangleReadOnly(535,697);
/** This is the Large Crown Quarto format */
public static final Rectangle LARGE_CROWN_QUARTO = new RectangleReadOnly(569,731);
/** This is the Demy Quarto format. */
public static final Rectangle DEMY_QUARTO = new RectangleReadOnly(620,782);
/** This is the Royal Quarto format. */
public static final Rectangle ROYAL_QUARTO = new RectangleReadOnly(671,884);
/** This is the Crown Octavo format */
public static final Rectangle CROWN_OCTAVO = new RectangleReadOnly(348,527);
/** This is the Large Crown Octavo format */
public static final Rectangle LARGE_CROWN_OCTAVO = new RectangleReadOnly(365,561);
/** This is the Demy Octavo format */
public static final Rectangle DEMY_OCTAVO = new RectangleReadOnly(391,612);
/** This is the Royal Octavo format. */
public static final Rectangle ROYAL_OCTAVO = new RectangleReadOnly(442,663);
/** This is the small paperback format. */
public static final Rectangle SMALL_PAPERBACK = new RectangleReadOnly(314,504);
/** This is the Pengiun small paperback format. */
public static final Rectangle PENGUIN_SMALL_PAPERBACK = new RectangleReadOnly(314,513);
/** This is the Penguin large paperback format. */
public static final Rectangle PENGUIN_LARGE_PAPERBACK = new RectangleReadOnly(365,561);
/**
* This method returns a Rectangle based on a String.
* Possible values are the the names of a constant in this class
* (for instance "A4", "LETTER",...) or a value like "595 842"
*/
public static Rectangle getRectangle(String name) {
name = name.trim().toUpperCase();
int pos = name.indexOf(' ');
if (pos == -1) {
try {
Field field = PageSize.class.getDeclaredField(name.toUpperCase());
return (Rectangle) field.get(null);
} catch (Exception e) {
throw new RuntimeException("Can't find page size " + name);
}
}
else {
try {
String width = name.substring(0, pos);
String height = name.substring(pos + 1);
return new Rectangle(Float.parseFloat(width), Float.parseFloat(height));
} catch(Exception e) {
throw new RuntimeException(name + " is not a valid page size format; " + e.getMessage());
}
}
}
} src/core/com/lowagie/text/Paragraph.java 100644 0 0 35351 11154165267 15724 0 ustar 0 0 /*
* $Id: Paragraph.java 3668 2009-02-01 09:08:50Z blowagie $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
/**
* A Paragraph
is a series of Chunk
s and/or Phrases
.
* Paragraph
has the same qualities of a Phrase
, but also
* some additional layout-parameters:
*
*
*
* Example:
*
*
* @see Element
* @see Phrase
* @see ListItem
*/
public class Paragraph extends Phrase {
// constants
private static final long serialVersionUID = 7852314969733375514L;
// membervariables
/** The alignment of the text. */
protected int alignment = Element.ALIGN_UNDEFINED;
/** The text leading that is multiplied by the biggest font size in the line. */
protected float multipliedLeading = 0;
/** The indentation of this paragraph on the left side. */
protected float indentationLeft;
/** The indentation of this paragraph on the right side. */
protected float indentationRight;
/** Holds value of property firstLineIndent. */
private float firstLineIndent = 0;
/** The spacing before the paragraph. */
protected float spacingBefore;
/** The spacing after the paragraph. */
protected float spacingAfter;
/** Holds value of property extraParagraphSpace. */
private float extraParagraphSpace = 0;
/** Does the paragraph has to be kept together on 1 page. */
protected boolean keeptogether = false;
// constructors
/**
* Constructs a
* Paragraph p = new Paragraph("This is a paragraph",
* FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLDITALIC, new Color(0, 0, 255)));
*
Paragraph
.
*/
public Paragraph() {
super();
}
/**
* Constructs a Paragraph
with a certain leading.
*
* @param leading the leading
*/
public Paragraph(float leading) {
super(leading);
}
/**
* Constructs a Paragraph
with a certain Chunk
.
*
* @param chunk a Chunk
*/
public Paragraph(Chunk chunk) {
super(chunk);
}
/**
* Constructs a Paragraph
with a certain Chunk
* and a certain leading.
*
* @param leading the leading
* @param chunk a Chunk
*/
public Paragraph(float leading, Chunk chunk) {
super(leading, chunk);
}
/**
* Constructs a Paragraph
with a certain String
.
*
* @param string a String
*/
public Paragraph(String string) {
super(string);
}
/**
* Constructs a Paragraph
with a certain String
* and a certain Font
.
*
* @param string a String
* @param font a Font
*/
public Paragraph(String string, Font font) {
super(string, font);
}
/**
* Constructs a Paragraph
with a certain String
* and a certain leading.
*
* @param leading the leading
* @param string a String
*/
public Paragraph(float leading, String string) {
super(leading, string);
}
/**
* Constructs a Paragraph
with a certain leading, String
* and Font
.
*
* @param leading the leading
* @param string a String
* @param font a Font
*/
public Paragraph(float leading, String string, Font font) {
super(leading, string, font);
}
/**
* Constructs a Paragraph
with a certain Phrase
.
*
* @param phrase a Phrase
*/
public Paragraph(Phrase phrase) {
super(phrase);
if (phrase instanceof Paragraph) {
Paragraph p = (Paragraph)phrase;
setAlignment(p.alignment);
setLeading(phrase.getLeading(), p.multipliedLeading);
setIndentationLeft(p.getIndentationLeft());
setIndentationRight(p.getIndentationRight());
setFirstLineIndent(p.getFirstLineIndent());
setSpacingAfter(p.spacingAfter());
setSpacingBefore(p.spacingBefore());
setExtraParagraphSpace(p.getExtraParagraphSpace());
}
}
// implementation of the Element-methods
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return Element.PARAGRAPH;
}
// methods
/**
* Adds an Object
to the Paragraph
.
*
* @param o object the object to add.
* @return true is adding the object succeeded
*/
public boolean add(Object o) {
if (o instanceof List) {
List list = (List) o;
list.setIndentationLeft(list.getIndentationLeft() + indentationLeft);
list.setIndentationRight(indentationRight);
return super.add(list);
}
else if (o instanceof Image) {
super.addSpecial(o);
return true;
}
else if (o instanceof Paragraph) {
super.add(o);
java.util.List chunks = getChunks();
if (!chunks.isEmpty()) {
Chunk tmp = ((Chunk) chunks.get(chunks.size() - 1));
super.add(new Chunk("\n", tmp.getFont()));
}
else {
super.add(Chunk.NEWLINE);
}
return true;
}
return super.add(o);
}
// setting the membervariables
/**
* Sets the alignment of this paragraph.
*
* @param alignment the new alignment
*/
public void setAlignment(int alignment) {
this.alignment = alignment;
}
/**
* Sets the alignment of this paragraph.
*
* @param alignment the new alignment as a String
*/
public void setAlignment(String alignment) {
if (ElementTags.ALIGN_CENTER.equalsIgnoreCase(alignment)) {
this.alignment = Element.ALIGN_CENTER;
return;
}
if (ElementTags.ALIGN_RIGHT.equalsIgnoreCase(alignment)) {
this.alignment = Element.ALIGN_RIGHT;
return;
}
if (ElementTags.ALIGN_JUSTIFIED.equalsIgnoreCase(alignment)) {
this.alignment = Element.ALIGN_JUSTIFIED;
return;
}
if (ElementTags.ALIGN_JUSTIFIED_ALL.equalsIgnoreCase(alignment)) {
this.alignment = Element.ALIGN_JUSTIFIED_ALL;
return;
}
this.alignment = Element.ALIGN_LEFT;
}
/**
* @see com.lowagie.text.Phrase#setLeading(float)
*/
public void setLeading(float fixedLeading) {
this.leading = fixedLeading;
this.multipliedLeading = 0;
}
/**
* Sets the variable leading. The resultant leading will be
* multipliedLeading*maxFontSize where maxFontSize is the
* size of the biggest font in the line.
* @param multipliedLeading the variable leading
*/
public void setMultipliedLeading(float multipliedLeading) {
this.leading = 0;
this.multipliedLeading = multipliedLeading;
}
/**
* Sets the leading fixed and variable. The resultant leading will be
* fixedLeading+multipliedLeading*maxFontSize where maxFontSize is the
* size of the biggest font in the line.
* @param fixedLeading the fixed leading
* @param multipliedLeading the variable leading
*/
public void setLeading(float fixedLeading, float multipliedLeading) {
this.leading = fixedLeading;
this.multipliedLeading = multipliedLeading;
}
/**
* Sets the indentation of this paragraph on the left side.
*
* @param indentation the new indentation
*/
public void setIndentationLeft(float indentation) {
this.indentationLeft = indentation;
}
/**
* Sets the indentation of this paragraph on the right side.
*
* @param indentation the new indentation
*/
public void setIndentationRight(float indentation) {
this.indentationRight = indentation;
}
/**
* Setter for property firstLineIndent.
* @param firstLineIndent New value of property firstLineIndent.
*/
public void setFirstLineIndent(float firstLineIndent) {
this.firstLineIndent = firstLineIndent;
}
/**
* Sets the spacing before this paragraph.
*
* @param spacing the new spacing
*/
public void setSpacingBefore(float spacing) {
this.spacingBefore = spacing;
}
/**
* Sets the spacing after this paragraph.
*
* @param spacing the new spacing
*/
public void setSpacingAfter(float spacing) {
this.spacingAfter = spacing;
}
/**
* Indicates that the paragraph has to be kept together on one page.
*
* @param keeptogether true of the paragraph may not be split over 2 pages
*/
public void setKeepTogether(boolean keeptogether) {
this.keeptogether = keeptogether;
}
/**
* Checks if this paragraph has to be kept together on one page.
*
* @return true if the paragraph may not be split over 2 pages.
*/
public boolean getKeepTogether() {
return keeptogether;
}
// methods to retrieve information
/**
* Gets the alignment of this paragraph.
*
* @return alignment
*/
public int getAlignment() {
return alignment;
}
/**
* Gets the variable leading
* @return the leading
*/
public float getMultipliedLeading() {
return multipliedLeading;
}
/**
* Gets the total leading.
* This method is based on the assumption that the
* font of the Paragraph is the font of all the elements
* that make part of the paragraph. This isn't necessarily
* true.
* @return the total leading (fixed and multiplied)
*/
public float getTotalLeading() {
float m = font == null ?
Font.DEFAULTSIZE * multipliedLeading : font.getCalculatedLeading(multipliedLeading);
if (m > 0 && !hasLeading()) {
return m;
}
return getLeading() + m;
}
/**
* Gets the indentation of this paragraph on the left side.
*
* @return the indentation
*/
public float getIndentationLeft() {
return indentationLeft;
}
/**
* Gets the indentation of this paragraph on the right side.
*
* @return the indentation
*/
public float getIndentationRight() {
return indentationRight;
}
/**
* Getter for property firstLineIndent.
* @return Value of property firstLineIndent.
*/
public float getFirstLineIndent() {
return this.firstLineIndent;
}
/**
* Gets the spacing before this paragraph.
* @return the spacing
* @since 2.1.5
*/
public float getSpacingBefore() {
return spacingBefore;
}
/**
* Gets the spacing after this paragraph.
* @return the spacing
* @since 2.1.5
*/
public float getSpacingAfter() {
return spacingAfter;
}
/**
* Getter for property extraParagraphSpace.
* @return Value of property extraParagraphSpace.
*/
public float getExtraParagraphSpace() {
return this.extraParagraphSpace;
}
/**
* Setter for property extraParagraphSpace.
* @param extraParagraphSpace New value of property extraParagraphSpace.
*/
public void setExtraParagraphSpace(float extraParagraphSpace) {
this.extraParagraphSpace = extraParagraphSpace;
}
// scheduled for removal
/**
* Gets the spacing before this paragraph.
*
* @return the spacing
* @deprecated As of iText 2.1.5, replaced by {@link #getSpacingBefore()},
* scheduled for removal at 2.3.0
*/
public float spacingBefore() {
return getSpacingBefore();
}
/**
* Gets the spacing after this paragraph.
*
* @return the spacing
* @deprecated As of iText 2.1.5, replaced by {@link #getSpacingAfter()},
* scheduled for removal at 2.3.0
*/
public float spacingAfter() {
return spacingAfter;
}
}
src/core/com/lowagie/text/Phrase.java 100644 0 0 47046 11213370070 15227 0 ustar 0 0 /*
* $Id: Phrase.java 3942 2009-05-28 18:14:10Z blowagie $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import com.lowagie.text.pdf.HyphenationEvent;
/**
* A Phrase
is a series of Chunk
s.
* Phrase
has a main Font
, but some chunks
* within the phrase can have a Font
that differs from the
* main Font
. All the Chunk
s in a Phrase
* have the same leading
.
*
*
* @see Element
* @see Chunk
* @see Paragraph
* @see Anchor
*/
public class Phrase extends ArrayList implements TextElementArray {
// constants
private static final long serialVersionUID = 2643594602455068231L;
// membervariables
/** This is the leading of this phrase. */
protected float leading = Float.NaN;
/** This is the font of this phrase. */
protected Font font;
/** Null, unless the Phrase has to be hyphenated.
* @since 2.1.2
*/
protected HyphenationEvent hyphenation = null;
// constructors
/**
* Constructs a
* // When no parameters are passed, the default leading = 16
* Phrase phrase0 = new Phrase();
* Phrase phrase1 = new Phrase("this is a phrase");
* // In this example the leading is passed as a parameter
* Phrase phrase2 = new Phrase(16, "this is a phrase with leading 16");
* // When a Font is passed (explicitly or embedded in a chunk), the default leading = 1.5 * size of the font
* Phrase phrase3 = new Phrase("this is a phrase with a red, normal font Courier, size 12", FontFactory.getFont(FontFactory.COURIER, 12, Font.NORMAL, new Color(255, 0, 0)));
* Phrase phrase4 = new Phrase(new Chunk("this is a phrase"));
* Phrase phrase5 = new Phrase(18, new Chunk("this is a phrase", FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD, new Color(255, 0, 0)));
*
Phrase
without specifying a leading.
*/
public Phrase() {
this(16);
}
/**
* Copy constructor for Phrase
.
*/
public Phrase(Phrase phrase) {
super();
this.addAll(phrase);
leading = phrase.getLeading();
font = phrase.getFont();
setHyphenation(phrase.getHyphenation());
}
/**
* Constructs a Phrase
with a certain leading.
*
* @param leading the leading
*/
public Phrase(float leading) {
this.leading = leading;
font = new Font();
}
/**
* Constructs a Phrase
with a certain Chunk
.
*
* @param chunk a Chunk
*/
public Phrase(Chunk chunk) {
super.add(chunk);
font = chunk.getFont();
setHyphenation(chunk.getHyphenation());
}
/**
* Constructs a Phrase
with a certain Chunk
* and a certain leading.
*
* @param leading the leading
* @param chunk a Chunk
*/
public Phrase(float leading, Chunk chunk) {
this.leading = leading;
super.add(chunk);
font = chunk.getFont();
setHyphenation(chunk.getHyphenation());
}
/**
* Constructs a Phrase
with a certain String
.
*
* @param string a String
*/
public Phrase(String string) {
this(Float.NaN, string, new Font());
}
/**
* Constructs a Phrase
with a certain String
and a certain Font
.
*
* @param string a String
* @param font a Font
*/
public Phrase(String string, Font font) {
this(Float.NaN, string, font);
}
/**
* Constructs a Phrase
with a certain leading and a certain String
.
*
* @param leading the leading
* @param string a String
*/
public Phrase(float leading, String string) {
this(leading, string, new Font());
}
/**
* Constructs a Phrase
with a certain leading, a certain String
* and a certain Font
.
*
* @param leading the leading
* @param string a String
* @param font a Font
*/
public Phrase(float leading, String string, Font font) {
this.leading = leading;
this.font = font;
/* bugfix by August Detlefsen */
if (string != null && string.length() != 0) {
super.add(new Chunk(string, font));
}
}
// implementation of the Element-methods
/**
* Processes the element by adding it (or the different parts) to an
* ElementListener
.
*
* @param listener an ElementListener
* @return true
if the element was processed successfully
*/
public boolean process(ElementListener listener) {
try {
for (Iterator i = iterator(); i.hasNext(); ) {
listener.add((Element) i.next());
}
return true;
}
catch(DocumentException de) {
return false;
}
}
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return Element.PHRASE;
}
/**
* Gets all the chunks in this element.
*
* @return an ArrayList
*/
public ArrayList getChunks() {
ArrayList tmp = new ArrayList();
for (Iterator i = iterator(); i.hasNext(); ) {
tmp.addAll(((Element) i.next()).getChunks());
}
return tmp;
}
/**
* @see com.lowagie.text.Element#isContent()
* @since iText 2.0.8
*/
public boolean isContent() {
return true;
}
/**
* @see com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return true;
}
// overriding some of the ArrayList-methods
/**
* Adds a Chunk
, an Anchor
or another Phrase
* to this Phrase
.
*
* @param index index at which the specified element is to be inserted
* @param o an object of type Chunk
, Anchor
or Phrase
* @throws ClassCastException when you try to add something that isn't a Chunk
, Anchor
or Phrase
*/
public void add(int index, Object o) {
if (o == null) return;
try {
Element element = (Element) o;
if (element.type() == Element.CHUNK) {
Chunk chunk = (Chunk) element;
if (!font.isStandardFont()) {
chunk.setFont(font.difference(chunk.getFont()));
}
if (hyphenation != null && chunk.getHyphenation() == null && !chunk.isEmpty()) {
chunk.setHyphenation(hyphenation);
}
super.add(index, chunk);
}
else if (element.type() == Element.PHRASE ||
element.type() == Element.ANCHOR ||
element.type() == Element.ANNOTATION ||
element.type() == Element.TABLE || // line added by David Freels
element.type() == Element.YMARK ||
element.type() == Element.MARKED) {
super.add(index, element);
}
else {
throw new ClassCastException(String.valueOf(element.type()));
}
}
catch(ClassCastException cce) {
throw new ClassCastException("Insertion of illegal Element: " + cce.getMessage());
}
}
/**
* Adds a Chunk
, Anchor
or another Phrase
* to this Phrase
.
*
* @param o an object of type Chunk
, Anchor
or Phrase
* @return a boolean
* @throws ClassCastException when you try to add something that isn't a Chunk
, Anchor
or Phrase
*/
public boolean add(Object o) {
if (o == null) return false;
if (o instanceof String) {
return super.add(new Chunk((String) o, font));
}
if (o instanceof RtfElementInterface) {
return super.add(o);
}
try {
Element element = (Element) o;
switch(element.type()) {
case Element.CHUNK:
return addChunk((Chunk) o);
case Element.PHRASE:
case Element.PARAGRAPH:
Phrase phrase = (Phrase) o;
boolean success = true;
Element e;
for (Iterator i = phrase.iterator(); i.hasNext(); ) {
e = (Element) i.next();
if (e instanceof Chunk) {
success &= addChunk((Chunk)e);
}
else {
success &= this.add(e);
}
}
return success;
case Element.MARKED:
case Element.ANCHOR:
case Element.ANNOTATION:
case Element.TABLE: // case added by David Freels
case Element.PTABLE: // case added by mr. Karen Vardanyan
// This will only work for PDF!!! Not for RTF/HTML
case Element.LIST:
case Element.YMARK:
return super.add(o);
default:
throw new ClassCastException(String.valueOf(element.type()));
}
}
catch(ClassCastException cce) {
throw new ClassCastException("Insertion of illegal Element: " + cce.getMessage());
}
}
/**
* Adds a collection of Chunk
s
* to this Phrase
.
*
* @param collection a collection of Chunk
s, Anchor
s and Phrase
s.
* @return true
if the action succeeded, false
if not.
* @throws ClassCastException when you try to add something that isn't a Chunk
, Anchor
or Phrase
*/
public boolean addAll(Collection collection) {
for (Iterator iterator = collection.iterator(); iterator.hasNext(); ) {
this.add(iterator.next());
}
return true;
}
/**
* Adds a Chunk.
* Object
to the Paragraph
.
*
* @param object the object to add.
*/
protected void addSpecial(Object object) {
super.add(object);
}
// other methods that change the member variables
/**
* Sets the leading of this phrase.
*
* @param leading the new leading
*/
public void setLeading(float leading) {
this.leading = leading;
}
/**
* Sets the main font of this phrase.
* @param font the new font
*/
public void setFont(Font font) {
this.font = font;
}
// methods to retrieve information
/**
* Gets the leading of this phrase.
*
* @return the linespacing
*/
public float getLeading() {
if (Float.isNaN(leading) && font != null) {
return font.getCalculatedLeading(1.5f);
}
return leading;
}
/**
* Checks you if the leading of this phrase is defined.
*
* @return true if the leading is defined
*/
public boolean hasLeading() {
if (Float.isNaN(leading)) {
return false;
}
return true;
}
/**
* Gets the font of the first Chunk
that appears in this Phrase
.
*
* @return a Font
*/
public Font getFont() {
return font;
}
/**
* Returns the content as a String object.
* This method differs from toString because toString will return an ArrayList with the toString value of the Chunks in this Phrase.
*/
public String getContent() {
StringBuffer buf = new StringBuffer();
for (Iterator i = getChunks().iterator(); i.hasNext(); ) {
buf.append(i.next().toString());
}
return buf.toString();
}
/**
* Checks is this Phrase
contains no or 1 empty Chunk
.
*
* @return false
if the Phrase
* contains more than one or more non-emptyChunk
s.
*/
public boolean isEmpty() {
switch(size()) {
case 0:
return true;
case 1:
Element element = (Element) get(0);
if (element.type() == Element.CHUNK && ((Chunk) element).isEmpty()) {
return true;
}
return false;
default:
return false;
}
}
/**
* Getter for the hyphenation settings.
* @return a HyphenationEvent
* @since 2.1.2
*/
public HyphenationEvent getHyphenation() {
return hyphenation;
}
/**
* Setter for the hyphenation.
* @param hyphenation a HyphenationEvent instance
* @since 2.1.2
*/
public void setHyphenation(HyphenationEvent hyphenation) {
this.hyphenation = hyphenation;
}
// kept for historical reasons; people should use FontSelector
// eligible for deprecation, but the methods are mentioned in the book p277.
/**
* Constructs a Phrase that can be used in the static getInstance() method.
* @param dummy a dummy parameter
*/
private Phrase(boolean dummy) {
}
/**
* Gets a special kind of Phrase that changes some characters into corresponding symbols.
* @param string
* @return a newly constructed Phrase
*/
public static final Phrase getInstance(String string) {
return getInstance(16, string, new Font());
}
/**
* Gets a special kind of Phrase that changes some characters into corresponding symbols.
* @param leading
* @param string
* @return a newly constructed Phrase
*/
public static final Phrase getInstance(int leading, String string) {
return getInstance(leading, string, new Font());
}
/**
* Gets a special kind of Phrase that changes some characters into corresponding symbols.
* @param leading
* @param string
* @param font
* @return a newly constructed Phrase
*/
public static final Phrase getInstance(int leading, String string, Font font) {
Phrase p = new Phrase(true);
p.setLeading(leading);
p.font = font;
if (font.getFamily() != Font.SYMBOL && font.getFamily() != Font.ZAPFDINGBATS && font.getBaseFont() == null) {
int index;
while((index = SpecialSymbol.index(string)) > -1) {
if (index > 0) {
String firstPart = string.substring(0, index);
((ArrayList)p).add(new Chunk(firstPart, font));
string = string.substring(index);
}
Font symbol = new Font(Font.SYMBOL, font.getSize(), font.getStyle(), font.getColor());
StringBuffer buf = new StringBuffer();
buf.append(SpecialSymbol.getCorrespondingSymbol(string.charAt(0)));
string = string.substring(1);
while (SpecialSymbol.index(string) == 0) {
buf.append(SpecialSymbol.getCorrespondingSymbol(string.charAt(0)));
string = string.substring(1);
}
((ArrayList)p).add(new Chunk(buf.toString(), symbol));
}
}
if (string != null && string.length() != 0) {
((ArrayList)p).add(new Chunk(string, font));
}
return p;
}
} src/core/com/lowagie/text/Rectangle.java 100644 0 0 52132 11154165267 15717 0 ustar 0 0 /*
* $Id: Rectangle.java 3742 2009-03-03 16:42:09Z blowagie $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.awt.Color;
import java.util.ArrayList;
import com.lowagie.text.pdf.GrayColor;
/**
* A Rectangle
is the representation of a geometric figure.
*
* Rectangles support constant width borders using
* {@link #setBorderWidth(float)}and {@link #setBorder(int)}.
* They also support borders that vary in width/color on each side using
* methods like {@link #setBorderWidthLeft(float)}or
* {@link #setBorderColorLeft(java.awt.Color)}.
*
* @see Element
* @see Table
* @see Cell
* @see HeaderFooter
*/
public class Rectangle implements Element {
// CONSTANTS:
/** This is the value that will be used as undefined . */
public static final int UNDEFINED = -1;
/** This represents one side of the border of the Rectangle
. */
public static final int TOP = 1;
/** This represents one side of the border of the Rectangle
. */
public static final int BOTTOM = 2;
/** This represents one side of the border of the Rectangle
. */
public static final int LEFT = 4;
/** This represents one side of the border of the Rectangle
. */
public static final int RIGHT = 8;
/** This represents a rectangle without borders. */
public static final int NO_BORDER = 0;
/** This represents a type of border. */
public static final int BOX = TOP + BOTTOM + LEFT + RIGHT;
// MEMBER VARIABLES:
/** the lower left x-coordinate. */
protected float llx;
/** the lower left y-coordinate. */
protected float lly;
/** the upper right x-coordinate. */
protected float urx;
/** the upper right y-coordinate. */
protected float ury;
/** The rotation of the Rectangle */
protected int rotation = 0;
/** This is the color of the background of this rectangle. */
protected Color backgroundColor = null;
/** This represents the status of the 4 sides of the rectangle. */
protected int border = UNDEFINED;
/** Whether variable width/color borders are used. */
protected boolean useVariableBorders = false;
/** This is the width of the border around this rectangle. */
protected float borderWidth = UNDEFINED;
/** The width of the left border of this rectangle. */
protected float borderWidthLeft = UNDEFINED;
/** The width of the right border of this rectangle. */
protected float borderWidthRight = UNDEFINED;
/** The width of the top border of this rectangle. */
protected float borderWidthTop = UNDEFINED;
/** The width of the bottom border of this rectangle. */
protected float borderWidthBottom = UNDEFINED;
/** The color of the border of this rectangle. */
protected Color borderColor = null;
/** The color of the left border of this rectangle. */
protected Color borderColorLeft = null;
/** The color of the right border of this rectangle. */
protected Color borderColorRight = null;
/** The color of the top border of this rectangle. */
protected Color borderColorTop = null;
/** The color of the bottom border of this rectangle. */
protected Color borderColorBottom = null;
// CONSTRUCTORS:
/**
* Constructs a Rectangle
-object.
*
* @param llx lower left x
* @param lly lower left y
* @param urx upper right x
* @param ury upper right y
*/
public Rectangle(float llx, float lly, float urx, float ury) {
this.llx = llx;
this.lly = lly;
this.urx = urx;
this.ury = ury;
}
/**
* Constructs a Rectangle
-object starting from the origin
* (0, 0).
*
* @param urx upper right x
* @param ury upper right y
*/
public Rectangle(float urx, float ury) {
this(0, 0, urx, ury);
}
/**
* Constructs a Rectangle
-object.
*
* @param rect another Rectangle
*/
public Rectangle(Rectangle rect) {
this(rect.llx, rect.lly, rect.urx, rect.ury);
cloneNonPositionParameters(rect);
}
// IMPLEMENTATION OF THE ELEMENT INTERFACE:e
/**
* Processes the element by adding it (or the different parts) to an
* ElementListener
.
*
* @param listener an ElementListener
* @return true
if the element was processed successfully
*/
public boolean process(ElementListener listener) {
try {
return listener.add(this);
}
catch (DocumentException de) {
return false;
}
}
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return Element.RECTANGLE;
}
/**
* Gets all the chunks in this element.
*
* @return an ArrayList
*/
public ArrayList getChunks() {
return new ArrayList();
}
/**
* @see com.lowagie.text.Element#isContent()
* @since iText 2.0.8
*/
public boolean isContent() {
return true;
}
/**
* @see com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return false;
}
// METHODS TO GET/SET THE DIMENSIONS:
/**
* Sets the lower left x-coordinate.
*
* @param llx the new value
*/
public void setLeft(float llx) {
this.llx = llx;
}
/**
* Returns the lower left x-coordinate.
*
* @return the lower left x-coordinate
*/
public float getLeft() {
return llx;
}
/**
* Returns the lower left x-coordinate, considering a given margin.
*
* @param margin a margin
* @return the lower left x-coordinate
*/
public float getLeft(float margin) {
return llx + margin;
}
/**
* Sets the upper right x-coordinate.
*
* @param urx the new value
*/
public void setRight(float urx) {
this.urx = urx;
}
/**
* Returns the upper right x-coordinate.
*
* @return the upper right x-coordinate
*/
public float getRight() {
return urx;
}
/**
* Returns the upper right x-coordinate, considering a given margin.
*
* @param margin a margin
* @return the upper right x-coordinate
*/
public float getRight(float margin) {
return urx - margin;
}
/**
* Returns the width of the rectangle.
*
* @return the width
*/
public float getWidth() {
return urx - llx;
}
/**
* Sets the upper right y-coordinate.
*
* @param ury the new value
*/
public void setTop(float ury) {
this.ury = ury;
}
/**
* Returns the upper right y-coordinate.
*
* @return the upper right y-coordinate
*/
public float getTop() {
return ury;
}
/**
* Returns the upper right y-coordinate, considering a given margin.
*
* @param margin a margin
* @return the upper right y-coordinate
*/
public float getTop(float margin) {
return ury - margin;
}
/**
* Sets the lower left y-coordinate.
*
* @param lly the new value
*/
public void setBottom(float lly) {
this.lly = lly;
}
/**
* Returns the lower left y-coordinate.
*
* @return the lower left y-coordinate
*/
public float getBottom() {
return lly;
}
/**
* Returns the lower left y-coordinate, considering a given margin.
*
* @param margin a margin
* @return the lower left y-coordinate
*/
public float getBottom(float margin) {
return lly + margin;
}
/**
* Returns the height of the rectangle.
*
* @return the height
*/
public float getHeight() {
return ury - lly;
}
/**
* Normalizes the rectangle.
* Switches lower left with upper right if necessary.
*/
public void normalize() {
if (llx > urx) {
float a = llx;
llx = urx;
urx = a;
}
if (lly > ury) {
float a = lly;
lly = ury;
ury = a;
}
}
// METHODS TO GET/SET THE ROTATION:
/**
* Gets the rotation of the rectangle
*
* @return a rotation value
*/
public int getRotation() {
return rotation;
}
/**
* Rotates the rectangle.
* Swaps the values of llx and lly and of urx and ury.
*
* @return the rotated Rectangle
*/
public Rectangle rotate() {
Rectangle rect = new Rectangle(lly, llx, ury, urx);
rect.rotation = rotation + 90;
rect.rotation %= 360;
return rect;
}
// METHODS TO GET/SET THE BACKGROUND COLOR:
/**
* Gets the backgroundcolor.
*
* @return a Color
*/
public Color getBackgroundColor() {
return backgroundColor;
}
/**
* Sets the backgroundcolor of the rectangle.
*
* @param backgroundColor a Color
*/
public void setBackgroundColor(Color backgroundColor) {
this.backgroundColor = backgroundColor;
}
/**
* Gets the grayscale.
*
* @return the grayscale color of the background
* or 0 if the background has no grayscale color.
*/
public float getGrayFill() {
if (backgroundColor instanceof GrayColor)
return ((GrayColor)backgroundColor).getGray();
return 0;
}
/**
* Sets the the background color to a grayscale value.
*
* @param value the new grayscale value
*/
public void setGrayFill(float value) {
backgroundColor = new GrayColor(value);
}
// METHODS TO GET/SET THE BORDER:
/**
* Returns the exact type of the border.
*
* @return a value
*/
public int getBorder() {
return border;
}
/**
* Indicates whether some type of border is set.
*
* @return a boolean
*/
public boolean hasBorders() {
switch (border) {
case UNDEFINED:
case NO_BORDER:
return false;
default:
return borderWidth > 0 || borderWidthLeft > 0
|| borderWidthRight > 0 || borderWidthTop > 0 || borderWidthBottom > 0;
}
}
/**
* Indicates whether the specified type of border is set.
*
* @param type the type of border
* @return a boolean
*/
public boolean hasBorder(int type) {
if (border == UNDEFINED)
return false;
return (border & type) == type;
}
/**
* Enables/Disables the border on the specified sides.
* The border is specified as an integer bitwise combination of
* the constants: LEFT, RIGHT, TOP, BOTTOM
.
*
* @see #enableBorderSide(int)
* @see #disableBorderSide(int)
* @param border the new value
*/
public void setBorder(int border) {
this.border = border;
}
/**
* Indicates whether variable width borders are being used.
* Returns true if setBorderWidthLeft, setBorderWidthRight,
* setBorderWidthTop, or setBorderWidthBottom
has been called.
*
* @return true if variable width borders are in use
*/
public boolean isUseVariableBorders() {
return useVariableBorders;
}
/**
* Sets a parameter indicating if the rectangle has variable borders
*
* @param useVariableBorders indication if the rectangle has variable borders
*/
public void setUseVariableBorders(boolean useVariableBorders) {
this.useVariableBorders = useVariableBorders;
}
/**
* Enables the border on the specified side.
*
* @param side the side to enable.
* One of LEFT, RIGHT, TOP, BOTTOM
*/
public void enableBorderSide(int side) {
if (border == UNDEFINED)
border = 0;
border |= side;
}
/**
* Disables the border on the specified side.
*
* @param side the side to disable.
* One of LEFT, RIGHT, TOP, BOTTOM
*/
public void disableBorderSide(int side) {
if (border == UNDEFINED)
border = 0;
border &= ~side;
}
// METHODS TO GET/SET THE BORDER WIDTH:
/**
* Gets the borderwidth.
*
* @return a value
*/
public float getBorderWidth() {
return borderWidth;
}
/**
* Sets the borderwidth of the table.
*
* @param borderWidth the new value
*/
public void setBorderWidth(float borderWidth) {
this.borderWidth = borderWidth;
}
/**
* Helper function returning the border width of a specific side.
*
* @param variableWidthValue a variable width (could be undefined)
* @param side the border you want to check
* @return the variableWidthValue if not undefined, otherwise the borderWidth
*/
private float getVariableBorderWidth(float variableWidthValue, int side) {
if ((border & side) != 0)
return variableWidthValue != UNDEFINED ? variableWidthValue : borderWidth;
return 0;
}
/**
* Helper function updating the border flag for a side
* based on the specified width.
* A width of 0 will disable the border on that side.
* Any other width enables it.
*
* @param width width of border
* @param side border side constant
*/
private void updateBorderBasedOnWidth(float width, int side) {
useVariableBorders = true;
if (width > 0)
enableBorderSide(side);
else
disableBorderSide(side);
}
/**
* Gets the width of the left border.
*
* @return a width
*/
public float getBorderWidthLeft() {
return getVariableBorderWidth(borderWidthLeft, LEFT);
}
/**
* Sets the width of the left border.
*
* @param borderWidthLeft a width
*/
public void setBorderWidthLeft(float borderWidthLeft) {
this.borderWidthLeft = borderWidthLeft;
updateBorderBasedOnWidth(borderWidthLeft, LEFT);
}
/**
* Gets the width of the right border.
*
* @return a width
*/
public float getBorderWidthRight() {
return getVariableBorderWidth(borderWidthRight, RIGHT);
}
/**
* Sets the width of the right border.
*
* @param borderWidthRight a width
*/
public void setBorderWidthRight(float borderWidthRight) {
this.borderWidthRight = borderWidthRight;
updateBorderBasedOnWidth(borderWidthRight, RIGHT);
}
/**
* Gets the width of the top border.
*
* @return a width
*/
public float getBorderWidthTop() {
return getVariableBorderWidth(borderWidthTop, TOP);
}
/**
* Sets the width of the top border.
*
* @param borderWidthTop a width
*/
public void setBorderWidthTop(float borderWidthTop) {
this.borderWidthTop = borderWidthTop;
updateBorderBasedOnWidth(borderWidthTop, TOP);
}
/**
* Gets the width of the bottom border.
*
* @return a width
*/
public float getBorderWidthBottom() {
return getVariableBorderWidth(borderWidthBottom, BOTTOM);
}
/**
* Sets the width of the bottom border.
*
* @param borderWidthBottom a width
*/
public void setBorderWidthBottom(float borderWidthBottom) {
this.borderWidthBottom = borderWidthBottom;
updateBorderBasedOnWidth(borderWidthBottom, BOTTOM);
}
// METHODS TO GET/SET THE BORDER COLOR:
/**
* Gets the color of the border.
*
* @return a Color
*/
public Color getBorderColor() {
return borderColor;
}
/**
* Sets the color of the border.
*
* @param borderColor a Color
*/
public void setBorderColor(Color borderColor) {
this.borderColor = borderColor;
}
/**
* Gets the color of the left border.
*
* @return a Color
*/
public Color getBorderColorLeft() {
if (borderColorLeft == null)
return borderColor;
return borderColorLeft;
}
/**
* Sets the color of the left border.
*
* @param borderColorLeft a Color
*/
public void setBorderColorLeft(Color borderColorLeft) {
this.borderColorLeft = borderColorLeft;
}
/**
* Gets the color of the right border.
*
* @return a Color
*/
public Color getBorderColorRight() {
if (borderColorRight == null)
return borderColor;
return borderColorRight;
}
/**
* Sets the color of the right border.
*
* @param borderColorRight a Color
*/
public void setBorderColorRight(Color borderColorRight) {
this.borderColorRight = borderColorRight;
}
/**
* Gets the color of the top border.
*
* @return a Color
*/
public Color getBorderColorTop() {
if (borderColorTop == null)
return borderColor;
return borderColorTop;
}
/**
* Sets the color of the top border.
*
* @param borderColorTop a Color
*/
public void setBorderColorTop(Color borderColorTop) {
this.borderColorTop = borderColorTop;
}
/**
* Gets the color of the bottom border.
*
* @return a Color
*/
public Color getBorderColorBottom() {
if (borderColorBottom == null)
return borderColor;
return borderColorBottom;
}
/**
* Sets the color of the bottom border.
*
* @param borderColorBottom a Color
*/
public void setBorderColorBottom(Color borderColorBottom) {
this.borderColorBottom = borderColorBottom;
}
// SPECIAL METHODS:
/**
* Gets a Rectangle that is altered to fit on the page.
*
* @param top the top position
* @param bottom the bottom position
* @return a Rectangle
*/
public Rectangle rectangle(float top, float bottom) {
Rectangle tmp = new Rectangle(this);
if (getTop() > top) {
tmp.setTop(top);
tmp.disableBorderSide(TOP);
}
if (getBottom() < bottom) {
tmp.setBottom(bottom);
tmp.disableBorderSide(BOTTOM);
}
return tmp;
}
/**
* Copies each of the parameters, except the position, from a
* Rectangle
object
*
* @param rect Rectangle
to copy from
*/
public void cloneNonPositionParameters(Rectangle rect) {
this.rotation = rect.rotation;
this.backgroundColor = rect.backgroundColor;
this.border = rect.border;
this.useVariableBorders = rect.useVariableBorders;
this.borderWidth = rect.borderWidth;
this.borderWidthLeft = rect.borderWidthLeft;
this.borderWidthRight = rect.borderWidthRight;
this.borderWidthTop = rect.borderWidthTop;
this.borderWidthBottom = rect.borderWidthBottom;
this.borderColor = rect.borderColor;
this.borderColorLeft = rect.borderColorLeft;
this.borderColorRight = rect.borderColorRight;
this.borderColorTop = rect.borderColorTop;
this.borderColorBottom = rect.borderColorBottom;
}
/**
* Copies each of the parameters, except the position, from a
* Rectangle
object if the value is set there
*
* @param rect Rectangle
to copy from
*/
public void softCloneNonPositionParameters(Rectangle rect) {
if (rect.rotation != 0)
this.rotation = rect.rotation;
if (rect.backgroundColor != null)
this.backgroundColor = rect.backgroundColor;
if (rect.border != UNDEFINED)
this.border = rect.border;
if (useVariableBorders)
this.useVariableBorders = rect.useVariableBorders;
if (rect.borderWidth != UNDEFINED)
this.borderWidth = rect.borderWidth;
if (rect.borderWidthLeft != UNDEFINED)
this.borderWidthLeft = rect.borderWidthLeft;
if (rect.borderWidthRight != UNDEFINED)
this.borderWidthRight = rect.borderWidthRight;
if (rect.borderWidthTop != UNDEFINED)
this.borderWidthTop = rect.borderWidthTop;
if (rect.borderWidthBottom != UNDEFINED)
this.borderWidthBottom = rect.borderWidthBottom;
if (rect.borderColor != null)
this.borderColor = rect.borderColor;
if (rect.borderColorLeft != null)
this.borderColorLeft = rect.borderColorLeft;
if (rect.borderColorRight != null)
this.borderColorRight = rect.borderColorRight;
if (rect.borderColorTop != null)
this.borderColorTop = rect.borderColorTop;
if (rect.borderColorBottom != null)
this.borderColorBottom = rect.borderColorBottom;
}
/**
* @return a String representation of the rectangle
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuffer buf = new StringBuffer("Rectangle: ");
buf.append(getWidth());
buf.append('x');
buf.append(getHeight());
buf.append(" (rot: ");
buf.append(rotation);
buf.append(" degrees)");
return buf.toString();
}
} src/core/com/lowagie/text/RectangleReadOnly.java 100644 0 0 22650 11154165267 17357 0 ustar 0 0 /*
* $Id: RectangleReadOnly.java 3746 2009-03-04 10:13:52Z blowagie $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.awt.Color;
/**
* A RectangleReadOnly
is the representation of a geometric figure.
* It's the same as a Rectangle
but immutable.
* Rectangles support constant width borders using
* {@link #setBorderWidth(float)}and {@link #setBorder(int)}.
* They also support borders that vary in width/color on each side using
* methods like {@link #setBorderWidthLeft(float)}or
* {@link #setBorderColorLeft(java.awt.Color)}.
*
* @see Element
* @see Table
* @see Cell
* @see HeaderFooter
* @since 2.1.2
*/
public class RectangleReadOnly extends Rectangle {
// CONSTRUCTORS
/**
* Constructs a RectangleReadOnly
-object.
*
* @param llx lower left x
* @param lly lower left y
* @param urx upper right x
* @param ury upper right y
*/
public RectangleReadOnly(float llx, float lly, float urx, float ury) {
super(llx, lly, urx, ury);
}
/**
* Constructs a RectangleReadOnly
-object starting from the origin
* (0, 0).
*
* @param urx upper right x
* @param ury upper right y
*/
public RectangleReadOnly(float urx, float ury) {
super(0, 0, urx, ury);
}
/**
* Constructs a RectangleReadOnly
-object.
*
* @param rect another Rectangle
*/
public RectangleReadOnly(Rectangle rect) {
super(rect.llx, rect.lly, rect.urx, rect.ury);
super.cloneNonPositionParameters(rect);
}
/**
* Throws an error because of the read only nature of this object.
*/
private void throwReadOnlyError() {
throw new UnsupportedOperationException("RectangleReadOnly: this Rectangle is read only.");
}
// OVERWRITE METHODS SETTING THE DIMENSIONS:
/**
* Sets the lower left x-coordinate.
*
* @param llx the new value
*/
public void setLeft(float llx) {
throwReadOnlyError();
}
/**
* Sets the upper right x-coordinate.
*
* @param urx the new value
*/
public void setRight(float urx) {
throwReadOnlyError();
}
/**
* Sets the upper right y-coordinate.
*
* @param ury the new value
*/
public void setTop(float ury) {
throwReadOnlyError();
}
/**
* Sets the lower left y-coordinate.
*
* @param lly the new value
*/
public void setBottom(float lly) {
throwReadOnlyError();
}
/**
* Normalizes the rectangle.
* Switches lower left with upper right if necessary.
*/
public void normalize() {
throwReadOnlyError();
}
// OVERWRITE METHODS SETTING THE BACKGROUND COLOR:
/**
* Sets the backgroundcolor of the rectangle.
*
* @param value the new value
*/
public void setBackgroundColor(Color value) {
throwReadOnlyError();
}
/**
* Sets the grayscale of the rectangle.
*
* @param value the new value
*/
public void setGrayFill(float value) {
throwReadOnlyError();
}
// OVERWRITE METHODS SETTING THE BORDER:
/**
* Enables/Disables the border on the specified sides.
* The border is specified as an integer bitwise combination of
* the constants: LEFT, RIGHT, TOP, BOTTOM
.
*
* @see #enableBorderSide(int)
* @see #disableBorderSide(int)
* @param border the new value
*/
public void setBorder(int border) {
throwReadOnlyError();
}
/**
* Sets a parameter indicating if the rectangle has variable borders
*
* @param useVariableBorders indication if the rectangle has variable borders
*/
public void setUseVariableBorders(boolean useVariableBorders) {
throwReadOnlyError();
}
/**
* Enables the border on the specified side.
*
* @param side the side to enable.
* One of LEFT, RIGHT, TOP, BOTTOM
*/
public void enableBorderSide(int side) {
throwReadOnlyError();
}
/**
* Disables the border on the specified side.
*
* @param side the side to disable.
* One of LEFT, RIGHT, TOP, BOTTOM
*/
public void disableBorderSide(int side) {
throwReadOnlyError();
}
// OVERWRITE METHODS SETTING THE BORDER WIDTH:
/**
* Sets the borderwidth of the table.
*
* @param borderWidth the new value
*/
public void setBorderWidth(float borderWidth) {
throwReadOnlyError();
}
/**
* Sets the width of the left border
*
* @param borderWidthLeft a width
*/
public void setBorderWidthLeft(float borderWidthLeft) {
throwReadOnlyError();
}
/**
* Sets the width of the right border
*
* @param borderWidthRight a width
*/
public void setBorderWidthRight(float borderWidthRight) {
throwReadOnlyError();
}
/**
* Sets the width of the top border
*
* @param borderWidthTop a width
*/
public void setBorderWidthTop(float borderWidthTop) {
throwReadOnlyError();
}
/**
* Sets the width of the bottom border
*
* @param borderWidthBottom a width
*/
public void setBorderWidthBottom(float borderWidthBottom) {
throwReadOnlyError();
}
// METHODS TO GET/SET THE BORDER COLOR:
/**
* Sets the color of the border.
*
* @param borderColor a Color
*/
public void setBorderColor(Color borderColor) {
throwReadOnlyError();
}
/**
* Sets the color of the left border.
*
* @param borderColorLeft a Color
*/
public void setBorderColorLeft(Color borderColorLeft) {
throwReadOnlyError();
}
/**
* Sets the color of the right border
*
* @param borderColorRight a Color
*/
public void setBorderColorRight(Color borderColorRight) {
throwReadOnlyError();
}
/**
* Sets the color of the top border.
*
* @param borderColorTop a Color
*/
public void setBorderColorTop(Color borderColorTop) {
throwReadOnlyError();
}
/**
* Sets the color of the bottom border.
*
* @param borderColorBottom a Color
*/
public void setBorderColorBottom(Color borderColorBottom) {
throwReadOnlyError();
}
// SPECIAL METHODS:
/**
* Copies each of the parameters, except the position, from a
* Rectangle
object
*
* @param rect Rectangle
to copy from
*/
public void cloneNonPositionParameters(Rectangle rect) {
throwReadOnlyError();
}
/**
* Copies each of the parameters, except the position, from a
* Rectangle
object if the value is set there.
*
* @param rect Rectangle
to copy from
*/
public void softCloneNonPositionParameters(Rectangle rect) {
throwReadOnlyError();
}
/**
* @return String version of the most important rectangle properties
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuffer buf = new StringBuffer("RectangleReadOnly: ");
buf.append(getWidth());
buf.append('x');
buf.append(getHeight());
buf.append(" (rot: ");
buf.append(rotation);
buf.append(" degrees)");
return buf.toString();
}
} src/core/com/lowagie/text/RomanList.java 100644 0 0 7667 11000354131 15674 0 ustar 0 0 /*
* Copyright 2003 by Michael Niedermair and 2007 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import com.lowagie.text.factories.RomanNumberFactory;
/**
*
* A special-version of LIST
which use roman-letters.
*
* @see com.lowagie.text.List
*/
public class RomanList extends List {
// constructors
/**
* Initialization
*/
public RomanList() {
super(true);
}
/**
* Initialization
*
* @param symbolIndent indent
*/
public RomanList(int symbolIndent) {
super(true, symbolIndent);
}
/**
* Initialization
* @param lowercase roman-char in lowercase
* @param symbolIndent indent
*/
public RomanList(boolean lowercase, int symbolIndent) {
super(true, symbolIndent);
this.lowercase = lowercase;
}
// overridden method
/**
* Adds an Object
to the List
.
*
* @param o the object to add.
* @return true if adding the object succeeded
*/
public boolean add(Object o) {
if (o instanceof ListItem) {
ListItem item = (ListItem) o;
Chunk chunk;
chunk = new Chunk(preSymbol, symbol.getFont());
chunk.append(RomanNumberFactory.getString(first + list.size(), lowercase));
chunk.append(postSymbol);
item.setListSymbol(chunk);
item.setIndentationLeft(symbolIndent, autoindent);
item.setIndentationRight(0);
list.add(item);
} else if (o instanceof List) {
List nested = (List) o;
nested.setIndentationLeft(nested.getIndentationLeft() + symbolIndent);
first--;
return list.add(nested);
} else if (o instanceof String) {
return this.add(new ListItem((String) o));
}
return false;
}
}
src/core/com/lowagie/text/Row.java 100644 0 0 30621 11012562273 14550 0 ustar 0 0 /*
* $Id: Row.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.util.ArrayList;
/**
* A Row
is part of a Table
* and contains some Cells
.
* Row
s are constructed by a Table
-object.
* You don't have to construct any Row
yourself.
* In fact you can't construct a Row
outside the package.
* Cell
can span several rows and/or columns
* a row can contain reserved space without any content.
*
* @see Element
* @see Cell
* @see Table
*/
public class Row implements Element {
// constants
/** id of a null element in a Row*/
public static final int NULL = 0;
/** id of the Cell element in a Row*/
public static final int CELL = 1;
/** id of the Table element in a Row*/
public static final int TABLE = 2;
// member variables
/** This is the number of columns in the Row
. */
protected int columns;
/** This is a valid position the Row
. */
protected int currentColumn;
/** This is the array that keeps track of reserved cells. */
protected boolean[] reserved;
/** This is the array of Objects (Cell
or Table
). */
protected Object[] cells;
/** This is the vertical alignment. */
protected int horizontalAlignment;
// constructors
/**
* Constructs a Row
with a certain number of columns.
*
* @param columns a number of columns
*/
protected Row(int columns) {
this.columns = columns;
reserved = new boolean[columns];
cells = new Object[columns];
currentColumn = 0;
}
// implementation of the Element-methods
/**
* Processes the element by adding it (or the different parts) to a
* ElementListener
.
*
* @param listener an ElementListener
* @return true
if the element was processed successfully
*/
public boolean process(ElementListener listener) {
try {
return listener.add(this);
}
catch(DocumentException de) {
return false;
}
}
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return Element.ROW;
}
/**
* Gets all the chunks in this element.
*
* @return an ArrayList
*/
public ArrayList getChunks() {
return new ArrayList();
}
/**
* @see com.lowagie.text.Element#isContent()
* @since iText 2.0.8
*/
public boolean isContent() {
return true;
}
/**
* @see com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return false;
}
// method to delete a column
/**
* Returns a Row
that is a copy of this Row
* in which a certain column has been deleted.
*
* @param column the number of the column to delete
*/
void deleteColumn(int column) {
if ((column >= columns) || (column < 0)) {
throw new IndexOutOfBoundsException("getCell at illegal index : " + column);
}
columns--;
boolean newReserved[] = new boolean[columns];
Object newCells[] = new Cell[columns];
for (int i = 0; i < column; i++) {
newReserved[i] = reserved[i];
newCells[i] = cells[i];
if (newCells[i] != null && (i + ((Cell) newCells[i]).getColspan() > column)) {
((Cell) newCells[i]).setColspan(((Cell) cells[i]).getColspan() - 1);
}
}
for (int i = column; i < columns; i++) {
newReserved[i] = reserved[i + 1];
newCells[i] = cells[i + 1];
}
if (cells[column] != null && ((Cell) cells[column]).getColspan() > 1) {
newCells[column] = cells[column];
((Cell) newCells[column]).setColspan(((Cell) newCells[column]).getColspan() - 1);
}
reserved = newReserved;
cells = newCells;
}
// methods
/**
* Adds a Cell
to the Row
.
*
* @param element the element to add (currently only Cells and Tables supported)
* @return the column position the Cell
was added,
* or -1
if the element
couldn't be added.
*/
int addElement(Object element) {
return addElement(element, currentColumn);
}
/**
* Adds an element to the Row
at the position given.
*
* @param element the element to add. (currently only Cells and Tables supported
* @param column the position where to add the cell.
* @return the column position the Cell
was added,
* or -1
if the Cell
couldn't be added.
*/
int addElement(Object element, int column) {
if (element == null) throw new NullPointerException("addCell - null argument");
if ((column < 0) || (column > columns)) throw new IndexOutOfBoundsException("addCell - illegal column argument");
if ( !((getObjectID(element) == CELL) || (getObjectID(element) == TABLE)) ) throw new IllegalArgumentException("addCell - only Cells or Tables allowed");
int lColspan = ( (Cell.class.isInstance(element)) ? ((Cell) element).getColspan() : 1);
if (!reserve(column, lColspan)) {
return -1;
}
cells[column] = element;
currentColumn += lColspan - 1;
return column;
}
/**
* Puts Cell
to the Row
at the position given, doesn't reserve colspan.
*
* @param aElement the cell to add.
* @param column the position where to add the cell.
*/
void setElement(Object aElement, int column) {
if (reserved[column]) throw new IllegalArgumentException("setElement - position already taken");
cells[column] = aElement;
if (aElement != null) {
reserved[column] = true;
}
}
/**
* Reserves a Cell
in the Row
.
*
* @param column the column that has to be reserved.
* @return true
if the column was reserved, false
if not.
*/
boolean reserve(int column) {
return reserve(column, 1);
}
/**
* Reserves a Cell
in the Row
.
*
* @param column the column that has to be reserved.
* @param size the number of columns
* @return true
if the column was reserved, false
if not.
*/
boolean reserve(int column, int size) {
if ((column < 0) || ((column + size) > columns)) throw new IndexOutOfBoundsException("reserve - incorrect column/size");
for(int i=column; i < column + size; i++)
{
if (reserved[i]) {
// undo reserve
for(int j=i; j >= column; j--) {
reserved[j] = false;
}
return false;
}
reserved[i] = true;
}
return true;
}
// methods to retrieve information
/**
* Returns true/false when this position in the Row
has been reserved, either filled or through a colspan of an Element.
*
* @param column the column.
* @return true
if the column was reserved, false
if not.
*/
boolean isReserved(int column) {
return reserved[column];
}
/**
* Returns the type-id of the element in a Row.
*
* @param column the column of which you'd like to know the type
* @return the type-id of the element in the row
*/
int getElementID(int column) {
if (cells[column] == null) return NULL;
else if (Cell.class.isInstance(cells[column])) return CELL;
else if (Table.class.isInstance(cells[column])) return TABLE;
return -1;
}
/**
* Returns the type-id of an Object.
*
* @param element the object of which you'd like to know the type-id, -1 if invalid
* @return the type-id of an object
*/
int getObjectID(Object element) {
if (element == null) return NULL;
else if (Cell.class.isInstance(element)) return CELL;
else if (Table.class.isInstance(element)) return TABLE;
return -1;
}
/**
* Gets a Cell
or Table
from a certain column.
*
* @param column the column the Cell/Table
is in.
* @return the Cell
,Table
or Object if the column was
* reserved or null if empty.
*/
public Object getCell(int column) {
if ((column < 0) || (column > columns)) {
throw new IndexOutOfBoundsException("getCell at illegal index :" + column + " max is " + columns);
}
return cells[column];
}
/**
* Checks if the row is empty.
*
* @return true
if none of the columns is reserved.
*/
public boolean isEmpty() {
for (int i = 0; i < columns; i++) {
if (cells[i] != null) {
return false;
}
}
return true;
}
/**
* Gets the number of columns.
*
* @return a value
*/
public int getColumns() {
return columns;
}
/**
* Sets the horizontal alignment.
*
* @param value the new value
*/
public void setHorizontalAlignment(int value) {
horizontalAlignment = value;
}
/**
* Gets the horizontal alignment.
*
* @return a value
*/
public int getHorizontalAlignment() {
return horizontalAlignment;
}
}
src/core/com/lowagie/text/RtfElementInterface.java 100644 0 0 5440 11012562273 17650 0 ustar 0 0 /*
* $Id: RtfElementInterface.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 2008 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
/**
* The RTF jar depends on the iText jar, but the iText jar may not
* depend on the RTF jar. This interface offers a temporary solution
* until we find a more elegant way to solve this.
* @since 2.1.0
*/
public interface RtfElementInterface {
}
src/core/com/lowagie/text/Section.java 100644 0 0 56723 11012562273 15420 0 ustar 0 0 /*
* $Id: Section.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* A Section
is a part of a Document
containing
* other Section
s, Paragraph
s, List
* and/or Table
s.
* Section
yourself.
* You will have to ask an instance of Section
to the
* Chapter
or Section
to which you want to
* add the new Section
.
*
*/
public class Section extends ArrayList implements TextElementArray, LargeElement {
// constant
/**
* A possible number style. The default number style: "1.2.3."
* @since iText 2.0.8
*/
public static final int NUMBERSTYLE_DOTTED = 0;
/**
* A possible number style. For instance: "1.2.3"
* @since iText 2.0.8
*/
public static final int NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT = 1;
/** A serial version uid. */
private static final long serialVersionUID = 3324172577544748043L;
// member variables
/** The title of this section. */
protected Paragraph title;
/** The bookmark title if different from the content title */
protected String bookmarkTitle;
/** The number of sectionnumbers that has to be shown before the section title. */
protected int numberDepth;
/**
* The style for sectionnumbers.
* @since iText 2.0.8
*/
protected int numberStyle = NUMBERSTYLE_DOTTED;
/** The indentation of this section on the left side. */
protected float indentationLeft;
/** The indentation of this section on the right side. */
protected float indentationRight;
/** The additional indentation of the content of this section. */
protected float indentation;
/** false if the bookmark children are not visible */
protected boolean bookmarkOpen = true;
/** true if the section has to trigger a new page */
protected boolean triggerNewPage = false;
/** This is the number of subsections. */
protected int subsections = 0;
/** This is the complete list of sectionnumbers of this section and the parents of this section. */
protected ArrayList numbers = null;
/**
* Indicates if the Section will be complete once added to the document.
* @since iText 2.0.8
*/
protected boolean complete = true;
/**
* Indicates if the Section was added completely to the document.
* @since iText 2.0.8
*/
protected boolean addedCompletely = false;
/**
* Indicates if this is the first time the section was added.
* @since iText 2.0.8
*/
protected boolean notAddedYet = true;
// constructors
/**
* Constructs a new
* Paragraph title2 = new Paragraph("This is Chapter 2", FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLDITALIC, new Color(0, 0, 255)));
* Chapter chapter2 = new Chapter(title2, 2);
* Paragraph someText = new Paragraph("This is some text");
* chapter2.add(someText);
* Paragraph title21 = new Paragraph("This is Section 1 in Chapter 2", FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD, new Color(255, 0, 0)));
* Section section1 = chapter2.addSection(title21);
* Paragraph someSectionText = new Paragraph("This is some silly paragraph in a chapter and/or section. It contains some text to test the functionality of Chapters and Section.");
* section1.add(someSectionText);
* Paragraph title211 = new Paragraph("This is SubSection 1 in Section 1 in Chapter 2", FontFactory.getFont(FontFactory.HELVETICA, 14, Font.BOLD, new Color(255, 0, 0)));
* Section section11 = section1.addSection(40, title211, 2);
* section11.add(someSectionText);
*
Section
.
*/
protected Section() {
title = new Paragraph();
numberDepth = 1;
}
/**
* Constructs a new Section
.
*
* @param title a Paragraph
* @param numberDepth the numberDepth
*/
protected Section(Paragraph title, int numberDepth) {
this.numberDepth = numberDepth;
this.title = title;
}
// implementation of the Element-methods
/**
* Processes the element by adding it (or the different parts) to an
* ElementListener
.
*
* @param listener the ElementListener
* @return true
if the element was processed successfully
*/
public boolean process(ElementListener listener) {
try {
Element element;
for (Iterator i = iterator(); i.hasNext(); ) {
element = (Element)i.next();
listener.add(element);
}
return true;
}
catch(DocumentException de) {
return false;
}
}
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return Element.SECTION;
}
/**
* Checks if this object is a Chapter
.
*
* @return true
if it is a Chapter
,
* false
if it is a Section
.
*/
public boolean isChapter() {
return type() == Element.CHAPTER;
}
/**
* Checks if this object is a Section
.
*
* @return true
if it is a Section
,
* false
if it is a Chapter
.
*/
public boolean isSection() {
return type() == Element.SECTION;
}
/**
* Gets all the chunks in this element.
*
* @return an ArrayList
*/
public ArrayList getChunks() {
ArrayList tmp = new ArrayList();
for (Iterator i = iterator(); i.hasNext(); ) {
tmp.addAll(((Element) i.next()).getChunks());
}
return tmp;
}
/**
* @see com.lowagie.text.Element#isContent()
* @since iText 2.0.8
*/
public boolean isContent() {
return true;
}
/**
* @see com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return false;
}
// overriding some of the ArrayList-methods
/**
* Adds a Paragraph
, List
or Table
* to this Section
.
*
* @param index index at which the specified element is to be inserted
* @param o an object of type Paragraph
, List
or Table
=
* @throws ClassCastException if the object is not a Paragraph
, List
or Table
*/
public void add(int index, Object o) {
if (isAddedCompletely()) {
throw new IllegalStateException("This LargeElement has already been added to the Document.");
}
try {
Element element = (Element) o;
if (element.isNestable()) {
super.add(index, element);
}
else {
throw new ClassCastException("You can't add a " + element.getClass().getName() + " to a Section.");
}
}
catch(ClassCastException cce) {
throw new ClassCastException("Insertion of illegal Element: " + cce.getMessage());
}
}
/**
* Adds a Paragraph
, List
, Table
or another Section
* to this Section
.
*
* @param o an object of type Paragraph
, List
, Table
or another Section
* @return a boolean
* @throws ClassCastException if the object is not a Paragraph
, List
, Table
or Section
*/
public boolean add(Object o) {
if (isAddedCompletely()) {
throw new IllegalStateException("This LargeElement has already been added to the Document.");
}
try {
Element element = (Element) o;
if (element.type() == Element.SECTION) {
Section section = (Section) o;
section.setNumbers(++subsections, numbers);
return super.add(section);
}
else if (o instanceof MarkedSection && ((MarkedObject)o).element.type() == Element.SECTION) {
MarkedSection mo = (MarkedSection)o;
Section section = (Section)mo.element;
section.setNumbers(++subsections, numbers);
return super.add(mo);
}
else if (element.isNestable()) {
return super.add(o);
}
else {
throw new ClassCastException("You can't add a " + element.getClass().getName() + " to a Section.");
}
}
catch(ClassCastException cce) {
throw new ClassCastException("Insertion of illegal Element: " + cce.getMessage());
}
}
/**
* Adds a collection of Element
s
* to this Section
.
*
* @param collection a collection of Paragraph
s, List
s and/or Table
s
* @return true
if the action succeeded, false
if not.
* @throws ClassCastException if one of the objects isn't a Paragraph
, List
, Table
*/
public boolean addAll(Collection collection) {
for (Iterator iterator = collection.iterator(); iterator.hasNext(); ) {
this.add(iterator.next());
}
return true;
}
// methods that return a Section
/**
* Creates a Section
, adds it to this Section
and returns it.
*
* @param indentation the indentation of the new section
* @param title the title of the new section
* @param numberDepth the numberDepth of the section
* @return a new Section object
*/
public Section addSection(float indentation, Paragraph title, int numberDepth) {
if (isAddedCompletely()) {
throw new IllegalStateException("This LargeElement has already been added to the Document.");
}
Section section = new Section(title, numberDepth);
section.setIndentation(indentation);
add(section);
return section;
}
/**
* Creates a Section
, adds it to this Section
and returns it.
*
* @param indentation the indentation of the new section
* @param title the title of the new section
* @return a new Section object
*/
public Section addSection(float indentation, Paragraph title) {
return addSection(indentation, title, numberDepth + 1);
}
/**
* Creates a Section
, add it to this Section
and returns it.
*
* @param title the title of the new section
* @param numberDepth the numberDepth of the section
* @return a new Section object
*/
public Section addSection(Paragraph title, int numberDepth) {
return addSection(0, title, numberDepth);
}
/**
* Adds a marked section. For use in class MarkedSection only!
*/
public MarkedSection addMarkedSection() {
MarkedSection section = new MarkedSection(new Section(null, numberDepth + 1));
add(section);
return section;
}
/**
* Creates a Section
, adds it to this Section
and returns it.
*
* @param title the title of the new section
* @return a new Section object
*/
public Section addSection(Paragraph title) {
return addSection(0, title, numberDepth + 1);
}
/**
* Adds a Section
to this Section
and returns it.
*
* @param indentation the indentation of the new section
* @param title the title of the new section
* @param numberDepth the numberDepth of the section
* @return a new Section object
*/
public Section addSection(float indentation, String title, int numberDepth) {
return addSection(indentation, new Paragraph(title), numberDepth);
}
/**
* Adds a Section
to this Section
and returns it.
*
* @param title the title of the new section
* @param numberDepth the numberDepth of the section
* @return a new Section object
*/
public Section addSection(String title, int numberDepth) {
return addSection(new Paragraph(title), numberDepth);
}
/**
* Adds a Section
to this Section
and returns it.
*
* @param indentation the indentation of the new section
* @param title the title of the new section
* @return a new Section object
*/
public Section addSection(float indentation, String title) {
return addSection(indentation, new Paragraph(title));
}
/**
* Adds a Section
to this Section
and returns it.
*
* @param title the title of the new section
* @return a new Section object
*/
public Section addSection(String title) {
return addSection(new Paragraph(title));
}
// public methods
/**
* Sets the title of this section.
*
* @param title the new title
*/
public void setTitle(Paragraph title) {
this.title = title;
}
/**
* Returns the title, preceded by a certain number of sectionnumbers.
*
* @return a Paragraph
*/
public Paragraph getTitle() {
return constructTitle(title, numbers, numberDepth, numberStyle);
}
/**
* Constructs a Paragraph that will be used as title for a Section or Chapter.
* @param title the title of the section
* @param numbers a list of sectionnumbers
* @param numberDepth how many numbers have to be shown
* @param numberStyle the numbering style
* @return a Paragraph object
* @since iText 2.0.8
*/
public static Paragraph constructTitle(Paragraph title, ArrayList numbers, int numberDepth, int numberStyle) {
if (title == null) {
return null;
}
int depth = Math.min(numbers.size(), numberDepth);
if (depth < 1) {
return title;
}
StringBuffer buf = new StringBuffer(" ");
for (int i = 0; i < depth; i++) {
buf.insert(0, ".");
buf.insert(0, ((Integer) numbers.get(i)).intValue());
}
if (numberStyle == NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT) {
buf.deleteCharAt(buf.length() - 2);
}
Paragraph result = new Paragraph(title);
result.add(0, new Chunk(buf.toString(), title.getFont()));
return result;
}
/**
* Sets the depth of the sectionnumbers that will be shown preceding the title.
* Section
.
*
* @return the numberdepth
*/
public int getNumberDepth() {
return numberDepth;
}
/**
* Sets the style for numbering sections.
* Possible values are NUMBERSTYLE_DOTTED: 1.2.3. (the default)
* or NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT: 1.2.3
* @since iText 2.0.8
*/
public void setNumberStyle(int numberStyle) {
this.numberStyle = numberStyle;
}
/**
* Gets the style used for numbering sections.
* @since iText 2.0.8
* @return a value corresponding with a numbering style
*/
public int getNumberStyle() {
return numberStyle;
}
/**
* Sets the indentation of this Section
on the left side.
*
* @param indentation the indentation
*/
public void setIndentationLeft(float indentation) {
indentationLeft = indentation;
}
/**
* Returns the indentation of this Section
on the left side.
*
* @return the indentation
*/
public float getIndentationLeft() {
return indentationLeft;
}
/**
* Sets the indentation of this Section
on the right side.
*
* @param indentation the indentation
*/
public void setIndentationRight(float indentation) {
indentationRight = indentation;
}
/**
* Returns the indentation of this Section
on the right side.
*
* @return the indentation
*/
public float getIndentationRight() {
return indentationRight;
}
/**
* Sets the indentation of the content of this Section
.
*
* @param indentation the indentation
*/
public void setIndentation(float indentation) {
this.indentation = indentation;
}
/**
* Returns the indentation of the content of this Section
.
*
* @return the indentation
*/
public float getIndentation() {
return indentation;
}
/** Setter for property bookmarkOpen.
* @param bookmarkOpen false if the bookmark children are not
* visible.
*/
public void setBookmarkOpen(boolean bookmarkOpen) {
this.bookmarkOpen = bookmarkOpen;
}
/**
* Getter for property bookmarkOpen.
* @return Value of property bookmarkOpen.
*/
public boolean isBookmarkOpen() {
return bookmarkOpen;
}
/**
* Setter for property triggerNewPage.
* @param triggerNewPage true if a new page has to be triggered.
*/
public void setTriggerNewPage(boolean triggerNewPage) {
this.triggerNewPage = triggerNewPage;
}
/**
* Getter for property bookmarkOpen.
* @return Value of property triggerNewPage.
*/
public boolean isTriggerNewPage() {
return triggerNewPage && notAddedYet;
}
/**
* Sets the bookmark title. The bookmark title is the same as the section title but
* can be changed with this method.
* @param bookmarkTitle the bookmark title
*/
public void setBookmarkTitle(String bookmarkTitle) {
this.bookmarkTitle = bookmarkTitle;
}
/**
* Gets the bookmark title.
* @return the bookmark title
*/
public Paragraph getBookmarkTitle() {
if (bookmarkTitle == null)
return getTitle();
else
return new Paragraph(bookmarkTitle);
}
/**
* Changes the Chapter number.
*/
public void setChapterNumber(int number) {
numbers.set(numbers.size() - 1, new Integer(number));
Object s;
for (Iterator i = iterator(); i.hasNext(); ) {
s = i.next();
if (s instanceof Section) {
((Section)s).setChapterNumber(number);
}
}
}
/**
* Returns the depth of this section.
*
* @return the depth
*/
public int getDepth() {
return numbers.size();
}
// private methods
/**
* Sets the number of this section.
*
* @param number the number of this section
* @param numbers an ArrayList
, containing the numbers of the Parent
*/
private void setNumbers(int number, ArrayList numbers) {
this.numbers = new ArrayList();
this.numbers.add(new Integer(number));
this.numbers.addAll(numbers);
}
/**
* Indicates if this is the first time the section is added.
* @since iText2.0.8
* @return true if the section wasn't added yet
*/
public boolean isNotAddedYet() {
return notAddedYet;
}
/**
* Sets the indication if the section was already added to
* the document.
* @since iText2.0.8
* @param notAddedYet
*/
public void setNotAddedYet(boolean notAddedYet) {
this.notAddedYet = notAddedYet;
}
/**
* @since iText 2.0.8
*/
protected boolean isAddedCompletely() {
return addedCompletely;
}
/**
* @since iText 2.0.8
*/
protected void setAddedCompletely(boolean addedCompletely) {
this.addedCompletely = addedCompletely;
}
/**
* @since iText 2.0.8
* @see com.lowagie.text.LargeElement#flushContent()
*/
public void flushContent() {
setNotAddedYet(false);
title = null;
Element element;
for (Iterator i = iterator(); i.hasNext(); ) {
element = (Element)i.next();
if (element instanceof Section) {
Section s = (Section)element;
if (!s.isComplete() && size() == 1) {
s.flushContent();
return;
}
else {
s.setAddedCompletely(true);
}
}
i.remove();
}
}
/**
* @since iText 2.0.8
* @see com.lowagie.text.LargeElement#isComplete()
*/
public boolean isComplete() {
return complete;
}
/**
* @since iText 2.0.8
* @see com.lowagie.text.LargeElement#setComplete(boolean)
*/
public void setComplete(boolean complete) {
this.complete = complete;
}
/**
* Adds a new page to the section.
* @since 2.1.1
*/
public void newPage() {
this.add(Chunk.NEXTPAGE);
}
} src/core/com/lowagie/text/SimpleCell.java 100644 0 0 36734 11154165267 16056 0 ustar 0 0 /*
* $Id: SimpleCell.java 3752 2009-03-04 18:02:40Z blowagie $
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.util.ArrayList;
import java.util.Iterator;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPCellEvent;
import com.lowagie.text.pdf.PdfPTable;
/**
* Rectangle that can be used for Cells.
* This Rectangle is padded and knows how to draw itself in a PdfPTable or PdfPcellEvent.
*/
public class SimpleCell extends Rectangle implements PdfPCellEvent, TextElementArray {
// constants
/** the CellAttributes object represents a row. */
public static final boolean ROW = true;
/** the CellAttributes object represents a cell. */
public static final boolean CELL = false;
// member variables
/** the content of the Cell. */
private ArrayList content = new ArrayList();
/** the width of the Cell. */
private float width = 0f;
/** the widthpercentage of the Cell. */
private float widthpercentage = 0f;
/** an extra spacing variable */
private float spacing_left = Float.NaN;
/** an extra spacing variable */
private float spacing_right = Float.NaN;
/** an extra spacing variable */
private float spacing_top = Float.NaN;
/** an extra spacing variable */
private float spacing_bottom = Float.NaN;
/** an extra padding variable */
private float padding_left = Float.NaN;
/** an extra padding variable */
private float padding_right = Float.NaN;
/** an extra padding variable */
private float padding_top = Float.NaN;
/** an extra padding variable */
private float padding_bottom = Float.NaN;
/** the colspan of a Cell */
private int colspan = 1;
/** horizontal alignment inside the Cell. */
private int horizontalAlignment = Element.ALIGN_UNDEFINED;
/** vertical alignment inside the Cell. */
private int verticalAlignment = Element.ALIGN_UNDEFINED;
/** indicates if these are the attributes of a single Cell (false) or a group of Cells (true). */
private boolean cellgroup = false;
/** Indicates that the largest ascender height should be used to determine the
* height of the first line. Note that this only has an effect when rendered
* to PDF. Setting this to true can help with vertical alignment problems. */
protected boolean useAscender = false;
/** Indicates that the largest descender height should be added to the height of
* the last line (so characters like y don't dip into the border). Note that
* this only has an effect when rendered to PDF. */
protected boolean useDescender = false;
/**
* Adjusts the cell contents to compensate for border widths. Note that
* this only has an effect when rendered to PDF.
*/
protected boolean useBorderPadding;
/**
* A CellAttributes object is always constructed without any dimensions.
* Dimensions are defined after creation.
* @param row only true if the CellAttributes object represents a row.
*/
public SimpleCell(boolean row) {
super(0f, 0f, 0f, 0f);
cellgroup = row;
setBorder(BOX);
}
/**
* Adds content to this object.
* @param element
* @throws BadElementException
*/
public void addElement(Element element) throws BadElementException {
if (cellgroup) {
if (element instanceof SimpleCell) {
if(((SimpleCell)element).isCellgroup()) {
throw new BadElementException("You can't add one row to another row.");
}
content.add(element);
return;
}
else {
throw new BadElementException("You can only add cells to rows, no objects of type " + element.getClass().getName());
}
}
if (element.type() == Element.PARAGRAPH
|| element.type() == Element.PHRASE
|| element.type() == Element.ANCHOR
|| element.type() == Element.CHUNK
|| element.type() == Element.LIST
|| element.type() == Element.MARKED
|| element.type() == Element.JPEG
|| element.type() == Element.JPEG2000
|| element.type() == Element.JBIG2
|| element.type() == Element.IMGRAW
|| element.type() == Element.IMGTEMPLATE) {
content.add(element);
}
else {
throw new BadElementException("You can't add an element of type " + element.getClass().getName() + " to a SimpleCell.");
}
}
/**
* Creates a Cell with these attributes.
* @param rowAttributes
* @return a cell based on these attributes.
* @throws BadElementException
*/
public Cell createCell(SimpleCell rowAttributes) throws BadElementException {
Cell cell = new Cell();
cell.cloneNonPositionParameters(rowAttributes);
cell.softCloneNonPositionParameters(this);
cell.setColspan(colspan);
cell.setHorizontalAlignment(horizontalAlignment);
cell.setVerticalAlignment(verticalAlignment);
cell.setUseAscender(useAscender);
cell.setUseBorderPadding(useBorderPadding);
cell.setUseDescender(useDescender);
Element element;
for (Iterator i = content.iterator(); i.hasNext(); ) {
element = (Element)i.next();
cell.addElement(element);
}
return cell;
}
/**
* Creates a PdfPCell with these attributes.
* @param rowAttributes
* @return a PdfPCell based on these attributes.
*/
public PdfPCell createPdfPCell(SimpleCell rowAttributes) {
PdfPCell cell = new PdfPCell();
cell.setBorder(NO_BORDER);
SimpleCell tmp = new SimpleCell(CELL);
tmp.setSpacing_left(spacing_left);
tmp.setSpacing_right(spacing_right);
tmp.setSpacing_top(spacing_top);
tmp.setSpacing_bottom(spacing_bottom);
tmp.cloneNonPositionParameters(rowAttributes);
tmp.softCloneNonPositionParameters(this);
cell.setCellEvent(tmp);
cell.setHorizontalAlignment(rowAttributes.horizontalAlignment);
cell.setVerticalAlignment(rowAttributes.verticalAlignment);
cell.setUseAscender(rowAttributes.useAscender);
cell.setUseBorderPadding(rowAttributes.useBorderPadding);
cell.setUseDescender(rowAttributes.useDescender);
cell.setColspan(colspan);
if (horizontalAlignment != Element.ALIGN_UNDEFINED)
cell.setHorizontalAlignment(horizontalAlignment);
if (verticalAlignment != Element.ALIGN_UNDEFINED)
cell.setVerticalAlignment(verticalAlignment);
if (useAscender)
cell.setUseAscender(useAscender);
if (useBorderPadding)
cell.setUseBorderPadding(useBorderPadding);
if (useDescender)
cell.setUseDescender(useDescender);
float p;
float sp_left = spacing_left;
if (Float.isNaN(sp_left)) sp_left = 0f;
float sp_right = spacing_right;
if (Float.isNaN(sp_right)) sp_right = 0f;
float sp_top = spacing_top;
if (Float.isNaN(sp_top)) sp_top = 0f;
float sp_bottom = spacing_bottom;
if (Float.isNaN(sp_bottom)) sp_bottom = 0f;
p = padding_left;
if (Float.isNaN(p)) p = 0f;
cell.setPaddingLeft(p + sp_left);
p = padding_right;
if (Float.isNaN(p)) p = 0f;
cell.setPaddingRight(p + sp_right);
p = padding_top;
if (Float.isNaN(p)) p = 0f;
cell.setPaddingTop(p + sp_top);
p = padding_bottom;
if (Float.isNaN(p)) p = 0f;
cell.setPaddingBottom(p + sp_bottom);
Element element;
for (Iterator i = content.iterator(); i.hasNext(); ) {
element = (Element)i.next();
cell.addElement(element);
}
return cell;
}
/**
* @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout(com.lowagie.text.pdf.PdfPCell, com.lowagie.text.Rectangle, com.lowagie.text.pdf.PdfContentByte[])
*/
public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
float sp_left = spacing_left;
if (Float.isNaN(sp_left)) sp_left = 0f;
float sp_right = spacing_right;
if (Float.isNaN(sp_right)) sp_right = 0f;
float sp_top = spacing_top;
if (Float.isNaN(sp_top)) sp_top = 0f;
float sp_bottom = spacing_bottom;
if (Float.isNaN(sp_bottom)) sp_bottom = 0f;
Rectangle rect = new Rectangle(position.getLeft(sp_left), position.getBottom(sp_bottom), position.getRight(sp_right), position.getTop(sp_top));
rect.cloneNonPositionParameters(this);
canvases[PdfPTable.BACKGROUNDCANVAS].rectangle(rect);
rect.setBackgroundColor(null);
canvases[PdfPTable.LINECANVAS].rectangle(rect);
}
/** Sets the padding parameters if they are undefined.
* @param padding
*/
public void setPadding(float padding) {
if (Float.isNaN(padding_right)) {
setPadding_right(padding);
}
if (Float.isNaN(padding_left)) {
setPadding_left(padding);
}
if (Float.isNaN(padding_top)) {
setPadding_top(padding);
}
if (Float.isNaN(padding_bottom)) {
setPadding_bottom(padding);
}
}
/**
* @return Returns the colspan.
*/
public int getColspan() {
return colspan;
}
/**
* @param colspan The colspan to set.
*/
public void setColspan(int colspan) {
if (colspan > 0) this.colspan = colspan;
}
/**
* @return Returns the padding_bottom.
*/
public float getPadding_bottom() {
return padding_bottom;
}
/**
* @param padding_bottom The padding_bottom to set.
*/
public void setPadding_bottom(float padding_bottom) {
this.padding_bottom = padding_bottom;
}
/**
* @return Returns the padding_left.
*/
public float getPadding_left() {
return padding_left;
}
/**
* @param padding_left The padding_left to set.
*/
public void setPadding_left(float padding_left) {
this.padding_left = padding_left;
}
/**
* @return Returns the padding_right.
*/
public float getPadding_right() {
return padding_right;
}
/**
* @param padding_right The padding_right to set.
*/
public void setPadding_right(float padding_right) {
this.padding_right = padding_right;
}
/**
* @return Returns the padding_top.
*/
public float getPadding_top() {
return padding_top;
}
/**
* @param padding_top The padding_top to set.
*/
public void setPadding_top(float padding_top) {
this.padding_top = padding_top;
}
/**
* @return Returns the spacing.
*/
public float getSpacing_left() {
return spacing_left;
}
/**
* @return Returns the spacing.
*/
public float getSpacing_right() {
return spacing_right;
}
/**
* @return Returns the spacing.
*/
public float getSpacing_top() {
return spacing_top;
}
/**
* @return Returns the spacing.
*/
public float getSpacing_bottom() {
return spacing_bottom;
}
/**
* @param spacing The spacing to set.
*/
public void setSpacing(float spacing) {
this.spacing_left = spacing;
this.spacing_right = spacing;
this.spacing_top = spacing;
this.spacing_bottom = spacing;
}
/**
* @param spacing The spacing to set.
*/
public void setSpacing_left(float spacing) {
this.spacing_left = spacing;
}
/**
* @param spacing The spacing to set.
*/
public void setSpacing_right(float spacing) {
this.spacing_right = spacing;
}
/**
* @param spacing The spacing to set.
*/
public void setSpacing_top(float spacing) {
this.spacing_top = spacing;
}
/**
* @param spacing The spacing to set.
*/
public void setSpacing_bottom(float spacing) {
this.spacing_bottom = spacing;
}
/**
* @return Returns the cellgroup.
*/
public boolean isCellgroup() {
return cellgroup;
}
/**
* @param cellgroup The cellgroup to set.
*/
public void setCellgroup(boolean cellgroup) {
this.cellgroup = cellgroup;
}
/**
* @return Returns the horizontal alignment.
*/
public int getHorizontalAlignment() {
return horizontalAlignment;
}
/**
* @param horizontalAlignment The horizontalAlignment to set.
*/
public void setHorizontalAlignment(int horizontalAlignment) {
this.horizontalAlignment = horizontalAlignment;
}
/**
* @return Returns the vertical alignment.
*/
public int getVerticalAlignment() {
return verticalAlignment;
}
/**
* @param verticalAlignment The verticalAligment to set.
*/
public void setVerticalAlignment(int verticalAlignment) {
this.verticalAlignment = verticalAlignment;
}
/**
* @return Returns the width.
*/
public float getWidth() {
return width;
}
/**
* @param width The width to set.
*/
public void setWidth(float width) {
this.width = width;
}
/**
* @return Returns the widthpercentage.
*/
public float getWidthpercentage() {
return widthpercentage;
}
/**
* @param widthpercentage The widthpercentage to set.
*/
public void setWidthpercentage(float widthpercentage) {
this.widthpercentage = widthpercentage;
}
/**
* @return Returns the useAscender.
*/
public boolean isUseAscender() {
return useAscender;
}
/**
* @param useAscender The useAscender to set.
*/
public void setUseAscender(boolean useAscender) {
this.useAscender = useAscender;
}
/**
* @return Returns the useBorderPadding.
*/
public boolean isUseBorderPadding() {
return useBorderPadding;
}
/**
* @param useBorderPadding The useBorderPadding to set.
*/
public void setUseBorderPadding(boolean useBorderPadding) {
this.useBorderPadding = useBorderPadding;
}
/**
* @return Returns the useDescender.
*/
public boolean isUseDescender() {
return useDescender;
}
/**
* @param useDescender The useDescender to set.
*/
public void setUseDescender(boolean useDescender) {
this.useDescender = useDescender;
}
/**
* @return Returns the content.
*/
ArrayList getContent() {
return content;
}
/**
* @see com.lowagie.text.TextElementArray#add(java.lang.Object)
*/
public boolean add(Object o) {
try {
addElement((Element)o);
return true;
}
catch(ClassCastException e) {
return false;
}
catch(BadElementException e) {
throw new ExceptionConverter(e);
}
}
/**
* @see com.lowagie.text.Element#type()
*/
public int type() {
return Element.CELL;
}
} src/core/com/lowagie/text/SimpleTable.java 100644 0 0 24621 11154165267 16216 0 ustar 0 0 /*
* $Id: SimpleTable.java 3752 2009-03-04 18:02:40Z blowagie $
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.util.ArrayList;
import java.util.Iterator;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfPTableEvent;
/**
* Rectangle that can be used for Cells.
* This Rectangle is padded and knows how to draw itself in a PdfPTable or PdfPcellEvent.
*/
public class SimpleTable extends Rectangle implements PdfPTableEvent, TextElementArray {
/** the content of a Table. */
private ArrayList content = new ArrayList();
/** the width of the Table. */
private float width = 0f;
/** the widthpercentage of the Table. */
private float widthpercentage = 0f;
/** the spacing of the Cells. */
private float cellspacing;
/** the padding of the Cells. */
private float cellpadding;
/** the alignment of the table. */
private int alignment;
/**
* A RectangleCell is always constructed without any dimensions.
* Dimensions are defined after creation.
*/
public SimpleTable() {
super(0f, 0f, 0f, 0f);
setBorder(BOX);
setBorderWidth(2f);
}
/**
* Adds content to this object.
* @param element
* @throws BadElementException
*/
public void addElement(SimpleCell element) throws BadElementException {
if(!element.isCellgroup()) {
throw new BadElementException("You can't add cells to a table directly, add them to a row first.");
}
content.add(element);
}
/**
* Creates a Table object based on this TableAttributes object.
* @return a com.lowagie.text.Table object
* @throws BadElementException
*/
public Table createTable() throws BadElementException {
if (content.isEmpty()) throw new BadElementException("Trying to create a table without rows.");
SimpleCell row = (SimpleCell)content.get(0);
SimpleCell cell;
int columns = 0;
for (Iterator i = row.getContent().iterator(); i.hasNext(); ) {
cell = (SimpleCell)i.next();
columns += cell.getColspan();
}
float[] widths = new float[columns];
float[] widthpercentages = new float[columns];
Table table = new Table(columns);
table.setAlignment(alignment);
table.setSpacing(cellspacing);
table.setPadding(cellpadding);
table.cloneNonPositionParameters(this);
int pos;
for (Iterator rows = content.iterator(); rows.hasNext(); ) {
row = (SimpleCell)rows.next();
pos = 0;
for (Iterator cells = row.getContent().iterator(); cells.hasNext(); ) {
cell = (SimpleCell)cells.next();
table.addCell(cell.createCell(row));
if (cell.getColspan() == 1) {
if (cell.getWidth() > 0) widths[pos] = cell.getWidth();
if (cell.getWidthpercentage() > 0) widthpercentages[pos] = cell.getWidthpercentage();
}
pos += cell.getColspan();
}
}
float sumWidths = 0f;
for(int i = 0; i < columns; i++) {
if (widths[i] == 0) {
sumWidths = 0;
break;
}
sumWidths += widths[i];
}
if (sumWidths > 0) {
table.setWidth(sumWidths);
table.setLocked(true);
table.setWidths(widths);
}
else {
for(int i = 0; i < columns; i++) {
if (widthpercentages[i] == 0) {
sumWidths = 0;
break;
}
sumWidths += widthpercentages[i];
}
if (sumWidths > 0) {
table.setWidths(widthpercentages);
}
}
if (width > 0) {
table.setWidth(width);
table.setLocked(true);
}
else if (widthpercentage > 0) {
table.setWidth(widthpercentage);
}
return table;
}
/**
* Creates a PdfPTable object based on this TableAttributes object.
* @return a com.lowagie.text.pdf.PdfPTable object
* @throws DocumentException
*/
public PdfPTable createPdfPTable() throws DocumentException {
if (content.isEmpty()) throw new BadElementException("Trying to create a table without rows.");
SimpleCell row = (SimpleCell)content.get(0);
SimpleCell cell;
int columns = 0;
for (Iterator i = row.getContent().iterator(); i.hasNext(); ) {
cell = (SimpleCell)i.next();
columns += cell.getColspan();
}
float[] widths = new float[columns];
float[] widthpercentages = new float[columns];
PdfPTable table = new PdfPTable(columns);
table.setTableEvent(this);
table.setHorizontalAlignment(alignment);
int pos;
for (Iterator rows = content.iterator(); rows.hasNext(); ) {
row = (SimpleCell)rows.next();
pos = 0;
for (Iterator cells = row.getContent().iterator(); cells.hasNext(); ) {
cell = (SimpleCell)cells.next();
if (Float.isNaN(cell.getSpacing_left())) {
cell.setSpacing_left(cellspacing / 2f);
}
if (Float.isNaN(cell.getSpacing_right())) {
cell.setSpacing_right(cellspacing / 2f);
}
if (Float.isNaN(cell.getSpacing_top())) {
cell.setSpacing_top(cellspacing / 2f);
}
if (Float.isNaN(cell.getSpacing_bottom())) {
cell.setSpacing_bottom(cellspacing / 2f);
}
cell.setPadding(cellpadding);
table.addCell(cell.createPdfPCell(row));
if (cell.getColspan() == 1) {
if (cell.getWidth() > 0) widths[pos] = cell.getWidth();
if (cell.getWidthpercentage() > 0) widthpercentages[pos] = cell.getWidthpercentage();
}
pos += cell.getColspan();
}
}
float sumWidths = 0f;
for(int i = 0; i < columns; i++) {
if (widths[i] == 0) {
sumWidths = 0;
break;
}
sumWidths += widths[i];
}
if (sumWidths > 0) {
table.setTotalWidth(sumWidths);
table.setWidths(widths);
}
else {
for(int i = 0; i < columns; i++) {
if (widthpercentages[i] == 0) {
sumWidths = 0;
break;
}
sumWidths += widthpercentages[i];
}
if (sumWidths > 0) {
table.setWidths(widthpercentages);
}
}
if (width > 0) {
table.setTotalWidth(width);
}
if (widthpercentage > 0) {
table.setWidthPercentage(widthpercentage);
}
return table;
}
/**
* @see com.lowagie.text.pdf.PdfPTableEvent#tableLayout(com.lowagie.text.pdf.PdfPTable, float[][], float[], int, int, com.lowagie.text.pdf.PdfContentByte[])
*/
public void tableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases) {
float[] width = widths[0];
Rectangle rect = new Rectangle(width[0], heights[heights.length - 1], width[width.length - 1], heights[0]);
rect.cloneNonPositionParameters(this);
int bd = rect.getBorder();
rect.setBorder(Rectangle.NO_BORDER);
canvases[PdfPTable.BACKGROUNDCANVAS].rectangle(rect);
rect.setBorder(bd);
rect.setBackgroundColor(null);
canvases[PdfPTable.LINECANVAS].rectangle(rect);
}
/**
* @return Returns the cellpadding.
*/
public float getCellpadding() {
return cellpadding;
}
/**
* @param cellpadding The cellpadding to set.
*/
public void setCellpadding(float cellpadding) {
this.cellpadding = cellpadding;
}
/**
* @return Returns the cellspacing.
*/
public float getCellspacing() {
return cellspacing;
}
/**
* @param cellspacing The cellspacing to set.
*/
public void setCellspacing(float cellspacing) {
this.cellspacing = cellspacing;
}
/**
* @return Returns the alignment.
*/
public int getAlignment() {
return alignment;
}
/**
* @param alignment The alignment to set.
*/
public void setAlignment(int alignment) {
this.alignment = alignment;
}
/**
* @return Returns the width.
*/
public float getWidth() {
return width;
}
/**
* @param width The width to set.
*/
public void setWidth(float width) {
this.width = width;
}
/**
* @return Returns the widthpercentage.
*/
public float getWidthpercentage() {
return widthpercentage;
}
/**
* @param widthpercentage The widthpercentage to set.
*/
public void setWidthpercentage(float widthpercentage) {
this.widthpercentage = widthpercentage;
}
/**
* @see com.lowagie.text.Element#type()
*/
public int type() {
return Element.TABLE;
}
/**
* @see com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return true;
}
/**
* @see com.lowagie.text.TextElementArray#add(java.lang.Object)
*/
public boolean add(Object o) {
try {
addElement((SimpleCell)o);
return true;
}
catch(ClassCastException e) {
return false;
}
catch(BadElementException e) {
throw new ExceptionConverter(e);
}
}
} src/core/com/lowagie/text/SpecialSymbol.java 100644 0 0 16332 11215636056 16560 0 ustar 0 0 /*
* $Id: SpecialSymbol.java 3963 2009-06-11 11:45:49Z psoares33 $
*
* Copyright 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
/**
* This class contains the symbols that correspond with special symbols.
* Phrase
with Phrase.getInstance using a String
,
* this String
can contain special Symbols. These are characters with an int value
* between 913 and 937 (except 930) and between 945 and 969. With this class the value of the
* corresponding character of the Font Symbol, can be retrieved.
*
* @see Phrase
*
* @author Bruno Lowagie
* @author Evelyne De Cordier
*/
public class SpecialSymbol {
/**
* Returns the first occurrence of a special symbol in a String
.
*
* @param string a String
* @return an index of -1 if no special symbol was found
*/
public static int index(String string) {
int length = string.length();
for (int i = 0; i < length; i++) {
if (getCorrespondingSymbol(string.charAt(i)) != ' ') {
return i;
}
}
return -1;
}
/**
* Gets a chunk with a symbol character.
* @param c a character that has to be changed into a symbol
* @param font Font if there is no SYMBOL character corresponding with c
* @return a SYMBOL version of a character
*/
public static Chunk get(char c, Font font) {
char greek = SpecialSymbol.getCorrespondingSymbol(c);
if (greek == ' ') {
return new Chunk(String.valueOf(c), font);
}
Font symbol = new Font(Font.SYMBOL, font.getSize(), font.getStyle(), font.getColor());
String s = String.valueOf(greek);
return new Chunk(s, symbol);
}
/**
* Looks for the corresponding symbol in the font Symbol.
*
* @param c the original ASCII-char
* @return the corresponding symbol in font Symbol
*/
public static char getCorrespondingSymbol(char c) {
switch(c) {
case 913:
return 'A'; // ALFA
case 914:
return 'B'; // BETA
case 915:
return 'G'; // GAMMA
case 916:
return 'D'; // DELTA
case 917:
return 'E'; // EPSILON
case 918:
return 'Z'; // ZETA
case 919:
return 'H'; // ETA
case 920:
return 'Q'; // THETA
case 921:
return 'I'; // IOTA
case 922:
return 'K'; // KAPPA
case 923:
return 'L'; // LAMBDA
case 924:
return 'M'; // MU
case 925:
return 'N'; // NU
case 926:
return 'X'; // XI
case 927:
return 'O'; // OMICRON
case 928:
return 'P'; // PI
case 929:
return 'R'; // RHO
case 931:
return 'S'; // SIGMA
case 932:
return 'T'; // TAU
case 933:
return 'U'; // UPSILON
case 934:
return 'F'; // PHI
case 935:
return 'C'; // CHI
case 936:
return 'Y'; // PSI
case 937:
return 'W'; // OMEGA
case 945:
return 'a'; // alfa
case 946:
return 'b'; // beta
case 947:
return 'g'; // gamma
case 948:
return 'd'; // delta
case 949:
return 'e'; // epsilon
case 950:
return 'z'; // zeta
case 951:
return 'h'; // eta
case 952:
return 'q'; // theta
case 953:
return 'i'; // iota
case 954:
return 'k'; // kappa
case 955:
return 'l'; // lambda
case 956:
return 'm'; // mu
case 957:
return 'n'; // nu
case 958:
return 'x'; // xi
case 959:
return 'o'; // omicron
case 960:
return 'p'; // pi
case 961:
return 'r'; // rho
case 962:
return 'V'; // sigma
case 963:
return 's'; // sigma
case 964:
return 't'; // tau
case 965:
return 'u'; // upsilon
case 966:
return 'f'; // phi
case 967:
return 'c'; // chi
case 968:
return 'y'; // psi
case 969:
return 'w'; // omega
default:
return ' ';
}
}
} src/core/com/lowagie/text/SplitCharacter.java 100644 0 0 10376 11012562273 16716 0 ustar 0 0 /*
* $Id: SplitCharacter.java 3374 2008-05-12 18:42:56Z xlv $
*
* Copyright 2001, 2002 by Paulo Soares
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import com.lowagie.text.pdf.PdfChunk;
/** Interface for customizing the split character.
*
* @author Paulo Soares (psoares@consiste.pt)
*/
public interface SplitCharacter {
/**
* Returns true
if the character can split a line. The splitting implementation
* is free to look ahead or look behind characters to make a decision.
*
* public boolean isSplitCharacter(int start, int current, int end, char[] cc, PdfChunk[] ck) {
* char c;
* if (ck == null)
* c = cc[current];
* else
* c = (char) ck[Math.min(current, ck.length - 1)].getUnicodeEquivalent(cc[current]);
* if (c <= ' ' || c == '-') {
* return true;
* }
* if (c < 0x2e80)
* return false;
* return ((c >= 0x2e80 && c < 0xd7a0)
* || (c >= 0xf900 && c < 0xfb00)
* || (c >= 0xfe30 && c < 0xfe50)
* || (c >= 0xff61 && c < 0xffa0));
* }
*
* @param start the lower limit of cc
inclusive
* @param current the pointer to the character in cc
* @param end the upper limit of cc
exclusive
* @param cc an array of characters at least end
sized
* @param ck an array of PdfChunk
. The main use is to be able to call
* {@link PdfChunk#getUnicodeEquivalent(int)}. It may be null
* or shorter than end
. If null
no conversion takes place.
* If shorter than end
the last element is used
* @return true
if the character(s) can split a line
*/
public boolean isSplitCharacter(int start, int current, int end, char cc[], PdfChunk ck[]);
}
src/core/com/lowagie/text/Table.java 100644 0 0 150137 11154165267 15066 0 ustar 0 0 /*
* $Id: Table.java 3754 2009-03-04 19:05:20Z blowagie $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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/
*
* Some methods in this class were contributed by Geert Poels, Kris Jespers and
* Steve Ogryzek. Check the CVS repository.
*/
package com.lowagie.text;
import java.awt.Dimension;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Iterator;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
/**
* A Table
is a Rectangle
that contains Cell
s,
* ordered in some kind of matrix.
* endHeaders()
.
* GridBagLayout
.
*
* The result of this code is a table:
*
* // Remark: You MUST know the number of columns when constructing a Table.
* // The number of rows is not important.
* Table table = new Table(3);
* table.setBorderWidth(1);
* table.setBorderColor(new Color(0, 0, 255));
* table.setPadding(5);
* table.setSpacing(5);
* Cell cell = new Cell("header");
* cell.setHeader(true);
* cell.setColspan(3);
* table.addCell(cell);
* table.endHeaders();
* cell = new Cell("example cell with colspan 1 and rowspan 2");
* cell.setRowspan(2);
* cell.setBorderColor(new Color(255, 0, 0));
* table.addCell(cell);
* table.addCell("1.1");
* table.addCell("2.1");
* table.addCell("1.2");
* table.addCell("2.2");
* table.addCell("cell test1");
* cell = new Cell("big cell");
* cell.setRowspan(2);
* cell.setColspan(2);
* table.addCell(cell);
* table.addCell("cell test2");
*
*
*
* @see Rectangle
* @see Element
* @see Row
* @see Cell
*/
public class Table extends Rectangle implements LargeElement {
// membervariables
/** This is the number of columns in the
*
*
* header
*
*
*
*
* example cell with colspan 1 and rowspan 2
*
*
* 1.1
*
*
* 2.1
*
*
*
*
* 1.2
*
*
* 2.2
*
*
*
*
* cell test1
*
*
* big cell
*
*
*
*
* cell test2
*
* Table
. */
private int columns;
/** This is the list of Row
s. */
private ArrayList rows = new ArrayList();
/** The current Position in the table. */
private Point curPosition = new Point(0, 0);
/** This Empty Cell contains the DEFAULT layout of each Cell added with the method addCell(String content). */
private Cell defaultCell = new Cell(true);
/** This is the number of the last row of the table headers. */
private int lastHeaderRow = -1;
/** This is the horizontal alignment. */
private int alignment = Element.ALIGN_CENTER;
/** This is cellpadding. */
private float cellpadding;
/** This is cellspacing. */
private float cellspacing;
/** This is the width of the table (in percent of the available space). */
private float width = 80;
/** Is the width a percentage (false) or an absolute width (true)? */
private boolean locked = false;
/** This is an array containing the widths (in percentages) of every column. */
private float[] widths;
/** Boolean to track if a table was inserted (to avoid unnecessary computations afterwards) */
private boolean mTableInserted = false;
/**
* Boolean to automatically fill empty cells before a table is rendered
* (takes CPU so may be set to false in case of certainty)
*/
protected boolean autoFillEmptyCells = false;
/** If true this table may not be split over two pages. */
boolean tableFitsPage = false;
/** If true cells may not be split over two pages. */
boolean cellsFitPage = false;
/** This is the offset of the table. */
float offset = Float.NaN;
/** if you want to generate tables the old way, set this value to false. */
protected boolean convert2pdfptable = false;
/**
* Indicates if this is the first time the section was added.
* @since iText 2.0.8
*/
protected boolean notAddedYet = true;
/**
* Indicates if the PdfPTable is complete once added to the document.
* @since iText 2.0.8
*/
protected boolean complete = true;
// constructors
/**
* Constructs a Table
with a certain number of columns.
*
* @param columns The number of columns in the table
* @throws BadElementException if the creator was called with less than 1 column
*/
public Table(int columns) throws BadElementException {
this(columns, 1);
}
/**
* Constructs a Table
with a certain number of columns
* and a certain number of Row
s.
*
* @param columns The number of columns in the table
* @param rows The number of rows
* @throws BadElementException if the creator was called with less than 1 column
*/
public Table(int columns, int rows) throws BadElementException {
// a Rectangle is create with BY DEFAULT a border with a width of 1
super(0, 0, 0, 0);
setBorder(BOX);
setBorderWidth(1);
defaultCell.setBorder(BOX);
// a table should have at least 1 column
if (columns <= 0) {
throw new BadElementException("A table should have at least 1 column.");
}
this.columns = columns;
// a certain number of rows are created
for (int i = 0; i < rows; i++) {
this.rows.add(new Row(columns));
}
curPosition = new Point(0, 0);
// the DEFAULT widths are calculated
widths = new float[columns];
float width = 100f / columns;
for (int i = 0; i < columns; i++) {
widths[i] = width;
}
}
/**
* Copy constructor (shallow copy).
*/
public Table(Table t) {
super(0, 0, 0, 0);
this.cloneNonPositionParameters(t);
this.columns = t.columns;
this.rows = t.rows;
this.curPosition = t.curPosition;
this.defaultCell = t.defaultCell;
this.lastHeaderRow = t.lastHeaderRow;
this.alignment = t.alignment;
this.cellpadding = t.cellpadding;
this.cellspacing = t.cellspacing;
this.width = t.width;
this.widths = t.widths;
this.autoFillEmptyCells = t.autoFillEmptyCells;
this.tableFitsPage = t.tableFitsPage;
this.cellsFitPage = t.cellsFitPage;
this.offset = t.offset;
this.convert2pdfptable = t.convert2pdfptable;
}
// implementation of the Element-methods
/**
* Processes the element by adding it (or the different parts) to an
* ElementListener
.
*
* @param listener an ElementListener
* @return true
if the element was processed successfully
*/
public boolean process(ElementListener listener) {
try {
return listener.add(this);
}
catch(DocumentException de) {
return false;
}
}
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return Element.TABLE;
}
/**
* Gets all the chunks in this element.
*
* @return an ArrayList
*/
public ArrayList getChunks() {
return new ArrayList();
}
/**
* @see com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return true;
}
// getters and setters
/**
* Gets the number of columns.
*
* @return a value
*/
public int getColumns() {
return columns;
}
/**
* Gets the number of rows in this Table
.
*
* @return the number of rows in this Table
*/
public int size() {
return rows.size();
}
/**
* Gets the dimension of this table
*
* @return dimension
*/
public Dimension getDimension() {
return new Dimension(columns, size());
}
/**
* Gets the default layout of the Table.
* @return a cell with all the defaults
* @since 2.0.7
*/
public Cell getDefaultCell() {
return defaultCell;
}
/**
* Sets the default layout of the Table to
* the provided Cell
* @param value a cell with all the defaults
* @since 2.0.7
*/
public void setDefaultCell(Cell value) {
defaultCell = value;
}
/**
* Gets the last number of the rows that contain headers.
*
* @return a rownumber
*/
public int getLastHeaderRow() {
return this.lastHeaderRow;
}
/**
* Sets the horizontal alignment.
*
* @param value the new value
*/
public void setLastHeaderRow(int value) {
lastHeaderRow = value;
}
/**
* Marks the last row of the table headers.
*
* @return the number of the last row of the table headers
*/
public int endHeaders() {
lastHeaderRow = curPosition.x - 1;
return lastHeaderRow;
}
/**
* Gets the horizontal alignment.
*
* @return a value
*/
public int getAlignment() {
return alignment;
}
/**
* Sets the horizontal alignment.
*
* @param value the new value
*/
public void setAlignment(int value) {
alignment = value;
}
/**
* Sets the alignment of this paragraph.
*
* @param alignment the new alignment as a String
*/
public void setAlignment(String alignment) {
if (ElementTags.ALIGN_LEFT.equalsIgnoreCase(alignment)) {
this.alignment = Element.ALIGN_LEFT;
return;
}
if (ElementTags.RIGHT.equalsIgnoreCase(alignment)) {
this.alignment = Element.ALIGN_RIGHT;
return;
}
this.alignment = Element.ALIGN_CENTER;
}
/**
* Gets the cellpadding.
*
* @return a value
*/
public float getPadding() {
return cellpadding;
}
/**
* Sets the cellpadding.
*
* @param value the new value
*/
public void setPadding(float value) {
cellpadding = value;
}
/**
* Gets the cellspacing.
*
* @return a value
*/
public float getSpacing() {
return cellspacing;
}
/**
* Sets the cellspacing.
*
* @param value the new value
*/
public void setSpacing(float value) {
cellspacing = value;
}
/**
* Enables/disables automatic insertion of empty cells before table is rendered. (default = false)
* As some people may want to create a table, fill only a couple of the cells and don't bother with
* investigating which empty ones need to be added, this default behavior may be very welcome.
* Disabling is recommended to increase speed. (empty cells should be added through extra code then)
*
* @param aDoAutoFill enable/disable autofill
*/
public void setAutoFillEmptyCells(boolean aDoAutoFill) {
autoFillEmptyCells = aDoAutoFill;
}
/**
* Gets the table width (a percentage).
*
* @return the table width
*/
public float getWidth() {
return width;
}
/**
* Sets the width of this table (in percentage of the available space).
*
* @param width the width
*/
public void setWidth(float width) {
this.width = width;
}
/**
* @return the locked
*/
public boolean isLocked() {
return locked;
}
/**
* @param locked the locked to set
*/
public void setLocked(boolean locked) {
this.locked = locked;
}
/**
* Gets the proportional widths of the columns in this Table
.
*
* @return the proportional widths of the columns in this Table
*/
public float[] getProportionalWidths() {
return widths;
}
/**
* Sets the widths of the different columns (percentages).
*
* The widths will be: a width of 50% for the first column,
* 25% for the second and third column.
*
* @param widths an array with values
* @throws BadElementException
*/
public void setWidths(float[] widths) throws BadElementException {
if (widths.length != columns) {
throw new BadElementException("Wrong number of columns.");
}
// The sum of all values is 100%
float hundredPercent = 0;
for (int i = 0; i < columns; i++) {
hundredPercent += widths[i];
}
// The different percentages are calculated
float width;
this.widths[columns - 1] = 100;
for (int i = 0; i < columns - 1; i++) {
width = (100.0f * widths[i]) / hundredPercent;
this.widths[i] = width;
this.widths[columns - 1] -= width;
}
}
/**
* Sets the widths of the different columns (percentages).
*
* float[] widths = {2, 1, 1};
* table.setWidths(widths)
*
Table
has to fit a page.
*
* @return true if the table may not be split
*/
public boolean isTableFitsPage() {
return tableFitsPage;
}
/**
* Allows you to control when a page break occurs.
* Table
have to fit a page.
*
* @return true if the cells may not be split
*/
public boolean isCellsFitPage() {
return cellsFitPage;
}
/**
* Allows you to control when a page break occurs.
* Cell
to the Table
at a certain row and column.
*
* @param aCell The Cell
to add
* @param row The row where the Cell
will be added
* @param column The column where the Cell
will be added
* @throws BadElementException
*/
public void addCell(Cell aCell, int row, int column) throws BadElementException {
addCell(aCell, new Point(row,column));
}
/**
* Adds a Cell
to the Table
at a certain location.
*
* @param aCell The Cell
to add
* @param aLocation The location where the Cell
will be added
* @throws BadElementException
*/
public void addCell(Cell aCell, Point aLocation) throws BadElementException {
if (aCell == null) throw new NullPointerException("addCell - cell has null-value");
if (aLocation == null) throw new NullPointerException("addCell - point has null-value");
if (aCell.isTable()) insertTable((Table)aCell.getElements().next(), aLocation);
if (aLocation.x < 0) throw new BadElementException("row coordinate of location must be >= 0");
if ((aLocation.y <= 0) && (aLocation.y > columns)) throw new BadElementException("column coordinate of location must be >= 0 and < nr of columns");
if (!isValidLocation(aCell, aLocation)) throw new BadElementException("Adding a cell at the location (" + aLocation.x + "," + aLocation.y + ") with a colspan of " + aCell.getColspan() + " and a rowspan of " + aCell.getRowspan() + " is illegal (beyond boundaries/overlapping).");
if (aCell.getBorder() == UNDEFINED) aCell.setBorder(defaultCell.getBorder());
aCell.fill();
placeCell(rows, aCell, aLocation);
setCurrentLocationToNextValidPosition(aLocation);
}
/**
* Adds a Cell
to the Table
.
*
* @param cell a Cell
*/
public void addCell(Cell cell) {
try {
addCell(cell, curPosition);
}
catch(BadElementException bee) {
// don't add the cell
}
}
/**
* Adds a Cell
to the Table
.
* addCell(Cell cell)
.
* The Phrase
will be converted to a Cell
.
*
* @param content a Phrase
* @throws BadElementException this should never happen
*/
public void addCell(Phrase content) throws BadElementException {
addCell(content, curPosition);
}
/**
* Adds a Cell
to the Table
.
* addCell(Cell cell, Point location)
.
* The Phrase
will be converted to a Cell
.
*
* @param content a Phrase
* @param location a Point
* @throws BadElementException this should never happen
*/
public void addCell(Phrase content, Point location) throws BadElementException {
Cell cell = new Cell(content);
cell.setBorder(defaultCell.getBorder());
cell.setBorderWidth(defaultCell.getBorderWidth());
cell.setBorderColor(defaultCell.getBorderColor());
cell.setBackgroundColor(defaultCell.getBackgroundColor());
cell.setHorizontalAlignment(defaultCell.getHorizontalAlignment());
cell.setVerticalAlignment(defaultCell.getVerticalAlignment());
cell.setColspan(defaultCell.getColspan());
cell.setRowspan(defaultCell.getRowspan());
addCell(cell, location);
}
/**
* Adds a Cell
to the Table
.
* addCell(Cell cell)
.
* The String
will be converted to a Cell
.
*
* @param content a String
* @throws BadElementException this should never happen
*/
public void addCell(String content) throws BadElementException {
addCell(new Phrase(content), curPosition);
}
/**
* Adds a Cell
to the Table
.
* addCell(Cell cell, Point location)
.
* The String
will be converted to a Cell
.
*
* @param content a String
* @param location a Point
* @throws BadElementException this should never happen
*/
public void addCell(String content, Point location) throws BadElementException {
addCell(new Phrase(content), location);
}
/**
* To put a table within the existing table at the current position
* generateTable will of course re-arrange the widths of the columns.
*
* @param aTable the table you want to insert
*/
public void insertTable(Table aTable) {
if (aTable == null) throw new NullPointerException("insertTable - table has null-value");
insertTable(aTable, curPosition);
}
/**
* To put a table within the existing table at the given position
* generateTable will of course re-arrange the widths of the columns.
*
* @param aTable The Table
to add
* @param row The row where the Cell
will be added
* @param column The column where the Cell
will be added
*/
public void insertTable(Table aTable, int row, int column) {
if (aTable == null) throw new NullPointerException("insertTable - table has null-value");
insertTable(aTable, new Point(row, column));
}
/**
* To put a table within the existing table at the given position
* generateTable will of course re-arrange the widths of the columns.
*
* @param aTable the table you want to insert
* @param aLocation a Point
*/
public void insertTable(Table aTable, Point aLocation) {
if (aTable == null) throw new NullPointerException("insertTable - table has null-value");
if (aLocation == null) throw new NullPointerException("insertTable - point has null-value");
mTableInserted = true;
aTable.complete();
if (aLocation.y > columns) {
throw new IllegalArgumentException("insertTable -- wrong columnposition("+ aLocation.y + ") of location; max =" + columns);
}
int rowCount = aLocation.x + 1 - rows.size();
int i = 0;
if ( rowCount > 0 ) { //create new rows ?
for (; i < rowCount; i++) {
rows.add(new Row(columns));
}
}
((Row) rows.get(aLocation.x)).setElement(aTable,aLocation.y);
setCurrentLocationToNextValidPosition(aLocation);
}
/**
* Gives you the possibility to add columns.
*
* @param aColumns the number of columns to add
*/
public void addColumns(int aColumns) {
ArrayList newRows = new ArrayList(rows.size());
int newColumns = columns + aColumns;
Row row;
for (int i = 0; i < rows.size(); i++) {
row = new Row(newColumns);
for (int j = 0; j < columns; j++) {
row.setElement(((Row) rows.get(i)).getCell(j) ,j);
}
for (int j = columns; j < newColumns && i < curPosition.x; j++) {
row.setElement(null, j);
}
newRows.add(row);
}
// applied 1 column-fix; last column needs to have a width of 0
float [] newWidths = new float[newColumns];
System.arraycopy(widths, 0, newWidths, 0, columns);
for (int j = columns; j < newColumns ; j++) {
newWidths[j] = 0;
}
columns = newColumns;
widths = newWidths;
rows = newRows;
}
/**
* Deletes a column in this table.
*
* @param column the number of the column that has to be deleted
* @throws BadElementException
*/
public void deleteColumn(int column) throws BadElementException {
float newWidths[] = new float[--columns];
System.arraycopy(widths, 0, newWidths, 0, column);
System.arraycopy(widths, column + 1, newWidths, column, columns - column);
setWidths(newWidths);
System.arraycopy(widths, 0, newWidths, 0, columns);
widths = newWidths;
Row row;
int size = rows.size();
for (int i = 0; i < size; i++) {
row = (Row) rows.get(i);
row.deleteColumn(column);
rows.set(i, row);
}
if (column == columns) {
curPosition.setLocation(curPosition.x+1, 0);
}
}
/**
* Deletes a row.
*
* @param row the number of the row to delete
* @return boolean true
if the row was deleted; false
if not
*/
public boolean deleteRow(int row) {
if (row < 0 || row >= rows.size()) {
return false;
}
rows.remove(row);
curPosition.setLocation(curPosition.x-1, curPosition.y);
return true;
}
/**
* Deletes all rows in this table.
* (contributed by dperezcar@fcc.es)
*/
public void deleteAllRows() {
rows.clear();
rows.add(new Row(columns));
curPosition.setLocation(0, 0);
lastHeaderRow = -1;
}
/**
* Deletes the last row in this table.
*
* @return boolean true
if the row was deleted; false
if not
*/
public boolean deleteLastRow() {
return deleteRow(rows.size() - 1);
}
/**
* Will fill empty cells with valid blank Cell
s
*/
public void complete() {
if (mTableInserted) {
mergeInsertedTables(); // integrate tables in the table
mTableInserted = false;
}
if (autoFillEmptyCells) {
fillEmptyMatrixCells();
}
}
// private helper classes
/**
* returns the element at the position row, column
* (Cast to Cell or Table)
*
* @param row
* @param column
* @return dimension
* @since 2.1.0 (was made private in 2.0.3)
*/
public Object getElement(int row, int column) {
return ((Row) rows.get(row)).getCell(column);
}
/**
* Integrates all added tables and recalculates column widths.
*/
private void mergeInsertedTables() {
int i=0, j=0;
float [] lNewWidths = null;
int [] lDummyWidths = new int[columns]; // to keep track in how many new cols this one will be split
float[][] lDummyColumnWidths = new float[columns][]; // bugfix Tony Copping
int [] lDummyHeights = new int[rows.size()]; // to keep track in how many new rows this one will be split
ArrayList newRows = null;
boolean isTable=false;
int lTotalRows = 0, lTotalColumns = 0;
int lNewMaxRows = 0, lNewMaxColumns = 0;
Table lDummyTable = null;
// first we'll add new columns when needed
// check one column at a time, find maximum needed nr of cols
// Search internal tables and find one with max columns
for (j=0; j < columns; j++) {
lNewMaxColumns = 1; // value to hold in how many columns the current one will be split
float [] tmpWidths = null;
for (i=0; i < rows.size(); i++) {
if ( Table.class.isInstance(((Row) rows.get(i)).getCell(j)) ) {
isTable=true;
lDummyTable = ((Table) ((Row) rows.get(i)).getCell(j));
if( tmpWidths == null) {
tmpWidths = lDummyTable.widths;
lNewMaxColumns=tmpWidths.length;
}
else {
int cols = lDummyTable.getDimension().width;
float [] tmpWidthsN = new float[ cols * tmpWidths.length];
float tpW=0, btW=0, totW=0;
int tpI=0, btI=0, totI=0;
tpW+=tmpWidths[0];
btW+=lDummyTable.widths[0];
while( tpICell
'fits' the table.
*
*
* @param aCell the cell that has to be checked
* @param aLocation the location where the cell has to be placed
* @return true if the location was valid
*/
private boolean isValidLocation(Cell aCell, Point aLocation) {
// rowspan not beyond last column
if ( aLocation.x < rows.size() ) // if false : new location is already at new, not-yet-created area so no check
{
if ((aLocation.y + aCell.getColspan()) > columns) {
return false;
}
int difx = ((rows.size() - aLocation.x) > aCell.getRowspan()) ? aCell.getRowspan() : rows.size() - aLocation.x;
int dify = ((columns - aLocation.y) > aCell.getColspan()) ? aCell.getColspan() : columns - aLocation.y;
// no other content at cells targeted by rowspan/colspan
for (int i=aLocation.x; i < (aLocation.x + difx); i++) {
for (int j=aLocation.y; j < (aLocation.y + dify); j++) {
if (((Row) rows.get(i)).isReserved(j)) {
return false;
}
}
}
}
else {
if ((aLocation.y + aCell.getColspan()) > columns) {
return false;
}
}
return true;
}
/**
* Sets the unset cell properties to be the table defaults.
*
* @param aCell The cell to set to table defaults as necessary.
*/
private void assumeTableDefaults(Cell aCell) {
if (aCell.getBorder() == Rectangle.UNDEFINED) {
aCell.setBorder(defaultCell.getBorder());
}
if (aCell.getBorderWidth() == Rectangle.UNDEFINED) {
aCell.setBorderWidth(defaultCell.getBorderWidth());
}
if (aCell.getBorderColor() == null) {
aCell.setBorderColor(defaultCell.getBorderColor());
}
if (aCell.getBackgroundColor() == null) {
aCell.setBackgroundColor(defaultCell.getBackgroundColor());
}
if (aCell.getHorizontalAlignment() == Element.ALIGN_UNDEFINED) {
aCell.setHorizontalAlignment(defaultCell.getHorizontalAlignment());
}
if (aCell.getVerticalAlignment() == Element.ALIGN_UNDEFINED) {
aCell.setVerticalAlignment(defaultCell.getVerticalAlignment());
}
}
/**
* Inserts a Cell in a cell-array and reserves cells defined by row-/colspan.
*
* @param someRows some rows
* @param aCell the cell that has to be inserted
* @param aPosition the position where the cell has to be placed
*/
private void placeCell(ArrayList someRows, Cell aCell, Point aPosition) {
int i;
Row row = null;
int rowCount = aPosition.x + aCell.getRowspan() - someRows.size();
assumeTableDefaults(aCell);
if ( (aPosition.x + aCell.getRowspan()) > someRows.size() ) {
for (i = 0; i < rowCount; i++) {
row = new Row(columns);
someRows.add(row);
}
}
// reserve cell in rows below
for (i = aPosition.x + 1; i < (aPosition.x + aCell.getRowspan()); i++) {
if ( !((Row) someRows.get(i)).reserve(aPosition.y, aCell.getColspan())) {
// should be impossible to come here :-)
throw new RuntimeException("addCell - error in reserve");
}
}
row = (Row) someRows.get(aPosition.x);
row.addElement(aCell, aPosition.y);
}
/**
* Sets current col/row to valid(empty) pos after addCell/Table
* @param aLocation a location in the Table
*/
private void setCurrentLocationToNextValidPosition(Point aLocation) {
// set latest location to next valid position
int i, j;
i = aLocation.x;
j = aLocation.y;
do {
if ( (j + 1) == columns ) { // goto next row
i++;
j = 0;
}
else {
j++;
}
}
while (
(i < rows.size()) && (j < columns) && (((Row) rows.get(i)).isReserved(j))
);
curPosition = new Point(i, j);
}
// public helper methods
/**
* Gets an array with the positions of the borders between every column.
* Iterator
of all the Row
s.
*
* @return an Iterator
*/
public Iterator iterator() {
return rows.iterator();
}
/**
* Create a PdfPTable based on this Table object.
* @return a PdfPTable object
* @throws BadElementException
*/
public PdfPTable createPdfPTable() throws BadElementException {
if (!convert2pdfptable) {
throw new BadElementException("No error, just an old style table");
}
setAutoFillEmptyCells(true);
complete();
PdfPTable pdfptable = new PdfPTable(widths);
pdfptable.setComplete(complete);
if (isNotAddedYet())
pdfptable.setSkipFirstHeader(true);
SimpleTable t_evt = new SimpleTable();
t_evt.cloneNonPositionParameters(this);
t_evt.setCellspacing(cellspacing);
pdfptable.setTableEvent(t_evt);
pdfptable.setHeaderRows(lastHeaderRow + 1);
pdfptable.setSplitLate(cellsFitPage);
pdfptable.setKeepTogether(tableFitsPage);
if (!Float.isNaN(offset)) {
pdfptable.setSpacingBefore(offset);
}
pdfptable.setHorizontalAlignment(alignment);
if (locked) {
pdfptable.setTotalWidth(width);
pdfptable.setLockedWidth(true);
}
else {
pdfptable.setWidthPercentage(width);
}
Row row;
for (Iterator iterator = iterator(); iterator.hasNext(); ) {
row = (Row) iterator.next();
Element cell;
PdfPCell pcell;
for (int i = 0; i < row.getColumns(); i++) {
if ((cell = (Element)row.getCell(i)) != null) {
if (cell instanceof Table) {
pcell = new PdfPCell(((Table)cell).createPdfPTable());
}
else if (cell instanceof Cell) {
pcell = ((Cell)cell).createPdfPCell();
pcell.setPadding(cellpadding + cellspacing / 2f);
SimpleCell c_evt = new SimpleCell(SimpleCell.CELL);
c_evt.cloneNonPositionParameters((Cell)cell);
c_evt.setSpacing(cellspacing * 2f);
pcell.setCellEvent(c_evt);
}
else {
pcell = new PdfPCell();
}
pdfptable.addCell(pcell);
}
}
}
return pdfptable;
}
/**
* Indicates if this is the first time the section is added.
* @since iText2.0.8
* @return true if the section wasn't added yet
*/
public boolean isNotAddedYet() {
return notAddedYet;
}
/**
* Sets the indication if the section was already added to
* the document.
* @since iText2.0.8
* @param notAddedYet
*/
public void setNotAddedYet(boolean notAddedYet) {
this.notAddedYet = notAddedYet;
}
/**
* @since iText 2.0.8
* @see com.lowagie.text.LargeElement#flushContent()
*/
public void flushContent() {
this.setNotAddedYet(false);
ArrayList headerrows = new ArrayList();
for (int i = 0; i < getLastHeaderRow() + 1; i++) {
headerrows.add(rows.get(i));
}
rows = headerrows;
}
/**
* @since iText 2.0.8
* @see com.lowagie.text.LargeElement#isComplete()
*/
public boolean isComplete() {
return complete;
}
/**
* @since iText 2.0.8
* @see com.lowagie.text.LargeElement#setComplete(boolean)
*/
public void setComplete(boolean complete) {
this.complete = complete;
}
/**
* Gets the default layout of the Table.
* @return a cell with all the defaults
* @deprecated As of iText 2.0.7, replaced by {@link #getDefaultCell()},
* scheduled for removal at 2.2.0
*/
public Cell getDefaultLayout() {
return getDefaultCell();
}
/**
* Sets the default layout of the Table to
* the provided Cell
* @param value a cell with all the defaults
* @deprecated As of iText 2.0.7, replaced by {@link #setDefaultCell(Cell)},
* scheduled for removal at 2.2.0
*/
public void setDefaultLayout(Cell value) {
defaultCell = value;
}
}
src/core/com/lowagie/text/TextElementArray.java 100644 0 0 5754 11012562273 17227 0 ustar 0 0 /*
* $Id: TextElementArray.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright (c) 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
/**
* Interface for a text element to which other objects can be added.
*
* @see Phrase
* @see Paragraph
* @see Section
* @see ListItem
* @see Chapter
* @see Anchor
* @see Cell
*/
public interface TextElementArray extends Element {
/**
* Adds an object to the TextElementArray
.
*
* @param o an object that has to be added
* @return true
if the addition succeeded; false
otherwise
*/
public boolean add(Object o);
} src/core/com/lowagie/text/Utilities.java 100644 0 0 26345 11036112746 15766 0 ustar 0 0 /*
* $Id: Utilities.java 3514 2008-06-27 09:26:36Z blowagie $
*
* Copyright 2007 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Set;
import com.lowagie.text.pdf.PRTokeniser;
/**
* A collection of convenience methods that were present in many different iText
* classes.
*/
public class Utilities {
/**
* Gets the keys of a Hashtable
*
* @param table
* a Hashtable
* @return the keyset of a Hashtable (or an empty set if table is null)
*/
public static Set getKeySet(Hashtable table) {
return (table == null) ? Collections.EMPTY_SET : table.keySet();
}
/**
* Utility method to extend an array.
*
* @param original
* the original array or null
* @param item
* the item to be added to the array
* @return a new array with the item appended
*/
public static Object[][] addToArray(Object original[][], Object item[]) {
if (original == null) {
original = new Object[1][];
original[0] = item;
return original;
} else {
Object original2[][] = new Object[original.length + 1][];
System.arraycopy(original, 0, original2, 0, original.length);
original2[original.length] = item;
return original2;
}
}
/**
* Checks for a true/false value of a key in a Properties object.
* @param attributes
* @param key
* @return a true/false value of a key in a Properties object
*/
public static boolean checkTrueOrFalse(Properties attributes, String key) {
return "true".equalsIgnoreCase(attributes.getProperty(key));
}
/**
* Unescapes an URL. All the "%xx" are replaced by the 'xx' hex char value.
* @param src the url to unescape
* @return the unescaped value
*/
public static String unEscapeURL(String src) {
StringBuffer bf = new StringBuffer();
char[] s = src.toCharArray();
for (int k = 0; k < s.length; ++k) {
char c = s[k];
if (c == '%') {
if (k + 2 >= s.length) {
bf.append(c);
continue;
}
int a0 = PRTokeniser.getHex(s[k + 1]);
int a1 = PRTokeniser.getHex(s[k + 2]);
if (a0 < 0 || a1 < 0) {
bf.append(c);
continue;
}
bf.append((char)(a0 * 16 + a1));
k += 2;
}
else
bf.append(c);
}
return bf.toString();
}
/**
* This method makes a valid URL from a given filename.
* InputStream.skip()
* -method that doesn't seem to work properly for big values of size
*
.
*
* @param is
* the InputStream
* @param size
* the number of bytes to skip
* @throws IOException
*/
static public void skip(InputStream is, int size) throws IOException {
long n;
while (size > 0) {
n = is.skip(size);
if (n <= 0)
break;
size -= n;
}
}
/**
* Measurement conversion from millimeters to points.
* @param value a value in millimeters
* @return a value in points
* @since 2.1.2
*/
public static final float millimetersToPoints(float value) {
return inchesToPoints(millimetersToInches(value));
}
/**
* Measurement conversion from millimeters to inches.
* @param value a value in millimeters
* @return a value in inches
* @since 2.1.2
*/
public static final float millimetersToInches(float value) {
return value / 25.4f;
}
/**
* Measurement conversion from points to millimeters.
* @param value a value in points
* @return a value in millimeters
* @since 2.1.2
*/
public static final float pointsToMillimeters(float value) {
return inchesToMillimeters(pointsToInches(value));
}
/**
* Measurement conversion from points to inches.
* @param value a value in points
* @return a value in inches
* @since 2.1.2
*/
public static final float pointsToInches(float value) {
return value / 72f;
}
/**
* Measurement conversion from inches to millimeters.
* @param value a value in inches
* @return a value in millimeters
* @since 2.1.2
*/
public static final float inchesToMillimeters(float value) {
return value * 25.4f;
}
/**
* Measurement conversion from inches to points.
* @param value a value in inches
* @return a value in points
* @since 2.1.2
*/
public static final float inchesToPoints(float value) {
return value * 72f;
}
/**
* Check if the value of a character belongs to a certain interval
* that indicates it's the higher part of a surrogate pair.
* @param c the character
* @return true if the character belongs to the interval
* @since 2.1.2
*/
public static boolean isSurrogateHigh(char c) {
return c >= '\ud800' && c <= '\udbff';
}
/**
* Check if the value of a character belongs to a certain interval
* that indicates it's the lower part of a surrogate pair.
* @param c the character
* @return true if the character belongs to the interval
* @since 2.1.2
*/
public static boolean isSurrogateLow(char c) {
return c >= '\udc00' && c <= '\udfff';
}
/**
* Checks if two subsequent characters in a String are
* are the higher and the lower character in a surrogate
* pair (and therefore eligible for conversion to a UTF 32 character).
* @param text the String with the high and low surrogate characters
* @param idx the index of the 'high' character in the pair
* @return true if the characters are surrogate pairs
* @since 2.1.2
*/
public static boolean isSurrogatePair(String text, int idx) {
if (idx < 0 || idx > text.length() - 2)
return false;
return isSurrogateHigh(text.charAt(idx)) && isSurrogateLow(text.charAt(idx + 1));
}
/**
* Checks if two subsequent characters in a character array are
* are the higher and the lower character in a surrogate
* pair (and therefore eligible for conversion to a UTF 32 character).
* @param text the character array with the high and low surrogate characters
* @param idx the index of the 'high' character in the pair
* @return true if the characters are surrogate pairs
* @since 2.1.2
*/
public static boolean isSurrogatePair(char[] text, int idx) {
if (idx < 0 || idx > text.length - 2)
return false;
return isSurrogateHigh(text[idx]) && isSurrogateLow(text[idx + 1]);
}
/**
* Returns the code point of a UTF32 character corresponding with
* a high and a low surrogate value.
* @param highSurrogate the high surrogate value
* @param lowSurrogate the low surrogate value
* @return a code point value
* @since 2.1.2
*/
public static int convertToUtf32(char highSurrogate, char lowSurrogate) {
return (((highSurrogate - 0xd800) * 0x400) + (lowSurrogate - 0xdc00)) + 0x10000;
}
/**
* Converts a unicode character in a character array to a UTF 32 code point value.
* @param text a character array that has the unicode character(s)
* @param idx the index of the 'high' character
* @return the code point value
* @since 2.1.2
*/
public static int convertToUtf32(char[] text, int idx) {
return (((text[idx] - 0xd800) * 0x400) + (text[idx + 1] - 0xdc00)) + 0x10000;
}
/**
* Converts a unicode character in a String to a UTF32 code point value
* @param text a String that has the unicode character(s)
* @param idx the index of the 'high' character
* @return the codepoint value
* @since 2.1.2
*/
public static int convertToUtf32(String text, int idx) {
return (((text.charAt(idx) - 0xd800) * 0x400) + (text.charAt(idx + 1) - 0xdc00)) + 0x10000;
}
/**
* Converts a UTF32 code point value to a String with the corresponding character(s).
* @param codePoint a Unicode value
* @return the corresponding characters in a String
* @since 2.1.2
*/
public static String convertFromUtf32(int codePoint) {
if (codePoint < 0x10000)
return Character.toString((char)codePoint);
codePoint -= 0x10000;
return new String(new char[]{(char)((codePoint / 0x400) + 0xd800), (char)((codePoint % 0x400) + 0xdc00)});
}
}
src/core/com/lowagie/text/ZapfDingbatsList.java 100644 0 0 10522 11000354131 17174 0 ustar 0 0 /*
* Copyright 2003 by Michael Niedermair.
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
/**
*
* A special-version of LIST
which use zapfdingbats-letters.
*
* @see com.lowagie.text.List
* @author Michael Niedermair and Bruno Lowagie
*/
public class ZapfDingbatsList extends List {
/**
* char-number in zapfdingbats
*/
protected int zn;
/**
* Creates a ZapfDingbatsList
*
* @param zn a char-number
*/
public ZapfDingbatsList(int zn) {
super(true);
this.zn = zn;
float fontsize = symbol.getFont().getSize();
symbol.setFont(FontFactory.getFont(FontFactory.ZAPFDINGBATS, fontsize, Font.NORMAL));
postSymbol = " ";
}
/**
* Creates a ZapfDingbatsList
*
* @param zn a char-number
* @param symbolIndent indent
*/
public ZapfDingbatsList(int zn, int symbolIndent) {
super(true, symbolIndent);
this.zn = zn;
float fontsize = symbol.getFont().getSize();
symbol.setFont(FontFactory.getFont(FontFactory.ZAPFDINGBATS, fontsize, Font.NORMAL));
postSymbol = " ";
}
/**
* set the char-number
* @param zn a char-number
*/
public void setCharNumber(int zn) {
this.zn = zn;
}
/**
* get the char-number
*
* @return char-number
*/
public int getCharNumber() {
return zn;
}
/**
* Adds an Object
to the List
.
*
* @param o the object to add.
* @return true if adding the object succeeded
*/
public boolean add(Object o) {
if (o instanceof ListItem) {
ListItem item = (ListItem) o;
Chunk chunk = new Chunk(preSymbol, symbol.getFont());
chunk.append(String.valueOf((char)zn));
chunk.append(postSymbol);
item.setListSymbol(chunk);
item.setIndentationLeft(symbolIndent, autoindent);
item.setIndentationRight(0);
list.add(item);
} else if (o instanceof List) {
List nested = (List) o;
nested.setIndentationLeft(nested.getIndentationLeft() + symbolIndent);
first--;
return list.add(nested);
} else if (o instanceof String) {
return this.add(new ListItem((String) o));
}
return false;
}
}
src/core/com/lowagie/text/ZapfDingbatsNumberList.java 100644 0 0 11267 11000354131 20354 0 ustar 0 0 /*
* Copyright 2003 by Michael Niedermair.
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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;
/**
*
* A special-version of LIST
which use zapfdingbats-numbers (1..10).
*
* @see com.lowagie.text.List
* @author Michael Niedermair and Bruno Lowagie
*/
public class ZapfDingbatsNumberList extends List {
/**
* which type
*/
protected int type;
/**
* Creates a ZapdDingbatsNumberList
* @param type the type of list
*/
public ZapfDingbatsNumberList(int type) {
super(true);
this.type = type;
float fontsize = symbol.getFont().getSize();
symbol.setFont(FontFactory.getFont(FontFactory.ZAPFDINGBATS, fontsize, Font.NORMAL));
postSymbol = " ";
}
/**
* Creates a ZapdDingbatsNumberList
* @param type the type of list
* @param symbolIndent indent
*/
public ZapfDingbatsNumberList(int type, int symbolIndent) {
super(true, symbolIndent);
this.type = type;
float fontsize = symbol.getFont().getSize();
symbol.setFont(FontFactory.getFont(FontFactory.ZAPFDINGBATS, fontsize, Font.NORMAL));
postSymbol = " ";
}
/**
* set the type
*
* @param type
*/
public void setType(int type) {
this.type = type;
}
/**
* get the type
*
* @return char-number
*/
public int getType() {
return type;
}
/**
* Adds an Object
to the List
.
*
* @param o the object to add.
* @return true if adding the object succeeded
*/
public boolean add(Object o) {
if (o instanceof ListItem) {
ListItem item = (ListItem) o;
Chunk chunk = new Chunk(preSymbol, symbol.getFont());
switch (type ) {
case 0:
chunk.append(String.valueOf((char)(first + list.size() + 171)));
break;
case 1:
chunk.append(String.valueOf((char)(first + list.size() + 181)));
break;
case 2:
chunk.append(String.valueOf((char)(first + list.size() + 191)));
break;
default:
chunk.append(String.valueOf((char)(first + list.size() + 201)));
}
chunk.append(postSymbol);
item.setListSymbol(chunk);
item.setIndentationLeft(symbolIndent, autoindent);
item.setIndentationRight(0);
list.add(item);
} else if (o instanceof List) {
List nested = (List) o;
nested.setIndentationLeft(nested.getIndentationLeft() + symbolIndent);
first--;
return list.add(nested);
} else if (o instanceof String) {
return this.add(new ListItem((String) o));
}
return false;
}
}
src/core/com/lowagie/text/apache_license.txt 100644 0 0 26411 11000354131 16611 0 ustar 0 0 Some files use code from different Apache projects.
The source code of these files contains the appropriate copyright notices
as described in the Appendix of http://www.apache.org/licenses/LICENSE-2.0
This is a copy of the text that can be found at that specific URL:
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License.
Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License.
Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution.
You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
* You must give any other recipients of the Work or
Derivative Works a copy of this License; and
* You must cause any modified files to carry prominent notices
stating that You changed the files; and
* You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
* If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions.
Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks.
This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty.
Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability.
In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability.
While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. src/core/com/lowagie/text/exceptions/BadPasswordException.java 100644 0 0 6125 11154165264 22242 0 ustar 0 0 /*
* $Id: BadPasswordException.java 3665 2009-01-26 22:32:15Z xlv $
*
* Copyright 2007 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.exceptions;
import java.io.IOException;
/**
* Typed exception used when opening an existing PDF document.
* Gets thrown when the document isn't a valid PDF document.
* @since 2.1.5 It was written for iText 2.0.8, but moved to another package
*/
public class BadPasswordException extends IOException {
/** Serial Version UID. */
private static final long serialVersionUID = -4333706268155063964L;
/**
* Creates an exception saying the user password was incorrect.
*/
public BadPasswordException(String message) {
super(message);
}
}
src/core/com/lowagie/text/exceptions/IllegalPdfSyntaxException.java 100644 0 0 5776 11213370067 23251 0 ustar 0 0 /*
* $Id: IllegalPdfSyntaxException.java 3820 2009-03-25 10:30:01Z blowagie $
*
* Copyright 2009 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-2009 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000-2009 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.exceptions;
/**
* Typed exception used when creating PDF syntax that isn't valid.
* @since 2.1.6
*/
public class IllegalPdfSyntaxException extends IllegalArgumentException {
/** Serial version ID */
private static final long serialVersionUID = -643024246596031671L;
/**
* Creates an exception saying the PDF syntax isn't correct.
* @param message some extra info about the exception
*/
public IllegalPdfSyntaxException(String message) {
super(message);
}
}
src/core/com/lowagie/text/exceptions/InvalidPdfException.java 100644 0 0 6103 11154165264 22045 0 ustar 0 0 /*
* $Id: InvalidPdfException.java 3665 2009-01-26 22:32:15Z xlv $
*
* Copyright 2009 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-2009 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000-2009 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.exceptions;
import java.io.IOException;
/**
* Typed exception used when opening an existing PDF document.
* Gets thrown when the document isn't a valid PDF document.
* @since 2.1.5
*/
public class InvalidPdfException extends IOException {
/** a serial version UID */
private static final long serialVersionUID = -2319614911517026938L;
/**
* Creates an instance of a NoPdfException.
* @param message the reason why the document isn't a PDF document according to iText.
*/
public InvalidPdfException(String message) {
super(message);
}
}
src/core/com/lowagie/text/exceptions/UnsupportedPdfException.java 100644 0 0 6525 11154165264 23017 0 ustar 0 0 /*
* $Id: UnsupportedPdfException.java 3665 2009-01-26 22:32:15Z xlv $
*
* Copyright 2009 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-2009 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000-2009 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.exceptions;
/**
* Typed exception used when opening an existing PDF document.
* Gets thrown when the document isn't a valid PDF document according to iText,
* but it's different from the InvalidPdfException in the sense that it may
* be an iText limitation (most of the times it isn't but you might have
* bumped into something that has been added to the PDF specs, but that isn't
* supported in iText yet).
* @since 2.1.5
*/
public class UnsupportedPdfException extends InvalidPdfException {
/** a serial version UID */
private static final long serialVersionUID = 2180764250839096628L;
/**
* Creates an instance of an UnsupportedPdfException.
* @param message the reason why the document isn't a PDF document according to iText.
*/
public UnsupportedPdfException(String message) {
super(message);
}
}
src/core/com/lowagie/text/factories/ElementFactory.java 100644 0 0 46412 11036112743 20705 0 ustar 0 0 /*
* $Id: ElementFactory.java 3528 2008-07-07 14:46:09Z Howard_s $
*
* Copyright 2007 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.
*
* Contributions by:
* Lubos Strapko
*
* 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.factories;
import java.awt.Color;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;
import com.lowagie.text.Anchor;
import com.lowagie.text.Annotation;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.ChapterAutoNumber;
import com.lowagie.text.Chunk;
import com.lowagie.text.ElementTags;
import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Image;
import com.lowagie.text.List;
import com.lowagie.text.ListItem;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Section;
import com.lowagie.text.Table;
import com.lowagie.text.Utilities;
import com.lowagie.text.html.Markup;
/**
* This class is able to create Element objects based on a list of properties.
*/
public class ElementFactory {
/**
* Creates a Chunk object based on a list of properties.
* @param attributes
* @return a Chunk
*/
public static Chunk getChunk(Properties attributes) {
Chunk chunk = new Chunk();
chunk.setFont(FontFactory.getFont(attributes));
String value;
value = attributes.getProperty(ElementTags.ITEXT);
if (value != null) {
chunk.append(value);
}
value = attributes.getProperty(ElementTags.LOCALGOTO);
if (value != null) {
chunk.setLocalGoto(value);
}
value = attributes.getProperty(ElementTags.REMOTEGOTO);
if (value != null) {
String page = attributes.getProperty(ElementTags.PAGE);
if (page != null) {
chunk.setRemoteGoto(value, Integer.parseInt(page));
} else {
String destination = attributes
.getProperty(ElementTags.DESTINATION);
if (destination != null) {
chunk.setRemoteGoto(value, destination);
}
}
}
value = attributes.getProperty(ElementTags.LOCALDESTINATION);
if (value != null) {
chunk.setLocalDestination(value);
}
value = attributes.getProperty(ElementTags.SUBSUPSCRIPT);
if (value != null) {
chunk.setTextRise(Float.parseFloat(value + "f"));
}
value = attributes.getProperty(Markup.CSS_KEY_VERTICALALIGN);
if (value != null && value.endsWith("%")) {
float p = Float.parseFloat(value.substring(0, value.length() - 1)
+ "f") / 100f;
chunk.setTextRise(p * chunk.getFont().getSize());
}
value = attributes.getProperty(ElementTags.GENERICTAG);
if (value != null) {
chunk.setGenericTag(value);
}
value = attributes.getProperty(ElementTags.BACKGROUNDCOLOR);
if (value != null) {
chunk.setBackground(Markup.decodeColor(value));
}
return chunk;
}
/**
* Creates a Phrase object based on a list of properties.
* @param attributes
* @return a Phrase
*/
public static Phrase getPhrase(Properties attributes) {
Phrase phrase = new Phrase();
phrase.setFont(FontFactory.getFont(attributes));
String value;
value = attributes.getProperty(ElementTags.LEADING);
if (value != null) {
phrase.setLeading(Float.parseFloat(value + "f"));
}
value = attributes.getProperty(Markup.CSS_KEY_LINEHEIGHT);
if (value != null) {
phrase.setLeading(Markup.parseLength(value,
Markup.DEFAULT_FONT_SIZE));
}
value = attributes.getProperty(ElementTags.ITEXT);
if (value != null) {
Chunk chunk = new Chunk(value);
if ((value = attributes.getProperty(ElementTags.GENERICTAG)) != null) {
chunk.setGenericTag(value);
}
phrase.add(chunk);
}
return phrase;
}
/**
* Creates an Anchor object based on a list of properties.
* @param attributes
* @return an Anchor
*/
public static Anchor getAnchor(Properties attributes) {
Anchor anchor = new Anchor(getPhrase(attributes));
String value;
value = attributes.getProperty(ElementTags.NAME);
if (value != null) {
anchor.setName(value);
}
value = (String) attributes.remove(ElementTags.REFERENCE);
if (value != null) {
anchor.setReference(value);
}
return anchor;
}
/**
* Creates a Paragraph object based on a list of properties.
* @param attributes
* @return a Paragraph
*/
public static Paragraph getParagraph(Properties attributes) {
Paragraph paragraph = new Paragraph(getPhrase(attributes));
String value;
value = attributes.getProperty(ElementTags.ALIGN);
if (value != null) {
paragraph.setAlignment(value);
}
value = attributes.getProperty(ElementTags.INDENTATIONLEFT);
if (value != null) {
paragraph.setIndentationLeft(Float.parseFloat(value + "f"));
}
value = attributes.getProperty(ElementTags.INDENTATIONRIGHT);
if (value != null) {
paragraph.setIndentationRight(Float.parseFloat(value + "f"));
}
return paragraph;
}
/**
* Creates a ListItem object based on a list of properties.
* @param attributes
* @return a ListItem
*/
public static ListItem getListItem(Properties attributes) {
ListItem item = new ListItem(getParagraph(attributes));
return item;
}
/**
* Creates a List object based on a list of properties.
* @param attributes
* @return the List
*/
public static List getList(Properties attributes) {
List list = new List();
list.setNumbered(Utilities.checkTrueOrFalse(attributes,
ElementTags.NUMBERED));
list.setLettered(Utilities.checkTrueOrFalse(attributes,
ElementTags.LETTERED));
list.setLowercase(Utilities.checkTrueOrFalse(attributes,
ElementTags.LOWERCASE));
list.setAutoindent(Utilities.checkTrueOrFalse(attributes,
ElementTags.AUTO_INDENT_ITEMS));
list.setAlignindent(Utilities.checkTrueOrFalse(attributes,
ElementTags.ALIGN_INDENTATION_ITEMS));
String value;
value = attributes.getProperty(ElementTags.FIRST);
if (value != null) {
char character = value.charAt(0);
if (Character.isLetter(character)) {
list.setFirst(character);
} else {
list.setFirst(Integer.parseInt(value));
}
}
value = attributes.getProperty(ElementTags.LISTSYMBOL);
if (value != null) {
list
.setListSymbol(new Chunk(value, FontFactory
.getFont(attributes)));
}
value = attributes.getProperty(ElementTags.INDENTATIONLEFT);
if (value != null) {
list.setIndentationLeft(Float.parseFloat(value + "f"));
}
value = attributes.getProperty(ElementTags.INDENTATIONRIGHT);
if (value != null) {
list.setIndentationRight(Float.parseFloat(value + "f"));
}
value = attributes.getProperty(ElementTags.SYMBOLINDENT);
if (value != null) {
list.setSymbolIndent(Float.parseFloat(value));
}
return list;
}
/**
* Creates a Cell object based on a list of properties.
* @param attributes
* @return a Cell
*/
public static Cell getCell(Properties attributes) {
Cell cell = new Cell();
String value;
cell.setHorizontalAlignment(attributes
.getProperty(ElementTags.HORIZONTALALIGN));
cell.setVerticalAlignment(attributes
.getProperty(ElementTags.VERTICALALIGN));
value = attributes.getProperty(ElementTags.WIDTH);
if (value != null) {
cell.setWidth(value);
}
value = attributes.getProperty(ElementTags.COLSPAN);
if (value != null) {
cell.setColspan(Integer.parseInt(value));
}
value = attributes.getProperty(ElementTags.ROWSPAN);
if (value != null) {
cell.setRowspan(Integer.parseInt(value));
}
value = attributes.getProperty(ElementTags.LEADING);
if (value != null) {
cell.setLeading(Float.parseFloat(value + "f"));
}
cell.setHeader(Utilities.checkTrueOrFalse(attributes,
ElementTags.HEADER));
if (Utilities.checkTrueOrFalse(attributes, ElementTags.NOWRAP)) {
cell.setMaxLines(1);
}
setRectangleProperties(cell, attributes);
return cell;
}
/**
* Creates an Table object based on a list of properties.
* @param attributes
* @return a Table
*/
public static Table getTable(Properties attributes) {
String value;
Table table;
try {
value = attributes.getProperty(ElementTags.WIDTHS);
if (value != null) {
StringTokenizer widthTokens = new StringTokenizer(value, ";");
ArrayList values = new ArrayList();
while (widthTokens.hasMoreTokens()) {
values.add(widthTokens.nextToken());
}
table = new Table(values.size());
float[] widths = new float[table.getColumns()];
for (int i = 0; i < values.size(); i++) {
value = (String) values.get(i);
widths[i] = Float.parseFloat(value + "f");
}
table.setWidths(widths);
} else {
value = attributes.getProperty(ElementTags.COLUMNS);
try {
table = new Table(Integer.parseInt(value));
} catch (Exception e) {
table = new Table(1);
}
}
table.setBorder(Table.BOX);
table.setBorderWidth(1);
table.getDefaultCell().setBorder(Table.BOX);
value = attributes.getProperty(ElementTags.LASTHEADERROW);
if (value != null) {
table.setLastHeaderRow(Integer.parseInt(value));
}
value = attributes.getProperty(ElementTags.ALIGN);
if (value != null) {
table.setAlignment(value);
}
value = attributes.getProperty(ElementTags.CELLSPACING);
if (value != null) {
table.setSpacing(Float.parseFloat(value + "f"));
}
value = attributes.getProperty(ElementTags.CELLPADDING);
if (value != null) {
table.setPadding(Float.parseFloat(value + "f"));
}
value = attributes.getProperty(ElementTags.OFFSET);
if (value != null) {
table.setOffset(Float.parseFloat(value + "f"));
}
value = attributes.getProperty(ElementTags.WIDTH);
if (value != null) {
if (value.endsWith("%"))
table.setWidth(Float.parseFloat(value.substring(0, value
.length() - 1)
+ "f"));
else {
table.setWidth(Float.parseFloat(value + "f"));
table.setLocked(true);
}
}
table.setTableFitsPage(Utilities.checkTrueOrFalse(attributes,
ElementTags.TABLEFITSPAGE));
table.setCellsFitPage(Utilities.checkTrueOrFalse(attributes,
ElementTags.CELLSFITPAGE));
table.setConvert2pdfptable(Utilities.checkTrueOrFalse(attributes,
ElementTags.CONVERT2PDFP));
setRectangleProperties(table, attributes);
return table;
} catch (BadElementException e) {
throw new ExceptionConverter(e);
}
}
/**
* Sets some Rectangle properties (for a Cell, Table,...).
*/
private static void setRectangleProperties(Rectangle rect,
Properties attributes) {
String value;
value = attributes.getProperty(ElementTags.BORDERWIDTH);
if (value != null) {
rect.setBorderWidth(Float.parseFloat(value + "f"));
}
int border = 0;
if (Utilities.checkTrueOrFalse(attributes, ElementTags.LEFT)) {
border |= Rectangle.LEFT;
}
if (Utilities.checkTrueOrFalse(attributes, ElementTags.RIGHT)) {
border |= Rectangle.RIGHT;
}
if (Utilities.checkTrueOrFalse(attributes, ElementTags.TOP)) {
border |= Rectangle.TOP;
}
if (Utilities.checkTrueOrFalse(attributes, ElementTags.BOTTOM)) {
border |= Rectangle.BOTTOM;
}
rect.setBorder(border);
String r = attributes.getProperty(ElementTags.RED);
String g = attributes.getProperty(ElementTags.GREEN);
String b = attributes.getProperty(ElementTags.BLUE);
if (r != null || g != null || b != null) {
int red = 0;
int green = 0;
int blue = 0;
if (r != null)
red = Integer.parseInt(r);
if (g != null)
green = Integer.parseInt(g);
if (b != null)
blue = Integer.parseInt(b);
rect.setBorderColor(new Color(red, green, blue));
} else {
rect.setBorderColor(Markup.decodeColor(attributes
.getProperty(ElementTags.BORDERCOLOR)));
}
r = (String) attributes.remove(ElementTags.BGRED);
g = (String) attributes.remove(ElementTags.BGGREEN);
b = (String) attributes.remove(ElementTags.BGBLUE);
value = attributes.getProperty(ElementTags.BACKGROUNDCOLOR);
if (r != null || g != null || b != null) {
int red = 0;
int green = 0;
int blue = 0;
if (r != null)
red = Integer.parseInt(r);
if (g != null)
green = Integer.parseInt(g);
if (b != null)
blue = Integer.parseInt(b);
rect.setBackgroundColor(new Color(red, green, blue));
} else if (value != null) {
rect.setBackgroundColor(Markup.decodeColor(value));
} else {
value = attributes.getProperty(ElementTags.GRAYFILL);
if (value != null) {
rect.setGrayFill(Float.parseFloat(value + "f"));
}
}
}
/**
* Creates a ChapterAutoNumber object based on a list of properties.
* @param attributes
* @return a Chapter
*/
public static ChapterAutoNumber getChapter(Properties attributes) {
ChapterAutoNumber chapter = new ChapterAutoNumber("");
setSectionParameters(chapter, attributes);
return chapter;
}
/**
* Creates a Section object based on a list of properties.
* @param attributes
* @return a Section
*/
public static Section getSection(Section parent, Properties attributes) {
Section section = parent.addSection("");
setSectionParameters(section, attributes);
return section;
}
/**
* Helper method to create a Chapter/Section object.
* @param attributes
*/
private static void setSectionParameters(Section section,
Properties attributes) {
String value;
value = attributes.getProperty(ElementTags.NUMBERDEPTH);
if (value != null) {
section.setNumberDepth(Integer.parseInt(value));
}
value = attributes.getProperty(ElementTags.INDENT);
if (value != null) {
section.setIndentation(Float.parseFloat(value + "f"));
}
value = attributes.getProperty(ElementTags.INDENTATIONLEFT);
if (value != null) {
section.setIndentationLeft(Float.parseFloat(value + "f"));
}
value = attributes.getProperty(ElementTags.INDENTATIONRIGHT);
if (value != null) {
section.setIndentationRight(Float.parseFloat(value + "f"));
}
}
/**
* Creates an Image object based on a list of properties.
* @param attributes
* @return an Image
*/
public static Image getImage(Properties attributes)
throws BadElementException, MalformedURLException, IOException {
String value;
value = attributes.getProperty(ElementTags.URL);
if (value == null)
throw new MalformedURLException("The URL of the image is missing.");
Image image = Image.getInstance(value);
value = attributes.getProperty(ElementTags.ALIGN);
int align = 0;
if (value != null) {
if (ElementTags.ALIGN_LEFT.equalsIgnoreCase(value))
align |= Image.LEFT;
else if (ElementTags.ALIGN_RIGHT.equalsIgnoreCase(value))
align |= Image.RIGHT;
else if (ElementTags.ALIGN_MIDDLE.equalsIgnoreCase(value))
align |= Image.MIDDLE;
}
if ("true".equalsIgnoreCase(attributes
.getProperty(ElementTags.UNDERLYING)))
align |= Image.UNDERLYING;
if ("true".equalsIgnoreCase(attributes
.getProperty(ElementTags.TEXTWRAP)))
align |= Image.TEXTWRAP;
image.setAlignment(align);
value = attributes.getProperty(ElementTags.ALT);
if (value != null) {
image.setAlt(value);
}
String x = attributes.getProperty(ElementTags.ABSOLUTEX);
String y = attributes.getProperty(ElementTags.ABSOLUTEY);
if ((x != null) && (y != null)) {
image.setAbsolutePosition(Float.parseFloat(x + "f"), Float
.parseFloat(y + "f"));
}
value = attributes.getProperty(ElementTags.PLAINWIDTH);
if (value != null) {
image.scaleAbsoluteWidth(Float.parseFloat(value + "f"));
}
value = attributes.getProperty(ElementTags.PLAINHEIGHT);
if (value != null) {
image.scaleAbsoluteHeight(Float.parseFloat(value + "f"));
}
value = attributes.getProperty(ElementTags.ROTATION);
if (value != null) {
image.setRotation(Float.parseFloat(value + "f"));
}
return image;
}
/**
* Creates an Annotation object based on a list of properties.
* @param attributes
* @return an Annotation
*/
public static Annotation getAnnotation(Properties attributes) {
float llx = 0, lly = 0, urx = 0, ury = 0;
String value;
value = attributes.getProperty(ElementTags.LLX);
if (value != null) {
llx = Float.parseFloat(value + "f");
}
value = attributes.getProperty(ElementTags.LLY);
if (value != null) {
lly = Float.parseFloat(value + "f");
}
value = attributes.getProperty(ElementTags.URX);
if (value != null) {
urx = Float.parseFloat(value + "f");
}
value = attributes.getProperty(ElementTags.URY);
if (value != null) {
ury = Float.parseFloat(value + "f");
}
String title = attributes.getProperty(ElementTags.TITLE);
String text = attributes.getProperty(ElementTags.CONTENT);
if (title != null || text != null) {
return new Annotation(title, text, llx, lly, urx, ury);
}
value = attributes.getProperty(ElementTags.URL);
if (value != null) {
return new Annotation(llx, lly, urx, ury, value);
}
value = attributes.getProperty(ElementTags.NAMED);
if (value != null) {
return new Annotation(llx, lly, urx, ury, Integer.parseInt(value));
}
String file = attributes.getProperty(ElementTags.FILE);
String destination = attributes.getProperty(ElementTags.DESTINATION);
String page = (String) attributes.remove(ElementTags.PAGE);
if (file != null) {
if (destination != null) {
return new Annotation(llx, lly, urx, ury, file, destination);
}
if (page != null) {
return new Annotation(llx, lly, urx, ury, file, Integer
.parseInt(page));
}
}
return new Annotation("", "", llx, lly, urx, ury);
}
} src/core/com/lowagie/text/factories/GreekAlphabetFactory.java 100644 0 0 11616 11012562263 22010 0 ustar 0 0 /*
* $Id: GreekAlphabetFactory.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 2007 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.factories;
import com.lowagie.text.SpecialSymbol;
/**
* This class can produce String combinations representing a number built with
* Greek letters (from alpha to omega, then alpha alpha, alpha beta, alpha gamma).
* We are aware of the fact that the original Greek numbering is different;
* See http://www.cogsci.indiana.edu/farg/harry/lan/grknum.htm#ancient
* but this isn't implemented yet; the main reason being the fact that we
* need a font that has the obsolete Greek characters qoppa and sampi.
*
* @since 2.0.7 (was called GreekNumberFactory in earlier versions)
*/
public class GreekAlphabetFactory {
/**
* Changes an int into a lower case Greek letter combination.
* @param index the original number
* @return the letter combination
*/
public static final String getString(int index) {
return getString(index, true);
}
/**
* Changes an int into a lower case Greek letter combination.
* @param index the original number
* @return the letter combination
*/
public static final String getLowerCaseString(int index) {
return getString(index);
}
/**
* Changes an int into a upper case Greek letter combination.
* @param index the original number
* @return the letter combination
*/
public static final String getUpperCaseString(int index) {
return getString(index).toUpperCase();
}
/**
* Changes an int into a Greek letter combination.
* @param index the original number
* @return the letter combination
*/
public static final String getString(int index, boolean lowercase) {
if (index < 1) return "";
index--;
int bytes = 1;
int start = 0;
int symbols = 24;
while(index >= symbols + start) {
bytes++;
start += symbols;
symbols *= 24;
}
int c = index - start;
char[] value = new char[bytes];
while(bytes > 0) {
bytes--;
value[bytes] = (char)(c % 24);
if (value[bytes] > 16) value[bytes]++;
value[bytes] += (lowercase ? 945 : 913);
value[bytes] = SpecialSymbol.getCorrespondingSymbol(value[bytes]);
c /= 24;
}
return String.valueOf(value);
}
/**
* Test this class using this main method.
*/
public static void main(String[] args) {
for (int i = 1; i < 1000; i++) {
System.out.println(getString(i));
}
}
}
src/core/com/lowagie/text/factories/RomanAlphabetFactory.java 100644 0 0 10753 11012562263 22030 0 ustar 0 0 /*
* $Id: RomanAlphabetFactory.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 2007 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.factories;
/**
* This class can produce String combinations representing a number.
* "a" to "z" represent 1 to 26, "AA" represents 27, "AB" represents 28,
* and so on; "ZZ" is followed by "AAA".
*/
public class RomanAlphabetFactory {
/**
* Translates a positive integer (not equal to zero)
* into a String using the letters 'a' to 'z';
* 1 = a, 2 = b, ..., 26 = z, 27 = aa, 28 = ab,...
*/
public static final String getString(int index) {
if (index < 1) throw new NumberFormatException(
"You can't translate a negative number into an alphabetical value.");
index--;
int bytes = 1;
int start = 0;
int symbols = 26;
while(index >= symbols + start) {
bytes++;
start += symbols;
symbols *= 26;
}
int c = index - start;
char[] value = new char[bytes];
while(bytes > 0) {
value[--bytes] = (char)( 'a' + (c % 26));
c /= 26;
}
return new String(value);
}
/**
* Translates a positive integer (not equal to zero)
* into a String using the letters 'a' to 'z';
* 1 = a, 2 = b, ..., 26 = z, 27 = aa, 28 = ab,...
*/
public static final String getLowerCaseString(int index) {
return getString(index);
}
/**
* Translates a positive integer (not equal to zero)
* into a String using the letters 'A' to 'Z';
* 1 = A, 2 = B, ..., 26 = Z, 27 = AA, 28 = AB,...
*/
public static final String getUpperCaseString(int index) {
return getString(index).toUpperCase();
}
/**
* Translates a positive integer (not equal to zero)
* into a String using the letters 'a' to 'z'
* (a = 1, b = 2, ..., z = 26, aa = 27, ab = 28,...).
*/
public static final String getString(int index, boolean lowercase) {
if (lowercase) {
return getLowerCaseString(index);
}
else {
return getUpperCaseString(index);
}
}
/**
* Test this class using this main method.
*/
public static void main(String[] args) {
for (int i = 1; i < 32000; i++) {
System.out.println(getString(i));
}
}
} src/core/com/lowagie/text/factories/RomanNumberFactory.java 100644 0 0 13066 11012562263 21540 0 ustar 0 0 /*
* $Id: RomanNumberFactory.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 2007 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.factories;
/**
* This class can produce String combinations representing a roman number.
*/
public class RomanNumberFactory {
/**
* Helper class for Roman Digits
*/
private static class RomanDigit {
/** part of a roman number */
public char digit;
/** value of the roman digit */
public int value;
/** can the digit be used as a prefix */
public boolean pre;
/**
* Constructs a roman digit
* @param digit the roman digit
* @param value the value
* @param pre can it be used as a prefix
*/
RomanDigit(char digit, int value, boolean pre) {
this.digit = digit;
this.value = value;
this.pre = pre;
}
}
/**
* Array with Roman digits.
*/
private static final RomanDigit[] roman = {
new RomanDigit('m', 1000, false),
new RomanDigit('d', 500, false),
new RomanDigit('c', 100, true),
new RomanDigit('l', 50, false),
new RomanDigit('x', 10, true),
new RomanDigit('v', 5, false),
new RomanDigit('i', 1, true)
};
/**
* Changes an int into a lower case roman number.
* @param index the original number
* @return the roman number (lower case)
*/
public static final String getString(int index) {
StringBuffer buf = new StringBuffer();
// lower than 0 ? Add minus
if (index < 0) {
buf.append('-');
index = -index;
}
// greater than 3000
if (index > 3000) {
buf.append('|');
buf.append(getString(index / 1000));
buf.append('|');
// remainder
index = index - (index / 1000) * 1000;
}
// number between 1 and 3000
int pos = 0;
while (true) {
// loop over the array with values for m-d-c-l-x-v-i
RomanDigit dig = roman[pos];
// adding as many digits as we can
while (index >= dig.value) {
buf.append(dig.digit);
index -= dig.value;
}
// we have the complete number
if (index <= 0) {
break;
}
// look for the next digit that can be used in a special way
int j = pos;
while (!roman[++j].pre);
// does the special notation apply?
if (index + roman[j].value >= dig.value) {
buf.append(roman[j].digit).append(dig.digit);
index -= dig.value - roman[j].value;
}
pos++;
}
return buf.toString();
}
/**
* Changes an int into a lower case roman number.
* @param index the original number
* @return the roman number (lower case)
*/
public static final String getLowerCaseString(int index) {
return getString(index);
}
/**
* Changes an int into an upper case roman number.
* @param index the original number
* @return the roman number (lower case)
*/
public static final String getUpperCaseString(int index) {
return getString(index).toUpperCase();
}
/**
* Changes an int into a roman number.
* @param index the original number
* @return the roman number (lower case)
*/
public static final String getString(int index, boolean lowercase) {
if (lowercase) {
return getLowerCaseString(index);
}
else {
return getUpperCaseString(index);
}
}
/**
* Test this class using this main method.
*/
public static void main(String[] args) {
for (int i = 1; i < 2000; i++) {
System.out.println(getString(i));
}
}
} src/core/com/lowagie/text/html/HtmlEncoder.java 100644 0 0 16400 11012562264 17150 0 ustar 0 0 /*
* $Id: HtmlEncoder.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.html;
import java.awt.Color;
import com.lowagie.text.Element;
/**
* This class converts a String
to the HTML-format of a String.
* String
, each character is examined:
*
*
*
* (with xxx = the value of the character)
*
*
*
* (with xxx = the value of the character)
*
* String htmlPresentation = HtmlEncoder.encode("Marie-Thérèse Sørensen");
*
String
to the HTML-format of this String
.
*
* @param string The String
to convert
* @return a String
*/
public static String encode(String string) {
int n = string.length();
char character;
StringBuffer buffer = new StringBuffer();
// loop over all the characters of the String.
for (int i = 0; i < n; i++) {
character = string.charAt(i);
// the Htmlcode of these characters are added to a StringBuffer one by one
if (character < 256) {
buffer.append(htmlCode[character]);
}
else {
// Improvement posted by Joachim Eyrich
buffer.append("").append((int)character).append(';');
}
}
return buffer.toString();
}
/**
* Converts a Color
into a HTML representation of this Color
.
*
* @param color the Color
that has to be converted.
* @return the HTML representation of this Tags
-class maps several XHTML-tags to iText-objects.
*/
public class HtmlTagMap extends HashMap {
private static final long serialVersionUID = 5287430058473705350L;
/**
* Constructs an HtmlTagMap.
*/
public HtmlTagMap() {
super();
HtmlPeer peer;
peer = new HtmlPeer(ElementTags.ITEXT, HtmlTags.HTML);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.PHRASE, HtmlTags.SPAN);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.CHUNK, HtmlTags.CHUNK);
peer.addAlias(ElementTags.FONT, HtmlTags.FONT);
peer.addAlias(ElementTags.SIZE, HtmlTags.SIZE);
peer.addAlias(ElementTags.COLOR, HtmlTags.COLOR);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.ANCHOR, HtmlTags.ANCHOR);
peer.addAlias(ElementTags.NAME, HtmlTags.NAME);
peer.addAlias(ElementTags.REFERENCE, HtmlTags.REFERENCE);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.PARAGRAPH, HtmlTags.PARAGRAPH);
peer.addAlias(ElementTags.ALIGN, HtmlTags.ALIGN);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.PARAGRAPH, HtmlTags.DIV);
peer.addAlias(ElementTags.ALIGN, HtmlTags.ALIGN);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.PARAGRAPH, HtmlTags.H[0]);
peer.addValue(ElementTags.SIZE, "20");
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.PARAGRAPH, HtmlTags.H[1]);
peer.addValue(ElementTags.SIZE, "18");
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.PARAGRAPH, HtmlTags.H[2]);
peer.addValue(ElementTags.SIZE, "16");
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.PARAGRAPH, HtmlTags.H[3]);
peer.addValue(ElementTags.SIZE, "14");
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.PARAGRAPH, HtmlTags.H[4]);
peer.addValue(ElementTags.SIZE, "12");
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.PARAGRAPH, HtmlTags.H[5]);
peer.addValue(ElementTags.SIZE, "10");
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.LIST, HtmlTags.ORDEREDLIST);
peer.addValue(ElementTags.NUMBERED, "true");
peer.addValue(ElementTags.SYMBOLINDENT, "20");
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.LIST, HtmlTags.UNORDEREDLIST);
peer.addValue(ElementTags.NUMBERED, "false");
peer.addValue(ElementTags.SYMBOLINDENT, "20");
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.LISTITEM, HtmlTags.LISTITEM);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.PHRASE, HtmlTags.I);
peer.addValue(ElementTags.STYLE, Markup.CSS_VALUE_ITALIC);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.PHRASE, HtmlTags.EM);
peer.addValue(ElementTags.STYLE, Markup.CSS_VALUE_ITALIC);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.PHRASE, HtmlTags.B);
peer.addValue(ElementTags.STYLE, Markup.CSS_VALUE_BOLD);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.PHRASE, HtmlTags.STRONG);
peer.addValue(ElementTags.STYLE, Markup.CSS_VALUE_BOLD);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.PHRASE, HtmlTags.S);
peer.addValue(ElementTags.STYLE, Markup.CSS_VALUE_LINETHROUGH);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.PHRASE, HtmlTags.CODE);
peer.addValue(ElementTags.FONT, FontFactory.COURIER);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.PHRASE, HtmlTags.VAR);
peer.addValue(ElementTags.FONT, FontFactory.COURIER);
peer.addValue(ElementTags.STYLE, Markup.CSS_VALUE_ITALIC);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.PHRASE, HtmlTags.U);
peer.addValue(ElementTags.STYLE, Markup.CSS_VALUE_UNDERLINE);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.CHUNK, HtmlTags.SUP);
peer.addValue(ElementTags.SUBSUPSCRIPT, "6.0");
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.CHUNK, HtmlTags.SUB);
peer.addValue(ElementTags.SUBSUPSCRIPT, "-6.0");
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.HORIZONTALRULE, HtmlTags.HORIZONTALRULE);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.TABLE, HtmlTags.TABLE);
peer.addAlias(ElementTags.WIDTH, HtmlTags.WIDTH);
peer.addAlias(ElementTags.BACKGROUNDCOLOR, HtmlTags.BACKGROUNDCOLOR);
peer.addAlias(ElementTags.BORDERCOLOR, HtmlTags.BORDERCOLOR);
peer.addAlias(ElementTags.COLUMNS, HtmlTags.COLUMNS);
peer.addAlias(ElementTags.CELLPADDING, HtmlTags.CELLPADDING);
peer.addAlias(ElementTags.CELLSPACING, HtmlTags.CELLSPACING);
peer.addAlias(ElementTags.BORDERWIDTH, HtmlTags.BORDERWIDTH);
peer.addAlias(ElementTags.ALIGN, HtmlTags.ALIGN);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.ROW, HtmlTags.ROW);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.CELL, HtmlTags.CELL);
peer.addAlias(ElementTags.WIDTH, HtmlTags.WIDTH);
peer.addAlias(ElementTags.BACKGROUNDCOLOR, HtmlTags.BACKGROUNDCOLOR);
peer.addAlias(ElementTags.BORDERCOLOR, HtmlTags.BORDERCOLOR);
peer.addAlias(ElementTags.COLSPAN, HtmlTags.COLSPAN);
peer.addAlias(ElementTags.ROWSPAN, HtmlTags.ROWSPAN);
peer.addAlias(ElementTags.NOWRAP, HtmlTags.NOWRAP);
peer.addAlias(ElementTags.HORIZONTALALIGN, HtmlTags.HORIZONTALALIGN);
peer.addAlias(ElementTags.VERTICALALIGN, HtmlTags.VERTICALALIGN);
peer.addValue(ElementTags.HEADER, "false");
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.CELL, HtmlTags.HEADERCELL);
peer.addAlias(ElementTags.WIDTH, HtmlTags.WIDTH);
peer.addAlias(ElementTags.BACKGROUNDCOLOR, HtmlTags.BACKGROUNDCOLOR);
peer.addAlias(ElementTags.BORDERCOLOR, HtmlTags.BORDERCOLOR);
peer.addAlias(ElementTags.COLSPAN, HtmlTags.COLSPAN);
peer.addAlias(ElementTags.ROWSPAN, HtmlTags.ROWSPAN);
peer.addAlias(ElementTags.NOWRAP, HtmlTags.NOWRAP);
peer.addAlias(ElementTags.HORIZONTALALIGN, HtmlTags.HORIZONTALALIGN);
peer.addAlias(ElementTags.VERTICALALIGN, HtmlTags.VERTICALALIGN);
peer.addValue(ElementTags.HEADER, "true");
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.IMAGE, HtmlTags.IMAGE);
// peer.addAlias(ElementTags.URL, HtmlTags.URL);
peer.addAlias(ElementTags.URL, ElementTags.SRC); // contributed by Lubos Strapko
peer.addAlias(ElementTags.ALT, HtmlTags.ALT);
peer.addAlias(ElementTags.PLAINWIDTH, HtmlTags.PLAINWIDTH);
peer.addAlias(ElementTags.PLAINHEIGHT, HtmlTags.PLAINHEIGHT);
put(peer.getAlias(), peer);
peer = new HtmlPeer(ElementTags.NEWLINE, HtmlTags.NEWLINE);
put(peer.getAlias(), peer);
}
/**
* Checks if this is the root tag.
* @param tag a tagvalue
* @return true if tag is HTML or html
*/
public static boolean isHtml(String tag) {
return HtmlTags.HTML.equalsIgnoreCase(tag);
}
/**
* Checks if this is the head tag.
* @param tag a tagvalue
* @return true if tag is HEAD or head
*/
public static boolean isHead(String tag) {
return HtmlTags.HEAD.equalsIgnoreCase(tag);
}
/**
* Checks if this is the meta tag.
* @param tag a tagvalue
* @return true if tag is META or meta
*/
public static boolean isMeta(String tag) {
return HtmlTags.META.equalsIgnoreCase(tag);
}
/**
* Checks if this is the link tag.
* @param tag a tagvalue
* @return true if tag is LINK or link
*/
public static boolean isLink(String tag) {
return HtmlTags.LINK.equalsIgnoreCase(tag);
}
/**
* Checks if this is the title tag.
* @param tag a tagvalue
* @return true if tag is TITLE or title
*/
public static boolean isTitle(String tag) {
return HtmlTags.TITLE.equalsIgnoreCase(tag);
}
/**
* Checks if this is the root tag.
* @param tag a tagvalue
* @return true if tag is BODY or body
*/
public static boolean isBody(String tag) {
return HtmlTags.BODY.equalsIgnoreCase(tag);
}
/**
* Checks if this is a special tag.
* @param tag a tagvalue
* @return true if tag is a HTML, HEAD, META, LINK or BODY tag (case insensitive)
*/
public static boolean isSpecialTag(String tag) {
return isHtml(tag) || isHead(tag) || isMeta(tag) || isLink(tag)
|| isBody(tag);
}
} src/core/com/lowagie/text/html/HtmlTags.java 100644 0 0 24227 11036112743 16474 0 ustar 0 0 /*
* $Id: HtmlTags.java 3533 2008-07-07 21:27:13Z Howard_s $
*
* Copyright 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.
*
* Contributions by:
* Lubos Strapko
*
* 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.html;
/**
* A class that contains all the possible tagnames and their attributes.
*/
public class HtmlTags {
/** the root tag. */
public static final String HTML = "html";
/** the head tag */
public static final String HEAD = "head";
/** This is a possible HTML attribute for the HEAD tag. */
public static final String CONTENT = "content";
/** the meta tag */
public static final String META = "meta";
/** attribute of the root tag */
public static final String SUBJECT = "subject";
/** attribute of the root tag */
public static final String KEYWORDS = "keywords";
/** attribute of the root tag */
public static final String AUTHOR = "author";
/** the title tag. */
public static final String TITLE = "title";
/** the script tag. */
public static final String SCRIPT = "script";
/** This is a possible HTML attribute for the SCRIPT tag. */
public static final String LANGUAGE = "language";
/** This is a possible value for the LANGUAGE attribute. */
public static final String JAVASCRIPT = "JavaScript";
/** the body tag. */
public static final String BODY = "body";
/** This is a possible HTML attribute for the BODY tag */
public static final String JAVASCRIPT_ONLOAD = "onLoad";
/** This is a possible HTML attribute for the BODY tag */
public static final String JAVASCRIPT_ONUNLOAD = "onUnLoad";
/** This is a possible HTML attribute for the BODY tag. */
public static final String TOPMARGIN = "topmargin";
/** This is a possible HTML attribute for the BODY tag. */
public static final String BOTTOMMARGIN = "bottommargin";
/** This is a possible HTML attribute for the BODY tag. */
public static final String LEFTMARGIN = "leftmargin";
/** This is a possible HTML attribute for the BODY tag. */
public static final String RIGHTMARGIN = "rightmargin";
// Phrases, Anchors, Lists and Paragraphs
/** the chunk tag */
public static final String CHUNK = "font";
/** the phrase tag */
public static final String CODE = "code";
/** the phrase tag */
public static final String VAR = "var";
/** the anchor tag */
public static final String ANCHOR = "a";
/** the list tag */
public static final String ORDEREDLIST = "ol";
/** the list tag */
public static final String UNORDEREDLIST = "ul";
/** the listitem tag */
public static final String LISTITEM = "li";
/** the paragraph tag */
public static final String PARAGRAPH = "p";
/** attribute of anchor tag */
public static final String NAME = "name";
/** attribute of anchor tag */
public static final String REFERENCE = "href";
/** attribute of anchor tag */
public static final String[] H = new String[6];
static {
H[0] = "h1";
H[1] = "h2";
H[2] = "h3";
H[3] = "h4";
H[4] = "h5";
H[5] = "h6";
}
// Chunks
/** attribute of the chunk tag */
public static final String FONT = "face";
/** attribute of the chunk tag */
public static final String SIZE = "point-size";
/** attribute of the chunk/table/cell tag */
public static final String COLOR = "color";
/** some phrase tag */
public static final String EM = "em";
/** some phrase tag */
public static final String I = "i";
/** some phrase tag */
public static final String STRONG = "strong";
/** some phrase tag */
public static final String B = "b";
/** some phrase tag */
public static final String S = "s";
/** some phrase tag */
public static final String U = "u";
/** some phrase tag */
public static final String SUB = "sub";
/** some phrase tag */
public static final String SUP = "sup";
/** the possible value of a tag */
public static final String HORIZONTALRULE = "hr";
// tables/cells
/** the table tag */
public static final String TABLE = "table";
/** the cell tag */
public static final String ROW = "tr";
/** the cell tag */
public static final String CELL = "td";
/** attribute of the cell tag */
public static final String HEADERCELL = "th";
/** attribute of the table tag */
public static final String COLUMNS = "cols";
/** attribute of the table tag */
public static final String CELLPADDING = "cellpadding";
/** attribute of the table tag */
public static final String CELLSPACING = "cellspacing";
/** attribute of the cell tag */
public static final String COLSPAN = "colspan";
/** attribute of the cell tag */
public static final String ROWSPAN = "rowspan";
/** attribute of the cell tag */
public static final String NOWRAP = "nowrap";
/** attribute of the table/cell tag */
public static final String BORDERWIDTH = "border";
/** attribute of the table/cell tag */
public static final String WIDTH = "width";
/** attribute of the table/cell tag */
public static final String BACKGROUNDCOLOR = "bgcolor";
/** attribute of the table/cell tag */
public static final String BORDERCOLOR = "bordercolor";
/** attribute of paragraph/image/table tag */
public static final String ALIGN = "align";
/** attribute of chapter/section/paragraph/table/cell tag */
public static final String LEFT = "left";
/** attribute of chapter/section/paragraph/table/cell tag */
public static final String RIGHT = "right";
/** attribute of the cell tag */
public static final String HORIZONTALALIGN = "align";
/** attribute of the cell tag */
public static final String VERTICALALIGN = "valign";
/** attribute of the table/cell tag */
public static final String TOP = "top";
/** attribute of the table/cell tag */
public static final String BOTTOM = "bottom";
// Misc
/** the image tag */
public static final String IMAGE = "img";
/** attribute of the image tag
* @see com.lowagie.text.ElementTags#SRC
*/
public static final String URL = "src";
/** attribute of the image tag */
public static final String ALT = "alt";
/** attribute of the image tag */
public static final String PLAINWIDTH = "width";
/** attribute of the image tag */
public static final String PLAINHEIGHT = "height";
/** the newpage tag */
public static final String NEWLINE = "br";
// alignment attribute values
/** the possible value of an alignment attribute */
public static final String ALIGN_LEFT = "Left";
/** the possible value of an alignment attribute */
public static final String ALIGN_CENTER = "Center";
/** the possible value of an alignment attribute */
public static final String ALIGN_RIGHT = "Right";
/** the possible value of an alignment attribute */
public static final String ALIGN_JUSTIFIED = "Justify";
/** the possible value of an alignment attribute */
public static final String ALIGN_TOP = "Top";
/** the possible value of an alignment attribute */
public static final String ALIGN_MIDDLE = "Middle";
/** the possible value of an alignment attribute */
public static final String ALIGN_BOTTOM = "Bottom";
/** the possible value of an alignment attribute */
public static final String ALIGN_BASELINE = "Baseline";
/** the possible value of an alignment attribute */
public static final String DEFAULT = "Default";
/** The DIV tag. */
public static final String DIV = "div";
/** The SPAN tag. */
public static final String SPAN = "span";
/** The LINK tag. */
public static final String LINK = "link";
/** This is a possible HTML attribute for the LINK tag. */
public static final String TEXT_CSS = "text/css";
/** This is a possible HTML attribute for the LINK tag. */
public static final String REL = "rel";
/** This is used for inline css style information */
public static final String STYLE = "style";
/** This is a possible HTML attribute for the LINK tag. */
public static final String TYPE = "type";
/** This is a possible HTML attribute. */
public static final String STYLESHEET = "stylesheet";
/** This is a possible HTML attribute for auto-formated
* @since 2.1.3
*/
public static final String PRE = "pre";
} src/core/com/lowagie/text/html/HtmlWriter.java 100644 0 0 116576 11106243444 17104 0 ustar 0 0 /*
* $Id: HtmlWriter.java 3583 2008-08-12 00:00:09Z xlv $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.html;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.EmptyStackException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import java.util.Stack;
import com.lowagie.text.Anchor;
import com.lowagie.text.Annotation;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Chunk;
import com.lowagie.text.DocWriter;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.Font;
import com.lowagie.text.Header;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.List;
import com.lowagie.text.ListItem;
import com.lowagie.text.MarkedObject;
import com.lowagie.text.MarkedSection;
import com.lowagie.text.Meta;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Row;
import com.lowagie.text.Section;
import com.lowagie.text.SimpleTable;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
/**
* A DocWriter
class for HTML.
* HtmlWriter
can be added as a DocListener
* to a certain Document
by getting an instance.
* Every Element
added to the original Document
* will be written to the OutputStream
of this HtmlWriter
.
*
* // creation of the document with a certain size and certain margins
* Document document = new Document(PageSize.A4, 50, 50, 50, 50);
* try {
* // this will write HTML to the Standard OutputStream
* HtmlWriter.getInstance(document, System.out);
* // this will write HTML to a file called text.html
* HtmlWriter.getInstance(document, new FileOutputStream("text.html"));
* // this will write HTML to for instance the OutputStream of a HttpServletResponse-object
* HtmlWriter.getInstance(document, response.getOutputStream());
* }
* catch(DocumentException de) {
* System.err.println(de.getMessage());
* }
* // this will close the document and all the OutputStreams listening to it
* document.close();
HtmlWriter
.
*
* @param doc The Document
that has to be written as HTML
* @param os The OutputStream
the writer has to write to.
*/
protected HtmlWriter(Document doc, OutputStream os) {
super(doc, os);
document.addDocListener(this);
this.pageN = document.getPageNumber();
try {
os.write(LT);
os.write(getISOBytes(HtmlTags.HTML));
os.write(GT);
os.write(NEWLINE);
os.write(TAB);
os.write(LT);
os.write(getISOBytes(HtmlTags.HEAD));
os.write(GT);
}
catch(IOException ioe) {
throw new ExceptionConverter(ioe);
}
}
// get an instance of the HtmlWriter
/**
* Gets an instance of the HtmlWriter
.
*
* @param document The Document
that has to be written
* @param os The OutputStream
the writer has to write to.
* @return a new HtmlWriter
*/
public static HtmlWriter getInstance(Document document, OutputStream os) {
return new HtmlWriter(document, os);
}
// implementation of the DocListener methods
/**
* Signals that an new page has to be started.
*
* @return true
if this action succeeded, false
if not.
*/
public boolean newPage() {
try {
writeStart(HtmlTags.DIV);
write(" ");
write(HtmlTags.STYLE);
write("=\"");
writeCssProperty(Markup.CSS_KEY_PAGE_BREAK_BEFORE, Markup.CSS_VALUE_ALWAYS);
write("\" /");
os.write(GT);
}
catch(IOException ioe) {
throw new ExceptionConverter(ioe);
}
return true;
}
/**
* Signals that an Element
was added to the Document
.
*
* @param element a high level object that has to be translated to HTML
* @return true
if the element was added, false
if not.
* @throws DocumentException when a document isn't open yet, or has been closed
*/
public boolean add(Element element) throws DocumentException {
if (pause) {
return false;
}
if (open && !element.isContent()) {
throw new DocumentException(
"The document is open; you can only add Elements with content.");
}
try {
switch(element.type()) {
case Element.HEADER:
try {
Header h = (Header) element;
if (HtmlTags.STYLESHEET.equals(h.getName())) {
writeLink(h);
}
else if (HtmlTags.JAVASCRIPT.equals(h.getName())) {
writeJavaScript(h);
}
else {
writeHeader(h);
}
}
catch(ClassCastException cce) {
}
return true;
case Element.SUBJECT:
case Element.KEYWORDS:
case Element.AUTHOR:
Meta meta = (Meta) element;
writeHeader(meta);
return true;
case Element.TITLE:
addTabs(2);
writeStart(HtmlTags.TITLE);
os.write(GT);
addTabs(3);
write(HtmlEncoder.encode(((Meta)element).getContent()));
addTabs(2);
writeEnd(HtmlTags.TITLE);
return true;
case Element.CREATOR:
writeComment("Creator: " + HtmlEncoder.encode(((Meta)element).getContent()));
return true;
case Element.PRODUCER:
writeComment("Producer: " + HtmlEncoder.encode(((Meta)element).getContent()));
return true;
case Element.CREATIONDATE:
writeComment("Creationdate: " + HtmlEncoder.encode(((Meta)element).getContent()));
return true;
case Element.MARKED:
if (element instanceof MarkedSection) {
MarkedSection ms = (MarkedSection)element;
addTabs(1);
writeStart(HtmlTags.DIV);
writeMarkupAttributes(ms.getMarkupAttributes());
os.write(GT);
MarkedObject mo = ((MarkedSection)element).getTitle();
if (mo != null) {
markup = mo.getMarkupAttributes();
mo.process(this);
}
ms.process(this);
writeEnd(HtmlTags.DIV);
return true;
}
else {
MarkedObject mo = (MarkedObject) element;
markup = mo.getMarkupAttributes();
return mo.process(this);
}
default:
write(element, 2);
return true;
}
}
catch(IOException ioe) {
throw new ExceptionConverter(ioe);
}
}
/**
* Signals that the Document
has been opened and that
* Elements
can be added.
* HEAD
-section of the HTML-document is written.
*/
public void open() {
super.open();
try {
writeComment(Document.getVersion());
writeComment("CreationDate: " + new Date().toString());
addTabs(1);
writeEnd(HtmlTags.HEAD);
addTabs(1);
writeStart(HtmlTags.BODY);
if (document.leftMargin() > 0) {
write(HtmlTags.LEFTMARGIN, String.valueOf(document.leftMargin()));
}
if (document.rightMargin() > 0) {
write(HtmlTags.RIGHTMARGIN, String.valueOf(document.rightMargin()));
}
if (document.topMargin() > 0) {
write(HtmlTags.TOPMARGIN, String.valueOf(document.topMargin()));
}
if (document.bottomMargin() > 0) {
write(HtmlTags.BOTTOMMARGIN, String.valueOf(document.bottomMargin()));
}
if (pageSize.getBackgroundColor() != null) {
write(HtmlTags.BACKGROUNDCOLOR, HtmlEncoder.encode(pageSize.getBackgroundColor()));
}
if (document.getJavaScript_onLoad() != null) {
write(HtmlTags.JAVASCRIPT_ONLOAD, HtmlEncoder.encode(document.getJavaScript_onLoad()));
}
if (document.getJavaScript_onUnLoad() != null) {
write(HtmlTags.JAVASCRIPT_ONUNLOAD, HtmlEncoder.encode(document.getJavaScript_onUnLoad()));
}
if (document.getHtmlStyleClass() != null) {
write(Markup.HTML_ATTR_CSS_CLASS, document.getHtmlStyleClass());
}
os.write(GT);
initHeader(); // line added by David Freels
}
catch(IOException ioe) {
throw new ExceptionConverter(ioe);
}
}
/**
* Signals that the Document
was closed and that no other
* Elements
will be added.
*/
public void close() {
try {
initFooter(); // line added by David Freels
addTabs(1);
writeEnd(HtmlTags.BODY);
os.write(NEWLINE);
writeEnd(HtmlTags.HTML);
super.close();
}
catch(IOException ioe) {
throw new ExceptionConverter(ioe);
}
}
// some protected methods
/**
* Adds the header to the top of the String
was added to the Document
.
*
* @param string a String to add to the HTML
* @return true
if the string was added, false
if not.
*/
public boolean add(String string) {
if (pause) {
return false;
}
try
{
write(string);
return true;
}
catch(IOException ioe) {
throw new ExceptionConverter(ioe);
}
}
/**
* Writes the HTML representation of an element.
*
* @param element the element
* @param indent the indentation
* @throws IOException
*/
protected void write(Element element, int indent) throws IOException {
Properties styleAttributes = null;
switch(element.type()) {
case Element.MARKED: {
try {
add(element);
} catch (DocumentException e) {
e.printStackTrace();
}
return;
}
case Element.CHUNK:
{
Chunk chunk = (Chunk) element;
// if the chunk contains an image, return the image representation
Image image = chunk.getImage();
if (image != null) {
write(image, indent);
return;
}
if (chunk.isEmpty()) return;
HashMap attributes = chunk.getAttributes();
if (attributes != null && attributes.get(Chunk.NEWPAGE) != null) {
return;
}
boolean tag = isOtherFont(chunk.getFont()) || markup.size() > 0;
if (tag) {
// start span tag
addTabs(indent);
writeStart(HtmlTags.SPAN);
if (isOtherFont(chunk.getFont())) {
write(chunk.getFont(), null);
}
writeMarkupAttributes(markup);
os.write(GT);
}
if (attributes != null && attributes.get(Chunk.SUBSUPSCRIPT) != null) {
// start sup or sub tag
if (((Float)attributes.get(Chunk.SUBSUPSCRIPT)).floatValue() > 0) {
writeStart(HtmlTags.SUP);
}
else {
writeStart(HtmlTags.SUB);
}
os.write(GT);
}
// contents
write(HtmlEncoder.encode(chunk.getContent()));
if (attributes != null && attributes.get(Chunk.SUBSUPSCRIPT) != null) {
// end sup or sub tag
os.write(LT);
os.write(FORWARD);
if (((Float)attributes.get(Chunk.SUBSUPSCRIPT)).floatValue() > 0) {
write(HtmlTags.SUP);
}
else {
write(HtmlTags.SUB);
}
os.write(GT);
}
if (tag) {
// end tag
writeEnd(Markup.HTML_TAG_SPAN);
}
return;
}
case Element.PHRASE:
{
Phrase phrase = (Phrase) element;
styleAttributes = new Properties();
if (phrase.hasLeading()) styleAttributes.setProperty(Markup.CSS_KEY_LINEHEIGHT, phrase.getLeading() + "pt");
// start tag
addTabs(indent);
writeStart(Markup.HTML_TAG_SPAN);
writeMarkupAttributes(markup);
write(phrase.getFont(), styleAttributes);
os.write(GT);
currentfont.push(phrase.getFont());
// contents
for (Iterator i = phrase.iterator(); i.hasNext(); ) {
write((Element) i.next(), indent + 1);
}
// end tag
addTabs(indent);
writeEnd(Markup.HTML_TAG_SPAN);
currentfont.pop();
return;
}
case Element.ANCHOR:
{
Anchor anchor = (Anchor) element;
styleAttributes = new Properties();
if (anchor.hasLeading()) styleAttributes.setProperty(Markup.CSS_KEY_LINEHEIGHT, anchor.getLeading() + "pt");
// start tag
addTabs(indent);
writeStart(HtmlTags.ANCHOR);
if (anchor.getName() != null) {
write(HtmlTags.NAME, anchor.getName());
}
if (anchor.getReference() != null) {
write(HtmlTags.REFERENCE, anchor.getReference());
}
writeMarkupAttributes(markup);
write(anchor.getFont(), styleAttributes);
os.write(GT);
currentfont.push(anchor.getFont());
// contents
for (Iterator i = anchor.iterator(); i.hasNext(); ) {
write((Element) i.next(), indent + 1);
}
// end tag
addTabs(indent);
writeEnd(HtmlTags.ANCHOR);
currentfont.pop();
return;
}
case Element.PARAGRAPH:
{
Paragraph paragraph = (Paragraph) element;
styleAttributes = new Properties();
if (paragraph.hasLeading()) styleAttributes.setProperty(Markup.CSS_KEY_LINEHEIGHT, paragraph.getTotalLeading() + "pt");
// start tag
addTabs(indent);
writeStart(HtmlTags.DIV);
writeMarkupAttributes(markup);
String alignment = HtmlEncoder.getAlignment(paragraph.getAlignment());
if (!"".equals(alignment)) {
write(HtmlTags.ALIGN, alignment);
}
write(paragraph.getFont(), styleAttributes);
os.write(GT);
currentfont.push(paragraph.getFont());
// contents
for (Iterator i = paragraph.iterator(); i.hasNext(); ) {
write((Element)i.next(), indent + 1);
}
// end tag
addTabs(indent);
writeEnd(HtmlTags.DIV);
currentfont.pop();
return;
}
case Element.SECTION:
case Element.CHAPTER:
{
// part of the start tag + contents
writeSection((Section) element, indent);
return;
}
case Element.LIST:
{
List list = (List) element;
// start tag
addTabs(indent);
if (list.isNumbered()) {
writeStart(HtmlTags.ORDEREDLIST);
}
else {
writeStart(HtmlTags.UNORDEREDLIST);
}
writeMarkupAttributes(markup);
os.write(GT);
// contents
for (Iterator i = list.getItems().iterator(); i.hasNext(); ) {
write((Element) i.next(), indent + 1);
}
// end tag
addTabs(indent);
if (list.isNumbered()) {
writeEnd(HtmlTags.ORDEREDLIST);
}
else {
writeEnd(HtmlTags.UNORDEREDLIST);
}
return;
}
case Element.LISTITEM:
{
ListItem listItem = (ListItem) element;
styleAttributes = new Properties();
if (listItem.hasLeading()) styleAttributes.setProperty(Markup.CSS_KEY_LINEHEIGHT, listItem.getTotalLeading() + "pt");
// start tag
addTabs(indent);
writeStart(HtmlTags.LISTITEM);
writeMarkupAttributes(markup);
write(listItem.getFont(), styleAttributes);
os.write(GT);
currentfont.push(listItem.getFont());
// contents
for (Iterator i = listItem.iterator(); i.hasNext(); ) {
write((Element) i.next(), indent + 1);
}
// end tag
addTabs(indent);
writeEnd(HtmlTags.LISTITEM);
currentfont.pop();
return;
}
case Element.CELL:
{
Cell cell = (Cell) element;
// start tag
addTabs(indent);
if (cell.isHeader()) {
writeStart(HtmlTags.HEADERCELL);
}
else {
writeStart(HtmlTags.CELL);
}
writeMarkupAttributes(markup);
if (cell.getBorderWidth() != Rectangle.UNDEFINED) {
write(HtmlTags.BORDERWIDTH, String.valueOf(cell.getBorderWidth()));
}
if (cell.getBorderColor() != null) {
write(HtmlTags.BORDERCOLOR, HtmlEncoder.encode(cell.getBorderColor()));
}
if (cell.getBackgroundColor() != null) {
write(HtmlTags.BACKGROUNDCOLOR, HtmlEncoder.encode(cell.getBackgroundColor()));
}
String alignment = HtmlEncoder.getAlignment(cell.getHorizontalAlignment());
if (!"".equals(alignment)) {
write(HtmlTags.HORIZONTALALIGN, alignment);
}
alignment = HtmlEncoder.getAlignment(cell.getVerticalAlignment());
if (!"".equals(alignment)) {
write(HtmlTags.VERTICALALIGN, alignment);
}
if (cell.getWidthAsString() != null) {
write(HtmlTags.WIDTH, cell.getWidthAsString());
}
if (cell.getColspan() != 1) {
write(HtmlTags.COLSPAN, String.valueOf(cell.getColspan()));
}
if (cell.getRowspan() != 1) {
write(HtmlTags.ROWSPAN, String.valueOf(cell.getRowspan()));
}
if (cell.getMaxLines() == 1) {
write(HtmlTags.STYLE, "white-space: nowrap;");
}
os.write(GT);
// contents
if (cell.isEmpty()) {
write(NBSP);
} else {
for (Iterator i = cell.getElements(); i.hasNext(); ) {
write((Element) i.next(), indent + 1);
}
}
// end tag
addTabs(indent);
if (cell.isHeader()) {
writeEnd(HtmlTags.HEADERCELL);
}
else {
writeEnd(HtmlTags.CELL);
}
return;
}
case Element.ROW:
{
Row row = (Row) element;
// start tag
addTabs(indent);
writeStart(HtmlTags.ROW);
writeMarkupAttributes(markup);
os.write(GT);
// contents
Element cell;
for (int i = 0; i < row.getColumns(); i++) {
if ((cell = (Element)row.getCell(i)) != null) {
write(cell, indent + 1);
}
}
// end tag
addTabs(indent);
writeEnd(HtmlTags.ROW);
return;
}
case Element.TABLE:
{
Table table;
try {
table = (Table) element;
}
catch(ClassCastException cce) {
try {
table = ((SimpleTable)element).createTable();
} catch (BadElementException e) {
throw new ExceptionConverter(e);
}
}
table.complete();
// start tag
addTabs(indent);
writeStart(HtmlTags.TABLE);
writeMarkupAttributes(markup);
os.write(SPACE);
write(HtmlTags.WIDTH);
os.write(EQUALS);
os.write(QUOTE);
write(String.valueOf(table.getWidth()));
if (!table.isLocked()){
write("%");
}
os.write(QUOTE);
String alignment = HtmlEncoder.getAlignment(table.getAlignment());
if (!"".equals(alignment)) {
write(HtmlTags.ALIGN, alignment);
}
write(HtmlTags.CELLPADDING, String.valueOf(table.getPadding()));
write(HtmlTags.CELLSPACING, String.valueOf(table.getSpacing()));
if (table.getBorderWidth() != Rectangle.UNDEFINED) {
write(HtmlTags.BORDERWIDTH, String.valueOf(table.getBorderWidth()));
}
if (table.getBorderColor() != null) {
write(HtmlTags.BORDERCOLOR, HtmlEncoder.encode(table.getBorderColor()));
}
if (table.getBackgroundColor() != null) {
write(HtmlTags.BACKGROUNDCOLOR, HtmlEncoder.encode(table.getBackgroundColor()));
}
os.write(GT);
// contents
Row row;
for (Iterator iterator = table.iterator(); iterator.hasNext(); ) {
row = (Row) iterator.next();
write(row, indent + 1);
}
// end tag
addTabs(indent);
writeEnd(HtmlTags.TABLE);
return;
}
case Element.ANNOTATION:
{
Annotation annotation = (Annotation) element;
writeComment(annotation.title() + ": " + annotation.content());
return;
}
case Element.IMGRAW:
case Element.JPEG:
case Element.JPEG2000:
case Element.IMGTEMPLATE:
{
Image image = (Image) element;
if (image.getUrl() == null) {
return;
}
// start tag
addTabs(indent);
writeStart(HtmlTags.IMAGE);
String path = image.getUrl().toString();
if (imagepath != null) {
if (path.indexOf('/') > 0) {
path = imagepath + path.substring(path.lastIndexOf('/') + 1);
}
else {
path = imagepath + path;
}
}
write(HtmlTags.URL, path);
if ((image.getAlignment() & Image.RIGHT) > 0) {
write(HtmlTags.ALIGN, HtmlTags.ALIGN_RIGHT);
}
else if ((image.getAlignment() & Image.MIDDLE) > 0) {
write(HtmlTags.ALIGN, HtmlTags.ALIGN_MIDDLE);
}
else {
write(HtmlTags.ALIGN, HtmlTags.ALIGN_LEFT);
}
if (image.getAlt() != null) {
write(HtmlTags.ALT, image.getAlt());
}
write(HtmlTags.PLAINWIDTH, String.valueOf(image.getScaledWidth()));
write(HtmlTags.PLAINHEIGHT, String.valueOf(image.getScaledHeight()));
writeMarkupAttributes(markup);
writeEnd();
return;
}
default:
return;
}
}
/**
* Writes the HTML representation of a section.
*
* @param section the section to write
* @param indent the indentation
* @throws IOException
*/
protected void writeSection(Section section, int indent) throws IOException {
if (section.getTitle() != null) {
int depth = section.getDepth() - 1;
if (depth > 5) {
depth = 5;
}
Properties styleAttributes = new Properties();
if (section.getTitle().hasLeading()) styleAttributes.setProperty(Markup.CSS_KEY_LINEHEIGHT, section.getTitle().getTotalLeading() + "pt");
// start tag
addTabs(indent);
writeStart(HtmlTags.H[depth]);
write(section.getTitle().getFont(), styleAttributes);
String alignment = HtmlEncoder.getAlignment(section.getTitle().getAlignment());
if (!"".equals(alignment)) {
write(HtmlTags.ALIGN, alignment);
}
writeMarkupAttributes(markup);
os.write(GT);
currentfont.push(section.getTitle().getFont());
// contents
for (Iterator i = section.getTitle().iterator(); i.hasNext(); ) {
write((Element)i.next(), indent + 1);
}
// end tag
addTabs(indent);
writeEnd(HtmlTags.H[depth]);
currentfont.pop();
}
for (Iterator i = section.iterator(); i.hasNext(); ) {
write((Element) i.next(), indent);
}
}
/**
* Writes the representation of a Font
.
*
* @param font a Font
* @param styleAttributes the style of the font
* @throws IOException
*/
protected void write(Font font, Properties styleAttributes) throws IOException {
if (font == null || !isOtherFont(font) /* || styleAttributes == null*/) return;
write(" ");
write(HtmlTags.STYLE);
write("=\"");
if (styleAttributes != null) {
String key;
for (Enumeration e = styleAttributes.propertyNames(); e.hasMoreElements(); ) {
key = (String)e.nextElement();
writeCssProperty(key, styleAttributes.getProperty(key));
}
}
if (isOtherFont(font)) {
writeCssProperty(Markup.CSS_KEY_FONTFAMILY, font.getFamilyname());
if (font.getSize() != Font.UNDEFINED) {
writeCssProperty(Markup.CSS_KEY_FONTSIZE, font.getSize() + "pt");
}
if (font.getColor() != null) {
writeCssProperty(Markup.CSS_KEY_COLOR, HtmlEncoder.encode(font.getColor()));
}
int fontstyle = font.getStyle();
BaseFont bf = font.getBaseFont();
if (bf != null) {
String ps = bf.getPostscriptFontName().toLowerCase();
if (ps.indexOf("bold") >= 0) {
if (fontstyle == Font.UNDEFINED)
fontstyle = 0;
fontstyle |= Font.BOLD;
}
if (ps.indexOf("italic") >= 0 || ps.indexOf("oblique") >= 0) {
if (fontstyle == Font.UNDEFINED)
fontstyle = 0;
fontstyle |= Font.ITALIC;
}
}
if (fontstyle != Font.UNDEFINED && fontstyle != Font.NORMAL) {
switch (fontstyle & Font.BOLDITALIC) {
case Font.BOLD:
writeCssProperty(Markup.CSS_KEY_FONTWEIGHT, Markup.CSS_VALUE_BOLD);
break;
case Font.ITALIC:
writeCssProperty(Markup.CSS_KEY_FONTSTYLE, Markup.CSS_VALUE_ITALIC);
break;
case Font.BOLDITALIC:
writeCssProperty(Markup.CSS_KEY_FONTWEIGHT, Markup.CSS_VALUE_BOLD);
writeCssProperty(Markup.CSS_KEY_FONTSTYLE, Markup.CSS_VALUE_ITALIC);
break;
}
// CSS only supports one decoration tag so if both are specified
// only one of the two will display
if ((fontstyle & Font.UNDERLINE) > 0) {
writeCssProperty(Markup.CSS_KEY_TEXTDECORATION, Markup.CSS_VALUE_UNDERLINE);
}
if ((fontstyle & Font.STRIKETHRU) > 0) {
writeCssProperty(Markup.CSS_KEY_TEXTDECORATION, Markup.CSS_VALUE_LINETHROUGH);
}
}
}
write("\"");
}
/**
* Writes out a CSS property.
* @param prop a CSS property
* @param value the value of the CSS property
* @throws IOException
*/
protected void writeCssProperty(String prop, String value) throws IOException {
write(new StringBuffer(prop).append(": ").append(value).append("; ").toString());
}
} src/core/com/lowagie/text/html/Markup.java 100644 0 0 35516 11154165264 16222 0 ustar 0 0 /*
* $Id: Markup.java 3654 2009-01-21 16:11:00Z blowagie $
*
* Copyright 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.
*
* Contributions by:
* Lubos Strapko
*
* 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.html;
import java.awt.Color;
import java.util.Properties;
import java.util.StringTokenizer;
/**
* A class that contains all the possible tagnames and their attributes.
*/
public class Markup {
// iText specific
/** the key for any tag */
public static final String ITEXT_TAG = "tag";
// HTML tags
/** the markup for the body part of a file */
public static final String HTML_TAG_BODY = "body";
/** The DIV tag. */
public static final String HTML_TAG_DIV = "div";
/** This is a possible HTML-tag. */
public static final String HTML_TAG_LINK = "link";
/** The SPAN tag. */
public static final String HTML_TAG_SPAN = "span";
// HTML attributes
/** the height attribute. */
public static final String HTML_ATTR_HEIGHT = "height";
/** the hyperlink reference attribute. */
public static final String HTML_ATTR_HREF = "href";
/** This is a possible HTML attribute for the LINK tag. */
public static final String HTML_ATTR_REL = "rel";
/** This is used for inline css style information */
public static final String HTML_ATTR_STYLE = "style";
/** This is a possible HTML attribute for the LINK tag. */
public static final String HTML_ATTR_TYPE = "type";
/** This is a possible HTML attribute. */
public static final String HTML_ATTR_STYLESHEET = "stylesheet";
/** the width attribute. */
public static final String HTML_ATTR_WIDTH = "width";
/** attribute for specifying externally defined CSS class */
public static final String HTML_ATTR_CSS_CLASS = "class";
/** The ID attribute. */
public static final String HTML_ATTR_CSS_ID = "id";
// HTML values
/** This is a possible value for the language attribute (SCRIPT tag). */
public static final String HTML_VALUE_JAVASCRIPT = "text/javascript";
/** This is a possible HTML attribute for the LINK tag. */
public static final String HTML_VALUE_CSS = "text/css";
// CSS keys
/** the CSS tag for background color */
public static final String CSS_KEY_BGCOLOR = "background-color";
/** the CSS tag for text color */
public static final String CSS_KEY_COLOR = "color";
/** CSS key that indicate the way something has to be displayed */
public static final String CSS_KEY_DISPLAY = "display";
/** the CSS tag for the font family */
public static final String CSS_KEY_FONTFAMILY = "font-family";
/** the CSS tag for the font size */
public static final String CSS_KEY_FONTSIZE = "font-size";
/** the CSS tag for the font style */
public static final String CSS_KEY_FONTSTYLE = "font-style";
/** the CSS tag for the font weight */
public static final String CSS_KEY_FONTWEIGHT = "font-weight";
/** the CSS tag for text decorations */
public static final String CSS_KEY_LINEHEIGHT = "line-height";
/** the CSS tag for the margin of an object */
public static final String CSS_KEY_MARGIN = "margin";
/** the CSS tag for the margin of an object */
public static final String CSS_KEY_MARGINLEFT = "margin-left";
/** the CSS tag for the margin of an object */
public static final String CSS_KEY_MARGINRIGHT = "margin-right";
/** the CSS tag for the margin of an object */
public static final String CSS_KEY_MARGINTOP = "margin-top";
/** the CSS tag for the margin of an object */
public static final String CSS_KEY_MARGINBOTTOM = "margin-bottom";
/** the CSS tag for the margin of an object */
public static final String CSS_KEY_PADDING = "padding";
/** the CSS tag for the margin of an object */
public static final String CSS_KEY_PADDINGLEFT = "padding-left";
/** the CSS tag for the margin of an object */
public static final String CSS_KEY_PADDINGRIGHT = "padding-right";
/** the CSS tag for the margin of an object */
public static final String CSS_KEY_PADDINGTOP = "padding-top";
/** the CSS tag for the margin of an object */
public static final String CSS_KEY_PADDINGBOTTOM = "padding-bottom";
/** the CSS tag for the margin of an object */
public static final String CSS_KEY_BORDERCOLOR = "border-color";
/** the CSS tag for the margin of an object */
public static final String CSS_KEY_BORDERWIDTH = "border-width";
/** the CSS tag for the margin of an object */
public static final String CSS_KEY_BORDERWIDTHLEFT = "border-left-width";
/** the CSS tag for the margin of an object */
public static final String CSS_KEY_BORDERWIDTHRIGHT = "border-right-width";
/** the CSS tag for the margin of an object */
public static final String CSS_KEY_BORDERWIDTHTOP = "border-top-width";
/** the CSS tag for the margin of an object */
public static final String CSS_KEY_BORDERWIDTHBOTTOM = "border-bottom-width";
/** the CSS tag for adding a page break when the document is printed */
public static final String CSS_KEY_PAGE_BREAK_AFTER = "page-break-after";
/** the CSS tag for adding a page break when the document is printed */
public static final String CSS_KEY_PAGE_BREAK_BEFORE = "page-break-before";
/** the CSS tag for the horizontal alignment of an object */
public static final String CSS_KEY_TEXTALIGN = "text-align";
/** the CSS tag for text decorations */
public static final String CSS_KEY_TEXTDECORATION = "text-decoration";
/** the CSS tag for text decorations */
public static final String CSS_KEY_VERTICALALIGN = "vertical-align";
/** the CSS tag for the visibility of objects */
public static final String CSS_KEY_VISIBILITY = "visibility";
// CSS values
/**
* value for the CSS tag for adding a page break when the document is
* printed
*/
public static final String CSS_VALUE_ALWAYS = "always";
/** A possible value for the DISPLAY key */
public static final String CSS_VALUE_BLOCK = "block";
/** a CSS value for text font weight */
public static final String CSS_VALUE_BOLD = "bold";
/** the value if you want to hide objects. */
public static final String CSS_VALUE_HIDDEN = "hidden";
/** A possible value for the DISPLAY key */
public static final String CSS_VALUE_INLINE = "inline";
/** a CSS value for text font style */
public static final String CSS_VALUE_ITALIC = "italic";
/** a CSS value for text decoration */
public static final String CSS_VALUE_LINETHROUGH = "line-through";
/** A possible value for the DISPLAY key */
public static final String CSS_VALUE_LISTITEM = "list-item";
/** a CSS value */
public static final String CSS_VALUE_NONE = "none";
/** a CSS value */
public static final String CSS_VALUE_NORMAL = "normal";
/** a CSS value for text font style */
public static final String CSS_VALUE_OBLIQUE = "oblique";
/** A possible value for the DISPLAY key */
public static final String CSS_VALUE_TABLE = "table";
/** A possible value for the DISPLAY key */
public static final String CSS_VALUE_TABLEROW = "table-row";
/** A possible value for the DISPLAY key */
public static final String CSS_VALUE_TABLECELL = "table-cell";
/** the CSS value for a horizontal alignment of an object */
public static final String CSS_VALUE_TEXTALIGNLEFT = "left";
/** the CSS value for a horizontal alignment of an object */
public static final String CSS_VALUE_TEXTALIGNRIGHT = "right";
/** the CSS value for a horizontal alignment of an object */
public static final String CSS_VALUE_TEXTALIGNCENTER = "center";
/** the CSS value for a horizontal alignment of an object */
public static final String CSS_VALUE_TEXTALIGNJUSTIFY = "justify";
/** a CSS value for text decoration */
public static final String CSS_VALUE_UNDERLINE = "underline";
/** a default value for font-size
* @since 2.1.3
*/
public static final float DEFAULT_FONT_SIZE = 12f;
/**
* Parses a length.
*
* @param string
* a length in the form of an optional + or -, followed by a
* number and a unit.
* @return a float
*/
public static float parseLength(String string) {
// TODO: Evaluate the effect of this.
// It may change the default behavour of the methd if this is changed.
// return parseLength(string, Markup.DEFAULT_FONT_SIZE);
int pos = 0;
int length = string.length();
boolean ok = true;
while (ok && pos < length) {
switch (string.charAt(pos)) {
case '+':
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.':
pos++;
break;
default:
ok = false;
}
}
if (pos == 0)
return 0f;
if (pos == length)
return Float.parseFloat(string + "f");
float f = Float.parseFloat(string.substring(0, pos) + "f");
string = string.substring(pos);
// inches
if (string.startsWith("in")) {
return f * 72f;
}
// centimeters
if (string.startsWith("cm")) {
return (f / 2.54f) * 72f;
}
// millimeters
if (string.startsWith("mm")) {
return (f / 25.4f) * 72f;
}
// picas
if (string.startsWith("pc")) {
return f * 12f;
}
// default: we assume the length was measured in points
return f;
}
/**
* New method contributed by: Lubos Strapko
*
* @since 2.1.3
*/
public static float parseLength(String string, float actualFontSize) {
if (string == null)
return 0f;
int pos = 0;
int length = string.length();
boolean ok = true;
while (ok && pos < length) {
switch (string.charAt(pos)) {
case '+':
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.':
pos++;
break;
default:
ok = false;
}
}
if (pos == 0)
return 0f;
if (pos == length)
return Float.parseFloat(string + "f");
float f = Float.parseFloat(string.substring(0, pos) + "f");
string = string.substring(pos);
// inches
if (string.startsWith("in")) {
return f * 72f;
}
// centimeters
if (string.startsWith("cm")) {
return (f / 2.54f) * 72f;
}
// millimeters
if (string.startsWith("mm")) {
return (f / 25.4f) * 72f;
}
// picas
if (string.startsWith("pc")) {
return f * 12f;
}
// 1em is equal to the current font size
if (string.startsWith("em")) {
return f * actualFontSize;
}
// one ex is the x-height of a font (x-height is usually about half the
// font-size)
if (string.startsWith("ex")) {
return f * actualFontSize / 2;
}
// default: we assume the length was measured in points
return f;
}
/**
* Converts a Color
into a HTML representation of this
* Color
.
*
* @param s
* the Color
that has to be converted.
* @return the HTML representation of this Tags
-class maps several XHTML-tags to iText-objects.
*/
public class SAXmyHtmlHandler extends SAXiTextHandler // SAXmyHandler
{
/** These are the properties of the body section. */
private Properties bodyAttributes = new Properties();
/** This is the status of the table border. */
private boolean tableBorder = false;
/**
* Constructs a new SAXiTextHandler that will translate all the events
* triggered by the parser to actions on the Document
-object.
*
* @param document
* this is the document on which events must be triggered
*/
public SAXmyHtmlHandler(DocListener document) {
super(document, new HtmlTagMap());
}
/**
* Constructs a new SAXiTextHandler that will translate all the events
* triggered by the parser to actions on the Document
-object.
*
* @param document
* this is the document on which events must be triggered
* @param bf
*/
public SAXmyHtmlHandler(DocListener document, BaseFont bf) {
super(document, new HtmlTagMap(), bf);
}
/**
* Constructs a new SAXiTextHandler that will translate all the events
* triggered by the parser to actions on the Document
-object.
*
* @param document
* this is the document on which events must be triggered
* @param htmlTags
* a tagmap translating HTML tags to iText tags
*/
public SAXmyHtmlHandler(DocListener document, HashMap htmlTags) {
super(document, htmlTags);
}
/**
* This method gets called when a start 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 is encountered
* @param attrs
* the list of attributes
*/
public void startElement(String uri, String lname, String name,
Attributes attrs) {
// System.err.println("Start: " + name);
// super.handleStartingTags is replaced with handleStartingTags
// suggestion by Vu Ngoc Tan/Hop
name = name.toLowerCase();
if (HtmlTagMap.isHtml(name)) {
// we do nothing
return;
}
if (HtmlTagMap.isHead(name)) {
// we do nothing
return;
}
if (HtmlTagMap.isTitle(name)) {
// we do nothing
return;
}
if (HtmlTagMap.isMeta(name)) {
// we look if we can change the body attributes
String meta = null;
String content = null;
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
String attribute = attrs.getQName(i);
if (attribute.equalsIgnoreCase(HtmlTags.CONTENT))
content = attrs.getValue(i);
else if (attribute.equalsIgnoreCase(HtmlTags.NAME))
meta = attrs.getValue(i);
}
}
if (meta != null && content != null) {
bodyAttributes.put(meta, content);
}
return;
}
if (HtmlTagMap.isLink(name)) {
// we do nothing for the moment, in a later version we could extract
// the style sheet
return;
}
if (HtmlTagMap.isBody(name)) {
// maybe we could extract some info about the document: color,
// margins,...
// but that's for a later version...
XmlPeer peer = new XmlPeer(ElementTags.ITEXT, name);
peer.addAlias(ElementTags.TOP, HtmlTags.TOPMARGIN);
peer.addAlias(ElementTags.BOTTOM, HtmlTags.BOTTOMMARGIN);
peer.addAlias(ElementTags.RIGHT, HtmlTags.RIGHTMARGIN);
peer.addAlias(ElementTags.LEFT, HtmlTags.LEFTMARGIN);
bodyAttributes.putAll(peer.getAttributes(attrs));
handleStartingTags(peer.getTag(), bodyAttributes);
return;
}
if (myTags.containsKey(name)) {
XmlPeer peer = (XmlPeer) myTags.get(name);
if (ElementTags.TABLE.equals(peer.getTag()) || ElementTags.CELL.equals(peer.getTag())) {
Properties p = peer.getAttributes(attrs);
String value;
if (ElementTags.TABLE.equals(peer.getTag())
&& (value = p.getProperty(ElementTags.BORDERWIDTH)) != null) {
if (Float.parseFloat(value + "f") > 0) {
tableBorder = true;
}
}
if (tableBorder) {
p.put(ElementTags.LEFT, String.valueOf(true));
p.put(ElementTags.RIGHT, String.valueOf(true));
p.put(ElementTags.TOP, String.valueOf(true));
p.put(ElementTags.BOTTOM, String.valueOf(true));
}
handleStartingTags(peer.getTag(), p);
return;
}
handleStartingTags(peer.getTag(), peer.getAttributes(attrs));
return;
}
Properties attributes = new Properties();
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
String attribute = attrs.getQName(i).toLowerCase();
attributes.setProperty(attribute, attrs.getValue(i).toLowerCase());
}
}
handleStartingTags(name, attributes);
}
/**
* 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) {
// System.err.println("End: " + name);
name = name.toLowerCase();
if (ElementTags.PARAGRAPH.equals(name)) {
try {
document.add((Element) stack.pop());
return;
} catch (DocumentException e) {
throw new ExceptionConverter(e);
}
}
if (HtmlTagMap.isHead(name)) {
// we do nothing
return;
}
if (HtmlTagMap.isTitle(name)) {
if (currentChunk != null) {
bodyAttributes.put(ElementTags.TITLE, currentChunk.getContent());
}
return;
}
if (HtmlTagMap.isMeta(name)) {
// we do nothing
return;
}
if (HtmlTagMap.isLink(name)) {
// we do nothing
return;
}
if (HtmlTagMap.isBody(name)) {
// we do nothing
return;
}
if (myTags.containsKey(name)) {
XmlPeer peer = (XmlPeer) myTags.get(name);
if (ElementTags.TABLE.equals(peer.getTag())) {
tableBorder = false;
}
super.handleEndingTags(peer.getTag());
return;
}
// super.handleEndingTags is replaced with handleEndingTags
// suggestion by Ken Auer
handleEndingTags(name);
}
} src/core/com/lowagie/text/html/WebColors.java 100644 0 0 33255 11012562264 16652 0 ustar 0 0 /*
* $Id: WebColors.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.html;
import java.awt.Color;
import java.util.HashMap;
import java.util.StringTokenizer;
/**
* This class is a HashMap that contains the names of colors as a key and the
* corresponding Color as value. (Source: Wikipedia
* http://en.wikipedia.org/wiki/Web_colors )
*
* @author blowagie
*/
public class WebColors extends HashMap {
private static final long serialVersionUID = 3542523100813372896L;
/** HashMap containing all the names and corresponding color values. */
public static final WebColors NAMES = new WebColors();
static {
NAMES.put("aliceblue", new int[] { 0xf0, 0xf8, 0xff, 0x00 });
NAMES.put("antiquewhite", new int[] { 0xfa, 0xeb, 0xd7, 0x00 });
NAMES.put("aqua", new int[] { 0x00, 0xff, 0xff, 0x00 });
NAMES.put("aquamarine", new int[] { 0x7f, 0xff, 0xd4, 0x00 });
NAMES.put("azure", new int[] { 0xf0, 0xff, 0xff, 0x00 });
NAMES.put("beige", new int[] { 0xf5, 0xf5, 0xdc, 0x00 });
NAMES.put("bisque", new int[] { 0xff, 0xe4, 0xc4, 0x00 });
NAMES.put("black", new int[] { 0x00, 0x00, 0x00, 0x00 });
NAMES.put("blanchedalmond", new int[] { 0xff, 0xeb, 0xcd, 0x00 });
NAMES.put("blue", new int[] { 0x00, 0x00, 0xff, 0x00 });
NAMES.put("blueviolet", new int[] { 0x8a, 0x2b, 0xe2, 0x00 });
NAMES.put("brown", new int[] { 0xa5, 0x2a, 0x2a, 0x00 });
NAMES.put("burlywood", new int[] { 0xde, 0xb8, 0x87, 0x00 });
NAMES.put("cadetblue", new int[] { 0x5f, 0x9e, 0xa0, 0x00 });
NAMES.put("chartreuse", new int[] { 0x7f, 0xff, 0x00, 0x00 });
NAMES.put("chocolate", new int[] { 0xd2, 0x69, 0x1e, 0x00 });
NAMES.put("coral", new int[] { 0xff, 0x7f, 0x50, 0x00 });
NAMES.put("cornflowerblue", new int[] { 0x64, 0x95, 0xed, 0x00 });
NAMES.put("cornsilk", new int[] { 0xff, 0xf8, 0xdc, 0x00 });
NAMES.put("crimson", new int[] { 0xdc, 0x14, 0x3c, 0x00 });
NAMES.put("cyan", new int[] { 0x00, 0xff, 0xff, 0x00 });
NAMES.put("darkblue", new int[] { 0x00, 0x00, 0x8b, 0x00 });
NAMES.put("darkcyan", new int[] { 0x00, 0x8b, 0x8b, 0x00 });
NAMES.put("darkgoldenrod", new int[] { 0xb8, 0x86, 0x0b, 0x00 });
NAMES.put("darkgray", new int[] { 0xa9, 0xa9, 0xa9, 0x00 });
NAMES.put("darkgreen", new int[] { 0x00, 0x64, 0x00, 0x00 });
NAMES.put("darkkhaki", new int[] { 0xbd, 0xb7, 0x6b, 0x00 });
NAMES.put("darkmagenta", new int[] { 0x8b, 0x00, 0x8b, 0x00 });
NAMES.put("darkolivegreen", new int[] { 0x55, 0x6b, 0x2f, 0x00 });
NAMES.put("darkorange", new int[] { 0xff, 0x8c, 0x00, 0x00 });
NAMES.put("darkorchid", new int[] { 0x99, 0x32, 0xcc, 0x00 });
NAMES.put("darkred", new int[] { 0x8b, 0x00, 0x00, 0x00 });
NAMES.put("darksalmon", new int[] { 0xe9, 0x96, 0x7a, 0x00 });
NAMES.put("darkseagreen", new int[] { 0x8f, 0xbc, 0x8f, 0x00 });
NAMES.put("darkslateblue", new int[] { 0x48, 0x3d, 0x8b, 0x00 });
NAMES.put("darkslategray", new int[] { 0x2f, 0x4f, 0x4f, 0x00 });
NAMES.put("darkturquoise", new int[] { 0x00, 0xce, 0xd1, 0x00 });
NAMES.put("darkviolet", new int[] { 0x94, 0x00, 0xd3, 0x00 });
NAMES.put("deeppink", new int[] { 0xff, 0x14, 0x93, 0x00 });
NAMES.put("deepskyblue", new int[] { 0x00, 0xbf, 0xff, 0x00 });
NAMES.put("dimgray", new int[] { 0x69, 0x69, 0x69, 0x00 });
NAMES.put("dodgerblue", new int[] { 0x1e, 0x90, 0xff, 0x00 });
NAMES.put("firebrick", new int[] { 0xb2, 0x22, 0x22, 0x00 });
NAMES.put("floralwhite", new int[] { 0xff, 0xfa, 0xf0, 0x00 });
NAMES.put("forestgreen", new int[] { 0x22, 0x8b, 0x22, 0x00 });
NAMES.put("fuchsia", new int[] { 0xff, 0x00, 0xff, 0x00 });
NAMES.put("gainsboro", new int[] { 0xdc, 0xdc, 0xdc, 0x00 });
NAMES.put("ghostwhite", new int[] { 0xf8, 0xf8, 0xff, 0x00 });
NAMES.put("gold", new int[] { 0xff, 0xd7, 0x00, 0x00 });
NAMES.put("goldenrod", new int[] { 0xda, 0xa5, 0x20, 0x00 });
NAMES.put("gray", new int[] { 0x80, 0x80, 0x80, 0x00 });
NAMES.put("green", new int[] { 0x00, 0x80, 0x00, 0x00 });
NAMES.put("greenyellow", new int[] { 0xad, 0xff, 0x2f, 0x00 });
NAMES.put("honeydew", new int[] { 0xf0, 0xff, 0xf0, 0x00 });
NAMES.put("hotpink", new int[] { 0xff, 0x69, 0xb4, 0x00 });
NAMES.put("indianred", new int[] { 0xcd, 0x5c, 0x5c, 0x00 });
NAMES.put("indigo", new int[] { 0x4b, 0x00, 0x82, 0x00 });
NAMES.put("ivory", new int[] { 0xff, 0xff, 0xf0, 0x00 });
NAMES.put("khaki", new int[] { 0xf0, 0xe6, 0x8c, 0x00 });
NAMES.put("lavender", new int[] { 0xe6, 0xe6, 0xfa, 0x00 });
NAMES.put("lavenderblush", new int[] { 0xff, 0xf0, 0xf5, 0x00 });
NAMES.put("lawngreen", new int[] { 0x7c, 0xfc, 0x00, 0x00 });
NAMES.put("lemonchiffon", new int[] { 0xff, 0xfa, 0xcd, 0x00 });
NAMES.put("lightblue", new int[] { 0xad, 0xd8, 0xe6, 0x00 });
NAMES.put("lightcoral", new int[] { 0xf0, 0x80, 0x80, 0x00 });
NAMES.put("lightcyan", new int[] { 0xe0, 0xff, 0xff, 0x00 });
NAMES.put("lightgoldenrodyellow", new int[] { 0xfa, 0xfa, 0xd2, 0x00 });
NAMES.put("lightgreen", new int[] { 0x90, 0xee, 0x90, 0x00 });
NAMES.put("lightgrey", new int[] { 0xd3, 0xd3, 0xd3, 0x00 });
NAMES.put("lightpink", new int[] { 0xff, 0xb6, 0xc1, 0x00 });
NAMES.put("lightsalmon", new int[] { 0xff, 0xa0, 0x7a, 0x00 });
NAMES.put("lightseagreen", new int[] { 0x20, 0xb2, 0xaa, 0x00 });
NAMES.put("lightskyblue", new int[] { 0x87, 0xce, 0xfa, 0x00 });
NAMES.put("lightslategray", new int[] { 0x77, 0x88, 0x99, 0x00 });
NAMES.put("lightsteelblue", new int[] { 0xb0, 0xc4, 0xde, 0x00 });
NAMES.put("lightyellow", new int[] { 0xff, 0xff, 0xe0, 0x00 });
NAMES.put("lime", new int[] { 0x00, 0xff, 0x00, 0x00 });
NAMES.put("limegreen", new int[] { 0x32, 0xcd, 0x32, 0x00 });
NAMES.put("linen", new int[] { 0xfa, 0xf0, 0xe6, 0x00 });
NAMES.put("magenta", new int[] { 0xff, 0x00, 0xff, 0x00 });
NAMES.put("maroon", new int[] { 0x80, 0x00, 0x00, 0x00 });
NAMES.put("mediumaquamarine", new int[] { 0x66, 0xcd, 0xaa, 0x00 });
NAMES.put("mediumblue", new int[] { 0x00, 0x00, 0xcd, 0x00 });
NAMES.put("mediumorchid", new int[] { 0xba, 0x55, 0xd3, 0x00 });
NAMES.put("mediumpurple", new int[] { 0x93, 0x70, 0xdb, 0x00 });
NAMES.put("mediumseagreen", new int[] { 0x3c, 0xb3, 0x71, 0x00 });
NAMES.put("mediumslateblue", new int[] { 0x7b, 0x68, 0xee, 0x00 });
NAMES.put("mediumspringgreen", new int[] { 0x00, 0xfa, 0x9a, 0x00 });
NAMES.put("mediumturquoise", new int[] { 0x48, 0xd1, 0xcc, 0x00 });
NAMES.put("mediumvioletred", new int[] { 0xc7, 0x15, 0x85, 0x00 });
NAMES.put("midnightblue", new int[] { 0x19, 0x19, 0x70, 0x00 });
NAMES.put("mintcream", new int[] { 0xf5, 0xff, 0xfa, 0x00 });
NAMES.put("mistyrose", new int[] { 0xff, 0xe4, 0xe1, 0x00 });
NAMES.put("moccasin", new int[] { 0xff, 0xe4, 0xb5, 0x00 });
NAMES.put("navajowhite", new int[] { 0xff, 0xde, 0xad, 0x00 });
NAMES.put("navy", new int[] { 0x00, 0x00, 0x80, 0x00 });
NAMES.put("oldlace", new int[] { 0xfd, 0xf5, 0xe6, 0x00 });
NAMES.put("olive", new int[] { 0x80, 0x80, 0x00, 0x00 });
NAMES.put("olivedrab", new int[] { 0x6b, 0x8e, 0x23, 0x00 });
NAMES.put("orange", new int[] { 0xff, 0xa5, 0x00, 0x00 });
NAMES.put("orangered", new int[] { 0xff, 0x45, 0x00, 0x00 });
NAMES.put("orchid", new int[] { 0xda, 0x70, 0xd6, 0x00 });
NAMES.put("palegoldenrod", new int[] { 0xee, 0xe8, 0xaa, 0x00 });
NAMES.put("palegreen", new int[] { 0x98, 0xfb, 0x98, 0x00 });
NAMES.put("paleturquoise", new int[] { 0xaf, 0xee, 0xee, 0x00 });
NAMES.put("palevioletred", new int[] { 0xdb, 0x70, 0x93, 0x00 });
NAMES.put("papayawhip", new int[] { 0xff, 0xef, 0xd5, 0x00 });
NAMES.put("peachpuff", new int[] { 0xff, 0xda, 0xb9, 0x00 });
NAMES.put("peru", new int[] { 0xcd, 0x85, 0x3f, 0x00 });
NAMES.put("pink", new int[] { 0xff, 0xc0, 0xcb, 0x00 });
NAMES.put("plum", new int[] { 0xdd, 0xa0, 0xdd, 0x00 });
NAMES.put("powderblue", new int[] { 0xb0, 0xe0, 0xe6, 0x00 });
NAMES.put("purple", new int[] { 0x80, 0x00, 0x80, 0x00 });
NAMES.put("red", new int[] { 0xff, 0x00, 0x00, 0x00 });
NAMES.put("rosybrown", new int[] { 0xbc, 0x8f, 0x8f, 0x00 });
NAMES.put("royalblue", new int[] { 0x41, 0x69, 0xe1, 0x00 });
NAMES.put("saddlebrown", new int[] { 0x8b, 0x45, 0x13, 0x00 });
NAMES.put("salmon", new int[] { 0xfa, 0x80, 0x72, 0x00 });
NAMES.put("sandybrown", new int[] { 0xf4, 0xa4, 0x60, 0x00 });
NAMES.put("seagreen", new int[] { 0x2e, 0x8b, 0x57, 0x00 });
NAMES.put("seashell", new int[] { 0xff, 0xf5, 0xee, 0x00 });
NAMES.put("sienna", new int[] { 0xa0, 0x52, 0x2d, 0x00 });
NAMES.put("silver", new int[] { 0xc0, 0xc0, 0xc0, 0x00 });
NAMES.put("skyblue", new int[] { 0x87, 0xce, 0xeb, 0x00 });
NAMES.put("slateblue", new int[] { 0x6a, 0x5a, 0xcd, 0x00 });
NAMES.put("slategray", new int[] { 0x70, 0x80, 0x90, 0x00 });
NAMES.put("snow", new int[] { 0xff, 0xfa, 0xfa, 0x00 });
NAMES.put("springgreen", new int[] { 0x00, 0xff, 0x7f, 0x00 });
NAMES.put("steelblue", new int[] { 0x46, 0x82, 0xb4, 0x00 });
NAMES.put("tan", new int[] { 0xd2, 0xb4, 0x8c, 0x00 });
NAMES.put("transparent", new int[] { 0x00, 0x00, 0x00, 0xff });
NAMES.put("teal", new int[] { 0x00, 0x80, 0x80, 0x00 });
NAMES.put("thistle", new int[] { 0xd8, 0xbf, 0xd8, 0x00 });
NAMES.put("tomato", new int[] { 0xff, 0x63, 0x47, 0x00 });
NAMES.put("turquoise", new int[] { 0x40, 0xe0, 0xd0, 0x00 });
NAMES.put("violet", new int[] { 0xee, 0x82, 0xee, 0x00 });
NAMES.put("wheat", new int[] { 0xf5, 0xde, 0xb3, 0x00 });
NAMES.put("white", new int[] { 0xff, 0xff, 0xff, 0x00 });
NAMES.put("whitesmoke", new int[] { 0xf5, 0xf5, 0xf5, 0x00 });
NAMES.put("yellow", new int[] { 0xff, 0xff, 0x00, 0x00 });
NAMES.put("yellowgreen", new int[] { 0x9, 0xacd, 0x32, 0x00 });
}
/**
* Gives you a Color based on a name.
*
* @param name
* a name such as black, violet, cornflowerblue or #RGB or #RRGGBB
* or rgb(R,G,B)
* @return the corresponding Color object
* @throws IllegalArgumentException
* if the String isn't a know representation of a color.
*/
public static Color getRGBColor(String name)
throws IllegalArgumentException {
int[] c = { 0, 0, 0, 0 };
if (name.startsWith("#")) {
if (name.length() == 4) {
c[0] = Integer.parseInt(name.substring(1, 2), 16) * 16;
c[1] = Integer.parseInt(name.substring(2, 3), 16) * 16;
c[2] = Integer.parseInt(name.substring(3), 16) * 16;
return new Color(c[0], c[1], c[2], c[3]);
}
if (name.length() == 7) {
c[0] = Integer.parseInt(name.substring(1, 3), 16);
c[1] = Integer.parseInt(name.substring(3, 5), 16);
c[2] = Integer.parseInt(name.substring(5), 16);
return new Color(c[0], c[1], c[2], c[3]);
}
throw new IllegalArgumentException(
"Unknown color format. Must be #RGB or #RRGGBB");
}
else if (name.startsWith("rgb(")) {
StringTokenizer tok = new StringTokenizer(name, "rgb(), \t\r\n\f");
for (int k = 0; k < 3; ++k) {
String v = tok.nextToken();
if (v.endsWith("%"))
c[k] = Integer.parseInt(v.substring(0, v.length() - 1)) * 255 / 100;
else
c[k] = Integer.parseInt(v);
if (c[k] < 0)
c[k] = 0;
else if (c[k] > 255)
c[k] = 255;
}
return new Color(c[0], c[1], c[2], c[3]);
}
name = name.toLowerCase();
if (!NAMES.containsKey(name))
throw new IllegalArgumentException("Color '" + name
+ "' not found.");
c = (int[]) NAMES.get(name);
return new Color(c[0], c[1], c[2], c[3]);
}
} src/core/com/lowagie/text/html/simpleparser/ALink.java 100644 0 0 5121 11000354011 20410 0 ustar 0 0 /*
* Copyright 2005 Paulo Soares
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.html.simpleparser;
import com.lowagie.text.Paragraph;
/**
*
* @author psoares
*/
public interface ALink {
boolean process(Paragraph current, ChainedProperties cprops);
}
src/core/com/lowagie/text/html/simpleparser/ChainedProperties.java 100644 0 0 11014 11213370067 23057 0 ustar 0 0 /*
* Copyright 2004 Paulo Soares
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.
*
* Contributions by:
* Lubos Strapko
*
* 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.html.simpleparser;
import com.lowagie.text.ElementTags;
import java.util.ArrayList;
import java.util.HashMap;
public class ChainedProperties {
public final static int fontSizes[] = { 8, 10, 12, 14, 18, 24, 36 };
public ArrayList chain = new ArrayList();
/** Creates a new instance of ChainedProperties */
public ChainedProperties() {
}
public String getProperty(String key) {
for (int k = chain.size() - 1; k >= 0; --k) {
Object obj[] = (Object[]) chain.get(k);
HashMap prop = (HashMap) obj[1];
String ret = (String) prop.get(key);
if (ret != null)
return ret;
}
return null;
}
public boolean hasProperty(String key) {
for (int k = chain.size() - 1; k >= 0; --k) {
Object obj[] = (Object[]) chain.get(k);
HashMap prop = (HashMap) obj[1];
if (prop.containsKey(key))
return true;
}
return false;
}
public void addToChain(String key, HashMap prop) {
// adjust the font size
String value = (String) prop.get(ElementTags.SIZE);
if (value != null) {
if (value.endsWith("pt")) {
prop.put(ElementTags.SIZE, value.substring(0,
value.length() - 2));
} else {
int s = 0;
if (value.startsWith("+") || value.startsWith("-")) {
String old = getProperty("basefontsize");
if (old == null)
old = "12";
float f = Float.parseFloat(old);
int c = (int) f;
for (int k = fontSizes.length - 1; k >= 0; --k) {
if (c >= fontSizes[k]) {
s = k;
break;
}
}
int inc = Integer.parseInt(value.startsWith("+") ? value
.substring(1) : value);
s += inc;
} else {
try {
s = Integer.parseInt(value) - 1;
} catch (NumberFormatException nfe) {
s = 0;
}
}
if (s < 0)
s = 0;
else if (s >= fontSizes.length)
s = fontSizes.length - 1;
prop.put(ElementTags.SIZE, Integer.toString(fontSizes[s]));
}
}
chain.add(new Object[] { key, prop });
}
public void removeChain(String key) {
for (int k = chain.size() - 1; k >= 0; --k) {
if (key.equals(((Object[]) chain.get(k))[0])) {
chain.remove(k);
return;
}
}
}
}
src/core/com/lowagie/text/html/simpleparser/FactoryProperties.java 100644 0 0 32636 11215636056 23155 0 ustar 0 0 /*
* Copyright 2004 Paulo Soares
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.
*
* Contributions by:
* Lubos Strapko
*
* 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.html.simpleparser;
import java.awt.Color;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import com.lowagie.text.Chunk;
import com.lowagie.text.Element;
import com.lowagie.text.ElementTags;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.FontFactoryImp;
import com.lowagie.text.ListItem;
import com.lowagie.text.Paragraph;
import com.lowagie.text.html.Markup;
import com.lowagie.text.html.HtmlTags;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.HyphenationAuto;
import com.lowagie.text.pdf.HyphenationEvent;
/**
*
* @author psoares
*/
public class FactoryProperties {
private FontFactoryImp fontImp = FontFactory.getFontImp();
/** Creates a new instance of FactoryProperties */
public FactoryProperties() {
}
public Chunk createChunk(String text, ChainedProperties props) {
Font font = getFont(props);
float size = font.getSize();
size /= 2;
Chunk ck = new Chunk(text, font);
if (props.hasProperty("sub"))
ck.setTextRise(-size);
else if (props.hasProperty("sup"))
ck.setTextRise(size);
ck.setHyphenation(getHyphenation(props));
return ck;
}
private static void setParagraphLeading(Paragraph p, String leading) {
if (leading == null) {
p.setLeading(0, 1.5f);
return;
}
try {
StringTokenizer tk = new StringTokenizer(leading, " ,");
String v = tk.nextToken();
float v1 = Float.parseFloat(v);
if (!tk.hasMoreTokens()) {
p.setLeading(v1, 0);
return;
}
v = tk.nextToken();
float v2 = Float.parseFloat(v);
p.setLeading(v1, v2);
} catch (Exception e) {
p.setLeading(0, 1.5f);
}
}
public static void createParagraph(Paragraph p, ChainedProperties props) {
String value = props.getProperty("align");
if (value != null) {
if (value.equalsIgnoreCase("center"))
p.setAlignment(Element.ALIGN_CENTER);
else if (value.equalsIgnoreCase("right"))
p.setAlignment(Element.ALIGN_RIGHT);
else if (value.equalsIgnoreCase("justify"))
p.setAlignment(Element.ALIGN_JUSTIFIED);
}
p.setHyphenation(getHyphenation(props));
setParagraphLeading(p, props.getProperty("leading"));
value = props.getProperty("before");
if (value != null) {
try {
p.setSpacingBefore(Float.parseFloat(value));
} catch (Exception e) {
}
}
value = props.getProperty("after");
if (value != null) {
try {
p.setSpacingAfter(Float.parseFloat(value));
} catch (Exception e) {
}
}
value = props.getProperty("extraparaspace");
if (value != null) {
try {
p.setExtraParagraphSpace(Float.parseFloat(value));
} catch (Exception e) {
}
}
}
public static Paragraph createParagraph(ChainedProperties props) {
Paragraph p = new Paragraph();
createParagraph(p, props);
return p;
}
public static ListItem createListItem(ChainedProperties props) {
ListItem p = new ListItem();
createParagraph(p, props);
return p;
}
public Font getFont(ChainedProperties props) {
String face = props.getProperty(ElementTags.FACE);
if (face != null) {
StringTokenizer tok = new StringTokenizer(face, ",");
while (tok.hasMoreTokens()) {
face = tok.nextToken().trim();
if (face.startsWith("\""))
face = face.substring(1);
if (face.endsWith("\""))
face = face.substring(0, face.length() - 1);
if (fontImp.isRegistered(face))
break;
}
}
int style = 0;
if (props.hasProperty(HtmlTags.I))
style |= Font.ITALIC;
if (props.hasProperty(HtmlTags.B))
style |= Font.BOLD;
if (props.hasProperty(HtmlTags.U))
style |= Font.UNDERLINE;
if (props.hasProperty(HtmlTags.S))
style |= Font.STRIKETHRU;
String value = props.getProperty(ElementTags.SIZE);
float size = 12;
if (value != null)
size = Float.parseFloat(value);
Color color = Markup.decodeColor(props.getProperty("color"));
String encoding = props.getProperty("encoding");
if (encoding == null)
encoding = BaseFont.WINANSI;
return fontImp.getFont(face, encoding, true, size, style, color);
}
/**
* Gets a HyphenationEvent based on the hyphenation entry in ChainedProperties.
* @param props ChainedProperties
* @return a HyphenationEvent
* @since 2.1.2
*/
public static HyphenationEvent getHyphenation(ChainedProperties props) {
return getHyphenation(props.getProperty("hyphenation"));
}
/**
* Gets a HyphenationEvent based on the hyphenation entry in a HashMap.
* @param props a HashMap with properties
* @return a HyphenationEvent
* @since 2.1.2
*/
public static HyphenationEvent getHyphenation(HashMap props) {
return getHyphenation((String) props.get("hyphenation"));
}
/**
* Gets a HyphenationEvent based on a String.
* For instance "en_UK,3,2" returns new HyphenationAuto("en", "UK", 3, 2);
* @param s a String, for instance "en_UK,2,2"
* @return a HyphenationEvent
* @since 2.1.2
*/
public static HyphenationEvent getHyphenation(String s) {
if (s == null || s.length() == 0) {
return null;
}
String lang = s;
String country = null;
int leftMin = 2;
int rightMin = 2;
int pos = s.indexOf('_');
if (pos == -1) {
return new HyphenationAuto(lang, country, leftMin, rightMin);
}
lang = s.substring(0, pos);
country = s.substring(pos + 1);
pos = country.indexOf(',');
if (pos == -1) {
return new HyphenationAuto(lang, country, leftMin, rightMin);
}
s = country.substring(pos + 1);
country = country.substring(0, pos);
pos = s.indexOf(',');
if (pos == -1) {
leftMin = Integer.parseInt(s);
} else {
leftMin = Integer.parseInt(s.substring(0, pos));
rightMin = Integer.parseInt(s.substring(pos + 1));
}
return new HyphenationAuto(lang, country, leftMin, rightMin);
}
/**
* This method isn't used by iText, but you can use it to analyze
* the value of a style attribute inside a HashMap.
* The different elements of the style attribute are added to the
* HashMap as key-value pairs.
* @param h a HashMap that should have at least a key named
* style. After this method is invoked, more keys could be added.
*/
public static void insertStyle(HashMap h) {
String style = (String) h.get("style");
if (style == null)
return;
Properties prop = Markup.parseAttributes(style);
for (Iterator it = prop.keySet().iterator(); it.hasNext();) {
String key = (String) it.next();
if (key.equals(Markup.CSS_KEY_FONTFAMILY)) {
h.put("face", prop.getProperty(key));
} else if (key.equals(Markup.CSS_KEY_FONTSIZE)) {
h.put("size", Float.toString(Markup.parseLength(prop
.getProperty(key)))
+ "pt");
} else if (key.equals(Markup.CSS_KEY_FONTSTYLE)) {
String ss = prop.getProperty(key).trim().toLowerCase();
if (ss.equals("italic") || ss.equals("oblique"))
h.put("i", null);
} else if (key.equals(Markup.CSS_KEY_FONTWEIGHT)) {
String ss = prop.getProperty(key).trim().toLowerCase();
if (ss.equals("bold") || ss.equals("700") || ss.equals("800")
|| ss.equals("900"))
h.put("b", null);
} else if (key.equals(Markup.CSS_KEY_TEXTDECORATION)) {
String ss = prop.getProperty(key).trim().toLowerCase();
if (ss.equals(Markup.CSS_VALUE_UNDERLINE))
h.put("u", null);
} else if (key.equals(Markup.CSS_KEY_COLOR)) {
Color c = Markup.decodeColor(prop.getProperty(key));
if (c != null) {
int hh = c.getRGB();
String hs = Integer.toHexString(hh);
hs = "000000" + hs;
hs = "#" + hs.substring(hs.length() - 6);
h.put("color", hs);
}
} else if (key.equals(Markup.CSS_KEY_LINEHEIGHT)) {
String ss = prop.getProperty(key).trim();
float v = Markup.parseLength(prop.getProperty(key));
if (ss.endsWith("%")) {
h.put("leading", "0," + (v / 100));
} else if ("normal".equalsIgnoreCase(ss)) {
h.put("leading", "0,1.5");
}
else {
h.put("leading", v + ",0");
}
} else if (key.equals(Markup.CSS_KEY_TEXTALIGN)) {
String ss = prop.getProperty(key).trim().toLowerCase();
h.put("align", ss);
}
}
}
/**
* New method contributed by Lubos Strapko
* @param h
* @param cprops
* @since 2.1.3
*/
public static void insertStyle(HashMap h, ChainedProperties cprops) {
String style = (String) h.get("style");
if (style == null)
return;
Properties prop = Markup.parseAttributes(style);
for (Iterator it = prop.keySet().iterator(); it.hasNext();) {
String key = (String) it.next();
if (key.equals(Markup.CSS_KEY_FONTFAMILY)) {
h.put(ElementTags.FACE, prop.getProperty(key));
} else if (key.equals(Markup.CSS_KEY_FONTSIZE)) {
float actualFontSize = Markup.parseLength(cprops
.getProperty(ElementTags.SIZE),
Markup.DEFAULT_FONT_SIZE);
if (actualFontSize <= 0f)
actualFontSize = Markup.DEFAULT_FONT_SIZE;
h.put(ElementTags.SIZE, Float.toString(Markup.parseLength(prop
.getProperty(key), actualFontSize))
+ "pt");
} else if (key.equals(Markup.CSS_KEY_FONTSTYLE)) {
String ss = prop.getProperty(key).trim().toLowerCase();
if (ss.equals("italic") || ss.equals("oblique"))
h.put("i", null);
} else if (key.equals(Markup.CSS_KEY_FONTWEIGHT)) {
String ss = prop.getProperty(key).trim().toLowerCase();
if (ss.equals("bold") || ss.equals("700") || ss.equals("800")
|| ss.equals("900"))
h.put("b", null);
} else if (key.equals(Markup.CSS_KEY_TEXTDECORATION)) {
String ss = prop.getProperty(key).trim().toLowerCase();
if (ss.equals(Markup.CSS_VALUE_UNDERLINE))
h.put("u", null);
} else if (key.equals(Markup.CSS_KEY_COLOR)) {
Color c = Markup.decodeColor(prop.getProperty(key));
if (c != null) {
int hh = c.getRGB();
String hs = Integer.toHexString(hh);
hs = "000000" + hs;
hs = "#" + hs.substring(hs.length() - 6);
h.put("color", hs);
}
} else if (key.equals(Markup.CSS_KEY_LINEHEIGHT)) {
String ss = prop.getProperty(key).trim();
float actualFontSize = Markup.parseLength(cprops
.getProperty(ElementTags.SIZE),
Markup.DEFAULT_FONT_SIZE);
if (actualFontSize <= 0f)
actualFontSize = Markup.DEFAULT_FONT_SIZE;
float v = Markup.parseLength(prop.getProperty(key),
actualFontSize);
if (ss.endsWith("%")) {
h.put("leading", "0," + (v / 100));
return;
}
if ("normal".equalsIgnoreCase(ss)) {
h.put("leading", "0,1.5");
return;
}
h.put("leading", v + ",0");
} else if (key.equals(Markup.CSS_KEY_TEXTALIGN)) {
String ss = prop.getProperty(key).trim().toLowerCase();
h.put("align", ss);
} else if (key.equals(Markup.CSS_KEY_PADDINGLEFT)) {
String ss = prop.getProperty(key).trim().toLowerCase();
h.put("indent", Float.toString(Markup.parseLength(ss)));
}
}
}
public FontFactoryImp getFontImp() {
return fontImp;
}
public void setFontImp(FontFactoryImp fontImp) {
this.fontImp = fontImp;
}
public static HashMap followTags = new HashMap();
static {
followTags.put("i", "i");
followTags.put("b", "b");
followTags.put("u", "u");
followTags.put("sub", "sub");
followTags.put("sup", "sup");
followTags.put("em", "i");
followTags.put("strong", "b");
followTags.put("s", "s");
followTags.put("strike", "s");
}
}
src/core/com/lowagie/text/html/simpleparser/HTMLWorker.java 100644 0 0 51156 11215636056 21425 0 ustar 0 0 /*
* Copyright 2004 Paulo Soares
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.
*
* Contributions by:
* Lubos Strapko
*
* 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.html.simpleparser;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Stack;
import java.util.StringTokenizer;
import com.lowagie.text.html.HtmlTags;
import com.lowagie.text.html.Markup;
import com.lowagie.text.Chunk;
import com.lowagie.text.DocListener;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.ElementTags;
import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.FontFactoryImp;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.ListItem;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.TextElementArray;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.draw.LineSeparator;
import com.lowagie.text.xml.simpleparser.SimpleXMLDocHandler;
import com.lowagie.text.xml.simpleparser.SimpleXMLParser;
public class HTMLWorker implements SimpleXMLDocHandler, DocListener {
protected ArrayList objectList;
protected DocListener document;
private Paragraph currentParagraph;
private ChainedProperties cprops = new ChainedProperties();
private Stack stack = new Stack();
private boolean pendingTR = false;
private boolean pendingTD = false;
private boolean pendingLI = false;
private StyleSheet style = new StyleSheet();
private boolean isPRE = false;
private Stack tableState = new Stack();
private boolean skipText = false;
private HashMap interfaceProps;
private FactoryProperties factoryProperties = new FactoryProperties();
/** Creates a new instance of HTMLWorker
* @param document A class that implements DocListener
* */
public HTMLWorker(DocListener document) {
this.document = document;
}
public void setStyleSheet(StyleSheet style) {
this.style = style;
}
public StyleSheet getStyleSheet() {
return style;
}
public void setInterfaceProps(HashMap interfaceProps) {
this.interfaceProps = interfaceProps;
FontFactoryImp ff = null;
if (interfaceProps != null)
ff = (FontFactoryImp) interfaceProps.get("font_factory");
if (ff != null)
factoryProperties.setFontImp(ff);
}
public HashMap getInterfaceProps() {
return interfaceProps;
}
public void parse(Reader reader) throws IOException {
SimpleXMLParser.parse(this, null, reader, true);
}
public static ArrayList parseToList(Reader reader, StyleSheet style)
throws IOException {
return parseToList(reader, style, null);
}
public static ArrayList parseToList(Reader reader, StyleSheet style,
HashMap interfaceProps) throws IOException {
HTMLWorker worker = new HTMLWorker(null);
if (style != null)
worker.style = style;
worker.document = worker;
worker.setInterfaceProps(interfaceProps);
worker.objectList = new ArrayList();
worker.parse(reader);
return worker.objectList;
}
public void endDocument() {
try {
for (int k = 0; k < stack.size(); ++k)
document.add((Element) stack.elementAt(k));
if (currentParagraph != null)
document.add(currentParagraph);
currentParagraph = null;
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
public void startDocument() {
HashMap h = new HashMap();
style.applyStyle("body", h);
cprops.addToChain("body", h);
}
public void startElement(String tag, HashMap h) {
if (!tagsSupported.containsKey(tag))
return;
try {
style.applyStyle(tag, h);
String follow = (String) FactoryProperties.followTags.get(tag);
if (follow != null) {
HashMap prop = new HashMap();
prop.put(follow, null);
cprops.addToChain(follow, prop);
return;
}
FactoryProperties.insertStyle(h, cprops);
if (tag.equals(HtmlTags.ANCHOR)) {
cprops.addToChain(tag, h);
if (currentParagraph == null) {
currentParagraph = new Paragraph();
}
stack.push(currentParagraph);
currentParagraph = new Paragraph();
return;
}
if (tag.equals(HtmlTags.NEWLINE)) {
if (currentParagraph == null) {
currentParagraph = new Paragraph();
}
currentParagraph.add(factoryProperties
.createChunk("\n", cprops));
return;
}
if (tag.equals(HtmlTags.HORIZONTALRULE)) {
// Attempting to duplicate the behavior seen on Firefox with
// http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_hr_test
// where an initial break is only inserted when the preceding element doesn't
// end with a break, but a trailing break is always inserted.
boolean addLeadingBreak = true;
if (currentParagraph == null) {
currentParagraph = new Paragraph();
addLeadingBreak = false;
}
if (addLeadingBreak) { // Not a new paragraph
int numChunks = currentParagraph.getChunks().size();
if (numChunks == 0 ||
((Chunk)(currentParagraph.getChunks().get(numChunks - 1))).getContent().endsWith("\n"))
addLeadingBreak = false;
}
String align = (String) h.get("align");
int hrAlign = Element.ALIGN_CENTER;
if (align != null) {
if (align.equalsIgnoreCase("left"))
hrAlign = Element.ALIGN_LEFT;
if (align.equalsIgnoreCase("right"))
hrAlign = Element.ALIGN_RIGHT;
}
String width = (String) h.get("width");
float hrWidth = 1;
if (width != null) {
float tmpWidth = Markup.parseLength(width, Markup.DEFAULT_FONT_SIZE);
if (tmpWidth > 0) hrWidth = tmpWidth;
if (!width.endsWith("%"))
hrWidth = 100; // Treat a pixel width as 100% for now.
}
String size = (String) h.get("size");
float hrSize = 1;
if (size != null) {
float tmpSize = Markup.parseLength(size, Markup.DEFAULT_FONT_SIZE);
if (tmpSize > 0)
hrSize = tmpSize;
}
if (addLeadingBreak)
currentParagraph.add(Chunk.NEWLINE);
currentParagraph.add(new LineSeparator(hrSize, hrWidth, null, hrAlign, currentParagraph.getLeading()/2));
currentParagraph.add(Chunk.NEWLINE);
return;
}
if (tag.equals(HtmlTags.CHUNK) || tag.equals(HtmlTags.SPAN)) {
cprops.addToChain(tag, h);
return;
}
if (tag.equals(HtmlTags.IMAGE)) {
String src = (String) h.get(ElementTags.SRC);
if (src == null)
return;
cprops.addToChain(tag, h);
Image img = null;
if (interfaceProps != null) {
ImageProvider ip = (ImageProvider) interfaceProps
.get("img_provider");
if (ip != null)
img = ip.getImage(src, h, cprops, document);
if (img == null) {
HashMap images = (HashMap) interfaceProps
.get("img_static");
if (images != null) {
Image tim = (Image) images.get(src);
if (tim != null)
img = Image.getInstance(tim);
} else {
if (!src.startsWith("http")) { // relative src references only
String baseurl = (String) interfaceProps
.get("img_baseurl");
if (baseurl != null) {
src = baseurl + src;
img = Image.getInstance(src);
}
}
}
}
}
if (img == null) {
if (!src.startsWith("http")) {
String path = cprops.getProperty("image_path");
if (path == null)
path = "";
src = new File(path, src).getPath();
}
img = Image.getInstance(src);
}
String align = (String) h.get("align");
String width = (String) h.get("width");
String height = (String) h.get("height");
String before = cprops.getProperty("before");
String after = cprops.getProperty("after");
if (before != null)
img.setSpacingBefore(Float.parseFloat(before));
if (after != null)
img.setSpacingAfter(Float.parseFloat(after));
float actualFontSize = Markup.parseLength(cprops
.getProperty(ElementTags.SIZE),
Markup.DEFAULT_FONT_SIZE);
if (actualFontSize <= 0f)
actualFontSize = Markup.DEFAULT_FONT_SIZE;
float widthInPoints = Markup.parseLength(width, actualFontSize);
float heightInPoints = Markup.parseLength(height,
actualFontSize);
if (widthInPoints > 0 && heightInPoints > 0) {
img.scaleAbsolute(widthInPoints, heightInPoints);
} else if (widthInPoints > 0) {
heightInPoints = img.getHeight() * widthInPoints
/ img.getWidth();
img.scaleAbsolute(widthInPoints, heightInPoints);
} else if (heightInPoints > 0) {
widthInPoints = img.getWidth() * heightInPoints
/ img.getHeight();
img.scaleAbsolute(widthInPoints, heightInPoints);
}
img.setWidthPercentage(0);
if (align != null) {
endElement("p");
int ralign = Image.MIDDLE;
if (align.equalsIgnoreCase("left"))
ralign = Image.LEFT;
else if (align.equalsIgnoreCase("right"))
ralign = Image.RIGHT;
img.setAlignment(ralign);
Img i = null;
boolean skip = false;
if (interfaceProps != null) {
i = (Img) interfaceProps.get("img_interface");
if (i != null)
skip = i.process(img, h, cprops, document);
}
if (!skip)
document.add(img);
cprops.removeChain(tag);
} else {
cprops.removeChain(tag);
if (currentParagraph == null) {
currentParagraph = FactoryProperties
.createParagraph(cprops);
}
currentParagraph.add(new Chunk(img, 0, 0));
}
return;
}
endElement("p");
if (tag.equals("h1") || tag.equals("h2") || tag.equals("h3")
|| tag.equals("h4") || tag.equals("h5") || tag.equals("h6")) {
if (!h.containsKey(ElementTags.SIZE)) {
int v = 7 - Integer.parseInt(tag.substring(1));
h.put(ElementTags.SIZE, Integer.toString(v));
}
cprops.addToChain(tag, h);
return;
}
if (tag.equals(HtmlTags.UNORDEREDLIST)) {
if (pendingLI)
endElement(HtmlTags.LISTITEM);
skipText = true;
cprops.addToChain(tag, h);
com.lowagie.text.List list = new com.lowagie.text.List(false);
try{
list.setIndentationLeft(new Float(cprops.getProperty("indent")).floatValue());
}catch (Exception e) {
list.setAutoindent(true);
}
list.setListSymbol("\u2022");
stack.push(list);
return;
}
if (tag.equals(HtmlTags.ORDEREDLIST)) {
if (pendingLI)
endElement(HtmlTags.LISTITEM);
skipText = true;
cprops.addToChain(tag, h);
com.lowagie.text.List list = new com.lowagie.text.List(true);
try{
list.setIndentationLeft(new Float(cprops.getProperty("indent")).floatValue());
}catch (Exception e) {
list.setAutoindent(true);
}
stack.push(list);
return;
}
if (tag.equals(HtmlTags.LISTITEM)) {
if (pendingLI)
endElement(HtmlTags.LISTITEM);
skipText = false;
pendingLI = true;
cprops.addToChain(tag, h);
ListItem item = FactoryProperties.createListItem(cprops);
stack.push(item);
return;
}
if (tag.equals(HtmlTags.DIV) || tag.equals(HtmlTags.BODY) || tag.equals("p")) {
cprops.addToChain(tag, h);
return;
}
if (tag.equals(HtmlTags.PRE)) {
if (!h.containsKey(ElementTags.FACE)) {
h.put(ElementTags.FACE, "Courier");
}
cprops.addToChain(tag, h);
isPRE = true;
return;
}
if (tag.equals("tr")) {
if (pendingTR)
endElement("tr");
skipText = true;
pendingTR = true;
cprops.addToChain("tr", h);
return;
}
if (tag.equals("td") || tag.equals("th")) {
if (pendingTD)
endElement(tag);
skipText = false;
pendingTD = true;
cprops.addToChain("td", h);
stack.push(new IncCell(tag, cprops));
return;
}
if (tag.equals("table")) {
cprops.addToChain("table", h);
IncTable table = new IncTable(h);
stack.push(table);
tableState.push(new boolean[] { pendingTR, pendingTD });
pendingTR = pendingTD = false;
skipText = true;
return;
}
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
public void endElement(String tag) {
if (!tagsSupported.containsKey(tag))
return;
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();
}
boolean skip = false;
if (interfaceProps != null) {
ALink 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();
int size = chunks.size();
for (int k = 0; k < 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(HtmlTags.UNORDEREDLIST)
|| tag.equals(HtmlTags.ORDEREDLIST)) {
if (pendingLI)
endElement(HtmlTags.LISTITEM);
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(HtmlTags.LISTITEM)) {
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(HtmlTags.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);
}
}
public void text(String str) {
if (skipText)
return;
String content = str;
if (isPRE) {
if (currentParagraph == null) {
currentParagraph = FactoryProperties.createParagraph(cprops);
}
Chunk chunk = factoryProperties.createChunk(content, cprops);
currentParagraph.add(chunk);
return;
}
if (content.trim().length() == 0 && content.indexOf(' ') < 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 (currentParagraph == null) {
currentParagraph = FactoryProperties.createParagraph(cprops);
}
Chunk chunk = factoryProperties.createChunk(buf.toString(), cprops);
currentParagraph.add(chunk);
}
public boolean add(Element element) throws DocumentException {
objectList.add(element);
return true;
}
public void clearTextWrap() throws DocumentException {
}
public void close() {
}
public boolean newPage() {
return true;
}
public void open() {
}
public void resetFooter() {
}
public void resetHeader() {
}
public void resetPageCount() {
}
public void setFooter(HeaderFooter footer) {
}
public void setHeader(HeaderFooter header) {
}
public boolean setMarginMirroring(boolean marginMirroring) {
return false;
}
/**
* @see com.lowagie.text.DocListener#setMarginMirroring(boolean)
* @since 2.1.6
*/
public boolean setMarginMirroringTopBottom(boolean marginMirroring) {
return false;
}
public boolean setMargins(float marginLeft, float marginRight,
float marginTop, float marginBottom) {
return true;
}
public void setPageCount(int pageN) {
}
public boolean setPageSize(Rectangle pageSize) {
return true;
}
public static final String tagsSupportedString = "ol ul li a pre font span br p div body table td th tr i b u sub sup em strong s strike"
+ " h1 h2 h3 h4 h5 h6 img hr";
public static final HashMap tagsSupported = new HashMap();
static {
StringTokenizer tok = new StringTokenizer(tagsSupportedString);
while (tok.hasMoreTokens())
tagsSupported.put(tok.nextToken(), null);
}
}
src/core/com/lowagie/text/html/simpleparser/ImageProvider.java 100644 0 0 5304 11000354011 22152 0 ustar 0 0 /*
* Copyright 2007 Paulo Soares
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.html.simpleparser;
import com.lowagie.text.DocListener;
import com.lowagie.text.Image;
import java.util.HashMap;
public interface ImageProvider {
Image getImage(String src, HashMap h, ChainedProperties cprops, DocListener doc);
}
src/core/com/lowagie/text/html/simpleparser/Img.java 100644 0 0 5240 11000354011 20130 0 ustar 0 0 /*
* Copyright 2005 Paulo Soares
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.html.simpleparser;
import java.util.HashMap;
import com.lowagie.text.DocListener;
import com.lowagie.text.Image;
/**
*
* @author psoares
*/
public interface Img {
boolean process(Image img, HashMap h, ChainedProperties cprops, DocListener doc);
}
src/core/com/lowagie/text/html/simpleparser/IncCell.java 100644 0 0 12417 11000354011 20751 0 ustar 0 0 /*
* Copyright 2004 Paulo Soares
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.html.simpleparser;
import java.util.ArrayList;
import com.lowagie.text.Element;
import com.lowagie.text.ElementListener;
import com.lowagie.text.Phrase;
import com.lowagie.text.TextElementArray;
import com.lowagie.text.html.Markup;
import com.lowagie.text.pdf.PdfPCell;
/**
*
* @author psoares
*/
public class IncCell implements TextElementArray {
private ArrayList chunks = new ArrayList();
private PdfPCell cell;
/** Creates a new instance of IncCell */
public IncCell(String tag, ChainedProperties props) {
cell = new PdfPCell((Phrase)null);
String value = props.getProperty("colspan");
if (value != null)
cell.setColspan(Integer.parseInt(value));
value = props.getProperty("align");
if (tag.equals("th"))
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
if (value != null) {
if ("center".equalsIgnoreCase(value))
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
else if ("right".equalsIgnoreCase(value))
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
else if ("left".equalsIgnoreCase(value))
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
else if ("justify".equalsIgnoreCase(value))
cell.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
}
value = props.getProperty("valign");
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
if (value != null) {
if ("top".equalsIgnoreCase(value))
cell.setVerticalAlignment(Element.ALIGN_TOP);
else if ("bottom".equalsIgnoreCase(value))
cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
}
value = props.getProperty("border");
float border = 0;
if (value != null)
border = Float.parseFloat(value);
cell.setBorderWidth(border);
value = props.getProperty("cellpadding");
if (value != null)
cell.setPadding(Float.parseFloat(value));
cell.setUseDescender(true);
value = props.getProperty("bgcolor");
cell.setBackgroundColor(Markup.decodeColor(value));
}
public boolean add(Object o) {
if (!(o instanceof Element))
return false;
cell.addElement((Element)o);
return true;
}
public ArrayList getChunks() {
return chunks;
}
public boolean process(ElementListener listener) {
return true;
}
public int type() {
return Element.RECTANGLE;
}
public PdfPCell getCell() {
return cell;
}
/**
* @see com.lowagie.text.Element#isContent()
* @since iText 2.0.8
*/
public boolean isContent() {
return true;
}
/**
* @see com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return true;
}
} src/core/com/lowagie/text/html/simpleparser/IncTable.java 100644 0 0 10622 11000354011 21115 0 ustar 0 0 /*
* Copyright 2004 Paulo Soares
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.html.simpleparser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
/**
*
* @author psoares
*/
public class IncTable {
private HashMap props = new HashMap();
private ArrayList rows = new ArrayList();
private ArrayList cols;
/** Creates a new instance of IncTable */
public IncTable(HashMap props) {
this.props.putAll(props);
}
public void addCol(PdfPCell cell) {
if (cols == null)
cols = new ArrayList();
cols.add(cell);
}
public void addCols(ArrayList ncols) {
if (cols == null)
cols = new ArrayList(ncols);
else
cols.addAll(ncols);
}
public void endRow() {
if (cols != null) {
Collections.reverse(cols);
rows.add(cols);
cols = null;
}
}
public ArrayList getRows() {
return rows;
}
public PdfPTable buildTable() {
if (rows.isEmpty())
return new PdfPTable(1);
int ncol = 0;
ArrayList c0 = (ArrayList)rows.get(0);
for (int k = 0; k < c0.size(); ++k) {
ncol += ((PdfPCell)c0.get(k)).getColspan();
}
PdfPTable table = new PdfPTable(ncol);
String width = (String)props.get("width");
if (width == null)
table.setWidthPercentage(100);
else {
if (width.endsWith("%"))
table.setWidthPercentage(Float.parseFloat(width.substring(0, width.length() - 1)));
else {
table.setTotalWidth(Float.parseFloat(width));
table.setLockedWidth(true);
}
}
for (int row = 0; row < rows.size(); ++row) {
ArrayList col = (ArrayList)rows.get(row);
for (int k = 0; k < col.size(); ++k) {
table.addCell((PdfPCell)col.get(k));
}
}
return table;
}
}
src/core/com/lowagie/text/html/simpleparser/StyleSheet.java 100644 0 0 7631 11036112743 21530 0 ustar 0 0 /*
* Copyright 2004 Paulo Soares
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.
*
* Contributions by:
* Lubos Strapko
*
* 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.html.simpleparser;
import com.lowagie.text.html.Markup;
import java.util.HashMap;
public class StyleSheet {
public HashMap classMap = new HashMap();
public HashMap tagMap = new HashMap();
/** Creates a new instance of StyleSheet */
public StyleSheet() {
}
public void applyStyle(String tag, HashMap props) {
HashMap map = (HashMap) tagMap.get(tag.toLowerCase());
if (map != null) {
HashMap temp = new HashMap(map);
temp.putAll(props);
props.putAll(temp);
}
String cm = (String) props.get(Markup.HTML_ATTR_CSS_CLASS);
if (cm == null)
return;
map = (HashMap) classMap.get(cm.toLowerCase());
if (map == null)
return;
props.remove(Markup.HTML_ATTR_CSS_CLASS);
HashMap temp = new HashMap(map);
temp.putAll(props);
props.putAll(temp);
}
public void loadStyle(String style, HashMap props) {
classMap.put(style.toLowerCase(), props);
}
public void loadStyle(String style, String key, String value) {
style = style.toLowerCase();
HashMap props = (HashMap) classMap.get(style);
if (props == null) {
props = new HashMap();
classMap.put(style, props);
}
props.put(key, value);
}
public void loadTagStyle(String tag, HashMap props) {
tagMap.put(tag.toLowerCase(), props);
}
public void loadTagStyle(String tag, String key, String value) {
tag = tag.toLowerCase();
HashMap props = (HashMap) tagMap.get(tag);
if (props == null) {
props = new HashMap();
tagMap.put(tag, props);
}
props.put(key, value);
}
} src/core/com/lowagie/text/lgpl.txt 100644 0 0 55314 11000354131 14630 0 ustar 0 0 GNU LIBRARY GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the library GPL. It is
numbered 2 because it goes with version 2 of the ordinary GPL.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Library General Public License, applies to some
specially designated Free Software Foundation software, and to any
other libraries whose authors decide to use it. You can use it for
your libraries, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if
you distribute copies of the library, or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link a program with the library, you must provide
complete object files to the recipients so that they can relink them
with the library, after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
Our method of protecting your rights has two steps: (1) copyright
the library, and (2) offer you this license which gives you legal
permission to copy, distribute and/or modify the library.
Also, for each distributor's protection, we want to make certain
that everyone understands that there is no warranty for this free
library. If the library is modified by someone else and passed on, we
want its recipients to know that what they have is not the original
version, so that any problems introduced by others will not reflect on
the original authors' reputations.
.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that companies distributing free
software will individually obtain patent licenses, thus in effect
transforming the program into proprietary software. To prevent this,
we have made it clear that any patent must be licensed for everyone's
free use or not licensed at all.
Most GNU software, including some libraries, is covered by the ordinary
GNU General Public License, which was designed for utility programs. This
license, the GNU Library General Public License, applies to certain
designated libraries. This license is quite different from the ordinary
one; be sure to read it in full, and don't assume that anything in it is
the same as in the ordinary license.
The reason we have a separate public license for some libraries is that
they blur the distinction we usually make between modifying or adding to a
program and simply using it. Linking a program with a library, without
changing the library, is in some sense simply using the library, and is
analogous to running a utility program or application program. However, in
a textual and legal sense, the linked executable is a combined work, a
derivative of the original library, and the ordinary General Public License
treats it as such.
Because of this blurred distinction, using the ordinary General
Public License for libraries did not effectively promote software
sharing, because most developers did not use the libraries. We
concluded that weaker conditions might promote sharing better.
However, unrestricted linking of non-free programs would deprive the
users of those programs of all benefit from the free status of the
libraries themselves. This Library General Public License is intended to
permit developers of non-free programs to use free libraries, while
preserving your freedom as a user of such programs to change the free
libraries that are incorporated in them. (We have not seen how to achieve
this as regards changes in header files, but we have achieved it as regards
changes in the actual functions of the Library.) The hope is that this
will lead to faster development of free libraries.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, while the latter only
works together with the library.
Note that it is possible for a library to be covered by the ordinary
General Public License rather than by this special one.
.
GNU LIBRARY GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library which
contains a notice placed by the copyright holder or other authorized
party saying it may be distributed under the terms of this Library
General Public License (also called "this License"). Each licensee is
addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
.
6. As an exception to the Sections above, you may also compile or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
c) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
d) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the source code distributed need not include anything that is normally
distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Library General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
src/core/com/lowagie/text/misc_licenses.txt 100644 0 0 21714 11000354131 16507 0 ustar 0 0 (1)
ExceptionConverter:
The original version of this class was published in an article by Heinz Kabutz.
Read http://www.javaspecialists.co.za/archive/newsletter.do?issue=033&print=yes&locale=en_US
"This material from The Java(tm) Specialists' Newsletter by Maximum Solutions
(South Africa). Please contact Maximum Solutions for more information.
(2)
SimpleXMLParser:
The original version of this class was published in a JavaWorld article by Steven Brandt:
http://www.javaworld.com/javaworld/javatips/jw-javatip128.html
Jennifer Orr (JavaWorld) wrote: "You have permission to use the code appearing in
Steven Brandt's JavaWorld article, 'Java Tip 128: Create a quick-and-dirty XML parser.'
We ask that you reference the author as the creator and JavaWorld as the original publisher
of the code." Steven Brandt also agreed with the use of this class.
(3)
The following files contain material that was copyrighted by SUN:
com/lowagie/text/pdf/LZWDecoder.java (first appearance in iText: 2002-02-08)
com/lowagie/text/pdf/codec/BmpImage.java (first appearance in iText: 2003-06-20)
com/lowagie/text/pdf/codec/PngImage.java (first appearance in iText: 2003-04-25)
com/lowagie/text/pdf/codec/TIFFDirectory.java (first appearance in iText: 2003-04-09)
com/lowagie/text/pdf/codec/TIFFFaxDecoder.java (first appearance in iText: 2003-04-09)
com/lowagie/text/pdf/codec/TIFFField.java (first appearance in iText: 2003-04-09)
com/lowagie/text/pdf/codec/TIFFLZWDecoder.java (first appearance in iText: 2003-04-09)
The original code was released under the BSD license, and contained the following
extra restriction: "You acknowledge that Software is not designed, licensed or intended
for use in the design, construction, operation or maintenance of any nuclear facility."
In a mail sent to Bruno Lowagie on January 23, 2008, Brian Burkhalter (@sun.com)
writes: "This code is under a BSD license and supersedes the older codec packages
on which your code is based. It also includes numerous fixes among them being the
ability to handle a lot of 'broken' TIFFs."
Note that numerous fixes were applied to the code used in iText by Paulo Soares,
but apart from the fixes there were no essential changes between the code that
was originally adapted and the code that is now available under the following
license:
Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistribution of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistribution in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
Neither the name of Sun Microsystems, Inc. or the names of
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
This software is provided "AS IS," without a warranty of any
kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
You acknowledge that this software is not designed or intended for
use in the design, construction, operation or maintenance of any
nuclear facility.
The main difference can be found in the final paragraph: the restriction
that the source code is not "licensed" in this particular situation has
been removed.
FYI: Brian also added: "A bit of history might be in order.
The codec classes that you used originally were based on some
classes included with JAI but not strictly part of JAI.
As of Java SE 1.4 an official Image I/O framework was
added in javax.imageio.... This frameork supports these formats:
Java 1.4: GIF (read only), JPEG, PNG
Java 1.5: Added support for BMP and WBMP
Java 1.6: Added support for writing GIF
The JAI Image I/O Tools packages (jai-imageio-core) were created
to support formats handled by JAI but not included in Java SE
as well as some new things like JPEG2000."
(4) the file com/lowagie/text/pdf/codec/TIFFConstants
and some other TIFF related code is derived from LIBTIFF:
Copyright (c) 1988-1997 Sam Leffler
Copyright (c) 1991-1997 Silicon Graphics, Inc.
Permission to use, copy, modify, distribute, and sell this software and
its documentation for any purpose is hereby granted without fee, provided
that (i) the above copyright notices and this permission notice appear in
all copies of the software and related documentation, and (ii) the names of
Sam Leffler and Silicon Graphics may not be used in any advertising or
publicity relating to the software without the specific, prior written
permission of Sam Leffler and Silicon Graphics.
THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
OF THIS SOFTWARE.
(5)
BidiOrder:
As stated in the Javadoc comments, materials from Unicode.org
are used in the class com/lowagie/text/pdf/BidiOrder.java
The following license applies to these materials:
http://www.unicode.org/copyright.html#Exhibit1
EXHIBIT 1
UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE
Unicode Data Files include all data files under the directories
http://www.unicode.org/Public/, http://www.unicode.org/reports/,
and http://www.unicode.org/cldr/data/ .
Unicode Software includes any source code published in the Unicode Standard
or under the directories http://www.unicode.org/Public/, http://www.unicode.org/reports/,
and http://www.unicode.org/cldr/data/.
NOTICE TO USER: Carefully read the following legal agreement. BY DOWNLOADING,
INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S DATA FILES ("DATA FILES"),
AND/OR SOFTWARE ("SOFTWARE"), YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY,
ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
COPYRIGHT AND PERMISSION NOTICE
Copyright (C) 1991-2007 Unicode, Inc. All rights reserved. Distributed under
the Terms of Use in http://www.unicode.org/copyright.html.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the Unicode data files and any associated documentation (the "Data Files")
or Unicode software and any associated documentation (the "Software") to deal
in the Data Files or Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, and/or sell copies
of the Data Files or Software, and to permit persons to whom the Data Files
or Software are furnished to do so, provided that (a) the above copyright
notice(s) and this permission notice appear with all copies of the Data Files
or Software, (b) both the above copyright notice(s) and this permission notice
appear in associated documentation, and (c) there is clear notice in each
modified Data File or in the Software as well as in the documentation associated
with the Data File(s) or Software that the data or software has been modified.
THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE
LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA FILES OR SOFTWARE.
Except as contained in this notice, the name of a copyright holder shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in these Data Files or Software without prior written authorization of the
copyright holder. src/core/com/lowagie/text/pdf/AcroFields.java 100644 0 0 312417 11215636056 16621 0 ustar 0 0 /*
* Copyright 2003-2005 by Paulo Soares.
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.pdf;
import java.awt.Color;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.w3c.dom.Node;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.codec.Base64;
/**
* Query and change fields in existing documents either by method
* calls or by FDF merging.
*
* @author Paulo Soares (psoares@consiste.pt)
*/
public class AcroFields {
PdfReader reader;
PdfWriter writer;
HashMap fields;
private int topFirst;
private HashMap sigNames;
private boolean append;
public static final int DA_FONT = 0;
public static final int DA_SIZE = 1;
public static final int DA_COLOR = 2;
private HashMap extensionFonts = new HashMap();
private XfaForm xfa;
/**
* A field type invalid or not found.
*/
public static final int FIELD_TYPE_NONE = 0;
/**
* A field type.
*/
public static final int FIELD_TYPE_PUSHBUTTON = 1;
/**
* A field type.
*/
public static final int FIELD_TYPE_CHECKBOX = 2;
/**
* A field type.
*/
public static final int FIELD_TYPE_RADIOBUTTON = 3;
/**
* A field type.
*/
public static final int FIELD_TYPE_TEXT = 4;
/**
* A field type.
*/
public static final int FIELD_TYPE_LIST = 5;
/**
* A field type.
*/
public static final int FIELD_TYPE_COMBO = 6;
/**
* A field type.
*/
public static final int FIELD_TYPE_SIGNATURE = 7;
private boolean lastWasString;
/** Holds value of property generateAppearances. */
private boolean generateAppearances = true;
private HashMap localFonts = new HashMap();
private float extraMarginLeft;
private float extraMarginTop;
private ArrayList substitutionFonts;
AcroFields(PdfReader reader, PdfWriter writer) {
this.reader = reader;
this.writer = writer;
try {
xfa = new XfaForm(reader);
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
if (writer instanceof PdfStamperImp) {
append = ((PdfStamperImp)writer).isAppend();
}
fill();
}
void fill() {
fields = new HashMap();
PdfDictionary top = (PdfDictionary)PdfReader.getPdfObjectRelease(reader.getCatalog().get(PdfName.ACROFORM));
if (top == null)
return;
PdfArray arrfds = (PdfArray)PdfReader.getPdfObjectRelease(top.get(PdfName.FIELDS));
if (arrfds == null || arrfds.size() == 0)
return;
for (int k = 1; k <= reader.getNumberOfPages(); ++k) {
PdfDictionary page = reader.getPageNRelease(k);
PdfArray annots = (PdfArray)PdfReader.getPdfObjectRelease(page.get(PdfName.ANNOTS), page);
if (annots == null)
continue;
for (int j = 0; j < annots.size(); ++j) {
PdfDictionary annot = annots.getAsDict(j);
if (annot == null) {
PdfReader.releaseLastXrefPartial(annots.getAsIndirectObject(j));
continue;
}
if (!PdfName.WIDGET.equals(annot.getAsName(PdfName.SUBTYPE))) {
PdfReader.releaseLastXrefPartial(annots.getAsIndirectObject(j));
continue;
}
PdfDictionary widget = annot;
PdfDictionary dic = new PdfDictionary();
dic.putAll(annot);
String name = "";
PdfDictionary value = null;
PdfObject lastV = null;
while (annot != null) {
dic.mergeDifferent(annot);
PdfString t = annot.getAsString(PdfName.T);
if (t != null)
name = t.toUnicodeString() + "." + name;
if (lastV == null && annot.get(PdfName.V) != null)
lastV = PdfReader.getPdfObjectRelease(annot.get(PdfName.V));
if (value == null && t != null) {
value = annot;
if (annot.get(PdfName.V) == null && lastV != null)
value.put(PdfName.V, lastV);
}
annot = annot.getAsDict(PdfName.PARENT);
}
if (name.length() > 0)
name = name.substring(0, name.length() - 1);
Item item = (Item)fields.get(name);
if (item == null) {
item = new Item();
fields.put(name, item);
}
if (value == null)
item.addValue(widget);
else
item.addValue(value);
item.addWidget(widget);
item.addWidgetRef(annots.getAsIndirectObject(j)); // must be a reference
if (top != null)
dic.mergeDifferent(top);
item.addMerged(dic);
item.addPage(k);
item.addTabOrder(j);
}
}
// some tools produce invisible signatures without an entry in the page annotation array
// look for a single level annotation
PdfNumber sigFlags = top.getAsNumber(PdfName.SIGFLAGS);
if (sigFlags == null || (sigFlags.intValue() & 1) != 1)
return;
for (int j = 0; j < arrfds.size(); ++j) {
PdfDictionary annot = arrfds.getAsDict(j);
if (annot == null) {
PdfReader.releaseLastXrefPartial(arrfds.getAsIndirectObject(j));
continue;
}
if (!PdfName.WIDGET.equals(annot.getAsName(PdfName.SUBTYPE))) {
PdfReader.releaseLastXrefPartial(arrfds.getAsIndirectObject(j));
continue;
}
PdfArray kids = (PdfArray)PdfReader.getPdfObjectRelease(annot.get(PdfName.KIDS));
if (kids != null)
continue;
PdfDictionary dic = new PdfDictionary();
dic.putAll(annot);
PdfString t = annot.getAsString(PdfName.T);
if (t == null)
continue;
String name = t.toUnicodeString();
if (fields.containsKey(name))
continue;
Item item = new Item();
fields.put(name, item);
item.addValue(dic);
item.addWidget(dic);
item.addWidgetRef(arrfds.getAsIndirectObject(j)); // must be a reference
item.addMerged(dic);
item.addPage(-1);
item.addTabOrder(-1);
}
}
/**
* Gets the list of appearance names. Use it to get the names allowed
* with radio and checkbox fields. If the /Opt key exists the values will
* also be included. The name 'Off' may also be valid
* even if not returned in the list.
*
* @param fieldName the fully qualified field name
* @return the list of names or null
if the field does not exist
*/
public String[] getAppearanceStates(String fieldName) {
Item fd = (Item)fields.get(fieldName);
if (fd == null)
return null;
HashMap names = new HashMap();
PdfDictionary vals = fd.getValue(0);
PdfString stringOpt = vals.getAsString( PdfName.OPT );
if (stringOpt != null) {
names.put(stringOpt.toUnicodeString(), null);
}
else {
PdfArray arrayOpt = vals.getAsArray(PdfName.OPT);
if (arrayOpt != null) {
for (int k = 0; k < arrayOpt.size(); ++k) {
PdfString valStr = arrayOpt.getAsString( k );
if (valStr != null)
names.put(valStr.toUnicodeString(), null);
}
}
}
for (int k = 0; k < fd.size(); ++k) {
PdfDictionary dic = fd.getWidget( k );
dic = dic.getAsDict(PdfName.AP);
if (dic == null)
continue;
dic = dic.getAsDict(PdfName.N);
if (dic == null)
continue;
for (Iterator it = dic.getKeys().iterator(); it.hasNext();) {
String name = PdfName.decodeName(((PdfName)it.next()).toString());
names.put(name, null);
}
}
String out[] = new String[names.size()];
return (String[])names.keySet().toArray(out);
}
private String[] getListOption(String fieldName, int idx) {
Item fd = getFieldItem(fieldName);
if (fd == null)
return null;
PdfArray ar = fd.getMerged(0).getAsArray(PdfName.OPT);
if (ar == null)
return null;
String[] ret = new String[ar.size()];
for (int k = 0; k < ar.size(); ++k) {
PdfObject obj = ar.getDirectObject( k );
try {
if (obj.isArray()) {
obj = ((PdfArray)obj).getDirectObject(idx);
}
if (obj.isString())
ret[k] = ((PdfString)obj).toUnicodeString();
else
ret[k] = obj.toString();
}
catch (Exception e) {
ret[k] = "";
}
}
return ret;
}
/**
* Gets the list of export option values from fields of type list or combo.
* If the field doesn't exist or the field type is not list or combo it will return
* null
.
*
* @param fieldName the field name
* @return the list of export option values from fields of type list or combo
*/
public String[] getListOptionExport(String fieldName) {
return getListOption(fieldName, 0);
}
/**
* Gets the list of display option values from fields of type list or combo.
* If the field doesn't exist or the field type is not list or combo it will return
* null
.
*
* @param fieldName the field name
* @return the list of export option values from fields of type list or combo
*/
public String[] getListOptionDisplay(String fieldName) {
return getListOption(fieldName, 1);
}
/**
* Sets the option list for fields of type list or combo. One of exportValues
* or displayValues
may be null
but not both. This method will only
* set the list but will not set the value or appearance. For that, calling setField()
* is required.
*
* PdfReader pdf = new PdfReader("input.pdf");
* PdfStamper stp = new PdfStamper(pdf, new FileOutputStream("output.pdf"));
* AcroFields af = stp.getAcroFields();
* af.setListOption("ComboBox", new String[]{"a", "b", "c"}, new String[]{"first", "second", "third"});
* af.setField("ComboBox", "b");
* stp.close();
*
*
* @param fieldName the field name
* @param exportValues the export values
* @param displayValues the display values
* @return true
if the operation succeeded, false
otherwise
*/
public boolean setListOption(String fieldName, String[] exportValues, String[] displayValues) {
if (exportValues == null && displayValues == null)
return false;
if (exportValues != null && displayValues != null && exportValues.length != displayValues.length)
throw new IllegalArgumentException("The export and the display array must have the same size.");
int ftype = getFieldType(fieldName);
if (ftype != FIELD_TYPE_COMBO && ftype != FIELD_TYPE_LIST)
return false;
Item fd = (Item)fields.get(fieldName);
String[] sing = null;
if (exportValues == null && displayValues != null)
sing = displayValues;
else if (exportValues != null && displayValues == null)
sing = exportValues;
PdfArray opt = new PdfArray();
if (sing != null) {
for (int k = 0; k < sing.length; ++k)
opt.add(new PdfString(sing[k], PdfObject.TEXT_UNICODE));
}
else {
for (int k = 0; k < exportValues.length; ++k) {
PdfArray a = new PdfArray();
a.add(new PdfString(exportValues[k], PdfObject.TEXT_UNICODE));
a.add(new PdfString(displayValues[k], PdfObject.TEXT_UNICODE));
opt.add(a);
}
}
fd.writeToAll( PdfName.OPT, opt, Item.WRITE_VALUE | Item.WRITE_MERGED );
return true;
}
/**
* Gets the field type. The type can be one of: FIELD_TYPE_PUSHBUTTON
,
* FIELD_TYPE_CHECKBOX
, FIELD_TYPE_RADIOBUTTON
,
* FIELD_TYPE_TEXT
, FIELD_TYPE_LIST
,
* FIELD_TYPE_COMBO
or FIELD_TYPE_SIGNATURE
.
* FIELD_TYPE_NONE
.
*
* @param fieldName the field name
* @return the field type
*/
public int getFieldType(String fieldName) {
Item fd = getFieldItem(fieldName);
if (fd == null)
return FIELD_TYPE_NONE;
PdfDictionary merged = fd.getMerged( 0 );
PdfName type = merged.getAsName(PdfName.FT);
if (type == null)
return FIELD_TYPE_NONE;
int ff = 0;
PdfNumber ffo = merged.getAsNumber(PdfName.FF);
if (ffo != null) {
ff = ffo.intValue();
}
if (PdfName.BTN.equals(type)) {
if ((ff & PdfFormField.FF_PUSHBUTTON) != 0)
return FIELD_TYPE_PUSHBUTTON;
if ((ff & PdfFormField.FF_RADIO) != 0)
return FIELD_TYPE_RADIOBUTTON;
else
return FIELD_TYPE_CHECKBOX;
}
else if (PdfName.TX.equals(type)) {
return FIELD_TYPE_TEXT;
}
else if (PdfName.CH.equals(type)) {
if ((ff & PdfFormField.FF_COMBO) != 0)
return FIELD_TYPE_COMBO;
else
return FIELD_TYPE_LIST;
}
else if (PdfName.SIG.equals(type)) {
return FIELD_TYPE_SIGNATURE;
}
return FIELD_TYPE_NONE;
}
/**
* Export the fields as a FDF.
*
* @param writer the FDF writer
*/
public void exportAsFdf(FdfWriter writer) {
for (Iterator it = fields.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
Item item = (Item)entry.getValue();
String name = (String)entry.getKey();
PdfObject v = item.getMerged(0).get(PdfName.V);
if (v == null)
continue;
String value = getField(name);
if (lastWasString)
writer.setFieldAsString(name, value);
else
writer.setFieldAsName(name, value);
}
}
/**
* Renames a field. Only the last part of the name can be renamed. For example,
* if the original field is "ab.cd.ef" only the "ef" part can be renamed.
*
* @param oldName the old field name
* @param newName the new field name
* @return true
if the renaming was successful, false
* otherwise
*/
public boolean renameField(String oldName, String newName) {
int idx1 = oldName.lastIndexOf('.') + 1;
int idx2 = newName.lastIndexOf('.') + 1;
if (idx1 != idx2)
return false;
if (!oldName.substring(0, idx1).equals(newName.substring(0, idx2)))
return false;
if (fields.containsKey(newName))
return false;
Item item = (Item)fields.get(oldName);
if (item == null)
return false;
newName = newName.substring(idx2);
PdfString ss = new PdfString(newName, PdfObject.TEXT_UNICODE);
item.writeToAll( PdfName.T, ss, Item.WRITE_VALUE | Item.WRITE_MERGED);
item.markUsed( this, Item.WRITE_VALUE );
fields.remove(oldName);
fields.put(newName, item);
return true;
}
public static Object[] splitDAelements(String da) {
try {
PRTokeniser tk = new PRTokeniser(PdfEncodings.convertToBytes(da, null));
ArrayList stack = new ArrayList();
Object ret[] = new Object[3];
while (tk.nextToken()) {
if (tk.getTokenType() == PRTokeniser.TK_COMMENT)
continue;
if (tk.getTokenType() == PRTokeniser.TK_OTHER) {
String operator = tk.getStringValue();
if (operator.equals("Tf")) {
if (stack.size() >= 2) {
ret[DA_FONT] = stack.get(stack.size() - 2);
ret[DA_SIZE] = new Float((String)stack.get(stack.size() - 1));
}
}
else if (operator.equals("g")) {
if (stack.size() >= 1) {
float gray = new Float((String)stack.get(stack.size() - 1)).floatValue();
if (gray != 0)
ret[DA_COLOR] = new GrayColor(gray);
}
}
else if (operator.equals("rg")) {
if (stack.size() >= 3) {
float red = new Float((String)stack.get(stack.size() - 3)).floatValue();
float green = new Float((String)stack.get(stack.size() - 2)).floatValue();
float blue = new Float((String)stack.get(stack.size() - 1)).floatValue();
ret[DA_COLOR] = new Color(red, green, blue);
}
}
else if (operator.equals("k")) {
if (stack.size() >= 4) {
float cyan = new Float((String)stack.get(stack.size() - 4)).floatValue();
float magenta = new Float((String)stack.get(stack.size() - 3)).floatValue();
float yellow = new Float((String)stack.get(stack.size() - 2)).floatValue();
float black = new Float((String)stack.get(stack.size() - 1)).floatValue();
ret[DA_COLOR] = new CMYKColor(cyan, magenta, yellow, black);
}
}
stack.clear();
}
else
stack.add(tk.getStringValue());
}
return ret;
}
catch (IOException ioe) {
throw new ExceptionConverter(ioe);
}
}
public void decodeGenericDictionary(PdfDictionary merged, BaseField tx) throws IOException, DocumentException {
int flags = 0;
// the text size and color
PdfString da = merged.getAsString(PdfName.DA);
if (da != null) {
Object dab[] = splitDAelements(da.toUnicodeString());
if (dab[DA_SIZE] != null)
tx.setFontSize(((Float)dab[DA_SIZE]).floatValue());
if (dab[DA_COLOR] != null)
tx.setTextColor((Color)dab[DA_COLOR]);
if (dab[DA_FONT] != null) {
PdfDictionary font = merged.getAsDict(PdfName.DR);
if (font != null) {
font = font.getAsDict(PdfName.FONT);
if (font != null) {
PdfObject po = font.get(new PdfName((String)dab[DA_FONT]));
if (po != null && po.type() == PdfObject.INDIRECT) {
PRIndirectReference por = (PRIndirectReference)po;
BaseFont bp = new DocumentFont((PRIndirectReference)po);
tx.setFont(bp);
Integer porkey = new Integer(por.getNumber());
BaseFont porf = (BaseFont)extensionFonts.get(porkey);
if (porf == null) {
if (!extensionFonts.containsKey(porkey)) {
PdfDictionary fo = (PdfDictionary)PdfReader.getPdfObject(po);
PdfDictionary fd = fo.getAsDict(PdfName.FONTDESCRIPTOR);
if (fd != null) {
PRStream prs = (PRStream)PdfReader.getPdfObject(fd.get(PdfName.FONTFILE2));
if (prs == null)
prs = (PRStream)PdfReader.getPdfObject(fd.get(PdfName.FONTFILE3));
if (prs == null) {
extensionFonts.put(porkey, null);
}
else {
try {
porf = BaseFont.createFont("font.ttf", BaseFont.IDENTITY_H, true, false, PdfReader.getStreamBytes(prs), null);
}
catch (Exception e) {
}
extensionFonts.put(porkey, porf);
}
}
}
}
if (tx instanceof TextField)
((TextField)tx).setExtensionFont(porf);
}
else {
BaseFont bf = (BaseFont)localFonts.get(dab[DA_FONT]);
if (bf == null) {
String fn[] = (String[])stdFieldFontNames.get(dab[DA_FONT]);
if (fn != null) {
try {
String enc = "winansi";
if (fn.length > 1)
enc = fn[1];
bf = BaseFont.createFont(fn[0], enc, false);
tx.setFont(bf);
}
catch (Exception e) {
// empty
}
}
}
else
tx.setFont(bf);
}
}
}
}
}
//rotation, border and background color
PdfDictionary mk = merged.getAsDict(PdfName.MK);
if (mk != null) {
PdfArray ar = mk.getAsArray(PdfName.BC);
Color border = getMKColor(ar);
tx.setBorderColor(border);
if (border != null)
tx.setBorderWidth(1);
ar = mk.getAsArray(PdfName.BG);
tx.setBackgroundColor(getMKColor(ar));
PdfNumber rotation = mk.getAsNumber(PdfName.R);
if (rotation != null)
tx.setRotation(rotation.intValue());
}
//flags
PdfNumber nfl = merged.getAsNumber(PdfName.F);
flags = 0;
tx.setVisibility(BaseField.VISIBLE_BUT_DOES_NOT_PRINT);
if (nfl != null) {
flags = nfl.intValue();
if ((flags & PdfFormField.FLAGS_PRINT) != 0 && (flags & PdfFormField.FLAGS_HIDDEN) != 0)
tx.setVisibility(BaseField.HIDDEN);
else if ((flags & PdfFormField.FLAGS_PRINT) != 0 && (flags & PdfFormField.FLAGS_NOVIEW) != 0)
tx.setVisibility(BaseField.HIDDEN_BUT_PRINTABLE);
else if ((flags & PdfFormField.FLAGS_PRINT) != 0)
tx.setVisibility(BaseField.VISIBLE);
}
//multiline
nfl = merged.getAsNumber(PdfName.FF);
flags = 0;
if (nfl != null)
flags = nfl.intValue();
tx.setOptions(flags);
if ((flags & PdfFormField.FF_COMB) != 0) {
PdfNumber maxLen = merged.getAsNumber(PdfName.MAXLEN);
int len = 0;
if (maxLen != null)
len = maxLen.intValue();
tx.setMaxCharacterLength(len);
}
//alignment
nfl = merged.getAsNumber(PdfName.Q);
if (nfl != null) {
if (nfl.intValue() == PdfFormField.Q_CENTER)
tx.setAlignment(Element.ALIGN_CENTER);
else if (nfl.intValue() == PdfFormField.Q_RIGHT)
tx.setAlignment(Element.ALIGN_RIGHT);
}
//border styles
PdfDictionary bs = merged.getAsDict(PdfName.BS);
if (bs != null) {
PdfNumber w = bs.getAsNumber(PdfName.W);
if (w != null)
tx.setBorderWidth(w.floatValue());
PdfName s = bs.getAsName(PdfName.S);
if (PdfName.D.equals(s))
tx.setBorderStyle(PdfBorderDictionary.STYLE_DASHED);
else if (PdfName.B.equals(s))
tx.setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
else if (PdfName.I.equals(s))
tx.setBorderStyle(PdfBorderDictionary.STYLE_INSET);
else if (PdfName.U.equals(s))
tx.setBorderStyle(PdfBorderDictionary.STYLE_UNDERLINE);
}
else {
PdfArray bd = merged.getAsArray(PdfName.BORDER);
if (bd != null) {
if (bd.size() >= 3)
tx.setBorderWidth(bd.getAsNumber(2).floatValue());
if (bd.size() >= 4)
tx.setBorderStyle(PdfBorderDictionary.STYLE_DASHED);
}
}
}
PdfAppearance getAppearance(PdfDictionary merged, String text, String fieldName) throws IOException, DocumentException {
topFirst = 0;
TextField tx = null;
if (fieldCache == null || !fieldCache.containsKey(fieldName)) {
tx = new TextField(writer, null, null);
tx.setExtraMargin(extraMarginLeft, extraMarginTop);
tx.setBorderWidth(0);
tx.setSubstitutionFonts(substitutionFonts);
decodeGenericDictionary(merged, tx);
//rect
PdfArray rect = merged.getAsArray(PdfName.RECT);
Rectangle box = PdfReader.getNormalizedRectangle(rect);
if (tx.getRotation() == 90 || tx.getRotation() == 270)
box = box.rotate();
tx.setBox(box);
if (fieldCache != null)
fieldCache.put(fieldName, tx);
}
else {
tx = (TextField)fieldCache.get(fieldName);
tx.setWriter(writer);
}
PdfName fieldType = merged.getAsName(PdfName.FT);
if (PdfName.TX.equals(fieldType)) {
tx.setText(text);
return tx.getAppearance();
}
if (!PdfName.CH.equals(fieldType))
throw new DocumentException("An appearance was requested without a variable text field.");
PdfArray opt = merged.getAsArray(PdfName.OPT);
int flags = 0;
PdfNumber nfl = merged.getAsNumber(PdfName.FF);
if (nfl != null)
flags = nfl.intValue();
if ((flags & PdfFormField.FF_COMBO) != 0 && opt == null) {
tx.setText(text);
return tx.getAppearance();
}
if (opt != null) {
String choices[] = new String[opt.size()];
String choicesExp[] = new String[opt.size()];
for (int k = 0; k < opt.size(); ++k) {
PdfObject obj = opt.getPdfObject(k);
if (obj.isString()) {
choices[k] = choicesExp[k] = ((PdfString)obj).toUnicodeString();
}
else {
PdfArray a = (PdfArray) obj;
choicesExp[k] = a.getAsString(0).toUnicodeString();
choices[k] = a.getAsString(1).toUnicodeString();
}
}
if ((flags & PdfFormField.FF_COMBO) != 0) {
for (int k = 0; k < choices.length; ++k) {
if (text.equals(choicesExp[k])) {
text = choices[k];
break;
}
}
tx.setText(text);
return tx.getAppearance();
}
int idx = 0;
for (int k = 0; k < choicesExp.length; ++k) {
if (text.equals(choicesExp[k])) {
idx = k;
break;
}
}
tx.setChoices(choices);
tx.setChoiceExports(choicesExp);
tx.setChoiceSelection(idx);
}
PdfAppearance app = tx.getListAppearance();
topFirst = tx.getTopFirst();
return app;
}
Color getMKColor(PdfArray ar) {
if (ar == null)
return null;
switch (ar.size()) {
case 1:
return new GrayColor(ar.getAsNumber(0).floatValue());
case 3:
return new Color(ExtendedColor.normalize(ar.getAsNumber(0).floatValue()), ExtendedColor.normalize(ar.getAsNumber(1).floatValue()), ExtendedColor.normalize(ar.getAsNumber(2).floatValue()));
case 4:
return new CMYKColor(ar.getAsNumber(0).floatValue(), ar.getAsNumber(1).floatValue(), ar.getAsNumber(2).floatValue(), ar.getAsNumber(3).floatValue());
default:
return null;
}
}
/**
* Gets the field value.
*
* @param name the fully qualified field name
* @return the field value
*/
public String getField(String name) {
if (xfa.isXfaPresent()) {
name = xfa.findFieldName(name, this);
if (name == null)
return null;
name = XfaForm.Xml2Som.getShortName(name);
return XfaForm.getNodeText(xfa.findDatasetsNode(name));
}
Item item = (Item)fields.get(name);
if (item == null)
return null;
lastWasString = false;
PdfDictionary mergedDict = item.getMerged( 0 );
// Jose A. Rodriguez posted a fix to the mailing list (May 11, 2009)
// explaining that the value can also be a stream value
// the fix was made against an old iText version. Bruno adapted it.
PdfObject v = PdfReader.getPdfObject(mergedDict.get(PdfName.V));
if (v == null)
return "";
if (v instanceof PRStream) {
byte[] valBytes;
try {
valBytes = PdfReader.getStreamBytes((PRStream)v);
return new String(valBytes);
} catch (IOException e) {
throw new ExceptionConverter(e);
}
}
PdfName type = mergedDict.getAsName(PdfName.FT);
if (PdfName.BTN.equals(type)) {
PdfNumber ff = mergedDict.getAsNumber(PdfName.FF);
int flags = 0;
if (ff != null)
flags = ff.intValue();
if ((flags & PdfFormField.FF_PUSHBUTTON) != 0)
return "";
String value = "";
if (v instanceof PdfName)
value = PdfName.decodeName(v.toString());
else if (v instanceof PdfString)
value = ((PdfString)v).toUnicodeString();
PdfArray opts = item.getValue(0).getAsArray(PdfName.OPT);
if (opts != null) {
int idx = 0;
try {
idx = Integer.parseInt(value);
PdfString ps = opts.getAsString(idx);
value = ps.toUnicodeString();
lastWasString = true;
}
catch (Exception e) {
}
}
return value;
}
if (v instanceof PdfString) {
lastWasString = true;
return ((PdfString)v).toUnicodeString();
} else if (v instanceof PdfName) {
return PdfName.decodeName(v.toString());
} else
return "";
}
/**
* Gets the field values of a Choice field.
*
* @param name the fully qualified field name
* @return the field value
* @since 2.1.3
*/
public String[] getListSelection(String name) {
String[] ret;
String s = getField(name);
if (s == null) {
ret = new String[]{};
}
else {
ret = new String[]{ s };
}
Item item = (Item)fields.get(name);
if (item == null)
return ret;
//PdfName type = (PdfName)PdfReader.getPdfObject(((PdfDictionary)item.merged.get(0)).get(PdfName.FT));
//if (!PdfName.CH.equals(type)) {
// return ret;
//}
PdfArray values = item.getMerged(0).getAsArray(PdfName.I);
if (values == null)
return ret;
ret = new String[values.size()];
String[] options = getListOptionExport(name);
PdfNumber n;
int idx = 0;
for (Iterator i = values.listIterator(); i.hasNext(); ) {
n = (PdfNumber)i.next();
ret[idx++] = options[n.intValue()];
}
return ret;
}
/**
* Sets a field property. Valid property names are:
*
*
*
* @param field the field name
* @param name the property name
* @param value the property value
* @param inst an array of BaseFont
.
* java.awt.Color
.
* Float
.
* java.awt.Color
.
* If null
removes the background.
* java.awt.Color
.
* If null
removes the border.
* int
indexing into AcroField.Item.merged
elements to process.
* Set to null
to process all
* @return true
if the property exists, false
otherwise
*/
public boolean setFieldProperty(String field, String name, Object value, int inst[]) {
if (writer == null)
throw new RuntimeException("This AcroFields instance is read-only.");
try {
Item item = (Item)fields.get(field);
if (item == null)
return false;
InstHit hit = new InstHit(inst);
PdfDictionary merged;
PdfString da;
if (name.equalsIgnoreCase("textfont")) {
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
merged = item.getMerged( k );
da = merged.getAsString(PdfName.DA);
PdfDictionary dr = merged.getAsDict(PdfName.DR);
if (da != null && dr != null) {
Object dao[] = splitDAelements(da.toUnicodeString());
PdfAppearance cb = new PdfAppearance();
if (dao[DA_FONT] != null) {
BaseFont bf = (BaseFont)value;
PdfName psn = (PdfName)PdfAppearance.stdFieldFontNames.get(bf.getPostscriptFontName());
if (psn == null) {
psn = new PdfName(bf.getPostscriptFontName());
}
PdfDictionary fonts = dr.getAsDict(PdfName.FONT);
if (fonts == null) {
fonts = new PdfDictionary();
dr.put(PdfName.FONT, fonts);
}
PdfIndirectReference fref = (PdfIndirectReference)fonts.get(psn);
PdfDictionary top = reader.getCatalog().getAsDict(PdfName.ACROFORM);
markUsed(top);
dr = top.getAsDict(PdfName.DR);
if (dr == null) {
dr = new PdfDictionary();
top.put(PdfName.DR, dr);
}
markUsed(dr);
PdfDictionary fontsTop = dr.getAsDict(PdfName.FONT);
if (fontsTop == null) {
fontsTop = new PdfDictionary();
dr.put(PdfName.FONT, fontsTop);
}
markUsed(fontsTop);
PdfIndirectReference frefTop = (PdfIndirectReference)fontsTop.get(psn);
if (frefTop != null) {
if (fref == null)
fonts.put(psn, frefTop);
}
else if (fref == null) {
FontDetails fd;
if (bf.getFontType() == BaseFont.FONT_TYPE_DOCUMENT) {
fd = new FontDetails(null, ((DocumentFont)bf).getIndirectReference(), bf);
}
else {
bf.setSubset(false);
fd = writer.addSimple(bf);
localFonts.put(psn.toString().substring(1), bf);
}
fontsTop.put(psn, fd.getIndirectReference());
fonts.put(psn, fd.getIndirectReference());
}
ByteBuffer buf = cb.getInternalBuffer();
buf.append(psn.getBytes()).append(' ').append(((Float)dao[DA_SIZE]).floatValue()).append(" Tf ");
if (dao[DA_COLOR] != null)
cb.setColorFill((Color)dao[DA_COLOR]);
PdfString s = new PdfString(cb.toString());
item.getMerged(k).put(PdfName.DA, s);
item.getWidget(k).put(PdfName.DA, s);
markUsed(item.getWidget(k));
}
}
}
}
}
else if (name.equalsIgnoreCase("textcolor")) {
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
merged = item.getMerged( k );
da = merged.getAsString(PdfName.DA);
if (da != null) {
Object dao[] = splitDAelements(da.toUnicodeString());
PdfAppearance cb = new PdfAppearance();
if (dao[DA_FONT] != null) {
ByteBuffer buf = cb.getInternalBuffer();
buf.append(new PdfName((String)dao[DA_FONT]).getBytes()).append(' ').append(((Float)dao[DA_SIZE]).floatValue()).append(" Tf ");
cb.setColorFill((Color)value);
PdfString s = new PdfString(cb.toString());
item.getMerged(k).put(PdfName.DA, s);
item.getWidget(k).put(PdfName.DA, s);
markUsed(item.getWidget(k));
}
}
}
}
}
else if (name.equalsIgnoreCase("textsize")) {
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
merged = item.getMerged( k );
da = merged.getAsString(PdfName.DA);
if (da != null) {
Object dao[] = splitDAelements(da.toUnicodeString());
PdfAppearance cb = new PdfAppearance();
if (dao[DA_FONT] != null) {
ByteBuffer buf = cb.getInternalBuffer();
buf.append(new PdfName((String)dao[DA_FONT]).getBytes()).append(' ').append(((Float)value).floatValue()).append(" Tf ");
if (dao[DA_COLOR] != null)
cb.setColorFill((Color)dao[DA_COLOR]);
PdfString s = new PdfString(cb.toString());
item.getMerged(k).put(PdfName.DA, s);
item.getWidget(k).put(PdfName.DA, s);
markUsed(item.getWidget(k));
}
}
}
}
}
else if (name.equalsIgnoreCase("bgcolor") || name.equalsIgnoreCase("bordercolor")) {
PdfName dname = (name.equalsIgnoreCase("bgcolor") ? PdfName.BG : PdfName.BC);
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
merged = item.getMerged( k );
PdfDictionary mk = merged.getAsDict(PdfName.MK);
if (mk == null) {
if (value == null)
return true;
mk = new PdfDictionary();
item.getMerged(k).put(PdfName.MK, mk);
item.getWidget(k).put(PdfName.MK, mk);
markUsed(item.getWidget(k));
} else {
markUsed( mk );
}
if (value == null)
mk.remove(dname);
else
mk.put(dname, PdfFormField.getMKColor((Color)value));
}
}
}
else
return false;
return true;
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
}
/**
* Sets a field property. Valid property names are:
*
*
*
* @param field the field name
* @param name the property name
* @param value the property value
* @param inst an array of
*
*
*
*
*
* int
indexing into AcroField.Item.merged
elements to process.
* Set to null
to process all
* @return true
if the property exists, false
otherwise
*/
public boolean setFieldProperty(String field, String name, int value, int inst[]) {
if (writer == null)
throw new RuntimeException("This AcroFields instance is read-only.");
Item item = (Item)fields.get(field);
if (item == null)
return false;
InstHit hit = new InstHit(inst);
if (name.equalsIgnoreCase("flags")) {
PdfNumber num = new PdfNumber(value);
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
item.getMerged(k).put(PdfName.F, num);
item.getWidget(k).put(PdfName.F, num);
markUsed(item.getWidget(k));
}
}
}
else if (name.equalsIgnoreCase("setflags")) {
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
PdfNumber num = item.getWidget(k).getAsNumber(PdfName.F);
int val = 0;
if (num != null)
val = num.intValue();
num = new PdfNumber(val | value);
item.getMerged(k).put(PdfName.F, num);
item.getWidget(k).put(PdfName.F, num);
markUsed(item.getWidget(k));
}
}
}
else if (name.equalsIgnoreCase("clrflags")) {
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
PdfDictionary widget = item.getWidget( k );
PdfNumber num = widget.getAsNumber(PdfName.F);
int val = 0;
if (num != null)
val = num.intValue();
num = new PdfNumber(val & (~value));
item.getMerged(k).put(PdfName.F, num);
widget.put(PdfName.F, num);
markUsed(widget);
}
}
}
else if (name.equalsIgnoreCase("fflags")) {
PdfNumber num = new PdfNumber(value);
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
item.getMerged(k).put(PdfName.FF, num);
item.getValue(k).put(PdfName.FF, num);
markUsed(item.getValue(k));
}
}
}
else if (name.equalsIgnoreCase("setfflags")) {
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
PdfDictionary valDict = item.getValue( k );
PdfNumber num = valDict.getAsNumber( PdfName.FF );
int val = 0;
if (num != null)
val = num.intValue();
num = new PdfNumber(val | value);
item.getMerged(k).put(PdfName.FF, num);
valDict.put(PdfName.FF, num);
markUsed(valDict);
}
}
}
else if (name.equalsIgnoreCase("clrfflags")) {
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
PdfDictionary valDict = item.getValue( k );
PdfNumber num = valDict.getAsNumber(PdfName.FF);
int val = 0;
if (num != null)
val = num.intValue();
num = new PdfNumber(val & (~value));
item.getMerged(k).put(PdfName.FF, num);
valDict.put(PdfName.FF, num);
markUsed(valDict);
}
}
}
else
return false;
return true;
}
/**
* Merges an XML data structure into this form.
*
* @param n the top node of the data structure
* @throws java.io.IOException on error
* @throws com.lowagie.text.DocumentException o error
*/
public void mergeXfaData(Node n) throws IOException, DocumentException {
XfaForm.Xml2SomDatasets data = new XfaForm.Xml2SomDatasets(n);
for (Iterator it = data.getOrder().iterator(); it.hasNext();) {
String name = (String)it.next();
String text = XfaForm.getNodeText((Node)data.getName2Node().get(name));
setField(name, text);
}
}
/**
* Sets the fields by FDF merging.
*
* @param fdf the FDF form
* @throws IOException on error
* @throws DocumentException on error
*/
public void setFields(FdfReader fdf) throws IOException, DocumentException {
HashMap fd = fdf.getFields();
for (Iterator i = fd.keySet().iterator(); i.hasNext();) {
String f = (String)i.next();
String v = fdf.getFieldValue(f);
if (v != null)
setField(f, v);
}
}
/**
* Sets the fields by XFDF merging.
*
* @param xfdf the XFDF form
* @throws IOException on error
* @throws DocumentException on error
*/
public void setFields(XfdfReader xfdf) throws IOException, DocumentException {
HashMap fd = xfdf.getFields();
for (Iterator i = fd.keySet().iterator(); i.hasNext();) {
String f = (String)i.next();
String v = xfdf.getFieldValue(f);
if (v != null)
setField(f, v);
List l = xfdf.getListValues(f);
if (l != null)
setListSelection(v, (String[])l.toArray(new String[l.size()]));
}
}
/**
* Regenerates the field appearance.
* This is useful when you change a field property, but not its value,
* for instance form.setFieldProperty("f", "bgcolor", Color.BLUE, null);
* This won't have any effect, unless you use regenerateField("f") after changing
* the property.
*
* @param name the fully qualified field name or the partial name in the case of XFA forms
* @throws IOException on error
* @throws DocumentException on error
* @return true
if the field was found and changed,
* false
otherwise
*/
public boolean regenerateField(String name) throws IOException, DocumentException {
String value = getField(name);
return setField(name, value, value);
}
/**
* Sets the field value.
*
* @param name the fully qualified field name or the partial name in the case of XFA forms
* @param value the field value
* @throws IOException on error
* @throws DocumentException on error
* @return true
if the field was found and changed,
* false
otherwise
*/
public boolean setField(String name, String value) throws IOException, DocumentException {
return setField(name, value, null);
}
/**
* Sets the field value and the display string. The display string
* is used to build the appearance in the cases where the value
* is modified by Acrobat with JavaScript and the algorithm is
* known.
*
* @param name the fully qualified field name or the partial name in the case of XFA forms
* @param value the field value
* @param display the string that is used for the appearance. If null
* the value
parameter will be used
* @return true
if the field was found and changed,
* false
otherwise
* @throws IOException on error
* @throws DocumentException on error
*/
public boolean setField(String name, String value, String display) throws IOException, DocumentException {
if (writer == null)
throw new DocumentException("This AcroFields instance is read-only.");
if (xfa.isXfaPresent()) {
name = xfa.findFieldName(name, this);
if (name == null)
return false;
String shortName = XfaForm.Xml2Som.getShortName(name);
Node xn = xfa.findDatasetsNode(shortName);
if (xn == null) {
xn = xfa.getDatasetsSom().insertNode(xfa.getDatasetsNode(), shortName);
}
xfa.setNodeText(xn, value);
}
Item item = (Item)fields.get(name);
if (item == null)
return false;
PdfDictionary merged = item.getMerged( 0 );
PdfName type = merged.getAsName(PdfName.FT);
if (PdfName.TX.equals(type)) {
PdfNumber maxLen = merged.getAsNumber(PdfName.MAXLEN);
int len = 0;
if (maxLen != null)
len = maxLen.intValue();
if (len > 0)
value = value.substring(0, Math.min(len, value.length()));
}
if (display == null)
display = value;
if (PdfName.TX.equals(type) || PdfName.CH.equals(type)) {
PdfString v = new PdfString(value, PdfObject.TEXT_UNICODE);
for (int idx = 0; idx < item.size(); ++idx) {
PdfDictionary valueDic = item.getValue(idx);
valueDic.put(PdfName.V, v);
valueDic.remove(PdfName.I);
markUsed(valueDic);
merged = item.getMerged(idx);
merged.remove(PdfName.I);
merged.put(PdfName.V, v);
PdfDictionary widget = item.getWidget(idx);
if (generateAppearances) {
PdfAppearance app = getAppearance(merged, display, name);
if (PdfName.CH.equals(type)) {
PdfNumber n = new PdfNumber(topFirst);
widget.put(PdfName.TI, n);
merged.put(PdfName.TI, n);
}
PdfDictionary appDic = widget.getAsDict(PdfName.AP);
if (appDic == null) {
appDic = new PdfDictionary();
widget.put(PdfName.AP, appDic);
merged.put(PdfName.AP, appDic);
}
appDic.put(PdfName.N, app.getIndirectReference());
writer.releaseTemplate(app);
}
else {
widget.remove(PdfName.AP);
merged.remove(PdfName.AP);
}
markUsed(widget);
}
return true;
}
else if (PdfName.BTN.equals(type)) {
PdfNumber ff = item.getMerged(0).getAsNumber(PdfName.FF);
int flags = 0;
if (ff != null)
flags = ff.intValue();
if ((flags & PdfFormField.FF_PUSHBUTTON) != 0) {
//we'll assume that the value is an image in base64
Image img;
try {
img = Image.getInstance(Base64.decode(value));
}
catch (Exception e) {
return false;
}
PushbuttonField pb = getNewPushbuttonFromField(name);
pb.setImage(img);
replacePushbuttonField(name, pb.getField());
return true;
}
PdfName v = new PdfName(value);
ArrayList lopt = new ArrayList();
PdfArray opts = item.getValue(0).getAsArray(PdfName.OPT);
if (opts != null) {
for (int k = 0; k < opts.size(); ++k) {
PdfString valStr = opts.getAsString(k);
if (valStr != null)
lopt.add(valStr.toUnicodeString());
else
lopt.add(null);
}
}
int vidx = lopt.indexOf(value);
PdfName valt = null;
PdfName vt;
if (vidx >= 0) {
vt = valt = new PdfName(String.valueOf(vidx));
}
else
vt = v;
for (int idx = 0; idx < item.size(); ++idx) {
merged = item.getMerged(idx);
PdfDictionary widget = item.getWidget(idx);
PdfDictionary valDict = item.getValue(idx);
markUsed(item.getValue(idx));
if (valt != null) {
PdfString ps = new PdfString(value, PdfObject.TEXT_UNICODE);
valDict.put(PdfName.V, ps);
merged.put(PdfName.V, ps);
}
else {
valDict.put(PdfName.V, v);
merged.put(PdfName.V, v);
}
markUsed(widget);
if (isInAP(widget, vt)) {
merged.put(PdfName.AS, vt);
widget.put(PdfName.AS, vt);
}
else {
merged.put(PdfName.AS, PdfName.Off);
widget.put(PdfName.AS, PdfName.Off);
}
}
return true;
}
return false;
}
/**
* Sets different values in a list selection.
* No appearance is generated yet; nor does the code check if multiple select is allowed.
*
* @param name the name of the field
* @param value an array with values that need to be selected
* @return true only if the field value was changed
* @since 2.1.4
*/
public boolean setListSelection(String name, String[] value) throws IOException, DocumentException {
Item item = getFieldItem(name);
if (item == null)
return false;
PdfName type = item.getMerged(0).getAsName(PdfName.FT);
if (!PdfName.CH.equals(type)) {
return false;
}
String[] options = getListOptionExport(name);
PdfArray array = new PdfArray();
for (int i = 0; i < value.length; i++) {
for (int j = 0; j < options.length; j++) {
if (options[j].equals(value[i])) {
array.add(new PdfNumber(j));
}
}
}
item.writeToAll(PdfName.I, array, Item.WRITE_MERGED | Item.WRITE_VALUE);
item.writeToAll(PdfName.V, null, Item.WRITE_MERGED | Item.WRITE_VALUE);
item.writeToAll(PdfName.AP, null, Item.WRITE_MERGED | Item.WRITE_WIDGET);
item.markUsed( this, Item.WRITE_VALUE | Item.WRITE_WIDGET );
return true;
}
boolean isInAP(PdfDictionary dic, PdfName check) {
PdfDictionary appDic = dic.getAsDict(PdfName.AP);
if (appDic == null)
return false;
PdfDictionary NDic = appDic.getAsDict(PdfName.N);
return (NDic != null && NDic.get(check) != null);
}
/**
* Gets all the fields. The fields are keyed by the fully qualified field name and
* the value is an instance of AcroFields.Item
.
*
* @return all the fields
*/
public HashMap getFields() {
return fields;
}
/**
* Gets the field structure.
*
* @param name the name of the field
* @return the field structure or null
if the field
* does not exist
*/
public Item getFieldItem(String name) {
if (xfa.isXfaPresent()) {
name = xfa.findFieldName(name, this);
if (name == null)
return null;
}
return (Item)fields.get(name);
}
/**
* Gets the long XFA translated name.
*
* @param name the name of the field
* @return the long field name
*/
public String getTranslatedFieldName(String name) {
if (xfa.isXfaPresent()) {
String namex = xfa.findFieldName(name, this);
if (namex != null)
name = namex;
}
return name;
}
/**
* Gets the field box positions in the document. The return is an array of float
* multiple of 5. For each of this groups the values are: [page, llx, lly, urx,
* ury]. The coordinates have the page rotation in consideration.
*
* @param name the field name
* @return the positions or null
if field does not exist
*/
public float[] getFieldPositions(String name) {
Item item = getFieldItem(name);
if (item == null)
return null;
float ret[] = new float[item.size() * 5];
int ptr = 0;
for (int k = 0; k < item.size(); ++k) {
try {
PdfDictionary wd = item.getWidget(k);
PdfArray rect = wd.getAsArray(PdfName.RECT);
if (rect == null)
continue;
Rectangle r = PdfReader.getNormalizedRectangle(rect);
int page = item.getPage(k).intValue();
int rotation = reader.getPageRotation(page);
ret[ptr++] = page;
if (rotation != 0) {
Rectangle pageSize = reader.getPageSize(page);
switch (rotation) {
case 270:
r = new Rectangle(
pageSize.getTop() - r.getBottom(),
r.getLeft(),
pageSize.getTop() - r.getTop(),
r.getRight());
break;
case 180:
r = new Rectangle(
pageSize.getRight() - r.getLeft(),
pageSize.getTop() - r.getBottom(),
pageSize.getRight() - r.getRight(),
pageSize.getTop() - r.getTop());
break;
case 90:
r = new Rectangle(
r.getBottom(),
pageSize.getRight() - r.getLeft(),
r.getTop(),
pageSize.getRight() - r.getRight());
break;
}
r.normalize();
}
ret[ptr++] = r.getLeft();
ret[ptr++] = r.getBottom();
ret[ptr++] = r.getRight();
ret[ptr++] = r.getTop();
}
catch (Exception e) {
// empty on purpose
}
}
if (ptr < ret.length) {
float ret2[] = new float[ptr];
System.arraycopy(ret, 0, ret2, 0, ptr);
return ret2;
}
return ret;
}
private int removeRefFromArray(PdfArray array, PdfObject refo) {
if (refo == null || !refo.isIndirect())
return array.size();
PdfIndirectReference ref = (PdfIndirectReference)refo;
for (int j = 0; j < array.size(); ++j) {
PdfObject obj = array.getPdfObject(j);
if (!obj.isIndirect())
continue;
if (((PdfIndirectReference)obj).getNumber() == ref.getNumber())
array.remove(j--);
}
return array.size();
}
/**
* Removes all the fields from page
.
*
* @param page the page to remove the fields from
* @return true
if any field was removed, false otherwise
*/
public boolean removeFieldsFromPage(int page) {
if (page < 1)
return false;
String names[] = new String[fields.size()];
fields.keySet().toArray(names);
boolean found = false;
for (int k = 0; k < names.length; ++k) {
boolean fr = removeField(names[k], page);
found = (found || fr);
}
return found;
}
/**
* Removes a field from the document. If page equals -1 all the fields with this
* name
are removed from the document otherwise only the fields in
* that particular page are removed.
*
* @param name the field name
* @param page the page to remove the field from or -1 to remove it from all the pages
* @return true
if the field exists, false otherwise
*/
public boolean removeField(String name, int page) {
Item item = getFieldItem(name);
if (item == null)
return false;
PdfDictionary acroForm = (PdfDictionary)PdfReader.getPdfObject(reader.getCatalog().get(PdfName.ACROFORM), reader.getCatalog());
if (acroForm == null)
return false;
PdfArray arrayf = acroForm.getAsArray(PdfName.FIELDS);
if (arrayf == null)
return false;
for (int k = 0; k < item.size(); ++k) {
int pageV = item.getPage(k).intValue();
if (page != -1 && page != pageV)
continue;
PdfIndirectReference ref = item.getWidgetRef(k);
PdfDictionary wd = item.getWidget( k );
PdfDictionary pageDic = reader.getPageN(pageV);
PdfArray annots = pageDic.getAsArray(PdfName.ANNOTS);
if (annots != null) {
if (removeRefFromArray(annots, ref) == 0) {
pageDic.remove(PdfName.ANNOTS);
markUsed(pageDic);
}
else
markUsed(annots);
}
PdfReader.killIndirect(ref);
PdfIndirectReference kid = ref;
while ((ref = wd.getAsIndirectObject(PdfName.PARENT)) != null) {
wd = wd.getAsDict( PdfName.PARENT );
PdfArray kids = wd.getAsArray(PdfName.KIDS);
if (removeRefFromArray(kids, kid) != 0)
break;
kid = ref;
PdfReader.killIndirect(ref);
}
if (ref == null) {
removeRefFromArray(arrayf, kid);
markUsed(arrayf);
}
if (page != -1) {
item.remove( k );
--k;
}
}
if (page == -1 || item.size() == 0)
fields.remove(name);
return true;
}
/**
* Removes a field from the document.
*
* @param name the field name
* @return true
if the field exists, false otherwise
*/
public boolean removeField(String name) {
return removeField(name, -1);
}
/**
* Gets the property generateAppearances.
*
* @return the property generateAppearances
*/
public boolean isGenerateAppearances() {
return generateAppearances;
}
/**
* Sets the option to generate appearances. Not generating appearances
* will speed-up form filling but the results can be
* unexpected in Acrobat. Don't use it unless your environment is well
* controlled. The default is true
.
*
* @param generateAppearances the option to generate appearances
*/
public void setGenerateAppearances(boolean generateAppearances) {
this.generateAppearances = generateAppearances;
PdfDictionary top = reader.getCatalog().getAsDict(PdfName.ACROFORM);
if (generateAppearances)
top.remove(PdfName.NEEDAPPEARANCES);
else
top.put(PdfName.NEEDAPPEARANCES, PdfBoolean.PDFTRUE);
}
/** The field representations for retrieval and modification. */
public static class Item {
/**
* writeToAll
constant.
*
* @since 2.1.5
*/
public static final int WRITE_MERGED = 1;
/**
* writeToAll
and markUsed
constant.
*
* @since 2.1.5
*/
public static final int WRITE_WIDGET = 2;
/**
* writeToAll
and markUsed
constant.
*
* @since 2.1.5
*/
public static final int WRITE_VALUE = 4;
/**
* This function writes the given key/value pair to all the instances
* of merged, widget, and/or value, depending on the writeFlags
setting
*
* @since 2.1.5
*
* @param key you'll never guess what this is for.
* @param value if value is null, the key will be removed
* @param writeFlags ORed together WRITE_* flags
*/
public void writeToAll(PdfName key, PdfObject value, int writeFlags) {
int i;
PdfDictionary curDict = null;
if ((writeFlags & WRITE_MERGED) != 0) {
for (i = 0; i < merged.size(); ++i) {
curDict = getMerged(i);
curDict.put(key, value);
}
}
if ((writeFlags & WRITE_WIDGET) != 0) {
for (i = 0; i < widgets.size(); ++i) {
curDict = getWidget(i);
curDict.put(key, value);
}
}
if ((writeFlags & WRITE_VALUE) != 0) {
for (i = 0; i < values.size(); ++i) {
curDict = getValue(i);
curDict.put(key, value);
}
}
}
/**
* Mark all the item dictionaries used matching the given flags
*
* @since 2.1.5
* @param writeFlags WRITE_MERGED is ignored
*/
public void markUsed( AcroFields parentFields, int writeFlags ) {
if ((writeFlags & WRITE_VALUE) != 0) {
for (int i = 0; i < size(); ++i) {
parentFields.markUsed( getValue( i ) );
}
}
if ((writeFlags & WRITE_WIDGET) != 0) {
for (int i = 0; i < size(); ++i) {
parentFields.markUsed(getWidget(i));
}
}
}
/**
* An array of PdfDictionary
where the value tag /V
* is present.
*
* @deprecated (will remove 'public' in the future)
*/
public ArrayList values = new ArrayList();
/**
* An array of PdfDictionary
with the widgets.
*
* @deprecated (will remove 'public' in the future)
*/
public ArrayList widgets = new ArrayList();
/**
* An array of PdfDictionary
with the widget references.
*
* @deprecated (will remove 'public' in the future)
*/
public ArrayList widget_refs = new ArrayList();
/**
* An array of PdfDictionary
with all the field
* and widget tags merged.
*
* @deprecated (will remove 'public' in the future)
*/
public ArrayList merged = new ArrayList();
/**
* An array of Integer
with the page numbers where
* the widgets are displayed.
*
* @deprecated (will remove 'public' in the future)
*/
public ArrayList page = new ArrayList();
/**
* An array of Integer
with the tab order of the field in the page.
*
* @deprecated (will remove 'public' in the future)
*/
public ArrayList tabOrder = new ArrayList();
/**
* Preferred method of determining the number of instances
* of a given field.
*
* @since 2.1.5
* @return number of instances
*/
public int size() {
return values.size();
}
/**
* Remove the given instance from this item. It is possible to
* remove all instances using this function.
*
* @since 2.1.5
* @param killIdx
*/
void remove(int killIdx) {
values.remove(killIdx);
widgets.remove(killIdx);
widget_refs.remove(killIdx);
merged.remove(killIdx);
page.remove(killIdx);
tabOrder.remove(killIdx);
}
/**
* Retrieve the value dictionary of the given instance
*
* @since 2.1.5
* @param idx instance index
* @return dictionary storing this instance's value. It may be shared across instances.
*/
public PdfDictionary getValue(int idx) {
return (PdfDictionary) values.get(idx);
}
/**
* Add a value dict to this Item
*
* @since 2.1.5
* @param value new value dictionary
*/
void addValue(PdfDictionary value) {
values.add(value);
}
/**
* Retrieve the widget dictionary of the given instance
*
* @since 2.1.5
* @param idx instance index
* @return The dictionary found in the appropriate page's Annot array.
*/
public PdfDictionary getWidget(int idx) {
return (PdfDictionary) widgets.get(idx);
}
/**
* Add a widget dict to this Item
*
* @since 2.1.5
* @param widget
*/
void addWidget(PdfDictionary widget) {
widgets.add(widget);
}
/**
* Retrieve the reference to the given instance
*
* @since 2.1.5
* @param idx instance index
* @return reference to the given field instance
*/
public PdfIndirectReference getWidgetRef(int idx) {
return (PdfIndirectReference) widget_refs.get(idx);
}
/**
* Add a widget ref to this Item
*
* @since 2.1.5
* @param widgRef
*/
void addWidgetRef(PdfIndirectReference widgRef) {
widget_refs.add(widgRef);
}
/**
* Retrieve the merged dictionary for the given instance. The merged
* dictionary contains all the keys present in parent fields, though they
* may have been overwritten (or modified?) by children.
* Example: a merged radio field dict will contain /V
*
* @since 2.1.5
* @param idx instance index
* @return the merged dictionary for the given instance
*/
public PdfDictionary getMerged(int idx) {
return (PdfDictionary) merged.get(idx);
}
/**
* Adds a merged dictionary to this Item.
*
* @since 2.1.5
* @param mergeDict
*/
void addMerged(PdfDictionary mergeDict) {
merged.add(mergeDict);
}
/**
* Retrieve the page number of the given instance
*
* @since 2.1.5
* @param idx
* @return remember, pages are "1-indexed", not "0-indexed" like field instances.
*/
public Integer getPage(int idx) {
return (Integer) page.get(idx);
}
/**
* Adds a page to the current Item.
*
* @since 2.1.5
* @param pg
*/
void addPage(int pg) {
page.add(new Integer(pg));
}
/**
* forces a page value into the Item.
*
* @since 2.1.5
* @param idx
*/
void forcePage(int idx, int pg) {
page.set(idx, new Integer( pg ));
}
/**
* Gets the tabOrder.
*
* @since 2.1.5
* @param idx
* @return tab index of the given field instance
*/
public Integer getTabOrder(int idx) {
return (Integer) tabOrder.get(idx);
}
/**
* Adds a tab order value to this Item.
*
* @since 2.1.5
* @param order
*/
void addTabOrder(int order) {
tabOrder.add(new Integer(order));
}
}
private static class InstHit {
IntHashtable hits;
public InstHit(int inst[]) {
if (inst == null)
return;
hits = new IntHashtable();
for (int k = 0; k < inst.length; ++k)
hits.put(inst[k], 1);
}
public boolean isHit(int n) {
if (hits == null)
return true;
return hits.containsKey(n);
}
}
/**
* Gets the field names that have signatures and are signed.
*
* @return the field names that have signatures and are signed
*/
public ArrayList getSignatureNames() {
if (sigNames != null)
return new ArrayList(sigNames.keySet());
sigNames = new HashMap();
ArrayList sorter = new ArrayList();
for (Iterator it = fields.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
Item item = (Item)entry.getValue();
PdfDictionary merged = item.getMerged(0);
if (!PdfName.SIG.equals(merged.get(PdfName.FT)))
continue;
PdfDictionary v = merged.getAsDict(PdfName.V);
if (v == null)
continue;
PdfString contents = v.getAsString(PdfName.CONTENTS);
if (contents == null)
continue;
PdfArray ro = v.getAsArray(PdfName.BYTERANGE);
if (ro == null)
continue;
int rangeSize = ro.size();
if (rangeSize < 2)
continue;
int length = ro.getAsNumber(rangeSize - 1).intValue() + ro.getAsNumber(rangeSize - 2).intValue();
sorter.add(new Object[]{entry.getKey(), new int[]{length, 0}});
}
Collections.sort(sorter, new AcroFields.SorterComparator());
if (!sorter.isEmpty()) {
if (((int[])((Object[])sorter.get(sorter.size() - 1))[1])[0] == reader.getFileLength())
totalRevisions = sorter.size();
else
totalRevisions = sorter.size() + 1;
for (int k = 0; k < sorter.size(); ++k) {
Object objs[] = (Object[])sorter.get(k);
String name = (String)objs[0];
int p[] = (int[])objs[1];
p[1] = k + 1;
sigNames.put(name, p);
}
}
return new ArrayList(sigNames.keySet());
}
/**
* Gets the field names that have blank signatures.
*
* @return the field names that have blank signatures
*/
public ArrayList getBlankSignatureNames() {
getSignatureNames();
ArrayList sigs = new ArrayList();
for (Iterator it = fields.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
Item item = (Item)entry.getValue();
PdfDictionary merged = item.getMerged(0);
if (!PdfName.SIG.equals(merged.getAsName(PdfName.FT)))
continue;
if (sigNames.containsKey(entry.getKey()))
continue;
sigs.add(entry.getKey());
}
return sigs;
}
/**
* Gets the signature dictionary, the one keyed by /V.
*
* @param name the field name
* @return the signature dictionary keyed by /V or null
if the field is not
* a signature
*/
public PdfDictionary getSignatureDictionary(String name) {
getSignatureNames();
name = getTranslatedFieldName(name);
if (!sigNames.containsKey(name))
return null;
Item item = (Item)fields.get(name);
PdfDictionary merged = item.getMerged(0);
return merged.getAsDict(PdfName.V);
}
/**
* Checks is the signature covers the entire document or just part of it.
*
* @param name the signature field name
* @return true
if the signature covers the entire document,
* false
otherwise
*/
public boolean signatureCoversWholeDocument(String name) {
getSignatureNames();
name = getTranslatedFieldName(name);
if (!sigNames.containsKey(name))
return false;
return ((int[])sigNames.get(name))[0] == reader.getFileLength();
}
/**
* Verifies a signature. An example usage is:
*
* KeyStore kall = PdfPKCS7.loadCacertsKeyStore();
* PdfReader reader = new PdfReader("my_signed_doc.pdf");
* AcroFields af = reader.getAcroFields();
* ArrayList names = af.getSignatureNames();
* for (int k = 0; k < names.size(); ++k) {
* String name = (String)names.get(k);
* System.out.println("Signature name: " + name);
* System.out.println("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
* PdfPKCS7 pk = af.verifySignature(name);
* Calendar cal = pk.getSignDate();
* Certificate pkc[] = pk.getCertificates();
* System.out.println("Subject: " + PdfPKCS7.getSubjectFields(pk.getSigningCertificate()));
* System.out.println("Document modified: " + !pk.verify());
* Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null, cal);
* if (fails == null)
* System.out.println("Certificates verified against the KeyStore");
* else
* System.out.println("Certificate failed: " + fails[1]);
* }
*
*
* @param name the signature field name
* @return a PdfPKCS7
class to continue the verification
*/
public PdfPKCS7 verifySignature(String name) {
return verifySignature(name, null);
}
/**
* Verifies a signature. An example usage is:
*
* KeyStore kall = PdfPKCS7.loadCacertsKeyStore();
* PdfReader reader = new PdfReader("my_signed_doc.pdf");
* AcroFields af = reader.getAcroFields();
* ArrayList names = af.getSignatureNames();
* for (int k = 0; k < names.size(); ++k) {
* String name = (String)names.get(k);
* System.out.println("Signature name: " + name);
* System.out.println("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
* PdfPKCS7 pk = af.verifySignature(name);
* Calendar cal = pk.getSignDate();
* Certificate pkc[] = pk.getCertificates();
* System.out.println("Subject: " + PdfPKCS7.getSubjectFields(pk.getSigningCertificate()));
* System.out.println("Document modified: " + !pk.verify());
* Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null, cal);
* if (fails == null)
* System.out.println("Certificates verified against the KeyStore");
* else
* System.out.println("Certificate failed: " + fails[1]);
* }
*
*
* @param name the signature field name
* @param provider the provider or null
for the default provider
* @return a PdfPKCS7
class to continue the verification
*/
public PdfPKCS7 verifySignature(String name, String provider) {
PdfDictionary v = getSignatureDictionary(name);
if (v == null)
return null;
try {
PdfName sub = v.getAsName(PdfName.SUBFILTER);
PdfString contents = v.getAsString(PdfName.CONTENTS);
PdfPKCS7 pk = null;
if (sub.equals(PdfName.ADBE_X509_RSA_SHA1)) {
PdfString cert = v.getAsString(PdfName.CERT);
pk = new PdfPKCS7(contents.getOriginalBytes(), cert.getBytes(), provider);
}
else
pk = new PdfPKCS7(contents.getOriginalBytes(), provider);
updateByteRange(pk, v);
PdfString str = v.getAsString(PdfName.M);
if (str != null)
pk.setSignDate(PdfDate.decode(str.toString()));
PdfObject obj = PdfReader.getPdfObject(v.get(PdfName.NAME));
if (obj != null) {
if (obj.isString())
pk.setSignName(((PdfString)obj).toUnicodeString());
else if(obj.isName())
pk.setSignName(PdfName.decodeName(obj.toString()));
}
str = v.getAsString(PdfName.REASON);
if (str != null)
pk.setReason(str.toUnicodeString());
str = v.getAsString(PdfName.LOCATION);
if (str != null)
pk.setLocation(str.toUnicodeString());
return pk;
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
}
private void updateByteRange(PdfPKCS7 pkcs7, PdfDictionary v) {
PdfArray b = v.getAsArray(PdfName.BYTERANGE);
RandomAccessFileOrArray rf = reader.getSafeFile();
try {
rf.reOpen();
byte buf[] = new byte[8192];
for (int k = 0; k < b.size(); ++k) {
int start = b.getAsNumber(k).intValue();
int length = b.getAsNumber(++k).intValue();
rf.seek(start);
while (length > 0) {
int rd = rf.read(buf, 0, Math.min(length, buf.length));
if (rd <= 0)
break;
length -= rd;
pkcs7.update(buf, 0, rd);
}
}
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
finally {
try{rf.close();}catch(Exception e){}
}
}
private void markUsed(PdfObject obj) {
if (!append)
return;
((PdfStamperImp)writer).markUsed(obj);
}
/**
* Gets the total number of revisions this document has.
*
* @return the total number of revisions
*/
public int getTotalRevisions() {
getSignatureNames();
return this.totalRevisions;
}
/**
* Gets this field
revision.
*
* @param field the signature field name
* @return the revision or zero if it's not a signature field
*/
public int getRevision(String field) {
getSignatureNames();
field = getTranslatedFieldName(field);
if (!sigNames.containsKey(field))
return 0;
return ((int[])sigNames.get(field))[1];
}
/**
* Extracts a revision from the document.
*
* @param field the signature field name
* @return an InputStream
covering the revision. Returns null
if
* it's not a signature field
* @throws IOException on error
*/
public InputStream extractRevision(String field) throws IOException {
getSignatureNames();
field = getTranslatedFieldName(field);
if (!sigNames.containsKey(field))
return null;
int length = ((int[])sigNames.get(field))[0];
RandomAccessFileOrArray raf = reader.getSafeFile();
raf.reOpen();
raf.seek(0);
return new RevisionStream(raf, length);
}
/**
* Gets the appearances cache.
*
* @return the appearances cache
* @since 2.1.5 this method used to return a HashMap
*/
public Map getFieldCache() {
return this.fieldCache;
}
/**
* Sets a cache for field appearances. Parsing the existing PDF to
* create a new TextField is time expensive. For those tasks that repeatedly
* fill the same PDF with different field values the use of the cache has dramatic
* speed advantages. An example usage:
*
* String pdfFile = ...;// the pdf file used as template
* ArrayList xfdfFiles = ...;// the xfdf file names
* ArrayList pdfOutFiles = ...;// the output file names, one for each element in xpdfFiles
* HashMap cache = new HashMap();// the appearances cache
* PdfReader originalReader = new PdfReader(pdfFile);
* for (int k = 0; k < xfdfFiles.size(); ++k) {
* PdfReader reader = new PdfReader(originalReader);
* XfdfReader xfdf = new XfdfReader((String)xfdfFiles.get(k));
* PdfStamper stp = new PdfStamper(reader, new FileOutputStream((String)pdfOutFiles.get(k)));
* AcroFields af = stp.getAcroFields();
* af.setFieldCache(cache);
* af.setFields(xfdf);
* stp.close();
* }
*
*
* @param fieldCache a Map that will carry the cached appearances
* @since 2.1.5 this method used to take a HashMap as parameter
*/
public void setFieldCache(Map fieldCache) {
this.fieldCache = fieldCache;
}
/**
* Sets extra margins in text fields to better mimic the Acrobat layout.
*
* @param extraMarginLeft the extra margin left
* @param extraMarginTop the extra margin top
*/
public void setExtraMargin(float extraMarginLeft, float extraMarginTop) {
this.extraMarginLeft = extraMarginLeft;
this.extraMarginTop = extraMarginTop;
}
/**
* Adds a substitution font to the list. The fonts in this list will be used if the original
* font doesn't contain the needed glyphs.
*
* @param font the font
*/
public void addSubstitutionFont(BaseFont font) {
if (substitutionFonts == null)
substitutionFonts = new ArrayList();
substitutionFonts.add(font);
}
private static final HashMap stdFieldFontNames = new HashMap();
/**
* Holds value of property totalRevisions.
*/
private int totalRevisions;
/**
* Holds value of property fieldCache.
*
* @since 2.1.5 this used to be a HashMap
*/
private Map fieldCache;
static {
stdFieldFontNames.put("CoBO", new String[]{"Courier-BoldOblique"});
stdFieldFontNames.put("CoBo", new String[]{"Courier-Bold"});
stdFieldFontNames.put("CoOb", new String[]{"Courier-Oblique"});
stdFieldFontNames.put("Cour", new String[]{"Courier"});
stdFieldFontNames.put("HeBO", new String[]{"Helvetica-BoldOblique"});
stdFieldFontNames.put("HeBo", new String[]{"Helvetica-Bold"});
stdFieldFontNames.put("HeOb", new String[]{"Helvetica-Oblique"});
stdFieldFontNames.put("Helv", new String[]{"Helvetica"});
stdFieldFontNames.put("Symb", new String[]{"Symbol"});
stdFieldFontNames.put("TiBI", new String[]{"Times-BoldItalic"});
stdFieldFontNames.put("TiBo", new String[]{"Times-Bold"});
stdFieldFontNames.put("TiIt", new String[]{"Times-Italic"});
stdFieldFontNames.put("TiRo", new String[]{"Times-Roman"});
stdFieldFontNames.put("ZaDb", new String[]{"ZapfDingbats"});
stdFieldFontNames.put("HySm", new String[]{"HYSMyeongJo-Medium", "UniKS-UCS2-H"});
stdFieldFontNames.put("HyGo", new String[]{"HYGoThic-Medium", "UniKS-UCS2-H"});
stdFieldFontNames.put("KaGo", new String[]{"HeiseiKakuGo-W5", "UniKS-UCS2-H"});
stdFieldFontNames.put("KaMi", new String[]{"HeiseiMin-W3", "UniJIS-UCS2-H"});
stdFieldFontNames.put("MHei", new String[]{"MHei-Medium", "UniCNS-UCS2-H"});
stdFieldFontNames.put("MSun", new String[]{"MSung-Light", "UniCNS-UCS2-H"});
stdFieldFontNames.put("STSo", new String[]{"STSong-Light", "UniGB-UCS2-H"});
}
private static class RevisionStream extends InputStream {
private byte b[] = new byte[1];
private RandomAccessFileOrArray raf;
private int length;
private int rangePosition = 0;
private boolean closed;
private RevisionStream(RandomAccessFileOrArray raf, int length) {
this.raf = raf;
this.length = length;
}
public int read() throws IOException {
int n = read(b);
if (n != 1)
return -1;
return b[0] & 0xff;
}
public int read(byte[] b, int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
} else if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
if (rangePosition >= length) {
close();
return -1;
}
int elen = Math.min(len, length - rangePosition);
raf.readFully(b, off, elen);
rangePosition += elen;
return elen;
}
public void close() throws IOException {
if (!closed) {
raf.close();
closed = true;
}
}
}
private static class SorterComparator implements Comparator {
public int compare(Object o1, Object o2) {
int n1 = ((int[])((Object[])o1)[1])[0];
int n2 = ((int[])((Object[])o2)[1])[0];
return n1 - n2;
}
}
/**
* Gets the list of substitution fonts. The list is composed of BaseFont
and can be null
. The fonts in this list will be used if the original
* font doesn't contain the needed glyphs.
*
* @return the list
*/
public ArrayList getSubstitutionFonts() {
return substitutionFonts;
}
/**
* Sets a list of substitution fonts. The list is composed of BaseFont
and can also be null
. The fonts in this list will be used if the original
* font doesn't contain the needed glyphs.
*
* @param substitutionFonts the list
*/
public void setSubstitutionFonts(ArrayList substitutionFonts) {
this.substitutionFonts = substitutionFonts;
}
/**
* Gets the XFA form processor.
*
* @return the XFA form processor
*/
public XfaForm getXfa() {
return xfa;
}
private static final PdfName[] buttonRemove = {PdfName.MK, PdfName.F , PdfName.FF , PdfName.Q , PdfName.BS , PdfName.BORDER};
/**
* Creates a new pushbutton from an existing field. If there are several pushbuttons with the same name
* only the first one is used. This pushbutton can be changed and be used to replace
* an existing one, with the same name or other name, as long is it is in the same document. To replace an existing pushbutton
* call {@link #replacePushbuttonField(String,PdfFormField)}.
*
* @param field the field name that should be a pushbutton
* @return a new pushbutton or null
if the field is not a pushbutton
*/
public PushbuttonField getNewPushbuttonFromField(String field) {
return getNewPushbuttonFromField(field, 0);
}
/**
* Creates a new pushbutton from an existing field. This pushbutton can be changed and be used to replace
* an existing one, with the same name or other name, as long is it is in the same document. To replace an existing pushbutton
* call {@link #replacePushbuttonField(String,PdfFormField,int)}.
*
* @param field the field name that should be a pushbutton
* @param order the field order in fields with same name
* @return a new pushbutton or null
if the field is not a pushbutton
*
* @since 2.0.7
*/
public PushbuttonField getNewPushbuttonFromField(String field, int order) {
try {
if (getFieldType(field) != FIELD_TYPE_PUSHBUTTON)
return null;
Item item = getFieldItem(field);
if (order >= item.size())
return null;
int posi = order * 5;
float[] pos = getFieldPositions(field);
Rectangle box = new Rectangle(pos[posi + 1], pos[posi + 2], pos[posi + 3], pos[posi + 4]);
PushbuttonField newButton = new PushbuttonField(writer, box, null);
PdfDictionary dic = item.getMerged(order);
decodeGenericDictionary(dic, newButton);
PdfDictionary mk = dic.getAsDict(PdfName.MK);
if (mk != null) {
PdfString text = mk.getAsString(PdfName.CA);
if (text != null)
newButton.setText(text.toUnicodeString());
PdfNumber tp = mk.getAsNumber(PdfName.TP);
if (tp != null)
newButton.setLayout(tp.intValue() + 1);
PdfDictionary ifit = mk.getAsDict(PdfName.IF);
if (ifit != null) {
PdfName sw = ifit.getAsName(PdfName.SW);
if (sw != null) {
int scale = PushbuttonField.SCALE_ICON_ALWAYS;
if (sw.equals(PdfName.B))
scale = PushbuttonField.SCALE_ICON_IS_TOO_BIG;
else if (sw.equals(PdfName.S))
scale = PushbuttonField.SCALE_ICON_IS_TOO_SMALL;
else if (sw.equals(PdfName.N))
scale = PushbuttonField.SCALE_ICON_NEVER;
newButton.setScaleIcon(scale);
}
sw = ifit.getAsName(PdfName.S);
if (sw != null) {
if (sw.equals(PdfName.A))
newButton.setProportionalIcon(false);
}
PdfArray aj = ifit.getAsArray(PdfName.A);
if (aj != null && aj.size() == 2) {
float left = aj.getAsNumber(0).floatValue();
float bottom = aj.getAsNumber(1).floatValue();
newButton.setIconHorizontalAdjustment(left);
newButton.setIconVerticalAdjustment(bottom);
}
PdfBoolean fb = ifit.getAsBoolean(PdfName.FB);
if (fb != null && fb.booleanValue())
newButton.setIconFitToBounds(true);
}
PdfObject i = mk.get(PdfName.I);
if (i != null && i.isIndirect())
newButton.setIconReference((PRIndirectReference)i);
}
return newButton;
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
}
/**
* Replaces the first field with a new pushbutton. The pushbutton can be created with
* {@link #getNewPushbuttonFromField(String)} from the same document or it can be a
* generic PdfFormField of the type pushbutton.
*
* @param field the field name
* @param button the PdfFormField
representing the pushbutton
* @return true
if the field was replaced, false
if the field
* was not a pushbutton
*/
public boolean replacePushbuttonField(String field, PdfFormField button) {
return replacePushbuttonField(field, button, 0);
}
/**
* Replaces the designated field with a new pushbutton. The pushbutton can be created with
* {@link #getNewPushbuttonFromField(String,int)} from the same document or it can be a
* generic PdfFormField of the type pushbutton.
*
* @param field the field name
* @param button the PdfFormField
representing the pushbutton
* @param order the field order in fields with same name
* @return true
if the field was replaced, false
if the field
* was not a pushbutton
*
* @since 2.0.7
*/
public boolean replacePushbuttonField(String field, PdfFormField button, int order) {
if (getFieldType(field) != FIELD_TYPE_PUSHBUTTON)
return false;
Item item = getFieldItem(field);
if (order >= item.size())
return false;
PdfDictionary merged = item.getMerged(order);
PdfDictionary values = item.getValue(order);
PdfDictionary widgets = item.getWidget(order);
for (int k = 0; k < buttonRemove.length; ++k) {
merged.remove(buttonRemove[k]);
values.remove(buttonRemove[k]);
widgets.remove(buttonRemove[k]);
}
for (Iterator it = button.getKeys().iterator(); it.hasNext();) {
PdfName key = (PdfName)it.next();
if (key.equals(PdfName.T) || key.equals(PdfName.RECT))
continue;
if (key.equals(PdfName.FF))
values.put(key, button.get(key));
else
widgets.put(key, button.get(key));
merged.put(key, button.get(key));
}
return true;
}
}
src/core/com/lowagie/text/pdf/ArabicLigaturizer.java 100644 0 0 75061 11000354131 20151 0 ustar 0 0 /*
* Copyright 2003 by Paulo Soares.
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.pdf;
/**
* Shape arabic characters. This code was inspired by an LGPL'ed C library:
* Pango ( see http://www.pango.com/ ). Note that the code of this is the
* original work of Paulo Soares. Hence it is perfectly justifiable to distribute
* it under the MPL.
*
* @author Paulo Soares (psoares@consiste.pt)
*/
public class ArabicLigaturizer {
static boolean isVowel(char s) {
return ((s >= 0x064B) && (s <= 0x0655)) || (s == 0x0670);
}
static char charshape(char s, int which)
/* which 0=isolated 1=final 2=initial 3=medial */
{
int l, r, m;
if ((s >= 0x0621) && (s <= 0x06D3)) {
l = 0;
r = chartable.length - 1;
while (l <= r) {
m = (l + r) / 2;
if (s == chartable[m][0]) {
return chartable[m][which + 1];
}
else if (s < chartable[m][0]) {
r = m - 1;
}
else {
l = m + 1;
}
}
}
else if (s >= 0xfef5 && s <= 0xfefb)
return (char)(s + which);
return s;
}
static int shapecount(char s) {
int l, r, m;
if ((s >= 0x0621) && (s <= 0x06D3) && !isVowel(s)) {
l = 0;
r = chartable.length - 1;
while (l <= r) {
m = (l + r) / 2;
if (s == chartable[m][0]) {
return chartable[m].length - 1;
}
else if (s < chartable[m][0]) {
r = m - 1;
}
else {
l = m + 1;
}
}
}
else if (s == ZWJ) {
return 4;
}
return 1;
}
static int ligature(char newchar, charstruct oldchar) {
/* 0 == no ligature possible; 1 == vowel; 2 == two chars; 3 == Lam+Alef */
int retval = 0;
if (oldchar.basechar == 0)
return 0;
if (isVowel(newchar)) {
retval = 1;
if ((oldchar.vowel != 0) && (newchar != SHADDA)) {
retval = 2; /* we eliminate the old vowel .. */
}
switch (newchar) {
case SHADDA:
if (oldchar.mark1 == 0) {
oldchar.mark1 = SHADDA;
}
else {
return 0; /* no ligature possible */
}
break;
case HAMZABELOW:
switch (oldchar.basechar) {
case ALEF:
oldchar.basechar = ALEFHAMZABELOW;
retval = 2;
break;
case LAM_ALEF:
oldchar.basechar = LAM_ALEFHAMZABELOW;
retval = 2;
break;
default:
oldchar.mark1 = HAMZABELOW;
break;
}
break;
case HAMZAABOVE:
switch (oldchar.basechar) {
case ALEF:
oldchar.basechar = ALEFHAMZA;
retval = 2;
break;
case LAM_ALEF:
oldchar.basechar = LAM_ALEFHAMZA;
retval = 2;
break;
case WAW:
oldchar.basechar = WAWHAMZA;
retval = 2;
break;
case YEH:
case ALEFMAKSURA:
case FARSIYEH:
oldchar.basechar = YEHHAMZA;
retval = 2;
break;
default: /* whatever sense this may make .. */
oldchar.mark1 = HAMZAABOVE;
break;
}
break;
case MADDA:
switch (oldchar.basechar) {
case ALEF:
oldchar.basechar = ALEFMADDA;
retval = 2;
break;
}
break;
default:
oldchar.vowel = newchar;
break;
}
if (retval == 1) {
oldchar.lignum++;
}
return retval;
}
if (oldchar.vowel != 0) { /* if we already joined a vowel, we can't join a Hamza */
return 0;
}
switch (oldchar.basechar) {
case LAM:
switch (newchar) {
case ALEF:
oldchar.basechar = LAM_ALEF;
oldchar.numshapes = 2;
retval = 3;
break;
case ALEFHAMZA:
oldchar.basechar = LAM_ALEFHAMZA;
oldchar.numshapes = 2;
retval = 3;
break;
case ALEFHAMZABELOW:
oldchar.basechar = LAM_ALEFHAMZABELOW;
oldchar.numshapes = 2;
retval = 3;
break;
case ALEFMADDA:
oldchar.basechar = LAM_ALEFMADDA;
oldchar.numshapes = 2;
retval = 3;
break;
}
break;
case 0:
oldchar.basechar = newchar;
oldchar.numshapes = shapecount(newchar);
retval = 1;
break;
}
return retval;
}
static void copycstostring(StringBuffer string, charstruct s, int level) {
/* s is a shaped charstruct; i is the index into the string */
if (s.basechar == 0)
return;
string.append(s.basechar);
s.lignum--;
if (s.mark1 != 0) {
if ((level & ar_novowel) == 0) {
string.append(s.mark1);
s.lignum--;
}
else {
s.lignum--;
}
}
if (s.vowel != 0) {
if ((level & ar_novowel) == 0) {
string.append(s.vowel);
s.lignum--;
}
else { /* vowel elimination */
s.lignum--;
}
}
// while (s.lignum > 0) { /* NULL-insertion for Langbox-font */
// string[i] = 0;
// i++;
// (s.lignum)--;
// }
// return i;
}
// return len
static void doublelig(StringBuffer string, int level)
/* Ok. We have presentation ligatures in our font. */
{
int len;
int olen = len = string.length();
int j = 0, si = 1;
char lapresult;
while (si < olen) {
lapresult = 0;
if ((level & ar_composedtashkeel) != 0) {
switch (string.charAt(j)) {
case SHADDA:
switch (string.charAt(si)) {
case KASRA:
lapresult = 0xFC62;
break;
case FATHA:
lapresult = 0xFC60;
break;
case DAMMA:
lapresult = 0xFC61;
break;
case 0x064C:
lapresult = 0xFC5E;
break;
case 0x064D:
lapresult = 0xFC5F;
break;
}
break;
case KASRA:
if (string.charAt(si) == SHADDA)
lapresult = 0xFC62;
break;
case FATHA:
if (string.charAt(si) == SHADDA)
lapresult = 0xFC60;
break;
case DAMMA:
if (string.charAt(si) == SHADDA)
lapresult = 0xFC61;
break;
}
}
if ((level & ar_lig) != 0) {
switch (string.charAt(j)) {
case 0xFEDF: /* LAM initial */
switch (string.charAt(si)) {
case 0xFE9E:
lapresult = 0xFC3F;
break; /* JEEM final */
case 0xFEA0:
lapresult = 0xFCC9;
break; /* JEEM medial */
case 0xFEA2:
lapresult = 0xFC40;
break; /* HAH final */
case 0xFEA4:
lapresult = 0xFCCA;
break; /* HAH medial */
case 0xFEA6:
lapresult = 0xFC41;
break; /* KHAH final */
case 0xFEA8:
lapresult = 0xFCCB;
break; /* KHAH medial */
case 0xFEE2:
lapresult = 0xFC42;
break; /* MEEM final */
case 0xFEE4:
lapresult = 0xFCCC;
break; /* MEEM medial */
}
break;
case 0xFE97: /* TEH inital */
switch (string.charAt(si)) {
case 0xFEA0:
lapresult = 0xFCA1;
break; /* JEEM medial */
case 0xFEA4:
lapresult = 0xFCA2;
break; /* HAH medial */
case 0xFEA8:
lapresult = 0xFCA3;
break; /* KHAH medial */
}
break;
case 0xFE91: /* BEH inital */
switch (string.charAt(si)) {
case 0xFEA0:
lapresult = 0xFC9C;
break; /* JEEM medial */
case 0xFEA4:
lapresult = 0xFC9D;
break; /* HAH medial */
case 0xFEA8:
lapresult = 0xFC9E;
break; /* KHAH medial */
}
break;
case 0xFEE7: /* NOON inital */
switch (string.charAt(si)) {
case 0xFEA0:
lapresult = 0xFCD2;
break; /* JEEM initial */
case 0xFEA4:
lapresult = 0xFCD3;
break; /* HAH medial */
case 0xFEA8:
lapresult = 0xFCD4;
break; /* KHAH medial */
}
break;
case 0xFEE8: /* NOON medial */
switch (string.charAt(si)) {
case 0xFEAE:
lapresult = 0xFC8A;
break; /* REH final */
case 0xFEB0:
lapresult = 0xFC8B;
break; /* ZAIN final */
}
break;
case 0xFEE3: /* MEEM initial */
switch (string.charAt(si)) {
case 0xFEA0:
lapresult = 0xFCCE;
break; /* JEEM medial */
case 0xFEA4:
lapresult = 0xFCCF;
break; /* HAH medial */
case 0xFEA8:
lapresult = 0xFCD0;
break; /* KHAH medial */
case 0xFEE4:
lapresult = 0xFCD1;
break; /* MEEM medial */
}
break;
case 0xFED3: /* FEH initial */
switch (string.charAt(si)) {
case 0xFEF2:
lapresult = 0xFC32;
break; /* YEH final */
}
break;
default:
break;
} /* end switch string[si] */
}
if (lapresult != 0) {
string.setCharAt(j, lapresult);
len--;
si++; /* jump over one character */
/* we'll have to change this, too. */
}
else {
j++;
string.setCharAt(j, string.charAt(si));
si++;
}
}
string.setLength(len);
}
static boolean connects_to_left(charstruct a) {
return a.numshapes > 2;
}
static void shape(char text[], StringBuffer string, int level) {
/* string is assumed to be empty and big enough.
* text is the original text.
* This routine does the basic arabic reshaping.
* *len the number of non-null characters.
*
* Note: We have to unshape each character first!
*/
int join;
int which;
char nextletter;
int p = 0; /* initialize for output */
charstruct oldchar = new charstruct();
charstruct curchar = new charstruct();
while (p < text.length) {
nextletter = text[p++];
//nextletter = unshape (nextletter);
join = ligature(nextletter, curchar);
if (join == 0) { /* shape curchar */
int nc = shapecount(nextletter);
//(*len)++;
if (nc == 1) {
which = 0; /* final or isolated */
}
else {
which = 2; /* medial or initial */
}
if (connects_to_left(oldchar)) {
which++;
}
which = which % (curchar.numshapes);
curchar.basechar = charshape(curchar.basechar, which);
/* get rid of oldchar */
copycstostring(string, oldchar, level);
oldchar = curchar; /* new values in oldchar */
/* init new curchar */
curchar = new charstruct();
curchar.basechar = nextletter;
curchar.numshapes = nc;
curchar.lignum++;
// (*len) += unligature (&curchar, level);
}
else if (join == 1) {
}
// else
// {
// (*len) += unligature (&curchar, level);
// }
// p = g_utf8_next_char (p);
}
/* Handle last char */
if (connects_to_left(oldchar))
which = 1;
else
which = 0;
which = which % (curchar.numshapes);
curchar.basechar = charshape(curchar.basechar, which);
/* get rid of oldchar */
copycstostring(string, oldchar, level);
copycstostring(string, curchar, level);
}
static int arabic_shape(char src[], int srcoffset, int srclength, char dest[], int destoffset, int destlength, int level) {
char str[] = new char[srclength];
for (int k = srclength + srcoffset - 1; k >= srcoffset; --k)
str[k - srcoffset] = src[k];
StringBuffer string = new StringBuffer(srclength);
shape(str, string, level);
if ((level & (ar_composedtashkeel | ar_lig)) != 0)
doublelig(string, level);
// string.reverse();
System.arraycopy(string.toString().toCharArray(), 0, dest, destoffset, string.length());
return string.length();
}
static void processNumbers(char text[], int offset, int length, int options) {
int limit = offset + length;
if ((options & DIGITS_MASK) != 0) {
char digitBase = '\u0030'; // European digits
switch (options & DIGIT_TYPE_MASK) {
case DIGIT_TYPE_AN:
digitBase = '\u0660'; // Arabic-Indic digits
break;
case DIGIT_TYPE_AN_EXTENDED:
digitBase = '\u06f0'; // Eastern Arabic-Indic digits (Persian and Urdu)
break;
default:
break;
}
switch (options & DIGITS_MASK) {
case DIGITS_EN2AN: {
int digitDelta = digitBase - '\u0030';
for (int i = offset; i < limit; ++i) {
char ch = text[i];
if (ch <= '\u0039' && ch >= '\u0030') {
text[i] += digitDelta;
}
}
}
break;
case DIGITS_AN2EN: {
char digitTop = (char)(digitBase + 9);
int digitDelta = '\u0030' - digitBase;
for (int i = offset; i < limit; ++i) {
char ch = text[i];
if (ch <= digitTop && ch >= digitBase) {
text[i] += digitDelta;
}
}
}
break;
case DIGITS_EN2AN_INIT_LR:
shapeToArabicDigitsWithContext(text, 0, length, digitBase, false);
break;
case DIGITS_EN2AN_INIT_AL:
shapeToArabicDigitsWithContext(text, 0, length, digitBase, true);
break;
default:
break;
}
}
}
static void shapeToArabicDigitsWithContext(char[] dest, int start, int length, char digitBase, boolean lastStrongWasAL) {
digitBase -= '0'; // move common adjustment out of loop
int limit = start + length;
for(int i = start; i < limit; ++i) {
char ch = dest[i];
switch (BidiOrder.getDirection(ch)) {
case BidiOrder.L:
case BidiOrder.R:
lastStrongWasAL = false;
break;
case BidiOrder.AL:
lastStrongWasAL = true;
break;
case BidiOrder.EN:
if (lastStrongWasAL && ch <= '\u0039') {
dest[i] = (char)(ch + digitBase);
}
break;
default:
break;
}
}
}
private static final char ALEF = 0x0627;
private static final char ALEFHAMZA = 0x0623;
private static final char ALEFHAMZABELOW = 0x0625;
private static final char ALEFMADDA = 0x0622;
private static final char LAM = 0x0644;
private static final char HAMZA = 0x0621;
private static final char TATWEEL = 0x0640;
private static final char ZWJ = 0x200D;
private static final char HAMZAABOVE = 0x0654;
private static final char HAMZABELOW = 0x0655;
private static final char WAWHAMZA = 0x0624;
private static final char YEHHAMZA = 0x0626;
private static final char WAW = 0x0648;
private static final char ALEFMAKSURA = 0x0649;
private static final char YEH = 0x064A;
private static final char FARSIYEH = 0x06CC;
private static final char SHADDA = 0x0651;
private static final char KASRA = 0x0650;
private static final char FATHA = 0x064E;
private static final char DAMMA = 0x064F;
private static final char MADDA = 0x0653;
private static final char LAM_ALEF = 0xFEFB;
private static final char LAM_ALEFHAMZA = 0xFEF7;
private static final char LAM_ALEFHAMZABELOW = 0xFEF9;
private static final char LAM_ALEFMADDA = 0xFEF5;
private static final char chartable[][] = {
{0x0621, 0xFE80}, /* HAMZA */
{0x0622, 0xFE81, 0xFE82}, /* ALEF WITH MADDA ABOVE */
{0x0623, 0xFE83, 0xFE84}, /* ALEF WITH HAMZA ABOVE */
{0x0624, 0xFE85, 0xFE86}, /* WAW WITH HAMZA ABOVE */
{0x0625, 0xFE87, 0xFE88}, /* ALEF WITH HAMZA BELOW */
{0x0626, 0xFE89, 0xFE8A, 0xFE8B, 0xFE8C}, /* YEH WITH HAMZA ABOVE */
{0x0627, 0xFE8D, 0xFE8E}, /* ALEF */
{0x0628, 0xFE8F, 0xFE90, 0xFE91, 0xFE92}, /* BEH */
{0x0629, 0xFE93, 0xFE94}, /* TEH MARBUTA */
{0x062A, 0xFE95, 0xFE96, 0xFE97, 0xFE98}, /* TEH */
{0x062B, 0xFE99, 0xFE9A, 0xFE9B, 0xFE9C}, /* THEH */
{0x062C, 0xFE9D, 0xFE9E, 0xFE9F, 0xFEA0}, /* JEEM */
{0x062D, 0xFEA1, 0xFEA2, 0xFEA3, 0xFEA4}, /* HAH */
{0x062E, 0xFEA5, 0xFEA6, 0xFEA7, 0xFEA8}, /* KHAH */
{0x062F, 0xFEA9, 0xFEAA}, /* DAL */
{0x0630, 0xFEAB, 0xFEAC}, /* THAL */
{0x0631, 0xFEAD, 0xFEAE}, /* REH */
{0x0632, 0xFEAF, 0xFEB0}, /* ZAIN */
{0x0633, 0xFEB1, 0xFEB2, 0xFEB3, 0xFEB4}, /* SEEN */
{0x0634, 0xFEB5, 0xFEB6, 0xFEB7, 0xFEB8}, /* SHEEN */
{0x0635, 0xFEB9, 0xFEBA, 0xFEBB, 0xFEBC}, /* SAD */
{0x0636, 0xFEBD, 0xFEBE, 0xFEBF, 0xFEC0}, /* DAD */
{0x0637, 0xFEC1, 0xFEC2, 0xFEC3, 0xFEC4}, /* TAH */
{0x0638, 0xFEC5, 0xFEC6, 0xFEC7, 0xFEC8}, /* ZAH */
{0x0639, 0xFEC9, 0xFECA, 0xFECB, 0xFECC}, /* AIN */
{0x063A, 0xFECD, 0xFECE, 0xFECF, 0xFED0}, /* GHAIN */
{0x0640, 0x0640, 0x0640, 0x0640, 0x0640}, /* TATWEEL */
{0x0641, 0xFED1, 0xFED2, 0xFED3, 0xFED4}, /* FEH */
{0x0642, 0xFED5, 0xFED6, 0xFED7, 0xFED8}, /* QAF */
{0x0643, 0xFED9, 0xFEDA, 0xFEDB, 0xFEDC}, /* KAF */
{0x0644, 0xFEDD, 0xFEDE, 0xFEDF, 0xFEE0}, /* LAM */
{0x0645, 0xFEE1, 0xFEE2, 0xFEE3, 0xFEE4}, /* MEEM */
{0x0646, 0xFEE5, 0xFEE6, 0xFEE7, 0xFEE8}, /* NOON */
{0x0647, 0xFEE9, 0xFEEA, 0xFEEB, 0xFEEC}, /* HEH */
{0x0648, 0xFEED, 0xFEEE}, /* WAW */
{0x0649, 0xFEEF, 0xFEF0, 0xFBE8, 0xFBE9}, /* ALEF MAKSURA */
{0x064A, 0xFEF1, 0xFEF2, 0xFEF3, 0xFEF4}, /* YEH */
{0x0671, 0xFB50, 0xFB51}, /* ALEF WASLA */
{0x0679, 0xFB66, 0xFB67, 0xFB68, 0xFB69}, /* TTEH */
{0x067A, 0xFB5E, 0xFB5F, 0xFB60, 0xFB61}, /* TTEHEH */
{0x067B, 0xFB52, 0xFB53, 0xFB54, 0xFB55}, /* BEEH */
{0x067E, 0xFB56, 0xFB57, 0xFB58, 0xFB59}, /* PEH */
{0x067F, 0xFB62, 0xFB63, 0xFB64, 0xFB65}, /* TEHEH */
{0x0680, 0xFB5A, 0xFB5B, 0xFB5C, 0xFB5D}, /* BEHEH */
{0x0683, 0xFB76, 0xFB77, 0xFB78, 0xFB79}, /* NYEH */
{0x0684, 0xFB72, 0xFB73, 0xFB74, 0xFB75}, /* DYEH */
{0x0686, 0xFB7A, 0xFB7B, 0xFB7C, 0xFB7D}, /* TCHEH */
{0x0687, 0xFB7E, 0xFB7F, 0xFB80, 0xFB81}, /* TCHEHEH */
{0x0688, 0xFB88, 0xFB89}, /* DDAL */
{0x068C, 0xFB84, 0xFB85}, /* DAHAL */
{0x068D, 0xFB82, 0xFB83}, /* DDAHAL */
{0x068E, 0xFB86, 0xFB87}, /* DUL */
{0x0691, 0xFB8C, 0xFB8D}, /* RREH */
{0x0698, 0xFB8A, 0xFB8B}, /* JEH */
{0x06A4, 0xFB6A, 0xFB6B, 0xFB6C, 0xFB6D}, /* VEH */
{0x06A6, 0xFB6E, 0xFB6F, 0xFB70, 0xFB71}, /* PEHEH */
{0x06A9, 0xFB8E, 0xFB8F, 0xFB90, 0xFB91}, /* KEHEH */
{0x06AD, 0xFBD3, 0xFBD4, 0xFBD5, 0xFBD6}, /* NG */
{0x06AF, 0xFB92, 0xFB93, 0xFB94, 0xFB95}, /* GAF */
{0x06B1, 0xFB9A, 0xFB9B, 0xFB9C, 0xFB9D}, /* NGOEH */
{0x06B3, 0xFB96, 0xFB97, 0xFB98, 0xFB99}, /* GUEH */
{0x06BA, 0xFB9E, 0xFB9F}, /* NOON GHUNNA */
{0x06BB, 0xFBA0, 0xFBA1, 0xFBA2, 0xFBA3}, /* RNOON */
{0x06BE, 0xFBAA, 0xFBAB, 0xFBAC, 0xFBAD}, /* HEH DOACHASHMEE */
{0x06C0, 0xFBA4, 0xFBA5}, /* HEH WITH YEH ABOVE */
{0x06C1, 0xFBA6, 0xFBA7, 0xFBA8, 0xFBA9}, /* HEH GOAL */
{0x06C5, 0xFBE0, 0xFBE1}, /* KIRGHIZ OE */
{0x06C6, 0xFBD9, 0xFBDA}, /* OE */
{0x06C7, 0xFBD7, 0xFBD8}, /* U */
{0x06C8, 0xFBDB, 0xFBDC}, /* YU */
{0x06C9, 0xFBE2, 0xFBE3}, /* KIRGHIZ YU */
{0x06CB, 0xFBDE, 0xFBDF}, /* VE */
{0x06CC, 0xFBFC, 0xFBFD, 0xFBFE, 0xFBFF}, /* FARSI YEH */
{0x06D0, 0xFBE4, 0xFBE5, 0xFBE6, 0xFBE7}, /* E */
{0x06D2, 0xFBAE, 0xFBAF}, /* YEH BARREE */
{0x06D3, 0xFBB0, 0xFBB1} /* YEH BARREE WITH HAMZA ABOVE */
};
public static final int ar_nothing = 0x0;
public static final int ar_novowel = 0x1;
public static final int ar_composedtashkeel = 0x4;
public static final int ar_lig = 0x8;
/**
* Digit shaping option: Replace European digits (U+0030...U+0039) by Arabic-Indic digits.
*/
public static final int DIGITS_EN2AN = 0x20;
/**
* Digit shaping option: Replace Arabic-Indic digits by European digits (U+0030...U+0039).
*/
public static final int DIGITS_AN2EN = 0x40;
/**
* Digit shaping option:
* Replace European digits (U+0030...U+0039) by Arabic-Indic digits
* if the most recent strongly directional character
* is an Arabic letter (its Bidi direction value is RIGHT_TO_LEFT_ARABIC).
* The initial state at the start of the text is assumed to be not an Arabic,
* letter, so European digits at the start of the text will not change.
* Compare to DIGITS_ALEN2AN_INIT_AL.
*/
public static final int DIGITS_EN2AN_INIT_LR = 0x60;
/**
* Digit shaping option:
* Replace European digits (U+0030...U+0039) by Arabic-Indic digits
* if the most recent strongly directional character
* is an Arabic letter (its Bidi direction value is RIGHT_TO_LEFT_ARABIC).
* The initial state at the start of the text is assumed to be an Arabic,
* letter, so European digits at the start of the text will change.
* Compare to DIGITS_ALEN2AN_INT_LR.
*/
public static final int DIGITS_EN2AN_INIT_AL = 0x80;
/** Not a valid option value. */
private static final int DIGITS_RESERVED = 0xa0;
/**
* Bit mask for digit shaping options.
*/
public static final int DIGITS_MASK = 0xe0;
/**
* Digit type option: Use Arabic-Indic digits (U+0660...U+0669).
*/
public static final int DIGIT_TYPE_AN = 0;
/**
* Digit type option: Use Eastern (Extended) Arabic-Indic digits (U+06f0...U+06f9).
*/
public static final int DIGIT_TYPE_AN_EXTENDED = 0x100;
/**
* Bit mask for digit type options.
*/
public static final int DIGIT_TYPE_MASK = 0x0100; // 0x3f00?
static class charstruct {
char basechar;
char mark1; /* has to be initialized to zero */
char vowel;
int lignum; /* is a ligature with lignum aditional characters */
int numshapes = 1;
};
}
src/core/com/lowagie/text/pdf/AsianFontMapper.java 100644 0 0 10343 11000354131 17565 0 ustar 0 0 /*
* Copyright 2004 by Takenori.
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.pdf;
import java.awt.Font;
public class AsianFontMapper extends DefaultFontMapper {
public static final String ChineseSimplifiedFont = "STSong-Light";
public static final String ChineseSimplifiedEncoding_H = "UniGB-UCS2-H";
public static final String ChineseSimplifiedEncoding_V = "UniGB-UCS2-V";
public static final String ChineseTraditionalFont_MHei = "MHei-Medium";
public static final String ChineseTraditionalFont_MSung = "MSung-Light";
public static final String ChineseTraditionalEncoding_H = "UniCNS-UCS2-H";
public static final String ChineseTraditionalEncoding_V = "UniCNS-UCS2-V";
public static final String JapaneseFont_Go = "HeiseiKakuGo-W5";
public static final String JapaneseFont_Min = "HeiseiMin-W3";
public static final String JapaneseEncoding_H = "UniJIS-UCS2-H";
public static final String JapaneseEncoding_V = "UniJIS-UCS2-V";
public static final String JapaneseEncoding_HW_H = "UniJIS-UCS2-HW-H";
public static final String JapaneseEncoding_HW_V = "UniJIS-UCS2-HW-V";
public static final String KoreanFont_GoThic = "HYGoThic-Medium";
public static final String KoreanFont_SMyeongJo = "HYSMyeongJo-Medium";
public static final String KoreanEncoding_H = "UniKS-UCS2-H";
public static final String KoreanEncoding_V = "UniKS-UCS2-V";
private final String defaultFont;
private final String encoding;
public AsianFontMapper(String font, String encoding) {
super();
this.defaultFont = font;
this.encoding = encoding;
}
public BaseFont awtToPdf(Font font) {
try {
BaseFontParameters p = getBaseFontParameters(font.getFontName());
if (p != null){
return BaseFont.createFont(p.fontName, p.encoding, p.embedded, p.cached, p.ttfAfm, p.pfb);
}else{
return BaseFont.createFont(defaultFont, encoding, true);
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
src/core/com/lowagie/text/pdf/BadPdfFormatException.java 100644 0 0 6332 11012562273 20704 0 ustar 0 0 /*
* $Id: BadPdfFormatException.java 3373 2008-05-12 16:21:24Z xlv $
*
* Copyright 1999, 2000, 2001, 2002 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.pdf;
/**
* Signals that a bad PDF format has been used to construct a PdfObject
.
*
* @see PdfException
* @see PdfBoolean
* @see PdfNumber
* @see PdfString
* @see PdfName
* @see PdfDictionary
*/
public class BadPdfFormatException extends PdfException {
// constructors
private static final long serialVersionUID = 1802317735708833538L;
/**
* Constructs a BadPdfFormatException
without a message.
*/
BadPdfFormatException() {
super();
}
/**
* Constructs a BadPdfFormatException
with a message.
*
* @param message a message describing the exception
*/
BadPdfFormatException(String message) {
super(message);
}
} src/core/com/lowagie/text/pdf/Barcode.java 100644 0 0 36232 11000354131 16102 0 ustar 0 0 /*
* $Id: Barcode.java 3117 2008-01-31 05:53:22Z xlv $
*
* Copyright 2002-2006 by Paulo Soares.
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.pdf;
import java.awt.Color;
import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
/** Base class containing properties and methods common to all
* barcode types.
*
* @author Paulo Soares (psoares@consiste.pt)
*/
public abstract class Barcode {
/** A type of barcode */
public static final int EAN13 = 1;
/** A type of barcode */
public static final int EAN8 = 2;
/** A type of barcode */
public static final int UPCA = 3;
/** A type of barcode */
public static final int UPCE = 4;
/** A type of barcode */
public static final int SUPP2 = 5;
/** A type of barcode */
public static final int SUPP5 = 6;
/** A type of barcode */
public static final int POSTNET = 7;
/** A type of barcode */
public static final int PLANET = 8;
/** A type of barcode */
public static final int CODE128 = 9;
/** A type of barcode */
public static final int CODE128_UCC = 10;
/** A type of barcode */
public static final int CODE128_RAW = 11;
/** A type of barcode */
public static final int CODABAR = 12;
/** The minimum bar width.
*/
protected float x;
/** The bar multiplier for wide bars or the distance between
* bars for Postnet and Planet.
*/
protected float n;
/** The text font. null
if no text.
*/
protected BaseFont font;
/** The size of the text or the height of the shorter bar
* in Postnet.
*/
protected float size;
/** If positive, the text distance under the bars. If zero or negative,
* the text distance above the bars.
*/
protected float baseline;
/** The height of the bars.
*/
protected float barHeight;
/** The text alignment. Can be Element.ALIGN_LEFT
,
* Element.ALIGN_CENTER
or Element.ALIGN_RIGHT
.
*/
protected int textAlignment;
/** The optional checksum generation.
*/
protected boolean generateChecksum;
/** Shows the generated checksum in the the text.
*/
protected boolean checksumText;
/** Show the start and stop character '*' in the text for
* the barcode 39 or 'ABCD' for codabar.
*/
protected boolean startStopText;
/** Generates extended barcode 39.
*/
protected boolean extended;
/** The code to generate.
*/
protected String code = "";
/** Show the guard bars for barcode EAN.
*/
protected boolean guardBars;
/** The code type.
*/
protected int codeType;
/** The ink spreading. */
protected float inkSpreading = 0;
/** Gets the minimum bar width.
* @return the minimum bar width
*/
public float getX() {
return x;
}
/** Sets the minimum bar width.
* @param x the minimum bar width
*/
public void setX(float x) {
this.x = x;
}
/** Gets the bar multiplier for wide bars.
* @return the bar multiplier for wide bars
*/
public float getN() {
return n;
}
/** Sets the bar multiplier for wide bars.
* @param n the bar multiplier for wide bars
*/
public void setN(float n) {
this.n = n;
}
/** Gets the text font. null
if no text.
* @return the text font. null
if no text
*/
public BaseFont getFont() {
return font;
}
/** Sets the text font.
* @param font the text font. Set to null
to suppress any text
*/
public void setFont(BaseFont font) {
this.font = font;
}
/** Gets the size of the text.
* @return the size of the text
*/
public float getSize() {
return size;
}
/** Sets the size of the text.
* @param size the size of the text
*/
public void setSize(float size) {
this.size = size;
}
/** Gets the text baseline.
* If positive, the text distance under the bars. If zero or negative,
* the text distance above the bars.
* @return the baseline.
*/
public float getBaseline() {
return baseline;
}
/** Sets the text baseline.
* If positive, the text distance under the bars. If zero or negative,
* the text distance above the bars.
* @param baseline the baseline.
*/
public void setBaseline(float baseline) {
this.baseline = baseline;
}
/** Gets the height of the bars.
* @return the height of the bars
*/
public float getBarHeight() {
return barHeight;
}
/** Sets the height of the bars.
* @param barHeight the height of the bars
*/
public void setBarHeight(float barHeight) {
this.barHeight = barHeight;
}
/** Gets the text alignment. Can be Element.ALIGN_LEFT
,
* Element.ALIGN_CENTER
or Element.ALIGN_RIGHT
.
* @return the text alignment
*/
public int getTextAlignment() {
return textAlignment;
}
/** Sets the text alignment. Can be Element.ALIGN_LEFT
,
* Element.ALIGN_CENTER
or Element.ALIGN_RIGHT
.
* @param textAlignment the text alignment
*/
public void setTextAlignment(int textAlignment) {
this.textAlignment = textAlignment;
}
/** Gets the optional checksum generation.
* @return the optional checksum generation
*/
public boolean isGenerateChecksum() {
return generateChecksum;
}
/** Setter for property generateChecksum.
* @param generateChecksum New value of property generateChecksum.
*/
public void setGenerateChecksum(boolean generateChecksum) {
this.generateChecksum = generateChecksum;
}
/** Gets the property to show the generated checksum in the the text.
* @return value of property checksumText
*/
public boolean isChecksumText() {
return checksumText;
}
/** Sets the property to show the generated checksum in the the text.
* @param checksumText new value of property checksumText
*/
public void setChecksumText(boolean checksumText) {
this.checksumText = checksumText;
}
/** Sets the property to show the start and stop character '*' in the text for
* the barcode 39.
* @return value of property startStopText
*/
public boolean isStartStopText() {
return startStopText;
}
/** Gets the property to show the start and stop character '*' in the text for
* the barcode 39.
* @param startStopText new value of property startStopText
*/
public void setStartStopText(boolean startStopText) {
this.startStopText = startStopText;
}
/** Gets the property to generate extended barcode 39.
* @return value of property extended.
*/
public boolean isExtended() {
return extended;
}
/** Sets the property to generate extended barcode 39.
* @param extended new value of property extended
*/
public void setExtended(boolean extended) {
this.extended = extended;
}
/** Gets the code to generate.
* @return the code to generate
*/
public String getCode() {
return code;
}
/** Sets the code to generate.
* @param code the code to generate
*/
public void setCode(String code) {
this.code = code;
}
/** Gets the property to show the guard bars for barcode EAN.
* @return value of property guardBars
*/
public boolean isGuardBars() {
return guardBars;
}
/** Sets the property to show the guard bars for barcode EAN.
* @param guardBars new value of property guardBars
*/
public void setGuardBars(boolean guardBars) {
this.guardBars = guardBars;
}
/** Gets the code type.
* @return the code type
*/
public int getCodeType() {
return codeType;
}
/** Sets the code type.
* @param codeType the code type
*/
public void setCodeType(int codeType) {
this.codeType = codeType;
}
/** Gets the maximum area that the barcode and the text, if
* any, will occupy. The lower left corner is always (0, 0).
* @return the size the barcode occupies.
*/
public abstract Rectangle getBarcodeSize();
/** Places the barcode in a PdfContentByte
. The
* barcode is always placed at coordinates (0, 0). Use the
* translation matrix to move it elsewhere.
*
* @param cb the
*
*
* barColor
* textColor
*
*
*
* null
* null
*
*
*
* barColor
* null
* barColor
*
*
* null
* textColor
*
text painted with textColor
*
*
* barColor
* textColor
* barColor
text painted with textColor
PdfContentByte
where the barcode will be placed
* @param barColor the color of the bars. It can be null
* @param textColor the color of the text. It can be null
* @return the dimensions the barcode occupies
*/
public abstract Rectangle placeBarcode(PdfContentByte cb, Color barColor, Color textColor);
/** Creates a template with the barcode.
* @param cb the PdfContentByte
to create the template. It
* serves no other use
* @param barColor the color of the bars. It can be null
* @param textColor the color of the text. It can be null
* @return the template
* @see #placeBarcode(PdfContentByte cb, Color barColor, Color textColor)
*/
public PdfTemplate createTemplateWithBarcode(PdfContentByte cb, Color barColor, Color textColor) {
PdfTemplate tp = cb.createTemplate(0, 0);
Rectangle rect = placeBarcode(tp, barColor, textColor);
tp.setBoundingBox(rect);
return tp;
}
/** Creates an Image
with the barcode.
* @param cb the PdfContentByte
to create the Image
. It
* serves no other use
* @param barColor the color of the bars. It can be null
* @param textColor the color of the text. It can be null
* @return the Image
* @see #placeBarcode(PdfContentByte cb, Color barColor, Color textColor)
*/
public Image createImageWithBarcode(PdfContentByte cb, Color barColor, Color textColor) {
try {
return Image.getInstance(createTemplateWithBarcode(cb, barColor, textColor));
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
}
/** Creates a java.awt.Image
. This image only
* contains the bars without any text.
* @param foreground the color of the bars
* @param background the color of the background
* @return the image
*/
public abstract java.awt.Image createAwtImage(Color foreground, Color background);
/** Gets the amount of ink spreading.
* @return the ink spreading
*
*/
public float getInkSpreading() {
return this.inkSpreading;
}
/** Sets the amount of ink spreading. This value will be subtracted
* to the width of each bar. The actual value will depend on the ink
* and the printing medium.
* @param inkSpreading the ink spreading
*
*/
public void setInkSpreading(float inkSpreading) {
this.inkSpreading = inkSpreading;
}
/**
* The alternate text to be used, if present.
*/
protected String altText;
/**
* Gets the alternate text.
* @return the alternate text
*/
public String getAltText() {
return this.altText;
}
/**
* Sets the alternate text. If present, this text will be used instead of the
* text derived from the supplied code.
* @param altText the alternate text
*/
public void setAltText(String altText) {
this.altText = altText;
}
}
src/core/com/lowagie/text/pdf/Barcode128.java 100644 0 0 70310 11036112746 16345 0 ustar 0 0 /*
* $Id: Barcode128.java 3427 2008-05-24 18:32:31Z xlv $
*
* Copyright 2002-2006 by Paulo Soares.
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.pdf;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Image;
import java.awt.image.MemoryImageSource;
import com.lowagie.text.Element;
import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.Rectangle;
/**
* Implements the code 128 and UCC/EAN-128. Other symbologies are allowed in raw mode.
*
*
* The default parameters are:
*
* x = 0.8f;
* font = BaseFont.createFont("Helvetica", "winansi", false);
* size = 8;
* baseline = size;
* barHeight = size * 3;
* textAlignment = Element.ALIGN_CENTER;
* codeType = CODE128;
*
* @author Paulo Soares (psoares@consiste.pt)
*/
public class Barcode128 extends Barcode{
/** The bars to generate the code.
*/
private static final byte BARS[][] =
{
{2, 1, 2, 2, 2, 2},
{2, 2, 2, 1, 2, 2},
{2, 2, 2, 2, 2, 1},
{1, 2, 1, 2, 2, 3},
{1, 2, 1, 3, 2, 2},
{1, 3, 1, 2, 2, 2},
{1, 2, 2, 2, 1, 3},
{1, 2, 2, 3, 1, 2},
{1, 3, 2, 2, 1, 2},
{2, 2, 1, 2, 1, 3},
{2, 2, 1, 3, 1, 2},
{2, 3, 1, 2, 1, 2},
{1, 1, 2, 2, 3, 2},
{1, 2, 2, 1, 3, 2},
{1, 2, 2, 2, 3, 1},
{1, 1, 3, 2, 2, 2},
{1, 2, 3, 1, 2, 2},
{1, 2, 3, 2, 2, 1},
{2, 2, 3, 2, 1, 1},
{2, 2, 1, 1, 3, 2},
{2, 2, 1, 2, 3, 1},
{2, 1, 3, 2, 1, 2},
{2, 2, 3, 1, 1, 2},
{3, 1, 2, 1, 3, 1},
{3, 1, 1, 2, 2, 2},
{3, 2, 1, 1, 2, 2},
{3, 2, 1, 2, 2, 1},
{3, 1, 2, 2, 1, 2},
{3, 2, 2, 1, 1, 2},
{3, 2, 2, 2, 1, 1},
{2, 1, 2, 1, 2, 3},
{2, 1, 2, 3, 2, 1},
{2, 3, 2, 1, 2, 1},
{1, 1, 1, 3, 2, 3},
{1, 3, 1, 1, 2, 3},
{1, 3, 1, 3, 2, 1},
{1, 1, 2, 3, 1, 3},
{1, 3, 2, 1, 1, 3},
{1, 3, 2, 3, 1, 1},
{2, 1, 1, 3, 1, 3},
{2, 3, 1, 1, 1, 3},
{2, 3, 1, 3, 1, 1},
{1, 1, 2, 1, 3, 3},
{1, 1, 2, 3, 3, 1},
{1, 3, 2, 1, 3, 1},
{1, 1, 3, 1, 2, 3},
{1, 1, 3, 3, 2, 1},
{1, 3, 3, 1, 2, 1},
{3, 1, 3, 1, 2, 1},
{2, 1, 1, 3, 3, 1},
{2, 3, 1, 1, 3, 1},
{2, 1, 3, 1, 1, 3},
{2, 1, 3, 3, 1, 1},
{2, 1, 3, 1, 3, 1},
{3, 1, 1, 1, 2, 3},
{3, 1, 1, 3, 2, 1},
{3, 3, 1, 1, 2, 1},
{3, 1, 2, 1, 1, 3},
{3, 1, 2, 3, 1, 1},
{3, 3, 2, 1, 1, 1},
{3, 1, 4, 1, 1, 1},
{2, 2, 1, 4, 1, 1},
{4, 3, 1, 1, 1, 1},
{1, 1, 1, 2, 2, 4},
{1, 1, 1, 4, 2, 2},
{1, 2, 1, 1, 2, 4},
{1, 2, 1, 4, 2, 1},
{1, 4, 1, 1, 2, 2},
{1, 4, 1, 2, 2, 1},
{1, 1, 2, 2, 1, 4},
{1, 1, 2, 4, 1, 2},
{1, 2, 2, 1, 1, 4},
{1, 2, 2, 4, 1, 1},
{1, 4, 2, 1, 1, 2},
{1, 4, 2, 2, 1, 1},
{2, 4, 1, 2, 1, 1},
{2, 2, 1, 1, 1, 4},
{4, 1, 3, 1, 1, 1},
{2, 4, 1, 1, 1, 2},
{1, 3, 4, 1, 1, 1},
{1, 1, 1, 2, 4, 2},
{1, 2, 1, 1, 4, 2},
{1, 2, 1, 2, 4, 1},
{1, 1, 4, 2, 1, 2},
{1, 2, 4, 1, 1, 2},
{1, 2, 4, 2, 1, 1},
{4, 1, 1, 2, 1, 2},
{4, 2, 1, 1, 1, 2},
{4, 2, 1, 2, 1, 1},
{2, 1, 2, 1, 4, 1},
{2, 1, 4, 1, 2, 1},
{4, 1, 2, 1, 2, 1},
{1, 1, 1, 1, 4, 3},
{1, 1, 1, 3, 4, 1},
{1, 3, 1, 1, 4, 1},
{1, 1, 4, 1, 1, 3},
{1, 1, 4, 3, 1, 1},
{4, 1, 1, 1, 1, 3},
{4, 1, 1, 3, 1, 1},
{1, 1, 3, 1, 4, 1},
{1, 1, 4, 1, 3, 1},
{3, 1, 1, 1, 4, 1},
{4, 1, 1, 1, 3, 1},
{2, 1, 1, 4, 1, 2},
{2, 1, 1, 2, 1, 4},
{2, 1, 1, 2, 3, 2}
};
/** The stop bars.
*/
private static final byte BARS_STOP[] = {2, 3, 3, 1, 1, 1, 2};
/** The charset code change.
*/
public static final char CODE_AB_TO_C = 99;
/** The charset code change.
*/
public static final char CODE_AC_TO_B = 100;
/** The charset code change.
*/
public static final char CODE_BC_TO_A = 101;
/** The code for UCC/EAN-128.
*/
public static final char FNC1_INDEX = 102;
/** The start code.
*/
public static final char START_A = 103;
/** The start code.
*/
public static final char START_B = 104;
/** The start code.
*/
public static final char START_C = 105;
public static final char FNC1 = '\u00ca';
public static final char DEL = '\u00c3';
public static final char FNC3 = '\u00c4';
public static final char FNC2 = '\u00c5';
public static final char SHIFT = '\u00c6';
public static final char CODE_C = '\u00c7';
public static final char CODE_A = '\u00c8';
public static final char FNC4 = '\u00c8';
public static final char STARTA = '\u00cb';
public static final char STARTB = '\u00cc';
public static final char STARTC = '\u00cd';
private static final IntHashtable ais = new IntHashtable();
/** Creates new Barcode128 */
public Barcode128() {
try {
x = 0.8f;
font = BaseFont.createFont("Helvetica", "winansi", false);
size = 8;
baseline = size;
barHeight = size * 3;
textAlignment = Element.ALIGN_CENTER;
codeType = CODE128;
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
}
/**
* Removes the FNC1 codes in the text.
* @param code the text to clean
* @return the cleaned text
*/
public static String removeFNC1(String code) {
int len = code.length();
StringBuffer buf = new StringBuffer(len);
for (int k = 0; k < len; ++k) {
char c = code.charAt(k);
if (c >= 32 && c <= 126)
buf.append(c);
}
return buf.toString();
}
/**
* Gets the human readable text of a sequence of AI.
* @param code the text
* @return the human readable text
*/
public static String getHumanReadableUCCEAN(String code) {
StringBuffer buf = new StringBuffer();
String fnc1 = String.valueOf(FNC1);
try {
while (true) {
if (code.startsWith(fnc1)) {
code = code.substring(1);
continue;
}
int n = 0;
int idlen = 0;
for (int k = 2; k < 5; ++k) {
if (code.length() < k)
break;
if ((n = ais.get(Integer.parseInt(code.substring(0, k)))) != 0) {
idlen = k;
break;
}
}
if (idlen == 0)
break;
buf.append('(').append(code.substring(0, idlen)).append(')');
code = code.substring(idlen);
if (n > 0) {
n -= idlen;
if (code.length() <= n)
break;
buf.append(removeFNC1(code.substring(0, n)));
code = code.substring(n);
}
else {
int idx = code.indexOf(FNC1);
if (idx < 0)
break;
buf.append(code.substring(0,idx));
code = code.substring(idx + 1);
}
}
}
catch (Exception e) {
//empty
}
buf.append(removeFNC1(code));
return buf.toString();
}
/** Returns true
if the next numDigits
* starting from index textIndex
are numeric skipping any FNC1.
* @param text the text to check
* @param textIndex where to check from
* @param numDigits the number of digits to check
* @return the check result
*/
static boolean isNextDigits(String text, int textIndex, int numDigits) {
int len = text.length();
while (textIndex < len && numDigits > 0) {
if (text.charAt(textIndex) == FNC1) {
++textIndex;
continue;
}
int n = Math.min(2, numDigits);
if (textIndex + n > len)
return false;
while (n-- > 0) {
char c = text.charAt(textIndex++);
if (c < '0' || c > '9')
return false;
--numDigits;
}
}
return numDigits == 0;
}
/** Packs the digits for charset C also considering FNC1. It assumes that all the parameters
* are valid.
* @param text the text to pack
* @param textIndex where to pack from
* @param numDigits the number of digits to pack. It is always an even number
* @return the packed digits, two digits per character
*/
static String getPackedRawDigits(String text, int textIndex, int numDigits) {
String out = "";
int start = textIndex;
while (numDigits > 0) {
if (text.charAt(textIndex) == FNC1) {
out += FNC1_INDEX;
++textIndex;
continue;
}
numDigits -= 2;
int c1 = text.charAt(textIndex++) - '0';
int c2 = text.charAt(textIndex++) - '0';
out += (char)(c1 * 10 + c2);
}
return (char)(textIndex - start) + out;
}
/** Converts the human readable text to the characters needed to
* create a barcode. Some optimization is done to get the shortest code.
* @param text the text to convert
* @param ucc true
if it is an UCC/EAN-128. In this case
* the character FNC1 is added
* @return the code ready to be fed to getBarsCode128Raw()
*/
public static String getRawText(String text, boolean ucc) {
String out = "";
int tLen = text.length();
if (tLen == 0) {
out += START_B;
if (ucc)
out += FNC1_INDEX;
return out;
}
int c = 0;
for (int k = 0; k < tLen; ++k) {
c = text.charAt(k);
if (c > 127 && c != FNC1)
throw new RuntimeException("There are illegal characters for barcode 128 in '" + text + "'.");
}
c = text.charAt(0);
char currentCode = START_B;
int index = 0;
if (isNextDigits(text, index, 2)) {
currentCode = START_C;
out += currentCode;
if (ucc)
out += FNC1_INDEX;
String out2 = getPackedRawDigits(text, index, 2);
index += out2.charAt(0);
out += out2.substring(1);
}
else if (c < ' ') {
currentCode = START_A;
out += currentCode;
if (ucc)
out += FNC1_INDEX;
out += (char)(c + 64);
++index;
}
else {
out += currentCode;
if (ucc)
out += FNC1_INDEX;
if (c == FNC1)
out += FNC1_INDEX;
else
out += (char)(c - ' ');
++index;
}
while (index < tLen) {
switch (currentCode) {
case START_A:
{
if (isNextDigits(text, index, 4)) {
currentCode = START_C;
out += CODE_AB_TO_C;
String out2 = getPackedRawDigits(text, index, 4);
index += out2.charAt(0);
out += out2.substring(1);
}
else {
c = text.charAt(index++);
if (c == FNC1)
out += FNC1_INDEX;
else if (c > '_') {
currentCode = START_B;
out += CODE_AC_TO_B;
out += (char)(c - ' ');
}
else if (c < ' ')
out += (char)(c + 64);
else
out += (char)(c - ' ');
}
}
break;
case START_B:
{
if (isNextDigits(text, index, 4)) {
currentCode = START_C;
out += CODE_AB_TO_C;
String out2 = getPackedRawDigits(text, index, 4);
index += out2.charAt(0);
out += out2.substring(1);
}
else {
c = text.charAt(index++);
if (c == FNC1)
out += FNC1_INDEX;
else if (c < ' ') {
currentCode = START_A;
out += CODE_BC_TO_A;
out += (char)(c + 64);
}
else {
out += (char)(c - ' ');
}
}
}
break;
case START_C:
{
if (isNextDigits(text, index, 2)) {
String out2 = getPackedRawDigits(text, index, 2);
index += out2.charAt(0);
out += out2.substring(1);
}
else {
c = text.charAt(index++);
if (c == FNC1)
out += FNC1_INDEX;
else if (c < ' ') {
currentCode = START_A;
out += CODE_BC_TO_A;
out += (char)(c + 64);
}
else {
currentCode = START_B;
out += CODE_AC_TO_B;
out += (char)(c - ' ');
}
}
}
break;
}
}
return out;
}
/** Generates the bars. The input has the actual barcodes, not
* the human readable text.
* @param text the barcode
* @return the bars
*/
public static byte[] getBarsCode128Raw(String text) {
int idx = text.indexOf('\uffff');
if (idx >= 0)
text = text.substring(0, idx);
int chk = text.charAt(0);
for (int k = 1; k < text.length(); ++k)
chk += k * text.charAt(k);
chk = chk % 103;
text += (char)chk;
byte bars[] = new byte[(text.length() + 1) * 6 + 7];
int k;
for (k = 0; k < text.length(); ++k)
System.arraycopy(BARS[text.charAt(k)], 0, bars, k * 6, 6);
System.arraycopy(BARS_STOP, 0, bars, k * 6, 7);
return bars;
}
/** Gets the maximum area that the barcode and the text, if
* any, will occupy. The lower left corner is always (0, 0).
* @return the size the barcode occupies.
*/
public Rectangle getBarcodeSize() {
float fontX = 0;
float fontY = 0;
String fullCode;
if (font != null) {
if (baseline > 0)
fontY = baseline - font.getFontDescriptor(BaseFont.DESCENT, size);
else
fontY = -baseline + size;
if (codeType == CODE128_RAW) {
int idx = code.indexOf('\uffff');
if (idx < 0)
fullCode = "";
else
fullCode = code.substring(idx + 1);
}
else if (codeType == CODE128_UCC)
fullCode = getHumanReadableUCCEAN(code);
else
fullCode = removeFNC1(code);
fontX = font.getWidthPoint(altText != null ? altText : fullCode, size);
}
if (codeType == CODE128_RAW) {
int idx = code.indexOf('\uffff');
if (idx >= 0)
fullCode = code.substring(0, idx);
else
fullCode = code;
}
else {
fullCode = getRawText(code, codeType == CODE128_UCC);
}
int len = fullCode.length();
float fullWidth = (len + 2) * 11 * x + 2 * x;
fullWidth = Math.max(fullWidth, fontX);
float fullHeight = barHeight + fontY;
return new Rectangle(fullWidth, fullHeight);
}
/** Places the barcode in a PdfContentByte
. The
* barcode is always placed at coordinates (0, 0). Use the
* translation matrix to move it elsewhere.
*
* @param cb the
*
*
* barColor
* textColor
*
*
*
* null
* null
*
*
*
* barColor
* null
* barColor
*
*
* null
* textColor
*
text painted with textColor
*
*
* barColor
* textColor
* barColor
text painted with textColor
PdfContentByte
where the barcode will be placed
* @param barColor the color of the bars. It can be null
* @param textColor the color of the text. It can be null
* @return the dimensions the barcode occupies
*/
public Rectangle placeBarcode(PdfContentByte cb, Color barColor, Color textColor) {
String fullCode;
if (codeType == CODE128_RAW) {
int idx = code.indexOf('\uffff');
if (idx < 0)
fullCode = "";
else
fullCode = code.substring(idx + 1);
}
else if (codeType == CODE128_UCC)
fullCode = getHumanReadableUCCEAN(code);
else
fullCode = removeFNC1(code);
float fontX = 0;
if (font != null) {
fontX = font.getWidthPoint(fullCode = altText != null ? altText : fullCode, size);
}
String bCode;
if (codeType == CODE128_RAW) {
int idx = code.indexOf('\uffff');
if (idx >= 0)
bCode = code.substring(0, idx);
else
bCode = code;
}
else {
bCode = getRawText(code, codeType == CODE128_UCC);
}
int len = bCode.length();
float fullWidth = (len + 2) * 11 * x + 2 * x;
float barStartX = 0;
float textStartX = 0;
switch (textAlignment) {
case Element.ALIGN_LEFT:
break;
case Element.ALIGN_RIGHT:
if (fontX > fullWidth)
barStartX = fontX - fullWidth;
else
textStartX = fullWidth - fontX;
break;
default:
if (fontX > fullWidth)
barStartX = (fontX - fullWidth) / 2;
else
textStartX = (fullWidth - fontX) / 2;
break;
}
float barStartY = 0;
float textStartY = 0;
if (font != null) {
if (baseline <= 0)
textStartY = barHeight - baseline;
else {
textStartY = -font.getFontDescriptor(BaseFont.DESCENT, size);
barStartY = textStartY + baseline;
}
}
byte bars[] = getBarsCode128Raw(bCode);
boolean print = true;
if (barColor != null)
cb.setColorFill(barColor);
for (int k = 0; k < bars.length; ++k) {
float w = bars[k] * x;
if (print)
cb.rectangle(barStartX, barStartY, w - inkSpreading, barHeight);
print = !print;
barStartX += w;
}
cb.fill();
if (font != null) {
if (textColor != null)
cb.setColorFill(textColor);
cb.beginText();
cb.setFontAndSize(font, size);
cb.setTextMatrix(textStartX, textStartY);
cb.showText(fullCode);
cb.endText();
}
return getBarcodeSize();
}
/** Creates a java.awt.Image
. This image only
* contains the bars without any text.
* @param foreground the color of the bars
* @param background the color of the background
* @return the image
*/
public java.awt.Image createAwtImage(Color foreground, Color background) {
int f = foreground.getRGB();
int g = background.getRGB();
Canvas canvas = new Canvas();
String bCode;
if (codeType == CODE128_RAW) {
int idx = code.indexOf('\uffff');
if (idx >= 0)
bCode = code.substring(0, idx);
else
bCode = code;
}
else {
bCode = getRawText(code, codeType == CODE128_UCC);
}
int len = bCode.length();
int fullWidth = (len + 2) * 11 + 2;
byte bars[] = getBarsCode128Raw(bCode);
boolean print = true;
int ptr = 0;
int height = (int)barHeight;
int pix[] = new int[fullWidth * height];
for (int k = 0; k < bars.length; ++k) {
int w = bars[k];
int c = g;
if (print)
c = f;
print = !print;
for (int j = 0; j < w; ++j)
pix[ptr++] = c;
}
for (int k = fullWidth; k < pix.length; k += fullWidth) {
System.arraycopy(pix, 0, pix, k, fullWidth);
}
Image img = canvas.createImage(new MemoryImageSource(fullWidth, height, pix, 0, fullWidth));
return img;
}
/**
* Sets the code to generate. If it's an UCC code and starts with '(' it will
* be split by the AI. This code in UCC mode is valid:
* (01)00000090311314(10)ABC123(15)060916
* @param code the code to generate
*/
public void setCode(String code) {
if (getCodeType() == Barcode128.CODE128_UCC && code.startsWith("(")) {
int idx = 0;
String ret = "";
while (idx >= 0) {
int end = code.indexOf(')', idx);
if (end < 0)
throw new IllegalArgumentException("Badly formed UCC string: " + code);
String sai = code.substring(idx + 1, end);
if (sai.length() < 2)
throw new IllegalArgumentException("AI too short: (" + sai + ")");
int ai = Integer.parseInt(sai);
int len = ais.get(ai);
if (len == 0)
throw new IllegalArgumentException("AI not found: (" + sai + ")");
sai = String.valueOf(ai);
if (sai.length() == 1)
sai = "0" + sai;
idx = code.indexOf('(', end);
int next = (idx < 0 ? code.length() : idx);
ret += sai + code.substring(end + 1, next);
if (len < 0) {
if (idx >= 0)
ret += FNC1;
}
else if (next - end - 1 + sai.length() != len)
throw new IllegalArgumentException("Invalid AI length: (" + sai + ")");
}
super.setCode(ret);
}
else
super.setCode(code);
}
static {
ais.put(0, 20);
ais.put(1, 16);
ais.put(2, 16);
ais.put(10, -1);
ais.put(11, 9);
ais.put(12, 8);
ais.put(13, 8);
ais.put(15, 8);
ais.put(17, 8);
ais.put(20, 4);
ais.put(21, -1);
ais.put(22, -1);
ais.put(23, -1);
ais.put(240, -1);
ais.put(241, -1);
ais.put(250, -1);
ais.put(251, -1);
ais.put(252, -1);
ais.put(30, -1);
for (int k = 3100; k < 3700; ++k)
ais.put(k, 10);
ais.put(37, -1);
for (int k = 3900; k < 3940; ++k)
ais.put(k, -1);
ais.put(400, -1);
ais.put(401, -1);
ais.put(402, 20);
ais.put(403, -1);
for (int k = 410; k < 416; ++k)
ais.put(k, 16);
ais.put(420, -1);
ais.put(421, -1);
ais.put(422, 6);
ais.put(423, -1);
ais.put(424, 6);
ais.put(425, 6);
ais.put(426, 6);
ais.put(7001, 17);
ais.put(7002, -1);
for (int k = 7030; k < 7040; ++k)
ais.put(k, -1);
ais.put(8001, 18);
ais.put(8002, -1);
ais.put(8003, -1);
ais.put(8004, -1);
ais.put(8005, 10);
ais.put(8006, 22);
ais.put(8007, -1);
ais.put(8008, -1);
ais.put(8018, 22);
ais.put(8020, -1);
ais.put(8100, 10);
ais.put(8101, 14);
ais.put(8102, 6);
for (int k = 90; k < 100; ++k)
ais.put(k, -1);
}
}
src/core/com/lowagie/text/pdf/Barcode39.java 100644 0 0 33664 11000354131 16264 0 ustar 0 0 /*
* $Id: Barcode39.java 3117 2008-01-31 05:53:22Z xlv $
*
* Copyright 2002-2006 by Paulo Soares.
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.pdf;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Image;
import java.awt.image.MemoryImageSource;
import com.lowagie.text.Element;
import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.Rectangle;
/** Implements the code 39 and code 39 extended. The default parameters are:
*
*x = 0.8f;
*n = 2;
*font = BaseFont.createFont("Helvetica", "winansi", false);
*size = 8;
*baseline = size;
*barHeight = size * 3;
*textAlignment = Element.ALIGN_CENTER;
*generateChecksum = false;
*checksumText = false;
*startStopText = true;
*extended = false;
*
*
* @author Paulo Soares (psoares@consiste.pt)
*/
public class Barcode39 extends Barcode{
/** The bars to generate the code.
*/
private static final byte BARS[][] =
{
{0,0,0,1,1,0,1,0,0},
{1,0,0,1,0,0,0,0,1},
{0,0,1,1,0,0,0,0,1},
{1,0,1,1,0,0,0,0,0},
{0,0,0,1,1,0,0,0,1},
{1,0,0,1,1,0,0,0,0},
{0,0,1,1,1,0,0,0,0},
{0,0,0,1,0,0,1,0,1},
{1,0,0,1,0,0,1,0,0},
{0,0,1,1,0,0,1,0,0},
{1,0,0,0,0,1,0,0,1},
{0,0,1,0,0,1,0,0,1},
{1,0,1,0,0,1,0,0,0},
{0,0,0,0,1,1,0,0,1},
{1,0,0,0,1,1,0,0,0},
{0,0,1,0,1,1,0,0,0},
{0,0,0,0,0,1,1,0,1},
{1,0,0,0,0,1,1,0,0},
{0,0,1,0,0,1,1,0,0},
{0,0,0,0,1,1,1,0,0},
{1,0,0,0,0,0,0,1,1},
{0,0,1,0,0,0,0,1,1},
{1,0,1,0,0,0,0,1,0},
{0,0,0,0,1,0,0,1,1},
{1,0,0,0,1,0,0,1,0},
{0,0,1,0,1,0,0,1,0},
{0,0,0,0,0,0,1,1,1},
{1,0,0,0,0,0,1,1,0},
{0,0,1,0,0,0,1,1,0},
{0,0,0,0,1,0,1,1,0},
{1,1,0,0,0,0,0,0,1},
{0,1,1,0,0,0,0,0,1},
{1,1,1,0,0,0,0,0,0},
{0,1,0,0,1,0,0,0,1},
{1,1,0,0,1,0,0,0,0},
{0,1,1,0,1,0,0,0,0},
{0,1,0,0,0,0,1,0,1},
{1,1,0,0,0,0,1,0,0},
{0,1,1,0,0,0,1,0,0},
{0,1,0,1,0,1,0,0,0},
{0,1,0,1,0,0,0,1,0},
{0,1,0,0,0,1,0,1,0},
{0,0,0,1,0,1,0,1,0},
{0,1,0,0,1,0,1,0,0}
};
/** The index chars to BARS
.
*/
private static final String CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%*";
/** The character combinations to make the code 39 extended.
*/
private static final String EXTENDED = "%U" +
"$A$B$C$D$E$F$G$H$I$J$K$L$M$N$O$P$Q$R$S$T$U$V$W$X$Y$Z" +
"%A%B%C%D%E /A/B/C/D/E/F/G/H/I/J/K/L - ./O" +
" 0 1 2 3 4 5 6 7 8 9/Z%F%G%H%I%J%V" +
" A B C D E F G H I J K L M N O P Q R S T U V W X Y Z" +
"%K%L%M%N%O%W" +
"+A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z" +
"%P%Q%R%S%T";
/** Creates a new Barcode39.
*/
public Barcode39() {
try {
x = 0.8f;
n = 2;
font = BaseFont.createFont("Helvetica", "winansi", false);
size = 8;
baseline = size;
barHeight = size * 3;
textAlignment = Element.ALIGN_CENTER;
generateChecksum = false;
checksumText = false;
startStopText = true;
extended = false;
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
}
/** Creates the bars.
* @param text the text to create the bars. This text does not include the start and
* stop characters
* @return the bars
*/
public static byte[] getBarsCode39(String text) {
text = "*" + text + "*";
byte bars[] = new byte[text.length() * 10 - 1];
for (int k = 0; k < text.length(); ++k) {
int idx = CHARS.indexOf(text.charAt(k));
if (idx < 0)
throw new IllegalArgumentException("The character '" + text.charAt(k) + "' is illegal in code 39.");
System.arraycopy(BARS[idx], 0, bars, k * 10, 9);
}
return bars;
}
/** Converts the extended text into a normal, escaped text,
* ready to generate bars.
* @param text the extended text
* @return the escaped text
*/
public static String getCode39Ex(String text) {
String out = "";
for (int k = 0; k < text.length(); ++k) {
char c = text.charAt(k);
if (c > 127)
throw new IllegalArgumentException("The character '" + c + "' is illegal in code 39 extended.");
char c1 = EXTENDED.charAt(c * 2);
char c2 = EXTENDED.charAt(c * 2 + 1);
if (c1 != ' ')
out += c1;
out += c2;
}
return out;
}
/** Calculates the checksum.
* @param text the text
* @return the checksum
*/
static char getChecksum(String text) {
int chk = 0;
for (int k = 0; k < text.length(); ++k) {
int idx = CHARS.indexOf(text.charAt(k));
if (idx < 0)
throw new IllegalArgumentException("The character '" + text.charAt(k) + "' is illegal in code 39.");
chk += idx;
}
return CHARS.charAt(chk % 43);
}
/** Gets the maximum area that the barcode and the text, if
* any, will occupy. The lower left corner is always (0, 0).
* @return the size the barcode occupies.
*/
public Rectangle getBarcodeSize() {
float fontX = 0;
float fontY = 0;
String fCode = code;
if (extended)
fCode = getCode39Ex(code);
if (font != null) {
if (baseline > 0)
fontY = baseline - font.getFontDescriptor(BaseFont.DESCENT, size);
else
fontY = -baseline + size;
String fullCode = code;
if (generateChecksum && checksumText)
fullCode += getChecksum(fCode);
if (startStopText)
fullCode = "*" + fullCode + "*";
fontX = font.getWidthPoint(altText != null ? altText : fullCode, size);
}
int len = fCode.length() + 2;
if (generateChecksum)
++len;
float fullWidth = len * (6 * x + 3 * x * n) + (len - 1) * x;
fullWidth = Math.max(fullWidth, fontX);
float fullHeight = barHeight + fontY;
return new Rectangle(fullWidth, fullHeight);
}
/** Places the barcode in a PdfContentByte
. The
* barcode is always placed at coordinates (0, 0). Use the
* translation matrix to move it elsewhere.
*
* @param cb the
*
*
* barColor
* textColor
*
*
*
* null
* null
*
*
*
* barColor
* null
* barColor
*
*
* null
* textColor
*
text painted with textColor
*
*
* barColor
* textColor
* barColor
text painted with textColor
PdfContentByte
where the barcode will be placed
* @param barColor the color of the bars. It can be null
* @param textColor the color of the text. It can be null
* @return the dimensions the barcode occupies
*/
public Rectangle placeBarcode(PdfContentByte cb, Color barColor, Color textColor) {
String fullCode = code;
float fontX = 0;
String bCode = code;
if (extended)
bCode = getCode39Ex(code);
if (font != null) {
if (generateChecksum && checksumText)
fullCode += getChecksum(bCode);
if (startStopText)
fullCode = "*" + fullCode + "*";
fontX = font.getWidthPoint(fullCode = altText != null ? altText : fullCode, size);
}
if (generateChecksum)
bCode += getChecksum(bCode);
int len = bCode.length() + 2;
float fullWidth = len * (6 * x + 3 * x * n) + (len - 1) * x;
float barStartX = 0;
float textStartX = 0;
switch (textAlignment) {
case Element.ALIGN_LEFT:
break;
case Element.ALIGN_RIGHT:
if (fontX > fullWidth)
barStartX = fontX - fullWidth;
else
textStartX = fullWidth - fontX;
break;
default:
if (fontX > fullWidth)
barStartX = (fontX - fullWidth) / 2;
else
textStartX = (fullWidth - fontX) / 2;
break;
}
float barStartY = 0;
float textStartY = 0;
if (font != null) {
if (baseline <= 0)
textStartY = barHeight - baseline;
else {
textStartY = -font.getFontDescriptor(BaseFont.DESCENT, size);
barStartY = textStartY + baseline;
}
}
byte bars[] = getBarsCode39(bCode);
boolean print = true;
if (barColor != null)
cb.setColorFill(barColor);
for (int k = 0; k < bars.length; ++k) {
float w = (bars[k] == 0 ? x : x * n);
if (print)
cb.rectangle(barStartX, barStartY, w - inkSpreading, barHeight);
print = !print;
barStartX += w;
}
cb.fill();
if (font != null) {
if (textColor != null)
cb.setColorFill(textColor);
cb.beginText();
cb.setFontAndSize(font, size);
cb.setTextMatrix(textStartX, textStartY);
cb.showText(fullCode);
cb.endText();
}
return getBarcodeSize();
}
/** Creates a java.awt.Image
. This image only
* contains the bars without any text.
* @param foreground the color of the bars
* @param background the color of the background
* @return the image
*/
public java.awt.Image createAwtImage(Color foreground, Color background) {
int f = foreground.getRGB();
int g = background.getRGB();
Canvas canvas = new Canvas();
String bCode = code;
if (extended)
bCode = getCode39Ex(code);
if (generateChecksum)
bCode += getChecksum(bCode);
int len = bCode.length() + 2;
int nn = (int)n;
int fullWidth = len * (6 + 3 * nn) + (len - 1);
byte bars[] = getBarsCode39(bCode);
boolean print = true;
int ptr = 0;
int height = (int)barHeight;
int pix[] = new int[fullWidth * height];
for (int k = 0; k < bars.length; ++k) {
int w = (bars[k] == 0 ? 1 : nn);
int c = g;
if (print)
c = f;
print = !print;
for (int j = 0; j < w; ++j)
pix[ptr++] = c;
}
for (int k = fullWidth; k < pix.length; k += fullWidth) {
System.arraycopy(pix, 0, pix, k, fullWidth);
}
Image img = canvas.createImage(new MemoryImageSource(fullWidth, height, pix, 0, fullWidth));
return img;
}
}
src/core/com/lowagie/text/pdf/BarcodeCodabar.java 100644 0 0 31477 11036112746 17401 0 ustar 0 0 /*
* $Id: BarcodeCodabar.java 3427 2008-05-24 18:32:31Z xlv $
*
* Copyright 2002-2006 by Paulo Soares.
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.pdf;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Image;
import java.awt.image.MemoryImageSource;
import com.lowagie.text.Element;
import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.Rectangle;
/** Implements the code codabar. The default parameters are:
*
*x = 0.8f;
*n = 2;
*font = BaseFont.createFont("Helvetica", "winansi", false);
*size = 8;
*baseline = size;
*barHeight = size * 3;
*textAlignment = Element.ALIGN_CENTER;
*generateChecksum = false;
*checksumText = false;
*startStopText = false;
*
*
* @author Paulo Soares (psoares@consiste.pt)
*/
public class BarcodeCodabar extends Barcode{
/** The bars to generate the code.
*/
private static final byte BARS[][] =
{
{0,0,0,0,0,1,1}, // 0
{0,0,0,0,1,1,0}, // 1
{0,0,0,1,0,0,1}, // 2
{1,1,0,0,0,0,0}, // 3
{0,0,1,0,0,1,0}, // 4
{1,0,0,0,0,1,0}, // 5
{0,1,0,0,0,0,1}, // 6
{0,1,0,0,1,0,0}, // 7
{0,1,1,0,0,0,0}, // 8
{1,0,0,1,0,0,0}, // 9
{0,0,0,1,1,0,0}, // -
{0,0,1,1,0,0,0}, // $
{1,0,0,0,1,0,1}, // :
{1,0,1,0,0,0,1}, // /
{1,0,1,0,1,0,0}, // .
{0,0,1,0,1,0,1}, // +
{0,0,1,1,0,1,0}, // a
{0,1,0,1,0,0,1}, // b
{0,0,0,1,0,1,1}, // c
{0,0,0,1,1,1,0} // d
};
/** The index chars to BARS
.
*/
private static final String CHARS = "0123456789-$:/.+ABCD";
private static final int START_STOP_IDX = 16;
/** Creates a new BarcodeCodabar.
*/
public BarcodeCodabar() {
try {
x = 0.8f;
n = 2;
font = BaseFont.createFont("Helvetica", "winansi", false);
size = 8;
baseline = size;
barHeight = size * 3;
textAlignment = Element.ALIGN_CENTER;
generateChecksum = false;
checksumText = false;
startStopText = false;
codeType = CODABAR;
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
}
/** Creates the bars.
* @param text the text to create the bars
* @return the bars
*/
public static byte[] getBarsCodabar(String text) {
text = text.toUpperCase();
int len = text.length();
if (len < 2)
throw new IllegalArgumentException("Codabar must have at least a start and stop character.");
if (CHARS.indexOf(text.charAt(0)) < START_STOP_IDX || CHARS.indexOf(text.charAt(len - 1)) < START_STOP_IDX)
throw new IllegalArgumentException("Codabar must have one of 'ABCD' as start/stop character.");
byte bars[] = new byte[text.length() * 8 - 1];
for (int k = 0; k < len; ++k) {
int idx = CHARS.indexOf(text.charAt(k));
if (idx >= START_STOP_IDX && k > 0 && k < len - 1)
throw new IllegalArgumentException("In codabar, start/stop characters are only allowed at the extremes.");
if (idx < 0)
throw new IllegalArgumentException("The character '" + text.charAt(k) + "' is illegal in codabar.");
System.arraycopy(BARS[idx], 0, bars, k * 8, 7);
}
return bars;
}
public static String calculateChecksum(String code) {
if (code.length() < 2)
return code;
String text = code.toUpperCase();
int sum = 0;
int len = text.length();
for (int k = 0; k < len; ++k)
sum += CHARS.indexOf(text.charAt(k));
sum = (sum + 15) / 16 * 16 - sum;
return code.substring(0, len - 1) + CHARS.charAt(sum) + code.substring(len - 1);
}
/** Gets the maximum area that the barcode and the text, if
* any, will occupy. The lower left corner is always (0, 0).
* @return the size the barcode occupies.
*/
public Rectangle getBarcodeSize() {
float fontX = 0;
float fontY = 0;
String text = code;
if (generateChecksum && checksumText)
text = calculateChecksum(code);
if (!startStopText)
text = text.substring(1, text.length() - 1);
if (font != null) {
if (baseline > 0)
fontY = baseline - font.getFontDescriptor(BaseFont.DESCENT, size);
else
fontY = -baseline + size;
fontX = font.getWidthPoint(altText != null ? altText : text, size);
}
text = code;
if (generateChecksum)
text = calculateChecksum(code);
byte bars[] = getBarsCodabar(text);
int wide = 0;
for (int k = 0; k < bars.length; ++k) {
wide += bars[k];
}
int narrow = bars.length - wide;
float fullWidth = x * (narrow + wide * n);
fullWidth = Math.max(fullWidth, fontX);
float fullHeight = barHeight + fontY;
return new Rectangle(fullWidth, fullHeight);
}
/** Places the barcode in a PdfContentByte
. The
* barcode is always placed at coordinates (0, 0). Use the
* translation matrix to move it elsewhere.
*
* @param cb the
*
*
* barColor
* textColor
*
*
*
* null
* null
*
*
*
* barColor
* null
* barColor
*
*
* null
* textColor
*
text painted with textColor
*
*
* barColor
* textColor
* barColor
text painted with textColor
PdfContentByte
where the barcode will be placed
* @param barColor the color of the bars. It can be null
* @param textColor the color of the text. It can be null
* @return the dimensions the barcode occupies
*/
public Rectangle placeBarcode(PdfContentByte cb, Color barColor, Color textColor) {
String fullCode = code;
if (generateChecksum && checksumText)
fullCode = calculateChecksum(code);
if (!startStopText)
fullCode = fullCode.substring(1, fullCode.length() - 1);
float fontX = 0;
if (font != null) {
fontX = font.getWidthPoint(fullCode = altText != null ? altText : fullCode, size);
}
byte bars[] = getBarsCodabar(generateChecksum ? calculateChecksum(code) : code);
int wide = 0;
for (int k = 0; k < bars.length; ++k) {
wide += bars[k];
}
int narrow = bars.length - wide;
float fullWidth = x * (narrow + wide * n);
float barStartX = 0;
float textStartX = 0;
switch (textAlignment) {
case Element.ALIGN_LEFT:
break;
case Element.ALIGN_RIGHT:
if (fontX > fullWidth)
barStartX = fontX - fullWidth;
else
textStartX = fullWidth - fontX;
break;
default:
if (fontX > fullWidth)
barStartX = (fontX - fullWidth) / 2;
else
textStartX = (fullWidth - fontX) / 2;
break;
}
float barStartY = 0;
float textStartY = 0;
if (font != null) {
if (baseline <= 0)
textStartY = barHeight - baseline;
else {
textStartY = -font.getFontDescriptor(BaseFont.DESCENT, size);
barStartY = textStartY + baseline;
}
}
boolean print = true;
if (barColor != null)
cb.setColorFill(barColor);
for (int k = 0; k < bars.length; ++k) {
float w = (bars[k] == 0 ? x : x * n);
if (print)
cb.rectangle(barStartX, barStartY, w - inkSpreading, barHeight);
print = !print;
barStartX += w;
}
cb.fill();
if (font != null) {
if (textColor != null)
cb.setColorFill(textColor);
cb.beginText();
cb.setFontAndSize(font, size);
cb.setTextMatrix(textStartX, textStartY);
cb.showText(fullCode);
cb.endText();
}
return getBarcodeSize();
}
/** Creates a java.awt.Image
. This image only
* contains the bars without any text.
* @param foreground the color of the bars
* @param background the color of the background
* @return the image
*/
public java.awt.Image createAwtImage(Color foreground, Color background) {
int f = foreground.getRGB();
int g = background.getRGB();
Canvas canvas = new Canvas();
String fullCode = code;
if (generateChecksum && checksumText)
fullCode = calculateChecksum(code);
if (!startStopText)
fullCode = fullCode.substring(1, fullCode.length() - 1);
byte bars[] = getBarsCodabar(generateChecksum ? calculateChecksum(code) : code);
int wide = 0;
for (int k = 0; k < bars.length; ++k) {
wide += bars[k];
}
int narrow = bars.length - wide;
int fullWidth = narrow + wide * (int)n;
boolean print = true;
int ptr = 0;
int height = (int)barHeight;
int pix[] = new int[fullWidth * height];
for (int k = 0; k < bars.length; ++k) {
int w = (bars[k] == 0 ? 1 : (int)n);
int c = g;
if (print)
c = f;
print = !print;
for (int j = 0; j < w; ++j)
pix[ptr++] = c;
}
for (int k = fullWidth; k < pix.length; k += fullWidth) {
System.arraycopy(pix, 0, pix, k, fullWidth);
}
Image img = canvas.createImage(new MemoryImageSource(fullWidth, height, pix, 0, fullWidth));
return img;
}
}
src/core/com/lowagie/text/pdf/BarcodeDatamatrix.java 100644 0 0 137551 11000354131 20147 0 ustar 0 0 /*
* $Id: BarcodeDatamatrix.java 3117 2008-01-31 05:53:22Z xlv $
*
* Copyright 2007 by Paulo Soares.
*
* 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, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 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.pdf;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.codec.CCITTG4Encoder;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.image.MemoryImageSource;
import java.util.Arrays;
import java.io.UnsupportedEncodingException;
import java.util.Hashtable;
/**
* A DataMatrix 2D barcode generator.
*/
public class BarcodeDatamatrix {
/**
* No error.
*/
public static final int DM_NO_ERROR = 0;
/**
* The text is too big for the symbology capabilities.
*/
public static final int DM_ERROR_TEXT_TOO_BIG = 1;
/**
* The dimensions given for the symbol are illegal.
*/
public static final int DM_ERROR_INVALID_SQUARE = 3;
/**
* An error while parsing an extension.
*/
public static final int DM_ERROR_EXTENSION = 5;
/**
* The best encodation will be used.
*/
public static final int DM_AUTO = 0;
/**
* ASCII encodation.
*/
public static final int DM_ASCII = 1;
/**
* C40 encodation.
*/
public static final int DM_C40 = 2;
/**
* TEXT encodation.
*/
public static final int DM_TEXT = 3;
/**
* Binary encodation.
*/
public static final int DM_B256 = 4;
/**
* X21 encodation.
*/
public static final int DM_X21 = 5;
/**
* EDIFACT encodation.
*/
public static final int DM_EDIFACT = 6;
/**
* No encodation needed. The bytes provided are already encoded.
*/
public static final int DM_RAW = 7;
/**
* Allows extensions to be embedded at the start of the text.
*/
public static final int DM_EXTENSION = 32;
/**
* Doesn't generate the image but returns all the other information.
*/
public static final int DM_TEST = 64;
private final static DmParams[] dmSizes = {
new DmParams(10, 10, 10, 10, 3, 3, 5),
new DmParams(12, 12, 12, 12, 5, 5, 7),
new DmParams(8, 18, 8, 18, 5, 5, 7),
new DmParams(14, 14, 14, 14, 8, 8, 10),
new DmParams(8, 32, 8, 16, 10, 10, 11),
new DmParams(16, 16, 16, 16, 12, 12, 12),
new DmParams(12, 26, 12, 26, 16, 16, 14),
new DmParams(18, 18, 18, 18, 18, 18, 14),
new DmParams(20, 20, 20, 20, 22, 22, 18),
new DmParams(12, 36, 12, 18, 22, 22, 18),
new DmParams(22, 22, 22, 22, 30, 30, 20),
new DmParams(16, 36, 16, 18, 32, 32, 24),
new DmParams(24, 24, 24, 24, 36, 36, 24),
new DmParams(26, 26, 26, 26, 44, 44, 28),
new DmParams(16, 48, 16, 24, 49, 49, 28),
new DmParams(32, 32, 16, 16, 62, 62, 36),
new DmParams(36, 36, 18, 18, 86, 86, 42),
new DmParams(40, 40, 20, 20, 114, 114, 48),
new DmParams(44, 44, 22, 22, 144, 144, 56),
new DmParams(48, 48, 24, 24, 174, 174, 68),
new DmParams(52, 52, 26, 26, 204, 102, 42),
new DmParams(64, 64, 16, 16, 280, 140, 56),
new DmParams(72, 72, 18, 18, 368, 92, 36),
new DmParams(80, 80, 20, 20, 456, 114, 48),
new DmParams(88, 88, 22, 22, 576, 144, 56),
new DmParams(96, 96, 24, 24, 696, 174, 68),
new DmParams(104, 104, 26, 26, 816, 136, 56),
new DmParams(120, 120, 20, 20, 1050, 175, 68),
new DmParams(132, 132, 22, 22, 1304, 163, 62),
new DmParams(144, 144, 24, 24, 1558, 156, 62)};
private static final String x12 = "\r*> 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private int extOut;
private short[] place;
private byte[] image;
private int height;
private int width;
private int ws;
private int options;
/**
* Creates an instance of this class.
*/
public BarcodeDatamatrix() {
}
private void setBit(int x, int y, int xByte) {
image[y * xByte + x / 8] |= (byte)(128 >> (x & 7));
}
private void draw(byte[] data, int dataSize, DmParams dm) {
int i, j, p, x, y, xs, ys, z;
int xByte = (dm.width + ws * 2 + 7) / 8;
Arrays.fill(image, (byte)0);
//alignment patterns
//dotted horizontal line
for (i = ws; i < dm.height + ws; i += dm.heightSection) {
for (j = ws; j < dm.width + ws; j += 2) {
setBit(j, i, xByte);
}
}
//solid horizontal line
for (i = dm.heightSection - 1 + ws; i < dm.height + ws; i += dm.heightSection) {
for (j = ws; j < dm.width + ws; ++j) {
setBit(j, i, xByte);
}
}
//solid vertical line
for (i = ws; i < dm.width + ws; i += dm.widthSection) {
for (j = ws; j < dm.height + ws; ++j) {
setBit(i, j, xByte);
}
}
//dotted vertical line
for (i = dm.widthSection - 1 + ws; i < dm.width + ws; i += dm.widthSection) {
for (j = 1 + ws; j < dm.height + ws; j += 2) {
setBit(i, j, xByte);
}
}
p = 0;
for (ys = 0; ys < dm.height; ys += dm.heightSection) {
for (y = 1; y < dm.heightSection - 1; ++y) {
for (xs = 0; xs < dm.width; xs += dm.widthSection) {
for (x = 1; x < dm.widthSection - 1; ++x) {
z = place[p++];
if (z == 1 || (z > 1 && ((data[z/8-1] & 0xff) & (128 >> (z%8))) != 0))
setBit(x + xs + ws, y + ys + ws, xByte);
}
}
}
}
}
private static void makePadding(byte[] data, int position, int count) {
//already in ascii mode
if (count <= 0)
return;
data[position++] = (byte)129;
while (--count > 0) {
int t = 129 + (((position + 1) * 149) % 253) + 1;
if (t > 254)
t -= 254;
data[position++] = (byte)t;
}
}
private static boolean isDigit(int c) {
return c >= '0' && c <= '9';
}
private static int asciiEncodation(byte[] text, int textOffset, int textLength, byte[] data, int dataOffset, int dataLength) {
int ptrIn, ptrOut, c;
ptrIn = textOffset;
ptrOut = dataOffset;
textLength += textOffset;
dataLength += dataOffset;
while (ptrIn < textLength) {
if (ptrOut >= dataLength)
return -1;
c = text[ptrIn++] & 0xff;
if (isDigit(c) && ptrIn < textLength && isDigit(text[ptrIn] & 0xff)) {
data[ptrOut++] = (byte)((c - '0') * 10 + (text[ptrIn++] & 0xff) - '0' + 130);
}
else if (c > 127) {
if (ptrOut + 1 >= dataLength)
return -1;
data[ptrOut++] = (byte)235;
data[ptrOut++] = (byte)(c - 128 + 1);
}
else {
data[ptrOut++] = (byte)(c + 1);
}
}
return ptrOut - dataOffset;
}
private static int b256Encodation(byte[] text, int textOffset, int textLength, byte[] data, int dataOffset, int dataLength) {
int k, j, prn, tv, c;
if (textLength == 0)
return 0;
if (textLength < 250 && textLength + 2 > dataLength)
return -1;
if (textLength >= 250 && textLength + 3 > dataLength)
return -1;
data[dataOffset] = (byte)231;
if (textLength < 250) {
data[dataOffset + 1] = (byte)textLength;
k = 2;
}
else {
data[dataOffset + 1] = (byte)(textLength / 250 + 249);
data[dataOffset + 2] = (byte)(textLength % 250);
k = 3;
}
System.arraycopy(text, textOffset, data, k + dataOffset, textLength);
k += textLength + dataOffset;
for (j = dataOffset + 1; j < k; ++j) {
c = data[j] & 0xff;
prn = ((149 * (j + 1)) % 255) + 1;
tv = c + prn;
if (tv > 255)
tv -= 256;
data[j] = (byte)tv;
}
return k - dataOffset;
}
private static int X12Encodation(byte[] text, int textOffset, int textLength, byte[] data, int dataOffset, int dataLength) {
int ptrIn, ptrOut, count, k, n, ci;
byte c;
if (textLength == 0)
return 0;
ptrIn = 0;
ptrOut = 0;
byte[] x = new byte[textLength];
count = 0;
for (; ptrIn < textLength; ++ptrIn) {
int i = x12.indexOf((char)text[ptrIn + textOffset]);
if (i >= 0) {
x[ptrIn] = (byte)i;
++count;
}
else {
x[ptrIn] = 100;
if (count >= 6)
count -= (count / 3) * 3;
for (k = 0; k < count; ++k)
x[ptrIn - k - 1] = 100;
count = 0;
}
}
if (count >= 6)
count -= (count / 3) * 3;
for (k = 0; k < count; ++k)
x[ptrIn - k - 1] = 100;
ptrIn = 0;
c = 0;
for (; ptrIn < textLength; ++ptrIn) {
c = x[ptrIn];
if (ptrOut >= dataLength)
break;
if (c < 40) {
if (ptrIn == 0 || (ptrIn > 0 && x[ptrIn - 1] > 40))
data[dataOffset + ptrOut++] = (byte)238;
if (ptrOut + 2 > dataLength)
break;
n = 1600 * x[ptrIn] + 40 * x[ptrIn + 1] + x[ptrIn + 2] + 1;
data[dataOffset + ptrOut++] = (byte)(n / 256);
data[dataOffset + ptrOut++] = (byte)n;
ptrIn += 2;
}
else {
if (ptrIn > 0 && x[ptrIn - 1] < 40)
data[dataOffset + ptrOut++] = (byte)254;
ci = text[ptrIn + textOffset] & 0xff;
if (ci > 127) {
data[dataOffset + ptrOut++] = (byte)235;
ci -= 128;
}
if (ptrOut >= dataLength)
break;
data[dataOffset + ptrOut++] = (byte)(ci + 1);
}
}
c = 100;
if (textLength > 0)
c = x[textLength - 1];
if (ptrIn != textLength || (c < 40 && ptrOut >= dataLength))
return -1;
if (c < 40)
data[dataOffset + ptrOut++] = (byte)(254);
return ptrOut;
}
private static int EdifactEncodation(byte[] text, int textOffset, int textLength, byte[] data, int dataOffset, int dataLength) {
int ptrIn, ptrOut, edi, pedi, c;
if (textLength == 0)
return 0;
ptrIn = 0;
ptrOut = 0;
edi = 0;
pedi = 18;
boolean ascii = true;
for (; ptrIn < textLength; ++ptrIn) {
c = text[ptrIn + textOffset] & 0xff;
if (((c & 0xe0) == 0x40 || (c & 0xe0) == 0x20) && c != '_') {
if (ascii) {
if (ptrOut + 1 > dataLength)
break;
data[dataOffset + ptrOut++] = (byte)240;
ascii = false;
}
c &= 0x3f;
edi |= c << pedi;
if (pedi == 0) {
if (ptrOut + 3 > dataLength)
break;
data[dataOffset + ptrOut++] = (byte)(edi >> 16);
data[dataOffset + ptrOut++] = (byte)(edi >> 8);
data[dataOffset + ptrOut++] = (byte)edi;
edi = 0;
pedi = 18;
}
else
pedi -= 6;
}
else {
if (!ascii) {
edi |= ('_' & 0x3f) << pedi;
if (ptrOut + (3 - pedi / 8) > dataLength)
break;
data[dataOffset + ptrOut++] = (byte)(edi >> 16);
if (pedi <= 12)
data[dataOffset + ptrOut++] = (byte)(edi >> 8);
if (pedi <= 6)
data[dataOffset + ptrOut++] = (byte)edi;
ascii = true;
pedi = 18;
edi = 0;
}
if (c > 127) {
if (ptrOut >= dataLength)
break;
data[dataOffset + ptrOut++] = (byte)235;
c -= 128;
}
if (ptrOut >= dataLength)
break;
data[dataOffset + ptrOut++] = (byte)(c + 1);
}
}
if (ptrIn != textLength)
return -1;
if (!ascii) {
edi |= ('_' & 0x3f) << pedi;
if (ptrOut + (3 - pedi / 8) > dataLength)
return -1;
data[dataOffset + ptrOut++] = (byte)(edi >> 16);
if (pedi <= 12)
data[dataOffset + ptrOut++] = (byte)(edi >> 8);
if (pedi <= 6)
data[dataOffset + ptrOut++] = (byte)edi;
}
return ptrOut;
}
private static int C40OrTextEncodation(byte[] text, int textOffset, int textLength, byte[] data, int dataOffset, int dataLength, boolean c40) {
int ptrIn, ptrOut, encPtr, last0, last1, i, a, c;
String basic, shift2, shift3;
if (textLength == 0)
return 0;
ptrIn = 0;
ptrOut = 0;
if (c40)
data[dataOffset + ptrOut++] = (byte)230;
else
data[dataOffset + ptrOut++] = (byte)239;
shift2 = "!\"#$%&'()*+,-./:;<=>?@[\\]^_";
if (c40) {
basic = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
shift3 = "`abcdefghijklmnopqrstuvwxyz{|}~\177";
}
else {
basic = " 0123456789abcdefghijklmnopqrstuvwxyz";
shift3 = "`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~\177";
}
int[] enc = new int[textLength * 4 + 10];
encPtr = 0;
last0 = 0;
last1 = 0;
while (ptrIn < textLength) {
if ((encPtr % 3) == 0) {
last0 = ptrIn;
last1 = encPtr;
}
c = text[textOffset + ptrIn++] & 0xff;
if (c > 127) {
c -= 128;
enc[encPtr++] = 1;
enc[encPtr++] = 30;
}
int idx = basic.indexOf((char)c);
if (idx >= 0) {
enc[encPtr++] = idx + 3;
}
else if (c < 32) {
enc[encPtr++] = 0;
enc[encPtr++] = c;
}
else if ((idx = shift2.indexOf((char)c)) >= 0) {
enc[encPtr++] = 1;
enc[encPtr++] = idx;
}
else if ((idx = shift3.indexOf((char)c)) >= 0) {
enc[encPtr++] = 2;
enc[encPtr++] = idx;
}
}
if ((encPtr % 3) != 0) {
ptrIn = last0;
encPtr = last1;
}
if (encPtr / 3 * 2 > dataLength - 2) {
return -1;
}
i = 0;
for (; i < encPtr; i += 3) {
a = 1600 * enc[i] + 40 * enc[i + 1] + enc[i + 2] + 1;
data[dataOffset + ptrOut++] = (byte)(a / 256);
data[dataOffset + ptrOut++] = (byte)a;
}
data[ptrOut++] = (byte)254;
i = asciiEncodation(text, ptrIn, textLength - ptrIn, data, ptrOut, dataLength - ptrOut);
if (i < 0)
return i;
return ptrOut + i;
}
private static int getEncodation(byte[] text, int textOffset, int textSize, byte[] data, int dataOffset, int dataSize, int options, boolean firstMatch) {
int e, j, k;
int[] e1 = new int[6];
if (dataSize < 0)
return -1;
e = -1;
options &= 7;
if (options == 0) {
e1[0] = asciiEncodation(text, textOffset, textSize, data, dataOffset, dataSize);
if (firstMatch && e1[0] >= 0)
return e1[0];
e1[1] = C40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, false);
if (firstMatch && e1[1] >= 0)
return e1[1];
e1[2] = C40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, true);
if (firstMatch && e1[2] >= 0)
return e1[2];
e1[3] = b256Encodation(text, textOffset, textSize, data, dataOffset, dataSize);
if (firstMatch && e1[3] >= 0)
return e1[3];
e1[4] = X12Encodation(text, textOffset, textSize, data, dataOffset, dataSize);
if (firstMatch && e1[4] >= 0)
return e1[4];
e1[5] = EdifactEncodation(text, textOffset, textSize, data, dataOffset, dataSize);
if (firstMatch && e1[5] >= 0)
return e1[5];
if (e1[0] < 0 && e1[1] < 0 && e1[2] < 0 && e1[3] < 0 && e1[4] < 0 && e1[5] < 0) {
return -1;
}
j = 0;
e = 99999;
for (k = 0; k < 6; ++k) {
if (e1[k] >= 0 && e1[k] < e) {
e = e1[k];
j = k;
}
}
if (j == 0)
e = asciiEncodation(text, textOffset, textSize, data, dataOffset, dataSize);
else if (j == 1)
e = C40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, false);
else if (j == 2)
e = C40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, true);
else if (j == 3)
e = b256Encodation(text, textOffset, textSize, data, dataOffset, dataSize);
else if (j == 4)
e = X12Encodation(text, textOffset, textSize, data, dataOffset, dataSize);
return e;
}
switch (options) {
case DM_ASCII:
return asciiEncodation(text, textOffset, textSize, data, dataOffset, dataSize);
case DM_C40:
return C40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, true);
case DM_TEXT:
return C40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, false);
case DM_B256:
return b256Encodation(text, textOffset, textSize, data, dataOffset, dataSize);
case DM_X21:
return X12Encodation(text, textOffset, textSize, data, dataOffset, dataSize);
case DM_EDIFACT:
return EdifactEncodation(text, textOffset, textSize, data, dataOffset, dataSize);
case DM_RAW:
if (textSize > dataSize)
return -1;
System.arraycopy(text, textOffset, data, dataOffset, textSize);
return textSize;
}
return -1;
}
private static int getNumber(byte[] text, int ptrIn, int n) {
int v, j, c;
v = 0;
for (j = 0; j < n; ++j) {
c = text[ptrIn++] &0xff;
if (c < '0' || c > '9')
return -1;
v = v * 10 + c - '0';
}
return v;
}
private int processExtensions(byte[] text, int textOffset, int textSize, byte[] data) {
int order, ptrIn, ptrOut, eci, fn, ft, fi, c;
if ((options & DM_EXTENSION) == 0)
return 0;
order = 0;
ptrIn = 0;
ptrOut = 0;
while (ptrIn < textSize) {
if (order > 20)
return -1;
c = text[textOffset + ptrIn++] &0xff;
++order;
switch (c) {
case '.':
extOut = ptrIn;
return ptrOut;
case 'e':
if (ptrIn + 6 > textSize)
return -1;
eci = getNumber(text, textOffset + ptrIn, 6);
if (eci < 0)
return -1;
ptrIn += 6;
data[ptrOut++] = (byte)241;
if (eci < 127)
data[ptrOut++] = (byte)(eci + 1);
else if (eci < 16383) {
data[ptrOut++] = (byte)((eci - 127) / 254 + 128);
data[ptrOut++] = (byte)(((eci - 127) % 254) + 1);
}
else {
data[ptrOut++] = (byte)((eci - 16383) / 64516 + 192);
data[ptrOut++] = (byte)((((eci - 16383) / 254) % 254) + 1);
data[ptrOut++] = (byte)(((eci - 16383) % 254) + 1);
}
break;
case 's':
if (order != 1)
return -1;
if (ptrIn + 9 > textSize)
return -1;
fn = getNumber(text, textOffset + ptrIn, 2);
if (fn <= 0 || fn > 16)
return -1;
ptrIn += 2;
ft = getNumber(text, textOffset + ptrIn, 2);
if (ft <= 1 || ft > 16)
return -1;
ptrIn += 2;
fi = getNumber(text, textOffset + ptrIn, 5);
if (fi < 0 || fn >= 64516)
return -1;
ptrIn += 5;
data[ptrOut++] = (byte)(233);
data[ptrOut++] = (byte)(((fn - 1) << 4) | (17 - ft));
data[ptrOut++] = (byte)(fi / 254 + 1);
data[ptrOut++] = (byte)((fi % 254) + 1);
break;
case 'p':
if (order != 1)
return -1;
data[ptrOut++] = (byte)(234);
break;
case 'm':
if (order != 1)
return -1;
if (ptrIn + 1 > textSize)
return -1;
c = text[textOffset + ptrIn++] &0xff;
if (c != '5' && c != '5')
return -1;
data[ptrOut++] = (byte)(234);
data[ptrOut++] = (byte)(c == '5' ? 236 : 237);
break;
case 'f':
if (order != 1 && (order != 2 || (text[textOffset] != 's' && text[textOffset] != 'm')))
return -1;
data[ptrOut++] = (byte)(232);
}
}
return -1;
}
/**
* Creates a barcode. The String
is interpreted with the ISO-8859-1 encoding
* @param text the text
* @return the status of the generation. It can be one of this values:
* DM_NO_ERROR
- no error.
* DM_ERROR_TEXT_TOO_BIG
- the text is too big for the symbology capabilities.
* DM_ERROR_INVALID_SQUARE
- the dimensions given for the symbol are illegal.
* DM_ERROR_EXTENSION
- an error was while parsing an extension.
* @throws java.io.UnsupportedEncodingException on error
*/
public int generate(String text) throws UnsupportedEncodingException {
byte[] t = text.getBytes("iso-8859-1");
return generate(t, 0, t.length);
}
/**
* Creates a barcode.
* @param text the text
* @param textOffset the offset to the start of the text
* @param textSize the text size
* @return the status of the generation. It can be one of this values:
* DM_NO_ERROR
- no error.
* DM_ERROR_TEXT_TOO_BIG
- the text is too big for the symbology capabilities.
* DM_ERROR_INVALID_SQUARE
- the dimensions given for the symbol are illegal.
* DM_ERROR_EXTENSION
- an error was while parsing an extension.
*/
public int generate(byte[] text, int textOffset, int textSize) {
int extCount, e, k, full;
DmParams dm, last;
byte[] data = new byte[2500];
extOut = 0;
extCount = processExtensions(text, textOffset, textSize, data);
if (extCount < 0) {
return DM_ERROR_EXTENSION;
}
e = -1;
if (height == 0 || width == 0) {
last = dmSizes[dmSizes.length - 1];
e = getEncodation(text, textOffset + extOut, textSize - extOut, data, extCount, last.dataSize - extCount, options, false);
if (e < 0) {
return DM_ERROR_TEXT_TOO_BIG;
}
e += extCount;
for (k = 0; k < dmSizes.length; ++k) {
if (dmSizes[k].dataSize >= e)
break;
}
dm = dmSizes[k];
height = dm.height;
width = dm.width;
}
else {
for (k = 0; k < dmSizes.length; ++k) {
if (height == dmSizes[k].height && width == dmSizes[k].width)
break;
}
if (k == dmSizes.length) {
return DM_ERROR_INVALID_SQUARE;
}
dm = dmSizes[k];
e = getEncodation(text, textOffset + extOut, textSize - extOut, data, extCount, dm.dataSize - extCount, options, true);
if (e < 0) {
return DM_ERROR_TEXT_TOO_BIG;
}
e += extCount;
}
if ((options & DM_TEST) != 0) {
return DM_NO_ERROR;
}
image = new byte[(((dm.width + 2 * ws) + 7) / 8) * (dm.height + 2 * ws)];
makePadding(data, e, dm.dataSize - e);
place = Placement.doPlacement(dm.height - (dm.height / dm.heightSection * 2), dm.width - (dm.width / dm.widthSection * 2));
full = dm.dataSize + ((dm.dataSize + 2) / dm.dataBlock) * dm.errorBlock;
ReedSolomon.generateECC(data, dm.dataSize, dm.dataBlock, dm.errorBlock);
draw(data, full, dm);
return DM_NO_ERROR;
}
/** Gets an Image
with the barcode. A successful call to the method generate()
* before calling this method is required.
* @return the barcode Image
* @throws BadElementException on error
*/
public Image createImage() throws BadElementException {
if (image == null)
return null;
byte g4[] = CCITTG4Encoder.compress(image, width + 2 * ws, height + 2 * ws);
return Image.getInstance(width + 2 * ws, height + 2 * ws, false, Image.CCITTG4, 0, g4, null);
}
/**
* Creates a java.awt.Image
. A successful call to the method generate()
* before calling this method is required.
* @param foreground the color of the bars
* @param background the color of the background
* @return the image
*/
public java.awt.Image createAwtImage(Color foreground, Color background) {
if (image == null)
return null;
int f = foreground.getRGB();
int g = background.getRGB();
Canvas canvas = new Canvas();
int w = width + 2 * ws;
int h = height + 2 * ws;
int pix[] = new int[w * h];
int stride = (w + 7) / 8;
int ptr = 0;
for (int k = 0; k < h; ++k) {
int p = k * stride;
for (int j = 0; j < w; ++j) {
int b = image[p + (j / 8)] & 0xff;
b <<= j % 8;
pix[ptr++] = (b & 0x80) == 0 ? g : f;
}
}
java.awt.Image img = canvas.createImage(new MemoryImageSource(w, h, pix, 0, w));
return img;
}
private static class DmParams {
DmParams(int height, int width, int heightSection, int widthSection, int dataSize, int dataBlock, int errorBlock) {
this.height = height;
this.width = width;
this.heightSection = heightSection;
this.widthSection = widthSection;
this.dataSize = dataSize;
this.dataBlock = dataBlock;
this.errorBlock = errorBlock;
}
int height;
int width;
int heightSection;
int widthSection;
int dataSize;
int dataBlock;
int errorBlock;
};
/**
* Gets the generated image. The image is represented as a stream of bytes, each byte representing
* 8 pixels, 0 for white and 1 for black, with the high-order bit of each byte first. Each row
* is aligned at byte boundaries. The dimensions of the image are defined by height and width
* plus 2 * ws.
* @return the generated image
*/
public byte[] getImage() {
return image;
}
/**
* Gets the height of the barcode. Will contain the real height used after a successful call
* to generate()
. This height doesn't include the whitespace border, if any.
* @return the height of the barcode
*/
public int getHeight() {
return height;
}
/**
* Sets the height of the barcode. If the height is zero it will be calculated. This height doesn't include the whitespace border, if any.
*
* 12, 12
* 8, 18
* 14, 14
* 8, 32
* 16, 16
* 12, 26
* 18, 18
* 20, 20
* 12, 36
* 22, 22
* 16, 36
* 24, 24
* 26, 26
* 16, 48
* 32, 32
* 36, 36
* 40, 40
* 44, 44
* 48, 48
* 52, 52
* 64, 64
* 72, 72
* 80, 80
* 88, 88
* 96, 96
* 104, 104
* 120, 120
* 132, 132
* 144, 144
* @param height the height of the barcode
*/
public void setHeight(int height) {
this.height = height;
}
/**
* Gets the width of the barcode. Will contain the real width used after a successful call
* to generate()
. This width doesn't include the whitespace border, if any.
* @return the width of the barcode
*/
public int getWidth() {
return width;
}
/**
* Sets the width of the barcode. If the width is zero it will be calculated. This width doesn't include the whitespace border, if any.
*
* 12, 12
* 8, 18
* 14, 14
* 8, 32
* 16, 16
* 12, 26
* 18, 18
* 20, 20
* 12, 36
* 22, 22
* 16, 36
* 24, 24
* 26, 26
* 16, 48
* 32, 32
* 36, 36
* 40, 40
* 44, 44
* 48, 48
* 52, 52
* 64, 64
* 72, 72
* 80, 80
* 88, 88
* 96, 96
* 104, 104
* 120, 120
* 132, 132
* 144, 144
* @param width the width of the barcode
*/
public void setWidth(int width) {
this.width = width;
}
/**
* Gets the whitespace border around the barcode.
* @return the whitespace border around the barcode
*/
public int getWs() {
return ws;
}
/**
* Sets the whitespace border around the barcode.
* @param ws the whitespace border around the barcode
*/
public void setWs(int ws) {
this.ws = ws;
}
/**
* Gets the barcode options.
* @return the barcode options
*/
public int getOptions() {
return options;
}
/**
* Sets the options for the barcode generation. The options can be:
* DM_AUTO
- the best encodation will be used
* DM_ASCII
- ASCII encodation
* DM_C40
- C40 encodation
* DM_TEXT
- TEXT encodation
* DM_B256
- binary encodation
* DM_X21
- X21 encodation
* DM_EDIFACT
- EDIFACT encodation
* DM_RAW
- no encodation. The bytes provided are already encoded and will be added directly to the barcode, using padding if needed. It assumes that the encodation state is left at ASCII after the last byte.
*
* DM_EXTENSION
- allows extensions to be embedded at the start of the text:
* m5 - macro 5
* m6 - macro 6
* f - FNC1
* saabbccccc - Structured Append, aa symbol position (1-16), bb total number of symbols (2-16), ccccc file identification (0-64515)
* p - Reader programming
* . - extension terminator
* DM_TEST
- doesn't generate the image but returns all the other information.
* @param options the barcode options
*/
public void setOptions(int options) {
this.options = options;
}
static class Placement {
private int nrow;
private int ncol;
private short[] array;
private static final Hashtable cache = new Hashtable();
private Placement() {
}
static short[] doPlacement(int nrow, int ncol) {
Integer key = new Integer(nrow * 1000 + ncol);
short[] pc = (short[])cache.get(key);
if (pc != null)
return pc;
Placement p = new Placement();
p.nrow = nrow;
p.ncol = ncol;
p.array = new short[nrow * ncol];
p.ecc200();
cache.put(key, p.array);
return p.array;
}
/* "module" places "chr+bit" with appropriate wrapping within array[] */
private void module(int row, int col, int chr, int bit) {
if (row < 0) { row += nrow; col += 4 - ((nrow+4)%8); }
if (col < 0) { col += ncol; row += 4 - ((ncol+4)%8); }
array[row*ncol+col] = (short)(8*chr + bit);
}
/* "utah" places the 8 bits of a utah-shaped symbol character in ECC200 */
private void utah(int row, int col, int chr) {
module(row-2,col-2,chr,0);
module(row-2,col-1,chr,1);
module(row-1,col-2,chr,2);
module(row-1,col-1,chr,3);
module(row-1,col,chr,4);
module(row,col-2,chr,5);
module(row,col-1,chr,6);
module(row,col,chr,7);
}
/* "cornerN" places 8 bits of the four special corner cases in ECC200 */
private void corner1(int chr) {
module(nrow-1,0,chr,0);
module(nrow-1,1,chr,1);
module(nrow-1,2,chr,2);
module(0,ncol-2,chr,3);
module(0,ncol-1,chr,4);
module(1,ncol-1,chr,5);
module(2,ncol-1,chr,6);
module(3,ncol-1,chr,7);
}
private void corner2(int chr){
module(nrow-3,0,chr,0);
module(nrow-2,0,chr,1);
module(nrow-1,0,chr,2);
module(0,ncol-4,chr,3);
module(0,ncol-3,chr,4);
module(0,ncol-2,chr,5);
module(0,ncol-1,chr,6);
module(1,ncol-1,chr,7);
}
private void corner3(int chr){
module(nrow-3,0,chr,0);
module(nrow-2,0,chr,1);
module(nrow-1,0,chr,2);
module(0,ncol-2,chr,3);
module(0,ncol-1,chr,4);
module(1,ncol-1,chr,5);
module(2,ncol-1,chr,6);
module(3,ncol-1,chr,7);
}
private void corner4(int chr){
module(nrow-1,0,chr,0);
module(nrow-1,ncol-1,chr,1);
module(0,ncol-3,chr,2);
module(0,ncol-2,chr,3);
module(0,ncol-1,chr,4);
module(1,ncol-3,chr,5);
module(1,ncol-2,chr,6);
module(1,ncol-1,chr,7);
}
/* "ECC200" fills an nrow x ncol array with appropriate values for ECC200 */
private void ecc200(){
int row, col, chr;
/* First, fill the array[] with invalid entries */
Arrays.fill(array, (short)0);
/* Starting in the correct location for character #1, bit 8,... */
chr = 1; row = 4; col = 0;
do {
/* repeatedly first check for one of the special corner cases, then... */
if ((row == nrow) && (col == 0)) corner1(chr++);
if ((row == nrow-2) && (col == 0) && (ncol%4 != 0)) corner2(chr++);
if ((row == nrow-2) && (col == 0) && (ncol%8 == 4)) corner3(chr++);
if ((row == nrow+4) && (col == 2) && (ncol%8 == 0)) corner4(chr++);
/* sweep upward diagonally, inserting successive characters,... */
do {
if ((row < nrow) && (col >= 0) && array[row*ncol+col] == 0)
utah(row,col,chr++);
row -= 2; col += 2;
} while ((row >= 0) && (col < ncol));
row += 1; col += 3;
/* & then sweep downward diagonally, inserting successive characters,... */
do {
if ((row >= 0) && (col < ncol) && array[row*ncol+col] == 0)
utah(row,col,chr++);
row += 2; col -= 2;
} while ((row < nrow) && (col >= 0));
row += 3; col += 1;
/* ... until the entire array is scanned */
} while ((row < nrow) || (col < ncol));
/* Lastly, if the lower righthand corner is untouched, fill in fixed pattern */
if (array[nrow*ncol-1] == 0) {
array[nrow*ncol-1] = array[nrow*ncol-ncol-2] = 1;
}
}
}
static class ReedSolomon {
private static final int log[] = {
0, 255, 1, 240, 2, 225, 241, 53, 3, 38, 226, 133, 242, 43, 54, 210,
4, 195, 39, 114, 227, 106, 134, 28, 243, 140, 44, 23, 55, 118, 211, 234,
5, 219, 196, 96, 40, 222, 115, 103, 228, 78, 107, 125, 135, 8, 29, 162,
244, 186, 141, 180, 45, 99, 24, 49, 56, 13, 119, 153, 212, 199, 235, 91,
6, 76, 220, 217, 197, 11, 97, 184, 41, 36, 223, 253, 116, 138, 104, 193,
229, 86, 79, 171, 108, 165, 126, 145, 136, 34, 9, 74, 30, 32, 163, 84,
245, 173, 187, 204, 142, 81, 181, 190, 46, 88, 100, 159, 25, 231, 50, 207,
57, 147, 14, 67, 120, 128, 154, 248, 213, 167, 200, 63, 236, 110, 92, 176,
7, 161, 77, 124, 221, 102, 218, 95, 198, 90, 12, 152, 98, 48, 185, 179,
42, 209, 37, 132, 224, 52, 254, 239, 117, 233, 139, 22, 105, 27, 194, 113,
230, 206, 87, 158, 80, 189, 172, 203, 109, 175, 166, 62, 127, 247, 146, 66,
137, 192, 35, 252, 10, 183, 75, 216, 31, 83, 33, 73, 164, 144, 85, 170,
246, 65, 174, 61, 188, 202, 205, 157, 143, 169, 82, 72, 182, 215, 191, 251,
47, 178, 89, 151, 101, 94, 160, 123, 26, 112, 232, 21, 51, 238, 208, 131,
58, 69, 148, 18, 15, 16, 68, 17, 121, 149, 129, 19, 155, 59, 249, 70,
214, 250, 168, 71, 201, 156, 64, 60, 237, 130, 111, 20, 93, 122, 177, 150
};
private static final int alog[] = {
1, 2, 4, 8, 16, 32, 64, 128, 45, 90, 180, 69, 138, 57, 114, 228,
229, 231, 227, 235, 251, 219, 155, 27, 54, 108, 216, 157, 23, 46, 92, 184,
93, 186, 89, 178, 73, 146, 9, 18, 36, 72, 144, 13, 26, 52, 104, 208,
141, 55, 110, 220, 149, 7, 14, 28, 56, 112, 224, 237, 247, 195, 171, 123,
246, 193, 175, 115, 230, 225, 239, 243, 203, 187, 91, 182, 65, 130, 41, 82,
164, 101, 202, 185, 95, 190, 81, 162, 105, 210, 137, 63, 126, 252, 213, 135,
35, 70, 140, 53, 106, 212, 133, 39, 78, 156, 21, 42, 84, 168, 125, 250,
217, 159, 19, 38, 76, 152, 29, 58, 116, 232, 253, 215, 131, 43, 86, 172,
117, 234, 249, 223, 147, 11, 22, 44, 88, 176, 77, 154, 25, 50, 100, 200,
189, 87, 174, 113, 226, 233, 255, 211, 139, 59, 118, 236, 245, 199, 163, 107,
214, 129, 47, 94, 188, 85, 170, 121, 242, 201, 191, 83, 166, 97, 194, 169,
127, 254, 209, 143, 51, 102, 204, 181, 71, 142, 49, 98, 196, 165, 103, 206,
177, 79, 158, 17, 34, 68, 136, 61, 122, 244, 197, 167, 99, 198, 161, 111,
222, 145, 15, 30, 60, 120, 240, 205, 183, 67, 134, 33, 66, 132, 37, 74,
148, 5, 10, 20, 40, 80, 160, 109, 218, 153, 31, 62, 124, 248, 221, 151,
3, 6, 12, 24, 48, 96, 192, 173, 119, 238, 241, 207, 179, 75, 150, 1
};
private static final int poly5[] = {
228, 48, 15, 111, 62
};
private static final int poly7[] = {
23, 68, 144, 134, 240, 92, 254
};
private static final int poly10[] = {
28, 24, 185, 166, 223, 248, 116, 255, 110, 61
};
private static final int poly11[] = {
175, 138, 205, 12, 194, 168, 39, 245, 60, 97, 120
};
private static final int poly12[] = {
41, 153, 158, 91, 61, 42, 142, 213, 97, 178, 100, 242
};
private static final int poly14[] = {
156, 97, 192, 252, 95, 9, 157, 119, 138, 45, 18, 186, 83, 185
};
private static final int poly18[] = {
83, 195, 100, 39, 188, 75, 66, 61, 241, 213, 109, 129, 94, 254, 225, 48,
90, 188
};
private static final int poly20[] = {
15, 195, 244, 9, 233, 71, 168, 2, 188, 160, 153, 145, 253, 79, 108, 82,
27, 174, 186, 172
};
private static final int poly24[] = {
52, 190, 88, 205, 109, 39, 176, 21, 155, 197, 251, 223, 155, 21, 5, 172,
254, 124, 12, 181, 184, 96, 50, 193
};
private static final int poly28[] = {
211, 231, 43, 97, 71, 96, 103, 174, 37, 151, 170, 53, 75, 34, 249, 121,
17, 138, 110, 213, 141, 136, 120, 151, 233, 168, 93, 255
};
private static final int poly36[] = {
245, 127, 242, 218, 130, 250, 162, 181, 102, 120, 84, 179, 220, 251, 80, 182,
229, 18, 2, 4, 68, 33, 101, 137, 95, 119, 115, 44, 175, 184, 59, 25,
225, 98, 81, 112
};
private static final int poly42[] = {
77, 193, 137, 31, 19, 38, 22, 153, 247, 105, 122, 2, 245, 133, 242, 8,
175, 95, 100, 9, 167, 105, 214, 111, 57, 121, 21, 1, 253, 57, 54, 101,
248, 202, 69, 50, 150, 177, 226, 5, 9, 5
};
private static final int poly48[] = {
245, 132, 172, 223, 96, 32, 117, 22, 238, 133, 238, 231, 205, 188, 237, 87,
191, 106, 16, 147, 118, 23, 37, 90, 170, 205, 131, 88, 120, 100, 66, 138,
186, 240, 82, 44, 176, 87, 187, 147, 160, 175, 69, 213, 92, 253, 225, 19
};
private static final int poly56[] = {
175, 9, 223, 238, 12, 17, 220, 208, 100, 29, 175, 170, 230, 192, 215, 235,
150, 159, 36, 223, 38, 200, 132, 54, 228, 146, 218, 234, 117, 203, 29, 232,
144, 238, 22, 150, 201, 117, 62, 207, 164, 13, 137, 245, 127, 67, 247, 28,
155, 43, 203, 107, 233, 53, 143, 46
};
private static final int poly62[] = {
242, 93, 169, 50, 144, 210, 39, 118, 202, 188, 201, 189, 143, 108, 196, 37,
185, 112, 134, 230, 245, 63, 197, 190, 250, 106, 185, 221, 175, 64, 114, 71,
161, 44, 147, 6, 27, 218, 51, 63, 87, 10, 40, 130, 188, 17, 163, 31,
176, 170, 4, 107, 232, 7, 94, 166, 224, 124, 86, 47, 11, 204
};
private static final int poly68[] = {
220, 228, 173, 89, 251, 149, 159, 56, 89, 33, 147, 244, 154, 36, 73, 127,
213, 136, 248, 180, 234, 197, 158, 177, 68, 122, 93, 213, 15, 160, 227, 236,
66, 139, 153, 185, 202, 167, 179, 25, 220, 232, 96, 210, 231, 136, 223, 239,
181, 241, 59, 52, 172, 25, 49, 232, 211, 189, 64, 54, 108, 153, 132, 63,
96, 103, 82, 186
};
private static int[] getPoly(int nc) {
switch (nc) {
case 5:
return poly5;
case 7:
return poly7;
case 10:
return poly10;
case 11:
return poly11;
case 12:
return poly12;
case 14:
return poly14;
case 18:
return poly18;
case 20:
return poly20;
case 24:
return poly24;
case 28:
return poly28;
case 36:
return poly36;
case 42:
return poly42;
case 48:
return poly48;
case 56:
return poly56;
case 62:
return poly62;
case 68:
return poly68;
}
return null;
}
private static void reedSolomonBlock(byte[] wd, int nd, byte[] ncout, int nc, int[] c) {
int i, j, k;
for (i=0; i<=nc; i++) ncout[i] = 0;
for (i=0; i