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));
}
將 PDF 光柵化為影像
IronPDF 可以從文件中載入、從來源內容(網頁、URL、HTML 等)轉換,或透過邊距、頁首、頁尾或其他自訂進行修改,然後將 PDF 文件的頁面匯出為圖像,這些圖像可以儲存到檔案系統、儲存在資料庫中或透過網路傳送(以及其他用途)。
toBufferedImages方法傳回一個包含BufferedImage物件集合的List 。 每個BufferedImage都包含原始PdfDocument中單一頁面的圖像位元組內容。 此外,BufferedImageList 依頁數升序排列。 開發人員可以在方法呼叫中包含一個 PageSelection 物件作為參數,以便為 PDF 中包含的頁面集生成此 List 。
範例程式碼建立了一個ToImageOptions對象,用於設定轉換後影像的預期寬度和高度。 該類別還包含一個用於更改圖像輸出的 DPI 的方法( setDpi )。 開發人員可以將此類實例與PageSelection實例配對,從而同時控制 PDF 到影像轉換的範圍、大小和品質。