/**
* ===========================================
* Java Pdf Extraction Decoding Access Library
* ===========================================
*
* Project Info: http://www.jpedal.org
* (C) Copyright 1997-2008, 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
/**
* <br>Description: Swing GUI functions in Viewer
*
*
*/ public class SwingGUI extends GUI implements GUIFactory {
private boolean previewOnSingleScroll =true;
private Timer memoryMonitor=null;
//flag for marks new thumbnail preview private boolean debugThumbnail=false;
ScrollListener scrollListener;
ScrollMouseListener scrollMouseListener;
JScrollBar thumbscroll=null;
private boolean isMultiPageTiff = false;
static final private boolean enableShowSign = true;
boolean finishedDecoding=false; static int startSize=30,expandedSize=190;
public static void setStartSize(int startSize) {
SwingGUI.startSize = startSize;
}
//use new GUI layout public boolean useNewLayout = true;
public static String windowTitle;
String pageTitle,bookmarksTitle, signaturesTitle,layersTitle; boolean hasListener=false; private boolean isSetup=false; int lastTabSelected=-1; public boolean messageShown=false;
/** grabbing cursor */ private Cursor grabCursor,grabbingCursor,panCursor,panCursorL,panCursorTL,panCursorT,panCursorTR,panCursorR,panCursorBR,panCursorB,panCursorBL; public final static int GRAB_CURSOR = 1; public final static int GRABBING_CURSOR = 2; public final static int DEFAULT_CURSOR = 3; public final static int PAN_CURSOR = 4; public final static int PAN_CURSORL = 5; public final static int PAN_CURSORTL = 6; public final static int PAN_CURSORT = 7; public final static int PAN_CURSORTR = 8; public final static int PAN_CURSORR = 9; public final static int PAN_CURSORBR = 10; public final static int PAN_CURSORB = 11; public final static int PAN_CURSORBL = 12;
private PaperSizes paperSizes;
/** Multibox for new GUI Layout*/
//Component to contain memory, cursor and loading bars private JPanel multibox = new JPanel(); public final static int CURSOR = 1;
//example code showing how we can add icons and then track public boolean addUniqueIconToFileAttachment=false;
ButtonGroup layoutGroup = new ButtonGroup();
ButtonGroup searchLayoutGroup = new ButtonGroup();
ButtonGroup borderGroup = new ButtonGroup();
/** Constants for glowing border */ public int glowThickness = 11; public Color glowOuterColor = new Color(0.0f, 0.0f, 0.0f ,0.0f); public Color glowInnerColor = new Color(0.8f, 0.75f, 0.45f, 0.8f);
/** Track whether both pages are properly displayed */ private boolean pageTurnScalingAppropriate =true;
/** Whether the left page drag or right page drag is drawing */ private boolean dragLeft = false; private boolean dragTop = false;
/**listener on buttons, menus, combboxes to execute options (one instance on all objects)*/ private CommandListener currentCommandListener;
/**holds OPEN, INFO,etc*/ private JToolBar topButtons = new JToolBar();
/**holds back/forward buttons at bottom of page*/ private JToolBar navButtons = new JToolBar();
/**holds rotation, quality, scaling and status*/ private JToolBar comboBoxBar = new JToolBar();
/**holds all menu entries (File, View, Help)*/ private JMenuBar currentMenu =new JMenuBar();
/**tell user on first form change it can be saved*/ private boolean firstTimeFormMessage=true;
/** visual display of current cursor co-ords on page*/ private JLabel coords=new JLabel();
/**root element to hold display*/ private Container frame=new JFrame();
/** alternative internal JFrame*/ private JDesktopPane desktopPane=new JDesktopPane();
/**flag to disable functions*/ boolean isSingle=true;
/**displayed on left to hold thumbnails, bookmarks*/ private JTabbedPane navOptionsPanel=new JTabbedPane();
/**split display between PDF and thumbnails/bookmarks*/ private JSplitPane displayPane;
/**Scrollpane for pdf panel*/ private JScrollPane scrollPane = new JScrollPane();
private Font headFont=new Font("SansSerif",Font.BOLD,14);
private Font textFont1=new Font("SansSerif",Font.PLAIN,12);
private Font textFont=new Font("Serif",Font.PLAIN,12);
/**Interactive display object - needs to be added to PdfDecoder*/ private StatusBar statusBar=new StatusBar(new Color(235, 154, 0)); private StatusBar downloadBar=new StatusBar(new Color(185, 209, 0));
private JLabel pageCounter1;
//allow user to control messages in Viewer
CustomMessageHandler customMessageHandler =null;
public JTextField pageCounter2 = new JTextField(4);
private JLabel pageCounter3;
private JLabel optimizationLabel;
private JTree signaturesTree;
private JPanel layersPanel=new JPanel();
/**user dir in which program can write*/ private String user_dir = System.getProperty( "user.dir" );
/**stop user forcing open tab before any pages loaded*/ private boolean tabsNotInitialised=true; private JToolBar navToolBar = new JToolBar(); private JToolBar pagesToolBar = new JToolBar();
//Optional Buttons for menu Search public GUIButton nextSearch,previousSearch;
//layers tab
PdfLayerList layersObject;
//Progress bar on nav bar private final JProgressBar memoryBar = new JProgressBar();
//Component to display cursor position on page
JToolBar cursor = new JToolBar();
//Buttons on the function bar private GUIButton openButton; private GUIButton printButton; private GUIButton searchButton; private GUIButton docPropButton; private GUIButton infoButton; public GUIButton mouseMode;
if(PdfDecoder.isRunningOnMac){
//String tabName="";
//see if there is an outlines tab for(int jj=0;jj<navOptionsPanel.getTabCount();jj++){ if(navOptionsPanel.getTitleAt(jj).equals(bookmarksTitle))
outlineTab=jj;
}
}else{
//String tabName="";
//see if there is an outlines tab for(int jj=0;jj<navOptionsPanel.getTabCount();jj++){ if(navOptionsPanel.getIconAt(jj).toString().equals(bookmarksTitle))
outlineTab=jj;
}
}
}else if(properties.getValue("Bookmarkstab").toLowerCase().equals("true")){ int outlineTab=-1; if(PdfDecoder.isRunningOnMac){
//String tabName="";
//see if there is an outlines tab for(int jj=0;jj<navOptionsPanel.getTabCount();jj++){ if(navOptionsPanel.getTitleAt(jj).equals(bookmarksTitle))
outlineTab=jj;
}
if(outlineTab==-1)
navOptionsPanel.addTab(bookmarksTitle,(SwingOutline) tree);
}else{
//String tabName="";
//see if there is an outlines tab for(int jj=0;jj<navOptionsPanel.getTabCount();jj++){ if(navOptionsPanel.getIconAt(jj).toString().equals(bookmarksTitle))
outlineTab=jj;
}
//@simon -new version to test
PdfArrayIterator filters = sigObject.getMixedArray(PdfDictionary.Filter); if(filters!=null && filters.hasMoreTokens())
filter=filters.getNextValueAsString(true);
DefaultMutableTreeNode filterNode = new DefaultMutableTreeNode("Filter: " + filter);
type.add(filterNode);
//add collapsed Tree at Top final JTree infoTree = new JTree(top);
infoTree.setToolTipText("Double click to see any metadata");
infoTree.setRootVisible(true);
infoTree.collapseRow(0);
layersPanel.add(infoTree, BorderLayout.NORTH);
/**
* Display list of layers which can be recursive
* layerNames can contain comments or sub-trees as Object[] or String name of Layer
*/ final Object[] layerNames=layersObject.getDisplayTree(); if(layerNames!=null){
topLayer.removeAllChildren();
final JTree layersTree = new JTree(topLayer);
layersTree.setName("LayersTree");
//Listener to redraw with altered layer
layersTree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)
layersTree.getLastSelectedPathComponent();
/* exit if nothing is selected */ if (node == null) return;
/* retrieve the full name of Layer that was selected */
String rawName = (String)node.getUserObject();
//and add path
Object[] patentNames = ((DefaultMutableTreeNode)node.getParent()).getUserObjectPath(); int size= patentNames.length; for(int jj=size-1;jj>0;jj--){ //note I ingore 0 which is root and work backwards
rawName=rawName+PdfLayerList.deliminator+ patentNames[jj].toString();
}
final String name=rawName;
//if allowed toggle and update display if(layersObject.isLayerName(name) && !layersObject.isLocked(name)){
//toggle layer status when clicked
Runnable updateAComponent = new Runnable() {
public void run() {
decode_pdf.setPDFCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//force refresh
decode_pdf.invalidate();
decode_pdf.updateUI();
decode_pdf.validate();
//update settings on display and in PdfDecoder
CheckNode checkNode=(CheckNode)node;
if(!checkNode.isEnabled()){ //selection not allowed so display info message
checkNode.setSelected(checkNode.isSelected());
ShowGUIMessage.showstaticGUIMessage(new StringBuffer("This layer has been disabled because its parent layer is disabled"),"Parent Layer disabled");
}else{ boolean reversedStatus=!checkNode.isSelected();
checkNode.setSelected(reversedStatus);
layersObject.setVisiblity(name,reversedStatus);
//may be radio buttons which disable others so sync values
//before repaint
syncTreeDisplay(topLayer,true);
//decode again with new settings try {
decode_pdf.decodePage(commonValues.getCurrentPage());
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
//deselect so works if user clicks on same again to deselect
layersTree.invalidate();
layersTree.clearSelection();
layersTree.repaint();
decode_pdf.setPDFCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
};
SwingUtilities.invokeLater(updateAComponent);
}
}
});
//build tree from values
topLayer.removeAllChildren();
addLayersToTree(layerNames, topLayer, true);
//@kieran this is temporary but works for now.
//DisplayPane adjustment int orig = displayPane.getDividerLocation();
displayPane.setDividerLocation(0);
displayPane.validate();
displayPane.setDividerLocation(orig);
//see if showing and set box to match if(layersObject.isVisible(name)){
((CheckNode)currentNode).setSelected(true);
parentIsSelected=true;
}else
parentIsSelected=false;
//check locks and allow Parents to disable children if(isEnabled)
isEnabled=!layersObject.isLocked(name);
private void checkTabShown(String title) { int outlineTab=-1; if(PdfDecoder.isRunningOnMac){
//see if there is an outlines tab for(int jj=0;jj<navOptionsPanel.getTabCount();jj++){ if(navOptionsPanel.getTitleAt(jj).equals(title))
outlineTab=jj;
}
if(outlineTab==-1){ if(title.equals(signaturesTitle) && properties.getValue("Signaturestab").toLowerCase().equals("true")){ if(signaturesTree==null){
signaturesTree = new JTree();
SignaturesTreeCellRenderer treeCellRenderer = new SignaturesTreeCellRenderer();
signaturesTree.setCellRenderer(treeCellRenderer);
}else{
//see if there is an outlines tab for(int jj=0;jj<navOptionsPanel.getTabCount();jj++){ if(navOptionsPanel.getIconAt(jj).toString().equals(title))
outlineTab=jj;
}
if(outlineTab==-1){
if(title.equals(signaturesTitle) && properties.getValue("Signaturestab").toLowerCase().equals("true")){ //stop spurious display of Sig tab
VTextIcon textIcon2 = new VTextIcon(navOptionsPanel, signaturesTitle, VTextIcon.ROTATE_LEFT);
navOptionsPanel.addTab(null, textIcon2, signaturesTree);
// navOptionsPanel.setTitleAt(navOptionsPanel.getTabCount()-1, signaturesTitle);
}else if(title.equals(layersTitle) && properties.getValue("Layerstab").toLowerCase().equals("true")){
VTextIcon textIcon = new VTextIcon(navOptionsPanel, layersTitle, VTextIcon.ROTATE_LEFT);
if(PdfDecoder.isRunningOnMac){
//String tabName="";
//see if there is an outlines tab for(int jj=0;jj<navOptionsPanel.getTabCount();jj++){ if(navOptionsPanel.getTitleAt(jj).equals(title))
outlineTab=jj;
}
}else{
//String tabName="";
//see if there is an outlines tab for(int jj=0;jj<navOptionsPanel.getTabCount();jj++){ if(navOptionsPanel.getIconAt(jj).toString().equals(title))
outlineTab=jj;
}
}
//disable page view buttons until we know we have multiple pages if(!commonValues.isContentExtractor())
setPageLayoutButtonsEnabled(false);
}
}
/* (non-Javadoc)
* @see org.jpedal.examples.simpleviewer.gui.swing.GUIFactory#setNoPagesDecoded()
*
* Called when new file opened so we set flags here
*/ public void setNoPagesDecoded() {
bookmarksGenerated=false;
resetNavBar();
//Ensure preview from last file doesn't appear if(scrollListener!=null)
scrollListener.lastImage = null;
pagesDecoded.clear();
}
public void setBackNavigationButtonsEnabled(boolean flag) {
//Font tree Display pane
JScrollPane fontScrollPane=new JScrollPane();
boolean sortFontsByDir = true;
/**
* show fonts on system displayed
*/ private JPanel getFontsFoundInfoBox(){
//Create font list display area
JPanel fontDetails=new JPanel(new BorderLayout());
fontDetails.setBackground(Color.WHITE);
JPanel panel = new JPanel(new BorderLayout());
panel.setBackground(Color.WHITE);
//This allows the title to be centered above the filter box
JPanel filterTitlePane = new JPanel();
filterTitlePane.setBackground(Color.WHITE);
JLabel filterTitle = new JLabel("Filter Font List");
filterTitlePane.add(filterTitle);
//Create buttons
ButtonGroup bg = new ButtonGroup();
JRadioButton folder = new JRadioButton("Sort By Folder");
folder.setBackground(Color.WHITE);
JRadioButton name = new JRadioButton("Sort By Name");
name.setBackground(Color.WHITE); final JTextField filter = new JTextField();
filter.addKeyListener(new KeyListener(){ public void keyPressed(KeyEvent e) {} public void keyReleased(KeyEvent e) {
DefaultMutableTreeNode fontlist = new DefaultMutableTreeNode("Fonts");
populateAvailableFonts(fontlist, ((JTextField)e.getSource()).getText());
displayAvailableFonts(fontlist);
} public void keyTyped(KeyEvent e) {}
});
//Start tree here
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Fonts");
//Populate font list and build tree
top = populateAvailableFonts(top, null);
JTree fontTree = new JTree(top);
//Added to keep the tree left aligned when top parent is closed
fontDetails.add(fontTree, BorderLayout.WEST);
//Peice it all together
panel.add(buttons, BorderLayout.NORTH);
panel.add(fontScrollPane, BorderLayout.CENTER);
panel.setPreferredSize(new Dimension(400,300));
//Remove old font tree display panel
fontScrollPane.getViewport().removeAll();
//Create new font list display
JPanel jp = new JPanel(new BorderLayout());
jp.setBackground(Color.WHITE);
jp.add(new JTree(fontlist), BorderLayout.WEST);
//Show font tree
fontScrollPane.getViewport().add(jp);
}
/**
* list of all fonts properties in sorted order
*/ private DefaultMutableTreeNode populateAvailableFonts(DefaultMutableTreeNode top, String filter){
//get list if(FontMappings.fontSubstitutionTable!=null){
Set fonts=FontMappings.fontSubstitutionTable.keySet();
Iterator fontList=FontMappings.fontSubstitutionTable.keySet().iterator();
int fontCount=fonts.size();
ArrayList fontNames=new ArrayList(fontCount);
ImageIcon logo = new ImageIcon(getClass().getResource("/org/jpedal/examples/simpleviewer/res/logo.gif"));
details.add(Box.createRigidArea(new Dimension(0, 25)));
JLabel idr = new JLabel(logo);
idr.setAlignmentX(Component.CENTER_ALIGNMENT);
details.add(idr);
final JLabel url = new JLabel("<html><center>" + Messages.getMessage("PdfViewerJpedalLibrary.Text")
+ Messages.getMessage("PdfViewer.WebAddress"));
url.setForeground(Color.blue);
url.setHorizontalAlignment(JLabel.CENTER);
url.setAlignmentX(Component.CENTER_ALIGNMENT);
String xmlText="This ebook was generated using the free PJES service offered by IDRSolutions. Go to our website to try it out yourself!";
if(xmlText.length()>0){
final JLabel url=new JLabel("<html><center>PJES from www.idrsolutions.com");
url.setForeground(Color.blue);
url.setHorizontalAlignment(JLabel.CENTER);
url.setAlignmentX(Component.CENTER_ALIGNMENT);
//@kieran - cursor
url.addMouseListener(new MouseListener() {
public void mouseEntered(MouseEvent e) {
details.setCursor(new Cursor(Cursor.HAND_CURSOR));
url.setText("<html><center><a href=\"http://www.idrsolutions.com\">PJES from www.idrsolutions.com</a></center>");
}
public void mouseExited(MouseEvent e) {
details.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
url.setText("<html><center>PJES from www.idrsolutions.com");
}
//>>> DON'T UNCOMMENT THIS LINE, causes major rotation issues, only useful for debuging <<< if (decode_pdf.getDisplayView() == Display.SINGLE_PAGE) {
rotation = currentPageData.getRotation(commonValues.getCurrentPage());
}
//else
//rotation=0;
if (getSelectedComboIndex(Commands.ROTATION) != (rotation / 90)) {
setSelectedComboIndex(Commands.ROTATION, (rotation / 90));
} else if (!commonValues.isProcessing()) {
decode_pdf.repaint();
}
}
/**
* show document properties
*/ private JScrollPane getPropertiesBox(String file, String path, String user_dir, long size, int pageCount,int currentPage) {
//add in if Linearized if(this.decode_pdf.getJPedalObject(PdfDictionary.Linearized)!=null)
g6Text=g6Text+" ("+Messages.getMessage("PdfViewerLinearized.text")+") ";
/**
* optional tab for new XML style info
*/
PdfFileInformation currentFileInformation=decode_pdf.getFileInformationData();
String xmlText=currentFileInformation.getFileXMLMetaData(); if(xmlText.length()>0){
tabbedPane.add(getXMLInfoBox(xmlText));
tabbedPane.setTitleAt(nextTab, "XML");
}
/** sort form names in alphabetical order */
Collections.sort(formsOnPage);
//get FormRenderer and Data objects
AcroRenderer renderer = decode_pdf.getFormRenderer(); if(renderer==null) return scroll;
GUIData formData=renderer.getCompData();
/**
* populate our list with details
*/ for (int i = 0; i < formCount; i++) {
// get name of form
String formName = (String) formsOnPage.get(i);
//swing component we map data into
Component[] comp = (Component[]) formRenderer.getComponentsByName(formName);
if (comp != null) {
//number of components - may be several child items
//int count = comp.length;
//take value or first if array to check for types (will be same if children)
FormObject formObj=null;
//extract list of actual PDF references to display and get FormObject
String PDFrefs = "PDF ref=";
JLabel ref = new JLabel();
//actual data read from PDF
Object[] rawFormData=formData.getRawForm(formName); int objCount=rawFormData.length; for(int ii=0;ii<objCount;ii++){
formObj=(FormObject)rawFormData[ii];
PDFrefs=PDFrefs+" "+formObj.getObjectRefAsString();
}
ref.setText(PDFrefs);
/** display the form component description */
// int formComponentType = ((Integer) formData.getTypeValueByName(formName)).intValue();
String formDescription = formName;
JLabel header = new JLabel(formDescription);
JLabel type = new JLabel();
type.setText("Type="+
PdfDictionary.showAsConstant(formObj.getParameterConstant(PdfDictionary.Type))+
" Subtype="+PdfDictionary.showAsConstant(formObj.getParameterConstant(PdfDictionary.Subtype)));
/** get the current Swing component type */
String standardDetails = "java class=" + comp[0].getClass();
menu.addPopupMenuListener(new PopupMenuListener() { public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
options.setSelected(false);
}
public void popupMenuCanceled(PopupMenuEvent e) {
options.setSelected(false);
}
});
}
return options;
}
/*
* Set Search Bar to be in the Top Button Bar
*/ public void searchInMenu(GUISearchWindow searchFrame){ this.searchFrame = searchFrame;
searchInMenu = true;
searchFrame.find(decode_pdf, commonValues);
// searchText.setPreferredSize(new Dimension(150,20));
topButtons.add(searchText);
topButtons.add(createMenuBarSearchOptions());
addButton(GUIFactory.BUTTONBAR, Messages.getMessage("PdfViewerSearch.Previous"), iconLocation+"search_previous.gif", Commands.PREVIOUSRESULT);
addButton(GUIFactory.BUTTONBAR, Messages.getMessage("PdfViewerSearch.Next"), iconLocation+"search_next.gif", Commands.NEXTRESULT);
//setup custom message and switch off error messages if used
customMessageHandler =(CustomMessageHandler)(decode_pdf.getExternalHandler(Options.CustomMessageOutput)); if(customMessageHandler!=null){
PdfDecoder.showErrorMessages=false;
SimpleViewer.showMessages=false;
}
/**
* Set up from properties
*/ try{
//Set viewer page inset
String propValue = properties.getValue("pageInsets"); if(propValue.length()>0)
inset = Integer.parseInt(propValue);
//Set whether to use hinting
propValue = properties.getValue("useHinting");
String propValue2 = System.getProperty("org.jpedal.useTTFontHinting");
//check JVM flag first if (propValue2 != null) {
//check if properties file conflicts if (propValue.length()>0 && !propValue2.toLowerCase().equals(propValue.toLowerCase()))
JOptionPane.showMessageDialog(null,Messages.getMessage("PdfCustomGui.hintingFlagFileConflict"));
if (propValue2.toLowerCase().equals("true"))
TTGlyph.useHinting = true; else
TTGlyph.useHinting = false;
//Dpi is taken into effect when zoom is called
propValue = properties.getValue("DPI"); if(propValue.length()>0)
decode_pdf.getDPIFactory().setDpi(Integer.parseInt(propValue));
//@kieran - in this code, it will break if we add new value for all users.
//could we recode these all defensively so change one below to
String val= properties.getValue("highlightBoxColor"); //empty string to old users if(val.length()>0)
DecoderOptions.highlightColor = new Color(Integer.parseInt(val));
//how it is at moment
//PdfDecoder.highlightColor = new Color(Integer.parseInt(properties.getValue("highlightBoxColor")));
////////////////////////////
propValue = properties.getValue("highlightTextColor"); if(propValue.length()>0)
DecoderOptions.backgroundColor = new Color(Integer.parseInt(propValue));
//Add Background color to the panel to help break up view if (decode_pdf.useNewGraphicsMode)
decode_pdf.setBackground(new Color(55,55,65)); else
decode_pdf.setBackground(new Color(190,190,190));
scalingBox=new SwingCombo(scalingValues);
scalingBox.setBackground(Color.white);
scalingBox.setEditable(true);
scalingBox.setSelectedIndex(defaultSelection); //set default before we add a listener
//if you enable, remember to change rotation and quality Comboboxes
//scalingBox.setPreferredSize(new Dimension(85,25));
rotationBox=new SwingCombo(rotationValues);
rotationBox.setBackground(Color.white);
rotationBox.setSelectedIndex(0); //set default before we add a listener
/**
* add the pdf display to show page
**/
JPanel containerForThumbnails=new JPanel(); if(isSingle){
previewOnSingleScroll = properties.getValue("previewOnSingleScroll").toLowerCase().equals("true"); if(previewOnSingleScroll){
thumbscroll = new JScrollBar(JScrollBar.VERTICAL,0,1,0, 1);
if (scrollListener == null){
scrollListener = new ScrollListener();
scrollMouseListener = new ScrollMouseListener();
}
thumbscroll.addAdjustmentListener(scrollListener);
thumbscroll.addMouseListener(scrollMouseListener);
//thumbscroll.addMouseMotionListener(scrollMouseListener);
if(isSingle){
/**
* Create a left-right split pane with tabs
* and add to main display
*/
navOptionsPanel.setTabPlacement(JTabbedPane.LEFT);
navOptionsPanel.setOpaque(true);
navOptionsPanel.setMinimumSize(new Dimension(0,100));
navOptionsPanel.setName("NavPanel");
if(previewOnSingleScroll)
displayPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, navOptionsPanel, containerForThumbnails); else
displayPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, navOptionsPanel, scrollPane);
displayPane.setOneTouchExpandable(false);
//update scaling when divider moved
displayPane.addPropertyChangeListener("dividerLocation", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) {
//hack to get it to use current values instead of old values
scrollPane.getViewport().setSize((scrollPane.getViewport().getWidth()+((Integer)e.getOldValue()).intValue()-((Integer)e.getNewValue()).intValue()),
scrollPane.getViewport().getHeight());
/**
* set colours on display boxes and add listener to page number
*/
pageCounter2.setEditable(true);
pageCounter2.setToolTipText(Messages.getMessage("PdfViewerTooltip.goto"));
pageCounter2.setBorder(BorderFactory.createLineBorder(Color.black));
pageCounter2.setColumns(4);
pageCounter2.setMaximumSize(pageCounter2.getPreferredSize());
/**
* create a menu bar and add to display
*/
JPanel top = new JPanel();
top.setLayout(new BorderLayout()); if(frame instanceof JFrame)
((JFrame)frame).getContentPane().add(top, BorderLayout.NORTH); else
frame.add(top, BorderLayout.NORTH);
/** nav bar at bottom to select pages and setup Toolbar on it*/
/**
* Menu bar for using the majority of functions
*/
createMainMenu(true);
//createSwingMenu(true);
/**
* sets up all the toolbar items
*/
//<start-wrap>
addButton(GUIFactory.BUTTONBAR,Messages.getMessage("PdfViewerToolbarTooltip.openFile"),iconLocation+"open.gif",Commands.OPENFILE);
//<end-wrap>
if (!useNewLayout || commonValues.getModeOfOperation()==Values.RUNNING_PLUGIN)
addButton(GUIFactory.BUTTONBAR,Messages.getMessage("PdfViewerToolbarTooltip.about"),iconLocation+"about.gif",Commands.INFO);
/**
* navigation toolbar for moving between pages
*/
createNavbar();
//<start-wrap>
addCursor();
//<end-wrap>
// p.setButtonDefaults(defaultValues);
/**
* external/itext button option example adding new option to Export menu
* an icon is set wtih location on classpath
* "/org/jpedal/examples/simpleviewer/res/newfunction.gif"
* Make sure it exists at location and is copied into jar if recompiled
*/
//currentGUI.addButton(currentGUI.BUTTONBAR,tooltip,"/org/jpedal/examples/simpleviewer/res/newfunction.gif",Commands.NEWFUNCTION);
/**
* external/itext menu option example adding new option to Export menu
* Tooltip text can be externalised in Messages.getMessage("PdfViewerTooltip.NEWFUNCTION")
* and text added into files in res package
*/
/**
* set display to occupy half screen size and display, add listener and
* make sure appears in centre
*/ if(commonValues.getModeOfOperation()!=Values.RUNNING_APPLET){
Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); int width = d.width / 2, height = d.height / 2; if(width<minimumScreenWidth)
width=minimumScreenWidth;
//allow user to alter size
String customWindowSize=System.getProperty("org.jpedal.startWindowSize"); if(customWindowSize!=null){
System.out.println(values.countTokens()); if(values.countTokens()!=2) throw new RuntimeException("Unable to use value for org.jpedal.startWindowSize="+customWindowSize+"\nValue should be in format org.jpedal.startWindowSize=200x300");
}catch(Exception ee){ throw new RuntimeException("Unable to use value for org.jpedal.startWindowSize="+customWindowSize+"\nValue should be in format org.jpedal.startWindowSize=200x300");
}
}
if (frame instanceof JFrame) {
((JFrame)frame).setSize(width, height);
((JFrame)frame).setLocationRelativeTo(null); //centre on screen
((JFrame)frame).setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
((JFrame)frame).addWindowListener(new FrameCloser((Commands) currentCommands, this,decode_pdf,(Printer)currentPrinter,thumbnails,commonValues,properties));
((JFrame)frame).setVisible(true);
}
}
/**Ensure Document is redrawn when frame is resized and scaling set to width, height or window*/
frame.addComponentListener(new ComponentListener(){ public void componentHidden(ComponentEvent e) {} public void componentMoved(ComponentEvent e) {} public void componentResized(ComponentEvent e) { if(decode_pdf.getParent()!=null &&
(getSelectedComboIndex(Commands.SCALING)<3 || decode_pdf.getDisplayView() == Display.FACING)) //always rezoom in facing mode for turnover
zoom(false);
} public void componentShown(ComponentEvent e) {}
});
//add a border if (decode_pdf.useNewGraphicsMode) {
decode_pdf.setPDFBorder(new AbstractBorder() {
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Graphics2D g2 = (Graphics2D) g;
int systemMask = java.awt.Event.CTRL_MASK; if(decode_pdf.isRunningOnMac){
systemMask = java.awt.Event.META_MASK;
}
switch(ID){
case Commands.FIND:
menuItem.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F,systemMask)); break;
case Commands.SAVE:
menuItem.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S,
systemMask)); break; case Commands.PRINT:
menuItem.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P,
systemMask)); break; case Commands.EXIT:
menuItem.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q,
systemMask)); break; case Commands.DOCINFO:
menuItem.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D,
systemMask)); break; case Commands.OPENFILE:
menuItem.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O,
systemMask)); break; case Commands.OPENURL:
menuItem.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_U,
systemMask)); break; case Commands.PREVIOUSDOCUMENT:
menuItem.setAccelerator( KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_LEFT,java.awt.event.KeyEvent.ALT_MASK | java.awt.event.KeyEvent.SHIFT_MASK)); break; case Commands.NEXTDOCUMENT:
menuItem.setAccelerator( KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_RIGHT,java.awt.event.KeyEvent.ALT_MASK | java.awt.event.KeyEvent.SHIFT_MASK)); break; case Commands.FIRSTPAGE:
menuItem.setAccelerator( KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_HOME,systemMask)); break; case Commands.BACKPAGE:
menuItem.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_UP, java.awt.event.KeyEvent.CTRL_MASK)); break; case Commands.FORWARDPAGE:
menuItem.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DOWN, java.awt.event.KeyEvent.CTRL_MASK)); break; case Commands.LASTPAGE:
menuItem.setAccelerator( KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_END,systemMask)); break; case Commands.GOTO:
menuItem.setAccelerator( KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N,systemMask | java.awt.event.KeyEvent.SHIFT_MASK)); break; case Commands.BITMAP:
menuItem.setAccelerator( KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B,java.awt.event.KeyEvent.ALT_MASK)); break; case Commands.COPY:
menuItem.setAccelerator( KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C,systemMask)); break; case Commands.SELECTALL:
menuItem.setAccelerator( KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A,systemMask)); break; case Commands.DESELECTALL:
menuItem.setAccelerator( KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A,systemMask+java.awt.event.KeyEvent.SHIFT_DOWN_MASK)); break; case Commands.PREFERENCES:
menuItem.setAccelerator( KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_K,systemMask)); break;
}
}
/* (non-Javadoc)
* @see org.jpedal.examples.simpleviewer.gui.swing.GUIFactory#addButton(int, java.lang.String, java.lang.String, int)
*/ public void addButton(int line,String toolTip,String path,final int ID) {
GUIButton newButton = new SwingButton();
/**specific buttons*/ switch(ID){
case Commands.FIRSTPAGE:
newButton=first; break; case Commands.FBACKPAGE:
newButton=fback; break; case Commands.BACKPAGE:
newButton=back; break; case Commands.FORWARDPAGE:
newButton=forward; break; case Commands.FFORWARDPAGE:
newButton=fforward; break; case Commands.LASTPAGE:
newButton=end; break; case Commands.SNAPSHOT:
newButton=snapshotButton; break; case Commands.SINGLE:
newButton=singleButton;
newButton.setName("SINGLE"); break; case Commands.CONTINUOUS:
newButton=continuousButton;
newButton.setName("CONTINUOUS"); break; case Commands.CONTINUOUS_FACING:
newButton=continuousFacingButton;
newButton.setName("CONTINUOUS_FACING"); break; case Commands.FACING:
newButton=facingButton;
newButton.setName("FACING"); break; case Commands.PAGEFLOW:
newButton=pageFlowButton;
newButton.setName("PAGEFLOW"); break; case Commands.PREVIOUSRESULT:
newButton=previousSearch;
newButton.setName("PREVIOUSRESULT"); break; case Commands.NEXTRESULT:
newButton=nextSearch;
newButton.setName("NEXTRESULT"); break; case Commands.OPENFILE:
newButton=openButton;
newButton.setName("open"); break; case Commands.PRINT:
newButton=printButton;
newButton.setName("print"); break; case Commands.FIND:
newButton=searchButton;
newButton.setName("search"); break; case Commands.DOCINFO:
newButton=docPropButton; break; case Commands.INFO:
newButton=infoButton; break; case Commands.MOUSEMODE:
newButton=mouseMode;
newButton.setName("mousemode"); break;
}
//@kieran : This may be a good idea. See how you feel when time to commit.
((SwingButton)newButton).addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) { if(SingleDisplay.allowChangeCursor)
((SwingButton)e.getSource()).setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
} public void mouseExited(MouseEvent e) { if(SingleDisplay.allowChangeCursor)
((SwingButton)e.getSource()).setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
});
//remove background for the applet as default L&F has a shaded toolbar if (mode==Values.RUNNING_APPLET)
((AbstractButton) newButton).setContentAreaFilled(false);
//add to toolbar if(line==BUTTONBAR || mode==Values.RUNNING_PLUGIN){
topButtons.add((AbstractButton) newButton);
//add spaces for plugin if(mode==Values.RUNNING_PLUGIN && (mode==Commands.LASTPAGE || mode==Commands.PAGEFLOW))
topButtons.add(Box.createHorizontalGlue());
switch(ID){ case Commands.OPENFILE :
open = (JMenuItem)menuItem;
parentMenu.add(open); break; case Commands.OPENURL :
openUrl = (JMenuItem)menuItem;
parentMenu.add(openUrl); break; case Commands.SAVE :
save = (JMenuItem)menuItem;
parentMenu.add(save); break; case Commands.SAVEFORM :
reSaveAsForms = (JMenuItem)menuItem;
//add name to resave option so fest can get to it.
reSaveAsForms.setName("resaveForms");
parentMenu.add(reSaveAsForms); break; case Commands.FIND :
find = (JMenuItem)menuItem;
parentMenu.add(find); break; case Commands.DOCINFO :
documentProperties = (JMenuItem)menuItem;
parentMenu.add(documentProperties); break; case Commands.SIGN :
signPDF = (JMenuItem)menuItem;
parentMenu.add(signPDF); break; case Commands.PRINT :
print = (JMenuItem)menuItem;
parentMenu.add(print); break; case Commands.EXIT :
exit = (JMenuItem)menuItem;
//set name to exit so fest can find it
exit.setName("exit");
parentMenu.add(exit); break; case Commands.COPY :
copy = (JMenuItem)menuItem;
parentMenu.add(copy); break; case Commands.SELECTALL :
selectAll = (JMenuItem)menuItem;
parentMenu.add(selectAll); break; case Commands.DESELECTALL :
deselectAll = (JMenuItem)menuItem;
parentMenu.add(deselectAll); break; case Commands.PREFERENCES :
preferences = (JMenuItem)menuItem;
parentMenu.add(preferences); break; case Commands.FIRSTPAGE :
firstPage = (JMenuItem)menuItem;
parentMenu.add(firstPage); break; case Commands.BACKPAGE :
backPage = (JMenuItem)menuItem;
parentMenu.add(backPage); break; case Commands.FORWARDPAGE :
forwardPage = (JMenuItem)menuItem;
parentMenu.add(forwardPage); break; case Commands.LASTPAGE :
lastPage = (JMenuItem)menuItem;
parentMenu.add(lastPage); break; case Commands.GOTO :
goTo = (JMenuItem)menuItem;
parentMenu.add(goTo); break; case Commands.PREVIOUSDOCUMENT :
previousDocument = (JMenuItem)menuItem;
parentMenu.add(previousDocument); break; case Commands.NEXTDOCUMENT :
nextDocument = (JMenuItem)menuItem;
parentMenu.add(nextDocument); break; case Commands.FULLSCREEN :
fullscreen = (JMenuItem)menuItem;
parentMenu.add(fullscreen); break; case Commands.MOUSEMODE :
fullscreen = (JMenuItem)menuItem;
parentMenu.add(fullscreen); break; case Commands.PANMODE :
panMode = (JMenuItem)menuItem;
parentMenu.add(panMode); break; case Commands.TEXTSELECT :
textSelect = (JMenuItem)menuItem;
parentMenu.add(textSelect); break; case Commands.SEPARATECOVER :
separateCover = (JCheckBoxMenuItem)menuItem; boolean separateCoverOn = properties.getValue("separateCoverOn").toLowerCase().equals("true");
separateCover.setState(separateCoverOn);
SingleDisplay.default_separateCover = separateCoverOn;
parentMenu.add(separateCover); break; case Commands.CASCADE :
cascade = (JMenuItem)menuItem;
parentMenu.add(cascade); break; case Commands.TILE :
tile = (JMenuItem)menuItem;
parentMenu.add(tile); break; case Commands.PDF :
onePerPage = (JMenuItem)menuItem;
parentMenu.add(onePerPage); break; case Commands.NUP :
nup = (JMenuItem)menuItem;
parentMenu.add(nup); break; case Commands.HANDOUTS :
handouts = (JMenuItem)menuItem;
parentMenu.add(handouts); break; case Commands.IMAGES :
images = (JMenuItem)menuItem;
parentMenu.add(images); break; case Commands.TEXT : this.text = (JMenuItem)menuItem;
parentMenu.add(this.text); break; case Commands.BITMAP :
bitmap = (JMenuItem)menuItem;
parentMenu.add(bitmap); break; case Commands.ROTATE :
rotatePages = (JMenuItem)menuItem;
parentMenu.add(rotatePages); break; case Commands.DELETE :
deletePages = (JMenuItem)menuItem;
parentMenu.add(deletePages); break; case Commands.ADD :
addPage = (JMenuItem)menuItem;
parentMenu.add(addPage); break; case Commands.ADDHEADERFOOTER :
addHeaderFooter = (JMenuItem)menuItem;
parentMenu.add(addHeaderFooter); break; case Commands.STAMPTEXT :
stampText = (JMenuItem)menuItem;
parentMenu.add(stampText); break; case Commands.STAMPIMAGE :
stampImage = (JMenuItem)menuItem;
parentMenu.add(stampImage); break; case Commands.SETCROP :
crop = (JMenuItem)menuItem;
parentMenu.add(crop); break; case Commands.VISITWEBSITE :
visitWebsite = (JMenuItem)menuItem;
parentMenu.add(visitWebsite); break; case Commands.TIP :
tipOfTheDay = (JMenuItem)menuItem;
parentMenu.add(tipOfTheDay); break; case Commands.UPDATE :
checkUpdates = (JMenuItem)menuItem;
parentMenu.add(checkUpdates); break; case Commands.INFO :
about = (JMenuItem)menuItem;
parentMenu.add(about); break;
default : if (menuItem instanceof JMenuItem)
parentMenu.add((JMenuItem)menuItem); else if (menuItem instanceof JCheckBoxMenuItem)
parentMenu.add((JCheckBoxMenuItem)menuItem);
}
}
/**
* @return the path of the directory containing overriding icons
*/ public String getIconLocation() { return iconLocation;
}
/**
* Retrieve the URL of the actual image to use f
* @param path Preferred name and location
* @return URL of file to use
*/ public URL getURLForImage(String path) {
String file = path.substring(path.lastIndexOf("/")+1);
URL url;
//<start-wrap>
//Check if file location provided
path = path.substring(0, path.indexOf('.'))+".gif";
File p = new File(path);
url = getClass().getResource(path);
//It's a file location check for gif if(p.exists()){ try {
url = p.toURI().toURL();
} catch (MalformedURLException e) {
}
}
if(url==null){
path = path.substring(0, path.indexOf('.'))+".png";
p = new File(path);
url = getClass().getResource(path);
SimpleAttributeSet token_attribute = new SimpleAttributeSet();
SimpleAttributeSet text_attribute = new SimpleAttributeSet();
SimpleAttributeSet plain_attribute = new SimpleAttributeSet();
StyleConstants.setForeground(token_attribute, Color.blue);
StyleConstants.setForeground(text_attribute, Color.black);
StyleConstants.setForeground(plain_attribute, Color.black); int pointer=0;
/**put content in and color XML*/ if((useXML)&&(content!=null)){
//tokenise and write out data
StringTokenizer data_As_tokens = new StringTokenizer(content,"<>", true);
while (data_As_tokens.hasMoreTokens()) {
String next_item = data_As_tokens.nextToken();
if ((next_item.equals("<"))&&((data_As_tokens.hasMoreTokens()))) {
//get current location and factor out scaling so we can put back at same page
//final float x= (decode_pdf.getVisibleRect().x/scaling);
//final float y= (decode_pdf.getVisibleRect().y/scaling);
//System.out.println(x+" "+y+" "+scaling+" "+decode_pdf.getVisibleRect());
/** update value and GUI */ int index=getSelectedComboIndex(Commands.SCALING);
//No long pageFlow. enable scaling option
scalingBox.setEnabled(true);
}
if(index==-1 && decode_pdf.getDisplayView()!=Display.PAGEFLOW){
String numberValue=(String)getSelectedComboItem(Commands.SCALING); float zoom=-1; if((numberValue!=null)&&(numberValue.length()>0)){ try{
zoom= Float.parseFloat(numberValue);
}catch(Exception e){
zoom=-1;
//its got characters in it so get first valid number string int length=numberValue.length(); int ii=0; while(ii<length){ char c=numberValue.charAt(ii); if(((c>='0')&&(c<='9'))|(c=='.'))
ii++; else break;
}
if(ii>0)
numberValue=numberValue.substring(0,ii);
//try again if we reset above if(zoom==-1){ try{
zoom= Float.parseFloat(numberValue);
}catch(Exception e1){zoom=-1;}
}
} if(zoom>1000){
zoom=1000;
}
}
//if nothing off either attempt, use window value if(zoom==-1){
//its not set so use To window value
index=defaultSelection;
setSelectedComboIndex(Commands.SCALING, index);
}else{
scaling=decode_pdf.getDPIFactory().adjustScaling(zoom/100);
if (isRotated) {
cw = pageData.getCropBoxHeight(leftPage);
//if first or last page double the width, otherwise add other page width if (leftPage+1 > commonValues.getPageCount() || leftPage == 1)
cw = cw * 2; else
cw += pageData.getCropBoxHeight(leftPage+1);
//if first or last page double the width, otherwise add other page width if (leftPage+1 > commonValues.getPageCount())
cw = cw * 2; else
cw += pageData.getCropBoxWidth(leftPage+1);
//this check for 0 to avoid error and replace with 1
//PdfPageData pagedata = decode_pdf.getPdfPageData();
//if((pagedata.getCropBoxHeight(commonValues.getCurrentPage())*scaling<100) &&//keep the page bigger than 100 pixels high
// (pagedata.getCropBoxWidth(commonValues.getCurrentPage())*scaling<100) && commonValues.isPDF()){//keep the page bigger than 100 pixels wide
// scaling=1;
// setSelectedComboItem(Commands.SCALING,"100");
//}
// THIS section commented out so altering scalingbox does NOT reset rotation
//if(!scalingBox.getSelectedIndex()<3){
/**update our components*/
//resetRotationBox();
//}
//Ensure page rotation is taken into account
//int pageRot = decode_pdf.getPdfPageData().getRotation(commonValues.getCurrentPage());
//allow for clicking on it before page opened
decode_pdf.setPageParameters(scaling, page,rotation);
//Ensure the page is displayed in the correct rotation
setRotation();
//move to correct page
//setPageNumber();
//decode_pdf.setDisplayView(decode_pdf.getDisplayView(),Display.DISPLAY_CENTERED);
//open new page
//if((!commonValues.isProcessing())&&(commonValues.getCurrentPage()!=newPage)){
//move to correct page
//scrollToPage is handled via the page change code so no need to do it here
// if(commonValues.isPDF())
// scrollToPage(commonValues.getCurrentPage());
//scrollPane.getViewport().scrollRectToVisible(new Rectangle((int)(x*scaling)-1,(int)(y*scaling),1,1));
//System.out.println("Scroll to page="+y+" "+(y*scaling)+" "+scaling);
PageOffsets offsets = (PageOffsets)decode_pdf.getExternalHandler(Options.CurrentOffset); switch(decode_pdf.getDisplayView()) { case Display.CONTINUOUS_FACING: if (isRotated) {
cw = offsets.getMaxH()*2;
ch = offsets.getMaxW();
}else{
cw = offsets.getMaxW()*2;
ch = offsets.getMaxH();
} break; case Display.CONTINUOUS: if (isRotated) {
cw = offsets.getMaxH();
ch = offsets.getMaxW();
}else{
cw = offsets.getMaxW();
ch = offsets.getMaxH();
} break; case Display.FACING: int leftPage; if (currentCommands.getPages().getSeparateCover()) {
leftPage = (commonValues.getCurrentPage()/2)*2; if (commonValues.getPageCount() == 2)
leftPage = 1;
} else {
leftPage = commonValues.getCurrentPage(); if ((leftPage & 1)==0)
leftPage--;
}
if (isRotated) {
cw = pageData.getCropBoxHeight(leftPage);
//if first or last page double the width, otherwise add other page width if (leftPage+1 > commonValues.getPageCount() || leftPage == 1)
cw = cw * 2; else
cw += pageData.getCropBoxHeight(leftPage+1);
//if first or last page double the width, otherwise add other page width if (leftPage+1 > commonValues.getPageCount())
cw = cw * 2; else
cw += pageData.getCropBoxWidth(leftPage+1);
int ch = (int)(pageData.getCropBoxHeight(commonValues.getCurrentPage())*scaling); int cw = (int)(pageData.getCropBoxWidth(commonValues.getCurrentPage())*scaling);
int centerH = xCord + ((cw-scrollPane.getHorizontalScrollBar().getVisibleAmount())/2); int centerV = yCord + (ch-scrollPane.getVerticalScrollBar().getVisibleAmount())/2;
//PAGEFLOW works differently if(decode_pdf.getDisplayView()==Display.PAGEFLOW)
centerH=xCord-decode_pdf.getInsetW();
//Set textbox size int col = ("/"+commonValues.getPageCount()).length(); if (decode_pdf.getDisplayView() == Display.FACING || decode_pdf.getDisplayView() == Display.CONTINUOUS_FACING)
col = col * 2; if (col < 4)
col = 4; if (col > 10)
col = 10;
pageCounter2.setColumns(col);
pageCounter2.setMaximumSize(pageCounter2.getPreferredSize());
navToolBar.invalidate();
navToolBar.doLayout();
//allow user to now open tabs
tabsNotInitialised=false;
/**ensure text and color extracted. If you do not need color, take out
* line for faster decode
*/ if(isContentExtractor)
decode_pdf.setExtractionMode(PdfDecoder.TEXT); else
decode_pdf.setExtractionMode(PdfDecoder.TEXT+PdfDecoder.TEXTCOLOR);
//remove any search highlight
decode_pdf.getTextLines().clearHighlights();
//<start-gpl>
//kick-off thread to create pages if(decode_pdf.getDisplayView() == Display.FACING){
/**reset as rotation may change!*/
//decode_pdf.setPageParameters(getScaling(), commonValues.getCurrentPage());
//resize (ensure at least certain size)
//must be here as otherwise will not redraw if new page opened
//in multipage mode
zoom(false);
scrollToPage(commonValues.getCurrentPage());
return ;
}else if(decode_pdf.getDisplayView() == Display.PAGEFLOW){
//resize (ensure at least certain size)
//must be here as otherwise will not redraw if new page opened
//in multipage mode
zoom(false);
//stop user changing scaling while decode in progress
resetComboBoxes(false); if(!commonValues.isContentExtractor())
setPageLayoutButtonsEnabled(false);
//System.out.println(imageDetails.countTokens()+" ==>"+str);
//if single image check further
if(imageDetails.countTokens()>2){ //ignore forms
String imageName=imageDetails.nextToken();
String imageType=imageDetails.nextToken();
String imageW=imageDetails.nextToken().substring(2);
String imageH=imageDetails.nextToken().substring(2);
String bitsPerPixel=imageDetails.nextToken();
String dpi=imageDetails.nextToken().substring(4);
//we can also look at PDF creation tool
String[] metaData=decode_pdf.getFileInformationData().getFieldValues();
//test here and take action or set flag
if(Integer.parseInt(dpi)<144 && metaData[5].equals("iText 2.1.7 by 1T3XT")){
System.out.println("Low resolution image will not print well in Java");
}
}
}
/**/
/**
* Tell user if hinting is probably required
*/ if(decode_pdf.getPageDecodeStatus(DecodeStatus.TTHintingRequired)){
String status = Messages.getMessage("PdfCustomGui.ttHintingRequired");
String status = ("This page contains non-embedded CID fonts \n" +
decode_pdf.getPageDecodeStatusReport(DecodeStatus.NonEmbeddedCIDFonts)+
"\nwhich may need mapping to display correctly.\n" +
"See http://www.jpedal.org/support_FontSub.php");
//create custom annot icons if(addUniqueIconToFileAttachment){
/**
* ANNOTATIONS code to create unique icons
*
* this code allows you to create a unique set on icons for any type of annotations, with
* an icons for every annotation, not just types.
*/
FormFactory formfactory = decode_pdf.getFormRenderer().getFormFactory();
//swing needs it to be done with invokeLater if(formfactory.getType()== FormFactory.SWING){ final Runnable doPaintComponent2 = new Runnable() { public void run() {
//tell user if we had a memory error on decodePage
String status=decode_pdf.getPageDecodeReport(); if((status.indexOf("java.lang.OutOfMemoryError")!=-1)&& PdfDecoder.showErrorMessages){
status = (Messages.getMessage("PdfViewer.OutOfMemoryDisplayError")+
Messages.getMessage("PdfViewer.OutOfMemoryDisplayError1")+
Messages.getMessage("PdfViewer.OutOfMemoryDisplayError2")+
Messages.getMessage("PdfViewer.OutOfMemoryDisplayError3")+
Messages.getMessage("PdfViewer.OutOfMemoryDisplayError4")+
Messages.getMessage("PdfViewer.OutOfMemoryDisplayError5"));
if (decode_pdf.getPageCount()>0 && thumbnails.isShownOnscreen() && decode_pdf.getDisplayView()==Display.SINGLE_PAGE)
thumbnails.generateOtherVisibleThumbnails(commonValues.getCurrentPage());
} catch (Exception e) {
e.printStackTrace();
commonValues.setProcessing(false);//remove processing flag so that the viewer can be exited.
setViewerTitle(null); //restore title
}
selectBookmark();
//Update multibox
statusBar.setProgress(100); if (useNewLayout) {
// ActionListener listener = new ActionListener(){
// public void actionPerformed(ActionEvent e) {
// setMultibox(new int[]{});
// }
// };
// t = new Timer(800, listener);
// t.setRepeats(false);
// t.start();
//reanable user changing scaling
resetComboBoxes(true); if(decode_pdf.getPageCount()>1 && !commonValues.isContentExtractor())
setPageLayoutButtonsEnabled(true);
addFormsListeners();
//resize (ensure at least certain size)
//zoom(flase) is called twice so remove this call
//zoom(false);
// sample code to add shapes and text on current page - should be called AFTER page decoded for display
// (can appear on multiple pages for printing)
//
// in this example, we create a rectangle, a filled rectangle and draw some text.
//initialise objects arrays - we will put 4 shapes on the page
// (using PDF co-ordinates with origin bottom left corner)
/*int count=4; //adding shapes to page
// Due to the way some pdf's are created it is necessery to take the offset of a page
// into account when addding custom objects to the page. Variables mX and mY represent
// that offset and need to be taken in to account when placing any additional object
// on a page.
int mX = decode_pdf.getPdfPageData().getMediaBoxX(1);
int mY = decode_pdf.getPdfPageData().getMediaBoxY(1);
int[] type=new int[count];
Color[] colors=new Color[count];
Object[] obj=new Object[count];
//example stroked shape
type[0]= org.jpedal.render.DynamicVectorRenderer.STROKEDSHAPE;
colors[0]=Color.RED;
obj[0]=new Rectangle(35+mX,35+mY,510,50); //ALSO sets location. Any shape can be used
//example filled shape
type[1]= org.jpedal.render.DynamicVectorRenderer.FILLEDSHAPE;
colors[1]=Color.GREEN;
obj[1]=new Rectangle(40+mX,40+mY,500,40); //ALSO sets location. Any shape can be used
//example text object
type[2]= org.jpedal.render.DynamicVectorRenderer.STRING;
org.jpedal.render.TextObject textObject=new org.jpedal.render.TextObject(); //composite object so we can pass in parameters
textObject.x=40+mX;
textObject.y=40+mY;
textObject.text="Example text on page "+commonValues.getCurrentPage();
textObject.font=new Font("Serif",Font.PLAIN,48);
colors[2]=Color.BLUE;
obj[2]=textObject; //ALSO sets location
//example custom (from version 3.40)
type[3]=org.jpedal.render.DynamicVectorRenderer.CUSTOM;
//pass into JPEDAL after page decoded - will be removed automatically on new page/open file
//BUT PRINTING retains values until manually removed
try{
decode_pdf.drawAdditionalObjectsOverPage(commonValues.getCurrentPage(),type,colors,obj);
}catch(PdfException e){
e.printStackTrace();
}
/**/
//this code will remove ALL items already drawn on page
//try{
// decode_pdf.flushAdditionalObjectsOnPage(commonValues.getCurrentPage());
//}catch(PdfException e){
// e.printStackTrace();
// //ShowGUIMessage.showGUIMessage( "", new JLabel(e.getMessage()),"Exception adding object to display");
//}
//Example to PRINT (needs to be create beforehand)
//objects can be the same as from draw
/* for(int pages=1;pages<decode_pdf.getPageCount()+1;pages++){ //note +1 for last page!!!
int count = 4;
// Due to the way some pdf's are created it is necessery to take the offset of a page
// into account when addding custom objects to the page. Variables mX and mY represent
// that offset and need to be taken in to account when placing any additional object
// on a page.
int mX = decode_pdf.getPdfPageData().getMediaBoxX(1);
int mY = decode_pdf.getPdfPageData().getMediaBoxY(1);
int[] typePrint=new int[count];
Color[] colorsPrint=new Color[count];
Object[] objPrint=new Object[count];
//example custom (from version 3.40)
typePrint[0]=org.jpedal.render.DynamicVectorRenderer.CUSTOM;
//example stroked shape
typePrint[1]= org.jpedal.render.DynamicVectorRenderer.STROKEDSHAPE;
colorsPrint[1]=Color.RED;
objPrint[1]=new Rectangle(35+mX,35+mY,510,50); //ALSO sets location. Any shape can be used
//example filled shape
typePrint[2]= org.jpedal.render.DynamicVectorRenderer.FILLEDSHAPE;
colorsPrint[2]=Color.GREEN;
objPrint[2]=new Rectangle(40+mX,40+mY,500,40); //ALSO sets location. Any shape can be used
//example text object
typePrint[3]= org.jpedal.render.DynamicVectorRenderer.STRING;
org.jpedal.render.TextObject textPrintObject=new org.jpedal.render.TextObject(); //composite object so we can pass in parameters
textPrintObject.x=40+mX;
textPrintObject.y=40+mY;
textPrintObject.text="Print Ex text on page "+pages;
textPrintObject.font=new Font("Serif",Font.PLAIN,48);
colorsPrint[3]=Color.BLUE;
objPrint[3]=textPrintObject; //ALSO sets location
//pass into JPEDAL after page decoded - will be removed automatically on new page/open file
//BUT PRINTING retains values until manually removed
try{
decode_pdf.printAdditionalObjectsOverPage(pages,typePrint ,colorsPrint, objPrint);
}catch(PdfException e){
e.printStackTrace();
}
}
/**/
//global printout
/* int count = 1;
// Due to the way some pdf's are created it is necessery to take the offset of a page
// into account when addding custom objects to the page. Variables medX and medY represent
// that offset and need to be taken in to account when placing any additional object
// on a page.
int medX = decode_pdf.getPdfPageData().getMediaBoxX(1);
int medY = decode_pdf.getPdfPageData().getMediaBoxY(1);
int[] typePrint=new int[count];
Color[] colorsPrint=new Color[count];
Object[] objPrint=new Object[count];
//example custom (from version 3.40)
typePrint[0]=org.jpedal.render.DynamicVectorRenderer.CUSTOM;
//pass into JPEDAL after page decoded - will be removed automatically on new page/open file
//BUT PRINTING retains values until manually removed
try{
decode_pdf.printAdditionalObjectsOverAllPages(typePrint ,colorsPrint, objPrint);
}catch(PdfException e){
e.printStackTrace();
}/**/
//
/**this method adds listeners to GUI widgets to track changes*/ public void addFormsListeners(){
//rest forms changed flag to show no changes
commonValues.setFormsChanged(false);
/**see if flag set - not default behaviour*/ boolean showMessage=false;
String formsFlag=System.getProperty("org.jpedal.listenforms"); if(formsFlag!=null)
showMessage=true;
//get the form renderer which also contains the processed form data.
//if you want simple form data, also look at the ExtractFormDataAsObject.java example
org.jpedal.objects.acroforms.rendering.AcroRenderer formRenderer=decode_pdf.getFormRenderer();
if(formRenderer==null) return;
//get list of forms on page
java.util.List formsOnPage=null;
/**
* once you have the name you can also use
* formRenderer.getComponentsByName(String objectName)
* to get all componentonce you know the name - return Object[] as
* can have multiple values (ie radio/check boxes)
*
*/ try {
formsOnPage = formRenderer.getComponentNameList(commonValues.getCurrentPage());
} catch (PdfException e) {
JPanel formPanel=new JPanel();
/**
* create a JPanel to list forms and tell user a box example
**/ if(showMessage){
formPanel.setLayout(new BoxLayout(formPanel,BoxLayout.Y_AXIS));
JLabel formHeader = new JLabel("This page contains "+formCount+" form objects");
formHeader.setFont(headFont);
formPanel.add(formHeader);
formPanel.add(Box.createRigidArea(new Dimension(10,10)));
JTextPane instructions = new JTextPane();
instructions.setPreferredSize(new Dimension(450,180));
instructions.setEditable(false);
instructions.setText("This provides a simple example of Forms handling. We have"+
" added a listener to each form so clicking on it shows the form name.\n\n"+
"Code is in addExampleListeners() in org.examples.simpleviewer.SimpleViewer\n\n"+
"This could be easily be extended to interface with a database directly "+
"or collect results on an action and write back using itext.\n\n"+
"Forms have been converted into Swing components and are directly accessible"+
" (as is the original data).\n\n"+
"If you don't like the standard SwingSet you can replace with your own set.");
instructions.setFont(textFont);
formPanel.add(instructions);
formPanel.add(Box.createRigidArea(new Dimension(10,10)));
}
/**
* pop-up to show forms on page
**/ if(showMessage){ final JDialog displayFrame = new JDialog((JFrame)null,true); if(commonValues.getModeOfOperation()!=Values.RUNNING_APPLET){
displayFrame.setLocationRelativeTo(null);
displayFrame.setLocation(frame.getLocationOnScreen().x+10,frame.getLocationOnScreen().y+10);
}
displayFrame.setSize(500,500);
displayFrame.setTitle("List of forms on this page");
displayFrame.getContentPane().setLayout(new BorderLayout());
displayFrame.getContentPane().add(scroll,BorderLayout.CENTER);
// close option just removes display
JButton no=new JButton(Messages.getMessage("PdfViewerButton.Close"));
no.setFont(new Font("SansSerif", Font.PLAIN, 12));
buttonBar.add(no,BorderLayout.EAST);
no.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
displayFrame.dispose();
}});
/**show the popup*/
displayFrame.setVisible(true);
}
}
/**
* put the outline data into a display panel which we can pop up
* for the user - outlines, thumbnails
*
private void createOutlinePanels() {
//boolean hasNavBars=false;
// set up first 10 thumbnails by default. Rest created as needed.
//add if statement or comment out this section to remove thumbnails
setupThumbnailPanel();
// add any outline
setBookmarks(false);
/**
* resize to show if there are nav bars
*
if(hasNavBars){
if(!thumbnails.isShownOnscreen()){
if( !commonValues.isContentExtractor())
navOptionsPanel.setVisible(true);
displayPane.setDividerLocation(divLocation);
//displayPane.invalidate();
//displayPane.repaint();
}
}
}/**/
// <start-thin> public void setupThumbnailPanel() {
//add listener so clicking on button changes to page - has to be in SimpleViewer so it can update it
Object[] buttons=thumbnails.getButtons(); for(int i=0;i<pages;i++)
((JButton)buttons[i]).addActionListener(new PageChanger(i));
//add global listener
thumbnails.addComponentListener();
}
}
// <end-thin>
public void setBookmarks(boolean alwaysGenerate) {
//ignore if not opened int currentSize=displayPane.getDividerLocation();
/** flatten out the tree so we can find the index of the selected node */
getFlattenedTreeNodes((TreeNode) treeModel.getRoot(), flattenedTree);
flattenedTree.remove(0); // remove the root node as we don't account for this
//align to viewer knows if page changed and set rotation to default for page
// if(pageToDisplay!=-1){
// currentCommands.gotoPage(Integer.toString(pageToDisplay));
// commonValues.setCurrentPage(pageToDisplay);
// setSelectedComboIndex(Commands.ROTATION, decode_pdf.getPdfPageData().getRotation(pageToDisplay)/90);
// }
}
// if((page==null)||(page.length()==0))
// page=tree.getPage(title);
//
// if(page!=null && page.length()>0){
// int pageToDisplay=Integer.parseInt(page);
//
// if((!commonValues.isProcessing())&&(commonValues.getCurrentPage()!=pageToDisplay)){
// commonValues.setCurrentPage(pageToDisplay);
// /**reset as rotation may change!*/
//
// decode_pdf.setPageParameters(getScaling(), commonValues.getCurrentPage());
// decodePage(false);
// }
//
// //Point p= tree.getPoint(title);
// //if(p!=null)
// // decode_pdf.ensurePointIsVisible(p);
//
// }else{
// showMessageDialog(Messages.getMessage("PdfViewerError.NoBookmarkLink")+title);
// System.out.println("No dest page set for "+title);
// }
}
});
}else{
tree.reset(null);
}
}
private static void getFlattenedTreeNodes(TreeNode theNode, List items) {
// add the item
items.add(theNode);
//moved to method so we can call it from the already added actions listeners on the forms public void checkformSavedMessage(){
String propValue = properties.getValue("showsaveformsmessage"); boolean showSaveFormsMessage = false;
/* (non-Javadoc)
* @see org.jpedal.examples.simpleviewer.gui.swing.GUIFactory#setPageNumber()
*/ public void setPageNumber() {
if (SwingUtilities.isEventDispatchThread())
setPageNumberWorker(); else {
Runnable r = new Runnable(){ public void run() {
setPageNumberWorker();
}
};
SwingUtilities.invokeLater(r);
}
}
public boolean isMultiPageTiff() { return isMultiPageTiff;
}
public void setMultiPageTiff(boolean isMultiPageTiff) { this.isMultiPageTiff = isMultiPageTiff;
}
if (!decode_pdf.isOpen() && !isMultiPageTiff) {
pageCounter2.setText(" ");
} else {
if(previewOnSingleScroll && thumbscroll!=null){
//hack because Listern does not f******g work on windows
scrollListener.ignoreChange=true;
thumbscroll.setMaximum(decode_pdf.getPageCount());
scrollListener.ignoreChange=true;
thumbscroll.setValue(commonValues.getCurrentPage()-1);
scrollListener.ignoreChange=false; if(debugThumbnail)
System.out.println("setpage="+commonValues.getCurrentPage());
}
int currentPage = commonValues.getCurrentPage(); if (decode_pdf.getDisplayView() == Display.FACING || decode_pdf.getDisplayView() == Display.CONTINUOUS_FACING) { if (decode_pdf.getPageCount() == 2)
pageCounter2.setText("1/2"); else if (currentCommands.getPages().getSeparateCover() || decode_pdf.getDisplayView() == Display.CONTINUOUS_FACING) { int base = currentPage & -2; if (base != decode_pdf.getPageCount() && base != 0)
pageCounter2.setText(base + "/"+(base+1)); else
pageCounter2.setText(String.valueOf(currentPage));
} else { int base = currentPage - (1 - (currentPage & 1)); if (base != decode_pdf.getPageCount())
pageCounter2.setText(base + "/" + (base+1)); else
pageCounter2.setText(String.valueOf(currentPage));
}
/**put page count in middle of forward and back*/
pageCounter1 = new JLabel(Messages.getMessage("PdfViewerPageLabel.text"));
pageCounter1.setOpaque(false);
navToolBar.add(pageCounter1);
// pageCounter2.setMaximumSize(new Dimension(5,50));
navToolBar.add(pageCounter2);
navToolBar.add(pageCounter3);
//<start-gpl>
//add buttons but not in Content Extractor if(!commonValues.isContentExtractor() && isSingle){
addButton(PAGES,Messages.getMessage("PageLayoutButton.SinglePage"),iconLocation+"single.gif",Commands.SINGLE);
//on top in plugin if(commonValues.getModeOfOperation()==Values.RUNNING_PLUGIN)
topButtons.add(navToolBar,BorderLayout.CENTER); else
navButtons.add(navToolBar,BorderLayout.CENTER);
commonValues.setCurrentPage(page);
setPageNumber();
//Page changed so save this page as last viewed
setThumbnails();
}
public void resetPageNav() {
pageCounter2.setText("");
pageCounter3.setText("");
}
public void setRotation(){
//PdfPageData currentPageData=decode_pdf.getPdfPageData();
//rotation=currentPageData.getRotation(commonValues.getCurrentPage());
//Broke files with when moving from rotated page to non rotated.
//The pages help previous rotation
//rotation = (rotation + (getSelectedComboIndex(Commands.ROTATION)*90));
//not set if I just run from jar as no IText.... if(includeAll && commonValues.isItextOnClasspath())
addMenuItem(fileMenu,
Messages.getMessage("PdfViewerFileMenuResaveForms.text"),
Messages.getMessage("PdfViewerFileMenuTooltip.saveForms"),
Commands.SAVEFORM);
// Remember to finish this off
addMenuItem(fileMenu, Messages.getMessage("PdfViewerFileMenuFind.text"), Messages.getMessage("PdfViewerFileMenuTooltip.find"), Commands.FIND);
/**
* external/itext menu option example adding new option to Export menu
*/
// addMenuItem(export,"NEW",tooltip,Commands.NEWFUNCTION);
/**
* external/itext menu option example adding new option to Export menu
* Tooltip text can be externalised in Messages.getMessage("PdfViewerTooltip.NEWFUNCTION")
* and text added into files in res package
*/
pdfMenu = new JMenu(Messages.getMessage("PdfViewerExportMenuPDF.text"));
pdfMenu.getPopupMenu().setLightWeightPopupEnabled(!Java3DHelper.isJava3DAvailable());
exportMenu.add(pdfMenu);
/**
* items options if IText available
*/ if(commonValues.isItextOnClasspath()){
pageToolsMenu = new JMenu(Messages.getMessage("PdfViewerPageToolsMenu.text"));
addToMainMenu(pageToolsMenu);
public JToolBar getDisplaySettingsBar() { return comboBoxBar;
}
public JMenuBar getMenuBar() { return currentMenu;
}
/* (non-Javadoc)
* @see org.jpedal.examples.simpleviewer.gui.swing.GUIFactory#showMessageDialog(java.lang.Object)
*/ public void showMessageDialog(Object message1){
/**
* allow user to replace messages with our action
*/ boolean showMessage=true;
//check user has not setup message and if we still show message if(customMessageHandler !=null)
showMessage= customMessageHandler.showMessage(message1);
/**
* allow user to replace messages with our action
*/ boolean showMessage=true;
//check user has not setup message and if we still show message if(customMessageHandler !=null)
showMessage= customMessageHandler.showMessage(message);
/* (non-Javadoc)
* @see org.jpedal.examples.simpleviewer.gui.swing.GUIFactory#showInputDialog(java.lang.Object, java.lang.String, int)
*/ public String showInputDialog(Object message, String title, int type) {
/**
* allow user to replace messages with our action
*/
String returnMessage=null;
//check user has not setup message and if we still show message if(customMessageHandler !=null)
returnMessage= customMessageHandler.requestInput(new Object[]{message,title, title});
/**
* allow user to replace messages with our action
*/
String returnMessage=null;
//check user has not setup message and if we still show message if(customMessageHandler !=null)
returnMessage= customMessageHandler.requestInput(new String[]{message});
/* (non-Javadoc)
* @see org.jpedal.examples.simpleviewer.gui.swing.GUIFactory#showOptionDialog(java.lang.Object, java.lang.String, int, int, java.lang.Object, java.lang.Object[], java.lang.Object)
*/ public int showOptionDialog(Object displayValue, String message, int option, int type, Object icon, Object[] options, Object initial) {
/**
* allow user to replace messages with our action
*/ int returnMessage=-1;
//check user has not setup message and if we still show message if(customMessageHandler !=null)
returnMessage= customMessageHandler.requestConfirm(new Object[]{displayValue, message, String.valueOf(option), String.valueOf(type), icon, options, initial});
/* (non-Javadoc)
* @see org.jpedal.examples.simpleviewer.gui.swing.GUIFactory#showConfirmDialog(java.lang.String, java.lang.String, int)
*/ public int showConfirmDialog(String message, String message2, int option) {
/**
* allow user to replace messages with our action
*/ int returnMessage=-1;
//check user has not setup message and if we still show message if(customMessageHandler !=null)
returnMessage= customMessageHandler.requestConfirm(new Object[]{message, message2, String.valueOf(option)});
/* (non-Javadoc)
* @see org.jpedal.examples.simpleviewer.gui.swing.GUIFactory#showOverwriteDialog(String file,boolean yesToAllPresent)
*/ public int showOverwriteDialog(String file,boolean yesToAllPresent) {
int n = -1;
/**
* allow user to replace messages with our action and remove popup
*/ int returnMessage=-1;
//check user has not setup message and if we still show message if(customMessageHandler !=null)
returnMessage= customMessageHandler.requestConfirm(new Object[]{file, String.valueOf(yesToAllPresent)});
if(returnMessage!=-1) return returnMessage;
if(yesToAllPresent){
final Object[] buttonRowObjects = new Object[] {
Messages.getMessage("PdfViewerConfirmButton.Yes"),
Messages.getMessage("PdfViewerConfirmButton.YesToAll"),
Messages.getMessage("PdfViewerConfirmButton.No"),
Messages.getMessage("PdfViewerConfirmButton.Cancel")
};
JEditorPane p = new JEditorPane(
"text/html",
"Itext is not on the classpath.<BR>"
+ "JPedal includes code to take advantage of itext and<BR>"
+ "provide additional functionality with options<BR>"
+ "to spilt pdf files, and resave forms data<BR>"
+ "\nItext website - <a href=http://itextpdf.com/>http://itextpdf.com</a>");
p.setEditable(false);
p.setOpaque(false);
p.addHyperlinkListener( new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) { try {
BrowserLauncher.openURL("http://itextpdf.com/");
} catch (IOException e1) {
showMessageDialog(Messages.getMessage("PdfViewer.ErrorWebsite"));
}
}
}
});
/**
* allow user to replace messages with our action
*/ boolean showMessage=true;
//check user has not setup message and if we still show message if(customMessageHandler !=null)
showMessage= customMessageHandler.showMessage(p);
if(showMessage)
showMessageDialog(p);
// Hack for 13 to make sure the message box is large enough to hold the message
/**
JOptionPane optionPane = new JOptionPane();
optionPane.setMessage(p);
optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
optionPane.setOptionType(JOptionPane.DEFAULT_OPTION);
//allow user to disable boolean showMessage=(customMessageHandler!=null && customMessageHandler.showMessage("first time popup")) ||
customMessageHandler==null;
try{ final JPanel a = new JPanel();
a.setLayout(new BoxLayout(a, BoxLayout.Y_AXIS));
JLabel m1,m2,m3;
//<start-gpl>
//m1 = new JLabel(Messages.getMessage("PdfViewerDemo.message1"));
//m2 = new JLabel(Messages.getMessage("PdfViewerDemo.message2"));
//m3 = new JLabel(Messages.getMessage("PdfViewerDemo.message3"));
//<end-gpl>
//<start-demo>
m1 = new JLabel(Messages.getMessage("PdfViewerGPL.message1"));
m2 = new JLabel(Messages.getMessage("PdfViewerGPL.message2"));
m3 = new JLabel(Messages.getMessage("PdfViewerGPL.message3"));
//<end-demo>
a.add(m1);
a.add(Box.createRigidArea(new Dimension(14,14)));
a.add(m2);
a.add(m3);
a.add(Box.createRigidArea(new Dimension(10,10)));
/**///to help comment out code not needed in gpl demos.
MouseAdapter supportListener = new MouseAdapter() { public void mouseEntered(MouseEvent e) { if(SingleDisplay.allowChangeCursor)
a.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
public void mouseExited(MouseEvent e) { if(SingleDisplay.allowChangeCursor)
a.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
JOptionPane.showMessageDialog(
frame,
a,
Messages.getMessage("PdfViewerTitle.RunningFirstTime"),
JOptionPane.PLAIN_MESSAGE);
}catch(Exception e){
//JOptionPane.showMessageDialog(null, "caught an exception "+e);
System.err.println(Messages.getMessage("PdfViewerFirstRunDialog.Error"));
}catch(Error e){
//JOptionPane.showMessageDialog(null, "caught an error "+e);
System.err.println(Messages.getMessage("PdfViewerFirstRunDialog.Error"));
}
}
/* (non-Javadoc)
* @see org.jpedal.examples.simpleviewer.gui.swing.GUIFactory#showConfirmDialog(java.lang.Object, java.lang.String, int, int)
*/ public int showConfirmDialog(Object message, String title, int optionType, int messageType) {
/**
* allow user to replace messages with our action
*/ int returnMessage=-1;
//check user has not setup message and if we still show message if(customMessageHandler !=null)
returnMessage= customMessageHandler.requestConfirm(new Object[]{message, title, String.valueOf(optionType), String.valueOf(messageType)});
//BOTH X and Y POSITIVE!!!!
g2.drawString("hello world", 60,60);
}else if(matrix[0]<0 && matrix[3]>0){ //180 degrees (origin now top right)
g2.transform(AffineTransform.getScaleInstance(-1, 1));
g2.drawString("hello world", -560,60);//subtract cropW from first number to use standard values
//BOTH X and Y NEGATIVE!!!!
g2.drawString("hello world", -560,-60); //subtract CropW and CropH if you want standard values
}else{ //0 degress
g2.transform(AffineTransform.getScaleInstance(1, -1));
// X ONLY POSITIVE!!!!
g2.drawString("hello world", 60,-60);
}
//restore!!!
g2.setTransform(aff);
}
}
public void setVisible(boolean isVisible) {
this.isVisible=isVisible;
}
public void setMedX(int medX) {
this.medX = medX;
}
public void setMedY(int medY) {
this.medY = medY;
}
}/**/
public void removeSearchWindow(boolean justHide) {
searchFrame.removeSearchWindow(justHide);
}
JPanel errorPanel = new JPanel();
errorPanel.setLayout(new BoxLayout(errorPanel, BoxLayout.Y_AXIS));
JLabel errorMessage = new JLabel("Your web browser could not be successfully loaded. " +
"Please copy and paste the URL below, manually into your web browser.");
errorMessage.setAlignmentX(JLabel.LEFT_ALIGNMENT);
errorMessage.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JTextArea textArea = new JTextArea("http://www.jpedal.org/jpedal.rss");
textArea.setEditable(false);
textArea.setRows(5);
textArea.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
textArea.setAlignmentX(JTextArea.LEFT_ALIGNMENT);
if(navOptionsPanel.getIconAt(i).toString().equals(signaturesTitle) && !set){
navOptionsPanel.remove(i);
}
}
}
/**
* Items from the menu item
*/ if(fileMenu!=null){ //all of these will be null in 'Wrapper' mode so ignore
propValue = properties.getValue("FileMenu");
set = propValue.length()>0 && propValue.toLowerCase().equals("true");
fileMenu.setEnabled(set);
fileMenu.setVisible(set);
propValue = properties.getValue("OpenMenu");
set = propValue.length()>0 && propValue.toLowerCase().equals("true");
openMenu.setEnabled(set);
openMenu.setVisible(set);
propValue = properties.getValue("Open");
set = propValue.length()>0 && propValue.toLowerCase().equals("true");
open.setEnabled(set);
open.setVisible(set);
propValue = properties.getValue("Openurl");
set = propValue.length()>0 && propValue.toLowerCase().equals("true");
openUrl.setEnabled(set);
openUrl.setVisible(set);
propValue = properties.getValue("Save");
set = propValue.length()>0 && propValue.toLowerCase().equals("true");
save.setEnabled(set);
save.setVisible(set);
//added check to code (as it may not have been initialised) if(value.equals("Resaveasforms") && reSaveAsForms!=null){ //will not be initialised if Itext not on path
reSaveAsForms.setEnabled(set);
reSaveAsForms.setVisible(set);
}
JLabel label = new JLabel("<html><p>Please click on this link for lots of tutorials and documentation</p>");
label.setAlignmentX(JLabel.LEFT_ALIGNMENT);
JPanel errorPanel = new JPanel();
errorPanel.setLayout(new BoxLayout(errorPanel, BoxLayout.Y_AXIS));
JLabel errorMessage = new JLabel("Your web browser could not be successfully loaded. " +
"Please copy and paste the URL below, manually into your web browser.");
errorMessage.setAlignmentX(JLabel.LEFT_ALIGNMENT);
errorMessage.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JTextArea textArea = new JTextArea("http://www.jpedal.org/support.php");
textArea.setEditable(false);
textArea.setRows(5);
textArea.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
textArea.setAlignmentX(JTextArea.LEFT_ALIGNMENT);
/* used by JS to set values that dont need to save the new forms values */ public boolean getFormsDirtyFlag() { return commonValues.isFormsChanged();
}
/* used by JS to set values that dont need to save the new forms values */ public void setFormsDirtyFlag(boolean dirty) {
commonValues.setFormsChanged(dirty);
}
public int getCurrentPage() { return commonValues.getCurrentPage();
}
public boolean getPageTurnScalingAppropriate() { return pageTurnScalingAppropriate;
}
public boolean getDragLeft() { return dragLeft;
}
public boolean getDragTop() { return dragTop;
}
public void setDragCorner(int a) { if (a == org.jpedal.external.OffsetOptions.INTERNAL_DRAG_CURSOR_BOTTOM_LEFT ||
a == org.jpedal.external.OffsetOptions.INTERNAL_DRAG_CURSOR_TOP_LEFT ||
a == org.jpedal.external.OffsetOptions.INTERNAL_DRAG_BLANK)
dragLeft = true; else
dragLeft = false;
if (a == org.jpedal.external.OffsetOptions.INTERNAL_DRAG_CURSOR_TOP_LEFT ||
a == org.jpedal.external.OffsetOptions.INTERNAL_DRAG_CURSOR_TOP_RIGHT)
dragTop = true; else
dragTop = false;
}
public void setCursor(int type) {
decode_pdf.setPDFCursor(getCursor(type));
}
public Cursor getCursor(int type) { switch (type) { case GRAB_CURSOR: if (grabCursor == null) {
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.getImage(getURLForImage(iconLocation+"grab32.png"));
grabCursor = kit.createCustomCursor(img, new Point(8,8),"grab");
} return grabCursor;
case GRABBING_CURSOR: if (grabbingCursor == null) {
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.getImage(getURLForImage(iconLocation+"grabbing32.png"));
grabbingCursor = kit.createCustomCursor(img, new Point(8,8),"grabbing");
} return grabbingCursor;
case PAN_CURSOR: if (panCursor == null) {
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.getImage(getURLForImage(iconLocation+"pan32.png"));
panCursor = kit.createCustomCursor(img, new Point(10,10),"pan");
} return panCursor;
case PAN_CURSORL: if (panCursorL == null) {
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.getImage(getURLForImage(iconLocation+"panl32.png"));
panCursorL = kit.createCustomCursor(img, new Point(11,10),"panl");
} return panCursorL;
case PAN_CURSORTL: if (panCursorTL == null) {
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.getImage(getURLForImage(iconLocation+"pantl32.png"));
panCursorTL = kit.createCustomCursor(img, new Point(10,10),"pantl");
} return panCursorTL;
case PAN_CURSORT: if (panCursorT == null) {
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.getImage(getURLForImage(iconLocation+"pant32.png"));
panCursorT = kit.createCustomCursor(img, new Point(10,11),"pant");
} return panCursorT;
case PAN_CURSORTR: if (panCursorTR == null) {
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.getImage(getURLForImage(iconLocation+"pantr32.png"));
panCursorTR = kit.createCustomCursor(img, new Point(10,10),"pantr");
} return panCursorTR;
case PAN_CURSORR: if (panCursorR == null) {
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.getImage(getURLForImage(iconLocation+"panr32.png"));
panCursorR = kit.createCustomCursor(img, new Point(10,10),"panr");
} return panCursorR;
case PAN_CURSORBR: if (panCursorBR == null) {
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.getImage(getURLForImage(iconLocation+"panbr32.png"));
panCursorBR = kit.createCustomCursor(img, new Point(10,10),"panbr");
} return panCursorBR;
case PAN_CURSORB: if (panCursorB == null) {
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.getImage(getURLForImage(iconLocation+"panb32.png"));
panCursorB = kit.createCustomCursor(img, new Point(10,10),"panb");
} return panCursorB;
case PAN_CURSORBL: if (panCursorBL == null) {
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.getImage(getURLForImage(iconLocation+"panbl32.png"));
panCursorBL = kit.createCustomCursor(img, new Point(10,10),"panbl");
} return panCursorBL;
default: return Cursor.getDefaultCursor();
}
}
public void rescanPdfLayers() { try { if (SwingUtilities.isEventDispatchThread()) {
//refresh the layers tab so JS updates are carried across.
syncTreeDisplay(topLayer,true);
layersPanel.invalidate();
layersPanel.repaint();
} else { final Runnable doPaintComponent = new Runnable() { public void run() {
//refresh the layers tab so JS updates are carried across.
syncTreeDisplay(topLayer,true);
layersPanel.invalidate();
layersPanel.repaint();
}
};
SwingUtilities.invokeAndWait(doPaintComponent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* generate thumbnails for display
*/ private class ScrollMouseListener extends MouseAdapter {
/**
* Class to handle thumbnail preview
*/ private class ScrollListener implements AdjustmentListener {
java.util.Timer t = null; int pNum=-1,lastPage=-1,lastPageSent=-1; boolean mousePressed=false; boolean showLast=false; public BufferedImage lastImage; public boolean ignoreChange=false;
private void startTimer() {
//turn if off if running if (t != null)
t.cancel();
//restart - if its not stopped it will trigger page update
TimerTask listener = new PageListener();
t = new java.util.Timer();
t.schedule(listener, 175);
}
/**
* get page and start timer to creatye thumbnail
* If not moved, will draw this page
*/ public void adjustmentValueChanged(AdjustmentEvent e) {
pNum=e.getAdjustable().getValue()+1;
//Show loading image if (showLast) {
//Use stored image
((SingleDisplay)decode_pdf.getExternalHandler(Options.Display)).setPreviewThumbnail(lastImage, "Page "+pNum+" of "+decode_pdf.getPageCount());
decode_pdf.repaint();
} else if (lastImage != null) {
//Create loading image
BufferedImage img = new BufferedImage(lastImage.getWidth(), lastImage.getHeight(), lastImage.getType());
Graphics2D g2 = (Graphics2D)img.getGraphics();
//Draw last image
g2.drawImage(lastImage,0,0,null);
//Gray out
g2.setPaint(new Color(0,0,0,130));
g2.fillRect(0,0,lastImage.getWidth(),lastImage.getHeight());
//Draw loading string
String l = "Loading..."; int textW = g2.getFontMetrics().stringWidth(l); int textH = g2.getFontMetrics().getHeight();
g2.setPaint(Color.WHITE);
g2.drawString(l,(lastImage.getWidth()/2)-(textW/2),(lastImage.getHeight()/2)+(textH/2));
//Store and set to reuse
lastImage = img;
showLast = true;
//Update
((SingleDisplay)decode_pdf.getExternalHandler(Options.Display)).setPreviewThumbnail(img,"Page "+pNum+" of "+decode_pdf.getPageCount());
decode_pdf.repaint();
}
//Store and turn off using stored image
lastImage = image;
showLast = false;
((SingleDisplay)decode_pdf.getExternalHandler(Options.Display)).setPreviewThumbnail(image,"Page "+pNum+" of "+decode_pdf.getPageCount());
decode_pdf.repaint();
}catch(Exception ee){
}
//}
}
}
public void releaseAndUpdate() {
//turn if off if running if (t != null)
t.cancel();
//System.out.println("releaseAndUpdate");
((SingleDisplay)decode_pdf.getExternalHandler(Options.Display)).setPreviewThumbnail(null,"Page "+pNum+" of "+decode_pdf.getPageCount());