Example #1
0
 private static void processPages(PdfFile file, int dpi, int start, int end) {
   try {
     Document document = new Document();
     String staticpath = Play.configuration.getProperty("staticpath", "");
     Logger.debug("process %s", staticpath + file.originalFile);
     document.setFile(staticpath + file.originalFile);
     int numberOfPages = document.getNumberOfPages();
     boolean thumbnail = false;
     if (start < 0 && end < 0) {
       file.numPages = numberOfPages;
       file.save();
       thumbnail = true;
     }
     if (end < 0) {
       end = numberOfPages;
     }
     if (start < 0) {
       start = 0;
     }
     Logger.debug("process %s which has pages %s", file.title, numberOfPages);
     for (int i = start; i < end; i++) {
       processPage(file, document, i, dpi, thumbnail);
     }
   } catch (PDFException e) {
     e.printStackTrace();
   } catch (PDFSecurityException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Example #2
0
 @Override
 public int getNbrOfPages() {
   Logger.getLogger(PdfHandler.class.getName())
       .entering(PdfHandler.class.getName(), "getNbrOfPages");
   Logger.getLogger(PdfHandler.class.getName())
       .exiting(PdfHandler.class.getName(), "getNbrOfPages", pdfDocument.getNumberOfPages());
   return pdfDocument.getNumberOfPages();
 }
Example #3
0
 @Override
 public List<String> getPagesName() {
   Logger.getLogger(PdfHandler.class.getName())
       .entering(PdfHandler.class.getName(), "getPagesName");
   List<String> pagesTitle = new ArrayList<>(pdfDocument.getNumberOfPages());
   for (int i = 0; i < pdfDocument.getNumberOfPages(); i++) {
     pagesTitle.add("Page " + i);
   }
   Logger.getLogger(PdfHandler.class.getName())
       .exiting(PdfHandler.class.getName(), "getPagesName", pagesTitle);
   return pagesTitle;
 }
 /**
  * As long as no windows have openned or closed, then the indexes in the returned list should
  * still be valid for doing operations on the respective Controller objects
  *
  * @param giveIndex Give this SwingControllers index in the list as an Integer appended to the
  *     List
  * @return List of String objects, each representing an open Document's origin. The last element
  *     may be an Integer
  */
 @SuppressWarnings({"rawtypes", "unchecked"})
 public List getWindowDocumentOriginList(SwingController giveIndex) {
   Integer foundIndex = null;
   int count = controllers.size();
   List list = new ArrayList(count + 1);
   for (int i = 0; i < count; i++) {
     Object toAdd = null;
     SwingController controller = controllers.get(i);
     if (giveIndex == controller) foundIndex = new Integer(i);
     Document document = controller.getDocument();
     if (document != null) toAdd = document.getDocumentOrigin();
     list.add(toAdd);
   }
   if (foundIndex != null) list.add(foundIndex);
   return list;
 }
Example #5
0
  private static void processPage(
      PdfFile file, Document document, int i, int scaleInt, boolean isthumbnail) {
    float scale = scaleInt / 100.0f;
    float rotation = 0f;

    PDimension size = document.getPageDimension(i, rotation, scale);

    // double dpi = Math.sqrt((size.getWidth() * size.getWidth()) +
    // (size.getHeight() * size.getHeight()))
    // / Math.sqrt((8.5 * 8.5) + (11 * 11));
    // if (dpi < (targetDPI - 0.1)) {
    // scale = (float) (targetDPI / dpi);
    size = document.getPageDimension(i, rotation, scale);
    // }

    int pageWidth = (int) (size.getWidth());
    int pageHeight = (int) (size.getHeight());
    BufferedImage image = new BufferedImage(pageWidth, pageHeight, BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D g = image.createGraphics();
    document.paintPage(i, g, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
    g.dispose();
    if (!isthumbnail) {
      String pageImage = getPageImagePath(file, i, scaleInt, isthumbnail);
      ImageUtil.saveJPEG(image, pageImage);
      Logger.debug("Page File Path: %s", pageImage);
    } else {
      String pageThumbnail = getPageImagePath(file, i, scaleInt, isthumbnail);
      BufferedImage thumbnail = ImageUtil.thumbnail(image, 140, 160, false, false);
      ImageUtil.saveJPEG(thumbnail, pageThumbnail);
      Logger.debug("Page Thumbnail Path: %s", pageThumbnail);
      models.Page page = models.Page.find("file= ? and page = ?", file, i).first();
      if (page == null) {
        page = new models.Page();
        page.file = file;
        page.page = i;
      }
      page.content = document.getPageText(i).toString();
      page.width = pageWidth;
      page.height = pageHeight;
      page.save();
    }
    Logger.debug("process page %s", i);
  }
Example #6
0
 /**
  * Constructor of this handler. Retrieve the pdfDocument which will contain all the images
  *
  * @param album the pdf album
  */
 public PdfHandler(File album) {
   Logger.getLogger(PdfHandler.class.getName())
       .entering(PdfHandler.class.getName(), "PdfHandler", album);
   pdfDocument = new Document();
   try {
     pdfDocument.setFile(album.getPath());
   } catch (PDFException | PDFSecurityException | IOException ex) {
     Logger.getLogger(PdfHandler.class.getName())
         .log(Level.SEVERE, "Cannot read the PDF document", ex);
     new InfoInterface(InfoInterface.InfoLevel.ERROR, "file-read", album.getName());
   }
   Logger.getLogger(PdfHandler.class.getName()).exiting(PdfHandler.class.getName(), "PdfHandler");
 }
Example #7
0
 @Override
 public BufferedImage getImage(int pageNumber) {
   Logger.getLogger(PdfHandler.class.getName())
       .entering(PdfHandler.class.getName(), "getImage", pageNumber);
   if (!isImageInRange(pageNumber)) {
     Logger.getLogger(PdfHandler.class.getName())
         .exiting(PdfHandler.class.getName(), "getImage", null);
     return null;
   }
   BufferedImage bufferedImage;
   try {
     bufferedImage = (BufferedImage) pdfDocument.getPageImages(--pageNumber).get(0);
   } catch (ClassCastException ex) {
     Image image = (Image) pdfDocument.getPageImages(pageNumber).get(0);
     bufferedImage = new ImageReader(image).convertImageToBufferedImage();
   } catch (ArrayIndexOutOfBoundsException ex) {
     Logger.getLogger(PdfHandler.class.getName())
         .exiting(PdfHandler.class.getName(), "getImage", null);
     return null;
   }
   Logger.getLogger(PdfHandler.class.getName())
       .exiting(PdfHandler.class.getName(), "getImage", bufferedImage);
   return bufferedImage;
 }
    LoadAllAnnotations() {
      taskRunning = true;
      MessageFormat loadingMessage =
          new MessageFormat(
              messageBundle.getString(
                  "viewer.utilityPane.annotation.tab.loadingAnnotations.label"));
      MessageFormat pageLabelFormat =
          new MessageFormat(
              messageBundle.getString("viewer.utilityPane.annotation.tab.tree.page.label"));
      try {
        current = 0;
        try {
          Document currentDocument = controller.getDocument();
          if (currentDocument != null) {
            Library library = currentDocument.getCatalog().getLibrary();
            int pageCount = currentDocument.getPageTree().getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
              // break if needed
              if (canceled || done) {
                break;
              }
              // Update task information
              current = i;
              taskStatusMessage = loadingMessage.format(new Object[] {i + 1, pageCount});
              String pageLabel = pageLabelFormat.format(new Object[] {i + 1});

              Page page = currentDocument.getPageTree().getPage(i);
              if (page != null) {
                ArrayList<Reference> annotationReferences = page.getAnnotationReferences();
                if (annotationReferences != null && annotationReferences.size() > 0) {
                  // insert page node
                  final String label = pageLabel;
                  SwingUtilities.invokeLater(
                      new Runnable() {
                        public void run() {
                          annotationHandlerPanel.addPageGroup(label);
                          // try repainting the container
                          annotationHandlerPanel.repaint();
                        }
                      });
                  Thread.yield();
                  // add child nodes for each annotation.
                  for (Object annotationReference : annotationReferences) {
                    final Object annotation = library.getObject(annotationReference);
                    // add the node to the signature panel tree but on the
                    // awt thread.
                    SwingUtilities.invokeLater(
                        new Runnable() {
                          public void run() {
                            // add the node
                            annotationHandlerPanel.addAnnotation(annotation);
                            // try repainting the container
                            annotationHandlerPanel.repaint();
                          }
                        });
                    Thread.yield();
                  }
                }
              }
            }
          }
          // update the dialog and end the task
          taskStatusMessage =
              messageBundle.getString("viewer.utilityPane.annotation.tab.loadingComplete.label");
          done = true;
        } catch (Exception e) {
          logger.log(Level.FINER, "Error loading annotations.", e);
        }
      } finally {
        taskRunning = false;
      }
      // repaint the view container
      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              annotationHandlerPanel.validate();
            }
          });
    }
