在Java-GAE上将PDF页面转换为JPG

Bom*_*tze 6 java pdf google-app-engine image

我正在寻找一个开源的java库,它使我能够在服务器端将单页PDF格式呈现为JPG或PNG.

不幸的是,它不能使用任何其他java.awt.*

  • java.awt.datatransfer.DataFlavor
  • java.awt.datatransfer.MimeType
  • java.awt.datatransfer.Transferable

如果有任何方法,一个小代码片段将是太棒了.

小智 0

我相信icepdf可能有你正在寻找的东西。

我不久前使用过这个开源项目,将上传的 pdf 文件转换为图像,以便在在线目录中使用。

import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;


public byte[][] convert(byte[] pdf, String format) {

    Document document = new Document();
    try {
        document.setByteArray(pdf, 0, pdf.length, null);

    } catch (PDFException ex) {
        System.out.println("Error parsing PDF document " + ex);
    } catch (PDFSecurityException ex) {
        System.out.println("Error encryption not supported " + ex);
    } catch (FileNotFoundException ex) {
        System.out.println("Error file not found " + ex);
    } catch (IOException ex) {
        System.out.println("Error handling PDF document " + ex);
    }
    byte[][] imageArray = new byte[document.getNumberOfPages()][];
    // save page captures to bytearray.
    float scale = 1.75f;
    float rotation = 0f;

    // Paint each pages content to an image and write the image to file
    for (int i = 0; i < document.getNumberOfPages(); i++) {
        BufferedImage image = (BufferedImage)
                document.getPageImage(i,
                                      GraphicsRenderingHints.SCREEN,
                                      Page.BOUNDARY_CROPBOX, rotation, scale);
       try {
            //get the picture util object
            PictureUtilLocal pum = (PictureUtilLocal) Component
            .getInstance("pictureUtil");
            //load image into util
            pum.loadBuffered(image);

            //write image in desired format
            imageArray[i] = pum.imageToByteArray(format, 1f);

            System.out.println("\t capturing page " + i);

        } catch (IOException e) {
            e.printStackTrace();
        }
        image.flush();
    }
    // clean up resources
    document.dispose();
    return imageArray;
}
Run Code Online (Sandbox Code Playgroud)

不过请注意,我在这个库在 open-jdk 上抛出 SegFault 时遇到了麻烦。在 Sun 上工作得很好。不确定它在 GAE 上会做什么。我不记得哪个版本有问题,所以请注意。