java - 如何在 Android 中将 PDF 页面转换为图像?

标签 java android pdf

我需要做的就是获取(本地保存的)PDF-document将其中的一个或所有页面转换为图像格式,例如 JPG 或 PNG。 p>

我尝试了很多 PDF 渲染/查看解决方案,例如 APV PDF Viewer , APDFViewer , droidreader , android-pdf , MuPdf和许多其他人,但到目前为止还无法弄清楚如何将 pdf 页面转换为图像?

编辑:另外,我宁愿拥有一个 PDF 到图像转换器,而不是一个我需要编辑以将 PDF 转换为图像的 PDF 渲染器。

最佳答案

要支持 API 8 及更高版本,请遵循:

使用这个库: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 时间(我已在评论中标记它们)。

关于java - 如何在 Android 中将 PDF 页面转换为图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10698360/

相关文章:

java - "Compilation failed; see the compiler error output for details."错误

java - iText - setSplitRows 问题

javascript - 使用javascript从pdf文件中提取文本

php - 创建 PDF 时未应用 dompdf 横向 View

java - React Native 运行 android Build 失败并出现异常

android - 在 ViewModel 中加载已在 SplashActvity 中检索到的数据

java - 在 Java 中将 UTF-8 转换为 ISO-8859-1

android - 检查日历是否为主

java - SLF4J : Class path contains multiple SLF4J bindings. 无法摆脱绑定(bind)

java - 当 io 包已经有方法可用时,java nio 包的确切用途是什么