إضافة خلفيات PDF في Java
Contents
[
Hide
]
تسمح لك العناصر الخلفية بوضع عناصر بصرية ليست جزءًا من المحتوى خلف محتوى الصفحة الرئيسي دون تغيير نص الوثيقة المنطقي.
إضافة صورة خلفية إلى PDF
استخدم هذا المثال عندما يجب أن تعرض الصفحة صورة كعنصر خلفية.
- افتح ملف PDF المصدر Document وتيار إدخال الصورة.
- أنشئ كائنًا من الفئة BackgroundArtifact وأسند تدفق الصورة.
- أضف القطعة إلى الصفحة المستهدفة واحفظ ملف 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());
}
}
إضافة صورة خلفية مع الشفافية
هذا المثال يضع صورة خلفية شبه شفافة خلف محتوى الصفحة.
- افتح ملف PDF المصدر Document وتدفق الصورة.
- أنشئ كائنًا من الفئة BackgroundArtifact، عيّن الصورة، واضبط الشفافية.
- أضف العنصر إلى الصفحة واحفظ المستند.
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
استخدم هذا المثال عندما يجب أن تستخدم الصفحة لون خلفية صلب بدلاً من صورة.
- افتح ملف PDF المصدر Document.
- أنشئ كائنًا من الفئة BackgroundArtifact وعيّن لون الخلفية.
- أضف العنصر إلى الصفحة واحفظ ملف الإخراج.
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());
}
}
إزالة العناصر الخلفية
استخدم هذه الطريقة عندما يجب حذف العناصر الخلفية الموجودة من الصفحة.
- افتح ملف PDF المصدر Document.
- مرّ على مجموعة عناصر الصفحة بترتيب عكسي.
- احذف العناصر التي نوعها pagination والفرعية هي background، ثم حفظ المستند.
public static void removeBackground(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
for (int i = document.getPages().get_Item(1).getArtifacts().size(); i >= 1; i--) {
Artifact artifact = document.getPages().get_Item(1).getArtifacts().get_Item(i);
if (artifact.getType() == Artifact.ArtifactType.Pagination
&& artifact.getSubtype() == Artifact.ArtifactSubtype.Background) {
document.getPages().get_Item(1).getArtifacts().delete(artifact);
}
}
document.save(outputFile.toString());
}
}