AndroidでPDFページを画像に変換するにはどうすればいいですか?質問する

AndroidでPDFページを画像に変換するにはどうすればいいですか?質問する

私がやるべきことは、(ローカルに保存されたPDF-document1ページまたは全ページを画像に変換するJPG や PNG などの形式。

私はPDFレンダリング/表示ソリューションをたくさん試してきました。APV PDF ビューアPDFビューアドロイドリーダーアンドロイド-pdfムPDF他にもたくさんありますが、今のところはPDF ページを画像に変換するにはどうすればいいですか?

編集: また、PDF を画像に変換するために編集する必要がある PDF レンダラーよりも、PDF から画像へのコンバーターの方が望ましいです。

ベストアンサー1

API 8 以上をサポートするには、次の手順に従ってください。

このライブラリを使用するには:android-pdfビュー次のコードを使用すると、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);
    }
}

かなりの数のメソッドが計算時間や IO 時間を費やすため、この作業はバックグラウンドで、つまりAsyncTaskまたは同様のものを使用して実行する必要があります (コメントでマークしました)。

おすすめ記事