/**
 * This class provides a very basic Font Properties Management system. When this class is initiated,
 * the properites file "pdfviewerfontcache.properties" is read from the default application file
 * path. If the file cannot be found then all system fonts are read from the operating system and
 * are written to the "pdfviewerfontcache.properties" file.
 *
 * <p>
 *
 * <p>This class is designed to speed up the load time of the viewer application by reading already
 * parsed font information from the properties file. If new fonts are added to the system, the
 * "pdfviewerfontcache.properties" file can be deleted to trigger this class to re-read the System
 * fonts and re-create a new "pdfviewerfontcache.properties" properites file.
 *
 * @since 2.0
 */
public class FontPropertiesManager {

  private static final Logger logger = Logger.getLogger(FontPropertiesManager.class.toString());

  private static final String DEFAULT_HOME_DIR = ".icesoft/icepdf_viewer";
  private static final String LOCK_FILE = "_syslock";
  private static final String USER_FILENAME = "pdfviewerfontcache.properties";

  private FontManager fontManager;

  // the version name, used in about dialog and start-up message
  String versionName = Document.getLibraryVersion();

  private Properties sysProps;
  private PropertiesManager props;
  private Properties fontProps;

  File userHome;

  // the swingri home directory
  private File dataDir;

  // not to save the bookmarks and properties if lockDir == null, that is
  // when we do not own the lock
  private File lockDir;

