이미지 조작
PDF Oxide는 두 가지 수준의 이미지 조작을 제공합니다: XObject 이름으로 이미지 위치 변경 및 크기 조절을 위한 DocumentEditor를 통한 저수준 작업, 이미지 메타데이터 쿼리를 위한 PdfPage를 통한 DOM 수준 접근. 두 방식 모두 PDF에 이미 임베드된 이미지와 작동합니다.
페이지 이미지 가져오기
DocumentEditor: Low-Level Image Info
XObject 이름과 변환 행렬을 포함하여 페이지의 모든 이미지에 대한 상세 배치 정보를 검색합니다.
from pdf_oxide import PdfDocument
doc = PdfDocument("brochure.pdf")
images = doc.page_images(0)
for img in images:
print(f"Name: {img['name']}")
print(f"Position: ({img['x']:.1f}, {img['y']:.1f})")
print(f"Size: {img['width']:.1f} x {img['height']:.1f}")
print(f"Matrix: {img['matrix']}")
import { WasmPdfDocument } from "pdf-oxide-wasm";
const doc = new WasmPdfDocument(bytes);
const images = doc.pageImages(0);
for (const img of images) {
console.log(`Name: ${img.name}`);
console.log(`Position: (${img.x}, ${img.y})`);
console.log(`Size: ${img.width} x ${img.height}`);
}
doc.free();
use pdf_oxide::editor::DocumentEditor;
let mut editor = DocumentEditor::open("brochure.pdf")?;
let images = editor.get_page_images(0)?;
for img in &images {
println!("Name: {}", img.name);
println!("Bounds: {:?}", img.bounds); // [x, y, width, height]
println!("Matrix: {:?}", img.matrix); // [a, b, c, d, e, f]
}
반환된 ImageInfo 구조체에는 다음이 포함됩니다:
| Field | 타입 | 설명 |
|---|---|---|
name |
String |
XObject name (e.g., "Im0", "Image1") |
bounds |
[f32; 4] |
Position and size [x, y, width, height] |
matrix |
[f32; 6] |
Full transformation matrix [a, b, c, d, e, f] |
PdfPage: DOM-Level Image Info
The DOM API provides richer metadata about each image.
doc = PdfDocument("brochure.pdf")
page = doc.page(0)
for img in page.find_images():
print(f"BBox: {img.bbox}")
print(f"Format: {img.format}")
print(f"Dimensions: {img.dimensions}")
let mut doc = Pdf::open("brochure.pdf")?;
let page = doc.page(0)?;
for img in page.find_images() {
println!("BBox: {:?}", img.bbox());
println!("Format: {:?}", img.format());
println!("Dimensions: {:?}", img.dimensions());
println!("Aspect ratio: {:.2}", img.aspect_ratio());
println!("Grayscale: {}", img.is_grayscale());
if let Some(alt) = img.alt_text() {
println!("Alt text: {}", alt);
}
if let Some((h_dpi, v_dpi)) = img.resolution() {
println!("Resolution: {:.0} x {:.0} DPI", h_dpi, v_dpi);
}
}
이미지 위치 변경
크기를 변경하지 않고 페이지에서 이미지를 새 위치로 이동합니다.
doc = PdfDocument("input.pdf")
images = doc.page_images(0)
# Move the first image to position (100, 500)
doc.reposition_image(0, images[0]["name"], 100, 500)
doc.save("moved.pdf")
import { WasmPdfDocument } from "pdf-oxide-wasm";
const doc = new WasmPdfDocument(bytes);
const images = doc.pageImages(0);
// Move the first image to position (100, 500)
doc.repositionImage(0, images[0].name, 100, 500);
const output = doc.save();
doc.free();
let mut editor = DocumentEditor::open("input.pdf")?;
let images = editor.get_page_images(0)?;
// Move the first image
editor.reposition_image(0, &images[0].name, 100.0, 500.0)?;
editor.save("moved.pdf")?;
이미지 크기 변경
위치를 이동하지 않고 이미지 크기를 변경합니다.
doc = PdfDocument("input.pdf")
images = doc.page_images(0)
# Resize the first image to 300x200 points
doc.resize_image(0, images[0]["name"], 300, 200)
doc.save("resized.pdf")
import { WasmPdfDocument } from "pdf-oxide-wasm";
const doc = new WasmPdfDocument(bytes);
const images = doc.pageImages(0);
// Resize the first image to 300x200 points
doc.resizeImage(0, images[0].name, 300, 200);
const output = doc.save();
doc.free();
let mut editor = DocumentEditor::open("input.pdf")?;
let images = editor.get_page_images(0)?;
editor.resize_image(0, &images[0].name, 300.0, 200.0)?;
editor.save("resized.pdf")?;
전체 이미지 경계 설정
단일 작업으로 위치와 크기를 모두 설정합니다.
doc = PdfDocument("input.pdf")
images = doc.page_images(0)
# Set position (72, 600) and size (468, 200)
doc.set_image_bounds(0, images[0]["name"], 72, 600, 468, 200)
doc.save("adjusted.pdf")
let mut editor = DocumentEditor::open("input.pdf")?;
let images = editor.get_page_images(0)?;
// x, y, width, height
editor.set_image_bounds(0, &images[0].name, 72.0, 600.0, 468.0, 200.0)?;
editor.save("adjusted.pdf")?;
이미지 수정 관리
수정 사항 해제
저장 전 페이지의 모든 보류 중인 이미지 수정 사항을 폐기합니다.
doc.clear_image_modifications(0)
editor.clear_image_modifications(0);
보류 중인 수정 확인
if doc.has_image_modifications(0):
print("Page 0 has pending image changes")
if editor.has_image_modifications(0) {
println!("Page 0 has pending image changes");
}
PdfImage DOM API (Rust)
DOM 수준의 PdfImage는 페이지에서 발견된 각 이미지에 대한 풍부한 메타데이터를 제공합니다.
| 메서드 | 반환값 | 설명 |
|---|---|---|
id() |
ElementId |
Unique element identifier |
bbox() |
Rect |
Position and size on the page |
format() |
ImageFormat |
이미지 형식 (JPEG, PNG, etc.) |
dimensions() |
(u32, u32) |
Width and height in pixels |
aspect_ratio() |
f32 |
Width / height ratio |
is_grayscale() |
bool |
True if grayscale image |
alt_text() |
Option<&str> |
Accessibility alt text |
set_alt_text(text) |
() |
Set accessibility alt text |
resolution() |
Option<(f32, f32)> |
DPI as (horizontal, vertical) |
horizontal_dpi() |
Option<f32> |
Horizontal DPI |
vertical_dpi() |
Option<f32> |
Vertical DPI |
is_high_resolution() |
bool |
Resolution >= 300 DPI |
is_medium_resolution() |
bool |
Resolution between 150-300 DPI |
is_low_resolution() |
bool |
Resolution < 150 DPI |
영역 내 이미지 찾기
use pdf_oxide::geometry::Rect;
let page = doc.page(0)?;
// Find images in the top half of the page
let region = Rect::new(0.0, 396.0, 612.0, 396.0);
let top_images = page.find_images_in_region(region);
println!("Found {} images in top half", top_images.len());
접근성 대체 텍스트 설정
let mut page = doc.page(0)?;
let images = page.find_images();
for img in &images {
if img.alt_text().is_none() {
page.set_image_alt_text(img.id(), "Descriptive alt text")?;
}
}
doc.save_page(page)?;
전체 API 레퍼런스
DocumentEditor Image 메서드s
| 메서드 | 반환값 | 설명 |
|---|---|---|
get_page_images(page) |
Result<Vec<ImageInfo>> |
List all images on a page |
reposition_image(page, name, x, y) |
Result<()> |
이미지 이동 to new position |
resize_image(page, name, w, h) |
Result<()> |
Change image dimensions |
set_image_bounds(page, name, x, y, w, h) |
Result<()> |
Set position and size |
clear_image_modifications(page) |
() |
Discard pending changes |
has_image_modifications(page) |
bool |
Check for pending changes |
고급 예제: 모든 이미지 중앙 정렬
use pdf_oxide::editor::DocumentEditor;
let mut editor = DocumentEditor::open("input.pdf")?;
let count = editor.current_page_count();
for page_idx in 0..count {
let media_box = editor.get_page_media_box(page_idx)?;
let page_width = media_box[2] - media_box[0];
let images = editor.get_page_images(page_idx)?;
for img in &images {
let img_width = img.bounds[2];
let centered_x = (page_width - img_width) / 2.0;
editor.reposition_image(page_idx, &img.name, centered_x, img.bounds[1])?;
}
}
editor.save("centered.pdf")?;
고급 예제: 너비에 맞게 크기 조절
from pdf_oxide import PdfDocument
doc = PdfDocument("photos.pdf")
for page_idx in range(doc.page_count()):
media_box = doc.page_media_box(page_idx)
page_width = media_box[2] - media_box[0]
margin = 72 # 1 inch
images = doc.page_images(page_idx)
for img in images:
target_width = page_width - 2 * margin
scale = target_width / img["width"]
new_height = img["height"] * scale
doc.set_image_bounds(
page_idx, img["name"],
margin, img["y"],
target_width, new_height
)
doc.save("fitted.pdf")
관련 페이지
- Editing Overview – opening, metadata, and save workflow
- Text Editing – modify text around images
- Page Operations – crop and resize pages
- Annotation Editing – add captions or notes near images