Saturday, March 28, 2009

Converting PDFs for Flex

Well as many of you know Flex can not display a PDF so I you basically need to either create a SWF or an image. Because the project I am working on the PDFs are retrieved from the database as the user performs a search. I ran across PDF Renderer this pure java tool written in Java 1.5. This is the only downside as we are running WebSphere 6 which is Java 1.4. The source code was easily updated to remove the Annotations.

Beyond that we also did not want to write a single file to the file system so that is where the trick came into play. So based on research, trial and error I give you a converter from PDF to an ArrayList of byte arrays.

private static ArrayList convertImage(byte[] fileBytes) throws Exception {
  ArrayList images = new ArrayList();
  ByteBuffer buf = ByteBuffer.wrap(fileBytes);
  PDFFile pdffile = new PDFFile(buf);
  // draw the first page to an image
  int numberOfPages = pdffile.getNumPages();
  System.out.println("NUMBER OF PAGES:" + numberOfPages);
  for (int i = 0; i < numberOfPages; i++) {
    PDFPage page = pdffile.getPage(i);
    // get the width and height for the doc at the default zoom
    int width = (int) page.getBBox().getWidth();
    int height = (int) page.getBBox().getHeight();
    Rectangle rect = new Rectangle(0, 0, width, height);
    int rotation = page.getRotation();
    Rectangle rect1 = rect;
    if (rotation == 90 || rotation == 270)
      rect1 = new Rectangle(0, 0, rect.height, rect.width);
    // generate the image
    BufferedImage img = (BufferedImage) page.getImage(rect.width,
        rect.height, // width & height
        rect1, // clip rect
        null, // null for the ImageObserver
        true, // fill background with white
        true // block until drawing is done
        );
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    ImageIO.write(img, "png", output);
    images.add(output.toByteArray());
  }
  return images;
}

No comments:

Post a Comment