diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/context/ContentFunctionFactory.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/context/ContentFunctionFactory.java index 5a7581ca8..29fa26d82 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/context/ContentFunctionFactory.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/context/ContentFunctionFactory.java @@ -103,9 +103,7 @@ protected boolean isCounter(FSFunction function, String counterName) { if (parameters.size() == 2) { param = (PropertyValue)parameters.get(1); - if (param.getPrimitiveType() != CSSPrimitiveValue.CSS_IDENT) { - return false; - } + return param.getPrimitiveType() == CSSPrimitiveValue.CSS_IDENT; } return true; @@ -175,18 +173,14 @@ public boolean canHandle(LayoutContext c, FSFunction function) { FSFunction f = ((PropertyValue)parameters.get(0)).getFunction(); if (f == null || f.getParameters().size() != 1 || - ((PropertyValue)f.getParameters().get(0)).getPrimitiveType() != CSSPrimitiveValue.CSS_IDENT || - ! ((PropertyValue)f.getParameters().get(0)).getStringValue().equals("href")) { + f.getParameters().get(0).getPrimitiveType() != CSSPrimitiveValue.CSS_IDENT || + ! f.getParameters().get(0).getStringValue().equals("href")) { return false; } PropertyValue param = (PropertyValue)parameters.get(1); - if (param.getPrimitiveType() != CSSPrimitiveValue.CSS_IDENT || - ! param.getStringValue().equals("page")) { - return false; - } - - return true; + return param.getPrimitiveType() == CSSPrimitiveValue.CSS_IDENT && + param.getStringValue().equals("page"); } } @@ -226,7 +220,7 @@ public String calculate(RenderingContext c, FSFunction function, InlineText text } // Get leader value and value width - PropertyValue param = (PropertyValue)function.getParameters().get(0); + PropertyValue param = function.getParameters().get(0); String value = param.getStringValue(); if (param.getPrimitiveType() == CSSPrimitiveValue.CSS_IDENT) { if (value.equals("dotted")) { @@ -241,7 +235,7 @@ public String calculate(RenderingContext c, FSFunction function, InlineText text // Compute value width using 100x string to get more precise width. // Otherwise there might be a small gap at the right side. This is // necessary because a TextRenderer usually use double/float for width. - StringBuffer tmp = new StringBuffer(100 * value.length()); + StringBuilder tmp = new StringBuilder(100 * value.length()); for (int i = 0; i < 100; i++) { tmp.append(value); } @@ -255,7 +249,7 @@ public String calculate(RenderingContext c, FSFunction function, InlineText text int count = (int) ((leaderWidth - (2 * spaceWidth)) / valueWidth); // build leader string - StringBuffer buf = new StringBuffer(count * value.length() + 2); + StringBuilder buf = new StringBuilder(count * value.length() + 2); buf.append(' '); for (int i = 0; i < count; i++) { buf.append(value); @@ -284,15 +278,11 @@ public boolean canHandle(LayoutContext c, FSFunction function) { List parameters = function.getParameters(); if (parameters.size() == 1) { PropertyValue param = (PropertyValue)parameters.get(0); - if (param.getPrimitiveType() != CSSPrimitiveValue.CSS_STRING && - (param.getPrimitiveType() != CSSPrimitiveValue.CSS_IDENT || - (!param.getStringValue().equals("dotted") && - !param.getStringValue().equals("solid") && - !param.getStringValue().equals("space")))) { - return false; - } - - return true; + return param.getPrimitiveType() == CSSPrimitiveValue.CSS_STRING || + (param.getPrimitiveType() == CSSPrimitiveValue.CSS_IDENT && + (param.getStringValue().equals("dotted") || + param.getStringValue().equals("solid") || + param.getStringValue().equals("space"))); } } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/context/StyleReference.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/context/StyleReference.java index b2a9a623c..7b1dc0689 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/context/StyleReference.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/context/StyleReference.java @@ -163,12 +163,10 @@ public boolean isHoverStyled(Element e) { * @param e The DOM Element for which to find properties * @return Map of CSS property names to CSSValue instance assigned to it. */ - public java.util.Map getCascadedPropertiesMap(Element e) { + public java.util.Map getCascadedPropertiesMap(Element e) { CascadedStyle cs = _matcher.getCascadedStyle(e, false);//this is only for debug, I think - java.util.LinkedHashMap props = new java.util.LinkedHashMap(); - for (java.util.Iterator i = cs.getCascadedPropertyDeclarations(); i.hasNext();) { - PropertyDeclaration pd = (PropertyDeclaration) i.next(); - + java.util.Map props = new java.util.LinkedHashMap(); + for (PropertyDeclaration pd : cs.getCascadedPropertyDeclarations()) { String propName = pd.getPropertyName(); CSSName cssName = CSSName.getByPropertyName(propName); props.put(propName, cs.propertyByName(cssName).getValue()); @@ -239,8 +237,8 @@ public void flushAllStyleSheets() { * * @return The stylesheets value */ - private List getStylesheets() { - List infos = new LinkedList(); + private List getStylesheets() { + List infos = new ArrayList(); long st = System.currentTimeMillis(); StylesheetInfo defaultStylesheet = _nsh.getDefaultStylesheet(_stylesheetFactory); @@ -251,22 +249,22 @@ private List getStylesheets() { StylesheetInfo[] refs = _nsh.getStylesheets(_doc); int inlineStyleCount = 0; if (refs != null) { - for (int i = 0; i < refs.length; i++) { + for (StylesheetInfo ref : refs) { String uri; - - if (! refs[i].isInline()) { - uri = _uac.resolveURI(refs[i].getUri()); - refs[i].setUri(uri); + + if (!ref.isInline()) { + uri = _uac.resolveURI(ref.getUri()); + ref.setUri(uri); } else { - refs[i].setUri(_uac.getBaseURL() + "#inline_style_" + (++inlineStyleCount)); + ref.setUri(_uac.getBaseURL() + "#inline_style_" + (++inlineStyleCount)); Stylesheet sheet = _stylesheetFactory.parse( - new StringReader(refs[i].getContent()), refs[i]); - refs[i].setStylesheet(sheet); - refs[i].setUri(null); + new StringReader(ref.getContent()), ref); + ref.setStylesheet(sheet); + ref.setUri(null); } } + infos.addAll(Arrays.asList(refs)); } - infos.addAll(Arrays.asList(refs)); // TODO: here we should also get user stylesheet from userAgent diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/extend/lib/DOMStaticXhtmlAttributeResolver.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/extend/lib/DOMStaticXhtmlAttributeResolver.java index 160b0f552..d172a7d89 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/extend/lib/DOMStaticXhtmlAttributeResolver.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/extend/lib/DOMStaticXhtmlAttributeResolver.java @@ -82,7 +82,7 @@ public String getLang(Object e) { public String getElementStyling(Object el) { Element e = ((Element) el); - StringBuffer style = new StringBuffer(); + StringBuilder style = new StringBuilder(); if (e.getNodeName().equals("td")) { String s; if (!(s = e.getAttribute("colspan")).equals("")) { @@ -114,8 +114,7 @@ public boolean isHover(Object e) { public boolean isLink(Object el) { Element e = ((Element) el); - if (e.getNodeName().equalsIgnoreCase("a") && !e.getAttribute("href").equals("")) return true; - return false; + return e.getNodeName().equalsIgnoreCase("a") && !e.getAttribute("href").equals(""); } public boolean isVisited(Object e) { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/CascadedStyle.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/CascadedStyle.java index 7db228ee2..38e8caea4 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/CascadedStyle.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/CascadedStyle.java @@ -60,21 +60,26 @@ public class CascadedStyle { /** * Map of PropertyDeclarations, keyed by {@link CSSName} */ - private Map cascadedProperties; + private Map cascadedProperties; private String fingerprint; /** - * Creates a CascadedStyle, setting the display property to - * to the value of the display parameter. + * Constructs a new CascadedStyle, given an {@link java.util.Iterator} of + * {@link com.openhtmltopdf.css.sheet.PropertyDeclaration}s already sorted + * by specificity of the CSS selector they came from. The Iterator can have + * multiple PropertyDeclarations with the same name; the property cascade + * will be resolved during instantiation, resulting in a set of + * PropertyDeclarations. Once instantiated, properties may be retrieved + * using the normal API for the class. + * + * @param iter An Iterator containing PropertyDeclarations in order of + * specificity. */ - public static CascadedStyle createAnonymousStyle(IdentValue display) { - CSSPrimitiveValue val = new PropertyValue(display); - - List props = Collections.singletonList( - new PropertyDeclaration(CSSName.DISPLAY, val, true, StylesheetInfo.USER)); - - return new CascadedStyle(props.iterator()); + CascadedStyle(java.util.Iterator iter) { + this(); + + addProperties(iter); } /** @@ -118,60 +123,59 @@ public static PropertyDeclaration createLayoutPropertyDeclaration( return new PropertyDeclaration(cssName, val, true, StylesheetInfo.USER); } + private CascadedStyle(CascadedStyle startingPoint, Iterator props) { + cascadedProperties = new TreeMap(startingPoint.cascadedProperties); + + addProperties(props); + } + /** - * Constructs a new CascadedStyle, given an {@link java.util.Iterator} of - * {@link com.openhtmltopdf.css.sheet.PropertyDeclaration}s already sorted - * by specificity of the CSS selector they came from. The Iterator can have - * multiple PropertyDeclarations with the same name; the property cascade - * will be resolved during instantiation, resulting in a set of - * PropertyDeclarations. Once instantiated, properties may be retrieved - * using the normal API for the class. - * - * @param iter An Iterator containing PropertyDeclarations in order of - * specificity. + * Default constructor with no initialization. Don't use this to instantiate + * the class, as the class is immutable and this will leave it without any + * properties. */ - CascadedStyle(java.util.Iterator iter) { - this(); + private CascadedStyle() { + cascadedProperties = new TreeMap(); + } + /** + * Creates a CascadedStyle, setting the display property to + * to the value of the display parameter. + */ + public static CascadedStyle createAnonymousStyle(IdentValue display) { + CSSPrimitiveValue val = new PropertyValue(display); - addProperties(iter); + List props = Collections.singletonList( + new PropertyDeclaration(CSSName.DISPLAY, val, true, StylesheetInfo.USER)); + + return new CascadedStyle(props.iterator()); } - private void addProperties(java.util.Iterator iter) { - //do a bucket-sort on importance and origin - //properties should already be in order of specificity - java.util.List[] buckets = new java.util.List[PropertyDeclaration.IMPORTANCE_AND_ORIGIN_COUNT]; - for (int i = 0; i < buckets.length; i++) { - buckets[i] = new java.util.LinkedList(); - } + private void addProperties(java.util.Iterator iter) { + /* + * do a bucket-sort on importance and origin /properties should already be in + * order of specificity + */ + //noinspection unchecked + java.util.List[] buckets = (java.util.List[])new java.util.List[PropertyDeclaration.IMPORTANCE_AND_ORIGIN_COUNT]; while (iter.hasNext()) { - PropertyDeclaration prop = (PropertyDeclaration) iter.next(); - buckets[prop.getImportanceAndOrigin()].add(prop); + PropertyDeclaration prop = iter.next(); + List bucket = buckets[prop.getImportanceAndOrigin()]; + if (bucket == null) { + bucket = new ArrayList(); + buckets[prop.getImportanceAndOrigin()] = bucket; + } + bucket.add(prop); } - for (int i = 0; i < buckets.length; i++) { - for (java.util.Iterator it = buckets[i].iterator(); it.hasNext();) { - PropertyDeclaration prop = (PropertyDeclaration) it.next(); + for (List bucket : buckets) { + if (bucket == null) + continue; + for (PropertyDeclaration prop : bucket) { cascadedProperties.put(prop.getCSSName(), prop); } } } - - private CascadedStyle(CascadedStyle startingPoint, Iterator props) { - cascadedProperties = new TreeMap(startingPoint.cascadedProperties); - - addProperties(props); - } - - - /** - * Default constructor with no initialization. Don't use this to instantiate - * the class, as the class is immutable and this will leave it without any - * properties. - */ - private CascadedStyle() { - cascadedProperties = new TreeMap(); - } /** * Get an empty singleton, used to negate inheritance of properties @@ -186,10 +190,8 @@ private CascadedStyle() { * @return True if the property is defined in this set. */ public boolean hasProperty(CSSName cssName) { - return cascadedProperties.get( cssName ) != null; + return cascadedProperties.get(cssName) != null; } - - /** * Returns a {@link com.openhtmltopdf.css.sheet.PropertyDeclaration} by CSS * property name, e.g. "font-family". Properties are already cascaded during @@ -201,9 +203,7 @@ public boolean hasProperty(CSSName cssName) { * if not found. */ public PropertyDeclaration propertyByName(CSSName cssName) { - PropertyDeclaration prop = (PropertyDeclaration)cascadedProperties.get(cssName); - - return prop; + return cascadedProperties.get(cssName); } /** @@ -227,23 +227,17 @@ public IdentValue getIdent(CSSName cssName) { * * @return Iterator over a set of properly cascaded PropertyDeclarations. */ - public java.util.Iterator getCascadedPropertyDeclarations() { - List list = new ArrayList(cascadedProperties.size()); - Iterator iter = cascadedProperties.values().iterator(); - while ( iter.hasNext()) { - list.add(iter.next()); - } - return list.iterator(); + public java.util.Collection getCascadedPropertyDeclarations() { + return cascadedProperties.values(); } public int countAssigned() { return cascadedProperties.size(); } public String getFingerprint() { if (this.fingerprint == null) { - StringBuffer sb = new StringBuffer(); - Iterator iter = cascadedProperties.values().iterator(); - while (iter.hasNext()) { - sb.append(((PropertyDeclaration)iter.next()).getFingerprint()); + StringBuilder sb = new StringBuilder(); + for (PropertyDeclaration o : cascadedProperties.values()) { + sb.append(o.getFingerprint()); } this.fingerprint = sb.toString(); } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/Matcher.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/Matcher.java index e8caefd70..82d5f650a 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/Matcher.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/Matcher.java @@ -31,6 +31,7 @@ import java.util.Set; import java.util.TreeMap; +import com.openhtmltopdf.css.constants.MarginBoxName; import com.openhtmltopdf.css.extend.AttributeResolver; import com.openhtmltopdf.css.extend.StylesheetFactory; import com.openhtmltopdf.css.extend.TreeResolver; @@ -44,30 +45,30 @@ */ public class Matcher { - Mapper docMapper; + private Mapper docMapper; private com.openhtmltopdf.css.extend.AttributeResolver _attRes; private com.openhtmltopdf.css.extend.TreeResolver _treeRes; private com.openhtmltopdf.css.extend.StylesheetFactory _styleFactory; - private java.util.Map _map; + private java.util.Map _map; //handle dynamic - private Set _hoverElements; - private Set _activeElements; - private Set _focusElements; - private Set _visitElements; + private Set _hoverElements; + private Set _activeElements; + private Set _focusElements; + private Set _visitElements; - private List _pageRules; + private List _pageRules; private List _fontFaceRules; public Matcher( - TreeResolver tr, AttributeResolver ar, StylesheetFactory factory, List stylesheets, String medium) { + TreeResolver tr, AttributeResolver ar, StylesheetFactory factory, List stylesheets, String medium) { newMaps(); _treeRes = tr; _attRes = ar; _styleFactory = factory; - _pageRules = new ArrayList(); + _pageRules = new ArrayList(); _fontFaceRules = new ArrayList(); docMapper = createDocumentMapper(stylesheets, medium); } @@ -77,7 +78,7 @@ public void removeStyle(Object e) { } public CascadedStyle getCascadedStyle(Object e, boolean restyle) { - synchronized (e) { + //synchronized (e) { Mapper em; if (!restyle) { em = getMapper(e); @@ -85,7 +86,7 @@ public CascadedStyle getCascadedStyle(Object e, boolean restyle) { em = matchElement(e); } return em.getCascadedStyle(e); - } + //} } /** @@ -93,26 +94,24 @@ public CascadedStyle getCascadedStyle(Object e, boolean restyle) { * We assume that restyle has already been done by a getCascadedStyle if necessary. */ public CascadedStyle getPECascadedStyle(Object e, String pseudoElement) { - synchronized (e) { + //synchronized (e) { Mapper em = getMapper(e); return em.getPECascadedStyle(e, pseudoElement); - } + //} } public PageInfo getPageCascadedStyle(String pageName, String pseudoPage) { - List props = new ArrayList(); - Map marginBoxes = new HashMap(); + List props = new ArrayList (); + Map> marginBoxes = new HashMap>(); - for (Iterator i = _pageRules.iterator(); i.hasNext(); ) { - PageRule pageRule = (PageRule)i.next(); - + for (PageRule pageRule : _pageRules) { if (pageRule.applies(pageName, pseudoPage)) { props.addAll(pageRule.getRuleset().getPropertyDeclarations()); marginBoxes.putAll(pageRule.getMarginBoxes()); } } - CascadedStyle style = null; + CascadedStyle style; if (props.isEmpty()) { style = CascadedStyle.emptyCascadedStyle; } else { @@ -143,7 +142,7 @@ public boolean isFocusStyled(Object e) { } protected Mapper matchElement(Object e) { - synchronized (e) { + //synchronized (e) { Object parent = _treeRes.getParentElement(e); Mapper child; if (parent != null) { @@ -153,39 +152,36 @@ protected Mapper matchElement(Object e) { child = docMapper.mapChild(e); } return child; - } + //} } - Mapper createDocumentMapper(List stylesheets, String medium) { - java.util.TreeMap sorter = new java.util.TreeMap(); + Mapper createDocumentMapper(List stylesheets, String medium) { + java.util.TreeMap sorter = new java.util.TreeMap(); addAllStylesheets(stylesheets, sorter, medium); XRLog.match("Matcher created with " + sorter.size() + " selectors"); return new Mapper(sorter.values()); } - private void addAllStylesheets(List stylesheets, TreeMap sorter, String medium) { + private void addAllStylesheets(List stylesheets, TreeMap sorter, String medium) { int count = 0; int pCount = 0; - for (Iterator i = stylesheets.iterator(); i.hasNext(); ) { - Stylesheet stylesheet = (Stylesheet)i.next(); - for (Iterator j = stylesheet.getContents().iterator(); j.hasNext(); ) { - Object obj = (Object)j.next(); + for (Stylesheet stylesheet : stylesheets) { + for (Object obj : stylesheet.getContents()) { if (obj instanceof Ruleset) { - for (Iterator k = ((Ruleset)obj).getFSSelectors().iterator(); k.hasNext(); ) { - Selector selector = (Selector)k.next(); + for (Selector selector : ((Ruleset) obj).getFSSelectors()) { selector.setPos(++count); sorter.put(selector.getOrder(), selector); } } else if (obj instanceof PageRule) { - ((PageRule)obj).setPos(++pCount); - _pageRules.add(obj); + ((PageRule) obj).setPos(++pCount); + _pageRules.add((PageRule) obj); } else if (obj instanceof MediaRule) { - MediaRule mediaRule = (MediaRule)obj; + MediaRule mediaRule = (MediaRule) obj; if (mediaRule.matches(medium)) { - for (Iterator k = mediaRule.getContents().iterator(); k.hasNext(); ) { - Ruleset ruleset = (Ruleset)k.next(); - for (Iterator l = ruleset.getFSSelectors().iterator(); l.hasNext(); ) { - Selector selector = (Selector)l.next(); + for (Object o : mediaRule.getContents()) { + Ruleset ruleset = (Ruleset) o; + for (Object o1 : ruleset.getFSSelectors()) { + Selector selector = (Selector) o1; selector.setPos(++count); sorter.put(selector.getOrder(), selector); } @@ -193,15 +189,12 @@ private void addAllStylesheets(List stylesheets, TreeMap sorter, String medium) } } } - + _fontFaceRules.addAll(stylesheet.getFontFaceRules()); } - Collections.sort(_pageRules, new Comparator() { - public int compare(Object o1, Object o2) { - PageRule p1 = (PageRule)o1; - PageRule p2 = (PageRule)o2; - + Collections.sort(_pageRules, new Comparator() { + public int compare(PageRule p1, PageRule p2) { if (p1.getOrder() - p2.getOrder() < 0) { return -1; } else if (p1.getOrder() == p2.getOrder()) { @@ -218,15 +211,15 @@ private void link(Object e, Mapper m) { } private void newMaps() { - _map = Collections.synchronizedMap(new java.util.HashMap()); - _hoverElements = Collections.synchronizedSet(new java.util.HashSet()); - _activeElements = Collections.synchronizedSet(new java.util.HashSet()); - _focusElements = Collections.synchronizedSet(new java.util.HashSet()); - _visitElements = Collections.synchronizedSet(new java.util.HashSet()); + _map = new java.util.HashMap(); + _hoverElements = new java.util.HashSet(); + _activeElements = new java.util.HashSet(); + _focusElements = new java.util.HashSet(); + _visitElements = new java.util.HashSet(); } private Mapper getMapper(Object e) { - Mapper m = (Mapper) _map.get(e); + Mapper m = _map.get(e); if (m != null) { return m; } @@ -282,7 +275,7 @@ public void remove() { } private com.openhtmltopdf.css.sheet.Ruleset getElementStyle(Object e) { - synchronized (e) { + //synchronized (e) { if (_attRes == null || _styleFactory == null) { return null; } @@ -293,11 +286,11 @@ private com.openhtmltopdf.css.sheet.Ruleset getElementStyle(Object e) { } return _styleFactory.parseStyleDeclaration(com.openhtmltopdf.css.sheet.StylesheetInfo.AUTHOR, style); - } + //} } private com.openhtmltopdf.css.sheet.Ruleset getNonCssStyle(Object e) { - synchronized (e) { + //synchronized (e) { if (_attRes == null || _styleFactory == null) { return null; } @@ -306,7 +299,7 @@ private com.openhtmltopdf.css.sheet.Ruleset getNonCssStyle(Object e) { return null; } return _styleFactory.parseStyleDeclaration(com.openhtmltopdf.css.sheet.StylesheetInfo.AUTHOR, style); - } + //} } /** @@ -317,13 +310,12 @@ private com.openhtmltopdf.css.sheet.Ruleset getNonCssStyle(Object e) { */ class Mapper { java.util.List axes; - private HashMap pseudoSelectors; - private List mappedSelectors; - private HashMap children; + private HashMap> pseudoSelectors; + private List mappedSelectors; + private Map children; - Mapper(java.util.Collection selectors) { - axes = new java.util.ArrayList(selectors.size()); - axes.addAll(selectors); + Mapper(java.util.Collection selectors) { + axes = new java.util.ArrayList(selectors); } private Mapper() { @@ -338,12 +330,12 @@ private Mapper() { */ Mapper mapChild(Object e) { //Mapper childMapper = new Mapper(); - java.util.List childAxes = new ArrayList(axes.size() + 10); - java.util.HashMap pseudoSelectors = new java.util.HashMap(); - java.util.List mappedSelectors = new java.util.LinkedList(); - StringBuffer key = new StringBuffer(); - for (int i = 0, size = axes.size(); i < size; i++) { - Selector sel = (Selector) axes.get(i); + java.util.List childAxes = new ArrayList(axes.size() + 10); + java.util.HashMap> pseudoSelectors = new java.util.HashMap>(); + java.util.List mappedSelectors = new java.util.ArrayList(); + StringBuilder key = new StringBuilder(); + for (Object axe : axes) { + Selector sel = (Selector) axe; if (sel.getAxis() == Selector.DESCENDANT_AXIS) { //carry it forward to other descendants childAxes.add(sel); @@ -356,9 +348,9 @@ Mapper mapChild(Object e) { //Assumption: if it is a pseudo-element, it does not also have dynamic pseudo-class String pseudoElement = sel.getPseudoElement(); if (pseudoElement != null) { - java.util.List l = (java.util.List) pseudoSelectors.get(pseudoElement); + List l = pseudoSelectors.get(pseudoElement); if (l == null) { - l = new java.util.LinkedList(); + l = new ArrayList(); pseudoSelectors.put(pseudoElement, l); } l.add(sel); @@ -390,8 +382,8 @@ Mapper mapChild(Object e) { childAxes.add(chain); } } - if (children == null) children = new HashMap(); - Mapper childMapper = (Mapper) children.get(key.toString()); + if (children == null) children = new HashMap(); + Mapper childMapper = children.get(key.toString()); if (childMapper == null) { childMapper = new Mapper(); childMapper.axes = childAxes; @@ -405,11 +397,11 @@ Mapper mapChild(Object e) { CascadedStyle getCascadedStyle(Object e) { CascadedStyle result; - synchronized (e) { + //synchronized (e) { CascadedStyle cs = null; com.openhtmltopdf.css.sheet.Ruleset elementStyling = getElementStyle(e); com.openhtmltopdf.css.sheet.Ruleset nonCssStyling = getNonCssStyle(e); - List propList = new LinkedList(); + List propList = new ArrayList(); //specificity 0,0,0,0 if (nonCssStyling != null) { propList.addAll(nonCssStyling.getPropertyDeclarations()); @@ -430,7 +422,7 @@ CascadedStyle getCascadedStyle(Object e) { } result = cs; - } + //} return result; } @@ -439,15 +431,15 @@ CascadedStyle getCascadedStyle(Object e) { * We assume that restyle has already been done by a getCascadedStyle if necessary. */ public CascadedStyle getPECascadedStyle(Object e, String pseudoElement) { - java.util.Iterator si = pseudoSelectors.entrySet().iterator(); + java.util.Iterator>> si = pseudoSelectors.entrySet().iterator(); if (!si.hasNext()) { return null; } CascadedStyle cs = null; - java.util.List pe = (java.util.List) pseudoSelectors.get(pseudoElement); + java.util.List pe = pseudoSelectors.get(pseudoElement); if (pe == null) return null; - java.util.List propList = new java.util.LinkedList(); + java.util.List propList = new java.util.ArrayList(); for (java.util.Iterator i = getSelectedRulesets(pe); i.hasNext();) { com.openhtmltopdf.css.sheet.Ruleset rs = (com.openhtmltopdf.css.sheet.Ruleset) i.next(); propList.addAll(rs.getPropertyDeclarations()); diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/PageInfo.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/PageInfo.java index b3eddf023..5dc185a92 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/PageInfo.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/newmatch/PageInfo.java @@ -33,16 +33,16 @@ public class PageInfo { private final List _properties; private final CascadedStyle _pageStyle; - private final Map _marginBoxes; + private final Map> _marginBoxes; private final List _xmpPropertyList; - public PageInfo(List properties, CascadedStyle pageStyle, Map marginBoxes) { + public PageInfo(List properties, CascadedStyle pageStyle, Map> marginBoxes) { _properties = properties; _pageStyle = pageStyle; _marginBoxes = marginBoxes; - _xmpPropertyList = (List)marginBoxes.remove(MarginBoxName.FS_PDF_XMP_METADATA); + _xmpPropertyList = marginBoxes.remove(MarginBoxName.FS_PDF_XMP_METADATA); } public Map getMarginBoxes() { @@ -58,18 +58,18 @@ public List getProperties() { } public CascadedStyle createMarginBoxStyle(MarginBoxName marginBox, boolean alwaysCreate) { - List marginProps = (List)_marginBoxes.get(marginBox); + List marginProps = _marginBoxes.get(marginBox); if ((marginProps == null || marginProps.size() == 0) && ! alwaysCreate) { return null; } - List all; + List all; if (marginProps != null) { - all = new ArrayList(marginProps.size() + 3); + all = new ArrayList(marginProps.size() + 3); all.addAll(marginProps); } else { - all = new ArrayList(3); + all = new ArrayList(3); } all.add(CascadedStyle.createLayoutPropertyDeclaration(CSSName.DISPLAY, IdentValue.TABLE_CELL)); @@ -89,8 +89,8 @@ public CascadedStyle createMarginBoxStyle(MarginBoxName marginBox, boolean alway } public boolean hasAny(MarginBoxName[] marginBoxes) { - for (int i = 0; i < marginBoxes.length; i++) { - if (_marginBoxes.containsKey(marginBoxes[i])) { + for (MarginBoxName marginBox : marginBoxes) { + if (_marginBoxes.containsKey(marginBox)) { return true; } } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/CSSParseException.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/CSSParseException.java index 32beb7944..73ab731cd 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/CSSParseException.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/CSSParseException.java @@ -46,7 +46,7 @@ public CSSParseException(Token found, Token expected, int line) { public CSSParseException(Token found, Token[] expected, int line) { _found = found; - _expected = expected == null ? new Token[]{} : (Token[]) expected.clone(); + _expected = expected == null ? new Token[]{} : expected.clone(); _line = line; _genericMessage = null; } @@ -65,7 +65,7 @@ private String descr(Token[] tokens) { if (tokens.length == 1) { return tokens[0].getExternalName(); } else { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); if (tokens.length > 2) { result.append("one of "); } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/CSSParser.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/CSSParser.java index aa3e2c812..27389a3ed 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/CSSParser.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/CSSParser.java @@ -1979,7 +1979,7 @@ private static boolean isHexChar(char c) { } private static String processEscapes(char[] ch, int start, int end) { - StringBuffer result = new StringBuffer(ch.length + 10); + StringBuilder result = new StringBuilder(ch.length + 10); for (int i = start; i < end; i++) { char c = ch[i]; diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/MakeTokens.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/MakeTokens.java index 1d439b9d0..f13ce0e9e 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/MakeTokens.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/MakeTokens.java @@ -51,8 +51,8 @@ public static final void main(String[] args) throws IOException { } } } - - StringBuffer buf = new StringBuffer(); + + StringBuilder buf = new StringBuilder(); int offset = 1; for (Iterator i = tokens.iterator(); i.hasNext(); offset++) { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/ParserTest.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/ParserTest.java index d3207c18b..636c82410 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/ParserTest.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/ParserTest.java @@ -24,7 +24,7 @@ public class ParserTest { public static void main(String[] args) throws Exception { String test = "div { background-image: url('something') }\n"; - StringBuffer longTest = new StringBuffer(); + StringBuilder longTest = new StringBuilder(); for (int i = 0 ; i < 10000; i++) { longTest.append(test); } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/property/PrimitivePropertyBuilders.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/property/PrimitivePropertyBuilders.java index e965090a5..82a124033 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/property/PrimitivePropertyBuilders.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/parser/property/PrimitivePropertyBuilders.java @@ -934,7 +934,7 @@ public List buildDeclarations( } private String concat(List strings, char separator) { - StringBuffer buf = new StringBuffer(64); + StringBuilder buf = new StringBuilder(64); for (Iterator i = strings.iterator(); i.hasNext(); ) { String s = (String)i.next(); buf.append(s); diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/sheet/PageRule.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/sheet/PageRule.java index a6c26b527..79655bdd4 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/sheet/PageRule.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/sheet/PageRule.java @@ -31,7 +31,7 @@ public class PageRule implements RulesetContainer { private Ruleset _ruleset; private int _origin; - private Map _marginBoxes = new HashMap(); + private Map> _marginBoxes = new HashMap>(); private int _pos; @@ -88,15 +88,15 @@ public void setName(String name) { _specificityF = 1; } - public List getMarginBoxProperties(MarginBoxName name) { - return (List)_marginBoxes.get(name); + public List getMarginBoxProperties(MarginBoxName name) { + return _marginBoxes.get(name); } - public void addMarginBoxProperties(MarginBoxName name, List props) { + public void addMarginBoxProperties(MarginBoxName name, List props) { _marginBoxes.put(name, props); } - public Map getMarginBoxes() { + public Map> getMarginBoxes() { return _marginBoxes; } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/sheet/Ruleset.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/sheet/Ruleset.java index f6b7b6d2f..5dc9ec4d4 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/sheet/Ruleset.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/sheet/Ruleset.java @@ -33,14 +33,14 @@ */ public class Ruleset { private int _origin; - private java.util.List _props; + private java.util.List _props; - private List _fsSelectors = new ArrayList(); + private List _fsSelectors; public Ruleset(int orig) { _origin = orig; - _props = new LinkedList(); - _fsSelectors = new LinkedList(); + _props = new ArrayList(); + _fsSelectors = new ArrayList(); } /** @@ -49,7 +49,7 @@ public Ruleset(int orig) { * * @return The propertyDeclarations value */ - public List getPropertyDeclarations() { + public List getPropertyDeclarations() { return Collections.unmodifiableList(_props); } @@ -57,7 +57,7 @@ public void addProperty(PropertyDeclaration decl) { _props.add(decl); } - public void addAllProperties(List props) { + public void addAllProperties(List props) { _props.addAll(props); } @@ -65,7 +65,7 @@ public void addFSSelector(Selector selector) { _fsSelectors.add(selector); } - public List getFSSelectors() { + public List getFSSelectors() { return _fsSelectors; } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/sheet/Stylesheet.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/sheet/Stylesheet.java index cdd7f885c..840b0ac0c 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/sheet/Stylesheet.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/sheet/Stylesheet.java @@ -44,8 +44,8 @@ public class Stylesheet implements RulesetContainer { */ private int _origin; - private List _fontFaceRules = new ArrayList(); - private List _importRules = new ArrayList(); + private List _fontFaceRules = new ArrayList(); + private List _importRules = new ArrayList(); private List _contents = new ArrayList(); /** @@ -105,7 +105,7 @@ public void addFontFaceRule(FontFaceRule rule) { _fontFaceRules.add(rule); } - public List getFontFaceRules() { + public List getFontFaceRules() { return _fontFaceRules; } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/style/CalculatedStyle.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/style/CalculatedStyle.java index 00e2e1d50..3b44e2303 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/style/CalculatedStyle.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/style/CalculatedStyle.java @@ -61,7 +61,7 @@ * when this style is created. A property retrieved by name should always have * only one value in this class (e.g. one-one map). Any methods to retrieve * property values from an instance of this class require a valid {@link - * org.xhtmlrenderer.layout.Context} be given to it, for some cases of property + * com.openhtmltopdf.layout.Context} be given to it, for some cases of property * resolution. Generally, a programmer will not use this class directly, but * will retrieve properties using a {@link com.openhtmltopdf.context.StyleReference} * implementation. @@ -94,7 +94,7 @@ public class CalculatedStyle { /** * Cache child styles of this style that have the same cascaded properties */ - private final java.util.HashMap _childCache = new java.util.HashMap(); + private final java.util.Map _childCache = new java.util.HashMap(); /*private java.util.HashMap _childCache = new java.util.LinkedHashMap(5, 0.75f, true) { private static final int MAX_ENTRIES = 10; @@ -179,7 +179,7 @@ private void checkBordersAllowed() { */ public synchronized CalculatedStyle deriveStyle(CascadedStyle matched) { String fingerprint = matched.getFingerprint(); - CalculatedStyle cs = (CalculatedStyle) _childCache.get(fingerprint); + CalculatedStyle cs = _childCache.get(fingerprint); if (cs == null) { cs = new CalculatedStyle(this, matched); @@ -603,9 +603,7 @@ private void derive(CascadedStyle matched) { return; }//nothing to derive - Iterator mProps = matched.getCascadedPropertyDeclarations(); - while (mProps.hasNext()) { - PropertyDeclaration pd = (PropertyDeclaration) mProps.next(); + for (PropertyDeclaration pd : matched.getCascadedPropertyDeclarations()) { FSDerivedValue val = deriveValue(pd.getCSSName(), pd.getValue()); _derivedValuesById[pd.getCSSName().FS_ID] = val; } @@ -616,7 +614,7 @@ private FSDerivedValue deriveValue(CSSName cssName, org.w3c.dom.css.CSSPrimitive } private String genStyleKey() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < _derivedValuesById.length; i++) { CSSName name = CSSName.getByID(i); FSDerivedValue val = _derivedValuesById[i]; @@ -976,12 +974,9 @@ public boolean requiresLayer() { } IdentValue overflow = getIdent(CSSName.OVERFLOW); - if ((overflow == IdentValue.SCROLL || overflow == IdentValue.AUTO) && - isOverflowApplies()) { - return true; - } + return (overflow == IdentValue.SCROLL || overflow == IdentValue.AUTO) && + isOverflowApplies(); - return false; } } @@ -994,7 +989,7 @@ public String getRunningName() { FunctionValue value = (FunctionValue)valueByName(CSSName.POSITION); FSFunction function = value.getFunction(); - PropertyValue param = (PropertyValue)function.getParameters().get(0); + PropertyValue param = function.getParameters().get(0); return param.getStringValue(); } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/style/Length.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/style/Length.java index d0e77cfa3..edd5636c5 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/style/Length.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/style/Length.java @@ -96,7 +96,7 @@ public long minWidth(int maxWidth) { } public String toString() { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); result.append("(type="); switch (_type) { case FIXED: diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/style/derived/LengthValue.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/style/derived/LengthValue.java index 29c387d3a..38658511a 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/style/derived/LengthValue.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/style/derived/LengthValue.java @@ -197,7 +197,7 @@ public static float calcFloatProportionalValue(CalculatedStyle style, } double d = Math.round((double) absVal); - absVal = new Float(d).floatValue(); + absVal = (float)d; return absVal; } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/value/FontSpecification.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/value/FontSpecification.java index 780177736..ae2a45d86 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/value/FontSpecification.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/css/value/FontSpecification.java @@ -19,7 +19,7 @@ public class FontSpecification { public IdentValue variant; public String toString() { - StringBuffer sb = new StringBuffer("Font specification: "); + StringBuilder sb = new StringBuilder("Font specification: "); sb .append(" families: " + Arrays.asList(families).toString()) .append(" size: " + size) diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxBuilder.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxBuilder.java index 7f1788aa4..c0db1e07e 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxBuilder.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxBuilder.java @@ -543,11 +543,11 @@ private static void createAnonymousTableContent(LayoutContext c, BlockBox source * If not, the table is returned. */ private static BlockBox reorderTableContent(LayoutContext c, TableBox table) { - List topCaptions = new LinkedList(); + List topCaptions = new ArrayList(); Box header = null; - List bodies = new LinkedList(); + List bodies = new ArrayList(); Box footer = null; - List bottomCaptions = new LinkedList(); + List bottomCaptions = new ArrayList(); for (Iterator i = table.getChildIterator(); i.hasNext();) { Box b = (Box) i.next(); @@ -1357,8 +1357,8 @@ private static void insertAnonymousBlocks( SharedContext c, Box parent, List children, boolean layoutRunningBlocks) { List inline = new ArrayList(); - LinkedList parents = new LinkedList(); - List savedParents = null; + LinkedList parents = new LinkedList(); + List savedParents = null; for (Iterator i = children.iterator(); i.hasNext();) { Styleable child = (Styleable) i.next(); @@ -1379,7 +1379,7 @@ private static void insertAnonymousBlocks( if (inline.size() > 0) { createAnonymousBlock(c, parent, inline, savedParents); inline = new ArrayList(); - savedParents = new ArrayList(parents); + savedParents = new ArrayList(parents); } parent.addChild((Box) child); } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxRangeHelper.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxRangeHelper.java index c2215deca..030853e01 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxRangeHelper.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/BoxRangeHelper.java @@ -27,7 +27,7 @@ import com.openhtmltopdf.util.XRRuntimeException; public class BoxRangeHelper { - private LinkedList _clipRegionStack = new LinkedList(); + private LinkedList _clipRegionStack = new LinkedList(); private OutputDevice _outputDevice; private List _rangeList; @@ -67,7 +67,7 @@ public void pushClipRegion(RenderingContext c, int contentIndex) { public void popClipRegions(RenderingContext c, int contentIndex) { while (_clipRegionStack.size() > 0) { - BoxRangeData data = (BoxRangeData)_clipRegionStack.getLast(); + BoxRangeData data = _clipRegionStack.getLast(); if (data.getRange().getEnd() == contentIndex) { _outputDevice.setClip(data.getClip()); _clipRegionStack.removeLast(); diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/CounterFunction.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/CounterFunction.java index 8413a6467..238bcfa18 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/CounterFunction.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/layout/CounterFunction.java @@ -41,15 +41,16 @@ public CounterFunction(List counterValues, String separator, IdentValue listStyl _listStyleType = listStyleType; } - public String evaluate() { - if (_counterValues == null) { - return createCounterText(_listStyleType, _counterValue); - } - StringBuffer sb = new StringBuffer(); - for (Iterator i = _counterValues.iterator(); i.hasNext();) { - Integer value = (Integer) i.next(); - sb.append(createCounterText(_listStyleType, value.intValue())); - if (i.hasNext()) sb.append(_separator); + private static String toRoman(int val) { + int[] ints = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; + String[] nums = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < ints.length; i++) { + int count = val / ints[i]; + for (int j = 0; j < count; j++) { + sb.append(nums[i]); + } + val -= ints[i] * count; } return sb.toString(); } @@ -83,17 +84,15 @@ private static String toLatin(int val) { } return result; } - - private static String toRoman(int val) { - int[] ints = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; - String[] nums = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < ints.length; i++) { - int count = (int) (val / ints[i]); - for (int j = 0; j < count; j++) { - sb.append(nums[i]); - } - val -= ints[i] * count; + public String evaluate() { + if (_counterValues == null) { + return createCounterText(_listStyleType, _counterValue); + } + StringBuilder sb = new StringBuilder(); + for (Iterator i = _counterValues.iterator(); i.hasNext();) { + Integer value = (Integer) i.next(); + sb.append(createCounterText(_listStyleType, value.intValue())); + if (i.hasNext()) sb.append(_separator); } return sb.toString(); } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/newtable/TableRowBox.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/newtable/TableRowBox.java index 9a68f2659..624b61247 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/newtable/TableRowBox.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/newtable/TableRowBox.java @@ -523,7 +523,7 @@ public void exportText(RenderingContext c, Writer writer) throws IOException { for (Iterator i = getChildIterator(); i.hasNext(); ) { TableCellBox cell = (TableCellBox)i.next(); - StringBuffer buffer = new StringBuffer(); + StringBuilder buffer = new StringBuilder(); cell.collectText(c, buffer); writer.write(buffer.toString().trim()); int cSpan = cell.getStyle().getColSpan(); diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/BlockBox.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/BlockBox.java index 49367cd30..98a2f19b3 100755 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/BlockBox.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/BlockBox.java @@ -83,7 +83,7 @@ public class BlockBox extends Box implements InlinePaintable { private int _childrenContentType; - private List _inlineContent; + private List _inlineContent; private boolean _topMarginCalculated; private boolean _bottomMarginCalculated; @@ -122,7 +122,7 @@ protected String getExtraBoxDescription() { } public String toString() { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); String className = getClass().getName(); result.append(className.substring(className.lastIndexOf('.') + 1)); result.append(": "); @@ -168,7 +168,7 @@ public String toString() { return result.toString(); } - protected void appendPositioningInfo(StringBuffer result) { + protected void appendPositioningInfo(StringBuilder result) { if (getStyle().isRelative()) { result.append("(relative) "); } @@ -184,7 +184,7 @@ protected void appendPositioningInfo(StringBuffer result) { } public String dump(LayoutContext c, String indent, int which) { - StringBuffer result = new StringBuffer(indent); + StringBuilder result = new StringBuilder(indent); ensureChildren(c); @@ -1053,7 +1053,7 @@ private void satisfyWidowsAndOrphans(LayoutContext c, int contentStart, boolean noContentLBs = 0; i = cCount-1; - while (i >= 0 && ((LineBox)getChild(i)).getAbsY() >= lastPage.getTop()) { + while (i >= 0 && getChild(i).getAbsY() >= lastPage.getTop()) { LineBox lB = (LineBox)getChild(i); if (lB.getAbsY() < lastPage.getTop()) { break; @@ -1089,15 +1089,14 @@ public void setChildrenContentType(int contentType) { _childrenContentType = contentType; } - public List getInlineContent() { + public List getInlineContent() { return _inlineContent; } - public void setInlineContent(List inlineContent) { + public void setInlineContent(List inlineContent) { _inlineContent = inlineContent; if (inlineContent != null) { - for (Iterator i = inlineContent.iterator(); i.hasNext();) { - Styleable child = (Styleable) i.next(); + for (Styleable child : inlineContent) { if (child instanceof Box) { ((Box) child).setContainingBlock(this); } @@ -1394,11 +1393,7 @@ public boolean isAutoHeight() { Box cb = getContainingBlock(); if (cb.isStyled() && (cb instanceof BlockBox)) { return ((BlockBox)cb).isAutoHeight(); - } else if (cb instanceof BlockBox && ((BlockBox)cb).isInitialContainingBlock()) { - return false; - } else { - return true; - } + } else return !(cb instanceof BlockBox) || !cb.isInitialContainingBlock(); } } @@ -1656,9 +1651,7 @@ private void calcMinMaxWidthInlineChildren(LayoutContext c) { InlineBox trimmableIB = null; - for (Iterator i = _inlineContent.iterator(); i.hasNext();) { - Styleable child = (Styleable) i.next(); - + for (Styleable child : _inlineContent) { if (child.getStyle().isAbsolute() || child.getStyle().isFixed() || child.getStyle().isRunning()) { continue; } @@ -1782,10 +1775,10 @@ public void styleText(LayoutContext c) { // FIXME Should be expanded into generic restyle facility public void styleText(LayoutContext c, CalculatedStyle style) { if (getChildrenContentType() == CONTENT_INLINE) { - LinkedList styles = new LinkedList(); + LinkedList styles = new LinkedList(); styles.add(style); - for (Iterator i = _inlineContent.iterator(); i.hasNext();) { - Styleable child = (Styleable) i.next(); + for (Object a_inlineContent : _inlineContent) { + Styleable child = (Styleable) a_inlineContent; if (child instanceof InlineBox) { InlineBox iB = (InlineBox) child; @@ -1798,13 +1791,13 @@ public void styleText(LayoutContext c, CalculatedStyle style) { cs = c.getCss().getPseudoElementStyle( iB.getElement(), iB.getPseudoElementOrClass()); } - styles.add(((CalculatedStyle) styles.getLast()).deriveStyle(cs)); + styles.add(styles.getLast().deriveStyle(cs)); } else { styles.add(style.createAnonymousStyle(IdentValue.INLINE)); } } - iB.setStyle(((CalculatedStyle) styles.getLast())); + iB.setStyle(styles.getLast()); iB.applyTextTransform(); if (iB.isEndsHere()) { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/Box.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/Box.java index d6836b448..a44f60308 100755 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/Box.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/Box.java @@ -103,7 +103,7 @@ protected Box() { protected void dumpBoxes( LayoutContext c, String indent, List boxes, - int which, StringBuffer result) { + int which, StringBuilder result) { for (Iterator i = boxes.iterator(); i.hasNext(); ) { Box b = (Box)i.next(); result.append(b.dump(c, indent + " ", which)); @@ -118,7 +118,7 @@ public int getWidth() { } public String toString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("Box: "); sb.append(" (" + getAbsX() + "," + getAbsY() + ")->(" + getWidth() + " x " + getHeight() + ")"); return sb.toString(); @@ -602,7 +602,7 @@ public int forcePageBreakBefore(LayoutContext c, IdentValue pageBreakValue, bool } if (pageBreakCount == 2) { - page = (PageBox)c.getRootLayer().getPages().get(page.getPageNo()+1); + page = c.getRootLayer().getPages().get(page.getPageNo()+1); delta += page.getContentHeight(c); if (pendingPageName) { @@ -638,7 +638,7 @@ public void forcePageBreakAfter(LayoutContext c, IdentValue pageBreakValue) { } if (needSecondPageBreak) { - page = (PageBox)c.getRootLayer().getPages().get(page.getPageNo()+1); + page = c.getRootLayer().getPages().get(page.getPageNo()+1); delta += page.getContentHeight(c); if (page == c.getRootLayer().getLastPage()) { @@ -1005,7 +1005,7 @@ public void setBoxDimensions(BoxDimensions dimensions) { setHeight(dimensions.getHeight()); } - public void collectText(RenderingContext c, StringBuffer buffer) throws IOException { + public void collectText(RenderingContext c, StringBuilder buffer) { for (Iterator i = getChildIterator(); i.hasNext(); ) { Box b = (Box)i.next(); b.collectText(c, buffer); @@ -1014,7 +1014,7 @@ public void collectText(RenderingContext c, StringBuffer buffer) throws IOExcept public void exportText(RenderingContext c, Writer writer) throws IOException { if (c.isPrint() && isRoot()) { - c.setPage(0, (PageBox)c.getRootLayer().getPages().get(0)); + c.setPage(0, c.getRootLayer().getPages().get(0)); c.getPage().exportLeadingText(c, writer); } for (Iterator i = getChildIterator(); i.hasNext(); ) { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/InlineBox.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/InlineBox.java index 3eb478175..d18521470 100755 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/InlineBox.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/InlineBox.java @@ -403,7 +403,7 @@ public void setPseudoElementOrClass(String pseudoElementOrClass) { } public String toString() { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); result.append("InlineBox: "); if (getElement() != null) { result.append("<"); @@ -436,7 +436,7 @@ public String toString() { return result.toString(); } - protected void appendPositioningInfo(StringBuffer result) { + protected void appendPositioningInfo(StringBuilder result) { if (getStyle().isRelative()) { result.append("(relative) "); } @@ -455,7 +455,7 @@ private String shortText() { if (_text == null) { return null; } else { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); for (int i = 0; i < _text.length() && i < 40; i++) { char c = _text.charAt(i); if (c == '\n') { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/InlineLayoutBox.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/InlineLayoutBox.java index 8b0956bd9..81d344e72 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/InlineLayoutBox.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/InlineLayoutBox.java @@ -161,7 +161,7 @@ public int getInlineWidth(CssContext cssCtx) { public void prunePending() { if (getInlineChildCount() > 0) { for (int i = getInlineChildCount() - 1; i >= 0; i--) { - Object child = (Object)getInlineChild(i); + Object child = getInlineChild(i); if (! (child instanceof InlineLayoutBox)) { break; } @@ -304,7 +304,7 @@ public Rectangle getBorderEdge(int left, int top, CssContext cssCtx) { float marginLeft = 0; float marginRight = 0; if (_startsHere || _endsHere) { - RectPropertySet margin = (RectPropertySet)getMargin(cssCtx); + RectPropertySet margin = getMargin(cssCtx); if (_startsHere) { marginLeft = margin.left(); } @@ -328,7 +328,7 @@ public Rectangle getMarginEdge(int left, int top, CssContext cssCtx, int tx, int float marginLeft = 0; float marginRight = 0; if (_startsHere || _endsHere) { - RectPropertySet margin = (RectPropertySet)getMargin(cssCtx); + RectPropertySet margin = getMargin(cssCtx); if (_startsHere) { marginLeft = margin.left(); } @@ -361,7 +361,7 @@ public Rectangle getContentAreaEdge(int left, int top, CssContext cssCtx) { float paddingRight = 0; if (_startsHere || _endsHere) { - RectPropertySet margin = (RectPropertySet)getMargin(cssCtx); + RectPropertySet margin = getMargin(cssCtx); if (_startsHere) { marginLeft = margin.left(); borderLeft = border.left(); @@ -409,7 +409,7 @@ public void setInlineWidth(int inlineWidth) { public boolean isContainsVisibleContent() { for (int i = 0; i < getInlineChildCount(); i++) { - Object child = (Object)getInlineChild(i); + Object child = getInlineChild(i); if (child instanceof InlineText) { InlineText iT = (InlineText)child; if (! iT.isEmpty()) { @@ -463,7 +463,7 @@ private void addToContentList(List list) { list.add(this); for (int i = 0; i < getInlineChildCount(); i++) { - Object child = (Object)getInlineChild(i); + Object child = getInlineChild(i); if (child instanceof InlineLayoutBox) { ((InlineLayoutBox)child).addToContentList(list); } else if (child instanceof Box) { @@ -796,7 +796,7 @@ public void setContainingBlockWidth(int containingBlockWidth) { } public String toString() { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); result.append("InlineLayoutBox: "); if (getElement() != null) { result.append("<"); @@ -826,8 +826,8 @@ public String dump(LayoutContext c, String indent, int which) { if (which != Box.DUMP_RENDER) { throw new IllegalArgumentException(); } - - StringBuffer result = new StringBuffer(indent); + + StringBuilder result = new StringBuilder(indent); result.append(this); result.append('\n'); @@ -875,9 +875,9 @@ public Box getRestyleTarget() { return result.getParent(); } - public void collectText(RenderingContext c, StringBuffer buffer) throws IOException { + public void collectText(RenderingContext c, StringBuilder buffer) { for (Iterator i = getInlineChildren().iterator(); i.hasNext(); ) { - Object obj = (Object)i.next(); + Object obj = i.next(); if (obj instanceof InlineText) { buffer.append(((InlineText)obj).getTextExportText()); } else { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/InlineText.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/InlineText.java index f3d9cae61..d5af539aa 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/InlineText.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/InlineText.java @@ -182,7 +182,7 @@ public void updateDynamicValue(RenderingContext c) { } public String toString() { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); result.append("InlineText: "); if (_containedLF || isDynamicFunction()) { result.append("("); @@ -278,7 +278,7 @@ public void selectAll() { public String getTextExportText() { char[] ch = getSubstring().toCharArray(); - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); if (isTrimmedLeadingSpace()) { result.append(' '); } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/LineBox.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/LineBox.java index 9b32c140f..6f8636cc3 100755 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/LineBox.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/render/LineBox.java @@ -87,7 +87,7 @@ public String dump(LayoutContext c, String indent, int which) { throw new IllegalArgumentException(); } - StringBuffer result = new StringBuffer(indent); + StringBuilder result = new StringBuilder(indent); result.append(this); result.append('\n'); @@ -143,7 +143,7 @@ public void paintInline(RenderingContext c) { private void lookForDynamicFunctions(RenderingContext c) { if (getChildCount() > 0) { for (int i = 0; i < getChildCount(); i++) { - Box b = (Box)getChild(i); + Box b = getChild(i); if (b instanceof InlineLayoutBox) { ((InlineLayoutBox)b).lookForDynamicFunctions(c); } @@ -159,7 +159,7 @@ public boolean isFirstLine() { public void prunePendingInlineBoxes() { if (getChildCount() > 0) { for (int i = getChildCount() - 1; i >= 0; i--) { - Box b = (Box)getChild(i); + Box b = getChild(i); if (! (b instanceof InlineLayoutBox)) { break; } @@ -339,7 +339,7 @@ public Rectangle getPaintingClipEdge(CssContext cssCtx) { private boolean intersectsInlineBlocks(CssContext cssCtx, Shape clip) { for (int i = 0; i < getChildCount(); i++) { - Box child = (Box)getChild(i); + Box child = getChild(i); if (child instanceof InlineLayoutBox) { boolean possibleResult = ((InlineLayoutBox)child).intersectsInlineBlocks( cssCtx, clip); @@ -529,7 +529,7 @@ public boolean isContainsOnlyBlockLevelContent() { } for (int i = 0; i < getChildCount(); i++) { - Box b = (Box)getChild(i); + Box b = getChild(i); if (! (b instanceof BlockBox)) { return false; } @@ -589,7 +589,7 @@ public void selectAll() { super.selectAll(); } - public void collectText(RenderingContext c, StringBuffer buffer) throws IOException { + public void collectText(RenderingContext c, StringBuilder buffer) { for (Iterator i = getNonFlowContent().iterator(); i.hasNext(); ) { Box b = (Box)i.next(); b.collectText(c, buffer); @@ -612,7 +612,7 @@ public void exportText(RenderingContext c, Writer writer) throws IOException { } if (isContainsContent()) { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); collectText(c, result); writer.write(result.toString().trim()); writer.write(LINE_SEPARATOR); diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/URLUTF8Encoder.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/URLUTF8Encoder.java index a3bf86a87..ca1fafda6 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/URLUTF8Encoder.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/URLUTF8Encoder.java @@ -89,7 +89,7 @@ public class URLUTF8Encoder { * @return The encoded string */ public static String encode( String s ) { - StringBuffer sbuf = new StringBuffer(); + StringBuilder sbuf = new StringBuilder(); int len = s.length(); for ( int i = 0; i < len; i++ ) { int ch = s.charAt( i ); @@ -105,7 +105,7 @@ public static String encode( String s ) { * @return Returns */ public static String encode( char[] chars ) { - StringBuffer sbuf = new StringBuffer(); + StringBuilder sbuf = new StringBuilder(); int len = chars.length; for ( int i = 0; i < len; i++ ) { int ch = chars[i]; @@ -120,7 +120,7 @@ public static String encode( char[] chars ) { * @param sbuf PARAM * @param ch PARAM */ - private static void append( StringBuffer sbuf, int ch ) { + private static void append( StringBuilder sbuf, int ch ) { if ( 'A' <= ch && ch <= 'Z' ) {// 'A'..'Z' sbuf.append( (char)ch ); } else if ( 'a' <= ch && ch <= 'z' ) {// 'a'..'z' diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/XhtmlCssOnlyNamespaceHandler.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/XhtmlCssOnlyNamespaceHandler.java index 8ec57763b..31ce888df 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/XhtmlCssOnlyNamespaceHandler.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/XhtmlCssOnlyNamespaceHandler.java @@ -110,6 +110,59 @@ protected String getAttribute(Element e, String attrName) { return result.length() == 0 ? null : result; } + private static String readTextContent(Element element) { + StringBuilder result = new StringBuilder(); + Node current = element.getFirstChild(); + while (current != null) { + short nodeType = current.getNodeType(); + if (nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE) { + Text t = (Text)current; + result.append(t.getData()); + } + current = current.getNextSibling(); + } + return result.toString(); + } + private static String collapseWhiteSpace(String text) { + StringBuilder result = new StringBuilder(); + int l = text.length(); + for (int i = 0; i < l; i++) { + char c = text.charAt(i); + if (Character.isWhitespace(c)) { + result.append(' '); + while (++i < l) { + c = text.charAt(i); + if (! Character.isWhitespace(c)) { + i--; + break; + } + } + } else { + result.append(c); + } + } + return result.toString(); + } + /** + * Gets the linkUri attribute of the XhtmlNamespaceHandler object + * + * @param e PARAM + * @return The linkUri value + */ + public String getLinkUri(org.w3c.dom.Element e) { + String href = null; + if (e.getNodeName().equalsIgnoreCase("a") && e.hasAttribute("href")) { + href = e.getAttribute("href"); + } + return href; + } + public String getAnchorName(Element e) { + if (e != null && e.getNodeName().equalsIgnoreCase("a") && + e.hasAttribute("name")) { + return e.getAttribute("name"); + } + return null; + } /** * Gets the elementStyling attribute of the XhtmlNamespaceHandler object * @@ -117,7 +170,7 @@ protected String getAttribute(Element e, String attrName) { * @return The elementStyling value */ public String getElementStyling(org.w3c.dom.Element e) { - StringBuffer style = new StringBuffer(); + StringBuilder style = new StringBuilder(); if (e.getNodeName().equals("td") || e.getNodeName().equals("th")) { String s; s = getAttribute(e, "colspan"); @@ -165,63 +218,6 @@ public String getElementStyling(org.w3c.dom.Element e) { return style.toString(); } - /** - * Gets the linkUri attribute of the XhtmlNamespaceHandler object - * - * @param e PARAM - * @return The linkUri value - */ - public String getLinkUri(org.w3c.dom.Element e) { - String href = null; - if (e.getNodeName().equalsIgnoreCase("a") && e.hasAttribute("href")) { - href = e.getAttribute("href"); - } - return href; - } - - public String getAnchorName(Element e) { - if (e != null && e.getNodeName().equalsIgnoreCase("a") && - e.hasAttribute("name")) { - return e.getAttribute("name"); - } - return null; - } - - private static String readTextContent(Element element) { - StringBuffer result = new StringBuffer(); - Node current = element.getFirstChild(); - while (current != null) { - short nodeType = current.getNodeType(); - if (nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE) { - Text t = (Text)current; - result.append(t.getData()); - } - current = current.getNextSibling(); - } - return result.toString(); - } - - private static String collapseWhiteSpace(String text) { - StringBuffer result = new StringBuffer(); - int l = text.length(); - for (int i = 0; i < l; i++) { - char c = text.charAt(i); - if (Character.isWhitespace(c)) { - result.append(' '); - while (++i < l) { - c = text.charAt(i); - if (! Character.isWhitespace(c)) { - i--; - break; - } - } - } else { - result.append(c); - } - } - return result.toString(); - } - /** * Returns the title of the document as located in the contents of /html/head/title, or "" if none could be found. * @@ -254,7 +250,6 @@ private Element findFirstChild(Element parent, String targetName) { return null; } - protected StylesheetInfo readStyleElement(Element style) { String media = style.getAttribute("media"); if ("".equals(media)) { @@ -266,7 +261,7 @@ protected StylesheetInfo readStyleElement(Element style) { info.setTitle(style.getAttribute("title")); info.setOrigin(StylesheetInfo.AUTHOR); - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); Node current = style.getFirstChild(); while (current != null) { if (current instanceof CharacterData) { @@ -277,7 +272,7 @@ protected StylesheetInfo readStyleElement(Element style) { String css = buf.toString().trim(); if (css.length() > 0) { - info.setContent(css.toString()); + info.setContent(css); return info; } else { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/XhtmlForm.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/XhtmlForm.java index a10484fa0..261b1655d 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/XhtmlForm.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/XhtmlForm.java @@ -96,12 +96,9 @@ private static String createNewDefaultGroupName() { private static boolean isFormField(Element e) { String nodeName = e.getNodeName(); - - if (nodeName.equals("input") || nodeName.equals("select") || nodeName.equals("textarea")) { - return true; - } - - return false; + + return nodeName.equals("input") || nodeName.equals("select") || nodeName.equals("textarea"); + } public FormField addComponent(Element e, LayoutContext context, BlockBox box) { @@ -139,7 +136,20 @@ public void reset() { ((FormField) fields.next()).reset(); } } - + public static String collectText(Element e) { + StringBuilder result = new StringBuilder(); + Node node = e.getFirstChild(); + if (node != null) { + do { + short nodeType = node.getNodeType(); + if (nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE) { + Text text = (Text) node; + result.append(text.getData()); + } + } while ((node = node.getNextSibling()) != null); + } + return result.toString().trim(); + } public void submit(JComponent source) { // If we don't have a
to tell us what to do, don't // do anything. @@ -147,7 +157,7 @@ public void submit(JComponent source) { return; } - StringBuffer data = new StringBuffer(); + StringBuilder data = new StringBuilder(); String action = _parentFormElement.getAttribute("action"); data.append(action).append("?"); Iterator fields = _componentCache.entrySet().iterator(); @@ -156,37 +166,22 @@ public void submit(JComponent source) { Map.Entry entry = (Map.Entry) fields.next(); FormField field = (FormField) entry.getValue(); - + if (field.includeInSubmission(source)) { String [] dataStrings = field.getFormDataStrings(); - + for (int i = 0; i < dataStrings.length; i++) { if (!first) { data.append('&'); } - + data.append(dataStrings[i]); first=false; } } } - - if(_formSubmissionListener !=null) _formSubmissionListener.submit(data.toString()); - } - public static String collectText(Element e) { - StringBuffer result = new StringBuffer(); - Node node = e.getFirstChild(); - if (node != null) { - do { - short nodeType = node.getNodeType(); - if (nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE) { - Text text = (Text) node; - result.append(text.getData()); - } - } while ((node = node.getNextSibling()) != null); - } - return result.toString().trim(); + if(_formSubmissionListener !=null) _formSubmissionListener.submit(data.toString()); } private static class ButtonGroupWrapper { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/XhtmlNamespaceHandler.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/XhtmlNamespaceHandler.java index bef54555d..2e4e80fa1 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/XhtmlNamespaceHandler.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/extend/XhtmlNamespaceHandler.java @@ -107,19 +107,19 @@ private String applyTextareaStyles(Element e) { } private String applyBlockAlign(Element e) { - StringBuffer style = new StringBuffer(); + StringBuilder style = new StringBuilder(); applyTextAlign(e, style); return style.toString(); } private String applyImgStyles(Element e) { - StringBuffer style = new StringBuffer(); + StringBuilder style = new StringBuilder(); applyFloatingAlign(e, style); return style.toString(); } private String applyTableCellStyles(Element e) { - StringBuffer style = new StringBuffer(); + StringBuilder style = new StringBuilder(); String s; //check for cellpadding Element table = findTable(e); @@ -170,7 +170,7 @@ private String applyTableCellStyles(Element e) { } private String applyTableStyles(Element e) { - StringBuffer style = new StringBuffer(); + StringBuilder style = new StringBuilder(); String s; s = getAttribute(e, "width"); if (s != null) { @@ -213,12 +213,12 @@ private String applyTableStyles(Element e) { } private String applyTableRowStyles(Element e) { - StringBuffer style = new StringBuffer(); + StringBuilder style = new StringBuilder(); applyTableContentAlign(e, style); return style.toString(); } - private void applyFloatingAlign(Element e, StringBuffer style) { + private void applyFloatingAlign(Element e, StringBuilder style) { String s; s = getAttribute(e, "align"); if (s != null) { @@ -233,7 +233,7 @@ private void applyFloatingAlign(Element e, StringBuffer style) { } } - private void applyTextAlign(Element e, StringBuffer style) { + private void applyTextAlign(Element e, StringBuilder style) { String s; s = getAttribute(e, "align"); if (s != null) { @@ -247,7 +247,7 @@ private void applyTextAlign(Element e, StringBuffer style) { } } - private void applyTableContentAlign(Element e, StringBuffer style) { + private void applyTableContentAlign(Element e, StringBuilder style) { String s; s = getAttribute(e, "align"); if (s != null) { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/XhtmlForm.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/XhtmlForm.java index e1dec27ce..8d805063e 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/XhtmlForm.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/XhtmlForm.java @@ -42,9 +42,9 @@ public XhtmlForm(String action, String method) { _method = method; } - protected List _controls = new LinkedList(); + protected List _controls = new ArrayList(); - private List _listeners = new ArrayList(); + private List _listeners = new ArrayList(); public void addFormListener(FormListener listener) { _listeners.add(listener); @@ -55,8 +55,7 @@ public void removeFormListener(FormListener listener) { } public FormControl getControl(String name) { - for (Iterator iter = _controls.iterator(); iter.hasNext();) { - FormControl control = (FormControl) iter.next(); + for (FormControl control : _controls) { if (control.getName().equals(name)) { return control; } @@ -64,10 +63,9 @@ public FormControl getControl(String name) { return null; } - public List getAllControls(String name) { - List result = new ArrayList(); - for (Iterator iter = _controls.iterator(); iter.hasNext();) { - FormControl control = (FormControl) iter.next(); + public List getAllControls(String name) { + List result = new ArrayList(); + for (FormControl control : _controls) { if (control.getName().equals(name)) { result.add(control); } @@ -75,7 +73,7 @@ public List getAllControls(String name) { return result; } - public Iterator getControls() { + public Iterator getControls() { return _controls.iterator(); } @@ -120,26 +118,26 @@ public static FormControl createControl(XhtmlForm form, Element e) { } public void reset() { - for (Iterator iter = _listeners.iterator(); iter.hasNext();) { - ((FormListener) iter.next()).resetted(this); + for (FormListener _listener : _listeners) { + (_listener).resetted(this); } } public void submit() { // TODO other encodings than urlencode? - StringBuffer data = new StringBuffer(); + StringBuilder data = new StringBuilder(); for (Iterator iter = getControls(); iter.hasNext();) { FormControl control = (FormControl) iter.next(); if (control.isSuccessful()) { if (control.isMultiple()) { String[] values = control.getMultipleValues(); - for (int i = 0; i < values.length; i++) { + for (String value : values) { if (data.length() > 0) { data.append('&'); } data.append(URLUTF8Encoder.encode(control.getName())); data.append('='); - data.append(URLUTF8Encoder.encode(values[i])); + data.append(URLUTF8Encoder.encode(value)); } } else { if (data.length() > 0) { @@ -158,8 +156,8 @@ public void submit() { System.out.println("Method: ".concat(_method)); System.out.println("Data: ".concat(data.toString())); - for (Iterator iter = _listeners.iterator(); iter.hasNext();) { - ((FormListener) iter.next()).submitted(this); + for (FormListener _listener : _listeners) { + (_listener).submitted(this); } } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/XhtmlNamespaceHandler.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/XhtmlNamespaceHandler.java index 3f17c2739..54960c73f 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/XhtmlNamespaceHandler.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/XhtmlNamespaceHandler.java @@ -73,7 +73,7 @@ public String getNonCssStyling(Element e) { } private String applyImgStyles(Element e) { - StringBuffer style = new StringBuffer(); + StringBuilder style = new StringBuilder(); applyFloatingAlign(e, style); return style.toString(); } @@ -113,7 +113,7 @@ private String applyTextareaStyles(Element e) { } private String applyTableCellStyles(Element e) { - StringBuffer style = new StringBuffer(); + StringBuilder style = new StringBuilder(); String s; //check for cellpadding Element table = findTable(e); @@ -164,7 +164,7 @@ private String applyTableCellStyles(Element e) { } private String applyTableStyles(Element e) { - StringBuffer style = new StringBuffer(); + StringBuilder style = new StringBuilder(); String s; s = getAttribute(e, "width"); if (s != null) { @@ -207,12 +207,12 @@ private String applyTableStyles(Element e) { } private String applyTableRowStyles(Element e) { - StringBuffer style = new StringBuffer(); + StringBuilder style = new StringBuilder(); applyAlignment(e, style); return style.toString(); } - private void applyFloatingAlign(Element e, StringBuffer style) { + private void applyFloatingAlign(Element e, StringBuilder style) { String s; s = getAttribute(e, "align"); if (s != null) { @@ -227,7 +227,7 @@ private void applyFloatingAlign(Element e, StringBuffer style) { } } - private void applyAlignment(Element e, StringBuffer style) { + private void applyAlignment(Element e, StringBuilder style) { String s; s = getAttribute(e, "align"); if (s != null) { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/controls/AbstractControl.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/controls/AbstractControl.java index 6709aac25..d498f9ccd 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/controls/AbstractControl.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/simple/xhtml/controls/AbstractControl.java @@ -170,7 +170,7 @@ public void reset() { } public static String collectText(Element e) { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); Node node = e.getFirstChild(); if (node != null) { do { diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/GeneralUtil.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/GeneralUtil.java index e03e2c308..9bd6dac92 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/GeneralUtil.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/GeneralUtil.java @@ -131,7 +131,7 @@ public static void dumpShortException(Exception ex) { */ public static String trackBack(int cnt) { Exception ex = new Exception(); - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); List list = new ArrayList(cnt); StackTraceElement[] stes = ex.getStackTrace(); if (cnt >= stes.length) { @@ -146,12 +146,12 @@ public static String trackBack(int cnt) { sb.append(ste.getMethodName()); sb.append("(ln ").append(ste.getLineNumber()).append(")"); list.add(sb.toString()); - sb = new StringBuffer(); + sb = new StringBuilder(); } Iterator iter = list.iterator(); - StringBuffer padding = new StringBuffer(""); - StringBuffer trackback = new StringBuffer(); + StringBuilder padding = new StringBuilder(); + StringBuilder trackback = new StringBuilder(); while (iter.hasNext()) { String s = (String) iter.next(); trackback.append(padding).append(s).append("\n"); @@ -214,8 +214,8 @@ public static boolean isMacOSX() { return false; } - public static StringBuffer htmlEscapeSpace(String uri) { - StringBuffer sbURI = new StringBuffer((int) (uri.length() * 1.5)); + public static StringBuilder htmlEscapeSpace(String uri) { + StringBuilder sbURI = new StringBuilder((int) (uri.length() * 1.5)); char ch; for (int i = 0; i < uri.length(); ++i) { ch = uri.charAt(i); @@ -300,7 +300,7 @@ public static int parseIntRelaxed(String s) { return 0; } - StringBuffer buffer = new StringBuffer(); + StringBuilder buffer = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); @@ -342,7 +342,7 @@ public static String escapeHTML(String s){ if (s == null) { return ""; } - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); int n = s.length(); for (int i = 0; i < n; i++) { char c = s.charAt(i); diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/Util.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/Util.java index 1adddda7d..9fd61ec0c 100755 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/Util.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/Util.java @@ -451,7 +451,7 @@ public static String file_to_string(File file) * @return Returns */ public static String replace(String source, String target, String replacement) { - StringBuffer output = new StringBuffer(); + StringBuilder output = new StringBuilder(); int n = 0; while (true) { //print("n = " + n); @@ -460,7 +460,7 @@ public static String replace(String source, String target, String replacement) { output.append(source.substring(n)); break; } - output.append(source.substring(n, off)); + output.append(source, n, off); output.append(replacement); n = off + target.length(); } diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/XRLog.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/XRLog.java index e8da5f3eb..884de30a1 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/XRLog.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/XRLog.java @@ -33,7 +33,7 @@ * @author empty */ public class XRLog { - private static final List LOGGER_NAMES = new ArrayList(20); + private static final List LOGGER_NAMES = new ArrayList(20); public final static String CONFIG = registerLoggerByName("com.openhtmltopdf.config"); public final static String EXCEPTION = registerLoggerByName("com.openhtmltopdf.exception"); public final static String GENERAL = registerLoggerByName("com.openhtmltopdf.general"); @@ -55,7 +55,7 @@ private static String registerLoggerByName(final String loggerName) { private static boolean initPending = true; private static XRLogger loggerImpl; - private static Boolean loggingEnabled; + private static volatile Boolean loggingEnabled; /** * Returns a list of all loggers that will be accessed by XRLog. Each entry is a String with a logger @@ -64,9 +64,9 @@ private static String registerLoggerByName(final String loggerName) { * * @return List of loggers, never null. */ - public static List listRegisteredLoggers() { + public static List listRegisteredLoggers() { // defensive copy - return new ArrayList(LOGGER_NAMES); + return new ArrayList(LOGGER_NAMES); } @@ -270,8 +270,8 @@ public static synchronized void setLevel(String log, Level level) { * to configuration file property xr.util-logging.loggingEnabled, or to * value passed to setLoggingEnabled(bool). */ - public static synchronized boolean isLoggingEnabled() { - return loggingEnabled; + public static boolean isLoggingEnabled() { + return loggingEnabled == true; } /** @@ -281,7 +281,7 @@ public static synchronized boolean isLoggingEnabled() { * if false, all logging calls fail silently. Corresponds * to configuration file property xr.util-logging.loggingEnabled */ - public static synchronized void setLoggingEnabled(boolean loggingEnabled) { + public static void setLoggingEnabled(boolean loggingEnabled) { XRLog.loggingEnabled = loggingEnabled; } diff --git a/openhtmltopdf-examples/src/main/java/com/openhtmltopdf/freemarker/FreeMarkerGenerator.java b/openhtmltopdf-examples/src/main/java/com/openhtmltopdf/freemarker/FreeMarkerGenerator.java index 53c26d5b3..468f20da3 100644 --- a/openhtmltopdf-examples/src/main/java/com/openhtmltopdf/freemarker/FreeMarkerGenerator.java +++ b/openhtmltopdf-examples/src/main/java/com/openhtmltopdf/freemarker/FreeMarkerGenerator.java @@ -1,5 +1,12 @@ package com.openhtmltopdf.freemarker; +import java.io.*; +import java.net.URL; +import java.util.Locale; + +import org.apache.pdfbox.io.MemoryUsageSetting; +import org.apache.pdfbox.pdmodel.PDDocument; + import com.openhtmltopdf.bidi.support.ICUBidiReorderer; import com.openhtmltopdf.bidi.support.ICUBidiSplitter; import com.openhtmltopdf.latexsupport.LaTeXDOMMutator; @@ -9,15 +16,10 @@ import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; import com.openhtmltopdf.svgsupport.BatikSVGDrawer; import com.openhtmltopdf.swing.NaiveUserAgent.DefaultUriResolver; + import freemarker.cache.ClassTemplateLoader; import freemarker.template.*; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.StringWriter; -import java.net.URL; -import java.util.Locale; - public class FreeMarkerGenerator { private Configuration cfg; @@ -59,15 +61,42 @@ public String generateHTML(String templateName, Locale locale, FreemarkerRootObj return stringWriter.toString(); } - public byte[] generatePDF(String html) throws IOException { + public void generateHTMLToFile(String templateName, Locale locale, FreemarkerRootObject object, File htmlFile) + throws IOException, TemplateException { + FileOutputStream output = new FileOutputStream(htmlFile); + Writer fw = new OutputStreamWriter(output, "UTF-8"); + cfg.getTemplate(templateName, locale, "UTF-8").process(object, fw); + fw.close(); + output.close(); + } + + public byte[] generatePDF(final String html) throws IOException { + return generatePDF(new ICallableWithPdfBuilder() { + @Override + public void apply(PdfRendererBuilder builder) { + builder.withHtmlContent(html, "/freemarker"); + } + }); + } + + public byte[] generatePDF(final File htmlFile) throws IOException { + return generatePDF(new ICallableWithPdfBuilder() { + @Override + public void apply(PdfRendererBuilder builder) { + builder.withFile(htmlFile); + } + }); + } + + private byte[] generatePDF(ICallableWithPdfBuilder callWithBuilder) throws IOException { PdfRendererBuilder builder = new PdfRendererBuilder(); builder.useUnicodeBidiSplitter(new ICUBidiSplitter.ICUBidiSplitterFactory()); builder.useUnicodeBidiReorderer(new ICUBidiReorderer()); builder.defaultTextDirection(PdfRendererBuilder.TextDirection.LTR); - builder.withHtmlContent(html, "/freemarker"); builder.useSVGDrawer(new BatikSVGDrawer()); builder.useMathMLDrawer(new MathMLDrawer()); builder.addDOMMutator(LaTeXDOMMutator.INSTANCE); + builder.usePDDocument(new PDDocument(MemoryUsageSetting.setupMixed(1000000))); builder.useUriResolver(new DefaultUriResolver() { @Override public String resolveURI(String baseUri, String uri) { @@ -87,6 +116,8 @@ public String resolveURI(String baseUri, String uri) { builder.useObjectDrawerFactory(objectDrawerFactory); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); builder.toStream(outputStream); + callWithBuilder.apply(builder); + PdfBoxRenderer pdfBoxRenderer = builder.buildPdfRenderer(); try { pdfBoxRenderer.layout(); @@ -97,4 +128,8 @@ public String resolveURI(String baseUri, String uri) { outputStream.close(); return outputStream.toByteArray(); } + + interface ICallableWithPdfBuilder { + void apply(PdfRendererBuilder builder); + } } diff --git a/openhtmltopdf-examples/src/main/resources/freemarker/many_pages.ftl b/openhtmltopdf-examples/src/main/resources/freemarker/many_pages.ftl new file mode 100644 index 000000000..53c8c6e27 --- /dev/null +++ b/openhtmltopdf-examples/src/main/resources/freemarker/many_pages.ftl @@ -0,0 +1,627 @@ +[#-- @ftlvariable name="" type="com.openhtmltopdf.freemarker.FreeMarkerGenerator.FreemarkerRootObject" --] + + + Document with *many* pages + + + + + + +
+
+
+
+
+ Page / +
+ +[#assign tableOfContentHTML = ""] +[#assign sectionAnchorCounter = 0] +[#macro hn level] + [#assign sectionAnchorCounter = sectionAnchorCounter + 1] + + [#local content][#nested][/#local] + ${content} + [#assign tableOfContentHTML] + ${tableOfContentHTML} +
  • ${content}
  • + [/#assign] +[/#macro] +[#macro h1][@hn 1][#nested][/@hn][/#macro] +[#macro h2][@hn 2][#nested][/@hn][/#macro] +[#macro h3][@hn 3][#nested][/@hn][/#macro] +[#macro h4][@hn 4][#nested][/@hn][/#macro] + + +[#list 1..10 as page] + [@h1]H1 on Page ${page}[/@h1] +Some nice text, just to fill ${page?c} with something... + + + + + + + + + + + + + + + + + +
    +
    +
    +
    +
    + REGISTRO DE LA EJECUCIÓN FINANCIERA DEL PRESUPUESTO DE GASTO HASTA EL + 30/04/2018 + + Fecha: + 06/04/2018 +
    + Hora: + 12:31 PM +
    +
    +
    + ORGANISMO: Alcaldía de Ningún Lugar +
    + [@h2]H2.1 on Page ${page}[/@h2] +Some nice text, just to fill ${page?c} with something... + [@h2]H2.2 on Page ${page}[/@h2] +Some nice text, just to fill ${page?c} with something... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + [#list 1..10 as subRow] + + + + + + + + + + + + + + + + + + + + + + + [/#list] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + UNIDAD EJECUTORA: MyonMyonMyonMyonMyonMyon +
    + PARTIDA: Fondo de victimaz del voraz Pyonta: victimas devoradas en el Templo Hakurei - + Reimu Hakurei +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + CÓDIGO PRESUPUESTARIO +
    + SECT + + PROG + + SUBP + + PROY + + ACTI + + PART + + GENE + + ESPE + + SUBE +
    + 01 + + 01 + + 09 + + 02 + + 03 + + 450 + + 02 + + 02 + + 01 +
    +
    + ASIENTO + + FECHA + + DETALLE + + ACTUALIZADO + + COMPROMISO + + AFECTADO POR + + POR COMPROMETER + + CAUSADO + + AFECTADO POR + + PAGADO +
    + 000000 + 01/01/2016 + + Inicio de la ejecución + + 120.000,00 + + 0,00 + + + 120.000,00 + + 0,00 + + + 0,00 +
    + 001010 + 30/12/2016 + + REVERSO: + + Orden de pago: 000357 - Fulanirigillo: Ranko! + + (2.060.877,00) + + 0,00 + + + (2.060.877,00) + + (350,00) + + + 0,00 +
    + 001011 + 30/12/2016 + + Orden de pago: 000358 - Fulanirigillo: Ranko! + + (2.060.877,00) + + 0,00 + + + (2.060.877,00) + + 1.000,00 + + + 0,00 +
    + TOTAL MES (Bs.): + + 100.000,00 + + 2.155.000,00 + + 2.332.100,00 +
    + TOTAL ACUMULADO PARTIDA (Bs.): + + 2.481.432,00 + + 2.402.430,00 + + 2.332.100,00 +
    + + [@h3]H3.1 on Page ${page}[/@h3] +Some nice text, just to fill ${page?c} with something... + + + + + + + + + + + [#list 1..50 as rownum] + + + + + [/#list] + +
    Header1Header2
    Cell 1 ${rownum}Cell 2 ${rownum}
    + [@h2]H2.3 on Page ${page}[/@h2] +Some nice text, just to fill ${page?c} with something... +
    +[/#list] + +
    + +
    + Table of Content +
      + ${tableOfContentHTML} +
    +
    + + + diff --git a/openhtmltopdf-examples/src/test/java/com/openhtmltopdf/freemarker/FreeMarkerGeneratorTest.java b/openhtmltopdf-examples/src/test/java/com/openhtmltopdf/freemarker/FreeMarkerGeneratorTest.java index 5e35a8692..71880fc53 100644 --- a/openhtmltopdf-examples/src/test/java/com/openhtmltopdf/freemarker/FreeMarkerGeneratorTest.java +++ b/openhtmltopdf-examples/src/test/java/com/openhtmltopdf/freemarker/FreeMarkerGeneratorTest.java @@ -1,13 +1,12 @@ package com.openhtmltopdf.freemarker; import com.openhtmltopdf.freemarker.FreeMarkerGenerator.FreemarkerRootObject; +import com.openhtmltopdf.util.XRLog; import freemarker.template.TemplateException; import org.apache.pdfbox.util.Charsets; import org.junit.Test; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; +import java.io.*; import java.util.Locale; public class FreeMarkerGeneratorTest { @@ -27,6 +26,25 @@ public void testFreeMarkerGenerator() throws IOException, TemplateException { fileOutputStream = new FileOutputStream(new File(targetDir, "featuredocumentation.pdf")); fileOutputStream.write(pdf); fileOutputStream.close(); + } + @Test + public void testFreeMarkerWithManyPages() throws IOException, TemplateException { + /* + * We really should disable logging here, as it takes ages anyway to generate + * the report... + */ + XRLog.setLoggingEnabled(false); + File targetDir = new File("target/test/freemarker"); + targetDir.mkdirs(); + FreeMarkerGenerator freeMarkerGenerator = new FreeMarkerGenerator(); + FreemarkerRootObject object = new FreemarkerRootObject(); + File htmlFile = new File(targetDir, "many_pages.html"); + freeMarkerGenerator.generateHTMLToFile("many_pages.ftl", Locale.GERMAN, object, htmlFile); + byte[] pdf = freeMarkerGenerator.generatePDF(htmlFile); + FileOutputStream fileOutputStream = new FileOutputStream(new File(targetDir, "many_pages.pdf")); + fileOutputStream.write(pdf); + fileOutputStream.close(); + XRLog.setLoggingEnabled(true); } } \ No newline at end of file diff --git a/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxRenderer.java b/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxRenderer.java index 8aa7c53cb..b3f017261 100644 --- a/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxRenderer.java +++ b/openhtmltopdf-pdfbox/src/main/java/com/openhtmltopdf/pdfboxout/PdfBoxRenderer.java @@ -522,7 +522,7 @@ private void writePDF(List pages, RenderingContext c, Rectangle2D first _outputDevice.finishPage(); if (i != pageCount - 1) { - PageBox nextPage = (PageBox) pages.get(i + 1); + PageBox nextPage = pages.get(i + 1); Rectangle2D nextPageSize = new Rectangle2D.Float(0, 0, nextPage.getWidth(c) / _dotsPerPoint, nextPage.getHeight(c) / _dotsPerPoint); PDPage pageNext = new PDPage(new PDRectangle((float) nextPageSize.getWidth(), (float) nextPageSize.getHeight())); @@ -569,7 +569,7 @@ else if(name.equals("keywords")) doc.setDocumentInformation(info); } - private void paintPage(RenderingContext c, PageBox page) throws IOException { + private void paintPage(RenderingContext c, PageBox page) { // TODO: provideMetadataToPage(_pdfDoc, page); page.paintBackground(c, 0, Layer.PAGED_MODE_PRINT); @@ -646,7 +646,7 @@ private static Element getFirstChildElement(Element element) { } private String createXPacket(String metadata) { - StringBuffer result = new StringBuffer(metadata.length() + 50); + StringBuilder result = new StringBuilder(metadata.length() + 50); result.append("\n"); result.append(metadata); result.append("\n"); @@ -736,7 +736,7 @@ public void cleanup() { * Cleanup thread resources. MUST be called after finishing with the renderer. */ @Override - public void close() throws IOException { + public void close() { this.cleanup(); } }