我需要做的就是获取(本地保存的)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/