  private File propertyFile;

  private ResourceBundle messageBundle;

  public FontPropertiesManager(
      PropertiesManager appProps, Properties sysProps, ResourceBundle messageBundle) {
    this.sysProps = sysProps;
    this.props = appProps;
    this.fontProps = new Properties();
    this.messageBundle = messageBundle;
    // create a new Font Manager.
    this.fontManager = FontManager.getInstance();

    setupHomeDir(null);

    recordMofifTime();

    setupLock();

    loadProperties();
  }

  public synchronized void loadProperties() {

    if (dataDir != null) {
      propertyFile = new File(dataDir, USER_FILENAME);
      // load font properties from last invocation
      if (propertyFile.exists()) {
        try {
          InputStream in = new FileInputStream(propertyFile);
          try {
            fontProps.load(in);
            fontManager.setFontProperties(fontProps);
          } finally {
            in.close();
          }
        } catch (IOException ex) {
          // check to make sure the storage relate dialogs can be shown
          if (getBoolean("application.showLocalStorageDialogs", true)) {
            Resources.showMessageDialog(
                null,
                JOptionPane.ERROR_MESSAGE,
                messageBundle,
                "fontManager.properties.title",
                "manager.properties.session.readError",
                ex);
          }
          // log the error
          if (logger.isLoggable(Level.WARNING)) {
            logger.log(Level.WARNING, "Error loading font properties cache", ex);
          }
        } catch (IllegalArgumentException e) {
          // propblem parsing fontProps, reread teh file
          setupDefaultProperties();
          saveProperties();
        }
      }
      // If no font data, then read font data and save the new file.
      else {
        setupDefaultProperties();
        saveProperties();
      }
    }
  }

  public synchronized void saveProperties() {
    if (ownLock()) {
      try {
        FileOutputStream out = new FileOutputStream(propertyFile);
        try {
          fontProps.store(out, "-- ICEpf Font properties --");
        } finally {
          out.close();
        }
        recordMofifTime();
      } catch (IOException ex) {
        // check to make sure the storage relate dialogs can be shown
        if (getBoolean("application.showLocalStorageDialogs", true)) {
          Resources.showMessageDialog(
              null,
              JOptionPane.ERROR_MESSAGE,
              messageBundle,
              "fontManager.properties.title",
              "manager.properties.saveError",
              ex);
        }
        // log the error
        if (logger.isLoggable(Level.WARNING)) {
          logger.log(Level.WARNING, "Error saving font properties cache", ex);
        }
      }
    }
  }

