PDFをBufferedImageに変換する
JPedalは、PDFファイルまたはPDFファイルのディレクトリからページをJavaのBufferedImageに簡単に変換する機能を提供します。これはJPedalのConvertPagesToImages クラスを使用します。
サンプルコード - ファイルパスを使用してPDFファイルを画像に変換
ConvertPagesToImages convert = new ConvertPagesToImages("inputFile.pdf");
//convert.setPassword("password"); //if password needed
try {
if (convert.openPDFFile()) {
int pageCount = convert.getPageCount();
for (int page = 1; page <= pageCount; page++) {
BufferedImage image = convert.getPageAsImage(page);
}
}
} catch (Exception e) {
e.printStackTrace();
}
convert.closePDFfile();
サンプルコード - メモリ内のPDFファイルを変換
// Disable all caching to file to reduce memory usage
PdfFileReader.alwaysCacheInMemory = -1;
// bytes is a byte[] with the PDF file data
ConvertPagesToImages convert = new ConvertPagesToImages(bytes);
// convert.setPassword("password"); // If password needed
try {
if (convert.openPDFFile()) {
int pageCount = convert.getPageCount();
for (int page = 1; page <= pageCount; page++) {
BufferedImage image = convert.getPageAsImage(page);
}
}
} catch (PdfException e) {
e.printStackTrace();
}
convert.closePDFfile();
この例では、アップスケーリング機能を提供するConvertPagesToHiResImages クラスを使用します。このクラスには多数の追加オプション があります。
サンプルコード
ConvertPagesToHiResImages convert = new ConvertPagesToHiResImages("inputFile.pdf");
//convert.setPassword("password");
boolean isBackgroundTransparent = false;
HashMap<Integer, Object> options = new HashMap<>();
//options.put(JPedalSettings.EXTRACT_AT_BEST_QUALITY_MAXSCALING, 10); //Do not scale image above the specified factor
//options.put(JPedalSettings.EXTRACT_AT_PAGE_SIZE, new String[]{Integer.toString(2000), Integer.toString(3000)}); //Extract page as the specified dimensions (aspect ratio preserved so will do best fit)
//options.put(JPedalSettings.ALLOW_PAGES_SMALLER_THAN_PAGE_SIZE, Boolean.TRUE); //Extracted pages smaller than original page size is allowed
//The full list of settings can be found here https://javadoc.idrsolutions.com/org/jpedal/constants/JPedalSettings.html
try {
if (convert.openPDFFile()) {
int pageCount = convert.getPageCount();
for (int page = 1; page <= pageCount; page++) {
BufferedImage image = convert.getPageAsHiResImage(page, isBackgroundTransparent, options);
}
}
} catch (Exception e) {
e.printStackTrace();
}
convert.closePDFfile();
