استبدال صورة في ملف PDF موجود باستخدام Java

استخدم إما مجموعة صور الصفحة أو البحث القائم على الموضع وفقًا لدقة الاستهداف التي تحتاجها للصورة.

استبدال صورة وفقًا لمؤشر المورد

  1. افتح ملف PDF المصدر Document.
  2. انتقل إلى موارد الصورة على الهدف Page.
  3. استبدل مورد الصورة الهدف بملف الصورة الجديد.
  4. احفظ ملف 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

  1. افتح ملف PDF المصدر Document.
  2. أنشئ كائنًا من الفئة ImagePlacementAbsorber وزر الهدف Page.
  3. احصل على الهدف ImagePlacement واستبدله بتدفق الصورة الجديد.
  4. احفظ ملف 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());
    }
}