Package org.jpedal.render.output.javafx

Source Code of org.jpedal.render.output.javafx.JavaFXDisplay

/**
* ===========================================
* Java Pdf Extraction Decoding Access Library
* ===========================================
*
* Project Info:  http://www.jpedal.org
* (C) Copyright 1997-2011, IDRsolutions and Contributors.
*
*   This file is part of JPedal
*
     This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


*
* ---------------
* ImageDisplay.java
* ---------------
*/
package org.jpedal.render.output.javafx;

import org.jpedal.color.PdfPaint;
import org.jpedal.examples.javafx.JavaFXFontMapper;
import org.jpedal.fonts.PdfFont;
import org.jpedal.fonts.glyph.PdfGlyph;
import org.jpedal.io.ObjectStore;
import org.jpedal.objects.GraphicsState;
import org.jpedal.render.DynamicVectorRenderer;
import org.jpedal.render.ShapeFactory;
import org.jpedal.render.output.FontMapper;
import org.jpedal.render.output.OutputDisplay;
import org.jpedal.render.output.TextBlock;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class JavaFXDisplay extends OutputDisplay {

  final private static String separator = System.getProperty("file.separator");

  String packageName="";

  /**used to give each shape a unique ID*/
  private int shapeCount=0;
  private String textName;

  //Root directory of the image
  private String imagePrefix=null;

  private String javaFxFileName="";
 
  //alt name for page 1
    private String firstPageName =System.getProperty("org.jpedal.pdf2javafx.firstPageName");

  public JavaFXDisplay( int pageNumber, Point2D midPoint, Rectangle cropBox, boolean addBackground, int defaultSize, ObjectStore newObjectRef) {
    super(pageNumber, midPoint, cropBox, addBackground, defaultSize, newObjectRef);

    type = DynamicVectorRenderer.CREATE_JAVAFX;

    //setup helper class for static helper code
    Helper=new org.jpedal.render.output.javafx.JavaFXHelper();
  }


  /**
   * Add current date
   *
   * @return returns date as string in 21 - November - 2011 format
   */

  public static String getDate(){

    DateFormat dateFormat = new SimpleDateFormat("dd - MMMMM - yyyy"); // get current date

    Date date = new Date();
    //System.out.println(dateFormat.format(date));
    return (String) dateFormat.format(date);
  }

  /**
   * add footer and other material to complete
   */
  protected void completeOutput() {

    //flush any cached text before we write out
    flushText();

    if(DEBUG_DRAW_PAGE_BORDER)
      drawPageBorder();




    /**
     * write a header
     */


    //Create default image path
    String defaultImageDir = rootDir.substring(0, rootDir.length()-1);

    //No nav bar on single page files.
    Boolean onePageFile = false;
    if(pageData.getPageCount() == 1)
      onePageFile = true;
   

    writeCustom(TOFILE, "/**");
    writeCustom(TOFILE, "* ===========================================");
    writeCustom(TOFILE, "* Java Pdf Extraction Decoding Access Library");
    writeCustom(TOFILE, "* ===========================================");
    writeCustom(TOFILE, "*");
    writeCustom(TOFILE, "* Project Info:  http://www.jpedal.org");
    writeCustom(TOFILE, "*");
    writeCustom(TOFILE, "* generated by JPedal PDF to javaFX 2.1");
    writeCustom(TOFILE, "*");
    writeCustom(TOFILE, "* --------------------------------------------");
    writeCustom(TOFILE, "* page"+pageNumberAsString+".java");
    writeCustom(TOFILE, "* --------------------------------------------");
    writeCustom(TOFILE, "* --------------------------------------------");
    writeCustom(TOFILE, "* "+ getDate());
    writeCustom(TOFILE, "* --------------------------------------------");
    writeCustom(TOFILE, "*/");
    writeCustom(TOFILE, "");
    writeCustom(TOFILE, "package "+packageName+ ';');
    writeCustom(TOFILE, "");
    writeCustom(TOFILE, "");
        writeCustom(TOFILE, "import java.io.File;");
    writeCustom(TOFILE, "import javafx.application.Application;");
    writeCustom(TOFILE, "import javafx.scene.Group;");
    writeCustom(TOFILE, "import javafx.scene.Scene;");
    writeCustom(TOFILE, "import javafx.scene.Node;");
    writeCustom(TOFILE, "import javafx.scene.paint.Color;");
    writeCustom(TOFILE, "import javafx.scene.shape.*;");
    writeCustom(TOFILE, "import javafx.stage.Stage;");
    writeCustom(TOFILE, "import javafx.collections.ObservableList;");
    writeCustom(TOFILE, "import javafx.scene.text.*;");
    writeCustom(TOFILE, "import javafx.scene.layout.BorderPane;");
        writeCustom(TOFILE, "import javafx.scene.image.Image;");
        writeCustom(TOFILE, "import javafx.scene.image.ImageView;");
   
    //Add imports for navBar functionality
        if(!onePageFile){
          writeCustom(TOFILE, "import javafx.scene.input.MouseEvent;");
          writeCustom(TOFILE, "import javafx.scene.layout.HBox;");
          writeCustom(TOFILE, "import javafx.scene.effect.*;");
          writeCustom(TOFILE, "import javafx.geometry.Pos;");
          writeCustom(TOFILE, "import javafx.event.EventHandler;");
          writeCustom(TOFILE, "import javafx.event.ActionEvent;");
          writeCustom(TOFILE, "import javafx.scene.control.*;");
          writeCustom(TOFILE, "import java.lang.reflect.Method;");
          writeCustom(TOFILE, "import java.net.URI;");
          writeCustom(TOFILE, "import java.net.URISyntaxException;");
          writeCustom(TOFILE, "import java.util.logging.Level;");
          writeCustom(TOFILE, "import java.util.logging.Logger;");
          writeCustom(TOFILE, "import java.io.IOException;");
        }
   
    writeCustom(TOFILE, " ");
    writeCustom(TOFILE, " ");
    writeCustom(TOFILE, "public class " +javaFxFileName+" extends Application {");//Default class name
    writeCustom(TOFILE, " ");
   
    writeCustom(TOFILE, "  BorderPane root;");
    writeCustom(TOFILE, "  Stage primaryStage;");
    writeCustom(TOFILE, "  Scene scene;");
    writeCustom(TOFILE, " ");
    writeCustom(TOFILE, " ");
    writeCustom(TOFILE, "\tpublic static void main(String[] args) {");
    writeCustom(TOFILE, "\t\tApplication.launch(args);");
    writeCustom(TOFILE, "\t}");
    writeCustom(TOFILE, " ");
    writeCustom(TOFILE, "\tpublic void start(Stage primaryStage) { ");
    writeCustom(TOFILE, "\t\tthis.primaryStage = primaryStage;");
           
    writeCustom(TOFILE, "\t\troot = new BorderPane();");
    writeCustom(TOFILE, "\t\tscene = new Scene(root, " + pageData.getCropBoxWidth(pageNumber) +", "+ (pageData.getCropBoxHeight(pageNumber)+75)+");");
    writeCustom(TOFILE, "\t\t//draw first page");
    writeCustom(TOFILE, "\t\tdrawPage(primaryStage, root, scene); //actual execution of commands");
    writeCustom(TOFILE, "");
   
    writeCustom(TOFILE, "\t}");




    /**add in CSS or link to file*/
    //        if(inlineCSS){
    //            if(css.length()>0){
    //                writeCustom(TOFILE, "\n<!-- Inline CSS values -->\n");
    //                writeCustom(TOFILE, "<style type=\"text/css\" >\n");
    //                writeCustom(TOFILE, css.toString()+'\n');
    //                writeCustom(TOFILE, "</style>\n");
    //            }
    //        }else{
    //            writeCustom(TOFILE, "<link rel=\"stylesheet\" type=\"text/css\" href=\""+fileName+"/styles.css\" />");
    //        }

    //        writeCustom(TOFILE, "<link rel=\"alternate\" type=\"application/atom+xml\" tile=\"feed\" href=\"/feed/\" />");
    //        writeCustom(TOFILE, "<link rel=\"search\" type=\"application/opensearchdescription+xml\" tile=\"search\" href=\"opensearch.xml\" />");
    //        writeCustom(TOFILE, "<link rel=\"shortcut.ico\" />");
    //
    //        writeCustom(TOFILE, "</meta>");
    //        writeCustom(TOFILE, "</head>\n");

    //        writeCustom(TOFILE,topSection.toString());

    //        /**
    //         * add any image data
    //         */
    //        if (images.length() > 0) {
    //            writeCustom(TOFILE, "\n<!-- Images defined here and referenced in Javascript -->\n");
    //            writeCustom(TOFILE, images.toString());
    //        }
    //
    //        /**
    //         * add any text div data
    //         */
    //        if (testDivs.length() > 0) {
    //            writeCustom(TOFILE, "\n<!-- Text defined here and setup in CSS -->\n");
    //            writeCustom(TOFILE, testDivs.toString());
    //        }
    //
    //
    //        /**
    //         * add any form data
    //         */
    //        if (form.length() > 0) {
    //            writeCustom(TOFILE, "\n<!-- Form Data here -->\n");
    //            writeCustom(TOFILE, tag[FORM_TAG]);
    //            writeCustom(TOFILE, form.toString());
    //            writeCustom(TOFILE, "</form>");
    //            //if JS images for forms write out initiator
    //            if(jsImagesAdded)
    //                writeCustom(TOFILE, "\n<!-- call to setup Radio and Checkboxes as images, " +
    //                        "without this call images dont work for them -->\n" +
    //                        "<script type=\"text/javascript\">\nreplaceChecks();\n</script>");
    //        }

    /**
     * start canvas
     */
    //        writeCustom(TOFILE, "\n<script type=\"application/javascript\">");
    //
    //        //add text sizing function to end if needed
    //        if(includeJSFontResizingCode){
    //            //see if we can write out js to set automatically for best fit
    //            writeCustom(TOFILE,"function setFontSize(divName,pixelSize,actualWidth) {\n" +
    //                    "\tvar el = document.getElementById(divName);\n " + //get HTML divElement
    //                    "\tel.style.fontSize = pixelSize+'px';\n" + //set raw pixel size
    //                    "\tvar rawWidth=el.offsetWidth;\n"+ //measure width that it makes at this pt size
    //                    "\tvar lastRawWidth=actualWidth;\n"+ //init in case not done in case loop not entered
    //                    "\tif(rawWidth>0){\n"+ //allow for single space which will return zero and hang code
    //                    "\t\tif(rawWidth>actualWidth){\n"+
    //                    "\t\t\twhile (rawWidth>actualWidth){\n"+ //reduce pixel size until smaller than gap
    //                    "\t\t\t\tpixelSize--;\n"+
    //                    "\t\t\t\tel.style.fontSize = pixelSize+'px';\n"+
    //                    "\t\t\t\tlastRawWidth=rawWidth;\n"+ //save for later
    //                    "\t\t\t\trawWidth=el.offsetWidth;\n"+ //recalc
    //                    "\t\t\t}\n"+
    //                    "\t\t\tvar lastDiff=lastRawWidth-actualWidth;\n"+ //if previous better guess use that
    //                    "\t\t\tvar nextDiff=actualWidth-rawWidth;\n"+
    //                    "\t\t\tif(lastDiff<nextDiff){\n"+
    //                    "\t\t\t\tpixelSize++;\n"+
    //                    "\t\t\t}\n"+
    //                    "\t\t}else{\n"+
    //                    "\t\t\twhile (rawWidth<actualWidth){\n"+ //increase pixel size until larger than gap
    //                    "\t\t\t\tpixelSize++;\n"+
    //                    "\t\t\t\tel.style.fontSize = pixelSize+'px';\n"+
    //                    "\t\t\t\tlastRawWidth=rawWidth;\n"+ //save for later
    //                    "\t\t\t\trawWidth=el.offsetWidth;\n"+ //recalc
    //                    "\t\t\t}\n"+
    //                    "\t\t\tvar lastDiff=actualWidth-lastRawWidth;\n"+ //if previous better guess use that
    //                    "\t\t\tvar nextDiff=rawWidth-actualWidth;\n"+
    //                    "\t\t\tif(lastDiff<nextDiff){\n"+
    //                    "\t\t\t\tpixelSize--;\n"+
    //                    "\t\t\t}\n"+
    //                    "\t\t}\n"+
    //                    "\t\tvar p=pixelSize+'px';\n"+  //set to my values
    //                    "\t\tel.style.fontSize = p;\n" +
    //                    "\t}\n"+
    //                    "}\n");
    //
    //        }
    writeCustom(TOFILE, "\n\tpublic static void drawPage(Stage primaryStage, BorderPane root, Scene scene) {");
    writeCustom(TOFILE, "\t\t");
    writeCustom(TOFILE, "\t\tprimaryStage.setWidth("+pageData.getCropBoxWidth(pageNumber)+");");//set the width of the new page
    writeCustom(TOFILE, "\t\tprimaryStage.setHeight("+(pageData.getCropBoxHeight(pageNumber)+75)+");");//set the height of the new page including the nav bar
    writeCustom(TOFILE, "\t\tprimaryStage.centerOnScreen();");//Always centre the window on screen regardless of size of window
    writeCustom(TOFILE, "\t\troot.getChildren().clear();");//Make sure nothing is on the screen when outputing the next page.
    writeCustom(TOFILE, "\t\t");
    writeCustom(TOFILE, "\t\tString imageDir = \""+ defaultImageDir +"\";");
    writeCustom(TOFILE, "\t\tFile checkExists=new File(imageDir);");
    writeCustom(TOFILE, "\t\tif(!checkExists.exists()){");
    writeCustom(TOFILE, "\t\t\tthrow new RuntimeException(\"Unable to find Image location - please alter imageDir in drawPage()\");");
    writeCustom(TOFILE, "\t\t}\n");

    writeCustom(TOFILE, "\t\tObservableList<Node> addToGroup;");
    writeCustom(TOFILE, "\t\t");
    writeCustom(TOFILE, "\t\tGroup pdfContent = new Group();");
    writeCustom(TOFILE, "\t\troot.setCenter(pdfContent);");
    writeCustom(TOFILE, "\t\taddToGroup = pdfContent.getChildren();");

    //        writeCustom(TOFILE, "\tvar pdf_canvas=document.getElementById(\"pdf\");");
    //        writeCustom(TOFILE, "\tvar pdf=pdf_canvas.getContext(\"2d\");");

    //black as default
    //        writeCustom(TOFILE, "\tpdf.fillStyle=\"rgb(0, 0, 0)\"; ");

    //script
    try {
            if(script.length()<1024*170) //ignore pages over a 170kb in size
      writeCustom(TOFILE, script.toString());
            else{//print out a message to user Letting them know that the file is too large
              writeCustom(TOFILE, "\n\t\tReflection r = new Reflection();");
              writeCustom(TOFILE, "\t\tr.setFraction(0.7f);");
              writeCustom(TOFILE, "");
              writeCustom(TOFILE, "\t\tText textBox = new Text(\"File too large\");");
              writeCustom(TOFILE, "\t\taddToGroup.add(textBox);");
              writeCustom(TOFILE, "\t\ttextBox.setEffect(r);");
              writeCustom(TOFILE, "\t\ttextBox.setFont(Font.font(null, FontWeight.BOLD, 30));");
              writeCustom(TOFILE, "\t\ttextBox.setFill(Color.rgb(255,0,0));");
            }
    } catch (Exception e) {
      e.printStackTrace();
    }

    //        writeCustom(TOFILE, "}");
    //        writeCustom(TOFILE, "</script>\n");
    //        writeCustom(TOFILE, "<body onload=\"draw();\">");
    //
    //        writeCustom(TOFILE, "\n<!-- Canvas we draw the content onto -->\n");

    //        switch(pageRotation){
    //
    //            case 90:
    //                writeCustom(OutputDisplay.CSS,"top:"+ setPrecision(8+(currentTextBlock.getX() * scaling)) + "px;\n");
    //                writeCustom(OutputDisplay.CSS,"left:"+ setPrecision(((currentTextBlock.getY() * scaling)-40)) + "px;\n");
    //                break;
    //
    //            case 270:
    //                writeCustom(OutputDisplay.CSS,"top:"+ setPrecision(8+(currentTextBlock.getX() * scaling)) + "px;\n");
    //                writeCustom(OutputDisplay.CSS,"left:"+ setPrecision(8+(currentTextBlock.getY() * scaling)) + "px;\n");
    //                break;
    //
    //            default:
    //                writeCustom(OutputDisplay.CSS,"left:"+ setPrecision(8+(currentTextBlock.getX() * scaling)) + "px;\n");
    //                writeCustom(OutputDisplay.CSS,"top:"+ setPrecision(8+(currentTextBlock.getY() * scaling)) + "px;\n");
    //                break;
    //        }
    //
    //        /**
    //         * set canvas size (allowing for page rotation)
    //         **/
    //        if(pageRotation==90 || pageRotation==270)
    //            writeCustom(TOFILE, "<canvas id=\"pdf\" width=\"" + (int)(cropBox.height*scaling) + "\" height=\"" + (int)(cropBox.width*scaling) + "\" />\n");
    //        else
    //            writeCustom(TOFILE, "<canvas id=\"pdf\" width=\"" + (int)(cropBox.width*scaling) + "\" height=\"" + (int)(cropBox.height*scaling) + "\" />\n");
    //
    //        writeCustom(TOFILE, "\n</body>");
    //        writeCustom(TOFILE, "</html>");
    //
    //        /**
    //         * and write out css if not empty and in file
    //         */
    //        if (!inlineCSS && css.length() > 0) {
    //
    //            //make sure css Dir exists
    //            String cssPath = rootDir + fileName + "/";
    //            File cssDir = new File(cssPath);
    //            if (!cssDir.exists()) {
    //                cssDir.mkdirs();
    //            }
    //
    //            try {
    //                PrintWriter CSSOutput = new PrintWriter(new FileOutputStream(cssPath + "styles.css"));
    //
    //                //css header
    //
    //                CSSOutput.println(css.toString());
    //
    //                CSSOutput.flush();
    //                CSSOutput.close();
    //
    //            } catch (Exception ee) {
    //                ee.printStackTrace();
    //            }
    //        }



    if(!onePageFile){//only print out page number if more than one page
      writeCustom(TOFILE, "\t\tprimaryStage.setTitle(\""+packageName +" page "+ pageNumber +"\");");
      writeCustom(TOFILE, "\t\taddNav(root, primaryStage, scene);");
    }else{//Set primary stage with updated page numbers if not one page file
      writeCustom(TOFILE, "\t\tprimaryStage.setTitle(\""+packageName+"\");");
    }
    writeCustom(TOFILE, "\t}\n");

    //add shared code for setting size
    writeCustom(TOFILE, "\tprivate static void setTextsize(Text textBox, float requiredWidth) {");

    writeCustom(TOFILE, "\t\tfloat actualWidth=(int) textBox.getLayoutBounds().getWidth();");
    writeCustom(TOFILE, "\t\tfloat dx=requiredWidth-actualWidth;");
    writeCustom(TOFILE, "\t\tfloat scalingNeeded=requiredWidth/actualWidth;");
    writeCustom(TOFILE, "\t\ttextBox.setScaleX(scalingNeeded);");
    writeCustom(TOFILE, "\t\ttextBox.setScaleY(scalingNeeded);");
    writeCustom(TOFILE, "\t\ttextBox.setTranslateX(dx/2);");

    //end of setTextsize method
    writeCustom(TOFILE, "\t}");

   
    //Add navBar if pages > 1
    if(!onePageFile){

      String pageName ="page"+pageNumberAsString;
     
      if(firstPageName!=null && firstPageName.length()>0 && pageNumber==1)
        pageName = firstPageName;

      //Create navBar
      writeCustom(TOFILE, "\n\tprivate static void addNav(BorderPane root, Stage primaryStage, Scene scene) {");
      writeCustom(TOFILE, "");
      writeCustom(TOFILE, "\t\tString imageDir = \""+ defaultImageDir +"\";");
      writeCustom(TOFILE, "");
      writeCustom(TOFILE, "\t\t//----- naviBar -----");
      writeCustom(TOFILE, "\t\tHBox naviBar = new HBox();");
      writeCustom(TOFILE, "\t\tnaviBar.setStyle(\"-fx-background-color: #F0F8FF; -fx-text-fill: white;\");");
      writeCustom(TOFILE, "\t\tButton start = makeButtons(\"smstart.gif\",\"Go to first Page\",0, root, primaryStage, scene);");
      writeCustom(TOFILE, "\t\tButton back = makeButtons(\"smback.gif\",\"Go back 1 page\",-1, root, primaryStage, scene);");
      writeCustom(TOFILE, "\t\tButton fback = makeButtons(\"smfback.gif\",\"Go back 10 pages\",-10, root, primaryStage, scene);");
      writeCustom(TOFILE, "\t\tString currentPageAsString= String.valueOf("+pageNumber+");");
      writeCustom(TOFILE, "\t\tTextField currentPage = makeTextField(false, currentPageAsString);");
      writeCustom(TOFILE, "\t\tLabel colon = makeLabel(\":\");");
      writeCustom(TOFILE, "\t\tString numberOfPagesAsString= String.valueOf("+pageData.getPageCount()+");");
      writeCustom(TOFILE, "\t\tTextField numberOfPages = makeTextField(false, numberOfPagesAsString);");
      writeCustom(TOFILE, "\t\tButton forward = makeButtons(\"smforward.gif\",\"Go forward 1 page\",1, root, primaryStage, scene);");
      writeCustom(TOFILE, "\t\tButton fforward = makeButtons(\"smfforward.gif\",\"Go forward 10 pages\",10, root, primaryStage, scene);");
      writeCustom(TOFILE, "\t\tButton end = makeButtons(\"smend.gif\",\"Go to last page\",9999, root, primaryStage, scene);");
      writeCustom(TOFILE, "");
      writeCustom(TOFILE, "\t\t//Logo with hyperlink to website");
      writeCustom(TOFILE, "\t\tImage logo = new Image(imageDir+\"/img/icons/logo.gif\", false);");
      writeCustom(TOFILE, "");
      writeCustom(TOFILE, "\t\tHyperlink hyperLinkLogo = new Hyperlink(\"\",new ImageView(logo));");
      writeCustom(TOFILE, "\t\thyperLinkLogo.tooltipProperty().set(new Tooltip(\"Visit our website\"));");
      writeCustom(TOFILE, "\t\thyperLinkLogo.setOnAction(new EventHandler<ActionEvent>() {");
      writeCustom(TOFILE, "");
      writeCustom(TOFILE, "\t\t\tpublic void handle(ActionEvent event) {");
      writeCustom(TOFILE, "\t\t\t\ttry {");
      writeCustom(TOFILE, "\t\t\t\t\ttry {");
      writeCustom(TOFILE, "\t\t\t\t\t\tjava.awt.Desktop.getDesktop().browse(new URI(\"http://www.jpedal.org/html_index.php\"));");
      writeCustom(TOFILE, "\t\t\t\t\t} catch (URISyntaxException ex) {");
      writeCustom(TOFILE, "\t\t\t\t\t\tLogger.getLogger("+ pageName +".class.getName()).log(Level.SEVERE, null, ex);");
      writeCustom(TOFILE, "\t\t\t\t\t}");
      writeCustom(TOFILE, "\t\t\t\t} catch (IOException ex) {");
      writeCustom(TOFILE, "\t\t\t\t\tLogger.getLogger("+ pageName +".class.getName()).log(Level.SEVERE, null, ex);");
      writeCustom(TOFILE, "\t\t\t\t}");
      writeCustom(TOFILE, "\t\t\t}");
      writeCustom(TOFILE, "");
      writeCustom(TOFILE, "\t\t});");
      writeCustom(TOFILE, "");
      writeCustom(TOFILE, "\t\tnaviBar.getChildren().addAll(start, fback, back, currentPage, colon, numberOfPages, forward, fforward, end, hyperLinkLogo);");
      writeCustom(TOFILE, "\t\tnaviBar.setSpacing(5);");
      writeCustom(TOFILE, "\t\tnaviBar.setPrefHeight(35);");
      writeCustom(TOFILE, "\t\tnaviBar.setAlignment(Pos.CENTER);");
      writeCustom(TOFILE, "\t\troot.setBottom(naviBar);");
      writeCustom(TOFILE, "\t\tprimaryStage.setScene(scene); ");
      writeCustom(TOFILE, "\t\tprimaryStage.show(); ");
      //close method
      writeCustom(TOFILE, "\t} ");


      //make labels
      writeCustom(TOFILE, "\n\tprivate static Label makeLabel(String text) {");

      writeCustom(TOFILE, "\t\tLabel label = new Label();");
      writeCustom(TOFILE, "\t\tlabel.setText(text);");
      writeCustom(TOFILE, "\t\treturn label;");

      //end of makeLabel method
      writeCustom(TOFILE, "\t}");

      //make TextFields
      writeCustom(TOFILE, "\n\tprivate static TextField makeTextField(Boolean check, String text) {");

      writeCustom(TOFILE, "\t\tTextField textfield = new TextField();");
      writeCustom(TOFILE, "\t\ttextfield.setEditable(check);");
      writeCustom(TOFILE, "\t\ttextfield.setAlignment(Pos.CENTER);");
      writeCustom(TOFILE, "\t\ttextfield.setText(text);");
      writeCustom(TOFILE, "\t\ttextfield.setMaxHeight(25);");
      writeCustom(TOFILE, "\t\ttextfield.setMaxWidth(50);");
      writeCustom(TOFILE, "\t\ttextfield.setPromptText(text);");
      writeCustom(TOFILE, "\t\treturn textfield;");

      //end of makeTextfield method
      writeCustom(TOFILE, "\t}");


      //make Buttons
      writeCustom(TOFILE, "\n\tprivate static Button makeButtons(String iconName, String toolTip, final int change, final BorderPane root, final Stage primaryStage, final Scene scene) {");
      writeCustom(TOFILE, "\t\tfinal int pageNumber= "+pageNumber+",pageCount= "+pageData.getPageCount()+ ';');
      writeCustom(TOFILE, "");
      writeCustom(TOFILE, "\t\tString imageDir = \""+ defaultImageDir +"\";");
      writeCustom(TOFILE, "\t\tFile checkExists=new File(imageDir);");
      writeCustom(TOFILE, "\t\tif(!checkExists.exists())");
      writeCustom(TOFILE, "\t\t\tthrow new RuntimeException(\"icon location in makeButtons() method cannot be found - please change imageDir to new location\");\n");

      writeCustom(TOFILE, "\t\tButton button = new Button();");
      writeCustom(TOFILE, "\t\tbutton.setTooltip(new Tooltip(toolTip));");
      writeCustom(TOFILE, "\t\t");
      writeCustom(TOFILE, "\t\tImage image = new Image(imageDir + \"/img/icons/\"+iconName,false);");
      writeCustom(TOFILE, "\t\tif (image != null) ");
      writeCustom(TOFILE, "\t\t\tbutton.setGraphic(new ImageView(image));");

      writeCustom(TOFILE, "\t\t");
      writeCustom(TOFILE, "\t\tcreatePressedLook(button);");
      writeCustom(TOFILE, "\t\t");
      writeCustom(TOFILE, "\t\t//event handler");
      writeCustom(TOFILE, "\t\t");
      writeCustom(TOFILE, "\t\tbutton.setOnAction(new EventHandler<ActionEvent>() {");
      writeCustom(TOFILE, "\t\t");
      writeCustom(TOFILE, "\t\t\tpublic void handle(ActionEvent event) {");
      writeCustom(TOFILE, "\t\t\t\tint newPage = 0;");
      writeCustom(TOFILE, "\t\t\t\t");
      writeCustom(TOFILE, "\t\t\t\tif (change == 0){ //special case 1st page");
      writeCustom(TOFILE, "\t\t\t\t\tnewPage = 1;");
      writeCustom(TOFILE, "\t\t\t\t} else if (change == 9999) {");
      writeCustom(TOFILE, "\t\t\t\t\tnewPage = pageCount;");
      writeCustom(TOFILE, "\t\t\t\t} else {");
      writeCustom(TOFILE, "\t\t\t\t\tnewPage = pageNumber + (change);");
      writeCustom(TOFILE, "\t\t\t\t}");
      writeCustom(TOFILE, "\t\t\t\t");
      writeCustom(TOFILE, "\t\t\t\t//error check for bounds");
      writeCustom(TOFILE, "\t\t\t\tif (newPage < 1) {");
      writeCustom(TOFILE, "\t\t\t\t\tnewPage = 1;");
      writeCustom(TOFILE, "\t\t\t\t}else if (newPage > pageCount) {");
      writeCustom(TOFILE, "\t\t\t\t\tnewPage = pageCount;");
      writeCustom(TOFILE, "\t\t\t\t}");
      writeCustom(TOFILE, "\t\t\t\t");

      //Check to make sure that firstPageName isn't empty
      if(firstPageName!=null && firstPageName.length()>0){
        writeCustom(TOFILE, "\t\t\t\tString customClassName = \""+packageName+ '.' +firstPageName+"\";");
        writeCustom(TOFILE, "\t\t\t\tBoolean customFirstPage = false;");
      }
      writeCustom(TOFILE, "\t\t\t\t");
      writeCustom(TOFILE, "\t\t\t\tString newPageAsString = String.valueOf(newPage);");
     
      //Check to make sure that firstPageName isn't empty
      if(firstPageName!=null && firstPageName.length()>0){
        writeCustom(TOFILE, "\t\t\t\t");
        writeCustom(TOFILE, "\t\t\t\tif(newPageAsString.equals(\"1\"))");
        writeCustom(TOFILE, "\t\t\t\t\tcustomFirstPage=true;");
        writeCustom(TOFILE, "\t\t\t\t");
      }
      writeCustom(TOFILE, "\t\t\t\tString maxNumberOfPages = String.valueOf(pageCount);");
      writeCustom(TOFILE, "\t\t\t\tint padding = maxNumberOfPages.length() - newPageAsString.length();");
      writeCustom(TOFILE, "\t\t\t\tfor (int ii = 0; ii < padding; ii++) {");
      writeCustom(TOFILE, "\t\t\t\tnewPageAsString = '0' + newPageAsString;");
      writeCustom(TOFILE, "\t\t\t\t}");
      writeCustom(TOFILE, "\t\t\t\t");
     
      //Check to make sure that firstPageName isn't empty
      if(firstPageName!=null && firstPageName.length()>0){
        writeCustom(TOFILE, "\t\t\t\t//workout new class from pageNumber");
        writeCustom(TOFILE, "\t\t\t\tString newClass=\"\";");
        writeCustom(TOFILE, "\t\t\t\t");
        writeCustom(TOFILE, "\t\t\t\tif(customFirstPage)");
        writeCustom(TOFILE, "\t\t\t\t\tnewClass=customClassName;");
        writeCustom(TOFILE, "\t\t\t\telse");
        writeCustom(TOFILE, "\t\t\t\t\tnewClass=\""+packageName+".page"+"\"+newPageAsString;");
      }else{
        writeCustom(TOFILE, "\t\t\t\t//workout new class from pageNumber");
        writeCustom(TOFILE, "\t\t\t\tString newClass=\""+packageName+".page"+"\"+newPageAsString;");
      }
      writeCustom(TOFILE, "\t\t\t\t");
      writeCustom(TOFILE, "\t\t\t\t//create an instance");
      writeCustom(TOFILE, "\t\t\t\ttry {");
      writeCustom(TOFILE, "\t\t\t\tClass c = Class.forName(newClass);");
      writeCustom(TOFILE, "\t\t\t\tApplication nextPage=(javafx.application.Application)c.newInstance();");
      writeCustom(TOFILE, "\t\t\t\t");
      writeCustom(TOFILE, "\t\t\t\tMethod m = c.getMethod(\"drawPage\", new Class[]{Stage.class, BorderPane.class, Scene.class});");
      writeCustom(TOFILE, "\t\t\t\tm.invoke(nextPage, new Object[]{primaryStage, root, scene});");
      writeCustom(TOFILE, "\t\t\t\t");
      writeCustom(TOFILE, "\t\t\t\t} catch (Exception e) {");
      writeCustom(TOFILE, "\t\t\t\t\te.printStackTrace();");
      writeCustom(TOFILE, "\t\t\t\t}");
      writeCustom(TOFILE, "\t\t\t}");
      writeCustom(TOFILE, "\t\t});");
      writeCustom(TOFILE, "\t\t\t\t");

      writeCustom(TOFILE, "\t\treturn button;");

      //end of makeButtons method
      writeCustom(TOFILE, "\t}");

      //add effects to Buttons
      writeCustom(TOFILE, "\n\tprivate static void createPressedLook(final Button button) {");

      writeCustom(TOFILE, "\t\tfinal DropShadow shadow = new DropShadow();");
      writeCustom(TOFILE, "\t\tshadow.setColor(Color.rgb(41, 36, 33));");
      writeCustom(TOFILE, "\t\t");
      writeCustom(TOFILE, "\t\t//Adding the shadow when the button is clicked");
      writeCustom(TOFILE, "\t\tbutton.addEventHandler(MouseEvent.MOUSE_PRESSED,");
      writeCustom(TOFILE, "\t\t\tnew EventHandler<MouseEvent>() {");
      writeCustom(TOFILE, "\t\t");
      writeCustom(TOFILE, "\t\t\t\t@Override");
      writeCustom(TOFILE, "\t\t\t\tpublic void handle(MouseEvent e) {");
      writeCustom(TOFILE, "\t\t\t\t\tbutton.setEffect(shadow);");
      writeCustom(TOFILE, "\t\t\t\t}");
      writeCustom(TOFILE, "\t\t\t});");
      writeCustom(TOFILE, "\t\t//Removing the shadow when the button is released");
      writeCustom(TOFILE, "\t\tbutton.addEventHandler(MouseEvent.MOUSE_RELEASED,");
      writeCustom(TOFILE, "\t\t\tnew EventHandler<MouseEvent>() {");
      writeCustom(TOFILE, "\t\t");
      writeCustom(TOFILE, "\t\t\t\t@Override");
      writeCustom(TOFILE, "\t\t\t\tpublic void handle(MouseEvent e) {");
      writeCustom(TOFILE, "\t\t\t\t\tbutton.setEffect(null);");
      writeCustom(TOFILE, "\t\t\t\t}");
      writeCustom(TOFILE, "\t\t\t});");

      //end of createPressedLook method
      writeCustom(TOFILE, "\t}");

    }

    //end of file
    writeCustom(TOFILE, "}");
    writeCustom(TOFILE, "");

    try{
      output.flush();
      output.close();
      output =null;
    }catch(Exception e){
      e.printStackTrace();
    }
  }

  private void writeoutJavaFXText()
  {
    if(currentTextBlock.isEmpty()) {
      throw new RuntimeException("writeoutTextAsDiv() called incorrectly.  Attempted to write out text with empty text block use flushText.");
    }

    /**
     * create a text block to show the text
     */

    //uniqueID
    textName = "textBox_"+textID;

    //set position of text block and content
    writeCustom(SCRIPT, "\n\t\tText "+ textName +" = new Text("+(int)currentTextBlock.getX()* scaling+" , " +(int)(currentTextBlock.getY()+fontSize)* scaling+ ", \""+ tidyQuotes(currentTextBlock.getOutputString(true))+"\");");

    //add it to the display group so it appears
    writeCustom(SCRIPT, "\taddToGroup.add("+textName+");");//add objects to the group

    //Set the font weight - update as needed.
    String weight = currentTextBlock.getWeight();
    String javaFxWeight = "";
    if(weight.equals("normal"))
      javaFxWeight="NORMAL";
    else if(weight.equals("bold"))
      javaFxWeight="BOLD";
    else if(weight.equals("bolder"))
      javaFxWeight="BLACK";
    else if(weight.equals("lighter"))
      javaFxWeight="EXTRA_LIGHT";
    else if(weight.equals("100"))
      javaFxWeight="THIN";
    else if(weight.equals("900"))
      javaFxWeight="BLACK";

   
    //set the font style - Regular or italic
    String style=currentTextBlock.getStyle();
    if(style.equals("normal"))
      writeCustom(SCRIPT, '\t' +textName+".setFont(Font.font(\""+currentTextBlock.getFont()+"\", FontWeight."+javaFxWeight+", FontPosture.REGULAR,"+ (currentTextBlock.getFontSize()*scaling)+"));");
    else
      writeCustom(SCRIPT, '\t' +textName+".setFont(Font.font(\""+currentTextBlock.getFont()+"\", FontWeight."+javaFxWeight+", FontPosture.ITALIC,"+ (currentTextBlock.getFontSize()*scaling)+"));");

    //scale the text to fit space used on PDF page
    writeCustom(SCRIPT, "\tsetTextsize("+textName+ ',' +(int)(currentTextBlock.getWidth()*scaling)+");");

    //update color if not black(-14475232)
    if(currentTextBlock.getColor() != -14475232)
      writeCustom(SCRIPT, '\t' +textName+".setFill(Color." + rgbToColor(currentTextBlock.getColor()) + ");");

    float rotateDegree = currentTextBlock.getRotationAngle();

    //get rotation used in degrees
    int rot=(int) ((rotateDegree * 180) / Math.PI);
    if(rot<0)
      rot=rot+360;
    //handle any rotation (not yet implemented)

    //Adjust text to fit correctly
    if(rotateDegree == 0 && !writeEveryGlyf) {

      //@Mark - HELP.. :)
      // JavaFX implementation

      //          writeCustom(SCRIPT, "\t"+textName+".translateXProperty().set("++");");
      writeCustom(SCRIPT, '\t' +textName+".translateYProperty().set(0);");

      //original HTML implementation
      //          writeCustom(SCRIPT, "pdf.translate(" + (currentTextBlock.getX() * scaling) + " * (1 - " + (currentTextBlock.getWidth() * scaling) + " / metrics.width), 0);");

      //          writeCustom(SCRIPT, ""+textName+".scaleXProperty().set("++");");
      writeCustom(SCRIPT, '\t' +textName+".scaleYProperty().set(1);");

      //            writeCustom(SCRIPT, "pdf.scale("+ (currentTextBlock.getWidth() * scaling) + " / metrics.width, 1);");

    }

    /**
     * Rotate text as needed
     */
    //        if (rot != 0) {
    //            writeCustom(SCRIPT, "\t"+textName+".rotateProperty().set(" + rot + ");");
    //    }


    //        if(pageRotation != 0 && rot != 0)
    //        System.out.println(pageRotation+" "+currentTextBlock.getOutputString(true)+" "+currentTextBlock.getRotationAngle()+" "+rot);

    //float targetX = 0, targetY = 0;

    switch(rot){

    case 90:
      writeCustom(SCRIPT, '\t' +textName+".rotateProperty().set(" + rot + ");");
      //                writeCustom(SCRIPT, "\t"+textName+".translateXProperty().set("+ ((pageData.getCropBoxHeight(pageNumber)-currentTextBlock.getY()-currentTextBlock.getFontSize()*2) * scaling) + ");");
      //                writeCustom(SCRIPT, "\t"+textName+".translateYProperty().set("+(currentTextBlock.getX() * scaling)+ ");");

      break;

    case 270:
      // writeCustom(SCRIPT, "\t"+textName+".translateXProperty().set("+(currentTextBlock.getX() * scaling)+ ");");
      // writeCustom(SCRIPT, "\t"+textName+".translateYProperty().set("+((currentTextBlock.getY()+fontSize) * scaling)+ ");");

      writeCustom(SCRIPT, '\t' +textName+".rotateProperty().set(" + rot + ");");
      break;

    }

    textID++;
  }

    /**
     * mhandle any characters which need conversion or escaping
     * @param outputString
     * @return
     */
    private static String tidyQuotes(String outputString) {

        outputString=outputString.replaceAll("\"","\\\\\"");

        return outputString;
    }

    //allow user to control various values
  public void setBooleanValue(int key,boolean value){

    switch(key){
    case IncludeJSFontResizingCode:
      this.includeJSFontResizingCode=value;
      break;

    default:
      super.setBooleanValue(key,value);
    }
  }



  /**
   * allow user to set own value for certain tags
   * Throws RuntimeException
   * @param type
   * @param value
   */
  public void setTag(int type,String value){

    switch (type) {

    case FORM_TAG:
      tag[FORM_TAG]=value;
      break;

    default:
      super.setTag(type,value);
    }
  }

  /**
   * not actually needed because all the FX stuff happens via flushText() and FXHelper
   * but added for development so we can disable
   */
  public void drawEmbeddedText(float[][] Trm, int fontSize, PdfGlyph embeddedGlyph,
                                 Object javaGlyph, int type, GraphicsState gs,
                                 AffineTransform at, String glyf, PdfFont currentFontData, float glyfWidth)
  {

    //@chika - remove to get text working
//            if(1==1)
//                return;


    super.drawEmbeddedText(Trm, fontSize, embeddedGlyph,javaGlyph, type,  gs,at,  glyf,  currentFontData, glyfWidth);
  }

  /**
   * not actually needed because all the FX stuff happens via JavaFXShape()
   * but added for development so we can disable
   */
  public void drawShape(Shape currentShape, GraphicsState gs, int cmd) {

    //        if(1==1)
    //            return;

    super.drawShape(currentShape,gs, cmd);
  }


  // save image in array to draw
  public int drawImage(int pageNumber, BufferedImage image, GraphicsState gs, boolean alreadyCached, String name, int optionsApplied, int previousUse) {

//          if(1==1)
//            return -1;

    int flag=super.drawImage(pageNumber, image, gs, alreadyCached, name, optionsApplied, previousUse);


    //assigning the root directory to imagePrefix
    //        imagePrefix = rootDir.substring(0, rootDir.length()-1);

    if(flag==-2){ //returned by Super to show we use

      /**
       * add in any image transparency
       */
      float opacity=gs.getAlpha(GraphicsState.FILL);
      if(opacity<1.0f)
        writeCustom(SCRIPT, "pdf.globalAlpha = "+opacity+"; ");

      /**
       * link in and add tag
       * set x,y position factoring in page rotation
       * value of 8 hardcoded to account for canvas border that seems unremovable.
       */

      switch(pageRotation){

      case 90:
        writeCustom(SCRIPT, "\n\t\t/**");
        writeCustom(SCRIPT, "\t* Image properties for "+ name);
        writeCustom(SCRIPT, "\t*/ ");
        writeCustom(SCRIPT,"\tImage "+name+" = new Image(imageDir+\""+imageName+"\",false);");                  
        writeCustom(SCRIPT,"\tImageView "+name+"ImageView = new ImageView("+name+");");
        writeCustom(SCRIPT, '\t' +name+"ImageView.setImage("+name+");");
        writeCustom(SCRIPT, '\t' +name+"ImageView.setFitWidth("+ih+");");
        writeCustom(SCRIPT, '\t' +name+"ImageView.setFitHeight("+iw+");");
        writeCustom(SCRIPT, '\t' +name+"ImageView.setX("+(int)(cropBox.height-coords[1]-ih)+");");
        writeCustom(SCRIPT, '\t' +name+"ImageView.setY("+(int)(coords[0])+");");
        writeCustom(SCRIPT,"\taddToGroup.add("+name+"ImageView);");

        //                    writeCustom(IMAGE, "<img id=\"" + id + "\" src=\"" + imageName + "\" alt=\"" + id + "\" width=\"" + ih + "\" height=\"" + iw + "\" style=\"display: none\" />\n");
        //                    writeCustom(SCRIPT, "pdf.drawImage(document.getElementById(\""+id+"\") ," + setPrecision(cropBox.height-coords[1]-ih) + "," + setPrecision(coords[0]) + "); ");
        //                    break;
        //
      case 270:

        writeCustom(SCRIPT, "\n\t\t/**");
        writeCustom(SCRIPT, "\t* Image properties for "+ name);
        writeCustom(SCRIPT, "\t*/ ");
        writeCustom(SCRIPT,"\tImage "+name+" = new Image(imageDir+\""+imageName+"\",false);")
        writeCustom(SCRIPT,"\tImageView "+name+"ImageView = new ImageView("+name+");");
        writeCustom(SCRIPT, '\t' +name+"ImageView.setImage("+name+");");
        writeCustom(SCRIPT, '\t' +name+"ImageView.setFitWidth("+ih+");");
        writeCustom(SCRIPT, '\t' +name+"ImageView.setFitHeight("+iw+");");
        writeCustom(SCRIPT, '\t' +name+"ImageView.setX("+setPrecision((int)coords[1])+");");
        writeCustom(SCRIPT, '\t' +name+"ImageView.setY("+setPrecision((int)coords[0])+");");
        writeCustom(SCRIPT,"\taddToGroup.add("+name+"ImageView);");

        //                    writeCustom(IMAGE,"<img id=\""+id+"\" src=\""+imageName+"\" alt=\""+id+"\" width=\""+ ih +"\" height=\""+iw+"\" style=\"display: none\" />\n");
        //                    writeCustom(SCRIPT, "pdf.drawImage(document.getElementById(\""+id+"\") ," + setPrecision(coords[1]) + "," + setPrecision(coords[0]) + "); ");
        //                    break;

      default:
        writeCustom(SCRIPT, "\n\t\t/**");
        writeCustom(SCRIPT, "\t* Image properties for "+ name);
        writeCustom(SCRIPT, "\t*/ ");
        writeCustom(SCRIPT,"\tImage "+name+" = new Image(imageDir+\""+imageName+"\", false);");
        writeCustom(SCRIPT,"\tImageView "+name+"ImageView = new ImageView("+name+");");
        writeCustom(SCRIPT, '\t' +name+"ImageView.setImage("+name+");");
        writeCustom(SCRIPT, '\t' +name+"ImageView.setFitWidth("+iw+");");
        writeCustom(SCRIPT, '\t' +name+"ImageView.setFitHeight("+ih+");");
        writeCustom(SCRIPT, '\t' +name+"ImageView.setX("+(int)coords[0]+");");
        writeCustom(SCRIPT, '\t' +name+"ImageView.setY("+(int)coords[1]+");");
        writeCustom(SCRIPT,"\taddToGroup.add("+name+"ImageView);");

        //writeCustom(IMAGE,"<img id=\""+id+"\" src=\""+imageName+"\" alt=\""+id+"\" width=\""+ iw +"\" height=\""+ih+"\" style=\"display: none\" />\n");
        // writeCustom(SCRIPT, "pdf.drawImage(document.getElementById(\""+id+"\") ," + setPrecision(coords[0]) + "," + setPrecision(coords[1]) + "); ");
        break;
      }

      /**
       * remove any transparency setting
       */
      if(opacity<1.0f)
        writeCustom(SCRIPT, "pdf_canvas.globalAlpha = 1.0; ");

    }

    return -1;

  }


  public void setOutputDir(String outputDir,String outputFilename, String pageNumberAsString) {

    super.setOutputDir(outputDir,outputFilename,pageNumberAsString);

    //create name as combination of both
    if(pageNumber==1 && firstPageName!=null && firstPageName.length()>0)//If firstPageName is set.
      javaFxFileName=firstPageName;
    else
      javaFxFileName="page"+pageNumberAsString;
    packageName=outputFilename;
    if(packageName.contains(" "))
      packageName = packageName.replaceAll(" ", "_");
  }


  /*setup renderer*/
  public void init(int width, int height, int rawRotation, Color backgroundColor) {

    super.init(width, height, rawRotation, backgroundColor);

    /**
     * create the file or tell user to set
     */
    if(rootDir==null)
      throw new RuntimeException("Please pass in output_dir (second param if running ExtractpageAsJavaFX");

    try{
      output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(rootDir+javaFxFileName+".java"), encodingType[JAVA_TYPE]));
    }catch(Exception ee){
      ee.printStackTrace();
    }


  }

  /**
   * Add HTML to correct area so we can assemble later.
   * Can also be used for any specific code features (ie setting a value)
   */
  public synchronized void writeCustom(int section, Object str) {

    //  System.out.println(output+" "+str);

    switch (section) {

    case TOFILE:
      try {
        output.write(str.toString());
        output.write('\n');
        output.flush();
      } catch (Exception e) {
        e.printStackTrace();
      }
      break;

    case TOP_SECTION:
      topSection.append('\t'); //indent
      topSection.append(str.toString());
      topSection.append('\n');
      break;

    case SCRIPT:
      script.append('\t'); //indent
      script.append(str.toString());
      script.append('\n');
      break;

    case FORM:
      form.append(str.toString());
      break;

    case IMAGE:

      images.append(str.toString());
      break;

    case TEXT:

      testDivs.append(str.toString());
      break;

    case CSS:
      css.append(str.toString());
      css.append('\n');
      break;

    case KEEP_GLYFS_SEPARATE:

      try {
        this.writeEveryGlyf= (Boolean) str;
      } catch (Exception e) {
        e.printStackTrace();
      }
      break;

    case SET_ENCODING_USED:

      try {
        this.encodingType=((String[])str);
      } catch (Exception e) {
        e.printStackTrace();
      }
      break;

    case JSIMAGESPECIAL:
      if(!jsImagesAdded){
        writeCustom(TOP_SECTION, str);
        jsImagesAdded = true;
      }
      break;

      //special case used from PdfStreamDecoder to get font data
    case SAVE_EMBEDDED_FONT:

      //save ttf font data as file
      Object[] fontData= (Object[]) str;
      PdfFont pdfFont=(PdfFont)fontData[0];
      String fontName=pdfFont.getFontName();
      String fileType=(String)fontData[2];

      //make sure Dir exists
      String fontPath = rootDir + javaFxFileName + '/';
      File cssDir = new File(fontPath);
      if (!cssDir.exists()) {
        cssDir.mkdirs();
      }

      try {
        BufferedOutputStream fontOutput =new BufferedOutputStream(new FileOutputStream(fontPath +fontName+ '.' +fileType));
        fontOutput.write((byte[]) fontData[1]);
        fontOutput.flush();
        fontOutput.close();

      } catch (Exception ee) {
        ee.printStackTrace();
      }

      //save details into CSS so we can put in HTML
      StringBuffer fontTag=new StringBuffer();
      fontTag.append("@font-face {\n"); //indent
      fontTag.append("\tfont-family: ").append(fontName).append(";\n");
      fontTag.append("\tsrc: url(\"").append(javaFxFileName).append("/").append(fontName).append(".").append(fileType).append("\");\n");
      fontTag.append("}\n");

      writeCustom(OutputDisplay.CSS, fontTag);

      break;

    default:
      super.writeCustom(section, str);
    }
  }



  /**
   * Write out text buffer in correct format
   */
  protected void flushText()
  {

    if(DEBUG_TEXT_AREA) {
      drawTextArea();
    }

    if(currentTextBlock==null || currentTextBlock.isEmpty()) {
      return;
    }else {
      writeoutJavaFXText();
    }

    //Reset current block and store the last one so we dont have to repeat javascript code later
    if(!currentTextBlock.isEmpty()) {
      previousTextBlock = currentTextBlock;
    }
    currentTextBlock = new TextBlock();

  }

  protected void drawPatternedShape(Shape currentShape, GraphicsState gs) {

    //      if(1==1)
    //        return;

    AffineTransform scalingTransform = new AffineTransform();
    scalingTransform.scale(scaling, scaling);

    PdfPaint col = gs.getNonstrokeColor();
    Rectangle bounds = currentShape.getBounds();
    bounds.setSize((int) (bounds.width * scaling), (int) (bounds.height * scaling));//dont like this cast
    if(col.isPattern()) {
      PaintContext context = col.createContext(null, bounds, bounds, scalingTransform, null);
      Raster raster = context.getRaster(bounds.x, bounds.y, bounds.width > 1 ? bounds.width : 1, bounds.height > 1 ? bounds.height : 1);

      BufferedImage img = new BufferedImage(bounds.width > 1 ? bounds.width : 1, bounds.height > 1 ? bounds.height : 1, BufferedImage.TYPE_4BYTE_ABGR);
      img.setData(raster);

      //make sure image Dir exists
      String imageDir= "img/shade/" + pageNumberAsString+ '/';
      File imgDir=new File(rootDir +imageDir);
      if(!imgDir.exists())
        imgDir.mkdirs();

      String id="shade" + (shadeId++);
      String imageName= imageDir+id+".png";

      /**
       * get dimensions before we rotate
       */
      int shadingWidth= (bounds.width > 1 ? bounds.width : 1);
      int shadingHeight= (bounds.height > 1 ? bounds.height : 1);
      float shadingX=(bounds.x * scaling);
      float shadingY=(h - (bounds.y * scaling) - img.getHeight());

      //switch round in this case
      if(pageRotation==90 || pageRotation==270){

        int tmp=shadingWidth;
        shadingWidth=shadingHeight;
        shadingHeight=tmp;

        float tmp2=shadingX;
        shadingX=cropBox.height-shadingY-240;
        shadingY=tmp2;

      }

      /**
       * Make and populate the shades with their X , Y , Width and Height.
       */

      //assigning the root directory to imagePrefix
      //            imagePrefix = rootDir.substring(0, rootDir.length()-1);

      writeCustom(SCRIPT, "\n\t\t/**");
      writeCustom(SCRIPT, "\t* Shade properties for "+ id);
      writeCustom(SCRIPT, "\t*/ ");
      writeCustom(SCRIPT,"\tImage "+id+" = new Image(imageDir+\""+ '/' +imageName+"\",false);");
      writeCustom(SCRIPT,"\tImageView "+id+"ImageView = new ImageView("+id+");");
      writeCustom(SCRIPT, '\t' +id+"ImageView.setImage("+id+");");
      writeCustom(SCRIPT, '\t' +id+"ImageView.setFitWidth("+shadingWidth+");");
      writeCustom(SCRIPT, '\t' +id+"ImageView.setFitHeight("+shadingHeight+");");
      writeCustom(SCRIPT, '\t' +id+"ImageView.setX("+shadingX+");");
      writeCustom(SCRIPT, '\t' +id+"ImageView.setY("+shadingY+");");
      writeCustom(SCRIPT,"\taddToGroup.add("+id+"ImageView);");

      //            writeCustom(IMAGE,"<img id=\""+id+"\" src=\""+imageName+"\" alt=\""+id+" width=\""+shadingWidth +"\" height=\"" + shadingHeight+ "\" style=\"display: none\" />");
      //            writeCustom(SCRIPT, "pdf.drawImage(document.getElementById(\""+id+"\") ," + shadingX + "," +shadingY  + "); ");

      /**
       * rotate if needed
       **/
      if(pageRotation==90 || pageRotation==270){
        img = rotateImage(img);
      }

      /**
       * store image
       */
      try{
        ImageIO.write(img, "PNG", new File(rootDir + imageName));
      }catch(Exception e){
        e.printStackTrace();
      }
    }
  }

  protected void drawNonPatternedShape(Shape currentShape, GraphicsState gs, int cmd,  String name) {
   
    //catch shapes with negative coords
//    if(currentShape.getBounds().x < 0){
//      System.out.println("shape bounds"+currentShape.getBounds());
//      System.out.println("cropboxwidth: "+pageData.getCropBoxHeight(shapeCount)+" cropboxWidth: "+pageData.getCropBoxWidth(shapeCount));
//      return;
//    }

    //        if(shapeCount==42)
    //        return;

        int offset=0;
        if(pageoffsets!=null)
            offset=pageoffsets[pageNumber];

    ShapeFactory shape = new org.jpedal.render.output.javafx.JavaFXShape(cmd,offset,shapeCount, scaling, currentShape, gs, new AffineTransform(), midPoint, cropBox, currentColor, dpCount, pageRotation, pageData, pageNumber, includeClip);
    shape.setShapeNumber(shapeCount);
    shapeCount++;

    if(!shape.isEmpty()) {
      writeCustom(SCRIPT, shape.getContent());

      //catch shapes with negative coords
      //            if(currentShape.getBounds().x < 0)
//                System.out.println(shape.getContent());
     
      //update current color
      currentColor = shape.getShapeColor();
    }
  }



  /**
   * Draws boxes around where the text should be.
   */
  protected void drawTextArea()
  {
    if(currentTextBlock.isEmpty())
      return;

    int yAdjust = currentTextBlock.getFontSize();


    double[] coords = {currentTextBlock.getX(), (int) currentTextBlock.getY() + yAdjust};
    writeCustom(SCRIPT, "pdf.moveTo(" + coordsToStringParam(coords, 2) + ");");
    coords[0] = currentTextBlock.getX() + currentTextBlock.getWidth();
    writeCustom(SCRIPT, "pdf.lineTo(" + coordsToStringParam(coords, 2) + ");");
    coords[1] = currentTextBlock.getY() - currentTextBlock.getFontSize() + yAdjust;
    writeCustom(SCRIPT, "pdf.lineTo(" + coordsToStringParam(coords, 2) + ");");
    coords[0] = currentTextBlock.getX();
    writeCustom(SCRIPT, "pdf.lineTo(" + coordsToStringParam(coords, 2) + ");");
    writeCustom(SCRIPT, "pdf.closePath();");
    writeCustom(SCRIPT, "pdf.strokeStyle = '" + rgbToColor(200) + "';");
    writeCustom(SCRIPT, "pdf.lineWidth = '1'");
    writeCustom(SCRIPT, "pdf.stroke();");
  }

  /**
   * Draw a debug area around border of page.
   */
  protected void drawPageBorder()
  {
    double[] coords = {cropBox.x, cropBox.y};
    writeCustom(SCRIPT, "pdf.moveTo(" + coordsToStringParam(coords, 2) + ");");
    coords[0] += cropBox.width;
    writeCustom(SCRIPT, "pdf.lineTo(" + coordsToStringParam(coords, 2) + ");");
    coords[1] +=  cropBox.height;
    writeCustom(SCRIPT, "pdf.lineTo(" + coordsToStringParam(coords, 2) + ");");
    coords[0] -= cropBox.width;
    writeCustom(SCRIPT, "pdf.lineTo(" + coordsToStringParam(coords, 2) + ");");
    writeCustom(SCRIPT, "pdf.closePath();");
    writeCustom(SCRIPT, "pdf.strokeStyle = '" + rgbToColor(0) + "';");
    writeCustom(SCRIPT, "pdf.lineWidth = '1'");
    writeCustom(SCRIPT, "pdf.stroke();");

  }

  protected FontMapper getFontMapper(PdfFont currentFontData) {
    return new JavaFXFontMapper(currentFontData.getFontName(),fontMode,currentFontData.isFontEmbedded);
  }


}
TOP

Related Classes of org.jpedal.render.output.javafx.JavaFXDisplay

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.