import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.image.ToImageOptions;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/composite.pdf"));
// Extract all the pages from the PDF file.
List<BufferedImage> extractedImages = pdf.toBufferedImages();
// With the ToImageOptions object, specify maximum image dimensions for each
// extracted image, as well as their DPI
ToImageOptions rasterOptions = new ToImageOptions();
rasterOptions.setImageMaxHeight(100);
rasterOptions.setImageMaxWidth(100);
// Call the toBufferedImage method along with a PageSelection object to choose the pages from which to
// extract the images
//
// Available PageSelection methods include: allPages, lastPage, firstPage, singlePage(int pageIndex),
// and pageRange(int startingPage, int endingPage)
List<BufferedImage> sizedExtractedImages = pdf.toBufferedImages(rasterOptions, PageSelection.allPages());
// Save all the extracted images to a file location
int i = 1;
for (BufferedImage extractedImage : sizedExtractedImages) {
String fileName = "assets/images/" + i++ + ".png";
ImageIO.write(extractedImage, "PNG", new File(fileName));
}
Rasterize a PDF to Images
文件載入完成後,無論是從檔案中載入,還是從其他資源內容(網頁、URL、HTML 等)進行轉換,IronPDF 都能將 PDF 文件的頁面匯出為圖像,這些圖像可以儲存到檔案系統中,存放於資料庫內,或是通過網路傳送(以及其他用途)。
方法BufferedImage物件的集合。 每個PdfDocument單頁的圖像位元組內容。 此外,BufferedImageList是按頁碼遞增的順序排列。 開發人員可以在方法呼叫中包含一個List,用於包含 PDF 的頁面集。
特色程式碼範例建立了一個ToImageOptions物件,以設定圖像轉換後的預期寬度和高度。 這個類別還包括一個用於更改圖像輸出DPI的方法(setDpi)。 開發人員可以將此類的實例與PageSelection的實例一起使用,以同時控制 PDF 到圖像轉換的範圍、大小和質量。