  private boolean ownLock() {
    return lockDir != null;
  }

  private void recordMofifTime() {
    Calendar c = new GregorianCalendar();
    c.setTime(new Date());
    c.set(Calendar.MINUTE, c.get(Calendar.MINUTE) + 1);
    c.set(Calendar.SECOND, 0);
  }

  private void setupLock() {
    if (dataDir == null) {
      lockDir = null;
    } else {
      File dir = new File(dataDir, LOCK_FILE);
      if (!dir.mkdir()) {

        dir.delete();
        if (!dir.mkdir()) {
          dir = null;
          if (getBoolean("application.showLocalStorageDialogs", true)) {
            Resources.showMessageDialog(
                null,
                JOptionPane.ERROR_MESSAGE,
                messageBundle,
                "fontManager.properties.title",
                "manager.properties.session.nolock",
                LOCK_FILE);
          }
        }
      }
      lockDir = dir;
    }
  }

  private boolean setupDefaultProperties() {
    fontProps = new Properties();

    // create program properties with default
    try {
      // If you application needs to look at other font directories
      // they can be added via the readSystemFonts method.
      fontManager.readSystemFonts(null);
      fontProps = fontManager.getFontProperties();

    } catch (Exception ex) {
      if (getBoolean("application.showLocalStorageDialogs", true)) {
        Resources.showMessageDialog(
            null,
            JOptionPane.ERROR_MESSAGE,
            messageBundle,
            "fontManager.properties.title",
            "manager.properties.session.readError",
            ex);
      } // log the error
      if (logger.isLoggable(Level.WARNING)) {
        logger.log(Level.WARNING, "Error loading default properties", ex);
      }
      return false;
    }
    return true;
  }

  private void setupHomeDir(String homeString) {
    if (homeString == null) {
      homeString = sysProps.getProperty("swingri.home");
    }

    if (homeString != null) {
      dataDir = new File(homeString);
    } else {
      userHome = new File(sysProps.getProperty("user.home"));
      String dataDirStr = props.getString("application.datadir", DEFAULT_HOME_DIR);
      dataDir = new File(userHome, dataDirStr);
    }

    if (!dataDir.isDirectory()) {
      String path = dataDir.getAbsolutePath();
      boolean create;
      if (props.hasUserRejectedCreatingLocalDataDir()) {
        create = false;
      } else if (getBoolean("application.showLocalStorageDialogs", true)) {
        create =
            Resources.showConfirmDialog(
                null,
                messageBundle,
                "fontManager.properties.title",
                "manager.properties.createNewDirectory",
                path);
        if (!create) props.setUserRejectedCreatingLocalDataDir();
      } else {
        // Always create local-storage directory if show user prompt dialog setting is false.
        create = true;
      }

      if (!create) {
        dataDir = null;
      } else {
        dataDir.mkdirs();
        if (!dataDir.isDirectory()) {
          // check to make sure that dialog should be shown on the error.
          if (getBoolean("application.showLocalStorageDialogs", true)) {
            Resources.showMessageDialog(
                null,
                JOptionPane.ERROR_MESSAGE,
                messageBundle,
                "fontManager.properties.title",
                "manager.properties.failedCreation",
                dataDir.getAbsolutePath());
          }
          dataDir = null;
        }
      }
    }
  }

  public boolean getBoolean(String propertyName, boolean defaultValue) {
    Boolean result = getBooleanImpl(propertyName);
    if (result == null) {
      return defaultValue;
    }
    return result == Boolean.TRUE;
  }

  private Boolean getBooleanImpl(String propertyName) {
    String value = props.getString(propertyName);
    if (value != null) {
      Boolean result = Parse.parseBoolean(value, messageBundle);
      if (result != null) {
        return result;
      }
      props.remove(propertyName);
    }
    value = props.getString(propertyName);
    if (value != null) {
      Boolean result = Parse.parseBoolean(value, null);
      if (result != null) {
        return result;
      }
      throwBrokenDefault(propertyName, value);
    }
    return null;
  }

  private void throwBrokenDefault(String propertyName, String value) {
    throw new IllegalStateException(
        "Broken default property '" + propertyName + "' value: '" + value + "'");
  }
}