הקדמה
Aspose.PDF FOSS עבור Python מתמקדת במחלקה Document, החשופה pages, form, outlines, tagged_content ו-attachments כנקודות הכניסה לעריכה מבנית ברמת המסמך. מעבר להוספת תוכן לעמוד, הספרייה מכסה את הפעולות שהופכות קובץ PDF למוצר שלם ומפיץ: שדות טופס אינטראקטיביים אשר אוספים ומציגים נתונים מובנים, קבצים מצורפים ברמת המסמך, גילוי והטמעת גופנים לכתיבת טקסט, ועץ סימניות לניווט. כל אחד מהתחומים הללו מעלה שגיאות דרך היררכיית חריגים יחידה המושרשת ב-AsposePdfException, כך שהקוראים יכולים לתפוס כשלים ספציפיים לחבילה מבלי לנחש סוגי חריגים מודול אחרי מודול.
מדריך זה מראה כיצד לעבוד עם ממשק ניהול המסמכים הזה: לתפוס ולהבדיל תתי-מחלקות של AsposePdfException, ליצור ולקרוא שדות AcroForm בעזרת Form ו-Field, להטמיע ולשחזר קבצים מצורפים דרך FileSpecification, לפתור גופנים עם FontRepository ו-FontRegistry, ולבנות עץ סימניות עם OutlineCollection ו-OutlineItem. כל סעיף משתמש רק במחלקות ובשיטות הקיימות בחבילה הנוכחית.
Aspose.PDF FOSS עבור Python היא חבילה Python, aspose-pdf-foss-for-python, שפורסמה תחת רישיון MIT, דורשת Python 3.11 או גרסה מאוחרת יותר. שם המודול ברמת העל הוא aspose_pdf. חבילה הליבה תלויה רק ב-cryptography וב-asn1crypto; תוספות אופציונליות מוסיפות פענוח תמונות מבוסס Pillow, תמיכה בגופנים WOFF2 מבוססי Brotli, ופריסה מורכבת של טקסט מבוססת HarfBuzz.
תכונות מרכזיות
טיפול בחריגות עם AsposePdfException
כל שגיאה ספציפית לחבילה ב-Aspose.PDF FOSS עבור Python נגזרת מ-AsposePdfException. רוב כשלונות עיבוד המסמכים נופלים תחת תת-מחלקת PdfException שלו, שהיא בתורה הבסיס ל-PdfParseException (קלט פגום), PdfSecurityException (כשלונות הצפנה וסיסמה, כולל InvalidPasswordException), ו-PdfValidationException (כשלונות מבניים או של תאימות). לתפוס את AsposePdfException אחרון, אחרי תתי-מחלקות ספציפיות יותר, מאפשר לקורא להגיב באופן שונה לסיסמה שגויה מאשר לקובץ פגום, תוך שמירה על טיפול אחיד לכל השאר שהחבילה יכולה לזרוק.
from aspose_pdf import Document
from aspose_pdf.exceptions import (
AsposePdfException,
InvalidPasswordException,
PdfParseException,
)
def open_document(path, password=None):
try:
document = Document()
document.load_from(path, password=password)
return document
except InvalidPasswordException:
print(f"{path}: a correct password is required")
except PdfParseException as error:
print(f"{path}: not a valid PDF ({error})")
except AsposePdfException as error:
# Catches every other aspose_pdf-specific error not handled above.
print(f"{path}: PDF operation failed ({error})")
return None
שדות טופס אינטראקטיביים
Document.form מחזיר Form חזית מעל שדות AcroForm של המסמך. Form.add_text_field(), add_checkbox() ו-add_radio_group() יוצרים שדות סופיים חדשים הקשורים לדף ולריבוע וידג’ט, כל אחד מחזיר Field. Field חושף את name, value ו-field_type כך שניתן לבדוק ולעדכן שדות קיימים לפי שם, ו-Field.remove() מוחק שדה לחלוטין.
from aspose_pdf import Document
with Document() as document:
page = document.pages.add()
document.form.add_text_field("customer_name", page, (72, 700, 300, 720))
document.form.add_checkbox("subscribe", page, (72, 670, 90, 688), on_value="Yes")
document.form.add_radio_group(
"plan",
page,
{"Basic": (72, 630, 90, 648), "Pro": (72, 600, 90, 618)},
value="Basic",
)
for field in document.form.fields:
print(field.name, field.field_type, field.value)
for field in document.form.fields:
if field.name == "customer_name":
field.value = "Jane Doe"
document.form.generate_appearances()
document.save("form.pdf")
קבצים משובצים וקבצים מצורפים
Document.add_attachment משבץ בתים כקובץ מצורף ברמת המסמך, שנכתב לעץ השמות /Names /EmbeddedFiles של ה-PDF בעת השמירה, יחד עם סוג MIME אופציונלי, תיאור ותאריכי יצירה/שינוי. Document.embedded_files קורא כל מצורף בחזרה כ-FileSpecification בעל טיפוס (name, contents, mime_type, description, size), ו-Document.get_embedded_file מחפש אחד לפי שם. FileSpecification.save() כותב את הבתים שהושבו לדיסק.
from aspose_pdf import Document
with Document() as document:
document.pages.add()
document.add_attachment(
"notes.txt",
b"Reviewed and approved.",
mime="text/plain",
description="Reviewer notes",
)
document.save("with-attachment.pdf")
with Document() as document:
document.load_from("with-attachment.pdf")
for spec in document.embedded_files:
print(spec.name, spec.mime_type, spec.size)
notes = document.get_embedded_file("notes.txt")
if notes is not None:
notes.save("notes-recovered.txt")
גילוי והטמעת גופנים
FontRepository מאגד מקורות גופנים ופותר גופנים לפי שם ברחבי המסמך. FontRepository.add_source() רושם FontSource כגון FolderFontSource (סורק תיקייה, אפשרי בצורה רקורסיבית); FontRepository.find_font() ו-search() לאחר מכן פותרים גופן לפי משפחה, שם מלא, או שם PostScript, ומשתמשים ברשימת הגופנים הסטנדרטית כגיבוי. כל התאמה היא FontDescriptor, שניתן להעביר ישירות ל-Page.add_text כדי להטמיע ולחתוך את הגופן. FontRegistry ממפה שמות לא-סטנדרטיים נפוצים (Arial, Times New Roman ודומיהם) לשם המקביל הקרוב ביותר ב-Standard-14 דרך search_font_by_name().
from aspose_pdf import Document, FolderFontSource, FontRepository
from aspose_pdf.font_registry import FontRegistry
FontRepository.add_source(FolderFontSource("./fonts", scan_subdirectories=True))
descriptor = FontRepository.find_font("Open Sans")
if descriptor is None:
# Fall back to the closest Standard-14 match for a common font name.
descriptor = FontRegistry().search_font_by_name("Arial")
with Document() as document:
page = document.pages.add()
page.add_text(
"Rendered with a resolved font",
x=72,
y=700,
font_size=14,
font=descriptor,
)
document.save("font-sample.pdf")
מתארי מסמך וסימניות
Document.outlines מחזיר OutlineCollection, מכולת הרמה העליונה לעץ הסימניות של PDF. OutlineCollection.add מוסיף OutlineItem ברמה העליונה; OutlineItem.add() משבץ סימנייה בת כמתחת לאחת קיימת. כל OutlineItem נושא title, יעד page_index, ודגלי תצוגה is_bold / is_italic, וכן חושף את רשימת children שלו.
from aspose_pdf import Document
from aspose_pdf.outlines import OutlineItem
with Document() as document:
document.pages.add()
document.pages.add()
chapter = OutlineItem("Chapter 1: Overview", page_index=0)
document.outlines.add(chapter)
chapter.add(OutlineItem("Section 1.1", page_index=0, is_italic=True))
document.outlines.add(OutlineItem("Chapter 2: Details", page_index=1, is_bold=True))
document.save("bookmarked.pdf")
התחלה מהירה
התקן את החבילה, ולאחר מכן בנה מסמך המשלב סימנייה, מטא-נתוני מסמך וקובץ מצורף בתסריט יחיד.
git clone https://github.com/aspose-pdf-foss/Aspose-PDF-FOSS-for-Python.git
cd Aspose-PDF-FOSS-for-Python
pip install -e .from aspose_pdf import Document
from aspose_pdf.outlines import OutlineItem
with Document() as document:
page = document.pages.add()
page.add_text("Quarterly Report", x=72, y=740, font_size=20)
document.outlines.add(OutlineItem("Quarterly Report", page_index=0))
document.info = {"Title": "Quarterly Report"}
document.add_attachment(
"source-data.csv", b"quarter,total\nQ1,1000\n", mime="text/csv"
)
document.save("report.pdf")
with Document() as reopened:
reopened.load_from("report.pdf")
print(reopened.page_count, "page(s),", reopened.info.get("Title"))
print([spec.name for spec in reopened.embedded_files])
פורמטים נתמכים
| פורמט | סיומת | קריאה | כתיבה |
|---|---|---|---|
| כן | כן | ||
| TIFF | tiff | - | Yes |
Page.render, Page.save_as_image, ו-Document.save_page_as_image גם מייצרים פלט רסטר PNG לצד TIFF.
אלו הם פלטי רסטריזציית דפים ולא פורמטים לטעינת מסמכים.
קוד פתוח ורישוי
Aspose.PDF FOSS עבור Python משוחרר תחת רישיון MIT: ללא מגבלות שימוש, ללא עמלות זמן ריצה, וללא דרישות רישום לשימוש מסחרי או אישי. קוד המקור מתארח ב-github.com/aspose-pdf-foss/Aspose-PDF-FOSS-for-Python, והחבילה מתפרסמת ב-PyPI בשם aspose-pdf-foss-for-python.