@@ -562,17 +562,10 @@ protected void writePage() throws IOException
562562
563563 // Resets the average character width when we see a change in font
564564 // or a change in the font size
565- if (lastPosition != null )
565+ if (lastPosition != null
566+ && hasFontOrSizeChanged (position , lastPosition .getTextPosition ()))
566567 {
567- TextPosition lastTextPosition = lastPosition .getTextPosition ();
568- boolean fontHasChanged = !position .getFont ().getName ()
569- .equals (lastTextPosition .getFont ().getName ());
570- boolean fontSizeChanged = Float .compare (position .getFontSize (),
571- lastTextPosition .getFontSize ()) != 0 ;
572- if (fontHasChanged || fontSizeChanged )
573- {
574- previousAveCharWidth = -1 ;
575- }
568+ previousAveCharWidth = -1 ;
576569 }
577570 float positionX ;
578571 float positionY ;
@@ -733,6 +726,38 @@ protected void writePage() throws IOException
733726 writePageEnd ();
734727 }
735728
729+ private boolean hasFontOrSizeChanged (TextPosition current , TextPosition last )
730+ {
731+ if (last == null )
732+ {
733+ return false ;
734+ }
735+ // compare font sizes
736+ if (Float .compare (current .getFontSize (), last .getFontSize ()) != 0 )
737+ {
738+ return true ;
739+ }
740+ // compare font instances, may not work if the resource cache is disabled
741+ if (current .getFont () == last .getFont ())
742+ {
743+ return false ;
744+ }
745+ String currentFontName = current .getFont ().getName ();
746+ String lastFontName = last .getFont ().getName ();
747+ if (currentFontName != null )
748+ {
749+ // compare font names
750+ return !currentFontName .equals (lastFontName );
751+ }
752+ if (lastFontName != null )
753+ {
754+ // currentFontName is null but lastFontName isn't -> font changes
755+ return true ;
756+ }
757+ // both fonts don't have a name -> compare hashes
758+ return current .getFont ().hashCode () != last .getFont ().hashCode ();
759+ }
760+
736761 private boolean overlap (float y1 , float height1 , float y2 , float height2 )
737762 {
738763 return within (y1 , y2 , .1f ) || y2 <= y1 && y2 >= y1 - height1
0 commit comments