استبدال صورة في ملف PDF موجود باستخدام Java
Contents
[
Hide
]
استخدم إما مجموعة صور الصفحة أو البحث القائم على الموضع وفقًا لدقة الاستهداف التي تحتاجها للصورة.
استبدال صورة وفقًا لمؤشر المورد
- افتح ملف PDF المصدر Document.
- انتقل إلى موارد الصورة على الهدف Page.
- استبدل مورد الصورة الهدف بملف الصورة الجديد.
- احفظ ملف PDF المحدث Document.
public static void replaceImage(Path inputFile, Path imageFile, Path outputFile) throws Exception {
try (Document document = new Document(inputFile.toString());
InputStream imageStream = Files.newInputStream(imageFile)) {
document.getPages().get_Item(1).getResources().getImages().replace(1, imageStream);
document.save(outputFile.toString());
}
}
استبدال صورة باستخدام ImagePlacementAbsorber
- افتح ملف PDF المصدر Document.
- أنشئ كائنًا من الفئة ImagePlacementAbsorber وزر الهدف Page.
- احصل على الهدف ImagePlacement واستبدله بتدفق الصورة الجديد.
- احفظ ملف PDF المحدث Document.
public static void replaceImageWithAbsorber(Path inputFile, Path imageFile, Path outputFile) throws Exception {
try (Document document = new Document(inputFile.toString())) {
ImagePlacementAbsorber absorber = new ImagePlacementAbsorber();
document.getPages().get_Item(1).accept(absorber);
if (absorber.getImagePlacements().size() > 0) {
ImagePlacement imagePlacement = absorber.getImagePlacements().get_Item(1);
try (InputStream imageStream = Files.newInputStream(imageFile)) {
imagePlacement.replace(imageStream);
}
}
document.save(outputFile.toString());
}
}