إضافة خلفيات إلى 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());
}
}
إضافة صورة خلفية شبه شفافة
يضبط المثال عتامة صورة الخلفية على 0.5.
- افتح ملف PDF المصدر باستخدام الفئة Document وافتح دفق إدخال الصورة.
- أنشئ كائنًا من الفئة BackgroundArtifact واضبط صورته وعتامته.
- أضف العنصر إلى الصفحة واحفظ ملف 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
يستخدم المثال لونًا موحّدًا لخلفية الصفحة.
- افتح ملف PDF المصدر باستخدام الفئة Document.
- أنشئ كائنًا من الفئة BackgroundArtifact وحدّد لون الخلفية.
- أضف العنصر إلى الصفحة واحفظ ملف 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());
}
}