用于将pdf转换为图像的库

时间:2013-10-16 18:16:00

标签: java android image pdf

我有一个Android应用程序,我想在其中显示PDF(没有外部应用程序)。我认为唯一的解决方案是将PDF页面转换为图像。有人有过这个问题的经验吗?你推荐我哪个图书馆?

我测试了下一个库,但我遇到了麻烦:

1)PdfRenderer library不适用于现代PDF
2)jPDFImages在Android中不起作用(适用于java桌面应用程序)

抱歉我的英文

3 个答案:

答案 0 :(得分:0)

您可以使用 MuPDF 。这是一个描述如何为Android构建MuPDF的链接:http://mupdf.com/docs/how-to-build-mupdf-for-android

答案 1 :(得分:0)

我建议使用此库android-pdfview

答案 2 :(得分:0)

我正在扩大应对的答案并提供完整的解决方案。

使用此库:android-pdfview和以下代码,您可以可靠地将PDF页面转换为图像(JPG,PNG):

DecodeServiceBase decodeService = new DecodeServiceBase(new PdfContext());
decodeService.setContentResolver(mContext.getContentResolver());

// a bit long running
decodeService.open(Uri.fromFile(pdf));

int pageCount = decodeService.getPageCount();
for (int i = 0; i < pageCount; i++) {
    PdfPage page = decodeService.getPage(i);
    RectF rectF = new RectF(0, 0, 1, 1);

    // do a fit center to 1920x1080
    double scaleBy = Math.min(AndroidUtils.PHOTO_WIDTH_PIXELS / (double) page.getWidth(), //
            AndroidUtils.PHOTO_HEIGHT_PIXELS / (double) page.getHeight());
    int with = (int) (page.getWidth() * scaleBy);
    int height = (int) (page.getHeight() * scaleBy);

    // you can change these values as you to zoom in/out
    // and even distort (scale without maintaining the aspect ratio)
    // the resulting images

    // Long running
    Bitmap bitmap = page.renderBitmap(with, height, rectF);

    try {
        File outputFile = new File(mOutputDir, System.currentTimeMillis() + FileUtils.DOT_JPEG);
        FileOutputStream outputStream = new FileOutputStream(outputFile);

        // a bit long running
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);

        outputStream.close();
    } catch (IOException e) {
        LogWrapper.fatalError(e);
    }
}

你应该在后台工作,即使用AsyncTask或类似的东西,因为很多方法需要计算或IO时间(我在评论中标记了它们)。