إضافة خلفيات إلى PDF باستخدام Java

تضع عناصر الخلفية صورة أو لونًا خلف محتوى الصفحة الرئيسي مع الحفاظ على النص المنطقي للمستند.

إضافة صورة خلفية إلى ملف PDF

يضع المثال صورة خلف محتوى الصفحة الأولى.

  1. افتح ملف PDF المصدر باستخدام الفئة Document وافتح دفق إدخال الصورة.
  2. أنشئ كائنًا من الفئة BackgroundArtifact وأسند إليه دفق الصورة.
  3. أضف العنصر إلى الصفحة واحفظ ملف PDF الناتج.
public static void addBackgroundImageToPdf(Path inputFile, Path imageFile, Path outputFile) throws Exception {
    try (Document document = new Document(inputFile.toString());
         InputStream imageStream = Files.newInputStream(imageFile)) {
        BackgroundArtifact artifact = new BackgroundArtifact();
        artifact.setBackgroundImage(imageStream);
        document.getPages().get_Item(1).getArtifacts().add(artifact);
        document.save(outputFile.toString());
    }
}

إضافة صورة خلفية شبه شفافة

يضبط المثال عتامة صورة الخلفية على 0.5.

  1. افتح ملف PDF المصدر باستخدام الفئة Document وافتح دفق إدخال الصورة.
  2. أنشئ كائنًا من الفئة BackgroundArtifact واضبط صورته وعتامته.
  3. أضف العنصر إلى الصفحة واحفظ ملف PDF الناتج.
public static void addBackgroundImageWithOpacityToPdf(Path inputFile, Path imageFile, Path outputFile)
        throws Exception {
    try (Document document = new Document(inputFile.toString());
         InputStream imageStream = Files.newInputStream(imageFile)) {
        BackgroundArtifact artifact = new BackgroundArtifact();
        artifact.setBackgroundImage(imageStream);
        artifact.setOpacity(0.5);
        document.getPages().get_Item(1).getArtifacts().add(artifact);
        document.save(outputFile.toString());
    }
}

إضافة لون خلفية إلى ملف PDF

يستخدم المثال لونًا موحّدًا لخلفية الصفحة.

  1. افتح ملف PDF المصدر باستخدام الفئة Document.
  2. أنشئ كائنًا من الفئة BackgroundArtifact وحدّد لون الخلفية.
  3. أضف العنصر إلى الصفحة واحفظ ملف PDF الناتج.
public static void addBackgroundColorToPdf(Path inputFile, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        BackgroundArtifact artifact = new BackgroundArtifact();
        artifact.setBackgroundColor(Color.getDarkKhaki().toRgb());
        document.getPages().get_Item(1).getArtifacts().add(artifact);
        document.save(outputFile.toString());
    }
}

مواضيع ذات صلة