From 9ae35d1b736112ec365a1918907b547e4e083eca Mon Sep 17 00:00:00 2001 From: Andriy Andruhovski Date: Fri, 8 May 2026 10:44:00 +0300 Subject: [PATCH 01/13] Add hugo-frontmatter-checker skill for auditing Markdown front matter --- .../skills/hugo-frontmatter-checker/SKILL.md | 59 +++ .../agents/openai.yaml | 4 + .../scripts/check_frontmatter.py | 373 ++++++++++++++++++ .../skills/hugo-frontmatter-checker/SKILL.md | 59 +++ .../agents/openai.yaml | 4 + .../scripts/check_frontmatter.py | 373 ++++++++++++++++++ AGENTS.md | 2 + 7 files changed, 874 insertions(+) create mode 100644 .agents/skills/hugo-frontmatter-checker/SKILL.md create mode 100644 .agents/skills/hugo-frontmatter-checker/agents/openai.yaml create mode 100644 .agents/skills/hugo-frontmatter-checker/scripts/check_frontmatter.py create mode 100644 .codex/skills/hugo-frontmatter-checker/SKILL.md create mode 100644 .codex/skills/hugo-frontmatter-checker/agents/openai.yaml create mode 100644 .codex/skills/hugo-frontmatter-checker/scripts/check_frontmatter.py diff --git a/.agents/skills/hugo-frontmatter-checker/SKILL.md b/.agents/skills/hugo-frontmatter-checker/SKILL.md new file mode 100644 index 000000000..b4ba27506 --- /dev/null +++ b/.agents/skills/hugo-frontmatter-checker/SKILL.md @@ -0,0 +1,59 @@ +--- +name: hugo-frontmatter-checker +description: "Audit Hugo Markdown documentation front matter for required keys, duplicate keys, YAML style hazards, URL shape, `type: docs`, integer weights, quoted `lastmod` dates, and trailing whitespace. Use this skill when a user asks to check, validate, lint, repair, or batch-scan Hugo front matter in Markdown docs, especially content repositories with language/product trees." +--- + +# Hugo Frontmatter Checker + +## Overview + +Use this skill to run a deterministic front matter audit on Hugo Markdown documentation pages. It is intended for syntax and style safety checks, not for rewriting page content or generating SEO text. + +The bundled script checks required and recommended top-level keys, duplicate keys, `type`, `url`, `weight`, `lastmod`, trailing whitespace, and unquoted colon hazards in scalar values. + +## Workflow + +1. Confirm the target scope from the user request. +2. Inspect nearby files when the request involves changing conventions, especially before adding or removing front matter keys. +3. Run `scripts/check_frontmatter.py` in audit mode first. +4. Review reported issues before applying fixes. +5. Apply auto-fixes only for safe mechanical repairs: + - `--fix-dates` quotes bare `lastmod` date values. + - `--fix-trailing` removes trailing whitespace inside front matter. +6. Re-run the audit after fixes. +7. For unresolved issues, edit the relevant Markdown files directly and preserve existing front matter structure. + +## Script Usage + +Audit a file or directory: + +```bash +python scripts/check_frontmatter.py path/to/file-or-dir +``` + +Show only required-key violations and hard YAML-style errors: + +```bash +python scripts/check_frontmatter.py path/to/file-or-dir --only-errors +``` + +Apply safe mechanical fixes: + +```bash +python scripts/check_frontmatter.py path/to/file-or-dir --fix-dates --fix-trailing +``` + +## Issue Handling + +- Treat missing required keys as content defects. +- Treat missing recommended keys as recommendations unless the surrounding section clearly requires them. +- Treat `url` changes as high risk. Prefer manual review before changing them. +- Treat `weight` changes as navigation changes, not formatting. +- Quote scalar values with `: ` manually when the script reports an unquoted colon hazard. +- Preserve structured metadata such as `TechArticle`, `FAQPage`, `ai_search_scope`, JSON-LD, aliases, and redirects unless the user explicitly asks to change them. + +## Repo Notes + +For Aspose.PDF documentation repositories, keep edits scoped to the requested language/product tree. Do not scan or batch-fix every language unless the user explicitly asks for a repository-wide audit. + +Use `frontmatter-seo-enricher` instead when the user asks to add or repair SEO metadata fields such as `AlternativeHeadline`, `Abstract`, or `TechArticle`. diff --git a/.agents/skills/hugo-frontmatter-checker/agents/openai.yaml b/.agents/skills/hugo-frontmatter-checker/agents/openai.yaml new file mode 100644 index 000000000..186024aee --- /dev/null +++ b/.agents/skills/hugo-frontmatter-checker/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Hugo Frontmatter Checker" + short_description: "Audit Hugo front matter style" + default_prompt: "Use $hugo-frontmatter-checker to scan Markdown documentation front matter, report required-key and YAML style issues, and apply only safe front matter fixes when requested." diff --git a/.agents/skills/hugo-frontmatter-checker/scripts/check_frontmatter.py b/.agents/skills/hugo-frontmatter-checker/scripts/check_frontmatter.py new file mode 100644 index 000000000..07f1512db --- /dev/null +++ b/.agents/skills/hugo-frontmatter-checker/scripts/check_frontmatter.py @@ -0,0 +1,373 @@ +""" +check_frontmatter.py +Checks Hugo Markdown front matter for YAML style issues across the docs tree. + +Usage: + python scripts/check_frontmatter.py [path] [--fix-dates] [--fix-trailing] [--only-errors] + +Arguments: + path Root directory to scan (default: current directory) + --fix-dates Auto-correct date values that are not quoted strings + --fix-trailing Auto-remove trailing whitespace from front matter lines + --only-errors Only report required-key violations and YAML errors; skip recommendations + +Exit codes: + 0 No issues found + 1 One or more issues found +""" + +from __future__ import annotations + +import argparse +import re +import sys +from pathlib import Path + +# ────────────────────────────────────────────────────────────────────────────── +# Configuration +# ────────────────────────────────────────────────────────────────────────────── + +REQUIRED_KEYS = {"title", "type", "url", "description"} +RECOMMENDED_KEYS = {"linktitle", "weight", "lastmod"} + +# Keys whose values must be quoted strings (YAML bare scalars would be wrong) +MUST_BE_QUOTED = {"lastmod"} + +DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") + +# ────────────────────────────────────────────────────────────────────────────── +# Helpers +# ────────────────────────────────────────────────────────────────────────────── + +_FRONTMATTER_RE = re.compile(r"^---\r?\n(.*?)\n---", re.DOTALL) + + +def extract_frontmatter(text: str) -> str | None: + """Return the raw front matter block (between the --- fences), or None.""" + m = _FRONTMATTER_RE.match(text) + return m.group(1) if m else None + + +def parse_top_level_keys(fm: str) -> list[tuple[int, str, str]]: + """ + Return a list of (line_number, key, raw_value) for every top-level + YAML mapping entry (lines that start with a non-space key: value). + Line numbers are 1-based relative to the front matter block. + """ + entries: list[tuple[int, str, str]] = [] + for lineno, line in enumerate(fm.splitlines(), start=1): + m = re.match(r'^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)', line) + if m: + entries.append((lineno, m.group(1), m.group(2).strip())) + return entries + + +# ────────────────────────────────────────────────────────────────────────────── +# Checkers — each returns a list of human-readable issue strings +# ────────────────────────────────────────────────────────────────────────────── + +def check_missing_fences(text: str) -> list[str]: + if not text.startswith("---"): + return ["No opening '---' front matter fence"] + if _FRONTMATTER_RE.match(text) is None: + return ["Front matter fence not properly closed with '---'"] + return [] + + +def check_duplicate_keys(entries: list[tuple[int, str, str]]) -> list[str]: + issues: list[str] = [] + seen: dict[str, int] = {} + for lineno, key, _ in entries: + if key in seen: + issues.append( + f"Duplicate key '{key}' at line {lineno} (first seen at line {seen[key]})" + ) + else: + seen[key] = lineno + return issues + + +def check_required_keys(keys: set[str]) -> list[str]: + missing = REQUIRED_KEYS - keys + return [f"Missing required key '{k}'" for k in sorted(missing)] + + +def check_recommended_keys(keys: set[str]) -> list[str]: + missing = RECOMMENDED_KEYS - keys + return [f"Missing recommended key '{k}'" for k in sorted(missing)] + + +def check_type_value(entries: list[tuple[int, str, str]]) -> list[str]: + for lineno, key, val in entries: + if key == "type" and val != "docs": + return [f"Key 'type' should be 'docs', got '{val}' at line {lineno}"] + return [] + + +def check_quoted_dates(entries: list[tuple[int, str, str]]) -> list[str]: + issues: list[str] = [] + for lineno, key, val in entries: + if key not in MUST_BE_QUOTED: + continue + # Acceptable: "2021-01-01" (with double quotes) + if val.startswith('"') and val.endswith('"'): + inner = val[1:-1] + if not DATE_RE.match(inner): + issues.append( + f"Key '{key}' at line {lineno} has unexpected quoted value: {val}" + ) + elif DATE_RE.match(val): + # Bare date — valid YAML but Hugo expects a quoted string + issues.append( + f"Key '{key}' at line {lineno} value should be quoted: {val}" + ) + else: + issues.append( + f"Key '{key}' at line {lineno} has unexpected value: {val}" + ) + return issues + + +def check_url_format(entries: list[tuple[int, str, str]]) -> list[str]: + issues: list[str] = [] + for lineno, key, val in entries: + if key != "url": + continue + # Strip surrounding quotes if present + url = val.strip('"').strip("'") + if not url.startswith("/"): + issues.append(f"Key 'url' at line {lineno} should start with '/': {url}") + if not url.endswith("/"): + issues.append(f"Key 'url' at line {lineno} should end with '/': {url}") + return issues + + +def check_weight(entries: list[tuple[int, str, str]]) -> list[str]: + issues: list[str] = [] + for lineno, key, val in entries: + if key != "weight": + continue + try: + int(val) + except ValueError: + issues.append( + f"Key 'weight' at line {lineno} should be an integer, got: {val}" + ) + return issues + + +def check_trailing_whitespace(fm: str) -> list[str]: + issues: list[str] = [] + for lineno, line in enumerate(fm.splitlines(), start=1): + if line != line.rstrip(): + issues.append(f"Trailing whitespace on line {lineno}") + return issues + + +def check_unquoted_colons(entries: list[tuple[int, str, str]]) -> list[str]: + """ + Detect top-level scalar values that contain ': ' (colon-space) or end with ':' + without being quoted. YAML treats 'key: value: more' as ambiguous and many + parsers (including Hugo's) will reject or misparse it. + """ + issues: list[str] = [] + for lineno, key, val in entries: + # Skip already-quoted values (single or double quotes) + if (val.startswith('"') and val.endswith('"')) or \ + (val.startswith("'") and val.endswith("'")): + continue + # Skip empty values, booleans, numbers — they can't carry ': ' + if not val or val in ("true", "false", "null"): + continue + # Flag if the bare value contains ': ' or ends with ':' + if ": " in val or val.endswith(":"): + issues.append( + f"Key '{key}' at line {lineno} value contains an unquoted colon " + f"and must be quoted: {val[:60]}{'...' if len(val) > 60 else ''}" + ) + return issues + + +# ────────────────────────────────────────────────────────────────────────────── +# Auto-fix helpers +# ────────────────────────────────────────────────────────────────────────────── + +def fix_trailing_whitespace(text: str) -> str: + """Remove trailing whitespace from every line in the front matter block.""" + fm_match = _FRONTMATTER_RE.match(text) + if not fm_match: + return text + fm = fm_match.group(1) + fixed_fm = "\n".join(line.rstrip() for line in fm.splitlines()) + return text[:fm_match.start(1)] + fixed_fm + text[fm_match.end(1):] + + +def fix_unquoted_dates(text: str) -> str: + """Quote bare date values for keys in MUST_BE_QUOTED.""" + def replacer(m: re.Match) -> str: + key = m.group(1) + val = m.group(2) + if key in MUST_BE_QUOTED and DATE_RE.match(val): + return f'{key}: "{val}"' + return m.group(0) + + fm_match = _FRONTMATTER_RE.match(text) + if not fm_match: + return text + fm = fm_match.group(1) + fixed_fm = re.sub(r'^([A-Za-z_][A-Za-z0-9_]*):\s+(\d{4}-\d{2}-\d{2})\s*$', + replacer, fm, flags=re.MULTILINE) + return text[:fm_match.start(1)] + fixed_fm + text[fm_match.end(1):] + + +# ────────────────────────────────────────────────────────────────────────────── +# Main scan logic +# ────────────────────────────────────────────────────────────────────────────── + +def check_file( + path: Path, + fix_dates: bool = False, + fix_trailing: bool = False, + only_errors: bool = False, +) -> list[str]: + text = path.read_text(encoding="utf-8", errors="replace") + + issues: list[str] = [] + + fence_issues = check_missing_fences(text) + if fence_issues: + return fence_issues # Cannot parse further without valid fences + + fm = extract_frontmatter(text) + if fm is None: + return ["Could not extract front matter"] + + entries = parse_top_level_keys(fm) + keys = {k for _, k, _ in entries} + + issues += check_duplicate_keys(entries) + issues += check_required_keys(keys) + if not only_errors: + issues += check_recommended_keys(keys) + issues += check_type_value(entries) + issues += check_quoted_dates(entries) + issues += check_url_format(entries) + issues += check_weight(entries) + issues += check_trailing_whitespace(fm) + issues += check_unquoted_colons(entries) + + modified = text + if fix_trailing and any("Trailing whitespace" in i for i in issues): + modified = fix_trailing_whitespace(modified) + + if fix_dates and any("should be quoted" in i for i in issues): + modified = fix_unquoted_dates(modified) + + if modified != text: + path.write_text(modified, encoding="utf-8") + + return issues + + +def iter_markdown_files(root: Path) -> list[Path]: + if root.is_file(): + return [root] if root.suffix.lower() == ".md" else [] + return sorted(root.rglob("*.md")) + + +def scan( + root: Path, + fix_dates: bool = False, + fix_trailing: bool = False, + only_errors: bool = False, +) -> int: + # Ensure stdout can handle Unicode on Windows (e.g. cp1251 consoles) + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + files = iter_markdown_files(root) + total_issues = 0 + files_with_issues = 0 + + for md in files: + # Skip root-level non-content files (README.md, AGENTS.md, etc.) + # Only apply this guard when scanning the repo root (root has no parent lang folder). + rel = md.relative_to(root) if root.is_dir() else Path(md.name) + parts = rel.parts + if len(parts) == 1 and md.stem.upper() in {"README", "AGENTS", "CONTRIBUTING"}: + continue + + issues = check_file( + md, + fix_dates=fix_dates, + fix_trailing=fix_trailing, + only_errors=only_errors, + ) + if issues: + files_with_issues += 1 + total_issues += len(issues) + print(f"\n{rel}") + for issue in issues: + print(f" [FAIL] {issue}") + + print( + f"\n{'-' * 60}\n" + f"Scanned {len(files)} files | " + f"{files_with_issues} files with issues | " + f"{total_issues} total issues" + ) + return 1 if total_issues else 0 + + +# ────────────────────────────────────────────────────────────────────────────── +# Entry point +# ────────────────────────────────────────────────────────────────────────────── + +def main() -> None: + parser = argparse.ArgumentParser( + description="Check Hugo front matter YAML style in Markdown files." + ) + parser.add_argument( + "path", + nargs="?", + default=".", + help="Root directory to scan (default: current directory)", + ) + parser.add_argument( + "--fix-dates", + action="store_true", + help="Auto-quote bare date values for lastmod and similar keys", + ) + parser.add_argument( + "--fix-trailing", + action="store_true", + help="Auto-remove trailing whitespace from front matter lines", + ) + parser.add_argument( + "--only-errors", + + action="store_true", + help="Only report required-key violations and YAML errors; skip recommendations", + ) + args = parser.parse_args() + + root = Path(args.path).resolve() + if not root.exists(): + print(f"Error: '{root}' does not exist", file=sys.stderr) + sys.exit(2) + if root.is_file() and root.suffix.lower() != ".md": + print(f"Error: '{root}' is not a Markdown file", file=sys.stderr) + sys.exit(2) + + sys.exit( + scan( + root, + fix_dates=args.fix_dates, + fix_trailing=args.fix_trailing, + only_errors=args.only_errors, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/.codex/skills/hugo-frontmatter-checker/SKILL.md b/.codex/skills/hugo-frontmatter-checker/SKILL.md new file mode 100644 index 000000000..b4ba27506 --- /dev/null +++ b/.codex/skills/hugo-frontmatter-checker/SKILL.md @@ -0,0 +1,59 @@ +--- +name: hugo-frontmatter-checker +description: "Audit Hugo Markdown documentation front matter for required keys, duplicate keys, YAML style hazards, URL shape, `type: docs`, integer weights, quoted `lastmod` dates, and trailing whitespace. Use this skill when a user asks to check, validate, lint, repair, or batch-scan Hugo front matter in Markdown docs, especially content repositories with language/product trees." +--- + +# Hugo Frontmatter Checker + +## Overview + +Use this skill to run a deterministic front matter audit on Hugo Markdown documentation pages. It is intended for syntax and style safety checks, not for rewriting page content or generating SEO text. + +The bundled script checks required and recommended top-level keys, duplicate keys, `type`, `url`, `weight`, `lastmod`, trailing whitespace, and unquoted colon hazards in scalar values. + +## Workflow + +1. Confirm the target scope from the user request. +2. Inspect nearby files when the request involves changing conventions, especially before adding or removing front matter keys. +3. Run `scripts/check_frontmatter.py` in audit mode first. +4. Review reported issues before applying fixes. +5. Apply auto-fixes only for safe mechanical repairs: + - `--fix-dates` quotes bare `lastmod` date values. + - `--fix-trailing` removes trailing whitespace inside front matter. +6. Re-run the audit after fixes. +7. For unresolved issues, edit the relevant Markdown files directly and preserve existing front matter structure. + +## Script Usage + +Audit a file or directory: + +```bash +python scripts/check_frontmatter.py path/to/file-or-dir +``` + +Show only required-key violations and hard YAML-style errors: + +```bash +python scripts/check_frontmatter.py path/to/file-or-dir --only-errors +``` + +Apply safe mechanical fixes: + +```bash +python scripts/check_frontmatter.py path/to/file-or-dir --fix-dates --fix-trailing +``` + +## Issue Handling + +- Treat missing required keys as content defects. +- Treat missing recommended keys as recommendations unless the surrounding section clearly requires them. +- Treat `url` changes as high risk. Prefer manual review before changing them. +- Treat `weight` changes as navigation changes, not formatting. +- Quote scalar values with `: ` manually when the script reports an unquoted colon hazard. +- Preserve structured metadata such as `TechArticle`, `FAQPage`, `ai_search_scope`, JSON-LD, aliases, and redirects unless the user explicitly asks to change them. + +## Repo Notes + +For Aspose.PDF documentation repositories, keep edits scoped to the requested language/product tree. Do not scan or batch-fix every language unless the user explicitly asks for a repository-wide audit. + +Use `frontmatter-seo-enricher` instead when the user asks to add or repair SEO metadata fields such as `AlternativeHeadline`, `Abstract`, or `TechArticle`. diff --git a/.codex/skills/hugo-frontmatter-checker/agents/openai.yaml b/.codex/skills/hugo-frontmatter-checker/agents/openai.yaml new file mode 100644 index 000000000..186024aee --- /dev/null +++ b/.codex/skills/hugo-frontmatter-checker/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Hugo Frontmatter Checker" + short_description: "Audit Hugo front matter style" + default_prompt: "Use $hugo-frontmatter-checker to scan Markdown documentation front matter, report required-key and YAML style issues, and apply only safe front matter fixes when requested." diff --git a/.codex/skills/hugo-frontmatter-checker/scripts/check_frontmatter.py b/.codex/skills/hugo-frontmatter-checker/scripts/check_frontmatter.py new file mode 100644 index 000000000..07f1512db --- /dev/null +++ b/.codex/skills/hugo-frontmatter-checker/scripts/check_frontmatter.py @@ -0,0 +1,373 @@ +""" +check_frontmatter.py +Checks Hugo Markdown front matter for YAML style issues across the docs tree. + +Usage: + python scripts/check_frontmatter.py [path] [--fix-dates] [--fix-trailing] [--only-errors] + +Arguments: + path Root directory to scan (default: current directory) + --fix-dates Auto-correct date values that are not quoted strings + --fix-trailing Auto-remove trailing whitespace from front matter lines + --only-errors Only report required-key violations and YAML errors; skip recommendations + +Exit codes: + 0 No issues found + 1 One or more issues found +""" + +from __future__ import annotations + +import argparse +import re +import sys +from pathlib import Path + +# ────────────────────────────────────────────────────────────────────────────── +# Configuration +# ────────────────────────────────────────────────────────────────────────────── + +REQUIRED_KEYS = {"title", "type", "url", "description"} +RECOMMENDED_KEYS = {"linktitle", "weight", "lastmod"} + +# Keys whose values must be quoted strings (YAML bare scalars would be wrong) +MUST_BE_QUOTED = {"lastmod"} + +DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") + +# ────────────────────────────────────────────────────────────────────────────── +# Helpers +# ────────────────────────────────────────────────────────────────────────────── + +_FRONTMATTER_RE = re.compile(r"^---\r?\n(.*?)\n---", re.DOTALL) + + +def extract_frontmatter(text: str) -> str | None: + """Return the raw front matter block (between the --- fences), or None.""" + m = _FRONTMATTER_RE.match(text) + return m.group(1) if m else None + + +def parse_top_level_keys(fm: str) -> list[tuple[int, str, str]]: + """ + Return a list of (line_number, key, raw_value) for every top-level + YAML mapping entry (lines that start with a non-space key: value). + Line numbers are 1-based relative to the front matter block. + """ + entries: list[tuple[int, str, str]] = [] + for lineno, line in enumerate(fm.splitlines(), start=1): + m = re.match(r'^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)', line) + if m: + entries.append((lineno, m.group(1), m.group(2).strip())) + return entries + + +# ────────────────────────────────────────────────────────────────────────────── +# Checkers — each returns a list of human-readable issue strings +# ────────────────────────────────────────────────────────────────────────────── + +def check_missing_fences(text: str) -> list[str]: + if not text.startswith("---"): + return ["No opening '---' front matter fence"] + if _FRONTMATTER_RE.match(text) is None: + return ["Front matter fence not properly closed with '---'"] + return [] + + +def check_duplicate_keys(entries: list[tuple[int, str, str]]) -> list[str]: + issues: list[str] = [] + seen: dict[str, int] = {} + for lineno, key, _ in entries: + if key in seen: + issues.append( + f"Duplicate key '{key}' at line {lineno} (first seen at line {seen[key]})" + ) + else: + seen[key] = lineno + return issues + + +def check_required_keys(keys: set[str]) -> list[str]: + missing = REQUIRED_KEYS - keys + return [f"Missing required key '{k}'" for k in sorted(missing)] + + +def check_recommended_keys(keys: set[str]) -> list[str]: + missing = RECOMMENDED_KEYS - keys + return [f"Missing recommended key '{k}'" for k in sorted(missing)] + + +def check_type_value(entries: list[tuple[int, str, str]]) -> list[str]: + for lineno, key, val in entries: + if key == "type" and val != "docs": + return [f"Key 'type' should be 'docs', got '{val}' at line {lineno}"] + return [] + + +def check_quoted_dates(entries: list[tuple[int, str, str]]) -> list[str]: + issues: list[str] = [] + for lineno, key, val in entries: + if key not in MUST_BE_QUOTED: + continue + # Acceptable: "2021-01-01" (with double quotes) + if val.startswith('"') and val.endswith('"'): + inner = val[1:-1] + if not DATE_RE.match(inner): + issues.append( + f"Key '{key}' at line {lineno} has unexpected quoted value: {val}" + ) + elif DATE_RE.match(val): + # Bare date — valid YAML but Hugo expects a quoted string + issues.append( + f"Key '{key}' at line {lineno} value should be quoted: {val}" + ) + else: + issues.append( + f"Key '{key}' at line {lineno} has unexpected value: {val}" + ) + return issues + + +def check_url_format(entries: list[tuple[int, str, str]]) -> list[str]: + issues: list[str] = [] + for lineno, key, val in entries: + if key != "url": + continue + # Strip surrounding quotes if present + url = val.strip('"').strip("'") + if not url.startswith("/"): + issues.append(f"Key 'url' at line {lineno} should start with '/': {url}") + if not url.endswith("/"): + issues.append(f"Key 'url' at line {lineno} should end with '/': {url}") + return issues + + +def check_weight(entries: list[tuple[int, str, str]]) -> list[str]: + issues: list[str] = [] + for lineno, key, val in entries: + if key != "weight": + continue + try: + int(val) + except ValueError: + issues.append( + f"Key 'weight' at line {lineno} should be an integer, got: {val}" + ) + return issues + + +def check_trailing_whitespace(fm: str) -> list[str]: + issues: list[str] = [] + for lineno, line in enumerate(fm.splitlines(), start=1): + if line != line.rstrip(): + issues.append(f"Trailing whitespace on line {lineno}") + return issues + + +def check_unquoted_colons(entries: list[tuple[int, str, str]]) -> list[str]: + """ + Detect top-level scalar values that contain ': ' (colon-space) or end with ':' + without being quoted. YAML treats 'key: value: more' as ambiguous and many + parsers (including Hugo's) will reject or misparse it. + """ + issues: list[str] = [] + for lineno, key, val in entries: + # Skip already-quoted values (single or double quotes) + if (val.startswith('"') and val.endswith('"')) or \ + (val.startswith("'") and val.endswith("'")): + continue + # Skip empty values, booleans, numbers — they can't carry ': ' + if not val or val in ("true", "false", "null"): + continue + # Flag if the bare value contains ': ' or ends with ':' + if ": " in val or val.endswith(":"): + issues.append( + f"Key '{key}' at line {lineno} value contains an unquoted colon " + f"and must be quoted: {val[:60]}{'...' if len(val) > 60 else ''}" + ) + return issues + + +# ────────────────────────────────────────────────────────────────────────────── +# Auto-fix helpers +# ────────────────────────────────────────────────────────────────────────────── + +def fix_trailing_whitespace(text: str) -> str: + """Remove trailing whitespace from every line in the front matter block.""" + fm_match = _FRONTMATTER_RE.match(text) + if not fm_match: + return text + fm = fm_match.group(1) + fixed_fm = "\n".join(line.rstrip() for line in fm.splitlines()) + return text[:fm_match.start(1)] + fixed_fm + text[fm_match.end(1):] + + +def fix_unquoted_dates(text: str) -> str: + """Quote bare date values for keys in MUST_BE_QUOTED.""" + def replacer(m: re.Match) -> str: + key = m.group(1) + val = m.group(2) + if key in MUST_BE_QUOTED and DATE_RE.match(val): + return f'{key}: "{val}"' + return m.group(0) + + fm_match = _FRONTMATTER_RE.match(text) + if not fm_match: + return text + fm = fm_match.group(1) + fixed_fm = re.sub(r'^([A-Za-z_][A-Za-z0-9_]*):\s+(\d{4}-\d{2}-\d{2})\s*$', + replacer, fm, flags=re.MULTILINE) + return text[:fm_match.start(1)] + fixed_fm + text[fm_match.end(1):] + + +# ────────────────────────────────────────────────────────────────────────────── +# Main scan logic +# ────────────────────────────────────────────────────────────────────────────── + +def check_file( + path: Path, + fix_dates: bool = False, + fix_trailing: bool = False, + only_errors: bool = False, +) -> list[str]: + text = path.read_text(encoding="utf-8", errors="replace") + + issues: list[str] = [] + + fence_issues = check_missing_fences(text) + if fence_issues: + return fence_issues # Cannot parse further without valid fences + + fm = extract_frontmatter(text) + if fm is None: + return ["Could not extract front matter"] + + entries = parse_top_level_keys(fm) + keys = {k for _, k, _ in entries} + + issues += check_duplicate_keys(entries) + issues += check_required_keys(keys) + if not only_errors: + issues += check_recommended_keys(keys) + issues += check_type_value(entries) + issues += check_quoted_dates(entries) + issues += check_url_format(entries) + issues += check_weight(entries) + issues += check_trailing_whitespace(fm) + issues += check_unquoted_colons(entries) + + modified = text + if fix_trailing and any("Trailing whitespace" in i for i in issues): + modified = fix_trailing_whitespace(modified) + + if fix_dates and any("should be quoted" in i for i in issues): + modified = fix_unquoted_dates(modified) + + if modified != text: + path.write_text(modified, encoding="utf-8") + + return issues + + +def iter_markdown_files(root: Path) -> list[Path]: + if root.is_file(): + return [root] if root.suffix.lower() == ".md" else [] + return sorted(root.rglob("*.md")) + + +def scan( + root: Path, + fix_dates: bool = False, + fix_trailing: bool = False, + only_errors: bool = False, +) -> int: + # Ensure stdout can handle Unicode on Windows (e.g. cp1251 consoles) + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + + files = iter_markdown_files(root) + total_issues = 0 + files_with_issues = 0 + + for md in files: + # Skip root-level non-content files (README.md, AGENTS.md, etc.) + # Only apply this guard when scanning the repo root (root has no parent lang folder). + rel = md.relative_to(root) if root.is_dir() else Path(md.name) + parts = rel.parts + if len(parts) == 1 and md.stem.upper() in {"README", "AGENTS", "CONTRIBUTING"}: + continue + + issues = check_file( + md, + fix_dates=fix_dates, + fix_trailing=fix_trailing, + only_errors=only_errors, + ) + if issues: + files_with_issues += 1 + total_issues += len(issues) + print(f"\n{rel}") + for issue in issues: + print(f" [FAIL] {issue}") + + print( + f"\n{'-' * 60}\n" + f"Scanned {len(files)} files | " + f"{files_with_issues} files with issues | " + f"{total_issues} total issues" + ) + return 1 if total_issues else 0 + + +# ────────────────────────────────────────────────────────────────────────────── +# Entry point +# ────────────────────────────────────────────────────────────────────────────── + +def main() -> None: + parser = argparse.ArgumentParser( + description="Check Hugo front matter YAML style in Markdown files." + ) + parser.add_argument( + "path", + nargs="?", + default=".", + help="Root directory to scan (default: current directory)", + ) + parser.add_argument( + "--fix-dates", + action="store_true", + help="Auto-quote bare date values for lastmod and similar keys", + ) + parser.add_argument( + "--fix-trailing", + action="store_true", + help="Auto-remove trailing whitespace from front matter lines", + ) + parser.add_argument( + "--only-errors", + + action="store_true", + help="Only report required-key violations and YAML errors; skip recommendations", + ) + args = parser.parse_args() + + root = Path(args.path).resolve() + if not root.exists(): + print(f"Error: '{root}' does not exist", file=sys.stderr) + sys.exit(2) + if root.is_file() and root.suffix.lower() != ".md": + print(f"Error: '{root}' is not a Markdown file", file=sys.stderr) + sys.exit(2) + + sys.exit( + scan( + root, + fix_dates=args.fix_dates, + fix_trailing=args.fix_trailing, + only_errors=args.only_errors, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/AGENTS.md b/AGENTS.md index 8e207fde7..aca678d1c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -147,6 +147,7 @@ This repository includes project-local skills under `.skills/`. Current skills: - `frontmatter-seo-enricher` +- `hugo-frontmatter-checker` - `java-style-reviewer` - `python-formatter-bootstrap` - `python-style-reviewer` @@ -154,6 +155,7 @@ Current skills: Use them when relevant: - `frontmatter-seo-enricher` for SEO metadata fields such as `AlternativeHeadline`, `Abstract`, and `TechArticle` +- `hugo-frontmatter-checker` for required-key, YAML style, URL, weight, `type`, `lastmod`, and trailing-whitespace audits in Hugo Markdown front matter - `java-style-reviewer` for Markdown structure and fenced `java` code cleanup in Java docs - `python-style-reviewer` for Python formatting in `.py` files and fenced Python code blocks in Markdown - `python-formatter-bootstrap` when a required Python formatter is missing from the environment From 839c01d80b0d62a2ca69b8fd357f08ee4af60d11 Mon Sep 17 00:00:00 2001 From: Andriy Andruhovski Date: Fri, 8 May 2026 10:45:11 +0300 Subject: [PATCH 02/13] Update documentation for PDF form field manipulation using Aspose.PDF for Python - Enhanced descriptions and abstracts for various articles related to adding, removing, and modifying form fields. - Standardized formatting and alignment in metadata across multiple documentation files. - Improved clarity in instructions for setting JavaScript actions, customizing field appearances, and managing list items in PDF forms. --- .../annotations/add-delete-and-get-annotation/_index.md | 2 +- .../media-annotations/_index.md | 2 +- .../shape-annotations/_index.md | 2 +- en/python-net/advanced-operations/artifacts/_index.md | 2 +- .../artifacts/add-bates-numbering/_index.md | 2 +- .../advanced-operations/artifacts/add-watermarks/_index.md | 2 +- .../artifacts/artifacts-header-footer/_index.md | 2 +- .../artifacts/counting-artifacts/_index.md | 2 +- .../advanced-operations/compare-pdf-documents/_index.md | 4 ++-- .../navigation-and-interaction/links/_index.md | 2 +- .../links/extract-links/_index.md | 4 ++-- .../navigation-and-interaction/links/update-links/_index.md | 2 +- .../advanced-operations/securing-and-signing/_index.md | 2 +- .../securing-and-signing/digitally-sign-pdf-file/_index.md | 4 ++-- .../securing-and-signing/extract-signature-info/_index.md | 2 +- .../securing-and-signing/set-privileges/_index.md | 4 ++-- .../sign-pdf-document-from-smart-card/_index.md | 4 ++-- .../working-with-documents/create-pdf-document/_index.md | 2 +- .../formatting-pdf-document/_index.md | 2 +- .../manipulate-pdf-document/_index.md | 2 +- .../working-with-documents/merge-pdf/_index.md | 2 +- .../working-with-documents/optimize-pdf-document/_index.md | 2 +- .../working-with-pages/rotate-pages/_index.md | 2 +- en/python-net/advanced-operations/zugferd/_index.md | 2 +- .../advanced-operations/zugferd/attach-zugferd/_index.md | 4 ++-- en/python-net/basic-operations/_index.md | 2 +- en/python-net/basic-operations/create/_index.md | 2 +- en/python-net/basic-operations/merge-pdf/_index.md | 2 +- en/python-net/basic-operations/saving/_index.md | 2 +- en/python-net/converting/_index.md | 2 +- en/python-net/converting/convert-html-to-pdf/_index.md | 2 +- .../converting/convert-images-format-to-pdf/_index.md | 4 ++-- .../converting/convert-other-files-to-pdf/_index.md | 2 +- en/python-net/converting/convert-pdf-to-excel/_index.md | 2 +- .../converting/convert-pdf-to-images-format/_index.md | 2 +- .../converting/convert-pdf-to-other-files/_index.md | 4 ++-- en/python-net/converting/convert-pdf-to-pdfx/_index.md | 2 +- .../converting/convert-pdf-to-powerpoint/_index.md | 2 +- en/python-net/converting/convert-pdf-to-word/_index.md | 2 +- en/python-net/converting/convert-pdfx-to-pdf/_index.md | 2 +- en/python-net/faq/_index.md | 2 +- en/python-net/get-started/hello-world-example/_index.md | 2 +- en/python-net/overview/licensing/_index.md | 2 +- en/python-net/parsing/_index.md | 2 +- en/python-net/whatsnew/_index.md | 2 +- .../form/button-fields-and-images/_index.md | 2 +- .../formeditor/adding-scripts-and-submit-actions/_index.md | 4 ++-- .../add-field-script/_index.md | 6 +++--- .../remove-field-action/_index.md | 2 +- .../set-field-script/_index.md | 4 ++-- .../set-submit-flag/_index.md | 4 ++-- .../set-submit-url/_index.md | 4 ++-- .../formeditor/creating-form-field/_index.md | 2 +- .../creating-form-field/create-checkbox-field/_index.md | 2 +- .../creating-form-field/create-combobox-field/_index.md | 2 +- .../creating-form-field/create-listbox-field/_index.md | 2 +- .../creating-form-field/create-radiobutton-field/_index.md | 2 +- .../creating-form-field/create-submit-button/_index.md | 2 +- .../creating-form-field/create-textbox-field/_index.md | 2 +- .../formeditor/customizing-field-appearance/_index.md | 4 ++-- .../customizing-field-appearance/decorate-field/_index.md | 4 ++-- .../get-field-appearance/_index.md | 4 ++-- .../set-field-alignment-vertical/_index.md | 4 ++-- .../set-field-alignment/_index.md | 4 ++-- .../set-field-appearance/_index.md | 4 ++-- .../set-field-comb-number/_index.md | 4 ++-- .../customizing-field-appearance/set-field-limit/_index.md | 4 ++-- .../formeditor/modifying-form-fields/_index.md | 4 ++-- .../modifying-form-fields/add-list-item/_index.md | 4 ++-- .../modifying-form-fields/copy-inner-field/_index.md | 4 ++-- .../modifying-form-fields/copy-outer-field/_index.md | 4 ++-- .../modifying-form-fields/del-list-item/_index.md | 6 +++--- .../formeditor/modifying-form-fields/move-field/_index.md | 4 ++-- .../formeditor/modifying-form-fields/remove-field/_index.md | 4 ++-- .../formeditor/modifying-form-fields/rename-field/_index.md | 4 ++-- .../modifying-form-fields/single-to-multiple/_index.md | 6 +++--- .../pdfcontenteditor/annotations/_index.md | 4 ++-- .../annotations/add-caret-annotation/_index.md | 4 ++-- .../annotations/add-free-text-annotation/_index.md | 2 +- .../annotations/add-markup-annotation/_index.md | 4 ++-- .../annotations/add-popup-annotation/_index.md | 2 +- .../pdfcontenteditor/attachments/_index.md | 2 +- .../attachments/add-file-attachment-annotation/_index.md | 2 +- .../add_file-attachment-annotation-from-stream/_index.md | 2 +- .../attachments/remove-attachments/_index.md | 2 +- .../pdfcontenteditor/document-actions/_index.md | 2 +- .../document-actions/add-bookmark-action/_index.md | 4 ++-- .../document-actions/add-document-action/_index.md | 4 ++-- .../document-actions/remove-open-action/_index.md | 2 +- .../pdfcontenteditor/drawing-annotations/_index.md | 4 ++-- .../drawing-annotations/add-circle-annotation/_index.md | 2 +- .../drawing-annotations/add-curve-annotation/_index.md | 2 +- .../drawing-annotations/add-line-annotation/_index.md | 2 +- .../drawing-annotations/add-polygon-annotation/_index.md | 2 +- .../drawing-annotations/add-polyline-annotation/_index.md | 2 +- .../drawing-annotations/add-square-annotation/_index.md | 2 +- .../pdfcontenteditor/image-operations/_index.md | 4 ++-- .../image-operations/delete-all-images/_index.md | 2 +- .../image-operations/delete-images/_index.md | 4 ++-- .../image-operations/replace-image/_index.md | 2 +- .../pdfcontenteditor/links-and-navigation/_index.md | 4 ++-- .../links-and-navigation/add-application-link/_index.md | 2 +- .../links-and-navigation/add-custom-action-link/_index.md | 2 +- .../links-and-navigation/add-javascript-link/_index.md | 2 +- .../links-and-navigation/add-local-link/_index.md | 2 +- .../links-and-navigation/add-pdf-document-link/_index.md | 2 +- .../links-and-navigation/add-web-link/_index.md | 2 +- .../links-and-navigation/extract-links/_index.md | 2 +- .../pdfcontenteditor/multimedia/_index.md | 2 +- .../pdfcontenteditor/stamps-management/_index.md | 2 +- .../stamps-management/add-rubber-stamp/_index.md | 2 +- .../create-rubber-stamp-with-appearance-file/_index.md | 2 +- .../create-rubber-stamp-with-appearance-stream/_index.md | 2 +- .../delete-stamp-by-ids-examples/_index.md | 4 ++-- .../stamps-management/delete-stamps-globally/_index.md | 2 +- .../stamps-management/list-stamps/_index.md | 2 +- .../stamps-management/manage-stamp-by-id/_index.md | 2 +- .../stamps-management/move-stamp-by-id-example/_index.md | 2 +- .../stamps-management/move-stamp-by-index/_index.md | 2 +- .../pdfcontenteditor/text-operations/_index.md | 2 +- .../replace-text-on-page-with-state/_index.md | 2 +- .../text-operations/replace-text-on-page/_index.md | 2 +- .../text-operations/replace-text-regex/_index.md | 2 +- .../text-operations/replace-text-simple/_index.md | 2 +- .../text-operations/replace-text-with-state/_index.md | 2 +- .../pdfcontenteditor/viewer-preferences/_index.md | 2 +- .../viewer-preferences/change-viewer-preferences/_index.md | 4 ++-- .../viewer-preferences/get-viewer-preferences/_index.md | 2 +- .../pdffileeditor/booklet-and-nup-layout/_index.md | 4 ++-- .../create-n-up-pdf-document/_index.md | 4 ++-- .../booklet-and-nup-layout/create-pdf-booklet/_index.md | 4 ++-- .../pdffileeditor/page-layout-and-margins/_index.md | 4 ++-- .../add-margins-to-pdf-pages/_index.md | 4 ++-- .../add-page-breaks-in-pdf/_index.md | 4 ++-- .../resize-pdf-page-contents/_index.md | 4 ++-- .../pdffileeditor/page-managment/_index.md | 4 ++-- .../page-managment/append-pages-to-pdf/_index.md | 4 ++-- .../page-managment/delete-pages-from-pdf/_index.md | 4 ++-- .../page-managment/extract-pages-from-pdf/_index.md | 4 ++-- .../page-managment/insert-pages-into-pdf/_index.md | 4 ++-- .../pdffileeditor/page-merging/_index.md | 4 ++-- .../page-merging/concatenate-large-number-files/_index.md | 4 ++-- .../concatenate-pdf-files-with-optimization/_index.md | 4 ++-- .../page-merging/concatenate-pdf-files/_index.md | 4 ++-- .../page-merging/concatenate-pdf-forms/_index.md | 4 ++-- .../page-merging/concatenate-two-files/_index.md | 4 ++-- .../page-merging/try-concatenate-pdf-files/_index.md | 4 ++-- .../page-merging/try-concatenate-two-files/_index.md | 4 ++-- .../pdffileeditor/splitting-pdf-documents/_index.md | 4 ++-- .../split-pdf-from-beginning/_index.md | 4 ++-- .../split-pdf-into-single-pages/_index.md | 2 +- .../splitting-pdf-documents/split-pdf-to-end/_index.md | 4 ++-- .../pdffileinfo/document-properties/_index.md | 4 ++-- .../document-properties/get-document-privileges/_index.md | 4 ++-- .../document-properties/get-pdf-version/_index.md | 4 ++-- .../pdffileinfo/page-information/_index.md | 4 ++-- .../pdffileinfo/page-information/get-page-info/_index.md | 4 ++-- .../pdffileinfo/page-information/get-page-offset/_index.md | 4 ++-- .../working-with-facades/pdffileinfo/pdf-metadata/_index.md | 4 ++-- .../pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md | 2 +- .../pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md | 4 ++-- .../pdf-metadata/save-metadata-with-xmp/_index.md | 4 ++-- .../pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md | 2 +- .../pdffilesecurity/change-password/_index.md | 2 +- .../pdffilesecurity/decrypt-pdf-file/_index.md | 2 +- .../pdffilesecurity/encrypt-pdf-file/_index.md | 4 ++-- .../pdffilesecurity/set-privileges/_index.md | 4 ++-- .../pdffilesignature/pdf-certification/_index.md | 2 +- .../pdffilesignature/pdf-signing/_index.md | 2 +- .../pdffilesignature/revision-permissions/_index.md | 2 +- .../pdffilesignature/signature-extraction/_index.md | 2 +- .../pdffilesignature/signature-information/_index.md | 2 +- .../pdffilesignature/signature-integrity-checks/_index.md | 2 +- .../pdffilesignature/signature-management/_index.md | 2 +- .../pdffilesignature/signature-verification/_index.md | 2 +- .../pdffilesignature/usage-rights-management/_index.md | 2 +- .../working-with-facades/pdffilestamp/add-footer/_index.md | 2 +- .../working-with-facades/pdffilestamp/add-header/_index.md | 2 +- .../pdffilestamp/add-page-number/_index.md | 2 +- .../working-with-facades/pdffilestamp/add-stamp/_index.md | 2 +- 180 files changed, 258 insertions(+), 258 deletions(-) diff --git a/en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md b/en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md index fc4a36ad7..e81944cfa 100644 --- a/en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md +++ b/en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-17" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: How to manipulate annotations in PDF with Python Abstract: Annotations in PDF documents enhance user interaction by allowing the addition of various elements such as notes, text highlights, shapes, and file attachments. These features improve the document's viewing experience and interactivity. The Aspose.PDF for Python library categorizes annotations into several groups- Text Annotations, Highlights Annotations, Figures Annotations, Sticky Annotations, and Extra Annotations, each serving different functions to enrich document engagement and usability. --- diff --git a/en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md b/en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md index a9ae42bfd..b149e4d51 100644 --- a/en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md +++ b/en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-21" sitemap: changefreq: "monthly" priority: 0.5 -TechArticle: true +TechArticle: true AlternativeHeadline: Work with multimedia and rich media PDF annotations in Python. Abstract: This article explains how to create and manage media annotations in PDF documents using Aspose.PDF for Python via .NET. It covers sound annotations, 3D annotations, screen annotations, rich media annotations, and techniques for listing or deleting multimedia annotations from a PDF page. --- diff --git a/en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md b/en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md index 5c86a1485..bc08c658a 100644 --- a/en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md +++ b/en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-21" sitemap: changefreq: "monthly" priority: 0.5 -TechArticle: true +TechArticle: true AlternativeHeadline: Work with geometric PDF annotations in Python. Abstract: This article explains how to create, read, and remove shape annotations in PDF documents using Aspose.PDF for Python via .NET. It covers line, square, circle, polygon, and polyline annotations, with each workflow broken into small steps and complete code examples. --- diff --git a/en/python-net/advanced-operations/artifacts/_index.md b/en/python-net/advanced-operations/artifacts/_index.md index 87c7ab5c9..37f158280 100644 --- a/en/python-net/advanced-operations/artifacts/_index.md +++ b/en/python-net/advanced-operations/artifacts/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Add backgrounds, watermarks, and Bates numbering artifacts in Python Abstract: This article explains how to work with PDF artifacts in Aspose.PDF for Python via .NET. Learn what artifacts are, why they matter for accessibility and document layout, and how to add background images, apply watermarks, add Bates numbering, and inspect artifact types in PDF files with Python. --- diff --git a/en/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md b/en/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md index 3ae865400..cb0828075 100644 --- a/en/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md +++ b/en/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Add Bates Numbering via Python Abstract: Bates numbering is a critical feature in legal, medical, and business document workflows, ensuring that each page in a set receives a unique, sequential identifier for reliable referencing. This article demonstrates how Aspose.PDF for Python via .NET simplifies the automation of Bates numbering through its flexible API. Using the BatesNArtifact class, developers can configure numbering behavior—including digit count, prefixes, suffixes, alignment, and margins—and apply it programmatically across entire documents. Multiple approaches are presented, from direct artifact application to delegate-based configuration, offering both static and dynamic control. In addition, the API supports complete removal of Bates numbers with a single method call, enabling full lifecycle management of pagination artifacts. Clear, step-by-step code examples illustrate how to add, customize, and delete Bates numbering, making this guide a practical resource for developers seeking to streamline document processing workflows. --- diff --git a/en/python-net/advanced-operations/artifacts/add-watermarks/_index.md b/en/python-net/advanced-operations/artifacts/add-watermarks/_index.md index d3e76d445..3563a5634 100644 --- a/en/python-net/advanced-operations/artifacts/add-watermarks/_index.md +++ b/en/python-net/advanced-operations/artifacts/add-watermarks/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: How to add watermark to PDF with Python Abstract: The article discusses the use of Aspose.PDF for Python via .NET to add watermarks to PDF documents through the management of artifacts. It introduces the key classes for handling artifacts - `Artifact` and `ArtifactCollection`, and describes how to access them via the `Artifacts` property of the `Page` class. The article details the properties of the `Artifact` class, including attributes such as `contents`, `form`, `image`, `text`, `rectangle`, `rotation`, and `opacity`, which enable comprehensive manipulation of artifacts within PDF files. Additionally, a practical example is provided, demonstrating how to programmatically add a watermark to the first page of a PDF using Python. The code snippet illustrates the creation and configuration of a `WatermarkArtifact`, setting its text, alignment, rotation, and opacity, before appending it to a PDF document and saving the changes. --- diff --git a/en/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md b/en/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md index dfa5c6cad..b71a48e97 100644 --- a/en/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md +++ b/en/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-21" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: How to Add, Customize, and Remove PDF Headers and Footers Using Python Abstract: Managing headers and footers is a common requirement when working with PDF documents in business, publishing, and automation workflows. This article demonstrates how to use Aspose.PDF for Python to add professional-looking headers and footers with custom styling such as font, size, color, and alignment. It also shows how to detect and remove existing pagination artifacts like headers and footers from a PDF page. With reusable functions and clear examples, developers can quickly integrate these features into document processing systems for branding, reporting, or file cleanup. --- diff --git a/en/python-net/advanced-operations/artifacts/counting-artifacts/_index.md b/en/python-net/advanced-operations/artifacts/counting-artifacts/_index.md index dac44ddb5..70cc3a5df 100644 --- a/en/python-net/advanced-operations/artifacts/counting-artifacts/_index.md +++ b/en/python-net/advanced-operations/artifacts/counting-artifacts/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Counting Artifacts in PDF using Python Abstract: Pagination artifacts such as watermarks, backgrounds, headers, and footers are commonly used in PDF documents to provide structure, branding, and identification. This example demonstrates how to inspect and count these artifacts programmatically using Aspose.PDF for Python via .NET. By filtering artifacts on a page and grouping them by subtype, developers can quickly analyze document composition and verify the presence of specific elements. The provided code illustrates how to open a PDF, extract pagination artifacts from the first page, count each subtype, and output the results, offering a practical approach to document auditing and validation. --- diff --git a/en/python-net/advanced-operations/compare-pdf-documents/_index.md b/en/python-net/advanced-operations/compare-pdf-documents/_index.md index 305cfaee6..500257555 100644 --- a/en/python-net/advanced-operations/compare-pdf-documents/_index.md +++ b/en/python-net/advanced-operations/compare-pdf-documents/_index.md @@ -1,6 +1,6 @@ --- title: Compare PDF Documents in Python -linktitle: Compare PDF +linktitle: Compare PDF type: docs weight: 130 url: /python-net/compare-pdf-documents/ @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Compare PDF pages and full documents with visual difference output in Python Abstract: This article explains how to compare PDF documents in Aspose.PDF for Python via .NET. Learn how to compare specific pages or entire PDF files with side-by-side output, and how to use graphical comparison methods to generate image-based or PDF-based difference reports. --- diff --git a/en/python-net/advanced-operations/navigation-and-interaction/links/_index.md b/en/python-net/advanced-operations/navigation-and-interaction/links/_index.md index 8ca76ee36..300f78953 100644 --- a/en/python-net/advanced-operations/navigation-and-interaction/links/_index.md +++ b/en/python-net/advanced-operations/navigation-and-interaction/links/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Create, extract, and update PDF links in Python Abstract: The Aspose.PDF for Python via .NET guide on working with links provides a comprehensive overview of how developers can programmatically manage hyperlinks and navigation elements within PDF documents using Python. It covers essential operations such as creating internal and external links, updating link destinations and appearance, and extracting existing links. --- diff --git a/en/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md b/en/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md index 6a3e472a0..557a0f0b3 100644 --- a/en/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md +++ b/en/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md @@ -9,9 +9,9 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: How to extract Links from PDF -Abstract: The Aspose.PDF for Python via .NET guide on extracting links explains how to programmatically retrieve hyperlink annotations from PDF documents using Python. The documentation includes practical code examples and highlights how this functionality can be used for tasks such as link auditing, navigation analysis, or building interactive document features. Whether you're working with single-page PDFs or processing large batches, this guide offers a clear and efficient approach to hyperlink extraction. +Abstract: The Aspose.PDF for Python via .NET guide on extracting links explains how to programmatically retrieve hyperlink annotations from PDF documents using Python. The documentation includes practical code examples and highlights how this functionality can be used for tasks such as link auditing, navigation analysis, or building interactive document features. Whether you're working with single-page PDFs or processing large batches, this guide offers a clear and efficient approach to hyperlink extraction. --- ## Extract Links from the PDF File diff --git a/en/python-net/advanced-operations/navigation-and-interaction/links/update-links/_index.md b/en/python-net/advanced-operations/navigation-and-interaction/links/update-links/_index.md index 43d066167..4a77a3331 100644 --- a/en/python-net/advanced-operations/navigation-and-interaction/links/update-links/_index.md +++ b/en/python-net/advanced-operations/navigation-and-interaction/links/update-links/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: How to update Links in PDF Abstract: The Aspose.PDF for Python via .NET guide on updating links walks developers through the process of modifying hyperlink behavior within PDF documents using Python. It explains how to change link destinations to point to specific pages, external websites, or even other PDF files. The documentation also covers how to adjust the appearance of link annotations, including text color, and provides practical code examples for each scenario. Whether you're correcting outdated URLs or enhancing navigation, this resource offers a clear and efficient approach to managing links programmatically. --- diff --git a/en/python-net/advanced-operations/securing-and-signing/_index.md b/en/python-net/advanced-operations/securing-and-signing/_index.md index 102e1da76..acee65107 100644 --- a/en/python-net/advanced-operations/securing-and-signing/_index.md +++ b/en/python-net/advanced-operations/securing-and-signing/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Sign, encrypt, decrypt, and protect PDF documents in Python Abstract: This section explains how to secure and sign PDF documents using Aspose.PDF for Python via .NET. Learn how to apply digital signatures, use smart cards and certificates, extract signature information, and manage PDF encryption, passwords, and access privileges in Python. --- diff --git a/en/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md b/en/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md index 28d18aca3..76e90c4be 100644 --- a/en/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md +++ b/en/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md @@ -9,9 +9,9 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Digitally sign PDF files with Python -Abstract: This guide explains how to digitally sign PDF documents using Aspose.PDF for Python via .NET. It details the process of applying standard and advanced digital signatures, utilizing certificates (PFX and PKCS#12), and customizing signature appearance and behavior. The documentation includes code examples that demonstrate how to sign existing PDFs, add timestamps, and verify signature validity. This enables developers to ensure document authenticity, integrity, and compliance with digital signature standards in their Python Applications. +Abstract: This guide explains how to digitally sign PDF documents using Aspose.PDF for Python via .NET. It details the process of applying standard and advanced digital signatures, utilizing certificates (PFX and PKCS#12), and customizing signature appearance and behavior. The documentation includes code examples that demonstrate how to sign existing PDFs, add timestamps, and verify signature validity. This enables developers to ensure document authenticity, integrity, and compliance with digital signature standards in their Python Applications. --- ## Sign PDF with digital signatures diff --git a/en/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md b/en/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md index 833d088a9..247a61aad 100644 --- a/en/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md +++ b/en/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Extract signature images and certificate details from PDFs in Python Abstract: This article explains how to extract image and digital signature information from PDF documents using Aspose.PDF for Python. Learn how to retrieve signature images, extract certificate data, inspect signature algorithms, and detect compromised signatures in signed PDF files. --- diff --git a/en/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md b/en/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md index 9f60d1f50..e5a375ab5 100644 --- a/en/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md +++ b/en/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md @@ -9,9 +9,9 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Set PDF permissions and manage encryption in Python -Abstract: This documentation page explains how to set document privileges, apply encryption, and decrypt PDF files using Aspose.PDF for Python. It guides developers through configuring user and owner passwords, defining access restrictions (such as printing, copying, or editing). Code examples illustrate how to protect sensitive content and manage PDF security effectively within Python applications, ensuring controlled access and data confidentiality. +Abstract: This documentation page explains how to set document privileges, apply encryption, and decrypt PDF files using Aspose.PDF for Python. It guides developers through configuring user and owner passwords, defining access restrictions (such as printing, copying, or editing). Code examples illustrate how to protect sensitive content and manage PDF security effectively within Python applications, ensuring controlled access and data confidentiality. --- Managing document security is essential when working with sensitive or business-critical content. Aspose.PDF for Python via .NET provides a robust API for programmatically applying encryption, controlling access through permissions, and decrypting protected PDF files. diff --git a/en/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md b/en/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md index 9fb8edf15..3252b243b 100644 --- a/en/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md +++ b/en/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md @@ -9,9 +9,9 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Sign PDF documents from a Smart Card with Python -Abstract: This guide explains how to digitally sign PDF documents using a smart card with Aspose.PDF for Python via .NET. It demonstrates how to access certificates stored on hardware devices (such as USB tokens or smart cards) through the Windows Certificate Store and apply them for signing PDF files. The documentation includes code examples that show how to locate the appropriate certificate, configure signature properties, and embed the digital signature into the PDF. This enables secure, hardware-backed signing in compliance with digital signature standards, suitable for high-trust enterprise and legal workflows. +Abstract: This guide explains how to digitally sign PDF documents using a smart card with Aspose.PDF for Python via .NET. It demonstrates how to access certificates stored on hardware devices (such as USB tokens or smart cards) through the Windows Certificate Store and apply them for signing PDF files. The documentation includes code examples that show how to locate the appropriate certificate, configure signature properties, and embed the digital signature into the PDF. This enables secure, hardware-backed signing in compliance with digital signature standards, suitable for high-trust enterprise and legal workflows. --- Aspose.PDF provides robust capabilities for integrating visual and cryptographic signature components, ensuring both authenticity and professional presentation in digitally signed PDF documents. diff --git a/en/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md b/en/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md index f4fa58493..75893305e 100644 --- a/en/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md +++ b/en/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Create PDF File with Python Abstract: Aspose.PDF for Python via .NET is a versatile API designed for developers to manipulate PDF files within Python applications targeting the .NET framework. It enables users to create, load, modify, and convert PDF documents effortlessly. This article provides a step-by-step guide to creating a simple PDF file using Aspose.PDF. The process involves initializing a `Document` object, adding a `Page` to the document, inserting a `TextFragment` into the page's paragraphs, and saving the file as a PDF. The included Python code snippet demonstrates these steps by creating a PDF document that contains the text "Hello World!". This API simplifies PDF handling with minimal code, enhancing productivity for developers working with PDFs in .NET environments. --- diff --git a/en/python-net/advanced-operations/working-with-documents/formatting-pdf-document/_index.md b/en/python-net/advanced-operations/working-with-documents/formatting-pdf-document/_index.md index 5ccd584e7..c454e44e5 100644 --- a/en/python-net/advanced-operations/working-with-documents/formatting-pdf-document/_index.md +++ b/en/python-net/advanced-operations/working-with-documents/formatting-pdf-document/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Formatting PDF documents using Python Abstract: The article provides a comprehensive guide on manipulating and formatting PDF documents using the Aspose.PDF library in Python. It covers various aspects of PDF customization, including setting document window and page display properties such as centering the window, reading direction, and hiding UI elements. The article explains how to retrieve and set these properties programmatically using the `Document` class. Additionally, it addresses font management, detailing how to embed Standard Type 1 fonts and other fonts into PDFs, ensuring document portability and visual consistency across systems. It also highlights techniques for setting a default font name, retrieving all fonts from a PDF, and enhancing font embedding using `FontSubsetStrategy`. Furthermore, the article elaborates on adjusting the zoom factor of PDF documents using the `GoToAction` class and configuring print dialog preset properties, including duplex printing options. Code snippets accompany each section, providing practical examples for implementing these features. --- diff --git a/en/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md b/en/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md index 50b889d7a..2eeb2aa51 100644 --- a/en/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md +++ b/en/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Guide on manipulating PDF documents using Python Abstract: This article provides a comprehensive guide on manipulating PDF documents using Python, specifically with the Aspose.PDF library. It covers several functionalities, including validating PDF documents for PDF/A-1a and PDF/A-1b compliance using the `validate` method of the `Document` class. It also details how to add, customize, and manage a Table of Contents (TOC) in PDF files, such as setting different TabLeaderTypes, hiding page numbers, and customizing page numbering with a prefix. Additionally, the article explains how to set an expiration date for a PDF document by embedding JavaScript for access restriction and how to flatten fillable forms in a PDF to make them uneditable. Each section is accompanied by code snippets demonstrating the implementation of these features using Aspose.PDF in Python. --- diff --git a/en/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md b/en/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md index 85d51c0bc..fc19001fd 100644 --- a/en/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md +++ b/en/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Combine PDF pages using Python Abstract: This article addresses the common need to merge multiple PDF files into a single document, a process valuable for organizing and optimizing storage and sharing of PDF content. It explores the use of Aspose.PDF for Python via .NET to efficiently combine PDF files, acknowledging that merging PDFs in Python can be challenging without third-party libraries. The article provides a step-by-step guide to concatenating PDF files - creating a new document, merging the files, and saving the merged document. A code snippet demonstrates the implementation using Aspose.PDF, highlighting the library's capability to streamline the merging process. Additionally, it introduces the Aspose.PDF Merger, an online tool for merging PDFs, enabling users to explore the functionality in a web-based environment. --- diff --git a/en/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md b/en/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md index be019f5a7..d230f3506 100644 --- a/en/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md +++ b/en/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Compress PDF pages using Python Abstract: This article provides a comprehensive guide on optimizing PDF files to reduce their size and enhance performance across various platforms, such as web pages, emails, and storage systems. The optimization techniques include reducing image sizes, removing unused resources, and unembedding fonts. Specific methods for optimizing PDFs for the web and reducing overall file size are discussed, utilizing the `Optimize` and `OptimizeResources` methods in Aspose.PDF for Python. Customization of optimization strategies is possible via `OptimizationOptions`, allowing for targeted actions like compressing images, removing unused objects and streams, linking duplicate streams, and unembedding fonts. Additional strategies cover flattening annotations, removing form fields, and converting PDF files from RGB to grayscale to further decrease size. The article also highlights the use of FlateDecode compression for image optimization, ensuring effective PDF file management while maintaining quality and functionality. --- diff --git a/en/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md b/en/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md index 7ffe28108..6efd2f83a 100644 --- a/en/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md +++ b/en/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: How to rotate Pages in PDF with Python Abstract: This article provides a guide on how to programmatically update or change the page orientation of pages in an existing PDF file using Python. Utilizing Aspose.PDF for Python via .NET, users can easily switch between landscape and portrait orientations by adjusting the page's MediaBox properties. The article includes a Python code snippet demonstrating how to iterate through pages in a PDF document, modify their MediaBox dimensions and positions, and adjust the CropBox if necessary. Additionally, it explains how to set the rotation angle of pages using the 'rotate' method to achieve the desired orientation. The process concludes with saving the updated PDF file. --- diff --git a/en/python-net/advanced-operations/zugferd/_index.md b/en/python-net/advanced-operations/zugferd/_index.md index 95e1b8d55..54a6c39c6 100644 --- a/en/python-net/advanced-operations/zugferd/_index.md +++ b/en/python-net/advanced-operations/zugferd/_index.md @@ -9,7 +9,7 @@ lastmod: "2025-02-27" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: The ZUGFeRD invoices with Aspose.PDF in Python Abstract: ZUGFeRD is an electronic invoicing standard predominantly used in Germany and other EU countries, designed to streamline the B2B invoicing process through a fully digital format. It facilitates the efficient creation, transmission, and processing of electronic invoices, promoting cost savings and operational efficiency. The ZUGFeRD format uniquely combines a human-readable PDF with a machine-readable XML, ensuring interoperability across different software platforms. This standard meets legal requirements for archiving and tax compliance and aligns with the European standard EN 16931. The latest version, ZUGFeRD 2.0, provides various profiles to cater to diverse business needs, offering benefits such as faster processing, reduced errors, improved cash flow, and a lower environmental impact. The article also references resources for implementing ZUGFeRD-compliant PDFs in Python, Java, and .NET. --- diff --git a/en/python-net/advanced-operations/zugferd/attach-zugferd/_index.md b/en/python-net/advanced-operations/zugferd/attach-zugferd/_index.md index d0bec451e..951750c5b 100644 --- a/en/python-net/advanced-operations/zugferd/attach-zugferd/_index.md +++ b/en/python-net/advanced-operations/zugferd/attach-zugferd/_index.md @@ -9,8 +9,8 @@ lastmod: "2025-02-27" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true -AlternativeHeadline: How to attach ZUGFeRD to a PDF document +TechArticle: true +AlternativeHeadline: How to attach ZUGFeRD to a PDF document Abstract: The article provides a step-by-step guide on how to attach ZUGFeRD (a format for electronic invoices) to a PDF document using the Aspose.PDF library. The procedure begins with importing the necessary library and setting up the directory paths for input and output files. It involves loading the target PDF file into a Document object, and creating a FileSpecification object for the XML invoice metadata file. Key properties like `mime_type` and `af_relationship` are set to ensure proper integration of the metadata. The XML file is then added to the PDF's embedded files collection, effectively attaching it as metadata. Subsequently, the PDF document is converted to the PDF/A-3A format, which is suitable for archiving electronic documents, before saving the final PDF with the embedded ZUGFeRD. The article concludes with a Python code snippet that demonstrates the implementation of these steps, showcasing the integration of ZUGFeRD with a PDF for enhanced document management. --- diff --git a/en/python-net/basic-operations/_index.md b/en/python-net/basic-operations/_index.md index 6d4392909..8b073646a 100644 --- a/en/python-net/basic-operations/_index.md +++ b/en/python-net/basic-operations/_index.md @@ -9,7 +9,7 @@ description: Basic operations section describes the possibilities of opening and sitemap: changefreq: "monthly" priority: 0.5 -TechArticle: true +TechArticle: true AlternativeHeadline: Overview of basic operations with PDF using Python Abstract: The article provides an overview of basic operations for handling PDF documents using Aspose.PDF for Python. It covers three fundamental tasks - creating, opening, and saving PDF files within a Python environment. The "Create PDF Document" section details the process of generating a PDF file using Python. The "Open PDF Document" section explores multiple methods for accessing PDF documents in a Python application. Lastly, the "Save PDF Document" section explains various techniques for saving a PDF document. Each section links to more detailed articles that guide users through these essential PDF operations. --- diff --git a/en/python-net/basic-operations/create/_index.md b/en/python-net/basic-operations/create/_index.md index 0ec4266c4..f5779049f 100644 --- a/en/python-net/basic-operations/create/_index.md +++ b/en/python-net/basic-operations/create/_index.md @@ -5,7 +5,7 @@ type: docs weight: 10 url: /python-net/create-document/ description: This page describes how to create PDF document from scratch with Aspose.PDF for Python via .NET library. -TechArticle: true +TechArticle: true AlternativeHeadline: Generating PDF files with Aspose.PDF for Python Abstract: In software development, generating PDF files programmatically is a common requirement, particularly for creating reports and other documents. Writing custom code for this task can be inefficient and time-consuming. Instead, developers can utilize **Aspose.PDF for Python via .NET**, a robust solution for creating PDF files using Python. The process involves creating a `Document` object, adding a `Page` object to the document's `Pages` collection, inserting a `TextFragment` into the page's `paragraphs` collection, and then saving the document. A sample Python code snippet demonstrates these steps, showcasing the ease with which PDF files can be generated using Aspose.PDF. --- diff --git a/en/python-net/basic-operations/merge-pdf/_index.md b/en/python-net/basic-operations/merge-pdf/_index.md index 20447354b..8218c69a3 100644 --- a/en/python-net/basic-operations/merge-pdf/_index.md +++ b/en/python-net/basic-operations/merge-pdf/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Combine PDF pages using Python Abstract: This article addresses the common need to merge multiple PDF files into a single document, a process valuable for organizing and optimizing storage and sharing of PDF content. It explores the use of Aspose.PDF for Python via .NET to efficiently combine PDF files, acknowledging that merging PDFs in Python can be challenging without third-party libraries. The article provides a step-by-step guide to concatenating PDF files - creating a new document, merging the files, and saving the merged document. A code snippet demonstrates the implementation using Aspose.PDF, highlighting the library's capability to streamline the merging process. Additionally, it introduces the Aspose.PDF Merger, an online tool for merging PDFs, enabling users to explore the functionality in a web-based environment. --- diff --git a/en/python-net/basic-operations/saving/_index.md b/en/python-net/basic-operations/saving/_index.md index 5ad80dd7a..74dd4c5aa 100644 --- a/en/python-net/basic-operations/saving/_index.md +++ b/en/python-net/basic-operations/saving/_index.md @@ -9,7 +9,7 @@ lastmod: "2025-02-27" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Saving PDF documents using the Aspose.PDF library in Python Abstract: The article provides guidance on saving PDF documents using the Aspose.PDF library in Python. It outlines three primary methods for saving PDFs - to the file system, to a stream, and in specific formats like PDF/A or PDF/X. The `save()` method of the `Document` class is central to these operations. To save a PDF to the file system, a document can be created or manipulated, such as adding a new page, and then saved directly to a path. For saving to a stream, the `Save` method's overloads allow writing a document to a stream object. Additionally, the article explains how to save documents in the PDF/A or PDF/X formats, which are standards for long-term archiving and graphics exchange, respectively. This process requires preparing the document with the `convert` method before saving it. The provided Python code snippets demonstrate each approach, illustrating the practical application of these methods. --- diff --git a/en/python-net/converting/_index.md b/en/python-net/converting/_index.md index 864c35c81..369fdf28e 100644 --- a/en/python-net/converting/_index.md +++ b/en/python-net/converting/_index.md @@ -9,7 +9,7 @@ description: Learn how to convert PDF documents to Word, Excel, PowerPoint, HTML sitemap: changefreq: "monthly" priority: 0.8 -TechArticle: true +TechArticle: true AlternativeHeadline: How to Convert PDF documents using Python Abstract: This article introduces **Aspose.PDF for Python**, a robust solution for converting PDF documents to various formats using Python. Python, a versatile object-oriented programming language, is extensively employed for developing software prototypes and data processing applications. The article emphasizes the capability of Aspose.PDF to convert PDFs for editing purposes, encompassing a wide array of documents including text, images, hyperlinks, and more. The library supports conversion to and from popular formats like Microsoft Word, Excel, and PowerPoint, as well as HTML and various image formats. It also enables conversion to specialized formats such as EPUB, Markdown, and PDF/A for long-term archiving. The article provides links to detailed guides on performing these conversions programmatically with Python, featuring code snippets for clarity. Additionally, users can explore conversion options online using the Aspose PDF Apps. This comprehensive overview demonstrates the versatility and ease of use of Aspose.PDF for handling document conversion tasks in Python. --- diff --git a/en/python-net/converting/convert-html-to-pdf/_index.md b/en/python-net/converting/convert-html-to-pdf/_index.md index 606b96df2..8a4fe2eac 100644 --- a/en/python-net/converting/convert-html-to-pdf/_index.md +++ b/en/python-net/converting/convert-html-to-pdf/_index.md @@ -9,7 +9,7 @@ description: Learn how to convert HTML and MHTML to PDF in Python with Aspose.PD sitemap: changefreq: "monthly" priority: 0.8 -TechArticle: true +TechArticle: true AlternativeHeadline: How to convert HTML to PDF in Python with Aspose.PDF Abstract: This article explains how to convert HTML and MHTML files to PDF using Aspose.PDF for Python via .NET. It covers the basic HTML-to-PDF workflow and shows how to control rendering with media types, CSS page rule priority, embedded fonts, single-page output, and logical structure generation for accessible tagged PDFs. --- diff --git a/en/python-net/converting/convert-images-format-to-pdf/_index.md b/en/python-net/converting/convert-images-format-to-pdf/_index.md index 30666fe1f..79e38cff0 100644 --- a/en/python-net/converting/convert-images-format-to-pdf/_index.md +++ b/en/python-net/converting/convert-images-format-to-pdf/_index.md @@ -9,9 +9,9 @@ description: Learn how to convert BMP, CGM, DICOM, PNG, TIFF, EMF, SVG, and othe sitemap: changefreq: "monthly" priority: 0.5 -TechArticle: true +TechArticle: true AlternativeHeadline: How to Convert Images to PDF in Python -Abstract: This article provides a comprehensive guide on converting various image formats to PDF using Python, specifically leveraging the Aspose.PDF library for Python via .NET. The article covers a range of image formats including BMP, CGM, DICOM, EMF, GIF, PNG, SVG, and TIFF. Each section details the steps required to perform the conversion, providing code snippets to illustrate the process. For example, converting BMP to PDF involves creating a new PDF document, defining image placement, inserting the image, and saving the document. Similarly, for formats like CGM, DICOM, and others, specific load options and processing steps are outlined. The article also highlights the advantages of using Aspose.PDF for such tasks, such as its support for different encoding methods and the ability to process both single-frame and multi-frame images. +Abstract: This article provides a comprehensive guide on converting various image formats to PDF using Python, specifically leveraging the Aspose.PDF library for Python via .NET. The article covers a range of image formats including BMP, CGM, DICOM, EMF, GIF, PNG, SVG, and TIFF. Each section details the steps required to perform the conversion, providing code snippets to illustrate the process. For example, converting BMP to PDF involves creating a new PDF document, defining image placement, inserting the image, and saving the document. Similarly, for formats like CGM, DICOM, and others, specific load options and processing steps are outlined. The article also highlights the advantages of using Aspose.PDF for such tasks, such as its support for different encoding methods and the ability to process both single-frame and multi-frame images. --- ## Related conversions diff --git a/en/python-net/converting/convert-other-files-to-pdf/_index.md b/en/python-net/converting/convert-other-files-to-pdf/_index.md index ee18b97dc..14cb62ce3 100644 --- a/en/python-net/converting/convert-other-files-to-pdf/_index.md +++ b/en/python-net/converting/convert-other-files-to-pdf/_index.md @@ -9,7 +9,7 @@ description: Learn how to convert EPUB, Markdown, PCL, XPS, PostScript, XML, and sitemap: changefreq: "monthly" priority: 0.5 -TechArticle: true +TechArticle: true AlternativeHeadline: How to Convert other file formats to PDF in Python Abstract: This article provides a comprehensive guide on converting various file formats to PDF using Python, leveraging the capabilities of Aspose.PDF for Python via .NET. The document outlines conversion processes for several formats, including EPUB, Markdown, PCL, Text, XPS, PostScript, XML, XSL-FO, and LaTeX/TeX. Each section provides specific code snippets and instructions for implementing these conversions. The article emphasizes the utility of Aspose.PDF's features, such as load options tailored for each file type, to ensure accurate and efficient conversion. Additionally, it highlights the availability of online conversion applications for users to explore the functionality firsthand. The guide serves as a practical resource for developers seeking to integrate PDF conversion capabilities into their Python applications. --- diff --git a/en/python-net/converting/convert-pdf-to-excel/_index.md b/en/python-net/converting/convert-pdf-to-excel/_index.md index 6bbc7d2cd..2f9de2c7a 100644 --- a/en/python-net/converting/convert-pdf-to-excel/_index.md +++ b/en/python-net/converting/convert-pdf-to-excel/_index.md @@ -9,7 +9,7 @@ description: Learn how to convert PDF files to Excel in Python with Aspose.PDF f sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: How to Convert PDF to Excel in Python Abstract: This article provides a comprehensive guide on converting PDF files to various Excel formats using Python, specifically with the Aspose.PDF for Python via .NET library. It details the conversion processes for XLS, XLSX, CSV, and ODS formats. The document explains the steps needed to convert PDF to XLS and XLSX, highlighting the creation of Document and ExcelSaveOptions instances, and the use of the Document.Save() method to specify output formats. The article also discusses features such as controlling the insertion of blank columns and minimizing worksheet numbers during conversion. Additionally, it provides examples of converting PDFs to single Excel worksheets and other formats like CSV and ODS, emphasizing the flexibility and functionality of Aspose.PDF. An online tool for PDF to XLSX conversion is also mentioned, allowing users to explore the conversion quality. The article concludes with a list of related topics and code snippets to further aid in understanding and implementing these conversions programmatically. --- diff --git a/en/python-net/converting/convert-pdf-to-images-format/_index.md b/en/python-net/converting/convert-pdf-to-images-format/_index.md index 272fc3694..5efc31c89 100644 --- a/en/python-net/converting/convert-pdf-to-images-format/_index.md +++ b/en/python-net/converting/convert-pdf-to-images-format/_index.md @@ -9,7 +9,7 @@ description: Explore how to convert PDF pages into images such as PNG, JPEG, or sitemap: changefreq: "monthly" priority: 0.5 -TechArticle: true +TechArticle: true AlternativeHeadline: How to Convert PDF to Image Formats in Python Abstract: This article provides a comprehensive guide on converting PDF files into various image formats using Python, specifically leveraging the Aspose.PDF for Python library. The document outlines methods for converting PDFs to image formats including TIFF, BMP, EMF, JPG, PNG, GIF, and SVG. Two primary conversion approaches are discussed - using the Device approach and SaveOption. The Device approach involves utilizing classes like `DocumentDevice` and `ImageDevice` for whole document or page-specific conversions. Detailed steps and Python code examples are provided for converting PDF pages to different formats such as TIFF using `TiffDevice`, and BMP, EMF, JPEG, PNG, and GIF using respective device classes (`BmpDevice`, `EmfDevice`, `JpegDevice`, `PngDevice`, `GifDevice`). For SVG conversion, the `SvgSaveOptions` class is introduced. The article also highlights online tools for trying these conversions. --- diff --git a/en/python-net/converting/convert-pdf-to-other-files/_index.md b/en/python-net/converting/convert-pdf-to-other-files/_index.md index 2f6a64f49..892ce9127 100644 --- a/en/python-net/converting/convert-pdf-to-other-files/_index.md +++ b/en/python-net/converting/convert-pdf-to-other-files/_index.md @@ -1,6 +1,6 @@ --- title: Convert PDF to EPUB, Text, XPS, and More in Python -linktitle: Convert PDF to other formats +linktitle: Convert PDF to other formats type: docs weight: 90 url: /python-net/convert-pdf-to-other-files/ @@ -9,7 +9,7 @@ description: Learn how to convert PDF files to EPUB, LaTeX, Markdown, text, XPS, sitemap: changefreq: "monthly" priority: 0.8 -TechArticle: true +TechArticle: true AlternativeHeadline: How to Convert PDF to other formats in Python Abstract: The article provides a comprehensive guide on converting PDF files into various formats using Aspose.PDF for Python. It covers the conversion of PDFs into EPUB, LaTeX/TeX, Text, XPS, and XML formats. Each section starts with an invitation to try online applications provided by Aspose for converting PDFs to the respective formats, highlighting the ease of use and quality of these tools. --- diff --git a/en/python-net/converting/convert-pdf-to-pdfx/_index.md b/en/python-net/converting/convert-pdf-to-pdfx/_index.md index 511f1b576..1729053b7 100644 --- a/en/python-net/converting/convert-pdf-to-pdfx/_index.md +++ b/en/python-net/converting/convert-pdf-to-pdfx/_index.md @@ -9,7 +9,7 @@ description: Learn how to convert PDF files to PDF/A, PDF/E, and PDF/X in Python sitemap: changefreq: "monthly" priority: 0.8 -TechArticle: true +TechArticle: true AlternativeHeadline: How to convert PDF to PDF/x formats Abstract: The article provides a comprehensive guide on converting PDF to PDF/A, PDF/E, and PDF/X formats using Aspose.PDF for Python. --- diff --git a/en/python-net/converting/convert-pdf-to-powerpoint/_index.md b/en/python-net/converting/convert-pdf-to-powerpoint/_index.md index 77ed1576a..fc18c19ed 100644 --- a/en/python-net/converting/convert-pdf-to-powerpoint/_index.md +++ b/en/python-net/converting/convert-pdf-to-powerpoint/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-14" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: How to Convert PDF to PowerPoint in Python Abstract: This article provides a comprehensive guide on converting PDF files into PowerPoint presentations using Python, specifically focusing on the PPTX format. It introduces the use of Aspose.PDF for Python via .NET, which facilitates the conversion process by allowing PDF pages to be transformed into individual slides in a PPTX file. The article outlines the necessary steps for conversion, including creating instances of the Document and PptxSaveOptions classes and utilizing the Save method. Additionally, it highlights a feature to convert PDFs to PPTX with slides as images by setting a specific property in the PptxSaveOptions. Code snippets are provided to illustrate the conversion process. The article also references an online application for testing the PDF to PPTX conversion feature, offering users a hands-on experience. Furthermore, it lists various related topics and functionalities available within this context, emphasizing the versatility and programmatic approach to handling PDF to PowerPoint conversions using Python. --- diff --git a/en/python-net/converting/convert-pdf-to-word/_index.md b/en/python-net/converting/convert-pdf-to-word/_index.md index b59518558..5ab18850d 100644 --- a/en/python-net/converting/convert-pdf-to-word/_index.md +++ b/en/python-net/converting/convert-pdf-to-word/_index.md @@ -9,7 +9,7 @@ description: Learn how to convert PDF files to DOC and DOCX in Python with Aspos sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: How to Convert PDF to Word in Python Abstract: This article provides a comprehensive guide on converting PDF files to Microsoft Word formats (DOC and DOCX) using Python, specifically utilizing the Aspose.PDF library. It outlines the advantages of converting PDFs to editable Word documents, enabling easier content manipulation such as text, tables, and images. The article details the process of converting PDF to DOC (Word 97-2003 format) and DOCX, with code snippets demonstrating these conversions through Python. The process involves creating a `Document` object from the PDF and saving it in the desired format using the `save()` method and the `SaveFormat` enumeration. Additionally, it introduces the `DocSaveOptions` class, which allows further customization of the conversion process, such as specifying recognition modes. The article also highlights online applications provided by Aspose.PDF for testing the conversion quality and functionality. The content includes a structured overview and links to corresponding sections for each format. --- diff --git a/en/python-net/converting/convert-pdfx-to-pdf/_index.md b/en/python-net/converting/convert-pdfx-to-pdf/_index.md index d65c4b718..2bebae5ff 100644 --- a/en/python-net/converting/convert-pdfx-to-pdf/_index.md +++ b/en/python-net/converting/convert-pdfx-to-pdf/_index.md @@ -9,7 +9,7 @@ description: Learn how to remove PDF/A and PDF/UA compliance from PDF files in P sitemap: changefreq: "monthly" priority: 0.8 -TechArticle: true +TechArticle: true AlternativeHeadline: How to convert PDF/A and PDF/UA to standard PDF in Python Abstract: This article explains how to remove PDF/A and PDF/UA compliance from standards-based PDF documents using Aspose.PDF for Python via .NET. It covers scenarios where you may need a standard PDF instead of an archival or accessibility-constrained file, and shows how to save the result after removing compliance metadata and restrictions. --- diff --git a/en/python-net/faq/_index.md b/en/python-net/faq/_index.md index 12b979592..42ee91563 100644 --- a/en/python-net/faq/_index.md +++ b/en/python-net/faq/_index.md @@ -1,5 +1,5 @@ --- -title: FAQ +title: FAQ linktitle: FAQ type: docs weight: 140 diff --git a/en/python-net/get-started/hello-world-example/_index.md b/en/python-net/get-started/hello-world-example/_index.md index ac7544d4c..5f586ac20 100644 --- a/en/python-net/get-started/hello-world-example/_index.md +++ b/en/python-net/get-started/hello-world-example/_index.md @@ -9,7 +9,7 @@ lastmod: "2025-02-27" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Hello World example via Python Abstract: This article provides a Hello World example using the Aspose.PDF for Python via .NET library to create a PDF document. The example demonstrates the basic steps of using the Aspose.PDF API by generating a PDF with the text "Hello World!". The process involves instantiating a `Document` object, adding a `Page`, creating a `TextFragment` object, setting text properties such as font size and color, and using a `TextBuilder` to add the text to the page. The resultant PDF is then saved as "HelloWorld_out.pdf". The article includes a complete Python code snippet illustrating these steps, serving as an introductory guide to the library's usage. --- diff --git a/en/python-net/overview/licensing/_index.md b/en/python-net/overview/licensing/_index.md index 5f7842854..beb831c5f 100644 --- a/en/python-net/overview/licensing/_index.md +++ b/en/python-net/overview/licensing/_index.md @@ -9,7 +9,7 @@ lastmod: "2025-02-21" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Licensing of Aspose.PDF for Python Abstract: The article discusses the limitations and licensing options for Aspose.PDF for Python. It highlights that the evaluation version allows full functionality testing but adds a watermark to generated PDFs, stating "Evaluation Only" along with copyright information. For users wishing to test without these limitations, a 30-day Temporary License is available. The article further explains how to implement a classic license by loading it from a file or stream, recommending placing the license file in the same directory as the Aspose.PDF.dll file and setting the license using the `Aspose.Pdf.License` class. Code snippets are provided to illustrate the licensing process. --- diff --git a/en/python-net/parsing/_index.md b/en/python-net/parsing/_index.md index ada272e0e..f06d36e42 100644 --- a/en/python-net/parsing/_index.md +++ b/en/python-net/parsing/_index.md @@ -9,7 +9,7 @@ lastmod: "2025-02-05" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Parse PDF files with Aspose.PDF for Python Abstract: The article Parse PDF delves into the various methodologies for extracting different types of information from PDF files. It highlights several key operations and guides. --- diff --git a/en/python-net/whatsnew/_index.md b/en/python-net/whatsnew/_index.md index 0e31b67a0..2cf1b0eb2 100644 --- a/en/python-net/whatsnew/_index.md +++ b/en/python-net/whatsnew/_index.md @@ -9,7 +9,7 @@ sitemap: changefreq: "monthly" priority: 0.8 lastmod: "2025-02-24" -TechArticle: false +TechArticle: false --- ## What's new in Aspose.PDF 26.3 diff --git a/en/python-net/working-with-facades/form/button-fields-and-images/_index.md b/en/python-net/working-with-facades/form/button-fields-and-images/_index.md index bb43748d3..ab8f13989 100644 --- a/en/python-net/working-with-facades/form/button-fields-and-images/_index.md +++ b/en/python-net/working-with-facades/form/button-fields-and-images/_index.md @@ -5,7 +5,7 @@ weight: 40 url: /python-net/button-fields-and-images/ description: This example demonstrates how to manage button fields in a PDF form using the Aspose.PDF Facades API. lastmod: "2026-02-19" -TechArticle: true +TechArticle: true AlternativeHeadline: Adding Image Appearance to Button Fields & Reading Submit Flags Abstract: PDF forms often include interactive buttons that either trigger JavaScript actions or submit the form data. You can enhance button fields visually by adding images as their appearance and programmatically inspect their submission behavior. --- diff --git a/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md b/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md index 903292308..f636bba32 100644 --- a/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md +++ b/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Add and Manage PDF Form Field Scripts and Submit Actions in Python -Abstract: Learn how to programmatically add, modify, or remove JavaScript actions for PDF form fields, and configure submit URLs using Aspose.PDF for Python. This guide explains how to attach scripts to fields, update existing scripts, remove field actions, and set URLs for form submission, enabling dynamic and interactive PDF forms. +Abstract: Learn how to programmatically add, modify, or remove JavaScript actions for PDF form fields, and configure submit URLs using Aspose.PDF for Python. This guide explains how to attach scripts to fields, update existing scripts, remove field actions, and set URLs for form submission, enabling dynamic and interactive PDF forms. --- - [Add Field Script](/pdf/python-net/add-field-script/) diff --git a/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md b/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md index 3c71f3aa2..2b22e7a90 100644 --- a/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md +++ b/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md @@ -3,14 +3,14 @@ title: Add Field Script type: docs weight: 10 url: /python-net/add-field-script/ -description: Interactive PDF forms can include JavaScript to automate actions when users interact with form fields. Using Aspose.PDF for Python, developers can easily attach scripts to form elements such as buttons or text fields. +description: Interactive PDF forms can include JavaScript to automate actions when users interact with form fields. Using Aspose.PDF for Python, developers can easily attach scripts to form elements such as buttons or text fields. lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Add JavaScript Actions to PDF Form Fields Using Python -Abstract: This article explains how to open a PDF form, assign JavaScript code to a specific form field, append additional script actions, and save the updated document. The example uses the FormEditor class from the Aspose.PDF Facades API to manipulate form behavior programmatically. +Abstract: This article explains how to open a PDF form, assign JavaScript code to a specific form field, append additional script actions, and save the updated document. The example uses the FormEditor class from the Aspose.PDF Facades API to manipulate form behavior programmatically. --- ## Add JavaScript Actions to PDF Form Fields Using Python diff --git a/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md b/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md index 18682d45d..bd6fca122 100644 --- a/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md +++ b/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Remove JavaScript Actions from PDF Form Fields Using Python Abstract: Using Aspose.PDF for Python, developers can programmatically remove JavaScript actions attached to form fields. This article explains how to open an existing PDF form, remove the script associated with a specific field using the FormEditor class, verify the operation, and save the modified document. --- diff --git a/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md b/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md index e3976ba63..b982dc254 100644 --- a/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md +++ b/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Set JavaScript Actions for PDF Form Fields Using Python -Abstract: This article explains how to open a PDF document, assign JavaScript code to a form field, update the script using the FormEditor class, and save the modified file. The example demonstrates how existing scripts can be overridden to modify the behavior of form fields. +Abstract: This article explains how to open a PDF document, assign JavaScript code to a form field, update the script using the FormEditor class, and save the modified file. The example demonstrates how existing scripts can be overridden to modify the behavior of form fields. --- Interactive PDF forms often rely on JavaScript to perform tasks such as displaying alerts, validating input, or triggering dynamic form behavior. With Aspose.PDF for Python, developers can programmatically manage these scripts. diff --git a/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md b/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md index 78e661f86..3b901485e 100644 --- a/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md +++ b/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Set Submit Flag for a PDF Form Button Using Aspose.PDF for Python -Abstract: PDF forms can be configured to submit form data to a server or endpoint in different formats. By setting a submit flag on a button field, developers can define how the data is sent. This tutorial demonstrates how to use the FormEditor class to set a submit flag for an existing submit button in a PDF document and save the updated file. +Abstract: PDF forms can be configured to submit form data to a server or endpoint in different formats. By setting a submit flag on a button field, developers can define how the data is sent. This tutorial demonstrates how to use the FormEditor class to set a submit flag for an existing submit button in a PDF document and save the updated file. --- PDF forms often include Submit Buttons to send user input to a server. The submit flag determines the data format sent (e.g., XFDF, FDF, HTML). diff --git a/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md b/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md index d1adfcfa4..9cc53ff01 100644 --- a/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md +++ b/en/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Set a Submit URL for a PDF Form Button Using Python -Abstract: This article explains how to open an existing PDF form, define a submission URL for a button field using the FormEditor class, verify that the operation succeeds, and save the updated PDF document. +Abstract: This article explains how to open an existing PDF form, define a submission URL for a button field using the FormEditor class, verify that the operation succeeds, and save the updated PDF document. --- PDF forms can be designed to submit their data to a web server when a user clicks a submit button. Using Aspose.PDF for Python, developers can programmatically configure a submit action for form fields. diff --git a/en/python-net/working-with-facades/formeditor/creating-form-field/_index.md b/en/python-net/working-with-facades/formeditor/creating-form-field/_index.md index f101cca05..c543d8929 100644 --- a/en/python-net/working-with-facades/formeditor/creating-form-field/_index.md +++ b/en/python-net/working-with-facades/formeditor/creating-form-field/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Create PDF Form Fields in Python Abstract: PDF forms enable users to enter or select data directly within a document. Using Aspose.PDF, developers can programmatically create a variety of form fields - CheckBox for boolean selections, ComboBox for drop-down lists, ListBox for multi-selection lists, RadioButton for exclusive options, TextBox for textual input, and SubmitButton for sending form data. This unified approach simplifies the creation of interactive PDFs, ensuring accurate placement, consistent styling, and compatibility with automated processing and user input handling. --- diff --git a/en/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md b/en/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md index 58925fec1..cdbd95f2e 100644 --- a/en/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md +++ b/en/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Create a Checkbox Field in a PDF Using Aspose.PDF for Python Abstract: Interactive form fields allow users to fill out and interact with PDF documents digitally. In this tutorial, you will learn how to add a checkbox field to a PDF using the Aspose.PDF Python API. The example shows how to bind an existing PDF document, create a checkbox form field at specified coordinates, and save the modified file. --- diff --git a/en/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md b/en/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md index b63b8131e..26a4ae6a5 100644 --- a/en/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md +++ b/en/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Create a ComboBox Field in a PDF Using Aspose.PDF for Python Abstract: Interactive form fields make PDFs more dynamic and user-friendly. A ComboBox field allows users to select an option from a predefined drop-down list. In this tutorial, you will learn how to create a ComboBox in a PDF using the FormEditor class in Aspose.PDF for Python, populate it with options, and save the modified document. --- diff --git a/en/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md b/en/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md index 2e4891b22..e8354a748 100644 --- a/en/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md +++ b/en/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Create a ListBox Field in a PDF Using Aspose.PDF for Python Abstract: PDF forms allow users to interact with documents by selecting options, entering data, and submitting information digitally. A ListBox field lets users choose one or multiple values from a visible list of options. In this tutorial, you will learn how to create a ListBox field in a PDF using the FormEditor class in Aspose.PDF for Python and populate it with predefined items. --- diff --git a/en/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md b/en/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md index da99eeb0a..0329aea63 100644 --- a/en/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md +++ b/en/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Create a Radio Button Field in a PDF Using Aspose.PDF for Python Abstract: Radio buttons are commonly used in PDF forms to allow users to select one option from a predefined group of choices. In this tutorial, you will learn how to create a radio button field in a PDF using the FormEditor class in Aspose.PDF for Python. The example shows how to define radio button items, set a default selection, and save the updated document. --- diff --git a/en/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md b/en/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md index 532e33052..149c03ead 100644 --- a/en/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md +++ b/en/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Create a Submit Button in a PDF Using Aspose.PDF for Python Abstract: Submit buttons in PDF forms allow users to send form data directly to a server or endpoint. In this guide, you will learn how to add a Submit Button field to a PDF using the FormEditor class in Aspose.PDF for Python. The example shows how to configure the button’s name, label, target URL, and position, then save the updated PDF document. --- diff --git a/en/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md b/en/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md index f25d2a603..0ea6c50ea 100644 --- a/en/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md +++ b/en/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Create TextBox Fields in a PDF Using Aspose.PDF for Python Abstract: TextBox fields in PDF forms allow users to enter and edit text, making documents interactive and user-friendly. In this tutorial, you will learn how to create TextBox form fields in a PDF using the FormEditor class in Aspose.PDF for Python. The example demonstrates adding multiple fields, specifying default values, and saving the modified PDF. --- diff --git a/en/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md b/en/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md index fb8ee3c8c..b77d9d703 100644 --- a/en/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md +++ b/en/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Customize PDF Form Field Appearance in Python - Alignment, Colors, Limits, and Attributes -Abstract: Learn how to customize the appearance and behavior of PDF form fields using Aspose.PDF for Python. This guide covers decorating fields with colors and borders, setting horizontal and vertical alignment, controlling visibility, adjusting field attributes, setting comb numbers and character limits, and retrieving field appearance information. These techniques help developers create visually consistent and user-friendly PDF forms. +Abstract: Learn how to customize the appearance and behavior of PDF form fields using Aspose.PDF for Python. This guide covers decorating fields with colors and borders, setting horizontal and vertical alignment, controlling visibility, adjusting field attributes, setting comb numbers and character limits, and retrieving field appearance information. These techniques help developers create visually consistent and user-friendly PDF forms. --- - [Decorate Field](/pdf/python-net/decorate-field/) diff --git a/en/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md b/en/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md index c995bf792..42f883709 100644 --- a/en/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md +++ b/en/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Decorate PDF Form Fields with Custom Colors and Alignment Using Python -Abstract: This article explains how to open a PDF document, configure styling options using the FormFieldFacade class, apply those settings to a form field, and save the updated PDF. The example demonstrates how to decorate a field named "First Name" with custom colors and centered text alignment. +Abstract: This article explains how to open a PDF document, configure styling options using the FormFieldFacade class, apply those settings to a form field, and save the updated PDF. The example demonstrates how to decorate a field named "First Name" with custom colors and centered text alignment. --- PDF forms often require visual customization to improve usability and create a consistent design. With Aspose.PDF for Python, developers can programmatically decorate form fields by setting properties such as colors, borders, and text alignment. diff --git a/en/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md b/en/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md index 301dabcfe..064def58b 100644 --- a/en/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md +++ b/en/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Retrieve PDF Form Field Appearance Using Python -Abstract: This example demonstrates how to retrieve the visual appearance properties of a form field in a PDF document using Aspose.PDF for Python. The code opens an existing PDF, accesses a specific form field, and prints its appearance details, including background color, text color, border color, and alignment. +Abstract: This example demonstrates how to retrieve the visual appearance properties of a form field in a PDF document using Aspose.PDF for Python. The code opens an existing PDF, accesses a specific form field, and prints its appearance details, including background color, text color, border color, and alignment. --- Form fields in PDF documents have visual properties such as background color, text color, border color, and alignment. With Aspose.PDF for Python, developers can programmatically inspect these appearance settings using the [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) class. diff --git a/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md b/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md index d47712520..5c07d5a8e 100644 --- a/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md +++ b/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Set Vertical Alignment for PDF Form Fields Using Python -Abstract: This article explains how to open a PDF, set vertical alignment for a field using the FormEditor class, and save the updated PDF. The example sets the vertical alignment of a field named "First Name" to the bottom of the field area. +Abstract: This article explains how to open a PDF, set vertical alignment for a field using the FormEditor class, and save the updated PDF. The example sets the vertical alignment of a field named "First Name" to the bottom of the field area. --- PDF form fields can contain text that needs proper vertical alignment for a consistent and professional appearance. Using Aspose.PDF for Python, developers can programmatically modify the vertical alignment of form fields. diff --git a/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md b/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md index 23a8c9e21..a3870de4f 100644 --- a/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md +++ b/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Set Text Alignment for PDF Form Fields Using Python -Abstract: This article explains how to open a PDF document, set the alignment of a specific field using the FormEditor class, and save the updated PDF. The example sets the text alignment of a field named "First Name" to center. +Abstract: This article explains how to open a PDF document, set the alignment of a specific field using the FormEditor class, and save the updated PDF. The example sets the text alignment of a field named "First Name" to center. --- PDF form fields often require customized text alignment to maintain a consistent and professional layout. Using Aspose.PDF for Python, developers can programmatically set the alignment of a form field’s text content. diff --git a/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md b/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md index 3101aaf3f..5f8863487 100644 --- a/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md +++ b/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Set PDF Form Field Appearance Using Python -Abstract: This article explains how to open a PDF, set the appearance of a form field using the FormEditor class, and save the updated document. The example sets the appearance of a field named "First Name" to invisible using the AnnotationFlags.INVISIBLE flag. +Abstract: This article explains how to open a PDF, set the appearance of a form field using the FormEditor class, and save the updated document. The example sets the appearance of a field named "First Name" to invisible using the AnnotationFlags.INVISIBLE flag. --- PDF form fields support appearance flags that control visibility, printability, and interactivity. Using Aspose.PDF for Python, developers can programmatically modify these flags for specific form fields. diff --git a/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md b/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md index a82ecf559..bdfc6822f 100644 --- a/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md +++ b/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Set Comb Number for PDF Form Fields Using Python -Abstract: Using Aspose.PDF for Python, developers can programmatically set the number of boxes (comb number) for a form field to enforce a fixed-length input. This article demonstrates setting the comb number for a field named "PIN". +Abstract: Using Aspose.PDF for Python, developers can programmatically set the number of boxes (comb number) for a form field to enforce a fixed-length input. This article demonstrates setting the comb number for a field named "PIN". --- The comb number defines how the field's content is split into equally spaced boxes, often used for PIN codes, serial numbers, or other fixed-length input fields. The code opens an existing PDF, sets the comb number for a field, and saves the modified document. diff --git a/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md b/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md index 39aeb4944..eab7f481a 100644 --- a/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md +++ b/en/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Set Maximum Character Limit for PDF Form Fields Using Python -Abstract: This example demonstrates setting the character limit for a field named "Last Name" to 10 characters, ensuring that users cannot enter more than the specified limit. +Abstract: This example demonstrates setting the character limit for a field named "Last Name" to 10 characters, ensuring that users cannot enter more than the specified limit. --- Form fields in PDF documents may require input restrictions to maintain proper formatting. Using Aspose.PDF for Python, developers can programmatically set a maximum number of characters for a field. diff --git a/en/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md b/en/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md index 37b7a31f5..d26f38bad 100644 --- a/en/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md +++ b/en/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Modify PDF Form Fields in Python- Add, Move, Copy, Rename, and Delete Fields -Abstract: Learn how to modify existing PDF form fields using Aspose.PDF for Python. This guide explains how to manage form elements by adding or deleting list items, moving fields, removing or renaming them, converting single-line fields to multi-line, and copying fields within or between documents. These techniques help developers dynamically update PDF forms and adapt them to evolving business requirements without recreating the entire form structure. +Abstract: Learn how to modify existing PDF form fields using Aspose.PDF for Python. This guide explains how to manage form elements by adding or deleting list items, moving fields, removing or renaming them, converting single-line fields to multi-line, and copying fields within or between documents. These techniques help developers dynamically update PDF forms and adapt them to evolving business requirements without recreating the entire form structure. --- - [Add List Item](/pdf/python-net/add-list-item/) diff --git a/en/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md b/en/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md index 589c3c54c..9e19964f3 100644 --- a/en/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md +++ b/en/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Add Items to PDF List Box Fields Using Python -Abstract: This article shows how to open a PDF document, append items to a list box field named "Country", and save the updated document. +Abstract: This article shows how to open a PDF document, append items to a list box field named "Country", and save the updated document. --- List box fields in PDFs allow users to select one or multiple options from a predefined set. Using Aspose.PDF for Python, developers can programmatically add new items to these fields. The [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) class provides the 'add_list_item' method to append items to an existing list box field. diff --git a/en/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md b/en/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md index 68d19a3e0..98e2ad348 100644 --- a/en/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md +++ b/en/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Copy PDF Form Fields to a New Position Using Python -Abstract: This example demonstrates how to copy an existing form field to a new position in a PDF document using Aspose.PDF for Python. The code opens a PDF, duplicates a field to a specified page and coordinates, and saves the updated document. +Abstract: This example demonstrates how to copy an existing form field to a new position in a PDF document using Aspose.PDF for Python. The code opens a PDF, duplicates a field to a specified page and coordinates, and saves the updated document. --- PDF forms often require duplicating fields while maintaining the original formatting and behavior. Using Aspose.PDF for Python, developers can copy an existing field to a new position on the same or another page programmatically. diff --git a/en/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md b/en/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md index 50736ea48..5daaa3d3e 100644 --- a/en/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md +++ b/en/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Copy PDF Form Fields from Another Document Using Python -Abstract: This article explains how to create a new PDF document, copy the "First Name" field from a source PDF to page 1 at coordinates (200, 600), and save the updated target document. +Abstract: This article explains how to create a new PDF document, copy the "First Name" field from a source PDF to page 1 at coordinates (200, 600), and save the updated target document. --- Sometimes, PDF forms require reusing fields from one document in another. Using Aspose.PDF for Python, developers can programmatically copy form fields from a source PDF to a target PDF. diff --git a/en/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md b/en/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md index ade5a46b0..3f466a256 100644 --- a/en/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md +++ b/en/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md @@ -3,14 +3,14 @@ title: Delete List Item type: docs weight: 40 url: /python-net/del-list-item/ -description: +description: lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Remove Items from PDF List Box Fields Using Python -Abstract: This example demonstrates how to remove an item from a list box form field in a PDF document using Aspose.PDF for Python. The code opens an existing PDF, deletes a specific item from a list box field, and saves the updated document. +Abstract: This example demonstrates how to remove an item from a list box form field in a PDF document using Aspose.PDF for Python. The code opens an existing PDF, deletes a specific item from a list box field, and saves the updated document. --- List box fields in PDFs allow users to select one or multiple predefined options. Using Aspose.PDF for Python, developers can programmatically remove items from these fields. diff --git a/en/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md b/en/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md index 0a7ad55e2..205fdf73f 100644 --- a/en/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md +++ b/en/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Move a PDF Form Field to a New Position Using Python -Abstract: This example demonstrates how to move an existing form field to a different position in a PDF document using Aspose.PDF for Python. The code opens an existing PDF, relocates the specified form field to new coordinates, and saves the updated document. +Abstract: This example demonstrates how to move an existing form field to a different position in a PDF document using Aspose.PDF for Python. The code opens an existing PDF, relocates the specified form field to new coordinates, and saves the updated document. --- PDF forms often require layout adjustments after creation. Using Aspose.PDF for Python, developers can move existing form fields to a new position without recreating them. diff --git a/en/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md b/en/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md index f6cdf5868..462c05921 100644 --- a/en/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md +++ b/en/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Remove a Form Field from a PDF Document Using Python -Abstract: This example demonstrates how to remove an existing form field from a PDF document using Aspose.PDF for Python. The code loads a PDF file, deletes the specified field using the FormEditor class, and saves the updated document. +Abstract: This example demonstrates how to remove an existing form field from a PDF document using Aspose.PDF for Python. The code loads a PDF file, deletes the specified field using the FormEditor class, and saves the updated document. --- PDF forms may contain fields that are no longer needed due to design changes or workflow updates. With Aspose.PDF for Python, developers can easily remove specific form fields programmatically. diff --git a/en/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md b/en/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md index e3de48587..afcbaf8fc 100644 --- a/en/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md +++ b/en/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Rename a PDF Form Field Using Python -Abstract: This example demonstrates how to rename an existing form field in a PDF document using Aspose.PDF for Python. The code opens an input PDF, changes the name of a specified form field using the FormEditor class, and saves the updated document. +Abstract: This example demonstrates how to rename an existing form field in a PDF document using Aspose.PDF for Python. The code opens an input PDF, changes the name of a specified form field using the FormEditor class, and saves the updated document. --- PDF forms often rely on field names for scripting, automation, and data processing. Using Aspose.PDF for Python, developers can rename existing fields without recreating them or altering the form layout. diff --git a/en/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md b/en/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md index ceeb1efaf..8db078460 100644 --- a/en/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md +++ b/en/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md @@ -1,5 +1,5 @@ --- -title: Single-Line Field to Multi-Line Field +title: Single-Line Field to Multi-Line Field type: docs weight: 80 url: /python-net/single-to-multiple/ @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Convert a Single-Line Text Field to a Multi-Line Field in a PDF Using Python -Abstract: This example demonstrates how to convert a single-line text field into a multi-line field in a PDF document using Aspose.PDF for Python. The code loads an existing PDF form, modifies the specified field to allow multiple lines of text, and saves the updated document. +Abstract: This example demonstrates how to convert a single-line text field into a multi-line field in a PDF document using Aspose.PDF for Python. The code loads an existing PDF form, modifies the specified field to allow multiple lines of text, and saves the updated document. --- PDF forms sometimes contain text fields designed for single-line input, which may not be sufficient for certain types of data. With Aspose.PDF for Python, developers can easily convert such fields into multi-line text fields without recreating them. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md index 967589daa..6980a8790 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md @@ -3,11 +3,11 @@ title: Annotations type: docs weight: 10 url: /python-net/annotations/ -description: +description: lastmod: "2026-03-20" sitemap: changefreq: "weekly" - priority: 0.7 + priority: 0.7 --- - [Add Text Annotations](/pdf/python-net/add-text-annotation/) diff --git a/en/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md index 540a71994..dcf237ee7 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-20" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Add Caret Annotation to a PDF Using Python -Abstract: This example demonstrates how to add a caret annotation to a PDF document using Aspose.PDF for Python via the Facades API. The sample shows how to bind a PDF file, define annotation placement using rectangles, configure caret properties, and save the updated document. +Abstract: This example demonstrates how to add a caret annotation to a PDF document using Aspose.PDF for Python via the Facades API. The sample shows how to bind a PDF file, define annotation placement using rectangles, configure caret properties, and save the updated document. --- Caret annotations are commonly used to indicate text insertions or editorial comments in a document. With PdfContentEditor, you can programmatically add caret annotations by specifying the page number, annotation bounds, callout area, symbol, note text, and color. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md index a55c48298..b6eec1384 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-03-20" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Add Free Text Annotation to a PDF Using Python Abstract: This example demonstrates how to insert a free text annotation into a PDF document using Aspose.PDF for Python via the Facades API. It shows how to bind a PDF, define annotation placement, add custom text, and save the updated document. --- diff --git a/en/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md index 4bc1052ef..91803a987 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-20" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Add Highlight, Underline, Strikeout, and Squiggly Markup Annotations in a PDF Using Python -Abstract: This example demonstrates how to add multiple markup annotations—highlight, underline, strikeout, and squiggly—to a PDF document using Aspose.PDF for Python via the Facades API. The sample shows how to define annotation areas, specify markup types, apply colors, and save the modified document. +Abstract: This example demonstrates how to add multiple markup annotations—highlight, underline, strikeout, and squiggly—to a PDF document using Aspose.PDF for Python via the Facades API. The sample shows how to define annotation areas, specify markup types, apply colors, and save the modified document. --- Markup annotations are used to emphasize or review text within a PDF. With PdfContentEditor, you can programmatically apply different markup styles by specifying a rectangle area, comment text, markup type, page number, and color. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md index 60c5f6249..aa55b6001 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-03-20" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Add Popup Annotations to a PDF Using Python Abstract: This example demonstrates how to insert a popup annotation into a PDF document using Aspose.PDF for Python via the Facades API. It explains how to define the popup area, set the annotation text, control visibility, and save the updated document. --- diff --git a/en/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md index c65717316..7b00fc812 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md @@ -3,7 +3,7 @@ title: Attachments type: docs weight: 20 url: /python-net/attachments/ -description: +description: lastmod: "2026-03-20" sitemap: changefreq: "weekly" diff --git a/en/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md index 294ed047b..1940fddd6 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Add File Attachment Annotations to a PDF Using Python -Abstract: This example demonstrates how to create a file attachment annotation in a PDF using a file path with Aspose.PDF for Python via the Facades API. It shows how to define annotation placement, set description text, choose an icon type, and save the modified document. +Abstract: This example demonstrates how to create a file attachment annotation in a PDF using a file path with Aspose.PDF for Python via the Facades API. It shows how to define annotation placement, set description text, choose an icon type, and save the modified document. --- File attachment annotations allow you to embed external files as interactive icons on a PDF page. Using the file-path overload, you can attach files directly from disk without manually opening streams. This method also lets you customize the annotation icon and provide a description for users. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md index e8bbc8759..3b1476fa2 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Add File Attachment Annotations to a PDF from a Stream in Python -Abstract: This example demonstrates how to create a file attachment annotation in a PDF using a file stream with Aspose.PDF for Python via the Facades API. It shows how to specify annotation position, set a description, include an opacity value, and save the modified document. +Abstract: This example demonstrates how to create a file attachment annotation in a PDF using a file stream with Aspose.PDF for Python via the Facades API. It shows how to specify annotation position, set a description, include an opacity value, and save the modified document. --- File attachment annotations allow embedding files as interactive icons within a PDF page. Using a stream-based approach, you can attach files dynamically without relying on a physical file path. This method also supports customizing the annotation's appearance, including opacity. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md index 88ca538c6..84e5290e9 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Remove All Attachments from a PDF Using Python -Abstract: This example demonstrates how to remove all file attachments from a PDF document using Aspose.PDF for Python via the Facades API. It shows how to bind a PDF, delete embedded attachments, and save the updated document. +Abstract: This example demonstrates how to remove all file attachments from a PDF document using Aspose.PDF for Python via the Facades API. It shows how to bind a PDF, delete embedded attachments, and save the updated document. --- PDFs may contain attachments such as documents, images, or other files. There are scenarios where you need to clean a PDF of all attachments for security, privacy, or distribution purposes. Using [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can programmatically remove all embedded attachments in a document. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md index 6151d3a42..f90b5eaa2 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md @@ -3,7 +3,7 @@ title: Document Actions type: docs weight: 40 url: /python-net/document-actions/ -description: +description: lastmod: "2026-03-20" sitemap: changefreq: "weekly" diff --git a/en/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md index 4782953e0..1bd1b99f8 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md @@ -3,14 +3,14 @@ title: Add Bookmark Action type: docs weight: 10 url: /python-net/add-bookmark-action/ -description: This example binds an input PDF, creates a bookmark labeled "PdfContentEditor Bookmark" that navigates to page 1, and saves the updated document. +description: This example binds an input PDF, creates a bookmark labeled "PdfContentEditor Bookmark" that navigates to page 1, and saves the updated document. lastmod: "2026-03-20" sitemap: changefreq: "weekly" priority: 0.7 TechArticle: true AlternativeHeadline: Create a Bookmark with Navigation Action in a PDF Using Python -Abstract: This example demonstrates how to add a bookmark with a navigation action to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to configure bookmark text, appearance, and an action that directs users to a specific page. +Abstract: This example demonstrates how to add a bookmark with a navigation action to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to configure bookmark text, appearance, and an action that directs users to a specific page. --- Bookmarks provide quick navigation within PDF documents. Using [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can programmatically create bookmarks and assign actions such as navigating to a page. You can also customize the bookmark appearance, including color and style options like bold or italic. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md index fc64fcb86..d9f06ae8a 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md @@ -3,14 +3,14 @@ title: Add Document Action type: docs weight: 20 url: /python-net/add-document-action/ -description: This example adds a JavaScript alert that appears when the PDF is opened. The script is attached to the document open event and executed automatically in supported PDF viewers. +description: This example adds a JavaScript alert that appears when the PDF is opened. The script is attached to the document open event and executed automatically in supported PDF viewers. lastmod: "2026-03-20" sitemap: changefreq: "weekly" priority: 0.7 TechArticle: true AlternativeHeadline: Add Document Open JavaScript Action to a PDF Using Python -Abstract: This example demonstrates how to add a document-level JavaScript action that triggers when a PDF is opened. Using Aspose.PDF for Python via the Facades API, the sample shows how to bind a document, assign an open event action, and save the updated PDF. +Abstract: This example demonstrates how to add a document-level JavaScript action that triggers when a PDF is opened. Using Aspose.PDF for Python via the Facades API, the sample shows how to bind a document, assign an open event action, and save the updated PDF. --- Document-level actions allow you to define behaviors that execute automatically when certain events occur, such as opening a PDF. With [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can attach JavaScript code to these events. This can be used for notifications, validation logic, or interactive workflows. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md index 6e2659948..ec9352683 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Remove Document Open Action from a PDF Using Python -Abstract: This example demonstrates how to remove a document open action from a PDF using Aspose.PDF for Python via the Facades API. It shows how to bind a PDF, clear the open action, and save the updated document. +Abstract: This example demonstrates how to remove a document open action from a PDF using Aspose.PDF for Python via the Facades API. It shows how to bind a PDF, clear the open action, and save the updated document. --- PDF documents may contain actions that execute automatically when the file is opened, such as JavaScript alerts, navigation commands, or other behaviors. In some scenarios, you may need to remove these actions for security, compliance, or user experience reasons. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md index c1e07d8f1..1846d0a70 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md @@ -3,11 +3,11 @@ title: Drawing Annotations type: docs weight: 50 url: /python-net/drawing-annotations/ -description: +description: lastmod: "2026-03-20" sitemap: changefreq: "weekly" - priority: 0.7 + priority: 0.7 --- - [Add Line Annotation](/pdf/python-net/add-line-annotation/) diff --git a/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md index 9beb0cd50..df71f5ced 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Add Circle Annotation to a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to add a circle annotation to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to define annotation bounds, set content text, configure color and appearance, and save the updated document. +Abstract: This example demonstrates how to add a circle annotation to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to define annotation bounds, set content text, configure color and appearance, and save the updated document. --- Circle annotations are useful for highlighting areas of interest in a PDF document. With [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can create circular shapes by specifying the rectangle that defines the circle’s bounds, along with annotation text, color, fill options, page number, and border width. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md index 24000e57e..70257a4c7 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Add Curve Annotation to a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to add a curve annotation to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to define curve vertices, border style, annotation bounds, text content, and save the updated document. +Abstract: This example demonstrates how to add a curve annotation to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to define curve vertices, border style, annotation bounds, text content, and save the updated document. --- Curve annotations are used to highlight irregular paths or shapes in a PDF, providing visual emphasis or marking important areas. Using [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can draw curves by specifying a sequence of vertices, border style, visibility, annotation rectangle, and descriptive text. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md index db4499dab..0d41181f3 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Add Line Annotation to a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to add a line annotation to a PDF document using Aspose.PDF for Python via the Facades API. It explains how to define the line’s start and end points, rectangle bounds, appearance properties, and save the updated document. +Abstract: This example demonstrates how to add a line annotation to a PDF document using Aspose.PDF for Python via the Facades API. It explains how to define the line’s start and end points, rectangle bounds, appearance properties, and save the updated document. --- Line annotations are useful for emphasizing text, highlighting relationships, or drawing attention to specific areas in a PDF. With [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can programmatically create line annotations by specifying the start and end points, bounding rectangle, color, border style, and line endings. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md index 7d3325935..16cb50218 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Add Polygon Annotation to a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to add a polygon annotation to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to define polygon vertices, border style, annotation bounds, descriptive text, and save the updated document. +Abstract: This example demonstrates how to add a polygon annotation to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to define polygon vertices, border style, annotation bounds, descriptive text, and save the updated document. --- Polygon annotations are used to highlight irregular areas or shapes in a PDF, providing visual emphasis or marking specific regions. Using [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can create polygons by specifying the vertices coordinates, border style, page number, and annotation rectangle. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md index 31a29f1f2..1bafa1c2f 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Add Polyline Annotation to a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to add a polyline annotation to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to define a sequence of vertices, border style, annotation rectangle, text, and save the updated document. +Abstract: This example demonstrates how to add a polyline annotation to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to define a sequence of vertices, border style, annotation rectangle, text, and save the updated document. --- Polyline annotations allow you to highlight a series of connected line segments in a PDF. Using [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can draw a polyline by specifying vertices coordinates, border style, page number, and annotation bounds. This is useful for visually representing paths, trends, or connections in diagrams and documents. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md index 1c28e7a80..de8114686 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Add Square Annotation to a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to add a square annotation to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to define the annotation rectangle, text content, color, fill options, and save the updated document. +Abstract: This example demonstrates how to add a square annotation to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to define the annotation rectangle, text content, color, fill options, and save the updated document. --- Square annotations are commonly used to highlight areas of interest, mark important sections, or provide visual cues in a PDF document. Using [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can create square (or circular) annotations by specifying the bounding rectangle, content text, border color, fill option, page number, and border width. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md index 0072683a2..4a2cca78b 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md @@ -3,11 +3,11 @@ title: Image Operations type: docs weight: 60 url: /python-net/image-operations/ -description: +description: lastmod: "2026-03-20" sitemap: changefreq: "weekly" - priority: 0.7 + priority: 0.7 --- - [Replace Images in PDF](/pdf/python-net/replace-image/) diff --git a/en/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md index c22fd3808..cc56ea93b 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Remove All Images from a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to delete all images from a PDF document using Aspose.PDF for Python via the Facades API. It shows how to bind a PDF, remove all embedded images, and save the updated document. +Abstract: This example demonstrates how to delete all images from a PDF document using Aspose.PDF for Python via the Facades API. It shows how to bind a PDF, remove all embedded images, and save the updated document. --- PDF documents often contain images for illustrations, branding, or decoration. There may be cases where you need to remove all images from a PDF, such as reducing file size, protecting sensitive visuals, or preparing a text-only version. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md index fe945d590..28156729f 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md @@ -3,14 +3,14 @@ title: Delete Images from PDF type: docs weight: 20 url: /python-net/delete-images/ -description: +description: lastmod: "2026-03-20" sitemap: changefreq: "weekly" priority: 0.7 TechArticle: true AlternativeHeadline: Delete Specific Images from a PDF Page Using PdfContentEditor in Python -Abstract: This example demonstrates how to delete specific images from a PDF document using Aspose.PDF for Python via the Facades API. It shows how to target images on a specific page and save the updated document. +Abstract: This example demonstrates how to delete specific images from a PDF document using Aspose.PDF for Python via the Facades API. It shows how to target images on a specific page and save the updated document. --- Sometimes, you may want to remove only certain images from a PDF rather than clearing all visuals. With [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can delete selected images by specifying the page number and the image index. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md index 76fd04bec..e08b5d365 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Replace an Image in a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to replace an existing image in a PDF document using Aspose.PDF for Python via the Facades API. It shows how to target a specific image on a page and replace it with a new image, then save the updated PDF. +Abstract: This example demonstrates how to replace an existing image in a PDF document using Aspose.PDF for Python via the Facades API. It shows how to target a specific image on a page and replace it with a new image, then save the updated PDF. --- PDFs often contain images that may need to be updated or replaced, such as logos, diagrams, or photos. With [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can replace a specific image on a given page by providing the page number, image index, and new image file path. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md index 196498964..e57255180 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md @@ -3,11 +3,11 @@ title: Links and Navigation type: docs weight: 70 url: /python-net/links-and-navigation/ -description: +description: lastmod: "2026-03-20" sitemap: changefreq: "weekly" - priority: 0.7 + priority: 0.7 --- - [Add Web Link](/pdf/python-net/add-web-link/) diff --git a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md index 8f2401755..b17bb801a 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Add an Application Launch Link to a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to add an application launch link to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to create a clickable area that opens a specified application when clicked, and save the updated PDF. +Abstract: This example demonstrates how to add an application launch link to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to create a clickable area that opens a specified application when clicked, and save the updated PDF. --- PDF can include interactive elements such as links that launch external applications. Using [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can define a rectangular region on a page that, when clicked, opens a specific executable file. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md index 355a8cc0d..74bf756de 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Add a Custom Action Link to a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to add a custom action link to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to create a clickable area on a page, assign a custom action, and save the updated document. +Abstract: This example demonstrates how to add a custom action link to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to create a clickable area on a page, assign a custom action, and save the updated document. --- Custom action links allow you to define interactive areas in a PDF that can trigger specific actions when clicked, such as executing scripts, navigating pages, or running application-specific commands. Using [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can create a custom action link by specifying the page, rectangle, color, and actions. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md index e8f2014c2..4f0074de4 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Add a JavaScript Link to a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to add a JavaScript link to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to create a clickable area that executes JavaScript code when clicked, and save the updated PDF. +Abstract: This example demonstrates how to add a JavaScript link to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to create a clickable area that executes JavaScript code when clicked, and save the updated PDF. --- JavaScript links in PDFs allow interactive functionality such as displaying alerts, performing calculations, or dynamically modifying document content. Using [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can define a clickable rectangle on a page and associate it with custom JavaScript code. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md index 8fa6248ca..2c2ce3d5e 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Add a Local Link to a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to add a local link to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to create a clickable area that navigates to another page within the same PDF and save the updated document. +Abstract: This example demonstrates how to add a local link to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to create a clickable area that navigates to another page within the same PDF and save the updated document. --- Local links in PDFs allow quick navigation between pages within the same document. Using [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can define a clickable rectangle that links one page to another, improving document usability and navigation. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md index 5b96f8cda..b8aff477f 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Add a PDF Document Link Using PdfContentEditor in Python -Abstract: This example demonstrates how to add a link to another PDF document using Aspose.PDF for Python via the Facades API. It shows how to create a clickable area that opens a different PDF and save the updated document. +Abstract: This example demonstrates how to add a link to another PDF document using Aspose.PDF for Python via the Facades API. It shows how to create a clickable area that opens a different PDF and save the updated document. --- PDF document links allow users to navigate from one PDF to another seamlessly. Using [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can define a clickable rectangle that links to a page in a different PDF file, making your documents interactive and connected. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md index 59fa98581..3823e0014 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Add a Web Link to a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to add a web link to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to create a clickable area on a page that opens a specified URL in a web browser and save the updated document. +Abstract: This example demonstrates how to add a web link to a PDF document using Aspose.PDF for Python via the Facades API. It shows how to create a clickable area on a page that opens a specified URL in a web browser and save the updated document. --- Web links in PDFs allow users to navigate directly to online resources, websites, or documentation. Using [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can define a rectangular area on a PDF page that, when clicked, opens a URL in the default web browser. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md index d3e62f947..80bb1c3b3 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Extract Links from a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to extract all links from a PDF document using Aspose.PDF for Python via the Facades API. It shows how to identify and retrieve web links or other actionable links embedded in the PDF. +Abstract: This example demonstrates how to extract all links from a PDF document using Aspose.PDF for Python via the Facades API. It shows how to identify and retrieve web links or other actionable links embedded in the PDF. --- PDF often contain interactive elements such as web links, document links, and custom actions. Using [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can programmatically extract all link annotations from a PDF. This allows you to inspect or process links, for example, to validate URLs or analyze navigation patterns in a document. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md index 70c80a3a7..ecd83ec72 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md @@ -3,7 +3,7 @@ title: Multimedia type: docs weight: 80 url: /python-net/multimedia/ -description: +description: lastmod: "2026-03-20" sitemap: changefreq: "weekly" diff --git a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md index 9f9d10837..bf211eed5 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md @@ -3,7 +3,7 @@ title: Stamps Management type: docs weight: 90 url: /python-net/stamps-management/ -description: +description: lastmod: "2026-03-20" sitemap: changefreq: "weekly" diff --git a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md index 1add56409..3638d7ea2 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Add a Rubber Stamp Annotation to a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to add a rubber stamp annotation to a PDF document using Aspose.PDF for Python via the Facades API. Rubber stamps allow you to visually mark pages with approvals, reviews, or custom labels. +Abstract: This example demonstrates how to add a rubber stamp annotation to a PDF document using Aspose.PDF for Python via the Facades API. Rubber stamps allow you to visually mark pages with approvals, reviews, or custom labels. --- Rubber stamp annotations are commonly used in PDFs to indicate approval, review status, or other notes. Using [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can define a rectangle for the stamp, set its text and comments, choose a color, and apply it to multiple pages of a document. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md index f5d96f746..5ed62f739 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Create a Rubber Stamp with Custom Appearance in a PDF Using PdfContentEditor -Abstract: This example demonstrates how to add a rubber stamp annotation with a custom appearance (image) to a PDF document using Aspose.PDF for Python via the Facades API. Custom stamps allow you to include logos, signatures, or branded visuals as part of the stamp. +Abstract: This example demonstrates how to add a rubber stamp annotation with a custom appearance (image) to a PDF document using Aspose.PDF for Python via the Facades API. Custom stamps allow you to include logos, signatures, or branded visuals as part of the stamp. --- Rubber stamp annotations can be customized not only with text but also by using an image file as their appearance. This approach is useful for adding company logos, signature stamps, or any visual indicator to your PDF pages. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md index 93543caae..1e96951a3 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Create a Rubber Stamp with Custom Image Appearance Using PdfContentEditor in Python -Abstract: This example shows how to create a rubber stamp annotation with a custom image appearance in a PDF using Aspose.PDF for Python via the Facades API. This approach lets you apply branded or visually rich stamps such as logos, seals, or signatures. +Abstract: This example shows how to create a rubber stamp annotation with a custom image appearance in a PDF using Aspose.PDF for Python via the Facades API. This approach lets you apply branded or visually rich stamps such as logos, seals, or signatures. --- Rubber stamp annotations can be customized using an external image file. Instead of relying only on text-based stamps, you can define a visual appearance (for example, a company logo or approval badge) and place it on a page. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md index 7bc7c5b57..ebc2aaaf8 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md @@ -3,14 +3,14 @@ title: Delete Stamp By ID type: docs weight: 85 url: /python-net/delete-stamp-by-ids-examples/ -description: +description: lastmod: "2026-03-20" sitemap: changefreq: "weekly" priority: 0.7 TechArticle: true AlternativeHeadline: Delete Rubber Stamps by Single or Multiple IDs in a PDF Using PdfContentEditor -Abstract: This example demonstrates how to remove rubber stamp annotations from a PDF based on their unique IDs using Aspose.PDF for Python via the Facades API. It covers both single-ID deletion and multiple-ID deletion. +Abstract: This example demonstrates how to remove rubber stamp annotations from a PDF based on their unique IDs using Aspose.PDF for Python via the Facades API. It covers both single-ID deletion and multiple-ID deletion. --- When working with PDFs containing multiple stamps, it is often necessary to remove specific stamps without affecting others. Using ID-based deletion, you can precisely control which stamps to remove: diff --git a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md index 252fbf3ca..273d7fb84 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Delete Rubber Stamps Globally in a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to delete rubber stamp annotations globally across all pages in a PDF using Aspose.PDF for Python via the Facades API. It shows how to remove stamps by ID without specifying individual pages. +Abstract: This example demonstrates how to delete rubber stamp annotations globally across all pages in a PDF using Aspose.PDF for Python via the Facades API. It shows how to remove stamps by ID without specifying individual pages. --- When working with multiple pages, you may need to remove certain stamps throughout the entire document. The 'delete_stamp_by_id()' and 'delete_stamp_by_ids()' methods allow you to delete stamps globally by their identifiers, eliminating the need to iterate through each page manually. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md index 5be51049f..960be35db 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: List Rubber Stamp Annotations in a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to retrieve and list rubber stamp annotations from a PDF document using Aspose.PDF for Python via the Facades API. It shows how to access stamps on a specific page and display their details. +Abstract: This example demonstrates how to retrieve and list rubber stamp annotations from a PDF document using Aspose.PDF for Python via the Facades API. It shows how to access stamps on a specific page and display their details. --- When working with annotated PDFs, you may need to inspect existing rubber stamps before modifying or removing them. The 'get_stamps()' method allows you to retrieve all stamps placed on a particular page. You can then iterate through the results and process them programmatically. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md index 068e01acc..afe191d3d 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Manage Rubber Stamps by ID in a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to manipulate rubber stamp annotations in a PDF by their unique IDs using Aspose.PDF for Python via the Facades API. You can hide or show specific stamps on certain pages without affecting other stamps. +Abstract: This example demonstrates how to manipulate rubber stamp annotations in a PDF by their unique IDs using Aspose.PDF for Python via the Facades API. You can hide or show specific stamps on certain pages without affecting other stamps. --- In PDFs with multiple rubber stamps, it can be useful to control individual stamps based on their ID. The 'hide_stamp_by_id()' and 'show_stamp_by_id()' methods allow selective visibility control. This example shows how to: diff --git a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md index 3ca07c29e..9d18d4931 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Move a Rubber Stamp by ID in a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to reposition an existing rubber stamp annotation in a PDF using Aspose.PDF for Python via the Facades API. It shows how to create a stamp and then move it programmatically using its ID. +Abstract: This example demonstrates how to reposition an existing rubber stamp annotation in a PDF using Aspose.PDF for Python via the Facades API. It shows how to create a stamp and then move it programmatically using its ID. --- After adding a rubber stamp annotation to a PDF, you may need to adjust its position. The 'move_stamp_by_id()' method allows you to relocate a stamp based on its identifier, without recreating it. This is useful in automated workflows where stamp placement must be dynamically adjusted. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md index 162eb95f0..f5d372288 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Move Rubber Stamps in a PDF Using Index-Based Positioning -Abstract: This example demonstrates how to reposition rubber stamp annotations in a PDF by using their index on a page with Aspose.PDF for Python via the Facades API. It highlights creating multiple stamps and preparing them for movement operations. +Abstract: This example demonstrates how to reposition rubber stamp annotations in a PDF by using their index on a page with Aspose.PDF for Python via the Facades API. It highlights creating multiple stamps and preparing them for movement operations. --- In PDF editing, it may be necessary to adjust the position of existing rubber stamps. This code snippet shows how to: diff --git a/en/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md index a47bfc235..3e715f88d 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md @@ -3,7 +3,7 @@ title: Text Operations type: docs weight: 100 url: /python-net/text-operations/ -description: +description: lastmod: "2026-03-20" sitemap: changefreq: "weekly" diff --git a/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md index 57dbea08b..be6c67cc4 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Replace Text with Custom Formatting on a Specific Page Using PdfContentEditor in Python -Abstract: This example demonstrates how to replace text on a specific page in a PDF while applying custom formatting using Aspose.PDF for Python via the Facades API. It shows how to control font size and color during text replacement. +Abstract: This example demonstrates how to replace text on a specific page in a PDF while applying custom formatting using Aspose.PDF for Python via the Facades API. It shows how to control font size and color during text replacement. --- Sometimes replacing text in a PDF also requires formatting changes such as color or font size. Using TextState, you can define styling properties and apply them during replacement. This allows you to highlight modified text or enforce consistent formatting across documents. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md index f4b9080da..764ed720c 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Replace Text on a Specific Page Using PdfContentEditor in Python -Abstract: This example demonstrates how to replace text in a PDF document using Aspose.PDF for Python via the Facades API. It shows how to replace the first occurrence of text on a page and save the updated document. +Abstract: This example demonstrates how to replace text in a PDF document using Aspose.PDF for Python via the Facades API. It shows how to replace the first occurrence of text on a page and save the updated document. --- Text replacement is a common requirement when updating PDF documents. Using [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can search for specific text and replace it with new content. The 'replace_text_strategy' property allows you to control how many occurrences are replaced. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md index c2efc5216..ecbbacd33 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Replace Text Using Regular Expressions with PdfContentEditor in Python -Abstract: This example demonstrates how to replace text in a PDF using regular expressions with Aspose.PDF for Python via the Facades API. It shows how to search for patterns and replace all matches across the document. +Abstract: This example demonstrates how to replace text in a PDF using regular expressions with Aspose.PDF for Python via the Facades API. It shows how to search for patterns and replace all matches across the document. --- Regular expressions allow flexible text replacement based on patterns instead of fixed strings. By enabling regex support in 'replace_text_strategy', you can match dynamic content such as numbers, dates, or formatted strings. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md index 503c386e2..b4779b27a 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Replace Text Across a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to replace text throughout an entire PDF document using Aspose.PDF for Python via the Facades API. It replaces all occurrences of a specified string with new text. +Abstract: This example demonstrates how to replace text throughout an entire PDF document using Aspose.PDF for Python via the Facades API. It replaces all occurrences of a specified string with new text. --- Simple text replacement is useful when updating repeated values in a document. With [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), you can define a replacement scope and substitute text globally across all pages. diff --git a/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md index 95c7dc594..8d9e8262f 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md @@ -9,7 +9,7 @@ sitemap: changefreq: "weekly" priority: 0.7 TechArticle: true -AlternativeHeadline: Replace Text with Custom Formatting in a PDF Using PdfContentEditor in Python +AlternativeHeadline: Replace Text with Custom Formatting in a PDF Using PdfContentEditor in Python Abstract: This example demonstrates how to replace text in a PDF document while applying custom formatting using Aspose.PDF for Python via the Facades API. It shows how to control text color and font size during replacement. --- diff --git a/en/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md index 62dd526d6..39e04e185 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md @@ -3,7 +3,7 @@ title: Viewer Preferences type: docs weight: 110 url: /python-net/viewer-preferences/ -description: +description: lastmod: "2026-03-20" sitemap: changefreq: "weekly" diff --git a/en/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md index 439d08978..a3c297035 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md @@ -3,14 +3,14 @@ title: Change PDF Viewer Preferences type: docs weight: 10 url: /python-net/change-viewer-preferences/ -description: This module demonstrates how to adjust a PDF document’s viewer settings using Aspose.PDF for Python. +description: This module demonstrates how to adjust a PDF document’s viewer settings using Aspose.PDF for Python. lastmod: "2026-03-20" sitemap: changefreq: "weekly" priority: 0.7 TechArticle: true AlternativeHeadline: Customize PDF Viewer Experience with Python -Abstract: Control how your PDF document appears when opened by modifying viewer preferences programmatically. This functionality allows you to tailor the user interface and layout, ensuring a consistent viewing experience. +Abstract: Control how your PDF document appears when opened by modifying viewer preferences programmatically. This functionality allows you to tailor the user interface and layout, ensuring a consistent viewing experience. --- PDF files have built-in viewer preferences that control aspects like page layout, toolbar visibility, and window behavior. Using this script, you can: diff --git a/en/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md index 3b92f6e14..d2330e428 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md @@ -10,7 +10,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Manage PDF Viewer Preferences with Aspose.PDF in Python -Abstract: This guide demonstrates how to read and modify PDF viewer preferences programmatically using Aspose.PDF for Python. Viewer preferences control how a PDF is displayed when opened in a PDF viewer, such as opening with outlines, hiding toolbars, or using single-page layout. +Abstract: This guide demonstrates how to read and modify PDF viewer preferences programmatically using Aspose.PDF for Python. Viewer preferences control how a PDF is displayed when opened in a PDF viewer, such as opening with outlines, hiding toolbars, or using single-page layout. --- Aspose.PDF provides tools to access and update PDF viewer preferences. These preferences define the initial layout and presentation behavior of a PDF document in PDF readers. This includes options such as enabling outline view, hiding menu bars, or specifying page layout modes. Using PdfContentEditor, you can retrieve existing preferences, check specific flags, and update them as needed. diff --git a/en/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md b/en/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md index 3cad205de..8e766e89e 100644 --- a/en/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Create Booklet and N-Up Layouts for PDF Documents in Python -Abstract: Learn how to transform PDF page layouts using Aspose.PDF for Python. This guide explains how to generate booklet-style documents and create N-Up layouts that place multiple pages on a single sheet. These techniques help optimize documents for printing, reduce paper usage, and create compact PDF outputs. +Abstract: Learn how to transform PDF page layouts using Aspose.PDF for Python. This guide explains how to generate booklet-style documents and create N-Up layouts that place multiple pages on a single sheet. These techniques help optimize documents for printing, reduce paper usage, and create compact PDF outputs. --- Booklet and N-Up features help prepare PDF documents for printing and compact page presentation. These workflows rearrange page order or place multiple source pages on a single sheet, which is useful for handouts, drafts, and print-ready booklet output. diff --git a/en/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md b/en/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md index 5113e39f4..317f2fde0 100644 --- a/en/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Create an N-Up PDF Layout in Python -Abstract: Learn how to generate an N-Up PDF layout using Aspose.PDF for Python. This example demonstrates how to combine multiple pages of a PDF document onto a single page using the 'make_n_up' or 'try_make_n_up' method of the PdfFileEditor class. +Abstract: Learn how to generate an N-Up PDF layout using Aspose.PDF for Python. This example demonstrates how to combine multiple pages of a PDF document onto a single page using the 'make_n_up' or 'try_make_n_up' method of the PdfFileEditor class. --- An N-Up layout places multiple pages of a PDF document onto a single page in a grid format. This layout is often used for printing presentations, handouts, or reports where multiple pages can be viewed at once. diff --git a/en/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md b/en/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md index 47672a5e5..e95305b4c 100644 --- a/en/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Create a PDF Booklet from an Existing PDF Using Python -Abstract: Learn how to generate a booklet-style PDF from an existing document using Aspose.PDF for Python. This example demonstrates how to use the PdfFileEditor class to rearrange pages so they can be printed and folded as a booklet. The method automatically orders pages to produce a proper booklet layout. +Abstract: Learn how to generate a booklet-style PDF from an existing document using Aspose.PDF for Python. This example demonstrates how to use the PdfFileEditor class to rearrange pages so they can be printed and folded as a booklet. The method automatically orders pages to produce a proper booklet layout. --- Creating booklet-style documents is a common requirement when preparing PDFs for printing. In a booklet layout, pages are rearranged so that when printed and folded, they appear in the correct order. diff --git a/en/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md b/en/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md index 7fce13eb9..def76f3da 100644 --- a/en/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Edit PDF Page Layout in Python - Add Margins, Resize Content, and Insert Page Breaks -Abstract: Learn how to modify PDF page layouts using Aspose.PDF for Python. This guide explains how to add margins to specific pages, resize page contents, and insert page breaks programmatically. These features allow developers to adjust document formatting, improve readability, and prepare PDFs for printing or structured layouts. +Abstract: Learn how to modify PDF page layouts using Aspose.PDF for Python. This guide explains how to add margins to specific pages, resize page contents, and insert page breaks programmatically. These features allow developers to adjust document formatting, improve readability, and prepare PDFs for printing or structured layouts. --- - [Add Margins to PDF Pages](/pdf/python-net/add-margins-to-pdf-pages/) diff --git a/en/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md b/en/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md index 133a90c23..bde8deb66 100644 --- a/en/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Add Custom Margins to Specific PDF Pages in Python -Abstract: Learn how to add custom margins to selected pages of a PDF using Aspose.PDF for Python. This example demonstrates how to expand page boundaries by specifying top, bottom, left, and right margins for individual pages, making PDFs more printable or visually consistent. +Abstract: Learn how to add custom margins to selected pages of a PDF using Aspose.PDF for Python. This example demonstrates how to expand page boundaries by specifying top, bottom, left, and right margins for individual pages, making PDFs more printable or visually consistent. --- Adding margins to PDF pages can enhance readability, prepare documents for printing, or allocate space for annotations. Using Aspose.PDF for Python, developers can programmatically add margins to specific pages of a PDF without modifying the content layout. diff --git a/en/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md b/en/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md index c60ecceb8..ae497c2d1 100644 --- a/en/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Add Page Breaks to PDF Pages Programmatically in Python -Abstract: Learn how to insert page breaks into a PDF document using Aspose.PDF for Python. This example demonstrates how to split a page at a specified vertical position, allowing developers to reorganize content and create additional pages dynamically. +Abstract: Learn how to insert page breaks into a PDF document using Aspose.PDF for Python. This example demonstrates how to split a page at a specified vertical position, allowing developers to reorganize content and create additional pages dynamically. --- Page breaks are useful when you need to split long PDF pages into multiple pages or control how content is distributed across a document. Using Aspose.PDF for Python, developers can insert page breaks at specific positions without manually editing the PDF. diff --git a/en/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md b/en/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md index b2c97d7c7..99c228ade 100644 --- a/en/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md @@ -8,8 +8,8 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true -AlternativeHeadline: Resize PDF Page Contents Programmatically in Python +TechArticle: true +AlternativeHeadline: Resize PDF Page Contents Programmatically in Python Abstract: Learn how to resize the contents of specific PDF pages using Aspose.PDF for Python. This example demonstrates how to adjust the width and height of page content while preserving the document structure, making it easier to optimize layouts for printing or viewing. --- diff --git a/en/python-net/working-with-facades/pdffileeditor/page-managment/_index.md b/en/python-net/working-with-facades/pdffileeditor/page-managment/_index.md index bf9d051f4..f87ad82e0 100644 --- a/en/python-net/working-with-facades/pdffileeditor/page-managment/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/page-managment/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Programmatically Manage PDF Pages in Python - Extract, Delete, Insert, and Append -Abstract: Learn how to perform page-level operations on PDF documents using Aspose.PDF for Python. This guide demonstrates how to extract specific pages, delete unwanted pages, insert pages from another PDF, and append pages to an existing document, enabling efficient and automated PDF page management. +Abstract: Learn how to perform page-level operations on PDF documents using Aspose.PDF for Python. This guide demonstrates how to extract specific pages, delete unwanted pages, insert pages from another PDF, and append pages to an existing document, enabling efficient and automated PDF page management. --- Page management tasks are central to many PDF workflows. With Aspose.PDF for Python, you can reorganize document structure, remove unnecessary pages, and combine content from multiple PDFs while keeping the original page content intact. diff --git a/en/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md b/en/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md index 81b1126d6..df1d93fc8 100644 --- a/en/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Append Pages from One PDF to Another in Python -Abstract: Learn how to append pages from one PDF document to another using Aspose.PDF for Python. This example demonstrates how to use the PdfFileEditor class to combine pages from multiple PDFs and create a single output document. +Abstract: Learn how to append pages from one PDF document to another using Aspose.PDF for Python. This example demonstrates how to use the PdfFileEditor class to combine pages from multiple PDFs and create a single output document. --- Combining pages from different PDF documents is a common requirement in document processing workflows. Using Aspose.PDF for Python, developers can easily append pages from one or more PDF files to an existing document. diff --git a/en/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md b/en/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md index 2f02db15c..b12ad112b 100644 --- a/en/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Delete Specific Pages from a PDF Document in Python -Abstract: Learn how to remove selected pages from a PDF document using Aspose.PDF for Python. This example demonstrates how to delete specific pages from an existing PDF file programmatically, creating a new document without the removed pages. +Abstract: Learn how to remove selected pages from a PDF document using Aspose.PDF for Python. This example demonstrates how to delete specific pages from an existing PDF file programmatically, creating a new document without the removed pages. --- Sometimes PDF documents contain unnecessary or sensitive pages that need to be removed. Using Aspose.PDF for Python, developers can programmatically delete specific pages from a PDF without manually editing the file. diff --git a/en/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md b/en/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md index 88c74dcc5..9d011f336 100644 --- a/en/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Extract Specific Pages from a PDF Document in Python -Abstract: Learn how to extract selected pages from a PDF document using Aspose.PDF for Python. This example demonstrates how to create a new PDF containing only the pages you need, enabling custom document creation and page-level manipulation. +Abstract: Learn how to extract selected pages from a PDF document using Aspose.PDF for Python. This example demonstrates how to create a new PDF containing only the pages you need, enabling custom document creation and page-level manipulation. --- Extracting pages from a PDF is useful when you need to create a subset of a document, share only specific content, or reorganize PDFs for presentations, reports, or printing. Using Aspose.PDF for Python, developers can programmatically extract pages from a PDF file and save them as a new document. diff --git a/en/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md b/en/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md index 412614225..40ce4008c 100644 --- a/en/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Insert Pages from Another PDF into an Existing PDF in Python -Abstract: Learn how to insert pages from one PDF into another using Aspose.PDF for Python. This example demonstrates how to add selected pages from a secondary PDF into a specific position of the original document, creating a combined PDF with precise page placement. +Abstract: Learn how to insert pages from one PDF into another using Aspose.PDF for Python. This example demonstrates how to add selected pages from a secondary PDF into a specific position of the original document, creating a combined PDF with precise page placement. --- Inserting pages into an existing PDF is a common requirement when combining documents, adding content, or reorganizing reports. Using Aspose.PDF for Python, developers can programmatically insert pages from one PDF into another at a specified location. diff --git a/en/python-net/working-with-facades/pdffileeditor/page-merging/_index.md b/en/python-net/working-with-facades/pdffileeditor/page-merging/_index.md index 2e1ee772e..e1127a56e 100644 --- a/en/python-net/working-with-facades/pdffileeditor/page-merging/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/page-merging/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Combine PDF Files in Python - Merge Two or Multiple PDFs with Aspose.PDF -Abstract: Learn how to concatenate PDF files programmatically using Aspose.PDF for Python. This guide demonstrates methods for merging two or multiple PDFs, handling large numbers of files, optimizing output, and concatenating PDF forms with unique suffixes to avoid naming conflicts. +Abstract: Learn how to concatenate PDF files programmatically using Aspose.PDF for Python. This guide demonstrates methods for merging two or multiple PDFs, handling large numbers of files, optimizing output, and concatenating PDF forms with unique suffixes to avoid naming conflicts. --- - [Concatenate Two PDF Files](/pdf/python-net/concatenate-two-files/) diff --git a/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md b/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md index dfa675581..d4f19dc9f 100644 --- a/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Concatenate Large PDF Files in Python Using Disk Buffering -Abstract: Learn how to merge a large number of PDF files efficiently using Aspose.PDF for Python. This example demonstrates how to enable disk buffering to handle large PDFs without exhausting system memory, ensuring smooth concatenation of many files. +Abstract: Learn how to merge a large number of PDF files efficiently using Aspose.PDF for Python. This example demonstrates how to enable disk buffering to handle large PDFs without exhausting system memory, ensuring smooth concatenation of many files. --- When working with large collections of PDF files, memory consumption can become a bottleneck during concatenation. Using Aspose.PDF for Python, you can enable disk buffering in the [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) class to merge many PDFs efficiently. The concatenate method combines the input files into a single PDF while the disk buffer prevents high memory usage. This approach is ideal for processing bulk documents, automated report generation, or consolidating large PDF archives. diff --git a/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md b/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md index 3b74e7502..4556c36da 100644 --- a/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Merge PDF Files with Optimized Output in Python -Abstract: Learn how to concatenate multiple PDF files into a single optimized PDF using Aspose.PDF for Python. This example demonstrates how to enable size optimization to reduce the output file size while preserving content and formatting. +Abstract: Learn how to concatenate multiple PDF files into a single optimized PDF using Aspose.PDF for Python. This example demonstrates how to enable size optimization to reduce the output file size while preserving content and formatting. --- When merging multiple PDFs, the resulting file can become large, especially if it contains images or complex content. Using Aspose.PDF for Python, developers can enable optimization during concatenation to reduce file size without losing quality. The optimize_size property in the [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) class ensures that the merged PDF is compact and efficient, making it suitable for sharing, storage, or archiving. diff --git a/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md b/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md index 09234e58f..4f0c1de44 100644 --- a/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Merge Multiple PDF Files into One PDF in Python -Abstract: Learn how to combine multiple PDF files into a single document using Aspose.PDF for Python. This example demonstrates how to use the concatenate method to merge several PDFs seamlessly while preserving their content and formatting. +Abstract: Learn how to combine multiple PDF files into a single document using Aspose.PDF for Python. This example demonstrates how to use the concatenate method to merge several PDFs seamlessly while preserving their content and formatting. --- Merging PDF files is a common task in document management, reporting, and automated workflows. Using Aspose.PDF for Python, developers can easily combine multiple PDF files into a single consolidated document. The concatenate method of the [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) class ensures that all pages from the input files are preserved in the final output, maintaining their original layout and content. This approach is useful for creating comprehensive reports, combining forms, or archiving multiple documents efficiently. diff --git a/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md b/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md index 8e270259e..ff6295f5d 100644 --- a/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Merge PDF Forms in Python While Avoiding Field Name Conflicts -Abstract: Learn how to concatenate multiple PDF forms using Aspose.PDF for Python while ensuring unique form field names. This example demonstrates how to set a custom suffix to prevent naming conflicts when merging PDFs that contain interactive form fields. +Abstract: Learn how to concatenate multiple PDF forms using Aspose.PDF for Python while ensuring unique form field names. This example demonstrates how to set a custom suffix to prevent naming conflicts when merging PDFs that contain interactive form fields. --- Merging PDF forms can lead to conflicts if multiple files contain fields with the same name. Using Aspose.PDF for Python, developers can assign a unique suffix to form fields during concatenation. The unique_suffix property in the [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) class automatically renames conflicting fields, preserving interactivity and ensuring that all form data remains functional. This approach is ideal for combining surveys, applications, or any interactive PDF documents programmatically. diff --git a/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md b/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md index 62c1a6779..9f9fdfc17 100644 --- a/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Merge Two PDF Files into a Single PDF in Python -Abstract: Learn how to concatenate two PDF files into a single document using Aspose.PDF for Python. This example demonstrates how to merge two PDFs seamlessly while preserving their original content and formatting. +Abstract: Learn how to concatenate two PDF files into a single document using Aspose.PDF for Python. This example demonstrates how to merge two PDFs seamlessly while preserving their original content and formatting. --- Combining two PDF files is a common task when consolidating reports, contracts, or forms. Using Aspose.PDF for Python, you can programmatically merge two PDFs into a single document using the concatenate method of the [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) class. This ensures that all pages from both files are included in the output PDF while maintaining the original layout, content, and structure. diff --git a/en/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md b/en/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md index 49bea1194..cb68f8527 100644 --- a/en/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Safely Merge PDF Files in Python with Error Handling -Abstract: Learn how to safely concatenate multiple PDF files using Aspose.PDF for Python. The try_concatenate method attempts to merge the PDFs without throwing exceptions, allowing developers to handle failures gracefully. +Abstract: Learn how to safely concatenate multiple PDF files using Aspose.PDF for Python. The try_concatenate method attempts to merge the PDFs without throwing exceptions, allowing developers to handle failures gracefully. --- Merging PDF files can sometimes fail due to corrupted files, incompatible formats, or other issues. Using Aspose.PDF for Python, you can use the try_concatenate method of the [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) class to safely attempt concatenation. Instead of raising an exception, the method returns False if the operation fails, enabling controlled error handling in automated workflows. diff --git a/en/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md b/en/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md index 29d09e9a4..dcabfa451 100644 --- a/en/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Safely Merge Two PDF Files in Python Without Exceptions -Abstract: Learn how to safely concatenate two PDF files using Aspose.PDF for Python. The try_concatenate method merges the files without raising exceptions, allowing for graceful error handling in case the operation fails. +Abstract: Learn how to safely concatenate two PDF files using Aspose.PDF for Python. The try_concatenate method merges the files without raising exceptions, allowing for graceful error handling in case the operation fails. --- Merging two PDF files can sometimes fail due to file corruption, incompatible formats, or other issues. Using Aspose.PDF for Python, the try_concatenate method of the PdfFileEditor class allows you to attempt merging two PDFs safely. If the operation fails, it returns False instead of raising an exception, giving you full control over error handling in automated workflows or batch processing. diff --git a/en/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md b/en/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md index 45cde93ab..d6a69cda5 100644 --- a/en/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Split PDF Documents in Python - From Beginning, to End, or Into Single File -Abstract: Learn how to split PDF documents programmatically using Aspose.PDF for Python. This guide demonstrates methods to extract pages from the beginning or end, divide a PDF into multiple documents, or split it into single-page PDFs for flexible document management. +Abstract: Learn how to split PDF documents programmatically using Aspose.PDF for Python. This guide demonstrates methods to extract pages from the beginning or end, divide a PDF into multiple documents, or split it into single-page PDFs for flexible document management. --- Splitting PDF documents is useful when you need to extract selected sections, distribute individual pages, or break large files into smaller units for storage and processing. Aspose.PDF for Python provides several `PdfFileEditor` methods to handle these scenarios efficiently. diff --git a/en/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md b/en/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md index a6de1e485..612bc313b 100644 --- a/en/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Split PDF from the Start in Python Using Aspose.PDF -Abstract: Learn how to split a PDF document from the beginning using Aspose.PDF for Python. This example demonstrates extracting a specific number of pages starting from the first page to create a new PDF document. +Abstract: Learn how to split a PDF document from the beginning using Aspose.PDF for Python. This example demonstrates extracting a specific number of pages starting from the first page to create a new PDF document. --- Splitting PDFs from the beginning is useful when you need the first few pages of a document as a separate file. Using Aspose.PDF for Python, the split_from_first method in the [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) class allows you to extract a defined number of pages starting from page one. This feature is ideal for generating excerpts, previews, or smaller sections of a larger PDF without manually editing the original file. diff --git a/en/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md b/en/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md index 5a46a2d25..de5a05076 100644 --- a/en/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Split a PDF into Individual Pages in Python Abstract: Learn how to divide a PDF document into single-page PDFs using Aspose.PDF for Python. This method extracts each page from the original PDF and saves it as a separate file for flexible document management and processing. --- diff --git a/en/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md b/en/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md index bc839d0b3..1853e6549 100644 --- a/en/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md +++ b/en/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-05" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Split a PDF from a Specific Page to the End in Python -Abstract: Learn how to split a PDF document from a given page to the last page using Aspose.PDF for Python. This example demonstrates extracting all pages starting from a specified page to create a new PDF file. +Abstract: Learn how to split a PDF document from a given page to the last page using Aspose.PDF for Python. This example demonstrates extracting all pages starting from a specified page to create a new PDF file. --- Splitting a PDF from a specific page to the end is useful when you need the latter portion of a document as a separate file. Using Aspose.PDF for Python, the split_to_end method of the [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) class allows you to extract pages starting from any page number to the last page of the document. This is ideal for creating excerpts, extracting chapters, or processing parts of a large PDF without manually editing it. diff --git a/en/python-net/working-with-facades/pdffileinfo/document-properties/_index.md b/en/python-net/working-with-facades/pdffileinfo/document-properties/_index.md index f2b70b4ac..415e1fc85 100644 --- a/en/python-net/working-with-facades/pdffileinfo/document-properties/_index.md +++ b/en/python-net/working-with-facades/pdffileinfo/document-properties/_index.md @@ -9,9 +9,9 @@ draft: false sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Get PDF Version and Document Privileges Using Aspose.PDF for Python -Abstract: Understanding a PDF’s metadata is essential for processing, compliance, and workflow automation. PDF version numbers indicate the supported features and compatibility, while document privileges control actions like printing, copying content, modifying annotations, or filling form fields. This tutorial demonstrates how to use the PdfFileInfo class in Aspose.PDF for Python. +Abstract: Understanding a PDF’s metadata is essential for processing, compliance, and workflow automation. PDF version numbers indicate the supported features and compatibility, while document privileges control actions like printing, copying content, modifying annotations, or filling form fields. This tutorial demonstrates how to use the PdfFileInfo class in Aspose.PDF for Python. --- - [Get PDF Version](/pdf/python-net/get-pdf-version/) diff --git a/en/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md b/en/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md index a78a973b6..0bd694326 100644 --- a/en/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md +++ b/en/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md @@ -9,9 +9,9 @@ draft: false sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Retrieve PDF Document Privileges Using Aspose.PDF for Python -Abstract: PDF documents can have security restrictions that limit actions like printing, copying, modifying, or filling forms. By accessing these privileges programmatically, developers can determine what operations are allowed on a PDF. This guide shows how to use the PdfFileInfo class to retrieve a PDF’s document privileges and display them in Python. +Abstract: PDF documents can have security restrictions that limit actions like printing, copying, modifying, or filling forms. By accessing these privileges programmatically, developers can determine what operations are allowed on a PDF. This guide shows how to use the PdfFileInfo class to retrieve a PDF’s document privileges and display them in Python. --- PDF privileges control what users can and cannot do with a document. Common permissions include: diff --git a/en/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md b/en/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md index bd29ae7ed..e477fef90 100644 --- a/en/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md +++ b/en/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md @@ -9,9 +9,9 @@ draft: false sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Retrieve PDF Version Using Aspose.PDF for Python -Abstract: PDF documents have version numbers that indicate the features and specifications they support (e.g., 1.4, 1.7, 2.0). Knowing the PDF version is important for compatibility, feature support, and document processing workflows. In this guide, you will learn how to retrieve the PDF version programmatically using the PdfFileInfo class in Aspose.PDF for Python. +Abstract: PDF documents have version numbers that indicate the features and specifications they support (e.g., 1.4, 1.7, 2.0). Knowing the PDF version is important for compatibility, feature support, and document processing workflows. In this guide, you will learn how to retrieve the PDF version programmatically using the PdfFileInfo class in Aspose.PDF for Python. --- PDF versions define the features and capabilities supported in a document, including form fields, encryption, annotations, and compression. For developers working with multiple PDFs, checking the version ensures compatibility with tools, libraries, or workflows that process these files. diff --git a/en/python-net/working-with-facades/pdffileinfo/page-information/_index.md b/en/python-net/working-with-facades/pdffileinfo/page-information/_index.md index 94479f43b..58378e1bf 100644 --- a/en/python-net/working-with-facades/pdffileinfo/page-information/_index.md +++ b/en/python-net/working-with-facades/pdffileinfo/page-information/_index.md @@ -9,9 +9,9 @@ draft: false sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Retrieve PDF Page Information and Offsets -Abstract: PDF pages may differ in size, rotation, and internal content positioning. The Get Page Information and Get Page Offset functions provide developers with a complete view of each page’s layout. Get Page Information returns page width, height, and rotation, while Get Page Offset retrieves the X and Y offsets in inches. Together, these methods allow precise alignment of text, images, annotations, and other content, supporting both single-page and multi-page automated workflows. +Abstract: PDF pages may differ in size, rotation, and internal content positioning. The Get Page Information and Get Page Offset functions provide developers with a complete view of each page’s layout. Get Page Information returns page width, height, and rotation, while Get Page Offset retrieves the X and Y offsets in inches. Together, these methods allow precise alignment of text, images, annotations, and other content, supporting both single-page and multi-page automated workflows. --- - [Get Page Info](/pdf/python-net/get-page-info/) diff --git a/en/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md b/en/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md index e6c3fc145..a66c2c9be 100644 --- a/en/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md +++ b/en/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md @@ -9,9 +9,9 @@ draft: false sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Get PDF Page Information Using Aspose.PDF for Python -Abstract: The function extracts the width, height, rotation, and horizontal (X) and vertical (Y) offsets of a PDF page. These properties are returned in points and reflect the page’s physical size and content positioning within the PDF. The function prints the retrieved values, allowing developers to understand page layout and orientation for further PDF manipulation. +Abstract: The function extracts the width, height, rotation, and horizontal (X) and vertical (Y) offsets of a PDF page. These properties are returned in points and reflect the page’s physical size and content positioning within the PDF. The function prints the retrieved values, allowing developers to understand page layout and orientation for further PDF manipulation. --- The 'get_page_information' utility function helps developers understand the structure and layout of PDF pages. Every PDF page may have different dimensions, rotation, and internal offsets, which can impact content placement or automation tasks. diff --git a/en/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md b/en/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md index cff350bce..6a376e786 100644 --- a/en/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md +++ b/en/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md @@ -9,9 +9,9 @@ draft: false sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Get PDF Page Offsets using Python -Abstract: The 'get_page_offsets' function extracts the horizontal (X) and vertical (Y) offsets of each page in a PDF file. These offsets represent the position of the page content relative to the PDF's origin. By converting points to inches, the function provides precise, human-readable measurements that can be used for accurate placement of annotations, images, or text. It supports multi-page PDFs and is intended for developers working on PDF layout, automation, or content alignment tasks. +Abstract: The 'get_page_offsets' function extracts the horizontal (X) and vertical (Y) offsets of each page in a PDF file. These offsets represent the position of the page content relative to the PDF's origin. By converting points to inches, the function provides precise, human-readable measurements that can be used for accurate placement of annotations, images, or text. It supports multi-page PDFs and is intended for developers working on PDF layout, automation, or content alignment tasks. --- The 'get_page_offsets' function provides developers with the exact horizontal (X) and vertical (Y) offsets of pages in a PDF file. In PDF documents, each page may have an internal origin point that differs from the top-left corner of the page, which can affect the positioning of text, images, annotations, or other content. diff --git a/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md b/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md index 777db94c8..2efdf6f7e 100644 --- a/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md +++ b/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md @@ -9,9 +9,9 @@ draft: false sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Manage PDF Metadata in Python -Abstract: PDF metadata contains information about a document, such as title, author, keywords, and creation date, which aids in cataloging, searching, and maintaining document integrity. Using Aspose.PDF, developers can programmatically Get PDF Metadata, Set PDF Metadata values, Clear PDF Metadata, and save the changes either in standard PDF metadata or XMP format. This comprehensive approach allows precise control over document properties and ensures consistent handling across workflows and applications. +Abstract: PDF metadata contains information about a document, such as title, author, keywords, and creation date, which aids in cataloging, searching, and maintaining document integrity. Using Aspose.PDF, developers can programmatically Get PDF Metadata, Set PDF Metadata values, Clear PDF Metadata, and save the changes either in standard PDF metadata or XMP format. This comprehensive approach allows precise control over document properties and ensures consistent handling across workflows and applications. --- - [Get PDF Metadata](/pdf/python-net/get-pdf-metadata/) diff --git a/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md b/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md index bc9ec8e78..f866e6efa 100644 --- a/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md +++ b/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md @@ -9,7 +9,7 @@ draft: false sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Clearing PDF Metadata Using Aspose.PDF for Python Abstract: This guide explains how to remove all metadata from a PDF document using Aspose.PDF for Python via .NET. You will learn to clear both standard and custom metadata fields and save the sanitized PDF. This is useful for privacy, security, or preparing PDFs for public release. --- diff --git a/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md b/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md index f5ed93105..369772291 100644 --- a/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md +++ b/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md @@ -9,9 +9,9 @@ draft: false sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Retrieving PDF Metadata Using Aspose.PDF for Python. -Abstract: This guide demonstrates how to extract and display metadata from PDF documents using Aspose.PDF for Python. You will learn to access standard PDF properties such as title, author, keywords, creation/modification dates, as well as custom metadata fields. Additionally, the guide covers checks for PDF validity, encryption, and portfolio status. +Abstract: This guide demonstrates how to extract and display metadata from PDF documents using Aspose.PDF for Python. You will learn to access standard PDF properties such as title, author, keywords, creation/modification dates, as well as custom metadata fields. Additionally, the guide covers checks for PDF validity, encryption, and portfolio status. --- PDF documents often contain valuable metadata that describes document content, authorship, and permissions. Aspose.PDF provides a convenient API to retrieve both standard and custom metadata properties. This code snippet how to use the [PdfFileInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileinfo/) class to inspect PDF files programmatically, including step-by-step examples in Python. diff --git a/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md b/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md index e34602407..2e4e76835 100644 --- a/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md +++ b/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md @@ -9,9 +9,9 @@ draft: false sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Saving PDF Metadata with XMP Using Aspose.PDF for Python -Abstract: This guide demonstrates how to save PDF metadata using XMP (Extensible Metadata Platform) with Aspose.PDF for Python via .NET. XMP ensures that both standard and custom metadata are embedded in a standardized XML format inside the PDF, improving compatibility across applications and workflows. +Abstract: This guide demonstrates how to save PDF metadata using XMP (Extensible Metadata Platform) with Aspose.PDF for Python via .NET. XMP ensures that both standard and custom metadata are embedded in a standardized XML format inside the PDF, improving compatibility across applications and workflows. --- PDF metadata can be stored in multiple ways, and XMP is the modern, standardized method for embedding metadata inside a PDF file. Using Aspose.PDF, you can update standard fields like Title, Subject, Keywords, and Creator, and then save them in XMP format to ensure wider compatibility and future-proofing. This method is recommended over legacy metadata storage methods. diff --git a/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md b/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md index 67c03f34e..5ece849a3 100644 --- a/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md +++ b/en/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md @@ -9,7 +9,7 @@ draft: false sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Updating PDF Metadata Using Aspose.PDF for Python Abstract: This guide explains how to modify and save metadata in PDF documents using Aspose.PDF for Python via .NET. It demonstrates how to update standard PDF properties like title, subject, keywords, and creator, as well as custom metadata fields. By the end, you’ll be able to programmatically update PDF metadata and save the changes. --- diff --git a/en/python-net/working-with-facades/pdffilesecurity/change-password/_index.md b/en/python-net/working-with-facades/pdffilesecurity/change-password/_index.md index 50e9020be..fce8ae3ee 100644 --- a/en/python-net/working-with-facades/pdffilesecurity/change-password/_index.md +++ b/en/python-net/working-with-facades/pdffilesecurity/change-password/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-03-18" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Update PDF Passwords Abstract: Learn how to change both user and owner passwords in a secured PDF file using Aspose.PDF for Python via .NET. This example demonstrates how to safely update access credentials while keeping the existing encryption and permissions intact. --- diff --git a/en/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md b/en/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md index 4e9c1ed95..567b9da9b 100644 --- a/en/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md +++ b/en/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-03-18" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Remove Password Protection from a PDF Abstract: This article demonstrates how to decrypt a PDF file using an owner password. It covers the process of removing security restrictions that limit actions like printing, editing, or copying content. By applying the correct owner password, users can unlock the document and regain full control over its functionality. --- diff --git a/en/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md b/en/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md index 0dcbdbfa9..ce7c33d58 100644 --- a/en/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md +++ b/en/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-18" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Encrypt PDF and Control User Actions -Abstract: Learn how to encrypt a PDF while defining specific user permissions using Aspose.PDF for Python via .NET. This guide shows how to allow or restrict actions such as printing and copying while keeping the document secure. +Abstract: Learn how to encrypt a PDF while defining specific user permissions using Aspose.PDF for Python via .NET. This guide shows how to allow or restrict actions such as printing and copying while keeping the document secure. --- ## Encrypt PDF with User and Owner Password diff --git a/en/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md b/en/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md index e71bdfdad..58c62b5ab 100644 --- a/en/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md +++ b/en/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md @@ -8,9 +8,9 @@ lastmod: "2026-03-18" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Manage PDF Permissions and Access Controls -Abstract: Learn how to control what users can do with a PDF by setting document privileges using Aspose.PDF for Python via .NET. This guide covers applying permissions with or without passwords to restrict actions such as printing, copying, or editing. +Abstract: Learn how to control what users can do with a PDF by setting document privileges using Aspose.PDF for Python via .NET. This guide covers applying permissions with or without passwords to restrict actions such as printing, copying, or editing. --- ## Set PDF Privileges Without Passwords diff --git a/en/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md b/en/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md index 8746d9d04..306e3d68f 100644 --- a/en/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md +++ b/en/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-04-02" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Certify PDF Documents with DocMDP Permissions in Python Abstract: This article explains how to certify PDF documents with Aspose.PDF for Python via .NET using the PdfFileSignature facade. It shows how to create a DocMDPSignature, apply certification with form-filling permissions, and lock a document with a no-changes certification level. --- diff --git a/en/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md b/en/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md index 63e3a91cd..2a6864633 100644 --- a/en/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md +++ b/en/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-04-14" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Sign PDF Documents with Digital Signatures in Python Abstract: This article shows how to sign PDF documents with Aspose.PDF for Python via .NET using the PdfFileSignature facade. It covers certificate configuration, signing with basic parameters, signing with a PKCS7 object, assigning a signature name, and applying a visible signature appearance. --- diff --git a/en/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md b/en/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md index ab0d3351a..5dac333a0 100644 --- a/en/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md +++ b/en/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-04-02" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Read PDF Signature Revision and Access Permission Data in Python Abstract: This article explains how to inspect revision and permission information in signed or certified PDF files with Aspose.PDF for Python via .NET. It shows how to get the revision number of a signature, count total document revisions, and read access permissions from a certified PDF. --- diff --git a/en/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md b/en/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md index ba8b138c4..1b2f849f3 100644 --- a/en/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md +++ b/en/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-04-02" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Extract Signature Image and Certificate from PDF in Python Abstract: This article explains how to extract signature-related data from signed PDF documents with Aspose.PDF for Python via .NET. It shows how to read the first available signature, export its image, and save the associated certificate stream to an output file. --- diff --git a/en/python-net/working-with-facades/pdffilesignature/signature-information/_index.md b/en/python-net/working-with-facades/pdffilesignature/signature-information/_index.md index a8ad88047..22ed3bd39 100644 --- a/en/python-net/working-with-facades/pdffilesignature/signature-information/_index.md +++ b/en/python-net/working-with-facades/pdffilesignature/signature-information/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-04-02" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Read Signature Details from PDF Documents in Python Abstract: This article explains how to inspect signature metadata in signed PDF documents with Aspose.PDF for Python via .NET. It shows how to list signature names, read signer details, get the signing date and time, and extract the signature reason and location. --- diff --git a/en/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md b/en/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md index f3e65ac3d..3c1c06faf 100644 --- a/en/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md +++ b/en/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-04-02" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Validate PDF Signature Coverage and Integrity in Python Abstract: This article explains how to inspect digital signature integrity in signed PDF documents with Aspose.PDF for Python via .NET. It shows how to verify whether a signature covers the whole document and how to validate the integrity of the signed content. --- diff --git a/en/python-net/working-with-facades/pdffilesignature/signature-management/_index.md b/en/python-net/working-with-facades/pdffilesignature/signature-management/_index.md index a4334f356..82e50fbc8 100644 --- a/en/python-net/working-with-facades/pdffilesignature/signature-management/_index.md +++ b/en/python-net/working-with-facades/pdffilesignature/signature-management/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-04-02" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Remove PDF Signatures and Clean Up Signature Fields in Python Abstract: This article explains how to manage existing digital signatures in PDF documents with Aspose.PDF for Python via .NET. It shows how to remove a signature from a PDF and how to remove a signature together with its associated signature field. --- diff --git a/en/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md b/en/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md index 60b518a9a..132639b3a 100644 --- a/en/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md +++ b/en/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-04-02" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Verify PDF Signatures in Python Abstract: This article explains how to verify digital signatures in PDF documents with Aspose.PDF for Python via .NET. It shows how to validate an existing signature and how to check whether a PDF contains any signatures. --- diff --git a/en/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md b/en/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md index a78c4227e..b402549fc 100644 --- a/en/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md +++ b/en/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md @@ -8,7 +8,7 @@ lastmod: "2026-04-02" sitemap: changefreq: "weekly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Remove PDF Usage Rights in Python Abstract: This article explains how to inspect and remove usage rights from PDF documents with Aspose.PDF for Python via .NET. It shows how to check whether a PDF contains usage rights and how to save a new version of the document after those rights are removed. --- diff --git a/en/python-net/working-with-facades/pdffilestamp/add-footer/_index.md b/en/python-net/working-with-facades/pdffilestamp/add-footer/_index.md index a1d9a8636..e71fc5c12 100644 --- a/en/python-net/working-with-facades/pdffilestamp/add-footer/_index.md +++ b/en/python-net/working-with-facades/pdffilestamp/add-footer/_index.md @@ -5,7 +5,7 @@ weight: 10 url: /python-net/add-footer/ description: Learn how to add text and image footers to PDF pages using PdfFileStamp in Python. lastmod: "2026-04-13" -TechArticle: true +TechArticle: true AlternativeHeadline: Add Text and Image Footers to PDF in Python Abstract: This article explains how to add footer content to PDF documents with Aspose.PDF for Python via .NET using the PdfFileStamp facade. It shows how to add a text footer, place an image footer, and apply custom footer margins before saving the updated PDF. --- diff --git a/en/python-net/working-with-facades/pdffilestamp/add-header/_index.md b/en/python-net/working-with-facades/pdffilestamp/add-header/_index.md index 5f4043bbf..42fe9f59f 100644 --- a/en/python-net/working-with-facades/pdffilestamp/add-header/_index.md +++ b/en/python-net/working-with-facades/pdffilestamp/add-header/_index.md @@ -5,7 +5,7 @@ weight: 20 url: /python-net/add-header/ description: Learn how to add text and image headers to PDF pages using PdfFileStamp in Python. lastmod: "2026-04-13" -TechArticle: true +TechArticle: true AlternativeHeadline: Add Text and Image Headers to PDF in Python Abstract: This article explains how to add header content to PDF documents with Aspose.PDF for Python via .NET using the PdfFileStamp facade. It shows how to add a text header, place an image header, and apply custom header margins before saving the updated PDF. --- diff --git a/en/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md b/en/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md index cfb46a733..3ce7a06ed 100644 --- a/en/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md +++ b/en/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md @@ -5,7 +5,7 @@ weight: 30 url: /python-net/page-number/ description: Learn how to add page numbers to PDF documents using PdfFileStamp in Python. lastmod: "2026-04-13" -TechArticle: true +TechArticle: true AlternativeHeadline: Add Page Numbers to PDF in Python Abstract: This article explains how to add page numbers to PDF documents with Aspose.PDF for Python via .NET using the PdfFileStamp facade. It shows how to add page numbers with the default placement, position them at custom coordinates, and control alignment and margins. --- diff --git a/en/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md b/en/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md index 3e8e6f62c..8ef994637 100644 --- a/en/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md +++ b/en/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md @@ -5,7 +5,7 @@ weight: 40 url: /python-net/add-stamp/ description: Learn how to add a stamp to PDF pages using PdfFileStamp in Python. lastmod: "2026-04-13" -TechArticle: true +TechArticle: true AlternativeHeadline: Add Text Stamps to PDF in Python Abstract: This article explains how to add stamp content to PDF documents with Aspose.PDF for Python via .NET using the PdfFileStamp facade. It shows how to create a stamp, position it on the page, control rotation and opacity, and save the updated PDF. --- From 78a1bf8f7cea65cbab56a5e66f6390c0cdda7c8c Mon Sep 17 00:00:00 2001 From: Andriy Andruhovski Date: Tue, 12 May 2026 10:43:09 +0300 Subject: [PATCH 03/13] Update Spanish documentation for PDF operations in Python (#580) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Update Spanish documentation for basic PDF operations, including creating, opening, saving, merging, splitting, and protecting PDF files using Aspose.PDF for Python. * Add text-based and watermark annotation documentation for Python - Created a comprehensive guide on adding, inspecting, and deleting text-based annotations in PDF documents using Aspose.PDF for Python via .NET. - Included examples for free text, highlight, underline, squiggly, and strikeout annotations. - Added documentation for watermark annotations, covering addition, inspection, and deletion processes. * Add documentation for working with PDF actions and links in Python - Created a comprehensive guide on working with PDF actions, including adding, updating, and removing document, page, and form actions using Aspose.PDF for Python. - Introduced sections on creating, extracting, and updating links in PDF documents, detailing how to manage hyperlinks programmatically. - Included code examples for various link actions such as GoTo, GoToRemote, and GoToURI, along with methods for updating link appearances and destinations. - Enhanced navigation and interactivity in PDFs through practical examples and clear explanations. * Add documentation for integrating, manipulating, and removing tables in PDF using Python - Introduced a new article on integrating tables from data sources into existing PDF documents. - Updated the article on manipulating tables in existing PDFs to enhance clarity and structure. - Added a section on removing tables from existing PDFs, including methods for single and multiple table removal. - Created a new article on working with vector graphics in PDFs, detailing extraction, movement, deletion, and copying of vector elements. * Remove outdated documentation on PDF annotations including highlights, import/export, sticky notes, and text annotations in Spanish. * Remove obsolete pages in working-with-text section * Update PDF annotations documentation for Python: revise content, add import/export section, and update last modified dates. * Actualiza la documentación para la conversión de PDF a PowerPoint y Word en Python, mejorando descripciones, ejemplos de código y enlaces a aplicaciones en línea. Cambia el enfoque de PDF/x a PDF/A y PDF/UA, proporcionando ejemplos claros para eliminar el cumplimiento de estándares y guardar como PDF estándar. Se ajustan las fechas de última modificación y se mejora la claridad del contenido. * Add SVG image for Aspose PDF for Python via .NET documentation * Update Spanish documentation for vector graphics and ZUGFeRD operations in Aspose.PDF for Python. Improved descriptions, fixed grammatical issues, and enhanced clarity in code examples. Added TechArticle and Abstract metadata for ZUGFeRD topics. * Add documentation for extracting data from PDF using Aspose.PDF for Python via .NET - Created articles for extracting tables, fonts, images, and text from PDF documents. - Included methods for region-based text extraction and handling special text formats like superscripts and subscripts. - Added techniques for improving text extraction from multi-column PDFs. - Documented vector data extraction methods, including saving graphics to SVG. - Updated the "What's New" page to reflect recent changes in the documentation. * Update last modified dates and improve abstract formatting across multiple documentation files for Aspose.PDF for Python. * Remove Spanish documentation for working with headings in PDF * Update PDF to image conversion documentation for Aspose.PDF in Python via .NET - Revised descriptions and abstracts to clarify the conversion of PDF pages to various image formats including TIFF, BMP, EMF, JPEG, PNG, GIF, and SVG. - Enhanced section headings and content structure for better readability and understanding. - Updated code examples for converting PDF to TIFF, BMP, EMF, JPEG, PNG, GIF, and SVG to reflect best practices and improved clarity. - Corrected links and references to ensure accuracy and consistency throughout the documentation. - Added alerts for online conversion tools to encourage user engagement and testing. * Updated brand name * Update sitemap values * Add translated files (ES) * Add linktitle to various PDF-related documentation pages for improved navigation - Added linktitle to the following pages: - Crear folleto PDF - Diseño de página y márgenes - Agregar márgenes a las páginas PDF - Agregar saltos de página en PDF - Redimensionar el contenido de las páginas PDF - Gestión de páginas - Agregar páginas al PDF - Eliminar páginas de PDF - Extraer páginas de PDF - Insertar páginas en PDF - Combinar archivos PDF - Concatenar gran número de archivos PDF - Concatenar archivos PDF con optimización - Concatenar varios archivos PDF - Concatenar formularios PDF con sufijo único - Concatenar dos archivos PDF - Intentar concatenar archivos PDF - Intente concatenar dos archivos PDF - Dividir documentos PDF - Dividir PDF desde el comienzo - Dividir PDF en páginas individuales - Dividir PDF hasta el final - Clase PdfFileInfo - Propiedades del documento - Obtener privilegios del documento - Obtener versión del PDF - Información de la página - Obtener información de la página - Obtener desplazamiento de página - Metadatos PDF - Borrar metadatos de PDF - Obtener metadatos de PDF - Guardar metadatos con XMP - Establecer metadatos PDF - Clase PdfFileSecurity - Cambiar la contraseña del archivo PDF - Descifrar archivo PDF - Cifrar archivo PDF - Establecer privilegios en un archivo PDF existente - Clase PdfFileSignature - Certificación PDF - Firmar documentos PDF - Revisión y Permisos - Extracción de firma - Informacion de firmas - Comprobaciones de Integridad de Firma - Administracion de firmas - Verificación de firmas - Administracion de derechos de uso - Clase PdfFileStamp - Agregar pie de pagina a PDF - Agregar encabezado a PDF - Agregar numero de pagina a PDF - Agregar sello a PDF - Clase PdfViewer - Clase Stamp --- .../advanced-operations/annotations/_index.md | 27 +- .../add-delete-and-get-annotation/_index.md | 7 +- .../import-export-annotations/_index.md | 0 .../convert-pdf-to-images-format/_index.md | 92 +- es/python-net/_index.md | 47 +- es/python-net/advanced-operations/_index.md | 104 +- .../accessibility-tagged-pdf/_index.md | 27 + .../create-tagged-pdf-documents/_index.md | 519 +++++++ .../_index.md | 152 ++ .../_index.md | 644 ++++++++ .../_index.md | 531 +++++++ .../advanced-operations/annotations/_index.md | 167 +-- .../add-delete-and-get-annotation/_index.md | 160 +- .../extra-annotations/_index.md | 281 ---- .../figures/_index.md | 438 ------ .../hightlights/_index.md | 396 ----- .../interactive-annotations/_index.md | 330 +++++ .../markup-annotations/_index.md | 499 +++++++ .../media-annotations/_index.md | 499 +++++++ .../security-annotations/_index.md | 218 +++ .../shape-annotations/_index.md | 720 +++++++++ .../sticks/_index.md | 154 -- .../text-based-annotations/_index.md | 749 ++++++++++ .../text/_index.md | 334 ----- .../watermark-annotations/_index.md | 186 +++ .../import-export-annotations/_index.md | 102 ++ .../advanced-operations/artifacts/_index.md | 67 + .../artifacts/add-backgrounds/_index.md | 148 ++ .../artifacts/add-bates-numbering/_index.md | 120 ++ .../artifacts/add-watermarks/_index.md | 120 ++ .../artifacts-header-footer/_index.md | 119 ++ .../artifacts/counting-artifacts/_index.md | 58 + .../advanced-operations/attachments/_index.md | 92 +- .../add-attachment-to-pdf-document/_index.md | 116 +- .../attachments/extract-attachment/_index.md | 126 ++ .../attachments/portfolio/_index.md | 224 +-- .../_index.md | 197 +-- .../compare-pdf-documents/_index.md | 189 +++ .../navigation-and-interaction/_index.md | 147 +- .../actions/_index.md | 360 +++++ .../bookmarks/_index.md | 91 +- .../add-and-delete-bookmark/_index.md | 261 ++-- .../get-update-expand-bookmark/_index.md | 202 +-- .../links/_index.md | 23 + .../links/create-links/_index.md | 147 ++ .../links/extract-links/_index.md | 92 ++ .../links/update-links/_index.md | 114 ++ .../pdf-file-metadata/_index.md | 147 ++ .../securing-and-signing/_index.md | 41 + .../digitally-sign-pdf-file/_index.md | 232 +++ .../extract-signature-info/_index.md | 170 +++ .../set-privileges/_index.md | 228 +++ .../_index.md | 131 ++ .../working-with-documents/_index.md | 164 +-- .../create-pdf-document/_index.md | 167 +-- .../formatting-pdf-document/_index.md | 393 ++--- .../manipulate-pdf-document/_index.md | 470 ++---- .../merge-pdf/_index.md | 409 ++++-- .../optimize-pdf-document/_index.md | 482 +++--- .../split-pdf/_index.md | 518 ++++--- .../working-with-headings/_index.md | 218 --- .../working-with-forms/_index.md | 86 +- .../working-with-forms/acroforms/_index.md | 159 +- .../acroforms/create-form/_index.md | 379 +++-- .../acroforms/extract-form/_index.md | 116 +- .../acroforms/fill-form/_index.md | 177 +-- .../import-export-form-data/_index.md | 226 +++ .../acroforms/modifying-form/_index.md | 139 ++ .../acroforms/posting-form/_index.md | 76 + .../acroforms/remove-form/_index.md | 65 + .../working-with-forms/xfa-forms/_index.md | 61 + .../working-with-graphs/_index.md | 43 + .../working-with-graphs/arc/_index.md | 95 ++ .../checking-shape-bounds/_index.md | 72 + .../working-with-graphs/circle/_index.md | 84 ++ .../working-with-graphs/curve/_index.md | 85 ++ .../working-with-graphs/ellipse/_index.md | 113 ++ .../working-with-graphs/line/_index.md | 109 ++ .../working-with-graphs/rectangle/_index.md | 195 +++ .../working-with-images/_index.md | 156 +- .../add-image-to-existing-pdf-file/_index.md | 295 ++-- .../delete-images-from-pdf-file/_index.md | 208 +-- .../extract-images-from-pdf-file/_index.md | 195 +-- .../_index.md | 70 + .../_index.md | 236 +++ .../working-with-layers/_index.md | 220 +++ .../working-with-operators/_index.md | 185 +++ .../working-with-pages/_index.md | 174 +-- .../add-backgrounds/_index.md | 6 +- .../add-page-number/_index.md | 8 +- .../working-with-pages/add-pages/_index.md | 181 +-- .../add-watermarks/_index.md | 4 +- .../_index.md | 567 ++++---- .../change-page-size/_index.md | 258 ++-- .../working-with-pages/crop-pages/_index.md | 229 +-- .../working-with-pages/delete-pages/_index.md | 190 +-- .../extract-pages/_index.md | 64 + .../get-and-set-page-properties/_index.md | 405 ++---- .../working-with-pages/move-pages/_index.md | 213 ++- .../working-with-pages/rotate-pages/_index.md | 179 +-- .../working-with-pages/stamping/_index.md | 149 +- .../stamping/add-page-number/_index.md | 118 ++ .../stamping/add-page-stamp/_index.md | 48 + .../image-stamps-in-pdf-page/_index.md | 265 +--- .../text-stamps-in-pdf-file/_index.md | 270 +--- .../working-with-tables/_index.md | 157 +- .../_index.md | 1076 +++++++++----- .../_index.md | 187 +-- .../_index.md | 103 ++ .../_index.md | 365 +---- .../remove-tables-from-existing-pdf/_index.md | 153 +- .../working-with-text/_index.md | 98 +- .../add-text-to-a-pdf-file/_index.md | 843 ----------- .../add-text-to-pdf-file/_index.md | 937 ++++++++++++ .../add-tooltip-to-text/_index.md | 434 +++--- .../determine-line-break/_index.md | 185 --- .../working-with-text/floating-box/_index.md | 304 ++++ .../replace-text-an-a-pdf/_index.md | 878 ++++++----- .../rotate-text-inside-pdf/_index.md | 565 ++++---- .../seach-and-get-text-from-pdf/_index.md | 835 +++++------ .../text-formatting-inside-pdf/_index.md | 1286 +++++++++++----- .../working-with-vector-graphics/_index.md | 214 +++ .../advanced-operations/zugferd/_index.md | 28 +- .../zugferd/attach-zugferd/_index.md | 68 +- es/python-net/aspose_pdf-for-python-net.png | Bin 0 -> 6589 bytes es/python-net/aspose_pdf-for-python-net.svg | 1 + es/python-net/basic-operations/_index.md | 31 +- .../basic-operations/create/_index.md | 46 +- .../basic-operations/merge-pdf/_index.md | 14 +- .../basic-operations/opening/_index.md | 34 +- .../basic-operations/protect/_index.md | 75 +- .../basic-operations/saving/_index.md | 54 +- .../basic-operations/split-pdf/_index.md | 43 +- es/python-net/converting/_index.md | 63 +- .../converting/convert-html-to-pdf/_index.md | 65 +- .../convert-images-format-to-pdf/_index.md | 336 ++--- .../convert-other-files-to-pdf/_index.md | 396 ++--- .../converting/convert-pdf-to-excel/_index.md | 177 +-- .../converting/convert-pdf-to-html/_index.md | 228 +-- .../convert-pdf-to-images-format/_index.md | 292 ++-- .../convert-pdf-to-other-files/_index.md | 158 +- .../converting/convert-pdf-to-pdfx/_index.md | 291 ++-- .../convert-pdf-to-powerpoint/_index.md | 94 +- .../converting/convert-pdf-to-word/_index.md | 102 +- .../converting/convert-pdfx-to-pdf/_index.md | 69 +- es/python-net/faq/_index.md | 16 + es/python-net/get-started/_index.md | 50 +- .../get-started/complex-pdf/_index.md | 70 +- .../get-started/hello-world-example/_index.md | 61 +- es/python-net/overview/_index.md | 50 +- es/python-net/overview/installation/_index.md | 41 +- es/python-net/overview/key-features/_index.md | 1126 +------------- es/python-net/overview/licensing/_index.md | 26 +- .../overview/supported-file-formats/_index.md | 57 +- .../overview/system-requirements/_index.md | 38 +- .../overview/technical-support/_index.md | 29 +- es/python-net/parsing/_index.md | 20 +- .../extract-data-from-acroform/_index.md | 197 +++ .../extract-data-from-tables/_index.md | 139 ++ .../parsing/extract-fonts-from-pdf/_index.md | 37 + .../parsing/extract-images-from-pdf/_index.md | 37 + .../parsing/extract-text-from-pdf/_index.md | 19 + .../annotations-and-special-text/_index.md | 161 ++ .../basic-text-extraction/_index.md | 78 + .../region-based-extraction/_index.md | 140 ++ .../_index.md | 88 ++ .../extract-vector-data-from-pdf/_index.md | 178 +++ es/python-net/whatsnew/_index.md | 1290 ++++++++++++++--- es/python-net/working-with-facades/_index.md | 60 + .../working-with-facades/form/_index.md | 22 + .../form/button-fields-and-images/_index.md | 86 ++ .../form/exporting-form-data/_index.md | 15 + .../export-to-fdf/_index.md | 43 + .../export-to-json/_index.md | 43 + .../export-to-xfdf/_index.md | 43 + .../export-to-xml/_index.md | 43 + .../extract-xfa-data/_index.md | 42 + .../form/filling-form-fields/_index.md | 16 + .../fill-barcode-fields/_index.md | 44 + .../fill-check-box-fields/_index.md | 45 + .../fill-fields-by-name-and-value/_index.md | 51 + .../fill-list-box/_index.md | 44 + .../fill-radio-button-fields/_index.md | 45 + .../fill-text-fields/_index.md | 46 + .../form/importing-form-data/_index.md | 15 + .../import-fdf-data/_index.md | 46 + .../import-json-data/_index.md | 47 + .../import-xfdf-data/_index.md | 47 + .../import-xml-data/_index.md | 47 + .../replace-xfa-data/_index.md | 47 + .../form/managing-form-fields/_index.md | 13 + .../flatten-all-fields/_index.md | 44 + .../flatten-specific-fields/_index.md | 48 + .../rename-form-fields/_index.md | 47 + .../form/reading-form-values/_index.md | 16 + .../get-field-facades/_index.md | 44 + .../get-field-values/_index.md | 44 + .../get-radio-button-options/_index.md | 43 + .../get-required-field-names/_index.md | 42 + .../get-rich-text-values/_index.md | 43 + .../resolve-full-field-names/_index.md | 43 + .../working-with-facades/formeditor/_index.md | 26 + .../_index.md | 22 + .../add-field-script/_index.md | 57 + .../remove-field-action/_index.md | 51 + .../set-field-script/_index.md | 60 + .../set-submit-flag/_index.md | 47 + .../set-submit-url/_index.md | 57 + .../formeditor/creating-form-field/_index.md | 22 + .../create-checkbox-field/_index.md | 55 + .../create-combobox-field/_index.md | 50 + .../create-listbox-field/_index.md | 50 + .../create-radiobutton-field/_index.md | 50 + .../create-submit-button/_index.md | 55 + .../create-textbox-field/_index.md | 51 + .../customizing-field-appearance/_index.md | 24 + .../decorate-field/_index.md | 56 + .../get-field-appearance/_index.md | 46 + .../set-field-alignment-vertical/_index.md | 57 + .../set-field-alignment/_index.md | 56 + .../set-field-appearance/_index.md | 56 + .../set-field-comb-number/_index.md | 51 + .../set-field-limit/_index.md | 54 + .../modifying-form-fields/_index.md | 25 + .../add-list-item/_index.md | 46 + .../copy-inner-field/_index.md | 72 + .../copy-outer-field/_index.md | 80 + .../del-list-item/_index.md | 51 + .../move-field/_index.md | 48 + .../remove-field/_index.md | 48 + .../rename-field/_index.md | 49 + .../single-to-multiple/_index.md | 49 + .../pdfannotationeditor/_index.md | 22 + .../pdfcontenteditor/_index.md | 32 + .../pdfcontenteditor/annotations/_index.md | 18 + .../add-caret-annotation/_index.md | 59 + .../add-free-text-annotation/_index.md | 48 + .../add-markup-annotation/_index.md | 73 + .../add-popup-annotation/_index.md | 51 + .../annotations/add-text-annotation/_index.md | 62 + .../pdfcontenteditor/attachments/_index.md | 18 + .../add-attachment-from-path/_index.md | 48 + .../attachments/add-attachment/_index.md | 51 + .../add-file-attachment-annotation/_index.md | 52 + .../_index.md | 58 + .../attachments/remove-attachments/_index.md | 45 + .../document-actions/_index.md | 16 + .../add-bookmark-action/_index.md | 53 + .../add-document-action/_index.md | 47 + .../remove-open-action/_index.md | 46 + .../drawing-annotations/_index.md | 19 + .../add-circle-annotation/_index.md | 50 + .../add-curve-annotation/_index.md | 56 + .../add-line-annotation/_index.md | 63 + .../add-polygon-annotation/_index.md | 55 + .../add-polyline-annotation/_index.md | 55 + .../add-square-annotation/_index.md | 50 + .../image-operations/_index.md | 16 + .../delete-all-images/_index.md | 45 + .../image-operations/delete-images/_index.md | 45 + .../image-operations/replace-image/_index.md | 43 + .../links-and-navigation/_index.md | 20 + .../add-application-link/_index.md | 54 + .../add-custom-action-link/_index.md | 55 + .../add-javascript-link/_index.md | 54 + .../add-local-link/_index.md | 54 + .../add-pdf-document-link/_index.md | 55 + .../add-web-link/_index.md | 53 + .../extract-links/_index.md | 61 + .../pdfcontenteditor/multimedia/_index.md | 15 + .../multimedia/add-movie-annotation/_index.md | 46 + .../multimedia/add-sound-annotation/_index.md | 47 + .../stamps-management/_index.md | 23 + .../add-rubber-stamp/_index.md | 53 + .../_index.md | 53 + .../_index.md | 53 + .../delete-stamp-by-ids-examples/_index.md | 69 + .../delete-stamp-by-index/_index.md | 64 + .../delete-stamps-globally/_index.md | 60 + .../stamps-management/list-stamps/_index.md | 53 + .../manage-stamp-by-id/_index.md | 71 + .../move-stamp-by-id-example/_index.md | 56 + .../move-stamp-by-index/_index.md | 71 + .../text-operations/_index.md | 18 + .../replace-text-on-page-with-state/_index.md | 54 + .../replace-text-on-page/_index.md | 48 + .../replace-text-regex/_index.md | 49 + .../replace-text-simple/_index.md | 48 + .../replace-text-with-state/_index.md | 54 + .../viewer-preferences/_index.md | 16 + .../change-viewer-preferences/_index.md | 76 + .../get-viewer-preferences/_index.md | 46 + .../pdffileeditor/_index.md | 31 + .../booklet-and-nup-layout/_index.md | 22 + .../create-n-up-pdf-document/_index.md | 85 ++ .../create-pdf-booklet/_index.md | 82 ++ .../page-layout-and-margins/_index.md | 19 + .../add-margins-to-pdf-pages/_index.md | 52 + .../add-page-breaks-in-pdf/_index.md | 48 + .../resize-pdf-page-contents/_index.md | 51 + .../pdffileeditor/page-managment/_index.md | 26 + .../append-pages-to-pdf/_index.md | 43 + .../delete-pages-from-pdf/_index.md | 47 + .../extract-pages-from-pdf/_index.md | 46 + .../insert-pages-into-pdf/_index.md | 45 + .../pdffileeditor/page-merging/_index.md | 23 + .../concatenate-large-number-files/_index.md | 38 + .../_index.md | 38 + .../concatenate-pdf-files/_index.md | 37 + .../concatenate-pdf-forms/_index.md | 40 + .../concatenate-two-files/_index.md | 37 + .../try-concatenate-pdf-files/_index.md | 38 + .../try-concatenate-two-files/_index.md | 40 + .../splitting-pdf-documents/_index.md | 23 + .../split-pdf-from-beginning/_index.md | 38 + .../split-pdf-into-single-pages/_index.md | 38 + .../split-pdf-to-end/_index.md | 38 + .../pdffileinfo/_index.md | 26 + .../pdffileinfo/document-properties/_index.md | 19 + .../get-document-privileges/_index.md | 60 + .../get-pdf-version/_index.md | 44 + .../pdffileinfo/page-information/_index.md | 19 + .../page-information/get-page-info/_index.md | 51 + .../get-page-offset/_index.md | 46 + .../pdffileinfo/pdf-metadata/_index.md | 21 + .../pdf-metadata/clear-pdf-metadata/_index.md | 47 + .../pdf-metadata/get-pdf-metadata/_index.md | 59 + .../save-metadata-with-xmp/_index.md | 50 + .../pdf-metadata/set-pdf-metadata/_index.md | 56 + .../pdffilesecurity/_index.md | 26 + .../pdffilesecurity/change-password/_index.md | 155 ++ .../decrypt-pdf-file/_index.md | 92 ++ .../encrypt-pdf-file/_index.md | 152 ++ .../pdffilesecurity/set-privileges/_index.md | 148 ++ .../pdffilesignature/_index.md | 83 ++ .../pdf-certification/_index.md | 86 ++ .../pdffilesignature/pdf-signing/_index.md | 183 +++ .../revision-permissions/_index.md | 82 ++ .../signature-extraction/_index.md | 63 + .../signature-information/_index.md | 111 ++ .../signature-integrity-checks/_index.md | 63 + .../signature-management/_index.md | 62 + .../signature-verification/_index.md | 61 + .../usage-rights-management/_index.md | 63 + .../pdffilestamp/_index.md | 26 + .../pdffilestamp/add-footer/_index.md | 85 ++ .../pdffilestamp/add-header/_index.md | 98 ++ .../pdffilestamp/add-page-number/_index.md | 123 ++ .../pdffilestamp/add-stamp/_index.md | 47 + .../working-with-facades/pdfviewer/_index.md | 116 ++ .../working-with-facades/stamp/_index.md | 229 +++ ru/python-net/_index.md | 30 +- ru/python-net/advanced-operations/_index.md | 4 +- .../advanced-operations/annotations/_index.md | 171 +-- .../add-delete-and-get-annotation/_index.md | 103 +- .../import-export-annotations/_index.md | 0 .../acroforms/remove-form/_index.md | 2 +- .../working-with-forms/xfa-forms/_index.md | 2 +- .../working-with-images/_index.md | 2 +- .../working-with-pages/_index.md | 2 +- .../change-page-size/_index.md | 2 +- .../_index.md | 2 +- .../_index.md | 2 +- .../rotate-text-inside-pdf/_index.md | 2 +- ru/python-net/basic-operations/_index.md | 2 +- .../basic-operations/merge-pdf/_index.md | 2 +- .../convert-pdf-to-images-format/_index.md | 296 ++-- ru/python-net/get-started/_index.md | 8 +- .../get-started/complex-pdf/_index.md | 4 +- .../get-started/hello-world-example/_index.md | 6 +- ru/python-net/overview/_index.md | 8 +- ru/python-net/overview/installation/_index.md | 6 +- ru/python-net/overview/key-features/_index.md | 6 +- .../overview/supported-file-formats/_index.md | 4 +- .../overview/system-requirements/_index.md | 4 +- .../overview/technical-support/_index.md | 2 +- ru/python-net/parsing/_index.md | 2 +- ru/python-net/working-with-facades/_index.md | 10 +- 378 files changed, 31306 insertions(+), 15357 deletions(-) rename en/python-net/advanced-operations/annotations/{add-delete-and-get-annotation => }/import-export-annotations/_index.md (100%) create mode 100644 es/python-net/advanced-operations/accessibility-tagged-pdf/_index.md create mode 100644 es/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/_index.md create mode 100644 es/python-net/advanced-operations/accessibility-tagged-pdf/extract-tagged-content-from-tagged-pdfs/_index.md create mode 100644 es/python-net/advanced-operations/accessibility-tagged-pdf/setting-structure-elements-properties/_index.md create mode 100644 es/python-net/advanced-operations/accessibility-tagged-pdf/working-with-table-in-tagged-pdfs/_index.md delete mode 100644 es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/extra-annotations/_index.md delete mode 100644 es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/figures/_index.md delete mode 100644 es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/hightlights/_index.md create mode 100644 es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/interactive-annotations/_index.md create mode 100644 es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/markup-annotations/_index.md create mode 100644 es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md create mode 100644 es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/security-annotations/_index.md create mode 100644 es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md delete mode 100644 es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/sticks/_index.md create mode 100644 es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text-based-annotations/_index.md delete mode 100644 es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text/_index.md create mode 100644 es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/watermark-annotations/_index.md create mode 100644 es/python-net/advanced-operations/annotations/import-export-annotations/_index.md create mode 100644 es/python-net/advanced-operations/artifacts/_index.md create mode 100644 es/python-net/advanced-operations/artifacts/add-backgrounds/_index.md create mode 100644 es/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md create mode 100644 es/python-net/advanced-operations/artifacts/add-watermarks/_index.md create mode 100644 es/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md create mode 100644 es/python-net/advanced-operations/artifacts/counting-artifacts/_index.md create mode 100644 es/python-net/advanced-operations/attachments/extract-attachment/_index.md create mode 100644 es/python-net/advanced-operations/compare-pdf-documents/_index.md create mode 100644 es/python-net/advanced-operations/navigation-and-interaction/actions/_index.md create mode 100644 es/python-net/advanced-operations/navigation-and-interaction/links/_index.md create mode 100644 es/python-net/advanced-operations/navigation-and-interaction/links/create-links/_index.md create mode 100644 es/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md create mode 100644 es/python-net/advanced-operations/navigation-and-interaction/links/update-links/_index.md create mode 100644 es/python-net/advanced-operations/pdf-file-metadata/_index.md create mode 100644 es/python-net/advanced-operations/securing-and-signing/_index.md create mode 100644 es/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md create mode 100644 es/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md create mode 100644 es/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md create mode 100644 es/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md delete mode 100644 es/python-net/advanced-operations/working-with-documents/working-with-headings/_index.md create mode 100644 es/python-net/advanced-operations/working-with-forms/acroforms/import-export-form-data/_index.md create mode 100644 es/python-net/advanced-operations/working-with-forms/acroforms/modifying-form/_index.md create mode 100644 es/python-net/advanced-operations/working-with-forms/acroforms/posting-form/_index.md create mode 100644 es/python-net/advanced-operations/working-with-forms/acroforms/remove-form/_index.md create mode 100644 es/python-net/advanced-operations/working-with-forms/xfa-forms/_index.md create mode 100644 es/python-net/advanced-operations/working-with-graphs/_index.md create mode 100644 es/python-net/advanced-operations/working-with-graphs/arc/_index.md create mode 100644 es/python-net/advanced-operations/working-with-graphs/checking-shape-bounds/_index.md create mode 100644 es/python-net/advanced-operations/working-with-graphs/circle/_index.md create mode 100644 es/python-net/advanced-operations/working-with-graphs/curve/_index.md create mode 100644 es/python-net/advanced-operations/working-with-graphs/ellipse/_index.md create mode 100644 es/python-net/advanced-operations/working-with-graphs/line/_index.md create mode 100644 es/python-net/advanced-operations/working-with-graphs/rectangle/_index.md create mode 100644 es/python-net/advanced-operations/working-with-images/replace-image-in-existing-pdf-file/_index.md create mode 100644 es/python-net/advanced-operations/working-with-images/search-and-get-images-from-pdf-document/_index.md create mode 100644 es/python-net/advanced-operations/working-with-layers/_index.md create mode 100644 es/python-net/advanced-operations/working-with-operators/_index.md create mode 100644 es/python-net/advanced-operations/working-with-pages/extract-pages/_index.md create mode 100644 es/python-net/advanced-operations/working-with-pages/stamping/add-page-number/_index.md create mode 100644 es/python-net/advanced-operations/working-with-pages/stamping/add-page-stamp/_index.md create mode 100644 es/python-net/advanced-operations/working-with-tables/integrate-table-in-existing-pdf-document/_index.md delete mode 100644 es/python-net/advanced-operations/working-with-text/add-text-to-a-pdf-file/_index.md create mode 100644 es/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/_index.md delete mode 100644 es/python-net/advanced-operations/working-with-text/determine-line-break/_index.md create mode 100644 es/python-net/advanced-operations/working-with-text/floating-box/_index.md create mode 100644 es/python-net/advanced-operations/working-with-vector-graphics/_index.md create mode 100644 es/python-net/aspose_pdf-for-python-net.png create mode 100644 es/python-net/aspose_pdf-for-python-net.svg create mode 100644 es/python-net/faq/_index.md create mode 100644 es/python-net/parsing/extract-data-from-acroform/_index.md create mode 100644 es/python-net/parsing/extract-data-from-tables/_index.md create mode 100644 es/python-net/parsing/extract-fonts-from-pdf/_index.md create mode 100644 es/python-net/parsing/extract-images-from-pdf/_index.md create mode 100644 es/python-net/parsing/extract-text-from-pdf/_index.md create mode 100644 es/python-net/parsing/extract-text-from-pdf/annotations-and-special-text/_index.md create mode 100644 es/python-net/parsing/extract-text-from-pdf/basic-text-extraction/_index.md create mode 100644 es/python-net/parsing/extract-text-from-pdf/region-based-extraction/_index.md create mode 100644 es/python-net/parsing/extract-text-from-pdf/text-extraction-from-multi-column-pdf/_index.md create mode 100644 es/python-net/parsing/extract-vector-data-from-pdf/_index.md create mode 100644 es/python-net/working-with-facades/_index.md create mode 100644 es/python-net/working-with-facades/form/_index.md create mode 100644 es/python-net/working-with-facades/form/button-fields-and-images/_index.md create mode 100644 es/python-net/working-with-facades/form/exporting-form-data/_index.md create mode 100644 es/python-net/working-with-facades/form/exporting-form-data/export-to-fdf/_index.md create mode 100644 es/python-net/working-with-facades/form/exporting-form-data/export-to-json/_index.md create mode 100644 es/python-net/working-with-facades/form/exporting-form-data/export-to-xfdf/_index.md create mode 100644 es/python-net/working-with-facades/form/exporting-form-data/export-to-xml/_index.md create mode 100644 es/python-net/working-with-facades/form/exporting-form-data/extract-xfa-data/_index.md create mode 100644 es/python-net/working-with-facades/form/filling-form-fields/_index.md create mode 100644 es/python-net/working-with-facades/form/filling-form-fields/fill-barcode-fields/_index.md create mode 100644 es/python-net/working-with-facades/form/filling-form-fields/fill-check-box-fields/_index.md create mode 100644 es/python-net/working-with-facades/form/filling-form-fields/fill-fields-by-name-and-value/_index.md create mode 100644 es/python-net/working-with-facades/form/filling-form-fields/fill-list-box/_index.md create mode 100644 es/python-net/working-with-facades/form/filling-form-fields/fill-radio-button-fields/_index.md create mode 100644 es/python-net/working-with-facades/form/filling-form-fields/fill-text-fields/_index.md create mode 100644 es/python-net/working-with-facades/form/importing-form-data/_index.md create mode 100644 es/python-net/working-with-facades/form/importing-form-data/import-fdf-data/_index.md create mode 100644 es/python-net/working-with-facades/form/importing-form-data/import-json-data/_index.md create mode 100644 es/python-net/working-with-facades/form/importing-form-data/import-xfdf-data/_index.md create mode 100644 es/python-net/working-with-facades/form/importing-form-data/import-xml-data/_index.md create mode 100644 es/python-net/working-with-facades/form/importing-form-data/replace-xfa-data/_index.md create mode 100644 es/python-net/working-with-facades/form/managing-form-fields/_index.md create mode 100644 es/python-net/working-with-facades/form/managing-form-fields/flatten-all-fields/_index.md create mode 100644 es/python-net/working-with-facades/form/managing-form-fields/flatten-specific-fields/_index.md create mode 100644 es/python-net/working-with-facades/form/managing-form-fields/rename-form-fields/_index.md create mode 100644 es/python-net/working-with-facades/form/reading-form-values/_index.md create mode 100644 es/python-net/working-with-facades/form/reading-form-values/get-field-facades/_index.md create mode 100644 es/python-net/working-with-facades/form/reading-form-values/get-field-values/_index.md create mode 100644 es/python-net/working-with-facades/form/reading-form-values/get-radio-button-options/_index.md create mode 100644 es/python-net/working-with-facades/form/reading-form-values/get-required-field-names/_index.md create mode 100644 es/python-net/working-with-facades/form/reading-form-values/get-rich-text-values/_index.md create mode 100644 es/python-net/working-with-facades/form/reading-form-values/resolve-full-field-names/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/creating-form-field/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md create mode 100644 es/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md create mode 100644 es/python-net/working-with-facades/pdfannotationeditor/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/annotations/add-text-annotation/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment-from-path/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/multimedia/add-movie-annotation/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/multimedia/add-sound-annotation/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md create mode 100644 es/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/page-managment/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/page-merging/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md create mode 100644 es/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md create mode 100644 es/python-net/working-with-facades/pdffileinfo/_index.md create mode 100644 es/python-net/working-with-facades/pdffileinfo/document-properties/_index.md create mode 100644 es/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md create mode 100644 es/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md create mode 100644 es/python-net/working-with-facades/pdffileinfo/page-information/_index.md create mode 100644 es/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md create mode 100644 es/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md create mode 100644 es/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md create mode 100644 es/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md create mode 100644 es/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md create mode 100644 es/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md create mode 100644 es/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md create mode 100644 es/python-net/working-with-facades/pdffilesecurity/_index.md create mode 100644 es/python-net/working-with-facades/pdffilesecurity/change-password/_index.md create mode 100644 es/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md create mode 100644 es/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md create mode 100644 es/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md create mode 100644 es/python-net/working-with-facades/pdffilesignature/_index.md create mode 100644 es/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md create mode 100644 es/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md create mode 100644 es/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md create mode 100644 es/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md create mode 100644 es/python-net/working-with-facades/pdffilesignature/signature-information/_index.md create mode 100644 es/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md create mode 100644 es/python-net/working-with-facades/pdffilesignature/signature-management/_index.md create mode 100644 es/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md create mode 100644 es/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md create mode 100644 es/python-net/working-with-facades/pdffilestamp/_index.md create mode 100644 es/python-net/working-with-facades/pdffilestamp/add-footer/_index.md create mode 100644 es/python-net/working-with-facades/pdffilestamp/add-header/_index.md create mode 100644 es/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md create mode 100644 es/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md create mode 100644 es/python-net/working-with-facades/pdfviewer/_index.md create mode 100644 es/python-net/working-with-facades/stamp/_index.md rename ru/python-net/advanced-operations/annotations/{add-delete-and-get-annotation => }/import-export-annotations/_index.md (100%) diff --git a/en/python-net/advanced-operations/annotations/_index.md b/en/python-net/advanced-operations/annotations/_index.md index b18602655..45febbe71 100644 --- a/en/python-net/advanced-operations/annotations/_index.md +++ b/en/python-net/advanced-operations/annotations/_index.md @@ -5,7 +5,7 @@ type: docs weight: 100 url: /python-net/annotations/ description: Learn how to add, modify, extract, and manage PDF annotations in Python with Aspose.PDF for Python via .NET, including text, highlights, links, figures, and more. -lastmod: "2026-04-14" +lastmod: "2026-05-08" sitemap: changefreq: "monthly" priority: 0.7 @@ -14,19 +14,30 @@ AlternativeHeadline: How to add Annotations to PDF using Python Abstract: The article discusses the use of annotations in PDFs as interactive elements that enhance document interactivity and user engagement. It highlights the capabilities of the Aspose.PDF for Python Library in supporting various annotation types, including text, highlights, figures, and multimedia annotations. Annotations serve multiple purposes such as commenting, reviewing, marking documents, and providing feedback, which facilitates collaboration, communication, and a deeper understanding of document content. The article also mentions a section detailing how to add, delete, and retrieve annotations, offering guidance on managing these elements effectively within PDF documents. --- -Annotations in PDFs are interactive elements that allow you to add notes, highlight text, draw shapes, attach files, and perform other actions that improve browsing, interactivity, and interaction. +Annotations in PDFs are interactive elements that let you add notes, highlight text, draw shapes, attach files, and trigger actions directly on a page. They are useful for review workflows, collaboration, navigation, and document markup. -The Aspose.PDF for Python Library supports various types of annotations, including text annotations (such as text, and popup annotation), highlights annotations (such as text markup), figures annotations( such as circle, polyline, polygon, line, and ink), multimedia annotations ( there are screen, sound, widget, and 3D) and more. +Aspose.PDF for Python via .NET supports a wide range of annotation scenarios, including note and popup annotations, text markup, links and buttons, shapes, watermarks, multimedia annotations, and annotation import or export workflows. -Annotations can be used to comment, review, mark documents, provide feedback, or add additional information. Annotations allow to establish cooperation, facilitate communication, and improve understanding of the content of documents. They enhance collaboration, improve communication, and make PDF documents more dynamic and engaging for users. +Use this section to choose the annotation workflow that matches your task, whether you need to create new annotations, inspect existing ones, remove them, or transfer them between PDF documents. ## Annotation Topics -Use this section when you need to add, retrieve, update, or remove annotations from PDF files in Python. These pages cover the most common annotation workflows, from text markup and links to figures, notes, and additional specialty annotations. +Use this section when you need to add, retrieve, update, remove, or transfer annotations in PDF files with Python. The linked pages below cover both the top-level annotation workflows and the grouped annotation families used throughout the documentation. -You are able to do the following: +You can use the following topics: -- [Add, Delete and Get Annotation](/pdf/python-net/add-delete-and-get-annotation/) - this section explains how to work with all types of allowed annotations. +- [Add, Delete and Get Annotation](/pdf/python-net/add-delete-and-get-annotation/) - start here for the main grouped annotation categories and the core create, inspect, and remove workflows. +- [Import and Export Annotations](/pdf/python-net/import-export-annotations/) - copy annotations from one PDF document into another PDF file. -Annotations are especially useful for document review, collaboration, content markup, and interactive navigation. Start with the grouped annotation overview below, then move into the specific annotation type that matches your PDF workflow. +### Annotation Groups +The grouped annotation guide includes these subtopics: + +- [Text Annotations](/pdf/python-net/text-based-Annotations/) - work with free text, highlight, underline, squiggly, and strikeout annotations. +- [Markup Annotations](/pdf/python-net/markup-annotations/) - add or inspect note, caret, and replace annotations used in review scenarios. +- [Interactive Annotations](/pdf/python-net/interactive-annotations/) - create link annotations, navigation buttons, and print buttons. +- [Shape Annotations](/pdf/python-net/shape-annotations/) - use line, square, circle, polygon, and polyline annotations. +- [Media Annotations](/pdf/python-net/media-annotations/) - add sound, screen, rich media, and 3D annotations. +- [Security Annotations](/pdf/python-net/security-annotations/) - work with file attachment, redaction, and related protection-oriented annotations. +- [Watermark Annotations](/pdf/python-net/watermark-annotations/) - add and manage annotation-based watermark elements. +Annotations are especially useful for document review, collaboration, content markup, and interactive navigation. Begin with the grouped overview when you want to browse supported annotation types, or go directly to a specific topic when you already know the workflow you need. diff --git a/en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md b/en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md index e81944cfa..c5ae38680 100644 --- a/en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md +++ b/en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md @@ -5,7 +5,7 @@ type: docs weight: 20 url: /python-net/add-delete-and-get-annotation/ description: With Aspose.PDF for Python you may add, delete and get annotation from your PDF file. Check all lists of annotations to resolve your task. -lastmod: "2026-04-17" +lastmod: "2026-05-08" sitemap: changefreq: "monthly" priority: 0.7 @@ -20,7 +20,6 @@ This page groups the main annotation types supported in this part of the documen We have combined the different kinds of annotation available for the Aspose.PDF for Python library into groups: -- [Import and Export Annotations](/pdf/python-net/import-export-annotations/) - [Interactive Annotations](/pdf/python-net/interactive-annotations/) - [Markup Annotations](/pdf/python-net/markup-annotations/) - [Media Annotations](/pdf/python-net/media-annotations/) @@ -32,6 +31,4 @@ We have combined the different kinds of annotation available for the Aspose.PDF ## Related Annotation Topics - [PDF Annotations overview](/pdf/python-net/annotations/) for the parent section and annotation concepts. -- [PDF Text Annotation](/pdf/python-net/text-annotation/) for note-style and text-based annotation workflows. -- [PDF Figures Annotation](/pdf/python-net/figures-annotation/) for shape-based annotations such as circles, polygons, and lines. - +- [Import and Export Annotations](/pdf/python-net/import-export-annotations/) diff --git a/en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/import-export-annotations/_index.md b/en/python-net/advanced-operations/annotations/import-export-annotations/_index.md similarity index 100% rename from en/python-net/advanced-operations/annotations/add-delete-and-get-annotation/import-export-annotations/_index.md rename to en/python-net/advanced-operations/annotations/import-export-annotations/_index.md diff --git a/en/python-net/converting/convert-pdf-to-images-format/_index.md b/en/python-net/converting/convert-pdf-to-images-format/_index.md index 5efc31c89..e44a64174 100644 --- a/en/python-net/converting/convert-pdf-to-images-format/_index.md +++ b/en/python-net/converting/convert-pdf-to-images-format/_index.md @@ -4,27 +4,32 @@ linktitle: Convert PDF to Images type: docs weight: 70 url: /python-net/convert-pdf-to-images-format/ -lastmod: "2026-04-14" -description: Explore how to convert PDF pages into images such as PNG, JPEG, or TIFF using Aspose.PDF in Python via .NET. +lastmod: "2026-05-08" +description: Learn how to render PDF pages as TIFF, BMP, EMF, JPEG, PNG, GIF, and SVG files in Python with Aspose.PDF for Python via .NET. sitemap: changefreq: "monthly" priority: 0.5 TechArticle: true -AlternativeHeadline: How to Convert PDF to Image Formats in Python -Abstract: This article provides a comprehensive guide on converting PDF files into various image formats using Python, specifically leveraging the Aspose.PDF for Python library. The document outlines methods for converting PDFs to image formats including TIFF, BMP, EMF, JPG, PNG, GIF, and SVG. Two primary conversion approaches are discussed - using the Device approach and SaveOption. The Device approach involves utilizing classes like `DocumentDevice` and `ImageDevice` for whole document or page-specific conversions. Detailed steps and Python code examples are provided for converting PDF pages to different formats such as TIFF using `TiffDevice`, and BMP, EMF, JPEG, PNG, and GIF using respective device classes (`BmpDevice`, `EmfDevice`, `JpegDevice`, `PngDevice`, `GifDevice`). For SVG conversion, the `SvgSaveOptions` class is introduced. The article also highlights online tools for trying these conversions. +AlternativeHeadline: Convert PDF Pages to TIFF, PNG, JPEG, GIF, BMP, EMF, and SVG in Python +Abstract: This article explains how to convert PDF files to common image formats with Aspose.PDF for Python via .NET. It covers document-wide TIFF export with `TiffDevice`, per-page raster image generation with `ImageDevice` subclasses such as `BmpDevice`, `JpegDevice`, `PngDevice`, `GifDevice`, and `EmfDevice`, and vector export to SVG with `SvgSaveOptions`. Each section includes the core steps and Python examples needed to save PDF content as image output. --- ## Python Convert PDF to Image -**Aspose.PDF for Python** uses several approaches to convert PDF to image. Generally speaking, we use two approaches: conversion using the Device approach and conversion using SaveOption. This section will show you how to convert PDF documents to image formats such as BMP, JPEG, GIF, PNG, EMF, TIFF, and SVG formats using one of those approaches. +**Aspose.PDF for Python via .NET** supports several ways to convert PDF content to images. In practice, most workflows use one of two options: -There are several classes in the library that allow you to use a virtual device to transform images. DocumentDevice is oriented for conversion whole document, but ImageDevice - for a particular page. +- the Device approach for rendering PDF pages to raster image formats +- the SaveOptions approach for exporting PDF content to SVG + +This article shows how to convert PDF files to TIFF, BMP, EMF, JPEG, PNG, GIF, and SVG. + +The library includes multiple rendering classes. `DocumentDevice` is designed for whole-document conversion, while `ImageDevice` targets individual pages. ## Convert PDF using DocumentDevice class -**Aspose.PDF for Python** makes a possible to convert PDF Pages to TIFF images. +Use `DocumentDevice` when you want to render the entire PDF into a single multi-page TIFF file. -The [TiffDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/) (based on DocumentDevice) class allows you to convert PDF pages to TIFF images. This class provides a method named [process](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/#methods) which allows you to convert all the pages in a PDF file to a single TIFF image. +The [TiffDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/) class is based on `DocumentDevice` and provides the [process](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/#methods) method for converting all pages in a PDF file into one TIFF output. {{% alert color="success" %}} **Try to convert PDF to TIFF online** @@ -36,14 +41,14 @@ Aspose.PDF for Python via .NET presents you online application ["PDF to TIFF"](h ### Convert PDF Pages to One TIFF Image -Aspose.PDF for Python explain how to convert all pages in a PDF file to a single TIFF image: +Aspose.PDF for Python via .NET can render every page in a PDF file into one TIFF image. Steps: Convert PDF to TIFF in Python -1. Create an object of the [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) class. -1. Create [TiffSettings](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffsettings/) and [TiffDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/) objects -1. Call the [process](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/#methods) method to convert the PDF document to TIFF. -1. To set the output file's properties, use the [TiffSettings](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffsettings/) class. +1. Load the source PDF with the [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) class. +1. Create [TiffSettings](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffsettings/) and [TiffDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/) objects. +1. Configure TIFF options such as compression, color depth, and blank-page handling. +1. Call the [process](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/#methods) method to write the TIFF file. The following code snippet shows how to convert all the PDF pages to a single TIFF image. @@ -70,36 +75,39 @@ def convert_PDF_to_TIFF(infile, outfile): ## Convert PDF using ImageDevice class -`ImageDevice` is the ancestor for `BmpDevice`, `JpegDevice`, `GifDevice`, `PngDevice` and `EmfDevice`. +Use `ImageDevice` when you need page-by-page output in a raster image format. + +`ImageDevice` is the base class for `BmpDevice`, `JpegDevice`, `GifDevice`, `PngDevice`, and `EmfDevice`. -- The [BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) class allows you to convert PDF pages to BMP images. -- The [EmfDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/emfdevice/) class allows you to convert PDF pages to EMF images. +- The [BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) class allows you to convert PDF pages to BMP images. +- The [EmfDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/emfdevice/) class allows you to convert PDF pages to EMF images. - The [JpegDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/jpegdevice/) class allows you to convert PDF pages to JPEG images. -- The [PngDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/pngdevice/) class allows you to convert PDF pages to PNG images. -- The [GifDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/gifdevice/) class allows you to convert PDF pages to GIF images. +- The [PngDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/pngdevice/) class allows you to convert PDF pages to PNG images. +- The [GifDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/gifdevice/) class allows you to convert PDF pages to GIF images. -Let's take a look at how to convert a PDF page to an image. +The workflow is the same for each format: load the document, create the appropriate device, then process the required page. -[BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) class provides a method named [process](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/#methods) which allows you to convert a particular page of the PDF file to BMP image format. The other classes have the same method. So, if we need to convert a PDF page to an image, we just instantiate the required class. +[BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) exposes the [process](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/#methods) method to render a specific page as BMP. The other image device classes follow the same pattern, so you can switch formats by changing the device class. -The following steps and code snippet in Python shows this possibility: +The following links and code samples show how to render PDF pages to common image formats: - - [Convert PDF to BMP in Python](#python-pdf-to-image) - - [Convert PDF to EMF in Python](#python-pdf-to-image) - - [Convert PDF to JPG in Python](#python-pdf-to-image) - - [Convert PDF to PNG in Python](#python-pdf-to-image) - - [Convert PDF to GIF in Python](#python-pdf-to-image) +- [Convert PDF to BMP in Python](#convert-pdf-to-bmp) +- [Convert PDF to EMF in Python](#convert-pdf-to-emf) +- [Convert PDF to JPEG in Python](#convert-pdf-to-jpeg) +- [Convert PDF to PNG in Python](#convert-pdf-to-png) +- [Convert PDF to GIF in Python](#convert-pdf-to-gif) Steps: PDF to Image (BMP, EMF, JPG, PNG, GIF) in Python -1. Load the PDF file using [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) class. -1. Create an instance of subclass of [ImageDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/imagedevice/) i.e. - * [BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) (to convert PDF to BMP) - * [EmfDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/emfdevice/) (to convert PDF to Emf) - * [JpegDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/jpegdevice/) (to convert PDF to JPG) - * [PngDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/pngdevice/) (to convert PDF to PNG) - * [GifDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/gifdevice/) (to convert PDF to GIF) -1. Call the [ImageDevice.process()](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/imagedevice/#methods) method to perform PDF to Image conversion. +1. Load the PDF file with the [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) class. +1. Create an instance of the required [ImageDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/imagedevice/) subclass: + - [BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) (to convert PDF to BMP) + - [EmfDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/emfdevice/) (to convert PDF to EMF) + - [JpegDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/jpegdevice/) (to convert PDF to JPG) + - [PngDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/pngdevice/) (to convert PDF to PNG) + - [GifDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/gifdevice/) (to convert PDF to GIF) +1. Loop through the pages you want to export. +1. Call the [ImageDevice.process()](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/imagedevice/#methods) method to save each page as an image. ### Convert PDF to BMP @@ -249,7 +257,7 @@ Aspose.PDF for Python presents you online application ["PDF to PNG"](https://pro ## Convert PDF using SaveOptions class -This part of article shows you how to convert PDF to SVG using Python and SaveOptions class. +Use `SaveOptions` when you want to export PDF content to SVG. {{% alert color="success" %}} **Try to convert PDF to SVG online** @@ -259,19 +267,19 @@ Aspose.PDF for Python via .NET presents you online application ["PDF to SVG"](ht [![Aspose.PDF Convertion PDF to SVG with App](pdf_to_svg.png)](https://products.aspose.app/pdf/conversion/pdf-to-svg) {{% /alert %}} -**Scalable Vector Graphics (SVG)** is a family of specifications of an XML-based file format for two-dimensional vector graphics, both static and dynamic (interactive or animated). The SVG specification is an open standard that has been under development by the World Wide Web Consortium (W3C) since 1999. +**Scalable Vector Graphics (SVG)** is an XML-based format for two-dimensional vector graphics. Because SVG remains vector-based, it is useful when you need scalable output for web, UI, or design workflows. -SVG images and their behaviors are defined in XML text files. This means that they can be searched, indexed, scripted and if required, compressed. As XML files, SVG images can be created and edited with any text editor, but it is often more convenient to create them with drawing programs such as Inkscape. +SVG files are text-based, searchable, and easy to post-process in other tools. -Aspose.PDF for Python supports the feature to convert SVG image to PDF format and also offers the capability to convert PDF files to SVG format. To accomplish this requirement, the [SvgSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/svgsaveoptions/) class has been introduced into the Aspose.PDF namespace. Instantiate an object of SvgSaveOptions and pass it as a second argument to the [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) method. +Aspose.PDF for Python via .NET can both convert SVG to PDF and export PDF pages to SVG. For PDF-to-SVG conversion, create a [SvgSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/svgsaveoptions/) object and pass it to the [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) method. -The following code snippet shows the steps for converting a PDF file to SVG format with Python. +The following steps show how to convert a PDF file to SVG with Python. Steps: Convert PDF to SVG in Python -1. Create an object of the [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) class. -1. Create [SvgSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/svgsaveoptions/) object with needed settings. -1. Call the [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) method and pass it [SvgSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/svgsaveoptions/) object convert the PDF document to SVG. +1. Load the source PDF using the [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) class. +1. Create a [SvgSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/svgsaveoptions/) object and configure the required options. +1. Call the [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) method with the `SvgSaveOptions` instance to write the SVG output. ### Convert PDF to SVG diff --git a/es/python-net/_index.md b/es/python-net/_index.md index eb7612349..9edf1637e 100644 --- a/es/python-net/_index.md +++ b/es/python-net/_index.md @@ -1,49 +1,50 @@ --- title: Documentación -linktitle: Aspose.PDF para Python a través de .NET -second_title: Aspose.PDF para Python a través de .NET +linktitle: Aspose.PDF for Python via .NET +second_title: Aspose.PDF for Python via .NET type: docs weight: 40 url: /es/python-net/ is_root: true -lastmod: "2022-10-24" -description: Aprenda a usar Aspose.PDF Python a través de .NET para crear aplicaciones para el procesamiento de documentos PDF en cualquier plataforma usando Python. Explore tutoriales, códigos de muestra y más. +lastmod: "2026-05-11" +description: Aprende a usar Aspose.PDF Python via .NET para crear aplicaciones de procesamiento de documentos PDF en cualquier plataforma usando Python. Explora tutoriales, ejemplos de código y más. sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Guía de documentación de Aspose.PDF for Python via .NET +Abstract: Aspose.PDF for Python via .NET es un componente versátil diseñado para que los desarrolladores creen y manipulen programáticamente documentos PDF usando Python en conjunto con .NET. Esta herramienta admite una amplia gama de funcionalidades, incluida la inserción de tablas, gráficos, imágenes, hipervínculos y fuentes personalizadas, así como compresión de PDF. También ofrece sólidas características de seguridad para garantizar la protección de los documentos. Cabe destacar que los desarrolladores pueden generar documentos PDF mediante una API o a partir de plantillas XML. La documentación está organizada en varios capítulos que cubren nuevas características, una visión general, guías de inicio, operaciones básicas y avanzadas, conversión de documentos y técnicas de análisis. Recursos adicionales incluyen aspectos destacados de las funcionalidades, notas de la versión, páginas del producto, enlaces de descarga, instrucciones de instalación, una guía de referencia de la API y acceso a foros de soporte y mesas de ayuda. --- -![Imagen del logotipo de Aspose.PDF para Python a través de .NET](aspose_pdf-for-python-net.png) +![Imagen del logotipo de Aspose.PDF for Python via .NET](aspose_pdf-for-python-net.png) -

Bienvenido a Aspose.PDF para Python a través de .NET

+## Bienvenido a Aspose.PDF for Python via .NET {{% alert color="primary" %}} -Aspose.PDF es un componente .NET diseñado para permitir a los desarrolladores crear documentos PDF, ya sean simples o complejos, de manera programática sobre la marcha. - Aspose.PDF for Python via .NET permite a los desarrolladores insertar tablas, gráficos, imágenes, hipervínculos, fuentes personalizadas - y más - en documentos PDF. Además, también es posible comprimir documentos PDF. Aspose.PDF for Python via .NET proporciona excelentes características de seguridad para desarrollar documentos PDF seguros. Y la característica más distintiva de Aspose.PDF for Python via .NET es que admite la creación de documentos PDF tanto a través de una API como desde plantillas XML. +Aspose.PDF es un componente .NET creado para permitir a los desarrolladores crear documentos PDF, ya sean simples o complejos, sobre la marcha de forma programática. Aspose.PDF for Python via .NET permite a los desarrolladores insertar tablas, gráficos, imágenes, hipervínculos, fuentes personalizadas - y más - en documentos PDF. Además, también es posible comprimir documentos PDF. Aspose.PDF for Python via .NET ofrece excelentes características de seguridad para desarrollar documentos PDF seguros. Y la característica más distintiva de Aspose.PDF for Python via .NET es que admite la creación de documentos PDF tanto mediante una API como a partir de plantillas XML. {{% /alert %}} -

Capítulos

+## Capítulos -- [Qué hay de nuevo](/pdf/es/python-net/whatsnew/) +- [Novedades](/pdf/es/python-net/whatsnew/) - [Visión general](/pdf/es/python-net/overview/) - [Comenzar](/pdf/es/python-net/get-started/) - [Operaciones básicas](/pdf/es/python-net/basic-operations/) - [Conversión de documentos](/pdf/es/python-net/converting/) - [Análisis de documentos PDF](/pdf/es/python-net/parsing/) - [Operaciones avanzadas](/pdf/es/python-net/advanced-operations/) -- [Muestras](/pdf/es/python-net/showcases/) - [Notas de la versión](https://releases.aspose.com/pdf/pythonnet/release-notes/) -

Recursos de Aspose.PDF para Python via .NET

- -Los siguientes son los enlaces a algunos recursos útiles que puede necesitar para realizar sus tareas. -- [Aspose.PDF para Python a través de .NET Características Clave](/pdf/es/python-net/key-features/) -- [Aspose.PDF para Python a través de .NET Notas de la Versión](https://releases.aspose.com/pdf/pythonnet/release-notes/) -- [Aspose.PDF para Python a través de .NET Página del Producto](https://products.aspose.com/pdf/python-net/) -- [Descargar Aspose.PDF para Python a través de .NET](https://releases.aspose.com/pdf/pythonnet/) -- [Instalar Aspose.PDF para Python a través de .NET Paquete NuGet](https://www.nuget.org/packages/Aspose.PDF/) -- [Aspose.PDF para Python a través de .NET Guía de Referencia de API](https://reference.aspose.com/pdf/net)! -- [Aspose.PDF para Python a través de .NET Foro de Soporte Gratuito](https://forum.aspose.com/c/pdf/10) -- [Aspose.PDF para Python a través de .NET Mesa de Ayuda de Soporte Pagado](https://helpdesk.aspose.com/) \ No newline at end of file +## Recursos de Aspose.PDF for Python via .NET + +A continuación se encuentran los enlaces a algunos recursos útiles que pueda necesitar para realizar sus tareas. + +- [Aspose.PDF for Python via .NET Características](/pdf/es/python-net/key-features/) +- [Aspose.PDF for Python via .NET Notas de la versión](https://releases.aspose.com/pdf/pythonnet/release-notes/) +- [Aspose.PDF for Python via .NET Página del producto](https://products.aspose.com/pdf/es/python-net/) +- [Descargar Aspose.PDF for Python via .NET](https://releases.aspose.com/pdf/pythonnet/) +- [Guía de referencia de API de Aspose.PDF for Python via .NET](https://reference.aspose.com/pdf/net)! +- [Foro de soporte gratuito de Aspose.PDF for Python via .NET](https://forum.aspose.com/c/pdf/10) +- [Helpdesk de soporte pago de Aspose.PDF for Python via .NET](https://helpdesk.aspose.com/) diff --git a/es/python-net/advanced-operations/_index.md b/es/python-net/advanced-operations/_index.md index 56d71929c..a55501c09 100644 --- a/es/python-net/advanced-operations/_index.md +++ b/es/python-net/advanced-operations/_index.md @@ -4,90 +4,32 @@ linktitle: Operaciones avanzadas type: docs weight: 90 url: /es/python-net/advanced-operations/ -description: Aspose.PDF para Python a través de .NET puede realizar tareas simples y fáciles y enfrentar objetivos más complejos. Consulte la siguiente sección para usuarios avanzados y desarrolladores. -lastmod: "2023-04-17" +description: Aspose.PDF for Python via .NET puede realizar tareas simples y fáciles y afrontar objetivos más complejos. Consulte la siguiente sección para usuarios y desarrolladores avanzados. +lastmod: "2025-02-27" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: La sección Operaciones avanzadas con Python +Abstract: La sección Operaciones avanzadas ofrece una guía completa sobre cómo manejar programáticamente archivos PDF existentes, sin importar su origen, utilizando diversas herramientas y técnicas. Esta sección amplía las habilidades fundamentales discutidas en Operaciones básicas al explorar funcionalidades avanzadas. --- - +**Operaciones avanzadas** es una sección sobre cómo tratar con archivos PDF existentes programáticamente, ya sean documentos creados con Aspose.PDF como se discute en [Operaciones básicas](/pdf/es/python-net/basic-operations/), o PDFs creados con Adobe Acrobat, Google Docs, Microsoft Office, Open Office o cualquier otro productor de PDF. -**Operaciones Avanzadas** es una sección sobre cómo manejar archivos PDF existentes programáticamente, ya sean documentos creados con Aspose.PDF como se discute en [Operaciones Básicas](/pdf/es/python-net/basic-operations/), o PDFs creados con Adobe Acrobat, Google Docs, Microsoft Office, Open Office o cualquier otro productor de PDF. +Aprenderás diferentes formas de: -Aprenderás diferentes maneras de: - -- [Trabajar con Documentos](/pdf/es/python-net/working-with-documents/) - comprimir, dividir y fusionar documentos y realizar otras operaciones con el documento completo. -- [Trabajar con Páginas](/pdf/es/python-net/working-with-pages/) - agregar, mover o eliminar, recortar páginas, añadir marcas de agua, sellos, etc. -- [Trabajar con Imágenes](/pdf/es/python-net/working-with-images/) - añadir, extraer o eliminar imágenes de documentos PDF. -- [Adjuntos](/pdf/es/python-net/attachments/) - aprenderás cómo agregar y eliminar el adjunto de un PDF programáticamente con Python. -- [Navegación e Interacción](/pdf/es/python-net/navigation-and-interaction/) - manejar acciones, marcadores, navegar por páginas. -- [Anotaciones](/pdf/es/python-net/annotations/) - las anotaciones permiten a los usuarios añadir contenido personalizado en las páginas PDF. - Puedes agregar, eliminar y modificar la anotación de los documentos PDF. -- [Trabajando con Tablas](/pdf/es/python-net/working-with-tables/) - insertar, decorar tablas en PDF, extraer datos tabulares. -- [Trabajando con Formularios](/pdf/es/python-net/working-with-forms/) - manejar documentos PDF interactivos, agregar campos de formulario, extraer datos. -- [Trabajando con Texto](/pdf/es/python-net/working-with-text/) - agregar, formatear, buscar y reemplazar texto en PDF. \ No newline at end of file +- [Trabajando con documentos](/pdf/es/python-net/working-with-documents/) - comprimir, dividir y combinar documentos y realizar otras operaciones con el documento completo. +- [Trabajando con páginas](/pdf/es/python-net/working-with-pages/) - agregar, mover o eliminar, recortar páginas, agregar marcas de agua, sellos, etc. +- [Trabajando con imágenes](/pdf/es/python-net/working-with-images/) - agregar, extraer o eliminar imágenes de documentos PDF. +- [Adjuntos](/pdf/es/python-net/attachments/) - aprenderás cómo agregar y eliminar el adjunto de un PDF de forma programática con Python. +- [Navegación e Interacción](/pdf/es/python-net/navigation-and-interaction/) - trabajar con acciones, marcadores, navegar páginas. +- [Anotaciones](/pdf/es/python-net/annotations/) - las anotaciones permiten a los usuarios añadir contenido personalizado en las páginas de PDF. Puedes agregar, eliminar y modificar la anotación de los documentos PDF. +- [Trabajando con tablas](/pdf/es/python-net/working-with-tables/) - insertar, decorar tablas en PDF, extraer datos tabulares. +- [Trabajando con Formularios](/pdf/es/python-net/working-with-forms/) - trabajar con documentos PDF interactivos, agregar campos de formulario, extraer datos. +- [Trabajando con texto](/pdf/es/python-net/working-with-text/) - agregar, formatear, buscar y reemplazar texto en PDF. +- [Comparar documentos PDF](/pdf/es/python-net/compare-pdf-documents/) - posible comparar el contenido de documentos PDF. +- [Metadatos en PDFs](/pdf/es/python-net/pdf-file-metadata/) - obtener o establecer metadatos en documentos, tratando con datos XMP. +- [Trabajando con gráficos](/pdf/es/python-net/working-with-graphs/) - manipular con formas en la página. +- [Trabajando con Operadores](/pdf/es/python-net/working-with-operators/) - realizar operaciones de bajo nivel en PDF. +- [Artefactos](/pdf/es/python-net/artifacts/) - tratar con marcas de agua y otros objetos especiales en PDF. +- [Trabajar con capas PDF](/python-net/work-with-pdf-layers/) - bloquear capas, extraer elementos, aplanar y combinar capas PDF. diff --git a/es/python-net/advanced-operations/accessibility-tagged-pdf/_index.md b/es/python-net/advanced-operations/accessibility-tagged-pdf/_index.md new file mode 100644 index 000000000..bb9689783 --- /dev/null +++ b/es/python-net/advanced-operations/accessibility-tagged-pdf/_index.md @@ -0,0 +1,27 @@ +--- +title: Accesibilidad y Tagged PDFs en Python +linktitle: Accesibilidad. Tagged PDF +type: docs +weight: 180 +url: /es/python-net/accessibility-tagged-pdf/ +description: Aprenda cómo crear PDFs etiquetados accesibles en Python con Aspose.PDF for Python via .NET, incluyendo la estructura PDF/UA, extracción de contenido etiquetado, propiedades de estructura y tablas. +lastmod: "2026-05-11" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +Un documento Tagged PDF puede ser accedido de manera más eficaz por personas con discapacidades. Añadir etiquetas de accesibilidad a los archivos PDF ayuda a los lectores de pantalla y otras tecnologías de asistencia a interpretar correctamente encabezados, tablas, hipervínculos, marcadores, texto alternativo y el orden de lectura. + +## Qué puedes hacer con Tagged PDFs + +Utilice esta sección cuando necesite crear o inspeccionar documentos PDF accesibles que cumplan con los requisitos PDF/UA. Estos artículos cubren los flujos de trabajo principales de tagged-PDF para crear la estructura, leer contenido semántico, actualizar propiedades de estructura y trabajar con tablas accesibles. + +## Temas de Tagged PDF + +- [Crear Tagged PDF](/pdf/es/python-net/create-tagged-pdf/) +- [Extraer contenido etiquetado de PDFs etiquetados](/pdf/es/python-net/extract-tagged-content-from-tagged-pdfs/) +- [Configuración de propiedades de Structure Elements](/pdf/es/python-net/setting-structure-elements-properties/) +- [Trabajando con tablas en PDF etiquetados](/pdf/es/python-net/working-with-table-in-tagged-pdfs/) + +Los PDFs etiquetados son especialmente útiles cuando necesita documentos empresariales accesibles, informes compatibles o contenido estructurado semánticamente para reutilización a largo plazo. Si está comenzando desde cero, comience creando un PDF etiquetado, luego continúe con la inspección de la estructura y la actualización de propiedades a medida que su flujo de trabajo se vuelva más avanzado. diff --git a/es/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/_index.md b/es/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/_index.md new file mode 100644 index 000000000..cfa6725d6 --- /dev/null +++ b/es/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/_index.md @@ -0,0 +1,519 @@ +--- +title: Crear Tagged PDF en Python +linktitle: Crear Tagged PDF +type: docs +weight: 10 +url: /es/python-net/create-tagged-pdf/ +description: Aprende cómo crear documentos PDF etiquetados en Python con Aspose.PDF for Python via .NET, incluidos los Structure Elements PDF/UA, formularios accesibles, páginas TOC y etiquetado automático. +lastmod: "2026-05-11" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +Crear un Tagged PDF implica agregar (o crear) ciertos elementos al documento que permitirán que el documento sea validado de acuerdo con los requisitos de PDF/UA. Estos elementos a menudo se denominan Structure Elements. + +## Creando PDF etiquetado (Escenario simple) + +Para crear elementos de estructura en un documento Tagged PDF, Aspose.PDF ofrece métodos para crear elementos de estructura usando el [ITaggedContent](https://reference.aspose.com/pdf/python-net/aspose.pdf.tagged/itaggedcontent/) interfaz. Este ejemplo crea un documento Tagged PDF — un PDF con estructura semántica, lo que lo hace más accesible y compatible con normas como PDF/UA. +El siguiente fragmento de código muestra cómo crear Tagged PDF que contiene 2 elementos: encabezado y párrafo. + +```python +import aspose.pdf as ap +import sys +from os import path + +def create_tagged_pdf_document_simple(outfile): + + # Create PDF Document + with ap.Document() as document: + # Get Content for working with TaggedPdf + tagged_content = document.tagged_content + root_element = tagged_content.root_element + + # Set Title and Language for Document + tagged_content.set_title("Tagged Pdf Document") + tagged_content.set_language("en-US") + main_header = tagged_content.create_header_element() + main_header.set_text("Main Header") + paragraph_element = tagged_content.create_paragraph_element() + paragraph_element.set_text( + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " + + "Aenean nec lectus ac sem faucibus imperdiet. Sed ut erat ac magna ullamcorper hendrerit. " + + "Cras pellentesque libero semper, gravida magna sed, luctus leo. Fusce lectus odio, laoreet " + + "nec ullamcorper ut, molestie eu elit. Interdum et malesuada fames ac ante ipsum primis in faucibus. " + + "Aliquam lacinia sit amet elit ac consectetur. Donec cursus condimentum ligula, vitae volutpat " + + "sem tristique eget. Nulla in consectetur massa. Vestibulum vitae lobortis ante. Nulla ullamcorper " + + "pellentesque justo rhoncus accumsan. Mauris ornare eu odio non lacinia. Aliquam massa leo, rhoncus " + + "ac iaculis eget, tempus et magna. Sed non consectetur elit. Sed vulputate, quam sed lacinia luctus, " + + "ipsum nibh fringilla purus, vitae posuere risus odio id massa. Cras sed venenatis lacus." + ) + root_element.append_child(main_header, True) + root_element.append_child(paragraph_element, True) + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Creando Tagged PDF (Avanzado) + +```python +import aspose.pdf as ap +import sys +from os import path + +def create_tagged_pdf_document_adv(outfile): + # Create PDF Document + with ap.Document() as document: + # Get Content for working with TaggedPdf + tagged_content = document.tagged_content + root_element = tagged_content.root_element + + # Set Title and Language for Document + tagged_content.set_title("Tagged Pdf Document") + tagged_content.set_language("en-US") + + # Create Header Level 1 + header1 = tagged_content.create_header_element(1) + header1.set_text("Header Level 1") + + # Create Paragraph with Quotes + paragraph_with_quotes = tagged_content.create_paragraph_element() + paragraph_with_quotes.structure_text_state.font = ( + ap.text.FontRepository.find_font("Arial") + ) + position_settings = ap.tagged.PositionSettings() + position_settings.margin = ap.MarginInfo(10, 5, 10, 5) + paragraph_with_quotes.adjust_position(position_settings) + + # Create Span Element + span_element1 = tagged_content.create_span_element() + span_element1.set_text( + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean nec lectus ac sem faucibus imperdiet. " + "Sed ut erat ac magna ullamcorper hendrerit. Cras pellentesque libero semper, gravida magna sed, " + "luctus leo. Fusce lectus odio, laoreet nec ullamcorper ut, molestie eu elit. Interdum et malesuada " + "fames ac ante ipsum primis in faucibus. Aliquam lacinia sit amet elit ac consectetur. Donec cursus " + "condimentum ligula, vitae volutpat sem tristique eget. Nulla in consectetur massa. Vestibulum vitae " + "lobortis ante. Nulla ullamcorper pellentesque justo rhoncus accumsan. Mauris ornare eu odio non " + "lacinia. Aliquam massa leo, rhoncus ac iaculis eget, tempus et magna. Sed non consectetur elit." + ) + + # Create Quote Element + quote_element = tagged_content.create_quote_element() + quote_element.set_text( + "Sed vulputate, quam sed lacinia luctus, ipsum nibh fringilla purus, vitae posuere risus odio id massa." + ) + quote_element.structure_text_state.font_style = ( + ap.text.FontStyles.BOLD | ap.text.FontStyles.ITALIC + ) + + # Create Another Span Element + span_element2 = tagged_content.create_span_element() + span_element2.set_text(" Sed non consectetur elit.") + + # Append Children to Paragraph + paragraph_with_quotes.append_child(span_element1, True) + paragraph_with_quotes.append_child(quote_element, True) + paragraph_with_quotes.append_child(span_element2, True) + + # Append Header and Paragraph to Root Element + root_element.append_child(header1, True) + root_element.append_child(paragraph_with_quotes, True) + + # Save Tagged PDF Document + document.save(outfile) +``` + +Obtendremos el siguiente documento después de la creación: + +![Documento Tagged PDF con 2 elementos - Encabezado y Párrafo](taggedpdf-01.png) + +## Estilizando la estructura del texto + +Los PDF etiquetados son documentos estructurados que proporcionan características de accesibilidad y significado semántico al contenido. + +El ejemplo crea un documento PDF con características de accesibilidad utilizando una estructura de contenido etiquetado. Demuestra cómo crear un elemento de párrafo con estilo personalizado y metadatos de documento adecuados. + +```python +import aspose.pdf as ap +import sys +from os import path + +def add_style(outfile): + + # Create PDF Document + with ap.Document() as document: + # Get Content for work with TaggedPdf + tagged_content = document.tagged_content + + # Set Title and Language for Document + tagged_content.set_title("Tagged Pdf Document") + tagged_content.set_language("en-US") + + paragraph_element = tagged_content.create_paragraph_element() + tagged_content.root_element.append_child(paragraph_element, True) + + paragraph_element.structure_text_state.font_size = 18.0 + paragraph_element.structure_text_state.foreground_color = ap.Color.red + paragraph_element.structure_text_state.font_style = ap.text.FontStyles.ITALIC + + paragraph_element.set_text("Red italic text.") + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Ilustrando Structure Elements + +Los PDFs etiquetados son esenciales para el cumplimiento de accesibilidad y proporcionan contenido estructurado que puede ser interpretado correctamente por lectores de pantalla y otras tecnologías de asistencia. El siguiente fragmento de código muestra cómo crear un documento PDF etiquetado con una imagen incrustada: + +1. Crear PDF etiquetado con imagen. +1. Configurar documento. +1. Crear y configurar la figura. +1. Establecer posicionamiento. +1. Guardar documento. + +```python +import aspose.pdf as ap +import sys +from os import path + +def illustrate_structure_elements(imagefile, outfile): + # Create PDF Document + with ap.Document() as document: + # Get Content for work with TaggedPdf + tagged_content = document.tagged_content + + # Set Title and Language for Document + tagged_content.set_title("Tagged Pdf Document") + tagged_content.set_language("en-US") + figure1 = tagged_content.create_figure_element() + tagged_content.root_element.append_child(figure1, True) + figure1.alternative_text = "Figure One" + figure1.title = "Image 1" + figure1.set_tag("Fig1") + figure1.set_image(imagefile, 300) + # Adjust position + position_settings = ap.tagged.PositionSettings() + margin_info = ap.MarginInfo() + margin_info.left = 50 + margin_info.top = 20 + position_settings.margin = margin_info + figure1.adjust_position(position_settings) + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Validar Tagged PDF + +Aspose.PDF for Python via .NET brinda la capacidad de validar un Documento PDF/UA Tagged PDF. El método 'validate_tagged_pdf' valida documentos PDF contra la norma PDF/UA-1, que forma parte de la especificación ISO 14289 para documentos PDF accesibles. Esto asegura que los PDF sean accesibles para usuarios con discapacidades y tecnologías de asistencia. + +- Estructura del documento. Etiquetado semántico adecuado y estructura lógica. +- Texto alternativo. Texto alternativo para imágenes y elementos que no son texto. +- Orden de lectura. Secuencia lógica para lectores de pantalla. +- Color y contraste. Ratios de contraste suficientes. +- Formularios. Campos y etiquetas de formulario accesibles. +- Navegación. Marcadores adecuados y estructura de navegación. + +```python +import aspose.pdf as ap +import sys +from os import path + +def validate_tagged_pdf(infile, logfile): + # Open PDF document + with ap.Document(infile) as document: + is_valid = document.validate(logfile, ap.PdfFormat.PDF_UA_1) + print(f"Is Valid: {is_valid}") +``` + +## Ajustar posición de Estructura de Texto + +El siguiente fragmento de código muestra cómo ajustar la posición de Text Structure en el documento Tagged PDF: + +```python +import aspose.pdf as ap +import sys +from os import path + +def adjust_position(outfile): + # Create PDF Document + with ap.Document() as document: + # Get Content for work with TaggedPdf + tagged_content = document.tagged_content + + # Set Title and Language for Document + tagged_content.set_title("Tagged Pdf Document") + tagged_content.set_language("en-US") + + # Create paragraph + paragraph = tagged_content.create_paragraph_element() + tagged_content.root_element.append_child(paragraph, True) + paragraph.set_text("Text.") + + # Adjust position + position_settings = ap.tagged.PositionSettings() + margin_info = ap.MarginInfo() + margin_info.left = 300 + margin_info.top = 20 + margin_info.right = 0 + margin_info.bottom = 0 + position_settings.margin = margin_info + position_settings.horizontal_alignment = ap.HorizontalAlignment.NONE + position_settings.vertical_alignment = ap.VerticalAlignment.NONE + position_settings.is_first_paragraph_in_column = False + position_settings.is_kept_with_next = False + position_settings.is_in_new_page = False + position_settings.is_in_line_paragraph = False + paragraph.adjust_position(position_settings) + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Convertir PDF a PDF/UA-1 con etiquetado automático + +Este fragmento de código explica cómo convertir un PDF estándar en un archivo compatible con PDF/UA-1 (Accesibilidad Universal) utilizando Aspose.PDF for Python via .NET. + +PDF/UA garantiza que los documentos sean accesibles para usuarios con discapacidades y compatibles con tecnologías de asistencia como los lectores de pantalla. Durante la conversión, la biblioteca puede generar automáticamente el árbol de estructura lógica y aplicar etiquetas semánticas mediante el autoetiquetado incorporado y el reconocimiento de encabezados. + +Al configurar PdfFormatConversionOptions y habilitar AutoTaggingSettings, puedes transformar de manera eficiente los PDFs existentes en documentos accesibles sin editar manualmente la estructura. + +1. Cargar el documento fuente. +1. Crear opciones de conversión PDF/UA. +1. Habilitar el etiquetado automático. +1. Configurar reconocimiento de encabezados. +1. Adjunte la configuración de etiquetado a las opciones de conversión. +1. Ejecute el proceso de conversión. +1. Guarda el PDF accesible. + +```python +import aspose.pdf as ap +import sys +from os import path + +def convert_to_pdf_ua_with_automatic_tagging(infile, outfile, logfile): + # Create PDF Document + with ap.Document(infile) as document: + # Create conversion options + options = ap.PdfFormatConversionOptions( + logfile, ap.PdfFormat.PDF_UA_1, ap.ConvertErrorAction.DELETE + ) + # Create auto-tagging settings + # aspose.pdf.AutoTaggingSettings.default may be used to set the same settings as given below + auto_tagging_settings = ap.AutoTaggingSettings() + # Enable auto-tagging during the conversion process + auto_tagging_settings.enable_auto_tagging = True + # Use the heading recognition strategy that's optimal for the given document structure + auto_tagging_settings.heading_recognition_strategy = ( + ap.HeadingRecognitionStrategy.AUTO + ) + # Assign auto-tagging settings to be used during the conversion process + options.auto_tagging_settings = auto_tagging_settings + # During the conversion, the document logical structure will be automatically created + document.convert(options) + # Save PDF document + document.save(outfile) +``` + +## Crear un Tagged PDF con un Signature FormField accesible + +1. Crear un nuevo documento PDF. +1. Acceder al contenido etiquetado. +1. Crear un campo Form de firma. +1. Añade el campo al AcroForm. +1. Crear un elemento de formulario en la estructura de etiquetas. +1. Vincular el elemento Structure al campo Form. +1. Añade el elemento Form al árbol de estructura lógica. +1. Guardar el documento. + +```python +import aspose.pdf as ap +import sys +from os import path + +def create_pdf_with_tagged_form_field(outfile): + # Create PDF document + with ap.Document() as document: + document.pages.add() + # Get Content for work with TaggedPdf + tagged_content = document.tagged_content + root_element = tagged_content.root_element + # Create a visible signature form field (AcroForm) + signature_field = ap.forms.SignatureField( + document.pages[1], ap.Rectangle(50, 50, 100, 100, True) + ) + signature_field.partial_name = "Signature1" + signature_field.alternate_name = "signature 1" + + # Add the signature field to the document's AcroForm + document.form.add(signature_field) + + # Create a /Form structure element in the tag tree + form = tagged_content.create_form_element() + form.alternative_text = "form 1" + + # Link the /Form tag to the signature field via an /OBJR reference + form.tag(signature_field) + + # Add the /Form structure element to the document’s logical structure tree + root_element.append_child(form, True) + + # Save PDF document + document.save(outfile) +``` + +## Crear un Tagged PDF con una página de Tabla de contenido (TOC) + +Este ejemplo muestra cómo crear un documento PDF etiquetado con una página de Tabla de Contenidos (TOC) estructurada usando Aspose.PDF for Python via .NET. + +1. Crear un nuevo documento PDF. +1. Crear una página de tabla de contenidos dedicada. +1. Crear y registrar el elemento TOC en el árbol de estructura lógica. +1. Agregar una página de contenido. +1. Crear un elemento de encabezado. +1. Crear un elemento /TOCI. +1. Enlazar el encabezado al TOC. +1. Guardar el documento. + +```python +import aspose.pdf as ap +import sys +from os import path + +def create_pdf_with_toc_page(outfile): + # Create PDF document + with ap.Document() as document: + # Get tagged content for the PDF structure + content = document.tagged_content + root_element = content.root_element + content.set_language("en-US") + # Add the table of contents (TOC) page + toc_page = document.pages.add() + toc_page.toc_info = ap.TocInfo() + # Create a TOC structure element + toc_element = content.create_toc_element() + # Add the TOC element to the document structure tree + root_element.append_child(toc_element, True) + # Add a content page + document.pages.add() + # Create a header element and set its text + header = content.create_header_element(1) + header.set_text("1. Header") + # Add the header to the document structure + root_element.append_child(header, True) + # Create a TOC item (TOCI) element + toci = content.create_toci_element() + # Add the TOCI element to the TOC element + toc_element.append_child(toci, True) + # Add an entry to the TOC page and link it to the TOCI element + header.add_entry_to_toc_page(toc_page, toci) + # Add a logical reference to the header within the TOCI element + toci.add_ref(header) + # Save PDF document + document.save(outfile) +``` + +## Crear un PDF etiquetado avanzado con tabla de contenido jerárquica (TOC) + +Utilizando Aspose.PDF for Python via .NET, puede crear un documento PDF avanzado y totalmente etiquetado con una Tabla de Contenidos estructurada y jerárquica (TOC). + +1. Cree el documento y habilite el contenido etiquetado. +1. Agregar y configurar la página del TOC. +1. Cree el elemento de estructura /TOC. +1. Vincula el título de la página del TOC a un elemento de encabezado. +1. Agregar página de contenido principal y primer encabezado. +1. Crear una entrada de TOC para el encabezado. +1. Crear subsecciones anidadas con estructura de lista. +1. Agregar una segunda sección de nivel superior. +1. Guardar el documento. + +```python +import aspose.pdf as ap +import sys +from os import path + +def create_pdf_with_toc_page_advanced(outfile): + # Create PDF document + with ap.Document() as document: + # Get tagged content for the PDF structure + content = document.tagged_content + root_element = content.root_element + content.set_language("en-US") + # Add the table of contents (TOC) page + toc_page = document.pages.add() + toc_page.toc_info = ap.TocInfo() + toc_page.toc_info.title = ap.text.TextFragment("Table of Contents") + # Create a TOC structure element + toc_element = content.create_toc_element() + # Create a header element for the TOC page title + header_for_toc_page_title = content.create_header_element(1) + toc_element.link_toc_page_title_to_header_element( + toc_page, header_for_toc_page_title + ) + # Add the TOC page title header and TOC element to the document structure tree + root_element.append_child(header_for_toc_page_title, True) + root_element.append_child(toc_element, True) + # Add a content page + document.pages.add() + # Create a header element and set its text + header = content.create_header_element(1) + header.set_text("1. Header") + # Add the header to the document structure + root_element.append_child(header, True) + # Create a TOC item (TOCI) element + toci = content.create_toci_element() + # Add the TOCI element to the TOC element + toc_element.append_child(toci, True) + # Add an entry to the TOC page and link it to the TOCI element + header.add_entry_to_toc_page(toc_page, toci) + # Add a logical reference to the header within the TOCI element + toci.add_ref(header) + # Create a list element for TOCI subitems + list_element = content.create_list_element() + for i in range(1, 4): + # Create a list item (LI) element + li = content.create_list_li_element() + # Add the list item to the list element + list_element.append_child(li, True) + # Create a sub-header element and set its properties + sub_header = content.create_header_element(2) + sub_header.structure_text_state.font_size = 14 + sub_header.language = "en-US" + sub_header.set_text(f"1.{i} subheader ") + # Add an entry to the TOC page and link it to the LI element + sub_header.add_entry_to_toc_page(toc_page, li) + # Add a logical reference to the subheader element + li.add_ref(sub_header) + # Create a paragraph element and set its text and language + p = content.create_paragraph_element() + p.set_text( + "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + ) + p.language = "en-US" + # Add the sub-header and paragraph to the document structure + root_element.append_child(sub_header, True) + root_element.append_child(p, True) + # Add the list element as a child to the TOCI element + toci.append_child(list_element, True) + # --- Additional TOC header example --- + # Create a second header element (see comments above for header 1) + header2 = content.create_header_element(1) + header2.set_text("2. Header") + root_element.append_child(header2, True) + + toci2 = content.create_toci_element() + toc_element.append_child(toci2, True) + + header2.add_entry_to_toc_page(toc_page, toci2) + toci2.add_ref(header2) + # Save the PDF document + document.save(outfile) +``` + +## Temas relacionados de Tagged PDF + +- [Extraer contenido etiquetado de PDFs etiquetados](/pdf/es/python-net/extract-tagged-content-from-tagged-pdfs/) para inspeccionar el árbol de estructura lógica después de la creación. +- [Configuración de propiedades de Structure Elements](/pdf/es/python-net/setting-structure-elements-properties/) para refinar títulos, lenguaje, texto alternativo y texto de expansión. +- [Trabajando con tablas en PDF etiquetados](/pdf/es/python-net/working-with-table-in-tagged-pdfs/) cuando su documento accesible incluye tablas estructuradas. diff --git a/es/python-net/advanced-operations/accessibility-tagged-pdf/extract-tagged-content-from-tagged-pdfs/_index.md b/es/python-net/advanced-operations/accessibility-tagged-pdf/extract-tagged-content-from-tagged-pdfs/_index.md new file mode 100644 index 000000000..d43d21d3c --- /dev/null +++ b/es/python-net/advanced-operations/accessibility-tagged-pdf/extract-tagged-content-from-tagged-pdfs/_index.md @@ -0,0 +1,152 @@ +--- +title: Extraer contenido etiquetado de PDFs en Python +linktitle: Extraer contenido etiquetado +type: docs +weight: 20 +url: /es/python-net/extract-tagged-content-from-tagged-pdfs/ +description: Aprenda cómo extraer contenido PDF etiquetado en Python con Aspose.PDF for Python via .NET, incluido el acceso al contenido etiquetado, la estructura raíz y los Structure Elements hijo. +lastmod: "2026-05-11" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +En este artículo, aprenderá cómo extraer contenido etiquetado de documentos PDF usando Python. + +Utilice estos ejemplos cuando necesite inspeccionar un Tagged PDF, leer el árbol de estructura lógica o validar que los Structure Elements se crearon correctamente para flujos de trabajo de accesibilidad. + +## Obtener contenido de Tagged PDF + +Para obtener el contenido del documento PDF con texto etiquetado, Aspose.PDF ofrece [tagged_content](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties) propiedad de [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase. + +Cree un documento PDF avanzado y totalmente etiquetado con una tabla de contenido estructurada y jerárquica (TOC): + +1. Crea un nuevo objeto Document. +1. Accede a la propiedad tagged_content. +1. Establece el título del documento usando 'set_title()'. +1. Establece el idioma del documento usando 'set_language()'. +1. Guardar el documento. + +```python +import aspose.pdf as ap +from aspose.pycore import cast +import sys +from os import path + +# region Extract Tagged Content from PDF +def get_tagged_content(outfile): + # Create PDF Document + with ap.Document() as document: + # Get Content for work with Tagged PDF + tagged_content = document.tagged_content + + # Work with Tagged PDF content + # Set Title and Language for Document + tagged_content.set_title("Simple Tagged Pdf Document") + tagged_content.set_language("en-US") + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Obteniendo la estructura raíz + +Los PDFs etiquetados contienen un árbol de estructura lógica que define la estructura semántica del documento. El StructTreeRoot representa la raíz de este árbol lógico, mientras que el RootElement proporciona una interfaz para interactuar con el elemento de estructura de nivel superior del documento. + +El siguiente fragmento de código muestra cómo obtener la estructura raíz de un documento PDF etiquetado: + +1. Crea un nuevo documento PDF etiquetado. +1. Accede al contenido etiquetado y establece los metadatos. +1. Accede a StructTreeRoot y RootElement. +1. Guarda el PDF etiquetado. + +```python +import aspose.pdf as ap +from aspose.pycore import cast +import sys +from os import path + +def get_root_structure(outfile): + + # Create PDF Document + with ap.Document() as document: + # Get Content for work with Tagged PDF + tagged_content = document.tagged_content + + # Set Title and Language for Document + tagged_content.set_title("Tagged Pdf Document") + tagged_content.set_language("en-US") + + # Properties StructTreeRootElement and RootElement are used for access to + # StructTreeRoot object of pdf document and to root structure element (Document structure element). + struct_tree_root_element = tagged_content.struct_tree_root_element + root_element = tagged_content.root_element + + print(f"StructTreeRootElement: {struct_tree_root_element}") + print(f"RootElement: {root_element}") + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Accediendo a los elementos secundarios + +Los PDFs con etiquetado (Tagged PDFs) contienen un árbol de estructura lógica que define la jerarquía semántica del documento (títulos, párrafos, formularios, listas, etc.). Acceder y modificar estos elementos de estructura le permite: + +- Inspeccionar metadatos como el título, el idioma, actual_text y propiedades relacionadas con la accesibilidad +- Actualizar propiedades para mejorar la accesibilidad o la localización +- Ajustar programáticamente la estructura lógica del documento para el cumplimiento de PDF/UA + + El siguiente fragmento de código muestra cómo acceder a los elementos hijos de un Tagged PDF Document: + +```python +import aspose.pdf as ap +from aspose.pycore import cast +import sys +from os import path + +def access_child_elements(infile, outfile): + + # Open PDF Document + with ap.Document(infile) as document: + # Get Content for work with Tagged PDF + tagged_content = document.tagged_content + + # Access to root element(s) + element_list = tagged_content.struct_tree_root_element.child_elements + + for element in element_list: + if isinstance(element, ap.logicalstructure.StructureElement): + structure_element = cast(ap.logicalstructure.StructureElement, element) + # Get properties + print( + "StructureElement properties - " + f"title: {structure_element.title}, " + f"language: {structure_element.language}, " + f"actual_text: {structure_element.actual_text}, " + f"expansion_text: {structure_element.expansion_text}, " + f"alternative_text: {structure_element.alternative_text}" + ) + + # Access to child elements of first element in root element + element_list = tagged_content.root_element.child_elements[1].child_elements + for element in element_list: + if isinstance(element, ap.logicalstructure.StructureElement): + structure_element = element + + # Set properties + structure_element.title = "title" + structure_element.language = "fr-FR" + structure_element.actual_text = "actual text" + structure_element.expansion_text = "exp" + structure_element.alternative_text = "alt" + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Temas relacionados de Tagged PDF + +- [Crear Tagged PDF](/pdf/es/python-net/create-tagged-pdf/) para crear documentos etiquetados accesibles antes de inspeccionar su estructura. +- [Configuración de propiedades de Structure Elements](/pdf/es/python-net/setting-structure-elements-properties/) para actualizar las propiedades semánticas después de extraer los elementos de estructura. +- [Trabajando con tablas en PDF etiquetados](/pdf/es/python-net/working-with-table-in-tagged-pdfs/) para flujos de trabajo de accesibilidad de tablas etiquetadas. \ No newline at end of file diff --git a/es/python-net/advanced-operations/accessibility-tagged-pdf/setting-structure-elements-properties/_index.md b/es/python-net/advanced-operations/accessibility-tagged-pdf/setting-structure-elements-properties/_index.md new file mode 100644 index 000000000..c4597a2bd --- /dev/null +++ b/es/python-net/advanced-operations/accessibility-tagged-pdf/setting-structure-elements-properties/_index.md @@ -0,0 +1,644 @@ +--- +title: Establecer propiedades de elementos de estructura Tagged PDF en Python +linktitle: Configuración de propiedades de Structure Elements +type: docs +weight: 30 +url: /es/python-net/setting-structure-elements-properties/ +description: Aprenda cómo establecer propiedades de elementos de estructura Tagged PDF en Python con Aspose.PDF for Python via .NET, incluyendo título, idioma, texto real, texto alternativo y texto de expansión. +lastmod: "2026-05-11" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +Structure elements definen la jerarquía semántica de un documento PDF, como secciones, encabezados, párrafos o tablas. Al establecer propiedades como title, language, alternative_text, actual_text y expansion_text, mejora la accesibilidad y el significado semántico del PDF para tecnologías de asistencia como los lectores de pantalla. + +El siguiente fragmento de código muestra cómo establecer las propiedades de los Structure Elements de un Tagged PDF Document: + +1. Crea un nuevo documento PDF etiquetado. +1. Establecer metadatos del documento. +1. Crear Structure Elements. +1. Establecer propiedades de accesibilidad. +1. Guarda el PDF etiquetado. + +```python +import aspose.pdf as ap +import sys +from os import path + +def set_properties(outfile): + # Create PDF Document + with ap.Document() as document: + # Get Content for work with Tagged PDF + tagged_content = document.tagged_content + + # Set Title and Language for Document + tagged_content.set_title("Tagged Pdf Document") + tagged_content.set_language("en-US") + + # Create Structure Elements + root_element = tagged_content.root_element + + section_element = tagged_content.create_sect_element() + root_element.append_child(section_element, True) + + header_element = tagged_content.create_header_element(1) + section_element.append_child(header_element, True) + header_element.set_text("The Header") + + header_element.title = "Title" + header_element.language = "en-US" + header_element.alternative_text = "Alternative Text" + header_element.expansion_text = "Expansion Text" + header_element.actual_text = "Actual Text" + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Configuración de Elementos de Estructura de Texto + +Para establecer los elementos de estructura de texto de un Tagged PDF Document, Aspose.PDF ofrece [Elemento de párrafo](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/paragraphelement/) clase. El siguiente fragmento de código muestra cómo establecer los elementos de estructura de texto de un Documento PDF con etiquetas: + +```python +import aspose.pdf as ap +import sys +from os import path + +def set_text_elements(outfile): + # Create PDF Document + with ap.Document() as document: + # Get Content for work with Tagged PDF + tagged_content = document.tagged_content + + # Set Title and Language for Document + tagged_content.set_title("Tagged Pdf Document") + tagged_content.set_language("en-US") + + # Get Root Structure Elements + root_element = tagged_content.root_element + + paragraph_element = tagged_content.create_paragraph_element() + + # Set Text to Text Structure Element + paragraph_element.set_text("Paragraph.") + root_element.append_child(paragraph_element, True) + + # Save Tagged PDF Document + document.save(outfile) + +``` + +## Configuración de los Elementos de Estructura del Bloque de Texto + +Este ejemplo de Python usa Aspose.PDF para crear un Tagged PDF que incluye una jerarquía estructurada de encabezados y un párrafo, mejorando las características semánticas y de accesibilidad del documento. + +1. Crea un nuevo documento PDF etiquetado. +1. Establecer metadatos del documento. +1. Acceda al elemento de estructura raíz. +1. Crear encabezados de varios niveles. +1. Agregar encabezados a la estructura raíz. +1. Crea un elemento de párrafo. +1. Añadir párrafo a la estructura raíz. +1. Guarda el PDF etiquetado. + +El siguiente fragmento de código muestra cómo establecer los elementos de estructura de bloque de texto de un Documento PDF con etiquetas: + +```python +import aspose.pdf as ap +import sys +from os import path + +def set_text_block_elements(outfile): + # Create PDF Document + with ap.Document() as document: + # Get Content for work with Tagged PDF + tagged_content = document.tagged_content + # Set Title and Language for Document + tagged_content.set_title("Tagged Pdf Document") + tagged_content.set_language("en-US") + # Get Root Structure Element + root_element = tagged_content.root_element + h1 = tagged_content.create_header_element(1) + h2 = tagged_content.create_header_element(2) + h3 = tagged_content.create_header_element(3) + h4 = tagged_content.create_header_element(4) + h5 = tagged_content.create_header_element(5) + h6 = tagged_content.create_header_element(6) + h1.set_text("H1. Header of Level 1") + h2.set_text("H2. Header of Level 2") + h3.set_text("H3. Header of Level 3") + h4.set_text("H4. Header of Level 4") + h5.set_text("H5. Header of Level 5") + h6.set_text("H6. Header of Level 6") + root_element.append_child(h1, True) + root_element.append_child(h2, True) + root_element.append_child(h3, True) + root_element.append_child(h4, True) + root_element.append_child(h5, True) + root_element.append_child(h6, True) + p = tagged_content.create_paragraph_element() + p.set_text( + "P. Lorem ipsum dolor sit amet, consectetur adipiscing elit. " + "Aenean nec lectus ac sem faucibus imperdiet. Sed ut erat ac magna ullamcorper hendrerit." + " Cras pellentesque libero semper, gravida magna sed, luctus leo. " + "Fusce lectus odio, laoreet nec ullamcorper ut, molestie eu elit. " + "Interdum et malesuada fames ac ante ipsum primis in faucibus. " + "Aliquam lacinia sit amet elit ac consectetur. " + "Donec cursus condimentum ligula, vitae volutpat sem tristique eget. " + "Nulla in consectetur massa. Vestibulum vitae lobortis ante. " + "Nulla ullamcorper pellentesque justo rhoncus accumsan. " + "Mauris ornare eu odio non lacinia. Aliquam massa leo, rhoncus ac iaculis eget, tempus et magna. " + "Sed non consectetur elit. Sed vulputate, quam sed lacinia luctus, ipsum nibh fringilla purus, " + "vitae posuere risus odio id massa. Cras sed venenatis lacus." + ) + root_element.append_child(p, True) + # Save Tagged PDF Document + document.save(outfile) +``` + +## Configuración de elementos de estructura en línea + +Crear elementos de texto en línea (/Span) dentro de encabezados y párrafos en un PDF etiquetado usando Aspose.PDF for Python via .NET. + +El siguiente fragmento de código muestra cómo establecer elementos de estructura en línea de un documento Tagged PDF: + +```python +import aspose.pdf as ap +import sys +from os import path + +def set_inline_elements(outfile): + # Create PDF Document + with ap.Document() as document: + # Get Content for work with Tagged PDF + tagged_content = document.tagged_content + + # Set Title and Language for Document + tagged_content.set_title("Tagged Pdf Document") + tagged_content.set_language("en-US") + + # Get Root Structure Element + root_element = tagged_content.root_element + + header_element_h1 = tagged_content.create_header_element(1) + header_element_h2 = tagged_content.create_header_element(2) + header_element_h3 = tagged_content.create_header_element(3) + header_element_h4 = tagged_content.create_header_element(4) + header_element_h5 = tagged_content.create_header_element(5) + header_element_h6 = tagged_content.create_header_element(6) + root_element.append_child(header_element_h1, True) + root_element.append_child(header_element_h2, True) + root_element.append_child(header_element_h3, True) + root_element.append_child(header_element_h4, True) + root_element.append_child(header_element_h5, True) + root_element.append_child(header_element_h6, True) + + span_element_h11 = tagged_content.create_span_element() + span_element_h11.set_text("H1. ") + header_element_h1.append_child(span_element_h11, True) + span_element_h12 = tagged_content.create_span_element() + span_element_h12.set_text("Level 1 Header") + header_element_h1.append_child(span_element_h12, True) + + span_element_h21 = tagged_content.create_span_element() + span_element_h21.set_text("H2. ") + header_element_h2.append_child(span_element_h21, True) + span_element_h22 = tagged_content.create_span_element() + span_element_h22.set_text("Level 2 Header") + header_element_h2.append_child(span_element_h22, True) + + span_element_h31 = tagged_content.create_span_element() + span_element_h31.set_text("H3. ") + header_element_h3.append_child(span_element_h31, True) + span_element_h32 = tagged_content.create_span_element() + span_element_h32.set_text("Level 3 Header") + header_element_h3.append_child(span_element_h32, True) + + span_element_h41 = tagged_content.create_span_element() + span_element_h41.set_text("H4. ") + header_element_h4.append_child(span_element_h41, True) + span_element_h42 = tagged_content.create_span_element() + span_element_h42.set_text("Level 4 Header") + header_element_h4.append_child(span_element_h42, True) + + span_element_h51 = tagged_content.create_span_element() + span_element_h51.set_text("H5. ") + header_element_h5.append_child(span_element_h51, True) + span_element_h52 = tagged_content.create_span_element() + span_element_h52.set_text("Level 5 Header") + header_element_h5.append_child(span_element_h52, True) + + span_element_h61 = tagged_content.create_span_element() + span_element_h61.set_text("H6. ") + header_element_h6.append_child(span_element_h61, True) + span_element_h62 = tagged_content.create_span_element() + span_element_h62.set_text("Level 6 Header") + header_element_h6.append_child(span_element_h62, True) + + paragraph_element = tagged_content.create_paragraph_element() + paragraph_element.set_text("P. ") + root_element.append_child(paragraph_element, True) + span_element_1 = tagged_content.create_span_element() + span_element_1.set_text( + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " + ) + paragraph_element.append_child(span_element_1, True) + span_element_2 = tagged_content.create_span_element() + span_element_2.set_text("Aenean nec lectus ac sem faucibus imperdiet. ") + paragraph_element.append_child(span_element_2, True) + span_element_3 = tagged_content.create_span_element() + span_element_3.set_text("Sed ut erat ac magna ullamcorper hendrerit. ") + paragraph_element.append_child(span_element_3, True) + span_element_4 = tagged_content.create_span_element() + span_element_4.set_text( + "Cras pellentesque libero semper, gravida magna sed, luctus leo. " + ) + paragraph_element.append_child(span_element_4, True) + span_element_5 = tagged_content.create_span_element() + span_element_5.set_text( + "Fusce lectus odio, laoreet nec ullamcorper ut, molestie eu elit. " + ) + paragraph_element.append_child(span_element_5, True) + span_element_6 = tagged_content.create_span_element() + span_element_6.set_text( + "Interdum et malesuada fames ac ante ipsum primis in faucibus. " + ) + paragraph_element.append_child(span_element_6, True) + span_element_7 = tagged_content.create_span_element() + span_element_7.set_text( + "Aliquam lacinia sit amet elit ac consectetur. Donec cursus condimentum ligula, vitae volutpat sem tristique eget. " + ) + paragraph_element.append_child(span_element_7, True) + span_element_8 = tagged_content.create_span_element() + span_element_8.set_text( + "Nulla in consectetur massa. Vestibulum vitae lobortis ante. Nulla ullamcorper pellentesque justo rhoncus accumsan. " + ) + paragraph_element.append_child(span_element_8, True) + span_element_9 = tagged_content.create_span_element() + span_element_9.set_text( + "Mauris ornare eu odio non lacinia. Aliquam massa leo, rhoncus ac iaculis eget, tempus et magna. Sed non consectetur elit. " + ) + paragraph_element.append_child(span_element_9, True) + span_element_10 = tagged_content.create_span_element() + span_element_10.set_text( + "Sed vulputate, quam sed lacinia luctus, ipsum nibh fringilla purus, vitae posuere risus odio id massa. Cras sed venenatis lacus." + ) + paragraph_element.append_child(span_element_10, True) + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Configuración del nombre de etiqueta personalizado + +Establecer nombres de etiquetas personalizados para la estructura y los elementos en línea en un PDF etiquetado usando Aspose.PDF for Python via .NET. + +El siguiente fragmento de código muestra cómo establecer un nombre de etiqueta personalizado: + +1. Crea un nuevo documento PDF etiquetado. +1. Establecer metadatos del documento. +1. Crear un elemento de sección. +1. Crea elementos de párrafo con etiquetas personalizadas. +1. Cree elementos span en línea con etiquetas personalizadas. +1. Guarda el PDF etiquetado. + +```python +import aspose.pdf as ap +import sys +from os import path + +def set_tag_name(outfile): + # Create PDF Document + with ap.Document() as document: + # Get Content for work with Tagged PDF + tagged_content = document.tagged_content + + # Set Title and Language for Document + tagged_content.set_title("Tagged Pdf Document") + tagged_content.set_language("en-US") + + # Create Logical Structure Elements + section_element = tagged_content.create_sect_element() + tagged_content.root_element.append_child(section_element, True) + + paragraph_element1 = tagged_content.create_paragraph_element() + paragraph_element2 = tagged_content.create_paragraph_element() + paragraph_element3 = tagged_content.create_paragraph_element() + paragraph_element4 = tagged_content.create_paragraph_element() + + paragraph_element1.set_text("P1. ") + paragraph_element2.set_text("P2. ") + paragraph_element3.set_text("P3. ") + paragraph_element4.set_text("P4. ") + + paragraph_element1.set_tag("P1") + paragraph_element2.set_tag("Para") + paragraph_element3.set_tag("Para") + paragraph_element4.set_tag("Paragraph") + + section_element.append_child(paragraph_element1, True) + section_element.append_child(paragraph_element2, True) + section_element.append_child(paragraph_element3, True) + section_element.append_child(paragraph_element4, True) + + span_element1 = tagged_content.create_span_element() + span_element2 = tagged_content.create_span_element() + span_element3 = tagged_content.create_span_element() + span_element4 = tagged_content.create_span_element() + + span_element1.set_text("Span 1.") + span_element2.set_text("Span 2.") + span_element3.set_text("Span 3.") + span_element4.set_text("Span 4.") + + span_element1.set_tag("SPAN") + span_element2.set_tag("Sp") + span_element3.set_tag("Sp") + span_element4.set_tag("TheSpan") + + paragraph_element1.append_child(span_element1, True) + paragraph_element2.append_child(span_element2, True) + paragraph_element3.append_child(span_element3, True) + paragraph_element4.append_child(span_element4, True) + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Agregar elemento de estructura a los elementos + +**Esta función es compatible con la versión 19.4 o posterior.** + +Crear enlaces y elementos de imagen en un PDF etiquetado usando Aspose.PDF for Python via .NET. + +El siguiente fragmento de código muestra cómo establecer elementos de estructura en un párrafo con texto de un documento Tagged PDF: + +```python +import aspose.pdf as ap +import sys +from os import path + +def set_elements(imagefile, outfile): + # Create PDF document + with ap.Document() as document: + tagged_content = document.tagged_content + + # Setting Title and Nature Language for document + tagged_content.set_title("Link Elements Example") + tagged_content.set_language("en-US") + + # Getting Root structure element (Document structure element) + root_element = tagged_content.root_element + + paragraph_element_1 = tagged_content.create_paragraph_element() + root_element.append_child(paragraph_element_1, True) + link_element_1 = tagged_content.create_link_element() + paragraph_element_1.append_child(link_element_1, True) + link_element_1.hyperlink = ap.WebHyperlink("http://google.com") + link_element_1.set_text("Google") + link_element_1.alternate_descriptions = "Link to Google" + + paragraph_element_2 = tagged_content.create_paragraph_element() + root_element.append_child(paragraph_element_2, True) + link_element_2 = tagged_content.create_link_element() + paragraph_element_2.append_child(link_element_2, True) + link_element_2.hyperlink = ap.WebHyperlink("http://google.com") + span_element_2 = tagged_content.create_span_element() + span_element_2.set_text("Google") + link_element_2.append_child(span_element_2, True) + link_element_2.alternate_descriptions = "Link to Google" + + paragraph_element_3 = tagged_content.create_paragraph_element() + root_element.append_child(paragraph_element_3, True) + link_element_3 = tagged_content.create_link_element() + paragraph_element_3.append_child(link_element_3, True) + link_element_3.hyperlink = ap.WebHyperlink("http://google.com") + span_element_31 = tagged_content.create_span_element() + span_element_31.set_text("G") + span_element_32 = tagged_content.create_span_element() + span_element_32.set_text("Google") + link_element_3.append_child(span_element_31, True) + link_element_3.set_text("-") + link_element_3.append_child(span_element_32, True) + link_element_3.alternate_descriptions = "Link to Google" + + paragraph_element_4 = tagged_content.create_paragraph_element() + root_element.append_child(paragraph_element_4, True) + link_element_4 = tagged_content.create_link_element() + paragraph_element_4.append_child(link_element_4, True) + link_element_4.hyperlink = ap.WebHyperlink("http://google.com") + link_element_4.set_text( + "The multiline link: Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google" + ) + link_element_4.alternate_descriptions = "Link to Google (multiline)" + + paragraph_element_5 = tagged_content.create_paragraph_element() + root_element.append_child(paragraph_element_5, True) + link_element_5 = tagged_content.create_link_element() + paragraph_element_5.append_child(link_element_5, True) + link_element_5.hyperlink = ap.WebHyperlink("http://google.com") + figure_element_5 = tagged_content.create_figure_element() + figure_element_5.set_image(imagefile, 1200) + figure_element_5.alternative_text = "Google icon" + link_layout_attributes = link_element_5.attributes.get_attributes( + ap.logicalstructure.AttributeOwnerStandard.LAYOUT + ) + placement_attribute = ap.logicalstructure.StructureAttribute( + ap.logicalstructure.AttributeKey.PLACEMENT + ) + placement_attribute.set_name_value( + ap.logicalstructure.AttributeName.PLACEMENT_BLOCK + ) + link_layout_attributes.set_attribute(placement_attribute) + link_element_5.append_child(figure_element_5, True) + link_element_5.alternate_descriptions = "Link to Google" + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Configuración del elemento de enlace de estructura + +La API Aspose.PDF for Python via .NET también permite agregar elementos de estructura de enlaces. + +El siguiente fragmento de código muestra cómo agregar un elemento de estructura de enlace en un documento Tagged PDF: + +```python +import aspose.pdf as ap +import sys +from os import path + +def add_link_element(outfile): + # Create PDF document + with ap.Document() as document: + tagged_content = document.tagged_content + + # Setting Title and Nature Language for document + tagged_content.set_title("Text Elements Example") + tagged_content.set_language("en-US") + + # Getting Root structure element (Document structure element) + root_element = tagged_content.root_element + + paragraph_element_1 = tagged_content.create_paragraph_element() + root_element.append_child(paragraph_element_1, True) + span_element_11 = tagged_content.create_span_element() + span_element_11.set_text("Span_11") + span_element_12 = tagged_content.create_span_element() + span_element_12.set_text(" and Span_12.") + paragraph_element_1.set_text("Paragraph with ") + paragraph_element_1.append_child(span_element_11, True) + paragraph_element_1.append_child(span_element_12, True) + + paragraph_element_2 = tagged_content.create_paragraph_element() + root_element.append_child(paragraph_element_2, True) + span_element_21 = tagged_content.create_span_element() + span_element_21.set_text("Span_21") + span_element_22 = tagged_content.create_span_element() + span_element_22.set_text("Span_22.") + paragraph_element_2.append_child(span_element_21, True) + paragraph_element_2.set_text(" and ") + paragraph_element_2.append_child(span_element_22, True) + + paragraph_element_3 = tagged_content.create_paragraph_element() + root_element.append_child(paragraph_element_3, True) + span_element_31 = tagged_content.create_span_element() + span_element_31.set_text("Span_31") + span_element_32 = tagged_content.create_span_element() + span_element_32.set_text(" and Span_32") + paragraph_element_3.append_child(span_element_31, True) + paragraph_element_3.append_child(span_element_32, True) + paragraph_element_3.set_text(".") + + paragraph_element_4 = tagged_content.create_paragraph_element() + root_element.append_child(paragraph_element_4, True) + span_element_41 = tagged_content.create_span_element() + span_element_411 = tagged_content.create_span_element() + span_element_411.set_text("Span_411, ") + span_element_41.set_text("Span_41, ") + span_element_41.append_child(span_element_411, True) + span_element_42 = tagged_content.create_span_element() + span_element_421 = tagged_content.create_span_element() + span_element_421.set_text("Span 421 and ") + span_element_42.append_child(span_element_421, True) + span_element_42.set_text("Span_42") + paragraph_element_4.append_child(span_element_41, True) + paragraph_element_4.append_child(span_element_42, True) + paragraph_element_4.set_text(".") + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Configuración del elemento de estructura de nota + +Aspose.PDF for Python via .NET API también permite agregar [ElementoNota](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/noteelement/) en un documento PDF etiquetado. El siguiente fragmento de código muestra cómo agregar un elemento de nota en un documento PDF etiquetado: + +```python +import aspose.pdf as ap +import sys +from os import path + +def set_note_element(outfile): + # Create PDF Document + with ap.Document() as document: + tagged_content = document.tagged_content + + tagged_content.set_title("Sample of Note Elements") + tagged_content.set_language("en-US") + + # Add Paragraph Element + paragraph_element = tagged_content.create_paragraph_element() + tagged_content.root_element.append_child(paragraph_element, True) + + # Add NoteElement + note_element_1 = tagged_content.create_note_element() + paragraph_element.append_child(note_element_1, True) + note_element_1.set_text("Note with auto generate ID. ") + + # Add NoteElement + note_element_2 = tagged_content.create_note_element() + paragraph_element.append_child(note_element_2, True) + note_element_2.set_text("Note with ID = 'note_002'. ") + note_element_2.set_id("note_002") + + # Add NoteElement + note_element_3 = tagged_content.create_note_element() + paragraph_element.append_child(note_element_3, True) + note_element_3.set_text("Note with ID = 'note_003'. ") + note_element_3.set_id("note_003") + + # Must throw exception - Aspose.Pdf.Tagged.TaggedException : Structure element with ID='note_002' already exists + # note_element_3.set_id("note_002") + + # Resultant document does not compliance to PDF/UA If ClearId() used for Note Structure Element + # note_element_3.clear_id() + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Cómo establecer el idioma y el título + +Aspose.PDF for Python via .NET API también permite establecer el idioma y el título de un documento de acuerdo con la especificación PDF/UA. El idioma puede configurarse tanto para todo el documento como para sus elementos estructurales separados. El siguiente fragmento de código muestra cómo establecer el idioma y el título en un documento Tagged PDF: + +1. Crea un nuevo documento PDF etiquetado. +1. Establecer título y idioma del documento. +1. Crear un elemento de encabezado. +1. Añadir párrafos con idiomas específicos. +1. Guarda el PDF etiquetado. + +```python +import aspose.pdf as ap +import sys +from os import path + +def set_language_and_title(outfile): + # Create PDF Document + with ap.Document() as document: + # Get TaggedContent + tagged_content = document.tagged_content + + # Set Title and Language + tagged_content.set_title("Example Tagged Document") + tagged_content.set_language("en-US") + + # Header (en-US, inherited from document) + header_element = tagged_content.create_header_element(1) + header_element.set_text("Phrase on different languages") + tagged_content.root_element.append_child(header_element, True) + + # Paragraph (English) + paragraph_element_en = tagged_content.create_paragraph_element() + paragraph_element_en.set_text("Hello, World!") + paragraph_element_en.language = "en-US" + tagged_content.root_element.append_child(paragraph_element_en, True) + + # Paragraph (German) + paragraph_element_de = tagged_content.create_paragraph_element() + paragraph_element_de.set_text("Hallo Welt!") + paragraph_element_de.language = "de-DE" + tagged_content.root_element.append_child(paragraph_element_de, True) + + # Paragraph (French) + paragraph_element_fr = tagged_content.create_paragraph_element() + paragraph_element_fr.set_text("Bonjour le monde!") + paragraph_element_fr.language = "fr-FR" + tagged_content.root_element.append_child(paragraph_element_fr, True) + + # Paragraph (Spanish) + paragraph_element_sp = tagged_content.create_paragraph_element() + paragraph_element_sp.set_text("¡Hola Mundo!") + paragraph_element_sp.language = "es-ES" + tagged_content.root_element.append_child(paragraph_element_sp, True) + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Temas relacionados de Tagged PDF + +- [Crear Tagged PDF](/pdf/es/python-net/create-tagged-pdf/) para generar los elementos de estructura antes de actualizar sus propiedades. +- [Extraer contenido etiquetado de PDFs etiquetados](/pdf/es/python-net/extract-tagged-content-from-tagged-pdfs/) para inspeccionar los nodos de estructura existentes y los metadatos. +- [Trabajando con tablas en PDF etiquetados](/pdf/es/python-net/working-with-table-in-tagged-pdfs/) si necesita aplicar propiedades accesibles a las estructuras de tabla. diff --git a/es/python-net/advanced-operations/accessibility-tagged-pdf/working-with-table-in-tagged-pdfs/_index.md b/es/python-net/advanced-operations/accessibility-tagged-pdf/working-with-table-in-tagged-pdfs/_index.md new file mode 100644 index 000000000..a1a0a355f --- /dev/null +++ b/es/python-net/advanced-operations/accessibility-tagged-pdf/working-with-table-in-tagged-pdfs/_index.md @@ -0,0 +1,531 @@ +--- +title: Trabajar con tablas en PDFs etiquetados en Python +linktitle: Trabajando con tablas en PDF etiquetados +type: docs +weight: 40 +url: /es/python-net/working-with-table-in-tagged-pdfs/ +description: Aprenda cómo trabajar con tablas accesibles en PDFs etiquetados en Python con Aspose.PDF for Python via .NET, incluyendo estructura, intervalos, alineación y marcado de tabla compatible con PDF/UA. +lastmod: "2026-05-11" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +## Crear tabla en Tagged PDF + +Siguiendo los pasos anteriores, puedes generar una tabla semánticamente rica y accesible en un documento PDF usando Aspose.PDF for Python. El archivo resultante cumple con los estándares de conformidad PDF/UA-1, garantizando la compatibilidad con lectores de pantalla y tecnologías de asistencia. Esto es ideal para casos de uso que involucren cumplimiento normativo, auditoría de accesibilidad y publicación de contenido inclusivo. + +El siguiente fragmento de código muestra, cómo crear una tabla en el documento Tagged PDF: + +1. Crea un nuevo documento PDF etiquetado. +1. Establecer metadatos del documento. +1. Crear la estructura de la tabla. +1. Crear fila de encabezado de tabla. +1. Crear filas del cuerpo de la tabla con celdas. +1. Crear fila de pie de tabla. +1. Establecer el atributo de resumen de la tabla. +1. Guardar el Tagged PDF. + +```python +import aspose.pdf as ap +import sys +from os import path + +def create_table(outfile): + # Create PDF document + with ap.Document() as document: + tagged_content = document.tagged_content + + tagged_content.set_title("Example table") + tagged_content.set_language("en-US") + + # Get root structure element + root_element = tagged_content.root_element + + table_element = tagged_content.create_table_element() + root_element.append_child(table_element, True) + + table_element.border = ap.BorderInfo(ap.BorderSide.ALL, 1.2, ap.Color.dark_blue) + + table_t_head_element = table_element.create_t_head() + table_t_body_element = table_element.create_t_body() + table_t_foot_element = table_element.create_t_foot() + row_count = 50 + col_count = 4 + + head_tr_element = table_t_head_element.create_tr() + head_tr_element.alternative_text = "Head Row" + head_tr_element.background_color = ap.Color.light_gray + + for column_index in range(col_count): + th_element = head_tr_element.create_th() + th_element.set_text(f"Head {column_index}") + + th_element.background_color = ap.Color.green_yellow + th_element.border = ap.BorderInfo(ap.BorderSide.ALL, 4.0, ap.Color.gray) + + th_element.is_no_border = True + th_element.margin = ap.MarginInfo(16.0, 2.0, 8.0, 2.0) + + th_element.alignment = ap.HorizontalAlignment.RIGHT + + for row_index in range(row_count): + tr_element = table_t_body_element.create_tr() + tr_element.alternative_text = f"Row {row_index}" + + for column_index in range(col_count): + col_span = 1 + row_span = 1 + + if column_index == 1 and row_index == 1: + col_span = 2 + row_span = 2 + elif (row_index == 1 and column_index == 2) or ( + row_index == 2 and column_index in (1, 2) + ): + continue + + td_element = tr_element.create_td() + td_element.set_text(f"Cell [{row_index}, {column_index}]") + + td_element.background_color = ap.Color.yellow + td_element.border = ap.BorderInfo(ap.BorderSide.ALL, 4.0, ap.Color.gray) + + td_element.is_no_border = False + td_element.margin = ap.MarginInfo(8.0, 2.0, 8.0, 2.0) + + td_element.alignment = ap.HorizontalAlignment.CENTER + + cell_text_state = ap.text.TextState() + cell_text_state.foreground_color = ap.Color.dark_blue + cell_text_state.font_size = 7.5 + cell_text_state.font_style = ap.text.FontStyles.BOLD + cell_text_state.font = ap.text.FontRepository.find_font("Arial") + td_element.default_cell_text_state = cell_text_state + + td_element.is_word_wrapped = True + td_element.vertical_alignment = ap.VerticalAlignment.CENTER + + td_element.col_span = col_span + td_element.row_span = row_span + + foot_tr_element = table_t_foot_element.create_tr() + foot_tr_element.alternative_text = "Foot Row" + foot_tr_element.background_color = ap.Color.light_sea_green + + for column_index in range(col_count): + td_element = foot_tr_element.create_td() + td_element.set_text(f"Foot {column_index}") + + td_element.alignment = ap.HorizontalAlignment.CENTER + td_element.structure_text_state.font_size = 7 + td_element.structure_text_state.font_style = ap.text.FontStyles.BOLD + + table_attributes = table_element.attributes.get_attributes( + ap.logicalstructure.AttributeOwnerStandard.TABLE + ) + summary_attribute = ap.logicalstructure.StructureAttribute( + ap.logicalstructure.AttributeKey.SUMMARY + ) + summary_attribute.set_string_value("The summary text for table") + table_attributes.set_attribute(summary_attribute) + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Elemento de tabla de estilo + +1. Crea un nuevo documento PDF etiquetado. +1. Establecer título y idioma del documento. +1. Crear elemento de estructura de tabla. +1. Configurar filas y columnas repetidas. +1. Agregar encabezado, cuerpo y pie de página. +1. Guarda el documento PDF etiquetado. + +El siguiente fragmento de código muestra cómo dar estilo a una tabla en un documento Tagged PDF: + +```python +import aspose.pdf as ap +import sys +from os import path + +def style_table(outfile): + # Create PDF document + with ap.Document() as document: + tagged_content = document.tagged_content + + tagged_content.set_title("Example table style") + tagged_content.set_language("en-US") + + # Get root structure element + root_element = tagged_content.root_element + + # Create table structure element + table_element = tagged_content.create_table_element() + root_element.append_child(table_element, True) + + table_element.background_color = ap.Color.beige + table_element.border = ap.BorderInfo(ap.BorderSide.ALL, 0.80, ap.Color.gray) + table_element.alignment = ap.HorizontalAlignment.CENTER + table_element.broken = ap.TableBroken.VERTICAL + table_element.column_adjustment = ap.ColumnAdjustment.AUTO_FIT_TO_WINDOW + table_element.column_widths = "80 80 80 80 80" + table_element.default_cell_border = ap.BorderInfo( + ap.BorderSide.ALL, 0.50, ap.Color.dark_blue + ) + table_element.default_cell_padding = ap.MarginInfo(16.0, 2.0, 8.0, 2.0) + table_element.default_cell_text_state.foreground_color = ap.Color.dark_cyan + table_element.default_cell_text_state.font_size = 8.0 + table_element.default_column_width = "70" + + table_element.is_broken = False + table_element.is_borders_included = True + + table_element.left = 0.0 + table_element.top = 40.0 + + table_element.repeating_columns_count = 2 + table_element.repeating_rows_count = 3 + row_style = ap.text.TextState() + row_style.background_color = ap.Color.light_coral + table_element.repeating_rows_style = row_style + + table_t_head_element = table_element.create_t_head() + table_t_body_element = table_element.create_t_body() + table_t_foot_element = table_element.create_t_foot() + row_count = 10 + col_count = 5 + + head_tr_element = table_t_head_element.create_tr() + head_tr_element.alternative_text = "Head Row" + + for col_index in range(col_count): + th_element = head_tr_element.create_th() + th_element.set_text(f"Head {col_index}") + + for row_index in range(row_count): + tr_element = table_t_body_element.create_tr() + tr_element.alternative_text = f"Row {row_index}" + + for col_index in range(col_count): + td_element = tr_element.create_td() + td_element.set_text(f"Cell [{row_index}, {col_index}]") + + foot_tr_element = table_t_foot_element.create_tr() + foot_tr_element.alternative_text = "Foot Row" + + for col_index in range(col_count): + td_element = foot_tr_element.create_td() + td_element.set_text(f"Foot {col_index}") + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Estilo de fila de tabla + +Aspose.PDF for Python via .NET permite aplicar estilo a una fila de tabla en un documento Tagged PDF. Para aplicar estilo a una fila de tabla, puede usar las propiedades de [TableTRElement](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/) clase. La siguiente es la lista de propiedades que puedes usar para dar estilo a una fila de tabla: + +- [color_de_fondo](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [borde](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [borde_de_celda_predeterminado](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [altura_mínima_fila](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [altura_fija_de_fila](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [es_en_nueva_pagina](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [está_fila_rota](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [estado_predeterminado_celda_texto](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [padding_celda_predeterminado](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [alineación_vertical](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). + +El siguiente fragmento de código muestra cómo dar estilo a una fila de tabla en el documento Tagged PDF: + +```python +import aspose.pdf as ap +import sys +from os import path + +def style_table_row(outfile): + # Create PDF document + with ap.Document() as document: + tagged_content = document.tagged_content + + tagged_content.set_title("Example table style") + tagged_content.set_language("en-US") + + # Get root structure element + root_element = tagged_content.root_element + + # Create table structure element + table_element = tagged_content.create_table_element() + root_element.append_child(table_element, True) + table_t_head_element = table_element.create_t_head() + table_t_body_element = table_element.create_t_body() + table_t_foot_element = table_element.create_t_foot() + row_count = 7 + col_count = 3 + head_tr_element = table_t_head_element.create_tr() + head_tr_element.alternative_text = "Head Row" + for col_index in range(col_count): + th_element = head_tr_element.create_th() + th_element.set_text(f"Head {col_index}") + for row_index in range(row_count): + tr_element = table_t_body_element.create_tr() + tr_element.alternative_text = f"Row {row_index}" + tr_element.background_color = ap.Color.light_goldenrod_yellow + tr_element.border = ap.BorderInfo( + ap.BorderSide.ALL, 0.75, ap.Color.dark_gray + ) + tr_element.default_cell_border = ap.BorderInfo( + ap.BorderSide.ALL, 0.50, ap.Color.blue + ) + tr_element.min_row_height = 100.0 + tr_element.fixed_row_height = 120.0 + tr_element.is_in_new_page = row_index % 3 == 1 + tr_element.is_row_broken = True + + cell_text_state = ap.text.TextState() + cell_text_state.foreground_color = ap.Color.red + tr_element.default_cell_text_state = cell_text_state + tr_element.default_cell_padding = ap.MarginInfo(16.0, 2.0, 8.0, 2.0) + tr_element.vertical_alignment = ap.VerticalAlignment.BOTTOM + for col_index in range(col_count): + td_element = tr_element.create_td() + td_element.set_text("Cell [{0}, {1}]".format(row_index, col_index)) + + foot_tr_element = table_t_foot_element.create_tr() + foot_tr_element.alternative_text = "Foot Row" + + for col_index in range(col_count): + td_element = foot_tr_element.create_td() + td_element.set_text("Foot {}".format(col_index)) + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Estilo de celda de tabla + +Aspose.PDF for Python via .NET permite aplicar estilo a una celda de tabla en un documento Tagged PDF. Para aplicar estilo a una celda de tabla, puedes usar las propiedades de [Elemento de celda de tabla](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/) clase. La siguiente es la lista de propiedades que puede usar para dar estilo a una celda de tabla: + +- [color_de_fondo](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [borde](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [sin_borde](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [margen](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [alineación](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [estado_predeterminado_celda_texto](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [es_palabra_envuelta](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [alineación_vertical](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [col_span](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [row_span](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). + +El siguiente fragmento de código muestra cómo aplicar estilo a una celda de tabla en el documento Tagged PDF: + +```python +import aspose.pdf as ap +import sys +from os import path + +def style_table_cell(outfile): + # Create PDF document + with ap.Document() as document: + tagged_content = document.tagged_content + + tagged_content.set_title("Example table cell style") + tagged_content.set_language("en-US") + + # Get root structure element + root_element = tagged_content.root_element + + # Create table structure element + table_element = tagged_content.create_table_element() + root_element.append_child(table_element, True) + + table_t_head_element = table_element.create_t_head() + table_t_body_element = table_element.create_t_body() + table_t_foot_element = table_element.create_t_foot() + row_count = 4 + col_count = 4 + + head_tr_element = table_t_head_element.create_tr() + head_tr_element.alternative_text = "Head Row" + + for col_index in range(col_count): + th_element = head_tr_element.create_th() + th_element.set_text("Head {}".format(col_index)) + + th_element.background_color = ap.Color.green_yellow + th_element.border = ap.BorderInfo(ap.BorderSide.ALL, 4.0, ap.Color.gray) + + th_element.is_no_border = True + th_element.margin = ap.MarginInfo(16.0, 2.0, 8.0, 2.0) + + th_element.alignment = ap.HorizontalAlignment.RIGHT + + for row_index in range(row_count): + tr_element = table_t_body_element.create_tr() + tr_element.alternative_text = "Row {}".format(row_index) + + for col_index in range(col_count): + col_span = 1 + row_span = 1 + + if col_index == 1 and row_index == 1: + col_span = 2 + row_span = 2 + elif (row_index == 1 and col_index == 2) or ( + row_index == 2 and col_index in (1, 2) + ): + continue + + td_element = tr_element.create_td() + td_element.set_text("Cell [{}, {}]".format(row_index, col_index)) + + td_element.background_color = ap.Color.yellow + td_element.border = ap.BorderInfo(ap.BorderSide.ALL, 4.0, ap.Color.gray) + + td_element.is_no_border = False + td_element.margin = ap.MarginInfo(8.0, 2.0, 8.0, 2.0) + + td_element.alignment = ap.HorizontalAlignment.CENTER + + cell_text_state = ap.text.TextState() + cell_text_state.foreground_color = ap.Color.dark_blue + cell_text_state.font_size = 7.5 + cell_text_state.font_style = ap.text.FontStyles.BOLD + cell_text_state.font = ap.text.FontRepository.find_font("Arial") + td_element.default_cell_text_state = cell_text_state + + td_element.is_word_wrapped = True + td_element.vertical_alignment = ap.VerticalAlignment.CENTER + + td_element.col_span = col_span + td_element.row_span = row_span + + foot_tr_element = table_t_foot_element.create_tr() + foot_tr_element.alternative_text = "Foot Row" + + for col_index in range(col_count): + td_element = foot_tr_element.create_td() + td_element.set_text("Foot {}".format(col_index)) + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Ajustar posición de la tabla + +Ajuste la posición de una tabla en un PDF etiquetado mientras mantiene las características de accesibilidad utilizando Aspose.PDF for Python via .NET. + +El siguiente fragmento de código muestra cómo ajustar la posición de la tabla en el documento Tagged PDF: + +```python +import aspose.pdf as ap +import sys +from os import path + +def adjust_table_position(outfile): + # Create PDF document + with ap.Document() as document: + # Create tagged content + tagged_content = document.tagged_content + tagged_content.set_title("Example table position") + tagged_content.set_language("en-US") + + # Get root structure element + root_element = tagged_content.root_element + + # Create table structure element + table_element = tagged_content.create_table_element() + root_element.append_child(table_element, True) + + # Create position settings + position_settings = ap.tagged.PositionSettings() + position_settings.horizontal_alignment = ap.HorizontalAlignment.NONE + position_settings.margin = ap.MarginInfo(left=20, right=0, top=0, bottom=0) + position_settings.vertical_alignment = ap.VerticalAlignment.NONE + position_settings.is_first_paragraph_in_column = False + position_settings.is_kept_with_next = False + position_settings.is_in_new_page = False + position_settings.is_in_line_paragraph = False + + # Adjust table position + table_element.adjust_position(position_settings) + + table_t_head_element = table_element.create_t_head() + table_t_body_element = table_element.create_t_body() + table_t_foot_element = table_element.create_t_foot() + row_count = 4 + col_count = 4 + + head_tr_element = table_t_head_element.create_tr() + head_tr_element.alternative_text = "Head Row" + + for col_index in range(col_count): + th_element = head_tr_element.create_th() + th_element.set_text(f"Head {col_index}") + + th_element.background_color = ap.Color.green_yellow + th_element.border = ap.BorderInfo(ap.BorderSide.ALL, 4.0, ap.Color.gray) + + th_element.is_no_border = True + th_element.margin = ap.MarginInfo(16.0, 2.0, 8.0, 2.0) + + th_element.alignment = ap.HorizontalAlignment.RIGHT + + for row_index in range(row_count): + tr_element = table_t_body_element.create_tr() + tr_element.alternative_text = f"Row {row_index}" + + for col_index in range(col_count): + col_span = 1 + row_span = 1 + + if col_index == 1 and row_index == 1: + col_span = 2 + row_span = 2 + elif (row_index == 1 and col_index == 2) or ( + row_index == 2 and col_index in (1, 2) + ): + continue + + td_element = tr_element.create_td() + td_element.set_text(f"Cell [{row_index}, {col_index}]") + + td_element.background_color = ap.Color.yellow + td_element.border = ap.BorderInfo(ap.BorderSide.ALL, 4.0, ap.Color.gray) + + td_element.is_no_border = False + td_element.margin = ap.MarginInfo(8.0, 2.0, 8.0, 2.0) + + td_element.alignment = ap.HorizontalAlignment.CENTER + + cell_text_state = ap.text.TextState() + cell_text_state.foreground_color = ap.Color.dark_blue + cell_text_state.font_size = 7.5 + cell_text_state.font_style = ap.text.FontStyles.BOLD + cell_text_state.font = ap.text.FontRepository.find_font("Arial") + td_element.default_cell_text_state = cell_text_state + + td_element.is_word_wrapped = True + td_element.vertical_alignment = ap.VerticalAlignment.CENTER + + td_element.col_span = col_span + td_element.row_span = row_span + + foot_tr_element = table_t_foot_element.create_tr() + foot_tr_element.alternative_text = "Foot Row" + + for col_index in range(col_count): + td_element = foot_tr_element.create_td() + td_element.set_text(f"Foot {col_index}") + + # Save Tagged PDF Document + document.save(outfile) +``` + +## Temas relacionados de Tagged PDF + +- [Crear Tagged PDF](/pdf/es/python-net/create-tagged-pdf/) para crear la estructura general del documento accesible alrededor del contenido de tu tabla. +- [Extraer contenido etiquetado de PDFs etiquetados](/pdf/es/python-net/extract-tagged-content-from-tagged-pdfs/) para inspeccionar los elementos de estructura relacionados con la tabla después de la generación. +- [Configuración de propiedades de Structure Elements](/pdf/es/python-net/setting-structure-elements-properties/) para refinar los metadatos accesibles en celdas de tabla y otros elementos de estructura. \ No newline at end of file diff --git a/es/python-net/advanced-operations/annotations/_index.md b/es/python-net/advanced-operations/annotations/_index.md index 77b13b3f9..53fb05ee7 100644 --- a/es/python-net/advanced-operations/annotations/_index.md +++ b/es/python-net/advanced-operations/annotations/_index.md @@ -1,152 +1,43 @@ --- -title: Anotaciones de PDF -linktitle: Anotaciones de PDF +title: Anotaciones PDF en Python +linktitle: Anotaciones PDF type: docs weight: 100 url: /es/python-net/annotations/ -description: Esta sección muestra cómo usar todo tipo de anotaciones en su archivo PDF con la biblioteca Aspose.PDF. -lastmod: "2023-02-17" +description: Aprenda cómo agregar, modificar, extraer y gestionar anotaciones PDF en Python con Aspose.PDF for Python via .NET, incluyendo texto, resaltados, enlaces, figuras y más. +lastmod: "2026-05-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo agregar anotaciones a PDF usando Python +Abstract: El artículo analiza el uso de anotaciones en PDFs como elementos interactivos que mejoran la interactividad del documento y la participación del usuario. Destaca las capacidades de la Aspose.PDF for Python Library para admitir varios tipos de anotaciones, incluyendo texto, resaltados, figuras y anotaciones multimedia. Las anotaciones cumplen múltiples propósitos, como comentar, revisar, marcar documentos y proporcionar retroalimentación, lo que facilita la colaboración, la comunicación y una comprensión más profunda del contenido del documento. El artículo también menciona una sección que detalla cómo agregar, eliminar y recuperar anotaciones, ofreciendo orientación sobre la gestión eficaz de estos elementos dentro de los documentos PDF. --- - +Las anotaciones en PDFs son elementos interactivos que le permiten agregar notas, resaltar texto, dibujar formas, adjuntar archivos y activar acciones directamente en una página. Son útiles para flujos de trabajo de revisión, colaboración, navegación y marcado de documentos. -Las anotaciones en los PDFs son elementos interactivos que te permiten agregar notas, resaltar texto, dibujar formas, adjuntar archivos y realizar otras acciones que mejoran la navegación, la interactividad y la interacción. +Aspose.PDF for Python via .NET admite una amplia gama de escenarios de anotaciones, incluidos anotaciones de nota y emergentes, marcado de texto, enlaces y botones, formas, marcas de agua, anotaciones multimedia y flujos de trabajo de importación o exportación de anotaciones. -La biblioteca Aspose.PDF para Python admite varios tipos de anotaciones, incluidas anotaciones de texto (como texto y anotaciones emergentes), anotaciones de resaltado (como marcas de texto), anotaciones de figuras (como círculo, polilínea, polígono, línea y tinta), anotaciones multimedia (hay pantalla, sonido, widget y 3D) y más. +Utilice esta sección para elegir el flujo de trabajo de anotaciones que coincida con su tarea, ya sea que necesite crear nuevas anotaciones, inspeccionar las existentes, eliminarlas o transferirlas entre documentos PDF. -Las anotaciones se pueden utilizar para comentar, revisar, marcar documentos, proporcionar retroalimentación o agregar información adicional. Las anotaciones permiten establecer cooperación, facilitar la comunicación y mejorar la comprensión del contenido de los documentos. Mejoran la colaboración, mejoran la comunicación y hacen que los documentos PDF sean más dinámicos y atractivos para los usuarios. +## Temas de anotaciones -Puedes hacer lo siguiente: +Utilice esta sección cuando necesite agregar, recuperar, actualizar, eliminar o transferir anotaciones en archivos PDF con Python. Las páginas vinculadas a continuación cubren tanto los flujos de trabajo de anotaciones de nivel superior como las familias de anotaciones agrupadas utilizadas a lo largo de la documentación. -- [Agregar, Eliminar y Obtener Anotación](/pdf/es/python-net/add-delete-and-get-annotation/) - esta sección explica cómo trabajar con todos los tipos de anotaciones permitidas. +Puede utilizar los siguientes temas: - \ No newline at end of file +- [Agregar, eliminar y obtener anotación](/pdf/es/python-net/add-delete-and-get-annotation/) - comience aquí para las principales categorías de anotaciones agrupadas y los flujos de trabajo centrales de crear, inspeccionar y eliminar. +- [Importar y Exportar Anotaciones](/pdf/es/python-net/import-export-annotations/) - copie anotaciones de un documento PDF a otro archivo PDF. + +### Grupos de Anotaciones + +La guía de anotaciones agrupadas incluye los siguientes subtemas: + +- [Anotaciones de Texto](/pdf/es/python-net/text-based-Annotations/) - trabajar con anotaciones de texto libre, resaltado, subrayado, ondulado y tachado. +- [Anotaciones de marcado](/pdf/es/python-net/markup-annotations/) - agregar o inspeccionar anotaciones de nota, cursor y reemplazo utilizadas en escenarios de revisión. +- [Anotaciones interactivas](/pdf/es/python-net/interactive-annotations/) - crear anotaciones de enlace, botones de navegación y botones de impresión. +- [Anotaciones de forma](/pdf/es/python-net/shape-annotations/) - usar anotaciones de línea, cuadrado, círculo, polígono y polilínea. +- [Anotaciones de medios](/pdf/es/python-net/media-annotations/) - agregar anotaciones de sonido, pantalla, medios enriquecidos y 3D. +- [Anotaciones de seguridad](/pdf/es/python-net/security-annotations/) - trabajar con anotaciones de adjunto de archivo, redacción y otras orientadas a la protección. +- [Anotaciones de marca de agua](/pdf/es/python-net/watermark-annotations/) - agregar y administrar elementos de marca de agua basados en anotaciones. +Las anotaciones son especialmente útiles para la revisión de documentos, la colaboración, el marcado de contenido y la navegación interactiva. Comience con la visión general agrupada cuando desee explorar los tipos de anotaciones admitidos, o diríjase directamente a un tema específico cuando ya conozca el flujo de trabajo que necesita. diff --git a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md index cc017fd23..1db848a48 100644 --- a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md +++ b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md @@ -1,154 +1,34 @@ --- -title: Añadir, Eliminar y Obtener Anotación usando Python -linktitle: Añadir, Eliminar y Obtener Anotación +title: Agregar, eliminar y obtener anotaciones PDF en Python +linktitle: Agregar, eliminar y obtener anotación type: docs weight: 20 url: /es/python-net/add-delete-and-get-annotation/ -description: Con Aspose.PDF para Python puedes añadir, eliminar y obtener anotaciones de tu archivo PDF. Consulta todas las listas de anotaciones para resolver tu tarea. -lastmod: "2023-02-17" +description: Con Aspose.PDF for Python puedes agregar, eliminar y obtener anotaciones de tu archivo PDF. Consulta todas las listas de anotaciones para resolver tu tarea. +lastmod: "2026-05-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo manipular anotaciones en PDF con Python +Abstract: 'Las anotaciones en documentos PDF mejoran la interacción del usuario al permitir la incorporación de varios elementos como notas, resaltados de texto, formas y archivos adjuntos. Estas funciones mejoran la experiencia de visualización del documento y su interactividad. La biblioteca Aspose.PDF for Python clasifica las anotaciones en varios grupos: Anotaciones de texto, Anotaciones de resaltado, Anotaciones de figuras, Anotaciones adhesivas y Anotaciones extra, cada una con distintas funciones para enriquecer la participación y la usabilidad del documento.' --- - +Las anotaciones en documentos PDF son elementos que permiten a los usuarios asignar contenido de cierta manera en el documento. Las anotaciones pueden usarse para añadir diferentes tipos de notas, resaltar texto, dibujar formas, adjuntar archivos y realizar otras acciones que mejoran la visualización, la interactividad y la interacción dentro de un documento. -**¿Qué son las anotaciones en documentos PDF?** +Esta página agrupa los principales tipos de anotación compatibles en esta parte de la documentación para que pueda saltar rápidamente al flujo de trabajo que necesita. -Las anotaciones en documentos PDF son elementos que permiten a los usuarios asignar contenido de cierta manera en el documento. Las anotaciones se pueden usar para agregar diferentes tipos de notas, resaltar texto, dibujar formas, adjuntar archivos y realizar otras acciones que mejoran la visualización, la interactividad y la interacción dentro de un documento. +Hemos combinado los diferentes tipos de anotación disponibles para la biblioteca Aspose.PDF for Python en grupos: -Hemos combinado los diferentes tipos de anotaciones disponibles para la biblioteca Aspose.PDF para Python en grupos: +- [Anotaciones interactivas](/pdf/es/python-net/interactive-annotations/) +- [Anotaciones de marcado](/pdf/es/python-net/markup-annotations/) +- [Anotaciones de medios](/pdf/es/python-net/media-annotations/) +- [Anotaciones de seguridad](/pdf/es/python-net/security-annotations/) +- [Anotaciones de forma](/pdf/es/python-net/shape-annotations/) +- [Anotaciones de texto](/pdf/es/python-net/text-based-Annotations/) +- [Anotaciones de marca de agua](/pdf/es/python-net/watermark-annotations/) -- [Anotación de Texto en PDF](/pdf/es/python-net/text-annotation/) -- [Anotación de Resaltados en PDF](/pdf/es/python-net/highlights-annotation/) -- [Anotación de Figuras en PDF](/pdf/es/python-net/figures-annotation/) -- [Anotaciones Adhesivas en PDF](/pdf/es/python-net/sticky-annotations/) -- [Anotaciones Extra](/pdf/es/python-net/extra-annotations/) +## Temas relacionados de anotaciones - \ No newline at end of file +- [Resumen de anotaciones PDF](/pdf/es/python-net/annotations/) para la sección principal y los conceptos de anotación. +- [Importar y exportar anotaciones](/pdf/es/python-net/import-export-annotations/) diff --git a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/extra-annotations/_index.md b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/extra-annotations/_index.md deleted file mode 100644 index 7fd7a912e..000000000 --- a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/extra-annotations/_index.md +++ /dev/null @@ -1,281 +0,0 @@ ---- -title: Anotaciones Extras usando Python -linktitle: Anotaciones Extras -type: docs -weight: 60 -url: /es/python-net/extra-annotations/ -description: Esta sección describe cómo agregar, obtener y eliminar tipos adicionales de anotaciones de su documento PDF. -lastmod: "2023-02-17" -sitemap: - changefreq: "weekly" - priority: 0.7 ---- - - - -## Cómo agregar una anotación de intercalación en un archivo PDF existente mediante Python - -La anotación de intercalación es un símbolo que indica la edición de texto. La anotación de intercalación también es una anotación de marcado, por lo que la clase Caret deriva de la clase Markup y también proporciona funciones para obtener o establecer propiedades de la anotación de intercalación y restablecer el flujo de la apariencia de la anotación de intercalación. -Las anotaciones de intercalación se utilizan a menudo para sugerir cambios, adiciones o modificaciones al texto. - -Pasos con los que creamos una anotación de intercalación: - -1. Cargar el archivo PDF - nuevo [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). -1. Crear un nuevo [CaretAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/caretannotation/) y establecer parámetros de intercalación (nuevo Rectángulo, título, asunto, banderas, color). Esta anotación se usa para indicar la inserción de texto. -1. Una vez que podemos agregar anotaciones a la página. - -El siguiente fragmento de código muestra cómo agregar una anotación de intercalación a un archivo PDF: - -```python - - import aspose.pdf as ap - - # Abrir documento - document = ap.Document(input_file) - - caretAnnotation1 = ap.annotations.CaretAnnotation( - document.pages[1], ap.Rectangle(200, 700.664, 308.708, 740.769, True) - ) - caretAnnotation1.title = "Usuario de Aspose" - caretAnnotation1.subject = "Texto insertado 1" - caretAnnotation1.flags = ap.annotations.AnnotationFlags.PRINT - caretAnnotation1.color = ap.Color.blue - - document.pages[1].annotations.append(caretAnnotation1) - document.save(output_file) -``` - - -### Obtener Anotación de Acento - -Por favor, intente usar el siguiente fragmento de código para obtener la Anotación de Acento en un documento PDF - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - caretAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.CARET) - ] - - for ca in caretAnnotations: - print(ca.rect) -``` - -### Eliminar Anotación de Acento - -El siguiente fragmento de código muestra cómo eliminar la Anotación de Acento de un archivo PDF usando Python. - -```python - - import aspose.pdf as ap - - # Cargar el archivo PDF - document = ap.Document(input_file) - caretAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.CARET) - ] - - for ca in caretAnnotations: - document.pages[1].annotations.delete(ca) - - document.save(output_file) -``` - -## Agregar Anotación de Enlace - -[Enlaces](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/linkannotation/) son anotaciones que abren URLs o se mueven a ciertas posiciones dentro del mismo documento o dentro de un documento externo cuando haces clic. - -Una Anotación de Enlace es un área rectangular que se puede colocar en cualquier lugar de la página. Cada enlace tiene una acción PDF correspondiente asociada a él. Esta acción se realiza cuando el usuario hace clic en el área de este enlace. - -El siguiente fragmento de código muestra cómo agregar una Anotación de Enlace a un archivo PDF usando un ejemplo de número de teléfono: - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - # Crear objeto TextFragmentAbsorber para encontrar un número de teléfono - textFragmentAbsorber = ap.text.TextFragmentAbsorber("file") - - # Aceptar el absorbedor solo para la primera página - document.pages[1].accept(textFragmentAbsorber) - - phoneNumberFragment = textFragmentAbsorber.text_fragments[1] - - # Crear Anotación de Enlace y establecer la acción para llamar a un número de teléfono - linkAnnotation = ap.annotations.LinkAnnotation(document.pages[1], phoneNumberFragment.rectangle) - linkAnnotation.action = ap.annotations.GoToURIAction("www.aspose.com") - - # Agregar anotación a la página - document.pages[1].annotations.append(linkAnnotation) - document.save(output_file) -``` - - -### Obtener Anotación de Enlace - -Por favor, intente usar el siguiente fragmento de código para obtener [LinkAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/linkannotation/) del documento PDF. - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - linkAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.LINK) - ] - - for la in linkAnnotations: - print(la.rect) -``` - -### Eliminar Anotación de Enlace - -El siguiente fragmento de código muestra cómo eliminar la anotación de enlace de un archivo PDF. Para esto, necesitamos encontrar y eliminar todas las anotaciones de enlace en la primera página. Después de esto, guardaremos el documento con la anotación eliminada. - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - highlightAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.LINK) - ] - - for hs in highlightAnnotations: - document.pages[1].annotations.delete(hs) - - document.save(output_file) -``` - - -## Redactar cierta región de la página con Anotación de Redacción usando Aspose.PDF para Python - -Aspose.PDF para Python a través de .NET admite la función de agregar y manipular Anotaciones en un archivo PDF existente. Las Anotaciones de Redacción en documentos PDF tienen el propósito de eliminar o ocultar permanentemente información confidencial del documento. El proceso de editar la información implica cubrir o sombrear contenido específico, como texto, imágenes o gráficos, de manera que restrinja su visibilidad y accesibilidad a otros. Esto asegura que la información sensible permanezca oculta y protegida dentro del documento. Para cumplir con este requisito, se proporciona una clase llamada [RedactionAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/redactionannotation/), que se puede usar para redactar ciertas regiones de la página o se puede usar para manipular RedactionAnnotations existentes y redactarlas (es decir, aplanar la anotación y eliminar el texto debajo de ella). - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - page = document.pages[1] - redactionAnnotation = ap.annotations.RedactionAnnotation(page, ap.Rectangle(270, 190, 371, 250, True)) - redactionAnnotation.title = "John Smith" - redactionAnnotation.fill_color = ap.Color.light_gray - redactionAnnotation.color = ap.Color.red - redactionAnnotation.redact() - - page.annotations.append(redactionAnnotation) - document.save(output_file) -``` - - -### Obtener Anotación de Redacción - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - redactionAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.REDACTION) - ] - - for pa in redactionAnnotations: - print(pa.rect) -``` - -### Eliminar Anotación de Redacción - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - redactionAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.REDACTION) - ] - - for pa in redactionAnnotations: - document.pages[1].annotations.delete(pa) - - document.save(output_file) -`` \ No newline at end of file diff --git a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/figures/_index.md b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/figures/_index.md deleted file mode 100644 index 51ab76bc0..000000000 --- a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/figures/_index.md +++ /dev/null @@ -1,438 +0,0 @@ ---- -title: Añadir Anotaciones de Figuras usando Python -linktitle: Anotaciones de Figuras -type: docs -weight: 30 -url: /es/python-net/figures-annotation/ -description: Este artículo describe cómo agregar, obtener y eliminar anotaciones de figuras de su documento PDF con Aspose.PDF para Python a través de .NET -lastmod: "2023-02-17" -sitemap: - changefreq: "weekly" - priority: 0.7 ---- - - - -## Agregar Anotaciones de Cuadro y Círculo - -En los documentos PDF, una anotación de cuadro se refiere a un tipo específico de anotación que se representa mediante una forma cuadrada. Las anotaciones de cuadro se utilizan para resaltar o llamar la atención sobre un área o sección específica dentro del documento. - -Las anotaciones de [Cuadro](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/squareannotation/) y [Círculo](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/circleannotation/) mostrarán, respectivamente, un rectángulo o una elipse en la página. - -Pasos para crear Anotaciones de Cuadro o Círculo: - -1. Cargar el archivo PDF - nuevo [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). -1. Crear nueva [SquareAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/squareannotation) y establecer parámetros (nuevo Rectángulo, título, color, color_interior, opacidad). -1. Después necesitamos agregar la Anotación de Cuadro a la página. - -El siguiente fragmento de código muestra cómo agregar Anotaciones de Cuadro en una página PDF. - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - - squareAnnotation = ap.annotations.SquareAnnotation(document.pages[1], ap.Rectangle(60, 600, 250, 450, True)) - squareAnnotation.title = "John Smith" - squareAnnotation.color = ap.Color.blue - squareAnnotation.interior_color = ap.Color.blue_violet - squareAnnotation.opacity = 0.25 - - document.pages[1].annotations.append(squareAnnotation) - - document.save(output_file) -``` - -El siguiente fragmento de código te muestra cómo añadir anotaciones de círculo en una página PDF. - -```python - - import aspose.pdf as ap - - # Abrir documento - document = ap.Document(input_file) - - circleAnnotation = ap.annotations.CircleAnnotation( - document.pages[1], ap.Rectangle(270, 160, 483, 383, True) - ) - circleAnnotation.title = "John Smith" - circleAnnotation.color = ap.Color.red - circleAnnotation.interior_color = ap.Color.misty_rose - circleAnnotation.opacity = 0.5 - circleAnnotation.popup = ap.annotations.PopupAnnotation( - document.pages[1], ap.Rectangle(842, 316, 1021, 459, True) - ) - - document.pages[1].annotations.append(circleAnnotation) - document.save(output_file) -``` - - -Como ejemplo, veremos el siguiente resultado de agregar anotaciones de Cuadrado y Círculo a un documento PDF: - -![Demostración de Anotación de Círculo y Cuadrado](circle_demo.png) - -### Obtener Anotación de Círculo - -Por favor, intente usar el siguiente fragmento de código para Obtener Anotación de Círculo del documento PDF. - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - circleAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.CIRCLE) - ] - - for ca in circleAnnotations: - print(ca.rect) -``` - -### Obtener Anotación de Cuadrado - -Por favor, intente usar el siguiente fragmento de código para Obtener Anotación de Cuadrado del documento PDF. - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - squareAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.SQUARE) - ] - - for pa in squareAnnotations: - print(pa.rect) -``` - -### Eliminar Anotación de Círculo - -El siguiente fragmento de código muestra cómo eliminar una anotación de círculo de un archivo PDF. - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - circleAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.CIRCLE) - ] - - for ca in circleAnnotations: - document.pages[1].annotations.delete(ca) - - document.save(output_file) -``` - -### Eliminar anotación de cuadrado - -El siguiente fragmento de código muestra cómo eliminar una anotación de cuadrado de un archivo PDF. - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - squareAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.SQUARE) - ] - - for pa in squareAnnotations: - document.pages[1].annotations.delete(pa) - - document.save(output_file) -``` - -## Agregar anotaciones de polígono y polilínea - -La herramienta Polilínea te permite crear formas y contornos con un número arbitrario de lados en el documento. - -[Polygon Annotations](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/polygonannotation/) representan polígonos en una página. Pueden tener cualquier número de vértices conectados por líneas rectas. - -[Polyline Annotations](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/polylineannotation/) son también similares a los polígonos, la única diferencia es que los primeros y últimos vértices no están conectados implícitamente. - -Pasos con los que creamos anotaciones de Polígono: - -1. Cargar el archivo PDF - nuevo [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). -1. Crear nueva [Polygon Annotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/polygonannotation) y establecer parámetros del Polígono (nuevo Rectángulo, nuevos Puntos, título, color, color_interior y opacidad). -1. Después podemos añadir anotaciones a la página. - -El siguiente fragmento de código muestra cómo añadir anotaciones de Polígono a un archivo PDF: - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - - polygonAnnotation = ap.annotations.PolygonAnnotation( - document.pages[1], - ap.Rectangle(200, 300, 400, 400, True), - [ - ap.Point(200, 300), - ap.Point(220, 300), - ap.Point(250, 330), - ap.Point(300, 304), - ap.Point(300, 400), - ], - ) - polygonAnnotation.title = "John Smith" - polygonAnnotation.color = ap.Color.blue - polygonAnnotation.interior_color = ap.Color.blue_violet - polygonAnnotation.opacity = 0.25 - - document.pages[1].annotations.append(polygonAnnotation) - document.save(output_file) -``` - - -El siguiente fragmento de código muestra cómo añadir anotaciones de polilínea a un archivo PDF: - -1. Cargar el archivo PDF - nuevo [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). -1. Crear nuevas [Polyline Annotations](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/polylineannotation/) y configurar los parámetros del polígono (nuevo Rectangle, nuevos Points, título, color, interior_color y opacidad). -1. Después podemos añadir las anotaciones a la página. - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - - # Crear una nueva anotación de polilínea - polylineAnnotation = ap.annotations.PolylineAnnotation( - document.pages[1], - ap.Rectangle(270, 193, 571, 383, True), - [ - ap.Point(545, 150), - ap.Point(545, 190), - ap.Point(667, 190), - ap.Point(667, 110), - ap.Point(626, 111), - ], - ) - polylineAnnotation.title = "John Smith" - polylineAnnotation.color = ap.Color.red - polylineAnnotation.popup = ap.annotations.PopupAnnotation( - document.pages[1], ap.Rectangle(842, 196, 1021, 338, True) - ) - - # Añadir la anotación a la página - document.pages[1].annotations.append(polylineAnnotation) - document.save(output_file) -``` - - -### Obtener Anotaciones de Polígono y Polilínea - -Por favor, intente usar el siguiente fragmento de código para obtener anotaciones de polígono en un documento PDF. - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - polygonAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.POLYGON) - ] - - for pa in polygonAnnotations: - print(pa.rect) -``` - -Por favor, intente usar el siguiente fragmento de código para obtener anotaciones de polilínea en un documento PDF. - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - polylineAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.POLY_LINE) - ] - - for pa in polylineAnnotations: - print(pa.rect) -``` - -### Eliminar Anotaciones de Polígono y Polilínea - -El siguiente fragmento de código muestra cómo eliminar anotaciones de polígono de un archivo PDF. - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - polygonAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.POLYGON) - ] - - for pa in polygonAnnotations: - document.pages[1].annotations.delete(pa) - - document.save(output_file) -``` - - -El siguiente fragmento de código muestra cómo eliminar anotaciones de polilínea de un archivo PDF. - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - polylineAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.POLY_LINE) - ] - - for pa in polylineAnnotations: - document.pages[1].annotations.delete(pa) - - document.save(output_file) -``` - - \ No newline at end of file diff --git a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/hightlights/_index.md b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/hightlights/_index.md deleted file mode 100644 index 7ab76df72..000000000 --- a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/hightlights/_index.md +++ /dev/null @@ -1,396 +0,0 @@ ---- -title: Anotación de Resaltados en PDF usando Python -linktitle: Anotación de Resaltados -type: docs -weight: 20 -url: /es/python-net/highlights-annotation/ -description: Las anotaciones de marcado se presentan en el texto como resaltados, subrayados, tachados o subrayados irregulares en el texto de un documento. -lastmod: "2023-02-17" -sitemap: - changefreq: "weekly" - priority: 0.7 ---- - - - -Las anotaciones de marcado de texto en PDF se utilizan para resaltar, subrayar, omitir o agregar notas al texto en el documento. Estas anotaciones están destinadas a resaltar o llamar la atención sobre partes específicas del texto. Tales anotaciones permiten a los usuarios marcar o modificar visualmente el contenido de un archivo PDF. - -La anotación de resaltado se utiliza para marcar el texto con un fondo de color, generalmente amarillo, para indicar su importancia o relevancia. - -La anotación de subrayado es una línea colocada debajo del texto seleccionado para indicar importancia, énfasis o sugerir ediciones. - -La anotación de tachado incluye el tachado de un texto particular para mostrar que ha sido eliminado, reemplazado o ya no es válido. - -La línea ondulada se utiliza para subrayar el texto para indicar un tipo diferente de acento, como errores ortográficos, problemas potenciales o cambios propuestos. - -## Agregar anotación de marcado de texto - -Para agregar una anotación de marcado de texto al documento PDF, necesitamos realizar las siguientes acciones: - -1. Cargar el archivo PDF - nuevo objeto [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). -1. Crear anotaciones: - - [HighlightAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/highlightannotation/) y establecer parámetros (título, color). - - [StrikeOutAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/strikeoutannotation/) y establecer parámetros (título, color). - - [SquigglyAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/squigglyannotation/) y establecer parámetros (título, color). - - [UnderlineAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/underlineannotation/) y establecer parámetros (título, color). -1. Después debemos añadir todas las anotaciones a la página. - -### Agregar Anotación de Resaltado - -```python - - import aspose.pdf as ap - - # Abrir documento - document = ap.Document(input_file) - - # Crear Anotación de Círculo - highlightAnnotation = ap.annotations.HighlightAnnotation( - document.pages[1], ap.Rectangle(300, 750, 320, 770, True) - ) - document.pages[1].annotations.append(highlightAnnotation) - document.save(output_file) -``` - - -### Añadir Anotación de Tachado - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - - strikeoutAnnotation = ap.annotations.StrikeOutAnnotation( - document.pages[1], ap.Rectangle(299.988, 713.664, 308.708, 720.769, True) - ) - strikeoutAnnotation.title = "Usuario de Aspose" - strikeoutAnnotation.subject = "Texto insertado 1" - strikeoutAnnotation.flags = ap.annotations.AnnotationFlags.PRINT - strikeoutAnnotation.color = ap.Color.blue - - document.pages[1].annotations.append(strikeoutAnnotation) - document.save(output_file) -``` - -### Añadir Anotación de Zigzag - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - page = document.pages[1] - squigglyAnnotation = ap.annotations.SquigglyAnnotation(page, ap.Rectangle(67, 317, 261, 459, True)) - squigglyAnnotation.title = "John Smith" - squigglyAnnotation.color = ap.Color.blue - - page.annotations.append(squigglyAnnotation) - - document.save(output_file) -``` - -### Añadir Anotación de Subrayado - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - - underlineAnnotation = ap.annotations.UnderlineAnnotation( - document.pages[1], ap.Rectangle(299.988, 713.664, 308.708, 720.769, True) - ) - underlineAnnotation.title = "Usuario de Aspose" - underlineAnnotation.subject = "Subrayado insertado 1" - underlineAnnotation.flags = ap.annotations.AnnotationFlags.PRINT - underlineAnnotation.color = ap.Color.blue - - document.pages[1].annotations.append(underlineAnnotation) - document.save(output_file) -``` - - -## Obtener anotación de marcado de texto - -Intente usar el siguiente fragmento de código para obtener la anotación de marcado de texto del documento PDF. - -### Obtener anotación de resaltar - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - highlightAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.HIGHLIGHT) - ] - - for ha in highlightAnnotations: - print(ha.rect) -``` - -### Obtener anotación de tachado - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - StrikeoutAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.STRIKE_OUT) - ] - - for pa in StrikeoutAnnotations: - print(pa.rect) -``` - -### Obtener anotación de línea ondulada - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - squigglyAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.SQUIGGLY) - ] - - for pa in squigglyAnnotations: - print(pa.rect) -``` - - -### Obtener Anotación de Subrayado - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - UnderlineAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.UNDERLINE) - ] - - for ta in UnderlineAnnotations: - print(ta.rect) -``` - -## Eliminar Anotación de Marcado de Texto - -El siguiente fragmento de código muestra cómo eliminar la anotación de marcado de texto de un archivo PDF. - -### Eliminar Anotación de Resaltado - -```python - - import aspose.pdf as ap - - # Cargar el archivo PDF - document = ap.Document(input_file) - highlightAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.HIGHLIGHT) - ] - - for hs in highlightAnnotations: - document.pages[1].annotations.delete(hs) - - document.save(output_file) -``` - -### Eliminar Anotación de Tachado - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - StrikeoutAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.STRIKE_OUT) - ] - - for pa in StrikeoutAnnotations: - document.pages[1].annotations.delete(pa) - - document.save(output_file) -``` - - -### Eliminar Anotación de Línea Ondulada - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - squigglyAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.SQUIGGLY) - ] - - for pa in squigglyAnnotations: - document.pages[1].annotations.delete(pa) - - document.save(output_file) -``` - -### Eliminar Anotación de Subrayado - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - underlineAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.UNDERLINE) - ] - - for ta in underlineAnnotations: - document.pages[1].annotations.delete(ta) - - document.save(output_file) -``` - - - \ No newline at end of file diff --git a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/interactive-annotations/_index.md b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/interactive-annotations/_index.md new file mode 100644 index 000000000..d8246fae6 --- /dev/null +++ b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/interactive-annotations/_index.md @@ -0,0 +1,330 @@ +--- +title: Anotaciones interactivas usando Python +linktitle: Anotaciones interactivas +type: docs +weight: 60 +url: /es/python-net/interactive-annotations/ +description: Aprenda cómo agregar, leer y eliminar anotaciones de enlace, y cómo crear botones de navegación e impresión en documentos PDF usando Aspose.PDF for Python via .NET. +lastmod: "2026-04-21" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Trabaja con anotaciones interactivas de PDF y botones en Python. +Abstract: Este artículo explica cómo trabajar con anotaciones interactivas en archivos PDF usando Aspose.PDF for Python via .NET. Cubre la adición de anotaciones de enlace, la lectura de áreas de enlace existentes, la eliminación de anotaciones de enlace, la creación de botones de navegación de página y la incorporación de un botón de impresión a un documento PDF. +--- + +Este artículo muestra cómo trabajar con anotaciones interactivas en documentos PDF utilizando Aspose.PDF for Python via .NET. + +El script de ejemplo muestra varios flujos de trabajo comunes: + +- agregar una anotación de enlace al texto existente +- obtener los rectángulos de anotación de enlace de una página +- eliminar anotaciones de enlace +- crear botones de navegación +- crear un botón de impresión + +## Anotación de enlace + +### Agregar anotación de enlace + +Este ejemplo busca en la primera página el fragmento de texto `"file"` y coloca una anotación de enlace clicable sobre el área de texto coincidente. Cuando el usuario hace clic en la anotación, el PDF abre la dirección web especificada. + +#### Cargue el documento y encuentre el texto objetivo + +Crear una `Document` objeto y usar `TextFragmentAbsorber` buscar el texto que se volverá interactivo. + +```python +document = ap.Document(infile) +text_fragment_absorber = ap.text.TextFragmentAbsorber("file") + +document.pages[1].accept(text_fragment_absorber) +phone_number_fragment = text_fragment_absorber.text_fragments[1] +``` + +#### Crear la anotación de enlace + +Construir un `LinkAnnotation` usando el rectángulo del fragmento de texto coincidente y asignar una acción URI a él. + +```python +link_annotation = ap.annotations.LinkAnnotation( + document.pages[1], phone_number_fragment.rectangle +) +link_annotation.action = ap.annotations.GoToURIAction("https://www.aspose.com") +``` + +#### Añade la anotación y guarda el PDF + +Agregue la anotación a la página y guarde el archivo actualizado. + +```python +document.pages[1].annotations.append(link_annotation) +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def link_add(infile, outfile): + document = ap.Document(infile) + text_fragment_absorber = ap.text.TextFragmentAbsorber("file") + + document.pages[1].accept(text_fragment_absorber) + phone_number_fragment = text_fragment_absorber.text_fragments[1] + + link_annotation = ap.annotations.LinkAnnotation( + document.pages[1], phone_number_fragment.rectangle + ) + link_annotation.action = ap.annotations.GoToURIAction("https://www.aspose.com") + + document.pages[1].annotations.append(link_annotation) + document.save(outfile) +``` + +### Obtener anotación de enlace + +Para inspeccionar los enlaces interactivos existentes, filtre la colección de anotaciones en la primera página y conserve solo los elementos cuyo tipo es `LINK`. La muestra luego imprime el rectángulo para cada anotación coincidente. + +#### Cargar el PDF y recopilar anotaciones de enlace + +```python +document = ap.Document(infile) +link_annotations = [ + a + for a in document.pages[1].annotations + if (a.annotation_type == ap.annotations.AnnotationType.LINK) +] +``` + +#### Leer los rectángulos de anotación + +Recorra las anotaciones filtradas y muestre las coordenadas de cada área de enlace. + +```python +for link_annotation in link_annotations: + print(link_annotation.rect) +``` + +#### Ejemplo completo + +```python +def link_get(infile, outfile): + document = ap.Document(infile) + link_annotations = [ + a + for a in document.pages[1].annotations + if (a.annotation_type == ap.annotations.AnnotationType.LINK) + ] + + for link_annotation in link_annotations: + print(link_annotation.rect) +``` + +### Eliminar anotación de enlace + +Este flujo de trabajo elimina todas las anotaciones de enlaces de la primera página y guarda el PDF limpio como un nuevo archivo. + +#### Encuentra las anotaciones de enlace para eliminar + +```python +document = ap.Document(infile) +link_annotations = [ + a + for a in document.pages[1].annotations + if (a.annotation_type == ap.annotations.AnnotationType.LINK) +] +``` + +#### Eliminar cada anotación de enlace + +```python +for link_annotation in link_annotations: + document.pages[1].annotations.delete(link_annotation) +``` + +#### Guardar el documento actualizado + +```python +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def link_delete(infile, outfile): + document = ap.Document(infile) + link_annotations = [ + a + for a in document.pages[1].annotations + if (a.annotation_type == ap.annotations.AnnotationType.LINK) + ] + + for link_annotation in link_annotations: + document.pages[1].annotations.delete(link_annotation) + + document.save(outfile) +``` + +## Anotación de widget + +### Agregar botón de navegación + +Los botones de navegación son útiles en PDFs de varias páginas cuando deseas que los lectores se desplacen entre páginas sin usar la interfaz del visor. Este ejemplo agrega `Previous Page` y `Next Page` botones a cada página. + +#### Definir configuración del botón + +Almacena los textos de los botones, sus posiciones y acciones predefinidas en una lista de configuración simple. + +```python +button_config = [ + ("Previous Page", 120.0, ap.annotations.PredefinedAction.PREV_PAGE), + ("Next Page", 230.0, ap.annotations.PredefinedAction.NEXT_PAGE), +] +``` + +#### Cargue el PDF y asegúrese de que existan varias páginas + +El ejemplo abre el documento fuente y agrega una página más para que las acciones de navegación tengan al menos dos páginas con las que trabajar. + +```python +document = ap.Document(infile) +document.pages.add() +``` + +#### Cree los botones en cada página + +Para cada página, crea un `ButtonField`, establezca su texto y colores, asigne una acción de navegación predefinida y agréguelo al formulario. + +```python +for page in document.pages: + for name, x_pos, action in button_config: + rect = ap.Rectangle(x_pos, 10.0, x_pos + 100, 40.0, True) + button = ap.forms.ButtonField(page, rect) + button.partial_name = name + button.value = name + button.characteristics.border = ap.Color.red.to_rgb() + button.characteristics.background = ap.Color.orange.to_rgb() + button.actions.on_release_mouse_btn = ap.annotations.NamedAction(action) + document.form.add(button) +``` + +#### Guardar el resultado + +```python +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def navigation_buttons_add(infile, outfile): + button_config = [ + ("Previous Page", 120.0, ap.annotations.PredefinedAction.PREV_PAGE), + ("Next Page", 230.0, ap.annotations.PredefinedAction.NEXT_PAGE), + ] + + document = ap.Document(infile) + document.pages.add() + + for page in document.pages: + for name, x_pos, action in button_config: + rect = ap.Rectangle(x_pos, 10.0, x_pos + 100, 40.0, True) + button = ap.forms.ButtonField(page, rect) + button.partial_name = name + button.value = name + button.characteristics.border = ap.Color.red.to_rgb() + button.characteristics.background = ap.Color.orange.to_rgb() + button.actions.on_release_mouse_btn = ap.annotations.NamedAction(action) + document.form.add(button) + + document.save(outfile) +``` + +### Agregar botón de impresión + +Este ejemplo crea un PDF de una sola página y coloca un botón de impresión cerca de la parte superior de la página. Al hacer clic en el botón se activa la acción de impresión predefinida en un visor de PDF compatible. + +#### Crear un nuevo PDF y añadir una página + +```python +document = ap.Document() +page = document.pages.add() +``` + +#### Crear y configurar el botón + +Definir el rectángulo del botón, crear el `ButtonField`, establezca su leyenda y adjunte la acción de impresión. + +```python +rect = ap.Rectangle(72, 748, 164, 768, True) + +print_button = ap.forms.ButtonField(page, rect) +print_button.alternate_name = "Print current document" +print_button.color = ap.Color.black +print_button.partial_name = "printBtn1" +print_button.value = "Print Document" +print_button.actions.on_release_mouse_btn = ap.annotations.NamedAction( + ap.annotations.PredefinedAction.FILE_PRINT +) +``` + +#### Establecer estilos de borde y fondo + +El ejemplo define un borde sólido y aplica colores personalizados para hacer que el botón sea visible en el documento. + +```python +border = ap.annotations.Border(print_button) +border.style = ap.annotations.BorderStyle.SOLID +border.width = 2 +print_button.border = border + +print_button.characteristics.border = ap.Color.blue.to_rgb() +print_button.characteristics.background = ap.Color.light_blue.to_rgb() +``` + +#### Añade el botón y guarda el PDF + +```python +document.form.add(print_button) +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def print_button_add(infile, outfile): + document = ap.Document() + page = document.pages.add() + + rect = ap.Rectangle(72, 748, 164, 768, True) + + print_button = ap.forms.ButtonField(page, rect) + print_button.alternate_name = "Print current document" + print_button.color = ap.Color.black + print_button.partial_name = "printBtn1" + print_button.value = "Print Document" + print_button.actions.on_release_mouse_btn = ap.annotations.NamedAction( + ap.annotations.PredefinedAction.FILE_PRINT + ) + + border = ap.annotations.Border(print_button) + border.style = ap.annotations.BorderStyle.SOLID + border.width = 2 + print_button.border = border + + print_button.characteristics.border = ap.Color.blue.to_rgb() + print_button.characteristics.background = ap.Color.light_blue.to_rgb() + + document.form.add(print_button) + document.save(outfile) +``` + +## Temas relacionados + +- [Importar y exportar anotaciones](/python-net/import-export-annotations/) +- [Anotaciones de marcado](/python-net/markup-annotations/) +- [Anotaciones de medios](/python-net/media-annotations/) +- [Anotaciones de Seguridad](/python-net/security-annotations/) +- [Anotaciones de forma](/python-net/shape-annotations/) +- [Anotaciones basadas en texto](/python-net/text-based-Annotations/) +- [Anotaciones de Marca de Agua](/python-net/watermark-annotations/) diff --git a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/markup-annotations/_index.md b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/markup-annotations/_index.md new file mode 100644 index 000000000..fa58e0aae --- /dev/null +++ b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/markup-annotations/_index.md @@ -0,0 +1,499 @@ +--- +title: Anotaciones de marcado usando Python +linktitle: Anotaciones de marcado +type: docs +weight: 30 +url: /es/python-net/markup-annotations/ +description: Aprende cómo agregar, leer y eliminar texto, cursor y reemplazar anotaciones en documentos PDF usando Aspose.PDF for Python via .NET. +lastmod: "2026-04-21" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Trabaja con anotaciones de marcado en archivos PDF usando Python. +Abstract: Este artículo explica cómo crear, inspeccionar y eliminar anotaciones de marcado en documentos PDF utilizando Aspose.PDF for Python via .NET. Cubre anotaciones de texto, anotaciones de cursor y anotaciones de sustitución, con cada flujo de trabajo dividido en pasos pequeños y ejemplos de código. +--- + +Este artículo muestra cómo trabajar con anotaciones de marcado en documentos PDF utilizando Aspose.PDF for Python via .NET. + +El script de ejemplo muestra tres flujos de trabajo comunes de anotaciones: + +- anotaciones de texto para comentarios de estilo nota +- anotaciones de caret para marcadores de inserción +- reemplazar anotaciones para el marcado de reemplazo de texto + +## Anotaciones de texto + +### Agregar anotaciones de texto + +Este ejemplo crea una anotación de texto en la primera página y la vincula a una ventana emergente. Las anotaciones de texto son útiles para comentarios al estilo de notas adhesivas en flujos de trabajo de revisión. + +#### Abra el PDF de origen + +```python +document = ap.Document(infile) +``` + +#### Crear y configurar la anotación de texto + +Defina el rectángulo de anotación y establezca su título, asunto, contenido, banderas de visualización, color e ícono. + +```python +text_annotation = ap.annotations.TextAnnotation( + document.pages[1], + ap.Rectangle(299.988, 613.664, 428.708, 680.769, True), +) +text_annotation.title = "Aspose User" +text_annotation.subject = "Sticky Note" +text_annotation.contents = ( + "This is a text annotation added by Aspose.PDF for Python via .NET" +) +text_annotation.flags = ap.annotations.AnnotationFlags.PRINT +text_annotation.color = ap.Color.blue +text_annotation.icon = ap.annotations.TextIcon.HELP +``` + +#### Crear la anotación emergente + +Crear una ventana emergente y conectarla a la anotación de texto. + +```python +popup = ap.annotations.PopupAnnotation( + document.pages[1], + ap.Rectangle(428.708, 613.664, 528.708, 713.664, True), +) +popup.open = True + +text_annotation.popup = popup +``` + +#### Añadir la anotación y guardar el PDF + +```python +document.pages[1].annotations.add(text_annotation, consider_rotation=False) +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def text_annotation_add(infile, outfile): + document = ap.Document(infile) + + text_annotation = ap.annotations.TextAnnotation( + document.pages[1], + ap.Rectangle(299.988, 613.664, 428.708, 680.769, True), + ) + text_annotation.title = "Aspose User" + text_annotation.subject = "Sticky Note" + text_annotation.contents = ( + "This is a text annotation added by Aspose.PDF for Python via .NET" + ) + text_annotation.flags = ap.annotations.AnnotationFlags.PRINT + text_annotation.color = ap.Color.blue + text_annotation.icon = ap.annotations.TextIcon.HELP + + popup = ap.annotations.PopupAnnotation( + document.pages[1], + ap.Rectangle(428.708, 613.664, 528.708, 713.664, True), + ) + popup.open = True + + text_annotation.popup = popup + + document.pages[1].annotations.add(text_annotation, consider_rotation=False) + document.save(outfile) +``` + +### Obtener anotaciones de texto + +Para inspeccionar las anotaciones de texto existentes, filtre la colección de anotaciones en la primera página y mantenga solo los elementos cuyo tipo sea `TEXT`. + +#### Cargar el documento y recopilar anotaciones de texto + +```python +document = ap.Document(infile) +text_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.TEXT +] +``` + +#### Imprimir los rectángulos de anotación + +```python +for annotation in text_annotations: + print(annotation.rect) +``` + +#### Ejemplo completo + +```python +def text_annotation_get(infile, outfile): + document = ap.Document(infile) + text_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.TEXT + ] + + for annotation in text_annotations: + print(annotation.rect) +``` + +### Eliminar anotaciones de texto + +Este flujo de trabajo elimina todas las anotaciones de texto de la primera página y guarda el PDF modificado. + +#### Buscar anotaciones de texto para eliminar + +```python +document = ap.Document(infile) +text_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.TEXT +] +``` + +#### Eliminar las anotaciones y guardar el archivo + +```python +for annotation in text_annotations: + document.pages[1].annotations.delete(annotation) + +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def text_annotation_delete(infile, outfile): + document = ap.Document(infile) + text_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.TEXT + ] + + for annotation in text_annotations: + document.pages[1].annotations.delete(annotation) + + document.save(outfile) +``` + +## Anotaciones de cursor + +### Agregar anotaciones de cursor + +Las anotaciones caret se utilizan para marcar puntos de inserción en escenarios de revisión. Este ejemplo agrega una anotación caret con una nota emergente adjunta. + +#### Abra el documento y obtenga la página objetivo + +```python +document = ap.Document(infile) +page = document.pages[1] +``` + +#### Crear y configurar la anotación caret + +```python +caret_annotation = ap.annotations.CaretAnnotation( + page, ap.Rectangle(299.988, 713.664, 308.708, 720.769, True) +) +caret_annotation.title = "Aspose User" +caret_annotation.subject = "Inserted text 1" +caret_annotation.flags = ap.annotations.AnnotationFlags.PRINT +caret_annotation.color = ap.Color.blue +``` + +#### Adjunte la ventana emergente y guarde el documento + +```python +caret_annotation.popup = ap.annotations.PopupAnnotation( + page, ap.Rectangle(310, 713, 410, 730, True) +) +page.annotations.append(caret_annotation) + +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def caret_annotations_add(infile, outfile): + document = ap.Document(infile) + page = document.pages[1] + + caret_annotation = ap.annotations.CaretAnnotation( + page, ap.Rectangle(299.988, 713.664, 308.708, 720.769, True) + ) + caret_annotation.title = "Aspose User" + caret_annotation.subject = "Inserted text 1" + caret_annotation.flags = ap.annotations.AnnotationFlags.PRINT + caret_annotation.color = ap.Color.blue + caret_annotation.popup = ap.annotations.PopupAnnotation( + page, ap.Rectangle(310, 713, 410, 730, True) + ) + page.annotations.append(caret_annotation) + + document.save(outfile) +``` + +### Obtener anotaciones de cursor + +Para inspeccionar las anotaciones caret, itere a través de las anotaciones de la página y filtre por el `CARET` tipo de anotación. + +#### Cargar el documento y la página + +```python +document = ap.Document(infile) +page = document.pages[1] +``` + +#### Imprimir rectángulos de anotación de caret + +```python +for annot in page.annotations: + if annot.annotation_type == ap.annotations.AnnotationType.CARET: + print(annot.rect) +``` + +#### Ejemplo completo + +```python +def caret_annotations_get(infile, outfile): + document = ap.Document(infile) + page = document.pages[1] + + for annot in page.annotations: + if annot.annotation_type == ap.annotations.AnnotationType.CARET: + print(annot.rect) +``` + +### Eliminar anotaciones de caret + +Este flujo de trabajo recopila primero las anotaciones de caret, las elimina una por una y luego guarda el archivo actualizado. + +#### Cargar el documento y recopilar las anotaciones de cursor + +```python +document = ap.Document(infile) +page = document.pages[1] + +caret_annotations = [ + annot + for annot in page.annotations + if annot.annotation_type == ap.annotations.AnnotationType.CARET +] +``` + +#### Elimina las anotaciones y guarda el documento + +```python +for annot in caret_annotations: + page.annotations.delete(annot) + +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def caret_annotations_delete(infile, outfile): + document = ap.Document(infile) + page = document.pages[1] + + caret_annotations = [ + annot + for annot in page.annotations + if annot.annotation_type == ap.annotations.AnnotationType.CARET + ] + + for annot in caret_annotations: + page.annotations.delete(annot) + + document.save(outfile) +``` + +## Reemplazar anotaciones + +### Agregar Reemplazar Anotaciones + +Las anotaciones de reemplazo combinan una anotación de caret y una anotación de tachado agrupada. Este patrón marca el texto que debe ser reemplazado y enlaza la nota de reemplazo con el contenido tachado. + +#### Abre el documento y obtén la página + +```python +document = ap.Document(infile) +page = document.pages[1] +``` + +#### Crear la anotación caret para texto de reemplazo + +```python +caret_annotation = ap.annotations.CaretAnnotation( + page, ap.Rectangle(361.246, 727.908, 370.081, 735.107, True) +) +caret_annotation.flags = ap.annotations.AnnotationFlags.PRINT +caret_annotation.subject = "Inserted text 2" +caret_annotation.title = "Aspose User" +caret_annotation.color = ap.Color.blue +caret_annotation.popup = ap.annotations.PopupAnnotation( + page, ap.Rectangle(310, 713, 410, 730, True) +) +``` + +#### Crear la anotación tachada agrupada + +Definir el área tachada, asignar los puntos cuádruples y vincularlo a la anotación caret a través de `in_reply_to` y `reply_type`. + +```python +strikeout_annotation = ap.annotations.StrikeOutAnnotation( + page, ap.Rectangle(318.407, 727.826, 368.916, 740.098, True) +) +strikeout_annotation.color = ap.Color.blue +strikeout_annotation.quad_points = [ + ap.Point(321.66, 739.416), + ap.Point(365.664, 739.416), + ap.Point(321.66, 728.508), + ap.Point(365.664, 728.508), +] +strikeout_annotation.subject = "Cross-out" +strikeout_annotation.in_reply_to = caret_annotation +strikeout_annotation.reply_type = ap.annotations.ReplyType.GROUP +``` + +#### Añade ambas anotaciones y guarda el PDF + +```python +page.annotations.append(caret_annotation) +page.annotations.append(strikeout_annotation) + +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def replace_annotations_add(infile, outfile): + document = ap.Document(infile) + page = document.pages[1] + + caret_annotation = ap.annotations.CaretAnnotation( + page, ap.Rectangle(361.246, 727.908, 370.081, 735.107, True) + ) + caret_annotation.flags = ap.annotations.AnnotationFlags.PRINT + caret_annotation.subject = "Inserted text 2" + caret_annotation.title = "Aspose User" + caret_annotation.color = ap.Color.blue + caret_annotation.popup = ap.annotations.PopupAnnotation( + page, ap.Rectangle(310, 713, 410, 730, True) + ) + + strikeout_annotation = ap.annotations.StrikeOutAnnotation( + page, ap.Rectangle(318.407, 727.826, 368.916, 740.098, True) + ) + strikeout_annotation.color = ap.Color.blue + strikeout_annotation.quad_points = [ + ap.Point(321.66, 739.416), + ap.Point(365.664, 739.416), + ap.Point(321.66, 728.508), + ap.Point(365.664, 728.508), + ] + strikeout_annotation.subject = "Cross-out" + strikeout_annotation.in_reply_to = caret_annotation + strikeout_annotation.reply_type = ap.annotations.ReplyType.GROUP + + page.annotations.append(caret_annotation) + page.annotations.append(strikeout_annotation) + + document.save(outfile) +``` + +### Obtener Reemplazar Anotaciones + +Para identificar anotaciones de reemplazo, encuentre anotaciones de tachado que estén agrupadas como respuestas a otra anotación. El ejemplo convierte cada anotación de tachado antes de comprobar sus campos de relación. + +#### Cargue el documento y recorra las anotaciones + +```python +document = ap.Document(infile) +page = document.pages[1] +``` + +#### Filtrar anotaciones de tachado agrupadas + +```python +for annot in page.annotations: + if annot.annotation_type == ap.annotations.AnnotationType.STRIKE_OUT: + sa = cast(ap.annotations.StrikeOutAnnotation, annot) + if ( + sa.in_reply_to is not None + and sa.reply_type == ap.annotations.ReplyType.GROUP + ): + print(f"Replace annotation rect: {sa.rect}") +``` + +#### Ejemplo completo + +```python +def replace_annotations_get(infile, outfile): + document = ap.Document(infile) + page = document.pages[1] + + for annot in page.annotations: + if annot.annotation_type == ap.annotations.AnnotationType.STRIKE_OUT: + sa = cast(ap.annotations.StrikeOutAnnotation, annot) + if ( + sa.in_reply_to is not None + and sa.reply_type == ap.annotations.ReplyType.GROUP + ): + print(f"Replace annotation rect: {sa.rect}") +``` + +### Eliminar Reemplazar Anotaciones + +Este flujo de trabajo recopila anotaciones de tachado utilizadas para reemplazar el marcado, las elimina de la página y guarda el PDF de salida. + +#### Cargar el documento y recopilar anotaciones de reemplazo + +```python +document = ap.Document(infile) +page = document.pages[1] + +replace_annotations = [ + cast(ap.annotations.StrikeOutAnnotation, annot) + for annot in page.annotations + if annot.annotation_type == ap.annotations.AnnotationType.STRIKE_OUT +] +``` + +#### Elimina las anotaciones y guarda el documento + +```python +for annot in replace_annotations: + page.annotations.delete(annot) + +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def replace_annotations_delete(infile, outfile): + document = ap.Document(infile) + page = document.pages[1] + + replace_annotations = [ + cast(ap.annotations.StrikeOutAnnotation, annot) + for annot in page.annotations + if annot.annotation_type == ap.annotations.AnnotationType.STRIKE_OUT + ] + + for annot in replace_annotations: + page.annotations.delete(annot) + + document.save(outfile) +``` diff --git a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md new file mode 100644 index 000000000..406aae74f --- /dev/null +++ b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md @@ -0,0 +1,499 @@ +--- +title: Anotaciones multimedia en PDF +linktitle: Anotaciones multimedia +type: docs +weight: 40 +url: /es/python-net/media-annotations/ +description: Aprenda cómo agregar anotaciones de sonido, 3D, pantalla y rich media a documentos PDF, y cómo inspeccionar o eliminar anotaciones multimedia usando Aspose.PDF for Python via .NET. +lastmod: "2026-04-21" +sitemap: + changefreq: "monthly" + priority: 0.5 +TechArticle: true +AlternativeHeadline: Trabaje con anotaciones PDF multimedia y rich media en Python. +Abstract: Este artículo explica cómo crear y gestionar anotaciones multimedia en documentos PDF usando Aspose.PDF for Python via .NET. Cubre anotaciones de sonido, anotaciones 3D, anotaciones de pantalla, anotaciones de medios enriquecidos y técnicas para enumerar o eliminar anotaciones multimedia de una página PDF. +--- + +Este artículo muestra cómo trabajar con anotaciones de medios en documentos PDF usando Aspose.PDF for Python via .NET. + +El script de ejemplo demuestra varios flujos de trabajo multimedia: + +- agregar una anotación de sonido +- crear una anotación 3D a partir de un modelo U3D +- agregar una anotación de pantalla desde un archivo multimedia +- agregar y eliminar anotaciones de medios enriquecidos +- inspeccionar anotaciones multimedia existentes + +## Agregar anotaciones de sonido + +Este ejemplo agrega una anotación de sonido a la primera página de un PDF existente y la vincula a un archivo de medios WAV almacenado en el directorio de entrada. + +### Abre el PDF y define el archivo multimedia + +```python +media_dir = path.dirname(infile) + +document = ap.Document(infile) +page = document.pages[1] + +media_file = path.join(media_dir, "file_example_WAV_1MG.wav") +``` + +### Crear y configurar la anotación de sonido + +Establezca el rectángulo de anotación, el color, el título y el asunto. Luego añada una anotación emergente para proporcionar detalles adicionales cuando se seleccione la anotación. + +```python +sound_annotation = ann.SoundAnnotation( + page, + ap.Rectangle(20, 700, 60, 740, True), + media_file, +) + +sound_annotation.color = ap.Color.blue +sound_annotation.title = "John Smith" +sound_annotation.subject = "Sound Annotation demo" + +sound_annotation.popup = ann.PopupAnnotation( + page, + ap.Rectangle(20, 700, 60, 740, True), +) +``` + +### Añadir la anotación y guardar el PDF + +```python +page.annotations.append(sound_annotation) +document.save(outfile) +``` + +### Ejemplo completo + +```python +def sound_annotation_add(infile, outfile): + media_dir = path.dirname(infile) + + document = ap.Document(infile) + page = document.pages[1] + + media_file = path.join(media_dir, "file_example_WAV_1MG.wav") + + sound_annotation = ann.SoundAnnotation( + page, + ap.Rectangle(20, 700, 60, 740, True), + media_file, + ) + + sound_annotation.color = ap.Color.blue + sound_annotation.title = "John Smith" + sound_annotation.subject = "Sound Annotation demo" + + sound_annotation.popup = ann.PopupAnnotation( + page, + ap.Rectangle(20, 700, 60, 740, True), + ) + + page.annotations.append(sound_annotation) + document.save(outfile) +``` + +## Agregar anotaciones 3D + +Este flujo de trabajo crea un nuevo PDF e incrusta un modelo 3D desde un archivo U3D. También define vistas preestablecidas y configuraciones de renderizado para el contenido 3D. + +### Crea el documento PDF y el contenido 3D + +```python +model_file = infile + +document = ap.Document() + +pdf3d_content = ann.PDF3DContent(model_file) +pdf3d_artwork = ann.PDF3DArtwork(document, pdf3d_content) +pdf3d_artwork.lighting_scheme = ann.PDF3DLightingScheme(type_name="CAD") +pdf3d_artwork.render_mode = ann.PDF3DRenderMode(type_name="Solid") +``` + +### Definir las matrices de vista 3D + +Estas matrices describen cómo se muestra el modelo 3D desde diferentes puntos de vista. + +```python +top_matrix = ap.Matrix3D( + 1, + 0, + 0, + 0, + -1, + 0, + 0, + 0, + -1, + 0.10271, + 0.08184, + 0.273836, +) + +front_matrix = ap.Matrix3D( + 0, + -1, + 0, + 0, + 0, + 1, + -1, + 0, + 0, + 0.332652, + 0.08184, + 0.085273, +) +``` + +### Agregar vistas con nombre a la obra + +```python +pdf3d_artwork.view_array.add(ann.PDF3DView(document, top_matrix, 0.188563, "Top")) +pdf3d_artwork.view_array.add(ann.PDF3DView(document, front_matrix, 0.188563, "Left")) +``` + +### Crea la anotación y guarda el documento + +```python +page = document.pages.add() + +pdf3d_annotation = ann.PDF3DAnnotation( + page, + ap.Rectangle(100, 500, 300, 700, True), + pdf3d_artwork, +) + +pdf3d_annotation.border = ann.Border(pdf3d_annotation) +pdf3d_annotation.set_default_view_index(1) +pdf3d_annotation.flags = ann.AnnotationFlags.NO_ZOOM +pdf3d_annotation.name = path.basename(model_file) + +page.annotations.append(pdf3d_annotation) +document.save(outfile) +``` + +### Ejemplo completo + +```python +def annotation_3d_add(infile, outfile): + model_file = infile + + document = ap.Document() + + pdf3d_content = ann.PDF3DContent(model_file) + pdf3d_artwork = ann.PDF3DArtwork(document, pdf3d_content) + pdf3d_artwork.lighting_scheme = ann.PDF3DLightingScheme(type_name="CAD") + pdf3d_artwork.render_mode = ann.PDF3DRenderMode(type_name="Solid") + + top_matrix = ap.Matrix3D( + 1, + 0, + 0, + 0, + -1, + 0, + 0, + 0, + -1, + 0.10271, + 0.08184, + 0.273836, + ) + + front_matrix = ap.Matrix3D( + 0, + -1, + 0, + 0, + 0, + 1, + -1, + 0, + 0, + 0.332652, + 0.08184, + 0.085273, + ) + + pdf3d_artwork.view_array.add(ann.PDF3DView(document, top_matrix, 0.188563, "Top")) + pdf3d_artwork.view_array.add( + ann.PDF3DView(document, front_matrix, 0.188563, "Left") + ) + + page = document.pages.add() + + pdf3d_annotation = ann.PDF3DAnnotation( + page, + ap.Rectangle(100, 500, 300, 700, True), + pdf3d_artwork, + ) + + pdf3d_annotation.border = ann.Border(pdf3d_annotation) + pdf3d_annotation.set_default_view_index(1) + pdf3d_annotation.flags = ann.AnnotationFlags.NO_ZOOM + pdf3d_annotation.name = path.basename(model_file) + + page.annotations.append(pdf3d_annotation) + document.save(outfile) +``` + +## Agregar anotaciones de pantalla + +Las anotaciones de pantalla le permiten adjuntar medios reproducibles a una página PDF. Este ejemplo crea un nuevo PDF y agrega una anotación de pantalla basada en un archivo SWF. + +### Crear el PDF y la página + +```python +media_file = infile + +document = ap.Document() +page = document.pages.add() +``` + +### Crear la anotación de pantalla + +```python +screen_annotation = ann.ScreenAnnotation( + page, + ap.Rectangle(170, 190, 470, 380, True), + media_file, +) +``` + +### Añadir la anotación y guardar el PDF + +```python +page.annotations.append(screen_annotation) +document.save(outfile) +``` + +### Ejemplo completo + +```python +def screen_annotation_with_media_add(infile, outfile): + media_file = infile + + document = ap.Document() + page = document.pages.add() + + screen_annotation = ann.ScreenAnnotation( + page, + ap.Rectangle(170, 190, 470, 380, True), + media_file, + ) + + page.annotations.append(screen_annotation) + document.save(outfile) +``` + +## Anotaciones de medios enriquecidos + +### Agregar anotaciones de medios enriquecidos + +Las anotaciones de medios enriquecidos pueden incrustar contenido interactivo avanzado, como reproductores de video con carteles, skins y configuraciones de reproducción personalizadas. + +### Prepare los recursos de medios y del reproductor + +El ejemplo carga el video, la imagen del póster y los archivos de la piel del reproductor desde ubicaciones predefinidas. + +```python +media_dir = path.dirname(infile) +path_to_adobe_app = ( + r"C:\\Program Files (x86)\\Adobe\\Acrobat 2017\\Acrobat\\Multimedia Skins" +) + +document = ap.Document() +page = document.pages.add() + +video_name = "file_example_MP4_480_1_5MG.mp4" +poster_name = "file_example_MP4_480_1_5MG_poster.jpg" +skin_name = "SkinOverAllNoFullNoCaption.swf" +``` + +### Crear la anotación de medios enriquecidos + +```python +rich_media_annotation = ann.RichMediaAnnotation( + page, + ap.Rectangle(100, 500, 300, 600, True), +) +``` + +### Adjunte el reproductor personalizado, la piel, el póster y el video + +```python +player_path = os.path.join(path_to_adobe_app, "Players", "Videoplayer.swf") +rich_media_annotation.custom_player = open(player_path, "rb") +rich_media_annotation.custom_flash_variables = f"source={video_name}&skin={skin_name}" + +skin_path = os.path.join(path_to_adobe_app, skin_name) +rich_media_annotation.add_custom_data(skin_name, open(skin_path, "rb")) + +poster_path = os.path.join(media_dir, poster_name) +rich_media_annotation.set_poster(open(poster_path, "rb")) + +video_path = os.path.join(media_dir, video_name) +with open(video_path, "rb") as video_file: + rich_media_annotation.set_content(video_name, video_file) +``` + +### Establecer el comportamiento de reproducción y guardar el PDF + +La anotación está configurada como contenido de video y se activa cuando el usuario hace clic en ella. + +```python +rich_media_annotation.type = ann.RichMediaAnnotation.ContentType.VIDEO +rich_media_annotation.activate_on = ann.RichMediaAnnotation.ActivationEvent.CLICK + +rich_media_annotation.update() + +page.annotations.append(rich_media_annotation) +document.save(outfile) +``` + +### Ejemplo completo + +```python +def rich_media_annotations_add(infile, outfile): + media_dir = path.dirname(infile) + path_to_adobe_app = ( + r"C:\\Program Files (x86)\\Adobe\\Acrobat 2017\\Acrobat\\Multimedia Skins" + ) + + document = ap.Document() + page = document.pages.add() + + video_name = "file_example_MP4_480_1_5MG.mp4" + poster_name = "file_example_MP4_480_1_5MG_poster.jpg" + skin_name = "SkinOverAllNoFullNoCaption.swf" + + rich_media_annotation = ann.RichMediaAnnotation( + page, + ap.Rectangle(100, 500, 300, 600, True), + ) + + player_path = os.path.join(path_to_adobe_app, "Players", "Videoplayer.swf") + rich_media_annotation.custom_player = open(player_path, "rb") + rich_media_annotation.custom_flash_variables = ( + f"source={video_name}&skin={skin_name}" + ) + + skin_path = os.path.join(path_to_adobe_app, skin_name) + rich_media_annotation.add_custom_data(skin_name, open(skin_path, "rb")) + + poster_path = os.path.join(media_dir, poster_name) + rich_media_annotation.set_poster(open(poster_path, "rb")) + + video_path = os.path.join(media_dir, video_name) + with open(video_path, "rb") as video_file: + rich_media_annotation.set_content(video_name, video_file) + + rich_media_annotation.type = ann.RichMediaAnnotation.ContentType.VIDEO + rich_media_annotation.activate_on = ann.RichMediaAnnotation.ActivationEvent.CLICK + + rich_media_annotation.update() + + page.annotations.append(rich_media_annotation) + document.save(outfile) +``` + +### Eliminar anotaciones de medios enriquecidos + +Este flujo de trabajo elimina todas las anotaciones de medios enriquecidos de la primera página de un PDF existente. + +### Abra el PDF y recopile anotaciones de medios enriquecidos + +```python +document = ap.Document(infile) +page = document.pages[1] + +to_delete = [ + annotation + for annotation in page.annotations + if annotation.annotation_type == ann.AnnotationType.RICH_MEDIA +] +``` + +### Elimina las anotaciones y guarda el documento + +```python +for annotation in to_delete: + page.annotations.delete(annotation) + +document.save(outfile) +``` + +### Ejemplo completo + +```python +def rich_media_annotations_delete(infile, outfile): + document = ap.Document(infile) + page = document.pages[1] + + to_delete = [ + annotation + for annotation in page.annotations + if annotation.annotation_type == ann.AnnotationType.RICH_MEDIA + ] + + for annotation in to_delete: + page.annotations.delete(annotation) + + document.save(outfile) +``` + +## Obtener Multimedia_annotations + +Para inspeccionar contenido multimedia ya almacenado en un PDF, filtre la colección de anotaciones para los tipos de anotación de pantalla, sonido y multimedia enriquecida. + +### Abra el documento y defina los tipos de anotación objetivo + +```python +document = ap.Document(infile) + +target_types = { + ann.AnnotationType.SCREEN, + ann.AnnotationType.SOUND, + ann.AnnotationType.RICH_MEDIA, +} +``` + +### Imprimir rectángulos de anotación multimedia + +```python +for annotation in document.pages[1].annotations: + if annotation.annotation_type in target_types: + print(f"{annotation.annotation_type} [{annotation.rect}]") +``` + +### Ejemplo completo + +```python +def multimedia_annotations_get(infile, outfile): + document = ap.Document(infile) + + target_types = { + ann.AnnotationType.SCREEN, + ann.AnnotationType.SOUND, + ann.AnnotationType.RICH_MEDIA, + } + + for annotation in document.pages[1].annotations: + if annotation.annotation_type in target_types: + print(f"{annotation.annotation_type} [{annotation.rect}]") +``` + +## Temas relacionados + +- [Importar y Exportar Anotaciones](/python-net/import-export-annotations/) +- [Anotaciones Interactivas](/python-net/interactive-annotations/) +- [Anotaciones de marcado](/python-net/markup-annotations/) +- [Anotaciones de seguridad](/python-net/security-annotations/) +- [Anotaciones de forma](/python-net/shape-annotations/) +- [Anotaciones basadas en texto](/python-net/text-based-Annotations/) +- [Anotaciones de marca de agua](/python-net/watermark-annotations/) diff --git a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/security-annotations/_index.md b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/security-annotations/_index.md new file mode 100644 index 000000000..a67476cfa --- /dev/null +++ b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/security-annotations/_index.md @@ -0,0 +1,218 @@ +--- +title: Anotaciones de seguridad usando Python +linktitle: Anotaciones de seguridad +type: docs +weight: 75 +url: /es/python-net/security-annotations/ +description: Aprenda cómo marcar texto para redactar, aplicar anotaciones de redacción y redactar áreas de imagen en archivos PDF usando Aspose.PDF for Python via .NET. +lastmod: "2026-04-21" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Redactar contenido sensible de PDF en Python con anotaciones de seguridad. +Abstract: Este artículo explica cómo trabajar con anotaciones de seguridad en documentos PDF usando Aspose.PDF for Python via .NET. Cubre el marcado de texto coincidente con anotaciones de redacción, la aplicación permanente de redacciones y la eliminación de áreas de imagen seleccionadas basándose en los rectángulos de ubicación de imagen detectados. +--- + +Este artículo muestra cómo utilizar anotaciones de seguridad en documentos PDF con Aspose.PDF for Python via .NET. + +El script de ejemplo muestra tres flujos de trabajo comunes de redacción: + +- marcar fragmentos de texto con anotaciones de redacción +- aplicar permanentemente las anotaciones de redacción existentes +- redactar un área de imagen detectada en una página + +## Marcar redacción de texto + +Este flujo de trabajo busca texto coincidente en el documento y coloca anotaciones de redacción sobre cada coincidencia. No elimina el contenido todavía; solo marca el texto para su posterior redacción. + +### Abra el PDF y busque el texto objetivo + +Crear un `TextFragmentAbsorber` para el término de búsqueda y habilitar las opciones de búsqueda de texto normales antes de escanear todas las páginas. + +```python +document = ap.Document(infile) +text_fragment_absorber = ap.text.TextFragmentAbsorber(search_term) + +text_search_options = ap.text.TextSearchOptions(True) +text_fragment_absorber.text_search_options = text_search_options +document.pages.accept(text_fragment_absorber) +``` + +### Crear anotaciones de redacción para cada coincidencia + +Para cada fragmento de texto coincidente, crear un `RedactionAnnotation` usando el rectángulo del fragmento y configurando su apariencia visual. + +```python +for text_fragment in text_fragment_absorber.text_fragments: + page = text_fragment.page + annotation_rectangle = text_fragment.rectangle + redaction_annotation = ap.annotations.RedactionAnnotation( + page, annotation_rectangle + ) + redaction_annotation.fill_color = ap.Color.gray + redaction_annotation.border_color = ap.Color.red + redaction_annotation.color = ap.Color.white + redaction_annotation.overlay_text = "REDACTED" + redaction_annotation.text_alignment = ap.HorizontalAlignment.CENTER + redaction_annotation.repeat = True + page.annotations.add(redaction_annotation, True) +``` + +### Guardar el PDF marcado + +```python +document.save(outfile) +``` + +### Ejemplo completo + +```python +def mark_text_redaction(infile, outfile, search_term): + document = ap.Document(infile) + text_fragment_absorber = ap.text.TextFragmentAbsorber(search_term) + + text_search_options = ap.text.TextSearchOptions(True) + text_fragment_absorber.text_search_options = text_search_options + document.pages.accept(text_fragment_absorber) + + for text_fragment in text_fragment_absorber.text_fragments: + page = text_fragment.page + annotation_rectangle = text_fragment.rectangle + redaction_annotation = ap.annotations.RedactionAnnotation( + page, annotation_rectangle + ) + redaction_annotation.fill_color = ap.Color.gray + redaction_annotation.border_color = ap.Color.red + redaction_annotation.color = ap.Color.white + redaction_annotation.overlay_text = "REDACTED" + redaction_annotation.text_alignment = ap.HorizontalAlignment.CENTER + redaction_annotation.repeat = True + page.annotations.add(redaction_annotation, True) + + document.save(outfile) +``` + + + +## Aplicar Redacción + +Después de que se hayan añadido anotaciones de redactado, este flujo de trabajo las aplica permanentemente en la primera página. Una vez aplicadas, el contenido original se elimina de la salida del documento. + +### Cargar el PDF y recopilar anotaciones de redacción + +```python +document = ap.Document(infile) +redaction_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.REDACTION +] +``` + +### Aplicar cada anotación de redacción + +La muestra verifica que cada anotación pueda ser tratada como una `RedactionAnnotation` antes de llamar `redact()`. + +```python +for redaction_annotation in redaction_annotations: + if is_assignable(redaction_annotation, ap.annotations.RedactionAnnotation): + cast(ap.annotations.RedactionAnnotation, redaction_annotation).redact() +``` + +### Guardar el PDF redactado + +```python +document.save(outfile) +``` + +### Ejemplo completo + +```python +def apply_redaction(infile, outfile): + document = ap.Document(infile) + redaction_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.REDACTION + ] + + for redaction_annotation in redaction_annotations: + if is_assignable(redaction_annotation, ap.annotations.RedactionAnnotation): + cast(ap.annotations.RedactionAnnotation, redaction_annotation).redact() + + document.save(outfile) +``` + + + +## Área de Redacción + +Este ejemplo redacta un área de imagen detectada en lugar de texto. Escanea la página en busca de ubicaciones de imágenes, selecciona un rectángulo de ubicación y agrega una anotación de redacción sobre esa área. + +### Abra el PDF y detecte la colocación de imágenes + +Usar `ImagePlacementAbsorber` para encontrar las posiciones de la imagen en la primera página. + +```python +document = ap.Document(infile) + +image_placement_absorber = ap.ImagePlacementAbsorber() +page = document.pages[1] +page.accept(image_placement_absorber) +``` + +### Crear una anotación de redacción para el área de imagen seleccionada + +El ejemplo utiliza la tercera ubicación de imagen detectada y aplica el mismo estilo de redacción utilizado en el ejemplo de marcación de texto. + +```python +target_rect = image_placement_absorber.image_placements[2].rectangle +redaction_annotation = ap.annotations.RedactionAnnotation(page, target_rect) +redaction_annotation.fill_color = ap.Color.gray +redaction_annotation.border_color = ap.Color.red +redaction_annotation.color = ap.Color.white +redaction_annotation.overlay_text = "REDACTED" +redaction_annotation.text_alignment = ap.HorizontalAlignment.CENTER +redaction_annotation.repeat = True +``` + +### Añadir la anotación y guardar el PDF + +```python +page.annotations.add(redaction_annotation, True) +document.save(outfile) +``` + +### Ejemplo completo + +```python +def redact_area(infile, outfile): + document = ap.Document(infile) + + image_placement_absorber = ap.ImagePlacementAbsorber() + page = document.pages[1] + page.accept(image_placement_absorber) + + target_rect = image_placement_absorber.image_placements[2].rectangle + redaction_annotation = ap.annotations.RedactionAnnotation(page, target_rect) + redaction_annotation.fill_color = ap.Color.gray + redaction_annotation.border_color = ap.Color.red + redaction_annotation.color = ap.Color.white + redaction_annotation.overlay_text = "REDACTED" + redaction_annotation.text_alignment = ap.HorizontalAlignment.CENTER + redaction_annotation.repeat = True + + page.annotations.add(redaction_annotation, True) + document.save(outfile) +``` + +## Temas relacionados + +- [Importar y Exportar Anotaciones](/python-net/import-export-annotations/) +- [Anotaciones Interactivas](/python-net/interactive-annotations/) +- [Anotaciones de marcado](/python-net/markup-annotations/) +- [Anotaciones multimedia](/python-net/media-annotations/) +- [Anotaciones de forma](/python-net/shape-annotations/) +- [Anotaciones basadas en texto](/python-net/text-based-Annotations/) +- [Anotaciones de marca de agua](/python-net/watermark-annotations/) diff --git a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md new file mode 100644 index 000000000..80a1d01ee --- /dev/null +++ b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md @@ -0,0 +1,720 @@ +--- +title: Anotaciones de forma mediante Python +linktitle: Anotaciones de forma +type: docs +weight: 20 +url: /es/python-net/shape-annotations/ +description: Aprenda cómo agregar, inspeccionar y eliminar anotaciones de línea, cuadrado, círculo, polígono y polilínea en documentos PDF usando Aspose.PDF for Python via .NET. +lastmod: "2026-04-21" +sitemap: + changefreq: "monthly" + priority: 0.5 +TechArticle: true +AlternativeHeadline: Trabaje con anotaciones geométricas de PDF en Python. +Abstract: Este artículo explica cómo crear, leer y eliminar anotaciones de forma en documentos PDF usando Aspose.PDF for Python via .NET. Cubre anotaciones de línea, cuadrado, círculo, polígono y polilínea, con cada flujo de trabajo dividido en pasos pequeños y ejemplos de código completos. +--- + +Este artículo muestra cómo trabajar con anotaciones de forma en documentos PDF usando Aspose.PDF for Python via .NET. + +El script de ejemplo muestra varios flujos de trabajo de anotación basados en geometría: + +- anotaciones de línea +- anotaciones cuadradas +- anotaciones de círculo +- anotaciones de polígonos +- anotaciones de polilínea + +## Anotación de línea + +### Agregar anotación de línea + +Este ejemplo agrega una anotación de línea a la primera página y configura los estilos de flecha, el ancho de línea y una ventana emergente. + +#### Abra el PDF de origen + +```python +document = ap.Document(infile) +``` + +#### Crear y configurar la anotación de línea + +```python +line_annotation = ap.annotations.LineAnnotation( + document.pages[1], + ap.Rectangle(550, 93, 562, 439, True), + ap.Point(556, 99), + ap.Point(556, 443), +) + +line_annotation.title = "John Smith" +line_annotation.color = ap.Color.red +line_annotation.width = 3 +line_annotation.starting_style = ap.annotations.LineEnding.OPEN_ARROW +line_annotation.ending_style = ap.annotations.LineEnding.OPEN_ARROW +``` + +#### Adjuntar el popup y guardar el PDF + +```python +popup = ap.annotations.PopupAnnotation( + document.pages[1], + ap.Rectangle(842, 124, 1021, 266, True), +) +line_annotation.popup = popup + +document.pages[1].annotations.append(line_annotation) +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def line_annotation_add(infile, outfile): + document = ap.Document(infile) + + line_annotation = ap.annotations.LineAnnotation( + document.pages[1], + ap.Rectangle(550, 93, 562, 439, True), + ap.Point(556, 99), + ap.Point(556, 443), + ) + + line_annotation.title = "John Smith" + line_annotation.color = ap.Color.red + line_annotation.width = 3 + line_annotation.starting_style = ap.annotations.LineEnding.OPEN_ARROW + line_annotation.ending_style = ap.annotations.LineEnding.OPEN_ARROW + + popup = ap.annotations.PopupAnnotation( + document.pages[1], + ap.Rectangle(842, 124, 1021, 266, True), + ) + line_annotation.popup = popup + + document.pages[1].annotations.append(line_annotation) + document.save(outfile) +``` + +### Obtener anotación de línea + +Para inspeccionar anotaciones de línea, filtre la colección de anotaciones en la primera página y convierta cada resultado a `LineAnnotation` para que puedas leer sus puntos de inicio y fin. + +#### Cargar el PDF y recopilar anotaciones de línea + +```python +document = ap.Document(infile) + +line_annotation = [ + cast(ap.annotations.LineAnnotation, annotation) + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.LINE +] +``` + +#### Imprime las coordenadas de la línea + +```python +for annotation in line_annotation: + print( + f"[{annotation.starting.x},{annotation.starting.y}]" + f"-[{annotation.ending.x},{annotation.ending.y}]" + ) +``` + +#### Ejemplo completo + +```python +def line_annotations_get(infile, outfile): + document = ap.Document(infile) + + line_annotation = [ + cast(ap.annotations.LineAnnotation, annotation) + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.LINE + ] + + for annotation in line_annotation: + print( + f"[{annotation.starting.x},{annotation.starting.y}]" + f"-[{annotation.ending.x},{annotation.ending.y}]" + ) +``` + +### Eliminar anotación de línea + +Este flujo de trabajo elimina todas las anotaciones de línea de la primera página y guarda el PDF actualizado. + +#### Buscar anotaciones de línea para eliminar + +```python +document = ap.Document(infile) +page = document.pages[1] + +line_annotations = [ + annotation + for annotation in page.annotations + if annotation.annotation_type == ap.annotations.AnnotationType.LINE +] +``` + +#### Eliminar las anotaciones y guardar el PDF + +```python +for annotation in line_annotations: + page.annotations.delete(annotation) + +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def line_annotations_delete(infile, outfile): + document = ap.Document(infile) + page = document.pages[1] + + line_annotations = [ + annotation + for annotation in page.annotations + if annotation.annotation_type == ap.annotations.AnnotationType.LINE + ] + + for annotation in line_annotations: + page.annotations.delete(annotation) + + document.save(outfile) +``` + + +## Anotaciones de Cuadrado y Círculo + +### Agregar anotación cuadrada + +Las anotaciones de tipo cuadrado son útiles para marcar áreas rectangulares en un documento. Este ejemplo crea una anotación de tipo cuadrado con ajustes de borde, relleno y transparencia. + +#### Abra el PDF y cree la anotación cuadrada + +```python +document = ap.Document(infile) + +square_annotation = ap.annotations.SquareAnnotation( + document.pages[1], + ap.Rectangle(60, 600, 250, 450, True), +) +square_annotation.title = "John Smith" +square_annotation.color = ap.Color.blue +square_annotation.interior_color = ap.Color.blue_violet +square_annotation.opacity = 0.25 +``` + +#### Añadir la anotación y guardar el PDF + +```python +document.pages[1].annotations.append(square_annotation) +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def square_annotation_add(infile, outfile): + document = ap.Document(infile) + + square_annotation = ap.annotations.SquareAnnotation( + document.pages[1], + ap.Rectangle(60, 600, 250, 450, True), + ) + square_annotation.title = "John Smith" + square_annotation.color = ap.Color.blue + square_annotation.interior_color = ap.Color.blue_violet + square_annotation.opacity = 0.25 + + document.pages[1].annotations.append(square_annotation) + document.save(outfile) +``` + +### Obtener anotación cuadrada + +Para inspeccionar anotaciones cuadradas, filtre las anotaciones de la primera página por el `SQUARE` escribe e imprime cada rectángulo. + +#### Cargar el documento y recopilar anotaciones cuadradas + +```python +document = ap.Document(infile) +square_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.SQUARE +] +``` + +#### Imprimir los rectángulos de anotación + +```python +for annotation in square_annotations: + print(annotation.rect) +``` + +#### Ejemplo completo + +```python +def square_annotation_get(infile, outfile): + document = ap.Document(infile) + square_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.SQUARE + ] + + for annotation in square_annotations: + print(annotation.rect) +``` + +### Eliminar anotación cuadrada + +Este flujo de trabajo elimina todas las anotaciones cuadradas de la primera página y guarda el documento. + +#### Buscar y eliminar anotaciones cuadradas + +```python +document = ap.Document(infile) +square_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.SQUARE +] + +for annotation in square_annotations: + document.pages[1].annotations.delete(annotation) + +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def square_annotation_delete(infile, outfile): + document = ap.Document(infile) + square_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.SQUARE + ] + + for annotation in square_annotations: + document.pages[1].annotations.delete(annotation) + + document.save(outfile) +``` + +### Agregar anotación de círculo + +Las anotaciones de círculo marcan áreas redondeadas en un PDF. Este ejemplo agrega una anotación de círculo con color de relleno, opacidad y una anotación emergente. + +#### Abra el PDF y cree la anotación de círculo + +```python +document = ap.Document(infile) + +circle_annotation = ap.annotations.CircleAnnotation( + document.pages[1], + ap.Rectangle(270, 160, 483, 383, True), +) +circle_annotation.title = "John Smith" +circle_annotation.color = ap.Color.red +circle_annotation.interior_color = ap.Color.misty_rose +circle_annotation.opacity = 0.5 +``` + +#### Adjuntar el popup y guardar el PDF + +```python +circle_annotation.popup = ap.annotations.PopupAnnotation( + document.pages[1], + ap.Rectangle(842, 316, 1021, 459, True), +) + +document.pages[1].annotations.append(circle_annotation) +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def circle_annotation_add(infile, outfile): + document = ap.Document(infile) + + circle_annotation = ap.annotations.CircleAnnotation( + document.pages[1], + ap.Rectangle(270, 160, 483, 383, True), + ) + circle_annotation.title = "John Smith" + circle_annotation.color = ap.Color.red + circle_annotation.interior_color = ap.Color.misty_rose + circle_annotation.opacity = 0.5 + circle_annotation.popup = ap.annotations.PopupAnnotation( + document.pages[1], + ap.Rectangle(842, 316, 1021, 459, True), + ) + + document.pages[1].annotations.append(circle_annotation) + document.save(outfile) +``` + +### Obtener anotación de círculo + +Para inspeccionar anotaciones de círculo, filtre las anotaciones de la página por el `CIRCLE` escriba e imprima sus rectángulos. + +#### Cargar el documento y recopilar anotaciones de círculo + +```python +document = ap.Document(infile) +circle_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.CIRCLE +] +``` + +#### Imprimir los rectángulos de anotación + +```python +for annotation in circle_annotations: + print(annotation.rect) +``` + +#### Ejemplo completo + +```python +def circle_annotation_get(infile, outfile): + document = ap.Document(infile) + circle_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.CIRCLE + ] + + for annotation in circle_annotations: + print(annotation.rect) +``` + +### Eliminar anotación de círculo + +Este flujo de trabajo elimina todas las anotaciones de círculo de la primera página y guarda el PDF de salida. + +#### Buscar y eliminar anotaciones de círculo + +```python +document = ap.Document(infile) +circle_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.CIRCLE +] + +for annotation in circle_annotations: + document.pages[1].annotations.delete(annotation) + +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def circle_annotation_delete(infile, outfile): + document = ap.Document(infile) + circle_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.CIRCLE + ] + + for annotation in circle_annotations: + document.pages[1].annotations.delete(annotation) + + document.save(outfile) +``` + + +## Anotaciones de Polígono y Polilínea + +### Agregar anotación de polígono + +Las anotaciones de polígono definen una forma cerrada de varios puntos. Este ejemplo crea una anotación de polígono a partir de un rectángulo y una lista de puntos. + +#### Abra el PDF y cree la anotación de polígono + +```python +document = ap.Document(infile) + +polygon_annotation = ap.annotations.PolygonAnnotation( + document.pages[1], + ap.Rectangle(200, 300, 400, 400, True), + [ + ap.Point(200, 300), + ap.Point(220, 300), + ap.Point(250, 330), + ap.Point(300, 304), + ap.Point(300, 400), + ], +) +polygon_annotation.title = "John Smith" +polygon_annotation.color = ap.Color.blue +polygon_annotation.interior_color = ap.Color.blue_violet +polygon_annotation.opacity = 0.25 +``` + +#### Añadir la anotación y guardar el PDF + +```python +document.pages[1].annotations.append(polygon_annotation) +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def polygon_annotation_add(infile, outfile): + document = ap.Document(infile) + + polygon_annotation = ap.annotations.PolygonAnnotation( + document.pages[1], + ap.Rectangle(200, 300, 400, 400, True), + [ + ap.Point(200, 300), + ap.Point(220, 300), + ap.Point(250, 330), + ap.Point(300, 304), + ap.Point(300, 400), + ], + ) + polygon_annotation.title = "John Smith" + polygon_annotation.color = ap.Color.blue + polygon_annotation.interior_color = ap.Color.blue_violet + polygon_annotation.opacity = 0.25 + + document.pages[1].annotations.append(polygon_annotation) + document.save(outfile) +``` + +### Obtener anotación de polígono + +Para inspeccionar anotaciones de polígono, filtre las anotaciones de la primera página por el `POLYGON` escribe e imprime cada rectángulo de anotación. + +#### Cargar el documento y recopilar anotaciones de polígonos + +```python +document = ap.Document(infile) +polygon_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.POLYGON +] +``` + +#### Imprimir los rectángulos de anotación + +```python +for annotation in polygon_annotations: + print(annotation.rect) +``` + +#### Ejemplo completo + +```python +def polygon_annotation_get(infile, outfile): + document = ap.Document(infile) + polygon_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.POLYGON + ] + + for annotation in polygon_annotations: + print(annotation.rect) +``` + +### Eliminar anotación de polígono + +Este flujo de trabajo elimina todas las anotaciones de polígonos de la primera página y guarda el PDF actualizado. + +#### Buscar y eliminar anotaciones de polígono + +```python +document = ap.Document(infile) +polygon_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.POLYGON +] + +for annotation in polygon_annotations: + document.pages[1].annotations.delete(annotation) + +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def polygon_annotation_delete(infile, outfile): + document = ap.Document(infile) + polygon_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.POLYGON + ] + + for annotation in polygon_annotations: + document.pages[1].annotations.delete(annotation) + + document.save(outfile) +``` + +### Agregar anotación de polilínea + +Las anotaciones de polilínea definen una ruta abierta a través de varios puntos. Este ejemplo crea una anotación de polilínea con una nota emergente. + +#### Abra el PDF y cree la anotación de polilínea + +```python +document = ap.Document(infile) + +polyline_annotation = ap.annotations.PolylineAnnotation( + document.pages[1], + ap.Rectangle(270, 193, 571, 383, True), + [ + ap.Point(545, 150), + ap.Point(545, 190), + ap.Point(667, 190), + ap.Point(667, 110), + ap.Point(626, 111), + ], +) +polyline_annotation.title = "John Smith" +polyline_annotation.color = ap.Color.red +``` + +#### Adjuntar el popup y guardar el PDF + +```python +polyline_annotation.popup = ap.annotations.PopupAnnotation( + document.pages[1], + ap.Rectangle(842, 196, 1021, 338, True), +) + +document.pages[1].annotations.append(polyline_annotation) +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def polyline_annotation_add(infile, outfile): + document = ap.Document(infile) + + polyline_annotation = ap.annotations.PolylineAnnotation( + document.pages[1], + ap.Rectangle(270, 193, 571, 383, True), + [ + ap.Point(545, 150), + ap.Point(545, 190), + ap.Point(667, 190), + ap.Point(667, 110), + ap.Point(626, 111), + ], + ) + polyline_annotation.title = "John Smith" + polyline_annotation.color = ap.Color.red + polyline_annotation.popup = ap.annotations.PopupAnnotation( + document.pages[1], + ap.Rectangle(842, 196, 1021, 338, True), + ) + + document.pages[1].annotations.append(polyline_annotation) + document.save(outfile) +``` + +### Obtener anotación PolyLine + +Para inspeccionar anotaciones de polilínea, filtre las anotaciones de la página por el `POLY_LINE` escriba e imprima sus rectángulos. + +#### Cargue el documento y recopile anotaciones de polilínea + +```python +document = ap.Document(infile) +polyline_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.POLY_LINE +] +``` + +#### Imprimir los rectángulos de anotación + +```python +for annotation in polyline_annotations: + print(annotation.rect) +``` + +#### Ejemplo completo + +```python +def polyline_annotation_get(infile, outfile): + document = ap.Document(infile) + polyline_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.POLY_LINE + ] + + for annotation in polyline_annotations: + print(annotation.rect) +``` + +### Eliminar anotación de polilínea + +Este flujo de trabajo elimina todas las anotaciones de polilínea de la primera página y guarda el PDF de salida. + +#### Buscar y eliminar anotaciones de polilínea + +```python +document = ap.Document(infile) +polyline_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.POLY_LINE +] + +for annotation in polyline_annotations: + document.pages[1].annotations.delete(annotation) + +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def polyline_annotation_delete(infile, outfile): + document = ap.Document(infile) + polyline_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.POLY_LINE + ] + + for annotation in polyline_annotations: + document.pages[1].annotations.delete(annotation) + + document.save(outfile) +``` + +## Temas relacionados + +- [Importar y Exportar Anotaciones](/python-net/import-export-annotations/) +- [Anotaciones Interactivas](/python-net/interactive-annotations/) +- [Anotaciones de marcado](/python-net/markup-annotations/) +- [Anotaciones multimedia](/python-net/media-annotations/) +- [Anotaciones de seguridad](/python-net/security-annotations/) +- [Anotaciones basadas en texto](/python-net/text-based-Annotations/) +- [Anotaciones de marca de agua](/python-net/watermark-annotations/) diff --git a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/sticks/_index.md b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/sticks/_index.md deleted file mode 100644 index c8cc263d4..000000000 --- a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/sticks/_index.md +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: Anotaciones adhesivas en PDF usando Python -linktitle: Anotación adhesiva -type: docs -weight: 50 -url: /es/python-net/sticky-annotations/ -description: Este tema trata sobre las anotaciones adhesivas, como ejemplo mostramos la Anotación de Marca de Agua en el texto. -lastmod: "2023-02-17" -sitemap: - changefreq: "weekly" - priority: 0.7 ---- - - - -## Añadir Anotación de Marca de Agua - -La más visible y fácil de visualizar y transmitir es la Anotación de Marca de Agua. Esta es la mejor manera de colocar en su documento PDF un logotipo o cualquier otro signo que confirme su originalidad. - -Se debe usar una anotación de marca de agua para representar gráficos que se imprimirán en un tamaño y posición fijos en una página, independientemente de las dimensiones de la página impresa. - -Puede agregar Texto de Marca de Agua utilizando [WatermarkAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/watermarkannotation/) en una posición específica de la página PDF. La opacidad de la Marca de Agua también se puede controlar usando la propiedad [opacity](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/watermarkannotation/#properties). - -Por favor, consulte el siguiente fragmento de código para agregar WatermarkAnnotation. - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - # Crear Anotación - # Cargar objeto Página para agregar Anotación - page = document.pages[1] - - # Crear Anotación - wa = ap.annotations.WatermarkAnnotation(page, ap.Rectangle(100, 0, 400, 100, True)) - - # Agregar anotación a la colección de Anotaciones de la Página - page.annotations.append(wa) - - # Crear TextState para la configuración de Fuente - ts = ap.text.TextState() - ts.foreground_color = ap.Color.blue - ts.font_size = 25 - ts.font = ap.text.FontRepository.find_font("Arial"); - - # Establecer nivel de opacidad del Texto de la Anotación - wa.opacity = 0.5 - - # Agregar Texto en la Anotación - wa.set_text_and_state([ "HELLO", "Line 1", "Line 2" ], ts) - - document.save(output_file) -``` - - -## Obtener Anotación de Marca de Agua - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - watermarkAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.WATERMARK) - ] - - for ta in watermarkAnnotations: - print(ta.rect) -``` - -## Eliminar Anotación de Marca de Agua - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - watermarkAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.WATERMARK) - ] - - for ta in watermarkAnnotations: - document.pages[1].annotations.delete(ta) - - document.save(output_file) \ No newline at end of file diff --git a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text-based-annotations/_index.md b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text-based-annotations/_index.md new file mode 100644 index 000000000..105d85f79 --- /dev/null +++ b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text-based-annotations/_index.md @@ -0,0 +1,749 @@ +--- +title: Anotaciones basadas en texto usando Python +linktitle: Anotaciones de texto +type: docs +weight: 10 +url: /es/python-net/text-based-Annotations/ +description: Aprenda cómo agregar, inspeccionar y eliminar anotaciones de texto libre, resaltado, subrayado, ondulado y tachado en documentos PDF usando Aspose.PDF for Python via .NET. +lastmod: "2026-04-21" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Trabaje con anotaciones PDF de texto y marcado de texto en Python. +Abstract: Este artículo explica cómo crear, leer y eliminar anotaciones basadas en texto en documentos PDF usando Aspose.PDF for Python via .NET. Cubre anotaciones de texto libre y anotaciones de marcado de texto como resaltado, subrayado, ondulado y tachado, incluidos flujos de trabajo avanzados de subrayado como aplanamiento, puntos cuádruples y extracción de texto marcado. +--- + +Este artículo muestra cómo trabajar con anotaciones basadas en texto en documentos PDF usando Aspose.PDF for Python via .NET. + +El script de ejemplo muestra varios flujos de trabajo de anotación de texto: + +- anotaciones de texto libre +- anotaciones de resaltado +- anotaciones de subrayado +- anotaciones onduladas +- anotaciones de tachado + +## Anotaciones de texto libre + +### Agregar anotaciones FreeText + +Las anotaciones de texto libre le permiten colocar comentarios de texto visibles directamente en una página PDF. Este ejemplo agrega una anotación de texto libre simple a la primera página. + +#### Abra el PDF de origen + +```python +document = ap.Document(infile) +``` + +#### Crear y configurar la anotación de texto libre + +```python +free_text_annotation = ap.annotations.FreeTextAnnotation( + document.pages[1], + ap.Rectangle(299, 713, 308, 720, True), + ap.annotations.DefaultAppearance(), +) +free_text_annotation.title = "Aspose User" +free_text_annotation.color = ap.Color.light_green +``` + +#### Añadir la anotación y guardar el PDF + +```python +document.pages[1].annotations.append(free_text_annotation) +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def free_text_annotation_add(infile, outfile): + document = ap.Document(infile) + + free_text_annotation = ap.annotations.FreeTextAnnotation( + document.pages[1], + ap.Rectangle(299, 713, 308, 720, True), + ap.annotations.DefaultAppearance(), + ) + free_text_annotation.title = "Aspose User" + free_text_annotation.color = ap.Color.light_green + + document.pages[1].annotations.append(free_text_annotation) + document.save(outfile) +``` + +### Obtener anotaciones de texto libre + +Para inspeccionar anotaciones de texto libre, filtre las anotaciones de la primera página por el `FREE_TEXT` escribe e imprime cada rectángulo de anotación. + +#### Cargue el documento y recopile anotaciones de texto libre + +```python +document = ap.Document(infile) +free_text_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.FREE_TEXT +] +``` + +#### Imprimir los rectángulos de anotación + +```python +for annotation in free_text_annotations: + print(annotation.rect) +``` + +#### Ejemplo completo + +```python +def free_text_annotation_get(infile, outfile): + document = ap.Document(infile) + free_text_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.FREE_TEXT + ] + + for annotation in free_text_annotations: + print(annotation.rect) +``` + +### Eliminar anotaciones de texto libre + +Este flujo de trabajo elimina todas las anotaciones de texto libre de la primera página y guarda el PDF actualizado. + +#### Buscar y eliminar anotaciones de texto libre + +```python +document = ap.Document(infile) +free_text_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.FREE_TEXT +] + +for annotation in free_text_annotations: + document.pages[1].annotations.delete(annotation) + +document.save(outfile) +``` + +#### Ejemplo completo + +```python +def free_text_annotation_delete(infile, outfile): + document = ap.Document(infile) + free_text_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.FREE_TEXT + ] + + for annotation in free_text_annotations: + document.pages[1].annotations.delete(annotation) + + document.save(outfile) +``` + + +## Anotaciones de marcado de texto + +### Resaltar anotaciones + +#### Agregar resaltado de texto + +Las anotaciones de resaltado enfatizan partes del documento sin cambiar el contenido subyacente. Este ejemplo agrega una anotación de resaltado a la primera página. + +```python +document = ap.Document(infile) + +highlight_annotation = ap.annotations.HighlightAnnotation( + document.pages[1], + ap.Rectangle(300, 750, 320, 770, True), +) + +document.pages[1].annotations.append(highlight_annotation) +document.save(outfile) +``` + +```python +def text_highlight_annotation_add(infile, outfile): + document = ap.Document(infile) + + highlight_annotation = ap.annotations.HighlightAnnotation( + document.pages[1], + ap.Rectangle(300, 750, 320, 770, True), + ) + + document.pages[1].annotations.append(highlight_annotation) + document.save(outfile) +``` + +#### Obtener resaltado de texto + +Para inspeccionar las anotaciones de resaltado, filtre las anotaciones de la página por el `HIGHLIGHT` escriba e imprima sus rectángulos. + +```python +document = ap.Document(infile) +highlight_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.HIGHLIGHT +] + +for annotation in highlight_annotations: + print(annotation.rect) +``` + +```python +def text_highlight_annotation_get(infile, outfile): + document = ap.Document(infile) + highlight_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.HIGHLIGHT + ] + + for annotation in highlight_annotations: + print(annotation.rect) +``` + +#### Eliminar resaltado de texto + +Este flujo de trabajo elimina todas las anotaciones de resaltado de la primera página y guarda el PDF de salida. + +```python +document = ap.Document(infile) +highlight_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.HIGHLIGHT +] + +for annotation in highlight_annotations: + document.pages[1].annotations.delete(annotation) + +document.save(outfile) +``` + +```python +def text_highlight_annotation_delete(infile, outfile): + document = ap.Document(infile) + highlight_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.HIGHLIGHT + ] + + for annotation in highlight_annotations: + document.pages[1].annotations.delete(annotation) + + document.save(outfile) +``` + + +### Anotaciones de subrayado + +#### Agregar anotaciones de subrayado de texto + +Las anotaciones de subrayado marcan el texto con un subrayado visible. Este ejemplo agrega una anotación de subrayado básica y establece sus metadatos y color. + +```python +document = ap.Document(infile) + +underline_annotation = ap.annotations.UnderlineAnnotation( + document.pages[1], + ap.Rectangle(299.988, 713.664, 308.708, 720.769, True), +) +underline_annotation.title = "Aspose User" +underline_annotation.subject = "Inserted Underline 1" +underline_annotation.flags = ap.annotations.AnnotationFlags.PRINT +underline_annotation.color = ap.Color.blue + +document.pages[1].annotations.append(underline_annotation) +document.save(outfile) +``` + +```python +def text_underline_annotation_add(infile, outfile): + document = ap.Document(infile) + + underline_annotation = ap.annotations.UnderlineAnnotation( + document.pages[1], + ap.Rectangle(299.988, 713.664, 308.708, 720.769, True), + ) + underline_annotation.title = "Aspose User" + underline_annotation.subject = "Inserted Underline 1" + underline_annotation.flags = ap.annotations.AnnotationFlags.PRINT + underline_annotation.color = ap.Color.blue + + document.pages[1].annotations.append(underline_annotation) + document.save(outfile) +``` + +#### Agregar Texto Subrayado Anotaciones Aplanar + +Si deseas que el subrayado se convierta en parte del contenido de la página en lugar de permanecer como una anotación interactiva, puedes aplanarlo después de añadirlo. + +```python +document = ap.Document(infile) + +underline_annotation = ap.annotations.UnderlineAnnotation( + document.pages[1], + ap.Rectangle(299.988, 713.664, 308.708, 720.769, True), +) +underline_annotation.title = "Aspose User" +underline_annotation.subject = "Inserted Underline to Flatten" +underline_annotation.flags = ap.annotations.AnnotationFlags.PRINT +underline_annotation.color = ap.Color.blue + +document.pages[1].annotations.append(underline_annotation) +underline_annotation.flatten() + +document.save(outfile) +``` + +```python +def text_underline_flatten_add(infile, outfile): + document = ap.Document(infile) + + underline_annotation = ap.annotations.UnderlineAnnotation( + document.pages[1], + ap.Rectangle(299.988, 713.664, 308.708, 720.769, True), + ) + underline_annotation.title = "Aspose User" + underline_annotation.subject = "Inserted Underline to Flatten" + underline_annotation.flags = ap.annotations.AnnotationFlags.PRINT + underline_annotation.color = ap.Color.blue + + document.pages[1].annotations.append(underline_annotation) + underline_annotation.flatten() + + document.save(outfile) +``` + +#### Agregar anotaciones de subrayado de texto con puntos cuádruples + +Los puntos quad le permiten definir el área exacta marcada para la anotación de subrayado. Esto es útil cuando necesita más control que un rectángulo simple. + +```python +document = ap.Document(infile) +rect = ap.Rectangle(299.988, 713.664, 308.708, 720.769, True) + +underline_annotation = ap.annotations.UnderlineAnnotation(document.pages[1], rect) +underline_annotation.title = "Aspose User" +underline_annotation.subject = "Inserted Underline with Quad Points" +underline_annotation.flags = ap.annotations.AnnotationFlags.PRINT +underline_annotation.color = ap.Color.blue +underline_annotation.quad_points = [ + ap.Point(rect.llx, rect.lly), + ap.Point(rect.urx, rect.lly), + ap.Point(rect.urx, rect.ury), + ap.Point(rect.llx, rect.ury), +] + +document.pages[1].annotations.append(underline_annotation) +document.save(outfile) +``` + +```python +def text_underline_with_quad_points_add(infile, outfile): + document = ap.Document(infile) + rect = ap.Rectangle(299.988, 713.664, 308.708, 720.769, True) + + underline_annotation = ap.annotations.UnderlineAnnotation(document.pages[1], rect) + underline_annotation.title = "Aspose User" + underline_annotation.subject = "Inserted Underline with Quad Points" + underline_annotation.flags = ap.annotations.AnnotationFlags.PRINT + underline_annotation.color = ap.Color.blue + underline_annotation.quad_points = [ + ap.Point(rect.llx, rect.lly), + ap.Point(rect.urx, rect.lly), + ap.Point(rect.urx, rect.ury), + ap.Point(rect.llx, rect.ury), + ] + + document.pages[1].annotations.append(underline_annotation) + document.save(outfile) +``` + +#### Eliminar anotaciones de subrayado de texto + +Este flujo de trabajo elimina todas las anotaciones de subrayado de la primera página y guarda el documento actualizado. + +```python +document = ap.Document(infile) +underline_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.UNDERLINE +] + +for annotation in underline_annotations: + document.pages[1].annotations.delete(annotation) + +document.save(outfile) +``` + +```python +def text_underline_annotation_delete(infile, outfile): + document = ap.Document(infile) + underline_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.UNDERLINE + ] + + for annotation in underline_annotations: + document.pages[1].annotations.delete(annotation) + + document.save(outfile) +``` + +#### Eliminar anotaciones de subrayado de texto por título + +Este flujo de trabajo muestra cómo eliminar selectivamente anotaciones de subrayado después de verificar su título. + +```python +document = ap.Document(infile) + +underline_annotations = [ + cast(ap.annotations.UnderlineAnnotation, annotation) + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.UNDERLINE +] + +for annotation in underline_annotations: + if annotation.title.startswith("a"): + document.pages[1].annotations.delete(annotation) + +document.save(outfile) +``` + +```python +def text_underline_by_title_delete(infile, outfile): + document = ap.Document(infile) + + underline_annotations = [ + cast(ap.annotations.UnderlineAnnotation, annotation) + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.UNDERLINE + ] + + for annotation in underline_annotations: + if annotation.title.startswith("a"): + document.pages[1].annotations.delete(annotation) + + document.save(outfile) +``` + +#### Obtener anotaciones de subrayado de texto + +Para inspeccionar anotaciones subrayadas, filtre las anotaciones de la primera página por el `UNDERLINE` escribe e imprime cada rectángulo. + +```python +document = ap.Document(infile) +underline_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.UNDERLINE +] + +for annotation in underline_annotations: + print(annotation.rect) +``` + +```python +def text_underline_annotation_get(infile, outfile): + document = ap.Document(infile) + underline_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.UNDERLINE + ] + + for annotation in underline_annotations: + print(annotation.rect) +``` + +#### Obtener texto subrayado de anotaciones de texto marcado + +Este flujo de trabajo convierte cada anotación de subrayado en una `UnderlineAnnotation` objeto y extrae el texto marcado. + +```python +document = ap.Document(infile) + +underline_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.UNDERLINE +] + +for annotation in underline_annotations: + ua = cast(ap.annotations.UnderlineAnnotation, annotation) + print(f"Marked text: {ua.get_marked_text()}") +``` + +```python +def text_underline_marked_text_get(infile, outfile): + document = ap.Document(infile) + + underline_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.UNDERLINE + ] + + for annotation in underline_annotations: + ua = cast(ap.annotations.UnderlineAnnotation, annotation) + print(f"Marked text: {ua.get_marked_text()}") +``` + +#### Obtener Fragmentos Marcados de Anotaciones de Subrayado de Texto + +Si necesita cada fragmento marcado por separado, puede iterar a través de la colección devuelta por `get_marked_text_fragments()`. + +```python +document = ap.Document(infile) + +underline_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.UNDERLINE +] + +for annotation in underline_annotations: + ua = cast(ap.annotations.UnderlineAnnotation, annotation) + for fragment in ua.get_marked_text_fragments(): + print(f"Fragment text: {fragment.text}") +``` + +```python +def text_underline_marked_fragments_get(infile, outfile): + document = ap.Document(infile) + + underline_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.UNDERLINE + ] + + for annotation in underline_annotations: + ua = cast(ap.annotations.UnderlineAnnotation, annotation) + for fragment in ua.get_marked_text_fragments(): + print(f"Fragment text: {fragment.text}") +``` + + +### Anotaciones onduladas + +#### Agregar anotaciones onduladas + +Las anotaciones onduladas se utilizan a menudo para marcar áreas de ortografía, gramática o atención en el texto. Este ejemplo añade una anotación ondulada a la primera página. + +```python +document = ap.Document(infile) +page = document.pages[1] + +squiggly_annotation = ap.annotations.SquigglyAnnotation( + page, + ap.Rectangle(67, 317, 261, 459, True), +) +squiggly_annotation.title = "John Smith" +squiggly_annotation.color = ap.Color.blue + +page.annotations.append(squiggly_annotation) +document.save(outfile) +``` + +```python +def text_squiggly_annotation_add(infile, outfile): + document = ap.Document(infile) + page = document.pages[1] + + squiggly_annotation = ap.annotations.SquigglyAnnotation( + page, + ap.Rectangle(67, 317, 261, 459, True), + ) + squiggly_annotation.title = "John Smith" + squiggly_annotation.color = ap.Color.blue + + page.annotations.append(squiggly_annotation) + document.save(outfile) +``` + +#### Obtener anotaciones onduladas + +Para inspeccionar anotaciones onduladas, filtre las anotaciones de la página por la `SQUIGGLY` escriba e imprima sus rectángulos. + +```python +document = ap.Document(infile) +squiggly_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.SQUIGGLY +] + +for annotation in squiggly_annotations: + print(annotation.rect) +``` + +```python +def text_squiggly_annotation_get(infile, outfile): + document = ap.Document(infile) + squiggly_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.SQUIGGLY + ] + + for annotation in squiggly_annotations: + print(annotation.rect) +``` + +#### Eliminar anotaciones onduladas + +Este flujo de trabajo elimina todas las anotaciones onduladas de la primera página y guarda el resultado. + +```python +document = ap.Document(infile) +squiggly_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.SQUIGGLY +] + +for annotation in squiggly_annotations: + document.pages[1].annotations.delete(annotation) + +document.save(outfile) +``` + +```python +def text_squiggly_annotation_delete(infile, outfile): + document = ap.Document(infile) + squiggly_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.SQUIGGLY + ] + + for annotation in squiggly_annotations: + document.pages[1].annotations.delete(annotation) + + document.save(outfile) +``` + + +### Anotaciones de tachado + +#### Agregar anotaciones de tachado de texto + +Las anotaciones de tachado marcan el texto que debe ser tratado como eliminado o tachado. Este ejemplo agrega una anotación de tachado y establece sus metadatos y color. + +```python +document = ap.Document(infile) + +strikeout_annotation = ap.annotations.StrikeOutAnnotation( + document.pages[1], + ap.Rectangle(299.988, 713.664, 308.708, 720.769, True), +) +strikeout_annotation.title = "Aspose User" +strikeout_annotation.subject = "Inserted text 1" +strikeout_annotation.flags = ap.annotations.AnnotationFlags.PRINT +strikeout_annotation.color = ap.Color.blue + +document.pages[1].annotations.append(strikeout_annotation) +document.save(outfile) +``` + +```python +def text_strikeout_annotation_add(infile, outfile): + document = ap.Document(infile) + + strikeout_annotation = ap.annotations.StrikeOutAnnotation( + document.pages[1], + ap.Rectangle(299.988, 713.664, 308.708, 720.769, True), + ) + strikeout_annotation.title = "Aspose User" + strikeout_annotation.subject = "Inserted text 1" + strikeout_annotation.flags = ap.annotations.AnnotationFlags.PRINT + strikeout_annotation.color = ap.Color.blue + + document.pages[1].annotations.append(strikeout_annotation) + document.save(outfile) +``` + +#### Obtener anotaciones de tachado de texto + +Para inspeccionar anotaciones de tachado, filtre las anotaciones de la página por el `STRIKE_OUT` escriba e imprima sus rectángulos. + +```python +document = ap.Document(infile) +strikeout_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.STRIKE_OUT +] + +for annotation in strikeout_annotations: + print(annotation.rect) +``` + +```python +def text_strikeout_annotation_get(infile, outfile): + document = ap.Document(infile) + strikeout_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.STRIKE_OUT + ] + + for annotation in strikeout_annotations: + print(annotation.rect) +``` + +#### Eliminar anotaciones de tachado de texto + +Este flujo de trabajo elimina todas las anotaciones de tachado de la primera página y guarda el documento actualizado. + +```python +document = ap.Document(infile) +strikeout_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.STRIKE_OUT +] + +for annotation in strikeout_annotations: + document.pages[1].annotations.delete(annotation) + +document.save(outfile) +``` + +```python +def text_strikeout_annotation_delete(infile, outfile): + document = ap.Document(infile) + strikeout_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.STRIKE_OUT + ] + + for annotation in strikeout_annotations: + document.pages[1].annotations.delete(annotation) + + document.save(outfile) +``` + +## Temas relacionados + +- [Importar y Exportar Anotaciones](/python-net/import-export-annotations/) +- [Anotaciones Interactivas](/python-net/interactive-annotations/) +- [Anotaciones de marcado](/python-net/markup-annotations/) +- [Anotaciones multimedia](/python-net/media-annotations/) +- [Anotaciones de seguridad](/python-net/security-annotations/) +- [Anotaciones de forma](/python-net/shape-annotations/) +- [Anotaciones de marca de agua](/python-net/watermark-annotations/) diff --git a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text/_index.md b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text/_index.md deleted file mode 100644 index 5b863f6ac..000000000 --- a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text/_index.md +++ /dev/null @@ -1,334 +0,0 @@ ---- -title: Uso de Anotación de Texto para PDF a través de Python -linktitle: Anotación de Texto -type: docs -weight: 10 -url: /es/python-net/text-annotation/ -description: Aspose.PDF para Python le permite Agregar, Obtener y Eliminar Anotación de Texto de su documento PDF. -lastmod: "2023-02-17" -sitemap: - changefreq: "monthly" - priority: 0.5 ---- - - - -## Cómo agregar una anotación de texto a un archivo PDF existente - -Una anotación de texto es una anotación adjunta a una ubicación específica en un documento PDF. Cuando está cerrada, la anotación se muestra como un ícono; cuando está abierta, debería mostrar una ventana emergente que contenga el texto de la nota en la fuente y tamaño elegidos por el lector. - -Las anotaciones están contenidas en la colección [Annotations](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/annotationcollection/) de una página en particular. Esta colección contiene las anotaciones solo para esa página individual; cada página tiene su propia colección de Annotations. - -Para agregar una anotación a una página en particular, agrégala a la colección Annotations de esa página con el método [add()](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/annotationcollection/#methods). - -1. Primero, crea una anotación que desees agregar al PDF. -1. Luego abre el PDF de entrada. - -1. Agrega la anotación a la colección de [Annotations](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/annotationcollection/) del objeto 'page'. - -El siguiente fragmento de código te muestra cómo agregar una anotación en una página PDF. - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - - textAnnotation = ap.annotations.TextAnnotation( - document.pages[1], ap.Rectangle(300, 700.664, 320, 720.769, True) - ) - textAnnotation.title = "Usuario de Aspose" - textAnnotation.subject = "Texto insertado 1" - textAnnotation.contents = "qwerty" - textAnnotation.flags = ap.annotations.AnnotationFlags.PRINT - textAnnotation.color = ap.Color.blue - - document.pages[1].annotations.append(textAnnotation) - document.save(output_file) -``` - -## Obtener anotación de texto del archivo PDF - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - textAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.TEXT) - ] - - for ta in textAnnotations: - print(ta.rect) -``` - - -## Eliminar anotación de texto de un archivo PDF - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - textAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.TEXT) - ] - - for ta in textAnnotations: - document.pages[1].annotations.delete(ta) - - document.save(output_file) -``` - -## Cómo agregar (o crear) una nueva anotación de texto libre - -Una anotación de texto libre muestra texto directamente en la página. La clase [FreeTextAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/freetextannotation/) permite crear este tipo de anotación. En el siguiente fragmento, agregamos una anotación de texto libre sobre la primera aparición de la cadena. - -```python - - import aspose.pdf as ap - - # Cargar el archivo PDF - document = ap.Document(input_file) - - freeTextAnnotation = ap.annotations.FreeTextAnnotation( - document.pages[1], ap.Rectangle(299, 713, 308, 720, True), ap.annotations.DefaultAppearance() - ) - freeTextAnnotation.title = "Aspose User" - freeTextAnnotation.color = ap.Color.light_green - - document.pages[1].annotations.append(freeTextAnnotation) - document.save(output_file) -``` - - -## Obtener anotación de texto libre de un archivo PDF - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - freeTextAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.FREE_TEXT) - ] - - for fa in freeTextAnnotations: - print(fa.rect) -``` - -## Eliminar anotación de texto libre de un archivo PDF - -```python - - import aspose.pdf as ap - - # Cargar el archivo PDF - document = ap.Document(input_file) - freeTextAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.FREE_TEXT) - ] - - for fa in freeTextAnnotations: - document.pages[1].annotations.delete(fa) - - document.save(output_file) -``` - -### Tachado de palabras usando StrikeOutAnnotation - -Aspose.PDF para Python te permite agregar, eliminar y actualizar anotaciones en documentos PDF. - Una de las clases también te permite tachar anotaciones. Cuando se aplica una StrikeOutAnnotation a un PDF, se dibuja una línea a través del texto especificado, indicando que debe ser eliminado o ignorado. - -El siguiente fragmento de código muestra cómo agregar una [StrikeOutAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/strikeoutannotation/) a un PDF. - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - - strikeoutAnnotation = ap.annotations.StrikeOutAnnotation( - document.pages[1], ap.Rectangle(299.988, 713.664, 308.708, 720.769, True) - ) - strikeoutAnnotation.title = "Usuario de Aspose" - strikeoutAnnotation.subject = "Texto insertado 1" - strikeoutAnnotation.flags = ap.annotations.AnnotationFlags.PRINT - strikeoutAnnotation.color = ap.Color.blue - - document.pages[1].annotations.append(strikeoutAnnotation) - document.save(output_file) -``` - -## Obtener StrikeOutAnnotation de PDF - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - StrikeoutAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.STRIKE_OUT) - ] - - for pa in StrikeoutAnnotations: - print(pa.rect) -``` - -## Eliminar StrikeOutAnnotation de PDF - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - StrikeoutAnnotations = [ - a - for a in document.pages[1].annotations - if (a.annotation_type == ap.annotations.AnnotationType.STRIKE_OUT) - ] - - for pa in StrikeoutAnnotations: - document.pages[1].annotations.delete(pa) - - document.save(output_file) -``` - - - \ No newline at end of file diff --git a/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/watermark-annotations/_index.md b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/watermark-annotations/_index.md new file mode 100644 index 000000000..4a97ca730 --- /dev/null +++ b/es/python-net/advanced-operations/annotations/add-delete-and-get-annotation/watermark-annotations/_index.md @@ -0,0 +1,186 @@ +--- +title: Anotaciones de marca de agua usando Python +linktitle: Anotaciones de marca de agua +type: docs +weight: 70 +url: /es/python-net/watermark-annotations/ +description: Aprenda cómo agregar, inspeccionar y eliminar anotaciones de marca de agua en documentos PDF usando Aspose.PDF for Python via .NET. +lastmod: "2026-04-21" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Trabaje con anotaciones de marca de agua en archivos PDF usando Python. +Abstract: Este artículo explica cómo crear, leer y eliminar anotaciones de marca de agua en documentos PDF usando Aspose.PDF for Python via .NET. Cubre la adición de una anotación de marca de agua de texto con estado de texto personalizado y opacidad, la inspección de anotaciones de marca de agua existentes y la eliminación de anotaciones de marca de agua de una página PDF. +--- + +Este artículo muestra cómo trabajar con anotaciones de marca de agua en documentos PDF usando Aspose.PDF for Python via .NET. + +El script de ejemplo muestra tres flujos de trabajo comunes: + +- agregar una anotación de marca de agua +- obtener rectángulos de anotación de marca de agua +- eliminar anotaciones de marca de agua + +## Agregar anotación de marca de agua + +Este ejemplo agrega una anotación de marca de agua a la primera página de un documento PDF. La marca de agua usa un estado de texto para controlar la configuración de la fuente y aplica una opacidad personalizada para lograr una apariencia semitransparente. + +### Abra el PDF y obtenga la página objetivo + +```python +document = ap.Document(infile) +page = document.pages[1] +``` + +### Crear la anotación de marca de agua + +Define el rectángulo de anotación y añádelo a la colección de anotaciones de la página. + +```python +watermark_annotation = ap.annotations.WatermarkAnnotation( + page, + ap.Rectangle(100, 100, 400, 200, True), +) + +page.annotations.append(watermark_annotation) +``` + +### Configurar la apariencia del texto + +Crear un `TextState` objeto para controlar el color del texto, el tamaño de fuente y la familia de fuentes. + +```python +text_state = ap.text.TextState() +text_state.foreground_color = ap.Color.blue +text_state.font_size = 25 +text_state.font = ap.text.FontRepository.find_font("Arial") +``` + +### Establecer opacidad y texto de marca de agua + +El ejemplo utiliza una opacidad del 50% y escribe tres líneas de texto en la anotación de marca de agua. + +```python +watermark_annotation.opacity = 0.5 +watermark_annotation.set_text_and_state(["HELLO", "Line 1", "Line 2"], text_state) +``` + +### Guardar el PDF + +```python +document.save(outfile) +``` + +### Ejemplo completo + +```python +def watermark_add(infile, outfile): + document = ap.Document(infile) + page = document.pages[1] + + watermark_annotation = ap.annotations.WatermarkAnnotation( + page, + ap.Rectangle(100, 100, 400, 200, True), + ) + + page.annotations.append(watermark_annotation) + + text_state = ap.text.TextState() + text_state.foreground_color = ap.Color.blue + text_state.font_size = 25 + text_state.font = ap.text.FontRepository.find_font("Arial") + + watermark_annotation.opacity = 0.5 + watermark_annotation.set_text_and_state(["HELLO", "Line 1", "Line 2"], text_state) + + document.save(outfile) +``` + +## Obtener anotación de marca de agua + +Para inspeccionar las anotaciones de marca de agua existentes, filtre las anotaciones de la primera página por la `WATERMARK` escriba e imprima sus rectángulos. + +### Cargar el documento y recopilar anotaciones de marca de agua + +```python +document = ap.Document(infile) +watermark_annotations = [ + a + for a in document.pages[1].annotations + if a.annotation_type == ap.annotations.AnnotationType.WATERMARK +] +``` + +### Imprimir los rectángulos de anotación + +```python +for watermark_annotation in watermark_annotations: + print(watermark_annotation.rect) +``` + +### Ejemplo completo + +```python +def watermark_get(infile, outfile): + document = ap.Document(infile) + watermark_annotations = [ + a + for a in document.pages[1].annotations + if a.annotation_type == ap.annotations.AnnotationType.WATERMARK + ] + + for watermark_annotation in watermark_annotations: + print(watermark_annotation.rect) +``` + +## Eliminar anotación de marca de agua + +Este flujo de trabajo elimina todas las anotaciones de marca de agua de la primera página y guarda el PDF actualizado. + +### Buscar anotaciones de marca de agua para eliminar + +```python +document = ap.Document(infile) +watermark_annotations = [ + a + for a in document.pages[1].annotations + if a.annotation_type == ap.annotations.AnnotationType.WATERMARK +] +``` + +### Eliminar las anotaciones y guardar el PDF + +```python +for watermark_annotation in watermark_annotations: + document.pages[1].annotations.delete(watermark_annotation) + +document.save(outfile) +``` + +### Ejemplo completo + +```python +def watermark_delete(infile, outfile): + document = ap.Document(infile) + watermark_annotations = [ + a + for a in document.pages[1].annotations + if a.annotation_type == ap.annotations.AnnotationType.WATERMARK + ] + + for watermark_annotation in watermark_annotations: + document.pages[1].annotations.delete(watermark_annotation) + + document.save(outfile) +``` + +## Temas relacionados + +- [Importar y Exportar Anotaciones](/python-net/import-export-annotations/) +- [Anotaciones Interactivas](/python-net/interactive-annotations/) +- [Anotaciones de marcado](/python-net/markup-annotations/) +- [Anotaciones multimedia](/python-net/media-annotations/) +- [Anotaciones de seguridad](/python-net/security-annotations/) +- [Anotaciones de forma](/python-net/shape-annotations/) +- [Anotaciones basadas en texto](/python-net/text-based-Annotations/) diff --git a/es/python-net/advanced-operations/annotations/import-export-annotations/_index.md b/es/python-net/advanced-operations/annotations/import-export-annotations/_index.md new file mode 100644 index 000000000..4ccd59c38 --- /dev/null +++ b/es/python-net/advanced-operations/annotations/import-export-annotations/_index.md @@ -0,0 +1,102 @@ +--- +title: Importar y exportar anotaciones usando Python +linktitle: Importar y exportar anotaciones +type: docs +weight: 80 +url: /es/python-net/import-export-annotations/ +description: Aprenda cómo importar anotaciones de un PDF y exportarlas a un nuevo documento PDF usando Aspose.PDF for Python via .NET. +lastmod: "2026-04-21" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Transfiera anotaciones PDF entre documentos en Python. +Abstract: Este artículo explica cómo copiar anotaciones de un PDF de origen y exportarlas a un nuevo documento PDF utilizando Aspose.PDF for Python via .NET. La guía divide el proceso en pasos pequeños, incluyendo la carga del archivo de origen, la creación del documento de destino, la adición de una página, la copia de anotaciones de la primera página y el guardado del resultado. +--- + +Este artículo muestra cómo importar anotaciones de un PDF existente y exportarlas a un nuevo documento PDF usando Aspose.PDF for Python via .NET. + +El ejemplo lee anotaciones de la primera página de un archivo de origen, crea un nuevo PDF, añade una página en blanco y copia cada anotación a esa nueva página. Este enfoque es útil cuando necesitas mover comentarios, marcas o notas de revisión a un documento de salida separado. + +## Cargar el PDF de origen + +Crear una `Document` objeto para el archivo de entrada que ya contiene anotaciones. Este objeto brinda acceso a la colección de páginas y a las anotaciones almacenadas en cada página. + +```python +source_document = ap.Document(infile) +``` + +## Crear el PDF de destino + +A continuación, cree un documento PDF vacío que recibirá las anotaciones importadas. En esta etapa, el documento de destino no contiene ninguna página. + +```python +destination_document = ap.Document() +``` + +## Agregar una página para anotaciones exportadas + +Dado que las anotaciones deben pertenecer a una página, añada una nueva página al documento de destino antes de copiar cualquier cosa. + +```python +page = destination_document.pages.add() +``` + +## Copiar anotaciones de la página de origen + +Iterar a través de la colección de anotaciones en la primera página del PDF de origen y agregar cada anotación a la nueva página en el documento de destino. + +El segundo argumento en `page.annotations.add(annot, True)` indica a Aspose.PDF que copie la anotación en la página de destino en lugar de solo reutilizar la referencia de objeto existente. + +```python +for annot in source_document.pages[1].annotations: + page.annotations.add(annot, True) +``` + +## Guarda el documento de salida + +Después de que se hayan copiado todas las anotaciones, guarde el documento de destino para crear el archivo PDF final. + +```python +destination_document.save(outfile) +``` + +## Ejemplo completo + +El siguiente código combina todos los pasos en una función reutilizable: + +```python +import sys +import aspose.pdf as ap +from os import path + + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def import_export(infile, outfile): + """ + Import annotations from one PDF document and export them to a new PDF document. + """ + source_document = ap.Document(infile) + destination_document = ap.Document() + + page = destination_document.pages.add() + + for annot in source_document.pages[1].annotations: + page.annotations.add(annot, True) + + destination_document.save(outfile) +``` + +## Temas relacionados + +- [Anotaciones interactivas](/python-net/interactive-annotations/) +- [Anotaciones de marcado](/python-net/markup-annotations/) +- [Anotaciones de medios](/python-net/media-annotations/) +- [Anotaciones de Seguridad](/python-net/security-annotations/) +- [Anotaciones de forma](/python-net/shape-annotations/) +- [Anotaciones basadas en texto](/python-net/text-based-Annotations/) +- [Anotaciones de Marca de Agua](/python-net/watermark-annotations/) diff --git a/es/python-net/advanced-operations/artifacts/_index.md b/es/python-net/advanced-operations/artifacts/_index.md new file mode 100644 index 000000000..ce2c116f7 --- /dev/null +++ b/es/python-net/advanced-operations/artifacts/_index.md @@ -0,0 +1,67 @@ +--- +title: Trabajar con artefactos PDF en Python +linktitle: Trabajando con artefactos +type: docs +weight: 170 +url: /es/python-net/artifacts/ +description: Aprenda cómo trabajar con artefactos PDF en Python para agregar fondos, marcas de agua y numeración Bates, y contar tipos de artefactos con Aspose.PDF for Python via .NET. +lastmod: "2026-05-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar artefactos de fondos, marcas de agua y numeración Bates en Python +Abstract: Este artículo explica cómo trabajar con artefactos PDF en Aspose.PDF for Python via .NET. Aprenda qué son los artefactos, por qué son importantes para la accesibilidad y el diseño de documentos, y cómo agregar imágenes de fondo, aplicar marcas de agua, agregar numeración Bates y examinar los tipos de artefactos en archivos PDF con Python. +--- + +Los artefactos en PDF son objetos gráficos u otros elementos que no forman parte del contenido real del documento. Normalmente se utilizan para decoración, diseño o propósitos de fondo. Ejemplos de artefactos incluyen encabezados y pies de página, separadores o imágenes que no transmiten ningún significado. + +El propósito de los artefactos en PDF es permitir la distinción entre elementos de contenido y elementos que no forman parte del contenido. Esto es importante para la accesibilidad, ya que los lectores de pantalla y otras tecnologías de asistencia pueden ignorar los artefactos y centrarse en el contenido relevante. Los artefactos también pueden mejorar el rendimiento y la calidad de los documentos PDF, ya que pueden omitirse en la impresión, la búsqueda o la copia. + +Utilice esta sección cuando necesite crear o inspeccionar elementos PDF que no forman parte del contenido en Python, como fondos de documentos, marcas de agua de página y marcas de numeración Bates. Las siguientes guías muestran los principales flujos de trabajo de artefactos compatibles con Aspose.PDF for Python via .NET. + +Para crear un elemento como artefacto en PDF, necesita usar la clase [Artifact](https://reference.aspose.com/pdf/python-net/aspose.pdf/artifact/). +Esta clase contiene las siguientes propiedades útiles: + +- **custom_type** - Obtiene el nombre del tipo de artefacto. Puede usarse si el tipo de artefacto no es estándar. +- **custom_subtype** - Obtiene el nombre del subtipo de artefacto. Puede usarse si el subtipo de artefacto no es un subtipo estándar. +- **type** - Obtiene el tipo de artefacto. +- **subtype** - Obtiene el subtipo de artefacto. Si el artefacto tiene un subtipo no estándar, el nombre del subtipo puede leerse a través de CustomSubtype. +- **contents** - Obtiene la colección de operadores internos del artefacto. +- **form** - Obtiene el XForm del artefacto (si se usa XForm). +- **rectangle** - Obtiene el rectángulo del artefacto. +- **position** - Obtiene o establece la posición del artefacto. Si se especifica esta propiedad, entonces los márgenes y alineaciones se ignoran. +- **right_margin** - Margen derecho del artefacto. Si la posición se especifica explícitamente (en la propiedad Position) este valor se ignora. +- **left_margin** - Margen izquierdo del artefacto. Si la posición se especifica explícitamente (en la propiedad Position) este valor se ignora. +- **top_margin** - Margen superior del artefacto. Si la posición se especifica explícitamente (en la propiedad Position) este valor se ignora. +- **bottom_margin** - Margen inferior del artefacto. Si la posición se especifica explícitamente (en la propiedad Position) este valor se ignora. +- **artifact_horizontal_alignment** - Alineación horizontal del artefacto. Si la posición se especifica explícitamente (en la propiedad Position) este valor se ignora. +- **artifact_vertical_alignment** - Alineación vertical del artefacto. Si la posición se especifica explícitamente (en la propiedad Position) este valor se ignora. +- **rotation** - Obtiene o establece el ángulo de rotación del artefacto. +- **text** - Obtiene el texto del artefacto. +- **image** - Obtiene la imagen del artefacto (si está presente). +- **opacity** - Obtiene o establece la opacidad del artefacto. Los valores posibles están en el rango 0..1. +- **lines** - Líneas del artefacto de texto multilínea. +- **text_state** - Estado de texto para el texto del artefacto. +- **is_background** - Si es verdadero, el Artefacto se coloca detrás del contenido de la página. + +Las siguientes clases también pueden ser útiles para trabajar con artefactos: + +- [ArtifactCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/artifactcollection/) +- [BackgroundArtifact](https://reference.aspose.com/pdf/python-net/aspose.pdf/backgroundartifact/) +- [HeaderArtifact](https://reference.aspose.com/pdf/python-net/aspose.pdf/headerartifact/) +- [FooterArtifact](https://reference.aspose.com/pdf/python-net/aspose.pdf/footerartifact/) +- [WatermarkArtifact](https://reference.aspose.com/pdf/python-net/aspose.pdf/watermarkartifact/) +- [BatesNArtifact](https://reference.aspose.com/pdf/python-net/aspose.pdf/batesnartifact/) + +## Flujos de trabajo de artefactos cubiertos en esta sección + +Por favor revise las siguientes secciones del artículo: + +- [Agregar fondos](/pdf/es/python-net/add-backgrounds/) - agregue una imagen de fondo a su archivo PDF con Python. +- [Agregar numeración Bates](/pdf/es/python-net/add-bates-numbering/) - agregar numeración Bates al PDF. +- [Agregar marca de agua](/pdf/es/python-net/add-watermarks/) - cómo agregar una marca de agua al PDF con Python. +- [Contar artefactos](/pdf/es/python-net/counting-artifacts/) - contar artefactos en PDF usando Python. +- [Administrar encabezados y pies de página de PDF](/pdf/es/python-net/artifacts-header-footer/) - gestionar encabezados y pies de página en documentos PDF. + +Estos tutoriales son útiles cuando necesitas gestionar elementos decorativos o estructurales del PDF sin cambiar el flujo de contenido principal del documento. diff --git a/es/python-net/advanced-operations/artifacts/add-backgrounds/_index.md b/es/python-net/advanced-operations/artifacts/add-backgrounds/_index.md new file mode 100644 index 000000000..fa020f35c --- /dev/null +++ b/es/python-net/advanced-operations/artifacts/add-backgrounds/_index.md @@ -0,0 +1,148 @@ +--- +title: Agregar fondos de PDF en Python +linktitle: Agregar fondos +type: docs +weight: 20 +url: /es/python-net/add-backgrounds/ +description: Aprenda cómo agregar una imagen de fondo a las páginas PDF en Python usando la clase BackgroundArtifact en Aspose.PDF for Python via .NET. +lastmod: "2026-04-15" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo agregar fondo a PDF con Python +Abstract: Este artículo analiza el uso de imágenes de fondo en documentos PDF mediante Aspose.PDF for Python via .NET. Destaca la capacidad de agregar marcas de agua o diseños sutiles a los documentos utilizando la clase `BackgroundArtifact`, que permite la incorporación de imágenes de fondo en objetos de página individuales. El artículo proporciona un ejemplo de código práctico que demuestra cómo implementar esta función. El proceso implica crear un nuevo documento PDF, agregar una página, crear un objeto `BackgroundArtifact`, establecer una imagen de fondo y agregar el artefacto de fondo a la colección de artefactos de la página. Finalmente, el documento modificado se guarda como un archivo PDF. Esta técnica permite una presentación visual mejorada de los documentos PDF. +--- + +## Agregar una imagen de fondo a un PDF + +Las imágenes de fondo pueden usarse para agregar una marca de agua, u otro diseño sutil, a los documentos. En Aspose.PDF for Python via .NET, cada documento PDF es una colección de páginas y cada página contiene una colección de artefactos. El [BackgroundArtifact](https://reference.aspose.com/pdf/python-net/aspose.pdf/backgroundartifact/) clase puede usarse para agregar una imagen de fondo a un objeto de página. + +Este enfoque es útil cuando necesitas colocar una imagen decorativa detrás del contenido principal del PDF sin convertirlo en texto del documento searchable. + +El siguiente fragmento de código muestra cómo agregar una imagen de fondo a las páginas PDF utilizando el objeto BackgroundArtifact con Python. + +1. Cargue el documento PDF. +1. Cree un artefacto de fondo. +1. Cargue el archivo de imagen. +1. Adjunte el artefacto a una página. +1. Guarde el documento actualizado. + +```python + +from os import path +from io import FileIO +import aspose.pdf as ap +import sys + +def add_background_image_to_pdf(infile, imagefile, outfile): + """Add a background image to a PDF document as an artifact.""" + with ap.Document(infile) as document: + artifact = ap.BackgroundArtifact() + artifact.background_image = FileIO(imagefile, "rb") + document.pages[1].artifacts.append(artifact) + document.save(outfile) +``` + +## Agregar una imagen de fondo con opacidad a un PDF + +Agregar una imagen de fondo semitransparente a una página PDF usando Aspose.PDF for Python. + +Al aplicar opacidad, la imagen de fondo se vuelve parcialmente transparente, permitiendo que el contenido original de la página (texto, imágenes, etc.) siga siendo claramente visible. Esto es especialmente útil para: + +- Marcas de agua +- Superposiciones de marca +- Sutiles mejoras de diseño + +El fondo se agrega como un artefacto, asegurando que permanezca detrás de todo el contenido de la página. + +1. Cargue el documento PDF. +1. Cree un artefacto de fondo. +1. Cargue el archivo de imagen. +1. Establezca el nivel de opacidad. +1. Adjunte el artefacto a una página. +1. Guarde el documento actualizado. + +```python + +from os import path +from io import FileIO +import aspose.pdf as ap +import sys + +def add_background_image_with_opacity_to_pdf(infile, imagefile, outfile): + """Add a background image with opacity to a PDF document as an artifact.""" + with ap.Document(infile) as document: + artifact = ap.BackgroundArtifact() + artifact.background_image = FileIO(imagefile, "rb") + artifact.opacity = 0.5 + document.pages[1].artifacts.append(artifact) + document.save(outfile) +``` + +## Agregar un color de fondo a un PDF + +Aplicar un color de fondo sólido a una página PDF usando Aspose.PDF for Python. + +1. Cargue el documento PDF. +1. Cree un artefacto de fondo. +1. Establecer el color de fondo. +1. Adjunte el artefacto a una página. +1. Guarde el documento actualizado. + +```python + +from os import path +from io import FileIO +import aspose.pdf as ap +import sys + +def add_background_color_to_pdf(infile, outfile): + """Add a solid color background to a PDF document as an artifact.""" + with ap.Document(infile) as document: + artifact = ap.BackgroundArtifact() + artifact.background_color = ap.Color.dark_khaki + document.pages[1].artifacts.append(artifact) + document.save(outfile) +``` + +## Eliminar fondo de un PDF + +Eliminar artefactos de fondo de una página PDF usando Aspose.PDF for Python. +Los fondos en los PDF a menudo se almacenan como artefactos, y este método identifica y elimina selectivamente solo aquellos artefactos que están clasificados como elementos de fondo. + +1. Cargue el documento PDF. +1. Acceder a los artefactos de página. +1. Filtrar artefactos de fondo. +1. Recopilar elementos de fondo. +1. Eliminar artefactos de fondo. +1. Guarde el documento actualizado. + +```python + +from os import path +from io import FileIO +import aspose.pdf as ap +import sys + +def remove_background(infile, outfile): + with ap.Document(infile) as document: + backgrounds = [ + artifact + for artifact in document.pages[1].artifacts + if artifact.type == ap.Artifact.ArtifactType.PAGINATION + and artifact.subtype == ap.Artifact.ArtifactSubtype.BACKGROUND + ] + + for background in backgrounds: + document.pages[1].artifacts.delete(background) + + document.save(outfile) +``` + +## Temas relacionados con artefactos + +- [Trabajar con artefactos PDF en Python](/pdf/es/python-net/artifacts/) +- [Agregar marcas de agua a PDF en Python](/pdf/es/python-net/add-watermarks/) +- [Agregar numeración Bates a PDF en Python](/pdf/es/python-net/add-bates-numbering/) +- [Contar tipos de artefactos en archivos PDF](/pdf/es/python-net/counting-artifacts/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md b/es/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md new file mode 100644 index 000000000..7374c4b6b --- /dev/null +++ b/es/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md @@ -0,0 +1,120 @@ +--- +title: Agregar numeración Bates a PDF en Python +linktitle: Agregar numeración Bates +type: docs +weight: 10 +url: /es/python-net/add-bates-numbering/ +description: Aprenda cómo agregar y eliminar la numeración Bates en documentos PDF usando Python con Aspose.PDF for Python via .NET. +lastmod: "2026-04-15" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar numeración Bates vía Python +Abstract: La numeración Bates es una característica crítica en los flujos de trabajo de documentos legales, médicos y empresariales, garantizando que cada página de un conjunto reciba un identificador único y secuencial para una referencia fiable. Este artículo muestra cómo Aspose.PDF for Python via .NET simplifica la automatización de la numeración Bates a través de su API flexible. Usando la clase BatesNArtifact, los desarrolladores pueden configurar el comportamiento de la numeración —incluyendo el recuento de dígitos, prefijos, sufijos, alineación y márgenes— y aplicarlo programáticamente en documentos completos. Se presentan varios enfoques, desde la aplicación directa del artefacto hasta la configuración basada en delegados, ofreciendo control tanto estático como dinámico. Además, la API admite la eliminación completa de los números Bates con una única llamada al método, lo que permite una gestión de ciclo de vida completa de los artefactos de paginación. Ejemplos de código claros y paso a paso ilustran cómo añadir, personalizar y eliminar la numeración Bates, convirtiendo esta guía en un recurso práctico para desarrolladores que buscan optimizar los flujos de trabajo de procesamiento de documentos. +--- + +La numeración Bates se usa ampliamente en flujos de trabajo legales, médicos y empresariales para asignar identificadores únicos y secuenciales a las páginas dentro de un conjunto de documentos. Aspose.PDF for Python via .NET ofrece una API simple y flexible para automatizar este proceso, permitiéndote aplicar números Bates estandarizados de forma programática en cualquier PDF. + +Usando el [`BatesNArtifact`](https://reference.aspose.com/pdf/python-net/aspose.pdf/batesnartifact/) clase, los desarrolladores pueden personalizar completamente el comportamiento de la numeración—incluyendo el número inicial, la cantidad de dígitos, los prefijos y sufijos, la alineación y los márgenes. Una vez configurado, el artefacto puede aplicarse al [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) a través del `add_bates_numbering` método en el [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) o añadido como parte de una lista de [`PaginationArtifact`](https://reference.aspose.com/pdf/python-net/aspose.pdf/paginationartifact/) objetos. Aspose.PDF también admite un estilo de configuración basado en delegados, que permite el control dinámico de la configuración de artefactos en tiempo de ejecución. + +Además de crear números Bates, la API proporciona una forma fácil de eliminarlos usando `delete_bates_numbering`, ofreciendo una flexibilidad completa en los flujos de trabajo de procesamiento de documentos. + +Este artículo muestra varios métodos para agregar y eliminar la numeración Bates en un PDF usando Aspose.PDF for Python via .NET, con ejemplos claros de configuración, aplicación y eliminación de artefactos. + +## Agregar artefacto de numeración Bates + +Este ejemplo muestra cómo agregar programáticamente la numeración Bates a un documento PDF usando Aspose.PDF for Python via .NET. Configurando un [`BatesNArtifact`](https://reference.aspose.com/pdf/python-net/aspose.pdf/batesnartifact/) con los ajustes deseados y aplicándolo a las páginas del documento, puede automatizar el proceso de añadir identificadores estandarizados a cada página. + +Para agregar un artefacto de numeración Bates a un [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/), llama al `AddBatesNumbering(BatesNArtifact)` método de extensión en el [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/), pasando un [`BatesNArtifact`](https://reference.aspose.com/pdf/python-net/aspose.pdf/batesnartifact/) instancia como el parámetro: + +```python +import sys +from os import path +import aspose.pdf as ap + +def _create_bates_artifact(): + """Create a Bates numbering artifact with default settings.""" + artifact = ap.BatesNArtifact() + artifact.start_page = 1 + artifact.end_page = 0 + artifact.subset = ap.Subset.ALL + artifact.number_of_digits = 6 + artifact.start_number = 1 + artifact.prefix = "" + artifact.suffix = "" + artifact.artifact_vertical_alignment = ap.VerticalAlignment.BOTTOM + artifact.artifact_horizontal_alignment = ap.HorizontalAlignment.RIGHT + artifact.right_margin = 72 + artifact.left_margin = 72 + artifact.top_margin = 36 + artifact.bottom_margin = 36 + return artifact +``` + +```python +import sys +from os import path +import aspose.pdf as ap + +def add_bates_n_artifact(infile, outfile): + """Add Bates numbering artifact to a PDF document.""" + with ap.Document(infile) as document: + for _ in range(2): + document.pages.add() + + bates_artifact = _create_bates_artifact() + ap.PageCollectionExtensions.add_bates_numbering(document.pages, bates_artifact) + document.save(outfile) +``` + +## Agregar numeración Bates usando artefactos de paginación + +Agregar numeración Bates a un PDF usando la colección de artefactos de paginación en Aspose.PDF for Python: + +1. Cargue el documento PDF. +1. Inserte páginas extra si es necesario antes de aplicar la numeración. +1. Cree un artefacto Bates. +1. Configure las propiedades del artefacto. +1. Añada el artefacto a la colección de paginación. +1. Aplicar paginación a las páginas. +1. Guarde el documento actualizado. + +```python +import sys +from os import path +import aspose.pdf as ap + +def add_bates_n_artifact_pagination(infile, outfile): + """Add Bates numbering using pagination artifacts collection.""" + with ap.Document(infile) as document: + for _ in range(2): + document.pages.add() + + bates_artifact = _create_bates_artifact() + ap.PageCollectionExtensions.add_pagination(document.pages, [bates_artifact]) + document.save(outfile) +``` + +## Eliminar numeración Bates + +Para eliminar la numeración Bates de un [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/), use el `delete_bates_numbering()` método en el [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/): + +```python +import sys +from os import path +import aspose.pdf as ap + +def delete_bates_numbering(infile, outfile): + """Delete Bates numbering from a PDF document.""" + with ap.Document(infile) as document: + ap.PageCollectionExtensions.delete_bates_numbering(document.pages) + document.save(outfile) +``` + +## Temas relacionados con artefactos + +- [Trabajar con artefactos PDF en Python](/pdf/es/python-net/artifacts/) +- [Agregar marcas de agua a PDF en Python](/pdf/es/python-net/add-watermarks/) +- [Agregar fondos PDF en Python](/pdf/es/python-net/add-backgrounds/) +- [Contar tipos de artefactos en archivos PDF](/pdf/es/python-net/counting-artifacts/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/artifacts/add-watermarks/_index.md b/es/python-net/advanced-operations/artifacts/add-watermarks/_index.md new file mode 100644 index 000000000..4bd70dea0 --- /dev/null +++ b/es/python-net/advanced-operations/artifacts/add-watermarks/_index.md @@ -0,0 +1,120 @@ +--- +title: Agregar marcas de agua a PDF en Python +linktitle: Agregar marca de agua +type: docs +weight: 30 +url: /es/python-net/add-watermarks/ +description: Aprenda cómo agregar artefactos de marca de agua a archivos PDF en Python usando Aspose.PDF for Python via .NET. +lastmod: "2026-04-15" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo agregar una marca de agua a PDF con Python +Abstract: El artículo discute el uso de Aspose.PDF for Python via .NET para agregar marcas de agua a documentos PDF mediante la gestión de artefactos. Presenta las clases clave para manejar artefactos - `Artifact` y `ArtifactCollection`, y describe cómo acceder a ellas a través de la propiedad `Artifacts` de la clase `Page`. El artículo detalla las propiedades de la clase `Artifact`, incluyendo atributos como `contents`, `form`, `image`, `text`, `rectangle`, `rotation` y `opacity`, que permiten una manipulación integral de los artefactos dentro de los archivos PDF. Además, se proporciona un ejemplo práctico, que muestra cómo agregar programáticamente una marca de agua a la primera página de un PDF usando Python. El fragmento de código ilustra la creación y configuración de un `WatermarkArtifact`, estableciendo su texto, alineación, rotación y opacidad, antes de añadirlo a un documento PDF y guardar los cambios. +--- + +Agregar un artefacto de marca de agua a un PDF [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) usando Aspose.PDF for Python via .NET. Una marca de agua es una superposición visual aplicada a las páginas para la marca, seguridad o propósitos informativos. El ejemplo muestra cómo configurar [`TextState`](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstate/) apariencia, posicionamiento con [`HorizontalAlignment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/horizontalalignment/) y [`VerticalAlignment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/verticalalignment/), rotación y transparencia antes de aplicar la marca de agua a un [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). + +## Extraer marcas de agua del PDF + +1. Cargue el documento PDF. +1. Acceder a los artefactos de página. +1. Filtrar artefactos de marcas de agua. +1. Recopilar elementos de marcas de agua. +1. Extraer propiedades de la marca de agua. +1. Mostrar información de la marca de agua. + +```python +from os import path +import sys +import aspose.pdf as ap + +def extract_watermark_from_pdf(infile): + with ap.Document(infile) as document: + watermarks = [ + artifact + for artifact in document.pages[1].artifacts + if artifact.type == ap.Artifact.ArtifactType.PAGINATION + and artifact.subtype == ap.Artifact.ArtifactSubtype.WATERMARK + ] + + for watermark in watermarks: + print(f"{watermark.text} {watermark.rectangle}") +``` + +## Agregar una marca de agua a PDF + +Agregar una marca de agua de texto a un documento PDF usando Aspose.PDF for Python: + +1. Cargue el documento PDF. +1. Crear un estado de texto. +1. Crear un artefacto de marca de agua. +1. Establecer el texto y el estilo de la marca de agua. +1. Configura la posición y la rotación. +1. Establece la opacidad y el comportamiento del fondo. +1. Adjunta la marca de agua a una página. +1. Guarde el documento actualizado. + +```python +from os import path +import sys +import aspose.pdf as ap + +def add_watermark_artifact(infile, outfile): + with ap.Document(infile) as document: + text_state = ap.text.TextState() + text_state.font_size = 72 + text_state.foreground_color = ap.Color.blue_violet + text_state.font_style = ap.text.FontStyles.BOLD + text_state.font = ap.text.FontRepository.find_font("Arial") + + watermark = ap.WatermarkArtifact() + watermark.set_text_and_state("WATERMARK", text_state) + watermark.artifact_horizontal_alignment = ap.HorizontalAlignment.CENTER + watermark.artifact_vertical_alignment = ap.VerticalAlignment.CENTER + watermark.rotation = 60 + watermark.opacity = 0.2 + watermark.is_background = True + + document.pages[1].artifacts.append(watermark) + document.save(outfile) + +``` + +## Eliminar artefactos de marca de agua de la página PDF + +Eliminar artefactos de marca de agua de una página específica en un documento PDF utilizando la Aspose.PDF for Python API. El enfoque busca los elementos de marca de agua almacenados como artefactos de página (específicamente los clasificados como subtipos de marca de agua de paginación), itera sobre ellos y los elimina antes de guardar el documento actualizado. + +1. Cargue el documento PDF. +1. Acceder a los artefactos de página. +1. Filtrar artefactos de marcas de agua. +1. Eliminar artefactos de marca de agua. +1. Guarde el documento actualizado. + +```python +from os import path +import sys +import aspose.pdf as ap + +def delete_watermark_artifact(infile, outfile): + with ap.Document(infile) as document: + watermarks = [ + artifact + for artifact in document.pages[1].artifacts + if artifact.type == ap.Artifact.ArtifactType.PAGINATION + and artifact.subtype == ap.Artifact.ArtifactSubtype.WATERMARK + ] + + for watermark in watermarks: + document.pages[1].artifacts.delete(watermark) + + document.save(outfile) +``` + +## Temas relacionados con artefactos + +- [Trabajar con artefactos PDF en Python](/pdf/es/python-net/artifacts/) +- [Agregar fondos PDF en Python](/pdf/es/python-net/add-backgrounds/) +- [Agregar numeración Bates a PDF en Python](/pdf/es/python-net/add-bates-numbering/) +- [Contar tipos de artefactos en archivos PDF](/pdf/es/python-net/counting-artifacts/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md b/es/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md new file mode 100644 index 000000000..9f921e053 --- /dev/null +++ b/es/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md @@ -0,0 +1,119 @@ +--- +title: Administrar encabezados y pies de página de PDF usando Python +linktitle: Administrar encabezados y pies de página de PDF +type: docs +weight: 70 +url: /es/python-net/artifacts-header-footer/ +description: Aprenda cómo administrar encabezados y pies de página en documentos PDF con Python y Aspose.PDF. +lastmod: "2026-04-21" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo agregar, personalizar y eliminar encabezados y pies de página de PDF usando Python +Abstract: La gestión de encabezados y pies de página es un requisito común al trabajar con documentos PDF en entornos empresariales, editoriales y de automatización. Este artículo muestra cómo usar Aspose.PDF for Python para agregar encabezados y pies de página de aspecto profesional con estilo personalizado como fuente, tamaño, color y alineación. También muestra cómo detectar y eliminar artefactos de paginación existentes, como encabezados y pies de página, de una página PDF. Con funciones reutilizables y ejemplos claros, los desarrolladores pueden integrar rápidamente estas funciones en sistemas de procesamiento de documentos para branding, generación de informes o limpieza de archivos. +--- + +## Crear artefactos de texto con estilo + +Esta función utilitaria explica cómo crear un artefacto de texto reutilizable para páginas PDF usando Aspose.PDF for Python. Está diseñada para generar encabezados o pies de página con estilo y un formato coherente, incluidos los ajustes de fuente, color, tamaño y alineación. La función abstrae la creación del artefacto para que pueda reutilizarse en diferentes decoraciones de texto a nivel de página. + +1. Instanciar el objeto artefacto. +1. Establecer el contenido de texto del artefacto. +1. Aplicar estilo de texto. +1. Establecer alineación. +1. Devolver artefacto configurado. + +```python +from os import path +import aspose.pdf as ap +import sys + +def _create_text_artifact(artifact_class, text): + """Create a text artifact (header/footer) with common styling.""" + artifact = artifact_class() + artifact.text = text + artifact.text_state.font_size = 14 + artifact.text_state.font = ap.text.FontRepository.find_font("Arial") + artifact.text_state.foreground_color = ap.Color.navy + artifact.artifact_horizontal_alignment = ap.HorizontalAlignment.CENTER + return artifact + +``` + +## Agregar encabezado al PDF + +1. Abrir el PDF de entrada. +1. Cree un HeaderArtifact con el texto "Sample Header". +1. Agréguelo a la primera página. +1. Guarde el PDF actualizado. + +```python +from os import path +import aspose.pdf as ap +import sys + +def add_header_artifact(infile, outfile): + """Add a header artifact to the first page of a PDF document.""" + with ap.Document(infile) as document: + header = _create_text_artifact(ap.HeaderArtifact, "Sample Header") + document.pages[1].artifacts.append(header) + document.save(outfile) +``` + +## Agregar pie de página al PDF + +1. Abrir el PDF de entrada. +1. Crear un FooterArtifact con el texto "Sample Footer". +1. Agréguelo a la primera página. +1. Guardar el archivo de salida. + +```python +from os import path +import aspose.pdf as ap +import sys + +def add_footer_artifact(infile, outfile): + """Add a footer artifact to the first page of a PDF document.""" + with ap.Document(infile) as document: + footer = _create_text_artifact(ap.FooterArtifact, "Sample Footer") + document.pages[1].artifacts.append(footer) + document.save(outfile) +``` + +## Eliminar artefactos de encabezado o pie de página + +1. Abrir el PDF. +1. Buscar artefactos marcados como encabezados o pies de página de paginación. +1. Elimínelos de la primera página. +1. Guarde el documento limpio. + +```python +from os import path +import aspose.pdf as ap +import sys + +def delete_header_footer_artifact(infile, outfile): + with ap.Document(infile) as document: + header_footers = [ + artifact + for artifact in document.pages[1].artifacts + if artifact.type == ap.Artifact.ArtifactType.PAGINATION + and ( + artifact.subtype == ap.Artifact.ArtifactSubtype.HEADER + or artifact.subtype == ap.Artifact.ArtifactSubtype.FOOTER + ) + ] + + for art in header_footers: + document.pages[1].artifacts.delete(art) + + document.save(outfile) +``` + +## Temas relacionados con artefactos + +- [Trabajar con artefactos PDF en Python](/pdf/es/python-net/artifacts/) +- [Agregar fondos PDF en Python](/pdf/es/python-net/add-backgrounds/) +- [Agregar numeración Bates a PDF en Python](/pdf/es/python-net/add-bates-numbering/) +- [Contar tipos de artefactos en archivos PDF](/pdf/es/python-net/counting-artifacts/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/artifacts/counting-artifacts/_index.md b/es/python-net/advanced-operations/artifacts/counting-artifacts/_index.md new file mode 100644 index 000000000..af6d9b494 --- /dev/null +++ b/es/python-net/advanced-operations/artifacts/counting-artifacts/_index.md @@ -0,0 +1,58 @@ +--- +title: Contar artefactos PDF en Python +linktitle: Contando artefactos +type: docs +weight: 40 +url: /es/python-net/counting-artifacts/ +description: Aprenda cómo inspeccionar y contar artefactos de paginación en documentos PDF usando Python con Aspose.PDF for Python via .NET. +lastmod: "2026-05-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Contando artefactos en PDF usando Python +Abstract: Los artefactos de paginación, como marcas de agua, fondos, encabezados y pies de página, se utilizan comúnmente en documentos PDF para proporcionar estructura, marca y identificación. Este ejemplo muestra cómo inspeccionar y contar estos artefactos de forma programática usando Aspose.PDF for Python via .NET. Al filtrar los artefactos en una página y agruparlos por subtipo, los desarrolladores pueden analizar rápidamente la composición del documento y verificar la presencia de elementos específicos. El código proporcionado ilustra cómo abrir un PDF, extraer los artefactos de paginación de la primera página, contar cada subtipo y mostrar los resultados, ofreciendo un enfoque práctico para la auditoría y validación de documentos. +--- + +## Contar artefactos de un tipo concreto + +Este ejemplo muestra cómo inspeccionar y contar artefactos de paginación en un PDF [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) usando Aspose.PDF for Python via .NET. Los artefactos de paginación incluyen elementos como marcas de agua, fondos, encabezados y pies de página que se aplican a las páginas con fines de diseño e identificación. Al filtrar objetos [`Artifact`](https://reference.aspose.com/pdf/python-net/aspose.pdf/artifact/) en una [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) y agruparlos por subtipo (`Artifact.ArtifactSubtype`), los desarrolladores pueden analizar rápidamente la estructura del documento y verificar la presencia de elementos específicos. + +Para calcular el recuento total de artefactos de un tipo concreto, por ejemplo el número total de marcas de agua, use el siguiente código. El ejemplo filtra la colección [`Artifacts`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) de la página, que es una [`ArtifactCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/artifactcollection/), por [`Artifact.ArtifactType`](https://reference.aspose.com/pdf/python-net/aspose.pdf/artifact/#properties) y luego cuenta los subtipos (`Artifact.ArtifactSubtype`). + +1. Abra el documento PDF (ver [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)). +1. Filtrar los artefactos de paginación usando la colección [`Artifacts`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) de la página. +1. Contar artefactos por subtipo (`Artifact.ArtifactSubtype`). +1. Imprima los resultados. + +```python + +from os import path +from collections import Counter +import sys +import aspose.pdf as ap + +def count_pdf_artifacts(infile): + """Count and display artifacts of different types on the first page.""" + with ap.Document(infile) as document: + pagination_artifacts = [ + artifact + for artifact in document.pages[1].artifacts + if artifact.type == ap.Artifact.ArtifactType.PAGINATION + ] + + subtypes = [artifact.subtype for artifact in pagination_artifacts] + counts = Counter(subtypes) + + print(f"Watermarks: {counts.get(ap.Artifact.ArtifactSubtype.WATERMARK, 0)}") + print(f"Backgrounds: {counts.get(ap.Artifact.ArtifactSubtype.BACKGROUND, 0)}") + print(f"Headers: {counts.get(ap.Artifact.ArtifactSubtype.HEADER, 0)}") + print(f"Footers: {counts.get(ap.Artifact.ArtifactSubtype.FOOTER, 0)}") +``` + +## Temas relacionados con artefactos + +- [Trabajar con artefactos PDF en Python](/pdf/es/python-net/artifacts/) +- [Agregar marcas de agua a PDF en Python](/pdf/es/python-net/add-watermarks/) +- [Agregar fondos PDF en Python](/pdf/es/python-net/add-backgrounds/) +- [Agregar numeración Bates a PDF en Python](/pdf/es/python-net/add-bates-numbering/) diff --git a/es/python-net/advanced-operations/attachments/_index.md b/es/python-net/advanced-operations/attachments/_index.md index b1f0a3bbc..d114042ea 100644 --- a/es/python-net/advanced-operations/attachments/_index.md +++ b/es/python-net/advanced-operations/attachments/_index.md @@ -1,84 +1,28 @@ --- -title: Trabajando con Adjuntos en PDF usando Python -linktitle: Trabajando con Adjuntos +title: Trabajar con archivos adjuntos PDF en Python +linktitle: Trabajando con adjuntos type: docs weight: 130 url: /es/python-net/attachments/ -description: Utilice la API de PDF de Python para acceder, agregar y eliminar adjuntos en archivos PDF usando Python desde sus aplicaciones. Guía completa con ejemplos de código en Python. -lastmod: "2023-02-17" +description: Aprenda cómo agregar, extraer, organizar y eliminar archivos adjuntos PDF en Python con Aspose.PDF for Python via .NET, incluyendo archivos incrustados y portafolios PDF. +lastmod: "2026-04-15" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar, eliminar y gestionar archivos adjuntos PDF y portafolios en Python +Abstract: Este artículo explica cómo trabajar con archivos adjuntos PDF en Aspose.PDF for Python via .NET. Aprenda cómo agregar archivos incrustados a documentos PDF, eliminar adjuntos programáticamente y crear o gestionar portafolios PDF que agrupan varios tipos de archivo en un único contenedor PDF. --- - +En esta sección, explicaremos cómo trabajar con adjuntos en PDF usando Aspose.PDF for Python via .NET. +Un adjunto es un archivo adicional que se adjunta a un documento principal; puede ser de varios tipos de archivo, como pdf, word, imagen o otros archivos. +Aprenderá cómo agregar adjuntos a pdf, obtener la información de un adjunto y guardarlo en un archivo, eliminar el adjunto de un PDF programáticamente con Python. -En esta sección, explicaremos cómo trabajar con archivos adjuntos en PDF utilizando Aspose.PDF para Python a través de .NET. Un archivo adjunto es un archivo adicional que se adjunta a un documento principal, puede ser una variedad de tipos de archivo, como pdf, word, imagen u otros archivos. Aprenderás a agregar archivos adjuntos a pdf, obtener la información de un archivo adjunto y guardarlo en un archivo, eliminar el archivo adjunto de un PDF programáticamente con Python. +Utilice estos artículos cuando necesite incrustar archivos de apoyo dentro de un PDF, eliminar archivos incrustados de un documento existente o agrupar materiales relacionados como una cartera PDF. -- [Añadir archivo adjunto a un documento PDF](/pdf/es/python-net/add-attachment-to-pdf-document/) -- [Eliminar archivo adjunto de un PDF existente](/pdf/es/python-net/removing-attachment-from-an-existing-pdf/) -- [Portafolio](/pdf/es/python-net/portfolio/) \ No newline at end of file +## Flujos de trabajo de adjuntos cubiertos en esta sección + +- [Agregar adjunto a un documento PDF](/pdf/es/python-net/add-attachment-to-pdf-document/) +- [Eliminar adjunto de un PDF existente](/pdf/es/python-net/removing-attachment-from-an-existing-pdf/) +- [Portafolio](/pdf/es/python-net/portfolio/) +- [Extraer archivos adjuntos](/pdf/es/python-net/extract-attachment/) diff --git a/es/python-net/advanced-operations/attachments/add-attachment-to-pdf-document/_index.md b/es/python-net/advanced-operations/attachments/add-attachment-to-pdf-document/_index.md index 39956606a..46ddfad79 100644 --- a/es/python-net/advanced-operations/attachments/add-attachment-to-pdf-document/_index.md +++ b/es/python-net/advanced-operations/attachments/add-attachment-to-pdf-document/_index.md @@ -1,105 +1,45 @@ --- -title: Añadiendo un archivo adjunto a un documento PDF utilizando Python -linktitle: Añadiendo un archivo adjunto a un documento PDF +title: Agregar archivos adjuntos a PDF en Python +linktitle: Agregar un adjunto a un documento PDF type: docs weight: 10 url: /es/python-net/add-attachment-to-pdf-document/ -description: Esta página describe cómo agregar un archivo adjunto a un archivo PDF con Aspose.PDF para Python a través de la biblioteca .NET. -lastmod: "2023-02-17" +description: Aprenda cómo agregar archivos adjuntos a documentos PDF en Python usando Aspose.PDF for Python via .NET. +lastmod: "2026-04-15" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo agregar archivos adjuntos a PDF con Python +Abstract: Este artículo brinda una guía paso a paso sobre cómo agregar adjuntos a un archivo PDF usando Python y la biblioteca Aspose.PDF. Detalla el proceso de configurar un nuevo proyecto Python, importar el paquete necesario de Aspose.PDF y crear un objeto `Document`. El artículo explica cómo crear un objeto `FileSpecification` con el archivo y la descripción deseados, y cómo agregar este objeto a la `EmbeddedFileCollection` del documento PDF mediante el método `add`. La `EmbeddedFileCollection` contiene todos los adjuntos dentro del PDF. Se incluye un fragmento de código para demostrar el proceso de abrir un documento, configurar un archivo para adjuntar, añadirlo a la colección de adjuntos del documento y guardar el PDF actualizado. --- - +Los adjuntos pueden contener una amplia variedad de información y pueden ser de diferentes tipos de archivo. Este artículo explica cómo agregar un adjunto a un archivo PDF. -Attachments pueden contener una amplia variedad de información y pueden ser de diversos tipos de archivos. Este artículo explica cómo agregar un adjunto a un archivo PDF. +Utilice archivos adjuntos PDF incrustados cuando necesite empaquetar archivos fuente de soporte, hojas de cálculo, imágenes o documentos relacionados junto con el PDF principal. -1. Crea un nuevo proyecto de Python. -1. Importa el paquete Aspose.PDF -1. Crea un objeto [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). -1. Crea un objeto [FileSpecification](https://reference.aspose.com/pdf/python-net/aspose.pdf/filespecification/) con el archivo que estás agregando y la descripción del archivo. -1. Agrega el objeto [FileSpecification](https://reference.aspose.com/pdf/python-net/aspose.pdf/filespecification/) a la colección [EmbeddedFileCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/) del objeto [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/), con el método [add](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/#methods) de la colección. +1. Cree un nuevo proyecto Python. +1. Importe el paquete Aspose.PDF +1. Cree un [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) objeto. +1. Cree un [FileSpecification](https://reference.aspose.com/pdf/python-net/aspose.pdf/filespecification/) objeto con el archivo que estás añadiendo y la descripción del archivo. +1. Agregar el [FileSpecification](https://reference.aspose.com/pdf/python-net/aspose.pdf/filespecification/) objeto al [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) del objeto [EmbeddedFileCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/) colección, con la de la colección [agregar](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/#methods) método. -La colección [EmbeddedFileCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/) contiene todos los adjuntos en el archivo PDF. - El siguiente fragmento de código te muestra cómo agregar un adjunto en un documento PDF. +El [EmbeddedFileCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/) La colección contiene todos los archivos adjuntos en el archivo PDF. El siguiente fragmento de código muestra cómo agregar un archivo adjunto en un documento PDF. ```python +from os import path +import aspose.pdf as ap - import aspose.pdf as ap +def add_attachments(infile, attachment_path, outfile): + with ap.Document(infile) as document: + file_spec = ap.FileSpecification(attachment_path, "Sample text file") + document.embedded_files.add(path.basename(attachment_path), file_spec) + document.save(outfile) +``` - # Abrir documento - document = ap.Document(input_pdf) +## Temas relacionados con archivos adjuntos - # Configurar nuevo archivo para ser agregado como adjunto - fileSpecification = ap.FileSpecification(attachment_file, "Archivo de texto de ejemplo") +- [Trabajar con archivos adjuntos PDF en Python](/pdf/es/python-net/attachments/) +- [Eliminar archivos adjuntos de PDF en Python](/pdf/es/python-net/removing-attachment-from-an-existing-pdf/) +- [Crear y gestionar portafolios PDF en Python](/pdf/es/python-net/portfolio/) - # Añadir adjunto a la colección de adjuntos del documento - document.embedded_files.append(fileSpecification) - - # Guardar nuevo resultado - document.save(output_pdf) \ No newline at end of file diff --git a/es/python-net/advanced-operations/attachments/extract-attachment/_index.md b/es/python-net/advanced-operations/attachments/extract-attachment/_index.md new file mode 100644 index 000000000..2fd46d516 --- /dev/null +++ b/es/python-net/advanced-operations/attachments/extract-attachment/_index.md @@ -0,0 +1,126 @@ +--- +title: Extraer archivos adjuntos de PDF +linktitle: Extraer archivos adjuntos +type: docs +weight: 50 +url: /es/python-net/extract-attachment/ +description: Aprenda cómo trabajar con archivos adjuntos PDF usando Python y Aspose.PDF. +lastmod: "2026-04-26" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: "Guía completa para administrar archivos adjuntos PDF en Python: agregar, extraer y procesar archivos incrustados" +Abstract: Los archivos adjuntos PDF se utilizan ampliamente para almacenar documentos de soporte, informes, imágenes y otros recursos directamente dentro de un archivo PDF. Este artículo ofrece una visión completa del manejo de archivos adjuntos PDF con Python usando Aspose.PDF. Explica cómo incrustar archivos externos en PDFs existentes, extraer adjuntos específicos o todos los adjuntos, inspeccionar metadatos como el tamaño del archivo y las marcas de tiempo, y recuperar archivos almacenados como anotaciones FileAttachment. Cada ejemplo muestra técnicas prácticas para automatizar flujos de trabajo de adjuntos, mejorar la portabilidad de documentos y simplificar la gestión de archivos. Ya sea construyendo sistemas de documentos empresariales o scripts de automatización personalizados, los desarrolladores pueden usar estos métodos para gestionar eficientemente los archivos incrustados dentro de documentos PDF. +--- + +## Extraer adjunto específico de PDF + +Extraiga un archivo incrustado único de un documento PDF usando Python y Aspose.PDF. Busca un adjunto por nombre, recupera su contenido y lo guarda como un archivo separado. Esto es útil para acceder a documentos incrustados como informes, registros o archivos de apoyo almacenados dentro del PDF. + +1. Definir función 'extract_single_attachment()'. +1. Abrir documento PDF. +1. Buscar adjunto. +1. Extraer contenido del adjunto. + +```python +import aspose.pdf as ap + +def extract_single_attachment(infile, attachment_name, outfile): + with ap.Document(infile) as document: + print(f"Extracting attachment: {attachment_name}") + + attachment_found = False + for file_spec in document.embedded_files: + if file_spec.name == attachment_name: + with open(outfile, "wb") as f: + f.write(file_spec.contents.read()) + print("Attachment extracted successfully") + attachment_found = True + break + + if not attachment_found: + raise ValueError(f"Attachment '{attachment_name}' not found in PDF") +``` + +## Mostrar metadatos del archivo adjunto + +Esta función auxiliar imprime la información de metadatos de un objeto de especificación de archivo. Normalmente se usa al trabajar con archivos adjuntos incrustados en PDFs usando Aspose.PDF, lo que permite a los desarrolladores inspeccionar detalles como suma de verificación, fecha de creación, fecha de modificación y tamaño del archivo. + +```python +def _print_file_params(params): + """Helper to print file specification parameters.""" + if params: + print(f"CheckSum: {params.check_sum}") + print(f"Creation Date: {params.creation_date}") + print(f"Modification Date: {params.mod_date}") + print(f"Size: {params.size}") +``` + +## Extraer e inspeccionar todos los archivos adjuntos PDF + +Este fragmento de código muestra cómo extraer todos los archivos incrustados de un documento PDF usando Python y Aspose.PDF. No solo guarda cada adjunto en una carpeta especificada, sino que también imprime metadatos detallados como el nombre del archivo, la descripción, el tipo MIME, la suma de verificación y las marcas de tiempo. Esto es útil para auditorías, exportaciones o el procesamiento de contenido incrustado en archivos PDF. + +```python +from os import path +import aspose.pdf as ap + +def extract_attachments(infile, output_dir): + with ap.Document(infile) as document: + print(f"Total files: {len(document.embedded_files)}") + + for file_spec in document.embedded_files: + print(f"Name: {file_spec.name}") + print(f"Description: {file_spec.description}") + print(f"Mime Type: {file_spec.mime_type}") + _print_file_params(file_spec.params) + + output_path = path.join(output_dir, file_spec.name) + with open(output_path, "wb") as f: + f.write(file_spec.contents.read()) +``` + +## Extraer archivos de anotaciones de adjuntos PDF + +Extraer un archivo incrustado de una anotación FileAttachment en un PDF usando Python y Aspose.PDF. Busca en la primera página la primera anotación de adjunto, recupera el archivo incrustado y lo guarda en un directorio de salida seleccionado. Esto es útil cuando los PDF contienen íconos de adjuntos de archivo clicables en lugar de colecciones estándar de archivos incrustados. + +```python +from os import path +import aspose.pdf as ap +from aspose.pycore import cast + +def extract_file_attachment_annotation(infile, output_dir): + # Open PDF document + with ap.Document(infile) as document: + + # Get first page + page = document.pages[1] + + # Find first FileAttachment annotation + file_attachment = next( + ( + annot + for annot in page.annotations + if annot.annotation_type == ap.annotations.AnnotationType.FILE_ATTACHMENT + ), + None, + ) + + if file_attachment is None: + print("No FileAttachment annotation found on the first page.") + return + + # Cast to FileAttachmentAnnotation + faa = cast(ap.annotations.FileAttachmentAnnotation, file_attachment) + + # Access embedded file + file_spec = faa.file + print(f"File name: {file_spec.name}") + + # Save embedded file to disk + output_path = path.join(output_dir, f"extracted-{file_spec.name}") + with open(output_path, "wb") as f: + f.write(file_spec.contents.read()) + + print(f"Extracted to: {output_path}") +``` \ No newline at end of file diff --git a/es/python-net/advanced-operations/attachments/portfolio/_index.md b/es/python-net/advanced-operations/attachments/portfolio/_index.md index c44260c6e..ec4e1e039 100644 --- a/es/python-net/advanced-operations/attachments/portfolio/_index.md +++ b/es/python-net/advanced-operations/attachments/portfolio/_index.md @@ -1,203 +1,85 @@ --- -title: Trabajando con Portafolio en PDF usando Python +title: Crear portafolios PDF en Python linktitle: Portafolio type: docs weight: 20 url: /es/python-net/portfolio/ -description: Cómo Crear un Portafolio en PDF con Python. Debe usar un archivo de Microsoft Excel, un documento de Word y un archivo de imagen para crear un Portafolio en PDF. -lastmod: "2023-02-17" +description: Aprenda cómo crear y administrar portafolios PDF en Python con Aspose.PDF for Python via .NET. +lastmod: "2026-04-15" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cree y edite portafolios PDF con archivos incrustados en Python +Abstract: Este artículo explica cómo crear y administrar portafolios PDF usando Aspose.PDF for Python via .NET. Aprenda cómo agrupar varios tipos de archivos en un único portafolio PDF, agregar archivos a una colección de documentos y eliminar elementos del portafolio de forma programática con Python. --- - - - -Crear un portafolio PDF permite consolidar y archivar diferentes tipos de archivos en un solo documento coherente. Dicho documento podría incluir archivos de texto, imágenes, hojas de cálculo, presentaciones y otros materiales, y garantizar que todo el material relevante esté almacenado y organizado en un solo lugar. - -El portafolio PDF ayudará a mostrar tu presentación de una manera de alta calidad, donde sea que lo uses. En general, crear un portafolio PDF es una tarea muy actual y moderna. - -## Cómo Crear un Portafolio PDF - -Aspose.PDF para Python a través de .NET permite crear documentos de Portafolio PDF usando la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). Agrega un archivo en un objeto document.collection después de obtenerlo con la clase [FileSpecification](https://reference.aspose.com/pdf/python-net/aspose.pdf/filespecification/). Cuando los archivos han sido agregados, usa el método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) de la clase Document para guardar el documento del portafolio. - -El siguiente ejemplo utiliza un archivo de Microsoft Excel, un documento de Word y un archivo de imagen para crear un Portafolio PDF. - -El siguiente código resulta en el siguiente portafolio. - -### Un Portafolio PDF creado con Aspose.PDF para Python - -![Un Portafolio PDF creado con Aspose.PDF para Python](working-with-pdf-portfolio_1.jpg) -```python +Crear un portafolio PDF permite consolidar y archivar diferentes tipos de archivos en un único documento coherente. Ese documento puede incluir archivos de texto, imágenes, hojas de cálculo, presentaciones y otros materiales, y garantiza que todo el material relevante se almacene y organice en un solo lugar. + +El portafolio PDF ayudará a mostrar su presentación de manera de alta calidad, dondequiera que lo utilice. En general, crear un portafolio PDF es una tarea muy actual y moderna. + +Utilice un portafolio PDF cuando desee distribuir una colección de archivos relacionados juntos, manteniendo cada archivo en su formato original dentro de un contenedor PDF. + +## Cómo crear un portafolio PDF + +Aspose.PDF for Python via .NET permite crear documentos de portafolio PDF usando el [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase. Añada un archivo en un document.collection objeto después de obtenerlo con la [FileSpecification](https://reference.aspose.com/pdf/python-net/aspose.pdf/filespecification/) clase. Cuando los archivos se hayan añadido, use la Document clase' [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método para guardar el documento del portafolio. + +El siguiente ejemplo utiliza un archivo Microsoft Excel, un documento Word y un archivo de imagen para crear un PDF Portfolio. + +El código a continuación da como resultado el siguiente portafolio. - import aspose.pdf as ap +### Un PDF Portfolio creado con Aspose.PDF for Python - # Instanciar objeto Document +![Un PDF Portfolio creado con Aspose.PDF for Python](working-with-pdf-portfolio_1.jpg) + +```python +import aspose.pdf as ap + +def create_pdf_portfolio(input_files, outfile): + # Instantiate Document Object document = ap.Document() - # Instanciar objeto Collection del documento + # Instantiate document Collection object document.collection = ap.Collection() - # Obtener archivos para añadir al portafolio - excel = ap.FileSpecification(input_excel) - word = ap.FileSpecification(input_doc) - image = ap.FileSpecification(input_jpg) + # Get Files to add to Portfolio + excel = ap.FileSpecification(input_files[0]) + word = ap.FileSpecification(input_files[1]) + image = ap.FileSpecification(input_files[2]) - # Proporcionar descripción de los archivos - excel.description = "Archivo Excel" - word.description = "Archivo Word" - image.description = "Archivo de Imagen" + # Provide description of the files + excel.description = "Excel File" + word.description = "Word File" + image.description = "Image File" - # Añadir archivos a la colección del documento + # Add files to document collection document.collection.append(excel) document.collection.append(word) document.collection.append(image) - # Guardar documento del portafolio - document.save(output_pdf) + # Save Portfolio document + document.save(outfile) ``` ## Eliminar archivos del Portafolio PDF -Para eliminar/quitar archivos del portafolio PDF, intente usar las siguientes líneas de código. +Para eliminar/quitar archivos del portafolio PDF, intenta usar las siguientes líneas de código. ```python +import aspose.pdf as ap - import aspose.pdf as ap - - # Abrir documento - document = ap.Document(input_pdf) +def remove_files_from_pdf_portfolio(infile, outfile): + # Open document + document = ap.Document(infile) document.collection.delete() - # Guardar archivo actualizado - document.save(output_pdf) + # Save updated file + document.save(outfile) ``` - \ No newline at end of file +## Temas relacionados con archivos adjuntos + +- [Trabajar con archivos adjuntos PDF en Python](/pdf/es/python-net/attachments/) +- [Agregar archivos adjuntos a PDF en Python](/pdf/es/python-net/add-attachment-to-pdf-document/) +- [Eliminar archivos adjuntos de PDF en Python](/pdf/es/python-net/removing-attachment-from-an-existing-pdf/) + diff --git a/es/python-net/advanced-operations/attachments/removing-attachment-from-an-existing-pdf/_index.md b/es/python-net/advanced-operations/attachments/removing-attachment-from-an-existing-pdf/_index.md index 2ea4d18ea..572fcbf71 100644 --- a/es/python-net/advanced-operations/attachments/removing-attachment-from-an-existing-pdf/_index.md +++ b/es/python-net/advanced-operations/attachments/removing-attachment-from-an-existing-pdf/_index.md @@ -1,166 +1,67 @@ --- -title: Eliminando adjunto de PDF usando Python -linktitle: Eliminando adjunto de un PDF existente +title: Eliminar archivos adjuntos de PDF en Python +linktitle: Eliminar adjunto de un PDF existente type: docs weight: 30 url: /es/python-net/removing-attachment-from-an-existing-pdf/ -description: Aspose.PDF puede eliminar adjuntos de tus documentos PDF. Usa la API de PDF de Python para eliminar adjuntos en archivos PDF usando Aspose.PDF para la biblioteca de Python a través de .NET. -lastmod: "2023-02-17" +description: Aspose.PDF puede eliminar adjuntos de sus documentos PDF. Utilice Python PDF API para eliminar adjuntos en archivos PDF usando Aspose.PDF for Python via .NET library. +lastmod: "2026-04-26" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo eliminar adjuntos de PDF con Python +Abstract: Este artículo discute cómo eliminar adjuntos de archivos PDF usando Aspose.PDF for Python. Los adjuntos en un documento PDF se almacenan dentro de la colección `EmbeddedFiles` del objeto `Document`. Para eliminar todos los adjuntos de un PDF, puede invocar el método `delete()` en la colección `EmbeddedFiles` y luego guardar el documento actualizado usando el método `save()` del objeto `Document`. Se proporciona un fragmento de código para demostrar este proceso, mostrando los pasos de abrir un documento, eliminar sus adjuntos y guardar el archivo modificado. --- - - - -Aspose.PDF para Python puede eliminar archivos adjuntos de archivos PDF. Los archivos adjuntos de un documento PDF se mantienen en la colección [EmbeddedFiles](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/) del objeto Document. - -Para eliminar todos los archivos adjuntos asociados con un archivo PDF: - -1. Llame al método [delete()](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/#methods) de la colección [EmbeddedFiles](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/). -2. Guarde el archivo actualizado usando el método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) del objeto [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). + +Aspose.PDF for Python puede eliminar adjuntos de archivos PDF. Los adjuntos de un documento PDF se encuentran en el objeto Document. [Archivos incrustados](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/) colección. + +Este flujo de trabajo es útil cuando necesita limpiar archivos incrustados obsoletos, reducir el tamaño del paquete o preparar un PDF para redistribución sin los materiales fuente adjuntos. + +Para eliminar todos los archivos adjuntos asociados a un archivo PDF: + +1. Llame al [Archivos incrustados](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/) colección\u0027s [delete()](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/#methods) método. +1. Guarde el archivo actualizado usando el [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) del objeto [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método. El siguiente fragmento de código muestra cómo eliminar archivos adjuntos de un documento PDF. ```python - import aspose.pdf as ap +import aspose.pdf as ap + +def remove_attachment(infile, outfile): + # Open PDF document + with ap.Document(infile) as document: + document.embedded_files.delete() + document.save(outfile) +``` + +## Eliminar un archivo adjunto específico por nombre - # Abrir documento - document = ap.Document(input_pdf) +Si necesitas eliminar solo un archivo adjunto y mantener los demás, usa el [delete_by_key()](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/delete_by_key/) método y pasa el nombre del adjunto. - # Eliminar todos los archivos adjuntos - document.embedded_files.delete() +Para eliminar un adjunto específico: - # Guardar archivo actualizado - document.save(output_pdf) +1. Abre el archivo PDF fuente. +1. Llamada `document.embedded_files.delete_by_key(attachment_name)`. +1. Guarda el archivo PDF actualizado. + +El siguiente fragmento de código elimina un adjunto por su nombre. + +```python + +import aspose.pdf as ap + +def remove_attachment(infile, attachment_name, outfile): + # Open PDF document + with ap.Document(infile) as document: + document.embedded_files.delete_by_key(attachment_name) + document.save(outfile) ``` +## Temas relacionados con archivos adjuntos + +- [Trabajar con archivos adjuntos PDF en Python](/pdf/es/python-net/attachments/) +- [Agregar archivos adjuntos a PDF en Python](/pdf/es/python-net/add-attachment-to-pdf-document/) +- [Crear y gestionar portafolios PDF en Python](/pdf/es/python-net/portfolio/) - \ No newline at end of file diff --git a/es/python-net/advanced-operations/compare-pdf-documents/_index.md b/es/python-net/advanced-operations/compare-pdf-documents/_index.md new file mode 100644 index 000000000..4aeeb120d --- /dev/null +++ b/es/python-net/advanced-operations/compare-pdf-documents/_index.md @@ -0,0 +1,189 @@ +--- +title: Comparar documentos PDF en Python +linktitle: Comparar PDF +type: docs +weight: 130 +url: /es/python-net/compare-pdf-documents/ +description: Aprenda cómo comparar documentos PDF en Python usando salida de diferencias lado a lado y gráfica con Aspose.PDF for Python via .NET. +lastmod: "2026-04-15" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Compare páginas PDF y documentos completos con salida visual de diferencias en Python +Abstract: Este artículo explica cómo comparar documentos PDF en Aspose.PDF for Python via .NET. Aprende cómo comparar páginas específicas o archivos PDF completos con salida lado a lado, y cómo usar métodos de comparación gráfica para generar informes de diferencias basados en imágenes o basados en PDF. +--- + +## Formas de comparar documentos PDF + +Al trabajar con documentos PDF, a veces necesitas comparar el contenido de dos documentos para identificar diferencias. La biblioteca Aspose.PDF for Python via .NET ofrece un conjunto de herramientas potente para este propósito. En este artículo, exploraremos cómo comparar documentos PDF usando un par de fragmentos de código sencillos. + +Utilice la comparación lado a lado cuando desee una salida PDF que resalte los cambios de texto y diseño entre las páginas. Utilice la comparación gráfica cuando necesite detección de diferencias basada en imágenes para flujos de revisión visual, verificaciones de regresión o informes de comparación de PDF. + +La funcionalidad de comparación en Aspose.PDF le permite comparar dos documentos PDF página por página. Puede elegir comparar páginas específicas o documentos completos. El documento de comparación resultante resalta las diferencias, facilitando la identificación de cambios entre los dos archivos. + +Aquí hay una lista de posibles formas de comparar documentos PDF utilizando la biblioteca Aspose.PDF for Python via .NET: + +1. **Comparando Páginas Específicas** - Compare las primeras páginas de dos documentos PDF. +1. **Comparar documentos completos** - Compara el contenido completo de dos documentos PDF. +1. **Comparar documentos PDF gráficamente**: + +- Compara PDF con el método 'comparer.get_difference' - imágenes individuales donde se marcan los cambios. +- Compara PDF con el método 'comparer.compare_documents_to_pdf' - documento PDF con imágenes donde se marcan los cambios. + +## Comparación de páginas específicas + +El primer fragmento de código muestra cómo comparar las primeras páginas de dos documentos PDF usando la clase SideBySidePdfComparer. + +1. Inicialización del documento. +1. Cree una función para realizar la comparación. +1. Proceso de comparación: + +- document1.pages[1] y document2.pages[1]: - especifican la primera página de cada documento para la comparación. Tenga en cuenta que la numeración de páginas comienza en 1 en Aspose.PDF. +- SideBySideComparisonOptions - esta clase permite personalizar el comportamiento de la comparación. +- additional_change_marks = True - habilita la visualización de marcadores de cambio adicionales, resaltando diferencias que podrían estar presentes en otras páginas, incluso si no están en la página actual que se compara. +- comparison_mode = ComparisonMode.IgnoreSpaces - establece el modo de comparación para ignorar los espacios en el texto, enfocándose solo en los cambios dentro de las palabras. + +1. El resultado de la comparación se guarda como un nuevo archivo PDF llamado ComparingSpecificPages_out.pdf en el data_dir especificado. + +```python +import aspose.pdf as ap +import sys +from os import path + +def comparing_specific_pages(infile1, infile2, outfile): + # Open PDF documents + document_1 = ap.Document(infile1) + document_2 = ap.Document(infile2) + + # Compare + options = ap.comparison.SideBySideComparisonOptions() + options.additional_change_marks = True + options.comparison_mode = ap.comparison.ComparisonMode.IGNORE_SPACES + + # Perform comparison and save the result + ap.comparison.SideBySidePdfComparer.compare( + document_1.pages[1], document_2.pages[1], outfile, options + ) +``` + +## Comparando documentos completos + +El segundo fragmento de código amplía el alcance para comparar el contenido completo de dos documentos PDF. + +```python +import aspose.pdf as ap +import sys +from os import path + +def comparing_entire_documents(infile1, infile2, outfile): + # Open PDF documents + document_1 = ap.Document(infile1) + document_2 = ap.Document(infile2) + + # Compare + options = ap.comparison.SideBySideComparisonOptions() + options.additional_change_marks = True + options.comparison_mode = ap.comparison.ComparisonMode.IGNORE_SPACES + + # Perform comparison and save the result + ap.comparison.SideBySidePdfComparer.compare( + document_1, document_2, outfile, options + ) +``` + +El código proporcionado demuestra la comparación de dos documentos PDF usando Aspose.PDF for Python via .NET. Utiliza la clase SideBySidePdfComparer para realizar una comparación página por página, generando un nuevo PDF que muestra las diferencias lado a lado. La comparación se configura con SideBySideComparisonOptions, donde additional_change_marks se establece en True para resaltar cambios no solo en la página actual sino también en otras páginas, y comparison_mode se establece en IgnoreSpaces para centrarse en diferencias de contenido significativas al ignorar variaciones de espacios en blanco. + +## Comparar usando GraphicalPdfComparer + +Al colaborar en documentos, especialmente en entornos profesionales, a menudo terminas con múltiples versiones del mismo archivo. +El código proporcionado demuestra cómo comparar visualmente páginas específicas de dos documentos PDF usando Aspose.PDF for Python via .NET. Al utilizar el `GraphicalPdfComparer` clase, resalta las diferencias entre las primeras páginas de los dos PDFs y genera imágenes correspondientes para representar esas diferencias. + +Puedes establecer las siguientes propiedades de la clase: + +- Resolution - resolución en unidades DPI para las imágenes de salida, así como para las imágenes generadas durante la comparación. +- Color - el color de las marcas de cambio. +- Umbral - umbral de cambio en porcentaje. El valor predeterminado es cero. Establecer un valor distinto de cero le permite ignorar los cambios gráficos que son insignificantes para usted. + +Con Aspose.PDF for Python via .NET, es posible comparar documentos y páginas y exportar el resultado de la comparación a un documento PDF o archivo de imagen. + +El `GraphicalPdfComparer` la clase tiene un método que le permite obtener diferencias de imágenes de página en un formato adecuado para un procesamiento posterior: `get_difference(document1.pages[1], document2.pages[1])`. + +Este método devuelve un objeto de `images_difference` tipo, que contiene una imagen de la primera página comparada y una matriz de diferencias. + +El `images_difference` objeto le permite generar una imagen diferente y obtener una imagen de la segunda página comparada aplicando una matriz de diferencias a la imagen original. Para hacer esto, use el `difference_to_image` y `get_destination_image` métodos. + +### Comparar PDF con el método Get Difference + +El código proporcionado define un método `get_difference` que compara dos documentos PDF y genera representaciones visuales de las diferencias entre ellos. + +Este método compara las primeras páginas de dos archivos PDF y genera dos imágenes PNG: + +- Una imagen resalta las diferencias entre las páginas en rojo. +- La otra imagen es una representación visual de la página PDF de destino (segunda). + +Este proceso puede ser útil para comparar visualmente los cambios o diferencias entre dos versiones de un documento. + +```python +import aspose.pdf as ap +import sys +from os import path + +def compare_pdf_with_get_difference_method(infile1, infile2, outfile1, outfile2): + # Open PDF documents + document1 = ap.Document(infile1) + document2 = ap.Document(infile2) + + # Create comparer + comparer = ap.comparison.GraphicalPdfComparer() + + # Compare specific pages + images_difference = comparer.get_difference(document1.pages[1], document2.pages[1]) + + # Get image showing differences in red over a white background + diff_img = images_difference.difference_to_image(ap.Color.red, ap.Color.white) + diff_img.save(outfile1) + + # Get the second image representing the destination page + dest_img = images_difference.get_destination_image() + dest_img.save(outfile2) +``` + +### Comparar PDF con el método CompareDocumentsToPdf + +El fragmento de código proporcionado utiliza el `compare_documents_to_pdf` método, que compara dos documentos y genera un informe PDF de los resultados de la comparación. + +```python +import aspose.pdf as ap +import sys +from os import path + +def compare_pdf_with_compare_documents_to_pdf_method(infile1, infile2, outfile): + # Open PDF documents + document_1 = ap.Document(infile1) + document_2 = ap.Document(infile2) + + # Create comparer and set options + pdf_comparer = ap.comparison.GraphicalPdfComparer() + pdf_comparer.threshold = 3.0 + pdf_comparer.color = ap.Color.blue + pdf_comparer.resolution = ap.devices.Resolution(300) + + # Compare and output to a PDF file + pdf_comparer.compare_documents_to_pdf(document_1, document_2, outfile) +``` + +Este ejemplo demuestra cómo realizar una comparación gráfica de dos documentos PDF completos usando Aspose.PDF for Python via .NET. Al aprovechar el `GraphicalPdfComparer` clase, genera un nuevo archivo PDF que resalta visualmente las diferencias entre los documentos. + +- La propiedad de umbral está establecida en 3.0, lo que significa que las diferencias menores por debajo de este porcentaje se ignoran durante la comparación, centrándose en cambios más significativos. +- Las diferencias se marcan en azul estableciendo la propiedad color a ap.Color.blue, lo que permite una clara distinción visual. +- La comparación se lleva a cabo a una resolución de 300 DPI estableciendo la propiedad de resolución, lo que asegura una salida detallada y clara. + +El `compare_documents_to_pdf` El método compara todas las páginas de ambos documentos y genera el resultado en un nuevo archivo PDF, compareDocumentsToPdf_out.pdf, con las diferencias resaltadas visualmente. + +## Temas relacionados + +- [Operaciones avanzadas de PDF en Python](/pdf/es/python-net/advanced-operations/) +- [Trabajar con documentos PDF en Python](/pdf/es/python-net/working-with-documents/) +- [Trabajar con páginas PDF en Python](/pdf/es/python-net/working-with-pages/) +- [Trabajar con texto PDF en Python](/pdf/es/python-net/working-with-text/) diff --git a/es/python-net/advanced-operations/navigation-and-interaction/_index.md b/es/python-net/advanced-operations/navigation-and-interaction/_index.md index b61df1702..9bf5a74d0 100644 --- a/es/python-net/advanced-operations/navigation-and-interaction/_index.md +++ b/es/python-net/advanced-operations/navigation-and-interaction/_index.md @@ -1,144 +1,23 @@ --- -title: Navegación e Interacción en PDF usando Python +title: Navegación e Interacción de PDF en Python linktitle: Navegación e interacción type: docs weight: 90 url: /es/python-net/navigation-and-interaction/ -description: Esta sección describe las características del trabajo con enlaces, acciones y marcadores con la Biblioteca Python. -lastmod: "2023-02-17" +description: Aprenda cómo trabajar con enlaces de PDF, acciones y marcadores en Python para la navegación y el comportamiento interactivo del documento. +lastmod: "2026-04-15" sitemap: - changefreq: "weekly" - priority: 0.7 + changefreq: "monthly" + priority: 0.5 +TechArticle: true +AlternativeHeadline: Trabaje con enlaces, acciones y marcadores en archivos PDF utilizando Python +Abstract: Esta sección explica cómo gestionar las características de navegación e interacción en documentos PDF con Python. Aprenda cómo crear y actualizar enlaces, agregar acciones interactivas y trabajar con marcadores para mejorar la navegación de PDF, la usabilidad y los flujos de trabajo del documento. --- - +Utilice esta sección cuando necesite crear una navegación interactiva de PDF en Python, ya sea creando marcadores, actualizando destinos de enlaces o adjuntando acciones a eventos del documento, páginas y elementos de formulario. -- [Marcadores](/pdf/es/python-net/bookmarks/)- las publicaciones grandes generalmente incluyen un marco de marcadores que se pueden ver y seleccionar fácilmente en el Panel de Marcadores, lo que le permite hacer clic en un marcador para saltar a la página o capítulo que representa. El Panel de Marcadores es un elemento consciente del contenido y es visible en la barra lateral solo si el documento PDF abierto contiene una estructura de marcadores. +## Temas en esta sección - \ No newline at end of file +- [Acciones](/pdf/es/python-net/actions/) - en este artículo, aprenderá cómo trabajar con diferentes tipos de acciones. +- [Marcadores](/pdf/es/python-net/bookmarks/)- las publicaciones extensas usualmente incluyen un marco de marcadores que pueden verse y seleccionarse fácilmente en el Panel de marcadores, lo que le permite hacer clic en un marcador para saltar a la página o capítulo que representa. El Panel de marcadores es un elemento sensible al contenido, y es visible en la barra lateral solo si el documento PDF abierto contiene una estructura de marcadores. +- [Enlaces](/pdf/es/python-net/links/)- trabajar con enlaces en los documentos PDF usando la biblioteca Python. diff --git a/es/python-net/advanced-operations/navigation-and-interaction/actions/_index.md b/es/python-net/advanced-operations/navigation-and-interaction/actions/_index.md new file mode 100644 index 000000000..357a6e328 --- /dev/null +++ b/es/python-net/advanced-operations/navigation-and-interaction/actions/_index.md @@ -0,0 +1,360 @@ +--- +title: Trabajar con Acciones PDF en Python +linktitle: Acciones +type: docs +weight: 20 +url: /es/python-net/actions/ +description: Aprende cómo agregar, actualizar y eliminar acciones de documento, página y formulario en archivos PDF utilizando Python. +lastmod: "2026-04-15" +sitemap: + changefreq: "monthly" + priority: 0.5 +TechArticle: true +AlternativeHeadline: Agrega acciones de documento, página y formulario a archivos PDF en Python +Abstract: Este artículo explora cómo trabajar con acciones en documentos PDF utilizando la biblioteca Aspose.PDF, cubriendo interacciones a nivel de documento, de página y de formulario. Las acciones PDF son disparadores predefinidos o personalizables que responden a eventos del usuario, habilitando la navegación, la ejecución de JavaScript, la reproducción multimedia, el envío de formularios y más. La guía muestra cómo agregar, personalizar y eliminar acciones, como abrir URL en eventos del documento, crear navegación o efectos de zoom específicos de la página, agregar botones interactivos para imprimir y navegar, ocultar elementos de formulario de forma dinámica y enviar datos de formulario a puntos finales web. A través de ejemplos de código Python detallados, los lectores aprenden a mejorar la interactividad de los PDF, optimizar flujos de trabajo e integrar los PDF con sistemas externos mientras comprenden consideraciones de compatibilidad del visor. +--- + +Las acciones en un PDF son tareas predefinidas que se activan mediante la interacción del usuario o eventos del documento. Se pueden usar para: + +- Navega a una página específica o archivo externo +- Abrir un enlace web +- Reproducir contenido multimedia +- Ejecutar JavaScript +- Enviar o restablecer un formulario +- Mostrar/ocultar campos +- Cambiar nivel de zoom o modo de vista + +Casi todas las acciones utilizan parámetros incorporados, pero hay algunas que pueden personalizarse. Por ejemplo - Acciones de JavaScript. + +## Agregar acciones de lanzamiento de PDF + +Agregue acciones de lanzamiento basadas en JavaScript a un documento PDF usando Python y Aspose.PDF. Asigna acciones a eventos clave del documento, como la apertura, el guardado y la impresión, permitiendo que las URL se lancen automáticamente cuando esos eventos ocurran en los visores PDF compatibles. + +```python +import aspose.pdf as ap +from aspose.pycore import is_assignable +from aspose.pdf import Rectangle +from aspose.pdf.forms import ButtonField, CheckboxField +from aspose.pdf.annotations import ( + NamedAction, + PredefinedAction, + HideAction, + SubmitFormAction, +) +from os import path +import sys + +def add_launch_actions(infile, outfile): + """Add JavaScript launch actions for document events. + + Adds JavaScript actions that launch URLs when specific document events occur: + - On document open: launches http://localhost:3000/open + - Before saving: launches http://localhost:3000/save + - Before printing: launches http://localhost:3000/print + + Args: + infile (str): Path to the input PDF file. + outfile (str): Path to save the output PDF with document actions. + + Returns: + None + + Example: + >>> add_launch_actions("sample_data/input/add_launch_actions_in.pdf", "sample_data/output/add_launch_actions_out.pdf") + + Notes: + - Uses `ap.annotations.JavascriptAction` with `app.launchURL()`. + - URLs are opened in the default browser depending on viewer support. + """ + + document = ap.Document(infile) + + # Add JavaScript actions for document events + document.open_action = ap.annotations.JavascriptAction( + "app.launchURL('http://localhost:3000/open');" + ) + document.actions.before_saving = ap.annotations.JavascriptAction( + "app.launchURL('http://localhost:3000/save');" + ) + document.actions.before_printing = ap.annotations.JavascriptAction( + "app.launchURL('http://localhost:3000/print');" + ) + + document.save(outfile) +``` + +## Eliminando acciones del documento PDF + +Para limpiar (o eliminar) acciones, simplemente establece el controlador en `None`. + +```python +import aspose.pdf as ap +from aspose.pycore import is_assignable +from aspose.pdf import Rectangle +from aspose.pdf.forms import ButtonField, CheckboxField +from aspose.pdf.annotations import ( + NamedAction, + PredefinedAction, + HideAction, + SubmitFormAction, +) +from os import path +import sys + +def remove_page_actions(infile, outfile): + document = ap.Document(infile) + + if len(document.pages) < 3: + print("Error: The document does not have at least 3 pages.") + return + + page = document.pages[3] + page.actions.remove_actions() + + document.save(outfile) +``` + +## Agregar acciones a la página en el documento PDF + +Los activadores similares se proporcionan para páginas: `on_open`, `on_close`. + +```python +import aspose.pdf as ap +from aspose.pycore import is_assignable +from aspose.pdf import Rectangle +from aspose.pdf.forms import ButtonField, CheckboxField +from aspose.pdf.annotations import ( + NamedAction, + PredefinedAction, + HideAction, + SubmitFormAction, +) +from os import path +import sys + +def add_page_actions(infile, outfile): + document = ap.Document(infile) + + if len(document.pages) < 3: + print("Error: The document does not have at least 3 pages.") + return + + page = document.pages[3] + + # Add GoTo action on page open - navigate to top of page + action = ap.annotations.GoToAction(page) + action.destination = ap.annotations.XYZExplicitDestination( + page, 0, page.page_info.height, 1 + ) + page.actions.on_open = action + + # Add JavaScript action on page close + page.actions.on_close = ap.annotations.JavascriptAction( + "app.launchURL('http://localhost:3000/page/3');" + ) + + document.save(outfile) +``` + +## Acciones en AcroForms + +### Usando acciones de navegación + +El estándar PDF contempla un conjunto determinado de acciones nombradas. El significado de dichas acciones se determina por su nombre. +En el siguiente código utilizaremos acciones para navegaciones. + +```python +import aspose.pdf as ap +from aspose.pycore import is_assignable +from aspose.pdf import Rectangle +from aspose.pdf.forms import ButtonField, CheckboxField +from aspose.pdf.annotations import ( + NamedAction, + PredefinedAction, + HideAction, + SubmitFormAction, +) +from os import path +import sys + +def add_navigation_buttons(infile, outfile): + # Configuration for each navigation button + button_config = [ + ("First Page", 10.0, PredefinedAction.FIRST_PAGE, lambda p, t: p == 1), + ("Previous Page", 120.0, PredefinedAction.PREV_PAGE, lambda p, t: p == 1), + ("Next Page", 230.0, PredefinedAction.NEXT_PAGE, lambda p, t: p == t), + ("Last Page", 340.0, PredefinedAction.LAST_PAGE, lambda p, t: p == t), + ] + + document = ap.Document(infile) + total_pages = len(document.pages) + + # Add navigation buttons to each page + for page in document.pages: + for name, x_pos, action, is_readonly_fn in button_config: + # Create button rectangle + rect = Rectangle(x_pos, 10.0, x_pos + 100, 40.0, True) + button = ButtonField(page, rect) + button.partial_name = name + button.value = name + button.characteristics.border = ap.Color.red.to_rgb() + button.characteristics.background = ap.Color.orange.to_rgb() + # Disable button when not applicable + button.read_only = is_readonly_fn(page.number, total_pages) + button.actions.on_release_mouse_btn = NamedAction(action) + document.form.add(button) + + document.save(outfile) +``` + +Este código agrega botones de navegación a cada página de un documento PDF, facilitando a los usuarios moverse entre páginas. Comienza determinando las rutas de archivo completas para los archivos de entrada y salida usando un método auxiliar. La lista button_config define cuatro tipos de botones de navegación—First Page, Previous Page, Next Page y Last Page—junto con sus posiciones horizontales, las acciones de navegación predefinidas que desencadenan y una función lambda que determina si cada botón debe ser de solo lectura en una página dada (por ejemplo, los botones "First Page" y "Previous Page" son de solo lectura en la primera página). + +El código luego carga el PDF y recorre cada página. Para cada página, recorre las configuraciones de botones, creando un área rectangular para cada botón e instanciando un ButtonField en esa ubicación. A cada botón se le asigna un nombre, su estado de solo lectura se establece según la página actual, y su acción de clic se asigna a la acción de navegación correspondiente. El botón se agrega luego a los campos de formulario del PDF. + +Después de que todos los botones se añaden a todas las páginas, el documento modificado se guarda. Si ocurre algún error durante este proceso, se captura y se imprime. Este enfoque asegura que cada página tenga un conjunto coherente de controles de navegación, mejorando la usabilidad de los PDFs de varias páginas. Una sutileza es el uso de la lambda is_readonly_fn para desactivar los botones de navegación cuando no tendrían sentido (por ejemplo, \u0022Next Page\u0022 en la última página), lo que ayuda a prevenir la confusión del usuario. + +### Usando acciones de impresión + +Al usar formularios PDF, a menudo es necesario imprimir dichos documentos PDF. Esta acción se puede realizar con un PDF Reader, pero a veces es más conveniente hacerlo directamente desde el documento mediante un botón especial. + +De hecho, este es otro ejemplo de cómo usar acciones nombradas. Usaremos `PredefinedAction.FILE_PRINT` (simulando el uso del elemento de menú File->Print), pero también puedes usar `PredefinedAction.PRINT` o `PredefinedAction.PRINT_DIALOG`, dependiendo de sus propios propósitos. + +```python +import aspose.pdf as ap +from aspose.pycore import is_assignable +from aspose.pdf import Rectangle +from aspose.pdf.forms import ButtonField, CheckboxField +from aspose.pdf.annotations import ( + NamedAction, + PredefinedAction, + HideAction, + SubmitFormAction, +) +from os import path +import sys + +def add_named_action_print(infile, outfile): + document = ap.Document(infile) + page = document.pages[1] + + # Create print button with specific dimensions and position + rect = Rectangle(10, 10, 100, 40, True) + print_button = ButtonField(page, rect) + print_button.partial_name = "printButton" + print_button.value = "Print" + print_button.actions.on_release_mouse_btn = NamedAction(PredefinedAction.FILE_PRINT) + + # Add border for better visibility + border = ap.annotations.Border(print_button) + border.width = 1 + print_button.border = border + + # Add button to the form on page 1 + document.form.add(print_button, 1) + document.save(outfile) +``` + +Este fragmento de código demuestra cómo agregar un botón "Print" a la primera página de un documento PDF. Comienza cargando el PDF desde la ruta de archivo de entrada especificada y seleccionando la primera página (document.pages[1]). + +Se define un área rectangular para la posición y el tamaño del botón en la página. Luego se crea un ButtonField en esa ubicación, se le asigna el nombre "printButton" y su valor de visualización se establece en "Print". El botón está configurado de modo que, cuando se pulsa (específicamente, cuando se suelta el botón del ratón), active la acción predefinida "Print File", lo que hace que el visor de PDF abra el cuadro de diálogo de impresión. + +Para mejorar la apariencia del botón, se crea un borde y se asigna al botón, con su ancho establecido en 1 unidad. Luego, el botón se añade a los campos de formulario PDF en la primera página. Finalmente, el documento modificado se guarda en la ruta del archivo de salida. Este enfoque brinda a los usuarios una forma conveniente de imprimir el documento directamente desde el PDF. Tenga en cuenta que la efectividad de esta función depende del soporte del visor PDF para campos de formulario interactivos y acciones predefinidas. + +### Usando la acción Ocultar + +```python +import aspose.pdf as ap +from aspose.pycore import is_assignable +from aspose.pdf import Rectangle +from aspose.pdf.forms import ButtonField, CheckboxField +from aspose.pdf.annotations import ( + NamedAction, + PredefinedAction, + HideAction, + SubmitFormAction, +) +from os import path +import sys + +def add_named_action_hide(infile, outfile): + document = ap.Document(infile) + # Collect all checkbox fields in the document + checkboxes = [ + field for field in document.form if is_assignable(field, CheckboxField) + ] + + # Create the hide button + rect = Rectangle(10, 410, 140, 440, True) + hide_button = ButtonField(document.pages[1], rect) + hide_button.partial_name = "HideButton" + hide_button.value = "Hide Checkboxes" + + # Add HideAction to button - will hide all checkboxes when clicked + hide_button.actions.on_release_mouse_btn = HideAction(checkboxes, True) + + # Add button to the form on page 1 + document.form.add(hide_button, 1) + + # Save the modified PDF + document.save(outfile) +``` + +Este fragmento de código agrega un botón a la primera página de un PDF que, al hacer clic, oculta todos los campos de casilla de verificación en el documento. Comienza resolviendo las rutas completas de los archivos de entrada y salida usando un método auxiliar. El PDF se carga y todos los campos de casilla de verificación se recopilan filtrando los campos del formulario por instancias de `ap.CheckboxField`. + +Se define un área rectangular para la posición del nuevo botón cerca de la parte superior de la página. Se crea un ButtonField en esta ubicación, llamado "HideButton", y etiquetado como "Hide Checkboxes". El botón está configurado de modo que, cuando se hace clic en él (al soltar el botón del ratón), ejecuta una HideAction que oculta todas las casillas de verificación recopiladas. + +El botón se agrega luego a los campos del formulario en la primera página, y el PDF modificado se guarda en el archivo de salida. Si ocurre algún error durante este proceso, se capturan y se imprimen. Esta característica brinda a los usuarios una forma de ocultar rápidamente todas las casillas de verificación en el PDF, lo que puede ser útil para personalizar la apariencia o el flujo de trabajo del documento. + +### Aplicando acción de envío + +```python +import aspose.pdf as ap +from aspose.pycore import is_assignable +from aspose.pdf import Rectangle +from aspose.pdf.forms import ButtonField, CheckboxField +from aspose.pdf.annotations import ( + NamedAction, + PredefinedAction, + HideAction, + SubmitFormAction, +) +from os import path +import sys + +def add_submit_action(infile, outfile): + document = ap.Document(infile) + + # Create the submit action + submit_action = SubmitFormAction() + submit_action.url = ap.FileSpecification("http://localhost:3000/submit") + submit_action.flags = ( + SubmitFormAction.EXPORT_FORMAT | SubmitFormAction.SUBMIT_COORDINATES + ) + + # Create the submit button + rect = Rectangle(10, 10, 100, 40, True) + submit_button = ButtonField(document.pages[1], rect) + submit_button.partial_name = "SubmitButton" + submit_button.value = "Submit" + submit_button.actions.on_release_mouse_btn = submit_action + + # Add the button to the form on page 1 + document.form.add(submit_button, 1) + + # Save the document + document.save(outfile) +``` + +Esta función agrega un botón "Submit" a la primera página de un formulario PDF, permitiendo a los usuarios enviar los datos del formulario a un punto final web especificado. Comienza construyendo las rutas completas para los archivos PDF de entrada y salida, luego carga el PDF de entrada usando la biblioteca Aspose.PDF. + +A `SubmitFormAction` se crea para definir el comportamiento cuando se hace clic en el botón. La url de la acción se establece usando un `FileSpecification` apuntando a http://localhost:3000/submit, lo que significa que los datos del formulario se enviarán a esta URL. La propiedad flags combina `EXPORT_FORMAT` y `SUBMIT_COORDINATES`, asegurándose de que los datos del formulario se exporten en un formato estándar y que las coordenadas del clic del botón se incluyan en el envío. + +Se define un área rectangular para la posición y el tamaño del botón en la página. Se crea un ButtonField en esta ubicación en la primera página, con el nombre "SubmitButton," y su valor de visualización se establece en "Submit." La acción de envío se asigna al evento de liberación del ratón del botón, de modo que la acción se dispara cuando el usuario hace clic en el botón. + +Finalmente, el botón se agrega a los campos del formulario en la primera página, y el PDF modificado se guarda en el archivo de salida. Si ocurre algún error durante este proceso, se captura y se muestra. Este enfoque brinda una forma fácil de usar para que los usuarios de PDF envíen los datos del formulario directamente a un punto final del servidor. + +## Temas de navegación relacionados + +- [Navegación e interacción en PDF usando Python](/pdf/es/python-net/navigation-and-interaction/) +- [Trabajar con marcadores en PDF usando Python](/pdf/es/python-net/bookmarks/) +- [Trabajar con enlaces en PDF usando Python](/pdf/es/python-net/links/) diff --git a/es/python-net/advanced-operations/navigation-and-interaction/bookmarks/_index.md b/es/python-net/advanced-operations/navigation-and-interaction/bookmarks/_index.md index 12f4679b2..ae749fbf8 100644 --- a/es/python-net/advanced-operations/navigation-and-interaction/bookmarks/_index.md +++ b/es/python-net/advanced-operations/navigation-and-interaction/bookmarks/_index.md @@ -1,86 +1,29 @@ --- -title: Trabajando con Marcadores en PDF usando Python +title: Trabajar con marcadores de PDF en Python linktitle: Marcadores type: docs weight: 30 url: /es/python-net/bookmarks/ -description: Esta sección explica cómo agregar, eliminar y obtener marcadores con Aspose.PDF para Python a través de .NET. -lastmod: "2023-02-17" +description: Aprenda cómo agregar, eliminar, recuperar, actualizar y expandir marcadores de PDF en Python. +lastmod: "2026-04-15" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo trabajar con marcadores en PDF usando Python +Abstract: El artículo analiza la importancia y utilidad de los marcadores en los documentos PDF. Los marcadores mejoran la experiencia del usuario al permitir una navegación eficiente, organización y estructuración de los archivos PDF, haciéndolos más accesibles. Funcionan como enlaces interactivos, permitiendo a los usuarios desplazarse rápidamente a secciones o páginas específicas, similar a una tabla de contenidos. El artículo brinda orientación sobre la gestión de marcadores, incluyendo cómo agregar, eliminar, obtener, actualizar y expandirlos, lo que permite a los usuarios gestionar y visualizar el contenido PDF de manera efectiva. --- - +Usar marcadores en PDF es una característica útil. Con ellos, puede configurar la navegación en sus documentos, organizar y estructurar archivos PDF, y hacer que dichos archivos sean más accesibles. Sirven como enlaces interactivos dentro del documento, permitiendo a los usuarios navegar rápidamente a secciones o páginas específicas. -Usar marcadores en PDF es una característica muy útil. Con ellos, puedes configurar la navegación en tus documentos, organizar y estructurar archivos PDF, y hacer que dichos archivos sean más accesibles. Actúan como enlaces interactivos en el documento, permitiendo a los usuarios navegar rápidamente a secciones o páginas específicas. +Los marcadores PDF son una herramienta práctica y esencial para leer archivos PDF. Permiten a los usuarios saltar rápidamente a otros lugares en un documento PDF, navegar por las páginas y ver rápidamente el contenido de un PDF, como una tabla de contenidos. -Los marcadores de PDF son una herramienta práctica y esencial cuando se trata de leer archivos PDF. Permiten a los usuarios saltar rápidamente a otros lugares en un documento PDF, navegar a través de las páginas y ver rápidamente el contenido de un PDF, al igual que una tabla de contenido. -En esta sección aprenderás cómo: +Utiliza las siguientes guías de marcadores cuando necesites crear una experiencia de navegación al estilo de una tabla de contenidos o inspeccionar y actualizar un árbol de marcadores existente en un PDF. -- [Agregar y Eliminar un Marcador](/pdf/es/python-net/add-and-delete-bookmark/) -- [Obtener, Actualizar y Expandir un Marcador](/pdf/es/python-net/get-update-and-expand-bookmark/) \ No newline at end of file +## Tareas de marcadores cubiertas + +En esta sección, aprenderás cómo: + +- [Agregar y eliminar un marcador](/pdf/es/python-net/add-and-delete-bookmark/) +- [Obtener, actualizar y expandir un marcador](/pdf/es/python-net/get-update-and-expand-bookmark/) +- [Visión general de la navegación e interacción](/pdf/es/python-net/navigation-and-interaction/) diff --git a/es/python-net/advanced-operations/navigation-and-interaction/bookmarks/add-and-delete-bookmark/_index.md b/es/python-net/advanced-operations/navigation-and-interaction/bookmarks/add-and-delete-bookmark/_index.md index dad38e126..bd9a84308 100644 --- a/es/python-net/advanced-operations/navigation-and-interaction/bookmarks/add-and-delete-bookmark/_index.md +++ b/es/python-net/advanced-operations/navigation-and-interaction/bookmarks/add-and-delete-bookmark/_index.md @@ -1,205 +1,160 @@ --- -title: Añadir y Eliminar un Marcador usando Python -linktitle: Añadir y Eliminar un Marcador +title: Agregar y eliminar marcadores PDF en Python +linktitle: Agregar y eliminar un marcador type: docs weight: 10 url: /es/python-net/add-and-delete-bookmark/ -description: Puede añadir un marcador a un documento PDF con Python. Es posible eliminar todos o algunos marcadores de un documento PDF. -lastmod: "2023-02-17" +description: Aprende cómo agregar y eliminar marcadores en documentos PDF usando Python. +lastmod: "2026-04-15" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo agregar y eliminar marcadores usando Python +Abstract: Este artículo proporciona instrucciones exhaustivas sobre la gestión de marcadores en documentos PDF usando la biblioteca Aspose.PDF for Python via .NET. Describe los procesos para agregar, modificar y eliminar marcadores dentro de un PDF. El artículo comienza con una guía sobre cómo añadir un marcador creando un objeto `OutlineItemCollection` y añadiéndolo a la `OutlineCollection` del documento. Incluye ejemplos de código que demuestran la creación y adición de marcadores tanto padre como hijo, resaltando una relación jerárquica. Además, el artículo cubre métodos para eliminar todos los marcadores o un marcador específico por título. Cada sección incluye fragmentos de código Python para ilustrar las operaciones, asegurando que los lectores puedan implementar fácilmente las funcionalidades descritas en sus tareas de manipulación de PDF. --- - - - -## Añadir un Marcador a un Documento PDF - -Los marcadores se mantienen en la colección [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) del objeto Document, que a su vez está en la colección [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/). - -Para añadir un marcador a un PDF: - -1. Abra un documento PDF usando el objeto [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). -1. Cree un marcador y defina sus propiedades. -1. Añada la colección [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) a la colección de Outlines. - -El siguiente fragmento de código muestra cómo añadir un marcador en un documento PDF. -```python - - import aspose.pdf as ap +## Agregar un marcador a un documento PDF - # Abrir documento - document = ap.Document(input_pdf) +Los marcadores se guardan en el objeto Document [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) colección, en sí misma en el [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) colección. - # Crear un objeto de marcador - outline = ap.OutlineItemCollection(document.outlines) - outline.title = "Marcador de Prueba" - outline.italic = True - outline.bold = True - # Establecer el número de página de destino - outline.action = ap.annotations.GoToAction(document.pages[1]) - # Añadir marcador en la colección de esquemas del documento. - document.outlines.append(outline) +Para agregar un marcador a un PDF: - # Guardar salida - document.save(output_pdf) -``` +1. Abra un documento PDF usando [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) objeto. +1. Crea un marcador y define sus propiedades. +1. Añade el [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) colección a la colección Outlines. +El siguiente fragmento de código le muestra cómo agregar un marcador en un documento PDF. -## Añadir un Marcador Hijo al Documento PDF +```python +import aspose.pdf as ap +import sys +from os import path -Los marcadores pueden estar anidados, indicando una relación jerárquica con marcadores padre e hijo. Este artículo explica cómo añadir un marcador hijo, es decir, un marcador de segundo nivel, a un PDF. +def add_bookmark(infile, outfile): + # Open PDF document + document = ap.Document(infile) -Para añadir un marcador hijo a un archivo PDF, primero añada un marcador padre: + # Create a bookmark object + pdf_outline = ap.OutlineItemCollection(document.outlines) + pdf_outline.title = "Test Outline" + pdf_outline.italic = True + pdf_outline.bold = True -1. Abra un documento. -1. Añada un marcador a la [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/), definiendo sus propiedades. -1. Añada la OutlineItemCollection a la colección [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) del objeto Document. + # Set the destination page number + pdf_outline.action = ap.annotations.GoToAction(document.pages[1]) -El marcador hijo se crea igual que el marcador padre, explicado arriba, pero se agrega a la colección de Contornos del marcador padre. + # Add bookmark to the document's outline collection + outlines = document.outlines + outlines.append(pdf_outline) -Los siguientes fragmentos de código muestran cómo añadir un marcador hijo a un documento PDF. + # Save PDF document + document.save(outfile) +``` -```python +## Agregar un marcador hijo al documento PDF - import aspose.pdf as ap +Los marcadores pueden anidarse, indicando una relación jerárquica con marcadores padre e hijo. Este artículo explica cómo agregar un marcador hijo, es decir, un marcador de segundo nivel, a un PDF. - # Abrir documento - document = ap.Document(input_pdf) +Para agregar un marcador hijo a un archivo PDF, primero agregue un marcador padre: - # Crear un objeto de marcador padre - outline = ap.OutlineItemCollection(document.outlines) - outline.title = "Contorno Padre" - outline.italic = True - outline.bold = True +1. Abrir un documento. +1. Agregar un marcador a la [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/), definiendo sus propiedades. +1. Agregar el OutlineItemCollection al objeto Document [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) colección. - # Crear un objeto de marcador hijo - childOutline = ap.OutlineItemCollection(document.outlines) - childOutline.title = "Contorno Hijo" - childOutline.italic = True - childOutline.bold = True +El marcador hijo se crea igual que el marcador padre, explicado arriba, pero se agrega a la colección Outlines del marcador padre - # Añadir marcador hijo en la colección del marcador padre - outline.append(childOutline) - # Añadir marcador padre en la colección de contornos del documento. - document.outlines.append(outline) +Los siguientes fragmentos de código muestran cómo agregar un marcador hijo a un documento PDF. - # Guardar salida - document.save(output_pdf) +```python +import aspose.pdf as ap +import sys +from os import path + +def add_child_bookmark(infile, outfile): + # Open PDF document + document = ap.Document(infile) + + # Create a parent bookmark object + pdf_outline = ap.OutlineItemCollection(document.outlines) + pdf_outline.title = "Parent Outline" + pdf_outline.italic = True + pdf_outline.bold = True + + # Create a child bookmark object + pdf_child_outline = ap.OutlineItemCollection(document.outlines) + pdf_child_outline.title = "Child Outline" + pdf_child_outline.italic = True + pdf_child_outline.bold = True + + # Add child bookmark to parent bookmark's collection + pdf_outline.append(pdf_child_outline) + + # Add parent bookmark to the document's outline collection + document.outlines.append(pdf_outline) + + # Save PDF document + document.save(outfile) ``` +## Eliminar todos los marcadores de un documento PDF -## Eliminar todos los Marcadores de un Documento PDF - -Todos los marcadores en un PDF se mantienen en la colección [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/). Este artículo explica cómo eliminar todos los marcadores de un archivo PDF. +Todos los marcadores en un PDF se almacenan en el [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) colección. Este artículo explica cómo eliminar todos los marcadores de un archivo PDF. Para eliminar todos los marcadores de un archivo PDF: -1. Llame al método Delete de la colección [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/). -2. Guarde el archivo modificado usando el método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) del objeto [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Llame al [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) método Delete de la colección. +1. Guarda el archivo modificado usando el [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) del objeto [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método. Los siguientes fragmentos de código muestran cómo eliminar todos los marcadores de un documento PDF. ```python +import aspose.pdf as ap +import sys +from os import path - import aspose.pdf as ap +def delete_bookmarks(infile, outfile): + # Open PDF document + document = ap.Document(infile) - # Abrir documento - document = ap.Document(input_pdf) - - # Eliminar todos los marcadores + # Delete all bookmarks in the PDF document document.outlines.delete() - # Guardar archivo actualizado - document.save(output_pdf) - + # Save PDF document + document.save(outfile) ``` -## Eliminar un Marcador Particular de un Documento PDF +## Eliminar un marcador específico de un documento PDF -Para eliminar un marcador particular de un archivo PDF: +Para eliminar un marcador específico de un archivo PDF: -1. Pase el título del marcador como parámetro al método Delete de la colección [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/). +1. Pase el título del marcador como parámetro a la [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) método Delete de la colección. 1. Luego guarde el archivo actualizado con el método Save del objeto Document. -La clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) proporciona la colección [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/). El método [delete()](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/#methods) elimina cualquier marcador con el título pasado al método. +El [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) la clase’ proporciona el [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) colección. El [delete()](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/#methods) el método elimina cualquier marcador con el título pasado al método. -Los siguientes fragmentos de código muestran cómo eliminar un marcador particular del documento PDF. +Los siguientes fragmentos de código muestran cómo eliminar un marcador específico del documento PDF. ```python +import aspose.pdf as ap +import sys +from os import path - import aspose.pdf as ap +def delete_bookmark(infile, outfile): + # Open PDF document + document = ap.Document(infile) - # Abrir documento - document = ap.Document(input_pdf) - - # Eliminar un esquema particular por título + # Delete a specific bookmark by title. + # Note: If multiple bookmarks have the same title, only the first matching bookmark will be deleted. document.outlines.delete("Child Outline") - # Guardar archivo actualizado - document.save(output_pdf) \ No newline at end of file + # Save PDF document + document.save(outfile) +``` + +## Temas relacionados de marcadores + +- [Trabajar con marcadores PDF en Python](/pdf/es/python-net/bookmarks/) +- [Obtener, actualizar y expandir marcadores PDF en Python](/pdf/es/python-net/get-update-and-expand-bookmark/) +- [Navegación e interacción en PDF usando Python](/pdf/es/python-net/navigation-and-interaction/) + diff --git a/es/python-net/advanced-operations/navigation-and-interaction/bookmarks/get-update-expand-bookmark/_index.md b/es/python-net/advanced-operations/navigation-and-interaction/bookmarks/get-update-expand-bookmark/_index.md index 4c48b9f70..90b28b892 100644 --- a/es/python-net/advanced-operations/navigation-and-interaction/bookmarks/get-update-expand-bookmark/_index.md +++ b/es/python-net/advanced-operations/navigation-and-interaction/bookmarks/get-update-expand-bookmark/_index.md @@ -1,96 +1,32 @@ --- -title: Obtener, Actualizar y Expandir un Marcador usando Python -linktitle: Obtener, Actualizar y Expandir un Marcador +title: Obtener, actualizar y expandir marcadores PDF en Python +linktitle: Obtener, actualizar y expandir un marcador type: docs weight: 20 url: /es/python-net/get-update-and-expand-bookmark/ -description: Este artículo describe cómo usar marcadores en un archivo PDF con nuestra biblioteca Aspose.PDF para Python. -lastmod: "2023-02-17" +description: Aprenda cómo recuperar, actualizar y expandir marcadores en documentos PDF usando Python. +lastmod: "2026-05-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo usar marcadores en PDF con Python +Abstract: Este artículo ofrece una guía completa sobre la gestión de marcadores dentro de un documento PDF utilizando la biblioteca Aspose.PDF en Python. Comienza explicando cómo recuperar los marcadores de un archivo PDF a través de la `OutlineCollection`, que contiene todos los marcadores, y detalla el acceso a los atributos del marcador mediante la `OutlineItemCollection`. Luego, el artículo describe el proceso de determinar el número de página asociado a un marcador usando el `PdfBookmarkEditor`. Además, explica cómo manejar estructuras jerárquicas de marcadores recuperando los marcadores secundarios dentro de cada `OutlineItemCollection`. También cubre la actualización de las propiedades de los marcadores, demostrando cómo modificar los atributos del marcador y guardar los cambios en un PDF. Finalmente, el artículo aborda el requisito de expandir los marcadores al visualizar un documento, mostrando cómo establecer el estado abierto de cada marcador para asegurarse de que se expandan por defecto. Los fragmentos de código acompañan a cada sección, proporcionando ejemplos prácticos de la implementación de estas funcionalidades. --- - - - -## Obtener Marcadores - -La colección [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) del objeto [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) contiene todos los marcadores de un archivo PDF. Este artículo explica cómo obtener marcadores de un archivo PDF y cómo determinar en qué página se encuentra un marcador en particular. - -Para obtener los marcadores, recorre la colección [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) y obtén cada marcador en la OutlineItemCollection. La [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) proporciona acceso a todos los atributos del marcador. El siguiente fragmento de código muestra cómo obtener marcadores del archivo PDF. -```python +## Obtener marcadores - import aspose.pdf as ap +La colección [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) del objeto [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) contiene todos los marcadores de un archivo PDF. Este artículo explica cómo obtener marcadores de un archivo PDF y cómo identificar en qué página se encuentra un marcador concreto. - # Abrir documento - document = ap.Document(input_pdf) +Para obtener los marcadores, recorra la colección [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) y obtenga cada marcador en `OutlineItemCollection`. [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) proporciona acceso a todos los atributos del marcador. El siguiente fragmento de código muestra cómo obtener marcadores del archivo PDF. + +```python +from os import path +import sys +import aspose.pdf as ap - # Recorrer todos los marcadores +def get_bookmarks(input_pdf): + document = ap.Document(input_pdf) for i in range(len(document.outlines)): outline_item = document.outlines[i + 1] print(outline_item.title) @@ -99,44 +35,43 @@ Para obtener los marcadores, recorre la colección [OutlineCollection](https://r print(outline_item.color) ``` +## Obtener el número de página de un marcador -## Obtener el Número de Página de un Marcador - -Una vez que hayas añadido un marcador, puedes averiguar en qué página se encuentra obteniendo el número de página de destino asociado con el objeto Bookmark. +Una vez que haya agregado un marcador, puede averiguar en qué página se encuentra obteniendo el número de página de destino asociado al objeto marcador. ```python - - import aspose.pdf as ap - - # Crear PdfBookmarkEditor - bookmarkEditor = ap.facades.PdfBookmarkEditor() - # Abrir archivo PDF - bookmarkEditor.bind_pdf(input_pdf) - # Extraer marcadores - bookmarks = bookmarkEditor.extract_bookmarks() +from os import path +import sys +import aspose.pdf as ap + +def get_bookmark_page_number(input_pdf): + # Create PdfBookmarkEditor + bookmark_editor = ap.facades.PdfBookmarkEditor() + # Open PDF file + bookmark_editor.bind_pdf(input_pdf) + # Extract bookmarks + bookmarks = bookmark_editor.extract_bookmarks() for bookmark in bookmarks: - str_level_seprator = "" + str_level_separator = "" for i in range(bookmark.level): - str_level_seprator += "----" + str_level_separator += "----" - print(str_level_seprator, "Título:", bookmark.title) - print(str_level_seprator, "Número de Página:", bookmark.page_number) - print(str_level_seprator, "Acción de Página:", bookmark.action) + print(str_level_separator, "Title:", bookmark.title) + print(str_level_separator, "Page Number:", bookmark.page_number) + print(str_level_separator, "Page Action:", bookmark.action) ``` -## Obtener Submarcadores de un Documento PDF +## Obtener marcadores secundarios de un documento PDF -Los marcadores pueden organizarse en una estructura jerárquica, con padres e hijos. - Para obtener todos los marcadores, recorra los colecciones de Outlines del objeto Document. Sin embargo, para obtener también los marcadores secundarios, recorra todos los marcadores en cada objeto [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) obtenido en el primer ciclo. Los siguientes fragmentos de código muestran cómo obtener marcadores secundarios de un documento PDF. +Los marcadores pueden organizarse en una estructura jerárquica, con nodos padre e hijo. Para obtener todos los marcadores, recorra las colecciones `Outlines` del objeto `Document`. Para obtener también los marcadores secundarios, recorra además todos los marcadores de cada objeto [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) obtenido en el primer bucle. Los siguientes fragmentos de código muestran cómo obtener marcadores secundarios de un documento PDF. ```python +from os import path +import sys +import aspose.pdf as ap - import aspose.pdf as ap - - # Abrir documento +def get_child_bookmarks(input_pdf): document = ap.Document(input_pdf) - - # Recorrer todos los marcadores for i in range(len(document.outlines)): outline_item = document.outlines[i + 1] print(outline_item.title) @@ -145,61 +80,64 @@ Los marcadores pueden organizarse en una estructura jerárquica, con padres e hi print(outline_item.color) count = len(outline_item) if count > 0: - print("Marcadores secundarios") - # Hay marcadores secundarios, entonces recorrer también + print("Child Bookmarks") + # There are child bookmarks then loop through that as well for j in range(len(outline_item)): - child_outline_item = outline_item[i + 1] + child_outline_item = outline_item[j + 1] print(child_outline_item.title) print(child_outline_item.italic) print(child_outline_item.bold) print(child_outline_item.color) ``` -## Actualizar Marcadores en un Documento PDF +## Actualizar marcadores en un documento PDF -Para actualizar un marcador en un archivo PDF, primero, obtén el marcador particular de la colección OutlineColletion del objeto Document especificando el índice del marcador. Una vez que hayas recuperado el marcador en el objeto [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/), puedes actualizar sus propiedades y luego guardar el archivo PDF actualizado usando el método Save. Los siguientes fragmentos de código muestran cómo actualizar marcadores en un documento PDF. +Para actualizar un marcador en un archivo PDF, primero obtenga el marcador deseado de la colección `OutlineCollection` del objeto `Document` especificando su índice. Una vez que haya recuperado el marcador en un objeto [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/), puede actualizar sus propiedades y luego guardar el archivo PDF actualizado con el método `Save`. Los siguientes fragmentos de código muestran cómo actualizar marcadores en un documento PDF. ```python +from os import path +import sys +import aspose.pdf as ap - import aspose.pdf as ap - - # Abrir documento +def update_bookmarks(input_pdf, output_pdf): + # Open document document = ap.Document(input_pdf) - # Obtener un objeto de marcador + # Get a bookmark object outline = document.outlines[1] - # Obtener objeto de marcador hijo + # Get child bookmark object child_outline = outline[1] - child_outline.title = "Outline Actualizado" + child_outline.title = "Updated Outline" child_outline.italic = True child_outline.bold = True - # Guardar salida + # Save output document.save(output_pdf) ``` -## Marcadores Expandidos al ver el documento +## Marcadores ampliados al visualizar el documento -Los marcadores se mantienen en la colección [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) del objeto Document, a su vez en la colección [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/). - Sin embargo, es posible que tengamos un requisito de tener todos los marcadores expandidos al ver el archivo PDF. +Los marcadores se guardan en la colección [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) del objeto `Document`, que a su vez forma parte de la colección [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/). En algunos casos puede ser necesario que todos los marcadores aparezcan expandidos al visualizar el archivo PDF. -Para cumplir con este requisito, podemos establecer el estado abierto para cada elemento de esquema/marcador como Abierto. El siguiente fragmento de código le muestra cómo establecer el estado abierto para cada marcador como expandido en un documento PDF. +Para cumplir con este requisito, podemos establecer el estado abierto de cada elemento de esquema o marcador en `Open`. El siguiente fragmento de código muestra cómo establecer el estado abierto de cada marcador para que aparezca expandido en un documento PDF. ```python +from os import path +import sys +import aspose.pdf as ap - import aspose.pdf as ap - - # Abrir documento +def expanded_bookmarks(input_pdf, output_pdf): document = ap.Document(input_pdf) - - # Establecer modo de vista de página, es decir, mostrar miniaturas, pantalla completa, mostrar panel de adjuntos document.page_mode = ap.PageMode.USE_OUTLINES - # Recorrer cada elemento de esquema en la colección de esquemas del archivo PDF for i in range(len(document.outlines)): item = document.outlines[i + 1] - # Establecer estado abierto para el elemento de esquema item.open = True + document.save(output_pdf) +``` + +## Temas relacionados de marcadores - # Guardar salida - document.save(output_pdf) \ No newline at end of file +- [Trabajar con marcadores PDF en Python](/pdf/es/python-net/bookmarks/) +- [Agregar y eliminar marcadores PDF en Python](/pdf/es/python-net/add-and-delete-bookmark/) +- [Navegación e interacción en PDF usando Python](/pdf/es/python-net/navigation-and-interaction/) diff --git a/es/python-net/advanced-operations/navigation-and-interaction/links/_index.md b/es/python-net/advanced-operations/navigation-and-interaction/links/_index.md new file mode 100644 index 000000000..57624422f --- /dev/null +++ b/es/python-net/advanced-operations/navigation-and-interaction/links/_index.md @@ -0,0 +1,23 @@ +--- +title: Trabajar con enlaces PDF en Python +linktitle: Enlaces +type: docs +weight: 10 +url: /es/python-net/links/ +description: Aprenda cómo crear, extraer y actualizar enlaces internos y externos en documentos PDF usando Python. +lastmod: "2026-04-15" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Crear, extraer y actualizar enlaces PDF en Python +Abstract: La guía de Aspose.PDF for Python via .NET sobre el trabajo con enlaces ofrece una visión completa de cómo los desarrolladores pueden gestionar programáticamente hipervínculos y elementos de navegación dentro de documentos PDF usando Python. Cubre operaciones esenciales como crear enlaces internos y externos, actualizar destinos y apariencia de los enlaces, y extraer enlaces existentes. +--- + +Utilice esta sección cuando necesite crear enlaces clicables, inspeccionar anotaciones de enlaces existentes, o actualizar la apariencia y los destinos de los enlaces en archivos PDF. + +## Tareas de enlaces cubiertas + +- [Crear enlaces](/pdf/es/python-net/create-links/) - aprender de forma sencilla una manera de crear enlaces en su archivo PDF usando Python. +- [Actualizar enlaces](/pdf/es/python-net/update-links/) - intentar establecer el objetivo a PDF, intentar establecer el destino del enlace a una dirección web, intentar establecer el objetivo del enlace a otro archivo PDF, actualizar el color del texto del enlace. +- [Extraer enlaces](/pdf/es/python-net/extract-links/) - extraer enlaces del archivo PDF usando Python. diff --git a/es/python-net/advanced-operations/navigation-and-interaction/links/create-links/_index.md b/es/python-net/advanced-operations/navigation-and-interaction/links/create-links/_index.md new file mode 100644 index 000000000..48e35f548 --- /dev/null +++ b/es/python-net/advanced-operations/navigation-and-interaction/links/create-links/_index.md @@ -0,0 +1,147 @@ +--- +title: Crear enlaces PDF en Python +linktitle: Crear enlaces +type: docs +weight: 10 +url: /es/python-net/create-links/ +description: Aprende cómo crear enlaces PDF internos, externos y remotos en Python. +lastmod: "2026-04-15" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo crear enlaces en PDF +Abstract: La guía Aspose.PDF for Python via .NET sobre la creación de enlaces proporciona a los desarrolladores instrucciones prácticas para agregar hipervínculos interactivos a documentos PDF usando Python. Cubre cómo crear varios tipos de enlaces, incluidos los que lanzan aplicaciones externas, navegan a páginas específicas dentro del mismo documento o abren otros archivos PDF. La documentación explica cómo usar objetos LinkAnnotation, definir áreas clicables con Rectangle y asignar acciones como LaunchAction o GoToRemoteAction. Con ejemplos de código claros y una guía paso a paso, este recurso ayuda a los desarrolladores a mejorar la navegación e interactividad de los PDF en sus aplicaciones Python. +--- + +## Enlaces en documentos PDF + +Según la especificación PDF 1.7 (ISO 32000-1:2008), una **Link annotation** puede activar varios tipos de acciones que definen lo que ocurre cuando se activa la anotación. Aquí están las acciones principales admitidas: + +1. **GoTo** – Navega a un destino dentro del mismo documento. +1. **GoToR** – Salta a un destino en otro archivo PDF (go-to remoto). +1. **URI** – Abre un identificador uniforme de recursos, típicamente un enlace web. +1. **Launch** – Lanza una aplicación o abre un archivo (dependiendo de la plataforma y a menudo restringido por motivos de seguridad). +1. **Named** – Ejecuta una acción predefinida, como ir a la página siguiente o imprimir el documento. +1. **JavaScript** – Ejecuta código JavaScript incrustado (se usa con precaución debido a preocupaciones de seguridad). +1. **SubmitForm** – Envía los datos del formulario a una URL especificada. +1. **ResetForm** – Restablece los campos del formulario a sus valores predeterminados. +1. **ImportData** – Importa datos al documento desde un archivo externo. + +Al agregar un enlace a una aplicación dentro de un documento, es posible enlazar a aplicaciones desde un documento. Esto es útil cuando deseas que los lectores realicen una acción determinada en un punto específico de un tutorial, por ejemplo, o para crear un documento con muchas funciones. + +Para crear un enlace a una aplicación con ‘LaunchAction’: + +```python +import aspose.pdf as ap +from os import path +import sys + +def create_link_annotation_launch_action(infile, outfile): + document = ap.Document(infile) + page = document.pages[1] + + link = ap.annotations.LinkAnnotation(page, ap.Rectangle(10, 580, 120, 600, True)) + border = ap.annotations.Border(link) + border.width = 5 + border.dash = ap.annotations.Dash(1, 1) + link.color = ap.Color.green + link.action = ap.annotations.LaunchAction(document, "sample.pdf") + page.annotations.append(link) + document.save(outfile) +``` + +## Crear enlace de documento PDF en un archivo PDF + +### Usando GoToRemoteAction + +Este fragmento de código demuestra cómo agregar una anotación de enlace a una página específica de un documento PDF usando una biblioteca PDF de Python. + +1. Abre el documento PDF +1. Selecciona la segunda página del documento (índice 1) +1. Crea una anotación de enlace: +1. Posicionado en las coordenadas (10, 580, 120, 600) +1. Coloreado verde +1. Enlaces a 'sample.pdf' en su primera página +1. Agregar la anotación de enlace a la página +1. Guardar el documento modificado en la ruta del archivo de salida + +Para crear un enlace de documento PDF usando 'GoToRemoteAction': + +```python +import aspose.pdf as ap +from os import path +import sys + +def create_link_annotation_go_to_remote_action(infile, outfile): + document = ap.Document(infile) + page = document.pages[1] + + link = ap.annotations.LinkAnnotation(page, ap.Rectangle(10, 580, 120, 600, True)) + link.color = ap.Color.green + link.action = ap.annotations.GoToRemoteAction("sample.pdf", 1) + page.annotations.append(link) + document.save(outfile) +``` + +### Usando GoToAction + +Este código muestra cómo agregar una anotación de enlace a una página específica de un documento PDF usando Aspose.PDF for Python. El enlace aparece como un rectángulo verde con borde discontinuo y permite al usuario navegar a otra página dentro del mismo PDF. Para crear un enlace de documento PDF usando 'GoToAction': + +```python +import aspose.pdf as ap +from os import path +import sys + +def create_link_annotation_go_to_action(infile, outfile): + document = ap.Document(infile) + page = document.pages[1] + + link = ap.annotations.LinkAnnotation(page, ap.Rectangle(10, 580, 120, 600, True)) + border = ap.annotations.Border(link) + border.width = 5 + border.dash = ap.annotations.Dash(1, 1) + link.color = ap.Color.green + if document.pages.length >= 4: + link.action = ap.annotations.GoToAction(document.pages[4]) + else: + link.action = ap.annotations.GoToAction(document.pages[document.pages.length]) + page.annotations.append(link) + document.save(outfile) +``` + +### Aplicando GoToURIAction + +El siguiente ejemplo muestra cómo agregar una anotación de enlace a un documento PDF usando Aspose.PDF for Python. El enlace aparece como un área verde clicable en la primera página, y al hacer clic, abre la documentación de Aspose.PDF for Python en un navegador web mediante una GoToURIAction. + +Esta funcionalidad es útil para incrustar referencias externas útiles, documentación o enlaces de soporte directamente dentro de sus PDFs. + +1. Cargue el documento PDF. Abra el archivo PDF existente usando ap.Document. +1. Acceda a la primera página. Use document.pages[1] para acceder a la primera página (Aspose usa indexación basada en 1). +1. Cree una anotación de enlace. Cree un objeto LinkAnnotation y especifique el área rectangular clicable usando ap.Rectangle. +1. Establecer apariencia de la anotación. Establecer el color de la anotación a verde usando link.color = ap.Color.green. +1. Asignar una acción URI. Utilizar GoToURIAction para vincular la anotación a una URL externa. +1. Agregar la anotación a la página. Añadir la anotación de enlace configurada a la colección de anotaciones de la primera página. +1. Guardar el documento modificado. Guardar el documento PDF actualizado en la ruta de salida especificada. + +```python +import aspose.pdf as ap +from os import path +import sys + +def create_link_annotation_go_to_URI_action(infile, outfile): + document = ap.Document(infile) + page = document.pages[1] + + link = ap.annotations.LinkAnnotation(page, ap.Rectangle(10, 580, 120, 600, True)) + link.color = ap.Color.green + link.action = ap.annotations.GoToURIAction("https://docs.aspose.com/pdf/python") + page.annotations.append(link) + document.save(outfile) +``` + +## Temas relacionados de enlaces + +- [Trabajar con enlaces PDF en Python](/pdf/es/python-net/links/) +- [Extraer enlaces del PDF en Python](/pdf/es/python-net/extract-links/) +- [Actualizar enlaces en el PDF usando Python](/pdf/es/python-net/update-links/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md b/es/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md new file mode 100644 index 000000000..422d3cd20 --- /dev/null +++ b/es/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md @@ -0,0 +1,92 @@ +--- +title: Extraer enlaces PDF en Python +linktitle: Extraer enlaces +type: docs +weight: 30 +url: /es/python-net/extract-links/ +description: Aprende cómo extraer anotaciones de enlace e hipervínculos de documentos PDF en Python. +lastmod: "2026-04-15" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo extraer enlaces de PDF +Abstract: La guía de Aspose.PDF for Python via .NET sobre la extracción de enlaces explica cómo recuperar programáticamente anotaciones de hipervínculo de documentos PDF mediante Python. La documentación incluye ejemplos de código prácticos y destaca cómo esta funcionalidad puede usarse para tareas como auditoría de enlaces, análisis de navegación o creación de características interactivas en documentos. Ya sea que estés trabajando con PDFs de una sola página o procesando lotes grandes, esta guía ofrece un enfoque claro y eficiente para la extracción de hipervínculos. +--- + +## Extraer enlaces del archivo PDF + +Este ejemplo muestra cómo iterar a través de todas las anotaciones de enlace en la primera página de un PDF usando Aspose.PDF for Python. Filtra las anotaciones para identificar aquellas de tipo LinkAnnotation, las convierte de forma segura y luego imprime su índice de página y su posición rectangular en la página. + +Esto puede usarse para depuración, análisis o actualizaciones automáticas de anotaciones de enlace existentes en un PDF. + +1. Cargue el documento PDF. Use ap.Document(path_infile) para abrir el archivo. +1. Acceda a las anotaciones de la primera página. Use document.pages[1].annotations para obtener todas las anotaciones. +1. Filtre solo los tipos LinkAnnotation. Verifique el annotation_type de cada anotación. +1. Convierta y procese las LinkAnnotations. Use is_assignable() y cast() para garantizar un acceso seguro a las propiedades de LinkAnnotation. +1. Imprimir detalles de anotaciones. Salida del índice de página y del rectángulo (ubicación) de cada enlace. + +```python +import aspose.pdf as ap +import sys +from os import path +from aspose.pycore import cast, is_assignable + +def extract_link_annotation(infile): + + document = ap.Document(infile) + link_annotations = [ + a + for a in document.pages[1].annotations + if (a.annotation_type == ap.annotations.AnnotationType.LINK) + ] + + for la in link_annotations: + if is_assignable(la, ap.annotations.LinkAnnotation): + annotation = cast(ap.annotations.LinkAnnotation, la) + print(f"Page: {annotation.page_index}, location: {annotation.rect}") +``` + +## Extraer hipervínculos del archivo PDF + +Este código demuestra cómo extraer todos los objetos LinkAnnotation de la primera página de un documento PDF usando Aspose.PDF for Python, y luego identificar aquellos que contienen un GoToURIAction. Para cada uno de esos enlaces, imprime el índice de página y el URI de destino. + +Esto es útil para tareas como: + +- Auditar enlaces externos en un PDF +- Extraer URLs de documentación o soporte +- Detectar hipervínculos rotos o desactualizados + +1. Cargar el documento PDF. Abrir el archivo usando ap.Document. +1. Obtenga todas las anotaciones de enlace de la primera página. Filtre las anotaciones para incluir solo aquellas con el tipo AnnotationType.LINK. +1. Verifique el tipo y convierta a LinkAnnotation. Asegúrese de que cada anotación sea realmente una LinkAnnotation antes de acceder a sus propiedades. +1. Compruebe el tipo de acción del enlace. Filtre los enlaces que utilizan un GoToURIAction (es decir, enlaces a una URL web). +1. Extraiga e imprima el URI y el índice de página. Utilice .uri para obtener el enlace externo y .page_index para el contexto. + +```python +import aspose.pdf as ap +import sys +from os import path +from aspose.pycore import cast, is_assignable + +def extract_hyperlinks(infile): + document = ap.Document(infile) + link_annotations = [ + a + for a in document.pages[1].annotations + if (a.annotation_type == ap.annotations.AnnotationType.LINK) + ] + + for la in link_annotations: + if is_assignable(la, ap.annotations.LinkAnnotation): + annotation = cast(ap.annotations.LinkAnnotation, la) + if is_assignable(annotation.action, ap.annotations.GoToURIAction): + action = cast(ap.annotations.GoToURIAction, annotation.action) + print(f"Page {annotation.page_index}, URI:{action.uri}") +``` + +## Temas relacionados de enlaces + +- [Trabajar con enlaces PDF en Python](/pdf/es/python-net/links/) +- [Crear enlaces PDF en Python](/pdf/es/python-net/create-links/) +- [Actualizar enlaces en el PDF usando Python](/pdf/es/python-net/update-links/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/navigation-and-interaction/links/update-links/_index.md b/es/python-net/advanced-operations/navigation-and-interaction/links/update-links/_index.md new file mode 100644 index 000000000..09848da63 --- /dev/null +++ b/es/python-net/advanced-operations/navigation-and-interaction/links/update-links/_index.md @@ -0,0 +1,114 @@ +--- +title: Actualizar enlaces PDF en Python +linktitle: Actualizar enlaces +type: docs +weight: 20 +url: /es/python-net/update-links/ +description: Aprende cómo actualizar la apariencia y los destinos de los enlaces PDF en Python. +lastmod: "2026-04-15" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo actualizar los enlaces en PDF +Abstract: La guía Aspose.PDF for Python via .NET sobre actualización de enlaces guía a los desarrolladores a través del proceso de modificar el comportamiento de los hipervínculos dentro de documentos PDF usando Python. Explica cómo cambiar los destinos de los enlaces para que apunten a páginas específicas, sitios web externos o incluso a otros archivos PDF. La documentación también cubre cómo ajustar la apariencia de las anotaciones de enlace, incluido el color del texto, y ofrece ejemplos de código prácticos para cada escenario. Ya sea que esté corrigiendo URL obsoletas o mejorando la navegación, este recurso ofrece un enfoque claro y eficiente para gestionar enlaces programáticamente. +--- + +## Actualizar color de texto de LinkAnnotation + +Este ejemplo muestra cómo detectar todas las anotaciones de enlace en la primera página de un PDF usando Aspose.PDF for Python, y luego resaltar el texto cercano a cada enlace cambiando el color de su fuente a rojo. Utiliza TextFragmentAbsorber con un área ligeramente ampliada alrededor de cada rectángulo de enlace para encontrar y modificar el texto cercano. + +Esto se puede usar para: + +- Marcar visualmente los enlaces en un documento +- Mejorar la accesibilidad enfatizando el contenido enlazado +- Preprocesamiento de archivos PDF antes de la revisión o exportación + +Para cada una de estas anotaciones de enlace, el script recupera su límite rectangular y amplía ligeramente esa región para incluir texto cercano, lo que permite una identificación visual más amplia. Luego aplica un TextFragmentAbsorber sobre esta área ampliada para extraer cualquier fragmento de texto situado dentro de ella. Estos fragmentos capturados se modifican cambiando su color de fuente a rojo, marcando efectivamente el texto circundante para enfatizar y revisar. Después de aplicar todas estas actualizaciones, el documento modificado se guarda en la ruta de salida, preservando las anotaciones resaltadas y su texto asociado. + +```python +import aspose.pdf as ap +import sys +from os import path +from aspose.pycore import cast, is_assignable + +def link_annotation_update_text_color(infile, outfile): + document = ap.Document(infile) + link_annotations = [ + a + for a in document.pages[1].annotations + if (a.annotation_type == ap.annotations.AnnotationType.LINK) + ] + + for la in link_annotations: + ta = ap.text.TextFragmentAbsorber() + rect = la.rect + rect.llx -= 2 + rect.lly -= 2 + rect.urx += 2 + rect.ury += 2 + ta.text_search_options = ap.text.TextSearchOptions(rect) + ta.visit(document.pages[1]) + for textFragment in ta.text_fragments: + textFragment.text_state.foreground_color = ap.Color.red + + document.save(outfile) +``` + +## Actualizar borde + +El script se centra en la primera página del documento y filtra todas las anotaciones, seleccionando solo aquellas del tipo LINK—estas generalmente representan elementos interactivos, como hipervínculos o disparadores de navegación. Para cada una de estas anotaciones de enlace, el código las convierte al tipo LinkAnnotation y actualiza su propiedad de color a rojo, resaltándolas visualmente para que se destaquen del resto del contenido. Después de que todas las anotaciones de enlace hayan sido modificadas, el documento actualizado se guarda en la ubicación de salida definida, preservando el nuevo estilo. + +```python +import aspose.pdf as ap +import sys +from os import path +from aspose.pycore import cast, is_assignable + +def link_annotation_update_border(infile, outfile): + document = ap.Document(infile) + link_annotations = [ + a + for a in document.pages[1].annotations + if (a.annotation_type == ap.annotations.AnnotationType.LINK) + ] + + for la in link_annotations: + link_annotation = cast(ap.annotations.LinkAnnotation, la) + link_annotation.color = ap.Color.red + + document.save(outfile) +``` + +## Actualizar destino web + +Una vez que las rutas están en su lugar, el documento original se carga utilizando la biblioteca Aspose.PDF, lo que permite que su contenido sea accesible para su modificación. El script luego se centra en la primera página del documento, filtrando todas las anotaciones y seleccionando solo aquellas de tipo enlace, que normalmente representan áreas clicables o hipervínculos. Para evitar errores de tipo y garantizar un manejo seguro, cada anotación se verifica con is_assignable y luego se convierte al tipo LinkAnnotation apropiado. Si el enlace está asociado a una GoToURIAction, lo que significa que apunta a una dirección web, el script actualiza esa URI para redirigir a los usuarios ahttps://www.aspose.com". Finalmente, después de que se hayan aplicado todos los cambios deseados, el documento modificado se guarda en la ruta de salida especificada. + +```python +import aspose.pdf as ap +import sys +from os import path +from aspose.pycore import cast, is_assignable + +def link_annotation_update_web_destination(infile, outfile): + document = ap.Document(infile) + link_annotations = [ + a + for a in document.pages[1].annotations + if (a.annotation_type == ap.annotations.AnnotationType.LINK) + ] + + for la in link_annotations: + if is_assignable(la, ap.annotations.LinkAnnotation): + annotation = cast(ap.annotations.LinkAnnotation, la) + if is_assignable(annotation.action, ap.annotations.GoToURIAction): + action = cast(ap.annotations.GoToURIAction, annotation.action) + action.uri = "https://www.aspose.com" + document.save(outfile) +``` + +## Temas relacionados de enlaces + +- [Trabajar con enlaces PDF en Python](/pdf/es/python-net/links/) +- [Crear enlaces PDF en Python](/pdf/es/python-net/create-links/) +- [Extraer enlaces PDF en Python](/pdf/es/python-net/extract-links/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/pdf-file-metadata/_index.md b/es/python-net/advanced-operations/pdf-file-metadata/_index.md new file mode 100644 index 000000000..354eb677e --- /dev/null +++ b/es/python-net/advanced-operations/pdf-file-metadata/_index.md @@ -0,0 +1,147 @@ +--- +title: Trabajar con metadatos de archivos PDF en Python +linktitle: Metadatos de archivos PDF +type: docs +weight: 200 +url: /es/python-net/pdf-file-metadata/ +description: Aprenda cómo extraer, actualizar y administrar los metadatos de archivos PDF y las propiedades XMP en Python usando Aspose.PDF. +lastmod: "2026-04-15" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Obtenga y establezca la información del documento PDF y los metadatos XMP en Python +Abstract: Este artículo explica cómo trabajar con los metadatos de PDF en Aspose.PDF for Python via .NET. Aprenda cómo leer la información del documento, como autor, título y palabras clave, actualizar las propiedades del archivo, establecer campos de metadatos XMP y registrar prefijos de metadatos personalizados para archivos PDF en Python. +--- + +Utilice esta guía cuando necesite inspeccionar las propiedades del documento, actualizar la información del archivo PDF para búsqueda o catalogación, o gestionar los metadatos XMP programáticamente en Python. + +## Obtener información del archivo PDF + +Este fragmento de código muestra cómo extraer metadatos de un documento PDF usando Aspose.PDF for Python via .NET. Al acceder a la propiedad info del objeto Document, recupera información clave como el autor, la fecha de creación, las palabras clave, la fecha de modificación, el asunto y el título. Esta funcionalidad es esencial para aplicaciones que requieren catalogación de documentos, optimización de búsquedas o validación de las propiedades del documento. + +1. Abra el archivo PDF usando la clase Document +1. Recupera los metadatos del documento a través de la propiedad info +1. Muestre la información de los metadatos. Imprima los campos de metadatos deseados + +```python +import aspose.pdf as ap +import datetime +import sys +from os import path + +def get_pdf_file_information(infile): + # Open PDF document + document = ap.Document(infile) + + # Get document information + doc_info = document.info + + # Display document information + print(f"Author: {doc_info.author}") + print(f"Creation Date: {doc_info.creation_date}") + print(f"Keywords: {doc_info.keywords}") + print(f"Modify Date: {doc_info.mod_date}") + print(f"Subject: {doc_info.subject}") + print(f"Title: {doc_info.title}") +``` + +## Establecer información del archivo PDF + +Aspose.PDF for Python via .NET le permite establecer información específica del archivo para un PDF, información como autor, fecha de creación, tema y título. Para establecer esta información: + +1. Abra el archivo PDF usando la clase Document. +1. Cree un [DocumentInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/documentinfo/) objeto y establezca las propiedades de metadatos deseadas. +1. Guarde los cambios en un nuevo archivo PDF usando el método save. + +El siguiente fragmento de código le muestra cómo establecer la información del archivo PDF. + +```python +import aspose.pdf as ap +import datetime +import sys +from os import path + +def set_file_information(infile, outfile): + + # Open PDF document + document = ap.Document(infile) + + # Specify document information + doc_info = ap.DocumentInfo(document) + doc_info.author = "Aspose" + doc_info.creation_date = datetime.datetime.now() + doc_info.keywords = "Aspose.Pdf, DOM, API" + doc_info.mod_date = datetime.datetime.now() + doc_info.subject = "PDF Information" + doc_info.title = "Setting PDF Document Information" + doc_info.producer = "Custom producer" + doc_info.creator = "Custom creator" + + # Save PDF document + document.save(outfile) +``` + +## Establecer metadatos XMP en un archivo PDF + +Este fragmento de código demuestra cómo establecer o actualizar programáticamente los metadatos XMP en un documento PDF usando Aspose.PDF for Python via .NET. Al modificar propiedades como xmp:CreateDate, xmp:Nickname y campos definidos por el usuario, puedes incrustar metadatos estandarizados en tus archivos PDF. Este enfoque es particularmente útil para mejorar la organización de documentos, facilitar la búsqueda e incrustar información esencial directamente en el archivo. + +Aspose.PDF le permite establecer metadatos en un archivo PDF. Para establecer metadatos: + +1. Abra el archivo PDF usando el [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase. +1. Modifique los metadatos XMP asignando valores a claves específicas. +1. Guarde el documento PDF actualizado. + +El siguiente fragmento de código le muestra cómo establecer metadatos en un archivo PDF. + +```python +import aspose.pdf as ap +import datetime +import sys +from os import path + +def set_xmp_metadata(infile, outfile): + # Open PDF document + document = ap.Document(infile) + + # Set XMP metadata properties + document.metadata.add("xmp:CreateDate", datetime.datetime.now().isoformat()) + document.metadata.add("xmp:Nickname", "Nickname") + document.metadata.add("xmp:CustomProperty", "Custom Value") + + # Save the updated PDF document + document.save(outfile) +``` + +## Insertar metadatos con prefijo + +Algunos desarrolladores necesitan crear un nuevo espacio de nombres de metadatos con un prefijo. El siguiente fragmento de código muestra cómo insertar metadatos con prefijo. + +```python +import aspose.pdf as ap +import datetime +import sys +from os import path + +def set_prefix_metadata(infile, outfile): + # Open PDF document + document = ap.Document(infile) + + # Register a namespace URI for the 'xmp' prefix + document.metadata.register_namespace_uri("xmp", "http://ns.adobe.com/xap/1.0/") + + # Set the metadata property using the registered prefix + document.metadata.add( + "xmp:ModifyDate", datetime.datetime.now().isoformat() + ) # ISO 8601 format + + # Save the updated PDF document + document.save(outfile) +``` + +## Temas relacionados + +- [Operaciones avanzadas de PDF en Python](/pdf/es/python-net/advanced-operations/) +- [Trabajar con documentos PDF en Python](/pdf/es/python-net/working-with-documents/) +- [Trabajar con archivos adjuntos PDF en Python](/pdf/es/python-net/attachments/) +- [Comparar documentos PDF en Python](/pdf/es/python-net/compare-pdf-documents/) diff --git a/es/python-net/advanced-operations/securing-and-signing/_index.md b/es/python-net/advanced-operations/securing-and-signing/_index.md new file mode 100644 index 000000000..b5c057fe5 --- /dev/null +++ b/es/python-net/advanced-operations/securing-and-signing/_index.md @@ -0,0 +1,41 @@ +--- +title: Proteger y firmar archivos PDF en Python +linktitle: Protección y firma en PDF +type: docs +weight: 210 +url: /es/python-net/securing-and-signing/ +description: Aprenda a firmar, cifrar, descifrar y proteger archivos PDF en Python, incluidas firmas digitales, tarjetas inteligentes y permisos de documentos. +lastmod: "2026-04-15" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Firme, cifre, descifre y proteja documentos PDF en Python +Abstract: Esta sección explica cómo proteger y firmar documentos PDF usando Aspose.PDF for Python via .NET. Aprenda cómo aplicar firmas digitales, usar tarjetas inteligentes y certificados, extraer información de firmas y gestionar el cifrado de PDF, contraseñas y privilegios de acceso en Python. +--- + +Esta sección explica cómo aplicar de forma segura firmas digitales a documentos PDF usando Python Library. Mientras que los términos firma electrónica y firma digital a veces se usan indistintamente, no son lo mismo. Una firma digital está respaldada por un [autoridad certificadora](https://en.wikipedia.org/wiki/Certificate_authority), proporcionando un sello de confianza que protege el documento contra la manipulación. En contraste, una firma electrónica se utiliza típicamente para indicar la intención de una persona de firmar un documento, sin el mismo nivel de validación de seguridad. + +Utilice estas guías cuando necesite proteger el contenido de PDF, controlar los permisos del documento, verificar la confianza o aplicar firmas basadas en certificados en flujos de trabajo de Python. + +## Tareas de seguridad y firma cubiertas + +Aspose.PDF admite firmas digitales: + +- PKCS1 con algoritmo de firma RSA y resumen SHA-1. +- PKCS7 con algoritmo de firma RSA y resumen SHA-1. +- PKCS7 separado con algoritmos de firma DSA, RSA y ECDSA. Los algoritmos de resumen admitidos dependen del algoritmo de firma. +- Firma de sello de tiempo. + +Algoritmos de resumen para PKCS7 separado: + +- DSA - SHA-1. +- RSA - SHA-1, SHA-256, SHA-384, SHA-512. +- ECDSA - SHA-256, SHA-384, SHA-512, SHA3-256, SHA3-384, SHA3-512. + +Se recomienda evitar firmas digitales con el algoritmo de resumen SHA-1 debido a su inseguridad. + +- [Firmar digitalmente archivo PDF](/pdf/es/python-net/digitally-sign-pdf-file/) +- [Establecer privilegios, cifrar y descifrar archivo PDF](/pdf/es/python-net/set-privileges-encrypt-and-decrypt-pdf-file/) +- [Extraer información de imagen y firma](/pdf/es/python-net/extract-image-and-signature-information/) +- [Firmar documento PDF desde tarjeta inteligente](/pdf/es/python-net/sign-pdf-document-from-smart-card/) diff --git a/es/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md b/es/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md new file mode 100644 index 000000000..bee048468 --- /dev/null +++ b/es/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md @@ -0,0 +1,232 @@ +--- +title: Agregar firma digital o firmar digitalmente PDF en Python +linktitle: Firmar PDF digitalmente +type: docs +weight: 10 +url: /es/python-net/digitally-sign-pdf-file/ +description: Aprenda a firmar digitalmente documentos PDF, agregar marcas de tiempo y validar firmas en Python. +lastmod: "2026-04-15" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Firme digitalmente archivos PDF con Python +Abstract: Esta guía explica cómo firmar digitalmente documentos PDF utilizando Aspose.PDF for Python via .NET. Detalla el proceso de aplicar firmas digitales estándar y avanzadas, utilizando certificados (PFX y PKCS#12), y personalizando la apariencia y el comportamiento de la firma. La documentación incluye ejemplos de código que demuestran cómo firmar PDFs existentes, agregar marcas de tiempo y verificar la validez de la firma. Esto permite a los desarrolladores garantizar la autenticidad, integridad y el cumplimiento de los estándares de firma digital en sus aplicaciones Python. +--- + +## Firmar PDF con firmas digitales + +```python +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def sign_document(infile: str, outfile: str, pfxfile: str) -> None: + """Sign a PDF document with a PKCS#7 certificate.""" + with ap.Document(infile) as document: + with ap.facades.PdfFileSignature(document) as signature: + pkcs = ap.forms.PKCS7(pfxfile, "12345") + signature.sign(1, True, drawing.Rectangle(300, 100, 400, 200), pkcs) + signature.save(outfile) +``` + +Una **firma PKCS#7 separada** agrega una firma digital a un documento sin incrustar el contenido en el bloque de firma. + +Utilice estos ejemplos cuando necesite aplicar firmas basadas en certificados a archivos PDF, verificar la validez de la firma o agregar marcas de tiempo confiables a documentos firmados. + +El siguiente ejemplo firma un documento PDF usando una firma digital PKCS#7 separada, aplicando la firma a la primera página en una zona rectangular especificada. + +```python +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def sign_document_PKCS7_detached( + infile: str, + outfile: str, + pfxfile: str, + password: str, +) -> None: + """Sign a PDF document with a detached PKCS#7 certificate.""" + with ap.Document(infile) as document: + with ap.facades.PdfFileSignature(document) as signature: + pkcs = ap.forms.PKCS7Detached( + pfxfile, + password, + ap.DigestHashAlgorithm.SHA256, + ) + signature.sign(1, True, drawing.Rectangle(300, 100, 400, 200), pkcs) + signature.save(outfile) +``` + +**Verificar todas las firmas digitales en un documento PDF** + +1. Crea una instancia de PdfFileSignature que le permite interactuar con firmas en PDF. +1. Obtener una lista de nombres de firma `get_signature_names(True)`. +1. Comprueba la primera firma en la lista `verify_signature` para el cumplimiento del certificado especificado. + +```python +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def verify(infile: str) -> None: + """Verify all digital signatures in a PDF document.""" + with ap.Document(infile) as document: + with ap.facades.PdfFileSignature(document) as signature: + for signature_name in signature.get_signature_names(True): + if not signature.verify_signature(signature_name): + raise Exception("Not verified") +``` + +**Verificar una firma con un archivo de certificado de clave pública** + +```python +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def verify_with_public_key_certificate1(certificate: str, infile: str) -> None: + """Verify a signature with a public key certificate file.""" + with ap.facades.PdfFileSignature(infile) as file_sign: + signature_names = file_sign.get_signature_names(True) + with open(certificate, "rb") as file_stream: + certificate_bytes = file_stream.read() + print(file_sign.verify_signature(signature_names[0], certificate_bytes)) +``` + +**Verificar una firma con el certificado extraído del archivo** + +```python +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def verify_with_public_key_certificate_from_signature(infile: str) -> None: + """Verify a signature with the certificate extracted from the file.""" + with ap.facades.PdfFileSignature(infile) as file_sign: + signature_names = file_sign.get_signature_names(True) + certificate = [] + if file_sign.try_extract_certificate(signature_names[0], certificate): + print(file_sign.verify_signature(signature_names[0], certificate[0])) + else: + print(False) +``` + +**Verificar firmas con validación de cadena de certificados habilitada** + +```python +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def verify_signature_with_certificate_check(infile: str) -> None: + """Verify signatures with certificate-chain validation enabled.""" + with ap.Document(infile) as document: + with ap.facades.PdfFileSignature(document) as signature: + for signature_name in signature.get_signature_names(True): + options = ap.security.ValidationOptions() + options.validation_mode = ap.security.ValidationMode.STRICT + options.validation_method = ap.security.ValidationMethod.AUTO + options.check_certificate_chain = True + options.request_timeout = 20000 + validation_result = [] + verified = signature.verify_signature( + signature_name, + options, + validation_result, + ) + print(f"Certificate validation result: {validation_result[0].status}") + print(f"Is verified: {verified}") +``` + +## Agregar marca de tiempo a la firma digital + +### Cómo firmar digitalmente un PDF con sello de tiempo + +Aspose.PDF for Python permite firmar digitalmente el PDF con un servidor de marca de tiempo o un servicio web. + +Para cumplir con este requisito, el [Configuración de marca de tiempo](https://reference.aspose.com/pdf/python-net/aspose.pdf/timestampsettings/) Se ha añadido una clase al espacio de nombres Aspose.PDF. Por favor, consulte el siguiente fragmento de código que obtiene la marca de tiempo y la añade al documento PDF: + +```python +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def sign_with_time_stamp_server( + infile: str, + outfile: str, + pfxfile: str, + password: str, +) -> None: + """Sign a PDF document and apply a timestamp from an external server.""" + with ap.Document(infile) as document: + with ap.facades.PdfFileSignature(document) as signature: + pkcs = ap.forms.PKCS7(pfxfile, password) + pkcs.timestamp_settings = ap.TimestampSettings( + "https://freetsa.org/tsr", + "", + ap.DigestHashAlgorithm.SHA256, + ) + rect = drawing.Rectangle(100, 100, 200, 100) + signature.sign( + 1, "Signature Reason", "Contact", "Location", True, rect, pkcs + ) + signature.save(outfile) +``` + +## Firmar documentos PDF usando ECDSA + +Firmar documentos PDF usando ECDSA (Elliptic Curve Digital Signature Algorithm) implica utilizar criptografía de curva elíptica para generar firmas digitales. + +El fragmento de código anterior ilustra cómo aplicar una firma digital PKCS#7 separada a un documento PDF usando Aspose.PDF for Python. Al cargar el documento, configurar la apariencia de la firma y los ajustes de seguridad, y guardar el resultado, este ejemplo demuestra un flujo de trabajo completo y fiable para firmar digitalmente archivos PDF. + +Este método garantiza la autenticidad e integridad del documento al incrustar una firma segura y verificable en la primera página. El uso de SHA-256 como algoritmo de resumen cumple con los estándares criptográficos modernos, mientras que la capacidad de controlar la ubicación de la firma ofrece flexibilidad para marcas de aprobación visibles. + +```python +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def sign_ecdsa(infile: str, outfile: str, pfxfile: str, password: str) -> None: + """Sign a PDF document with an ECDSA signature.""" + with ap.Document(infile) as document: + with ap.facades.PdfFileSignature(document) as signature: + pkcs = ap.forms.PKCS7Detached( + pfxfile, + password, + ap.DigestHashAlgorithm.SHA256, + ) + signature.sign(1, True, drawing.Rectangle(300, 100, 400, 200), pkcs) + signature.save(outfile) +``` + +**Verificar firmas ECDSA en un documento PDF** + +```python +def verify_ecdsa(infile: str) -> None: + """Verify ECDSA signatures in a PDF document.""" + with ap.Document(infile) as document: + with ap.facades.PdfFileSignature(document) as signature: + if not signature.contains_signature(): + raise Exception("Not contains signature") + + for signature_name in signature.get_signature_names(True): + if not signature.verify_signature(signature_name): + raise Exception("Not verified") +``` + +## Temas de Seguridad Relacionados + +- [Protege y firma archivos PDF en Python](/pdf/es/python-net/securing-and-signing/) +- [Extraer información de imágenes y firmas en Python](/pdf/es/python-net/extract-image-and-signature-information/) +- [Firmar documentos PDF desde una tarjeta inteligente en Python](/pdf/es/python-net/sign-pdf-document-from-smart-card/) +- [Cifrar y descifrar archivos PDF en Python](/pdf/es/python-net/set-privileges-encrypt-and-decrypt-pdf-file/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md b/es/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md new file mode 100644 index 000000000..2d38bd6fb --- /dev/null +++ b/es/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md @@ -0,0 +1,170 @@ +--- +title: Extraer información de la firma del PDF en Python +linktitle: Extraer detalles de la firma +type: docs +weight: 20 +url: /es/python-net/extract-image-and-signature-information/ +description: Aprenda cómo extraer imágenes de firmas, certificados y detalles de firmas digitales de archivos PDF en Python. +lastmod: "2026-04-15" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Extraiga imágenes de firmas y detalles de certificados de PDFs en Python +Abstract: Este artículo explica cómo extraer información de imágenes y firmas digitales de documentos PDF utilizando Aspose.PDF for Python. Aprenda cómo recuperar imágenes de firmas, extraer datos de certificados, inspeccionar algoritmos de firma y detectar firmas comprometidas en archivos PDF firmados. +--- + +## Extraer imagen de un campo de firma + +Aspose.PDF for Python via .NET le permite recuperar la imagen visual incrustada en un [CampoDeFirma](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/signaturefield/). Esto es útil cuando necesitas mostrar o archivar la apariencia de la firma sin renderizar el PDF completo. + +El ejemplo a continuación itera sobre todos los campos de formulario, encontrando cada uno `SignatureField`, y guarda su imagen como un archivo JPEG: + +```python +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def extract_images_from_signature_field(infile: str, outfile: str) -> None: + """Extract the image stored in a signature field.""" + with ap.Document(infile) as document: + for field in document.form: + if not isinstance(field, ap.forms.SignatureField): + continue + + image_stream = field.extract_image() + if image_stream is None: + continue + + image = drawing.Bitmap.from_stream(image_stream) + image.save(outfile, drawing.imaging.ImageFormat.jpeg) +``` + +## Leer detalles del algoritmo de firma + +Usar `PdfFileSignature.get_signatures_info()` leer los metadatos criptográficos de cada firma en un documento — incluyendo el algoritmo de resumen, el tipo de algoritmo, la norma criptográfica y el nombre de la firma: + +```python +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def get_signatures_info(infile: str) -> None: + """Print information about all signatures in a PDF document.""" + with ap.Document(infile) as document: + with ap.facades.PdfFileSignature(document) as signature: + for signature_info in signature.get_signatures_info(): + print(signature_info.DIGEST_HASH_ALGORITHM) + print(signature_info.ALGORITHM_TYPE) + print(signature_info.CRYPTOGRAPHIC_STANDARD) + print(signature_info.signature_name) +``` + +## Extraer un certificado digital de un campo de firma + +Usa el [extract_certificate](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/signaturefield/#methods) método en un `SignatureField` para recuperar el certificado incrustado como un flujo de bytes y guardarlo en disco para validación externa: + +```python +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def extract_certificate(infile: str, outfile: str) -> None: + """Extract a certificate from a signature field and save it to disk.""" + with ap.Document(infile, password="owner") as document: + for field in document.form: + if not isinstance(field, ap.forms.SignatureField): + continue + + certificate_stream = field.extract_certificate() + if certificate_stream is None: + continue + + with certificate_stream: + bytes_data = bytearray(certificate_stream.length) + certificate_stream.read(bytes_data, 0, len(bytes_data)) + with open(outfile, "wb") as file_stream: + file_stream.write(bytes_data) + return +``` + +## Extraer certificados usando la fachada PdfFileSignature + +`PdfFileSignature.try_extract_certificate()` proporciona una forma alternativa de obtener certificados por nombre de firma. El siguiente ejemplo itera sobre todos los nombres de firma e intenta la extracción para cada uno: + +```python +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def extract_certificate_try_extract_certificate_method(infile: str) -> None: + """Extract certificates with the try_extract_certificate facade method.""" + with ap.Document(infile, password="owner") as document: + with ap.facades.PdfFileSignature(document) as signature: + for signature_name in signature.get_signature_names(True): + certificate = [] + if signature.try_extract_certificate(signature_name, certificate): + print("The certificate extraction succeeded") +``` + +## Verificar firmas digitales externas + +Para confirmar que un documento no ha sido modificado después de firmarlo, verifique cada firma externa usando `PdfFileSignature.verify_signature()`. El ejemplo a continuación genera una excepción para cualquier firma que falle la verificación: + +```python +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def verify_external_signature(infile: str) -> None: + """Verify an external signature in a PDF document.""" + with ap.Document(infile) as document: + with ap.facades.PdfFileSignature(document) as pdf_signature: + for signature_name in pdf_signature.get_signature_names(True): + if not pdf_signature.verify_signature(signature_name): + raise Exception("Not verified") +``` + +## Detectar firmas comprometidas + +`SignaturesCompromiseDetector` verifica si alguna firma digital en un documento ha sido invalidada por cambios posteriores. Utilízalo en flujos de trabajo legales, financieros o de cumplimiento donde se debe garantizar la integridad del documento. + +El siguiente ejemplo verifica firmas comprometidas y reporta sus nombres junto con la cobertura total de firmas del documento: + +```python +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def check(infile: str) -> None: + """Check whether a PDF contains compromised signatures.""" + with ap.Document(infile) as document: + detector = ap.SignaturesCompromiseDetector(document) + result = [] + + if detector.check(result): + print("No signature compromise detected") + return + + if result[0].has_compromised_signatures: + print( + f"Count of compromised signatures: {len(result[0].COMPROMISED_SIGNATURES)}" + ) + for signature_name in result[0].COMPROMISED_SIGNATURES: + print(f"Signature name: {signature_name.FULL_NAME}") + + print(result[0].signatures_coverage) +``` + +## Temas de Seguridad Relacionados + +- [Protege y firma archivos PDF en Python](/pdf/es/python-net/securing-and-signing/) +- [Firmar digitalmente archivos PDF en Python](/pdf/es/python-net/digitally-sign-pdf-file/) +- [Firmar documentos PDF desde una tarjeta inteligente en Python](/pdf/es/python-net/sign-pdf-document-from-smart-card/) +- [Cifrar y descifrar archivos PDF en Python](/pdf/es/python-net/set-privileges-encrypt-and-decrypt-pdf-file/) diff --git a/es/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md b/es/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md new file mode 100644 index 000000000..a6d759cc2 --- /dev/null +++ b/es/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md @@ -0,0 +1,228 @@ +--- +title: Cifrar y descifrar archivos PDF en Python +linktitle: Cifrar y descifrar archivo PDF +type: docs +weight: 70 +url: /es/python-net/set-privileges-encrypt-and-decrypt-pdf-file/ +description: Aprende cómo establecer privilegios de PDF, encriptar archivos, descifrar PDFs protegidos y cambiar contraseñas en Python. +lastmod: "2026-04-15" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Establece permisos de PDF y gestiona el cifrado en Python. +Abstract: Esta página de documentación explica cómo establecer privilegios de documento, aplicar cifrado y descifrar archivos PDF usando Aspose.PDF for Python. Guía a los desarrolladores a través de la configuración de contraseñas de usuario y propietario, definiendo restricciones de acceso (como imprimir, copiar o editar). Los ejemplos de código ilustran cómo proteger contenido sensible y gestionar la seguridad de PDF de manera eficaz dentro de aplicaciones Python, garantizando un acceso controlado y la confidencialidad de los datos. +--- + +Gestionar la seguridad de documentos es esencial al trabajar con contenido sensible o crítico para el negocio. Aspose.PDF for Python via .NET ofrece una API robusta para aplicar encriptación de forma programática, controlar el acceso mediante permisos y descifrar archivos PDF protegidos. + +Este artículo guía a los desarrolladores de Python a través de ejemplos prácticos para establecer privilegios, aplicar y eliminar encriptación, cambiar contraseñas y detectar estados de protección — todo dentro de un flujo de trabajo de PDF. + +Aspose.PDF for Python via .NET brinda a los desarrolladores un control total sobre la seguridad de PDF: + +**Establecer privilegios** - Control de acceso granular mediante permisos. +**Cifrar archivo** - Aplicar cifrado AES o RC4 con contraseñas personalizadas. +**Desencriptar archivo** - Eliminar la seguridad usando la contraseña del propietario. +**Cambiar contraseñas** - Rotar o actualizar credenciales sin alterar el contenido. +**Inspect Security** - Detectar estado de cifrado o tipos de contraseña requeridos. + +Utilice esta página cuando necesite proteger documentos PDF con contraseñas, restringir la impresión o la copia, rotar credenciales o inspeccionar si un documento está cifrado. + +## Establecer privilegios en un archivo PDF existente + +Puede restringir o permitir operaciones específicas (p. ej., imprimir, copiar, rellenar formularios) asignando contraseñas de usuario y de propietario junto con privilegios de acceso. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def set_privileges_on_existing_pdf_file(infile: str, outfile: str) -> None: + """Set restricted privileges on an existing PDF document.""" + with ap.Document(infile) as document: + document_privilege = ap.facades.DocumentPrivilege.forbid_all + document_privilege.allow_screen_readers = True + document.encrypt( + "user", + "owner", + document_privilege, + ap.CryptoAlgorithm.AESx128, + False, + ) + document.save(outfile) +``` + +## Cifrar archivo PDF usando diferentes tipos y algoritmos de cifrado + +Cifrar un PDF asegura que solo los usuarios con credenciales válidas puedan abrir o modificar el archivo. + +>Términos clave: + +- Contraseña de usuario. Requerida para abrir el documento. + +- Contraseña del propietario. Necesaria para cambiar permisos o eliminar el cifrado. + +- KeySize. Use AE_SX128 para obtener la máxima seguridad en flujos de trabajo modernos. + +El siguiente fragmento de código le muestra cómo cifrar archivos PDF. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def encrypt_pdf_file(infile: str, outfile: str) -> None: + """Encrypt a PDF document with user and owner passwords.""" + with ap.Document(infile) as document: + document.encrypt( + "user", + "owner", + ap.Permissions.EXTRACT_CONTENT, + ap.CryptoAlgorithm.AESx128, + ) + document.save(outfile) +``` + +## Descifrar archivo PDF usando la contraseña del propietario + +Para eliminar la protección con contraseña y restaurar el acceso completo: + +1. Carga el PDF cifrado usando la contraseña correcta ('password' es la contraseña de usuario o de propietario). +1. Elimina toda la protección con contraseña y la configuración de cifrado del documento. +1. Guarda el PDF ahora sin protección en el archivo de salida especificado. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def decrypt_pdf_file(infile: str, outfile: str) -> None: + """Decrypt a password-protected PDF document.""" + with ap.Document(infile, "password") as document: + document.decrypt() + document.save(outfile) +``` + +## Cifrar y descifrar un PDF con certificados de clave pública + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def pub_sec_encryption( + crypto_algorithm, + pub_cert: str, + in_pfx: str, + outfile: str, +) -> None: + """Demonstrate public-key encryption and decryption.""" + pfx_password = "12345" + + with ap.Document() as document: + document.info.title = "TestTitle" + document.info.author = "TestAuthor" + page = document.pages.add() + page.paragraphs.add(ap.text.TextFragment("Hello World!")) + + with open(pub_cert, "rb") as file_stream: + byte_content = file_stream.read() + + document.encrypt( + ap.Permissions.PRINT_DOCUMENT, + crypto_algorithm, + [byte_content], + ) + document.save(outfile) + + with ap.Document( + outfile, + ap.security.CertificateEncryptionOptions(pub_cert, in_pfx, pfx_password), + ) as document: + print(document.info.title) + print(document.info.author) + + text_absorber = ap.text.TextAbsorber() + document.pages[1].accept(text_absorber) + print(text_absorber.text) + + document.decrypt() + document.save(path.join(path.dirname(outfile), "pubsec_decrypted_out.pdf")) +``` + +## Cambiar la contraseña de un archivo PDF + +Actualizar las credenciales de seguridad (contraseñas de usuario y propietario) de un documento PDF mientras se preserva su contenido y estructura. + +1. Abre el PDF usando la contraseña de propietario existente ('owner'), lo que brinda acceso total, incluida la autorización para cambiar la configuración de seguridad. +1. Reemplaza las contraseñas antiguas con una nueva contraseña de usuario ('newuser') y una nueva contraseña de propietario ('newowner'). +1. Guarda el PDF con la configuración de contraseña actualizada. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def change_password(infile: str, outfile: str) -> None: + """Change the passwords of a password-protected PDF document.""" + with ap.Document(infile, "owner") as document: + document.change_passwords("owner", "newuser", "newowner") + document.save(outfile) +``` + +## Cómo - determinar si el PDF de origen está protegido con contraseña + +### Determinar la contraseña correcta del array + +En algunos escenarios, es posible que necesite identificar la contraseña correcta de una lista de candidatos potenciales para acceder a un PDF protegido. El fragmento de código a continuación demuestra cómo verificar si un archivo PDF está protegido con contraseña y luego intentar desbloquearlo iterando a través de una lista predefinida de contraseñas usando Aspose.PDF for Python via .NET. + +El proceso incluye: + +1. Usando PdfFileInfo para detectar si el PDF está encriptado. +1. Intenta abrir el PDF con cada contraseña usando ap.Document(). +1. Si tiene éxito, imprime el número de páginas. +1. Si no, captura la excepción y reporta la contraseña fallida. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def determine_correct_password_from_array(infile: str) -> None: + """Try a list of passwords until the document opens successfully.""" + with ap.facades.PdfFileInfo() as pdf_file_info: + pdf_file_info.bind_pdf(infile) + print(f"File is password protected {pdf_file_info.is_encrypted}") + + passwords = ["test", "test1", "test2", "test3", "sample"] + + for password in passwords: + try: + with ap.Document(infile, password) as document: + if len(document.pages) > 0: + print(f"Password = {password} is correct") + print(f"Number of pages in document = {len(document.pages)}") + break + except Exception: + print(f"Password = {password} is not correct") +``` + +## Temas de Seguridad Relacionados + +- [Protege y firma archivos PDF en Python](/pdf/es/python-net/securing-and-signing/) +- [Firmar digitalmente archivos PDF en Python](/pdf/es/python-net/digitally-sign-pdf-file/) +- [Extraer información de la firma del PDF en Python](/pdf/es/python-net/extract-image-and-signature-information/) +- [Firmar documentos PDF desde una tarjeta inteligente en Python](/pdf/es/python-net/sign-pdf-document-from-smart-card/) + diff --git a/es/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md b/es/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md new file mode 100644 index 000000000..10f77af8a --- /dev/null +++ b/es/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md @@ -0,0 +1,131 @@ +--- +title: Firmar documentos PDF desde una Smart Card en Python +linktitle: Firma de PDF con Smart Card +type: docs +weight: 30 +url: /es/python-net/sign-pdf-document-from-smart-card/ +description: Aprenda a firmar documentos PDF con tarjetas inteligentes y certificados externos en Python. +lastmod: "2026-04-15" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Firmar documentos PDF desde una Smart Card con Python +Abstract: Esta guía explica cómo firmar digitalmente documentos PDF usando una tarjeta inteligente con Aspose.PDF for Python via .NET. Demuestra cómo acceder a los certificados almacenados en dispositivos de hardware (como USB tokens o smart cards) a través del Windows Certificate Store y utilizarlos para firmar archivos PDF. La documentación incluye ejemplos de código que muestran cómo localizar el certificado adecuado, configurar las propiedades de la firma y incrustar la firma digital en el PDF. Esto permite una firma segura, respaldada por hardware, cumpliendo con los estándares de firma digital, adecuada para flujos de trabajo empresariales y legales de alta confianza. +--- + +Aspose.PDF ofrece capacidades robustas para integrar componentes de firma visual y criptográfica, garantizando tanto la autenticidad como una presentación profesional en documentos PDF firmados digitalmente. + +Utilice este flujo de trabajo cuando su proceso de firma dependa de certificados almacenados en dispositivos con soporte de hardware, como tarjetas inteligentes, tokens USB o almacenes de certificados gestionados. + +## Firmar con tarjeta inteligente usando campo de firma + +Este ejemplo muestra cómo firmar digitalmente un documento PDF utilizando un certificado externo con Aspose.PDF for Python y aplicar una imagen personalizada de apariencia de firma: + +1. Abriendo el documento PDF. +1. Creando un objeto PdfFileSignature y vinculándolo al documento. +1. Recuperando un certificado digital local mediante un método personalizado `get_local_certificate()`. +1. Configurando una ExternalSignature basada en el certificado seleccionado. +1. Aplicando una imagen de apariencia de firma personalizada (p.ej., un logotipo de la empresa o una firma manuscrita). +1. Firmando digitalmente la primera página del documento con metadatos especificados (razón, contacto, ubicación). +1. Guardando el documento firmado en un nuevo archivo de salida. + +Este método es ideal para casos en los que las firmas deben aplicarse programáticamente usando certificados externos—como tokens de hardware, almacenes de certificados o proveedores de confianza—y presentarse con un diseño visual personalizado. + +A continuación se muestran los fragmentos de código para firmar un documento PDF desde una tarjeta inteligente: + +```python +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def sign_with_smart_card(infile: str, outfile: str, pngfile: str) -> None: + """Sign a PDF document using a smart-card certificate.""" + with ap.Document(infile) as document: + with ap.facades.PdfFileSignature() as pdf_signature: + pdf_signature.bind_pdf(document) + external_signature = ap.forms.ExternalSignature(get_local_certificate()) + pdf_signature.signature_appearance = pngfile + pdf_signature.sign( + 1, + "Reason", + "Contact", + "Location", + True, + drawing.Rectangle(100, 100, 200, 200), + external_signature, + ) + pdf_signature.save(outfile) +``` + +## Verificar firmas digitales + +Este fragmento de código muestra cómo verificar firmas digitales en un documento PDF usando Aspose.PDF for Python: + +1. Abriendo el archivo PDF. +1. Crear un objeto 'PdfFileSignature' y vincularlo al documento. +1. Recuperar la lista de todos los nombres de campos de firma usando 'get_signature_names()'. +1. Iterar a través de cada firma y verificar su validez con 'verify_signature()'. +1. Lanzar una excepción si alguna firma no pasa la verificación. + +```python +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def verify_external_signature(infile: str) -> None: + """Verify an external signature in a PDF document.""" + with ap.Document(infile) as document: + with ap.facades.PdfFileSignature(document) as pdf_signature: + for signature_name in pdf_signature.get_signature_names(True): + if not pdf_signature.verify_signature(signature_name): + raise Exception("Not verified") +``` + +## Firmar con certificado externo + +Este fragmento de código muestra cómo agregar y firmar un campo de firma digital en un documento PDF usando Aspose.PDF for Python con un certificado externo: + +1. Abriendo el archivo PDF como un flujo binario. +1. Creando un SignatureField y colocándolo en la primera página del documento en una posición especificada. +1. Recuperando un certificado digital local mediante un método personalizado `get_local_certificate()`. +1. Configurando un ExternalSignature con metadatos como autoridad, motivo y información de contacto. +1. Asignando un nombre de campo único al campo de firma (partial_name = \"sig1\"). +1. Agregar el campo de firma a los campos del formulario del PDF. +1. Firmando el campo con el certificado externo. +1. Guardando el documento firmado en un archivo de salida. + +```python +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def get_signature_info_using_signature_field(infile: str, outfile: str) -> None: + """Create a signature field and sign it with an external certificate.""" + with open(infile, "rb+") as file_stream: + document = ap.Document(file_stream) + signature_field = ap.forms.SignatureField( + document.pages[1], + ap.Rectangle(100, 400, 10, 10, True), + ) + selected_certificate = get_local_certificate() + external_signature = ap.forms.ExternalSignature(selected_certificate) + external_signature.authority = "Me" + external_signature.reason = "Reason" + external_signature.contact_info = "Contact" + signature_field.partial_name = "sig1" + document.form.add(signature_field, 1) + signature_field.sign(external_signature) + document.save(outfile) +``` + +## Temas de Seguridad Relacionados + +- [Protege y firma archivos PDF en Python](/pdf/es/python-net/securing-and-signing/) +- [Firmar digitalmente archivos PDF en Python](/pdf/es/python-net/digitally-sign-pdf-file/) +- [Extraer información de la firma del PDF en Python](/pdf/es/python-net/extract-image-and-signature-information/) +- [Cifrar y descifrar archivos PDF en Python](/pdf/es/python-net/set-privileges-encrypt-and-decrypt-pdf-file/) + diff --git a/es/python-net/advanced-operations/working-with-documents/_index.md b/es/python-net/advanced-operations/working-with-documents/_index.md index 5ea6add7d..d022b7601 100644 --- a/es/python-net/advanced-operations/working-with-documents/_index.md +++ b/es/python-net/advanced-operations/working-with-documents/_index.md @@ -1,157 +1,33 @@ --- -title: Trabajando con Documentos PDF usando Python -linktitle: Trabajando con Documentos +title: Trabajar con documentos PDF en Python +linktitle: Trabajando con documentos type: docs weight: 10 url: /es/python-net/working-with-documents/ -description: Este artículo describe qué manipulaciones se pueden hacer con el documento con la biblioteca Aspose.PDF para Python a través de .NET. -lastmod: "2023-04-12" +description: Aprenda cómo crear, formatear, manipular, optimizar, combinar, dividir y administrar documentos PDF en Python. +lastmod: "2026-04-15" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Crear, formatear, combinar, dividir y optimizar documentos PDF en Python +Abstract: Esta sección explica cómo trabajar con documentos PDF usando Aspose.PDF for Python via .NET. Aprenda cómo crear archivos PDF, formatear propiedades del documento, manipular la estructura del contenido, optimizar el tamaño del archivo, combinar y dividir PDFs, y administrar capas de contenido opcional en flujos de trabajo de Python. --- - +Los archivos PDF están diseñados para el intercambio seguro y de alta calidad de documentos, sin importar qué software o sistema operativo se utilice para verlos. Pueden abrirse y visualizarse en muchos dispositivos y sistemas operativos, incluidos ordenadores, tabletas y teléfonos inteligentes. Hoy en día, dichos documentos pueden contener imágenes, tablas, varios elementos interactivos, etc. -Los archivos PDF están diseñados para el intercambio seguro y de alta calidad de documentos, sin importar qué software o sistema operativo se utilice para verlos. Se pueden abrir y ver en muchos dispositivos y sistemas operativos, incluidas computadoras, tabletas y teléfonos inteligentes. Hoy en día, dichos documentos pueden contener imágenes, tablas, varios elementos interactivos, etc. +Los documentos PDF pueden verse e imprimirse, pero no siempre es fácil editarlos. Sin embargo, el **Aspose.PDF for Python via .NET** le ayudará a afrontar incluso la tarea más difícil al trabajar con PDF. -Los documentos PDF se pueden ver e imprimir, pero no siempre se editan fácilmente. Sin embargo, la **Biblioteca Aspose.PDF para Python** te ayudará a enfrentar incluso la tarea más difícil al trabajar con PDF. +Utilice esta sección cuando necesite trabajar con flujos de trabajo de PDF de documento completo en Python, como crear archivos, validar normas, optimizar el tamaño, combinar varios PDFs o dividir documentos grandes en archivos más pequeños. -Puedes hacer lo siguiente: +## Tareas del documento cubiertas -- [Crear Documento PDF](/pdf/es/python-net/create-pdf-document/) - crear un documento PDF simple. -- [Formatear Documento PDF](/pdf/es/python-net/formatting-pdf-document/) - crear un documento, obtener y establecer propiedades del documento, incrustar fuentes y otras operaciones con archivos PDF. +Puede hacer lo siguiente: -- [Manipular Documento PDF](/pdf/es/python-net/manipulate-pdf-document/) - validar un documento PDF para el estándar PDF A, trabajar con TOC, establecer fecha de expiración del PDF, etc. -- [Optimizar PDF](/pdf/es/python-net/optimize-pdf/) - optimizar el contenido de la página, optimizar el tamaño del archivo, eliminar objetos no utilizados, comprimir todas las imágenes para una optimización exitosa del documento. -- [Unir PDF](/pdf/es/python-net/merge-pdf-documents/) - unir múltiples archivos PDF en un único documento PDF usando Python. -- [Dividir PDF](/pdf/es/python-net/split-document/) - dividir páginas PDF en archivos PDF individuales en tus aplicaciones de Python. -- [Trabajar con Encabezados](/pdf/es/python-net/working-with-headings/) - puedes crear numeración en el encabezado de tu documento PDF con Python. - - \ No newline at end of file +- [Crear documento PDF](/pdf/es/python-net/create-pdf-document/) - crear un documento PDF simple. +- [Formatear documento PDF](/pdf/es/python-net/formatting-pdf-document/) - crear un documento, obtener y establecer propiedades del documento, incrustar fuentes y otras operaciones con archivos PDF. +- [Manipular documento PDF](/pdf/es/python-net/manipulate-pdf-document/) - validar un documento PDF para el estándar PDF A, trabajar con TOC, establecer la fecha de vencimiento del PDF, etc. +- [Optimizar PDF](/pdf/es/python-net/optimize-pdf/) - optimizar el contenido de la página, optimizar el tamaño del archivo, eliminar objetos no usados, comprimir todas las imágenes para una optimización exitosa del documento. +- [Combinar PDF](/pdf/es/python-net/merge-pdf-documents/) - combinar varios archivos PDF en un único documento PDF usando Python. +- [Dividir PDF](/pdf/es/python-net/split-document/) - dividir páginas PDF en archivos PDF individuales en tus aplicaciones Python. +- [Trabajando con encabezados](/pdf/es/python-net/working-with-headings/) - puedes crear numeración en el encabezado de tu documento PDF con Python. diff --git a/es/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md b/es/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md index 24bdb1d81..7be4cef7e 100644 --- a/es/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md +++ b/es/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md @@ -1,103 +1,94 @@ --- -title: Cómo Crear PDF usando Python -linktitle: Crear Documento PDF +title: Crear archivos PDF en Python +linktitle: Crear documento PDF type: docs weight: 10 url: /es/python-net/create-pdf-document/ -description: Crear y dar formato al Documento PDF con Aspose.PDF para Python a través de .NET. -lastmod: "2023-04-12" +description: Aprenda cómo crear archivos PDF y generar PDFs buscables en Python usando Aspose.PDF for Python via .NET. +lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Crear archivo PDF con Python +Abstract: Aspose.PDF for Python via .NET es una API versátil diseñada para que los desarrolladores manipulen archivos PDF dentro de aplicaciones Python dirigidas al framework .NET. Permite a los usuarios crear, cargar, modificar y convertir documentos PDF sin esfuerzo. Este artículo proporciona una guía paso a paso para crear un archivo PDF simple usando Aspose.PDF. El proceso implica inicializar un `Document` object, añadir una `Page` al documento, insertar un `TextFragment` en los párrafos de la página, y guardar el archivo como PDF. El fragmento de código Python incluido demuestra estos pasos creando un documento PDF que contiene el texto "Hello World!". Esta API simplifica la manipulación de PDF con código mínimo, mejorando la productividad de los desarrolladores que trabajan con PDFs en entornos .NET. --- - - - -**Aspose.PDF para Python a través de .NET** es una API de manipulación de PDF que permite a los desarrolladores crear, cargar, modificar y convertir archivos PDF directamente desde aplicaciones de Python para .NET con solo unas pocas líneas de código. - -## Cómo Crear un Archivo PDF Simple - -Para crear un PDF usando Python a través de .NET con Aspose.PDF, puedes seguir estos pasos: - -1. Crear un objeto de la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) -1. Agregar un objeto [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) a la colección [pages](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties) del objeto Document -1. Agregar [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/) a la colección [paragraphs](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) de la página + +**Aspose.PDF for Python via .NET** es una API de manipulación de PDF que permite a los desarrolladores crear, cargar, modificar y convertir archivos PDF directamente desde Python para aplicaciones .NET con solo unas pocas líneas de código. + +Utiliza estos ejemplos cuando necesites generar nuevos archivos PDF desde cero o convertir la salida de OCR en documentos PDF buscables en Python. + +## Cómo crear un archivo PDF simple + +Para crear un PDF usando Python vía .NET con Aspose.PDF, puedes seguir estos pasos: + +1. Crear un objeto de [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase +1. Añadir un [Página](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) objeto al [páginas](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties) colección del objeto Document +1. Agregar [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/) a [párrafos](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) colección de la página 1. Guardar el documento PDF resultante ```python +import sys +from os import path +import aspose.pdf as ap - import aspose.pdf as ap - - # Inicializar objeto de documento +def create_new_document(output_pdf): + """Create a simple PDF with a single “Hello World!” page.""" document = ap.Document() - # Agregar página page = document.pages.add() - # Agregar texto a la nueva página - page.paragraphs.add(ap.text.TextFragment("¡Hola Mundo!")) - # Guardar PDF actualizado + page.paragraphs.add(ap.text.TextFragment("Hello World!")) document.save(output_pdf) -``` \ No newline at end of file +``` + +## Cómo crear un documento PDF buscable + +Aspose.PDF for Python via .NET permite crear y manipular documentos PDF existentes. Al agregar elementos de texto a un archivo PDF, el PDF resultante es buscable. Sin embargo, al convertir una imagen que contiene texto a un archivo PDF, el contenido del PDF resultante no es buscable. Como solución alternativa, podemos aplicar OCR al archivo resultante para que se vuelva buscable. + +El siguiente es el código completo para cumplir con este requisito: + +1. Cargue el PDF usando 'ap.Document'. +1. Configurar la resolución de renderizado. +1. Usar 'PngDevice.process' para convertir la página PDF seleccionada en una imagen. +1. Ejecutar OCR en la imagen generada. +1. Crear un nuevo PDF a partir de la salida de OCR. +1. Guardar el PDF buscable. + +```python +import aspose.pdf as ap +import io + +# Requires: pip install pytesseract +# Also ensure the Tesseract OCR engine is installed and available on your system PATH. +import pytesseract +from pathlib import Path + + +# Path to the source PDF +input_pdf_path = "input.pdf" +# Path for the temporary image +temp_image_path = "temp_image.png" +# Path for the searchable PDF +output_pdf_path = "output_searchable.pdf" +page_number = 1 +image_stream = io.FileIO(temp_image_path, "w") +try: + document = ap.Document(input_pdf_path) + resolution = ap.devices.Resolution(300) + png_device = ap.devices.PngDevice(resolution) + png_device.process(document.pages[page_number], image_stream) + image_stream.close() + pdf = pytesseract.image_to_pdf_or_hocr(temp_image_path, extension="pdf") + document = ap.Document(io.BytesIO(pdf)) + document.save(output_pdf_path) +finally: + image_file = Path(temp_image_path) + image_file.unlink(missing_ok=True) +``` + +## Temas de documentos relacionados + +- [Trabajar con documentos PDF en Python](/pdf/es/python-net/working-with-documents/) +- [Formatear documentos PDF en Python](/pdf/es/python-net/formatting-pdf-document/) +- [Manipular documentos PDF en Python](/pdf/es/python-net/manipulate-pdf-document/) +- [Optimizar archivos PDF en Python](/pdf/es/python-net/optimize-pdf/) + diff --git a/es/python-net/advanced-operations/working-with-documents/formatting-pdf-document/_index.md b/es/python-net/advanced-operations/working-with-documents/formatting-pdf-document/_index.md index 5eb6d2abd..df1d1fda2 100644 --- a/es/python-net/advanced-operations/working-with-documents/formatting-pdf-document/_index.md +++ b/es/python-net/advanced-operations/working-with-documents/formatting-pdf-document/_index.md @@ -1,389 +1,256 @@ --- -title: Formateo de Documento PDF usando Python -linktitle: Formateo de Documento PDF +title: Formatear documentos PDF en Python +linktitle: Formatear documento PDF type: docs weight: 11 url: /es/python-net/formatting-pdf-document/ -description: Crear y formatear el Documento PDF con Aspose.PDF para Python vía .NET. Use el siguiente fragmento de código para resolver sus tareas. -lastmod: "2023-04-12" +description: Aprenda cómo formatear documentos PDF, incrustar fuentes, controlar la configuración del visor y ajustar las opciones de visualización en Python. +lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Formateo de documentos PDF usando Python +Abstract: El artículo proporciona una guía completa sobre la manipulación y el formato de documentos PDF utilizando la biblioteca Aspose.PDF en Python. Cubre varios aspectos de la personalización de PDF, incluido el ajuste de la ventana del documento y las propiedades de visualización de página, como centrar la ventana, la dirección de lectura y ocultar elementos de la interfaz de usuario. El artículo explica cómo obtener y establecer estas propiedades programáticamente usando la clase `Document`. Además, aborda la gestión de fuentes, detallando cómo incrustar fuentes Standard Type 1 y otras fuentes en los PDFs, asegurando la portabilidad del documento y la consistencia visual entre sistemas. También destaca técnicas para establecer un nombre de fuente predeterminado, recuperar todas las fuentes de un PDF y mejorar la incrustación de fuentes usando `FontSubsetStrategy`. Asimismo, el artículo profundiza en el ajuste del factor de zoom de los documentos PDF mediante la clase `GoToAction` y la configuración de propiedades predefinidas del cuadro de diálogo de impresión, incluidas las opciones de impresión a doble cara. Los fragmentos de código acompañan a cada sección, proporcionando ejemplos prácticos para implementar estas funcionalidades. --- - - - -## Formateo de Documento PDF - -### Obtener Propiedades de la Ventana del Documento y de la Visualización de Páginas - -Este tema te ayuda a entender cómo obtener las propiedades de la ventana del documento, la aplicación de visualización y cómo se muestran las páginas. Para establecer estas propiedades: - -Abre el archivo PDF usando la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). Ahora, puedes establecer las propiedades del objeto Document, tales como - -- CenterWindow – Centrar la ventana del documento en la pantalla. Por defecto: falso. -- Direction – Orden de lectura. Esto determina cómo se disponen las páginas cuando se muestran lado a lado. Por defecto: de izquierda a derecha. -- DisplayDocTitle – Mostrar el título del documento en la barra de título de la ventana del documento. Por defecto: falso (el título se muestra). -- HideMenuBar – Ocultar o mostrar la barra de menú de la ventana del documento. Por defecto: falso (la barra de menú se muestra). -- HideToolBar – Ocultar o mostrar la barra de herramientas de la ventana del documento. Por defecto: falso (la barra de herramientas se muestra). -- HideWindowUI – Ocultar o mostrar elementos de la ventana del documento como las barras de desplazamiento. - Default: false (se muestran los elementos de la interfaz de usuario). -- NonFullScreenPageMode – Cómo se muestra el documento cuando no está en modo de pantalla completa. -- PageLayout – El diseño de la página. -- PageMode – Cómo se muestra el documento cuando se abre por primera vez. Las opciones son mostrar miniaturas, pantalla completa, mostrar panel de adjuntos. - -El siguiente fragmento de código te muestra cómo obtener las propiedades usando la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). - -```python - - import aspose.pdf as ap - - # Abrir documento - document = ap.Document(input_pdf) - # Obtener diferentes propiedades del documento - # Posición de la ventana del documento - Predeterminado: falso - print("CenterWindow :", document.center_window) +Esta guía es útil cuando necesitas controlar el comportamiento del visor PDF, la incrustación de fuentes, la configuración de visualización predeterminada o las preferencias de impresión en documentos generados con Python. - # Orden de lectura predominante; determina la posición de la página - # Cuando se muestra lado a lado - Predeterminado: L2R - print("Direction :", document.direction) +## Formatear documento PDF - # Si la barra de título de la ventana debe mostrar el título del documento - # Si es falso, la barra de título muestra el nombre del archivo PDF - Predeterminado: falso - print("DisplayDocTitle :", document.display_doc_title) +### Obtener propiedades de ventana del documento y de visualización de página - # Si se redimensiona la ventana del documento para ajustarse al tamaño de - # La primera página mostrada - Predeterminado: falso - print("FitWindow :", document.fit_window) +Este tema le ayuda a comprender cómo obtener las propiedades de la ventana del documento, la aplicación del visor y cómo se muestran las páginas. Para establecer estas propiedades: - # Si se oculta la barra de menú de la aplicación del visor - Predeterminado: falso - print("HideMenuBar :", document.hide_menubar) +Abra el archivo PDF usando el [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase. Ahora, puedes establecer las propiedades del objeto Document, como - # Si se oculta la barra de herramientas de la aplicación del visor - Predeterminado: falso - print("HideToolBar :", document.hide_tool_bar) +- CenterWindow – Centrar la ventana del documento en la pantalla. Predeterminado: false. +- Dirección – Orden de lectura. Esto determina cómo se disponen las páginas cuando se muestran una al lado de la otra. Predeterminado: de izquierda a derecha. +- DisplayDocTitle – Mostrar el título del documento en la barra de título de la ventana del documento. Predeterminado: false (el título se muestra). +- HideMenuBar – Ocultar o mostrar la barra de menús de la ventana del documento. Predeterminado: false (la barra de menús se muestra). +- HideToolBar – Ocultar o mostrar la barra de herramientas de la ventana del documento. Predeterminado: false (la barra de herramientas se muestra). +- HideWindowUI – Ocultar o mostrar los elementos de la ventana del documento, como las barras de desplazamiento. Predeterminado: false (los elementos de la UI se muestran). +- NonFullScreenPageMode – Cómo se muestra el documento cuando no está en modo de pantalla completa. +- PageLayout – El diseño de página. +- PageMode – Cómo se muestra el documento al abrirlo por primera vez. Las opciones son mostrar miniaturas, pantalla completa, mostrar el panel de adjuntos. - # Si se ocultan elementos de la interfaz de usuario como barras de desplazamiento - # Y solo se muestran los contenidos de la página - Predeterminado: falso - print("HideWindowUI :", document.hide_window_ui) +El siguiente fragmento de código le muestra cómo obtener las propiedades usando [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase. - # Modo de página del documento. Cómo mostrar el documento al salir del modo de pantalla completa. - print("NonFullScreenPageMode :", document.non_full_screen_page_mode) +```python +import aspose.pdf as ap - # El diseño de la página, es decir, una sola página, una columna - print("PageLayout :", document.page_layout) - # Cómo debe mostrarse el documento cuando se abre - # Es decir, mostrar miniaturas, pantalla completa, mostrar panel de adjuntos - print("pageMode :", document.page_mode) +def get_document_window(input_pdf, output_pdf): + """Print document window metadata for inspection.""" + document = ap.Document(input_pdf) + print("CenterWindow:", document.center_window) + print("Direction:", document.direction) + print("DisplayDocTitle:", document.display_doc_title) + print("FitWindow:", document.fit_window) + print("HideMenuBar:", document.hide_menubar) + print("HideToolBar:", document.hide_tool_bar) + print("HideWindowUI:", document.hide_window_ui) + print("NonFullScreenPageMode:", document.non_full_screen_page_mode) + print("PageLayout:", document.page_layout) + print("PageMode:", document.page_mode) ``` -### Configurar Propiedades de Ventana de Documento y Visualización de Página +### Establecer propiedades de la ventana del documento y de la visualización de la página -Este tema explica cómo configurar las propiedades de la ventana del documento, la aplicación de visualización y la visualización de la página. Para configurar estas diferentes propiedades: +Este tema explica cómo establecer las propiedades de la ventana del documento, la aplicación del visor y la visualización de la página. Para establecer estas diferentes propiedades: -1. Abra el archivo PDF usando la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). -1. Configure las propiedades del objeto Document. +1. Abra el archivo PDF usando el [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase. +1. Establezca las propiedades del objeto Document. 1. Guarde el archivo PDF actualizado usando el método save. Las propiedades disponibles son: -- CenterWindow -- Direction +- CentrarVentana +- Dirección - DisplayDocTitle -- FitWindow -- HideMenuBar -- HideToolBar -- HideWindowUI +- AjustarVentana +- OcultarBarraDeMenú +- OcultarBarraDeHerramientas +- OcultarVentanaUI - NonFullScreenPageMode -- PageLayout -- PageMode +- Diseño de página +- Modo de página -Cada una se utiliza y describe en el código a continuación. El siguiente fragmento de código le muestra cómo configurar las propiedades usando la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +Cada uno se usa y se describe en el código a continuación. El siguiente - fragmento de código muestra cómo establecer las propiedades usando el [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase. ```python +import aspose.pdf as ap - import aspose.pdf as ap - # Abrir documento +def set_document_window(input_pdf, output_pdf): + """Set document window properties and save the result.""" document = ap.Document(input_pdf) - # Configurar diferentes propiedades del documento - # Especificar la posición de la ventana del documento - Predeterminado: false document.center_window = True - - # Orden de lectura predominante; determina la posición de la página - # Cuando se muestra lado a lado - Predeterminado: L2R document.direction = ap.Direction.R2L - - # Especificar si la barra de título de la ventana debe mostrar el título del documento - # Si es false, la barra de título muestra el nombre del archivo PDF - Predeterminado: false document.display_doc_title = True - - # Especificar si redimensionar la ventana del documento para ajustar el tamaño de - # La primera página mostrada - Predeterminado: false document.fit_window = True - - # Especificar si ocultar la barra de menú de la aplicación de visualización - Predeterminado: false document.hide_menubar = True - - # Especificar si ocultar la barra de herramientas de la aplicación de visualización - Predeterminado: false document.hide_tool_bar = True - - # Especificar si ocultar elementos de la interfaz de usuario como barras de desplazamiento - # Y dejar solo el contenido de la página mostrado - Predeterminado: false document.hide_window_ui = True - - # Modo de página del documento. especificar cómo mostrar el documento al salir del modo de pantalla completa. document.non_full_screen_page_mode = ap.PageMode.USE_OC - - # Especificar el diseño de página, es decir, página única, una columna document.page_layout = ap.PageLayout.TWO_COLUMN_LEFT - - # Especificar cómo se debe mostrar el documento al abrirse - # Es decir, mostrar miniaturas, pantalla completa, mostrar panel de adjuntos document.page_mode = ap.PageMode.USE_THUMBS - # Guardar archivo PDF actualizado document.save(output_pdf) ``` +### Incrustación de fuentes estándar Tipo 1 -### Incrustación de Fuentes Tipo 1 Estándar - -Algunos documentos PDF tienen fuentes de un conjunto especial de fuentes de Adobe. Las fuentes de este conjunto se llaman "Fuentes Tipo 1 Estándar". Este conjunto incluye 14 fuentes y la incrustación de este tipo de fuentes requiere el uso de banderas especiales, es decir, [embed_standard_fonts](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties). A continuación se muestra el fragmento de código que se puede usar para obtener un documento con todas las fuentes incrustadas, incluidas las Fuentes Tipo 1 Estándar: +Algunos documentos PDF tienen fuentes de un conjunto especial de fuentes de Adobe. Las fuentes de este conjunto se denominan “Standard Type 1 Fonts”. Este conjunto incluye 14 fuentes y la incrustación de este tipo de fuentes requiere usar banderas especiales, es decir [incorporar_fuentes_estándar](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties). A continuación se muestra el fragmento de código que se puede usar para obtener un documento con todas las fuentes incrustadas, incluidas las fuentes estándar Type 1: ```python +import aspose.pdf as ap - import aspose.pdf as ap - # Cargar un documento PDF existente +def embedded_fonts(input_pdf, output_pdf): + """Ensure fonts in an existing PDF are embedded.""" document = ap.Document(input_pdf) - # Establecer la propiedad EmbedStandardFonts del documento document.embed_standard_fonts = True + for page in document.pages: - if page.resources.fonts != None: + if page.resources.fonts: for page_font in page.resources.fonts: - # Verificar si la fuente ya está incrustada if not page_font.is_embedded: page_font.is_embedded = True document.save(output_pdf) ``` -### Incrustación de Fuentes al crear PDF +### Incrustar fuentes al crear PDF -Si necesita usar cualquier fuente que no sean las 14 fuentes principales compatibles con Adobe Reader, debe incrustar la descripción de la fuente al generar el archivo PDF. Si la información de la fuente no está incrustada, Adobe Reader la tomará del Sistema Operativo si está instalada en el sistema, o construirá una fuente sustituta de acuerdo con el descriptor de fuente en el PDF. +Si necesita usar cualquier fuente que no sea una de las 14 fuentes básicas admitidas por Adobe Reader, debe incrustar la descripción de la fuente al generar el archivo PDF. Si la información de la fuente no está incrustada, Adobe Reader la tomará del Sistema Operativo si está instalada en el sistema, o construirá una fuente de sustitución según el descriptor de fuente en el PDF. ->Tenga en cuenta que la fuente incrustada debe estar instalada en la máquina anfitriona, es decir, en el caso del siguiente código, la fuente 'Univers Condensed' está instalada en el sistema. +>Tenga en cuenta que la fuente incrustada debe estar instalada en la máquina host, es decir, en el caso del siguiente código la fuente ‘Univers Condensed’ está instalada en el sistema. -Usamos la propiedad 'is_embedded' para incrustar la información de la fuente en el archivo PDF. Establecer el valor de esta propiedad en 'True' incrustará el archivo completo de la fuente en el PDF, sabiendo que aumentará el tamaño del archivo PDF. A continuación se muestra el fragmento de código que se puede usar para incrustar la información de la fuente en el PDF. +Utilizamos la propiedad 'is_embedded' para incrustar la información de la fuente en el archivo PDF. Establecer el valor de esta propiedad a 'True' incrustará el archivo de fuente completo en el PDF, sabiendo que aumentará el tamaño del archivo PDF. A continuación se muestra el fragmento de código que puede usarse para incrustar la información de la fuente en el PDF. ```python +import aspose.pdf as ap - import aspose.pdf as ap - # Crear una instancia del objeto Pdf llamando a su constructor vacío - doc = ap.Document() - - # Crear una sección en el objeto Pdf - page = doc.pages.add() +def embedded_fonts_in_new_document(input_pdf, output_pdf): + """Embed fonts while generating a document from scratch.""" + document = ap.Document() + page = document.pages.add() fragment = ap.text.TextFragment("") - segment = ap.text.TextSegment(" Este es un texto de ejemplo usando una fuente personalizada.") - ts = ap.text.TextState() - ts.font = ap.text.FontRepository.find_font("Arial") - ts.font.is_embedded = True - segment.text_state = ts + segment = ap.text.TextSegment(" This is a sample text using Custom font.") + text_state = ap.text.TextState() + text_state.font = ap.text.FontRepository.find_font("Arial") + text_state.font.is_embedded = True + segment.text_state = text_state fragment.segments.append(segment) page.paragraphs.add(fragment) - # Guardar documento PDF - doc.save(output_pdf) + document.save(output_pdf) ``` +### Establecer nombre de fuente predeterminado al guardar PDF -### Establecer el Nombre de Fuente Predeterminado al Guardar PDF - -Cuando un documento PDF contiene fuentes que no están disponibles en el documento mismo y en el dispositivo, la API reemplaza estas fuentes con la fuente predeterminada. Si la fuente está disponible (instalada en el dispositivo o incrustada en el documento), el PDF de salida debería tener la misma fuente (no debería ser reemplazada por la fuente predeterminada). El valor de la fuente predeterminada debe contener el nombre de la fuente (no la ruta a los archivos de fuente). Hemos implementado una función para establecer el nombre de la fuente predeterminada al guardar un documento como PDF. El siguiente fragmento de código puede usarse para establecer la fuente predeterminada: +Cuando un documento PDF contiene fuentes que no están disponibles en el propio documento ni en el dispositivo, la API reemplaza estas fuentes por la fuente predeterminada. Si la fuente está disponible (instalada en el dispositivo o incrustada en el documento), el PDF de salida debe conservar la misma fuente (no debe ser reemplazada por la fuente predeterminada). El valor de la fuente predeterminada debe contener el nombre de la fuente (no la ruta a los archivos de fuente). Hemos implementado una función para establecer el nombre de la fuente predeterminada al guardar un documento como PDF. El siguiente fragmento de código puede usarse para establecer la fuente predeterminada: ```python +import aspose.pdf as ap - import aspose.pdf as ap - # Cargar un documento PDF existente con fuente faltante +def set_default_font(input_pdf, output_pdf): + """Assign a fallback font when saving a PDF.""" document = ap.Document(input_pdf) - pdfSaveOptions = ap.PdfSaveOptions() - # Especificar el Nombre de Fuente Predeterminado - newName = "Arial" - pdfSaveOptions.default_font_name = newName - document.save(output_pdf, pdfSaveOptions) + save_options = ap.PdfSaveOptions() + save_options.default_font_name = "Arial" + document.save(output_pdf, save_options) ``` -### Obtener Todas las Fuentes de un Documento PDF +### Obtener todas las fuentes del documento PDF -En caso de que desees obtener todas las fuentes de un documento PDF, puedes usar el método [font_utilities](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties) proporcionado en la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). - Por favor, revise el siguiente fragmento de código para obtener todas las fuentes de un documento PDF existente: +En caso de que quieras obtener todas las fuentes de un documento PDF, puedes usar [utilidades_de_fuente](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties) método proporcionado en [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase. Por favor, revisa el siguiente fragmento de código para obtener todas las fuentes de un documento PDF existente: ```python +import aspose.pdf as ap - import aspose.pdf as ap - doc = ap.Document(input_pdf) - fonts = doc.font_utilities.get_all_fonts() - for font in fonts: +def get_all_fonts(input_pdf, output_pdf): + """Print all fonts referenced by a document.""" + document = ap.Document(input_pdf) + for font in document.font_utilities.get_all_fonts(): print(font.font_name) ``` -### Mejorar la Incrustación de Fuentes usando FontSubsetStrategy +### Mejorar la incrustación de fuentes usando FontSubsetStrategy -El siguiente fragmento de código muestra cómo establecer la propiedad [FontSubsetStrategy](https://reference.aspose.com/pdf/python-net/aspose.pdf/fontsubsetstrategy/) utilizada en [font_utilities](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties): +El siguiente fragmento de código muestra cómo establecer [FontSubsetStrategy](https://reference.aspose.com/pdf/python-net/aspose.pdf/fontsubsetstrategy/) usado [utilidades_de_fuente](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties) propiedad: ```python +import aspose.pdf as ap + - import aspose.pdf as ap +def improve_fonts_embedding(input_pdf, output_pdf): + """Apply different font subset strategies to reduce file size.""" + document = ap.Document(input_pdf) + + document.font_utilities.subset_fonts(ap.FontSubsetStrategy.SUBSET_ALL_FONTS) + document.font_utilities.subset_fonts( + ap.FontSubsetStrategy.SUBSET_EMBEDDED_FONTS_ONLY + ) - doc = ap.Document(input_pdf) - # Todas las fuentes se incrustarán como subconjunto en el documento en caso de SubsetAllFonts. - doc.font_utilities.subset_fonts(ap.FontSubsetStrategy.SUBSET_ALL_FONTS) - # El subconjunto de fuentes se incrustará para las fuentes completamente incrustadas, pero las fuentes que no están incrustadas en el documento no se verán afectadas. - doc.font_utilities.subset_fonts(ap.FontSubsetStrategy.SUBSET_EMBEDDED_FONTS_ONLY) - doc.save(output_pdf) + document.save(output_pdf) ``` -### Obtener-Establecer Factor de Zoom de un Archivo PDF +### Obtener-Establecer factor de zoom del archivo PDF A veces, deseas determinar cuál es el factor de zoom actual de un documento PDF. Con Aspose.Pdf, puedes averiguar el valor actual así como establecer uno. -La propiedad Destination de la clase [GoToAction](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/gotoaction/) te permite obtener el valor de zoom asociado con un archivo PDF. De manera similar, puede ser utilizada para establecer el factor de zoom de un archivo. +El [AcciónIrA](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/gotoaction/) La propiedad Destination de la clase permite obtener el valor de zoom asociado a un archivo PDF. De manera similar, puede usarse para establecer el factor de zoom de un archivo. -#### Establecer Factor de Zoom +#### Establecer factor de zoom El siguiente fragmento de código muestra cómo establecer el factor de zoom de un archivo PDF. ```python +import aspose.pdf as ap - import aspose.pdf as ap - # Instanciar nuevo objeto Document - doc = ap.Document(input_pdf) +def set_zoom_factor(input_pdf, output_pdf): + """Set an initial zoom level via document open action.""" + document = ap.Document(input_pdf) - action = ap.annotations.GoToAction(ap.annotations.XYZExplicitDestination(1, 0.0, 0.0, 0.5)) - doc.open_action = action - # Guardar el documento - doc.save(output_pdf) + action = ap.annotations.GoToAction( + ap.annotations.XYZExplicitDestination(1, 0.0, 0.0, 0.5) + ) + document.open_action = action + document.save(output_pdf) ``` -#### Obtener Factor de Zoom +#### Obtener factor de zoom El siguiente fragmento de código muestra cómo obtener el factor de zoom de un archivo PDF. ```python +import aspose.pdf as ap - import aspose.pdf as ap - - # Instanciar nuevo objeto Document - doc = ap.Document(input_pdf) - - # Crear objeto GoToAction - action = doc.open_action - - # Obtener el factor de Zoom del archivo PDF - print(action.destination.zoom) -``` - - -### Configuración de Propiedades Preestablecidas del Diálogo de Impresión - -Aspose.PDF permite configurar los miembros [DUPLEX_FLIP_LONG_EDGE](https://reference.aspose.com/pdf/python-net/aspose.pdf/printduplex/#members) de un documento PDF. Esto te permite cambiar la propiedad DuplexMode de un documento PDF, que está configurada como simplex por defecto. Esto se puede lograr utilizando dos metodologías diferentes como se muestra a continuación. - -```python - import aspose.pdf as ap +def get_zoom_factor(input_pdf, output_pdf): + """Print the zoom level configured in the document open action.""" + document = ap.Document(input_pdf) - doc = ap.Document() - doc.pages.add() - doc.duplex = ap.PrintDuplex.DUPLEX_FLIP_LONG_EDGE - doc.save(output_pdf) + action = document.open_action + if action and action.destination: + print("Zoom:", action.destination.zoom) + else: + print("Zoom: not set") ``` -### Configuración de Propiedades Preestablecidas del Diálogo de Impresión usando el Editor de Contenido PDF - -```python - - import aspose.pdf as ap - - ed = ap.facades.PdfContentEditor() - ed.bind_pdf(input_pdf) - if (ed.get_viewer_preference() & ap.facades.ViewerPreference.DUPLEX_FLIP_SHORT_EDGE) > 0: - print("El archivo tiene dúplex con el borde corto") +## Temas de documentos relacionados - ed.change_viewer_preference(ap.facades.ViewerPreference.DUPLEX_FLIP_SHORT_EDGE) - ed.save(output_pdf) -``` \ No newline at end of file +- [Trabajar con documentos PDF en Python](/pdf/es/python-net/working-with-documents/) +- [Crear archivos PDF en Python](/pdf/es/python-net/create-pdf-document/) +- [Manipular documentos PDF en Python](/pdf/es/python-net/manipulate-pdf-document/) +- [Optimizar archivos PDF en Python](/pdf/es/python-net/optimize-pdf/) diff --git a/es/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md b/es/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md index 2b97e49f3..81df4bf61 100644 --- a/es/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md +++ b/es/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md @@ -1,198 +1,118 @@ --- -title: Manipular Documento PDF en Python a través de .NET -linktitle: Manipular Documento PDF +title: Manipular documentos PDF en Python +linktitle: Manipular documento PDF type: docs weight: 20 url: /es/python-net/manipulate-pdf-document/ -description: Este artículo contiene información sobre cómo validar un Documento PDF para el Estándar PDF A usando Python, cómo trabajar con el índice, cómo establecer la fecha de caducidad del PDF, etc. -lastmod: "2023-04-13" +description: Aprende cómo validar, estructurar y modificar documentos PDF en Python, incluyendo la gestión de TOC y la verificación de PDF/A. +lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Guía sobre la manipulación de documentos PDF usando Python +Abstract: Este artículo proporciona una guía completa sobre la manipulación de documentos PDF usando Python, específicamente con la biblioteca Aspose.PDF. Cubre varias funcionalidades, incluyendo la validación de documentos PDF para el cumplimiento de PDF/A-1a y PDF/A-1b utilizando el método `validate` de la clase `Document`. También detalla cómo agregar, personalizar y gestionar una Tabla de contenidos (TOC) en archivos PDF, como establecer diferentes TabLeaderTypes, ocultar números de página y personalizar la numeración de páginas con un prefijo. Además, el artículo explica cómo establecer una fecha de expiración para un documento PDF incrustando JavaScript para restringir el acceso y cómo aplanar formularios rellenables en un PDF para que no sean editables. Cada sección está acompañada de fragmentos de código que demuestran la implementación de estas características usando Aspose.PDF en Python. --- - - - -## Manipular Documento PDF en Python - -## Validar Documento PDF para el Estándar PDF A (A 1A y A 1B) - -Para validar un documento PDF para la compatibilidad con PDF/A-1a o PDF/A-1b, utiliza el método [validate](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) de la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). Este método te permite especificar el nombre del archivo en el que se guardará el resultado y el tipo de validación requerida enumeración PdfFormat: PDF_A_1A o PDF_A_1B. - -El siguiente fragmento de código te muestra cómo validar un documento PDF para PDF/A-1A. + +Esta página es útil cuando necesitas validar el cumplimiento de PDF, crear o personalizar una tabla de contenido, establecer el comportamiento de expiración del documento, o aplanar PDFs rellenables en flujos de trabajo de Python. + +## Manipular documento PDF en Python + +## Validar documento PDF para el estándar PDF/A (A 1A y A 1B) + +Para validar un documento PDF para compatibilidad con PDF/A-1a o PDF/A-1b, utilice el [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase [validar](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método. Este método le permite especificar el nombre del archivo en el que se guardará el resultado y el tipo de validación requerido, enumeración PdfFormat: PDF_A_1A o PDF_A_1B. + +El siguiente fragmento de código le muestra cómo validar un documento PDF para PDF/A-1A. ```python +import sys +from os import path +import aspose.pdf as ap - import aspose.pdf as ap - # Abrir documento +def validate_pdfa_standard_a1a(input_pdf, output_pdf): document = ap.Document(input_pdf) - - # Validar PDF para PDF/A-1a - document.validate(output_xml, ap.PdfFormat.PDF_A_1A) + document.validate(output_pdf, ap.PdfFormat.PDF_A_1A) ``` -El siguiente fragmento de código te muestra cómo validar un documento PDF para PDF/A-1b. +El siguiente fragmento de código le muestra cómo validar un documento PDF para PDF/A-1b. ```python +import sys +from os import path +import aspose.pdf as ap - import aspose.pdf as ap - # Abrir documento +def validate_pdfa_standard_a1b(input_pdf, output_pdf): document = ap.Document(input_pdf) - - # Validar PDF para PDF/A-1b - document.validate(output_xml, ap.PdfFormat.PDF_A_1B) + document.validate(output_pdf, ap.PdfFormat.PDF_A_1B) ``` - ## Trabajando con TOC -### Agregar TOC a un PDF Existente +### Agregar TOC a PDF existente -TOC en PDF significa "Tabla de Contenidos". Es una característica que permite a los usuarios navegar rápidamente a través de un documento proporcionando una visión general de sus secciones y encabezados. +TOC en PDF significa "Table of Contents". Es una función que permite a los usuarios navegar rápidamente a través de un documento proporcionando una visión general de sus secciones y encabezados. -Para agregar un TOC a un archivo PDF existente, use la clase Heading en el espacio de nombres [aspose.pdf](https://reference.aspose.com/pdf/python-net/aspose.pdf/). El espacio de nombres [aspose.pdf](https://reference.aspose.com/pdf/python-net/aspose.pdf/) puede tanto crear nuevos archivos PDF como manipular archivos PDF existentes. Para agregar un TOC a un PDF existente, use el espacio de nombres Aspose.Pdf. El siguiente fragmento de código muestra cómo crear una tabla de contenidos dentro de un archivo PDF existente usando Python a través de .NET. +Para agregar una TOC a un archivo PDF existente, use la clase Heading en el [aspose.pdf](https://reference.aspose.com/pdf/python-net/aspose.pdf/) namespace. El [aspose.pdf](https://reference.aspose.com/pdf/python-net/aspose.pdf/) namespace puede crear nuevos y manipular archivos PDF existentes. Para agregar un TOC a un PDF existente, use el namespace Aspose.Pdf. El siguiente fragmento de código muestra cómo crear una tabla de contenido dentro de un archivo PDF existente usando Python vía .NET. ```python +import sys +from os import path +import aspose.pdf as ap - import aspose.pdf as ap - - # Cargar un archivo PDF existente - doc = ap.Document(input_pdf) - # Acceder a la primera página del archivo PDF - tocPage = doc.pages.insert(1) - - # Crear objeto para representar la información del TOC - tocInfo = ap.TocInfo() - title = ap.text.TextFragment("Tabla de Contenidos") +def add_table_of_contents(input_pdf, output_pdf): + document = ap.Document(input_pdf) + toc_page = document.pages.insert(1) + toc_info = ap.TocInfo() + title = ap.text.TextFragment("Table Of Contents") title.text_state.font_size = 20 title.text_state.font_style = ap.text.FontStyles.BOLD + toc_info.title = title + toc_page.toc_info = toc_info - # Establecer el título para el TOC - tocInfo.title = title - tocPage.toc_info = tocInfo - - # Crear objetos de cadena que se usarán como elementos del TOC - titles = ["Primera página", "Segunda página", "Tercera página", "Cuarta página"] - for i in range(0, 2): - # Crear objeto Heading - heading2 = ap.Heading(1) - segment2 = ap.text.TextSegment() - heading2.toc_page = tocPage - heading2.segments.append(segment2) - - # Especificar la página de destino para el objeto heading - heading2.destination_page = doc.pages[i + 2] - - # Página de destino - heading2.top = doc.pages[i + 2].rect.height - - # Coordenada de destino - segment2.text = titles[i] - - # Agregar encabezado a la página que contiene el TOC - tocPage.paragraphs.add(heading2) - - # Guardar el documento actualizado - doc.save(output_pdf) + titles = ["First page", "Second page"] + for index, title_text in enumerate(titles[:2]): + heading = ap.Heading(1) + segment = ap.text.TextSegment(title_text) + heading.toc_page = toc_page + heading.segments.append(segment) + destination_page = document.pages[index + 2] + heading.destination_page = destination_page + heading.top = destination_page.rect.height + toc_page.paragraphs.add(heading) + + document.save(output_pdf) ``` - ### Establecer diferentes TabLeaderType para diferentes niveles de TOC -Aspose.PDF para Python también permite establecer diferentes TabLeaderType para diferentes niveles de TOC. Necesitas establecer la propiedad [line_dash](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/#properties) de [TocInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/). +Aspose.PDF for Python también permite establecer diferentes TabLeaderType para diferentes niveles de TOC. Necesita establecer [linea_guion](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/#properties) propiedad de [InfoTOC](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/). ```python +import sys +from os import path +import aspose.pdf as ap - import aspose.pdf as ap - doc = ap.Document() - tocPage = doc.pages.add() +def set_toc_levels(input_pdf, output_pdf): + document = ap.Document(input_pdf) + toc_page = document.pages.add() toc_info = ap.TocInfo() - - # establecer LeaderType toc_info.line_dash = ap.text.TabLeaderType.SOLID - title = ap.text.TextFragment("Tabla de Contenidos") + title = ap.text.TextFragment("Table Of Contents") title.text_state.font_size = 30 toc_info.title = title - - # Añadir la sección de la lista a la colección de secciones del documento Pdf - tocPage.toc_info = toc_info - # Definir el formato de los cuatro niveles de lista estableciendo los márgenes izquierdos - # y - # configuraciones de formato de texto de cada nivel + toc_page.toc_info = toc_info toc_info.format_array_length = 4 toc_info.format_array[0].margin.left = 0 toc_info.format_array[0].margin.right = 30 toc_info.format_array[0].line_dash = ap.text.TabLeaderType.DOT - toc_info.format_array[0].text_state.font_style = ap.text.FontStyles.BOLD | ap.text.FontStyles.ITALIC + toc_info.format_array[0].text_state.font_style = ( + ap.text.FontStyles.BOLD | ap.text.FontStyles.ITALIC + ) toc_info.format_array[1].margin.left = 10 toc_info.format_array[1].margin.right = 30 toc_info.format_array[1].line_dash = 3 @@ -205,226 +125,146 @@ Aspose.PDF para Python también permite establecer diferentes TabLeaderType para toc_info.format_array[3].margin.right = 30 toc_info.format_array[3].text_state.font_style = ap.text.FontStyles.BOLD - # Crear una sección en el documento Pdf - page = doc.pages.add() - - # Añadir cuatro encabezados en la sección - for Level in range(1, 5): - heading2 = ap.Heading(Level) - segment2 = ap.text.TextSegment() - heading2.segments.append(segment2) - heading2.is_auto_sequence = True - heading2.toc_page = tocPage - segment2.text = "Encabezado de Ejemplo" + str(Level) - heading2.text_state.font = ap.text.FontRepository.find_font("Arial") - - # Añadir el encabezado en la Tabla de Contenidos. - heading2.is_in_list = True - page.paragraphs.add(heading2) - - # guardar el Pdf - doc.save(output_pdf) + page = document.pages.add() + for level in range(1, 5): + heading = ap.Heading(level) + heading.is_auto_sequence = True + heading.toc_page = toc_page + heading.text_state.font = ap.text.FontRepository.find_font("Arial") + segment = ap.text.TextSegment(f"Sample Heading{level}") + heading.segments.append(segment) + heading.is_in_list = True + page.paragraphs.add(heading) + + document.save(output_pdf) ``` +### Ocultar números de página en TOC -### Ocultar Números de Página en el TOC - -En caso de que no desees mostrar los números de página, junto con los encabezados en el TOC, puedes usar la propiedad [is_show_page_numbers](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/#properties) de la Clase [TocInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/) como falso. Por favor, revisa el siguiente fragmento de código para ocultar los números de página en la tabla de contenidos: +En caso de que no desees mostrar los números de página, junto con los encabezados en el TOC, puedes usar [is_show_page_numbers](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/#properties) propiedad de [InfoTOC](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/) Clase como falso. Por favor revise el siguiente fragmento de código para ocultar los números de página en la tabla de contenidos: ```python +import sys +from os import path +import aspose.pdf as ap - import aspose.pdf as ap - doc = ap.Document() - toc_page = doc.pages.add() +def hide_page_numbers_in_toc(input_pdf, output_pdf): + document = ap.Document(input_pdf) + toc_page = document.pages.add() toc_info = ap.TocInfo() - title = ap.text.TextFragment("Tabla de Contenidos") + title = ap.text.TextFragment("Table Of Contents") title.text_state.font_size = 20 title.text_state.font_style = ap.text.FontStyles.BOLD toc_info.title = title - # Agregar la sección de la lista a la colección de secciones del documento Pdf + toc_info.is_show_page_numbers = False toc_page.toc_info = toc_info - # Definir el formato de la lista de cuatro niveles configurando los márgenes - # a la izquierda y la configuración del formato del texto de cada nivel - toc_info.is_show_page_numbers = False toc_info.format_array_length = 4 toc_info.format_array[0].margin.right = 0 - toc_info.format_array[0].text_state.font_style = ap.text.FontStyles.BOLD | ap.text.FontStyles.ITALIC + toc_info.format_array[0].text_state.font_style = ( + ap.text.FontStyles.BOLD | ap.text.FontStyles.ITALIC + ) toc_info.format_array[1].margin.left = 30 toc_info.format_array[1].text_state.underline = True toc_info.format_array[1].text_state.font_size = 10 toc_info.format_array[2].text_state.font_style = ap.text.FontStyles.BOLD toc_info.format_array[3].text_state.font_style = ap.text.FontStyles.BOLD - page = doc.pages.add() - # Agregar cuatro encabezados en la sección - for Level in range(1, 5): - heading2 = ap.Heading(Level) - segment2 = ap.text.TextSegment() - heading2.toc_page = toc_page - heading2.segments.append(segment2) - heading2.is_auto_sequence = True - segment2.text = "este es el encabezado de nivel " + str(Level) - heading2.is_in_list = True - page.paragraphs.add(heading2) - doc.save(output_pdf) + page = document.pages.add() + for level in range(1, 2): + heading = ap.Heading(level) + heading.toc_page = toc_page + heading.is_auto_sequence = True + heading.is_in_list = True + segment = ap.text.TextSegment(f"this is heading of level {level}") + heading.segments.append(segment) + page.paragraphs.add(heading) + + document.save(output_pdf) ``` +### Personalizar los números de página al agregar el TOC -### Personalizar los Números de Página al Agregar un Índice - -Es común personalizar la numeración de las páginas en el índice al agregarlo en un documento PDF. Por ejemplo, puede ser necesario añadir algún prefijo antes del número de página como P1, P2, P3, etc. En tal caso, Aspose.PDF para Python proporciona la propiedad [page_numbers_prefix](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/#properties) de la clase [TocInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/) que se puede utilizar para personalizar los números de página como se muestra en el siguiente ejemplo de código. +Es común personalizar la numeración de páginas en el TOC al agregar TOC en un documento PDF. Por ejemplo, puede que necesitemos añadir algún prefijo antes del número de página, como P1, P2, P3, etc. En tal caso, Aspose.PDF for Python proporciona [page_numbers_prefix](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/#properties) propiedad de [InfoTOC](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/) clase que se puede usar para personalizar los números de página como se muestra en el siguiente ejemplo de código. ```python +import sys +from os import path +import aspose.pdf as ap - import aspose.pdf as ap - # Cargar un archivo PDF existente - doc = ap.Document(input_pdf) - # Acceder a la primera página del archivo PDF - toc_page = doc.pages.insert(1) - # Crear objeto para representar la información del índice +def customize_page_numbers_in_toc(input_pdf, output_pdf): + document = ap.Document(input_pdf) + toc_page = document.pages.insert(1) toc_info = ap.TocInfo() - title = ap.text.TextFragment("Tabla de Contenidos") + title = ap.text.TextFragment("Table Of Contents") title.text_state.font_size = 20 title.text_state.font_style = ap.text.FontStyles.BOLD - # Establecer el título para el índice toc_info.title = title toc_info.page_numbers_prefix = "P" toc_page.toc_info = toc_info - for i in range(len(doc.pages)): - # Crear objeto de encabezado - heading2 = ap.Heading(1) - segment2 = ap.text.TextSegment() - heading2.toc_page = toc_page - heading2.segments.append(segment2) - # Especificar la página de destino para el objeto de encabezado - heading2.destination_page = doc.pages[i + 1] - # Página de destino - heading2.top = doc.pages[i + 1].rect.height - # Coordenada de destino - segment2.text = "Página " + str(i) - # Añadir encabezado a la página que contiene el índice - toc_page.paragraphs.add(heading2) - - # Guardar el documento actualizado - doc.save(output_pdf) -``` + for index, page in enumerate(document.pages, start=1): + heading = ap.Heading(1) + heading.toc_page = toc_page + heading.destination_page = page + heading.top = page.rect.height + segment = ap.text.TextSegment(f"Page {index}") + heading.segments.append(segment) + toc_page.paragraphs.add(heading) + document.save(output_pdf) +``` -## Cómo establecer la fecha de vencimiento de un PDF +## Cómo establecer la fecha de vencimiento del PDF -Aplicamos privilegios de acceso a archivos PDF para que un cierto grupo de usuarios pueda acceder a características/objetos particulares de documentos PDF. Para restringir el acceso al archivo PDF, usualmente aplicamos cifrado y podemos tener el requerimiento de establecer la expiración del archivo PDF, de modo que el usuario que accede/visualiza el documento reciba un aviso válido sobre la expiración del archivo PDF. +Aplicamos privilegios de acceso en los archivos PDF para que un determinado grupo de usuarios pueda acceder a características/objetos específicos de los documentos PDF. Para restringir el acceso al archivo PDF, normalmente aplicamos cifrado y puede que tengamos un requisito de establecer una expiración del archivo PDF, de modo que el usuario que accede/visualiza el documento reciba una notificación válida sobre la expiración del archivo PDF. ```python +import sys +from os import path +import aspose.pdf as ap - import aspose.pdf as ap - # Instanciar objeto Document - doc = ap.Document() - # Agregar página a la colección de páginas del archivo PDF - doc.pages.add() - # Agregar fragmento de texto a la colección de párrafos del objeto página - doc.pages[1].paragraphs.add(ap.text.TextFragment("Hola Mundo...")) - # Crear objeto JavaScript para establecer la fecha de vencimiento del PDF - javaScript = ap.annotations.JavascriptAction( +def set_pdf_expiry_date(input_pdf, output_pdf): + document = ap.Document(input_pdf) + document.pages.add() + document.pages[1].paragraphs.add(ap.text.TextFragment("Hello World...")) + script = ap.annotations.JavascriptAction( "var year=2017;" - + "var month=5;" - + "today = new Date(); today = new Date(today.getFullYear(), today.getMonth());" - + "expiry = new Date(year, month);" - + "if (today.getTime() > expiry.getTime())" - + "app.alert('El archivo ha expirado. Necesitas uno nuevo.');" + "var month=5;" + "today = new Date(); today = new Date(today.getFullYear(), today.getMonth());" + "expiry = new Date(year, month);" + "if (today.getTime() > expiry.getTime())" + "app.alert('The file is expired. You need a new one.');" ) - # Establecer JavaScript como acción de apertura del PDF - doc.open_action = javaScript - - # Guardar Documento PDF - doc.save(output_pdf) + document.open_action = script + document.save(output_pdf) ``` +## Aplanar PDF rellenable en Python -## Aplanar PDF Rellenable en Python - -Los documentos PDF a menudo incluyen formularios con widgets interactivos rellenables como botones de opción, casillas de verificación, cuadros de texto, listas, etc. Para hacerlo no editable para varios propósitos de aplicación, necesitamos aplanar el archivo PDF. Aspose.PDF proporciona la función para aplanar tu PDF en Python con solo unas pocas líneas de código: +Los documentos PDF a menudo incluyen formularios con widgets interactivos rellenables, como botones de radio, casillas de verificación, cuadros de texto, listas, etc. Para que sea no editable con diversos propósitos de aplicación, necesitamos aplanar el archivo PDF. +Aspose.PDF proporciona la función para aplanar su PDF en Python con solo unas pocas líneas de código: ```python +import sys +from os import path +import aspose.pdf as ap - import aspose.pdf as ap - - # Cargar el formulario PDF de origen - doc = ap.Document(input_pdf) - - # Aplanar PDF Rellenable Aplanado - if len(doc.form.fields) > 0: - for item in doc.form.fields: - item.flatten() - # Guardar el documento actualizado - doc.save(output_pdf) +def flatten_fillable_pdf(input_pdf, output_pdf): + document = ap.Document(input_pdf) + if document.form and document.form.fields: + for field in document.form.fields: + field.flatten() + document.save(output_pdf) ``` - \ No newline at end of file +## Temas de documentos relacionados + +- [Trabajar con documentos PDF en Python](/pdf/es/python-net/working-with-documents/) +- [Formatear documentos PDF en Python](/pdf/es/python-net/formatting-pdf-document/) +- [Crear archivos PDF en Python](/pdf/es/python-net/create-pdf-document/) +- [Optimizar archivos PDF en Python](/pdf/es/python-net/optimize-pdf/) diff --git a/es/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md b/es/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md index b4b4fe66c..c2281a4eb 100644 --- a/es/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md +++ b/es/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md @@ -1,185 +1,276 @@ --- -title: Cómo Combinar PDF usando Python +title: Combinar archivos PDF en Python linktitle: Combinar archivos PDF type: docs weight: 50 url: /es/python-net/merge-pdf-documents/ -description: Esta página explica cómo combinar documentos PDF en un solo archivo PDF con Python. -lastmod: "2023-04-14" +description: Aprende cómo combinar varios archivos PDF en un solo documento en Python. +lastmod: "2026-05-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Combina páginas PDF usando Python +Abstract: 'Este artículo aborda la necesidad común de combinar varios archivos PDF en un solo documento, un proceso valioso para organizar y optimizar el almacenamiento y la compartición del contenido PDF. Explora el uso de Aspose.PDF for Python via .NET para combinar eficientemente archivos PDF, reconociendo que la fusión de PDFs en Python puede ser un desafío sin bibliotecas de terceros. El artículo proporciona una guía paso a paso para concatenar archivos PDF: crear un nuevo documento, combinar los archivos y guardar el documento combinado. Un fragmento de código demuestra la implementación usando Aspose.PDF, destacando la capacidad de la biblioteca para simplificar el proceso de fusión. Además, presenta Aspose.PDF Merger, una herramienta en línea para combinar PDFs, que permite a los usuarios explorar la funcionalidad en un entorno web.' --- - - - -## Fusionar o combinar varios PDF en un solo PDF en Python - -Combinar archivos PDF es una consulta muy popular entre los usuarios. Esto puede ser útil cuando tienes varios archivos PDF que deseas compartir o almacenar juntos como un solo documento. - -Fusionar archivos PDF puede ayudarte a organizar tus documentos, liberar espacio de almacenamiento en tu PC y compartir varios archivos PDF con otros al combinarlos en un solo documento. + +## Combinar o fusionar varios PDF en un único PDF en Python + +Combinar archivos PDF es una consulta muy popular entre los usuarios Esto puede ser útil cuando tienes varios archivos PDF que deseas compartir o almacenar juntos como un solo documento. + +Combinar archivos PDF puede ayudarle a organizar sus documentos, liberar espacio de almacenamiento en su PC y compartir varios archivos PDF con otros al combinarlos en un solo documento. Fusionar PDF en Python a través de .NET no es una tarea sencilla sin usar una biblioteca de terceros. -Este artículo muestra cómo fusionar varios archivos PDF en un solo documento PDF utilizando Aspose.PDF para Python a través de .NET. +Este artículo muestra cómo combinar varios archivos PDF en un único documento PDF usando Aspose.PDF for Python via .NET. ## Fusionar archivos PDF usando Python y DOM Para concatenar dos archivos PDF: -1. Crea dos objetos [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/), cada uno conteniendo uno de los archivos PDF de entrada. +1. Crear un nuevo documento. +1. Combinar los archivos PDF +1. Guardar el documento combinado + +Combinar varios documentos PDF en un solo archivo: + +```python +import sys +import aspose.pdf as ap +from os import path + + +def merge_two_documents(infile1, infile2, outfile): + document1 = ap.Document(infile1) + document2 = ap.Document(infile2) + document1.pages.add(document2.pages) + document1.save(outfile) +``` + +## Añadir un rango de páginas de un PDF a otro -1. Luego, llame al método [add()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) de la colección [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) para el objeto Document al que desea agregar el otro archivo PDF. -1. Pase la colección PageCollection del segundo objeto Document al método [add()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) de la primera colección PageCollection. -1. Finalmente, guarde el archivo PDF de salida usando el método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods). +Copiar y agregar un rango específico de páginas de un documento PDF de origen a un documento PDF de destino utilizando Aspose.PDF for Python. -El siguiente fragmento de código muestra cómo concatenar archivos PDF. +1. Abre los archivos PDF usando la clase Document. +1. Verifique si el documento fuente tiene páginas. +1. Validar el rango de páginas. +1. Omita la operación si la página inicial es mayor que la página final. +1. Iterar a través del rango de páginas. +1. Añadir páginas al documento de destino. ```python +import sys +import aspose.pdf as ap +from os import path - import aspose.pdf as ap - # Abrir el primer documento - document1 = ap.Document(input_pdf_1) - # Abrir el segundo documento - document2 = ap.Document(input_pdf_2) +def _append_page_range(source_document, destination_document, start_page, end_page): + total_pages = len(source_document.pages) + if total_pages == 0: + return - # Añadir páginas del segundo documento al primero - document1.pages.add(document2.pages) + start = max(1, start_page) + end = min(end_page, total_pages) + if start > end: + return + + for page_number in range(start, end + 1): + destination_document.pages.add(source_document.pages[page_number]) +``` + +## Combinar varios documentos PDF en uno + +Este fragmento de código explica cómo combinar varios archivos PDF en un solo documento: + +1. Crea un documento de salida vacío. +1. Itera a través de los archivos de entrada. +1. Cargue cada documento de origen. +1. Determinar el rango de páginas. +1. Agregar páginas al documento de salida. +1. Repita para todos los documentos. +1. Guardar el PDF fusionado. + +```python +import sys +import aspose.pdf as ap +from os import path + + +def merge_multiple_documents(input_files, outfile): + output_document = ap.Document() + + for input_file in input_files: + source_document = ap.Document(input_file) + _append_page_range( + source_document, output_document, 1, len(source_document.pages) + ) + + output_document.save(outfile) +``` + +## Combinar rangos de páginas seleccionados de varios PDF + +1. Cargar los documentos PDF de origen. +1. Crear un documento de salida. +1. Definir rangos de páginas para cada documento. +1. Agregar páginas del primer documento. +1. Añadir páginas del segundo documento. +1. Combina las páginas en el orden deseado. +1. Guardar el PDF fusionado. + +```python +import sys +import aspose.pdf as ap +from os import path + + +def merge_selected_page_ranges(infile1, infile2, outfile): + document1 = ap.Document(infile1) + document2 = ap.Document(infile2) + output_document = ap.Document() - # Guardar archivo de salida concatenado - document1.save(output_pdf) + _append_page_range(document1, output_document, 1, 2) + _append_page_range(document2, output_document, 2, 3) + + output_document.save(outfile) ``` -## Ejemplo en Vivo - -[Aspose.PDF Merger](https://products.aspose.app/pdf/merger) es una aplicación web gratuita en línea que te permite investigar cómo funciona la funcionalidad de combinación de presentaciones. - -[![Aspose.PDF Merger](merger.png)](https://products.aspose.app/pdf/merger) - - \ No newline at end of file +## Insertar un PDF en otro en una posición específica + +1. Cargue la base e inserte los documentos. +1. Crear un documento de salida. +1. Determinar el total de páginas en el documento base. +1. Validar el índice de inserción. +1. Agregar páginas antes del punto de inserción. +1. Añadir todas las páginas del documento insertado. +1. Agregar las páginas restantes del documento base. +1. Guarda el PDF resultante. + +```python +import sys +import aspose.pdf as ap +from os import path + + +def merge_insert_document_at_position(infile1, infile2, insert_after_page, outfile): + base_document = ap.Document(infile1) + insert_document = ap.Document(infile2) + output_document = ap.Document() + + base_total_pages = len(base_document.pages) + insert_index = max(0, min(insert_after_page, base_total_pages)) + + _append_page_range(base_document, output_document, 1, insert_index) + _append_page_range(insert_document, output_document, 1, len(insert_document.pages)) + _append_page_range( + base_document, output_document, insert_index + 1, base_total_pages + ) + + output_document.save(outfile) +``` + +## Combinar PDFs alternando páginas + +Este ejemplo demuestra cómo combinar dos documentos PDF alternando sus páginas usando Aspose.PDF for Python. + +1. Cargue los documentos PDF de entrada. +1. Crear un documento de salida. +1. Obtenga el número de páginas en cada documento. +1. Calcule el número máximo de páginas. +1. Iterar sobre los números de página. +1. Agregar páginas alternadamente. +1. Manejar recuentos de páginas desiguales. +1. Guardar el PDF fusionado. + +```python +import sys +import aspose.pdf as ap +from os import path + + +def merge_alternating_pages(infile1, infile2, outfile): + document1 = ap.Document(infile1) + document2 = ap.Document(infile2) + output_document = ap.Document() + + document1_pages = len(document1.pages) + document2_pages = len(document2.pages) + max_pages = max(document1_pages, document2_pages) + + for page_number in range(1, max_pages + 1): + if page_number <= document1_pages: + output_document.pages.add(document1.pages[page_number]) + if page_number <= document2_pages: + output_document.pages.add(document2.pages[page_number]) + + output_document.save(outfile) +``` + +## Combinar PDFs con separadores de sección y marcadores + +Combina varios documentos PDF en un único archivo con secciones estructuradas y marcadores de navegación usando Aspose.PDF for Python. + +1. Crear un documento de salida. +1. Itera a través de los archivos de entrada. +1. Cargar el documento fuente. +1. Agregar una página separadora. +1. Crear un marcador de sección. +1. Agregar páginas del documento de origen. +1. Rastrear la primera página de contenido. +1. Agregar un marcador de contenido anidado (opcional). +1. Repita para todos los documentos. +1. Guardar el PDF fusionado. + +```python +import sys +import aspose.pdf as ap +from os import path + + +def merge_with_section_separators_and_bookmarks(input_files, outfile): + output_document = ap.Document() + + for section_index, input_file in enumerate(input_files, start=1): + source_document = ap.Document(input_file) + source_page_count = len(source_document.pages) + + separator_page = output_document.pages.add() + separator_page.paragraphs.add( + ap.text.TextFragment( + f"Section {section_index}: {path.basename(input_file)}" + ) + ) + + section_bookmark = ap.OutlineItemCollection(output_document.outlines) + section_bookmark.title = f"Section {section_index}" + section_bookmark.action = ap.annotations.GoToAction(separator_page) + output_document.outlines.append(section_bookmark) + + first_content_page_number = len(output_document.pages) + 1 + _append_page_range(source_document, output_document, 1, source_page_count) + + if source_page_count > 0 and first_content_page_number <= len( + output_document.pages + ): + content_bookmark = ap.OutlineItemCollection(output_document.outlines) + content_bookmark.title = f"Section {section_index} Content" + content_bookmark.action = ap.annotations.GoToAction( + output_document.pages[first_content_page_number] + ) + section_bookmark.append(content_bookmark) + + output_document.save(outfile) +``` + +## Ejemplo en vivo + +[Aspose.PDF Fusionador](https://products.aspose.app/pdf/merger) es una aplicación web gratuita en línea que le permite investigar cómo funciona la funcionalidad de fusión de presentaciones. + +[![Aspose.PDF Fusionador](merger.png)](https://products.aspose.app/pdf/merger) + +## Temas de documentos relacionados + +- [Trabajar con documentos PDF en Python](/pdf/es/python-net/working-with-documents/) +- [Dividir archivos PDF en Python](/pdf/es/python-net/split-document/) +- [Optimizar archivos PDF en Python](/pdf/es/python-net/optimize-pdf/) +- [Manipular documentos PDF en Python](/pdf/es/python-net/manipulate-pdf-document/) + diff --git a/es/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md b/es/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md index 67e7b67bd..34c699037 100644 --- a/es/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md +++ b/es/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md @@ -1,401 +1,359 @@ --- -title: Optimizar, Comprimir o Reducir el Tamaño de PDF en Python +title: Optimizar archivos PDF en Python linktitle: Optimizar PDF type: docs weight: 30 url: /es/python-net/optimize-pdf/ -description: Optimizar archivo PDF, reducir todas las imágenes, reducir tamaño de PDF, Desincrustar fuentes, Eliminar objetos no utilizados con Python. -lastmod: "2023-04-17" +description: Aprenda cómo optimizar, comprimir y reducir el tamaño de archivo PDF en Python usando Aspose.PDF. +lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Comprima páginas PDF usando Python +Abstract: Este artículo ofrece una guía completa sobre la optimización de archivos PDF para reducir su tamaño y mejorar el rendimiento en diversas plataformas, como páginas web, correos electrónicos y sistemas de almacenamiento. Las técnicas de optimización incluyen la reducción del tamaño de las imágenes, la eliminación de recursos no utilizados y la desincorporación de fuentes. Se discuten métodos específicos para optimizar PDFs para la web y reducir el tamaño total del archivo, utilizando los métodos `Optimize` y `OptimizeResources` en Aspose.PDF for Python. La personalización de las estrategias de optimización es posible a través de `OptimizationOptions`, lo que permite acciones dirigidas como comprimir imágenes, eliminar objetos y flujos no utilizados, vincular flujos duplicados y desincorporar fuentes. Estrategias adicionales cubren la aplanación de anotaciones, la eliminación de campos de formulario y la conversión de archivos PDF de RGB a escala de grises para reducir aún más el tamaño. El artículo también destaca el uso de la compresión FlateDecode para la optimización de imágenes, garantizando una gestión eficaz de archivos PDF mientras se mantiene la calidad y la funcionalidad. --- - - - -Un documento PDF a veces puede contener datos adicionales. Reducir el tamaño de un archivo PDF te ayudará a optimizar la transferencia de red y el almacenamiento. Esto es especialmente útil para publicar en páginas web, compartir en redes sociales, enviar por correo electrónico o archivar en almacenamiento. Podemos usar varias técnicas para optimizar PDF: + +Un documento PDF a veces puede contener datos adicionales. Reducir el tamaño de un archivo PDF le ayudará a optimizar la transferencia de red y el almacenamiento. Esto es especialmente útil para publicar en páginas web, compartir en redes sociales, enviar por correo electrónico o archivar en almacenamiento. Podemos usar varias técnicas para optimizar el PDF: + +Utilice esta página cuando necesite reducir el tamaño del PDF para entrega web, compartir por correo electrónico, ahorro de almacenamiento o salida apta para impresión sin reconstruir el documento desde cero. - Optimizar el contenido de la página para la navegación en línea - Reducir o comprimir todas las imágenes -- Permitir la reutilización del contenido de la página -- Unir flujos duplicados -- Desincrustar fuentes +- Habilitar la reutilización del contenido de la página +- Combinar flujos duplicados +- Desincorporar fuentes - Eliminar objetos no utilizados -- Eliminar campos de formulario aplanados +- Eliminar el aplanado de los campos de formulario - Eliminar o aplanar anotaciones {{% alert color="primary" %}} -Se puede encontrar una explicación detallada de los métodos de optimización en la página Resumen de Métodos de Optimización. + Una explicación detallada de los métodos de optimización se puede encontrar en la página Visión general de los métodos de optimización. {{% /alert %}} -## Optimizar Documento PDF para la Web +## Optimizar documento PDF para la web -La optimización, o linealización para la Web, se refiere al proceso de hacer un archivo PDF adecuado para la navegación en línea usando un navegador web. Para optimizar un archivo para visualización web: +La optimización, o linealización para la web, se refiere al proceso de hacer que un archivo PDF sea adecuado para la navegación en línea mediante un navegador web. Para optimizar un archivo para su visualización en la web: -1. Abra el documento de entrada en un objeto [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). -1. Use el método [Optimize](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods). -1. Guarde el documento optimizado usando el método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods). +1. Abra el documento de entrada en un [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) objeto. +1. Usa el [Optimizar](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método. +1. Guarde el documento optimizado usando el [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método. El siguiente fragmento de código muestra cómo optimizar un documento PDF para la web. -```python - - import aspose.pdf as ap +```python +import aspose.pdf as ap +from os import path, stat +import sys - # Abrir documento - document = ap.Document(input_pdf) - # Optimizar para la web +def optimize_pdf(infile, outfile): + document = ap.Document(infile) document.optimize() - - # Guardar documento de salida - document.save(output_pdf) + document.save(outfile) + file_stats_1 = stat(infile) + file_stats_2 = stat(outfile) + print( + "Original file size: {}. Reduced file size: {}".format( + file_stats_1.st_size, file_stats_2.st_size + ) + ) ``` -## Reducir Tamaño PDF +## Reducir tamaño PDF -El método [OptimizeResources()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) le permite reducir el tamaño del documento eliminando la información innecesaria. Por defecto, este método funciona de la siguiente manera: +El [OptimizeResources()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) El método le permite reducir el tamaño del documento eliminando la información innecesaria. De forma predeterminada, este método funciona de la siguiente manera: -- Se eliminan los recursos que no se utilizan en las páginas del documento +- Los recursos que no se utilizan en las páginas del documento se eliminan - Los recursos iguales se unen en un solo objeto - -- Se eliminan los objetos no utilizados +- Los objetos no utilizados se eliminan El fragmento a continuación es un ejemplo. Sin embargo, tenga en cuenta que este método no puede garantizar la reducción del documento. ```python - - import aspose.pdf as ap - - # Abrir documento - documento = ap.Document(input_pdf) - # Optimizar documento PDF. Sin embargo, tenga en cuenta que este método no puede garantizar la reducción del documento - documento.optimize_resources() - # Guardar documento actualizado - documento.save(output_pdf) +import aspose.pdf as ap +from os import path, stat +import sys + + +def reduce_size_pdf(infile, outfile): + # Open document + document = ap.Document(infile) + # Optimize PDF document. Note, though, that this method cannot guarantee document shrinking + document.optimize_resources() + # Save updated document + document.save(outfile) + file_stats_1 = stat(infile) + file_stats_2 = stat(outfile) + print( + "Original file size: {}. Reduced file size: {}".format( + file_stats_1.st_size, file_stats_2.st_size + ) + ) ``` ## Gestión de Estrategia de Optimización -También podemos personalizar la estrategia de optimización. Actualmente, el método [OptimizeResources()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) utiliza 5 técnicas. Estas técnicas se pueden aplicar utilizando el método OptimizeResources() con el parámetro [OptimizationOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf.optimization/optimizationoptions/). +También podemos personalizar la estrategia de optimización. Actualmente, la [OptimizeResources()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) el método usa 5 técnicas. Estas técnicas pueden aplicarse usando el método OptimizeResources() con el [OptimizationOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf.optimization/optimizationoptions/) parámetro. -### Reduciendo o Comprimendo Todas las Imágenes +### Reducir o comprimir todas las imágenes -Tenemos dos maneras de trabajar con imágenes: reducir la calidad de la imagen y/o cambiar su resolución. - En cualquier caso, se deben aplicar [ImageCompressionOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf.optimization/imagecompressionoptions/). En el siguiente ejemplo, reducimos las imágenes disminuyendo la Calidad de Imagen a 50. +Tenemos dos formas de trabajar con imágenes: reducir la calidad de la imagen y/o cambiar su resolución. En cualquier caso, [OpcionesDeCompresiónDeImagen](https://reference.aspose.com/pdf/python-net/aspose.pdf.optimization/imagecompressionoptions/) debe aplicarse. En el siguiente ejemplo, reducimos las imágenes al disminuir ImageQuality al 50. ```python +import aspose.pdf as ap +from os import path, stat +import sys - import aspose.pdf as ap - # Abrir documento - document = ap.Document(input_pdf) - # Inicializar OptimizationOptions +def shrinking_or_compressing_all_images(infile, outfile): + # Open document + document = ap.Document(infile) + # Initialize OptimizationOptions optimizeOptions = ap.optimization.OptimizationOptions() - # Configurar opción CompressImages + # Set CompressImages option optimizeOptions.image_compression_options.compress_images = True - # Configurar opción ImageQuality + # Set ImageQuality option optimizeOptions.image_compression_options.image_quality = 50 - # Optimizar documento PDF usando OptimizationOptions + # Optimize PDF document using OptimizationOptions document.optimize_resources(optimizeOptions) - # Guardar documento actualizado - document.save(output_pdf) + # Save updated document + document.save(outfile) + file_stats_1 = stat(infile) + file_stats_2 = stat(outfile) + print( + "Original file size: {}. Reduced file size: {}".format( + file_stats_1.st_size, file_stats_2.st_size + ) + ) ``` -### Eliminación de Objetos No Utilizados +### Eliminando objetos no utilizados -Un documento PDF a veces contiene objetos PDF que no están referenciados desde ningún otro objeto en el documento. Esto puede suceder, por ejemplo, cuando una página se elimina del árbol de páginas del documento pero el objeto de la página en sí no se elimina. Eliminar estos objetos no invalida el documento, sino que lo reduce. +Un documento PDF a veces contiene objetos PDF que no están referenciados desde ningún otro objeto en el documento. Esto puede suceder, por ejemplo, cuando se elimina una página del árbol de páginas del documento pero el propio objeto de la página no se elimina. Eliminar estos objetos no invalida el documento, sino que lo reduce. ```python +import aspose.pdf as ap +from os import path, stat +import sys - import aspose.pdf as ap - # Abrir documento - document = ap.Document(input_pdf) - # Establecer opción RemoveUsedObject +def removing_unused_objects(infile, outfile): + # Open document + document = ap.Document(infile) + # Set RemoveUnusedObjects option optimizeOptions = ap.optimization.OptimizationOptions() optimizeOptions.remove_unused_objects = True - # Optimizar documento PDF usando OptimizationOptions + # Optimize PDF document using OptimizationOptions document.optimize_resources(optimizeOptions) - # Guardar documento actualizado - document.save(output_pdf) + # Save updated document + document.save(outfile) + file_stats_1 = stat(infile) + file_stats_2 = stat(outfile) + print( + "Original file size: {}. Reduced file size: {}".format( + file_stats_1.st_size, file_stats_2.st_size + ) + ) ``` -### Eliminando Flujos No Usados +### Eliminando flujos sin usar -A veces el documento contiene flujos de recursos no utilizados. Estos flujos no son “objetos no utilizados” porque se referencian desde un diccionario de recursos de la página. Por lo tanto, no se eliminan con un método de “eliminar objetos no utilizados”. Pero estos flujos nunca se utilizan con el contenido de la página. Esto puede suceder en casos cuando una imagen ha sido eliminada de la página pero no de los recursos de la página. Además, esta situación a menudo ocurre cuando las páginas se extraen del documento y las páginas del documento tienen recursos “comunes”, es decir, el mismo objeto de Recursos. Se analizan los contenidos de la página para determinar si un flujo de recursos se utiliza o no. Los flujos no utilizados se eliminan. A veces disminuye el tamaño del documento. El uso de esta técnica es similar al paso anterior: +A veces el documento contiene flujos de recursos no utilizados. Estos flujos no son “unused objects” porque están referenciados desde un diccionario de recursos de página. Por lo tanto, no se eliminan con un método “remove unused objects”. Pero estos flujos nunca se usan con el contenido de la página. Esto puede ocurrir en casos en que una imagen ha sido eliminada de la página pero no de los recursos de la página. Además, esta situación ocurre a menudo cuando se extraen páginas del documento y las páginas del documento tienen recursos “common”, es decir, el mismo objeto Resources. El contenido de la página se analiza para determinar si un flujo de recurso se usa o no. Los flujos no utilizados se eliminan. A veces disminuye el tamaño del documento. El uso de esta técnica es similar al paso anterior: ```python +import aspose.pdf as ap +from os import path, stat +import sys - import aspose.pdf as ap - # Abrir documento - document = ap.Document(input_pdf) - # Establecer la opción RemoveUsedStreams +def removing_unused_streams(infile, outfile): + # Open document + document = ap.Document(infile) + # Set RemoveUnusedStreams option optimizeOptions = ap.optimization.OptimizationOptions() optimizeOptions.remove_unused_streams = True - # Optimizar documento PDF usando OptimizationOptions + # Optimize PDF document using OptimizationOptions document.optimize_resources(optimizeOptions) - # Guardar documento actualizado - document.save(output_pdf) + # Save updated document + document.save(outfile) + file_stats_1 = stat(infile) + file_stats_2 = stat(outfile) + print( + "Original file size: {}. Reduced file size: {}".format( + file_stats_1.st_size, file_stats_2.st_size + ) + ) ``` -### Vinculación de Flujos Duplicados +### Vinculación de flujos duplicados -Algunos documentos pueden contener varios flujos de recursos idénticos (como imágenes, por ejemplo). Esto puede ocurrir, por ejemplo, cuando un documento se concatena consigo mismo. El documento de salida contiene dos copias independientes del mismo flujo de recursos. Analizamos todos los flujos de recursos y los comparamos. Si los flujos están duplicados, se fusionan, es decir, solo queda una copia. Las referencias se cambian adecuadamente, y las copias del objeto se eliminan. En algunos casos, esto ayuda a disminuir el tamaño del documento. +Algunos documentos pueden contener varios flujos de recursos idénticos (como imágenes, por ejemplo). Esto puede ocurrir, por ejemplo, cuando un documento se concatena consigo mismo. El documento de salida contiene dos copias independientes del mismo flujo de recursos. Analizamos todos los flujos de recursos y los comparamos. Si los flujos están duplicados, se fusionan, es decir, solo queda una copia. Las referencias se modifican adecuadamente y se eliminan las copias del objeto. En algunos casos, ayuda a reducir el tamaño del documento. ```python +import aspose.pdf as ap +from os import path, stat +import sys - import aspose.pdf as ap - # Abrir documento - document = ap.Document(input_pdf) - # Establecer la opción LinkDuplicateStreams +def linking_duplicate_streams(infile, outfile): + # Open document + document = ap.Document(infile) + # Set link_duplicate_streams option optimizeOptions = ap.optimization.OptimizationOptions() - optimizeOptions.link_duplcate_streams = True - # Optimizar documento PDF usando OptimizationOptions + optimizeOptions.link_duplicate_streams = True + # Optimize PDF document using OptimizationOptions document.optimize_resources(optimizeOptions) - # Guardar documento actualizado - document.save(output_pdf) + # Save updated document + document.save(outfile) + file_stats_1 = stat(infile) + file_stats_2 = stat(outfile) + print( + "Original file size: {}. Reduced file size: {}".format( + file_stats_1.st_size, file_stats_2.st_size + ) + ) ``` -### Desincrustación de Fuentes +### Desincorporar fuentes -Si el documento usa fuentes incrustadas, significa que todos los datos de las fuentes están almacenados en el documento. - La ventaja es que el documento es visible independientemente de si la fuente está instalada en la máquina del usuario o no. Pero incrustar fuentes hace que el documento sea más grande. El método de desincrustar fuentes elimina todas las fuentes incrustadas. Por lo tanto, el tamaño del documento disminuye, pero el documento en sí puede volverse ilegible si la fuente correcta no está instalada. +Si el documento utiliza fuentes incrustadas, significa que todos los datos de la fuente se almacenan en el documento. La ventaja es que el documento se puede visualizar independientemente de si la fuente está instalada en la máquina del usuario o no. Pero incrustar fuentes hace que el documento sea más grande. El método de desaplicar fuentes elimina todas las fuentes incrustadas. Así, el tamaño del documento disminuye, pero el propio documento puede volverse ilegible si la fuente correcta no está instalada. ```python - - import aspose.pdf as ap - - # Abrir documento - document = ap.Document(input_pdf) - # Establecer la opción UnembedFonts - optimizeOptions = ap.optimization.OptimizationOptions() - optimizeOptions.unembed_fonts = True - # Optimizar documento PDF usando OptimizationOptions - document.optimize_resources(optimizeOptions) - # Guardar documento actualizado - document.save(output_pdf) - file_stats_1 = os.stat(input_pdf) - file_stats_2 = os.stat(output_pdf) +import aspose.pdf as ap +from os import path, stat +import sys + + +def unembed_fonts(infile, outfile): + # Open document + document = ap.Document(infile) + # Set unembed_fonts option + optimize_options = ap.optimization.OptimizationOptions() + optimize_options.unembed_fonts = True + # Optimize PDF document using OptimizationOptions + document.optimize_resources(optimize_options) + # Save updated document + document.save(outfile) + file_stats_1 = stat(infile) + file_stats_2 = stat(outfile) print( - "Tamaño del archivo original: {}. Tamaño del archivo reducido: {}".format( + "Original file size: {}. Reduced file size: {}".format( file_stats_1.st_size, file_stats_2.st_size ) ) ``` -Los recursos de optimización aplican estos métodos al documento. Si se aplica cualquiera de estos métodos, el tamaño del documento probablemente disminuirá. Si no se aplica ninguno de estos métodos, el tamaño del documento no cambiará, lo cual es obvio. +Los recursos de optimización aplican estos métodos al documento. Si se aplica cualquiera de estos métodos, el tamaño del documento probablemente disminuya. Si no se aplica ninguno de estos métodos, el tamaño del documento no cambiará, lo cual es obvio. -## Formas Adicionales de Reducir el Tamaño del Documento PDF +## Formas adicionales de reducir el tamaño del documento PDF -### Eliminar o Aplanar Anotaciones +### Eliminar o aplanar anotaciones -Las anotaciones pueden eliminarse cuando no son necesarias. Cuando son necesarias pero no requieren edición adicional, pueden aplanarse. Ambas técnicas reducirán el tamaño del archivo. +Las anotaciones pueden eliminarse cuando son innecesarias. Cuando son necesarias pero no requieren edición adicional, pueden aplanarse. Ambas técnicas reducirán el tamaño del archivo. ```python +import aspose.pdf as ap +from os import path, stat +import sys - import aspose.pdf as ap - # Abrir documento - document = ap.Document(input_pdf) - # Aplanar anotaciones +def flatten_annotations(infile, outfile): + # Open document + document = ap.Document(infile) + # Flatten annotations for page in document.pages: for annotation in page.annotations: annotation.flatten() - # Guardar documento actualizado - document.save(output_pdf) + # Save updated document + document.save(outfile) ``` -### Eliminar Campos de Formularios +### Eliminando campos de formulario Si el documento PDF contiene AcroForms, podemos intentar reducir el tamaño del archivo aplanando los campos de formulario. ```python +import aspose.pdf as ap +from os import path, stat +import sys - import aspose.pdf as ap - # Cargar formulario PDF fuente - doc = ap.Document(input_pdf) +def flatten_forms(infile, outfile): + # Load source PDF form + doc = ap.Document(infile) - # Aplanar Formularios + # Flatten Forms if len(doc.form.fields) > 0: for item in doc.form.fields: item.flatten() - # Guardar el documento actualizado - doc.save(output_pdf) + # Save the updated document + doc.save(outfile) + file_stats_1 = stat(infile) + file_stats_2 = stat(outfile) + print( + "Original file size: {}. Reduced file size: {}".format( + file_stats_1.st_size, file_stats_2.st_size + ) + ) ``` -### Convertir un PDF de espacio de color RGB a escala de grises +### Convertir un PDF del espacio de color RGB a escala de grises -Un archivo PDF comprende Texto, Imagen, Adjunto, Anotaciones, Gráficos y otros objetos. Puede surgir la necesidad de convertir un PDF de espacio de color RGB a escala de grises para que sea más rápido al imprimir esos archivos PDF. Además, cuando el archivo se convierte a escala de grises, el tamaño del documento también se reduce, pero igualmente puede causar una disminución en la calidad del documento. Esta característica es compatible actualmente con la función Pre-Flight de Adobe Acrobat, pero cuando se habla de automatización de Office, Aspose.PDF es una solución definitiva para proporcionar tales ventajas para manipulaciones de documentos. Para cumplir con este requisito, se puede usar el siguiente fragmento de código. +Un archivo PDF comprende Text, Image, Attachment, Annotations, Graphs y otros objetos. Puede encontrarse con la necesidad de convertir un PDF del espacio de color RGB a escala de grises para que la impresión de esos archivos PDF sea más rápida. Además, cuando el archivo se convierte a escala de grises, el tamaño del documento también se reduce, pero también puede provocar una disminución de la calidad del documento. Esta funcionalidad está soportada actualmente por la característica Pre-Flight de Adobe Acrobat, pero al hablar de automatización de Office, Aspose.PDF es una solución definitiva para proporcionar tales ventajas en la manipulación de documentos. Para cumplir con este requerimiento, se puede usar el siguiente fragmento de código. ```python +import aspose.pdf as ap +from os import path, stat +import sys - import aspose.pdf as ap - # Cargar archivo PDF de origen - document = ap.Document(input_pdf) +def сonvert_PDF_from_RGB_colorspace_to_grayscale(infile, outfile): + document = ap.Document(infile) strategy = ap.RgbToDeviceGrayConversionStrategy() for page in document.pages: - # Convertir la imagen de espacio de color RGB a espacio de color de escala de grises + # Convert the RGB colorspace image to GrayScale colorspace strategy.convert(page) - # Guardar archivo resultante - document.save(output_pdf) + # Save resultant file + document.save(outfile) ``` - ### Compresión FlateDecode -Aspose.PDF para Python a través de .NET proporciona soporte de compresión FlateDecode para la funcionalidad de Optimización de PDF. El siguiente fragmento de código muestra cómo usar la opción en Optimización para almacenar imágenes con compresión **FlateDecode**: +Aspose.PDF for Python via .NET brinda soporte de compresión FlateDecode para la funcionalidad de Optimización de PDF. El siguiente fragmento de código muestra cómo usar la opción en Optimización para almacenar imágenes con compresión **FlateDecode**: ```python +import aspose.pdf as ap +from os import path, stat +import sys + - import aspose.pdf as ap +def using_flatedecode_compression(infile, outfile): - # Abrir Documento - doc = ap.Document(input_pdf) - # Inicializar OptimizationOptions + # Open Document + doc = ap.Document(infile) + # Initialize OptimizationOptions optimizationOptions = ap.optimization.OptimizationOptions() - # Para optimizar la imagen usando Compresión FlateDecode, establecer opciones de optimización en Flate - optimizationOptions.image_compression_options.encoding = ap.optimization.ImageEncoding.FLATE - # Establecer Opciones de Optimización + # To optimise image using FlateDecode Compression set optimization options to Flate + optimizationOptions.image_compression_options.encoding = ( + ap.optimization.ImageEncoding.FLATE + ) + # Set Optimization Options doc.optimize_resources(optimizationOptions) - # Guardar Documento - doc.save(output_pdf) + # Save Document + doc.save(outfile) ``` - \ No newline at end of file +## Temas de documentos relacionados + +- [Trabajar con documentos PDF en Python](/pdf/es/python-net/working-with-documents/) +- [Fusionar archivos PDF en Python](/pdf/es/python-net/merge-pdf-documents/) +- [Dividir archivos PDF en Python](/pdf/es/python-net/split-document/) +- [Manipular documentos PDF en Python](/pdf/es/python-net/manipulate-pdf-document/) + diff --git a/es/python-net/advanced-operations/working-with-documents/split-pdf/_index.md b/es/python-net/advanced-operations/working-with-documents/split-pdf/_index.md index 480e73169..8368743e4 100644 --- a/es/python-net/advanced-operations/working-with-documents/split-pdf/_index.md +++ b/es/python-net/advanced-operations/working-with-documents/split-pdf/_index.md @@ -1,178 +1,372 @@ --- -title: Dividir PDF programáticamente en Python +title: Dividir archivos PDF en Python linktitle: Dividir archivos PDF type: docs weight: 60 url: /es/python-net/split-pdf-document/ -description: Este tema muestra cómo dividir páginas de PDF en archivos PDF individuales en tus aplicaciones de Python. -lastmod: "2023-04-17" +description: Aprende cómo dividir páginas PDF en archivos PDF separados en Python. +lastmod: "2026-04-15" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Dividir páginas PDF usando Python +Abstract: El artículo analiza el proceso de dividir páginas PDF en archivos individuales usando Python, resaltando la utilidad de dicha función para gestionar documentos PDF grandes. Hace referencia al Aspose.PDF Splitter, una herramienta en línea diseñada para demostrar la funcionalidad de división de PDF. El artículo proporciona un método detallado para lograr esto en aplicaciones Python, que implica iterar a través de las páginas de un documento PDF mediante la `PageCollection` del objeto `Document`. Para cada página, se crea un nuevo objeto `Document`, se añade la página a este, y el nuevo archivo PDF se guarda usando el método `save()`. Un fragmento de código Python adjunto ilustra este proceso, mostrando los pasos necesarios para dividir un documento PDF en archivos separados iterando sus páginas y guardando cada una como un PDF individual. --- - - - -Dividir páginas de PDF puede ser una función útil para aquellos que desean separar un archivo grande en páginas individuales o grupos de páginas. - -## Ejemplo en Vivo - -[Aspose.PDF Splitter](https://products.aspose.app/pdf/splitter) es una aplicación web gratuita en línea que te permite investigar cómo funciona la funcionalidad de división de presentaciones. - -[![Aspose Split PDF](splitter.png)](https://products.aspose.app/pdf/splitter) - -Este tema muestra cómo dividir páginas de PDF en archivos PDF individuales en tus aplicaciones de Python. Para dividir páginas de PDF en archivos PDF de una sola página usando Python, se pueden seguir los siguientes pasos: - -1. Recorre las páginas del documento PDF a través de la colección [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) del objeto [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) -1. Para cada iteración, crea un nuevo objeto Document y añade el objeto [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) individual al documento vacío - -1. Guarda el nuevo PDF usando el método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) - -## Dividir PDF en múltiples archivos o pdfs separados en Python - -El siguiente fragmento de código en Python te muestra cómo dividir las páginas de un PDF en archivos PDF individuales. + +Dividir páginas PDF puede ser una característica útil para quienes desean dividir un archivo grande en páginas separadas o grupos de páginas. + +Utilice este flujo de trabajo cuando necesite dividir archivos PDF grandes en archivos de una sola página o en conjuntos de documentos más pequeños para distribución, revisión o procesamiento posterior. + +## Ejemplo en vivo + +[Divisor de Aspose.PDF](https://products.aspose.app/pdf/splitter) es una aplicación web gratuita en línea que le permite investigar cómo funciona la funcionalidad de división de presentaciones. + +[![Aspose Dividir PDF](splitter.png)](https://products.aspose.app/pdf/splitter) + +Este tema muestra cómo dividir páginas PDF en archivos PDF individuales en sus aplicaciones Python. Para dividir páginas PDF en archivos PDF de una sola página usando Python, se pueden seguir los siguientes pasos: + +1. Recorrer las páginas del documento PDF a través de la [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) del objeto [ColecciónDePáginas](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) colección +1. Para cada iteración, crea un nuevo objeto Document y agrega el individual [Página](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) objeto en el documento vacío +1. Guardar el nuevo PDF usando [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método + +## Dividir PDF en varios archivos o pdfs separados en Python + +El siguiente fragmento de código Python le muestra cómo dividir las páginas PDF en archivos PDF individuales. + +```python +import sys +import aspose.pdf as ap +from os import path + + +def split_documents(infile, outdir): + document = ap.Document(infile) + for page_num in range(1, len(document.pages) + 1): + with ap.Document() as new_document: + new_document.pages.add(document.pages[page_num]) + new_document.save(path.join(outdir, f"Page_{page_num}.pdf")) +``` + +## Dividir un PDF en dos partes iguales + +1. Cargue el documento PDF. +1. Determinar el número total de páginas. +1. Calcule el punto medio. +1. Crea el primer documento de salida. +1. Eliminar las páginas de la segunda mitad del primer documento. +1. Guarda la primera parte. +1. Cree el segundo documento de salida. +1. Eliminar las páginas de la primera mitad del segundo documento. +1. Guardar la segunda parte. + +```python +import sys +import aspose.pdf as ap +from os import path + + +def split_documents_into_two_parts(infile, outdir): + document = ap.Document(infile) + total_pages = len(document.pages) + mid_point = total_pages // 2 + + # First part + with ap.Document(infile) as first_document: + first_part_range = range(mid_point + 1, total_pages + 1) + first_document.pages.delete(first_part_range) + first_document.save(path.join(outdir, "Part_1.pdf")) + + # Second part + with ap.Document(infile) as second_document: + second_part_range = range(1, mid_point + 1) + second_document.pages.delete(second_part_range) + second_document.save(path.join(outdir, "Part_2.pdf")) +``` + +## Dividir un PDF en varios archivos cada N páginas + +Divida un documento PDF en varios archivos más pequeños basándose en un número fijo de páginas usando Aspose.PDF for Python via .NET. + +1. Cargue el documento PDF. +1. Determinar el número total de páginas. +1. Definir páginas por parte. +1. Itera a través del documento en fragmentos. +1. Calcule el rango de páginas para cada parte. +1. Crea un nuevo documento para cada parte. +1. Copiar páginas al nuevo documento. +1. Guarda el documento dividido. +1. Repita hasta que se procesen todas las páginas. ```python +import sys +import aspose.pdf as ap +from os import path - import aspose.pdf as ap - # Abrir documento - document = ap.Document(input_pdf) +def split_documents_every_n_pages(infile, outdir, pages_per_part=3): + document = ap.Document(infile) + total_pages = len(document.pages) - page_count = 1 + part_index = 1 + for start_page in range(1, total_pages + 1, pages_per_part): + end_page = min(start_page + pages_per_part - 1, total_pages) - # Bucle a través de todas las páginas - for pdfPage in document.pages: - new_document = ap.Document() - new_document.pages.add(pdfPage) - new_document.save(output_path + "_page_" + str(page_count) + ".pdf") - page_count = page_count + 1 + with ap.Document() as part_document: + for page_num in range(start_page, end_page + 1): + part_document.pages.add(document.pages[page_num]) + part_document.save( + path.join(outdir, f"Every_{pages_per_part}_Part_{part_index}.pdf") + ) + + part_index += 1 +``` + +## Dividir un PDF por rangos de página personalizados + +Dividir un documento PDF en varios archivos basados en rangos de páginas personalizados usando Aspose.PDF for Python. + +1. Cargue el documento PDF. +1. Determinar el número total de páginas. +1. Crea una lista de tuplas que representen rangos (start_page, end_page). +1. Iterar a través de los rangos definidos. +1. Validar la página de inicio. +1. Ajusta la página final. +1. Validar el rango efectivo. +1. Cree un nuevo documento para cada rango. +1. Copiar páginas al nuevo documento. +1. Guarde cada documento dividido. + +```python +import sys +import aspose.pdf as ap +from os import path + + +def split_documents_by_page_ranges(infile, outdir): + document = ap.Document(infile) + total_pages = len(document.pages) + # Define ranges as (start_page, end_page). Use None to indicate last page. + ranges = [(1, 3), (4, 6), (7, None)] + + for index, (start_page, end_page) in enumerate(ranges, start=1): + if start_page > total_pages: + continue + + effective_end = total_pages if end_page is None else min(end_page, total_pages) + if start_page > effective_end: + continue + + with ap.Document() as range_document: + for page_num in range(start_page, effective_end + 1): + range_document.pages.add(document.pages[page_num]) + range_document.save( + path.join(outdir, f"Range_{index}_{start_page}_to_{effective_end}.pdf") + ) +``` + +## Dividir un PDF en Primera página y Páginas restantes + +Separe la primera página de un documento PDF del resto de las páginas usando Aspose.PDF for Python. + +1. Cargue el documento PDF. +1. Determinar el número total de páginas. +1. Verifique si el documento está vacío. +1. Crea un documento para la primera página. +1. Agregar la primera página. +1. Guardar el documento de la primera página. +1. Verifique si hay páginas adicionales. +1. Crea un documento para las páginas restantes. +1. Copiar páginas restantes. +1. Guarda el documento de páginas restantes. + +```python +import sys +import aspose.pdf as ap +from os import path + + +def split_documents_first_page_and_rest(infile, outdir): + document = ap.Document(infile) + total_pages = len(document.pages) + + if total_pages == 0: + return + + with ap.Document() as first_page_document: + first_page_document.pages.add(document.pages[1]) + first_page_document.save(path.join(outdir, "First_Page.pdf")) + + if total_pages == 1: + return + + with ap.Document() as remaining_pages_document: + for page_num in range(2, total_pages + 1): + remaining_pages_document.pages.add(document.pages[page_num]) + remaining_pages_document.save(path.join(outdir, "Remaining_Pages.pdf")) ``` - \ No newline at end of file +## Dividir un PDF en la última página y las páginas anteriores + +Extraiga la última página de un documento PDF y sepárela de las páginas restantes usando Aspose.PDF for Python. + +1. Cargue el documento PDF. +1. Determinar el número total de páginas. +1. Verifique si el documento está vacío. +1. Crea un documento para la última página. +1. Agregar la última página. +1. Guarda el documento de la última página. +1. Verificar documentos de una sola página. +1. Elimina la última página del documento original. +1. Guarda las páginas restantes. + +```python +import sys +import aspose.pdf as ap +from os import path + + +def split_documents_last_page_and_rest(infile, outdir): + document = ap.Document(infile) + total_pages = len(document.pages) + + if total_pages == 0: + return + + with ap.Document() as last_page_document: + last_page_document.pages.add(document.pages[total_pages]) + last_page_document.save(path.join(outdir, "Last_Page.pdf")) + + if total_pages == 1: + return + + document.pages.delete(total_pages) # Remove last page from original document + document.save(path.join(outdir, "Previous_Pages.pdf")) +``` + +## Dividir un PDF en tres partes + +Divida un documento PDF en tres partes separadas usando Aspose.PDF for Python. + +1. Cargue el documento PDF. +1. Determinar el número total de páginas. +1. Verifique si el documento está vacío. +1. Calcular el tamaño de la pieza. +1. Iterar a través de tres partes. +1. Determine el rango de páginas para cada parte. +1. Validar el rango de páginas. +1. Crea un nuevo documento para cada parte. +1. Copiar páginas en el documento de la parte. +1. Guarda cada parte. + +```python +import sys +import aspose.pdf as ap +from os import path + + +def split_documents_into_three_parts(infile, outdir): + document = ap.Document(infile) + total_pages = len(document.pages) + + if total_pages == 0: + return + + part_size = max(1, (total_pages + 2) // 3) + + for part_index in range(3): + start_page = part_index * part_size + 1 + end_page = min((part_index + 1) * part_size, total_pages) + + if start_page > total_pages: + break + + with ap.Document() as part_document: + for page_num in range(start_page, end_page + 1): + part_document.pages.add(document.pages[page_num]) + part_document.save(path.join(outdir, f"Three_Parts_{part_index + 1}.pdf")) +``` + +## Divisor de páginas PDF personalizado + +Divida un documento PDF en varios archivos basándose en grupos de páginas definidos de forma personalizada usando Aspose.PDF for Python. + +```python +import sys +import aspose.pdf as ap +from os import path + + +def split_documents_custom_page_groups(infile, outdir): + document = ap.Document(infile) + total_pages = len(document.pages) + groups = [ + [1, 2, 5], + [3, 4, 6, 7], + ] + + for group_index, group in enumerate(groups, start=1): + valid_pages = [page_num for page_num in group if 1 <= page_num <= total_pages] + if not valid_pages: + continue + + with ap.Document() as group_document: + for page_num in valid_pages: + group_document.pages.add(document.pages[page_num]) + group_document.save(path.join(outdir, f"Custom_Group_{group_index}.pdf")) +``` + +## Dividir PDF en páginas individuales con nombres de archivo estables + +Divida un documento PDF en páginas individuales y guárdelas con nombres de archivo estables utilizando Aspose.PDF for Python. + +```python +import sys +import aspose.pdf as ap +from os import path + + +def split_documents_with_stable_filenames(infile, outdir): + document = ap.Document(infile) + total_pages = len(document.pages) + + for page_num in range(1, total_pages + 1): + with ap.Document() as new_document: + new_document.pages.add(document.pages[page_num]) + new_document.save(path.join(outdir, f"Page_{page_num:03d}.pdf")) +``` + +## Dividir PDF en páginas impares y pares + +Divida un documento PDF en dos archivos separados que contengan, respectivamente, las páginas impares y pares, usando Aspose.PDF for Python via .NET. + +```python +import sys +import aspose.pdf as ap +from os import path + + +def split_documents_odd_even_pages(infile, outdir): + document = ap.Document(infile) + total_pages = len(document.pages) + + # Odd pages document + with ap.Document(infile) as document: + with ap.Document() as odd_document: + for page_num in range(1, total_pages + 1, 2): + odd_document.pages.add(document.pages[page_num]) + odd_document.save(path.join(outdir, "Odd_Pages.pdf")) + + with ap.Document() as even_document: + for page_num in range(2, total_pages + 1, 2): + even_document.pages.add(document.pages[page_num]) + even_document.save(path.join(outdir, "Even_Pages.pdf")) +``` + +## Temas de documentos relacionados + +- [Trabajar con documentos PDF en Python](/pdf/es/python-net/working-with-documents/) +- [Fusionar archivos PDF en Python](/pdf/es/python-net/merge-pdf-documents/) +- [Optimizar archivos PDF en Python](/pdf/es/python-net/optimize-pdf/) +- [Manipular documentos PDF en Python](/pdf/es/python-net/manipulate-pdf-document/) + diff --git a/es/python-net/advanced-operations/working-with-documents/working-with-headings/_index.md b/es/python-net/advanced-operations/working-with-documents/working-with-headings/_index.md deleted file mode 100644 index 0de75e358..000000000 --- a/es/python-net/advanced-operations/working-with-documents/working-with-headings/_index.md +++ /dev/null @@ -1,218 +0,0 @@ ---- -title: Trabajando con Encabezados en PDF -type: docs -weight: 40 -url: /es/python-net/working-with-headings/ -description: Crear numeración en el encabezado de su documento PDF con Python. Aspose.PDF para Python a través de .NET ofrece diferentes tipos de estilos de numeración. -lastmod: "2023-04-17" -sitemap: - changefreq: "weekly" - priority: 0.7 ---- - - - -## Aplicar Estilo de Numeración en Encabezados - -Los encabezados son partes importantes de cualquier documento. Los escritores siempre intentan hacer que los encabezados sean más prominentes y significativos para sus lectores. Si hay más de un encabezado en un documento, un escritor tiene varias opciones para organizar estos encabezados. Una de las aproximaciones más comunes para organizar encabezados es escribirlos en Estilo de Numeración. - -[Aspose.PDF para Python via .NET](/pdf/es/python-net/) ofrece muchos estilos de numeración predefinidos. Estos estilos de numeración predefinidos se almacenan en una enumeración, [NumberingStyle](https://reference.aspose.com/pdf/python-net/aspose.pdf/numberingstyle/). Los valores predefinidos de la enumeración NumberingStyle y sus descripciones se dan a continuación: - -|**Tipos de Encabezado**|**Descripción**| -| :- | :- | -|NumeralsArabic|Tipo árabe, por ejemplo, 1,1.1,...| -|NumeralsRomanUppercase|Tipo romano mayúscula, por ejemplo, I,I.II, ...| -|NumeralsRomanLowercase|Tipo romano minúscula, por ejemplo, i,i.ii, ...| -|LettersUppercase|Tipo inglés mayúscula, por ejemplo, A,A.B, ...| - -|LettersLowercase|Tipo inglés minúscula, por ejemplo, a,a.b, ...| -La propiedad [style](https://reference.aspose.com/pdf/python-net/aspose.pdf/heading/#properties) de la clase [Heading](https://reference.aspose.com/pdf/python-net/aspose.pdf/heading/) se utiliza para establecer los estilos de numeración de los encabezados. - -|**Figura: Estilos de numeración predefinidos**| -| :- | -El código fuente, para obtener la salida mostrada en la figura anterior, se proporciona a continuación en el ejemplo. - -```python - - import aspose.pdf as ap - - document = ap.Document() - document.page_info.width = 612.0 - document.page_info.height = 792.0 - document.page_info.margin = ap.MarginInfo() - document.page_info.margin.left = 72 - document.page_info.margin.right = 72 - document.page_info.margin.top = 72 - document.page_info.margin.bottom = 72 - - page = document.pages.add() - page.page_info.width = 612.0 - page.page_info.height = 792.0 - page.page_info.margin = ap.MarginInfo() - page.page_info.margin.left = 72 - page.page_info.margin.right = 72 - page.page_info.margin.top = 72 - page.page_info.margin.bottom = 72 - - float_box = ap.FloatingBox() - float_box.margin = page.page_info.margin - - page.paragraphs.add(float_box) - - heading = ap.Heading(1) - heading.is_in_list = True - heading.start_number = 1 - heading.text = "Lista 1" - heading.style = ap.NumberingStyle.NUMERALS_ROMAN_LOWERCASE - heading.is_auto_sequence = True - - float_box.paragraphs.add(heading) - - heading2 = ap.Heading(1) - heading2.is_in_list = True - heading2.start_number = 13 - heading2.text = "Lista 2" - heading2.style = ap.NumberingStyle.NUMERALS_ROMAN_LOWERCASE - heading2.is_auto_sequence = True - - float_box.paragraphs.add(heading2) - - heading3 = ap.Heading(2) - heading3.is_in_list = True - heading3.start_number = 1 - heading3.text = "el valor, a la fecha de vigencia del plan, de la propiedad que se distribuirá bajo el plan debido a cada permitido" - heading3.style = ap.NumberingStyle.LETTERS_LOWERCASE - heading3.is_auto_sequence = True - - float_box.paragraphs.add(heading3) - document.save(output_pdf) -``` - - - \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-forms/_index.md b/es/python-net/advanced-operations/working-with-forms/_index.md index aed903090..2c5fa421b 100644 --- a/es/python-net/advanced-operations/working-with-forms/_index.md +++ b/es/python-net/advanced-operations/working-with-forms/_index.md @@ -1,84 +1,22 @@ --- -title: Trabajando con Formularios usando Python -linktitle: Trabajando con Formularios +title: Trabajar con formularios PDF en Python +linktitle: Trabajar con formularios type: docs weight: 60 url: /es/python-net/working-with-forms/ -description: Esta sección describe cómo trabajar con AcroForms en documentos PDF con Aspose.PDF. para Python vía .NET. -lastmod: "2023-02-17" +description: Esta sección describe cómo trabajar con AcroForms en documentos PDF con Aspose.PDF for Python via .NET. +lastmod: "2026-05-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo trabajar con formularios en Python +Abstract: Este artículo describe un método sencillo para completar programáticamente documentos PDF utilizando la biblioteca Aspose.PDF for Python via .NET. Destaca el proceso de utilizar la biblioteca para identificar y mapear campos en PDFs existentes que utilizan AcroForms. Los AcroForms son formularios electrónicos que permiten a los usuarios rellenar, enviar y almacenar información de manera eficiente, sirviendo como una herramienta conveniente para la recopilación de datos. Además, el artículo ofrece información sobre la creación de formularios, el relleno de campos de formulario, la extracción de datos y la gestión de campos en PDFs utilizando la biblioteca Python. --- - +Esta sección describe un enfoque rápido y sencillo para completar programáticamente un documento PDF mediante el uso de la biblioteca Aspose.PDF for Python via .NET. También explica cómo utilizar Aspose.PDF for Python para detectar y mapear los campos disponibles en un PDF existente con AcroForms. -Esta sección describe un enfoque rápido y sencillo para completar programáticamente un documento PDF mediante el uso de la biblioteca Aspose.PDF para Python a través de .NET. La sección también discute cómo se podría usar Aspose.PDF para Python para descubrir y mapear los campos disponibles dentro de un PDF existente con AcroForms. +AcroForms permite a los usuarios rellenar, enviar y almacenar los formularios electrónicamente, lo que los convierte en una forma cómoda y eficiente de recopilar información. -AcroForms permite a los usuarios completar, enviar y almacenar formularios electrónicamente, lo que los convierte en una forma conveniente y eficiente de recopilar información. - -- [AcroForms](/pdf/es/python-net/acroforms/) - crear formulario, llenar campo de formulario, extraer datos del formulario, agregar y eliminar campos en tu PDF con la biblioteca de Python. \ No newline at end of file +- [AcroForms](/pdf/es/python-net/acroforms/) - crear formularios, rellenar campos, extraer datos y agregar o eliminar campos en un PDF con la biblioteca de Python. +- [Formularios XFA](/pdf/es/python-net/xfa-forms/) - convertir XFA y usar `IgnoreNeedsRendering`. diff --git a/es/python-net/advanced-operations/working-with-forms/acroforms/_index.md b/es/python-net/advanced-operations/working-with-forms/acroforms/_index.md index f67215fe2..dfd945f29 100644 --- a/es/python-net/advanced-operations/working-with-forms/acroforms/_index.md +++ b/es/python-net/advanced-operations/working-with-forms/acroforms/_index.md @@ -4,155 +4,30 @@ linktitle: AcroForms type: docs weight: 10 url: /es/python-net/acroforms/ -description: Con Aspose.PDF para Python puedes crear un formulario desde cero, completar el campo del formulario en un documento PDF, extraer datos del formulario, etc. -lastmod: "2023-02-17" +description: Aprenda cómo crear, rellenar, extraer, importar, exportar y administrar campos de AcroForm en documentos PDF utilizando Aspose.PDF for Python via .NET. +lastmod: "2026-04-28" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Guía para trabajar con AcroForms en Python +Abstract: Esta sección introduce AcroForms y explica cómo trabajar con formularios PDF interactivos utilizando Aspose.PDF for Python via .NET. Cubre flujos de trabajo principales como crear formularios, rellenar campos, extraer valores, importar y exportar datos de formularios, y modificar o eliminar campos de formulario. Estos tutoriales le ayudan a crear canalizaciones prácticas de procesamiento de formularios para escenarios de automatización de documentos. --- - - ## Fundamentos de AcroForms -**AcroForms** - tecnología de formularios PDF única de Adobe. AcroForms es un formulario orientado a la página. Aparecieron por primera vez en 1998. Aceptan entrada en forma de formato de Datos o FDF y formato de Datos de formulario XML o xFDF. Proveedores de terceros apoyan AcroForms. Cuando Adobe introdujo AcroForms, los llamaron el "formulario PDF, que es el autor de Adobe Acrobat Pro/Standard y no es un tipo especial de formulario XFA estático o dinámico. AcroForms son portátiles y funcionan en todas las plataformas. - -Puedes usar AcroForms para agregar páginas adicionales al documento de formulario PDF. Gracias al concepto de Plantillas, puedes usar AcroForms para apoyar el llenado del formulario con múltiples registros de base de datos. - -PDF 1.7 admite dos métodos diferentes para integrar datos y formularios PDF. +AcroForms son formularios PDF interactivos y orientados a páginas, introducidos por Adobe e incluidos en la especificación PDF desde la versión 1.2. Son ampliamente compatibles y pueden usarse para la captura de datos, validación e intercambio en flujos de trabajo multiplataforma. -*AcroForms (también conocidos como formularios Acrobat)*, introducidos e incluidos en la especificación de formato PDF 1.2. +En flujos de trabajo basados en AcroForm, los datos del formulario pueden intercambiarse en formatos como FDF y XFDF. Esto hace que AcroForms sea adecuado para escenarios en los que necesita rellenar campos previamente desde sistemas externos, extraer los valores enviados o sincronizar los datos del formulario entre documentos. -Para un aprendizaje más detallado de las capacidades de la biblioteca Java, consulta los siguientes artículos: +Aspose.PDF for Python via .NET ofrece API para crear y administrar AcroForms de forma programática, incluyendo el llenado de campos, la exportación de datos, la modificación de la estructura del formulario y la adición de acciones de envío. -- [Crear AcroForm](/pdf/es/python-net/create-form) - crear formulario desde cero con Python. -- [Rellenar AcroForm](/pdf/es/python-net/fill-form) - rellena el campo de formulario en tu documento PDF. -- [Extraer AcroForm](/pdf/es/python-net/extract-form) - obtiene el valor de todos o de un campo individual del documento PDF. +Para ejemplos prácticos, consulte los siguientes artículos: - \ No newline at end of file +- [Crear AcroForm](/pdf/es/python-net/create-form/) - crear un formulario desde cero. +- [Rellenar AcroForm](/pdf/es/python-net/fill-form/) - rellenar campos de formulario en un documento PDF. +- [Extraer AcroForm](/pdf/es/python-net/extract-form/) - extraer valores de todos los campos o de un campo específico. +- [Importar y Exportar datos de Form](/pdf/es/python-net/import-export-form-data/) - importar y exportar datos de formulario en formatos comunes. +- [Modificando AcroForm](/pdf/es/python-net/modifying-form/) - modificar propiedades del campo AcroForm. +- [Eliminar formularios de PDF](/pdf/es/python-net/remove-form/) - eliminar campos de formulario de un documento PDF. +- [Publicar formularios](/pdf/es/python-net/posting-form/) - añadir funcionalidad de envío a un formulario PDF. diff --git a/es/python-net/advanced-operations/working-with-forms/acroforms/create-form/_index.md b/es/python-net/advanced-operations/working-with-forms/acroforms/create-form/_index.md index e6e1f3cee..90b3af2f0 100644 --- a/es/python-net/advanced-operations/working-with-forms/acroforms/create-form/_index.md +++ b/es/python-net/advanced-operations/working-with-forms/acroforms/create-form/_index.md @@ -1,184 +1,255 @@ --- -title: Crear AcroForm - Crear PDF Rellenable en Python +title: Crear AcroForm - Crear PDF rellenable en Python linktitle: Crear AcroForm type: docs weight: 10 url: /es/python-net/create-form/ -description: Con Aspose.PDF para Python puedes crear un formulario desde cero en tu archivo PDF -lastmod: "2023-02-17" +description: Crear campos AcroForm desde cero en documentos PDF utilizando Aspose.PDF for Python via .NET. +lastmod: "2026-04-28" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo crear AcroForm en PDF utilizando Python +Abstract: Este artículo explica cómo crear campos AcroForm en documentos PDF utilizando Aspose.PDF for Python via .NET. Cubre la creación básica de campos con TextBoxField, la personalización de la apariencia de cajas de texto multi‑widget y tipos de campos adicionales como botones de opción, cuadros combinados, casillas de verificación, listas desplegables, campos de firma y campos de código de barras. Estos ejemplos le ayudan a crear formularios PDF interactivos para la recopilación de datos y flujos de trabajo de automatización de documentos. --- - - - -## Crear formulario desde cero + +## Crear Formulario desde cero ### Agregar campo de formulario en un documento PDF -La clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) proporciona una colección llamada [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/form/) que te ayuda a gestionar campos de formulario en un documento PDF. +El [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) la clase proporciona una colección llamada [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/form/) que le ayuda a gestionar los campos de formulario en un documento PDF. Para agregar un campo de formulario: 1. Crea el campo de formulario que deseas agregar. -1. Llama al método [add](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/form/#methods) de la colección Form. +1. Llamar a la colección Form [agregar](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/form/#methods) método. ### Agregar TextBoxField -El ejemplo a continuación muestra cómo agregar un [TextBoxField](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/textboxfield/). +El siguiente ejemplo muestra cómo agregar un [Campo de cuadro de texto](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/textboxfield/). + +```python +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def add_text_box_field(output_file_name): + document = ap.Document() + page = document.pages.add() + + rectangle = ap.Rectangle(10, 600, 110, 620, True) + text_box_field = ap.forms.TextBoxField(page, rectangle) + text_box_field.partial_name = "textbox1" + text_box_field.value = "Text Box" + + text_box_field.default_appearance = ap.annotations.DefaultAppearance( + "Arial", 10, drawing.Color.dark_blue + ) + + border = ap.annotations.Border(text_box_field) + border.width = 1 + border.style = ap.annotations.BorderStyle.DASHED + border.dash = ap.annotations.Dash(3, 3) + text_box_field.border = border + + text_box_field.characteristics.border = ap.Color.red.to_rgb() + text_box_field.characteristics.background = ap.Color.yellow.to_rgb() + + document.form.add(text_box_field, 1) + document.save(output_file_name) +``` + +### Campo de cuadro de texto Multi-Widget en PDF + +Crea un campo de formulario de cuadro de texto con múltiples apariencias de widget en un PDF usando Python y Aspose.PDF. Coloca varias áreas de entrada de texto en una página, aplica diferentes fuentes y colores a cada widget, personaliza los bordes y establece estilos de fondo para un formulario PDF interactivo. + +1. Crear nuevo documento PDF. +1. Definir posiciones de los campos de texto. +1. Crear diferentes apariencias predeterminadas. +1. Crear campo de cuadro de texto. +1. Aplicar apariencia a cada widget. +1. Personalizar estilo de borde. +1. Agregar campo al formulario. +1. Guardar archivo PDF. + +```python +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def add_text_box_field_nt(output_file_name): + document = ap.Document() + page = document.pages.add() + + rects = [ + ap.Rectangle(10, 600, 110, 620, normalize_coordinates=True), + ap.Rectangle(10, 630, 110, 650, normalize_coordinates=True), + ap.Rectangle(10, 660, 110, 680, normalize_coordinates=True), + ] + + default_appearances = [ + ap.annotations.DefaultAppearance("Arial", 10, drawing.Color.dark_blue), + ap.annotations.DefaultAppearance("Helvetica", 12, drawing.Color.dark_green), + ap.annotations.DefaultAppearance( + ap.text.FontRepository.find_font("Calibri"), 14, drawing.Color.dark_magenta + ), + ] + + text_box_field = ap.forms.TextBoxField(page, rects) + text_box_field.partial_name = "textbox1" + text_box_field.value = "Some text" + + for i, widget in enumerate(text_box_field): + widget.default_appearance = default_appearances[i] + + border = ap.annotations.Border(text_box_field) + border.width = 1 + border.style = ap.annotations.BorderStyle.DASHED + border.dash = ap.annotations.Dash(3, 3) + text_box_field.border = border + + text_box_field.characteristics.border = ap.Color.red.to_rgb() + text_box_field.characteristics.background = ap.Color.yellow.to_rgb() + + document.form.add(text_box_field) + document.save(output_file_name) +``` + +## Agregar Other Form Fields + +Los siguientes fragmentos de código muestran cómo agregar varios tipos de campos, como botones de opción, cuadros combinados, casillas de verificación, listas desplegables, campos de firma y campos de código de barras. Cada función crea un nuevo documento PDF, agrega un campo objetivo con las opciones seleccionadas y guarda el archivo actualizado. + +1. Agregar campo de botón de opción +1. Agregar campo de cuadro combinado +1. Agregar campo de casilla de verificación +1. Agregar campo de lista +1. Agregar campo de firma +1. Agregar campo de código de barras + +### Agregar campo de botón de opción + +```python +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def add_radio_button(output_file_name): + document = ap.Document() + document.pages.add() + + radio = ap.forms.RadioButtonField(document.pages[1]) + radio.add_option( + "Option 1", ap.Rectangle(100, 640, 120, 680, normalize_coordinates=True) + ) + radio.add_option( + "Option 2", ap.Rectangle(140, 640, 160, 680, normalize_coordinates=True) + ) + + document.form.add(radio) + document.save(output_file_name) +``` + +### Agregar campo de cuadro combinado + +```python +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def add_combo_box(output_file_name): + document = ap.Document() + page = document.pages.add() + + combo = ap.forms.ComboBoxField( + page, ap.Rectangle(100, 640, 150, 656, normalize_coordinates=True) + ) + combo.add_option("Red") + combo.add_option("Yellow") + combo.add_option("Green") + combo.add_option("Blue") + combo.selected = 3 + + document.form.add(combo) + document.save(output_file_name) +``` + +### Agregar campo de casilla de verificación ```python +import aspose.pdf as ap +import aspose.pydrawing as drawing - import aspose.pdf as ap +def add_checkbox_field_to_pdf(output_file_name): + document = ap.Document() + page = document.pages.add() - # Abrir documento - pdfDocument = ap.Document(input_file) + checkbox = ap.forms.CheckboxField( + page, ap.Rectangle(50, 620, 100, 650, normalize_coordinates=True) + ) + checkbox.characteristics.background = ap.Color.aqua.to_rgb() + checkbox.style = ap.forms.BoxStyle.CIRCLE - # Crear un campo - textBoxField = ap.forms.TextBoxField(pdfDocument.pages[1], ap.Rectangle(100, 200, 300, 300, True)) - textBoxField.partial_name = "textbox1" - textBoxField.value = "Text Box" + document.form.add(checkbox) + document.save(output_file_name) +``` - border = ap.annotations.Border(textBoxField) - border.width = 5 - border.dash = ap.annotations.Dash(1, 1) - textBoxField.border = border +### Agregar campo de lista - textBoxField.color = ap.Color.green +```python +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def add_list_box_field_to_pdf(output_file_name): + document = ap.Document() + page = document.pages.add() + + list_box = ap.forms.ListBoxField( + page, ap.Rectangle(50, 650, 100, 700, normalize_coordinates=True) + ) + list_box.partial_name = "list" + list_box.add_option("Red") + list_box.add_option("Green") + list_box.add_option("Blue") + + document.form.add(list_box) + document.save(output_file_name) +``` - # Agregar campo al documento - pdfDocument.form.add(textBoxField, 1) +### Agregar campo de firma - # Guardar PDF modificado - pdfDocument.save(output_pdf) +```python +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def add_signature_field(output_file_name): + document = ap.Document() + page = document.pages.add() + + signature_field = ap.forms.SignatureField( + page, ap.Rectangle(100, 700, 200, 800, True) + ) + signature_field.partial_name = "Signature1" + document.form.add(signature_field) + document.save(output_file_name) +``` + +### Agregar campo de código de barras + +```python +import aspose.pdf as ap +import aspose.pydrawing as drawing + +def add_barcode_field(output_file_name): + document = ap.Document() + page = document.pages.add() + + barcode = ap.forms.BarcodeField(page, ap.Rectangle(100, 700, 200, 740, True)) + barcode.partial_name = "Barcode1" + barcode.add_barcode("1234567890") + document.form.add(barcode) + document.save(output_file_name) ``` +## Temas relacionados - \ No newline at end of file +- [Rellenar AcroForm](/pdf/es/python-net/fill-form/) +- [Extraer AcroForm](/pdf/es/python-net/extract-form/) +- [Modificando AcroForm](/pdf/es/python-net/modifying-form/) +- [Importar y Exportar datos de Form](/pdf/es/python-net/import-export-form-data/) diff --git a/es/python-net/advanced-operations/working-with-forms/acroforms/extract-form/_index.md b/es/python-net/advanced-operations/working-with-forms/acroforms/extract-form/_index.md index 73fb30c0b..7c69be584 100644 --- a/es/python-net/advanced-operations/working-with-forms/acroforms/extract-form/_index.md +++ b/es/python-net/advanced-operations/working-with-forms/acroforms/extract-form/_index.md @@ -1,99 +1,53 @@ --- -title: Extraer AcroForm - Extraer datos de formularios de PDF en Python +title: Extraer AcroForm - Extraer datos de Form de PDF en Python linktitle: Extraer AcroForm type: docs weight: 30 url: /es/python-net/extract-form/ -description: Extrae formularios de tu documento PDF con la biblioteca Aspose.PDF para Python. Obtén el valor de un campo individual de un archivo PDF. -lastmod: "2023-02-17" +description: Extraer valores de los campos AcroForm en documentos PDF utilizando Aspose.PDF for Python via .NET. +lastmod: "2026-04-28" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo obtener datos de Form de PDF usando Python +Abstract: Este artículo muestra cómo extraer datos de los campos AcroForm en documentos PDF utilizando Aspose.PDF for Python via .NET. El ejemplo itera a través de los nombres de los campos Form, lee los valores mediante la fachada Form y devuelve un diccionario para el procesamiento posterior. Este flujo de trabajo es útil para la generación de informes, la validación y la integración con sistemas externos. --- - +## Extraer datos de Form -## Extraer datos del formulario +### Obtener valores de todos los campos en un documento PDF -### Obtener valores de todos los campos del documento PDF +Para leer los valores de todos los campos en un documento PDF, itere a través de los nombres de los campos del formulario y recupere cada valor del [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) fachada. -Para obtener valores de todos los campos en un documento PDF, necesitas navegar a través de todos los campos del formulario y luego obtener el valor usando la propiedad Value. Obtén cada campo de la colección Form, en el tipo base de campo llamado [Field](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/field/) y accede a su propiedad [value](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/field/#properties). +Utilice los siguientes pasos: -Los siguientes fragmentos de código en Python muestran cómo obtener los valores de todos los campos de un documento PDF. +1. Vincular el PDF de entrada a un `Form` objeto. +1. Iterar a través de `field_names`. +1. Lea cada valor con `get_field()`. +1. Almacenar valores en un diccionario. +1. Devolver o procesar los valores extraídos. + +El siguiente fragmento de código Python muestra este enfoque. ```python +import aspose.pdf as ap + + +def get_values_from_all_fields(input_file_name): + form = ap.facades.Form(input_file_name) + + form_values = {} + for field_name in form.field_names: + form_values[field_name] = form.get_field(field_name) - import aspose.pdf as ap + print(form_values) + return form_values +``` - # Abrir documento - pdfDocument = ap.Document(input_file) +## Temas relacionados - # Obtener valores de todos los campos - for formField in pdfDocument.form.fields: - # Analizar nombres y valores si es necesario - print("Nombre del campo : " + formField.partial_name) - print("Valor : " + str(formField.value)) \ No newline at end of file +- [Crear AcroForm](/pdf/es/python-net/create-form/) +- [Rellenar AcroForm](/pdf/es/python-net/fill-form/) +- [Importar y Exportar datos de Form](/pdf/es/python-net/import-export-form-data/) +- [Modificando AcroForm](/pdf/es/python-net/modifying-form/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-forms/acroforms/fill-form/_index.md b/es/python-net/advanced-operations/working-with-forms/acroforms/fill-form/_index.md index 48bc4fe73..9fd205f6e 100644 --- a/es/python-net/advanced-operations/working-with-forms/acroforms/fill-form/_index.md +++ b/es/python-net/advanced-operations/working-with-forms/acroforms/fill-form/_index.md @@ -1,164 +1,53 @@ --- -title: Rellenar AcroForm - Rellenar Formulario PDF usando Python +title: Rellenar AcroForm - Rellenar formulario PDF usando Python linktitle: Rellenar AcroForm type: docs weight: 20 url: /es/python-net/fill-form/ -description: Puede rellenar formularios en su documento PDF con la biblioteca Aspose.PDF para Python. -lastmod: "2023-02-17" +description: Rellenar campos AcroForm en un documento PDF mediante Aspose.PDF for Python via .NET. +lastmod: "2026-04-28" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo rellenar un campo de formulario en PDF usando Python +Abstract: Este artículo explica cómo rellenar campos AcroForm en un documento PDF mediante Aspose.PDF for Python via .NET. El ejemplo utiliza la fachada Form, asigna nombres de campos a nuevos valores en un diccionario, actualiza los campos coincidentes y guarda el PDF de salida. Este enfoque es útil para flujos de trabajo automatizados de completado de documentos y procesamiento masivo de formularios. --- - +## Rellenar campo de formulario en un documento PDF -## Rellenar un Campo de Formulario en un Documento PDF +El siguiente ejemplo rellena varios campos en un formulario PDF existente mediante el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) fachada. -Para rellenar un campo de formulario, obtenga el campo de la colección [Formulario](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/form/) del objeto Documento. Luego, establezca el valor del campo utilizando la propiedad [valor](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/form/#properties) del campo. +Utilice los siguientes pasos: -Este ejemplo selecciona un [TextBoxField](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/textboxfield/) y establece su valor utilizando la propiedad Valor. +1. Crea un diccionario con nombres de campo y valores. +1. Vincula el PDF de entrada a un objeto Form. +1. Itera a través de los campos de formulario disponibles. +1. Rellena los campos que existen en el diccionario. +1. Guarda el PDF actualizado. ```python +import aspose.pdf as ap + +def fill_form(input_file_name, output_file_name): + new_field_values = { + "First Name": "Alexander_New", + "Last Name": "Greenfield_New", + "City": "Yellowtown_New", + "Country": "Redland_New", + } - import aspose.pdf as ap + form = ap.facades.Form(input_file_name) - # Abrir documento - pdfDocument = ap.Document(input_file) - for formField in pdfDocument.form.fields: - if formField.partial_name == "Field 1": - # Modificar valor del campo - formField.value = "777" + for field_name in form.field_names: + if field_name in new_field_values: + form.fill_field(field_name, new_field_values[field_name]) - # Guardar documento actualizado - pdfDocument.save(output_pdf) + form.save(output_file_name) ``` +## Temas relacionados - \ No newline at end of file +- [Crear AcroForm](/pdf/es/python-net/create-form/) +- [Extraer AcroForm](/pdf/es/python-net/extract-form/) +- [Importar y Exportar datos de Form](/pdf/es/python-net/import-export-form-data/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-forms/acroforms/import-export-form-data/_index.md b/es/python-net/advanced-operations/working-with-forms/acroforms/import-export-form-data/_index.md new file mode 100644 index 000000000..eb6519e10 --- /dev/null +++ b/es/python-net/advanced-operations/working-with-forms/acroforms/import-export-form-data/_index.md @@ -0,0 +1,226 @@ +--- +title: Importar y Exportar datos del formulario +linktitle: Importar y Exportar datos del formulario +type: docs +weight: 80 +url: /es/python-net/import-export-form-data/ +description: Importar y exportar datos de campos AcroForm en formatos XML, FDF, XFDF y JSON usando Aspose.PDF for Python via .NET. +lastmod: "2026-04-28" +TechArticle: true +AlternativeHeadline: Técnicas de importación y exportación utilizando Aspose.PDF for Python via .NET. +Abstract: Esta compilación presenta un conjunto completo de técnicas de importación y exportación de datos de formularios utilizando Aspose.PDF for Python via .NET. Cubre flujos de trabajo para integrar formularios PDF con formatos de datos externos, incluidos XML, FDF, XFDF y JSON. Los usuarios pueden automatizar el llenado masivo de formularios importando datos estructurados en campos interactivos, o extraer valores de campos para análisis, copia de seguridad o integración con otros sistemas. Los ejemplos demuestran cómo vincular formularios PDF, transferir datos entre formatos y guardar documentos actualizados, lo que permite un procesamiento de documentos escalable y coherente en diversas aplicaciones. +--- + +Esta página muestra flujos de trabajo comunes para importar y exportar datos de AcroForm con Aspose.PDF for Python via .NET. Todas las operaciones usan el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) fachada. + +## Importar datos de FormField desde XML + +Utilice este enfoque para rellenar un formulario PDF a partir de datos XML externos. + +1. Crear un `Form` objeto. +1. Vincular el PDF de entrada. +1. Abre el archivo de datos XML. +1. Importar datos XML al formulario. +1. Guarda el PDF actualizado. + +```python +from io import FileIO +import aspose.pdf as ap + +def import_data_from_xml(input_file_name, data_file_name, output_file_name): + form = ap.facades.Form() + form.bind_pdf(input_file_name) + + with FileIO(data_file_name, "r") as f: + form.import_xml(f) + + form.save(output_file_name) +``` + +## Exportar datos de FormField a XML + +Este método exporta los valores de los campos de formulario de un documento PDF a XML. + +1. Crear un `Form` objeto. +1. Vincular el PDF de entrada. +1. Abra el archivo de salida XML. +1. Exportar datos del formulario a XML. + +```python +from io import FileIO +import aspose.pdf as ap + +def export_data_to_xml(input_file_name, output_file_name): + form = ap.facades.Form() + form.bind_pdf(input_file_name) + with FileIO(output_file_name, "w") as f: + form.export_xml(f) +``` + +## Importar datos de campos de formulario desde FDF + +El `import_data_from_fdf` Método importa datos de campos de formulario de un archivo FDF (Formato de Datos de Formularios) en un formulario PDF. + +1. Crear un `Form` objeto. +1. Vincular el PDF de entrada. +1. Importar los datos del formulario con `import_fdf()`. +1. Guarda el PDF actualizado. + +```python +from io import FileIO +import aspose.pdf as ap + +def import_data_from_fdf(input_file_name, data_file_name, output_file_name): + form = ap.facades.Form() + form.bind_pdf(input_file_name) + + with FileIO(data_file_name, "r") as f: + form.import_fdf(f) + form.save(output_file_name) +``` + +## Exportar datos de campos de formulario a FDF + +Este ejemplo exporta los datos del formulario de un documento PDF a un archivo FDF. + +1. Crear un `Form` objeto. +1. Vincular el documento PDF. +1. Exportar datos del formulario con `export_fdf()`. + +```python +from io import FileIO +import aspose.pdf as ap + +def export_data_to_fdf(input_file_name, output_file_name): + form = ap.facades.Form() + form.bind_pdf(input_file_name) + + with FileIO(output_file_name, "w") as f: + form.export_fdf(f) +``` + +## Importar datos de campos de formulario desde XFDF + +Utilice este método para importar datos de campos de formulario desde un archivo XFDF (Formato de datos de formularios XML) a un formulario PDF. + +1. Crear un `Form` objeto. +1. Vincular el PDF de entrada. +1. Importar datos de formulario desde un archivo XFDF. +1. Guarda el PDF actualizado. + +```python +from io import FileIO +import aspose.pdf as ap + +def import_data_from_xfdf(input_file_name, data_file_name, output_file_name): + form = ap.facades.Form() + form.bind_pdf(input_file_name) + + with FileIO(data_file_name, "r") as f: + form.import_xfdf(f) + form.save(output_file_name) +``` + +## Exportar datos de campo de formulario a XFDF + +Este código exporta los datos de los campos de formulario de un documento PDF a un archivo XFDF. + +1. Crear un `Form` objeto. +1. Vincular el PDF de entrada. +1. Exportar datos del formulario a XFDF. + +```python +from io import FileIO +import aspose.pdf as ap + +def export_data_to_xfdf(input_file_name, output_file_name): + form = ap.facades.Form() + form.bind_pdf(input_file_name) + + with FileIO(output_file_name, "w") as f: + form.export_xfdf(f) +``` + +## Importar datos de otro PDF + +Este ejemplo transfiere datos de campos de formulario de un PDF de origen a un PDF de destino exportando XFDF a un flujo en memoria e importándolo al formulario de destino. + +1. Crear origen y destino `Form` objetos. +1. Vincula los PDFs de origen y destino. +1. Exportar datos del formulario del PDF de origen. +1. Importar datos del formulario al PDF de destino. +1. Guarde el PDF de destino actualizado. + +```python +from io import StringIO +import aspose.pdf as ap + +def import_data_from_another_pdf(source_pdf_name, destination_pdf_name, output_file_name): + form_source = ap.facades.Form() + form_dest = ap.facades.Form() + + form_source.bind_pdf(source_pdf_name) + form_dest.bind_pdf(destination_pdf_name) + + with StringIO() as xfdf_stream: + form_source.export_xfdf(xfdf_stream) + xfdf_stream.seek(0) + form_dest.import_xfdf(xfdf_stream) + + form_dest.save(output_file_name) +``` + +## Extraer campos de formulario a JSON + +Este método exporta los campos de formulario a un archivo JSON mediante `export_json()`. + +1. Crear un `Form` objeto. +1. Abra el archivo de salida JSON. +1. Exportar campos de formulario mediante `export_json()`. + +```python +from io import FileIO +import aspose.pdf as ap + +def extract_form_fields_to_json(input_file_name, output_file_name): + form = ap.facades.Form(input_file_name) + with FileIO(output_file_name, "w") as json_file: + form.export_json(json_file, True) +``` + +## Extraer campos de formulario a documento JSON + +Este ejemplo crea un documento JSON personalizado a partir de los nombres y valores de los campos de formulario. + +1. Crear un objeto Form a partir del archivo de entrada. +1. Inicializa un diccionario vacío para almacenar los datos de los campos del formulario. +1. Iterar a través de todos los campos del formulario y extraer sus valores. +1. Serialice el diccionario de datos del formulario a una cadena JSON con una sangría de 4 espacios. +1. Escriba la cadena JSON en el archivo de salida con codificación UTF-8. + +```python +import json +import aspose.pdf as ap + +def extract_form_fields_to_json_doc(input_file_name, output_file_name): + form = ap.facades.Form(input_file_name) + form_data = {} + for field_name in form.field_names: + form_data[field_name] = form.get_field(field_name) + + json_string = json.dumps(form_data, indent=4) + + with open(output_file_name, "w", encoding="utf-8") as json_file: + json_file.write(json_string) +``` + +## Temas relacionados (enfoque de Fachadas) + +- [Importar datos XML](/pdf/es/python-net/import-xml-data/) +- [Importar datos FDF](/pdf/es/python-net/import-fdf-data/) +- [Importar datos XFDF](/pdf/es/python-net/import-xfdf-data/) +- [Importar datos JSON](/pdf/es/python-net/import-json-data/) +- [Exportar a XML](/pdf/es/python-net/export-to-xml/) +- [Exportar a FDF](/pdf/es/python-net/export-to-fdf/) +- [Exportar a XFDF](/pdf/es/python-net/export-to-xfdf/) +- [Exportar a JSON](/pdf/es/python-net/export-to-json/) diff --git a/es/python-net/advanced-operations/working-with-forms/acroforms/modifying-form/_index.md b/es/python-net/advanced-operations/working-with-forms/acroforms/modifying-form/_index.md new file mode 100644 index 000000000..920c57dd9 --- /dev/null +++ b/es/python-net/advanced-operations/working-with-forms/acroforms/modifying-form/_index.md @@ -0,0 +1,139 @@ +--- +title: Modificando AcroForm +linktitle: Modificando AcroForm +type: docs +weight: 45 +url: /es/python-net/modifying-form/ +description: Modificar campos AcroForm en documentos PDF utilizando Aspose.PDF for Python via .NET, incluyendo borrar texto, establecer límites, aplicar estilos a los campos y eliminar campos. +lastmod: "2026-04-28" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Gestión y personalización de campos de formulario PDF +Abstract: Este artículo presenta ejemplos prácticos para modificar campos AcroForm utilizando Aspose.PDF for Python via .NET. Cubre la eliminación de texto del contenido de formulario Typewriter, el establecimiento y lectura de límites de caracteres en campos de texto, la aplicación de una apariencia de fuente personalizada y la eliminación de campos por nombre. Estos flujos de trabajo respaldan tareas comunes de mantenimiento de formularios en tuberías de procesamiento automático de PDF. +--- + +## Borrar texto en el formulario + +Este ejemplo muestra cómo borrar texto de los campos de formulario Typewriter en un PDF usando Aspose.PDF for Python via .NET. Escanea la primera página del PDF, identifica formularios Typewriter, elimina su contenido y guarda el documento actualizado. Este enfoque es útil para restablecer o sanitizar los campos de formulario antes de redistribuir un PDF. + +1. Cargue el documento PDF de entrada. +1. Acceda a los formularios en la primera página. +1. Iterar sobre cada formulario y comprobar si es un `Typewriter` formulario. +1. Utilice TextFragmentAbsorber para encontrar fragmentos de texto en el formulario. +1. Borre el texto de cada fragmento. +1. Guarde el PDF modificado en el archivo de salida. + +```python +import aspose.pdf as ap + + +def clear_text_in_form(input_file_name, output_file_name): + document = ap.Document(input_file_name) + + forms = document.pages[1].resources.forms + + for form in forms: + if form.it == "Typewriter" and form.subtype == "Form": + absorber = ap.text.TextFragmentAbsorber() + absorber.visit(form) + + for fragment in absorber.text_fragments: + fragment.text = "" + + document.save(output_file_name) +``` + +## Establecer límite de campo + +Usar `set_field_limit(field, limit)` de `FormEditor` para definir el número máximo de caracteres permitidos en un campo de texto. + +1. Cree un `FormEditor` objeto. +1. Vincula el PDF de entrada. +1. Establezca el límite del campo para un campo objetivo. +1. Guarda el PDF actualizado. + +```python +import aspose.pdf as ap + + +def set_field_limit(input_file_name, output_file_name): + form = ap.facades.FormEditor() + form.bind_pdf(input_file_name) + form.set_field_limit("First Name", 15) + form.save(output_file_name) +``` + +## Obtener límite del campo + +También puedes leer el límite de caracteres de un campo de texto. + +1. Cargue el documento PDF. +1. Accede al campo de formulario objetivo. +1. Asegúrese de que el campo sea un `TextBoxField`. +1. Leer e imprimir `max_len`. + +```python +import aspose.pdf as ap +from aspose.pycore import cast, is_assignable + + +def get_field_limit(input_file_name): + document = ap.Document(input_file_name) + if is_assignable(document.form[1], ap.forms.TextBoxField): + text_box_field = cast(ap.forms.TextBoxField, document.form[1]) + print(f"Limit: {text_box_field.max_len}") +``` + +## Establecer fuente personalizada para el campo del formulario + +Este ejemplo establece una apariencia predeterminada personalizada para un campo de cuadro de texto, incluyendo la fuente, el tamaño y el color. + +1. Cargue el documento PDF. +1. Acceda al campo objetivo y verifique su tipo. +1. Buscar la fuente en `FontRepository`. +1. Aplicar un nuevo `DefaultAppearance`. +1. Guarda el PDF actualizado. + +```python +import aspose.pdf as ap +from aspose.pycore import cast, is_assignable + + +def set_form_field_font(input_file_name, output_file_name): + document = ap.Document(input_file_name) + if is_assignable(document.form[1], ap.forms.TextBoxField): + text_box_field = cast(ap.forms.TextBoxField, document.form[1]) + font = ap.text.FontRepository.find_font("Calibri") + text_box_field.default_appearance = ap.annotations.DefaultAppearance( + font, 10, ap.Color.black.to_rgb() + ) + + document.save(output_file_name) +``` + +## Eliminar campos en un formulario existente + +Este código elimina un campo de formulario específico (por su nombre) de un documento PDF y guarda el archivo actualizado usando Aspose.PDF for Python via .NET. + +1. Cargue el documento PDF. +1. Eliminar un campo de formulario por nombre. +1. Guarda el PDF actualizado. + +```python +import aspose.pdf as ap + + +def delete_form_field(input_file_name, output_file_name): + document = ap.Document(input_file_name) + document.form.delete("First Name") + document.save(output_file_name) +``` + +## Temas relacionados + +- [Crear AcroForm](/pdf/es/python-net/create-form/) +- [Rellenar AcroForm](/pdf/es/python-net/fill-form/) +- [Extraer AcroForm](/pdf/es/python-net/extract-form/) +- [Importar y Exportar datos de Form](/pdf/es/python-net/import-export-form-data/) diff --git a/es/python-net/advanced-operations/working-with-forms/acroforms/posting-form/_index.md b/es/python-net/advanced-operations/working-with-forms/acroforms/posting-form/_index.md new file mode 100644 index 000000000..3f87f6dd5 --- /dev/null +++ b/es/python-net/advanced-operations/working-with-forms/acroforms/posting-form/_index.md @@ -0,0 +1,76 @@ +--- +title: Publicar formularios en PDF mediante Python +linktitle: Publicar formularios +type: docs +weight: 75 +url: /es/python-net/posting-form/ +description: Agregar botones de envío y acciones de envío a los PDF AcroForms mediante Aspose.PDF for Python via .NET. +lastmod: "2026-04-28" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo agregar botones de envío y acciones de envío de formularios a un PDF usando Python +Abstract: Este artículo muestra dos enfoques para agregar funcionalidad de envío a formularios PDF mediante Aspose.PDF for Python via .NET. Puedes agregar un botón de envío prefabricado a través de FormEditor o crear un campo de botón personalizado con SubmitFormAction para un control avanzado. Estos patrones ayudan a integrar formularios PDF con puntos finales de procesamiento de formularios del lado del servidor. +--- + +## Agregar botón de envío con FormEditor + +El siguiente fragmento de código muestra cómo agregar un botón de envío a un formulario PDF usando la clase FormEditor en Aspose.PDF for Python via .NET. El botón está configurado para enviar los datos del formulario a una URL especificada al hacer clic. + +1. Cree un `FormEditor` objeto. +1. Agregar un botón de envío a la página objetivo. +1. Establecer la URL de envío y las coordenadas del botón. +1. Guarda el PDF actualizado. + +```python +import aspose.pdf as ap + +def add_submit_button(input_file_name, output_file_name): + editor = ap.facades.FormEditor(input_file_name, output_file_name) + editor.add_submit_btn( + "submitbutton", 1, "Submit", "http://localhost/testing/show", 100, 450, 150, 475 + ) + editor.save() +``` + +## Agregar acción de envío personalizada + +El siguiente fragmento de código explica cómo crear un botón de envío personalizado en un formulario PDF usando Aspose.PDF for Python via .NET. El botón está configurado para enviar los datos del formulario a una URL especificada al hacer clic. + +1. Abra el PDF con ap.Document(). +1. Crear una acción de envío. +1. Establezca la URL de destino y las banderas de envío. +1. Cree un campo de botón y vincule su acción de clic. +1. Agregue el botón al formulario. +1. Guarda el PDF actualizado. + +```python +import aspose.pdf as ap + +def add_submit_action(input_file_name, output_file_name): + document = ap.Document(input_file_name) + + submit_action = ap.annotations.SubmitFormAction() + submit_action.url = ap.FileSpecification("http://localhost:3000/submit") + submit_action.flags = ( + ap.annotations.SubmitFormAction.EXPORT_FORMAT + | ap.annotations.SubmitFormAction.SUBMIT_COORDINATES + ) + + rect = ap.Rectangle(10, 10, 100, 40) + submit_button = ap.forms.ButtonField(document.pages[1], rect) + submit_button.partial_name = "SubmitButton" + submit_button.value = "Submit" + submit_button.actions.on_release_mouse_btn = submit_action + + document.form.add(submit_button, 1) + document.save(output_file_name) +``` + +## Temas relacionados + +- [Crear AcroForm](/pdf/es/python-net/create-form/) +- [Rellenar AcroForm](/pdf/es/python-net/fill-form/) +- [Modificando AcroForm](/pdf/es/python-net/modifying-form/) +- [Importar y Exportar datos de Form](/pdf/es/python-net/import-export-form-data/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-forms/acroforms/remove-form/_index.md b/es/python-net/advanced-operations/working-with-forms/acroforms/remove-form/_index.md new file mode 100644 index 000000000..a71290fb5 --- /dev/null +++ b/es/python-net/advanced-operations/working-with-forms/acroforms/remove-form/_index.md @@ -0,0 +1,65 @@ +--- +title: Eliminar formularios de PDF en Python +linktitle: Eliminar formularios +type: docs +weight: 70 +url: /es/python-net/remove-form/ +description: Eliminar objetos de formulario de las páginas PDF utilizando Aspose.PDF for Python via .NET, incluyendo una limpieza completa y eliminación dirigida. +lastmod: "2026-04-28" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Eliminar formularios de PDF con Aspose.PDF for Python via .NET +Abstract: Este artículo presenta dos enfoques para eliminar elementos de formulario de documentos PDF mediante Aspose.PDF for Python via .NET. El primer método elimina todos los objetos de formulario de una página seleccionada, mientras que el segundo método elimina solo los recursos de formulario Typewriter coincidentes. Estos ejemplos ayudan con la limpieza de formularios, la preparación de plantillas y los flujos de trabajo de normalización de documentos. +--- + +## Eliminar todos los formularios de una página + +Este código elimina todos los objetos de formulario de la página especificada por `page_num` y guarda el documento actualizado. + +1. Cargue el documento PDF. +1. Acceder a los recursos de la página. +1. Borrar objetos de formulario. +1. Guardar el documento actualizado. + +```python +import aspose.pdf as ap + +def remove_all_forms(input_file_name, page_num, output_file_name): + document = ap.Document(input_file_name) + forms = document.pages[page_num].resources.forms + forms.clear() + document.save(output_file_name) +``` + +## Eliminar un tipo de formulario específico + +El siguiente ejemplo recorre los objetos de formulario en una página PDF dada, identifica las anotaciones de formulario de máquina de escribir, las elimina y luego guarda el PDF actualizado usando Aspose.PDF for Python via .NET. + +1. Cargue el documento PDF. +1. Acceder a los formularios de la página. +1. Iterar sobre los formularios. +1. Comprobar formularios de máquina de escribir. +1. Eliminar el formulario coincidente. +1. Guardar el documento actualizado. + +```python +import aspose.pdf as ap + +def remove_specified_form(input_file_name, page_num, output_file_name): + document = ap.Document(input_file_name) + forms = document.pages[page_num].resources.forms + for form in forms: + if form.it == "Typewriter" and form.subtype == "Form": + name = forms.get_form_name(form) + forms.delete(name) + document.save(output_file_name) +``` + +## Temas relacionados + +- [Crear AcroForm](/pdf/es/python-net/create-form/) +- [Rellenar AcroForm](/pdf/es/python-net/fill-form/) +- [Modificando AcroForm](/pdf/es/python-net/modifying-form/) +- [Publicar formularios](/pdf/es/python-net/posting-form/) diff --git a/es/python-net/advanced-operations/working-with-forms/xfa-forms/_index.md b/es/python-net/advanced-operations/working-with-forms/xfa-forms/_index.md new file mode 100644 index 000000000..a1b28765a --- /dev/null +++ b/es/python-net/advanced-operations/working-with-forms/xfa-forms/_index.md @@ -0,0 +1,61 @@ +--- +title: Trabajando con formularios XFA +linktitle: Formularios XFA +type: docs +weight: 20 +url: /es/python-net/xfa-forms/ +description: Aspose.PDF for Python via .NET API le permite trabajar con campos XFA y XFA Acroform en un documento PDF. +lastmod: "2025-02-17" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +## Convertir XFA a Acroform + +{{% alert color="primary" %}} + +Probar en línea +Puede verificar la calidad de la conversión de Aspose.PDF y ver los resultados en línea en este enlace: [products.aspose.app/pdf/xfa/acroform](https://products.aspose.app/pdf/xfa/acroform) + +{{% /alert %}} + +El siguiente fragmento de código muestra cómo convertir un formulario XFA (XML Forms Architecture) dinámico a un AcroForm estándar. + +**Los pasos clave incluyen:** + +1. Cargando el documento PDF de entrada. +1. Cambiando el tipo de formulario a ESTÁNDAR. +1. Guardando el PDF convertido en un archivo nuevo. + +Esta conversión permite una mejor compatibilidad y un manejo coherente de formularios en diferentes lectores y aplicaciones de PDF. + +```python +import aspose.pdf as ap +import sys +from os import path + +def convert_dynamic_xfa_to_acroform(infile: str, outfile: str): + """Convert dynamic XFA form to standard AcroForm.""" + with ap.Document(infile) as document: + document.form.type = ap.forms.FormType.STANDARD + document.save(outfile) +``` + +## Uso de IgnoreNeedsRendering + +Este ejemplo muestra cómo convertir un formulario XFA dinámico a un AcroForm estándar usando Aspose.PDF for Python. El código verifica si el PDF de entrada contiene un formulario XFA y anula la renderización si es necesario. Luego establece el tipo de formulario como STANDARD y guarda el PDF actualizado. + +```python +import aspose.pdf as ap +import sys +from os import path + +def convert_xfa_form_with_ignore_needs_rendering(infile: str, outfile: str): + """Convert XFA form ignoring needs rendering flag.""" + with ap.Document(infile) as document: + if not document.form.needs_rendering and document.form.has_xfa: + document.form.ignore_needs_rendering = True + document.form.type = ap.forms.FormType.STANDARD + document.save(outfile) +``` diff --git a/es/python-net/advanced-operations/working-with-graphs/_index.md b/es/python-net/advanced-operations/working-with-graphs/_index.md new file mode 100644 index 000000000..95b78c29f --- /dev/null +++ b/es/python-net/advanced-operations/working-with-graphs/_index.md @@ -0,0 +1,43 @@ +--- +title: Trabajar con gráficos PDF en Python +linktitle: Trabajando con gráficos +type: docs +weight: 70 +url: /es/python-net/working-with-graphs/ +description: Aprenda cómo dibujar gráficos y formas en archivos PDF con Python, incluyendo arcos, círculos, curvas, líneas, rectángulos y elipses. +lastmod: "2026-05-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Dibuje y personalice formas de gráficos vectoriales en archivos PDF usando Python +Abstract: Esta sección presenta la clase Graph en Aspose.PDF for Python via .NET y explica cómo crear formas vectoriales comunes en documentos PDF. Aprenda cómo agregar y dar estilo a arcos, círculos, curvas, líneas, rectángulos, elipses y validar los límites de las formas. +--- + +## Qué es Graph + +[Aspose.PDF for Python via .NET](/pdf/es/python-net/) provee el [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) clase para dibujar gráficos vectoriales en documentos PDF. + +`Graph` es un elemento a nivel de párrafo, por lo que lo añades a una página a través de la página `paragraphs` colección. Cada gráfico contiene un `Shapes` colección donde puedes agregar objetos de dibujo como líneas, arcos, círculos, curvas, rectángulos y elipses. + +Utiliza esta sección cuando necesites dibujar gráficos vectoriales directamente en páginas PDF en Python, ya sea para gráficos, diagramas, ilustraciones o anotaciones personalizadas en la página. + +## Formas de Graph cubiertas + +Los siguientes tipos de formas son compatibles con el [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) clase: + +- [Arco](/pdf/es/python-net/add-arc/) - dibujar segmentos de arco para círculos parciales y elementos de diagrama curvos. +- [Círculo](/pdf/es/python-net/add-circle/) - crear contornos de círculo o círculos rellenos para marcadores y resaltados visuales. +- [Curva](/pdf/es/python-net/add-curve/) - agregar curvas de estilo Bezier para rutas personalizadas y elementos gráficos suaves. +- [Línea](/pdf/es/python-net/add-line/) - dibujar líneas rectas, incluidas líneas con estilo y líneas discontinuas. +- [Rectángulo](/pdf/es/python-net/add-rectangle/) - crear formas de rectángulo con contorno, relleno, degradado o transparentes. +- [Elipse](/pdf/es/python-net/add-ellipse/) - dibujar formas ovales y añadir texto dentro de ellas cuando sea necesario. + +También puedes validar la colocación de formas con comprobación de límites: + +- [Verifique los límites de la forma en gráficos PDF con Python](/pdf/es/python-net/aspose-pdf-drawing-graph-shapes-bounds-check/) + +Los ejemplos en esta sección se ilustran en la figura a continuación: + +![Figuras en Gráficos](graphs.png) + diff --git a/es/python-net/advanced-operations/working-with-graphs/arc/_index.md b/es/python-net/advanced-operations/working-with-graphs/arc/_index.md new file mode 100644 index 000000000..72bdd5c71 --- /dev/null +++ b/es/python-net/advanced-operations/working-with-graphs/arc/_index.md @@ -0,0 +1,95 @@ +--- +title: Agregar formas de arco a PDF en Python +linktitle: Agregar arco +type: docs +weight: 10 +url: /es/python-net/add-arc/ +description: Aprende cómo dibujar y rellenar formas de arco en archivos PDF con Python. +lastmod: "2026-04-16" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Dibuja formas de arco en archivos PDF usando Python +Abstract: Este artículo muestra cómo agregar formas de arco a documentos PDF con Aspose.PDF for Python via .NET. Cubre la creación de arcos contorneados, el dibujo de segmentos de arco rellenos y su incorporación a un contenedor Graph. +--- + +## Agregar objeto Arc + +Aspose.PDF for Python via .NET le permite agregar [Arco](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/arc/) formas a páginas PDF usando el [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) clase. Puede dibujar arcos contorneados y segmentos de arco rellenos para diagramas e ilustraciones técnicas. + +Siga los pasos a continuación: + +1. Crear [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) instancia. +1. Crear [Objeto de gráfico](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/) con ciertas dimensiones. +1. Establecer [borde](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/#properties) para el objeto Graph. +1. Cree un objeto arco correspondiente. +1. Agregue este objeto a la colección Shapes del objeto graph. +1. Agregar [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) objeto a la colección de párrafos de la página. +1. Guarde nuestro archivo PDF. + +El siguiente fragmento de código muestra cómo agregar un [Arco](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/arc/) objeto. + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + +def add_arc(outfile: str): + document = ap.Document() + page = document.pages.add() + graph = drawing.Graph(400, 400) + graph.border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.green) + + arc1 = drawing.Arc(100, 100, 95, 0, 90) + arc1.graph_info.color = ap.Color.green_yellow + graph.shapes.add(arc1) + + arc2 = drawing.Arc(100, 100, 90, 70, 180) + arc2.graph_info.color = ap.Color.dark_blue + graph.shapes.add(arc2) + + arc3 = drawing.Arc(100, 100, 85, 120, 210) + arc3.graph_info.color = ap.Color.red + graph.shapes.add(arc3) + + page.paragraphs.add(graph) + document.save(outfile) +``` + +## Crear objeto de arco relleno + +Este ejemplo muestra cómo agregar un segmento de arco relleno de color. + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + +def add_arc_filled(outfile: str): + document = ap.Document() + page = document.pages.add() + graph = drawing.Graph(400, 400) + graph.border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.green) + + arc = drawing.Arc(100, 100, 95, 0, 90) + + arc.graph_info.fill_color = ap.Color.green_yellow + graph.shapes.add(arc) + + line = drawing.Line([195, 100, 100, 100, 100, 195]) + line.graph_info.fill_color = ap.Color.green_yellow + graph.shapes.add(line) + + page.paragraphs.add(graph) + document.save(outfile) +``` + +Resultado de agregar un arco relleno: + +![Arco relleno](filled_arc.png) + +## Temas relacionados con gráficos + +- [Trabajar con gráficos PDF en Python](/pdf/es/python-net/working-with-graphs/) +- [Agregar formas de círculo al PDF en Python](/pdf/es/python-net/add-circle/) +- [Agregar formas de curva al PDF en Python](/pdf/es/python-net/add-curve/) +- [Agregar formas de línea al PDF en Python](/pdf/es/python-net/add-line/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-graphs/checking-shape-bounds/_index.md b/es/python-net/advanced-operations/working-with-graphs/checking-shape-bounds/_index.md new file mode 100644 index 000000000..e748ce22c --- /dev/null +++ b/es/python-net/advanced-operations/working-with-graphs/checking-shape-bounds/_index.md @@ -0,0 +1,72 @@ +--- +title: Comprobar límites de forma en gráficos PDF con Python +linktitle: Comprobar límites de forma +type: docs +weight: 70 +url: /es/python-net/aspose-pdf-drawing-graph-shapes-bounds-check/ +description: Aprenda cómo validar los límites de forma en colecciones de gráficos PDF con Python. +lastmod: "2026-04-16" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Validar los límites de forma de los gráficos en archivos PDF usando Python +Abstract: Este artículo muestra cómo validar los límites de forma en colecciones de Graph con Aspose.PDF for Python via .NET. Cubre la configuración de BoundsCheckMode, la detección de formas fuera de rango y el manejo seguro de excepciones de límites. +--- + +## Comprobar límites de forma en un Graph + +Cuando agregas formas a un [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/), puedes habilitar la validación de límites para asegurar que cada forma encaje dentro del área del gráfico. + +Usar [BoundsCheckMode](https://reference.aspose.com/pdf/python-net/aspose.pdf/boundscheckmode/) para definir el comportamiento cuando una forma está fuera de rango. En este ejemplo, `THROW_EXCEPTION_IF_DOES_NOT_FIT` se usa para generar una excepción. + +Siga los pasos a continuación: + +1. Crea un nuevo PDF [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Añadir un [Página](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +1. Cree un [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) y añádelo a la página. +1. Cree un [Rectángulo](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/rectangle/) que se extiende fuera de los límites del gráfico. +1. Establecer modo de verificación de límites a `THROW_EXCEPTION_IF_DOES_NOT_FIT`. +1. Agregue el rectángulo y maneje la excepción. +1. Guarde el documento. + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + + +def check_shape_bounds(outfile: str): + document = ap.Document() + page = document.pages.add() + + graph = drawing.Graph(100, 100) + graph.top = 10 + graph.left = 15 + graph.border = ap.BorderInfo(ap.BorderSide.BOX, 1, ap.Color.black) + page.paragraphs.add(graph) + + rect = drawing.Rectangle(-1, 0, 50, 50) + rect.graph_info.fill_color = ap.Color.tomato + + try: + graph.shapes.update_bounds_check_mode( + ap.BoundsCheckMode.THROW_EXCEPTION_IF_DOES_NOT_FIT + ) + graph.shapes.add(rect) + except Exception as e: + print(e) + + document.save(outfile) +``` + +## Notas + +- Usar `THROW_EXCEPTION_IF_DOES_NOT_FIT` cuando se requiere una validación estricta del diseño. +- Para un comportamiento permisivo, elige otro `BoundsCheckMode` opción basada en sus necesidades de diseño. + +## Temas relacionados con gráficos + +- [Trabajar con gráficos PDF en Python](/pdf/es/python-net/working-with-graphs/) +- [Agregar formas rectangulares al PDF en Python](/pdf/es/python-net/add-rectangle/) +- [Agregar formas de línea al PDF en Python](/pdf/es/python-net/add-line/) +- [Agregar formas elípticas al PDF en Python](/pdf/es/python-net/add-ellipse/) diff --git a/es/python-net/advanced-operations/working-with-graphs/circle/_index.md b/es/python-net/advanced-operations/working-with-graphs/circle/_index.md new file mode 100644 index 000000000..d77dbb13b --- /dev/null +++ b/es/python-net/advanced-operations/working-with-graphs/circle/_index.md @@ -0,0 +1,84 @@ +--- +title: Agregar formas de círculo a PDF en Python +linktitle: Agregar círculo +type: docs +weight: 20 +url: /es/python-net/add-circle/ +description: Aprenda cómo dibujar y rellenar formas de círculo en archivos PDF con Python. +lastmod: "2026-04-16" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Dibujar formas de círculo en archivos PDF usando Python +Abstract: Este artículo muestra cómo agregar formas de círculo a documentos PDF con Aspose.PDF for Python via .NET. Cubre la creación de círculos contorneados, el relleno de círculos con color y la inserción de texto dentro de objetos círculo. +--- + +## Agregar objeto círculo + +Aspose.PDF for Python via .NET le permite agregar [Círculo](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/circle/) formas a páginas PDF a través del [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) clase. Utiliza círculos para diagramas, anotaciones y elementos visuales simples. + +Siga los pasos a continuación: + +1. Crear [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) instancia. +1. Crear [Objeto de gráfico](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/) con ciertas dimensiones. +1. Establecer [borde](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/#properties) para el objeto Graph. +1. Agregar [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) objeto a la colección de párrafos de la página. +1. Guarde nuestro archivo PDF. + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + +def add_circle(outfile: str): + document = ap.Document() + page = document.pages.add() + graph = drawing.Graph(400, 200) + graph.border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.green) + + circle = drawing.Circle(100, 100, 40) + circle.graph_info.color = ap.Color.green_yellow + graph.shapes.add(circle) + + page.paragraphs.add(graph) + document.save(outfile) +``` + +Nuestro círculo dibujado se verá así: + +![Dibujando círculo](drawing_circle.png) + +## Crear objeto de círculo relleno + +Este ejemplo muestra cómo agregar un círculo y rellenarlo con color. + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + +def add_circle_filled(outfile: str): + document = ap.Document() + page = document.pages.add() + graph = drawing.Graph(400, 200) + graph.border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.green) + + circle = drawing.Circle(100, 100, 40) + circle.graph_info.color = ap.Color.green_yellow + circle.graph_info.fill_color = ap.Color.green + circle.text = ap.text.TextFragment("Circle") + graph.shapes.add(circle) + + page.paragraphs.add(graph) + document.save(outfile) +``` + +Resultado de agregar un círculo relleno: + +![Círculo relleno](filled_circle.png) + +## Temas relacionados con gráficos + +- [Trabajar con gráficos PDF en Python](/pdf/es/python-net/working-with-graphs/) +- [Agregar formas de arco al PDF en Python](/pdf/es/python-net/add-arc/) +- [Agregar formas elípticas al PDF en Python](/pdf/es/python-net/add-ellipse/) +- [Agregar formas rectangulares al PDF en Python](/pdf/es/python-net/add-rectangle/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-graphs/curve/_index.md b/es/python-net/advanced-operations/working-with-graphs/curve/_index.md new file mode 100644 index 000000000..f7267ae83 --- /dev/null +++ b/es/python-net/advanced-operations/working-with-graphs/curve/_index.md @@ -0,0 +1,85 @@ +--- +title: Agregar formas de curva a PDF en Python +linktitle: Agregar curva +type: docs +weight: 30 +url: /es/python-net/add-curve/ +description: Aprenda cómo dibujar y rellenar formas de curva en archivos PDF en Python. +lastmod: "2026-04-16" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Dibujar formas de curva en archivos PDF usando Python +Abstract: Este artículo muestra cómo agregar formas de curva a documentos PDF con Aspose.PDF for Python via .NET. Cubre la creación de curvas contorneadas, el relleno de objetos de curva y la representación de rutas de curva personalizadas en un contenedor Graph. +--- + +## Agregar objeto de curva + +Aspose.PDF for Python via .NET le permite agregar [Curva](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/curve/) formas a páginas PDF a través del [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) clase. + +Este artículo muestra cómo crear curvas con contorno y rellenas. + +Siga los pasos a continuación: + +1. Crear [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) instancia. +1. Crear [Objeto de gráfico](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/) con ciertas dimensiones. +1. Establecer [borde](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/#properties) para el objeto Graph. +1. Agregar [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) objeto a la colección de párrafos de la página. +1. Guarde nuestro archivo PDF. + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + +def add_curve(outfile: str): + document = ap.Document() + page = document.pages.add() + graph = drawing.Graph(400, 200) + graph.border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.green) + + curve1 = drawing.Curve([10, 10, 50, 60, 70, 10, 100, 120]) + curve1.graph_info.color = ap.Color.green_yellow + graph.shapes.add(curve1) + + page.paragraphs.add(graph) + document.save(outfile) +``` + +La siguiente imagen muestra el resultado ejecutado con nuestro fragmento de código: + +![Dibujo de Curva](drawing_curve.png) + +## Crear objeto de Curva rellena + +Este ejemplo muestra cómo agregar un objeto de Curva que está relleno de color. + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + + +def add_curve_filled(outfile: str): + document = ap.Document() + page = document.pages.add() + graph = drawing.Graph(400, 200) + graph.border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.green) + + curve1 = drawing.Curve([10, 10, 50, 60, 70, 10, 100, 120]) + curve1.graph_info.fill_color = ap.Color.green_yellow + graph.shapes.add(curve1) + + page.paragraphs.add(graph) + document.save(outfile) +``` + +Resultado de añadir una curva rellena: + +![Curva rellena](filled_curve.png) + +## Temas relacionados con gráficos + +- [Trabajar con gráficos PDF en Python](/pdf/es/python-net/working-with-graphs/) +- [Agregar formas de arco al PDF en Python](/pdf/es/python-net/add-arc/) +- [Agregar formas de línea al PDF en Python](/pdf/es/python-net/add-line/) +- [Agregar formas elípticas al PDF en Python](/pdf/es/python-net/add-ellipse/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-graphs/ellipse/_index.md b/es/python-net/advanced-operations/working-with-graphs/ellipse/_index.md new file mode 100644 index 000000000..828a125c5 --- /dev/null +++ b/es/python-net/advanced-operations/working-with-graphs/ellipse/_index.md @@ -0,0 +1,113 @@ +--- +title: Agregar formas de elipse a PDF en Python +linktitle: Agregar elipse +type: docs +weight: 60 +url: /es/python-net/add-ellipse/ +description: Aprenda cómo dibujar, rellenar y etiquetar formas de elipse en archivos PDF con Python. +lastmod: "2026-04-16" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Dibujar formas de elipse en archivos PDF usando Python +Abstract: Este artículo muestra cómo agregar formas de elipse a documentos PDF con Aspose.PDF for Python via .NET. Cubre elipses contorneadas, elipses rellenas y la incorporación de texto dentro de objetos elipse. +--- + +## Agregar objeto Ellipse + +Aspose.PDF for Python via .NET le permite agregar [Elipse](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/ellipse/) formas a páginas PDF con el [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) clase. Puedes dibujar contornos de elipse, aplicar colores de relleno y colocar texto dentro de los objetos elipse. + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + +def add_ellipse(outfile: str): + document = ap.Document() + page = document.pages.add() + graph = drawing.Graph(400, 400) + graph.border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.green) + + ellipse1 = drawing.Ellipse(150, 100, 120, 60) + ellipse1.graph_info.color = ap.Color.green_yellow + ellipse1.text = ap.text.TextFragment("Ellipse") + graph.shapes.add(ellipse1) + + ellipse2 = drawing.Ellipse(50, 50, 18, 300) + ellipse2.graph_info.color = ap.Color.dark_red + graph.shapes.add(ellipse2) + + page.paragraphs.add(graph) + document.save(outfile) +``` + +![Agregar elipse](ellipse.png) + +## Crear objeto elipse relleno + +El siguiente fragmento de código muestra cómo agregar un [Elipse](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/ellipse/) objeto que está relleno de color. + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + +def create_ellipse_filled(outfile: str): + document = ap.Document() + page = document.pages.add() + graph = drawing.Graph(400, 400) + graph.border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.green) + + ellipse1 = drawing.Ellipse(100, 100, 120, 180) + ellipse1.graph_info.fill_color = ap.Color.green_yellow + graph.shapes.add(ellipse1) + + ellipse2 = drawing.Ellipse(200, 150, 180, 120) + ellipse2.graph_info.fill_color = ap.Color.dark_red + graph.shapes.add(ellipse2) + + page.paragraphs.add(graph) + document.save(outfile) +``` + +![Elipse rellena](fill_ellipse.png) + +## Agregar texto dentro de la elipse + +Aspose.PDF for Python via .NET también te permite colocar texto dentro de objetos de forma. El siguiente ejemplo agrega texto a las formas de elipse. + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + +def add_text_inside_ellipse(outfile: str): + document = ap.Document() + page = document.pages.add() + graph = drawing.Graph(400, 400) + graph.border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.green) + + text_fragment = ap.text.TextFragment("Ellipse") + text_fragment.text_state.font = ap.text.FontRepository.find_font("Helvetica") + text_fragment.text_state.font_size = 24 + + ellipse1 = ap.drawing.Ellipse(100, 100, 120, 180) + ellipse1.graph_info.fill_color = ap.Color.green_yellow + ellipse1.text = text_fragment + graph.shapes.add(ellipse1) + + ellipse2 = ap.drawing.Ellipse(200, 150, 180, 120) + ellipse2.graph_info.fill_color = ap.Color.dark_red + ellipse2.text = text_fragment + graph.shapes.add(ellipse2) + + page.paragraphs.add(graph) + document.save(outfile) +``` + +![Texto dentro de la elipse](text_ellipse.png) + +## Temas relacionados con gráficos + +- [Trabajar con gráficos PDF en Python](/pdf/es/python-net/working-with-graphs/) +- [Agregar formas de círculo al PDF en Python](/pdf/es/python-net/add-circle/) +- [Agregar formas de curva al PDF en Python](/pdf/es/python-net/add-curve/) +- [Agregar formas rectangulares al PDF en Python](/pdf/es/python-net/add-rectangle/) diff --git a/es/python-net/advanced-operations/working-with-graphs/line/_index.md b/es/python-net/advanced-operations/working-with-graphs/line/_index.md new file mode 100644 index 000000000..2b70f65ff --- /dev/null +++ b/es/python-net/advanced-operations/working-with-graphs/line/_index.md @@ -0,0 +1,109 @@ +--- +title: Agregar formas de línea al PDF en Python +linktitle: Agregar línea +type: docs +weight: 40 +url: /es/python-net/add-line/ +description: Aprenda cómo dibujar formas de línea y líneas con estilo en archivos PDF en Python. +lastmod: "2026-04-16" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Dibujar formas de línea en archivos PDF usando Python +Abstract: Este artículo muestra cómo agregar formas de línea a documentos PDF con Aspose.PDF for Python via .NET. Cubre la creación de líneas básicas, la configuración de estilos de línea punteada y el dibujo de líneas a través de una página. +--- + +## Agregar objeto Line + +Aspose.PDF for Python via .NET le permite agregar [Línea](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/line/) formas a páginas PDF usando el [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) clase. Puede controlar el color de la línea, el patrón de guiones y la ubicación. + +Siga los pasos a continuación: + +1. Crear [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) instancia. +1. Crear un objeto de gráfico +1. Agregar [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) objeto a la colección de párrafos de la página. +1. Crear y configurar la línea +1. Agregar el [Línea](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/line/) al gráfico +1. Guarde nuestro archivo PDF. + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + + +def add_line(outfile: str): + document = ap.Document() + page = document.pages.add() + graph = drawing.Graph(100, 400) + page.paragraphs.add(graph) + + line = drawing.Line([100, 100, 200, 100]) + line.graph_info.dash_array = [0, 1, 0] + line.graph_info.dash_phase = 1 + graph.shapes.add(line) + + document.save(outfile) +``` + +![Agregar línea](add_line.png) + +## Cómo agregar una línea punteada y discontinua a su documento PDF + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + +def add_dotted_dashed_line(outfile: str): + document = ap.Document() + page = document.pages.add() + graph = drawing.Graph(100, 400) + page.paragraphs.add(graph) + + line = drawing.Line([100, 100, 200, 100]) + line.graph_info.color = ap.Color.red + line.graph_info.dash_array = [0, 1, 0] + line.graph_info.dash_phase = 1 + graph.shapes.add(line) + + document.save(outfile) +``` + +Resultado de agregar una línea punteada y discontinua: + +![Línea discontinua](dash_line.png) + +## Dibujar línea a través de la página + +También puedes dibujar líneas a través de la página para formar una cruz. + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + +def draw_line_across_page(outfile: str): + document = ap.Document() + page = document.pages.add() + page.page_info.margin.left = 0 + page.page_info.margin.right = 0 + page.page_info.margin.bottom = 0 + page.page_info.margin.top = 0 + + graph = drawing.Graph(page.page_info.width, page.page_info.height) + line = drawing.Line([page.rect.llx, 0, page.page_info.width, page.rect.ury]) + graph.shapes.add(line) + line2 = drawing.Line([0, page.rect.ury, page.page_info.width, page.rect.llx]) + graph.shapes.add(line2) + page.paragraphs.add(graph) + + document.save(outfile) +``` + +![Dibujo de línea](draw_line.png) + +## Temas relacionados con gráficos + +- [Trabajar con gráficos PDF en Python](/pdf/es/python-net/working-with-graphs/) +- [Agregar formas de curva al PDF en Python](/pdf/es/python-net/add-curve/) +- [Agregar formas rectangulares al PDF en Python](/pdf/es/python-net/add-rectangle/) +- [Verifique los límites de la forma en gráficos PDF con Python](/pdf/es/python-net/aspose-pdf-drawing-graph-shapes-bounds-check/) diff --git a/es/python-net/advanced-operations/working-with-graphs/rectangle/_index.md b/es/python-net/advanced-operations/working-with-graphs/rectangle/_index.md new file mode 100644 index 000000000..65b2eff6c --- /dev/null +++ b/es/python-net/advanced-operations/working-with-graphs/rectangle/_index.md @@ -0,0 +1,195 @@ +--- +title: Agregar formas de rectángulo a PDF en Python +linktitle: Agregar rectángulo +type: docs +weight: 50 +url: /es/python-net/add-rectangle/ +description: Aprenda cómo dibujar y rellenar formas de rectángulo en archivos PDF con Python. +lastmod: "2026-04-16" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Dibujar formas de rectángulo en archivos PDF usando Python +Abstract: Este artículo muestra cómo agregar formas de rectángulo a documentos PDF con Aspose.PDF for Python via .NET. Cubre rectángulos contorneados, rellenos sólidos y degradados, transparencia alfa y control del orden Z. +--- + +## Agregar objeto Rectangle + +Aspose.PDF for Python via .NET le permite agregar [Rectángulo](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/rectangle/) formas a páginas PDF a través del [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) clase. Puede dibujar rectángulos contorneados y aplicar rellenos sólidos, degradados o transparentes. + +Siga los pasos a continuación: + +1. Crea un nuevo PDF [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Agregar [Página](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) a la colección de páginas del archivo PDF. +1. Agregar [Fragmento de texto](https://reference.aspose.com/pdf/python-net/aspose.pdf/textfragment/) a la colección de párrafos de la instancia de página. +1. Crear [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) instancia. +1. Establecer borde para [Objeto de gráfico](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/). +1. Agregar [Rectángulo](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/rectangle/) objeto a la colección de shapes del objeto Graph. +1. Agregar objeto gráfico a la colección de párrafos de la instancia de página. +1. Agregar [Fragmento de texto](https://reference.aspose.com/pdf/python-net/aspose.pdf/textfragment/) a la colección de párrafos de la instancia de página. +1. Y guarde su archivo PDF + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + +def add_rectangle(outfile: str): + document = ap.Document() + page = document.pages.add() + text_fragment = ap.text.TextFragment("Rectangle") + page.paragraphs.add(text_fragment) + + graph = drawing.Graph(400, 300) + page.paragraphs.add(graph) + graph.border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.red) + + rect = drawing.Rectangle(20, 20, 350, 250) + graph.shapes.add(rect) + page.paragraphs.add(text_fragment) + + document.save(outfile) +``` + +![Crear rectángulo](create_rectangle.png) + +## Crear objeto de rectángulo relleno + +Aspose.PDF for Python via .NET también ofrece la funcionalidad de rellenar el objeto de rectángulo con un color determinado. + +El siguiente fragmento de código muestra cómo agregar un [Rectángulo](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/rectangle/) objeto que está relleno de color. + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + +def create_rectangle_filled(outfile: str): + document = ap.Document() + page = document.pages.add() + graph = drawing.Graph(100, 400) + page.paragraphs.add(graph) + + rect = drawing.Rectangle(100, 100, 200, 120) + rect.graph_info.fill_color = ap.Color.red + graph.shapes.add(rect) + + document.save(outfile) +``` + +Resultado del rectángulo rellenado con un color sólido: + +![Rectángulo Relleno](fill_rectangle.png) + +## Agregar dibujo con relleno degradado + +Aspose.PDF for Python via .NET admite la función de agregar objetos de gráfico a documentos PDF y, a veces, es necesario rellenar los objetos de gráfico con Color degradado. + +El siguiente fragmento de código muestra cómo agregar un [Rectángulo](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/rectangle/) objeto que está rellenado con Color degradado. + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + +def add_drawing_with_gradient_fill(outfile: str): + document = ap.Document() + page = document.pages.add() + graph = drawing.Graph(400, 400) + page.paragraphs.add(graph) + + rect = drawing.Rectangle(0, 0, 300, 300) + gradient_color = ap.Color() + gradient_settings = drawing.GradientAxialShading(ap.Color.red, ap.Color.blue) + gradient_settings.start = ap.Point(0, 0) + gradient_settings.end = ap.Point(350, 350) + gradient_color.pattern_color_space = gradient_settings + rect.graph_info.fill_color = gradient_color + graph.shapes.add(rect) + + document.save(outfile) +``` + +![Rectángulo de degradado](gradient.png) + +## Crear rectángulo con canal de color alfa + +Aspose.PDF for Python via .NET también admite la transparencia a través de un canal de color alfa. + +El siguiente fragmento de código muestra cómo agregar un [Rectángulo](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/rectangle/) objeto con valores alfa. + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + +def create_rectangle_with_alpha_color_channel(outfile: str): + document = ap.Document() + page = document.pages.add() + graph = drawing.Graph(100, 400) + page.paragraphs.add(graph) + + rect = drawing.Rectangle(100, 100, 200, 120) + rect.graph_info.fill_color = ap.Color.from_argb(128, 244, 180, 0) + graph.shapes.add(rect) + + rect1 = drawing.Rectangle(200, 150, 200, 100) + rect1.graph_info.fill_color = ap.Color.from_argb(160, 120, 0, 120) + graph.shapes.add(rect1) + + document.save(outfile) +``` + +![Color del canal alfa del rectángulo](rectangle_color.png) + +## Controlar Z-Order de las formas + +Aspose.PDF for .NET admite la función de agregar objetos gráficos (por ejemplo gráfico, línea, rectángulo, etc.) a documentos PDF. Al agregar más de una instancia del mismo objeto dentro del archivo PDF, podemos controlar su renderizado especificando el Z-Order. Z-Order también se utiliza cuando necesitamos renderizar objetos uno encima del otro. + +El siguiente fragmento de código muestra los pasos para renderizar [Rectángulo](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/rectangle/) objetos uno encima del otro. + +```python +import aspose.pdf as ap +import aspose.pdf.drawing as drawing + + +def _add_rectangle_to_page( + page: ap.Page, + x: float, + y: float, + width: float, + height: float, + color: ap.Color, + zindex: int, +): + graph = drawing.Graph(width, height) + graph.is_change_position = False + graph.left = x + graph.top = y + rect = drawing.Rectangle(0, 0, width, height) + rect.graph_info.fill_color = color + rect.graph_info.color = color + graph.shapes.add(rect) + graph.z_index = zindex + page.paragraphs.add(graph) + + +def control_z_order_of_rectangle(outfile: str): + document = ap.Document() + page = document.pages.add() + page.set_page_size(375, 300) + page.page_info.margin.left = 0 + page.page_info.margin.top = 0 + + _add_rectangle_to_page(page, 50, 40, 60, 40, ap.Color.red, 2) + _add_rectangle_to_page(page, 20, 20, 30, 30, ap.Color.blue, 1) + _add_rectangle_to_page(page, 40, 40, 60, 30, ap.Color.green, 0) + + document.save(outfile) +``` + +![Control del orden Z](control.png) + +## Temas relacionados con gráficos + +- [Trabajar con gráficos PDF en Python](/pdf/es/python-net/working-with-graphs/) +- [Verifique los límites de la forma en gráficos PDF con Python](/pdf/es/python-net/aspose-pdf-drawing-graph-shapes-bounds-check/) +- [Agregar formas de línea al PDF en Python](/pdf/es/python-net/add-line/) +- [Agregar formas elípticas al PDF en Python](/pdf/es/python-net/add-ellipse/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-images/_index.md b/es/python-net/advanced-operations/working-with-images/_index.md index f2d643677..9af9de09b 100644 --- a/es/python-net/advanced-operations/working-with-images/_index.md +++ b/es/python-net/advanced-operations/working-with-images/_index.md @@ -1,150 +1,30 @@ --- -title: Trabajando con Imágenes en PDF usando Python -linktitle: Trabajando con Imágenes +title: Trabajar con imágenes en PDF usando Python +linktitle: Trabajando con imágenes type: docs weight: 40 url: /es/python-net/working-with-images/ -description: Esta sección describe las características de trabajar con imágenes en un archivo PDF usando la biblioteca de Python. -lastmod: "2023-04-17" +description: Aprende cómo agregar, eliminar, extraer, reemplazar e inspeccionar imágenes en documentos PDF usando Python. +lastmod: "2026-05-05" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Gestiona imágenes en archivos PDF con Python +Abstract: Esta sección muestra cómo trabajar con imágenes en documentos PDF usando Aspose.PDF for Python via .NET. Cubre agregar, eliminar, extraer, reemplazar e inspeccionar imágenes en archivos PDF existentes. --- - +Aspose.PDF for Python via .NET proporciona un conjunto completo de herramientas para operaciones de imágenes en documentos PDF existentes. -Hay muchos métodos y herramientas para editar y manipular imágenes en documentos PDF. Además de las funciones habituales de añadir y eliminar imágenes del archivo PDF, la biblioteca Aspose.PDF para Python también permite extraer imágenes. **Aspose.PDF para Python** es una herramienta inteligente y eficiente para trabajar con imágenes en un PDF existente. +Utilice esta sección para insertar nuevas imágenes, eliminar o reemplazar imágenes incrustadas, extraer el contenido de la imagen y examinar los detalles de la ubicación de la imagen en una página. -Puedes hacer lo siguiente: +## Tareas de Imagen Cubiertas -- [Añadir Imagen a un Archivo PDF Existente](/pdf/es/python-net/add-image-to-existing-pdf-file/) - añadir imágenes y referencias de una sola imagen en un documento PDF, después de eso controlar la calidad. -- [Eliminar Imágenes de un Archivo PDF](/pdf/es/python-net/delete-images-from-pdf-file/) - revisar fragmento de código para eliminar imágenes del archivo PDF. -- [Extraer Imágenes de un Archivo PDF](/pdf/es/python-net/extract-images-from-pdf-file/) - el siguiente artículo muestra cómo extraer imágenes de un archivo PDF usando la biblioteca de Python. +Se cubren las siguientes tareas: + +- [Agregar Imagen a un Archivo PDF Existente](/pdf/es/python-net/add-image-to-existing-pdf-file/) - colocar imágenes en coordenadas fijas e incrustar imágenes con diferentes opciones. +- [Eliminar imágenes del archivo PDF](/pdf/es/python-net/delete-images-from-pdf-file/) - eliminar un recurso de imagen o todas las imágenes de una página seleccionada. +- [Extraer imágenes de un archivo PDF](/pdf/es/python-net/extract-images-from-pdf-file/) - extraer imágenes incrustadas de las páginas del PDF. +- [Reemplazar imagen en un archivo PDF existente](/pdf/es/python-net/replace-image-in-existing-pdf-file/) - reemplazar imágenes incrustadas por índice de recurso o ubicación. +- [Buscar y obtener imágenes de un documento PDF](/pdf/es/python-net/search-and-get-images-from-pdf-document/) - encontrar imágenes e inspeccionar la ubicación de las imágenes en un documento. - \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-images/add-image-to-existing-pdf-file/_index.md b/es/python-net/advanced-operations/working-with-images/add-image-to-existing-pdf-file/_index.md index 74a089922..c73b602a3 100644 --- a/es/python-net/advanced-operations/working-with-images/add-image-to-existing-pdf-file/_index.md +++ b/es/python-net/advanced-operations/working-with-images/add-image-to-existing-pdf-file/_index.md @@ -1,186 +1,159 @@ --- -title: Añadir Imagen a PDF usando Python -linktitle: Añadir Imagen +title: Agregar imagen a PDF usando Python +linktitle: Agregar imagen type: docs weight: 10 url: /es/python-net/add-image-to-existing-pdf-file/ -description: Esta sección describe cómo añadir una imagen a un archivo PDF existente usando la biblioteca de Python. -lastmod: "2022-02-17" +description: Aprende cómo agregar imágenes a archivos PDF existentes en Python. +lastmod: "2026-05-05" +TechArticle: true +AlternativeHeadline: Agregar imágenes a archivos PDF existentes con Python +Abstract: Este artículo muestra cómo agregar imágenes a documentos PDF con Aspose.PDF for Python via .NET. Cubre la inserción de una imagen en coordenadas fijas, la colocación de imágenes con operadores de bajo nivel, la asignación de texto alternativo para accesibilidad y la incrustación de imágenes con compresión Flate. --- - - - -## Añadir Imagen en un Archivo PDF Existente - -El siguiente fragmento de código muestra cómo añadir una imagen en el archivo PDF. - -1. Cargar el archivo PDF de entrada. -1. Especificar el número de página en la que se colocará la imagen. -1. Para definir la posición de la imagen en la página, llame al método [add_image](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods) de la clase [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). -1. Llame al método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) de la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). + +## Agregar imagen en un archivo PDF existente + +Este ejemplo muestra cómo colocar una imagen en una posición fija en una página PDF existente usando Aspose.PDF for Python via .NET. + +Utilice estos ejemplos de esta página cuando necesite colocar logotipos, fotos u otros gráficos en coordenadas fijas dentro de un diseño PDF existente. + +1. Cargar un PDF existente con `ap.Document(infile)`. +1. Seleccione la página objetivo (`document.pages[1]` para la primera página). +1. Llamada `page.add_image()` con: + - La ruta del archivo de imagen. + - A `Rectangle` definir coordenadas de colocación. +1. Guarda el PDF actualizado. ```python +import aspose.pdf as ap + + +def add_image(infile, image_file, outfile): + document = ap.Document(infile) + page = document.pages[1] + page.add_image(image_file, ap.Rectangle(20, 730, 120, 830, True)) + document.save(outfile) +``` - import aspose.pdf as ap +## Agregar una imagen usando operadores - # Abrir documento - document = ap.Document(input_file) +Este enfoque agrega una imagen con operadores PDF de bajo nivel en lugar de los de alto nivel `add_image()` ayudante. - document.pages[1].add_image(image_file, ap.Rectangle(20, 730, 120, 830, True)) +1. Crear un nuevo `Document` y agregue una página. +1. Agregar la imagen a los recursos de la página (`page.resources.images`). +1. Crear operadores de transformación (`GSave`, `ConcatenateMatrix`, `Do`, `GRestore`). +1. Agregar operadores al contenido de la página. +1. Guarda el PDF resultante. - document.save(output_pdf) +```python +import aspose.pdf as ap +from io import FileIO + + +def add_image_using_operators(image_file, outfile): + document = ap.Document() + page = document.pages.add() + page.set_page_size(842, 595) + resources_images = page.resources.images + + with FileIO(image_file, "rb") as image_stream: + image_id = resources_images.add(image_stream) + + rectangle = ap.Rectangle(0, 0, page.media_box.width, page.media_box.height, True) + + operators = [ + ap.operators.GSave(), + ap.operators.ConcatenateMatrix( + ap.Matrix( + rectangle.urx - rectangle.llx, + 0, + 0, + rectangle.ury - rectangle.lly, + rectangle.llx, + rectangle.lly, + ) + ), + ap.operators.Do(image_id), + ap.operators.GRestore(), + ] + + page.contents.add(operators) + document.save(outfile) ``` -## Añadir Imagen en un Archivo PDF Existente (Facades) +## Agregar imagen con texto alternativo + +Este ejemplo agrega una imagen y asigna texto alternativo para accesibilidad. -También hay una manera alternativa, más fácil de añadir una Imagen a un archivo PDF. - Puedes usar el método [AddImage](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilemend/methods/addimage/index) de la clase [PdfFileMend](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilemend/). El método [add_image()](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilemend/#methods) requiere la imagen que se va a añadir, el número de página en el que se necesita añadir la imagen y la información de coordenadas. Después de eso, guarda el archivo PDF actualizado y cierra el objeto PdfFileMend usando el método [close()](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilemend/#methods). El siguiente fragmento de código te muestra cómo añadir una imagen en un archivo PDF existente. +1. Crear un nuevo `Document` y agregue una página. +1. Añadir la imagen a la página con `page.add_image()`. +1. Obtener recursos de imagen de `page.resources.images`. +1. Establecer texto alternativo usando `try_set_alternative_text()`. +1. Guarda el PDF resultante. ```python +import aspose.pdf as ap - import aspose.pdf as ap - # Abrir documento - mender = ap.facades.PdfFileMend() +def add_image_set_alternative_text(image_file, outfile): + document = ap.Document() + page = document.pages.add() + page.set_page_size(842, 595) - # Crear objeto PdfFileMend para añadir texto - mender.bind_pdf(input_file) + page.add_image(image_file, ap.Rectangle(0, 0, 842, 595, True)) + resources_images = page.resources.images + x_image = resources_images[1] + result = x_image.try_set_alternative_text("Alternative text for image", page) - # Añadir imagen en el archivo PDF - mender.add_image(image_file, 1, 100.0, 600.0, 200.0, 700.0) + if result: + print("Alternative text has been added successfully") + + document.save(outfile) +``` - # Guardar cambios - mender.save(output_pdf) +## Agregar una imagen a un PDF con compresión Flate - # Cerrar objeto PdfFileMend - mender.close() +Este ejemplo inserta una imagen usando `ImageFilterType.FLATE` compresión. +1. Crear un nuevo `Document` y agregue una página. +1. Agregar la imagen a los recursos de la página con compresión Flate. +1. Usar operadores de matriz para colocar y dibujar la imagen. +1. Guarde el documento. + +```python +import aspose.pdf as ap +from io import FileIO + + +def add_image_to_pdf_with_flate_compression(image_file, outfile): + document = ap.Document() + page = document.pages.add() + resources_images = page.resources.images + + with FileIO(image_file, "rb") as image_stream: + image_id = resources_images.add(image_stream, ap.ImageFilterType.FLATE) + + rectangle = ap.Rectangle(0, 0, 600, 600, True) + matrix = ap.Matrix( + rectangle.urx - rectangle.llx, + 0, + 0, + rectangle.ury - rectangle.lly, + rectangle.llx, + rectangle.lly, + ) + + page.contents.add([ap.operators.GSave()]) + page.contents.add([ap.operators.ConcatenateMatrix(matrix)]) + page.contents.add([ap.operators.Do(image_id)]) + page.contents.add([ap.operators.GRestore()]) + + document.save(outfile) ``` - \ No newline at end of file +## Temas de imágenes relacionadas + +- [Trabajar con imágenes en PDF usando Python](/pdf/es/python-net/working-with-images/) +- [Reemplazar imágenes en archivos PDF existentes](/pdf/es/python-net/replace-image-in-existing-pdf-file/) +- [Eliminar imágenes de archivos PDF](/pdf/es/python-net/delete-images-from-pdf-file/) +- [Extraer imágenes de archivos PDF](/pdf/es/python-net/extract-images-from-pdf-file/) diff --git a/es/python-net/advanced-operations/working-with-images/delete-images-from-pdf-file/_index.md b/es/python-net/advanced-operations/working-with-images/delete-images-from-pdf-file/_index.md index 06dda7414..0f3b5fd50 100644 --- a/es/python-net/advanced-operations/working-with-images/delete-images-from-pdf-file/_index.md +++ b/es/python-net/advanced-operations/working-with-images/delete-images-from-pdf-file/_index.md @@ -1,192 +1,58 @@ --- -title: Eliminar Imágenes de un Archivo PDF usando Python -linktitle: Eliminar Imágenes +title: Eliminar imágenes de archivo PDF usando Python +linktitle: Eliminar imágenes type: docs weight: 20 url: /es/python-net/delete-images-from-pdf-file/ -description: Esta sección explica cómo eliminar imágenes de un archivo PDF usando Aspose.PDF para Python vía .NET. -lastmod: "2023-04-17" +description: Aprenda cómo eliminar imágenes específicas o todas las imágenes de archivos PDF en Python. +lastmod: "2026-05-05" +TechArticle: true +AlternativeHeadline: Eliminar imágenes de archivos PDF con Python +Abstract: Este artículo muestra cómo eliminar imágenes de documentos PDF con Aspose.PDF for Python via .NET. Cubre la eliminación de un recurso de imagen específico y la eliminación de todas las imágenes de una página seleccionada. --- - - - -Hay muchas razones para eliminar todas o algunas imágenes de los PDFs. - -A veces, un archivo PDF puede contener imágenes importantes que deben eliminarse para proteger la privacidad o prevenir el acceso no autorizado a cierta información. - -Eliminar imágenes no deseadas o redundantes puede ayudar a reducir el tamaño del archivo, facilitando así compartir o almacenar los PDFs. - -Si es necesario, puedes reducir el número de páginas eliminando todas las imágenes del documento. Además, eliminar imágenes del documento ayudará a preparar el PDF para la compresión o extracción de la información de texto. - -**Aspose.PDF para Python a través de .NET** te ayudará con esta tarea. - -## Eliminar Imágenes del Archivo PDF - -Para eliminar una imagen de un archivo PDF: - -1. Abre el Documento PDF existente. -1. Elimina una imagen en particular. -1. Guarda el archivo PDF actualizado. - -El siguiente fragmento de código muestra cómo eliminar una imagen de un archivo PDF. -```python +Utilice esta página cuando necesite eliminar gráficos innecesarios, reducir el tamaño del PDF o limpiar contenido visual sensible de un documento. + +## Eliminar imágenes del archivo PDF - import aspose.pdf as ap +Utilice los siguientes pasos para eliminar una imagen de una página: - # Abrir documento - document = ap.Document(input_file) +1. Cargar el PDF de origen con `ap.Document(infile)`. +1. Seleccione la página y el índice del recurso de imagen. +1. Eliminar la imagen con `resources.images.delete(index)`. +1. Guarda el PDF actualizado. - # Eliminar imagen particular - document.pages[2].resources.images.delete(1) +```python +import aspose.pdf as ap - # Guardar archivo PDF actualizado - document.save(output_pdf) + +def delete_image(infile, outfile): + document = ap.Document(infile) + document.pages[1].resources.images.delete(1) + document.save(outfile) ``` +## Eliminar todas las imágenes de una página -## Eliminar todas las imágenes del PDF de entrada +Utilice este ejemplo para eliminar cada imagen de una página específica. ```python +import aspose.pdf as ap - import aspose.pdf as ap - # Abrir documento - document = ap.Document(input_file) +def delete_all_images_from_page(infile, outfile, page_number): + document = ap.Document(infile) + page = document.pages[page_number] - # Eliminar todas las imágenes en todas las páginas - for i in range(len(document.pages)): - while len(document.pages[i + 1].resources.images) != 0: - document.pages[i + 1].resources.images.delete(1) + while len(page.resources.images) != 0: + page.resources.images.delete(1) - # Guardar archivo PDF actualizado - document.save(output_file) + document.save(outfile) ``` - \ No newline at end of file +## Temas de imágenes relacionadas + +- [Trabajar con imágenes en PDF usando Python](/pdf/es/python-net/working-with-images/) +- [Reemplazar imágenes en archivos PDF existentes](/pdf/es/python-net/replace-image-in-existing-pdf-file/) +- [Extraer imágenes de archivos PDF](/pdf/es/python-net/extract-images-from-pdf-file/) +- [Agregar imágenes a archivos PDF existentes](/pdf/es/python-net/add-image-to-existing-pdf-file/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-images/extract-images-from-pdf-file/_index.md b/es/python-net/advanced-operations/working-with-images/extract-images-from-pdf-file/_index.md index 075100965..37466bcd8 100644 --- a/es/python-net/advanced-operations/working-with-images/extract-images-from-pdf-file/_index.md +++ b/es/python-net/advanced-operations/working-with-images/extract-images-from-pdf-file/_index.md @@ -1,162 +1,69 @@ --- -title: Extraer Imágenes de un Archivo PDF usando Python -linktitle: Extraer Imágenes +title: Extraer imágenes de un archivo PDF usando Python +linktitle: Extraer imágenes type: docs weight: 30 url: /es/python-net/extract-images-from-pdf-file/ -description: Esta sección muestra cómo extraer imágenes de un archivo PDF usando la biblioteca de Python. -lastmod: "2023-02-17" +description: Aprenda cómo extraer imágenes incrustadas de archivos PDF en Python. +lastmod: "2026-05-05" +TechArticle: true +AlternativeHeadline: Extraer imágenes de archivos PDF con Python +Abstract: Este artículo muestra cómo extraer imágenes de documentos PDF con Aspose.PDF for Python via .NET. Cubre la extracción de una única imagen incrustada y la exportación de imágenes encontradas dentro de una región rectangular específica en una página. --- - +Utilice esta página cuando necesite reutilizar gráficos incrustados, archivar recursos de imágenes o procesar contenido de imágenes fuera del PDF. -¿Necesitas separar imágenes de tus archivos PDF? Para una gestión, archivo, análisis o compartición de imágenes de tus documentos de manera simplificada, utiliza **Aspose.PDF para Python** y extrae imágenes de archivos PDF. +1. Cargar el PDF de origen con `ap.Document(infile)`. +1. Seleccione la página objetivo y el índice del recurso de imagen. +1. Guarde el objeto de imagen en un flujo de salida. -Las imágenes se encuentran en la colección [resources](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) de cada página, en la colección [XImage](https://reference.aspose.com/pdf/python-net/aspose.pdf/ximagecollection/). Para extraer una página en particular, obtén la imagen de la colección de Imágenes usando el índice particular de la imagen. +```python +import aspose.pdf as ap +from io import FileIO + + +def extract_image(infile, outfile): + document = ap.Document(infile) + x_image = document.pages[1].resources.images[1] + with FileIO(outfile, "wb") as output_image: + x_image.save(output_image) +``` + +## Extraer imágenes de una región específica en PDF + +Este ejemplo extrae imágenes ubicadas dentro de una región rectangular especificada en una página PDF y las guarda como archivos separados. -El índice de la imagen devuelve un objeto [XImage](https://reference.aspose.com/pdf/python-net/aspose.pdf/ximage/). Este objeto proporciona un método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) que puede ser utilizado para guardar la imagen extraída. El siguiente fragmento de código muestra cómo extraer imágenes de un archivo PDF. +1. Cargar el PDF de origen. +1. Crear `ImagePlacementAbsorber` y aceptarlo en la página de destino. +1. Define el rectángulo de destino. +1. Itera a través de las colocaciones de imágenes y verifica si los límites de cada imagen encajan en la región. +1. Guardar imágenes coincidentes en archivos de salida. ```python +import aspose.pdf as ap +from io import FileIO - import aspose.pdf as ap - # Abrir documento - document = ap.Document(input_file) +def extract_image_from_specific_region(infile, outfile): + document = ap.Document(infile) + rectangle = ap.Rectangle(0, 0, 590, 590, True) + absorber = ap.ImagePlacementAbsorber() + document.pages[1].accept(absorber) - # Extraer una imagen en particular - xImage = document.pages[2].resources.images[1] - outputImage = io.FileIO(output_image, "w") + index = 1 + for image_placement in absorber.image_placements: + point1 = ap.Point(image_placement.rectangle.llx, image_placement.rectangle.lly) + point2 = ap.Point(image_placement.rectangle.urx, image_placement.rectangle.ury) - # Guardar imagen de salida - xImage.save(outputImage) - outputImage.close() + if rectangle.contains(point1, True) and rectangle.contains(point2, True): + with FileIO(outfile.replace("index", str(index)), "wb") as output_image: + image_placement.image.save(output_image) + index += 1 ``` +## Temas de imágenes relacionadas - \ No newline at end of file +- [Trabajar con imágenes en PDF usando Python](/pdf/es/python-net/working-with-images/) +- [Reemplazar imágenes en archivos PDF existentes](/pdf/es/python-net/replace-image-in-existing-pdf-file/) +- [Eliminar imágenes de archivos PDF](/pdf/es/python-net/delete-images-from-pdf-file/) +- [Agregar imágenes a archivos PDF existentes](/pdf/es/python-net/add-image-to-existing-pdf-file/) diff --git a/es/python-net/advanced-operations/working-with-images/replace-image-in-existing-pdf-file/_index.md b/es/python-net/advanced-operations/working-with-images/replace-image-in-existing-pdf-file/_index.md new file mode 100644 index 000000000..78bd32e26 --- /dev/null +++ b/es/python-net/advanced-operations/working-with-images/replace-image-in-existing-pdf-file/_index.md @@ -0,0 +1,70 @@ +--- +title: Reemplazar imagen en archivo PDF existente usando Python +linktitle: Reemplazar imagen +type: docs +weight: 70 +url: /es/python-net/replace-image-in-existing-pdf-file/ +description: Aprenda cómo reemplazar imágenes incrustadas en archivos PDF existentes con Python. +lastmod: "2026-05-05" +TechArticle: true +AlternativeHeadline: Reemplazar imágenes en archivos PDF existentes con Python +Abstract: Este artículo muestra cómo reemplazar imágenes en documentos PDF con Aspose.PDF for Python via .NET. Cubre el reemplazo de una imagen por índice de recurso y el reemplazo de una imagen específica encontrada con ImagePlacementAbsorber. +--- + +## Reemplazar una imagen en PDF + +Utilice esta página cuando necesite actualizar logotipos, diagramas u otros gráficos incrustados en un PDF sin reconstruir el diseño del documento. + +1. Cargar el PDF de origen con `ap.Document(infile)`. +1. Abra la imagen de reemplazo como un flujo binario. +1. Reemplace un recurso de imagen por índice en una página. +1. Guarda el PDF actualizado. + +```python +import aspose.pdf as ap +from io import FileIO + + +def replace_image(infile, image_file, outfile): + document = ap.Document(infile) + + with FileIO(image_file, "rb") as image_stream: + document.pages[1].resources.images.replace(1, image_stream) + + document.save(outfile) +``` + +## Reemplazar una imagen específica + +Este ejemplo reemplaza una ubicación de imagen específica encontrada por `ImagePlacementAbsorber`. + +1. Cargar el PDF de origen. +1. Crear `ImagePlacementAbsorber` y recopilar las ubicaciones de imágenes en la página. +1. Verifique si existen ubicaciones de imágenes en la página. +1. Reemplace la ubicación seleccionada con una nueva secuencia de imagen. +1. Guarda el PDF actualizado. + +```python +import aspose.pdf as ap +from io import FileIO + + +def replace_image_with_absorber(infile, image_file, outfile): + document = ap.Document(infile) + absorber = ap.ImagePlacementAbsorber() + document.pages[1].accept(absorber) + + if len(absorber.image_placements) > 0: + image_placement = absorber.image_placements[1] + with FileIO(image_file, "rb") as image_stream: + image_placement.replace(image_stream) + + document.save(outfile) +``` + +## Temas de imágenes relacionadas + +- [Trabajar con imágenes en PDF usando Python](/pdf/es/python-net/working-with-images/) +- [Eliminar imágenes de archivos PDF](/pdf/es/python-net/delete-images-from-pdf-file/) +- [Extraer imágenes de archivos PDF](/pdf/es/python-net/extract-images-from-pdf-file/) +- [Agregar imágenes a archivos PDF existentes](/pdf/es/python-net/add-image-to-existing-pdf-file/) diff --git a/es/python-net/advanced-operations/working-with-images/search-and-get-images-from-pdf-document/_index.md b/es/python-net/advanced-operations/working-with-images/search-and-get-images-from-pdf-document/_index.md new file mode 100644 index 000000000..b3ba46f6d --- /dev/null +++ b/es/python-net/advanced-operations/working-with-images/search-and-get-images-from-pdf-document/_index.md @@ -0,0 +1,236 @@ +--- +title: Obtener y buscar imágenes en PDF +linktitle: Obtener y buscar imágenes +type: docs +weight: 40 +url: /es/python-net/search-and-get-images-from-pdf-document/ +description: Aprenda cómo buscar e inspeccionar imágenes en documentos PDF con Python. +lastmod: "2026-04-17" +TechArticle: true +AlternativeHeadline: Buscar e inspeccionar imágenes en archivos PDF con Python +Abstract: Este artículo muestra cómo buscar e inspeccionar imágenes en documentos PDF con Aspose.PDF for Python via .NET. Cubre el uso de ImagePlacementAbsorber para analizar la ubicación de la imagen, el tamaño, la resolución y el texto alternativo. +--- + +## Inspeccionar las propiedades de ubicación de la imagen en una página PDF + +Este ejemplo demuestra cómo analizar y mostrar las propiedades de todas las imágenes en una página PDF específica usando Aspose.PDF for Python via .NET. + +Utilice esta página cuando necesite auditar la ubicación de las imágenes, inspeccionar la resolución de la imagen o identificar objetos de imagen incrustados en distintas páginas PDF. + +1. Crea un 'ImagePlacementAbsorber' para recopilar todas las imágenes en la página. +1. Llama a 'document.pages[1].accept(absorber)' para analizar la ubicación de las imágenes en la primera página. +1. Itera a través de 'absorber.image_placements' y muestra las propiedades clave de cada imagen: + - Ancho y Alto (puntos). + - Coordenadas X (LLX) e Y (LLY) de la esquina inferior izquierda. + - Resolución horizontal (X) y vertical (Y) (DPI). + +```python +import math +import aspose.pdf as ap +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as drawing + +def extract_image_params(infile): + document = ap.Document(infile) + absorber = ap.ImagePlacementAbsorber() + document.pages[1].accept(absorber) + + for image_placement in absorber.image_placements: + print("image width: " + str(image_placement.rectangle.width)) + print("image height: " + str(image_placement.rectangle.height)) + print("image LLX: " + str(image_placement.rectangle.llx)) + print("image LLY: " + str(image_placement.rectangle.lly)) + print("image horizontal resolution: " + str(image_placement.resolution.x)) + print("image vertical resolution: " + str(image_placement.resolution.y)) +``` + +## Extraer y contar tipos de imagen en un PDF + +Esta función analiza todas las imágenes en la primera página de un PDF y cuenta cuántas son imágenes en escala de grises y RGB. + +1. Crea un 'ImagePlacementAbsorber' para recopilar todas las imágenes en la página. +1. Inicializar contadores para imágenes en escala de grises y RGB. +1. Llame a 'document.pages[1].accept(absorber)' para analizar la ubicación de las imágenes. +1. Imprima el número total de imágenes encontradas. +1. Itere a través de cada imagen en 'absorber.image_placements': + - Obtenga el tipo de color de la imagen usando 'image_placement.image.get_color_type()'. + - Incrementa el contador correspondiente (grayscaled o rgb). + - Imprime un mensaje para cada imagen indicando si es en escala de grises o RGB. + +```python +import math +import aspose.pdf as ap +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as drawing + +def extract_image_types_from_pdf(infile): + """ + Extract and count image types (grayscale/RGB) with resolution analysis. + + Args: + infile (str): Input PDF filename + + Returns: + None + + Example: + extract_image_types_from_pdf("sample_extr.pdf") + + Note: + Prints total images count, color type for each image, and resolution info. + """ + + document = ap.Document(infile) + absorber = ap.ImagePlacementAbsorber() + + # Counters for grayscale and RGB images + grayscaled = 0 + rgb = 0 + + document.pages[1].accept(absorber) + + print("--------------------------------") + print("Total Images = " + str(len(absorber.image_placements))) + + image_counter = 1 + + for image_placement in absorber.image_placements: + # Determine the color type of the image + colorType = image_placement.image.get_color_type() + if colorType == ap.ColorType.GRAYSCALE: + grayscaled += 1 + print(f"Image {image_counter} is Grayscale...") + elif colorType == ap.ColorType.RGB: + rgb += 1 + print(f"Image {image_counter} is RGB...") + image_counter += 1 + + print("--------------------------------") + print("Grayscale Images = " + str(grayscaled)) + print("RGB Images = " + str(rgb)) +``` + +## Extraer información detallada de imágenes de un PDF + +Esta función analiza todas las imágenes en la primera página de un PDF y calcula sus dimensiones escaladas y resolución efectiva basándose en las transformaciones gráficas de la página. + +1. Cargar PDF e inicializar variables +1. Recopilar recursos de imagen +1. Procesar operadores de contenido de página: + - 'GSave' - empujar la CTM actual a la pila. + - 'GRestore' - elimina la última CTM de la pila. + - 'ConcatenateMatrix' - actualiza la CTM actual multiplicándola por la matriz del operador. +1. Imprime el nombre de la imagen, las dimensiones escaladas y la resolución calculada. + +```python +import math +import aspose.pdf as ap +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as drawing + +def extract_image_information_from_pdf(infile): + with ap.Document(infile) as document: + default_resolution = 72 + graphics_state = [] + + image_names = list(document.pages[1].resources.images.names) + + graphics_state.append( + drawing.drawing2d.Matrix( + float(1), float(0), float(0), float(1), float(0), float(0) + ) + ) + + for op in document.pages[1].contents: + if is_assignable(op, ap.operators.GSave): + graphics_state.append( + cast(drawing.drawing2d.Matrix, graphics_state[-1]).clone() + ) + + elif is_assignable(op, ap.operators.GRestore): + graphics_state.pop() + + elif is_assignable(op, ap.operators.ConcatenateMatrix): + op_cm = cast(ap.operators.ConcatenateMatrix, op) + cm = drawing.drawing2d.Matrix( + float(op_cm.matrix.a), + float(op_cm.matrix.b), + float(op_cm.matrix.c), + float(op_cm.matrix.d), + float(op_cm.matrix.e), + float(op_cm.matrix.f), + ) + + graphics_state[-1].multiply(cm) + continue + + elif is_assignable(op, ap.operators.Do): + op_do = cast(ap.operators.Do, op) + if op_do.name in image_names: + last_ctm = cast(drawing.drawing2d.Matrix, graphics_state[-1]) + index = image_names.index(op_do.name) + 1 + image = document.pages[1].resources.images[index] + + scaled_width = math.sqrt( + last_ctm.elements[0] ** 2 + last_ctm.elements[1] ** 2 + ) + scaled_height = math.sqrt( + last_ctm.elements[2] ** 2 + last_ctm.elements[3] ** 2 + ) + + original_width = image.width + original_height = image.height + + res_horizontal = ( + original_width * default_resolution / scaled_width + ) + res_vertical = ( + original_height * default_resolution / scaled_height + ) + + info = ( + f"{infile} image {op_do.name} " + f"({scaled_width:.2f}:{scaled_height:.2f}): " + f"res {res_horizontal:.2f} x {res_vertical:.2f}\n" + ) + print(info.rstrip()) +``` + +## Extraer texto alternativo de imágenes en un PDF + +Esta función recupera el texto alternativo (alt text) de todas las imágenes en la primera página de un PDF, útil para la accesibilidad y las comprobaciones de cumplimiento de PDF/UA. + +1. Cargue el documento PDF usando 'ap.Document()'. +1. Crea un 'ImagePlacementAbsorber' para recopilar todas las imágenes en la página. +1. Acepta el absorbente en la primera página (page.accept(absorber)). +1. Itere a través de cada imagen en 'absorber.image_placements': + - Imprima el nombre de la imagen en la colección de recursos de la página (get_name_in_collection()). + - Recupera el texto alternativo usando 'get_alternative_text(page)'. + - Imprime la primera línea del texto alternativo. + +```python +import math +import aspose.pdf as ap +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as drawing + +def extract_image_alt_text(infile): + document = ap.Document(infile) + absorber = ap.ImagePlacementAbsorber() + page = document.pages[1] + page.accept(absorber) + + for image_placement in absorber.image_placements: + print( + "Name in collection: " + str(image_placement.image.get_name_in_collection()) + ) + lines = image_placement.image.get_alternative_text(page) + print("Alt Text: " + lines[0]) +``` + +## Temas de imágenes relacionadas + +- [Trabajar con imágenes en PDF usando Python](/pdf/es/python-net/working-with-images/) +- [Extraer imágenes de archivos PDF](/pdf/es/python-net/extract-images-from-pdf-file/) +- [Reemplazar imágenes en archivos PDF existentes](/pdf/es/python-net/replace-image-in-existing-pdf-file/) +- [Agregar imágenes a archivos PDF existentes](/pdf/es/python-net/add-image-to-existing-pdf-file/) diff --git a/es/python-net/advanced-operations/working-with-layers/_index.md b/es/python-net/advanced-operations/working-with-layers/_index.md new file mode 100644 index 000000000..1212465dd --- /dev/null +++ b/es/python-net/advanced-operations/working-with-layers/_index.md @@ -0,0 +1,220 @@ +--- +title: Trabajar con capas PDF usando Python +linktitle: Trabajar con capas PDF +type: docs +weight: 50 +url: /es/python-net/working-with-pdf-layers/ +description: Aprenda cómo agregar, bloquear, extraer, aplanar y combinar capas PDF en Python. +lastmod: "2026-04-27" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Administre capas PDF con Python +Abstract: Este artículo explica cómo trabajar con capas PDF (Grupos de Contenido Opcional) usando Aspose.PDF for Python via .NET. Aprenda cómo agregar capas, bloquear la visibilidad de capas, extraer el contenido de la capa, aplanar el contenido de capas y combinar capas en una. +--- + +Las capas de PDF, también llamadas Grupos de Contenido Opcional (OCGs), le permiten organizar el contenido en grupos visuales separados que pueden mostrarse u ocultarse en visores de PDF compatibles. En Aspose.PDF, las operaciones de capa se construyen alrededor del [`Layer`](https://reference.aspose.com/pdf/python-net/aspose.pdf/layer/) API. + +Con Aspose.PDF for Python via .NET, puedes: + +- Agregar varias capas a una página. +- Bloquee y desbloquee capas para controlar el comportamiento de visibilidad. +- Extraer capas en archivos o flujos separados. +- Aplanar contenido en capas en la página. +- Combinar varias capas en una capa. + +## Agregar capas a un PDF + +Este ejemplo crea un PDF con tres capas. Utiliza un [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/), agrega un [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/), y añade [`Layer`](https://reference.aspose.com/pdf/python-net/aspose.pdf/layer/) objetos a esa página. + +1. Crear un nuevo [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) y agregar un [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +1. Crear y agregar la capa roja. +1. Crear y agregar la capa verde. +1. Crear y agregar la capa azul. +1. Guarde el documento PDF. + +El PDF resultante contendrá tres capas separadas: una línea roja, una línea verde y una línea azul. Cada una puede activarse o desactivarse en los lectores de PDF que admiten contenido en capas. + +```python +import aspose.pdf as ap + +def add_layers(outfile: str) -> None: + document = ap.Document() + page = document.pages.add() + + # Red layer + layer = ap.Layer("oc1", "Red Line") + layer.contents.append(ap.operators.SetRGBColorStroke(1, 0, 0)) + layer.contents.append(ap.operators.MoveTo(500, 700)) + layer.contents.append(ap.operators.LineTo(400, 700)) + layer.contents.append(ap.operators.Stroke()) + page.layers.append(layer) + + # Green layer + layer = ap.Layer("oc2", "Green Line") + layer.contents.append(ap.operators.SetRGBColorStroke(0, 1, 0)) + layer.contents.append(ap.operators.MoveTo(500, 750)) + layer.contents.append(ap.operators.LineTo(400, 750)) + layer.contents.append(ap.operators.Stroke()) + page.layers.append(layer) + + # Blue layer + layer = ap.Layer("oc3", "Blue Line") + layer.contents.append(ap.operators.SetRGBColorStroke(0, 0, 1)) + layer.contents.append(ap.operators.MoveTo(500, 800)) + layer.contents.append(ap.operators.LineTo(400, 800)) + layer.contents.append(ap.operators.Stroke()) + page.layers.append(layer) + + document.save(outfile) + print(f"Layers added successfully. File saved at {outfile}") +``` + +## Bloquear una capa PDF + +Este ejemplo abre un PDF, bloquea una capa específica en la primera página y guarda el archivo actualizado. + +Bloquear una capa evita que los usuarios cambien el estado de visibilidad de esa capa en los visores PDF compatibles. Las capas se acceden desde una página y se gestionan a través de la colección de capas de la página. + +Métodos y propiedad disponibles: + +- [`Layer.lock()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/layer/#methods) bloquea la capa. +- [`Layer.unlock()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/layer/#methods) desbloquea la capa. +- [`Layer.locked`](https://reference.aspose.com/pdf/python-net/aspose.pdf/layer/#properties) devuelve el estado actual del bloqueo. + +1. Abra el documento PDF. +1. Acceda a la primera página del PDF. +1. Verifique si la página tiene capas. +1. Obtén la primera capa y bloquéala. +1. Guarda el PDF actualizado. + +Si el PDF contiene capas, la primera capa se bloqueará, garantizando que su estado de visibilidad no pueda ser cambiado por el usuario. Si no se encuentran capas, se imprimirá un mensaje en su lugar. + +```python +import aspose.pdf as ap + +def lock_layer(infile: str, outfile: str) -> None: + document = ap.Document(infile) + page = document.pages[1] + + if len(page.layers) > 0: + layer = page.layers[0] + layer.lock() + document.save(outfile) + print(f"Layer locked successfully. File saved at {outfile}") + else: + print("No layers found in the document.") +``` + +## Extraer elementos de capa PDF + +Este ejemplo usa la biblioteca Aspose.PDF for Python via .NET para extraer capas individuales de la primera página de un documento PDF y guardar cada capa como un archivo PDF separado mediante [`Layer.save()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/layer/#methods). + +Para crear un nuevo PDF a partir de una capa, se puede usar el siguiente fragmento de código: + +1. Cargar el PDF [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Acceder a capas en la página 1 mediante [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +1. Verifique si existen capas. +1. Iterar sobre las capas y guardar cada una. + +```python +import aspose.pdf as ap + +def extract_layers(infile: str, outfile: str) -> None: + document = ap.Document(infile) + layers = document.pages[1].layers + + if len(layers) == 0: + print("No layers found in the document.") + return + + index = 1 + for layer in layers: + output_file = outfile.replace(".pdf", f"{index}.pdf") + layer.save(output_file) + print(f"Layer {index} saved to {output_file}") + index += 1 +``` + +Es posible extraer los elementos de capa de PDF y guardarlos en una nueva secuencia de archivo PDF: + +```python +from io import FileIO +import aspose.pdf as ap + +def extract_layers_stream(infile: str, outfile: str) -> None: + document = ap.Document(infile) + + if len(document.pages[1].layers) == 0: + print("No layers found in the document.") + return + + layer = document.pages[1].layers[0] + + with FileIO(outfile, "wb") as output_layer: + layer.save(output_layer) + print(f"Layer extracted to stream: {outfile}") +``` + +## Aplanar un PDF en capas + +Este script usa Aspose.PDF for Python via .NET para aplanar todas las capas en la primera página de un documento PDF. El aplanado combina el contenido visual de cada capa en una capa unificada, facilitando la impresión, el intercambio o el archivado sin perder la fidelidad visual ni los datos específicos de la capa. La operación se realiza con [`Layer.flatten()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/layer/#methods). + +1. Cargue el documento PDF. +1. Acceder a las capas en la página 1. +1. Verifique si existen capas. +1. Aplana cada capa con `layer.flatten(True)`. +1. Guarda el documento modificado. + +```python +import aspose.pdf as ap + +def flatten_layers(infile: str, outfile: str) -> None: + document = ap.Document(infile) + layers = document.pages[1].layers + + if len(layers) == 0: + print("No layers found in the document.") + return + + for layer in layers: + layer.flatten(True) + + document.save(outfile) + print(f"Layers flattened successfully. File saved at {outfile}") +``` + +## Fusionar todas las capas de un PDF en una + +Este fragmento de código utiliza Aspose.PDF para combinar todas las capas de la primera página de un PDF en una única capa unificada con un nombre personalizado mediante [`Page.merge_layers()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods). + +1. Cargue el documento PDF. +1. Acceda a la página 1 y recupere sus capas. +1. Verifique si existen capas. +1. Definir un nuevo nombre de capa. +1. Fusiona las capas en una. +1. Guarde el documento. + +```python +import aspose.pdf as ap + +def merge_layers(infile: str, outfile: str) -> None: + document = ap.Document(infile) + page = document.pages[1] + + if len(page.layers) == 0: + print("No layers found in the document.") + return + + new_layer_name = "LayerNew" + page.merge_layers(new_layer_name) + document.save(outfile) + print(f"Layers merged successfully. File saved at {outfile}") +``` + +## Temas de capa relacionados + +- [Trabajar con páginas PDF en Python](/pdf/es/python-net/working-with-pages/) +- [Trabajar con tablas en PDF usando Python](/pdf/es/python-net/working-with-tables/) +- [Agregar páginas PDF en Python](/pdf/es/python-net/add-pages/) diff --git a/es/python-net/advanced-operations/working-with-operators/_index.md b/es/python-net/advanced-operations/working-with-operators/_index.md new file mode 100644 index 000000000..698c9bab5 --- /dev/null +++ b/es/python-net/advanced-operations/working-with-operators/_index.md @@ -0,0 +1,185 @@ +--- +title: Trabajar con Operadores PDF en Python +linktitle: Trabajando con Operadores +type: docs +weight: 90 +url: /es/python-net/working-with-operators/ +description: Aprende cómo usar operadores PDF de bajo nivel en Python para una manipulación precisa del flujo de contenido y control gráfico. +lastmod: "2026-04-17" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Usa operadores PDF de bajo nivel para el control del flujo de contenido en Python +Abstract: Este artículo explica cómo trabajar con operadores PDF de bajo nivel en Aspose.PDF for Python via .NET. Aprenda cómo manipular flujos de contenido directamente, posicionar gráficos con precisión mediante clases de operadores y eliminar objetos dibujados de las páginas PDF en flujos de trabajo de Python. +--- + +## Introducción a los Operadores PDF y su Uso + +Un operador es una palabra clave PDF que especifica alguna acción que debe ejecutarse, como pintar una forma gráfica en la página. Una palabra clave de operador se distingue de un objeto nombrado por la ausencia de un carácter de barra inicial (2Fh). Los operadores solo tienen significado dentro del flujo de contenido. + +Un flujo de contenido es un objeto de flujo PDF cuyos datos consisten en instrucciones que describen los elementos gráficos que se deben pintar en una página. Se pueden encontrar más detalles sobre los operadores PDF en el [Especificación PDF](https://opensource.adobe.com/dc-acrobat-sdk-docs/). + +Utilice esta página cuando necesite control directo sobre los flujos de contenido PDF en Python, como colocar gráficos en coordenadas exactas, envolver cambios del estado gráfico, o eliminar operadores de dibujo específicos de una página. + +## Agregar imágenes con clases de operador + +Utilice clases de operador de bajo nivel cuando necesite colocar contenido de imagen con gran precisión en el flujo de una página PDF sin depender de abstracciones de diseño de alto nivel. + +Este método proporciona un control granular sobre la colocación de imágenes dentro de un PDF al manipular directamente el flujo de contenido con operadores gráficos de bajo nivel. Es particularmente útil cuando se requiere un posicionamiento y transformación precisos de las imágenes, como por ejemplo: + +- agregar marcas de agua o logotipos en ubicaciones específicas. +- superponer imágenes sobre contenido existente con alineación exacta. +- implementar diseños personalizados que no son posibles con abstracciones de nivel superior. + +Al usar operadores como GSave, ConcatenateMatrix, Do y GRestore, los desarrolladores pueden garantizar que las imágenes se rendericen con precisión y sin efectos secundarios no deseados en el contenido de otras páginas. + +- El [GSave](https://reference.aspose.com/pdf/python-net/aspose.pdf.operators/gsave/) el operador guarda el estado gráfico actual del PDF. +- El [ConcatenateMatrix](https://reference.aspose.com/pdf/python-net/aspose.pdf.operators/concatenatematrix/) El operador (concatenate matrix) se usa para definir cómo se debe colocar una imagen en la página PDF. +- El [Do](https://reference.aspose.com/pdf/python-net/aspose.pdf.operators/do/) El operador dibuja la imagen en la página. +- El [GRestore](https://reference.aspose.com/pdf/python-net/aspose.pdf.operators/grestore/) el operador restaura el estado gráfico. + +Para agregar una imagen a un archivo PDF: + +1. Abrir el documento PDF +1. Definir coordenadas de colocación de la imagen +1. Acceder a la página de destino +1. Cargar la imagen en un flujo +1. Guardar el estado gráfico actual +1. Crear un rectángulo y una matriz de transformación +1. Aplicar la Matriz de Transformación +1. Dibujar la Imagen +1. Restaurar el Estado Gráfico Anterior +1. Guardar el Documento PDF Modificado + +El siguiente fragmento de código muestra cómo usar los operadores PDF: + +```python +import sys +import aspose.pdf as ap +from os import path + +def add_image_using_pdf_operators(infile, imagefile, outfile): + with ap.Document(infile) as document: + lower_left_x = 100 + lower_left_y = 100 + upper_right_x = 200 + upper_right_y = 200 + + page = document.pages[1] + + with open(imagefile, "rb") as image_stream: + page.resources.images.add(image_stream) + + page.contents.append(ap.operators.GSave()) + + rectangle = ap.Rectangle( + lower_left_x, lower_left_y, upper_right_x, upper_right_y, True + ) + matrix = ap.Matrix( + [ + rectangle.urx - rectangle.llx, + 0, + 0, + rectangle.ury - rectangle.lly, + rectangle.llx, + rectangle.lly, + ] + ) + + page.contents.append(ap.operators.ConcatenateMatrix(matrix)) + + x_image = page.resources.images[len(page.resources.images)] + + page.contents.append(ap.operators.Do(x_image.name)) + + page.contents.append(ap.operators.GRestore()) + + document.save(outfile) +``` + +## Dibujar XForm en la página usando operadores + +Este ejemplo utilizó el poder de XForms y los operadores gráficos para reutilizar eficientemente contenido gráfico dentro de un PDF. Al encapsular la imagen en un XForm, puede dibujarse múltiples veces sin duplicar los datos de la imagen, lo que conduce a tamaños de archivo más pequeños y un rendimiento mejorado. Este enfoque es particularmente beneficioso cuando: + +- la misma imagen o gráfico necesita aparecer múltiples veces en un documento. + +- se requiere un control preciso sobre la ubicación y transformación de los gráficos. + +- optimizar el PDF para el rendimiento y el tamaño es una prioridad. + +Al gestionar el estado gráfico con GSave y GRestore, y al utilizar matrices de transformación con ConcatenateMatrix, esta técnica garantiza que cada gráfico se renderice correctamente y de forma independiente. + +```python +import sys +import aspose.pdf as ap +from os import path + +def draw_xform_on_page(infile, imagefile, outfile): + with ap.Document(infile) as document: + page_contents = document.pages[1].contents + + page_contents.insert(1, ap.operators.GSave()) + page_contents.append(ap.operators.GRestore()) + + page_contents.append(ap.operators.GSave()) + + form = ap.XForm.create_new_form(document.pages[1], document) + document.pages[1].resources.forms.append(form) + + form.contents.append(ap.operators.GSave()) + form.contents.append(ap.operators.ConcatenateMatrix(200, 0, 0, 200, 0, 0)) + + with open(imagefile, "rb") as image_stream: + form.resources.images.add(image_stream) + + x_image = form.resources.images[len(form.resources.images)] + form.contents.append(ap.operators.Do(x_image.name)) + form.contents.append(ap.operators.GRestore()) + + # Draw XForm at (100, 500) + page_contents.append(ap.operators.GSave()) + page_contents.append(ap.operators.ConcatenateMatrix(1, 0, 0, 1, 100, 500)) + page_contents.append(ap.operators.Do(form.name)) + page_contents.append(ap.operators.GRestore()) + + # Draw XForm at (100, 300) + page_contents.append(ap.operators.GSave()) + page_contents.append(ap.operators.ConcatenateMatrix(1, 0, 0, 1, 100, 300)) + page_contents.append(ap.operators.Do(form.name)) + page_contents.append(ap.operators.GRestore()) + + page_contents.append(ap.operators.GRestore()) + + document.save(outfile) +``` + +## Eliminar objetos gráficos usando clases de operador + +El siguiente fragmento de código muestra cómo eliminar gráficos. Tenga en cuenta que si el archivo PDF contiene etiquetas de texto para los gráficos, podrían permanecer en el archivo PDF al usar este enfoque. Por lo tanto, busque los operadores gráficos para un método alternativo que elimine dichas imágenes. + +```python +import sys +import aspose.pdf as ap +from os import path + +def remove_graphics_objects(infile, outfile): + with ap.Document(infile) as document: + page = document.pages[1] + # Collect operators to remove in single pass + # Operator codes: S=Stroke, h=ClosePathStroke, f=Fill' + graphics_operators = {"S", "h", "f"} + operators_to_remove = [ + op for op in page.contents if str(op) in graphics_operators + ] + + page.contents.delete(operators_to_remove) + document.save(outfile) +``` + +## Temas relacionados + +- [Operaciones avanzadas de PDF en Python](/pdf/es/python-net/advanced-operations/) +- [Trabajar con páginas PDF en Python](/pdf/es/python-net/working-with-pages/) +- [Trabajar con imágenes en PDF usando Python](/pdf/es/python-net/working-with-images/) +- [Trabajar con gráficos PDF en Python](/pdf/es/python-net/working-with-graphs/) diff --git a/es/python-net/advanced-operations/working-with-pages/_index.md b/es/python-net/advanced-operations/working-with-pages/_index.md index c9e3437af..d86cac1e4 100644 --- a/es/python-net/advanced-operations/working-with-pages/_index.md +++ b/es/python-net/advanced-operations/working-with-pages/_index.md @@ -1,164 +1,34 @@ --- -title: Trabajando con Páginas PDF en Python -linktitle: Trabajando con Páginas +title: Trabajar con páginas PDF en Python +linktitle: Trabajando con páginas type: docs weight: 20 url: /es/python-net/working-with-pages/ -description: Cómo agregar páginas, agregar encabezados y pies de página, agregar marcas de agua lo puedes conocer en esta sección. Aspose.PDF para Python a través de .NET te explica todos los detalles sobre este tema. -lastmod: "2023-04-19" +description: Aprenda cómo agregar, mover, rotar, recortar, extraer, estampar y administrar páginas PDF en Python. +lastmod: "2026-05-05" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Administrar páginas PDF en Python +Abstract: Esta sección muestra cómo trabajar con páginas PDF usando Aspose.PDF for Python via .NET. Cubre la adición, eliminación, movimiento, extracción, rotación, cambio de tamaño, recorte y estampado de páginas, así como la gestión de propiedades de página, encabezados, pies de página y numeración. --- - +Utilice esta sección cuando necesite realizar operaciones de PDF a nivel de página en Python. -**Aspose.PDF para Python a través de .NET** te permite insertar una página en un documento PDF en cualquier ubicación del archivo, así como agregar páginas al final de un archivo PDF. Esta sección muestra cómo añadir páginas a un PDF sin Acrobat Reader. Puedes agregar texto o imágenes en los encabezados y pies de página de tu archivo PDF, y elegir diferentes encabezados en tu documento con la biblioteca de Python de Aspose. También, intenta recortar páginas en un documento PDF de manera programática usando Python. +Con **Aspose.PDF for Python via .NET**, puedes insertar, eliminar, mover, extraer, rotar, cambiar el tamaño y recortar páginas, y luego aplicar encabezados, pies de página, números de página, marcas de agua y sellos para flujos de trabajo de diseño y revisión. -Esta sección te enseña cómo agregar marcas de agua en tu archivo PDF usando la clase Artifact. Revisarás el ejemplo de programación para esta tarea. Agrega número de página usando la clase [PageNumberStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagenumberstamp/). Para agregar un sello en tu documento usa las clases [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) y [TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/). Usa la adición de una marca de agua para crear imágenes de fondo en tu archivo PDF con **Aspose.PDF para Python a través de .NET**. +## Tareas de página cubiertas +Se cubren las siguientes tareas: -You are able to do the following: - -- [Add Pages](/pdf/es/python-net/add-pages/) - agregar páginas en la ubicación deseada o al final de un archivo PDF y eliminar una página de su documento. -- [Move Pages](/pdf/es/python-net/move-pages/) - mover páginas de un documento a otro. -- [Delete Pages](/pdf/es/python-net/delete-pages/) - eliminar página de su archivo PDF utilizando la colección PageCollection. -- [Change Page size](/pdf/es/python-net/change-page-size/) - puede cambiar el tamaño de página del PDF con un fragmento de código utilizando la biblioteca Aspose.PDF. -- [Rotate Pages](/pdf/es/python-net/rotate-pages/) - puede cambiar la orientación de las páginas en un archivo PDF existente. -- [Split Pages](/pdf/es/python-net/split-document/) - puede dividir archivos PDF en uno o varios PDF. -- [Add Headers and/or Footers](/pdf/es/python-net/add-headers-and-footers-of-pdf-file/) - agregar texto o imágenes en los encabezados y pies de página de su archivo PDF. -- [Crop Pages](/pdf/es/python-net/crop-pages/) - puede recortar páginas en un documento PDF programáticamente con diferentes propiedades de página. - -- [Add Watermarks](/pdf/es/python-net/add-watermarks/) - agregar marcas de agua en su archivo PDF con la Clase Artifact. -- [Agregar Numeración de Páginas en Archivo PDF](/pdf/es/python-net/add-page-number/) - La clase PageNumberStamp te ayudará a agregar un número de página en tu archivo PDF. -- [Agregar Fondos](/pdf/es/python-net/add-backgrounds/) - se pueden usar imágenes de fondo para agregar una marca de agua. -- [Sellado](/pdf/es/python-net/stamping/) - puedes usar la clase ImageStamp para agregar un sello de imagen a un archivo PDF y la clase TextStamp para agregar un texto. -- [Obtener y Establecer Propiedades de Página](/pdf/es/python-net/get-and-set-page-properties/) - esta sección muestra cómo obtener el número de páginas en un archivo PDF, obtener información sobre las propiedades de la página PDF como el color y establecer propiedades de página. - - \ No newline at end of file +- [Agregar páginas](/pdf/es/python-net/add-pages/) - insertar páginas en posiciones específicas o añadir páginas al final de un documento. +- [Mover páginas](/pdf/es/python-net/move-pages/) - mover páginas dentro de un documento o entre documentos. +- [Eliminar páginas](/pdf/es/python-net/delete-pages/) - eliminar páginas de un documento PDF. +- [Extrayendo páginas](/pdf/es/python-net/extract-pages/) - extraer páginas seleccionadas a un nuevo archivo PDF. +- [Rotación de páginas](/pdf/es/python-net/rotate-pages/) - cambiar la orientación de la página en un archivo PDF existente. +- [Cambiar tamaño de página](/pdf/es/python-net/change-page-size/) - redimensionar las dimensiones de la página en un documento PDF. +- [Agregar encabezados y pies de página](/pdf/es/python-net/add-headers-and-footers-of-pdf-file/) - agregar texto repetitivo, imágenes o contenido estructurado de encabezado/pie de página. +- [Recorte de páginas PDF](/pdf/es/python-net/crop-pages/) - recortar el contenido de la página usando la configuración de geometría de página. +- [Obtener y establecer propiedades de página](/pdf/es/python-net/get-and-set-page-properties/) - acceder y modificar varias propiedades de las páginas PDF, como el tamaño, la rotación y los atributos de color. +- [Estampado](/pdf/es/python-net/stamping/) - aplicar sellos de texto, imagen, página y número de página a las páginas PDF. diff --git a/es/python-net/advanced-operations/working-with-pages/add-backgrounds/_index.md b/es/python-net/advanced-operations/working-with-pages/add-backgrounds/_index.md index 1b6b7ac26..87e51394b 100644 --- a/es/python-net/advanced-operations/working-with-pages/add-backgrounds/_index.md +++ b/es/python-net/advanced-operations/working-with-pages/add-backgrounds/_index.md @@ -7,7 +7,7 @@ url: /es/python-net/add-backgrounds/ description: Añadir imagen de fondo a su archivo PDF con Python. Use la clase BackgroundArtifact. lastmod: "2023-04-17" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 --- -Las imágenes de fondo se pueden utilizar para añadir una marca de agua u otro diseño sutil a los documentos. En Aspose.PDF para Python a través de .NET, cada documento PDF es una colección de páginas y cada página contiene una colección de artefactos. La clase [BackgroundArtifact](https://reference.aspose.com/pdf/python-net/aspose.pdf/backgroundartifact/) se puede utilizar para añadir una imagen de fondo a un objeto de página. +Las imágenes de fondo se pueden utilizar para añadir una marca de agua u otro diseño sutil a los documentos. En Aspose.PDF for Python via .NET, cada documento PDF es una colección de páginas y cada página contiene una colección de artefactos. La clase [BackgroundArtifact](https://reference.aspose.com/pdf/python-net/aspose.pdf/backgroundartifact/) se puede utilizar para añadir una imagen de fondo a un objeto de página. El siguiente fragmento de código muestra cómo añadir una imagen de fondo a las páginas PDF usando el objeto BackgroundArtifact con Python. @@ -109,7 +109,7 @@ El siguiente fragmento de código muestra cómo añadir una imagen de fondo a la { "@context": "http://schema.org", "@type": "SoftwareApplication", - "name": "Aspose.PDF para Python a través de .NET Library", + "name": "Aspose.PDF for Python via .NET Library", "image": "https://www.aspose.cloud/templates/aspose/img/products/pdf/aspose_pdf-for-python-net.svg", "url": "https://www.aspose.com/", "publisher": { diff --git a/es/python-net/advanced-operations/working-with-pages/add-page-number/_index.md b/es/python-net/advanced-operations/working-with-pages/add-page-number/_index.md index 60272bba3..83ad547c2 100644 --- a/es/python-net/advanced-operations/working-with-pages/add-page-number/_index.md +++ b/es/python-net/advanced-operations/working-with-pages/add-page-number/_index.md @@ -4,10 +4,10 @@ linktitle: Añadir Número de Página type: docs weight: 30 url: /es/python-net/add-page-number/ -description: Aspose.PDF para Python a través de .NET te permite añadir un Sello de Número de Página a tu archivo PDF usando la clase PageNumberStamp. +description: Aspose.PDF for Python via .NET te permite añadir un Sello de Número de Página a tu archivo PDF usando la clase PageNumberStamp. lastmod: "2023-04-17" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 --- All the documents must have page numbers in it. The page number makes it easier for the reader to locate different parts of the document. -**Aspose.PDF para Python vía .NET** le permite agregar números de página con [PageNumberStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagenumberstamp/). +**Aspose.PDF for Python via .NET** le permite agregar números de página con [PageNumberStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagenumberstamp/). Puede usar la clase [PageNumberStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagenumberstamp/) para agregar un sello de número de página en un archivo PDF. [PageNumberStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagenumberstamp/) clase proporciona las propiedades necesarias para crear un sello basado en el número de página como formato, márgenes, alineaciones, número de inicio, etc. Para agregar un sello de número de página, necesitas crear un objeto [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) y un objeto [PageNumberStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagenumberstamp/) usando las propiedades requeridas. Después de eso, puedes llamar al método [add_stamp()](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods) de la [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) para agregar el sello en el PDF. También puedes establecer los atributos de fuente del sello de número de página. El siguiente fragmento de código te muestra cómo agregar números de página en un archivo PDF. diff --git a/es/python-net/advanced-operations/working-with-pages/add-pages/_index.md b/es/python-net/advanced-operations/working-with-pages/add-pages/_index.md index 1b243bb67..21e368cdf 100644 --- a/es/python-net/advanced-operations/working-with-pages/add-pages/_index.md +++ b/es/python-net/advanced-operations/working-with-pages/add-pages/_index.md @@ -1,133 +1,96 @@ --- -title: Añadir Páginas en PDF con Python -linktitle: Añadir Páginas +title: Agregar páginas PDF en Python +linktitle: Agregar páginas type: docs weight: 10 url: /es/python-net/add-pages/ -description: Este artículo enseña cómo insertar (añadir) una página en la ubicación deseada de un archivo PDF. Aprenda cómo mover, eliminar (borrar) páginas de un archivo PDF usando C#. -lastmod: "2022-02-17" +description: Aprenda cómo agregar o insertar páginas en documentos PDF con Python. +lastmod: "2026-04-27" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar o insertar páginas PDF con Python +Abstract: Este artículo explica cómo agregar páginas a archivos PDF usando Aspose.PDF for Python via .NET. Aprende cómo insertar páginas en blanco en posiciones específicas, agregar páginas al final de un documento y importar una página de otro PDF utilizando las APIs Document y PageCollection. --- - - - -Aspose.PDF para Python a través de .NET API proporciona total flexibilidad para trabajar con páginas en un documento PDF usando Python. Mantiene todas las páginas de un documento PDF en [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) que se puede usar para trabajar con páginas PDF. Aspose.PDF para Python a través de .NET te permite insertar una página en un documento PDF en cualquier ubicación del archivo, así como agregar páginas al final de un archivo PDF. Esta sección muestra cómo agregar páginas a un PDF usando Python. - -## Agregar o Insertar Página en un Archivo PDF - -Aspose.PDF para Python a través de .NET te permite insertar una página en un documento PDF en cualquier ubicación del archivo, así como agregar páginas al final de un archivo PDF. - -### Insertar Página Vacía en un Archivo PDF en la Ubicación Deseada - -Para insertar una página vacía en un archivo PDF: - -1. Crea un objeto de la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) con el archivo PDF de entrada. - -1. Llame al método [insert](https://reference.aspose.com/pdf/net/aspose.pdf/pagecollection/methods/insert) de la colección [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) con el índice especificado. -1. Guarde el PDF de salida usando el método [save](https://reference.aspose.com/pdf/net/aspose.pdf.document/save/methods/4). - -El siguiente fragmento de código le muestra cómo insertar una página en un archivo PDF. -```python +Aspose.PDF for Python via .NET proporciona operaciones flexibles a nivel de página para documentos PDF. Puedes gestionar páginas a través de [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) y agregar páginas a un [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) en posiciones específicas o al final del archivo. + +Utilice esta página cuando necesite insertar nuevas páginas en blanco en un PDF existente o agregar páginas al final de un documento durante los flujos de trabajo de generación. + +## Agregar o Insertar páginas en un archivo PDF + +Aspose.PDF for Python via .NET admite tanto la inserción de página en un índice específico como la adición de páginas al final de un PDF. + +### Insertar una página en blanco en un archivo PDF + +Para insertar una página en blanco en un archivo PDF: - import aspose.pdf as ap +1. Abrir un existente [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) usando métodos apropiados. +1. Inserte una nueva página vacía en un índice específico usando el [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) `insert()` método. +1. Guarde lo modificado [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) a la ruta de salida deseada. - # Abrir documento - document = ap.Document(input_pdf) - # Insertar una página vacía en un PDF +Inserte una página en blanco en un archivo PDF existente en una posición especificada: + +```python +import aspose.pdf as ap + +def insert_empty_page(input_file_name: str, output_file_name: str) -> None: + document = ap.Document(input_file_name) document.pages.insert(2) - # Guardar archivo de salida - document.save(output_pdf) + document.save(output_file_name) ``` -### Agregar una Página Vacía al Final de un Archivo PDF +### Agregar una página en blanco al final de un archivo PDF -A veces, desea asegurarse de que un documento termine en una página vacía. Este tema explica cómo insertar una página vacía al final del documento PDF. +A veces, desea asegurarse de que un documento termine en una página en blanco. Este tema explica cómo insertar una página en blanco al final del documento PDF. -Para insertar una página vacía al final de un archivo PDF: +Para insertar una página en blanco al final de un archivo PDF: -1. Cree un objeto de la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) con el archivo PDF de entrada. - -1. Llame al método [add()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) de la colección [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/), sin ningún parámetro. -1. Guarde el PDF de salida usando el método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods). +1. Abrir un existente [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) usando métodos apropiados. +1. Agregar una nueva página en blanco al final del documento usando el [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) `add()` método. +1. Guardar lo actualizado [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). El siguiente fragmento de código le muestra cómo insertar una página vacía al final de un archivo PDF. ```python +import aspose.pdf as ap - import aspose.pdf as ap +def add_empty_page_to_end(input_file_name: str, output_file_name: str) -> None: + document = ap.Document(input_file_name) + document.pages.add() + document.save(output_file_name) +``` - # Abrir documento - document = ap.Document(input_pdf) +### Agregar una página de otro documento PDF - # Insertar una página vacía al final de un archivo PDF - document.pages.add() +Con Aspose.PDF for Python via .NET, puedes crear un nuevo [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/), agrega una página inicial y luego importa una página de otro PDF en ella. + +1. Crear un nuevo [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Añade un nuevo blanco [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) y escribe algo de texto en él usando [`TextFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/textfragment/). +1. Abrir otro existente [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Copiar un [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) desde ese documento. +1. Pegar la página copiada en su documento principal usando [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. Guarda el archivo combinado. + +```python +import aspose.pdf as ap + +def add_page_from_another_document(input_file_name: str, output_file_name: str) -> None: + document = ap.Document() + page = document.pages.add() + text_fragment = ap.text.TextFragment("This is first page!") + page.paragraphs.add(text_fragment) + + another_document = ap.Document(input_file_name) + document.pages.add(another_document.pages[1]) + + document.save(output_file_name) +``` + +## Temas de página relacionados - # Guardar archivo de salida - document.save(output_pdf) \ No newline at end of file +- [Trabajar con páginas PDF en Python](/pdf/es/python-net/working-with-pages/) +- [Mover páginas PDF en Python](/pdf/es/python-net/move-pages/) +- [Eliminar páginas PDF en Python](/pdf/es/python-net/delete-pages/) +- [Extraer páginas PDF en Python](/pdf/es/python-net/extract-pages/) diff --git a/es/python-net/advanced-operations/working-with-pages/add-watermarks/_index.md b/es/python-net/advanced-operations/working-with-pages/add-watermarks/_index.md index 0bb0ecab4..b29381aa1 100644 --- a/es/python-net/advanced-operations/working-with-pages/add-watermarks/_index.md +++ b/es/python-net/advanced-operations/working-with-pages/add-watermarks/_index.md @@ -77,7 +77,7 @@ sitemap: -**Aspose.PDF para Python a través de .NET** permite agregar marcas de agua a su documento PDF utilizando Artefactos. Por favor, consulte este artículo para resolver su tarea. +**Aspose.PDF for Python via .NET** permite agregar marcas de agua a su documento PDF utilizando Artefactos. Por favor, consulte este artículo para resolver su tarea. Para trabajar con artefactos, Aspose.PDF tiene dos clases: [Artifact](https://reference.aspose.com/pdf/python-net/aspose.pdf/artifact/) y [ArtifactCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/artifactcollection/). @@ -127,7 +127,7 @@ El siguiente fragmento de código muestra cómo obtener cada marca de agua en la { "@context": "http://schema.org", "@type": "SoftwareApplication", - "name": "Aspose.PDF para Python a través de .NET Library", + "name": "Aspose.PDF for Python via .NET Library", "image": "https://www.aspose.cloud/templates/aspose/img/products/pdf/aspose_pdf-for-python-net.svg", "url": "https://www.aspose.com/", "publisher": { diff --git a/es/python-net/advanced-operations/working-with-pages/adding-headers-and-footers-of-pdf-file/_index.md b/es/python-net/advanced-operations/working-with-pages/adding-headers-and-footers-of-pdf-file/_index.md index 5dfd00158..2b4a89d07 100644 --- a/es/python-net/advanced-operations/working-with-pages/adding-headers-and-footers-of-pdf-file/_index.md +++ b/es/python-net/advanced-operations/working-with-pages/adding-headers-and-footers-of-pdf-file/_index.md @@ -1,308 +1,343 @@ --- -title: Añadir encabezado y pie de página al PDF usando Python -linktitle: Añadir encabezado y pie de página al PDF +title: Agregar encabezados y pies de página al PDF en Python +linktitle: Agregar encabezado y pie de página al PDF type: docs weight: 50 url: /es/python-net/add-headers-and-footers-of-pdf-file/ -description: Aspose.PDF para Python a través de .NET te permite añadir encabezados y pies de página a tu archivo PDF usando la clase TextStamp. -lastmod: "2023-04-17" +description: Aprende cómo agregar encabezados y pies de página a archivos PDF en Python usando texto, imágenes y contenido estructurado. +lastmod: "2026-05-05" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Agrega encabezados y pies de página a archivos PDF con Python +Abstract: Este artículo muestra cómo agregar encabezados y pies de página a documentos PDF con Aspose.PDF for Python via .NET. Cubre texto, numeración de páginas, HTML, imagen, tabla y contenido de encabezado y pie de página basado en LaTeX. --- - - - -**Aspose.PDF for Python via .NET** le permite agregar encabezados y pies de página en su archivo PDF existente. Puede agregar imágenes o texto a un documento PDF. Además, intente agregar diferentes encabezados en un archivo PDF con Python. - -## Agregar texto en el encabezado del archivo PDF - -Puede usar la clase [TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/) para agregar texto en el encabezado de un archivo PDF. La clase TextStamp proporciona propiedades necesarias para crear un sello basado en texto como tamaño de fuente, estilo de fuente y color de fuente, etc. Para agregar texto en el encabezado, necesita crear un objeto Document y un objeto TextStamp utilizando las propiedades requeridas. Después de eso, puede llamar al método 'add_stamp' de la Página para agregar el texto en el encabezado del PDF. - -Necesita configurar la propiedad [top_margin](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/#properties) de tal manera que ajuste el texto en el área del encabezado de su PDF. También necesita configurar 'horizontal_alignment' a Center y 'vertical_alignment' a Top. - -El siguiente fragmento de código le muestra cómo agregar texto en el encabezado de un archivo PDF con Python: -```python +Utilice esta página para agregar contenido de encabezado y pie de página coherente en todas las páginas del PDF con **Aspose.PDF for Python via .NET**. + +Puedes crear encabezados y pies de página con [`TextFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/textfragment/), [`HtmlFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/htmlfragment/), [`TeXFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/texfragment/), [`Image`](https://reference.aspose.com/pdf/python-net/aspose.pdf/image/), y [`Table`](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/) objetos, luego aplícalos a través de [`HeaderFooter`](https://reference.aspose.com/pdf/python-net/aspose.pdf/headerfooter/) en cada página. + +## Agregar encabezados y pies de página como fragmentos de texto - import aspose.pdf as ap +Agrega encabezados y pies de página de texto simples a todas las páginas de un PDF. Crea [`HeaderFooter`](https://reference.aspose.com/pdf/python-net/aspose.pdf/headerfooter/) objetos, inserciones [`TextFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/textfragment/) elementos en ellos, conjuntos [`MarginInfo`](https://reference.aspose.com/pdf/python-net/aspose.pdf/margininfo/) para un posicionamiento adecuado y los adjunta a cada página del documento. El resultado es un PDF donde cada página muestra texto de encabezado y pie de página consistentes. - # Abrir documento - document = ap.Document(input_pdf) +El siguiente fragmento de código muestra cómo agregar encabezados y pies de página como fragmentos de texto en un PDF usando Python: - # Crear encabezado - textStamp = ap.TextStamp("Header Text") - # Establecer propiedades del sello - textStamp.top_margin = 10 - textStamp.horizontal_alignment = ap.HorizontalAlignment.CENTER - textStamp.vertical_alignment = ap.VerticalAlignment.TOP - # Agregar encabezado en todas las páginas - for page in document.pages: - page.add_stamp(textStamp) +1. Crear fragmentos de texto para el encabezado y el pie de página. +1. Crear objetos HeaderFooter y agregar los fragmentos de texto a ellos. +1. Defina la configuración de márgenes para controlar la ubicación del encabezado y el pie de página. +1. Cargue el documento PDF desde el archivo de entrada. +1. Iterar a través de todas las páginas del documento. +1. Asigna el encabezado y el pie de página a cada página. +1. Guarde el PDF modificado en el archivo de salida. - # Guardar documento actualizado - document.save(output_pdf) +```python +import aspose.pdf as ap + +def add_header_and_footer_as_text(input_file, output_file): + # Create header text + header_text = ap.text.TextFragment("Demo header") + # Create header + header = ap.HeaderFooter() + header.paragraphs.add(header_text) + + # Create footer text + footer_text = ap.text.TextFragment("Demo footer") + + # Create footer + footer = ap.HeaderFooter() + footer.paragraphs.add(footer_text) + + # Set header margin + margin = ap.MarginInfo() + margin.left = 50 + margin.top = 20 + header.margin = margin + + # Set footer margin + footer.margin = margin + + # Open PDF document + with ap.Document(input_file) as document: + for i in range(1, len(document.pages) + 1): + # Bind the header and footer to the page + document.pages[i].header = header + document.pages[i].footer = footer + + # Save PDF document + document.save(output_file) ``` -## Agregar Texto en el Pie de Página del Archivo PDF +Este método es útil para añadir títulos consistentes, indicadores de página o avisos legales en la parte superior e inferior de cada página. También puedes ampliarlo para incluir imágenes o contenido dinámico, como números de página. -Puede usar la clase [TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/) para agregar texto en el pie de página de un archivo PDF. - Clase TextStamp proporciona propiedades necesarias para crear un sello basado en texto como tamaño de fuente, estilo de fuente y color de fuente, etc. Para agregar texto en el pie de página, necesitas crear un objeto Document y un objeto TextStamp usando las propiedades requeridas. Después de eso, puedes llamar al método 'add_stamp' de la Página para agregar el texto en el pie de página del PDF. +## Añadiendo encabezados y pies de página para la numeración de páginas -El siguiente fragmento de código te muestra cómo agregar texto en el pie de página de un archivo PDF con Python: +Agregar numeración automática de páginas a los encabezados y pies de página de un documento PDF usando Aspose.PDF for Python. Usando las variables integradas $p (número de página actual) y $P (número total de páginas), el script inserta dinámicamente la numeración de páginas en cada página. Los encabezados muestran el formato \u0027Page X from Y\u0027, mientras que los pies de página muestran \u0027Page X / Y\u0027. The [`MarginInfo`](https://reference.aspose.com/pdf/python-net/aspose.pdf/margininfo/) garantiza una colocación adecuada en cada página. -```python +1. Cree un TextFragment para el encabezado usando "Page $p from $P" para mostrar la página actual y el total de páginas. +1. Cree un objeto HeaderFooter y añada el texto del encabezado a él. +1. Cree un TextFragment para el pie de página usando \"Page $p / $P\" para un estilo de numeración alternativo. +1. Crea un objeto Footer y añade el texto del pie de página. +1. Definir la configuración de márgenes (izquierda = 50, superior = 20) y aplicarlos tanto al encabezado como al pie de página. +1. Abra el documento PDF del archivo de entrada. +1. Itere a través de todas las páginas y asigne el encabezado y el pie de página a cada una. +1. Guarde el PDF actualizado en la ruta de salida. - import aspose.pdf as ap - - # Abrir documento - document = ap.Document(input_pdf) - # Crear pie de página - textStamp = ap.TextStamp("Texto del Pie de Página") - # Establecer propiedades del sello - textStamp.bottom_margin = 10 - textStamp.horizontal_alignment = ap.HorizontalAlignment.CENTER - textStamp.vertical_alignment = ap.VerticalAlignment.BOTTOM - # Agregar pie de página en todas las páginas - for page in document.pages: - page.add_stamp(textStamp) - - # Guardar archivo PDF actualizado - document.save(output_pdf) +```python +import aspose.pdf as ap + +def using_header_and_footer_for_page_numbering(input_file, output_file): + # Create header text + header_text = ap.text.TextFragment("Page $p from $P") + # Create header + header = ap.HeaderFooter() + header.paragraphs.add(header_text) + + # Create footer text + footer_text = ap.text.TextFragment("Page $p / $P") + + # Create footer + footer = ap.HeaderFooter() + footer.paragraphs.add(footer_text) + + # Create margins + margin = ap.MarginInfo() + margin.left = 50 + margin.top = 20 + + # Set header margin + header.margin = margin + # Set footer margin + footer.margin = margin + + # Open PDF document + with ap.Document(input_file) as document: + for i in range(1, len(document.pages) + 1): + # Bind the header and footer to the page + document.pages[i].header = header + document.pages[i].footer = footer + + # Save PDF document + document.save(output_file) ``` -## Añadir Imagen en el Encabezado de un Archivo PDF +## Agregar encabezados y pies de página como fragmentos HTML -Puedes usar la clase [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) para añadir una imagen en el encabezado de un archivo PDF. La clase Image Stamp proporciona las propiedades necesarias para crear un sello basado en imagen, como el tamaño de fuente, el estilo de fuente y el color de fuente, etc. Para agregar una imagen en el encabezado, necesitas crear un objeto Document y un objeto Image Stamp utilizando las propiedades necesarias. Después de eso, puedes llamar al método 'add_stamp' de la Page para agregar la imagen en el encabezado del PDF. +Aplicar encabezados y pies de página con formato HTML a cada página de un documento PDF usando Aspose.PDF for Python. Al usar [`HtmlFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/htmlfragment/), el script permite que el estilo de texto enriquecido—como negrita y cursiva—aparezca en el encabezado y pie de página. [`MarginInfo`](https://reference.aspose.com/pdf/python-net/aspose.pdf/margininfo/) se aplica para una colocación adecuada, y los mismos elementos formateados se adjuntan a cada página del documento. -El siguiente fragmento de código te muestra cómo agregar una imagen en el encabezado de un archivo PDF con Python: +El siguiente fragmento de código demuestra cómo agregar encabezados y pies de página como fragmentos HTML a un PDF usando Python: -```python +1. Crear un fragmento de encabezado HTML usando HtmlFragment—incluyendo texto con estilo como '' para negrita. +1. Crea un objeto HeaderFooter y añade el encabezado HTML a él. +1. Crea un fragmento de pie de página HTML usando '' para estilo cursiva. +1. Cree un objeto Footer y añada el HTML del pie de página a él. +1. Configure los márgenes (left = 50, top = 20) y asígnelos tanto al encabezado como al pie de página. +1. Cargue el documento PDF usando 'ap.Document()'. +1. Recorra todas las páginas y asigne el encabezado y el pie de página a cada una. +1. Guarda el PDF modificado en la ruta de salida especificada. - import aspose.pdf as ap +```python +import aspose.pdf as ap + +def add_header_and_footer_as_html(input_file, output_file): + # Create header HTML + header_html = ap.HtmlFragment("This is an HTML Header") + # Create header + header = ap.HeaderFooter() + header.paragraphs.add(header_html) + + # Create footer HTML + footer_html = ap.HtmlFragment("Powered by Aspose.PDF") + + # Create footer + footer = ap.HeaderFooter() + footer.paragraphs.add(footer_html) + + # Set header margin + margin = ap.MarginInfo() + margin.left = 50 + margin.top = 20 + header.margin = margin + + # Set footer margin + footer.margin = margin + + # Open PDF document + with ap.Document(input_file) as document: + for i in range(1, len(document.pages) + 1): + # Bind the header and footer to the page + document.pages[i].header = header + document.pages[i].footer = footer + + # Save PDF document + document.save(output_file) +``` - # Abrir documento - document = ap.Document(input_pdf) +Usar HtmlFragment permite un formato enriquecido con estilos en línea o marcado HTML, brindándole mayor flexibilidad de diseño en comparación con texto plano. - # Crear encabezado - image_stamp = ap.ImageStamp(input_image) - # Establecer propiedades del sello - image_stamp.top_margin = 10 - image_stamp.horizontal_alignment = ap.HorizontalAlignment.CENTER - image_stamp.vertical_alignment = ap.VerticalAlignment.TOP - # Agregar encabezado en todas las páginas - for page in document.pages: - page.add_stamp(image_stamp) +## Agregar encabezados y pies de página como imágenes - # Guardar documento actualizado - document.save(output_pdf) -``` +Agregar encabezados y pies de página basados en imágenes a cada página de un documento PDF usando Aspose.PDF for Python. El mismo archivo de imagen se utiliza tanto para el encabezado como para el pie de página en cada página. [`MarginInfo`](https://reference.aspose.com/pdf/python-net/aspose.pdf/margininfo/) posiciona las imágenes, y la imagen se ajusta automáticamente para encajar dentro del área del encabezado/pie de página. -## Agregar Imagen en el Pie de Página del Archivo PDF +El siguiente fragmento de código muestra cómo agregar encabezados y pies de página como imágenes a un PDF usando Python: -Puedes usar la clase [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) para agregar una imagen en el pie de página de un archivo PDF. [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) class proporciona propiedades necesarias para crear un sello basado en imagen como tamaño de fuente, estilo de fuente y color de fuente, etc. Para agregar una imagen en el pie de página, necesitas crear un objeto Document y un objeto Image Stamp utilizando las propiedades requeridas. Después de eso, puedes llamar al método 'add_stamp' de la Página para agregar la imagen en el pie de página del PDF. +1. Cargue la imagen en un objeto 'ap.Image' y prepárela para usarla como encabezado. +1. Cree un objeto HeaderFooter y adjunte la imagen del encabezado a él. +1. Cargue la misma imagen de nuevo para usarla como pie de página. +1. Cree un objeto Footer y agregue la imagen del pie de página a él. +1. Cargue el documento PDF de entrada usando 'ap.Document()'. +1. Iterar a través de todas las páginas del documento. +1. Aplicar márgenes (izquierda = 50) para posicionar tanto el encabezado como el pie de página. +1. Asigne el encabezado y el pie de página a cada página del PDF. +1. Guarde el PDF actualizado en el archivo de salida especificado. -El siguiente fragmento de código te muestra cómo agregar una imagen en el pie de página de un archivo PDF con Python: +Esta técnica es ideal para marcar documentos con logotipos o marcas de agua en el área de encabezado/pie de página. ```python - - import aspose.pdf as ap - - # Abrir documento - document = ap.Document(input_pdf) - # Crear pie de página - image_stamp = ap.ImageStamp(input_image) - # Establecer propiedades del sello - image_stamp.bottom_margin = 10 - image_stamp.horizontal_alignment = ap.HorizontalAlignment.CENTER - image_stamp.vertical_alignment = ap.VerticalAlignment.BOTTOM - # Agregar pie de página en todas las páginas - for page in document.pages: - page.add_stamp(image_stamp) - - # Guardar archivo PDF actualizado - document.save(output_pdf) +import aspose.pdf as ap + +def add_header_and_footer_as_image(input_file, image_file, output_file): + # Create header image + header_image = ap.Image() + header_image.file = image_file + # Create header + header = ap.HeaderFooter() + header.paragraphs.add(header_image) + + # Create footer image + footer_image = ap.Image() + footer_image.file = image_file + + # Create footer + footer = ap.HeaderFooter() + footer.paragraphs.add(footer_image) + + # Open PDF document + with ap.Document(input_file) as document: + for i in range(1, len(document.pages) + 1): + # Set header margin + margin = ap.MarginInfo() + margin.left = 50 + header.margin = margin + + # Set footer margin + footer.margin = margin + + # Bind the header and footer to the page + document.pages[i].header = header + document.pages[i].footer = footer + + # Save PDF document + document.save(output_file) ``` -## Añadir diferentes encabezados en un archivo PDF +## Agregar encabezados y pies de página como tabla + +Agregar encabezados y pies de página estructurados, basados en tablas, a todas las páginas de un documento PDF usando Aspose.PDF for Python. [`Table`](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/) Los objetos ofrecen un mejor control de diseño, alineación y formato consistente para encabezados y pies de página complejos. El texto del encabezado está centrado mientras que el texto del pie de página está alineado a la izquierda, ambos usando la fuente Arial 12pt. Los anchos de columna se calculan dinámicamente según las dimensiones de la página para garantizar una colocación adecuada. -Sabemos que podemos añadir TextStamp en la sección de Encabezado/Pie de página del documento utilizando las propiedades [top_margin](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/#properties) o [bottom_margin](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/#properties), pero a veces podemos tener el requisito de añadir múltiples encabezados/pies de página en un único documento PDF. **Aspose.PDF para Python a través de .NET** explica cómo hacer esto. +Este fragmento de código agrega encabezados y pies de página (usando tablas) a cada página de un documento PDF con Aspose.PDF for Python via .NET. -Para cumplir con este requisito, crearemos objetos individuales de TextStamp (el número de objetos depende del número de encabezados/pies de página requeridos) y los añadiremos al documento PDF. - Podemos especificar también diferente información de formato para cada objeto sello individual. En el siguiente ejemplo, hemos creado un objeto Document y tres objetos TextStamp y luego hemos utilizado el método 'add_stamp' de Page para añadir el texto en la sección del encabezado del PDF. El siguiente fragmento de código te muestra cómo añadir una imagen en el pie de página de un archivo PDF con Aspose.PDF para Python: +1. Definir estilos de texto usando [`TextState`](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstate/) para encabezado y pie de página (fuente, tamaño, alineación). +1. Crear [`HeaderFooter`](https://reference.aspose.com/pdf/python-net/aspose.pdf/headerfooter/) objetos para el encabezado y pie de página. +1. Construir el encabezado [`Table`](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/) con una sola fila y una celda que contiene el texto del encabezado. +1. Construir el pie de página [`Table`](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/) con una única fila y celda que contiene el texto del pie de página. +1. Agregue las tablas a las correspondientes [`HeaderFooter`](https://reference.aspose.com/pdf/python-net/aspose.pdf/headerfooter/) objetos. +1. Establecer pie de página [`MarginInfo`](https://reference.aspose.com/pdf/python-net/aspose.pdf/margininfo/) para un posicionamiento horizontal adecuado. +1. Abre el [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) usando métodos apropiados. +1. Iterar a través de todas las páginas y asignar el encabezado y pie de página basados en tabla a cada página. +1. Guarde lo modificado [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) al archivo de salida. ```python +import aspose.pdf as ap + +def add_header_and_footer_as_table(input_file, output_file): + text_state_header = ap.text.TextState() + text_state_header.font = ap.text.FontRepository.find_font("Arial") + text_state_header.font_size = 12 + text_state_header.horizontal_alignment = ap.HorizontalAlignment.CENTER + text_state_footer = ap.text.TextState() + text_state_footer.font = ap.text.FontRepository.find_font("Arial") + text_state_footer.font_size = 12 + text_state_footer.horizontal_alignment = ap.HorizontalAlignment.LEFT + # Create header + header = ap.HeaderFooter() + # Create footer + footer = ap.HeaderFooter() + # Create header Table + table_header = ap.Table() + table_header.column_widths = str(594 - header.margin.left - header.margin.right) + header_row = table_header.rows.add() + header_row.cells.add("This is a Table Header", text_state_header) + # Create footer Table + table = ap.Table() + table.column_widths = str(594 - footer.margin.left - footer.margin.right) + table.rows.add().cells.add("Powered by Aspose.PDF", text_state_footer) + header.paragraphs.add(table_header) + footer.paragraphs.add(table) + # Set footer margin + footer.margin.left = 150 + + # Open PDF document + with ap.Document(input_file) as document: + for i in range(1, len(document.pages) + 1): + # Bind the header and footer to the page + document.pages[i].header = header + document.pages[i].footer = footer + + # Save PDF document + document.save(output_file) +``` + +## Agregar encabezados y pies de página como LaTeX + +Agregue encabezados y pies de página que contengan contenido formateado en LaTeX a todas las páginas de un documento PDF usando Aspose.PDF for Python. LaTeX permite la representación de símbolos matemáticos, fechas, marcas de derechos de autor y otros formatos avanzados. El encabezado incluye una fecha dinámica, mientras que el pie de página muestra el símbolo de derechos de autor junto con el número de página actual y el recuento total de páginas. - import aspose.pdf as ap - - # Crear tres sellos - stamp1 = ap.TextStamp("Encabezado 1") - stamp2 = ap.TextStamp("Encabezado 2") - stamp3 = ap.TextStamp("Encabezado 3") - - # Establecer la alineación del sello (colocar el sello en la parte superior de la página, centrado horizontalmente) - stamp1.vertical_alignment = ap.VerticalAlignment.TOP - stamp1.horizontal_alignment = ap.HorizontalAlignment.CENTER - # Especificar el estilo de fuente como Negrita - stamp1.text_state.font_style = ap.text.FontStyles.BOLD - # Establecer la información del color del texto de primer plano como rojo - stamp1.text_state.foreground_color = ap.Color.red - # Especificar el tamaño de fuente como 14 - stamp1.text_state.font_size = 14 - - # Ahora necesitamos establecer la alineación vertical del segundo objeto sello como Superior - stamp2.vertical_alignment = ap.VerticalAlignment.TOP - # Establecer la información de alineación horizontal para el sello como Centrado - stamp2.horizontal_alignment = ap.HorizontalAlignment.CENTER - # Establecer el factor de zoom para el objeto sello - stamp2.zoom = 10 - - # Establecer el formato del tercer objeto sello - # Especificar la información de alineación vertical para el objeto sello como SUPERIOR - stamp3.vertical_alignment = ap.VerticalAlignment.TOP - # Establecer la información de alineación horizontal para el objeto sello como Centrado - stamp3.horizontal_alignment = ap.HorizontalAlignment.CENTER - # Establecer el ángulo de rotación para el objeto sello - stamp3.rotate_angle = 35 - # Establecer el color de fondo del sello como rosa - stamp3.text_state.background_color = ap.Color.pink - # Cambiar la información de la fuente del sello a Verdana - stamp3.text_state.font = ap.text.FontRepository.find_font("Verdana") - # El primer sello se añade en la primera página; - document.pages[1].add_stamp(stamp1) - # El segundo sello se añade en la segunda página; - document.pages[2].add_stamp(stamp2) - # El tercer sello se añade en la tercera página. - document.pages[3].add_stamp(stamp3) - - # Guardar el documento actualizado - document.save(output_pdf) +El siguiente fragmento de código muestra cómo usar [`TeXFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/texfragment/) en encabezados y pies de página para un PDF usando Aspose.PDF for Python via .NET. + +1. Abre el [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) usando métodos apropiados. +1. Determinar el recuento total de páginas para usar en pies de página dinámicos. +1. Iterar a través de todas las páginas del documento. +1. Cree un [`HeaderFooter`](https://reference.aspose.com/pdf/python-net/aspose.pdf/headerfooter/) objeto para el encabezado. +1. Cree un [`TeXFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/texfragment/) para el texto del encabezado que contiene comandos LaTeX (p. ej., `\\today\\`). +1. Cree un [`HeaderFooter`](https://reference.aspose.com/pdf/python-net/aspose.pdf/headerfooter/) objeto para el pie de página. +1. Cree un [`TeXFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/texfragment/) para el texto del pie de página que incluye símbolos LaTeX y numeración de página. +1. Agregar el [`TeXFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/texfragment/) al objeto de encabezado/pie de página correspondiente. +1. Vincula el encabezado y el pie de página a la página actual. +1. Guarde lo modificado [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) al archivo de salida. + +```python +import aspose.pdf as ap + +def add_header_and_footer_as_latex(input_file, output_file): + # Open PDF document + with ap.Document(input_file) as document: + page_count = len(document.pages) + for i in range(1, page_count + 1): + # Create header + header = ap.HeaderFooter() + h_latex_text = "This is a LaTeX Header. \\today\\" + h_l_text = ap.TeXFragment(h_latex_text, True) + # Create footer + footer = ap.HeaderFooter() + f_latex_text = ( + f"\\copyright\\ 2025 My Company -- Page \\thepage\\ is {page_count}" + ) + f_l_text = ap.TeXFragment(f_latex_text, True) + + header.paragraphs.add(h_l_text) + footer.paragraphs.add(f_l_text) + # Bind the header and footer to the page + document.pages[i].header = header + document.pages[i].footer = footer + + # Save PDF document + document.save(output_file) ``` - \ No newline at end of file +## Temas de página relacionados + +- [Trabajar con páginas PDF en Python](/pdf/es/python-net/working-with-pages/) +- [Agregar números de página al PDF en Python](/pdf/es/python-net/add-page-number/) +- [Estampar páginas PDF en Python](/pdf/es/python-net/stamping/) +- [Formatear documentos PDF en Python](/pdf/es/python-net/formatting-pdf-document/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-pages/change-page-size/_index.md b/es/python-net/advanced-operations/working-with-pages/change-page-size/_index.md index 0e5d30442..22f595c54 100644 --- a/es/python-net/advanced-operations/working-with-pages/change-page-size/_index.md +++ b/es/python-net/advanced-operations/working-with-pages/change-page-size/_index.md @@ -1,172 +1,120 @@ --- -title: Cambiar el Tamaño de la Página PDF con Python -linktitle: Cambiar el Tamaño de la Página PDF +title: Cambiar el tamaño de página de PDF en Python +linktitle: Cambiar tamaño de página type: docs -weight: 60 +weight: 40 url: /es/python-net/change-page-size/ -description: Cambia el tamaño de la página de tu documento PDF usando la biblioteca Aspose.PDF para Python a través de .NET. -lastmod: "2023-04-17" +description: Aprenda cómo leer y cambiar las dimensiones de la página PDF en Python. +lastmod: "2026-04-15" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cambiar tamaño de página usando Python +Abstract: Este artículo demuestra cómo leer y modificar las dimensiones de la página PDF usando Aspose.PDF. El ejemplo Get Page Size recupera el ancho y la altura de una página PDF específica, lo que permite a los usuarios inspeccionar el diseño de la página, validar el formato o analizar la estructura del documento. El ejemplo Set Page Size muestra cómo cambiar las dimensiones de una página—por ejemplo, convertir la primera página al tamaño A4—mientras también muestra las propiedades de caja (CropBox, TrimBox, ArtBox, BleedBox, MediaBox) antes y después de la modificación. --- - - - -## Cambiar el Tamaño de Página del PDF - -Aspose.PDF para Python a través de .NET te permite cambiar el tamaño de página del PDF con simples líneas de código en tus aplicaciones Python. Este tema explica cómo actualizar/cambiar las dimensiones de página (tamaño) de un archivo PDF existente. - -La clase [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) contiene el método [set_page_size()](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods) que te permite establecer el tamaño de la página. El fragmento de código a continuación actualiza las dimensiones de la página en unos pocos pasos fáciles: - -1. Cargar el archivo PDF de origen. -1. Obtener las páginas en el objeto [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). -1. Obtener una página dada. -1. Llamar al método set_page_size() para actualizar sus dimensiones. -1. Llamar al método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) de la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) para generar el archivo PDF con dimensiones de página actualizadas. -```python +Aspose.PDF for Python via .NET le permite cambiar el tamaño de la página PDF con simples líneas de código. Este tema muestra cómo actualizar las dimensiones de la página usando el [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) y [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) APIs. + +Utilice esta guía cuando necesite cambiar el tamaño de páginas PDF existentes, normalizar las dimensiones del documento o inspeccionar la configuración de cajas de página en Python. + +{{% alert color="primary" %}} + +Tenga en cuenta que las propiedades de altura y anchura utilizan puntos como unidad básica, donde 1 pulgada = 72 puntos y 1 cm = 1/2.54 pulgada = 0.3937 pulgada = 28.3 puntos. + +{{% /alert %}} + +## Establezca el tamaño de página de una página PDF a A4 + +El ejemplo actualiza el tamaño de la primera página de un documento PDF a las dimensiones estándar de A4. También muestra las dimensiones de los recuadros de la página (CropBox, TrimBox, ArtBox, BleedBox, MediaBox) antes y después del redimensionado para que pueda verificar los cambios. - import aspose.pdf as ap +El siguiente fragmento de código muestra cómo cambiar las dimensiones de la página PDF al tamaño A4: - document = ap.Document(input_pdf) +1. Acceder al primero [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) del [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Mostrar los tamaños de caja de la página antes de la modificación (CropBox, TrimBox, ArtBox, BleedBox, MediaBox). +1. Aplicar dimensiones A4 (597.6 × 842.4 points) usando la API de página. +1. Mostrar los tamaños de caja de página actualizados. +1. Guarde lo modificado [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) a la ruta de salida especificada. - # Obtener una página en particular +```python +import aspose.pdf as ap + +def set_page_size(input_file_name, output_file_name): + document = ap.Document(input_file_name) + # Get particular page page = document.pages[1] - # Establecer el tamaño de la página como A4 (11.7 x 8.3 in) y en Aspose.Pdf, 1 pulgada = 72 puntos - # Así que las dimensiones A4 en puntos serán (842.4, 597.6) + # Set the page size as A4 (8.3 x 11.7 in) and in Aspose.Pdf, 1 inch = 72 points + # So A4 dimensions in points will be (597.6, 842.4) for portrait orientation + print("Before set") + print(f"CropBox: {page.crop_box.width} x {page.crop_box.height}") + print(f"TrimBox: {page.trim_box.width} x {page.trim_box.height}") + print(f"ArtBox: {page.art_box.width} x {page.art_box.height}") + print(f"BleedBox: {page.bleed_box.width} x {page.bleed_box.height}") + print(f"MediaBox: {page.media_box.width} x {page.media_box.height}") + page.set_page_size(597.6, 842.4) + print("After set") + print(f"CropBox: {page.crop_box.width} x {page.crop_box.height}") + print(f"TrimBox: {page.trim_box.width} x {page.trim_box.height}") + print(f"ArtBox: {page.art_box.width} x {page.art_box.height}") + print(f"BleedBox: {page.bleed_box.width} x {page.bleed_box.height}") + print(f"MediaBox: {page.media_box.width} x {page.media_box.height}") + + # Save the updated document + document.save(output_file_name) +``` + +## Obtener tamaño de página PDF + +Este fragmento lee un PDF y recupera las dimensiones (ancho y alto) de la primera página. Utiliza el [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) API para extraer el límite de la página [`Rectangle`](https://reference.aspose.com/pdf/python-net/aspose.pdf/rectangle/) y muestra su tamaño en la consola. Esto es útil para inspeccionar el diseño de la página, verificar formatos o preparar documentos para un procesamiento adicional. - # Guardar el documento actualizado - document.save(output_pdf) +1. Cargar el PDF como un [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Acceder al primero [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +1. Recuperar el rectángulo delimitador de la página usando `get_page_rect()`. +1. Extraer los valores de ancho y alto. +1. Imprimir las dimensiones de la página. + +```python +import aspose.pdf as ap + +def get_page_size(input_file_name, output_file_name): + document = ap.Document(input_file_name) + + # Get particular page + page = document.pages[1] + rectangle = page.get_page_rect(True) + print(f"{rectangle.width} : {rectangle.height}") +``` + +### Obtener el tamaño de página PDF antes y después de la rotación + +Recupere las dimensiones de una página PDF antes y después de aplicar una rotación de 90°. Esto demuestra cómo la rotación afecta el ancho y la altura y cómo usar `get_page_rect()` con o sin consideración de rotación. + +1. Abre el PDF como un [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Acceder al primero [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +1. Aplicar una rotación de 90° usando `page.rotate = ap.Rotation.ON90` (ver el [`Rotation`](https://reference.aspose.com/pdf/python-net/aspose.pdf/rotation/) enum). +1. Recuperar el rectángulo de la página sin rotación usando `get_page_rect(False)` y muestra su ancho y altura. +1. Recuperar el rectángulo de la página considerando la rotación usando `get_page_rect(True)` y muestra su ancho y altura. +1. Compare cómo cambian las dimensiones debido a la rotación. + +```python +import aspose.pdf as ap + +def get_page_size_rotation(input_file_name, output_file_name): + document = ap.Document(input_file_name) + # Get particular page + page = document.pages[1] + page.rotate = ap.Rotation.ON90 + rectangle = page.get_page_rect(False) + print(f"{rectangle.width} : {rectangle.height}") + rectangle = page.get_page_rect(True) + print(f"{rectangle.width} : {rectangle.height}") ``` +## Temas de página relacionados - \ No newline at end of file +- [Trabajar con páginas PDF en Python](/pdf/es/python-net/working-with-pages/) +- [Recortar páginas PDF en Python](/pdf/es/python-net/crop-pages/) +- [Obtener y establecer propiedades de página PDF en Python](/pdf/es/python-net/get-and-set-page-properties/) +- [Rotar páginas PDF en Python](/pdf/es/python-net/rotate-pages/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-pages/crop-pages/_index.md b/es/python-net/advanced-operations/working-with-pages/crop-pages/_index.md index 82761aee0..6bf095479 100644 --- a/es/python-net/advanced-operations/working-with-pages/crop-pages/_index.md +++ b/es/python-net/advanced-operations/working-with-pages/crop-pages/_index.md @@ -1,177 +1,94 @@ --- -title: Recortar Páginas de PDF programáticamente en Python -linktitle: Recortar Páginas +title: Recortar páginas PDF en Python +linktitle: Recorte de páginas PDF type: docs weight: 70 url: /es/python-net/crop-pages/ -description: Puede obtener propiedades de página, como el ancho, altura, bleed-, crop- y trimbox utilizando Aspose.PDF para Python vía .NET. -lastmod: "2023-04-17" +description: Aprenda cómo recortar páginas PDF y ajustar las cajas crop, trim, bleed y media en Python. +lastmod: "2026-04-15" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo acceder y modificar las propiedades de página en PDF usando Python +Abstract: El artículo proporciona una visión general de cómo acceder y modificar las propiedades de página en un documento PDF usando Aspose.PDF for Python. Describe varias propiedades de página, incluyendo la media box, bleed box, trim box, art box y crop box, explicando sus funciones para definir las dimensiones y los límites de una página PDF con fines de impresión y visualización. La media box representa el tamaño de página más grande, mientras que la bleed box garantiza la cobertura de tinta más allá del borde de la página para el recorte. La trim box indica el tamaño final del documento después del recorte, y la art box engloba el contenido real de la página. La crop box define el área visible en Adobe Acrobat. El artículo incluye un fragmento de código Python que demuestra cómo establecer una nueva crop box, junto con otras cajas, para una página específica en un documento PDF. Los ejemplos visuales ilustran la apariencia de la página antes y después de aplicar el recorte, mostrando la aplicación práctica de la modificación de estas propiedades. --- - - - -## Obtener Propiedades de la Página - -Cada página en un archivo PDF tiene una serie de propiedades, como el ancho, alto, sangrado, caja de recorte y caja de corte. Aspose.PDF para Python te permite acceder a estas propiedades. - -- **media_box**: La caja de medios es la caja de página más grande. Corresponde al tamaño de la página (por ejemplo, A4, A5, Carta de EE. UU., etc.) seleccionado cuando el documento fue impreso en PostScript o PDF. En otras palabras, la caja de medios determina el tamaño físico del medio en el que se muestra o imprime el documento PDF. -- **bleed_box**: Si el documento tiene sangrado, el PDF también tendrá una caja de sangrado. El sangrado es la cantidad de color (o arte) que se extiende más allá del borde de una página. Se utiliza para asegurarse de que cuando el documento se imprime y se corta al tamaño ("corte"), la tinta llegue hasta el borde de la página. Incluso si la página se corta mal - cortada ligeramente fuera de las marcas de corte - no aparecerán bordes blancos en la página. -- **trim_box**: La caja de corte indica el tamaño final de un documento después de imprimir y cortar. -- **art_box**: La caja de arte es la caja dibujada alrededor del contenido real de las páginas en tus documentos. - Esta caja de página se utiliza al importar documentos PDF en otras aplicaciones. -- **crop_box**: La caja de recorte es el tamaño de "página" en el que se muestra su documento PDF en Adobe Acrobat. En la vista normal, solo se muestran los contenidos de la caja de recorte en Adobe Acrobat. Para descripciones detalladas de estas propiedades, lea la especificación de Adobe.Pdf, particularmente 10.10.1 Límites de Página. - -El fragmento a continuación muestra cómo recortar la página: -```python +## Obtener propiedades de página + +Cada página en un archivo PDF tiene varias propiedades, como el ancho, la altura, bleed-, crop- y trimbox. Aspose.PDF for Python le permite acceder a estas propiedades. + +Utilice esta página cuando necesite reducir el área visible de la página, preparar archivos para flujos de trabajo de impresión o inspeccionar la geometría de los recuadros de página en documentos PDF. - import aspose.pdf as ap +- **media_box**: La media box es el recuadro de página más grande. Corresponde al tamaño de página (por ejemplo A4, A5, US Letter, etc.) seleccionado cuando el documento se imprimió a PostScript o PDF. En otras palabras, la media box determina el tamaño físico del medio en el que se muestra o imprime el documento PDF. +- **bleed_box**: Si el documento tiene sangrado, el PDF también tendrá un bleed box. El sangrado es la cantidad de color (o arte) que se extiende más allá del borde de una página. Se utiliza para asegurarse de que cuando el documento se imprime y se corta al tamaño (\u0022trimmed\u0022), la tinta llegue hasta el borde de la página. Incluso si la página se corta incorrectamente - recortada ligeramente fuera de las marcas de recorte - no aparecerán bordes blancos en la página. +- **trim_box**: El trim box indica el tamaño final de un documento después de la impresión y el recorte. +- **art_box**: El art box es el cuadro dibujado alrededor del contenido real de las páginas en sus documentos. Este cuadro de página se utiliza al importar documentos PDF en otras aplicaciones. +- **crop_box**: El crop box es el tamaño "página" con el que se muestra su documento PDF en Adobe Acrobat. En la vista normal, solo se muestra el contenido del crop box en Adobe Acrobat. Para descripciones detalladas de estas propiedades, lea la especificación Adobe.Pdf, particularmente 10.10.1 Límites de página. - document = ap.Document(input_pdf) +Recortar el primero [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) de un PDF a un área rectangular específica usando Aspose.PDF for Python. La función ajusta múltiples cajas de página—`crop_box`, `trim_box`, `art_box`, y `bleed_box`—para garantizar resultados visuales consistentes. El recorte puede ser útil para eliminar márgenes no deseados o enfocar una región particular de una página. + +1. Cargar el PDF como un [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) (usar `ap.Document()`). +1. Defina el rectángulo de recorte usando [`Rectangle`](https://reference.aspose.com/pdf/python-net/aspose.pdf/rectangle/) con las coordenadas deseadas (en puntos). +1. Establecer el [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/)es `crop_box`, `trim_box`, `art_box`, y `bleed_box` al rectángulo definido. +1. Guarde lo modificado [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) a un nuevo archivo de salida. + +```python +import sys +import aspose.pdf as ap +from os import path + +def crop_page(input_file_name, output_file_name): + document = ap.Document(input_file_name) - # Crear nuevo Rectángulo de Caja new_box = ap.Rectangle(200, 220, 2170, 1520, True) document.pages[1].crop_box = new_box document.pages[1].trim_box = new_box document.pages[1].art_box = new_box document.pages[1].bleed_box = new_box - document.save(output_pdf) + document.save(output_file_name) ``` -En este ejemplo, utilizamos un archivo de muestra [aquí](crop_page.pdf). Inicialmente, nuestra página se ve como se muestra en la Figura 1. -![Figura 1. Página Recortada](crop_page.png) +En este ejemplo utilizamos un archivo de muestra [aquí](crop_page.pdf). Inicialmente, nuestra página se ve como se muestra en la Figura 1. +![Figura 1. Página recortada](crop_page.png) Después del cambio, la página se verá como la Figura 2. -![Figura 2. Página Recortada](crop_page2.png) - - \ No newline at end of file +![Figura 2. Página recortada](crop_page2.png) + +## Recortar página PDF según el contenido de la primera imagen + +Recortar el primero [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) dinámicamente basado en los límites de la primera imagen encontrada en la página. Al usar [`ImagePlacementAbsorber`](https://reference.aspose.com/pdf/python-net/aspose.pdf/imageplacementabsorber/), el script identifica la primera imagen y ajusta la página `crop_box` para coincidir con las dimensiones de la imagen. Este enfoque es útil cuando deseas enfocarte en contenido visual específico en lugar de coordenadas predefinidas. + +1. Cargar el PDF como un [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Ubica imágenes en la primera página usando [`ImagePlacementAbsorber`](https://reference.aspose.com/pdf/python-net/aspose.pdf/imageplacementabsorber/). +1. Verifica si existen imágenes: + - Si se encuentran, establece el [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) `crop_box` para que coincida con la de la primera imagen [`Rectangle`](https://reference.aspose.com/pdf/python-net/aspose.pdf/rectangle/). + - Si no, mantenga la página sin cambios y notifique al usuario. +1. Guarde lo modificado [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) al archivo de salida especificado. + +```python +import sys +import aspose.pdf as ap +from os import path + +def crop_page_by_content(input_file_name, output_file_name): + document = ap.Document(input_file_name) + # Find first image on first page using ImagePlacementAbsorber + absorber = ap.ImagePlacementAbsorber() + document.pages[1].accept(absorber) + + if len(absorber.image_placements) > 0: + first_image = absorber.image_placements[1] + document.pages[1].crop_box = first_image.rectangle + else: + print("No images found on the first page") + document.save(output_file_name) +``` + +## Temas de página relacionados + +- [Trabajar con páginas PDF en Python](/pdf/es/python-net/working-with-pages/) +- [Cambiar el tamaño de página del PDF en Python](/pdf/es/python-net/change-page-size/) +- [Obtener y establecer propiedades de página PDF en Python](/pdf/es/python-net/get-and-set-page-properties/) +- [Rotar páginas PDF en Python](/pdf/es/python-net/rotate-pages/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-pages/delete-pages/_index.md b/es/python-net/advanced-operations/working-with-pages/delete-pages/_index.md index 492c8f15f..b93036c45 100644 --- a/es/python-net/advanced-operations/working-with-pages/delete-pages/_index.md +++ b/es/python-net/advanced-operations/working-with-pages/delete-pages/_index.md @@ -1,164 +1,64 @@ --- -title: Eliminar Páginas de PDF programáticamente Python -linktitle: Eliminar Páginas de PDF +title: Eliminar páginas PDF en Python +linktitle: Eliminando páginas PDF type: docs weight: 80 url: /es/python-net/delete-pages/ -description: Puede eliminar páginas de su archivo PDF usando la biblioteca Aspose.PDF para Python a través de .NET. -lastmod: "2023-04-17" +description: Aprende cómo eliminar páginas de archivos PDF en Python. +lastmod: "2026-04-27" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Eliminar una o más páginas PDF en Python +Abstract: Este artículo explica cómo eliminar páginas de archivos PDF usando Aspose.PDF for Python via .NET. Aprende cómo eliminar una sola página o varias páginas de un documento usando la API PageCollection y luego guarda el PDF actualizado. --- - +Puedes eliminar páginas de un archivo PDF usando Aspose.PDF for Python via .NET. Para eliminar una página en particular, usa el [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) de un [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). -Puedes eliminar páginas de un archivo PDF usando Aspose.PDF para Python a través de .NET. Para eliminar una página en particular de la colección [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +Utilice este flujo de trabajo cuando necesite eliminar páginas no deseadas de un PDF antes de compartir, archivar o combinar documentos. -## Eliminar Página de un Archivo PDF +## Eliminar página del archivo PDF -1. Llama al método [delete()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) y especifica el índice de la página -1. Llama al método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) para guardar el archivo PDF actualizado -El siguiente fragmento de código muestra cómo eliminar una página en particular del archivo PDF usando Python. +Aspose.PDF for Python via .NET elimina la página 2 del PDF de entrada y guarda el documento actualizado en un nuevo archivo. Esta característica es útil para eliminar páginas no deseadas o sensibles sin alterar el resto del documento. -```python +1. Cargue el PDF de entrada como un [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Elimine la página usando el [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. Llame al [`Document.save()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método para guardar el archivo PDF actualizado. - import aspose.pdf as ap +El siguiente fragmento de código muestra cómo eliminar una página concreta del archivo PDF usando Python. - # Abrir documento - document = ap.Document(input_pdf) +```python +import aspose.pdf as ap - # Eliminar una página en particular +def delete_page(input_file_name: str, output_file_name: str) -> None: + document = ap.Document(input_file_name) document.pages.delete(2) + document.save(output_file_name) +``` + +## Eliminar varias páginas de un documento PDF + +Eliminar varias páginas permite eliminar un conjunto de páginas especificadas en una única operación, lo que es más eficiente que eliminar páginas una por una. El PDF resultante se guarda en un nuevo archivo, preservando el documento original. - # Guardar PDF actualizado - document.save(output_pdf) +1. Cargue el PDF de entrada como un [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Elimina las páginas enumeradas en la matriz pages usando el [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. Guardar lo actualizado [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) a un nuevo archivo. + +```python +import aspose.pdf as ap + +def delete_multiple_pages(input_file_name: str, output_file_name: str) -> None: + document = ap.Document(input_file_name) + # Example: delete pages 2, 3, and 4. + pages = [2, 3, 4] + document.pages.delete(pages) + document.save(output_file_name) ``` - \ No newline at end of file +## Temas de página relacionados + +- [Trabajar con páginas PDF en Python](/pdf/es/python-net/working-with-pages/) +- [Agregar páginas PDF en Python](/pdf/es/python-net/add-pages/) +- [Mover páginas PDF en Python](/pdf/es/python-net/move-pages/) +- [Extraer páginas PDF en Python](/pdf/es/python-net/extract-pages/) diff --git a/es/python-net/advanced-operations/working-with-pages/extract-pages/_index.md b/es/python-net/advanced-operations/working-with-pages/extract-pages/_index.md new file mode 100644 index 000000000..3c548c66b --- /dev/null +++ b/es/python-net/advanced-operations/working-with-pages/extract-pages/_index.md @@ -0,0 +1,64 @@ +--- +title: Extraer páginas PDF en Python +linktitle: Extrayendo páginas PDF +type: docs +weight: 80 +url: /es/python-net/extract-pages/ +description: Aprende cómo extraer una o varias páginas PDF en nuevos archivos con Python. +lastmod: "2026-04-27" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo extraer páginas PDF usando Python +Abstract: Este artículo explica cómo extraer páginas de archivos PDF usando Aspose.PDF for Python via .NET. Aprende cómo copiar una página individual o varias páginas en un nuevo documento utilizando la indexación de páginas basada en 1 y la API PageCollection. +--- + +## Extraer una sola página de un PDF + +Extrae una página específica de un documento PDF y guárdala como un archivo nuevo. Usando la biblioteca Aspose.PDF, el script copia la página deseada a un nuevo PDF, dejando el documento original sin cambios. Esto es útil para dividir PDFs o aislar páginas importantes para su distribución. + +1. Cargue el PDF de origen usando el [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) API (`ap.Document()`). +1. Crear un nuevo [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) para contener la página extraída. +1. Añada el deseado [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) del documento de origen al nuevo PDF usando el documento de destino [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) (`dst_document.pages.add(...)`). + - En este ejemplo, la página 2 se extrae (indexación basada en 1). +1. Guarda el nuevo [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) con la página extraída al archivo de salida especificado. + +```python +import aspose.pdf as ap + +def extract_page(input_file_name: str, output_file_name: str) -> None: + src_document = ap.Document(input_file_name) + dst_document = ap.Document() + dst_document.pages.add(src_document.pages[2]) + dst_document.save(output_file_name) +``` + +## Extraer varias páginas de un PDF + +Extraiga varias páginas específicas de un documento PDF y guárdelas en un nuevo archivo. Con la biblioteca Aspose.PDF, las páginas seleccionadas se copian a un nuevo PDF mientras se mantiene intacto el documento original. Esto es útil para crear PDFs más pequeños que contengan solo las secciones relevantes de un documento más grande. + +1. Cargue el PDF de origen usando el [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) API (`ap.Document()`). +1. Crear un nuevo [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) para contener las páginas extraídas. +1. Seleccione las páginas a extraer (en este ejemplo, páginas 2 y 3 usando indexación basada en 1). +1. Agregue cada seleccionado [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) del documento fuente al nuevo PDF usando su [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. Guarda el nuevo [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) con las páginas extraídas al archivo de salida especificado. + +```python +import aspose.pdf as ap + +def extract_multiple_pages(input_file_name: str, output_file_name: str) -> None: + document = ap.Document(input_file_name) + pages = [2, 3] + another_document = ap.Document() + for page_index in pages: + another_document.pages.add(document.pages[page_index]) + another_document.save(output_file_name) +``` + +## Temas de página relacionados + +- [Trabajar con páginas PDF en Python](/pdf/es/python-net/working-with-pages/) +- [Eliminar páginas PDF en Python](/pdf/es/python-net/delete-pages/) +- [Mover páginas PDF en Python](/pdf/es/python-net/move-pages/) +- [Dividir archivos PDF en Python](/pdf/es/python-net/split-document/) diff --git a/es/python-net/advanced-operations/working-with-pages/get-and-set-page-properties/_index.md b/es/python-net/advanced-operations/working-with-pages/get-and-set-page-properties/_index.md index 94f441eb3..161a79e31 100644 --- a/es/python-net/advanced-operations/working-with-pages/get-and-set-page-properties/_index.md +++ b/es/python-net/advanced-operations/working-with-pages/get-and-set-page-properties/_index.md @@ -1,349 +1,158 @@ --- -title: Obtener y Establecer Propiedades de Página usando Python -linktitle: Obtener y Establecer Propiedades de Página +title: Obtener y establecer propiedades de página PDF en Python +linktitle: Obtener y establecer propiedades de página type: docs weight: 90 url: /es/python-net/get-and-set-page-properties/ -description: Esta sección muestra cómo obtener el número de páginas en un archivo PDF, obtener información sobre las propiedades de la página PDF como el color y establecer propiedades de página. -lastmod: "2023-04-17" +description: Aprende cómo inspeccionar y actualizar las propiedades de página PDF, como el tamaño, el recuento y la información de color, en Python. +lastmod: "2026-04-15" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo obtener y establecer propiedades de página usando Python +Abstract: Este artículo discute las capacidades de Aspose.PDF for Python via .NET, centrándose en la lectura y configuración de propiedades de página en archivos PDF usando Python. El artículo cubre varias funcionalidades, incluyendo la determinación del número de páginas en un PDF, el acceso y la modificación de propiedades de página, y el manejo de información de color. Para obtener el número de páginas, se utilizan la clase `Document` y la colección `PageCollection`, con fragmentos de código que demuestran cómo recuperar el recuento de páginas, incluso sin guardar el documento. El artículo explica diferentes propiedades de página como MediaBox, BleedBox, TrimBox, ArtBox y CropBox, y proporciona ejemplos de código para acceder a estas propiedades. Además, cubre la recuperación de una página específica de un PDF y su guardado como un documento separado, así como la determinación del tipo de color de cada página. Los ejemplos a lo largo del texto se implementan en Python, ilustrando aplicaciones prácticas de estas funciones. --- - - - -Aspose.PDF para Python a través de .NET te permite leer y establecer propiedades de páginas en un archivo PDF en tus aplicaciones Python. Esta sección muestra cómo obtener el número de páginas en un archivo PDF, obtener información sobre las propiedades de las páginas del PDF como el color y establecer propiedades de la página. Los ejemplos dados están en Python. - -## Obtener el Número de Páginas en un Archivo PDF - -Cuando trabajas con documentos, a menudo deseas saber cuántas páginas contienen. Con Aspose.PDF esto no toma más de dos líneas de código. + +Aspose.PDF for Python via .NET le permite leer y establecer propiedades de páginas en un archivo PDF en sus aplicaciones Python. Esta sección muestra cómo obtener el número de páginas en un archivo PDF, obtener información sobre las propiedades de la página PDF, como el color, y establecer propiedades de la página. Los ejemplos usan el [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) y [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) APIs y están escritas en Python. + +Utilice esta guía cuando necesite inspeccionar los metadatos de la página, determinar el recuento de páginas o actualizar las características a nivel de página como parte del análisis o tareas de normalización de documentos. + +## Obtener número de páginas en un archivo PDF + +Al trabajar con documentos, a menudo deseas saber cuántas páginas contienen. Con Aspose.PDF esto no requiere más de dos líneas de código. Para obtener el número de páginas en un archivo PDF: -1. Abre el archivo PDF usando la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). -1. Luego usa la propiedad Count de la colección [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) (del objeto Document) para obtener el número total de páginas en el documento. +1. Abra el archivo PDF usando el [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase. +1. Luego usa el [ColecciónDePáginas](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) propiedad Count de collection\u0027s (del objeto Document) para obtener el número total de páginas en el documento. El siguiente fragmento de código muestra cómo obtener el número de páginas de un archivo PDF. ```python +import sys +import aspose.pdf as ap +from os import path - import aspose.pdf as ap - - # Abrir documento - document = ap.Document(input_pdf) +def get_page_count(input_file_name): + # Open document + document = ap.Document(input_file_name) - # Obtener conteo de páginas - print("Conteo de Páginas:", str(len(document.pages))) + # Get page count + print("Page Count:", str(len(document.pages))) ``` +### Obtener el recuento de páginas sin guardar el documento -### Obtener el número de páginas sin guardar el documento - -A veces generamos archivos PDF sobre la marcha y durante la creación del archivo PDF, podemos encontrar el requisito (crear tabla de contenidos, etc.) de obtener el número de páginas del archivo PDF sin guardarlo en el sistema o flujo. Por lo tanto, para satisfacer este requisito, se ha introducido un método [process_paragraphs()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) en la clase Document. Por favor, eche un vistazo al siguiente fragmento de código que muestra los pasos para obtener el número de páginas sin guardar el documento. +A veces generamos los archivos PDF sobre la marcha y, durante la creación del archivo PDF, podemos encontrarnos con el requisito (crear la Tabla de Contenidos, etc.) de obtener el recuento de páginas del archivo PDF sin guardar el archivo en el sistema o en un flujo. Por lo tanto, para atender este requisito, se ha introducido un método [process_paragraphs()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) ha sido introducido en la clase Document. Por favor, eche un vistazo al siguiente fragmento de código que muestra los pasos para obtener el recuento de páginas sin guardar el documento. ```python +import sys +import aspose.pdf as ap +from os import path - import aspose.pdf as ap - - # Instanciar instancia de Document +def get_page_count_without_saving(input_file_name): + # Instantiate Document instance document = ap.Document() - # Agregar página a la colección de páginas del archivo PDF + # Add page to pages collection of PDF file page = document.pages.add() - # Crear instancia de bucle - for i in range(0, 300): - # Agregar TextFragment a la colección de párrafos del objeto página - page.paragraphs.add(ap.text.TextFragment("Prueba de conteo de páginas")) - # Procesar los párrafos en el archivo PDF para obtener un conteo de páginas preciso + # Create loop instance + for _ in range(0, 300): + # Add TextFragment to paragraphs collection of page object + page.paragraphs.add(ap.text.TextFragment("Pages count test")) + # Process the paragraphs in PDF file to get accurate page count document.process_paragraphs() - # Imprimir número de páginas en el documento - print("Número de páginas en el documento =", str(len(document.pages))) + # Print number of pages in document + print("Number of pages in document =", str(len(document.pages))) ``` +## Obtener propiedades de página -## Obtener Propiedades de la Página - -Cada página en un archivo PDF tiene una serie de propiedades, como el ancho, alto, caja de sangrado, de recorte y de corte. Aspose.PDF te permite acceder a estas propiedades. - -### **Entendiendo las Propiedades de la Página: la Diferencia entre Artbox, BleedBox, CropBox, MediaBox, TrimBox y la propiedad Rect** +Cada página en un archivo PDF tiene varias propiedades, como el ancho, la altura, bleed-, crop- y trimbox. Aspose.PDF le permite acceder a estas propiedades. -- **Caja de medios**: La caja de medios es la caja de página más grande. Corresponde al tamaño de la página (por ejemplo A4, A5, Carta de EE. UU., etc.) seleccionado cuando el documento fue impreso en PostScript o PDF. En otras palabras, la caja de medios determina el tamaño físico del medio en el que se muestra o imprime el documento PDF. -- **Caja de sangrado**: Si el documento tiene sangrado, el PDF también tendrá una caja de sangrado. - Bleed es la cantidad de color (o arte) que se extiende más allá del borde de una página. Se utiliza para asegurarse de que cuando el documento se imprima y corte al tamaño ("recortado"), la tinta llegue hasta el borde de la página. Incluso si la página se corta incorrectamente, cortada ligeramente fuera de las marcas de recorte, no aparecerán bordes blancos en la página. +### Comprendiendo las propiedades de página: la diferencia entre Artbox, BleedBox, CropBox, MediaBox, TrimBox y la propiedad Rect -- **Caja de recorte**: La caja de recorte indica el tamaño final de un documento después de imprimir y recortar. -- **Caja de arte**: La caja de arte es la caja dibujada alrededor del contenido real de las páginas en tus documentos. Esta caja de página se utiliza al importar documentos PDF en otras aplicaciones. -- **Caja de cultivo**: La caja de cultivo es el tamaño de "página" en el que se muestra tu documento PDF en Adobe Acrobat. En vista normal, solo se muestran los contenidos de la caja de cultivo en Adobe Acrobat. - Para descripciones detalladas de estas propiedades, lee la especificación de Adobe.Pdf, particularmente 10.10.1 Límites de Página. -- **Page.Rect**: la intersección (comúnmente rectángulo visible) de la MediaBox y DropBox. La imagen a continuación ilustra estas propiedades. +- **Media box**: La Media box es la caja de página más grande. Corresponde al tamaño de página (por ejemplo A4, A5, US Letter, etc.) seleccionado cuando el documento se imprimió a PostScript o PDF. En otras palabras, la Media box determina el tamaño físico del medio en el que se muestra o imprime el documento PDF. +- **Bleed box**: Si el documento tiene sangrado, el PDF también tendrá un cuadro de sangrado. El sangrado es la cantidad de color (o arte) que se extiende más allá del borde de una página. Se utiliza para asegurarse de que, cuando el documento se imprime y se corta al tamaño (“trimmed”), la tinta llegue hasta el borde de la página. Incluso si la página se corta de manera incorrecta - cortada ligeramente fuera de las marcas de recorte - no aparecerán bordes blancos en la página. +- **Trim box**: El cuadro de recorte indica el tamaño final de un documento después de imprimir y recortar. +- **Art box**: El cuadro de arte es el cuadro dibujado alrededor del contenido real de las páginas en sus documentos. Este cuadro de página se usa al importar documentos PDF en otras aplicaciones. +- **Crop box**: La crop box es el tamaño de “página” en el que su documento PDF se muestra en Adobe Acrobat. En vista normal, sólo el contenido de la crop box se muestra en Adobe Acrobat. + Para descripciones detalladas de estas propiedades, lea la especificación Adobe.Pdf, particularmente la sección 10.10.1 Page Boundaries. +-- **Page.Rect**: la intersección (rectángulo visible comúnmente) del MediaBox y el DropBox (`Page.rect`). Ver el [`Rectangle`](https://reference.aspose.com/pdf/python-net/aspose.pdf/rectangle/) tipo para las propiedades del rectángulo. La imagen de abajo ilustra estas propiedades. Para más detalles, por favor visite [esta página](http://www.enfocus.com/manuals/ReferenceGuide/PP/10/enUS/en-us/concept/c_aa1095731.html). -### **Accediendo a las Propiedades de la Página** +### Accediendo a las propiedades de la página -La clase [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) proporciona todas las propiedades relacionadas con una página PDF en particular. Todas las páginas de los archivos PDF están contenidas en la colección [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) del objeto [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +El [Página](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) La clase proporciona todas las propiedades relacionadas con una página PDF en particular. Todas las páginas de los archivos PDF están contenidas en el de la [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) del objeto [ColecciónDePáginas](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) colección. -Desde allí, es posible acceder a objetos de página individuales usando su índice, o recorrer la colección utilizando un bucle foreach, para obtener todas las páginas. Una vez que se accede a una página individual, podemos obtener sus propiedades. El siguiente fragmento de código muestra cómo obtener las propiedades de la página. +Desde allí, es posible acceder a cualquiera de los individuales `Page` objetos usando su índice, o recorrer la colección para obtener todas las páginas. Una vez que se accede a una página individual, podemos obtener sus propiedades. El siguiente fragmento de código muestra cómo obtener las propiedades de la página (la `Page` API). ```python - - import aspose.pdf as ap - - # Abrir documento - document = ap.Document(input_pdf) - # Obtener página particular +import sys +import aspose.pdf as ap +from os import path + +def get_page_properties(input_file_name): + # Open document + document = ap.Document(input_file_name) + # Get particular page page = document.pages[1] - # Obtener propiedades de la página - print( - "ArtBox : Height={},Width={},LLX={},LLY={},URX={},URY={}".format( - page.art_box.height, - page.art_box.width, - page.art_box.llx, - page.art_box.lly, - page.art_box.urx, - page.art_box.ury, - ) - ) - print( - "BleedBox : Height={},Width={},LLX={},LLY={},URX={},URY={}".format( - page.bleed_box.height, - page.bleed_box.width, - page.bleed_box.llx, - page.bleed_box.lly, - page.bleed_box.urx, - page.bleed_box.ury, - ) - ) - print( - "CropBox : Height={},Width={},LLX={},LLY={},URX={},URY={}".format( - page.crop_box.height, - page.crop_box.width, - page.crop_box.llx, - page.crop_box.lly, - page.crop_box.urx, - page.crop_box.ury, - ) - ) - print( - "MediaBox : Height={},Width={},LLX={},LLY={},URX={},URY={}".format( - page.media_box.height, - page.media_box.width, - page.media_box.llx, - page.media_box.lly, - page.media_box.urx, - page.media_box.ury, - ) - ) - print( - "TrimBox : Height={},Width={},LLX={},LLY={},URX={},URY={}".format( - page.trim_box.height, - page.trim_box.width, - page.trim_box.llx, - page.trim_box.lly, - page.trim_box.urx, - page.trim_box.ury, - ) - ) - print( - "Rect : Height={},Width={},LLX={},LLY={},URX={},URY={}".format( - page.rect.height, - page.rect.width, - page.rect.llx, - page.rect.lly, - page.rect.urx, - page.rect.ury, - ) - ) - print("Número de Página :", page.number) - print("Rotar :", page.rotate) -``` -## Obtener una Página Particular del Archivo PDF - -Aspose.PDF para Python permite [dividir un PDF en páginas individuales](/pdf/es/python-net/split-pdf-document/) y guardarlas como archivos PDF. Obtener una página especificada en un archivo PDF y guardarla como un nuevo PDF es una operación muy similar: abrir el documento fuente, acceder a la página, crear un nuevo documento y agregar la página a este. - -El [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document) object's [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection) contiene las páginas en el archivo PDF. Para obtener una página particular de esta colección: - -1. Especifique el índice de la página usando la propiedad Pages. -1. Cree un nuevo objeto [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). -1. Agregue el objeto [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) al nuevo objeto Document. -1. Guarde la salida usando el método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods). - -El siguiente fragmento de código muestra cómo obtener una página particular de un archivo PDF y guardarla como un nuevo archivo. - -```python - - import aspose.pdf as ap - - # Abrir documento - document = ap.Document(input_pdf) + # Get page properties + boxes = { + "ArtBox": page.art_box, + "BleedBox": page.bleed_box, + "CropBox": page.crop_box, + "MediaBox": page.media_box, + "TrimBox": page.trim_box, + "Rect": page.rect, + } - # Obtener página particular - page = document.pages[2] + # Print box properties + for box_name, box in boxes.items(): + print( + f"{box_name} : Height={box.height},Width={box.width},LLX={box.llx},LLY={box.lly},URX={box.urx},URY={box.ury}" + ) - # Guardar la página como archivo PDF - new_document = ap.Document() - new_document.pages.add(page) - new_document.save(output_pdf) + # Print other page properties + print(f"Page Number : {page.number}") + print(f"Rotate : {page.rotate}") ``` -## Determinar el Color de la Página +## Determinar color de página -La clase [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) proporciona las propiedades relacionadas con una página particular en un documento PDF, incluyendo qué tipo de color - RGB, blanco y negro, escala de grises o indefinido - la página utiliza. +El [Página](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) La clase proporciona las propiedades relacionadas con una página particular en un documento PDF, incluido el tipo de color - RGB, blanco y negro, escala de grises o indefinido - que utiliza la página. -Todas las páginas de los archivos PDF están contenidas por la colección [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). - El atributo [color_type](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) especifica el color de los elementos en la página. Para obtener o determinar la información de color para una página PDF en particular, use la propiedad [color_type](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) del objeto [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +Todas las páginas de los archivos PDF están contenidas por el [ColecciónDePáginas](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) colección. El [color_type](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) la propiedad especifica el color de los elementos en la página. Para obtener o determinar la información de color de una página PDF en particular, use la [Página](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) del objeto [color_type](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) propiedad. -El siguiente fragmento de código muestra cómo iterar a través de cada página de un archivo PDF para obtener información de color. +El siguiente fragmento de código muestra cómo iterar a través de una página individual del archivo PDF para obtener información de color. ```python - - import aspose.pdf as ap - - # Abrir archivo PDF de origen - document = ap.Document(input_pdf) - # Iterar a través de todas las páginas del archivo PDF - for page_n in range(0, len(document.pages)): - page_number = page_n + 1 - # Obtener la información del tipo de color para una página PDF en particular +import sys +import aspose.pdf as ap +from os import path + +def get_page_color_type(input_file_name): + # Open source PDF file + document = ap.Document(input_file_name) + # Iterate through all the page of PDF file + for page_number in range(1, len(document.pages) + 1): + # Get the color type information for particular PDF page page_color_type = document.pages[page_number].color_type - if page_color_type == ap.ColorType.BLACK_AND_WHITE: - print("La página # " + str(page_number) + " es en blanco y negro.") - - if page_color_type == ap.ColorType.GRAYSCALE: - print("La página # " + str(page_number) + " es en escala de grises.") - - if page_color_type == ap.ColorType.RGB: - print("La página # " + str(page_number) + " es RGB.") - - if page_color_type == ap.ColorType.UNDEFINED: - print("El color de la página # " + str(page_number) + " es indefinido.") + color_type_map = { + ap.ColorType.BLACK_AND_WHITE: "Black and white", + ap.ColorType.GRAYSCALE: "Gray Scale", + ap.ColorType.RGB: "RGB", + ap.ColorType.UNDEFINED: "undefined", + } + color_description = color_type_map.get(page_color_type, "unknown") + print(f"Page # {page_number} is {color_description}.") ``` - \ No newline at end of file +## Temas de página relacionados + +- [Trabajar con páginas PDF en Python](/pdf/es/python-net/working-with-pages/) +- [Cambiar el tamaño de página del PDF en Python](/pdf/es/python-net/change-page-size/) +- [Recortar páginas PDF en Python](/pdf/es/python-net/crop-pages/) +- [Rotar páginas PDF en Python](/pdf/es/python-net/rotate-pages/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-pages/move-pages/_index.md b/es/python-net/advanced-operations/working-with-pages/move-pages/_index.md index da9603ca1..bb1b73712 100644 --- a/es/python-net/advanced-operations/working-with-pages/move-pages/_index.md +++ b/es/python-net/advanced-operations/working-with-pages/move-pages/_index.md @@ -1,161 +1,110 @@ --- -title: Mover páginas de PDF programáticamente a través de Python -linktitle: Mover páginas de PDF +title: Mover páginas PDF en Python +linktitle: Mover páginas PDF type: docs weight: 100 url: /es/python-net/move-pages/ -description: Intente mover páginas a la ubicación deseada o al final de un archivo PDF usando Aspose.PDF para Python a través de .NET. -lastmod: "2023-04-17" +description: Aprenda cómo mover páginas PDF dentro de un documento o entre documentos en Python. +lastmod: "2026-04-27" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Mover páginas PDF entre documentos en Python +Abstract: Este artículo explica cómo mover páginas en PDFs usando Aspose.PDF for Python via .NET. Aprende cómo mover una sola página o varias páginas a otro documento, y cómo reubicar una página dentro del mismo PDF usando las APIs Document y PageCollection. --- - - - -## Mover una Página de un Documento PDF a Otro - -Este tema explica cómo mover una página de un documento PDF al final de otro documento usando Python. -Para mover una página debemos: - -1. Crear un objeto de clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) con el archivo PDF de origen. -1. Crear un objeto de clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) con el archivo PDF de destino. -1. Obtener la página de la colección [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). -1. [add()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) la página al documento de destino. -1. Guardar el PDF de salida usando el método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods). -1. [delete()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) la página en el documento de origen. - -1. Guarde el PDF de origen usando el método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods). -El siguiente fragmento de código le muestra cómo mover una página. +## Mover una página de un documento PDF a otro -```python +Aspose.PDF for Python le permite mover una página (no solo copiarla) de un PDF a otro. Elimina la página seleccionada del documento original y luego la agrega a un nuevo archivo PDF. - import aspose.pdf as ap +Piense en ello como cortar una página de un libro y pegarla en otro — la página ya no existe en el archivo original después del movimiento. - srcDocument = ap.Document(src_file_name) - dstDocument = ap.Document(dst_File_name) - page = srcDocument.pages[2] - dstDocument.pages.add(page) - # Guardar archivo de salida - dstDocument.save(dst_File_name_new) - srcDocument.pages.delete(2) - srcDocument.save(src_file_name_new) -``` +1. Abra el documento PDF de origen usando el [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase. +1. Seleccione una página específica para mover (en este caso, la página 2) — esto se refiere a un [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +1. Cree un nuevo documento PDF (instancie otro [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)). +1. Agregue la página seleccionada al nuevo documento PDF usando el documento de destino [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) (por ejemplo, `another_document.pages.add(page)`). +1. Elimine la página del documento original mediante su [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) (por ejemplo, `document.pages.delete(index)`). +1. Guarde ambos documentos. -## Mover un Conjunto de Páginas de un Documento PDF a Otro +El siguiente fragmento de código le muestra cómo mover una página. -1. Cree un objeto de clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) con el archivo PDF de origen. -2. Cree un objeto de clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) con el archivo PDF de destino. -3. Defina un array con los números de página a mover. -4. Ejecute un bucle a través del array: +```python +import aspose.pdf as ap + +def move_page_from_one_document_to_another( + input_file_name: str, output_file_name: str +) -> None: + + document = ap.Document(input_file_name) + page = document.pages[2] + another_document = ap.Document() + another_document.pages.add(page) + document.pages.delete(2) + document.save(input_file_name.replace(".pdf", "_new.pdf")) + another_document.save(output_file_name) +``` -1. Obtener página de la [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). -1. [add()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) página al documento de destino. -1. Guardar el PDF de salida usando el método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods). -1. [delete()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) página en el documento fuente usando array. -1. Guardar el PDF fuente usando el método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods). +## Mover varias páginas de un documento PDF a otro -El siguiente fragmento de código te muestra cómo insertar una página vacía al final de un archivo PDF. +A diferencia de copiar, esta operación transfiere las páginas seleccionadas — eliminándolas del archivo origen y guardándolas en un nuevo PDF. -```python +1. Crear un nuevo documento de destino vacío (`Document`). +1. Seleccione varias páginas (en este caso, las páginas 1 y 3) del documento de origen [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. Recorra las páginas seleccionadas y agregue cada una al documento de destino [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. Guarda el documento de destino que contiene las páginas movidas. +1. Elimina las páginas movidas del documento origen usando su [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. Guarda el documento origen modificado con un nuevo nombre de archivo para conservar ambas versiones. - import aspose.pdf as ap +El siguiente fragmento de código muestra cómo mover varias páginas. - srcDocument = ap.Document(input_pdf) - dstDocument = ap.Document() - pages = [1, 3] +```python +import aspose.pdf as ap + +def move_multiple_pages_from_one_document_to_another( + input_file_name: str, output_file_name: str +) -> None: + src_document = ap.Document(input_file_name) + dst_document = ap.Document() + pages = [1, 2] for page_index in pages: - page = srcDocument.pages[page_index] - dstDocument.pages.add(page) - # Guardar archivos de salida - dstDocument.save(output_pdf_1) - srcDocument.pages.delete(pages) - srcDocument.save(output_pdf_2) + page = src_document.pages[page_index] + dst_document.pages.add(page) + # Save output files + dst_document.save(output_file_name) + src_document.pages.delete(pages) + src_document.save(input_file_name.replace(".pdf", "_new.pdf")) ``` +## Mover una página a una nueva ubicación en el mismo documento PDF -## Moviendo una Página a una nueva ubicación en el Documento PDF actual +Muestra cómo mover una página específica a una posición diferente dentro del mismo documento — una necesidad común al reorganizar o editar diseños de PDF. -1. Cree un objeto de la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) con el archivo PDF de origen. -1. Obtenga la Página de la colección [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). -1. [add()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) página a la nueva ubicación (por ejemplo, al final). -1. [delete()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) página en la ubicación anterior. -1. Guarde el PDF de salida usando el método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods). +1. Cargue el documento PDF de entrada usando el [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase. +1. Seleccione la página que desea mover (página 2) — esto es un [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +1. Agrégala al final del documento usando el documento [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. Eliminar la página original de su ubicación anterior a través de la [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. Guardar el documento modificado como un archivo nuevo. ```python +import aspose.pdf as ap - import aspose.pdf as ap +def move_page_in_new_location_in_same_document( + input_file_name: str, output_file_name: str +) -> None: + src_document = ap.Document(input_file_name) - srcDocument = ap.Document(input_pdf) + page = src_document.pages[2] + src_document.pages.add(page) + src_document.pages.delete(2) + + # Save output file + src_document.save(output_file_name) +``` - page = srcDocument.pages[2] - srcDocument.pages.add(page) - srcDocument.pages.delete(2) +## Temas de página relacionados - # Guardar archivo de salida - srcDocument.save(output_pdf) \ No newline at end of file +- [Trabajar con páginas PDF en Python](/pdf/es/python-net/working-with-pages/) +- [Agregar páginas PDF en Python](/pdf/es/python-net/add-pages/) +- [Eliminar páginas PDF en Python](/pdf/es/python-net/delete-pages/) +- [Extraer páginas PDF en Python](/pdf/es/python-net/extract-pages/) diff --git a/es/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md b/es/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md index 261c1ab7a..c01a191bf 100644 --- a/es/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md +++ b/es/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md @@ -1,175 +1,44 @@ --- -title: Rotar Páginas de PDF Usando Python -linktitle: Rotar Páginas de PDF +title: Rotar páginas PDF en Python +linktitle: Rotación de páginas PDF type: docs weight: 110 url: /es/python-net/rotate-pages/ -description: Este tema describe cómo rotar la orientación de la página en un archivo PDF existente programáticamente con Python. -lastmod: "2023-04-17" +description: Aprenda cómo rotar páginas PDF y cambiar la orientación de la página en Python. +lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo rotar páginas en PDF con Python +Abstract: Este artículo ofrece una guía sobre cómo actualizar o cambiar programáticamente la orientación de página de las páginas en un archivo PDF existente utilizando Python. Utilizando Aspose.PDF for Python via .NET, los usuarios pueden cambiar fácilmente entre orientaciones horizontal y vertical ajustando las propiedades MediaBox de la página. El artículo incluye un fragmento de código Python que muestra cómo iterar a través de las páginas de un documento PDF, modificar sus dimensiones y posiciones MediaBox, y ajustar el CropBox si es necesario. Además, explica cómo establecer el ángulo de rotación de las páginas usando el método 'rotate' para lograr la orientación deseada. El proceso concluye guardando el archivo PDF actualizado. --- - +Este tema describe cómo actualizar o cambiar la orientación de página de las páginas en un archivo PDF existente programáticamente con Python. -Este tema describe cómo actualizar o cambiar la orientación de las páginas en un archivo PDF existente de manera programática con Python. +Utilice esta página cuando necesite cambiar las páginas entre orientación vertical y horizontal o aplicar ángulos de rotación al contenido PDF existente. -## Cambiar la Orientación de la Página +## Cambiar orientación de página -Aspose.PDF para Python a través de .NET soporta grandes características como cambiar la orientación de la página de horizontal a vertical y viceversa. Para cambiar la orientación de la página, establezca el MediaBox de la página usando el siguiente fragmento de código. También puede cambiar la orientación de la página estableciendo el ángulo de rotación usando el método 'rotate'. +Esta función rota cada página de un PDF [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 90 grados en sentido horario usando Aspose.PDF for Python. +Es útil para corregir problemas de orientación de página, como documentos escaneados que están de lado. El PDF original permanece sin cambios, y la versión rotada se guarda como un nuevo archivo. ```python +import sys +import aspose.pdf as ap +from os import path - import aspose.pdf as ap - - doc = ap.Document(input_pdf) - for page in doc.pages: - r = page.media_box - newHeight = r.width - newWidth = r.height - newLLX = r.llx - # Debemos mover la página hacia arriba para compensar el cambio de tamaño de la página - # (el borde inferior de la página es 0,0 y la información generalmente se coloca desde el - # La parte superior de la página. Es por eso que movemos el borde inferior hacia arriba en la diferencia entre - # La altura antigua y la nueva. - newLLY = r.lly + (r.height - newHeight) - page.media_box = ap.Rectangle(newLLX, newLLY, newLLX + newWidth, newLLY + newHeight, True) - # A veces también necesitamos establecer el CropBox (si estaba establecido en el archivo original) - page.crop_box = ap.Rectangle(newLLX, newLLY, newLLX + newWidth, newLLY + newHeight, True) - - # Estableciendo el ángulo de rotación de la página +def rotate_page(infile, outfile): + document = ap.Document(infile) + for page in document.pages: page.rotate = ap.Rotation.ON90 - # Guardar archivo de salida - doc.save(output_pdf) + document.save(outfile) ``` +## Temas de página relacionados - \ No newline at end of file +- [Trabajar con páginas PDF en Python](/pdf/es/python-net/working-with-pages/) +- [Cambiar el tamaño de página del PDF en Python](/pdf/es/python-net/change-page-size/) +- [Recortar páginas PDF en Python](/pdf/es/python-net/crop-pages/) +- [Obtener y establecer propiedades de página PDF en Python](/pdf/es/python-net/get-and-set-page-properties/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-pages/stamping/_index.md b/es/python-net/advanced-operations/working-with-pages/stamping/_index.md index 6b44e5c27..13d277f1f 100644 --- a/es/python-net/advanced-operations/working-with-pages/stamping/_index.md +++ b/es/python-net/advanced-operations/working-with-pages/stamping/_index.md @@ -1,150 +1,29 @@ --- -title: Stamping with Aspose.PDF using Python -linktitle: Stamping +title: Estampar páginas de PDF en Python +linktitle: Estampado type: docs weight: 120 url: /es/python-net/stamping/ -description: Esta sección describe cómo agregar sellos de imagen y sellos de texto a una página PDF mediante Python. -lastmod: "2023-04-17" +description: Aprende cómo agregar números de página, sellos de página, sellos de imagen y sellos de texto a páginas de PDF en Python. +lastmod: "2026-04-15" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo agregar sellos a PDF usando Python +Abstract: Este artículo analiza el concepto y la aplicación de los sellos en documentos PDF, que son similares a los sellos de goma en documentos de papel, proporcionando información adicional y mejorando la seguridad del documento. Destaca el uso de **Aspose.PDF for Python via .NET** para agregar sellos de imagen o texto a los PDF. El artículo incluye orientación sobre cómo agregar sellos de imagen, controlar la calidad de la imagen y usar sellos de imagen como fondos, así como instrucciones para agregar sellos de texto, establecer la alineación y rellenar texto de trazo en un PDF. Los lectores pueden explorar dos secciones para obtener instrucciones detalladas - \u0022Add Image stamps in PDF page\u0022 y \u0022Add Text stamps in the PDF File\u0022. --- - +Un sello en un documento PDF es análogo a aplicar un sello de goma en un documento de papel. +El sello en el archivo PDF proporciona información adicional para el archivo PDF, como proteger el archivo PDF para que sea usado por otros y confirmar la seguridad del contenido del archivo PDF. **Aspose.PDF for Python via .NET** permite agregar una imagen o sello de texto en su documento PDF. -Un sello en un documento PDF es análogo a aplicar un sello de goma en un documento de papel. El sello en el archivo PDF proporciona información adicional para el archivo PDF, como proteger el archivo PDF para que no sea utilizado por otros y confirmar la seguridad del contenido del archivo PDF. **Aspose.PDF para Python a través de .NET** permite agregar una imagen o texto como sello en su documento PDF. +Utilice esta sección cuando necesite agregar superposiciones como números de página, marcas de agua, logotipos o marcadores de texto a páginas PDF existentes. Consulte las siguientes secciones para aprender cómo agregar un sello con Python: - [Agregar sellos de imagen en la página PDF](/pdf/es/python-net/image-stamps-in-pdf-page/) - agregar sello de imagen, controlar la calidad de la imagen, sello de imagen como fondo de su archivo PDF. -- [Agregar sellos de texto en el archivo PDF](/pdf/es/python-net/text-stamps-in-the-pdf-file/) - agregar sello de texto, definir la alineación para el objeto TextStamp, rellenar texto trazo como sello en el archivo PDF. +- [Agregar sellos de texto en el archivo PDF](/pdf/es/python-net/text-stamps-in-the-pdf-file/) - agregar sello de texto, definir alineación para el objeto TextStamp, rellenar texto de trazo como sello en el archivo PDF. +- [Agregar sellos de página en el archivo PDF](/pdf/es/python-net/page-stamps-in-the-pdf-file/) - agregar sellos de página para superponer páginas completas o secciones, útil para marcas de agua, versionado de documentos o agregar fondos personalizados a archivos PDF. +- [Agregar sellos de número de página en el archivo PDF](/pdf/es/python-net/add-page-number/) - agregar números de página a su documento PDF, personalizar su apariencia y controlar su ubicación. - \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-pages/stamping/add-page-number/_index.md b/es/python-net/advanced-operations/working-with-pages/stamping/add-page-number/_index.md new file mode 100644 index 000000000..e05b01e6f --- /dev/null +++ b/es/python-net/advanced-operations/working-with-pages/stamping/add-page-number/_index.md @@ -0,0 +1,118 @@ +--- +title: Agregar números de página a PDF en Python +linktitle: Agregar número de página +type: docs +weight: 30 +url: /es/python-net/add-page-number/ +description: Aprenda cómo agregar sellos de número de página a documentos PDF en Python. +lastmod: "2026-04-15" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo agregar número de página a PDF usando Python +Abstract: Este artículo analiza la importancia de agregar números de página a los documentos para una navegación más fácil e introduce la biblioteca Aspose.PDF for Python via .NET como una herramienta para lograr esto en archivos PDF. La biblioteca utiliza la clase PageNumberStamp, que ofrece propiedades para personalizar el sello de número de página, incluyendo formato, márgenes, alineaciones y número inicial. El proceso implica crear un objeto Document y un objeto PageNumberStamp, configurar las propiedades deseadas y aplicar el sello a las páginas PDF usando el método add_stamp(). El artículo proporciona un ejemplo de código Python que demuestra cómo configurar y aplicar sellos de número de página con atributos de fuente personalizables. +--- + +Todos los documentos deben tener números de página. El número de página facilita al lector localizar diferentes partes del documento. + +**Aspose.PDF for Python via .NET** permite agregar números de página con [PageNumberStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagenumberstamp/). + +## Agregar sello de número de página a un PDF + +Agregar sellos de número de página dinámicos a un PDF [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) usando Aspose.PDF for Python. El [`PageNumberStamp`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagenumberstamp/) objeto le permite mostrar automáticamente el número de página actual junto con el número total de páginas. El ejemplo muestra cómo crear un sello de número de página, personalizar su apariencia (fuente, tamaño, estilo, color, alineación y márgenes) usando [`TextState`](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstate/), y aplicarlo a un específico [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) en el PDF mediante el [`Page.add_stamp()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods) método. Los valores de alineación provienen de la [`HorizontalAlignment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/horizontalalignment/) enum, y color/fuente/estilo están disponibles a través de [`Color`](https://reference.aspose.com/pdf/python-net/aspose.pdf/color/) y [`FontStyles`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/fontstyles/) (fuentes descubiertas a través de [`FontRepository.find_font()`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/fontrepository/#methods)). Esta funcionalidad es útil para generar documentos profesionales numerados y automatizar la paginación en flujos de trabajo PDF. + +1. Abra el documento PDF. +1. Crear un sello de número de página. +1. Establecer propiedades del sello. +1. Personalizar el estilo del texto. +1. Aplicar el sello a una página. +1. Guardar el PDF modificado. + +```python +import sys +import aspose.pdf as ap +from os import path + +def add_page_num_stamp(input_file_name, output_file_name): + # Open document + document = ap.Document(input_file_name) + + # Create page number stamp + page_number_stamp = ap.PageNumberStamp() + # Whether the stamp is background + page_number_stamp.background = False + page_number_stamp.format = "Page # of " + str(len(document.pages)) + page_number_stamp.bottom_margin = 10 + page_number_stamp.horizontal_alignment = ap.HorizontalAlignment.CENTER + page_number_stamp.starting_number = 1 + # Set text properties + page_number_stamp.text_state.font = ap.text.FontRepository.find_font("Arial") + page_number_stamp.text_state.font_size = 14.0 + page_number_stamp.text_state.font_style = ( + ap.text.FontStyles.BOLD | ap.text.FontStyles.ITALIC + ) + page_number_stamp.text_state.foreground_color = ap.Color.blue_violet + + # Add stamp to particular page + document.pages[1].add_stamp(page_number_stamp) + + # Save output document + document.save(output_file_name) +``` + +## Agregar números de página en números romanos a un PDF + +Agregar números de página en formato de números romanos a todas las páginas de un documento PDF. Los números de página se añaden como sellos usando [`PageNumberStamp`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagenumberstamp/), con fuente, tamaño, estilo, color y alineación personalizables. Use el [`NumberingStyle`](https://reference.aspose.com/pdf/python-net/aspose.pdf/numberingstyle/) enum para elegir números romanos u otros esquemas de numeración. La numeración también puede comenzar desde cualquier valor especificado. + +1. Abra el documento PDF. +1. Crear un sello de número de página. +1. Configura las propiedades del sello. +1. Establece la apariencia del texto. +1. Aplica el sello a todas las páginas. +1. Guardar el PDF modificado. + +```python +import sys +import aspose.pdf as ap +from os import path + +def add_page_num_stamp_roman(input_file_name, output_file_name): + # Open document + document = ap.Document(input_file_name) + + # Create page number stamp + page_number_stamp = ap.PageNumberStamp() + # Whether the stamp is background + page_number_stamp.background = False + page_number_stamp.bottom_margin = 10 + page_number_stamp.horizontal_alignment = ap.HorizontalAlignment.CENTER + page_number_stamp.starting_number = 42 + page_number_stamp.numbering_style = ap.NumberingStyle.NUMERALS_ROMAN_UPPERCASE + + # Set text properties + page_number_stamp.text_state.font = ap.text.FontRepository.find_font("Arial") + page_number_stamp.text_state.font_size = 14.0 + page_number_stamp.text_state.font_style = ap.text.FontStyles.BOLD + page_number_stamp.text_state.foreground_color = ap.Color.blue_violet + + # Add stamp to particular page + for page in document.pages: + page.add_stamp(page_number_stamp) + + # Save output document + document.save(output_file_name) +``` + +## Ejemplo en vivo + +[Agregar números de página al PDF](https://products.aspose.app/pdf/page-number) es una aplicación web gratuita en línea que le permite investigar cómo funciona la funcionalidad de agregar números de página. + +[![Cómo agregar números de página en PDF usando Python](page_number.png)](https://products.aspose.app/pdf/page-number) + +## Temas relacionados con el estampado + +- [Estampar páginas PDF en Python](/pdf/es/python-net/stamping/) +- [Agregar sellos de página al PDF en Python](/pdf/es/python-net/page-stamps-in-the-pdf-file/) +- [Agregar sellos de imagen al PDF en Python](/pdf/es/python-net/image-stamps-in-pdf-page/) +- [Agregar sellos de texto al PDF en Python](/pdf/es/python-net/text-stamps-in-the-pdf-file/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-pages/stamping/add-page-stamp/_index.md b/es/python-net/advanced-operations/working-with-pages/stamping/add-page-stamp/_index.md new file mode 100644 index 000000000..2837beff4 --- /dev/null +++ b/es/python-net/advanced-operations/working-with-pages/stamping/add-page-stamp/_index.md @@ -0,0 +1,48 @@ +--- +title: Agregar sellos de página a PDF en Python +linktitle: Agregar sellos de página +type: docs +weight: 30 +url: /es/python-net/page-stamps-in-the-pdf-file/ +description: Aprende cómo agregar sellos de página PDF como superposiciones o fondos en Python. +lastmod: "2026-04-15" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo agregar sellos de página a PDF usando Python +Abstract: Este artículo explica cómo agregar un sello de página a un documento PDF usando Aspose.PDF for Python. Un sello de página le permite superponer o subyacer contenido —como logotipos, marcas de agua o anotaciones— a una página específica en un PDF. El ejemplo muestra cómo abrir un PDF existente, crear un objeto PdfPageStamp a partir de otra página PDF, configurarlo como sello de fondo y aplicarlo a una página en particular. El PDF sellado se guarda luego como un nuevo documento. Esta técnica es útil para la marca, el marcado de agua o para resaltar contenido a nivel de página en flujos de trabajo PDF automatizados. +--- + +Aspose.PDF for Python via .NET muestra cómo aplicar un sello de página (marca de agua o superposición) a una página específica en un PDF [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). El sello de página puede ser una página PDF existente utilizada como capa de fondo o de primer plano (ver [`PdfPageStamp`](https://reference.aspose.com/pdf/python-net/aspose.pdf.pdfpagestamp/)). Esto es útil para agregar logotipos, marcas de agua u otro contenido de página repetitivo. + +1. Abra el documento PDF usando `ap.Document()` (ver [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)). +1. Cree un `PdfPageStamp` objeto usando la página PDF o archivo a usar como sello (ver [`PdfPageStamp`](https://reference.aspose.com/pdf/python-net/aspose.pdf.pdfpagestamp/)). +1. Establezca las propiedades del sello, p. ej., `background = True` para colocarlo detrás del contenido. +1. Agregar el sello a una página específica usando `document.pages[page_number].add_stamp(page_stamp)` (ver [`Page.add_stamp()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods) y [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/)). +1. Guarda el PDF modificado en el archivo de salida especificado usando [`Document.save()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods). + +```python +import sys +import aspose.pdf as ap +from os import path + +def add_page_stamp(input_file_name, page_stamp_name, output_file_name): + # Open PDF document + document = ap.Document(input_file_name) + + page_stamp = ap.PdfPageStamp(page_stamp_name, 1) + page_stamp.background = True + + # Add stamp to particular page + document.pages[1].add_stamp(page_stamp) + + document.save(output_file_name) +``` + +## Temas relacionados con el estampado + +- [Estampar páginas PDF en Python](/pdf/es/python-net/stamping/) +- [Agregar números de página al PDF en Python](/pdf/es/python-net/add-page-number/) +- [Agregar sellos de imagen al PDF en Python](/pdf/es/python-net/image-stamps-in-pdf-page/) +- [Agregar sellos de texto al PDF en Python](/pdf/es/python-net/text-stamps-in-the-pdf-file/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-pages/stamping/image-stamps-in-pdf-page/_index.md b/es/python-net/advanced-operations/working-with-pages/stamping/image-stamps-in-pdf-page/_index.md index 34f541abb..f3b527a55 100644 --- a/es/python-net/advanced-operations/working-with-pages/stamping/image-stamps-in-pdf-page/_index.md +++ b/es/python-net/advanced-operations/working-with-pages/stamping/image-stamps-in-pdf-page/_index.md @@ -1,101 +1,38 @@ --- -title: Añadir sellos de imagen en PDF usando Python -linktitle: Sellos de imagen en archivo PDF +title: Agregar Image Stamps a PDF en Python +linktitle: Image stamps en archivo PDF type: docs weight: 10 url: /es/python-net/image-stamps-in-pdf-page/ -description: Añadir el sello de imagen en tu documento PDF usando la clase ImageStamp con la biblioteca Aspose.PDF para Python. -lastmod: "2023-04-17" +description: Aprende cómo agregar image stamps a páginas PDF en Python. +lastmod: "2026-04-15" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo agregar Image stamps en PDF usando Python +Abstract: Este artículo ofrece una guía completa sobre cómo agregar sellos de imagen a archivos PDF utilizando la biblioteca Aspose.PDF for Python via .NET. Detalla el uso de la clase `ImageStamp`, que permite la personalización de sellos basados en imágenes, incluyendo propiedades como altura, ancho, opacidad y rotación. El proceso implica crear un objeto `Document` y un objeto `ImageStamp` con las propiedades deseadas, y luego agregar el sello a una página específica del PDF mediante el método `add_stamp()`. El artículo incluye fragmentos de código Python que demuestran cómo aplicar un sello de imagen a un PDF y controlar su calidad usando la propiedad `quality`, que ajusta la calidad de la imagen en términos porcentuales. Además, el artículo explica cómo usar los sellos de imagen como fondos en cajas flotantes con la clase `FloatingBox`, proporcionando otro ejemplo de código para mostrar cómo se puede implementar. Esta guía sirve como un recurso útil para los desarrolladores que buscan mejorar los PDFs con sellos de imagen usando Aspose.PDF. --- - - - -## Añadir Sello de Imagen en Archivo PDF - -Puede utilizar la clase [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) para añadir un sello de imagen a un archivo PDF. La clase [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) proporciona las propiedades necesarias para crear un sello basado en una imagen, como altura, anchura, opacidad, etc. - -Para añadir un sello de imagen: - -1. Cree un objeto Document y un objeto ImageStamp utilizando las propiedades requeridas. -1. Llame al método [add_stamp()](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods) de la clase [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) para añadir el sello al PDF. - -El siguiente fragmento de código muestra cómo añadir un sello de imagen en el archivo PDF. -```python +## Agregar sello de imagen en archivo PDF + +Puedes usar el [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) clase para agregar un sello de imagen a un archivo PDF. El [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) La clase proporciona las propiedades necesarias para crear un sello basado en imagen, como altura, anchura, opacidad, etc. El sello puede ser posicionado, redimensionado, rotado y hecho parcialmente transparente, lo que permite marcas de agua, branding o anotaciones. - import aspose.pdf as ap +El siguiente fragmento de código muestra cómo agregar un sello de imagen en el archivo PDF. - # Abrir documento - document = ap.Document(input_pdf) +1. Cargue el PDF usando 'ap.Document()'. +1. Cree un sello de imagen con 'ImageStamp()'. +1. Configura las propiedades del sello. +1. Agregue el sello a la página de destino. +1. Guardar el PDF modificado. + +```python +import sys +import aspose.pdf as ap +from os import path - # Crear sello de imagen +def add_image_stamp(infile, input_image_file, outfile): + document = ap.Document(infile) image_stamp = ap.ImageStamp(input_image_file) image_stamp.background = True image_stamp.x_indent = 100 @@ -104,133 +41,85 @@ El siguiente fragmento de código muestra cómo añadir un sello de imagen en el image_stamp.width = 300 image_stamp.rotate = ap.Rotation.ON270 image_stamp.opacity = 0.5 - # Añadir sello a una página en particular - document.pages[1].add_stamp(image_stamp) - # Guardar documento de salida - document.save(output_pdf) + document.pages[1].add_stamp(image_stamp) + document.save(outfile) ``` +## Controlar la calidad de la imagen al añadir la marca -## Controlar la Calidad de la Imagen al Agregar un Sello +Al agregar una imagen como objeto de sello, puede controlar la calidad de la imagen. El [calidad](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/#properties) propiedad del [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) clase se utiliza para este propósito. Indica la calidad de la imagen en porcentajes (los valores válidos son 0..100). +Al establecer la propiedad quality, puedes reducir la resolución de la imagen para optimizar el tamaño del PDF o mantener una mayor fidelidad para una mejor claridad. -Al agregar una imagen como un objeto de sello, puedes controlar la calidad de la imagen. La propiedad [quality](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/#properties) de la clase [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) se utiliza para este propósito. Indica la calidad de la imagen en porcentajes (los valores válidos son 0..100). +1. Abra el documento PDF. +1. Crear una marca de imagen. +1. Establecer la calidad de la imagen. +1. Agregue el sello a la página de destino. +1. Guardar el PDF modificado. ```python +import sys +import aspose.pdf as ap +from os import path - import aspose.pdf as ap - - # Abrir documento - document = ap.Document(input_pdf) +def add_image_stamp_with_quality_control(infile, input_image_file, outfile): + document = ap.Document(infile) - # Crear sello de imagen - image_stamp = ap.ImageStamp(input_jpg) + image_stamp = ap.ImageStamp(input_image_file) image_stamp.quality = 10 - # Agregar sello a una página en particular - document.pages[1].add_stamp(image_stamp) - # Guardar documento de salida - document.save(output_pdf) + document.pages[1].add_stamp(image_stamp) + document.save(outfile) ``` -## Sello de Imagen como Fondo en un Cuadro Flotante +## Image Stamp como fondo en Floating Box -Aspose.PDF para Python API te permite agregar un sello de imagen como fondo en un cuadro flotante. - El atributo [background](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/#properties) de la clase [FloatingBox](https://reference.aspose.com/pdf/python-net/aspose.pdf/floatingbox/) se puede utilizar para establecer la imagen de fondo para un cuadro flotante como se muestra en el siguiente ejemplo de código. +Cree un [FloatingBox](https://reference.aspose.com/pdf/python-net/aspose.pdf/floatingbox/) en un PDF y aplicar una imagen como su fondo. También muestra cómo agregar texto, establecer bordes, color de fondo y posicionar la caja precisamente en la página. Esto es útil para crear contenido PDF visualmente rico, como llamados, banners o secciones resaltadas con texto sobre imágenes. -```python +1. Abra o cree un documento PDF. +1. Cree un objeto 'FloatingBox'. +1. Agregue contenido de texto al cuadro. +1. Establezca el borde y el color de fondo del cuadro. +1. Agregar una imagen de fondo. +1. Agregar el FloatingBox a la página. +1. Guarde el documento PDF. - import aspose.pdf as ap - - # Crear objeto Document - document = ap.Document() - # Añadir página al documento PDF - page = document.pages.add() - # Crear objeto FloatingBox +```python +import sys +import aspose.pdf as ap +from os import path + +def add_image_as_background_in_floating_box(infile, input_image_file, outfile): + document = ap.Document(infile) + page = document.pages[1] + # Create FloatingBox object box = ap.FloatingBox(200.0, 100.0) - # Establecer posición izquierda para FloatingBox + # Set left position for FloatingBox box.left = 40 - # Establecer posición superior para FloatingBox + # Set Top position for FloatingBox box.top = 80 - # Establecer la alineación horizontal para FloatingBox + # Set the Horizontal alignment for FloatingBox box.horizontal_alignment = ap.HorizontalAlignment.CENTER - # Añadir fragmento de texto a la colección de párrafos de FloatingBox - box.paragraphs.add(ap.text.TextFragment("texto principal")) - # Establecer borde para FloatingBox + # Add text fragment to paragraphs collection of FloatingBox + box.paragraphs.add(ap.text.TextFragment("Text in Floating Box")) + # Set border for FloatingBox box.border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.red) img = ap.Image() img.file = input_image_file - # Añadir imagen de fondo + # Add background image box.background_image = img - # Establecer color de fondo para FloatingBox + # Set background color for FloatingBox box.background_color = ap.Color.yellow - # Añadir FloatingBox a la colección de párrafos del objeto page + # Add FloatingBox to paragraphs collection of page object page.paragraphs.add(box) - # Guardar el documento PDF - document.save(output_pdf) + # Save the PDF document + document.save(outfile) ``` - \ No newline at end of file +## Temas relacionados con el estampado + +- [Estampar páginas PDF en Python](/pdf/es/python-net/stamping/) +- [Agregar sellos de página al PDF en Python](/pdf/es/python-net/page-stamps-in-the-pdf-file/) +- [Agregar sellos de texto al PDF en Python](/pdf/es/python-net/text-stamps-in-the-pdf-file/) +- [Agregar números de página al PDF en Python](/pdf/es/python-net/add-page-number/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-pages/stamping/text-stamps-in-pdf-file/_index.md b/es/python-net/advanced-operations/working-with-pages/stamping/text-stamps-in-pdf-file/_index.md index 41b4af1a0..e62a8abd7 100644 --- a/es/python-net/advanced-operations/working-with-pages/stamping/text-stamps-in-pdf-file/_index.md +++ b/es/python-net/advanced-operations/working-with-pages/stamping/text-stamps-in-pdf-file/_index.md @@ -1,259 +1,65 @@ --- -title: Agregar sellos de texto en PDF mediante Python +title: Agregar sellos de texto a PDF en Python linktitle: Sellos de texto en archivo PDF type: docs weight: 20 url: /es/python-net/text-stamps-in-the-pdf-file/ -description: Agregue un sello de texto a un documento PDF utilizando la clase TextStamp con la biblioteca Aspose.PDF para Python. -lastmod: "2023-04-17" +description: Aprenda cómo agregar sellos de texto a documentos PDF en Python. +lastmod: "2026-04-15" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo agregar sellos de texto en PDF usando Python +Abstract: Este artículo proporciona una guía completa sobre cómo agregar sellos de texto a archivos PDF usando la biblioteca Aspose.PDF for Python via .NET. Describe el uso de la clase `TextStamp` para crear sellos de texto personalizables con propiedades como tamaño de fuente, estilo, color y alineación. El artículo incluye fragmentos de código que demuestran cómo agregar un sello de texto simple, configurar la alineación del texto y aplicar modos de renderizado avanzados como texto con trazo rellenado. La primera sección explica la creación de un objeto `Document` y `TextStamp`, la configuración de las propiedades del texto y la adición del sello a una página específica. La segunda sección introduce la propiedad `text_alignment` para alinear el texto horizontal y verticalmente, proporcionando un ejemplo de código que centra el texto en una página PDF. La sección final discute los modos de renderizado, demostrando cómo agregar texto con trazo rellenado usando un objeto `TextState` para establecer el color del trazo y el modo de renderizado antes de vincularlo a un sello. Cada sección está acompañada de ejemplos prácticos para facilitar la comprensión e implementación. --- - +## Agregar sello de texto con Python -## Añadir Sello de Texto con Python +Puedes usar [TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/) clase para agregar una marca de texto en un archivo PDF. [TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/) la clase proporciona propiedades necesarias para crear una marca basada en texto, como tamaño de fuente, estilo de fuente y color de fuente, etc. Para agregar una marca de texto, necesitas crear un objeto Document y un objeto TextStamp usando las propiedades requeridas. Después de eso, puedes llamar [add_stamp()](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods) método de la Page para agregar la marca en el PDF. El siguiente fragmento de código muestra cómo agregar una marca de texto en el archivo PDF. Esto es útil para agregar anotaciones, marcas de agua o etiquetas a las páginas PDF. -Puede usar la clase [TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/) para agregar un sello de texto en un archivo PDF. La clase [TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/) proporciona las propiedades necesarias para crear un sello basado en texto como tamaño de fuente, estilo de fuente, y color de fuente, etc. Para agregar un sello de texto, necesita crear un objeto Document y un objeto TextStamp usando las propiedades requeridas. Después de eso, puede llamar al método [add_stamp()](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods) de la Página para agregar el sello en el PDF. El siguiente fragmento de código le muestra cómo agregar un sello de texto en el archivo PDF. +1. Abra el documento PDF. +1. Cree un objeto TextStamp. +1. Establezca el comportamiento de fondo del sello. +1. Posicione el sello en la página. +1. Gire el sello si es necesario. +1. Establezca las propiedades del texto. +1. Agregue el sello a una página. +1. Guarde el documento PDF modificado. ```python +import sys +import aspose.pdf as ap +from os import path - import aspose.pdf as ap +def add_text_stamp(input_file_name, output_file_name): + document = ap.Document(input_file_name) - # Abrir documento - document = ap.Document(input_pdf) - - # Crear sello de texto + # Create text stamp text_stamp = ap.TextStamp("Sample Stamp") - # Configurar si el sello es de fondo + # Set whether stamp is background text_stamp.background = True - # Establecer origen + # Set origin text_stamp.x_indent = 100 text_stamp.y_indent = 100 - # Rotar sello + # Rotate stamp text_stamp.rotate = ap.Rotation.ON90 - # Configurar propiedades de texto + # Set text properties text_stamp.text_state.font = ap.text.FontRepository.find_font("Arial") text_stamp.text_state.font_size = 14.0 - text_stamp.text_state.font_style = ap.text.FontStyles.BOLD - text_stamp.text_state.font_style = ap.text.FontStyles.ITALIC - text_stamp.text_state.foreground_color = ap.Color.aqua - # Agregar sello a una página en particular - document.pages[1].add_stamp(text_stamp) - - # Guardar documento de salida - document.save(output_pdf) -``` - - -## Definir alineación para el objeto TextStamp - -Agregar marcas de agua a documentos PDF es una de las características más demandadas y Aspose.PDF para Python es completamente capaz de agregar tanto marcas de agua de imagen como de texto. Tenemos una clase llamada [TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/) que proporciona la función de agregar sellos de texto sobre el archivo PDF. Recientemente ha habido un requisito para admitir la característica de especificar la alineación del texto al usar el objeto TextStamp. Así que, para cumplir con este requisito, hemos introducido la propiedad [text_alignment](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/#properties) en la clase [TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/). Usando esta propiedad, podemos especificar la alineación de texto [horizontal_alignment](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/#properties). - -Los siguientes fragmentos de código muestran un ejemplo de cómo cargar un documento PDF existente y agregar un TextStamp sobre él. - -```python - - import aspose.pdf as ap - - # Instanciar objeto Documento con archivo de entrada - doc = ap.Document(input_pdf) - # Instanciar objeto FormattedText con cadena de ejemplo - text = ap.facades.FormattedText("This") - # Agregar nueva línea de texto a FormattedText - text.add_new_line_text("es un ejemplo") - text.add_new_line_text("Centrado") - text.add_new_line_text("TextStamp") - text.add_new_line_text("Objeto") - # Crear objeto TextStamp usando FormattedText - stamp = ap.TextStamp(text) - # Especificar la alineación horizontal del sello de texto como centrado - stamp.horizontal_alignment = ap.HorizontalAlignment.CENTER - # Especificar la alineación vertical del sello de texto como centrado - stamp.vertical_alignment = ap.VerticalAlignment.CENTER - # Especificar la alineación horizontal del texto de TextStamp como centrado - stamp.text_alignment = ap.HorizontalAlignment.CENTER - # Establecer margen superior para el objeto sello - stamp.top_margin = 20 - # Agregar el objeto sello sobre la primera página del documento - doc.pages[1].add_stamp(stamp) - - # Guardar el documento actualizado - doc.save(output_pdf) -``` - - -## Rellenar Texto de Trazo como Sello en un Archivo PDF - -Hemos implementado la configuración del modo de renderizado para escenarios de adición y edición de texto. Para renderizar texto de trazo, cree un objeto TextState para transferir propiedades avanzadas. Establezca el color para el trazo. Después, configure el modo de renderizado de texto. El siguiente paso es vincular TextState y agregar el Sello. - -El siguiente fragmento de código demuestra cómo agregar Texto de Trazo de Relleno: - -```python - - import aspose.pdf as ap - - # Crear un objeto TextState para transferir propiedades avanzadas - ts = ap.text.TextState() - # Establecer color para el trazo - ts.stroking_color = ap.Color.gray - # Establecer modo de renderizado de texto - ts.rendering_mode = ap.text.TextRenderingMode.STROKE_TEXT - # Cargar un documento PDF de entrada - file_stamp = ap.facades.PdfFileStamp(ap.Document(input_pdf)) - - stamp = ap.facades.Stamp() - stamp.bind_logo( - ap.facades.FormattedText( - "PAGADO COMPLETAMENTE", - ap.facades.FontColor(100, 100, 100), - ap.facades.FontStyle.TIMES_ROMAN, - ap.facades.EncodingType.WINANSI, - True, - 78.0, - ) + text_stamp.text_state.font_style = ( + ap.text.FontStyles.BOLD | ap.text.FontStyles.ITALIC ) + text_stamp.text_state.foreground_color = ap.Color.dark_green + # Add stamp to particular page + document.pages[1].add_stamp(text_stamp) - # Vincular TextState - stamp.bind_text_state(ts) - # Establecer origen X,Y - stamp.set_origin(100, 100) - stamp.opacity = 5 - stamp.blending_space = ap.facades.BlendingColorSpace.DEVICE_RGB - stamp.rotation = 45.0 - stamp.is_background = False - # Agregar Sello - file_stamp.add_stamp(stamp) - file_stamp.save(output_pdf) - file_stamp.close() + document.save(output_file_name) ``` +## Temas relacionados con el estampado - \ No newline at end of file +- [Estampar páginas PDF en Python](/pdf/es/python-net/stamping/) +- [Agregar sellos de página al PDF en Python](/pdf/es/python-net/page-stamps-in-the-pdf-file/) +- [Agregar sellos de imagen al PDF en Python](/pdf/es/python-net/image-stamps-in-pdf-page/) +- [Agregar números de página al PDF en Python](/pdf/es/python-net/add-page-number/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-tables/_index.md b/es/python-net/advanced-operations/working-with-tables/_index.md index adff56ece..b814834a0 100644 --- a/es/python-net/advanced-operations/working-with-tables/_index.md +++ b/es/python-net/advanced-operations/working-with-tables/_index.md @@ -1,152 +1,29 @@ --- -title: Trabajando con Tablas en PDF usando Python -linktitle: Trabajando con Tablas +title: Trabajar con tablas en PDF usando Python +linktitle: Trabajando con tablas type: docs weight: 50 url: /es/python-net/working-with-tables/ -description: Esta sección describe cómo agregar y extraer una tabla, cómo manipular una tabla usando la biblioteca Python. -lastmod: "2023-09-17" +description: Aprenda cómo agregar, extraer, integrar, manipular y eliminar tablas en documentos PDF usando Python. +lastmod: "2026-05-05" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar, extraer, integrar y gestionar tablas PDF en Python +Abstract: Esta sección explica cómo trabajar con tablas en documentos PDF usando Aspose.PDF for Python via .NET. Aprenda cómo crear e insertar tablas, extraer datos tabulares, integrar tablas con fuentes de datos, modificar el contenido de las tablas y eliminar tablas de archivos PDF existentes en flujos de trabajo de Python. --- - +**Aspose.PDF for Python via .NET** proporciona herramientas completas para trabajar con tablas en archivos PDF. Puede crear y agregar tablas, controlar el diseño de la tabla y el flujo de página, extraer datos tabulares, actualizar tablas existentes y eliminar una o varias tablas de PDFs existentes. -**Aspose.PDF para Python a través de .NET** te permite trabajar con tablas en archivos PDF de manera avanzada. Esta herramienta perfecta ayuda a luchar contra la simplicidad de los PDF extrayendo tablas. Con el recurso de la biblioteca de Python puedes crear o agregar fácilmente una tabla en un documento PDF existente, determinar si la tabla se romperá en la página actual, extraer la tabla y eliminar tablas de los PDFs existentes. +Utilice esta sección cuando necesite crear informes basados en tablas, extraer datos estructurados de PDFs o actualizar contenido tabular en documentos existentes con Python. -Puedes hacer lo siguiente: +## Tareas de Tablas Cubiertas -- [Crear o Agregar Tabla en un Documento PDF existente](/pdf/es/python-net/add-table-in-existing-pdf-document/) - crea tu tabla en un archivo PDF fusionando las columnas o filas considerando bordes, márgenes y relleno. -- [Extraer una Tabla de un Documento PDF existente](/pdf/es/python-net/extract-table-from-existing-pdf-document/) - puedes extraer una tabla de un archivo PDF. -- [Manipular Tablas en un PDF existente](/pdf/es/python-net/manipulate-tables-in-existing-pdf/) - manipula tablas en tu PDF usando TableAbsorber. +Puede hacer lo siguiente: -- [Eliminar Tablas de un PDF existente](/pdf/es/python-net/remove-tables-from-existing-pdf/) - elimina una tabla o múltiples tablas de un documento PDF. - - \ No newline at end of file +- [Agregar tablas](/pdf/es/python-net/adding-tables/) - crear tablas en archivos PDF, incluidas filas/columnas combinadas, bordes, márgenes y relleno. +- [Extracción de Tablas](/pdf/es/python-net/extracting-table/) - extraer datos de tabla de archivos PDF existentes. +- [Integración de Tablas con Fuentes de Datos](/pdf/es/python-net/integrate-table/) - crear tablas a partir de bases de datos y datos de DataFrame de pandas en Python. +- [Manipulación de tablas](/pdf/es/python-net/manipulating-tables/) - inspeccionar y actualizar tablas existentes dentro de documentos PDF. +- [Eliminación de tablas](/pdf/es/python-net/removing-tables/) - eliminar una o varias tablas de documentos PDF. diff --git a/es/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/_index.md b/es/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/_index.md index 13072b72a..c1f46ffe6 100644 --- a/es/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/_index.md +++ b/es/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/_index.md @@ -1,173 +1,220 @@ --- -title: Crear o Agregar Tabla en PDF usando Python -linktitle: Crear o Agregar Tabla +title: Agregar tablas a PDF en Python +linktitle: Agregar tablas type: docs weight: 10 -url: /es/python-net/add-table-in-existing-pdf-document/ -description: Aspose.PDF para Python via .NET es una biblioteca utilizada para crear, leer y editar tablas PDF. Consulta otras funciones avanzadas en este tema. -lastmod: "2023-02-17" +url: /es/python-net/adding-tables/ +description: Aprenda a agregar y configurar tablas en documentos PDF existentes en Python. +lastmod: "2026-05-05" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregue y formatee tablas en documentos PDF con Python +Abstract: Este artículo explica cómo añadir y configurar tablas en documentos PDF usando Aspose.PDF for Python via .NET. Cubre la creación de tablas, bordes, márgenes, relleno, combinaciones de filas y columnas, el comportamiento AutoFit, el manejo del ancho de la tabla, la inserción de imágenes en celdas y el control de renderizado a través de páginas. --- - - - -## Creación de Tabla usando Python - -Las tablas son importantes cuando se trabaja con documentos PDF. Proporcionan grandes características para mostrar información de manera sistemática. El espacio de nombres Aspose.PDF contiene clases llamadas [Table](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/), [Cell](https://reference.aspose.com/pdf/python-net/aspose.pdf/cell/), y [Row](https://reference.aspose.com/pdf/python-net/aspose.pdf/row/) que proporcionan funcionalidad para crear tablas al generar documentos PDF desde cero. - -La tabla se puede crear creando un objeto de la Clase Table. -```python +Agregar tablas a documentos PDF existentes es un requisito común para la presentación de datos, contenido estructurado y generación de informes. **Aspose.PDF for Python via .NET** proporciona una API práctica para insertar y formatear tablas en PDFs existentes. + +Esta guía ofrece ejemplos paso a paso para la creación de tablas, el dimensionado de columnas, bordes, filas y celdas, y la guardado del documento modificado. También cubre opciones avanzadas como bordes de celdas, márgenes, relleno y configuraciones AutoFit para el dimensionado dinámico de tablas. + +Utilice esta página cuando necesite agregar nuevas tablas a PDFs existentes y controlar su comportamiento de diseño en Python. + +## Creando tablas básicas + +### Creando tabla + +Este ejemplo muestra cómo crear una Tabla en un documento PDF con bordes y varias filas. +1. Crear un nuevo documento PDF. +1. Agrega una página en blanco al documento. +1. Inicializar la tabla. +1. Establecer el borde general de la tabla. +1. Establece el borde para celdas individuales. +1. Agregar filas y celdas. +1. Inserte la tabla en la página. +1. Guarde el PDF en la ruta especificada. + +```python +import aspose.pdf as ap +from aspose.pdf import Color, HorizontalAlignment +from os import path +import sys + +def create_table(outfile: str) -> None: + # Create new PDF document + document = ap.Document() + page = document.pages.add() + # Initializes a new instance of the Table table = ap.Table() -``` + # Set the table border color as LightGray + table.border = ap.BorderInfo(ap.BorderSide.ALL, 5, ap.Color.light_gray) + # Set the border for table cells + table.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, 5, ap.Color.light_gray) + # Create a loop to add 10 rows + for row_count in range(10): + # Add row to table + row = table.rows.add() + # Add table cells + row.cells.add("Column (" + str(row_count) + ", 1)") + row.cells.add("Column (" + str(row_count) + ", 2)") + row.cells.add("Column (" + str(row_count) + ", 3)") + # Add table object to first page of input document + page.paragraphs.add(table) -### Añadiendo Tabla en Documento PDF Existente + # Save updated document containing table object + document.save(outfile) +``` -Para agregar una tabla a un archivo PDF existente con Aspose.PDF para Python a través de .NET, siga los siguientes pasos: +### Agregar imágenes a las celdas de la tabla -1. Cargue el archivo fuente. -1. Inicialice una tabla y configure sus columnas y filas. -1. Establezca la configuración de la tabla (hemos establecido los bordes). -1. Llene la tabla. -1. Agregue la tabla a una página. -1. Guarde el archivo. +Este fragmento de código muestra cómo insertar imágenes en celdas de tabla en un documento PDF. -Los siguientes fragmentos de código muestran cómo agregar texto en un archivo PDF existente. +1. Crear un nuevo documento PDF. +1. Inicializar la tabla. +1. Establecer anchos de columna en puntos. +1. Se agrega un fragmento de texto a la primera celda. +1. Se agrega una instancia de 'ap.Image()' a la segunda celda. +1. Establezca la ruta al archivo de imagen con 'img.file'. +1. Los 'img.fix_width' y 'img.fix_height' controlan el tamaño de la imagen dentro de la celda. +1. Inserte la tabla en la página PDF. +1. Guardar el PDF. ```python +import aspose.pdf as ap +from aspose.pdf import Color, HorizontalAlignment +from os import path +import sys + +def add_image(image: str, outfile: str) -> None: + # Instantiate Document object + document = ap.Document() + page = document.pages.add() + # Instantiate a table object + table = ap.Table() + # Set width for table cells + table.column_widths = "200 100" + + # Create row object and add it to table instance + row = table.rows.add() + # Create cell object and add it to row instance + cell = row.cells.add() + # Add textfragment to paragraphs collection of cell object + cell.paragraphs.add(ap.text.TextFragment(image)) + # Create an image instance + img = ap.Image() + # Set image type as SVG + # Path for source file + img.file = image + # Set width for image instance + img.fix_width = 50 + # Set height for image instance + img.fix_height = 50 + # Add another cell to row object + cell = row.cells.add() + # Add SVG image to paragraphs collection of recently added cell instance + cell.paragraphs.add(img) - import aspose.pdf as ap + # Add table to paragraphs collection of page object + page.paragraphs.add(table) + # Save PDF file + document.save(outfile) +``` + +Puedes agregar imágenes SVG en celdas de tabla en un documento PDF: - # Cargar documento PDF fuente - doc = ap.Document(input_file) - # Inicializa una nueva instancia de la Tabla +```python +import aspose.pdf as ap +from aspose.pdf import Color, HorizontalAlignment +from os import path +import sys + +def add_svg_image(images: list[str], outfile: str) -> None: + # Instantiate Document object + document = ap.Document() + page = document.pages.add() + # Instantiate a table object table = ap.Table() - # Establecer el color del borde de la tabla como LightGray - table.border = ap.BorderInfo(ap.BorderSide.ALL, 5, ap.Color.from_rgb(apd.Color.light_gray)) - # Establecer el borde para las celdas de la tabla - table.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, 5, ap.Color.from_rgb(apd.Color.light_gray)) - # Crear un bucle para agregar 10 filas - for row_count in range(0, 10): - # Agregar fila a la tabla + # Set width for table cells + table.column_widths = "200 100" + for image in images: + # Create row object and add it to table instance row = table.rows.add() - # Agregar celdas a la tabla - row.cells.add("Columna (" + str(row_count) + ", 1)") - row.cells.add("Columna (" + str(row_count) + ", 2)") - row.cells.add("Columna (" + str(row_count) + ", 3)") - # Agregar objeto tabla a la primera página del documento de entrada - doc.pages[1].paragraphs.add(table) - # Guardar documento actualizado que contiene el objeto tabla - doc.save(output_file) + # Create cell object and add it to row instance + cell = row.cells.add() + # Add textfragment to paragraphs collection of cell object + cell.paragraphs.add(ap.text.TextFragment(image)) + # Create an image instance + img = ap.Image() + # Set image type as SVG + img.file_type = ap.ImageFileType.SVG + # Path for source file + img.file = image + # Set width for image instance + img.fix_width = 50 + # Set height for image instance + img.fix_height = 50 + # Add another cell to row object + cell = row.cells.add() + # Add SVG image to paragraphs collection of recently added cell instance + cell.paragraphs.add(img) + + # Add table to paragraphs collection of page object + page.paragraphs.add(table) + # Save PDF file + document.save(outfile) ``` ### ColSpan y RowSpan en Tablas -Aspose.PDF para Python a través de .NET proporciona la propiedad [col_span](https://reference.aspose.com/pdf/python-net/aspose.pdf/cell/#properties) para fusionar las columnas en una tabla y la propiedad [row_span](https://reference.aspose.com/pdf/python-net/aspose.pdf/cell/#properties) para fusionar las filas. +Este ejemplo muestra cómo fusionar celdas de tabla vertical y horizontalmente para crear diseños de tabla complejos. - -Usamos la propiedad `col_span` o `row_span` en el objeto `Cell` que crea la celda de la tabla. Después de aplicar las propiedades requeridas, la celda creada se puede agregar a la tabla. +1. Establecer el borde general de la tabla. +1. Establecer los bordes predeterminados de la celda. +1. Combina dos celdas horizontalmente en una. +1. Combinar la celda verticalmente a lo largo de dos filas. +1. La fila 5 tiene en cuenta el rowspan omitiendo la columna fusionada. +1. Inserte la tabla en la página. +1. Guardar el PDF. ```python +import aspose.pdf as ap +from aspose.pdf import Color, HorizontalAlignment +from os import path +import sys - import aspose.pdf as ap +def add_rowspan_or_colspan(outfile: str) -> None: + # Create new PDF document + document = ap.Document() + page = document.pages.add() - # Inicializar el objeto Document llamando a su constructor vacío - pdf_document = ap.Document() - pdf_document.pages.add() - # Inicializa una nueva instancia de la Tabla + # Initializes a new instance of the Table table = ap.Table() - # Establecer el color del borde de la tabla como LightGray + # Set the table border color as LightGray table.border = ap.BorderInfo(ap.BorderSide.ALL, 0.5, ap.Color.black) - # Establecer el borde para las celdas de la tabla + # Set the border for table cells table.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, 0.5, ap.Color.black) - # Agregar la 1ra fila a la tabla + # Add 1st row to table row1 = table.rows.add() - for cellCount in range(1, 5): - # Agregar celdas a la tabla - row1.cells.add("Test 1" + str(cellCount)) + for cell_count in range(1, 5): + # Add table cells + row1.cells.add("Test 1" + str(cell_count)) - # Agregar la 2da fila a la tabla + # Add 2nd row to table row2 = table.rows.add() row2.cells.add("Test 2 1") cell = row2.cells.add("Test 2 2") cell.col_span = 2 row2.cells.add("Test 2 4") - # Agregar la 3ra fila a la tabla + # Add 3rd row to table row3 = table.rows.add() row3.cells.add("Test 3 1") row3.cells.add("Test 3 2") row3.cells.add("Test 3 3") row3.cells.add("Test 3 4") - # Agregar la 4ta fila a la tabla + # Add 4th row to table row4 = table.rows.add() row4.cells.add("Test 4 1") cell = row4.cells.add("Test 4 2") @@ -175,371 +222,620 @@ Usamos la propiedad `col_span` o `row_span` en el objeto `Cell` que crea la celd row4.cells.add("Test 4 3") row4.cells.add("Test 4 4") - # Agregar la 5ta fila a la tabla + # Add 5th row to table row5 = table.rows.add() row5.cells.add("Test 5 1") row5.cells.add("Test 5 3") row5.cells.add("Test 5 4") - # Agregar el objeto tabla a la primera página del documento de entrada - pdf_document.pages[1].paragraphs.add(table) - # Guardar el documento actualizado que contiene el objeto tabla - pdf_document.save(output_file) + # Add table object to first page of input document + page.paragraphs.add(table) + # Save updated document containing table object + document.save(outfile) ``` - -El resultado del código de ejecución a continuación es la tabla representada en la siguiente imagen: - ![Demostración de ColSpan y RowSpan](colspan_rowspan.png) -## Trabajando con Bordes, Márgenes y Relleno +### Aplicando bordes a tablas y celdas -Por favor, tenga en cuenta que también se admite la función para establecer el estilo de borde, márgenes y relleno de celdas para tablas. Antes de entrar en más detalles técnicos, es importante entender los conceptos de borde, márgenes y relleno que se presentan a continuación en un diagrama: +Este ejemplo muestra cómo establecer el relleno de celdas, los márgenes de la tabla y controlar el ajuste de línea del texto en las celdas de la tabla. -![Bordes, márgenes y relleno](set-border-style-margins-and-padding-of-table_1.png) - -En la figura anterior, puedes ver que los bordes de la tabla, fila y celda se superponen. Usando Aspose.PDF, una tabla puede tener márgenes y las celdas pueden tener relleno. Para establecer márgenes de celda, tenemos que establecer el relleno de celda. - -### Bordes - -Para establecer los bordes de los objetos [Table](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/), [Row](https://reference.aspose.com/pdf/python-net/aspose.pdf/row/) y [Cell](https://reference.aspose.com/pdf/python-net/aspose.pdf/cell/), use las propiedades Table.border, Row.border y Cell.border. - Los bordes de las celdas también se pueden establecer usando la propiedad [default_cell_border](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/#properties) de la clase [Table](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/) o Row. Todas las propiedades relacionadas con los bordes discutidas anteriormente se asignan a una instancia de la clase Row, que se crea llamando a su constructor. La clase Row tiene muchas sobrecargas que toman casi todos los parámetros necesarios para personalizar el borde. - -### Márgenes o Relleno - -El relleno de las celdas se puede gestionar utilizando la propiedad [default_cell_padding](https://reference.aspose.com/pdf/python-net/aspose.pdf/row/#properties) de la clase Table. Todas las propiedades relacionadas con el relleno se asignan a una instancia de la clase [MarginInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/margininfo/) que toma información sobre los parámetros `left`, `right`, `top` y `bottom` para crear márgenes personalizados. -En el siguiente ejemplo, el ancho del borde de la celda se establece en 0.1 puntos, el ancho del borde de la tabla se establece en 1 punto y el relleno de la celda se establece en 5 puntos. - -![Margen y Borde en Tabla PDF](margin-border.png) +1. Establezca los anchos de las columnas. +1. Definir los bordes de la tabla y de las celdas. +1. Establecer relleno dentro de las celdas para un espaciado consistente. +1. Aplica el relleno a todas las celdas por defecto. +1. Agregar texto y controlar el ajuste. +1. Agregar filas y celdas. +1. Guardar el PDF. ```python - - import aspose.pdf as ap - - # Instanciar el objeto Document llamando a su constructor vacío - doc = ap.Document() - page = doc.pages.add() - # Instanciar un objeto de tabla +import aspose.pdf as ap +from aspose.pdf import Color, HorizontalAlignment +from os import path +import sys + +def add_borders(outfile: str) -> None: + # Create new PDF document + document = ap.Document() + page = document.pages.add() + # Instantiate a table object tab1 = ap.Table() - # Agregar la tabla en la colección de párrafos de la sección deseada + # Add the table in paragraphs collection of the desired section page.paragraphs.add(tab1) - # Establecer los anchos de columna de la tabla + # Set with column widths of the table tab1.column_widths = "50 50 50" - # Establecer el borde de celda predeterminado usando el objeto BorderInfo + # Set default cell border using BorderInfo object tab1.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, 0.1) - # Establecer el borde de la tabla usando otro objeto BorderInfo personalizado + # Set table border using another customized BorderInfo object tab1.border = ap.BorderInfo(ap.BorderSide.ALL, 1) - # Crear un objeto MarginInfo y establecer sus márgenes izquierdo, inferior, derecho y superior + # Create MarginInfo object and set its left, bottom, right and top margins margin = ap.MarginInfo() margin.top = 5 margin.left = 5 margin.right = 5 margin.bottom = 5 - # Establecer el relleno de celda predeterminado en el objeto MarginInfo + # Set the default cell padding to the MarginInfo object tab1.default_cell_padding = margin - # Crear filas en la tabla y luego celdas en las filas + # Create rows in the table and then cells in the rows row1 = tab1.rows.add() row1.cells.add("col1") row1.cells.add("col2") row1.cells.add() - my_text = ap.text.TextFragment("col3 con una larga cadena de texto") - # Row1.Cells.Add("col3 con una larga cadena de texto para ser colocado dentro de la celda") - row1.cells[2].paragraphs.add(my_text) + text = ap.text.TextFragment("col3 with large text string") + row1.cells[2].paragraphs.add(text) row1.cells[2].is_word_wrapped = False row2 = tab1.rows.add() row2.cells.add("item1") row2.cells.add("item2") row2.cells.add("item3") - # Guardar el Pdf - doc.save(output_file) + # Save updated document containing table object + document.save(outfile) ``` +![Margen y borde en tabla PDF](margin-border.png) -Para crear una tabla con esquinas redondeadas, utiliza el valor [rounded_border_radius](https://reference.aspose.com/pdf/python-net/aspose.pdf/borderinfo/#properties) de la [clase BorderInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/borderinfo/) y establece el estilo de las esquinas de la tabla a redondeado. +## Diseño y dimensionamiento de la tabla -```python - - import aspose.pdf as ap - - tab1 = ap.Table() - graph = ap.GraphInfo() - graph.color = ap.Color.red - # Crear un objeto BorderInfo en blanco - b_info = ap.BorderInfo(ap.BorderSide.ALL, graph) - # Establecer el borde como un borde redondeado donde el radio del redondeo es 15 - b_info.rounded_border_radius = 15 - # Establecer el estilo de esquina de la tabla como Redondeado - tab1.corner_style = ap.BorderCornerStyle.ROUND - # Establecer la información del borde de la tabla - tab1.border = b_info -``` +### Ajuste automático de columnas y filas -## Aplicar Diferentes Configuraciones de AutoAjuste a una Tabla +Este fragmento de código muestra cómo ajustar automáticamente el ancho de las columnas de la tabla para que encajen en la página. +Tenga en cuenta que en el parámetro table.column_widths = "50 50 50" - son puntos. Pero también puede especificar centímetros (cm), pulgadas o %. -Al diseñar una tabla utilizando una herramienta visual como Microsoft Word, frecuentemente utilizarás una de las características de AutoAjuste para ajustar convenientemente el tamaño de la tabla al ancho deseado. - Por ejemplo, puedes emplear la opción "AUTO_FIT_TO_WINDOW" para ajustar el ancho de la tabla a la página o AUTO_FIT_TO_CONTENT. Por defecto, al usar Aspose.Pdf para crear una nueva tabla, utiliza el [column_adjustment](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/#properties) con un valor "Customized". En el siguiente fragmento de código, establecemos los parámetros del objeto [MarginInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/margininfo/) y los objetos [BorderInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/borderinfo/) en la tabla. Prueba el ejemplo y evalúa el resultado. +1. Establecer anchos de columna iniciales. +1. Ajusta automáticamente las columnas al ancho de la página. +1. Definir bordes de celda y tabla. +1. El 'table.default_cell_padding' usa 'MarginInfo()' para un espaciado consistente dentro de las celdas. +1. Agregar filas con 'table.rows.add()', y agregar celdas con 'row.cells.add()'. +1. Guardar el PDF. ```python +import aspose.pdf as ap +from aspose.pdf import Color, HorizontalAlignment +from os import path +import sys + +def auto_fit(outfile: str) -> None: + # Create new PDF document + document = ap.Document() + page = document.pages.add() + # Instantiate a table object + table = ap.Table() - import aspose.pdf as ap + page.paragraphs.add(table) + + table.column_widths = "50 50 50" + table.column_adjustment = ap.ColumnAdjustment.AUTO_FIT_TO_WINDOW + + table.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, 0.1) + + table.border = ap.BorderInfo(ap.BorderSide.ALL, 1) - # Instanciar el objeto Pdf llamando a su constructor vacío - doc = ap.Document() - # Crear la sección en el objeto Pdf - sec1 = doc.pages.add() - # Instanciar un objeto de tabla - tab1 = ap.Table() - # Agregar la tabla en la colección de párrafos de la sección deseada - sec1.paragraphs.add(tab1) - # Establecer anchos de columna de la tabla - tab1.column_widths = "50 50 50" - tab1.column_adjustment = ap.ColumnAdjustment.AUTO_FIT_TO_WINDOW - # Establecer el borde de celda predeterminado usando el objeto BorderInfo - tab1.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, 0.1) - # Establecer el borde de la tabla usando otro objeto BorderInfo personalizado - tab1.border = ap.BorderInfo(ap.BorderSide.ALL, 1) - # Crear un objeto MarginInfo y establecer sus márgenes izquierdo, inferior, derecho y superior margin = ap.MarginInfo() margin.top = 5 margin.left = 5 margin.right = 5 margin.bottom = 5 - # Establecer el relleno de celda predeterminado al objeto MarginInfo - tab1.default_cell_padding = margin - # Crear filas en la tabla y luego celdas en las filas - row1 = tab1.rows.add() + + table.default_cell_padding = margin + + row1 = table.rows.add() row1.cells.add("col1") row1.cells.add("col2") row1.cells.add("col3") - row2 = tab1.rows.add() + row2 = table.rows.add() row2.cells.add("item1") row2.cells.add("item2") row2.cells.add("item3") - # Guardar el documento actualizado que contiene el objeto tabla - doc.save(output_file) + + document.save(outfile) ``` -### Obtener Ancho de la Tabla +### Crear tablas PDF complejas con celdas combinadas y columnas repetidas -A veces, es necesario obtener el ancho de la tabla dinámicamente. La clase Aspose.PDF.Table tiene un método [get_width()](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/#methods) para este propósito. Por ejemplo, no has establecido el ancho de las columnas de la tabla explícitamente y has configurado [column_adjustment](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/#properties) a 'AUTO_FIT_TO_CONTENT'. En este caso, puedes obtener el ancho de la tabla de la siguiente manera. +Construye una tabla avanzada en un PDF usando Python y Aspose.PDF. Incluye celdas de encabezado combinadas, fondos de color, columnas repetidas y un gran conjunto de datos estructurado. La tabla está configurada para manejar rupturas verticales y diseños complejos para documentos tipo informe. ```python +import aspose.pdf as ap +from aspose.pdf import Color, HorizontalAlignment +from os import path +import sys - import aspose.pdf as ap +def add_table_hide_borders(outfile: str) -> None: + # Create PDF document + document = ap.Document() + page = document.pages.add() - # Crear un nuevo documento - doc = ap.Document() - # Agregar página en el documento - page = doc.pages.add() - # Inicializar nueva tabla + # Instantiate a table object that will be nested inside outerTable that will break inside the same page table = ap.Table() - table.column_adjustment = ap.ColumnAdjustment.AUTO_FIT_TO_CONTENT - # Agregar fila en la tabla + table.broken = ap.TableBroken.VERTICAL + table.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL) + table.repeating_columns_count = 2 + page.paragraphs.add(table) + + # Add header Row row = table.rows.add() - # Agregar celda en la tabla - cell = row.cells.add("Texto de la Celda 1") - cell = row.cells.add("Texto de la Celda 2") - # Obtener ancho de la tabla - print(table.get_width()) + cell = row.cells.add("header 1") + cell.col_span = 2 + cell.background_color = ap.Color.light_gray + row.cells.add("header 3") + + cell2 = row.cells.add("header 4") + cell2.col_span = 2 + cell2.background_color = ap.Color.light_blue + row.cells.add("header 6") + + cell3 = row.cells.add("header 7") + cell3.col_span = 2 + cell3.background_color = ap.Color.light_green + cell4 = row.cells.add("header 9") + + cell4.col_span = 3 + cell4.background_color = ap.Color.light_coral + row.cells.add("header 12") + row.cells.add("header 13") + row.cells.add("header 14") + row.cells.add("header 15") + row.cells.add("header 16") + row.cells.add("header 17") + + row_counter = 0 + while row_counter < 3: + # Create rows in the table and then cells in the rows + row1 = table.rows.add() + row1.cells.add("col " + str(row_counter) + ", 1") + row1.cells.add("col " + str(row_counter) + ", 2") + row1.cells.add("col " + str(row_counter) + ", 3") + row1.cells.add("col " + str(row_counter) + ", 4") + row1.cells.add("col " + str(row_counter) + ", 5") + row1.cells.add("col " + str(row_counter) + ", 6") + row1.cells.add("col " + str(row_counter) + ", 7") + row1.cells.add("col " + str(row_counter) + ", 8") + row1.cells.add("col " + str(row_counter) + ", 9") + row1.cells.add("col " + str(row_counter) + ", 10") + row1.cells.add("col " + str(row_counter) + ", 11") + row1.cells.add("col " + str(row_counter) + ", 12") + row1.cells.add("col " + str(row_counter) + ", 13") + row1.cells.add("col " + str(row_counter) + ", 14") + row1.cells.add("col " + str(row_counter) + ", 15") + row1.cells.add("col " + str(row_counter) + ", 16") + row1.cells.add("col " + str(row_counter) + ", 17") + row_counter += 1 + + document.save(outfile) ``` -## Agregar Imagen SVG a la Celda de la Tabla +![Bordes, márgenes y relleno](set-border-style-margins-and-padding-of-table_1.png) + +### Estilizando esquinas de tabla -Aspose.PDF para Python a través de .NET proporciona la capacidad de insertar celdas de tabla en un archivo PDF. - Al construir una tabla, puede incluir tanto texto como imágenes dentro de estas celdas. Además, la API ofrece la funcionalidad de transformar archivos SVG en formato PDF. Al aprovechar estas funcionalidades juntas, puede cargar una imagen SVG y colocarla dentro de una celda de la tabla. +Aspose.PDF for Python via .NET muestra cómo aplicar esquinas redondeadas a una tabla y personalizar el radio del borde. -El siguiente fragmento de código demuestra el proceso de crear un objeto de tabla e incrustar una imagen SVG dentro de una de sus celdas. +1. Crea una nueva instancia de tabla. +1. Inicializa un borde para todos los lados. +1. Establecer el radio de la esquina. +1. Aplicar el estilo de esquina redondeada. +1. Agregar filas y celdas. +1. Inserte la tabla en la página PDF con 'page.paragraphs.add(table)'. +1. Guarde el documento PDF. ```python +import aspose.pdf as ap +from aspose.pdf import Color, HorizontalAlignment +from os import path +import sys - import aspose.pdf as ap +def create_table_with_round_corner(outfile: str) -> None: + # Create new PDF document + document = ap.Document() + page = document.pages.add() - # Instanciar objeto Document - doc = ap.Document() - # Crear una instancia de imagen - img = ap.Image() - # Establecer tipo de imagen como SVG - img.file_type = ap.ImageFileType.SVG - # Ruta para el archivo fuente - img.file = DIR_INPUT_TABLE + "SVGToPDF.svg" - # Establecer ancho para la instancia de imagen - img.fix_width = 50 - # Establecer altura para la instancia de imagen - img.fix_height = 50 - # Crear instancia de tabla + # Create a table table = ap.Table() - # Establecer ancho para las celdas de la tabla - table.column_widths = "100 100" - # Crear objeto fila y añadirlo a la instancia de tabla - row = table.rows.add() - # Crear objeto celda y añadirlo a la instancia de fila - cell = row.cells.add() - # Añadir fragmento de texto a la colección de párrafos del objeto celda - cell.paragraphs.add(ap.text.TextFragment("Primera celda")) - # Añadir otra celda al objeto fila - cell = row.cells.add() - # Añadir imagen SVG a la colección de párrafos de la instancia de celda recientemente añadida - cell.paragraphs.add(img) - # Crear objeto página y añadirlo a la colección de páginas de la instancia de documento - page = doc.pages.add() - # Añadir tabla a la colección de párrafos del objeto página + + # Create a blank BorderInfo object + b_info = ap.BorderInfo(ap.BorderSide.ALL) + + # Set the border a rounded border where radius of round is 15 + b_info.rounded_border_radius = 15 + + # Set the table corner style as Round + table.corner_style = ap.BorderCornerStyle.ROUND + + # Set the table border information + table.border = b_info + + # Create a loop to add 10 rows + for row_count in range(0, 10): + # Add row to table + row = table.rows.add() + # Add table cells + row.cells.add("Column (" + str(row_count) + ", 1)") + row.cells.add("Column (" + str(row_count) + ", 2)") + row.cells.add("Column (" + str(row_count) + ", 3)") + + # Add table object to first page of input document page.paragraphs.add(table) - # Guardar archivo PDF - doc.save(output_file) + # Save updated document containing table object + document.save(outfile) ``` -## Insertar un salto de página entre las filas de la tabla +## Agregar contenido a tablas -Por defecto, cuando creas una tabla dentro de un archivo PDF, la tabla se extenderá a través de múltiples páginas si se extiende más allá del margen inferior de la tabla. Sin embargo, hay situaciones en las que necesitamos forzar saltos de página después de que un número específico de filas se haya agregado a la tabla. El siguiente fragmento de código describe el proceso de insertar un salto de página cuando se han incluido 10 filas en la tabla. +### Uso de fragmentos HTML en celdas + +Este ejemplo muestra cómo insertar contenido con formato HTML en celdas de tabla. + +1. Definir bordes de tabla y celda. +1. Agregar contenido HTML. +1. Agregar filas. Un bucle agrega varias filas con contenido con formato HTML en cada celda. +1. Inserte la tabla en la página PDF con 'page.paragraphs.add(table)'. +1. Guarde el documento PDF. + +```python +import aspose.pdf as ap +from aspose.pdf import Color, HorizontalAlignment +from os import path +import sys + +def add_html_fragments(outfile: str) -> None: + # Instantiate Document object + document = ap.Document() + page = document.pages.add() + # Instantiate a table object + table = ap.Table() + + # Set the table border color as LightGray + table.border = ap.BorderInfo(ap.BorderSide.ALL, 0.5, ap.Color.light_gray) + # Set the border for table cells + table.default_cell_border = ap.BorderInfo( + ap.BorderSide.ALL, 0.5, ap.Color.light_gray + ) + # Create a loop to add 10 rows + row_count = 1 + while row_count < 10: + # Add row to table + row = table.rows.add() + # Add table cells + cell = row.cells.add() + cell.paragraphs.add( + ap.HtmlFragment(f"Column ({row_count}, 1)") + ) + + cell = row.cells.add() + cell.paragraphs.add( + ap.HtmlFragment(f"Column ({row_count}, 2)") + ) + + cell = row.cells.add() + cell.paragraphs.add( + ap.HtmlFragment( + f"Column ({row_count}, 3)" + ) + ) + row_count += 1 + + # Add table object to first page of input document + page.paragraphs.add(table) + # Save updated document containing table object + document.save(outfile) +``` + +### Uso de fragmentos LaTeX en celdas + +Este ejemplo muestra cómo insertar contenido formateado en LaTeX en celdas de tabla para expresiones matemáticas o con estilo. + +1. Definir bordes de tabla y celda. +1. Agregar contenido LaTeX. +1. Agregar filas. Un bucle agrega varias filas con contenido formateado en LaTeX en cada celda. +1. Inserte la tabla en la página PDF con 'page.paragraphs.add(table)'. +1. Guarde el documento PDF. + +```python +import aspose.pdf as ap +from aspose.pdf import Color, HorizontalAlignment +from os import path +import sys + +def add_latex_fragments(outfile: str) -> None: + # Instantiate Document object + document = ap.Document() + page = document.pages.add() + # Instantiate a table object + table = ap.Table() + + # Set the table border color as LightGray + table.border = ap.BorderInfo(ap.BorderSide.ALL, 0.5, ap.Color.light_gray) + # Set the border for table cells + table.default_cell_border = ap.BorderInfo( + ap.BorderSide.ALL, 0.5, ap.Color.light_gray + ) + # Create a loop to add 10 rows + row_count = 1 + while row_count < 10: + # Add row to table + row = table.rows.add() + # Add table cells + cell = row.cells.add() + cell.paragraphs.add(ap.LatexFragment(f"Column $\\mathbf{{({row_count}, 1)}}$")) + + cell = row.cells.add() + cell.paragraphs.add( + ap.LatexFragment(f"Column $\\textcolor{{red}}{{({row_count}, 2)}}$") + ) + + cell = row.cells.add() + cell.paragraphs.add( + ap.LatexFragment(f"Column $\\underline{{({row_count}, 3)}}$") + ) + row_count += 1 + + # Add table object to first page of input document + page.paragraphs.add(table) + # Save updated document containing table object + document.save(outfile) +``` + +## Funciones avanzadas de tabla + +### Insertar saltos de página automáticos en una tabla PDF + +Crear una tabla grande en un PDF usando Python y Aspose.PDF, con saltos de página automáticos después de un número específico de filas. Construye una tabla de varias filas, aplica bordes y fuerza que filas seleccionadas comiencen en una nueva página para un mejor control del diseño. ```python +import aspose.pdf as ap +from aspose.pdf import Color, HorizontalAlignment +from os import path +import sys + +def insert_page_break(outfile: str) -> None: + # Create PDF document + document = ap.Document() + + # Add page + page = document.pages.add() + + # Create table instance + table = ap.Table() + + # Set border style for table + table.border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.red) - import aspose.pdf as ap - - # Instanciar la instancia del documento - doc = ap.Document() - # Añadir página a la colección de páginas del archivo PDF - doc.pages.add() - # Crear instancia de tabla - tab = ap.Table() - # Establecer estilo de borde para la tabla - tab.border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.red) - # Establecer estilo de borde predeterminado para la tabla con color de borde rojo - tab.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.red) - # Especificar el ancho de las columnas de la tabla - tab.column_widths = "100 100" - # Crear un bucle para añadir 200 filas a la tabla - for counter in range(0, 201): + # Set default border style for table with border color as Red + table.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.red) + + # Specify table columns width + table.column_widths = "100 100" + + # Create a loop to add 200 rows for table + for counter in range(201): row = ap.Row() - tab.rows.add(row) + table.rows.add(row) + cell1 = ap.Cell() - cell1.paragraphs.add(ap.text.TextFragment("Cell " + str(counter) + ", 0")) + cell1.paragraphs.add(ap.text.TextFragment(f"Cell {counter}, 0")) row.cells.add(cell1) + cell2 = ap.Cell() - cell2.paragraphs.add(ap.text.TextFragment("Cell " + str(counter) + ", 1")) + cell2.paragraphs.add(ap.text.TextFragment(f"Cell {counter}, 1")) row.cells.add(cell2) - # Cuando se añaden 10 filas, renderizar nueva fila en nueva página + + # When 10 rows are added, render new row in new page if counter % 10 == 0 and counter != 0: row.is_in_new_page = True - # Añadir tabla a la colección de párrafos del archivo PDF - doc.pages[1].paragraphs.add(tab) - # Guardar el documento PDF - doc.save(output_file) -``` + # Add table to paragraphs collection of PDF file + page.paragraphs.add(table) -## Representar una Tabla en una Nueva Página + # Save PDF document + document.save(outfile) +``` -Por defecto, los párrafos se añaden a la colección de Párrafos de un objeto Página. Sin embargo, es posible representar una tabla en una nueva página en lugar de directamente después del objeto de nivel de párrafo añadido anteriormente en la página. +### Filas de encabezado repetidas en varias páginas -### Ejemplo: Cómo Representar una Tabla en una Nueva Página usando Python +Este ejemplo muestra cómo crear una tabla que se extienda a varias páginas mientras se mantiene visible la fila de encabezado en cada página. -Para representar una tabla en una nueva página, use la propiedad [is_in_new_page](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/#properties) en la clase [BaseParagraph](https://reference.aspose.com/pdf/python-net/aspose.pdf/baseparagraph/). El siguiente fragmento de código muestra cómo hacerlo. +1. Inicializar la tabla. +1. Repetir filas de encabezado incluyendo fuente, tamaño y color. +1. Establecer anchos de columna y aplicar bordes a la tabla. +1. Agregar filas de encabezado. +1. Agrega muchas filas de datos para forzar que la tabla se extienda a varias páginas. +1. Inserte la tabla en la página PDF con 'page.paragraphs.add(table)'. +1. Guarde el documento PDF. ```python +import aspose.pdf as ap +from aspose.pdf import Color, HorizontalAlignment +from os import path +import sys + +def add_repeating_rows(outfile: str) -> None: + # Create PDF document + document = ap.Document() + page = document.pages.add() - import aspose.pdf as ap + # Instantiate a table object + table = ap.Table() + + # Set the table to break across pages + table.broken = ap.TableBroken.VERTICAL + + # Set number of repeating header rows + table.repeating_rows_count = 2 - doc = ap.Document() - page_info = doc.page_info - margin_info = page_info.margin + text_state = ap.text.TextState() + text_state.font_size = 12 + text_state.font = ap.text.FontRepository.find_font("TimesNewRoman") + text_state.foreground_color = ap.Color.red + table.repeating_rows_style = text_state - margin_info.left = 37 - margin_info.right = 37 - margin_info.top = 37 - margin_info.bottom = 37 + # Set column widths + table.column_widths = "100 100 100" + + # Set borders + table.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, 0.5, ap.Color.black) + table.border = ap.BorderInfo(ap.BorderSide.ALL, 1, ap.Color.black) - page_info.is_landscape = True + # Add header rows that will repeat on each page + header_row1 = table.rows.add() + header_row1.cells.add("Header 1-1") + header_row1.cells.add("Header 1-2") + header_row1.cells.add("Header 1-3") + # Set background color for header rows + for cell in header_row1.cells: + cell.background_color = ap.Color.light_gray + + header_row2 = table.rows.add() + header_row2.cells.add("Header 2-1") + header_row2.cells.add("Header 2-2") + header_row2.cells.add("Header 2-3") + + for cell in header_row2.cells: + cell.background_color = ap.Color.light_blue + + # Add many data rows to force table across multiple pages + for i in range(1, 101): + row = table.rows.add() + row.cells.add(f"Data {i}-1") + row.cells.add(f"Data {i}-2") + row.cells.add(f"Data {i}-3") + + # Add table to page + page.paragraphs.add(table) + + # Save document + document.save(outfile) +``` + +### Columnas repetidas + +La función 'add_repeating_columns' crea un documento PDF con una tabla que tiene columnas repetidas. Configura una tabla con bordes, añade encabezados, rellena filas de datos y guarda el archivo PDF generado en la ubicación especificada. Establecer esta propiedad hará que la tabla se rompa a la siguiente página por columnas y repita el número de columnas indicado al inicio de la siguiente página. + +1. Inicializa un nuevo documento PDF. +1. Agrega una página con dimensiones personalizadas. +1. Establecer estilo de borde de tabla. +1. Inicializar Tabla. +1. Agregar tabla a la página PDF. +1. Agregar fila de encabezado. +1. Agregar filas de datos. +1. Guardar documento PDF. + +```python +import aspose.pdf as ap +from aspose.pdf import Color, HorizontalAlignment +from os import path +import sys + +def add_repeating_columns(outfile: str) -> None: + # Create PDF document + document = ap.Document() + + # Add page + page = document.pages.add() + page.set_page_size(ap.PageSize.a5.height, ap.PageSize.a5.width) + + # Define border + border = ap.BorderInfo(ap.BorderSide.ALL, 0.5, ap.Color.light_gray) + + # Create table table = ap.Table() - table.column_widths = "50 100" - # Página añadida. - cur_page = doc.pages.add() - for i in range(1, 121): + table.broken = ap.TableBroken.VERTICAL_IN_SAME_PAGE + table.column_adjustment = ap.ColumnAdjustment.AUTO_FIT_TO_CONTENT + table.repeating_columns_count = 5 + table.border = border + table.default_cell_border = border + + # Add table to page + page.paragraphs.add(table) + + # Add header row + row = table.rows.add() + for i in range(1, 6): + cell = row.cells.add(f"header {i}") + cell.background_color = ap.Color.light_gray + + for i in range(6, 18): + row.cells.add(f"header {i}") + + # Add data rows + for row_counter in range(1, 6): row = table.rows.add() - row.fixed_row_height = 15 - cell1 = row.cells.add() - cell1.paragraphs.add(ap.text.TextFragment("Contenido 1")) - cell2 = row.cells.add() - cell2.paragraphs.add(ap.text.TextFragment("HHHHH")) - paragraphs = cur_page.paragraphs - paragraphs.add(table) - - table1 = ap.Table() - table1.column_widths = "100 100" - for i in range(1, 11): - row = table1.rows.add() - cell1 = row.cells.add() - cell1.paragraphs.add(ap.text.TextFragment("LAAAAAAA")) - cell2 = row.cells.add() - cell2.paragraphs.add(ap.text.TextFragment("LAAGGGGGG")) - table1.is_in_new_page = True - # Quiero mantener la tabla 1 en la siguiente página por favor... - paragraphs.add(table1) - doc.save(output_file) + for i in range(1, 6): + cell = row.cells.add(f"cell {row_counter},{i}") + cell.background_color = ap.Color.light_gray + for i in range(6, 18): + row.cells.add(f"cell {row_counter},{i}") + + # Save PDF document + document.save(outfile) +``` + +### Crear una tabla PDF con celdas de texto rotado + +Crea una tabla en un PDF usando Python y Aspose.PDF con texto rotado en diferentes ángulos dentro de cada celda. Es útil para encabezados verticales, diseños creativos, tablas compactas y formato personalizado de informes. + +```python +import aspose.pdf as ap +from aspose.pdf import Color, HorizontalAlignment +from os import path +import sys + +def rotated_text_table(outfile: str) -> None: + # Create PDF document + document = ap.Document() + + # Add page + page = document.pages.add() + + # Initializes a new instance of the Table + table = ap.Table() + table.border = ap.BorderInfo(ap.BorderSide.ALL, 0.5, Color.black) + table.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, 0.5, Color.black) + + # Add 1st row to table + row1 = table.rows.add() + row1.min_row_height = 200 + + for cell_count in range(4): + # Add table cells + cell = row1.cells.add() + + tf = ap.text.TextFragment(f"Cell 1 {cell_count - 1}") + tf.text_state.rotation = 90 * cell_count + tf.horizontal_alignment = HorizontalAlignment.CENTER + + cell.paragraphs.add(tf) + + # Add table object to first page of input document + page.paragraphs.add(table) + + # Save result + document.save(outfile) ``` +## Temas relacionados de la tabla - \ No newline at end of file +- [Trabajar con tablas en PDF usando Python](/pdf/es/python-net/working-with-tables/) +- [Extraer tablas de documentos PDF](/pdf/es/python-net/extracting-table/) +- [Integrar tablas PDF con fuentes de datos](/pdf/es/python-net/integrate-table/) +- [Manipular tablas en PDFs existentes](/pdf/es/python-net/manipulating-tables/) diff --git a/es/python-net/advanced-operations/working-with-tables/extract-table-from-existing-pdf-document/_index.md b/es/python-net/advanced-operations/working-with-tables/extract-table-from-existing-pdf-document/_index.md index ae5b60841..f3ea4dc7e 100644 --- a/es/python-net/advanced-operations/working-with-tables/extract-table-from-existing-pdf-document/_index.md +++ b/es/python-net/advanced-operations/working-with-tables/extract-table-from-existing-pdf-document/_index.md @@ -1,167 +1,64 @@ --- -title: Extraer Tabla de Documento PDF -linktitle: Extraer Tabla +title: Extraer tablas de PDF en Python +linktitle: Extraer tabla type: docs weight: 20 -url: /es/python-net/extract-table-from-existing-pdf-document/ -description: Aspose.PDF para Python a través de .NET hace posible realizar varias manipulaciones con las tablas contenidas en su documento pdf. -lastmod: "2023-02-17" +url: /es/python-net/extracting-table/ +description: Aprenda cómo extraer datos de tabla de documentos PDF existentes en Python. +lastmod: "2026-05-05" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Extraer datos de tabla de archivos PDF con Python +Abstract: Este artículo explica cómo extraer tablas de documentos PDF usando Aspose.PDF for Python via .NET. Muestra cómo usar `TableAbsorber` para detectar tablas por página, iterar filas y celdas, y recuperar el texto de las celdas para análisis y procesamiento de datos posteriores. --- - +## Extraer tabla de PDF -## Extraer Tabla de PDF +Extraer tablas de PDFs es útil para la generación de informes, la migración de datos y los flujos de trabajo de análisis. Con Aspose.PDF for Python via .NET, puedes detectar y leer el contenido de tablas de documentos PDF existentes de manera eficiente. -Extraer tablas de PDFs usando Python puede ser increíblemente útil para la extracción y el análisis de datos. Con la biblioteca Aspose.PDF para Python vía .NET, puedes trabajar eficientemente con tablas incrustadas en documentos PDF para diversas tareas relacionadas con datos. +Este fragmento de código abre un archivo PDF existente, escanea cada página en busca de tablas y extrae el contenido de texto de las celdas. Utiliza `TableAbsorber` para detectar tablas y luego iterar a través de filas y celdas para imprimir el texto extraído. -```python +1. Carga el PDF en un objeto ap.Document. +1. Recorre las páginas. +1. Crea un objeto TableAbsorber. +1. Itera a través de las tablas. +1. Iterar a través de filas y celdas. +1. Extraer e imprimir texto de las celdas. + +Este ejemplo lee un PDF, encuentra todas las tablas y muestra su contenido de celdas fila por fila. - import aspose.pdf as ap +```python +import aspose.pdf as ap +from os import path +import sys - # Cargar documento PDF de origen - pdf_document = ap.Document(input_file) - for page in pdf_document.pages: +def extract(infile: str) -> None: + """Extract and print all tables from a PDF file.""" + document = ap.Document(infile) + for page in document.pages: absorber = ap.text.TableAbsorber() absorber.visit(page) for table in absorber.table_list: + print("Table ----") for row in table.row_list: + print("Row:") + row_txt = "" for cell in row.cell_list: + cell_txt = "" text_fragment_collection = cell.text_fragments for fragment in text_fragment_collection: - txt = "" for seg in fragment.segments: - txt += seg.text - print(txt) - + cell_txt += seg.text + row_txt += " | " + row_txt += cell_txt + print(row_txt) ``` - \ No newline at end of file +## Temas relacionados de la tabla + +- [Trabajar con tablas en PDF usando Python](/pdf/es/python-net/working-with-tables/) +- [Agregar tablas al PDF usando Python](/pdf/es/python-net/adding-tables/) +- [Integrar tablas PDF con fuentes de datos](/pdf/es/python-net/integrate-table/) +- [Eliminar tablas de PDFs existentes](/pdf/es/python-net/removing-tables/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-tables/integrate-table-in-existing-pdf-document/_index.md b/es/python-net/advanced-operations/working-with-tables/integrate-table-in-existing-pdf-document/_index.md new file mode 100644 index 000000000..7a9a1c27f --- /dev/null +++ b/es/python-net/advanced-operations/working-with-tables/integrate-table-in-existing-pdf-document/_index.md @@ -0,0 +1,103 @@ +--- +title: Integrar tablas PDF con fuentes de datos en Python +linktitle: Integrar tabla +type: docs +weight: 30 +url: /es/python-net/integrate-table/ +description: Aprenda cómo integrar tablas PDF con fuentes de datos como bases de datos y DataFrames de pandas en Python. +lastmod: "2026-05-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Integrar tablas PDF con bases de datos y DataFrames usando Python +Abstract: Este artículo explica cómo integrar tablas PDF con fuentes de datos externas usando Aspose.PDF for Python via .NET. Aprenda cómo crear tablas PDF a partir de DataFrames de pandas y otras fuentes estructuradas, insertarlas en documentos y controlar el flujo de la tabla al renderizarse en varias páginas PDF en Python. +--- + +## Crear PDF a partir de DataFrame + +El `create_pdf_from_dataframe` función crea un nuevo PDF e inserta una tabla generada a partir de un DataFrame de pandas. Este enfoque es útil para flujos de trabajo de generación de informes donde sus datos ya existen en forma tabular. + +La función realiza los siguientes pasos: + +1. Crear un documento PDF vacío con `ap.Document()`. +1. Agregue una página al documento. +1. Convierta el DataFrame en una tabla Aspose.PDF llamando `create_table_from_dataframe(df, max_rows)`. +1. Agregar la tabla a la página con `page.paragraphs.add(table)`. +1. Guarda el PDF en la ruta de salida. + +```python +from os import path +import sys + +import pandas as pd +import aspose.pdf as ap +from config import set_license, initialize_data_dir + +def create_pdf_from_dataframe( + outfile: str, df: pd.DataFrame, max_rows: int = 20 +) -> None: + # Create new PDF document + document = ap.Document() + page = document.pages.add() + + table = create_table_from_dataframe(df, max_rows) + + # Add table object to first page of input document + page.paragraphs.add(table) + document.save(outfile) +``` + +## Crear tabla a partir de DataFrame + +El `create_table_from_dataframe` función convierte un DataFrame en un Aspose.PDF `Table` objeto que puedes añadir a cualquier página. + +Hace lo siguiente: + +1. Crear un vacío `ap.Table()` instancia. +1. Establecer bordes de tabla y celda para un formato consistente. +1. Agregar una fila de encabezado usando los nombres de columna del DataFrame. +1. Agregar filas de datos de `df.head(max_rows)`. +1. Devolver el objeto de tabla poblado. + +```python +from os import path +import sys + +import pandas as pd +import aspose.pdf as ap +from config import set_license, initialize_data_dir + +def create_table_from_dataframe(df: pd.DataFrame, max_rows: int = 20) -> ap.Table: + """Create an Aspose.PDF table from a pandas DataFrame.""" + # Initializes a new instance of the Table + table = ap.Table() + # Set the table border color as LightGray + table.border = ap.BorderInfo(ap.BorderSide.ALL, 1, ap.Color.light_gray) + # Set the border for table cells + table.default_cell_border = ap.BorderInfo( + ap.BorderSide.BOTTOM, 1, ap.Color.light_gray + ) + + # Add header row with column names + header_row = table.rows.add() + header_row.is_row_broken = False # Prevent header row from being split across pages + for column_name in df.columns: + cell = header_row.cells.add(str(column_name)) + cell.background_color = ap.Color.light_gray + + # Add data rows + for row_data in df.head(max_rows).itertuples(index=False): + row = table.rows.add() + for value in row_data: + row.cells.add(str(value)) + + return table +``` + +## Temas relacionados de la tabla + +- [Trabajar con tablas en PDF usando Python](/pdf/es/python-net/working-with-tables/) +- [Agregar tablas al PDF usando Python](/pdf/es/python-net/adding-tables/) +- [Extraer tablas de documentos PDF](/pdf/es/python-net/extracting-table/) +- [Manipular tablas en PDFs existentes](/pdf/es/python-net/manipulating-tables/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-tables/manipulate-tables-in-existing-pdf/_index.md b/es/python-net/advanced-operations/working-with-tables/manipulate-tables-in-existing-pdf/_index.md index 569e54eb3..be2cf55bf 100644 --- a/es/python-net/advanced-operations/working-with-tables/manipulate-tables-in-existing-pdf/_index.md +++ b/es/python-net/advanced-operations/working-with-tables/manipulate-tables-in-existing-pdf/_index.md @@ -1,325 +1,114 @@ --- -title: Manipular Tablas en PDF existente -linktitle: Manipular Tablas +title: Manipular tablas en documentos PDF existentes +linktitle: Manipular tablas type: docs weight: 40 -url: /es/python-net/manipulate-tables-in-existing-pdf/ -lastmod: "2023-02-17" +url: /es/python-net/manipulating-tables/ +description: Aprenda cómo inspeccionar y modificar tablas en documentos PDF existentes usando Python. +lastmod: "2026-05-05" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Inspeccionar y modificar tablas PDF existentes con Python +Abstract: Este artículo explica cómo manipular tablas ya presentes en documentos PDF usando Aspose.PDF for Python via .NET. Aprenda cómo localizar tablas con TableAbsorber, acceder a filas y celdas específicas, actualizar el contenido de texto de la tabla y guardar el PDF modificado en Python. --- - +## Manipular tablas en PDF existente -## Manipular tablas en un PDF existente +Aspose.PDF for Python via .NET le permite actualizar tablas que ya existen en un documento PDF. Puede usar el [TableAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/) clase para encontrar tablas en una página, acceder a filas y celdas, cambiar el contenido de texto, y guardar el archivo actualizado. -Una de las primeras características soportadas por Aspose.PDF para Python a través de .NET es su capacidad de trabajar con tablas y proporciona un gran soporte para agregar tablas en archivos PDF que se generan desde cero o en cualquier archivo PDF existente. En esta nueva versión, hemos implementado una nueva función de búsqueda y análisis de tablas simples que ya existen en la página de un documento PDF. Una nueva clase llamada [TableAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/) proporciona estas capacidades. El uso de TableAbsorber es muy similar a la clase existente [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber/). El siguiente fragmento de código muestra los pasos para actualizar contenidos en una celda de tabla en particular. +Utilice esta página cuando necesite actualizar el contenido de tablas existente en PDFs sin recrear el diseño completo del documento. -```python +## Buscar y Reemplazar Texto en Celdas de Tablas PDF - import aspose.pdf as ap +Este ejemplo encuentra la primera tabla en la página 1, accede a la primera celda, reemplaza su texto y guarda el PDF de salida. - # Cargar archivo PDF existente - pdf_document = ap.Document(input_file) - # Crear objeto TableAbsorber para encontrar tablas - absorber = ap.text.TableAbsorber() - # Visitar la primera página con el absorber - absorber.visit(pdf_document.pages[1]) - # Obtener acceso a la primera tabla en la página, su primera celda y fragmentos de texto en ella - fragment = absorber.table_list[0].row_list[0].cell_list[0].text_fragments[1] - # Cambiar el texto del primer fragmento de texto en la celda - fragment.text = "hola mundo" - pdf_document.save(output_file) -``` +1. Abra el PDF de entrada. +1. Cree un TableAbsorber y visite la página 1. +1. Asegúrese de que se detecte al menos una tabla. +1. Acceda a la primera celda de la primera fila de la primera tabla. +1. Asegúrese de que la celda contenga fragmentos de texto, luego actualice el primer fragmento. +1. Guardar el PDF modificado. +```python +import aspose.pdf as ap -## Reemplazar la tabla antigua con una nueva en un documento PDF +def replace_cell_text(infile: str, outfile: str) -> None: + """Replace text in the first cell of the first detected table.""" + # Open PDF document + document = ap.Document(infile) -En caso de que necesites encontrar una tabla en particular y reemplazarla con la deseada, puedes usar el método [replace()](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/#methods) de la clase [TableAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/) para hacerlo. El siguiente ejemplo demuestra la funcionalidad para reemplazar la tabla dentro de un documento PDF: + # Create TableAbsorber object to find tables + absorber = ap.text.TableAbsorber() -```python + # Visit first page with absorber + absorber.visit(document.pages[1]) - import aspose.pdf as ap + if len(absorber.table_list) == 0: + raise ValueError("No tables were found on page 1.") - # Cargar documento PDF existente - pdf_document = ap.Document(input_file) - # Crear objeto TableAbsorber para encontrar tablas - absorber = ap.text.TableAbsorber() - # Visitar la primera página con el absorber - absorber.visit(pdf_document.pages[1]) - # Obtener la primera tabla en la página - table = absorber.table_list[0] - # Crear nueva tabla - new_table = ap.Table() - new_table.column_widths = "100 100 100" - new_table.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, 1) + first_cell = absorber.table_list[0].row_list[0].cell_list[0] + if len(first_cell.text_fragments) == 0: + raise ValueError("The target cell has no text fragments.") - row = new_table.rows.add() - row.cells.add("Col 1") - row.cells.add("Col 2") - row.cells.add("Col 3") + # Change text of the first text fragment in the cell + first_cell.text_fragments[0].text = "New Value" - # Reemplazar la tabla con la nueva - absorber.replace(pdf_document.pages[1], table, new_table) - # Guardar documento - pdf_document.save(output_file) + # Save PDF document + document.save(outfile) ``` +## Reemplazar una tabla existente por una tabla nueva -## Cómo determinar si la tabla se romperá en la página actual +También puedes reemplazar una tabla detectada con una recién creada. Este enfoque es útil cuando tanto la estructura como el contenido deben cambiar. -Este código genera un documento PDF que contiene una tabla, calcula el espacio disponible en la página y verifica si agregar más filas a la tabla provocará un salto de página basado en las restricciones de espacio. El resultado se guarda en un archivo de salida. +El código a continuación abre un PDF, encuentra la primera tabla en la página 1, crea una tabla de reemplazo, intercambia la tabla antigua con la nueva y guarda el resultado. ```python +import aspose.pdf as ap - import aspose.pdf as ap +def replace_table(infile: str, outfile: str) -> None: + """Replace an entire table with a new one.""" + # Open PDF document + document = ap.Document(infile) - # Instanciar un objeto de la clase PDF - pdf = ap.Document() - # Agregar la sección a la colección de secciones del documento PDF - page = pdf.pages.add() - # Instanciar un objeto de tabla - table1 = ap.Table() - table1.margin.top = 300 - # Agregar la tabla en la colección de párrafos de la sección deseada - page.paragraphs.add(table1) - # Establecer los anchos de columna de la tabla - table1.column_widths = "100 100 100" - # Establecer el borde de celda predeterminado usando el objeto BorderInfo - table1.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, 0.1) - # Establecer el borde de la tabla usando otro objeto BorderInfo personalizado - table1.border = ap.BorderInfo(ap.BorderSide.ALL, 1) - # Crear objeto MarginInfo y establecer sus márgenes izquierdo, inferior, derecho y superior - margin = ap.MarginInfo() - margin.top = 5 - margin.left = 5 - margin.right = 5 - margin.bottom = 5 - # Establecer el relleno de celda predeterminado en el objeto MarginInfo - table1.default_cell_padding = margin - # Si incrementas el contador a 17, la tabla se romperá - # Porque no puede ser acomodada más en esta página - for row_counter in range(0, 17): - # Crear filas en la tabla y luego celdas en las filas - row1 = table1.rows.add() - row1.cells.add("col " + str(row_counter) + ", 1") - row1.cells.add("col " + str(row_counter) + ", 2") - row1.cells.add("col " + str(row_counter) + ", 3") - # Obtener la información de altura de la página - page_height = pdf.page_info.height - # Obtener la información de altura total del margen superior e inferior de la página, - # margen superior de la tabla y altura de la tabla. - total_objects_height = page.page_info.margin.top + page.page_info.margin.bottom + table1.margin.top + \ - table1.get_height(None) - # Mostrar información de altura de la página, altura de la tabla, margen superior de la tabla y - # información del margen superior e inferior de la página - print("Altura del documento PDF = " + str(pdf.page_info.height) + "\nInformación del margen superior = " + str(page.page_info.margin.top) - + "\nInformación del margen inferior = " + str(page.page_info.margin.bottom) + "\n\nInformación del margen superior de la tabla = " - + str(table1.margin.top) + "\nAltura promedio de fila = " + str(table1.rows[0].min_row_height) + " \nAltura de la tabla " - + str(table1.get_height(None)) + "\n ----------------------------------------" + "\nAltura total de la página =" - + str(page_height) + "\nAltura acumulada incluyendo la tabla =" + str(total_objects_height)) - # Verificar si al restar la suma del margen superior de la página + margen inferior de la página - # + margen superior de la tabla y altura de la tabla de la altura de la página es menor - # A 10 (una fila promedio puede ser mayor a 10) - if (page_height - total_objects_height) <= 10: - # Si el valor es menor a 10, entonces mostrar el mensaje. - # Que muestra que no se puede colocar otra fila y si agregamos una nueva - # Fila, la tabla se romperá. Depende del valor de la altura de la fila. - print("Altura de la página - Altura de los objetos < 10, por lo que la tabla se romperá") - # Guardar el documento PDF - pdf.save(output_file) -``` + # Create TableAbsorber object to find tables + absorber = ap.text.TableAbsorber() + # Visit first page with absorber + absorber.visit(document.pages[1]) -## Añadir Columna Repetida en la Tabla + if len(absorber.table_list) == 0: + raise ValueError("No tables were found on page 1.") -En la clase [Aspose.Pdf.Table](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/), puede establecer un [repeating_rows_count](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/#properties) que repetirá filas si la tabla es demasiado larga verticalmente y se desborda a la siguiente página. Sin embargo, en algunos casos, las tablas son demasiado anchas para caber en una sola página y necesitan continuar en la siguiente página. Para cumplir con el propósito, hemos implementado la propiedad [repeating_columns_count](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/#properties) en la clase [Aspose.Pdf.Table](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/). Establecer esta propiedad hará que la tabla se divida a la siguiente página en columnas y repita el número de columnas dado al inicio de la siguiente página. El siguiente fragmento de código muestra el uso de la propiedad [repeating_columns_count](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/#properties): + # Get first table on the page + old_table = absorber.table_list[0] -```python + # Create new table + new_table = ap.Table() + new_table.column_widths = "100 100 100" + new_table.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, 1.0) + + row = new_table.rows.add() + row.cells.add("Col 1") + row.cells.add("Col 2") + row.cells.add("Col 3") + row = new_table.rows.add() + row.cells.add("Col 12") + row.cells.add("Col 22") + row.cells.add("Col 32") - import aspose.pdf as ap + # Replace the old table with the new one + absorber.replace(document.pages[1], old_table, new_table) - # Crear un nuevo documento - doc = ap.Document() - page = doc.pages.add() - # Instanciar una tabla externa que ocupa toda la página - outer_table = ap.Table() - outer_table.column_widths = "100%" - outer_table.horizontal_alignment = ap.HorizontalAlignment.LEFT - # Instanciar un objeto de tabla que se anidará dentro de outerTable que se romperá dentro de la misma página - my_table = ap.Table() - my_table.broken = ap.TableBroken.VERTICAL_IN_SAME_PAGE - my_table.column_adjustment = ap.ColumnAdjustment.AUTO_FIT_TO_CONTENT - # Agregar outerTable a los párrafos de la página - # Agregar mi tabla a outerTable - page.paragraphs.add(outer_table) - body_row = outer_table.rows.add() - body_cell = body_row.cells.add() - body_cell.paragraphs.add(my_table) - my_table.repeating_columns_count = 5 - page.paragraphs.add(my_table) - # Agregar fila de encabezado - row = my_table.rows.add() - row.cells.add("encabezado 1") - row.cells.add("encabezado 2") - row.cells.add("encabezado 3") - row.cells.add("encabezado 4") - row.cells.add("encabezado 5") - row.cells.add("encabezado 6") - row.cells.add("encabezado 7") - row.cells.add("encabezado 11") - row.cells.add("encabezado 12") - row.cells.add("encabezado 13") - row.cells.add("encabezado 14") - row.cells.add("encabezado 15") - row.cells.add("encabezado 16") - row.cells.add("encabezado 17") - for row_counter in range(0, 6): - # Crear filas en la tabla y luego celdas en las filas - row1 = my_table.rows.add() - row1.cells.add("col " + str(row_counter) + ", 1") - row1.cells.add("col " + str(row_counter) + ", 2") - row1.cells.add("col " + str(row_counter) + ", 3") - row1.cells.add("col " + str(row_counter) + ", 4") - row1.cells.add("col " + str(row_counter) + ", 5") - row1.cells.add("col " + str(row_counter) + ", 6") - row1.cells.add("col " + str(row_counter) + ", 7") - row1.cells.add("col " + str(row_counter) + ", 11") - row1.cells.add("col " + str(row_counter) + ", 12") - row1.cells.add("col " + str(row_counter) + ", 13") - row1.cells.add("col " + str(row_counter) + ", 14") - row1.cells.add("col " + str(row_counter) + ", 15") - row1.cells.add("col " + str(row_counter) + ", 16") - row1.cells.add("col " + str(row_counter) + ", 17") - doc.save(output_file) + # Save PDF document + document.save(outfile) ``` +## Temas relacionados de la tabla - \ No newline at end of file +- [Trabajar con tablas en PDF usando Python](/pdf/es/python-net/working-with-tables/) +- [Agregar tablas al PDF usando Python](/pdf/es/python-net/adding-tables/) +- [Extraer tablas de documentos PDF](/pdf/es/python-net/extracting-table/) +- [Eliminar tablas de PDFs existentes](/pdf/es/python-net/removing-tables/) diff --git a/es/python-net/advanced-operations/working-with-tables/remove-tables-from-existing-pdf/_index.md b/es/python-net/advanced-operations/working-with-tables/remove-tables-from-existing-pdf/_index.md index 42518d976..01e1690f4 100644 --- a/es/python-net/advanced-operations/working-with-tables/remove-tables-from-existing-pdf/_index.md +++ b/es/python-net/advanced-operations/working-with-tables/remove-tables-from-existing-pdf/_index.md @@ -1,130 +1,75 @@ --- -title: Eliminar tablas de un PDF existente -linktitle: Eliminar Tablas +title: Eliminar tablas de documentos PDF existentes +linktitle: Eliminar tablas +description: Aprenda cómo eliminar una o más tablas de documentos PDF existentes en Python. +lastmod: "2026-05-05" type: docs weight: 50 -url: /es/python-net/remove-tables-from-existing-pdf/ -lastmod: "2023-02-17" +url: /es/python-net/removing-tables/ sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Eliminar una o varias tablas de archivos PDF con Python +Abstract: Este artículo explica cómo eliminar tablas de documentos PDF existentes usando Aspose.PDF for Python via .NET. Introduce `TableAbsorber` para localizar tablas y muestra cómo eliminar una sola tabla o eliminar todas las tablas detectadas de una página. --- - +## Eliminar tabla de documento PDF -{{% alert color="primary" %}} +Aspose.PDF for Python le permite eliminar una tabla de un PDF. Abre un PDF existente, detecta la primera tabla en la primera página con `TableAbsorber`, elimina esa tabla usando `remove()`, y guarda el PDF actualizado en un nuevo archivo. -Aspose.PDF para Python a través de .NET ofrece la capacidad de insertar/crear una tabla dentro de un documento PDF mientras se genera desde cero o también puede agregar el objeto de tabla en cualquier documento PDF existente. Sin embargo, puede tener un requisito de [Manipular tablas en PDF existente](https://docs.aspose.com/pdf/python-net/manipulate-tables-in-existing-pdf/) donde puede actualizar los contenidos en las celdas de tablas existentes. Sin embargo, puede encontrarse con un requisito para eliminar objetos de tabla de un documento PDF existente. - -{{% /alert %}} - -Para eliminar las tablas, necesitamos usar la clase [TableAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/) para obtener las tablas en un PDF existente y luego llamar a [remove()](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/#methods). - -## Eliminar tabla del documento PDF - -Hemos añadido una nueva función, es decir, - [remove()](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/#methods) a la clase existente [TableAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/) para eliminar la tabla del documento PDF. Una vez que el absorbedor encuentra tablas en la página con éxito, se vuelve capaz de eliminarlas. Por favor, revise el siguiente fragmento de código que muestra cómo eliminar una tabla de un documento PDF: +Utilice esta página cuando necesite limpiar PDFs con muchas tablas, eliminar contenido tabular desactualizado o simplificar documentos antes de redistribuirlos. ```python +import aspose.pdf as ap +from os import path +import sys - import aspose.pdf as ap +def remove_one_table(infile: str, outfile: str) -> None: + # Load existing PDF document + document = ap.Document(infile) - # Cargar documento PDF existente - pdf_document = ap.Document(input_file) - # Crear objeto TableAbsorber para encontrar tablas + # Create TableAbsorber object to find tables absorber = ap.text.TableAbsorber() - # Visitar la primera página con el absorbedor - absorber.visit(pdf_document.pages[1]) - # Obtener la primera tabla en la página + # Visit first page with absorber + absorber.visit(document.pages[1]) + # Get first table on the page table = absorber.table_list[0] - # Eliminar la tabla + # Remove the table absorber.remove(table) - # Guardar PDF - pdf_document.save(output_file) + # Save PDF + document.save(outfile) ``` -## Eliminar Múltiples Tablas de un Documento PDF +## Eliminar todas las tablas del documento PDF -A veces, un documento PDF puede contener más de una tabla y puede surgir la necesidad de eliminar múltiples tablas de él. Para eliminar múltiples tablas de un documento PDF, utilice el siguiente fragmento de código: +Con nuestra biblioteca, puedes eliminar todas las tablas de una página específica en un PDF. El código abre un PDF existente, detecta todas las tablas en la segunda página con TableAbsorber, recorre las tablas detectadas, elimina cada una y luego guarda el PDF modificado en un nuevo archivo. Es útil cuando necesitas eliminar en bloque las tablas de una página mientras dejas intacto el resto del contenido del PDF. ```python +import aspose.pdf as ap +from os import path +import sys - import aspose.pdf as ap +def remove_all_tables(infile: str, outfile: str) -> None: + # Load existing PDF document + document = ap.Document(infile) - # Cargar documento PDF existente - pdf_document = ap.Document(input_file) - # Crear objeto TableAbsorber para encontrar tablas + # Create TableAbsorber object to find tables absorber = ap.text.TableAbsorber() - # Visitar la segunda página con el absorbedor - absorber.visit(pdf_document.pages[1]) - # Obtener copia de la colección de tablas - tables = absorber.table_list - # Recorrer la copia de la colección y eliminar tablas + # Visit first page with absorber + absorber.visit(document.pages[1]) + # Loop through the copy of collection and removing tables + tables = list(absorber.table_list) for table in tables: absorber.remove(table) - # Guardar documento - pdf_document.save(output_file) \ No newline at end of file + + # Save document + document.save(outfile) +``` + +## Temas relacionados de la tabla + +- [Trabajar con tablas en PDF usando Python](/pdf/es/python-net/working-with-tables/) +- [Agregar tablas al PDF usando Python](/pdf/es/python-net/adding-tables/) +- [Extraer tablas de documentos PDF](/pdf/es/python-net/extracting-table/) +- [Manipular tablas en PDFs existentes](/pdf/es/python-net/manipulating-tables/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-text/_index.md b/es/python-net/advanced-operations/working-with-text/_index.md index cfc327b46..8a4204c93 100644 --- a/es/python-net/advanced-operations/working-with-text/_index.md +++ b/es/python-net/advanced-operations/working-with-text/_index.md @@ -1,91 +1,31 @@ --- -title: Trabajando con Texto en PDF usando Python -linktitle: Trabajando con Texto +title: Trabajar con texto en PDF usando Python +linktitle: Trabajando con texto type: docs weight: 30 url: /es/python-net/working-with-text/ -description: Esta sección explica varias técnicas de manejo de texto. Aprenda cómo añadir, reemplazar, rotar, buscar texto usando Aspose.PDF para Python. -lastmod: "2024-01-17" +description: Aprenda cómo agregar, buscar, formatear, reemplazar, rotar y examinar texto en documentos PDF usando Python. +lastmod: "2026-05-05" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar, formatear, buscar, reemplazar y rotar texto PDF en Python +Abstract: Esta sección explica cómo trabajar con texto en documentos PDF usando Aspose.PDF for Python via .NET. Aprenda cómo agregar y formatear texto, crear tooltips y diseños de texto flotante, buscar y extraer texto, reemplazar texto existente y rotar elementos de texto en flujos de trabajo de Python. --- - + A veces todos necesitamos agregar texto a un archivo PDF. Por ejemplo, puede que desee colocar una traducción debajo del texto principal, agregar una leyenda junto a una imagen, o rellenar un formulario de solicitud. También es útil cuando todos los elementos de texto pueden formatearse en el estilo que prefiera. Las operaciones de texto comunes incluyen agregar texto, formatear texto, reemplazar texto y rotar texto en un documento. **Aspose.PDF for Python via .NET** ofrece todo lo que necesita para trabajar con contenido de texto en PDF. -Todos necesitamos a veces agregar texto al archivo PDF. Por ejemplo, cuando deseas agregar una traducción debajo del texto principal, colocar un pie de foto junto a una imagen o simplemente completar un formulario de solicitud. También es útil si todos los elementos de texto pueden ser formateados en el estilo deseado. Las manipulaciones de texto más populares en tu archivo PDF son: agregar texto al PDF, formatear texto dentro del archivo PDF, reemplazar y rotar texto en tu documento. **Aspose.PDF para Python a través de .NET** es la mejor solución que tiene todo lo que necesitas para interactuar con el contenido PDF. +Utilice esta sección cuando necesite generar, formatear, inspeccionar o modificar texto directamente dentro de páginas PDF en aplicaciones Python. -Puedes hacer lo siguiente: +## Tareas de texto cubiertas -- [Agregar Texto al archivo PDF](/pdf/es/python-net/add-text-to-pdf-file/) - agrega texto a tu PDF, usa fuentes de flujo y archivos, agrega una cadena HTML, agrega un hipervínculo, etc. -- [Tooltip PDF](/pdf/es/python-net/pdf-tooltip/) - puedes agregar un tooltip al texto buscado añadiendo un botón invisible usando Python. -- [Formato de Texto dentro de PDF](/pdf/es/python-net/text-formatting-inside-pdf/) - Muchas características puedes agregar a tu documento al formatear el texto dentro de él. - Agrega sangría de línea, añade borde de texto, subraya texto, añade salto de línea con la biblioteca Aspose.PDF. -- [Reemplazar Texto en PDF](/pdf/es/python-net/replace-text-in-pdf/) - para reemplazar texto en todas las páginas de un documento PDF. Primero necesitas usar TextFragmentAbsorber. -- [Rotar Texto Dentro de PDF](/pdf/es/python-net/rotate-text-inside-pdf/) - rota texto dentro del PDF usando la propiedad de rotación de la Clase TextFragment. -- [Buscar y Obtener Texto de las Páginas de un Documento PDF](/pdf/es/python-net/search-and-get-text-from-pdf/) - puedes usar la clase TextFragmentAbsorber para buscar y obtener texto de las páginas. -- [Determinar Salto de Línea](/pdf/es/python-net/determine-line-break/) - este tema explica cómo rastrear el salto de línea de fragmentos de texto multi-línea. \ No newline at end of file + Puede hacer lo siguiente: + +- [Agregar texto a archivo PDF](/pdf/es/python-net/add-text-to-pdf-file/) - agregar texto a su PDF, usar fuentes desde stream y archivos, agregar una cadena HTML, agregar un hipervínculo, etc. +- [Información sobre herramientas PDF](/pdf/es/python-net/pdf-tooltip/) - puede agregar una información sobre herramientas al texto buscado añadiendo un botón invisible usando Python. +- [Usando FloatingBox](/pdf/es/python-net/floating-box/) - colocar texto con estilo y otro contenido dentro de un contenedor flotante. +- [Reemplazar texto en PDF](/pdf/es/python-net/replace-text-in-pdf/) - reemplazar o eliminar texto existente en un archivo PDF. +- [Rotar texto dentro del PDF](/pdf/es/python-net/rotate-text-inside-pdf/) - rotar fragmentos de texto y párrafos dentro de un PDF. +- [Buscar y obtener texto del PDF](/pdf/es/python-net/search-and-get-text-from-pdf/) - buscar texto e inspeccionar los detalles del texto extraído de las páginas. +- [Formato de texto dentro de PDF](/pdf/es/python-net/text-formatting-inside-pdf/) - controlar el espaciado de líneas, bordes, sangría y estilo de texto. diff --git a/es/python-net/advanced-operations/working-with-text/add-text-to-a-pdf-file/_index.md b/es/python-net/advanced-operations/working-with-text/add-text-to-a-pdf-file/_index.md deleted file mode 100644 index 7a82e8de6..000000000 --- a/es/python-net/advanced-operations/working-with-text/add-text-to-a-pdf-file/_index.md +++ /dev/null @@ -1,843 +0,0 @@ ---- -title: Añadir Texto a PDF usando Python -linktitle: Añadir Texto a PDF -type: docs -weight: 10 -url: /es/python-net/add-text-to-pdf-file/ -description: Este artículo describe varios aspectos del trabajo con texto en Aspose.PDF. Aprende cómo añadir texto a PDF, añadir fragmentos HTML o usar fuentes OTF personalizadas. -lastmod: "2024-02-17" -sitemap: - changefreq: "monthly" - priority: 0.7 ---- - - - -## Agregar Texto - -1. Abra el documento PDF de entrada usando Aspose.PDF. -1. Seleccione la página en particular a la que desea agregar el texto. -1. Cree un objeto TextFragment. Se crea un fragmento de texto con el contenido 'texto principal'. Este fragmento se posiciona en las coordenadas (100, 600) en la página. -1. Configuración de Propiedades de Texto. Se establecen varias propiedades del texto, como tamaño de fuente, tipo de fuente (Times New Roman), color de fondo (gris claro) y color de primer plano (rojo). -1. Crear el Objeto TextBuilder. Se instancia un objeto TextBuilder con la página seleccionada. -1. Anexar el Fragmento de Texto. El fragmento de texto creado anteriormente se adjunta a la página PDF usando el objeto TextBuilder. -1. Llamar al método [document.save](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) y guardar el archivo PDF de salida. - -El siguiente fragmento de código le muestra cómo agregar texto en un archivo PDF existente: - -```python - - import aspose.pdf as ap - - # Abrir documento - document = ap.Document(input_pdf) - - # Obtener página en particular - page = document.pages[1] - - # Crear fragmento de texto - text_fragment = ap.text.TextFragment("texto principal") - text_fragment.position = ap.text.Position(100, 600) - - # Establecer propiedades del texto - text_fragment.text_state.font_size = 12 - text_fragment.text_state.font = ap.text.FontRepository.find_font("TimesNewRoman") - text_fragment.text_state.background_color = ap.Color.light_gray - text_fragment.text_state.foreground_color = ap.Color.red - - # Crear objeto TextBuilder - builder = ap.text.TextBuilder(page) - - # Anexar el fragmento de texto a la página PDF - builder.append_text(text_fragment) - - # Guardar el documento PDF resultante. - document.save(output_pdf) -``` - - -## Cargando Fuente desde un Flujo - -El siguiente fragmento de código muestra cómo cargar una fuente desde un objeto de flujo al agregar texto a un documento PDF. - -```python - - import aspose.pdf as ap - - # Cargar archivo PDF de entrada - document = ap.Document() - document.pages.add() - # Crear objeto constructor de texto para la primera página del documento - text_builder = ap.text.TextBuilder(document.pages[1]) - # Crear fragmento de texto con cadena de ejemplo - text_fragment = ap.text.TextFragment("Hola mundo") - - if input_ttf != "": - # Cargar la fuente TrueType en el objeto de flujo - font_stream = open(input_ttf, "rb") - # Establecer el nombre de la fuente para la cadena de texto - text_fragment.text_state.font = ap.text.FontRepository.open_font( - font_stream, ap.text.FontTypes.TTF - ) - # Especificar la posición para el Fragmento de Texto - text_fragment.position = ap.text.Position(10, 10) - # Agregar el texto al TextBuilder para que pueda colocarse sobre el archivo PDF - text_builder.append_text(text_fragment) - # Guardar el documento PDF resultante. - document.save(output_pdf) -``` - - -## Añadir Texto usando TextParagraph - -El siguiente fragmento de código te muestra cómo agregar texto en un documento PDF utilizando la clase [TextParagraph](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textparagraph/). - -```python - - import aspose.pdf as ap - - # Abrir documento - document = ap.Document() - # Añadir página a la colección de páginas del objeto Document - page = document.pages.add() - builder = ap.text.TextBuilder(page) - # Crear párrafo de texto - paragraph = ap.text.TextParagraph() - # Establecer la sangría de las líneas subsiguientes - paragraph.subsequent_lines_indent = 20 - # Especificar la ubicación para añadir TextParagraph - paragraph.rectangle = ap.Rectangle(100, 300, 200, 700, False) - # Especificar el modo de ajuste de palabras - paragraph.formatting_options.wrap_mode = ( - ap.text.TextFormattingOptions.WordWrapMode.BY_WORDS - ) - # Crear fragmento de texto - fragment1 = ap.text.TextFragment("the quick brown fox jumps over the lazy dog") - fragment1.text_state.font = ap.text.FontRepository.find_font("Times New Roman") - fragment1.text_state.font_size = 12 - # Añadir fragmento al párrafo - paragraph.append_line(fragment1) - # Añadir párrafo - builder.append_paragraph(paragraph) - - # Guardar el documento PDF resultante. - document.save(output_pdf) -``` - - -## Añadir Hipervínculo a TextSegment - -Este código demuestra cómo crear contenido dinámico e interactivo dentro de un documento PDF, incluyendo hipervínculos a recursos externos. - -Una página PDF puede componerse de uno o más objetos TextFragment, donde cada objeto TextFragment puede tener una o más instancias de [TextSegment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textsegment/). - -Por favor, intente usar el siguiente fragmento de código para cumplir con este requisito: - -```python - - import aspose.pdf as ap - - # Crear una instancia de documento - document = ap.Document() - # Añadir página a la colección de páginas del archivo PDF - page1 = document.pages.add() - # Crear una instancia de TextFragment - tf = ap.text.TextFragment("Fragmento de Texto de Ejemplo") - # Establecer alineación horizontal para TextFragment - tf.horizontal_alignment = ap.HorizontalAlignment.RIGHT - # Crear un textsegment con texto de ejemplo - segment = ap.text.TextSegment(" ... Segmento de Texto 1...") - # Añadir segmento a la colección de segmentos de TextFragment - tf.segments.append(segment) - # Crear un nuevo TextSegment - segment = ap.text.TextSegment("Enlace a Google") - # Añadir segmento a la colección de segmentos de TextFragment - tf.segments.append(segment) - # Establecer hipervínculo para TextSegment - segment.hyperlink = ap.WebHyperlink("www.google.com") - # Establecer color de primer plano para el segmento de texto - segment.text_state.foreground_color = ap.Color.blue - # Establecer formato de texto como cursiva - segment.text_state.font_style = ap.text.FontStyles.ITALIC - # Crear otro objeto TextSegment - segment = ap.text.TextSegment("TextSegment sin hipervínculo") - # Añadir segmento a la colección de segmentos de TextFragment - tf.segments.append(segment) - # Añadir TextFragment a la colección de párrafos del objeto de página - page1.paragraphs.add(tf) - # Guardar el documento PDF resultante. - document.save(output_pdf) -``` - - -## Usar Fuente OTF - -Aspose.PDF para Python a través de .NET ofrece la función de usar fuentes Personalizadas/TrueType al crear/manipular los contenidos de archivos PDF para que los contenidos del archivo se muestren utilizando fuentes distintas a las fuentes del sistema predeterminadas. - -```python - - import aspose.pdf as ap - - # Crear una nueva instancia de documento - document = ap.Document() - # Agregar página a la colección de páginas del archivo PDF - page = document.pages.add() - # Crear instancia de TextFragment con texto de muestra - fragment = ap.text.TextFragment("Texto de muestra en fuente OTF") - # O incluso puede especificar la ruta de la fuente OTF en el directorio del sistema - fragment.text_state.font = ap.text.FontRepository.open_font(input_otf) - # Especificar para embeber la fuente dentro del archivo PDF, para que se muestre correctamente, - # Incluso si la fuente específica no está instalada/presente en la máquina de destino - fragment.text_state.font.is_embedded = True - # Agregar TextFragment a la colección de párrafos de la instancia de Page - page.paragraphs.add(fragment) - # Guardar el documento PDF resultante. - document.save(output_pdf) -``` - - -## Agregar cadena HTML utilizando DOM - -El siguiente código de Python utiliza la biblioteca Aspose.PDF para crear un documento PDF con un fragmento HTML. - -1. Instanciar Document. Se crea una instancia de la clase Document, que representa el documento PDF. -1. Agregar página al documento PDF. -1. Instanciar un objeto HtmlFragment con contenido HTML. -1. Establecer márgenes para el fragmento HTML. En este caso, el margen inferior se establece en 10 puntos y el margen superior en 200 puntos. -1. Agregar fragmento HTML a la página. -1. Guardar archivo PDF. - -```python - - import aspose.pdf as ap - - # Instanciar objeto Document - doc = ap.Document() - # Agregar una página a la colección de páginas del archivo PDF - page = doc.pages.add() - # Instanciar HtmlFragment con contenido HTML - title = ap.HtmlFragment("Table") - # Establecer información del margen inferior - title.margin.bottom = 10 - # Establecer información del margen superior - title.margin.top = 200 - # Agregar fragmento HTML a la colección de párrafos de la página - page.paragraphs.add(title) - # Guardar archivo PDF - doc.save(output_pdf) -``` - - -### Estilo de línea personalizado para FootNote - -El siguiente ejemplo demuestra cómo agregar notas al pie en la parte inferior de la página PDF y definir un estilo de línea personalizado. - -```python - - import aspose.pdf as ap - - # Crear una instancia de Documento - doc = ap.Document() - # Agregar página a la colección de páginas del PDF - page = doc.pages.add() - # Crear objeto GraphInfo - graph = ap.GraphInfo() - # Establecer el ancho de línea como 2 - graph.line_width = 2 - # Establecer el color para el objeto gráfico - graph.color = ap.Color.red - # Establecer el valor del array de guiones como 3 - graph.dash_array = [3] - # Establecer el valor de fase de guiones como 1 - graph.dash_phase = 1 - # Establecer el estilo de línea de la nota al pie de la página como gráfico - page.note_line_style = graph - # Crear una instancia de TextFragment - text = ap.text.TextFragment("Hello World") - # Establecer el valor de FootNote para TextFragment - text.foot_note = ap.Note("nota al pie para el texto de prueba 1") - # Agregar TextFragment a la colección de párrafos de la primera página del documento - page.paragraphs.add(text) - # Crear el segundo TextFragment - text = ap.text.TextFragment("Aspose.Pdf for .NET") - # Establecer la nota al pie para el segundo fragmento de texto - text.foot_note = ap.Note("nota al pie para el texto de prueba 2") - # Agregar el segundo fragmento de texto a la colección de párrafos del archivo PDF - page.paragraphs.add(text) - # Guardar el documento PDF resultante. - doc.save(output_pdf) -``` - - -### Personalizar etiqueta de nota al pie - -El siguiente fragmento de código muestra cómo crear un documento PDF con un fragmento de texto que contiene una nota al pie. - -Por defecto, el número de la nota al pie es incremental comenzando desde 1. Sin embargo, podemos tener el requerimiento de establecer una etiqueta de nota al pie personalizada. Para cumplir con este requisito, intenta usar el siguiente fragmento de código - -```python - - import aspose.pdf as ap - - # Crear una instancia de Document - document = ap.Document() - # Agregar página a la colección de páginas del PDF - page = document.pages.add() - # Crear objeto GraphInfo - graph = ap.GraphInfo() - # Establecer el ancho de línea como 2 - graph.line_width = 2 - # Establecer el color para el objeto graph - graph.color = ap.Color.red - # Establecer el valor del array de guiones como 3 - graph.dash_array = [3] - # Establecer el valor de fase de guiones como 1 - graph.dash_phase = 1 - # Establecer el estilo de línea de nota al pie para la página como graph - page.note_line_style = graph - # Crear una instancia de TextFragment - text = ap.text.TextFragment("Hello World") - # Establecer el valor de FootNote para TextFragment - text.foot_note = ap.Note("nota al pie para el texto de prueba 1") - # Especificar etiqueta personalizada para FootNote - text.foot_note.text = " Aspose" - # Agregar TextFragment a la colección de párrafos de la primera página del documento - page.paragraphs.add(text) - # Guardar el documento PDF resultante. - document.save(output_pdf) -``` - - -## Añadir Imagen y Tabla a la Nota al Pie - -Este código demuestra cómo crear un documento PDF con un fragmento de texto que contiene una nota al pie compleja que incluye una imagen, texto y una tabla utilizando Aspose.PDF para Python. - -```python - - import aspose.pdf as ap - - document = ap.Document() - page = document.pages.add() - text = ap.text.TextFragment("algún texto") - page.paragraphs.add(text) - - text.foot_note = ap.Note() - image = ap.Image() - image.file = input_jpg - image.fix_height = 20 - text.foot_note.paragraphs.add(image) - foot_note = ap.text.TextFragment("texto de la nota al pie") - foot_note.text_state.font_size = 20 - foot_note.is_in_line_paragraph = True - text.foot_note.paragraphs.add(foot_note) - table = ap.Table() - table.rows.add().cells.add().paragraphs.add(ap.text.TextFragment("Fila 1 Celda 1")) - text.foot_note.paragraphs.add(table) - - # Guardar el documento PDF resultante. - document.save(output_pdf) -``` - -## Cómo Crear Notas al Final - -Una Nota al Final es una cita de fuente que refiere a los lectores a un lugar específico al final del documento donde pueden encontrar la fuente de la información o palabras citadas o mencionadas en el documento. - Cuando se utilizan notas al final, la oración citada o parafraseada o el material resumido es seguido por un número en superíndice. - -Este código demuestra cómo agregar un fragmento de texto con una nota al final a un documento PDF usando Aspose.PDF para Python: - -```python - - import aspose.pdf as ap - - # Crear instancia de Document - document = ap.Document() - # Agregar página a la colección de páginas del PDF - page = document.pages.add() - # Crear instancia de TextFragment - text = ap.text.TextFragment("Hola Mundo") - # Establecer valor de EndNote para TextFragment - text.end_note = ap.Note("nota al final de ejemplo") - # Especificar etiqueta personalizada para FootNote - text.end_note.text = " Aspose" - # Agregar TextFragment a la colección de párrafos de la primera página del documento - page.paragraphs.add(text) - # Guardar el documento PDF resultante. - document.save(output_pdf) -``` - -## Texto e Imagen como Párrafo en Línea - -El diseño predeterminado del archivo PDF es diseño de flujo (de arriba a la izquierda a abajo a la derecha). Por lo tanto, cada nuevo elemento que se añade al archivo PDF se agrega en el flujo inferior derecho. Sin embargo, podemos tener un requisito para mostrar varios elementos de la página, es decir, Imagen y Texto al mismo nivel (uno tras otro). Un enfoque puede ser crear una instancia de Tabla y agregar ambos elementos a objetos de celda individuales. Sin embargo, otro enfoque puede ser el párrafo InLine. Al establecer la propiedad IsInLineParagraph de Imagen y Texto como verdadera, estos párrafos aparecerán como en línea con otros elementos de la página. - -El siguiente fragmento de código te muestra cómo agregar texto e imagen como párrafos en línea en un archivo PDF. - -```python - - import aspose.pdf as ap - - # Instanciar instancia de Documento - document = ap.Document() - # Añadir página a la colección de páginas de la instancia de Documento - page = document.pages.add() - # Crear TextFragment - text = ap.text.TextFragment("Hola Mundo.. ") - # Añadir fragmento de texto a la colección de párrafos del objeto Page - page.paragraphs.add(text) - # Crear una instancia de imagen - image = ap.Image() - # Establecer imagen como párrafo en línea para que aparezca justo después - # del objeto de párrafo anterior (TextFragment) - image.is_in_line_paragraph = True - # Especificar la ruta del archivo de imagen - image.file = input_jpg - # Establecer altura de imagen (opcional) - image.fix_height = 30 - # Establecer ancho de imagen (opcional) - image.fix_width = 100 - # Añadir imagen a la colección de párrafos del objeto de página - page.paragraphs.add(image) - # Re-inicializar objeto TextFragment con diferentes contenidos - text = ap.text.TextFragment(" Hola de nuevo..") - # Establecer TextFragment como párrafo en línea - text.is_in_line_paragraph = True - # Añadir el nuevo TextFragment creado a la colección de párrafos de la página - page.paragraphs.add(text) - # Guardar el documento PDF resultante. - document.save(output_pdf) -``` - -## Especificar el Espaciado de Caracteres al agregar Texto - -El siguiente fragmento de código muestra cómo generar un documento PDF que contiene un fragmento de texto con espaciado de caracteres aumentado. - -El texto se puede agregar dentro de una colección de párrafos de archivos PDF usando la instancia de TextFragment o utilizando el objeto TextParagraph e incluso puedes estampar el texto dentro del PDF usando la clase TextStamp. - -### Usando TextBuilder y TextFragment - -```python - - import aspose.pdf as ap - - # Crear instancia de Document - document = ap.Document() - # Agregar página a la colección de páginas del Documento - document.pages.add() - # Crear instancia de TextBuilder - builder = ap.text.TextBuilder(document.pages[1]) - # Crear instancia de fragmento de texto con contenido de ejemplo - wide_fragment = ap.text.TextFragment("Texto con espaciado de caracteres aumentado") - wide_fragment.text_state.apply_changes_from(ap.text.TextState("Arial", 12)) - # Especificar el espaciado de caracteres para TextFragment - wide_fragment.text_state.character_spacing = 2.0 - # Especificar la posición de TextFragment - wide_fragment.position = ap.text.Position(100, 650) - # Agregar TextFragment a la instancia de TextBuilder - builder.append_text(wide_fragment) - # Guardar el documento PDF resultante. - document.save(output_pdf) -``` - - -### Usando TextParagraph - -```python - - import aspose.pdf as ap - - # Crear instancia de Document - document = ap.Document() - # Añadir página a la colección de páginas del Document - document.pages.add() - # Crear instancia de TextBuilder - builder = ap.text.TextBuilder(document.pages[1]) - # Instanciar instancia de TextParagraph - paragraph = ap.text.TextParagraph() - # Crear instancia de TextState para especificar el nombre y tamaño de la fuente - state = ap.text.TextState(12.0) - state.font = ap.text.FontRepository.find_font("Arial") - # Especificar el espaciado de caracteres - state.character_spacing = 1.5 - # Añadir texto al objeto TextParagraph - tt = "Este es un párrafo con espaciado de caracteres" - paragraph.append_line(tt, state) - # Especificar la posición para TextParagraph - paragraph.position = ap.text.Position(100, 550) - # Añadir TextParagraph a la instancia de TextBuilder - builder.append_paragraph(paragraph) - # Guardar el documento PDF resultante. - document.save(output_pdf) -``` - -### Usando TextStamp - -```python - - import aspose.pdf as ap - - # Crear instancia de Document - document = ap.Document() - # Añadir página a la colección de páginas del Document - page = document.pages.add() - # Instanciar instancia de TextStamp con texto de muestra - stamp = ap.TextStamp("Este es un sello de texto con espaciado de caracteres") - # Especificar el nombre de la fuente para el objeto Stamp - stamp.text_state.font = ap.text.FontRepository.find_font("Arial") - # Especificar el tamaño de la fuente para TextStamp - stamp.text_state.font_size = 12 - # Especificar espaciado de caracteres como 1 - stamp.text_state.character_spacing = 1 - # Establecer la x_indent para Stamp - stamp.x_indent = 100 - # Establecer la y_indent para Stamp - stamp.y_indent = 500 - # Añadir sello textual a la instancia de página - stamp.put(page) - # Guardar el documento PDF resultante. - document.save(output_pdf) -``` - - -## Crear documento PDF de varias columnas - -[Aspose.PDF para Python a través de .NET](https://docs.aspose.com/pdf/python-net/) también ofrece la función de crear múltiples columnas dentro de las páginas de documentos PDF. Para crear un archivo PDF de varias columnas, podemos hacer uso de la clase FloatingBox ya que proporciona la propiedad column_info para especificar el número de columnas dentro de FloatingBox y también podemos especificar el espacio entre columnas y los anchos de las columnas usando las propiedades column_spacing y width respectivamente. - -El espacio entre columnas significa el espacio entre las columnas y el espacio predeterminado entre las columnas es de 1,25 cm. Si no se especifica el ancho de la columna, entonces [Aspose.PDF para Python a través de .NET](https://docs.aspose.com/pdf/python-net/) calcula el ancho de cada columna automáticamente de acuerdo con el tamaño de la página y el espacio entre columnas. - -A continuación se da un ejemplo para demostrar la creación de dos columnas con objetos Graphs (Line) y se añaden a la colección de párrafos de FloatingBox, que luego se añade a la colección de párrafos de la instancia Page. - -```python - - import aspose.pdf as ap - - document = ap.Document() - # Especificar la información del margen izquierdo para el archivo PDF - document.page_info.margin.left = 40 - # Especificar la información del margen derecho para el archivo PDF - document.page_info.margin.right = 40 - page = document.pages.add() - - graph1 = ap.drawing.Graph(500, 2) - # Agregar la línea a la colección de párrafos del objeto sección - page.paragraphs.add(graph1) - - # Especificar las coordenadas para la línea - pos1 = [1.0, 2.0, 500.0, 2.0] - l1 = ap.drawing.Line(pos1) - graph1.shapes.append(l1) - # Crear variables string con texto que contiene etiquetas html - s = ( - '' - + " Cómo evitar las estafas de dinero " - + "" - ) - # Crear párrafos de texto que contienen texto HTML - heading_text = ap.HtmlFragment(s) - page.paragraphs.add(heading_text) - - box = ap.FloatingBox() - # Añadir cuatro columnas en la sección - box.column_info.column_count = 2 - # Establecer el espacio entre las columnas - box.column_info.column_spacing = "5" - - box.column_info.column_widths = "105 105" - text1 = ap.text.TextFragment("Por Un Googler (El Blog Oficial de Google)") - text1.text_state.font_size = 8 - text1.text_state.line_spacing = 2 - box.paragraphs.add(text1) - text1.text_state.font_size = 10 - - text1.text_state.font_style = ap.text.FontStyles.ITALIC - # Crear un objeto de gráficos para dibujar una línea - graph2 = ap.drawing.Graph(50, 10) - # Especificar las coordenadas para la línea - pos2 = [1.0, 10.0, 100.0, 10.0] - l2 = ap.drawing.Line(pos2) - graph2.shapes.append(l2) - - # Añadir la línea a la colección de párrafos del objeto sección - box.paragraphs.add(graph2) - - text2 = ap.text.TextFragment( - "Sed augue tortor, sodales id, luctus et, pulvinar ut, eros. Suspendisse vel dolor. Sed quam. Curabitur ut massa vitae eros euismod aliquam. Pellentesque sit amet elit. Vestibulum interdum pellentesque augue. Cras mollis arcu sit amet purus. Donec augue. Nam mollis tortor a elit. Nulla viverra nisl vel mauris. Vivamus sapien. nascetur ridiculus mus. Nam justo lorem, aliquam luctus, sodales et, semper sed, enim Nam justo lorem, aliquam luctus, sodales et,nAenean posuere ante ut neque. Morbi sollicitudin congue felis. Praesent turpis diam, iaculis sed, pharetra non, mollis ac, mauris. Phasellus nisi ipsum, pretium vitae, tempor sed, molestie eu, dui. Duis lacus purus, tristique ut, iaculis cursus, tincidunt vitae, risus. Sed commodo. *** sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam justo lorem, aliquam luctus, sodales et, semper sed, enim Nam justo lorem, aliquam luctus, sodales et, semper sed, enim Nam justo lorem, aliquam luctus, sodales et, semper sed, enim nAenean posuere ante ut neque. Morbi sollicitudin congue felis. Praesent turpis diam, iaculis sed, pharetra non, mollis ac, mauris. Phasellus nisi ipsum, pretium vitae, tempor sed, molestie eu, dui. Duis lacus purus, tristique ut, iaculis cursus, tincidunt vitae, risus. Sed commodo. *** sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed urna. . Duis convallis ultrices nisi. Maecenas non ligula. Nunc nibh est, tincidunt in, placerat sit amet, vestibulum a, nulla. Praesent porttitor turpis eleifend ante. Morbi sodales.nAenean posuere ante ut neque. Morbi sollicitudin congue felis. Praesent turpis diam, iaculis sed, pharetra non, mollis ac, mauris. Phasellus nisi ipsum, pretium vitae, tempor sed, molestie eu, dui. Duis lacus purus, tristique ut, iaculis cursus, tincidunt vitae, risus. Sed commodo. *** sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed urna. . Duis convallis ultrices nisi. Maecenas non ligula. Nunc nibh est, tincidunt in, placerat sit amet, vestibulum a, nulla. Praesent porttitor turpis eleifend ante. Morbi sodales." - ) - box.paragraphs.add(text2) - page.paragraphs.add(box) - # Guardar archivo PDF - document.save(output_pdf) -``` - - -## Trabajando con Tabulaciones Personalizadas - -Este fragmento de código en Python muestra cómo crear un documento PDF que contiene fragmentos de texto organizados utilizando tabulaciones para simular una estructura de tabla. - -Aquí hay un ejemplo de cómo establecer tabulaciones personalizadas. - -```python - - import aspose.pdf as ap - - document = ap.Document() - page = document.pages.add() - - ts = ap.text.TabStops() - ts1 = ts.add(100.0) - ts1.alignment_type = ap.text.TabAlignmentType.RIGHT - ts1.leader_type = ap.text.TabLeaderType.SOLID - ts2 = ts.add(200.0) - ts2.alignment_type = ap.text.TabAlignmentType.CENTER - ts2.leader_type = ap.text.TabLeaderType.DASH - ts3 = ts.add(300.0) - ts3.alignment_type = ap.text.TabAlignmentType.LEFT - ts3.leader_type = ap.text.TabLeaderType.DOT - - header = ap.text.TextFragment( - "Este es un ejemplo de formación de tabla con tabulaciones", ts - ) - text0 = ap.text.TextFragment("#$TABHead1 #$TABHead2 #$TABHead3", ts) - - text1 = ap.text.TextFragment("#$TABdata11 #$TABdata12 #$TABdata13", ts) - text2 = ap.text.TextFragment("#$TABdata21 ", ts) - text2.segments.append(ap.text.TextSegment("#$TAB")) - text2.segments.append(ap.text.TextSegment("data22 ")) - text2.segments.append(ap.text.TextSegment("#$TAB")) - text2.segments.append(ap.text.TextSegment("data23")) - - page.paragraphs.add(header) - page.paragraphs.add(text0) - page.paragraphs.add(text1) - page.paragraphs.add(text2) - - document.save(output_pdf) -``` - - -## Cómo Agregar Texto Transparente en PDF - -Un archivo PDF contiene objetos de Imagen, Texto, Gráfico, adjuntos, Anotaciones y al crear un TextFragment, puedes establecer información de color de primer plano, color de fondo, así como el formato de texto. Aspose.PDF para Python a través de .NET admite la característica de agregar texto con canal de color Alpha. - -El siguiente fragmento de código muestra cómo agregar texto con color transparente. - -```python - - import aspose.pdf as ap - - # Crear instancia de Documento - document = ap.Document() - # Crear página para la colección de páginas del archivo PDF - page = document.pages.add() - - # Crear instancia de TextFragment con un valor de ejemplo - text = ap.text.TextFragment( - "texto transparente texto transparente texto transparente texto transparente texto transparente texto transparente texto transparente texto transparente texto transparente texto transparente texto transparente texto transparente texto transparente texto transparente texto transparente texto transparente " - ) - # Crear objeto de color desde el canal Alpha - color = ap.Color.from_argb(30, 0, 255, 0) - # Establecer información de color para la instancia de texto - text.text_state.foreground_color = color - # Agregar texto a la colección de párrafos de la instancia de página - page.paragraphs.add(text) - - document.save(output_pdf) -``` - - -## Especificar el Espaciado entre Líneas para Fuentes - -Cada fuente tiene un cuadrado abstracto, cuya altura es la distancia prevista entre líneas de texto en el mismo tamaño de fuente. Este cuadrado se llama el cuadrado em y es la cuadrícula de diseño en la que se definen los contornos de los glifos. Muchas letras de la fuente de entrada tienen puntos que están colocados fuera de los límites del cuadrado em de la fuente, por lo que para mostrar la fuente correctamente, se necesita el uso de una configuración especial. - -El siguiente fragmento de código carga un PDF, agrega un fragmento de texto con un espaciado entre líneas específico usando una fuente TrueType, y guarda el documento PDF modificado: - -```python - - import aspose.pdf as ap - - # Cargar archivo PDF de entrada - document = ap.Document() - # Crear TextFormattingOptions con LineSpacingMode.FULL_SIZE - options = ap.text.TextFormattingOptions() - options.line_spacing = ap.text.TextFormattingOptions.LineSpacingMode.FULL_SIZE - - # Crear fragmento de texto con cadena de ejemplo - text_fragment = ap.text.TextFragment("Hola mundo") - - # Cargar la fuente TrueType en el objeto stream - font_stream = open(input_ttf, "rb") - # Establecer el nombre de la fuente para la cadena de texto - text_fragment.text_state.font = ap.text.FontRepository.open_font( - font_stream, ap.text.FontTypes.TTF - ) - # Especificar la posición para el Fragmento de Texto - text_fragment.position = ap.text.Position(100, 600) - # Establecer TextFormattingOptions del fragmento actual a predefinido (que apunta a LineSpacingMode.FULL_SIZE) - text_fragment.text_state.formatting_options = options - page = document.pages.add() - page.paragraphs.add(text_fragment) - - # Guardar el documento PDF resultante - document.save(output_pdf) -``` - - -## Obtener el Ancho del Texto Dinámicamente - -Este fragmento de código en Python realiza una comparación entre las mediciones de cadenas obtenidas de un objeto de fuente y un objeto de estado de texto en Aspose.PDF: - -```python - - import math as ap - - font = ap.text.FontRepository.find_font("Arial") - ts = ap.text.TextState() - ts.font = font - ts.font_size = 14 - - if mt.fabs(font.measure_string("A", 14) - 9.337) > 0.001: - print("¡Medición de cadena de fuente inesperada!") - - if mt.fabs(ts.measure_string("z") - 7.0) > 0.001: - print("¡Medición de cadena de fuente inesperada!") - - c_code = ord("A") - while c_code <= ord("z"): - c = chr(c_code) - - fn_measure = font.measure_string(str(c), 14) - ts_measure = ts.measure_string(str(c)) - - print(str(c_code) + "-" + c + "-" + str(ts_measure)) - - if mt.fabs(fn_measure - ts_measure) > 0.001: - print("¡La medición de cadenas de fuente y estado no coincide!") - - c_code += 1 -``` - - \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/_index.md b/es/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/_index.md new file mode 100644 index 000000000..d0d3e4dc3 --- /dev/null +++ b/es/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/_index.md @@ -0,0 +1,937 @@ +--- +title: Agregar texto a PDF en Python +linktitle: Agregar texto a PDF +type: docs +weight: 10 +url: /es/python-net/add-text-to-pdf-file/ +description: Aprenda cómo agregar texto, fragmentos HTML, listas, enlaces y fuentes personalizadas a documentos PDF en Python. +lastmod: "2026-05-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agrega texto, enlaces, HTML y fuentes a archivos PDF con Python. +Abstract: Este artículo explica cómo agregar y dar formato al texto en documentos PDF usando Aspose.PDF for Python via .NET. Cubre técnicas básicas como la posición del texto, la aplicación de configuraciones de fuente y estilo, la inserción de enlaces y listas, y el uso de HTML, LaTeX y fuentes personalizadas en flujos de trabajo de Python. +--- + +Esta guía explica cómo agregar contenido de texto a documentos PDF usando Aspose.PDF for Python via .NET. Aprenderá técnicas básicas de inserción de texto, desde colocar un fragmento de texto simple en una posición concreta hasta aplicarle estilo con fuente, tamaño, color y otros atributos, trabajar con idiomas de derecha a izquierda (RTL), incrustar hipervínculos y usar diseños con párrafos, listas y efectos de transparencia. El artículo también cubre escenarios avanzados, como el uso de fragmentos HTML o LaTeX, fuentes personalizadas y opciones de formato como el interlineado y el espaciado entre caracteres. + +Tanto si está creando anotaciones sencillas como composiciones tipográficas más elaboradas, este recurso reúne los elementos fundamentales para trabajar con texto en PDF usando Aspose.PDF. + +## Inserción de texto básica + +Aspose.PDF for Python via .NET proporciona una API potente y flexible para manejar texto dentro de archivos PDF. Ya sea que necesite etiquetas estáticas simples, contenido con formato enriquecido, texto multilingue o hipervínculos interactivos, este conjunto de herramientas permite hacerlo con código Python conciso. + +### Agregar texto: caso simple + +Aspose.PDF for Python via .NET muestra cómo agregar un fragmento de texto simple a una posición específica en una página. Aprenderá cómo crear un nuevo documento PDF, agregar una página, insertar texto en coordenadas dadas y guardar el archivo resultante. + +1. Crear un nuevo objeto [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Usar `document.pages.add()` para crear una [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) en blanco. +1. Cree un [`TextFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/) con el contenido de texto. +1. Establecer la posición del texto usando la clase [`Position`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/position/). Si especifica `Position`, el texto se colocará en la ubicación indicada dentro de la página. +1. Personaliza la apariencia del texto. Puedes establecer el tamaño de fuente, color, estilo de fuente y más a través de [`TextState`](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstate/). +1. Agregar el `TextFragment` a la colección de párrafos de la página con `page.paragraphs.add(text_fragment)`. +1. Guarde el documento. + +El siguiente fragmento de código le muestra cómo agregar texto en un archivo PDF existente: + +```python +import math +import sys +import os +import aspose.pdf as ap + +# region Basic text insertion +def add_text_simple_case(output_file_name): + # Create a new document + document = ap.Document() + page = document.pages.add() + + # Add a text fragment at a specific position + text_fragment = ap.text.TextFragment("Hello, Aspose!") + text_fragment.position = ap.text.Position(100, 600) + + page.paragraphs.add(text_fragment) + document.save(output_file_name) +``` + +Este ejemplo de código utiliza un `TextFragment`. También puede agregar texto a una página PDF usando un `TextParagraph`. +Un **[TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/)** es una pieza individual de texto. Representa una cadena de texto que puede colocarse, estilizarse y posicionarse de forma independiente. Es ideal cuando necesita agregar contenido breve y simple. + +Un **[TextParagraph](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textparagraph/)** es un grupo de `TextFragment`. Puede incluir varias líneas de texto. `TextParagraph` actúa como contenedor de uno o más objetos `TextFragment`, por lo que resulta útil cuando necesita agrupar varios fragmentos para crear un bloque de texto con varias líneas, palabras o elementos con formato. +`TextParagraph` también gestiona la alineación del texto, el interlineado y el diseño automático en la página. La sangría de primera línea solo está disponible con `TextParagraph`. + +Para obtener más información sobre cómo trabajar con texto, consulte [Formato de texto dentro de PDF](/pdf/es/python-net/text-formatting-inside-pdf/) y [Buscar y obtener texto del PDF](/pdf/es/python-net/search-and-get-text-from-pdf/). + +### Agregar texto usando TextParagraph + +Aspose.PDF for Python via .NET puede agregar un párrafo de texto usando [`TextBuilder`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textbuilder/) y [`TextParagraph`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textparagraph/) con opciones de ajuste. + +1. Crear un nuevo [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) y una [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) en blanco usando `document.pages.add()`. +1. Lea el texto de un archivo o use el texto predeterminado. +1. Cree un [`TextBuilder`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textbuilder/) para agregar contenido a nivel de párrafo con control de diseño y ajuste. +1. Cree un [`TextParagraph`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textparagraph/) y establezca el modo de ajuste (el ejemplo usa `DISCRETIONARY_HYPHENATION`). +1. Cree un [`TextFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/), aplique estilos y añada el fragmento al párrafo. +1. Añade el párrafo a la página usando el `TextBuilder`. +1. Guarde el documento. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def add_paragraph(output_file_name): + document = ap.Document() + page = document.pages.add() + + lorem_path = LOREM_PATH + if os.path.exists(lorem_path): + with open(lorem_path, "r", encoding="utf-8") as file: + text = file.read() + else: + text = "Lorem ipsum sample text not found." + + builder = ap.text.TextBuilder(page) + paragraph = ap.text.TextParagraph() + paragraph.first_line_indent = 20 + paragraph.rectangle = ap.Rectangle(80, 800, 400, 200, True) + # paragraph.formatting_options.wrap_mode = TextFormattingOptions.WordWrapMode.BY_WORDS + paragraph.formatting_options.wrap_mode = ( + ap.text.TextFormattingOptions.WordWrapMode.DISCRETIONARY_HYPHENATION + ) + + fragment = ap.text.TextFragment(text) + fragment.text_state.font = ap.text.FontRepository.find_font("Times New Roman") + fragment.text_state.font_size = 12 + + paragraph.append_line(fragment) + builder.append_paragraph(paragraph) + + document.save(output_file_name) +``` + +![Agregar texto usando TextParagraph](text_paragraph.png) + +### Agregar párrafos con sangrías en PDF + +El siguiente fragmento de código muestra cómo crear un nuevo documento PDF y agregar dos párrafos de texto con diferentes estilos de sangría: + +- El primer párrafo muestra una sangría en la primera línea (solo la primera línea está indentada). + +- El segundo párrafo demuestra una sangría de líneas subsiguientes (todas las líneas después de la primera están sangradas). + +Utiliza las clases `TextParagraph`, `TextBuilder` y `TextFragment` de Aspose.PDF para controlar con precisión el diseño y el formato. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def add_paragraphs_indents(output_file_name): + document = ap.Document() + page = document.pages.add() + + lorem_path = LOREM_PATH + if os.path.exists(lorem_path): + with open(lorem_path, "r", encoding="utf-8") as file: + text = file.read() + else: + text = "Lorem ipsum sample text not found." + + fragment = ap.text.TextFragment(text) + fragment.text_state.font = ap.text.FontRepository.find_font("Times New Roman") + fragment.text_state.font_size = 12 + + builder = ap.text.TextBuilder(page) + paragraph1 = ap.text.TextParagraph() + paragraph1.first_line_indent = 20 + paragraph1.rectangle = ap.Rectangle(80, 800, 300, 50, True) + paragraph1.formatting_options.wrap_mode = ( + ap.text.TextFormattingOptions.WordWrapMode.BY_WORDS + ) + + paragraph1.append_line(fragment) + builder.append_paragraph(paragraph1) + + paragraph2 = ap.text.TextParagraph() + paragraph2.subsequent_lines_indent = 20 + paragraph2.rectangle = ap.Rectangle(320, 800, 500, 50, True) + paragraph2.formatting_options.wrap_mode = ( + ap.text.TextFormattingOptions.WordWrapMode.BY_WORDS + ) + + paragraph2.append_line(fragment) + builder.append_paragraph(paragraph2) + document.save(output_file_name) +``` + +### Agregar una nueva línea de texto en PDF + +Aspose.PDF for Python via .NET permite insertar texto de varias líneas en un documento PDF usando las clases `TextFragment`, `TextParagraph` y `TextBuilder`. + +1. Crear un nuevo documento. +1. Definir un TextFragment que contenga un carácter de nueva línea. +1. Establecer estilo de texto. +1. Agrega el fragmento a un párrafo. +1. Posicione el párrafo. +1. Renderizar párrafo en la página. +1. Guarde el documento. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def add_new_line(output_file): + """Add a new line of text to a PDF document.""" + # Create PDF document + document = ap.Document() + page = document.pages.add() + + # Initialize new TextFragment with text containing required newline markers + text_fragment = ap.text.TextFragment("Applicant Name: " + os.linesep + " Joe Smoe") + + # Set text fragment properties if necessary + text_fragment.text_state.font_size = 12 + text_fragment.text_state.font = ap.text.FontRepository.find_font("TimesNewRoman") + text_fragment.text_state.background_color = ap.Color.light_gray + text_fragment.text_state.foreground_color = ap.Color.red + + # Create TextParagraph object + par = ap.text.TextParagraph() + + # Add new TextFragment to paragraph + par.append_line(text_fragment) + + # Set paragraph position + par.position = ap.text.Position(100, 600) + + # Create TextBuilder object + text_builder = ap.text.TextBuilder(page) + + # Add the TextParagraph using TextBuilder + text_builder.append_paragraph(par) + + # Save PDF document + document.save(output_file) +``` + +### Determinar saltos de línea y registrar notificaciones en un PDF + +Este ejemplo muestra cómo crear un documento PDF que contenga varios fragmentos de texto y habilitar el registro de notificaciones de Aspose.PDF para supervisar eventos de diseño, como los saltos de línea y el ajuste de texto, durante la renderización. + +1. Crear un nuevo documento PDF. +1. Habilitar el registro de notificaciones. +1. Utilice document.pages.add() para crear la primera página. +1. Agregar varios fragmentos de texto. +1. Utilice page.paragraphs.add(text) para renderizar cada fragmento de texto. +1. Guarde el documento. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def determine_line_break(output_file): + """Create a PDF document with multiple text fragments and log notifications.""" + # Create PDF document + document = ap.Document() + + # Enable notification logging + document.enable_notification_logging = True + + page = document.pages.add() + + for i in range(4): + text = ap.text.TextFragment( + "Lorem ipsum \r\ndolor sit amet, consectetur adipiscing elit, " + "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. " + "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris " + "nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in " + "reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla " + "pariatur. Excepteur sint occaecat cupidatat non proident, sunt in " + "culpa qui officia deserunt mollit anim id est laborum." + ) + text.text_state.font_size = 20 + page.paragraphs.add(text) + + # Save PDF document + document.save(output_file) + + notifications = document.pages[1].get_notifications() + print(notifications) +``` + +### Medir dinámicamente el ancho del texto en PDF + +Mida dinámicamente el ancho de caracteres y cadenas en una fuente concreta usando Aspose.PDF for Python via .NET. Este enfoque utiliza los métodos `Font.measure_string()` y `TextState.measure_string()` para verificar que los anchos medidos sean consistentes y precisos. + +1. Utilice `FontRepository.find_font()` para recuperar la fuente Arial del repositorio. +1. Cree un objeto `TextState` para gestionar las propiedades de la fuente. +1. Medir caracteres individuales. +1. Comparar los resultados de ambos métodos para todos los caracteres entre `A` y `z`. +1. Asegúrese de que ambos enfoques de medición produzcan los mismos resultados. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def get_text_width_dynamically(output_file): + font = ap.text.FontRepository.find_font("Arial") + ts = ap.text.TextState() + ts.font = font + ts.font_size = 14 + + if math.fabs(font.measure_string("A", 14) - 9.337) > 0.001: + print("Unexpected font string measure!") + + if math.fabs(ts.measure_string("z") - 7.0) > 0.001: + print("Unexpected font string measure!") + + c_code = ord("A") + while c_code <= ord("z"): + c = chr(c_code) + + fn_measure = font.measure_string(str(c), 14) + ts_measure = ts.measure_string(str(c)) + + if math.fabs(fn_measure - ts_measure) > 0.001: + print("Font and state string measuring doesn't match!") + + c_code += 1 +``` + +### Agregar texto con hipervínculos + +Agregue hipervínculos sobre texto en un PDF usando Aspose.PDF for Python via .NET. Esta técnica muestra cómo agregar varios segmentos de texto dentro de un único `TextFragment`, aplicar un hipervínculo a un segmento específico y dar estilo a cada segmento de manera individual, por ejemplo con color o cursiva. + +1. Crea un nuevo documento y página usando 'Document()', y 'document.pages.add()' para añadir una página en blanco. +1. Crear un TextFragment. +1. Agrega varios objetos TextSegment. Cada segmento puede tener su propio contenido y estilo. Por ejemplo texto plano o texto con hipervínculo. +1. Aplicar un hipervínculo a un segmento. Crear un objeto WebHyperlink con la URL deseada. +1. Estiliza el segmento. Personaliza el color, el estilo de fuente, el tamaño, etc., usando text_state. +1. Agrega el fragmento a la página usando 'page.paragraphs.add()'. +1. Guardar el PDF. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def add_text_with_hyperlink(output_file_name): + document = ap.Document() + page = document.pages.add() + + fragment = ap.text.TextFragment("Sample Text Fragment") + + segment = ap.text.TextSegment(" ... Text Segment 1...") + fragment.segments.append(segment) + + segment = ap.text.TextSegment("Link to Aspose") + fragment.segments.append(segment) + segment.hyperlink = ap.WebHyperlink("https://products.aspose.com/pdf") + segment.text_state.foreground_color = ap.Color.blue + segment.text_state.font_style = ap.text.FontStyles.ITALIC + + segment = ap.text.TextSegment("TextSegment without hyperlink") + fragment.segments.append(segment) + + page.paragraphs.add(fragment) + document.save(output_file_name) +``` + +![Fragmento de texto mostrado en un PDF que muestra contenido mixto con Sample Text Fragment seguido por Text Segment 1, luego un texto hipervinculado azul que dice Link to Aspose (enlazando a https://products.aspose.com/pdf), y terminando con TextSegment sin hipervínculo en formato de texto negro regular](hyperlink_text.png) + +### Agregar texto de derecha a izquierda (RTL) al documento PDF + +RTL (de Right To Left) es una propiedad que indica la dirección de escritura del texto, donde el texto se escribe de derecha a izquierda. +Aspose.PDF for Python via .NET. demuestra cómo agregar texto de derecha a izquierda (RTL), como árabe o hebreo, a un documento PDF. + +1. Crea un nuevo documento y página usando 'Document()', y 'document.pages.add()' para añadir una página en blanco. +1. Cree un TextFragment con contenido RTL. Inserte su texto en árabe, hebreo o en otro idioma RTL como contenido del fragmento. +Establecer fuente y estilo. Elija una fuente que admita el script RTL (p. ej., Tahoma, Arial Unicode MS). Establezca font_size y foreground_color según sea necesario. +1. Establezca la alineación horizontal a la derecha usando 'text_fragment.horizontal_alignment'. +1. Agregar el fragmento de texto a la página. +1. Guarde el documento PDF. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def add_text_with_rtl_text(output_file_name): + document = ap.Document() + page = document.pages.add() + # Styled text fragment + text_fragment = ap.text.TextFragment( + "يعتبر خوجا نصر الدين شخصية فولكلورية من الشرق الإسلامي وبعض شعوب البحر الأبيض المتوسط ​​والبلقان، وهو بطل القصص والحكايات القصيرة الفكاهية والساخرة، وأحيانًا الحكايات اليومية." + ) + text_fragment.text_state.font = ap.text.FontRepository.find_font("Tahoma") + text_fragment.text_state.font_size = 14 + text_fragment.text_state.foreground_color = ap.Color.blue + text_fragment.horizontal_alignment = ap.HorizontalAlignment.RIGHT + + page.paragraphs.add(text_fragment) + document.save(output_file_name) +``` + +![Texto de derecha a izquierda](rtl_text.png) + +## Estilo de texto + +### Agregar texto con estilo de fuente + +Este es un ejemplo más avanzado que muestra el estilo del texto, la personalización de Font y texto con formato mixto (usando segmentos de texto en subíndice). Aspose.PDF explica cómo aplicar propiedades de Font como Font family, size, color, bold, italic y underline a un TextFragment. +Además, este fragmento de código muestra cómo usar varios segmentos de texto dentro de un solo fragmento para crear expresiones de texto complejas — por ejemplo, incluyendo caracteres subíndice o superíndice, a menudo requeridos en fórmulas o notaciones científicas. + +1. Crea un nuevo documento y página usando 'Document()', y 'document.pages.add()' para añadir una página en blanco. +1. Crea un TextFragment para texto con estilo sencillo. +1. Definir contenido de texto. +1. Establezca la posición usando las coordenadas Position(x, y). +1. Aplicar estilo mediante la 'text_state property' - font, font_size, foreground_color, font_style, underline. +1. Crea una expresión compleja con varios objetos TextSegment. Cada TextSegment representa una porción de texto que puede tener su propio estilo. Esto te permite construir expresiones, como fórmulas matemáticas o químicas. +1. Defina varios objetos TextState. Uno para el texto principal (text_state_letters). Otro para texto subíndice o superíndice (text_state_index). +1. Combine los segmentos de texto. Añada cada segmento a un 'TextFragment' usando 'segments.append()'. +1. Agrega ambos objetos de texto a la página. Usa 'page.paragraphs.add()' para colocarlos en el documento. +1. Guarda el documento final. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def add_text_with_font_styling(output_file_name): + document = ap.Document() + page = document.pages.add() + + # Initialize an empty TextFragment to build a formula using segments + formula = ap.text.TextFragment() + text_fragment = ap.text.TextFragment("Hello, Aspose!") + text_fragment.position = ap.text.Position(100, 600) + text_fragment.text_state.font = ap.text.FontRepository.find_font("Arial") + text_fragment.text_state.font_size = 14 + text_fragment.text_state.foreground_color = ap.Color.blue + text_fragment.text_state.font_style = ( + ap.text.FontStyles.BOLD | ap.text.FontStyles.ITALIC + ) + text_fragment.text_state.underline = True + text_fragment.horizontal_alignment = ap.HorizontalAlignment.LEFT + + text_state_letters = ap.text.TextState() + text_state_letters.font = ap.text.FontRepository.find_font("Arial") + text_state_letters.font_size = 14 + text_state_letters.foreground_color = ap.Color.blue + text_state_letters.font_style = ap.text.FontStyles.BOLD + + text_state_index = ap.text.TextState() + text_state_index.font = ap.text.FontRepository.find_font("Arial") + text_state_index.font_size = 14 + text_state_index.foreground_color = ap.Color.dark_red + # text_state_index.superscript = True + text_state_index.subscript = True + + position = ap.text.Position(100, 500) + + # Helper function to add segments + def add_segment(text, state): + seg = ap.text.TextSegment(text) + seg.text_state = state + seg.position = position + formula.segments.append(seg) + + add_segment("S = a", text_state_letters) + add_segment("2n", text_state_index) + add_segment(" + a", text_state_letters) + add_segment("2n+1", text_state_index) + add_segment(" + a", text_state_letters) + add_segment("2n+2", text_state_index) + formula.horizontal_alignment = ap.HorizontalAlignment.LEFT + + page.paragraphs.add(text_fragment) + page.paragraphs.add(formula) + document.save(output_file_name) +``` + +![Fragmento de texto mostrado con fuente Arial azul en cursiva que contiene el texto Hello, Aspose! seguido de una fórmula matemática que muestra S = a subíndice 2n \u002B a subíndice 2n\u002B1 \u002B a subíndice 2n\u002B2 con texto principal azul y formato de subíndice rojo](styled_text.png) + +## Agregar texto transparente + +Agregar formas y texto semitransparentes a un documento PDF usando Aspose.PDF for Python via .NET. +Crea un rectángulo de color con opacidad parcial y superpone un TextFragment con un color de primer plano transparente. + +1. Inicializa un objeto Document y agrega una página en blanco para dibujar contenido. +1. Utiliza 'ap.drawing.Graph' para crear un lienzo que te permite dibujar formas. +1. Añade un rectángulo con relleno semitransparente. +1. Prevenir el desplazamiento de posición del lienzo. +1. Agrega el lienzo a la página. Inserta las formas gráficas en la colección de párrafos de la página. +1. Crear un fragmento de texto transparente. +1. Inserte el fragmento de texto en la colección de párrafos de la página. +1. Guarde el documento PDF. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def add_text_transparent(output_file_name): + # Create PDF document + document = ap.Document() + page = document.pages.add() + + # Create Graph object + canvas = ap.drawing.Graph(100.0, 400.0) + + # Create rectangle with semi-transparent fill + rect = ap.drawing.Rectangle(100, 100, 400, 400) + rect.graph_info.fill_color = ap.Color.from_argb(128, 0xC5, 0xB5, 0xFF) + canvas.shapes.add(rect) + + # Prevent position shift + canvas.is_change_position = False + page.paragraphs.add(canvas) + + # Create transparent text + text = ap.text.TextFragment( + "This is the transparent text. " + "This is the transparent text. " + "This is the transparent text." + ) + text.text_state.foreground_color = ap.Color.from_argb(30, 0, 255, 0) + page.paragraphs.add(text) + + document.save(output_file_name) +``` + +### Agregar texto invisible al PDF + +Este ejemplo demuestra cómo crear un documento PDF que contenga texto tanto visible como invisible. El texto invisible sigue formando parte de la estructura del documento pero está oculto a la vista, lo que lo hace útil para incrustar metadatos, etiquetas de accesibilidad o contenido buscable sin afectar el diseño. + +1. Crear documento PDF y página. +1. Cree un fragmento de texto con contenido visible repetido. +1. Agrega un segundo fragmento de texto y márcalo como invisible. +1. Guardar el documento. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def add_text_invisible(output_file_name): + # Create PDF document + document = ap.Document() + page = document.pages.add() + + # Add visible text + text1 = ap.text.TextFragment( + "This is the visible text. This is the visible text. This is the visible text." + ) + page.paragraphs.add(text1) + + # Create transparent text + text2 = ap.text.TextFragment( + "This is the invisible text. " + "This is the invisible text. " + "This is the invisible text." + ) + text2.text_state.invisible = True + page.paragraphs.add(text2) + + document.save(output_file_name) +``` + +### Agregar texto con estilo de borde en PDF + +La biblioteca Aspose.PDF muestra cómo crear un documento PDF que contiene un fragmento de texto con estilo y un borde visible. El método aplica colores de fondo y de primer plano, configuraciones de fuente y un trazo (borde) alrededor del rectángulo de texto para realzar la énfasis visual. + +1. Crea un documento PDF y una página. +1. Crear y posicionar fragmento de texto. Añadir un fragmento de texto con el mensaje y establecer su posición. +1. Aplicar estilo de texto. Establecer la fuente a Times New Roman, tamaño 12. Aplicar un fondo gris claro y un color de primer plano (texto) rojo. +1. Configurar estilo de borde. +1. Agregar texto a la página. Use TextBuilder para añadir el texto con estilo a la página. +1. Guardar el documento. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def add_text_border(output_file_name): + # Create PDF document + document = ap.Document() + # Get particular page + page = document.pages.add() + # Create text fragment + text_fragment = ap.text.TextFragment("This is sample text with border.") + text_fragment.position = ap.text.Position(10, 700) + + # Set text properties + text_fragment.text_state.font = ap.text.FontRepository.find_font("Times New Roman") + text_fragment.text_state.font_size = 12 + text_fragment.text_state.background_color = ap.Color.light_gray + text_fragment.text_state.foreground_color = ap.Color.red + # Set StrokingColor property for drawing border (stroking) around text rectangle. + # Note: This only affects the border if draw_text_rectangle_border is set to True. + text_fragment.text_state.stroking_color = ap.Color.dark_red + # Enable drawing of the text rectangle border + text_fragment.text_state.draw_text_rectangle_border = True + + text_builder = ap.text.TextBuilder(page) + text_builder.append_text(text_fragment) + + # Save PDF document + document.save(output_file_name) +``` + +### Agregar texto tachado a un PDF + +Agregar formato de tachado (strikethrough) a un fragmento de texto en un documento PDF. El texto tachado es útil para indicar eliminaciones, revisiones o énfasis en documentos anotados. + +1. Crea un nuevo documento y página usando 'Document()', y 'document.pages.add()' para añadir una página en blanco. +1. Crear y aplicar estilo al fragmento de texto. +1. Aplicar formato de color y tachado. Establecer el fondo a gris claro, el color del texto a rojo y habilitar el tachado. +1. Posicionar el Texto. +1. Use 'TextBuilder' para agregar el texto con estilo a la página. +1. Guardar el documento. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def add_strikeout_text(output_file_name): + # Create PDF document + document = ap.Document() + page = document.pages.add() + + # Create text fragment + text_fragment = ap.text.TextFragment("This is sample strikeout text.") + # Set text properties + text_fragment.text_state.font_size = 12 + text_fragment.text_state.font = ap.text.FontRepository.find_font("TimesNewRoman") + text_fragment.text_state.background_color = ap.Color.light_gray + text_fragment.text_state.foreground_color = ap.Color.red + text_fragment.text_state.strike_out = True + text_fragment.text_state.font_style = ap.text.FontStyles.BOLD + text_fragment.position = ap.text.Position(100, 600) + + # Create TextBuilder object + text_builder = ap.text.TextBuilder(page) + text_builder.append_text(text_fragment) + + # Save PDF document + document.save(output_file_name) +``` + +## Efectos avanzados de color + +### Aplicar un degradado axial al texto en un PDF + +Aspose.PDF for Python via .NET demuestra cómo aplicar un efecto de degradado lineal al texto en un documento PDF. El degradado axial transita suavemente de rojo a azul a lo largo del texto, creando un encabezado visualmente impactante. Esta técnica es ideal para títulos estilizados, branding o elementos decorativos en diseños de documentos PDF. + +1. Inicializa un nuevo documento y agrega una página en blanco. +1. Crear y dar estilo al TextFragment. Añadir título, establecer posición, fuente y tamaño. +1. Aplicar sombreado de degradado axial con 'GradientAxialShading'. Establecer el color de primer plano usando GradientAxialShading de rojo a azul. +1. Agregar estilo subrayado. +1. Inserte el fragmento de texto con estilo en la página. +1. Guardar el documento. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def apply_gradient_axial_shading_to_text(output_file_name): + # Create PDF document + document = ap.Document() + page = document.pages.add() + + text_fragment = ap.text.TextFragment("PDF TITLE") + text_fragment.position = ap.text.Position(100, 600) + text_fragment.text_state.font_size = 36 + text_fragment.text_state.font = ap.text.FontRepository.find_font("Arial Bold") + + text_fragment.text_state.foreground_color = ap.Color() + text_fragment.text_state.foreground_color.pattern_color_space = ( + ap.drawing.GradientAxialShading(ap.Color.red, ap.Color.blue) + ) + text_fragment.text_state.underline = True + + page.paragraphs.add(text_fragment) + document.save(output_file_name) +``` + +### Aplicar un degradado radial al texto en un PDF + +Un degradado radial crea una transición de color circular que se irradia desde el centro del texto, ofreciendo una opción de estilo visualmente dinámica para títulos, encabezados o elementos decorativos. + +1. Inicializa un nuevo documento y agrega una página en blanco. +1. Crear y dar estilo al TextFragment. Añadir título, establecer posición, fuente y tamaño. +1. Aplicar degradado radial con 'GradientRadialShading'. Establecer el color de primer plano usando GradientRadialShading de rojo a azul. +1. Agregar estilo subrayado. +1. Inserte el fragmento de texto con estilo en la página. +1. Guardar el documento. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def apply_gradient_radial_shading_to_text(output_file_name): + # Create PDF document + document = ap.Document() + page = document.pages.add() + + text_fragment = ap.text.TextFragment("PDF TITLE") + text_fragment.position = ap.text.Position(100, 600) + text_fragment.text_state.font_size = 36 + text_fragment.text_state.font = ap.text.FontRepository.find_font("Arial Bold") + + # Apply radial gradient shading (red to blue) + text_fragment.text_state.foreground_color = ap.Color() + text_fragment.text_state.foreground_color.pattern_color_space = ( + ap.drawing.GradientRadialShading(ap.Color.red, ap.Color.blue) + ) + text_fragment.text_state.underline = True + + page.paragraphs.add(text_fragment) + document.save(output_file_name) +``` + +![Aplicar sombreado de degradado radial](gradient_radial_shading.png) + +## Fragmentos HTML y LaTeX + +### Agregar texto HTML al documento PDF + +La biblioteca Aspose.PDF for Python via .NET permite insertar contenido con formato HTML en un documento PDF mediante la clase HtmlFragment. Al usar etiquetas HTML, puedes renderizar texto con estilo, estructurado o similar a fórmulas directamente en un PDF. + +1. Crea un nuevo documento y página usando 'Document()', y 'document.pages.add()' para añadir una página en blanco. +1. Cree una instancia de la clase HtmlFragment y pase su cadena HTML como parámetro. +1. Agrega el fragmento a la página usando 'page.paragraphs.add()' para insertar el contenido HTML. +1. Guardar el PDF. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def add_text_html_fragment(output_file_name): + # Create a new document + document = ap.Document() + page = document.pages.add() + + # Add a text fragment at a specific position + text_fragment = ap.HtmlFragment("
S=a2n+a2
")
+
+    page.paragraphs.add(text_fragment)
+    document.save(output_file_name)
+```
+
+![Agregar texto HTML a un documento PDF](html_fragment.png)
+
+### Agregar fragmento HTML con estilo y varios formatos a un documento PDF
+
+Podemos definir un fragmento HTML y establecer el estilo del texto directamente usando etiquetas HTML. Insertar contenido HTML con estilo en un documento PDF. Este fragmento de código crea un nuevo archivo PDF, agrega una página, inserta un fragmento HTML con varios elementos de formato (encabezados, párrafos, enlaces y estilos en línea), y guarda el resultado en la ruta especificada.
+
+1. Inicializa un nuevo objeto Document para representar el PDF.
+1. Agrega una página en blanco al documento donde se colocará el contenido HTML.
+1. Preparar contenido HTML. La cadena HTML contiene un encabezado h1, un párrafo de color verde con texto en negrita, cursiva y subrayado, y un hipervínculo a un sitio web con tamaño de fuente aumentado.
+1. Crear fragmento HTML. Envuelva la cadena HTML en un objeto HtmlFragment.
+1. Insertar HTML en Page. Añade el fragmento HTML a la colección de párrafos de Page, renderizando el HTML como contenido nativo de PDF.
+1. Guardar el documento.
+
+```python
+import math
+import sys
+import os
+import aspose.pdf as ap
+
+def add_html_fragment(output_file_name):
+    document = ap.Document()
+    page = document.pages.add()
+    html_content = """
+        

Hello, Aspose!

+

This is a sample paragraph with bold, italic, and underlined text.

+

This paragraph is green.

+ Visit Aspose + """ + html_fragment = ap.HtmlFragment(html_content) + page.paragraphs.add(html_fragment) + document.save(output_file_name) +``` + +![Agregar contenido HTML a un documento PDF](html_content.png) + +### Agregar fragmento HTML con estado de texto sobrescrito + +Como vimos en el ejemplo anterior, es posible establecer estilos directamente en el código HTML. Esto tiene sus ventajas, pero también algunas desventajas. Supongamos que estamos trabajando con el HTML de un cliente y queremos unificar la apariencia de nuestra salida. +En este caso, podemos sobrescribir el estilo del cliente usando nuestro propio TextState, como se muestra en el siguiente ejemplo. + +1. Crea un nuevo documento y página usando 'Document()', y 'document.pages.add()' para añadir una página en blanco. +1. Preparar contenido HTML. La cadena HTML contiene un encabezado h1 con fuente Verdana, un párrafo de color verde con texto en negrita, cursiva y subrayado, y un hipervínculo a un sitio web con un tamaño de fuente mayor. +1. Crear fragmento HTML. Envuelva la cadena HTML en un objeto HtmlFragment. +1. Anular el formato de texto. Crear un objeto TextState y establecer la Font, la Font Size y el Color del texto. +1. Agrega el fragmento HTML a la colección de párrafos de la página. +1. Guardar el documento. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def add_html_fragment_override_text_state(output_file_name): + document = ap.Document() + page = document.pages.add() + html_content = """ +

Hello, Aspose!

+

This is a sample paragraph with bold, italic, and underlined text.

+

This paragraph is green.

+ Visit Aspose + """ + html_fragment = ap.HtmlFragment(html_content) + html_fragment.text_state = ap.text.TextState() + html_fragment.text_state.font = ap.text.FontRepository.find_font("Arial") + html_fragment.text_state.font_size = 14 + html_fragment.text_state.foreground_color = ap.Color.red + + page.paragraphs.add(html_fragment) + document.save(output_file_name) +``` + +![Agregar estado de texto de anulación de fragmento HTML](html_override.png) + +### Agregar texto LaTeX al documento PDF + +Agregar expresiones matemáticas con formato LaTeX a un documento PDF utilizando la clase TeXFragment en Aspose.PDF for Python via .NET. +LaTeX es un potente sistema de composición tipográfica ampliamente utilizado para crear documentos científicos y matemáticos. Al usar TeXFragment, puedes renderizar directamente la notación y los símbolos matemáticos de LaTeX dentro de una página PDF. + +1. Crea un nuevo documento y página usando 'Document()', y 'document.pages.add()' para añadir una página en blanco. +1. Utilice la clase TeXFragment para renderizar la sintaxis LaTeX directamente. +1. Agrega el contenido LaTeX al diseño del PDF con 'page.paragraphs.add()'. +1. Guardar el PDF. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def add_text_latex_fragment(output_file_name): + # Create a new document + document = ap.Document() + page = document.pages.add() + + # Add a text fragment at a specific position + text_fragment = ap.TeXFragment( + "\\underbrace{\\overbrace{a+b}^6 \\cdot \\overbrace{c+d}^7}_\\text{example of text} = 42" + ) + + page.paragraphs.add(text_fragment) + document.save(output_file_name) +``` + +![Expresión matemática compleja mostrada en un PDF que muestra la fórmula LaTeX con notación de overbrace sobre (a+b)⁶, notación de underbrace bajo toda la expresión (a+b)⁶ · (c+d)⁷, etiquetada como ejemplo de texto, y es igual a 42. La fórmula demuestra tipografía matemática avanzada con espaciado adecuado y estilo de corchetes típico de la renderización LaTeX.](latex_fragment.png) + +## Fuentes personalizadas + +### Usar una Font personalizada desde un archivo + +Este ejemplo le permite añadir texto a un archivo PDF usando una fuente OpenType personalizada en Aspose.PDF for Python via .NET. Muestra cómo crear un nuevo documento PDF, posicionar el texto con precisión en la página y aplicar un formato personalizado como tipo de fuente, tamaño, color y estilo cursiva. + +1. Crea un nuevo documento PDF y agrega una página. +1. Define el contenido de texto que desea agregar al PDF. +1. Establecer la posición del texto. +1. Agrega el TextFragment a la página. +1. Guarde el documento PDF. + +Esta función funciona no solo con fuentes OTF, sino también con fuentes TTF. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def use_custom_font_from_file(output_file_name): + font_path = os.path.join(FONT_DIR, "BriosoPro Italic.otf") + document = ap.Document() + page = document.pages.add() + + fragment = ap.text.TextFragment("Hello, Aspose!") + fragment.position = ap.text.Position(100, 600) + fragment.text_state.font = ap.text.FontRepository.open_font(font_path) + fragment.text_state.font_size = 24 + fragment.text_state.foreground_color = ap.Color.blue + fragment.text_state.font_style = ap.text.FontStyles.ITALIC + + page.paragraphs.add(fragment) + document.save(output_file_name) +``` + +![Fragmento de texto mostrado en un documento PDF que muestra Hello, Aspose! renderizado en fuente BriosoPro azul itálica, demostrando la integración de fuentes OpenType personalizadas y las capacidades de estilo dentro del formateado de texto PDF](custom_font.png) + +### Usa una Font personalizada desde un flujo + +Este fragmento de código muestra cómo agregar texto a un documento PDF usando una fuente OpenType (OTF) personalizada incrustada con Aspose.PDF for Python via .NET. Muestra cómo abrir un archivo de fuente como flujo, incrustarlo en el PDF para garantizar la disponibilidad de la fuente en diferentes sistemas, y aplicar formato de texto como tamaño de fuente, color y estilo cursiva. Este enfoque es ideal para crear PDFs visualmente consistentes que preserven la tipografía incluso cuando se comparten o se visualizan en dispositivos sin la fuente instalada. + +1. Cargar archivo Font como un flujo binario. +1. Abra e incruste la fuente usando 'FontRepository.open_font'. +1. Crea un nuevo documento PDF y agrega una página. +1. Agregar un fragmento de texto con estilo: + - Fuente personalizada incrustada. + - Estilo cursiva y color azul. + - Tamaño de fuente específico y posición. +1. Guarde el documento final en una ruta de salida especificada. + +```python +import math +import sys +import os +import aspose.pdf as ap + +def use_custom_font_from_stream(output_file_name): + font_path = os.path.join(FONT_DIR, "BriosoPro Italic.otf") + with open(font_path, "rb") as font_stream: + font = ap.text.FontRepository.open_font(font_stream, ap.text.FontTypes.OTF) + font.is_embedded = True + + document = ap.Document() + page = document.pages.add() + + fragment = ap.text.TextFragment("Hello, Aspose!") + fragment.position = ap.text.Position(100, 600) + fragment.text_state.font = font + fragment.text_state.font_size = 14 + fragment.text_state.foreground_color = ap.Color.blue + fragment.text_state.font_style = ap.text.FontStyles.ITALIC + + page.paragraphs.add(fragment) + document.save(output_file_name) +``` + +Incorporar fuentes garantiza una renderización coherente en todas las plataformas, lo que hace que este método sea ideal para la marca, la fidelidad del diseño y el soporte multilingüe. + +## Temas de texto relacionados + +- [Trabajar con texto en PDF usando Python](/pdf/es/python-net/working-with-text/) +- [Formatear texto PDF en Python](/pdf/es/python-net/text-formatting-inside-pdf/) +- [Reemplazar texto en PDF mediante Python](/pdf/es/python-net/replace-text-in-pdf/) +- [Buscar y extraer texto PDF en Python](/pdf/es/python-net/search-and-get-text-from-pdf/) diff --git a/es/python-net/advanced-operations/working-with-text/add-tooltip-to-text/_index.md b/es/python-net/advanced-operations/working-with-text/add-tooltip-to-text/_index.md index 349387b4a..f4fd06513 100644 --- a/es/python-net/advanced-operations/working-with-text/add-tooltip-to-text/_index.md +++ b/es/python-net/advanced-operations/working-with-text/add-tooltip-to-text/_index.md @@ -1,295 +1,187 @@ --- -title: Tooltip en PDF usando Python -linktitle: Tooltip en PDF +title: Agregar información sobre herramientas al texto PDF en Python +linktitle: Información sobre herramientas PDF type: docs weight: 20 url: /es/python-net/pdf-tooltip/ -description: Aprende cómo agregar un tooltip al fragmento de texto en PDF usando Python y Aspose.PDF -lastmod: "2024-02-17" +description: Aprenda cómo agregar información sobre herramientas a fragmentos de texto en documentos PDF con Python. +lastmod: "2026-05-05" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar información sobre herramientas interactivas a fragmentos de texto PDF usando Python +Abstract: Este artículo ofrece dos ejemplos de Python para agregar ayuda interactiva al texto PDF usando Aspose.PDF for Python via .NET. El primer ejemplo añade descripciones emergentes a fragmentos de texto coincidentes al colocar elementos `ButtonField` invisibles y establecer `alternate_name`. El segundo ejemplo crea un `TextBoxField` oculto que aparece al pasar el cursor al conectar eventos `HideAction` a un `ButtonField` invisible. --- - +## Agregar descripción emergente al texto buscado en un PDF -## Agregar Tooltip al Texto Buscado mediante un Botón Invisible +Este fragmento de código muestra cómo superponer invisible [`ButtonField`](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/buttonfield/) elementos en específico [`TextFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/) objetos en un PDF para mostrar información sobre herramientas cuando el usuario pasa el cursor sobre ellos. Soporta tanto mensajes de información sobre herramientas cortos como largos utilizando el `alternate_name` propiedad de `ButtonField`. -Este código demuestra cómo agregar tooltips a fragmentos de texto específicos en un documento PDF usando Aspose.PDF. Los tooltips se muestran cuando el cursor del ratón se coloca sobre el texto correspondiente. +Utilice esta página cuando necesite hacer el texto PDF más interactivo añadiendo ayuda emergente, explicaciones en línea o notas contextuales. -El siguiente fragmento de código te mostrará cómo lograr esta funcionalidad: +1. Crear un nuevo [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Guarde el documento inicial. +1. Vuelva a abrir el documento PDF. +1. Buscar texto objetivo usando [`TextFragmentAbsorber`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber/). +1. Añadir un invisible [`ButtonField`](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/buttonfield/) con una descripción breve. +1. Buscar el segundo texto objetivo. +1. Añadir un invisible [`ButtonField`](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/buttonfield/) con una descripción larga sobre el fragmento coincidente. +1. Guarda el documento final. ```python - - import aspose.pdf as ap - - document = ap.Document() - document.pages.add().paragraphs.add( - ap.text.TextFragment("Mueve el cursor del ratón aquí para mostrar un tooltip") - ) - document.pages[1].paragraphs.add( - ap.text.TextFragment( - "Mueve el cursor del ratón aquí para mostrar un tooltip muy largo" +import aspose.pdf as ap +import aspose.pydrawing as drawing +import sys +from os import path + +# region PDF Tooltip +def add_tool_tip_to_searched_text(outfile): + # Create PDF document + with ap.Document() as document: + document.pages.add().paragraphs.add( + ap.text.TextFragment("Move the mouse cursor here to display a tooltip") ) - ) - document.save(output_pdf) - - # Abre el documento con texto - document = ap.Document(output_pdf) - # Crea un objeto TextAbsorber para encontrar todas las frases que coinciden con la expresión regular - absorber = ap.text.TextFragmentAbsorber( - "Mueve el cursor del ratón aquí para mostrar un tooltip" - ) - # Acepta el absorber para las páginas del documento - document.pages.accept(absorber) - # Obtén los fragmentos de texto extraídos - text_fragments = absorber.text_fragments - - # Recorre los fragmentos - for fragment in text_fragments: - # Crea un botón invisible en la posición del fragmento de texto - field = ap.forms.ButtonField(fragment.page, fragment.rectangle) - # El valor de alternate_name se mostrará como tooltip por una aplicación de visualización - field.alternate_name = "Tooltip para el texto." - # Agrega el campo de botón al documento - document.form.add(field) - - # A continuación, será una muestra de un tooltip muy largo - absorber = ap.text.TextFragmentAbsorber( - "Mueve el cursor del ratón aquí para mostrar un tooltip muy largo" - ) - document.pages.accept(absorber) - text_fragments = absorber.text_fragments - - for fragment in text_fragments: - field = ap.forms.ButtonField(fragment.page, fragment.rectangle) - # Establece texto muy largo - field.alternate_name = ( - "Lorem ipsum dolor sit amet, consectetur adipiscing elit," - " sed do eiusmod tempor incididunt ut labore et dolore magna" - " aliqua. Ut enim ad minim veniam, quis nostrud exercitation" - " ullamco laboris nisi ut aliquip ex ea commodo consequat." - " Duis aute irure dolor in reprehenderit in voluptate velit" - " esse cillum dolore eu fugiat nulla pariatur. Excepteur sint" - " occaecat cupidatat non proident, sunt in culpa qui officia" - " deserunt mollit anim id est laborum." + document.pages[1].paragraphs.add( + ap.text.TextFragment( + "Move the mouse cursor here to display a very long tooltip" + ) ) - document.form.add(field) + document.save(outfile) - # Guarda el documento - document.save(output_pdf) + # Open document with text + with ap.Document(outfile) as document: + # Create TextAbsorber object to find all the phrases matching the regular expression + absorber = ap.text.TextFragmentAbsorber( + "Move the mouse cursor here to display a tooltip" + ) + # Accept the absorber for the document pages + document.pages.accept(absorber) + # Get the extracted text fragments + text_fragments = absorber.text_fragments + + # Loop through the fragments + for fragment in text_fragments: + # Create invisible button on text fragment position + field = ap.forms.ButtonField(fragment.page, fragment.rectangle) + # alternate_name value will be displayed as tooltip by a viewer application + field.alternate_name = "Tooltip for text." + # Add button field to the document + document.form.add(field) + + # Next will be sample of very long tooltip + absorber = ap.text.TextFragmentAbsorber( + "Move the mouse cursor here to display a very long tooltip" + ) + document.pages.accept(absorber) + text_fragments = absorber.text_fragments + + for fragment in text_fragments: + field = ap.forms.ButtonField(fragment.page, fragment.rectangle) + # Set very long text + field.alternate_name = ( + "Lorem ipsum dolor sit amet, consectetur adipiscing elit," + " sed do eiusmod tempor incididunt ut labore et dolore magna" + " aliqua. Ut enim ad minim veniam, quis nostrud exercitation" + " ullamco laboris nisi ut aliquip ex ea commodo consequat." + " Duis aute irure dolor in reprehenderit in voluptate velit" + " esse cillum dolore eu fugiat nulla pariatur. Excepteur sint" + " occaecat cupidatat non proident, sunt in culpa qui officia" + " deserunt mollit anim id est laborum." + ) + document.form.add(field) + + # Save document + document.save(outfile) ``` +## Crear un bloque de texto oculto que aparece al pasar el cursor en un PDF -## Crear un Bloque de Texto Oculto y Mostrarlo al Pasar el Ratón +Agregar texto flotante interactivo a un documento PDF. Se superpone a un invisible [`ButtonField`](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/buttonfield/) en una frase objetivo y revela un oculto [`TextBoxField`](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/textboxfield/) cuando el usuario pasa el cursor sobre él. Esta técnica es ideal para ayuda contextual, anotaciones o presentación de contenido dinámico. -Este fragmento de código en Python muestra cómo agregar texto flotante a un documento PDF, que aparece cuando el cursor del ratón se coloca sobre un área específica. - -Primero, se crea un nuevo documento PDF y se le añade un párrafo que contiene el texto "Mueva el cursor del ratón aquí para mostrar texto flotante". Luego, se guarda el documento. - -A continuación, se vuelve a abrir el documento guardado y se crea un objeto TextAbsorber para encontrar el fragmento de texto previamente añadido. Este fragmento de texto se utiliza entonces para definir la posición y las características del campo de texto flotante. - -Se crea un objeto TextBoxField para representar el campo de texto flotante, y sus propiedades como posición, valor, estado de solo lectura y visibilidad se configuran en consecuencia. Además, se asigna un nombre único y características de apariencia al campo. - -El campo de texto flotante se añade al formulario del documento, y se crea un campo de botón invisible en la posición del fragmento de texto original. - HideAction events se asignan al campo de botón, especificando que el campo de texto flotante debe aparecer cuando el cursor del mouse entra en su vecindad y desaparecer cuando el cursor sale. - -Finalmente, el campo de botón se agrega al formulario del documento y se guarda el documento modificado. - -Este fragmento de código proporciona un método para crear elementos de texto flotante interactivos en un documento PDF usando Aspose.PDF para Python. +1. Crear un nuevo documento PDF. +1. Guarde el PDF para que pueda ser reabierto para la configuración de interactividad. +1. Vuelva a abrir el documento PDF. +1. Ubique el texto objetivo usando [`TextFragmentAbsorber`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber/). +1. Crear un oculto [`TextBoxField`](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/textboxfield/). +1. Agregar el campo oculto al documento [`Form`](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/form/) colección. +1. Crear un invisible [`ButtonField`](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/buttonfield/). +1. Asignar acciones del ratón ("`on_enter`, `on_exit`) usando [`HideAction`](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/hideaction/) para mostrar/ocultar el campo oculto. +1. Guarda el documento final. ```python - - import aspose.pdf as ap - - document = ap.Document() - document.pages.add().paragraphs.add( - ap.text.TextFragment("Mueva el cursor del mouse aquí para mostrar el texto flotante") - ) - document.save(output_pdf) - - # Abrir documento con texto - document = ap.Document(output_pdf) - # Crear objeto TextAbsorber para encontrar todas las frases que coincidan con la expresión regular - absorber = ap.text.TextFragmentAbsorber( - "Mueva el cursor del mouse aquí para mostrar el texto flotante" - ) - # Aceptar el absorbedor para las páginas del documento - document.pages.accept(absorber) - # Obtener el primer fragmento de texto extraído - text_fragments = absorber.text_fragments - fragment = text_fragments[1] - - # Crear campo de texto oculto para texto flotante en el rectángulo especificado de la página - floating_field = ap.forms.TextBoxField( - fragment.page, ap.Rectangle(100.0, 700.0, 220.0, 740.0, False) - ) - # Establecer texto a mostrar como valor del campo - floating_field.value = 'Este es el "campo de texto flotante".' - # Recomendamos hacer que el campo sea 'solo lectura' para este escenario - floating_field.read_only = True - # Establecer la bandera 'oculto' para hacer que el campo sea invisible al abrir el documento - floating_field.flags |= ap.annotations.AnnotationFlags.HIDDEN - - # No es necesario pero permitido establecer un nombre de campo único - floating_field.partial_name = "FloatingField_1" - - # No es necesario, pero mejora establecer características de apariencia del campo - floating_field.default_appearance = ap.annotations.DefaultAppearance( - "Helv", 10, ap.Color.blue.to_rgb() - ) - floating_field.characteristics.background = ap.Color.light_blue.to_rgb() - floating_field.characteristics.border = ap.Color.dark_blue.to_rgb() - floating_field.border = ap.annotations.Border(floating_field) - floating_field.border.width = 1 - floating_field.multiline = True - - # Agregar campo de texto al documento - document.form.add(floating_field) - # Crear botón invisible en la posición del fragmento de texto - button_field = ap.forms.ButtonField(fragment.page, fragment.rectangle) - # Crear nueva acción de ocultar para el campo (anotación) especificado y la bandera de invisibilidad. - # (También puede referirse al campo flotante por el nombre si lo especificó anteriormente.) - # Agregar acciones en la entrada/salida del mouse en el campo de botón invisible - - button_field.actions.on_enter = ap.annotations.HideAction( - floating_field.partial_name, False - ) - button_field.actions.on_exit = ap.annotations.HideAction( - floating_field.partial_name - ) - - # Agregar campo de botón al documento - document.form.add(button_field) - - # Guardar documento - document.save(output_pdf) +import aspose.pdf as ap +import aspose.pydrawing as drawing +import sys +from os import path + +def create_hidden_text_block(outfile): + # Create PDF document + with ap.Document() as document: + # Add paragraph with text + document.pages.add().paragraphs.add( + ap.text.TextFragment("Move the mouse cursor here to display floating text") + ) + # Save PDF document + document.save(outfile) + + # Open document with text + with ap.Document(outfile) as document: + # Create TextAbsorber object to find all the phrases matching the regular expression + absorber = ap.text.TextFragmentAbsorber( + "Move the mouse cursor here to display floating text" + ) + # Accept the absorber for the document pages + document.pages.accept(absorber) + # Get the first extracted text fragment + text_fragments = absorber.text_fragments + fragment = text_fragments[1] + + # Create hidden text field for floating text in the specified rectangle of the page + floating_field = ap.forms.TextBoxField( + fragment.page, ap.Rectangle(100.0, 700.0, 220.0, 740.0, False) + ) + # Set text to be displayed as field value + floating_field.value = 'This is the "floating text field".' + # We recommend to make field 'readonly' for this scenario + floating_field.read_only = True + # Set 'hidden' flag to make field invisible on document opening + floating_field.flags |= ap.annotations.AnnotationFlags.HIDDEN + + # Setting a unique field name isn't necessary but allowed + floating_field.partial_name = "FloatingField_1" + + # Setting characteristics of field appearance isn't necessary but makes it better + floating_field.default_appearance = ap.annotations.DefaultAppearance( + "Helv", 10, drawing.Color.blue + ) + floating_field.characteristics.background = drawing.Color.light_blue + floating_field.characteristics.border = drawing.Color.dark_blue + floating_field.border = ap.annotations.Border(floating_field) + floating_field.border.width = 1 + floating_field.multiline = True + + # Add text field to the document + document.form.add(floating_field) + # Create invisible button on text fragment position + button_field = ap.forms.ButtonField(fragment.page, fragment.rectangle) + # Create new hide action for specified field (annotation) and invisibility flag. + # (You also may refer floating field by the name if you specified it above.) + # Add actions on mouse enter/exit at the invisible button field + + button_field.actions.on_enter = ap.annotations.HideAction(floating_field, False) + button_field.actions.on_exit = ap.annotations.HideAction(floating_field) + + # Add button field to the document + document.form.add(button_field) + + # Save document + document.save(outfile) ``` - \ No newline at end of file +## Temas de texto relacionados + +- [Trabajar con texto en PDF usando Python](/pdf/es/python-net/working-with-text/) +- [Utilice FloatingBox para el diseño de texto PDF en Python](/pdf/es/python-net/floating-box/) +- [Buscar y extraer texto PDF en Python](/pdf/es/python-net/search-and-get-text-from-pdf/) +- [Agregar texto al PDF](/pdf/es/python-net/add-text-to-pdf-file/) diff --git a/es/python-net/advanced-operations/working-with-text/determine-line-break/_index.md b/es/python-net/advanced-operations/working-with-text/determine-line-break/_index.md deleted file mode 100644 index 8b6605e9f..000000000 --- a/es/python-net/advanced-operations/working-with-text/determine-line-break/_index.md +++ /dev/null @@ -1,185 +0,0 @@ ---- -title: Determinar Salto de Línea -linktitle: Determinar Salto de Línea -type: docs -weight: 70 -url: /es/python-net/determine-line-break/ -description: Aprende más sobre cómo determinar un salto de línea de un TextFragment de varias líneas usando Python -lastmod: "2024-02-17" -sitemap: - changefreq: "weekly" - priority: 0.7 ---- - - - -## Seguimiento del Salto de Línea de TextFragment Multilínea - -El siguiente fragmento de código muestra cómo rastrear el comportamiento de salto de línea de un TextFragment multilínea dentro de un documento PDF. - -La función track_line_breaking() está definida para demostrar esta funcionalidad. Comienza especificando las rutas de archivo de salida tanto para el documento PDF generado como para un archivo de texto correspondiente que contendrá información sobre el salto de línea. - -Dentro de la función, se crea un nuevo objeto de documento PDF y se añade una nueva página a él. Posteriormente, se emplea un bucle para generar cuatro instancias de un TextFragment que contiene un texto con saltos de línea ("\r\n") insertados dentro de la cadena para simular texto multilínea. - -Cada TextFragment se configura con un tamaño de fuente de 20 puntos antes de ser añadido a los párrafos de la página. - -Después de que todos los TextFragments son añadidos, el documento se guarda. - -La función luego procede a extraer notificaciones sobre el salto de línea de la segunda página del documento PDF generado utilizando el método get_notifications(). - Estas notificaciones se escriben en un archivo de texto especificado anteriormente. - -Este fragmento de código ilustra cómo crear un documento PDF que contiene texto de varias líneas y luego extraer información sobre el comportamiento de los saltos de línea, proporcionando información sobre cómo se organiza el texto dentro del documento. - -```python - - import aspose.pdf as ap - - def track_line_breaking(): - """Rastrear los saltos de línea de un TextFragment de varias líneas""" - output_pdf = DIR_OUTPUT_TEXTS + "track_line_breaking.pdf" - output_txt = DIR_OUTPUT_TEXTS + "track_line_breaking.txt" - - # Crear un nuevo objeto de documento - document = ap.Document() - page = document.pages.add() - - for i in range(4): - text = ap.text.TextFragment( - "Lorem ipsum \r\ndolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." - ) - text.text_state.font_size = 20 - page.paragraphs.add(text) - document.save(output_pdf) - - notifications = document.pages[1].get_notifications() - with open(output_txt, "w") as f: - f.write(notifications) -``` - - \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-text/floating-box/_index.md b/es/python-net/advanced-operations/working-with-text/floating-box/_index.md new file mode 100644 index 000000000..3bdc5dcad --- /dev/null +++ b/es/python-net/advanced-operations/working-with-text/floating-box/_index.md @@ -0,0 +1,304 @@ +--- +title: Usar FloatingBox para el diseño de PDF en Python +linktitle: Usando FloatingBox +type: docs +weight: 30 +url: /es/python-net/floating-box/ +description: Aprende a usar FloatingBox para el diseño de texto, contenido de varias columnas y posicionamiento preciso en documentos PDF con Python. +lastmod: "2026-05-05" +sitemap: + changefreq: "monthly" + priority: 0.5 +TechArticle: true +AlternativeHeadline: Crea y posiciona contenedores FloatingBox con estilo en PDF con Python. +Abstract: Este artículo explica cómo usar FloatingBox en Aspose.PDF for Python via .NET. Aprenda cómo colocar texto y otro contenido en contenedores flotantes con estilo, controlar el diseño, los bordes, la alineación y el recorte, y crear diseños de página PDF más estructurados en Python. +--- + +## Uso básico de FloatingBox + +El [`FloatingBox`](https://reference.aspose.com/pdf/python-net/aspose.pdf/floatingbox/) Una clase es un contenedor para colocar texto y otro contenido en una página PDF. Le brinda un mayor control sobre el diseño, los bordes y el estilo que los párrafos de texto habituales. Si el contenido supera el tamaño del cuadro, el comportamiento de recorte se controla mediante la configuración del cuadro. + +Utilice esta página cuando necesite contenedores de texto estructurados, diseños de varias columnas y posicionamiento preciso en documentos PDF con Aspose.PDF for Python via .NET. + +1. Crear un nuevo [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Añadir un [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) al documento. +1. Cree un [`FloatingBox`](https://reference.aspose.com/pdf/python-net/aspose.pdf/floatingbox/). +1. Establecer el borde de la caja usando [`BorderInfo`](https://reference.aspose.com/pdf/python-net/aspose.pdf/borderinfo/) y [`BorderSide`](https://reference.aspose.com/pdf/python-net/aspose.pdf/borderside/). +1. Repetición de cuadro de control con el [`is_need_repeating`](https://reference.aspose.com/pdf/python-net/aspose.pdf/floatingbox/#properties) propiedad. +1. Agregar contenido de texto usando [`TextFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/). +1. Agregar el `FloatingBox` al [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +1. Guarda el documento PDF final usando [`Document.save()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods). + +```python +import aspose.pdf as ap + +def create_and_add_floating_box(outfile): + # Create PDF document + with ap.Document() as document: + # Add page to pages collection of PDF + page = document.pages.add() + # Create and fill box + box = ap.FloatingBox(400, 30) + box.border = ap.BorderInfo(ap.BorderSide.ALL, 1.5, ap.Color.dark_green) + box.is_need_repeating = False + phrase = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quam odio, sollicitudin ac mauris vel, suscipit pellentesque nisi." + box.paragraphs.add(ap.text.TextFragment(phrase)) + # Add box + page.paragraphs.add(box) + document.save(outfile) +``` + +En el ejemplo anterior, el `FloatingBox` se crea con un ancho de 400 pt y una altura de 30 pt. +El texto supera intencionalmente la altura disponible, por lo que parte de él está recortado. + +![Imagen 1](image01.png) + +El [`is_need_repeating`](https://reference.aspose.com/pdf/python-net/aspose.pdf/floatingbox/#properties) propiedad con un valor de `False` limita la renderización de texto a una sola página. + +Si establece esta propiedad en `True`, el texto se refluye a páginas subsecuentes en la misma posición. + +![Imagen 2](image02.png) + +## Funciones avanzadas de FloatingBox + +### Compatibilidad multicolumna + +#### Diseño de varias columnas (caso simple) + +`FloatingBox` admite diseño de varias columnas. Para crear dicho diseño, debe definir los valores de [`ColumnInfo`](https://reference.aspose.com/pdf/python-net/aspose.pdf/columninfo/) propiedades. + +* `column_widths` es una cadena que define el ancho de cada columna en puntos. +* `column_spacing` es una cadena que define el ancho del espacio entre columnas. +* `column_count` es el número de columnas. + +```python +import sys +import aspose.pdf as ap +from os import path + +def multi_column_layout(outfile): + # Create PDF document + with ap.Document() as document: + # Add page to pages collection of PDF + page = document.pages.add() + # Set margin settings + page.page_info.margin = ap.MarginInfo(36, 18, 36, 18) + column_count = 3 + spacing = 10 + width = ( + page.page_info.width + - page.page_info.margin.left + - page.page_info.margin.right + - (column_count - 1) * spacing + ) + column_width = width / 3 + # Create FloatingBox + box = ap.FloatingBox() + box.is_need_repeating = True + box.column_info.column_widths = f"{column_width} {column_width} {column_width}" + box.column_info.column_spacing = f"{spacing}" + box.column_info.column_count = 3 + phrase = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quam odio, sollicitudin ac mauris vel, suscipit pellentesque nisi." + paragraphs = [ + phrase, + phrase, + phrase, + phrase, + phrase, + phrase, + phrase, + phrase, + phrase, + phrase, + ] + for paragraph in paragraphs: + box.paragraphs.add(ap.text.TextFragment(paragraph)) + # Add a box to a page + page.paragraphs.add(box) + # Save PDF document + document.save(outfile) +``` + +El ejemplo genera párrafos de muestra y los coloca en tres columnas. El contenido continúa en páginas adicionales hasta que se rendericen todos los párrafos. + +#### Diseño de varias columnas con inicio de columna forzado + +Este ejemplo usa la misma configuración de varias columnas, pero obliga a que cada párrafo añadido comience en una nueva columna. Para hacer eso, establezca `is_first_paragraph_in_column = True` en cada `TextFragment` antes de añadirlo a `FloatingBox`. + +```python +import sys +import aspose.pdf as ap +from os import path + +def multi_column_layout_2(outfile): + # Create PDF document + with ap.Document() as document: + # Add page to pages collection of PDF + page = document.pages.add() + # Set margin settings + page.page_info.margin = ap.MarginInfo(36, 18, 36, 18) + column_count = 3 + spacing = 10 + width = ( + page.page_info.width + - page.page_info.margin.left + - page.page_info.margin.right + - (column_count - 1) * spacing + ) + column_width = width / 3 + # Create FloatingBox + box = ap.FloatingBox() + box.is_need_repeating = True + box.column_info.column_widths = f"{column_width} {column_width} {column_width}" + box.column_info.column_spacing = f"{spacing}" + box.column_info.column_count = 3 + phrase = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quam odio, sollicitudin ac mauris vel, suscipit pellentesque nisi." + paragraphs = [ + phrase, + phrase, + phrase, + phrase, + phrase, + phrase, + phrase, + phrase, + phrase, + phrase, + ] + for paragraph in paragraphs: + text = ap.text.TextFragment(paragraph) + text.is_first_paragraph_in_column = True + box.paragraphs.add(text) + # Add a box to a page + page.paragraphs.add(box) + # Save PDF document + document.save(outfile) +``` + +### Soporte de fondo + +Aplicar un color de fondo a un `FloatingBox` en un documento PDF usando Aspose.PDF for Python via .NET. +Al asignar un [`Color`](https://reference.aspose.com/pdf/python-net/aspose.pdf/color/) a `background_color`, puedes resaltar contenido para encabezados, llamados de atención o secciones con estilo. + +Este fragmento de código muestra cómo crear un cuadro de texto verde claro simple con contenido de ejemplo. + +```python +import sys +import aspose.pdf as ap +from os import path + +def background_support(outfile): + # Create PDF document + with ap.Document() as document: + # Add page to pages collection of PDF + page = document.pages.add() + # Create and fill box + box = ap.FloatingBox(400, 30) + box.background_color = ap.Color.light_green + box.is_need_repeating = False + box.paragraphs.add(ap.text.TextFragment("text example")) + # Add box + page.paragraphs.add(box) + # Save PDF document + document.save(outfile) +``` + +### Soporte de posicionamiento + +La posición de un `FloatingBox` en la página está controlado por `positioning_mode`, `left`, y `top`. +Cuando `positioning_mode` es: + +* [`ParagraphPositioningMode.DEFAULT`](https://reference.aspose.com/pdf/python-net/aspose.pdf/paragraphpositioningmode/) (predeterminado) + +La ubicación depende de los elementos añadidos previamente. Añadir un nuevo párrafo afecta al flujo de los elementos subsiguientes. Si [`left`](https://reference.aspose.com/pdf/python-net/aspose.pdf/floatingbox/#properties) o [`top`](https://reference.aspose.com/pdf/python-net/aspose.pdf/floatingbox/#properties) son diferentes de cero, también se aplican. + +* [`ParagraphPositioningMode.ABSOLUTE`](https://reference.aspose.com/pdf/python-net/aspose.pdf/paragraphpositioningmode/) + +La ubicación está fijada por `left` y `top`; no depende de elementos anteriores y no afecta el flujo de los posteriores. + +```python +import sys +import aspose.pdf as ap +from os import path + +def offset_support(outfile): + # Create PDF document + with ap.Document() as document: + # Add page to pages collection of PDF + page = document.pages.add() + # Create and fill box + box = ap.FloatingBox(400, 30) + box.top = 45 + box.left = 15 + box.positioning_mode = ap.ParagraphPositioningMode.ABSOLUTE + box.border = ap.BorderInfo(ap.BorderSide.ALL, 1.5, ap.Color.dark_green) + box.paragraphs.add(ap.text.TextFragment("text example 1")) + page.paragraphs.add(ap.text.TextFragment("text example 2")) + # Add the box to the page + page.paragraphs.add(box) + page.paragraphs.add(ap.text.TextFragment("text example 3")) + document.save(outfile) +``` + +### Alinear cajas flotantes con alineación vertical y horizontal en PDF + +Alinear `FloatingBox` elementos en una página PDF usando [`VerticalAlignment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/verticalalignment/) y [`HorizontalAlignment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/horizontalalignment/) en Aspose.PDF for Python via .NET. Esto le ayuda a colocar contenedores flotantes en posiciones superior, central o inferior para diseños de página, bloques de encabezado/pie de página o notas laterales. + +1. Crear un nuevo documento PDF. +1. Agregue una página al documento. +1. Agregar el primero `FloatingBox` con alineación inferior derecha. +1. Agregar el segundo `FloatingBox` con alineación centrado-derecha. +1. Agregar el tercero `FloatingBox` con alineación superior derecha. +1. Guarde el documento. + +```python +import sys +import aspose.pdf as ap +from os import path + +def align_text_to_float(outfile): + # Create PDF document + with ap.Document() as document: + # Add page to pages collection of PDF + page = document.pages.add() + + # Create float box + float_box = ap.FloatingBox(100, 100) + # Set settings to float box + float_box.vertical_alignment = ap.VerticalAlignment.BOTTOM + float_box.horizontal_alignment = ap.HorizontalAlignment.RIGHT + float_box.paragraphs.add(ap.text.TextFragment("FloatingBox_bottom")) + float_box.border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.blue) + # Add float box + page.paragraphs.add(float_box) + + # Create float box + float_box_2 = ap.FloatingBox(100, 100) + # Set settings to float box + float_box_2.vertical_alignment = ap.VerticalAlignment.CENTER + float_box_2.horizontal_alignment = ap.HorizontalAlignment.RIGHT + float_box_2.paragraphs.add(ap.text.TextFragment("FloatingBox_center")) + float_box_2.border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.blue) + # Add float box + page.paragraphs.add(float_box_2) + + # Create float box + float_box_3 = ap.FloatingBox(100, 100) + # Set settings to float box + float_box_3.vertical_alignment = ap.VerticalAlignment.TOP + float_box_3.horizontal_alignment = ap.HorizontalAlignment.RIGHT + float_box_3.paragraphs.add(ap.text.TextFragment("FloatingBox_top")) + float_box_3.border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.blue) + # Add float box + page.paragraphs.add(float_box_3) + + # Save the document + document.save(outfile) +``` + +## Temas de texto relacionados + +* [Trabajar con texto en PDF usando Python](/pdf/es/python-net/working-with-text/) +* [Agregar texto al PDF](/pdf/es/python-net/add-text-to-pdf-file/) +* [Formatear texto PDF en Python](/pdf/es/python-net/text-formatting-inside-pdf/) +* [Agregar información sobre herramientas al texto PDF en Python](/pdf/es/python-net/pdf-tooltip/) diff --git a/es/python-net/advanced-operations/working-with-text/replace-text-an-a-pdf/_index.md b/es/python-net/advanced-operations/working-with-text/replace-text-an-a-pdf/_index.md index b2bd718dc..b12537da8 100644 --- a/es/python-net/advanced-operations/working-with-text/replace-text-an-a-pdf/_index.md +++ b/es/python-net/advanced-operations/working-with-text/replace-text-an-a-pdf/_index.md @@ -1,559 +1,507 @@ --- -title: Reemplazar Texto en PDF a través de Python -linktitle: Reemplazar Texto en PDF +title: Reemplazar texto en PDF con Python +linktitle: Reemplazar texto en PDF type: docs weight: 40 url: /es/python-net/replace-text-in-pdf/ -description: Aprende más sobre varias formas de reemplazar y eliminar texto de Aspose.PDF para Python a través de la biblioteca .NET. -lastmod: "2024-02-17" +description: Aprende cómo reemplazar, reorganizar y eliminar texto en documentos PDF usando Python. +lastmod: "2026-05-05" sitemap: changefreq: "monthly" priority: 0.7 +aliases: + - /python-net/replace-text-in-a-pdf-document/ +TechArticle: true +AlternativeHeadline: Reemplaza, elimina y ajusta el contenido de texto en PDF usando Python +Abstract: Este artículo cubre flujos de trabajo prácticos de sustitución de texto en documentos PDF utilizando Aspose.PDF for Python via .NET. Incluye la sustitución de texto en varias páginas, la limitación de la sustitución a regiones específicas, el ajuste del diseño del texto durante la sustitución, el trabajo con coincidencias basadas en expresiones regulares, la sustitución de fuentes y la eliminación del contenido de texto cuando sea necesario. --- - - - -## Reemplazar texto en todas las páginas de un documento PDF + +Estos ejemplos muestran cómo **modificar o eliminar texto en un PDF existente**. + +Utilice esta página cuando necesite actualizar valores de texto, eliminar contenido no deseado o aplicar reglas de sustitución de texto en todas las páginas del PDF. + +## Reemplazar texto existente + +### Reemplazar texto en todas las páginas del documento PDF {{% alert color="primary" %}} -Puede intentar encontrar y reemplazar el texto en el documento usando Aspose.PDF y obtener los resultados en línea en este [enlace](https://products.aspose.app/pdf/redaction) +Puedes intentar buscar y reemplazar el texto en el documento usando Aspose.PDF y obtener los resultados en línea en este [enlace](https://products.aspose.app/pdf/redaction) {{% /alert %}} -Para reemplazar texto en todas las páginas de un documento PDF, primero necesita usar [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber/) para encontrar la frase particular que desea reemplazar. Después de eso, debe recorrer todos los TextFragments para reemplazar el texto y cambiar cualquier otro atributo. Una vez hecho esto, solo necesita guardar el PDF de salida usando el método Save del objeto Document. El siguiente fragmento de código le muestra cómo reemplazar texto en todas las páginas de un documento PDF. +La sustitución de texto es un requisito común al actualizar o corregir contenido en documentos PDF existentes — por ejemplo, cambiar nombres de productos, corregir errores tipográficos o actualizar la terminología en varias páginas. -```python +Aspose.PDF for Python via .NET ofrece un método potente y eficiente para buscar y reemplazar texto programáticamente a través del [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber/) clase. - import aspose.pdf as ap +Este ejemplo demuestra cómo encontrar todas las apariciones de una frase específica (en este caso, "Black cat") y reemplazarlas con una nueva frase ("White dog") a lo largo de todo un documento PDF. - # Abrir documento - document = ap.Document(input_pdf) +1. Especifique frases de búsqueda y reemplazo. Establezca el texto que desea encontrar y el texto con el que desea sustituirlo. +1. Cargar el documento PDF. +1. Crea un Text Absorber. Un TextFragmentAbsorber se inicializa con la frase de búsqueda. Escanea el documento para todas las instancias de la frase dada. +1. Aplicar el Absorber a Todas las Páginas. Esto itera a través de todas las páginas y recopila fragmentos de texto que coinciden con la frase. +1. Reemplaza cada fragmento encontrado. Cada instancia de "Black cat" debe cambiarse a "White dog". +1. Guardar el PDF actualizado. - # Crear objeto TextAbsorber para encontrar todas las instancias de la frase de búsqueda de entrada - absorber = ap.text.TextFragmentAbsorber("format") +```python +import sys +import aspose.pdf as ap +from os import path - # Aceptar el absorber para todas las páginas - document.pages.accept(absorber) +def replace_text_on_all_pages(infile, outfile): + search_phrase = "PDF" + replace_phrase = "pdf" - # Obtener los fragmentos de texto extraídos - collection = absorber.text_fragments + with ap.Document(infile) as document: + absorber = ap.text.TextFragmentAbsorber(search_phrase) + document.pages.accept(absorber) - # Recorrer los fragmentos - for text_fragment in collection: - # Actualizar texto y otras propiedades - text_fragment.text = "FORMAT" - text_fragment.text_state.font = ap.text.FontRepository.find_font("Verdana") - text_fragment.text_state.font_size = 22 - text_fragment.text_state.foreground_color = ap.Color.blue - text_fragment.text_state.background_color = ap.Color.green + for fragment in absorber.text_fragments: + fragment.text = replace_phrase - # Guardar el documento - document.save(output_pdf) + document.save(outfile) ``` +### Reemplazar texto en una región de página particular + +A veces, es posible que necesite reemplazar texto solo dentro de un área específica de una página PDF en lugar de buscar en todo el documento — por ejemplo, actualizar un encabezado, pie de página o una celda de tabla en una posición conocida. + +La biblioteca Aspose.PDF for Python via .NET habilita esta funcionalidad al utilizar la [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber/) en conjunto con la búsqueda de texto basada en regiones. -## Reemplazar texto en una región específica de la página +Este ejemplo muestra cómo encontrar y reemplazar todas las ocurrencias de una frase objetivo dentro de una región rectangular definida en una página específica. -Para reemplazar texto en una región particular de la página, primero necesitamos instanciar un objeto TextFragmentAbsorber, especificar la región de la página usando la propiedad TextSearchOptions.Rectangle y luego iterar a través de todos los TextFragments para reemplazar el texto. Una vez que estas operaciones se completan, solo necesitamos guardar el PDF de salida usando el método Save del objeto Document. El siguiente fragmento de código te muestra cómo reemplazar texto en todas las páginas del documento PDF. +1. Especificar frases de búsqueda y reemplazo. +1. Cargar el documento PDF. +1. Crear un TextAbsorber para buscar. Inicializar un TextFragmentAbsorber para encontrar el texto deseado. +1. Restringir el área de búsqueda. El rectángulo especifica los límites de coordenadas x e y en la página. +1. Aplicar el Absorber a una página específica. Esto realiza la búsqueda y recoge los fragmentos de texto coincidentes dentro del área especificada. +1. Reemplazar el texto encontrado. Cada aparición de 'doc' en la región definida se convierte en 'DOC'. +1. Guardar el PDF actualizado. ```python -// cargar archivo PDF -Aspose.PDF.Document pdf = new Aspose.PDF.Document("c:/pdftest/programaticallyproducedpdf.pdf"); +import sys +import aspose.pdf as ap +from os import path -// instanciar objeto TextFragment Absorber -Aspose.PDF.Text.TextFragmentAbsorber TextFragmentAbsorberAddress = new Aspose.PDF.Text.TextFragmentAbsorber(); +def replace_text_in_particular_page_region(infile, outfile): + search_phrase = "doc" + replace_phrase = "DOC" -// buscar texto dentro de los límites de la página -TextFragmentAbsorberAddress.TextSearchOptions.LimitToPageBounds = true; + with ap.Document(infile) as document: + absorber = ap.text.TextFragmentAbsorber(search_phrase) + absorber.text_search_options.limit_to_page_bounds = True + absorber.text_search_options.rectangle = ap.Rectangle(300, 442, 500, 742, True) + document.pages[1].accept(absorber) + + for fragment in absorber.text_fragments: + fragment.text = replace_phrase + + document.save(outfile) +``` -// especificar la región de la página para las opciones de búsqueda de texto -TextFragmentAbsorberAddress.TextSearchOptions.Rectangle = new Aspose.PDF.Rectangle(100, 100, 200, 200); +### Redimensionar y desplazar texto sin cambiar el tamaño de la fuente -// buscar texto desde la primera página del archivo PDF -pdf.Pages[1].Accept(TextFragmentAbsorberAddress); +Al reemplazar texto en un PDF, a veces deseas ajustar o reposicionar el nuevo texto dentro de un área específica sin modificar el tamaño de la fuente. +Aspose.PDF for Python via .NET proporciona opciones para ajustar el diseño y el espaciado del texto mientras mantiene intacto el tamaño original de Font. -// iterar a través de cada TextFragment -foreach( Aspose.PDF.Text.TextFragment tf in TextFragmentAbsorberAddress.TextFragments) -{ - // actualizar texto a caracteres en blanco - tf.Text = ""; -} +1. Cargar el documento PDF. +1. Recopile todos los fragmentos de texto en la página usando un 'TextFragmentAbsorber'. +1. Seleccione el Fragmento para modificar. +1. Desplazar y cambiar el tamaño del rectángulo de texto. +1. Ajustar el espaciado del texto. Habilite el ajuste de espaciado para que el texto quepa dentro del rectángulo modificado. +1. Reemplaza el texto del fragmento. +1. Guardar el PDF actualizado. -// guardar archivo PDF actualizado después de reemplazar el texto -pdf.Save("c:/pdftest/TextUpdated.pdf"); +```python +import sys +import aspose.pdf as ap +from os import path + +def replace_text_and_resize_and_shift_without_changing_font_size(infile, outfile): + with ap.Document(infile) as document: + absorber = ap.text.TextFragmentAbsorber() + absorber.visit(document.pages[1]) + fragment = absorber.text_fragments[1] + text = fragment.text + rect = fragment.rectangle + rect.llx += 50 + rect.urx -= 50 + fragment.replace_options.rectangle = rect + fragment.replace_options.replace_adjustment_action = ( + ap.text.TextReplaceOptions.ReplaceAdjustment.ADJUST_SPACE_WIDTH + ) + fragment.text = f"{text} {text}" + document.save(outfile) ``` +### Redimensionar y desplazar un párrafo en PDF -## Reemplazar Texto Basado en una Expresión Regular +Al trabajar con PDFs, a veces es necesario reemplazar o ampliar un párrafo mientras se mantiene alineado visualmente con el diseño de la página. Aspose.PDF le permite redimensionar el rectángulo delimitador del párrafo y ajustar el espaciado para encajar el nuevo texto, todo sin cambiar el tamaño de la fuente. -Si deseas reemplazar algunas frases basadas en una expresión regular, primero necesitas encontrar todas las frases que coincidan con esa expresión regular particular utilizando TextFragmentAbsorber. Tendrás que pasar la expresión regular como un parámetro al constructor de TextFragmentAbsorber. También necesitas crear un objeto TextSearchOptions que especifique si se está utilizando la expresión regular o no. Una vez que obtengas las frases coincidentes en TextFragments, necesitas iterar a través de todas ellas y actualizarlas según sea necesario. Finalmente, necesitas guardar el PDF actualizado usando el método Save del objeto Document. El siguiente fragmento de código te muestra cómo reemplazar texto basado en una expresión regular. +1. Cargar el documento PDF. +1. Utiliza 'TextFragmentAbsorber' para recopilar todos los fragmentos de texto en la página. +1. Seleccione el Fragmento para modificar. +1. Redimensionar y desplazar el párrafo. Use la caja de medios de la página para determinar los límites y ajustar el rectángulo. +1. Ajustar espaciado. Esto modifica el espaciado entre palabras/letras en lugar de cambiar el tamaño de la fuente. +1. Reemplaza el texto del fragmento. +1. Guarda el PDF modificado. ```python -// Para ejemplos completos y archivos de datos, por favor visita https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); - -// Abrir documento -Document pdfDocument = new Document(dataDir + "SearchRegularExpressionPage.pdf"); - -// Crear objeto TextAbsorber para encontrar todas las frases que coinciden con la expresión regular -TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("\\d{4}-\\d{4}"); // Como 1999-2000 - -// Establecer opción de búsqueda de texto para especificar el uso de expresión regular -TextSearchOptions textSearchOptions = new TextSearchOptions(true); -textFragmentAbsorber.TextSearchOptions = textSearchOptions; - -// Aceptar el absorbente para una sola página -pdfDocument.Pages[1].Accept(textFragmentAbsorber); - -// Obtener los fragmentos de texto extraídos -TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; - -// Iterar a través de los fragmentos -foreach (TextFragment textFragment in textFragmentCollection) -{ - // Actualizar texto y otras propiedades - textFragment.Text = "Nueva Frase"; - // Establecer a una instancia de un objeto. - textFragment.TextState.Font = FontRepository.FindFont("Verdana"); - textFragment.TextState.FontSize = 22; - textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Blue); - textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Green); -} -dataDir = dataDir + "ReplaceTextonRegularExpression_out.pdf"; -pdfDocument.Save(dataDir); +import sys +import aspose.pdf as ap +from os import path + +def replace_text_and_resize_and_shift_paragraph(infile, outfile): + with ap.Document(infile) as document: + absorber = ap.text.TextFragmentAbsorber() + absorber.visit(document.pages[1]) + fragment = absorber.text_fragments[1] + text = fragment.text + rect = document.pages[1].media_box + rect.llx += 20 + rect.urx -= 20 + rect.ury -= 20 + fragment.replace_options.rectangle = rect + fragment.replace_options.replace_adjustment_action = ( + ap.text.TextReplaceOptions.ReplaceAdjustment.ADJUST_SPACE_WIDTH + ) + fragment.text = f"{text} {text}" + document.save(outfile) ``` +### Reemplazar texto y expandir automáticamente la fuente para llenar el área objetivo -## Reemplazar fuentes en un archivo PDF existente +Reemplazar texto en un PDF mientras se redimensiona y expande automáticamente la fuente para llenar un área rectangular específica. Usando la biblioteca Aspose.PDF for Python via .NET, el código ajusta dinámicamente el tamaño y el espaciado de la fuente de modo que el nuevo contenido de texto encaje perfectamente dentro de un cuadro delimitador definido — sin cálculos manuales de fuentes. -Aspose.PDF para Python a través de .NET admite la capacidad de reemplazar texto en un documento PDF. Sin embargo, a veces tienes el requisito de solo reemplazar la fuente que se está utilizando dentro del documento PDF. Así que, en lugar de reemplazar el texto, solo la fuente que se está utilizando es reemplazada. Una de las sobrecargas del constructor TextFragmentAbsorber acepta un objeto TextEditOptions como argumento y podemos usar el valor RemoveUnusedFonts de la enumeración TextEditOptions.FontReplace para cumplir con nuestros requisitos. El siguiente fragmento de código muestra cómo reemplazar la fuente dentro del documento PDF. +1. Cargar el PDF. +1. Capturar fragmentos de texto. +1. Seleccionar un fragmento específico. +1. Definir rectángulo objetivo. +1. Habilitar opciones de ajuste de texto. +1. Reemplazar texto. +1. Guardar el documento. ```python -// Para ejemplos completos y archivos de datos, por favor vaya a https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); - -// Cargar archivo PDF de origen -Document pdfDocument = new Document(dataDir + "ReplaceTextPage.pdf"); -// Buscar fragmentos de texto y establecer la opción de edición para eliminar fuentes no usadas -TextFragmentAbsorber absorber = new TextFragmentAbsorber(new TextEditOptions(TextEditOptions.FontReplace.RemoveUnusedFonts)); - -// Aceptar el absorbedor para todas las páginas -pdfDocument.Pages.Accept(absorber); -// Recorrer todos los TextFragments -foreach (TextFragment textFragment in absorber.TextFragments) -{ - // Si el nombre de la fuente es ArialMT, reemplazar el nombre de la fuente con Arial - if (textFragment.TextState.Font.FontName == "Arial,Bold") - { - textFragment.TextState.Font = FontRepository.FindFont("Arial"); - } - -} - -dataDir = dataDir + "ReplaceFonts_out.pdf"; -// Guardar documento actualizado -pdfDocument.Save(dataDir); +import sys +import aspose.pdf as ap +from os import path + +def replace_text_and_resize_and_expand_font(infile, outfile): + with ap.Document(infile) as document: + absorber = ap.text.TextFragmentAbsorber() + absorber.visit(document.pages[1]) + fragment = absorber.text_fragments[1] + text = fragment.text + fragment.replace_options.rectangle = ap.Rectangle(100, 300, 512, 692, True) + fragment.replace_options.replace_adjustment_action = ( + ap.text.TextReplaceOptions.ReplaceAdjustment.ADJUST_SPACE_WIDTH + ) + fragment.replace_options.font_size_adjustment_action = ( + ap.text.TextReplaceOptions.FontSizeAdjustment.SCALE_TO_FILL + ) + fragment.text = f"{text} {text}" + document.save(outfile) ``` +### Reemplazar texto y ajustarlo a un rectángulo + +Reemplazar texto en un documento PDF asegurándose de que el nuevo contenido encaje dentro del área rectangular del texto original reduciendo automáticamente el tamaño de la fuente cuando sea necesario. + +Usando la biblioteca Aspose.PDF for Python via .NET, esta función ajusta tanto el layout del texto como el tamaño de la Font de forma dinámica, preservando la estructura del documento mientras evita el desbordamiento. + +1. Cree un objeto TextFragmentAbsorber para extraer todos los fragmentos de texto de la primera página. +1. Acceder a un fragmento de texto específico. +1. Establezca el Área de Reemplazo. +1. Configure las opciones de ajuste de texto. Establezca dos opciones clave de reemplazo: + - Ajuste del tamaño de fuente - 'SHRINK_TO_FIT' reduce automáticamente el tamaño de la fuente si el nuevo texto es demasiado largo. + - Ajuste de espaciado - 'ADJUST_SPACE_WIDTH' mantiene el espaciado proporcional. +1. Reemplazar el texto. +1. Guarda el PDF modificado. + +```python +import sys +import aspose.pdf as ap +from os import path + +def replace_text_and_fit_text_into_rectangle(infile, outfile): + with ap.Document(infile) as document: + absorber = ap.text.TextFragmentAbsorber() + absorber.visit(document.pages[1]) + fragment = absorber.text_fragments[1] + text = fragment.text + fragment.replace_options.rectangle = fragment.rectangle + fragment.replace_options.font_size_adjustment_action = ( + ap.text.TextReplaceOptions.FontSizeAdjustment.SHRINK_TO_FIT + ) + fragment.replace_options.replace_adjustment_action = ( + ap.text.TextReplaceOptions.ReplaceAdjustment.ADJUST_SPACE_WIDTH + ) + fragment.text = f"{text} {text}" + document.save(outfile) +``` -## El reemplazo de texto debería reordenar automáticamente el contenido de la página +### Reemplazar automáticamente el texto de marcador de posición y reorganizar el diseño del PDF -Aspose.PDF para Python a través de .NET admite la función de buscar y reemplazar texto dentro del archivo PDF. Sin embargo, recientemente algunos clientes encontraron problemas durante el reemplazo de texto cuando un TextFragment particular se reemplaza con contenido más pequeño y algunos espacios extra se muestran en el PDF resultante o en caso de que el TextFragment se reemplace con una cadena más larga, entonces las palabras se superponen al contenido existente de la página. Así que el requisito era introducir un mecanismo que, una vez que se reemplace el texto dentro de un documento PDF, el contenido debe reordenarse. +Reemplaza el texto de marcador de posición dentro de un PDF (p. ej., plantillas o formularios) con datos reales, como nombres o información de la empresa. +Ajusta automáticamente el diseño de la página para adaptarse al nuevo texto mientras aplica formato personalizado (Font, color, size). -Para atender los escenarios mencionados anteriormente, Aspose.PDF para Python a través de .NET ha sido mejorado para que no aparezcan tales problemas al reemplazar texto dentro del archivo PDF. El siguiente fragmento de código muestra cómo reemplazar texto dentro de un archivo PDF y el contenido de la página debe reordenarse automáticamente. +1. Importar y cargar el PDF. +1. Crear un TextAbsorber para el Placeholder. +1. Aplicar el Absorber a Todas las Páginas. +1. Recorrer fragmentos de texto encontrados. +1. Aplicar formato de texto personalizado. +1. Guardar el documento actualizado. ```python -// Para ejemplos completos y archivos de datos, por favor visite https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); - -// Cargar archivo PDF de origen -Document doc = new Document(dataDir + "ExtractTextPage.pdf"); -// Crear objeto TextFragment Absorber con expresión regular -TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("[TextFragmentAbsorber,companyname,Textbox,50]"); -doc.Pages.Accept(textFragmentAbsorber); -// Reemplazar cada TextFragment -foreach (TextFragment textFragment in textFragmentAbsorber.TextFragments) -{ - // Establecer la fuente del fragmento de texto que se reemplaza - textFragment.TextState.Font = FontRepository.FindFont("Arial"); - // Establecer tamaño de fuente - textFragment.TextState.FontSize = 12; - textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Navy; - // Reemplazar el texto con una cadena más grande que el marcador de posición - textFragment.Text = "Esta es una cadena más grande para la prueba de este problema"; -} -dataDir = dataDir + "RearrangeContentsUsingTextReplacement_out.pdf"; -// Guardar PDF resultante -doc.Save(dataDir); +import sys +import aspose.pdf as ap +from os import path + +def automatically_rearrange_page_contents(input_file, output_file): + document = ap.Document(input_file) + + absorber = ap.text.TextFragmentAbsorber("[Long_placeholder_Long_placeholder]") + document.pages.accept(absorber) + + for text_fragment in absorber.text_fragments: + # text_fragment.text = "John Smith" + text_fragment.text = "John Smith, South Development Studio" + text_fragment.text_state.font = ap.text.FontRepository.find_font("Calibri") + text_fragment.text_state.font_size = 12 + text_fragment.text_state.foreground_color = ap.Color.navy + + # Save PDF document + document.save(output_file) ``` +### Reemplazar texto basado en una expresión regular -## Renderización de Símbolos Reemplazables durante la creación de PDF +Al trabajar con documentos PDF, es posible que necesites reemplazar texto que siga un patrón en lugar de una frase específica — por ejemplo, números de teléfono, códigos o formatos tipo fecha. -Los símbolos reemplazables son símbolos especiales en una cadena de texto que pueden ser reemplazados con el contenido correspondiente en tiempo de ejecución. Los símbolos reemplazables que actualmente admite el nuevo Modelo de Objetos del Documento del espacio de nombres Aspose.PDF son `$P`, `$p`, `\n`, `\r`. Los símbolos `$p` y `$P` se utilizan para manejar la numeración de páginas en tiempo de ejecución. `$p` se reemplaza con el número de la página donde se encuentra la clase Paragraph actual. `$P` se reemplaza con el número total de páginas en el documento. Al agregar `TextFragment` a la colección de párrafos de documentos PDF, no admite el salto de línea dentro del texto. Sin embargo, para agregar texto con un salto de línea, utilice `TextFragment` con `TextParagraph`: +Aspose.PDF for Python via .NET permite realizar tales reemplazos usando expresiones regulares (regex) con la clase TextFragmentAbsorber. -- use "\r\n" o Environment.NewLine en TextFragment en lugar de un solo "\n"; -- cree un objeto TextParagraph. Agregará texto con división de líneas; -- agregue el TextFragment con TextParagraph.AppendLine; -- agregue el TextParagraph con TextBuilder.AppendParagraph. +Este ejemplo muestra cómo encontrar patrones de texto (en este caso, cualquier texto que coincida con el formato ####-####, como 1234-5678) y reemplazarlos con una cadena formateada 'ABC1-2XZY'. También muestra cómo personalizar la fuente, el color y el tamaño del texto reemplazado. + +El siguiente fragmento de código le muestra cómo reemplazar texto basado en una expresión regular. + +1. Cargar el documento PDF. +1. Crear un TextAbsorber basado en expresiones regulares. Inicializar el TextFragmentAbsorber con un patrón de expresión regular. +1. Activar el modo de expresión regular. El parámetro \u0027True\u0027 activa el modo de búsqueda de expresiones regulares. +1. Aplica el Absorber a una página. Esto escanea la página en busca de todos los fragmentos de texto que coinciden con el patrón regex definido. +1. Reemplazar cada coincidencia con nuevo texto y aplicar estilo personalizado. +1. Guardar el documento modificado. ```python -// Para ejemplos completos y archivos de datos, por favor visite https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); +import sys +import aspose.pdf as ap +from os import path + +def replace_text_based_on_regex(infile, outfile): + with ap.Document(infile) as document: + absorber = ap.text.TextFragmentAbsorber(r"\d{4}-\d{4}") + absorber.text_search_options = ap.text.TextSearchOptions(True) + document.pages[1].accept(absorber) + + for fragment in absorber.text_fragments: + fragment.text = "ABC1-2XZY" + fragment.text_state.font = ap.text.FontRepository.find_font("Verdana") + fragment.text_state.font_size = 12 + fragment.text_state.foreground_color = ap.Color.blue + fragment.text_state.background_color = ap.Color.light_green + + document.save(outfile) +``` -Aspose.Pdf.Document pdfApplicationDoc = new Aspose.Pdf.Document(); -Aspose.Pdf.Page applicationFirstPage = (Aspose.Pdf.Page)pdfApplicationDoc.Pages.Add(); +## Reemplazar fuentes o eliminar fuentes no utilizadas -// Inicializar un nuevo TextFragment con texto que contiene los marcadores de nueva línea requeridos -Aspose.Pdf.Text.TextFragment textFragment = new Aspose.Pdf.Text.TextFragment("Nombre del Solicitante: " + Environment.NewLine + " Joe Smoe"); +### Reemplazar Font en un archivo PDF existente -// Establecer propiedades del fragmento de texto si es necesario -textFragment.TextState.FontSize = 12; -textFragment.TextState.Font = Aspose.Pdf.Text.FontRepository.FindFont("TimesNewRoman"); -textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray; -textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Red; +En ocasiones, necesitas estandarizar o actualizar fuentes en un PDF — por ejemplo, reemplazando una fuente obsoleta o propietaria por una más accesible. La biblioteca Aspose.PDF for Python via .NET permite detectar y reemplazar fuentes programáticamente, garantizando una tipografía coherente y compatibilidad del documento. -// Crear objeto TextParagraph -TextParagraph par = new TextParagraph(); +Este ejemplo muestra cómo reemplazar todas las instancias de una fuente específica (p. ej., 'Arial-BoldMT') con otra fuente (p. ej., 'Verdana') a lo largo de un documento PDF. -// Agregar nuevo TextFragment al párrafo -par.AppendLine(textFragment); +El siguiente fragmento de código muestra cómo reemplazar la fuente dentro del documento PDF: + +1. Abre el documento PDF. +1. Inicializar un TextFragmentAbsorber. +1. Utilice el Absorber para extraer fragmentos de texto de cada página del documento. +1. Identificar y Reemplazar Fuentes. El script verifica si la fuente actual de un fragmento es 'Arial-BoldMT'. Si es así, la reemplaza por la fuente 'Verdana' usando el método FontRepository.find_font(). +1. Guardar el documento modificado. + +```python +import sys +import aspose.pdf as ap +from os import path -// Establecer la posición del párrafo -par.Position = new Aspose.Pdf.Text.Position(100, 600); +def replace_fonts(infile, outfile): + with ap.Document(infile) as document: + absorber = ap.text.TextFragmentAbsorber() + document.pages.accept(absorber) -// Crear objeto TextBuilder -TextBuilder textBuilder = new TextBuilder(applicationFirstPage); -// Agregar el TextParagraph usando TextBuilder -textBuilder.AppendParagraph(par); + for fragment in absorber.text_fragments: + if fragment.text_state.font.font_name == "Arial-BoldMT": + fragment.text_state.font = ap.text.FontRepository.find_font("Verdana") -dataDir = dataDir + "RenderingReplaceableSymbols_out.pdf"; -pdfApplicationDoc.Save(dataDir); + document.save(outfile) ``` +### Eliminar fuentes no utilizadas -## Símbolos reemplazables en el área de Encabezado/Pie de página +Con el tiempo, los documentos PDF pueden acumular fuentes no utilizadas o incrustadas que aumentan el tamaño del archivo y ralentizan el procesamiento. Estas fuentes no utilizadas a menudo permanecen incluso después de ediciones o reemplazos de texto, especialmente al trabajar con PDFs grandes o complejos. -Los símbolos reemplazables también pueden colocarse dentro de la sección de Encabezado/Pie de página del archivo PDF. Por favor, echa un vistazo al siguiente fragmento de código para obtener detalles sobre cómo agregar un símbolo reemplazable en la sección del pie de página. +La biblioteca Aspose.PDF for Python via .NET proporciona una forma eficiente de eliminar esas fuentes redundantes usando la clase TextEditOptions. Esto no solo optimiza su documento, sino que también garantiza que solo se usen las fuentes realmente aplicadas al texto visible. + +El método 'remove_unused_fonts()' es una forma simple pero poderosa de optimizar archivos PDF al eliminar datos de fuentes redundantes. + +Este ejemplo demuestra cómo: + +- Escanea un PDF en busca de fuentes no utilizadas. +- Elimínalos de forma segura. +- Reasignar fragmentos de texto activos a una fuente consistente (p. ej., Times New Roman). + +1. Abre el documento PDF. +1. Configure las opciones de edición de texto. Esto instruye al motor a eliminar cualquier fuente incrustada que no se esté utilizando actualmente en el texto visible. +1. Crea un Text Absorber con Options. Un TextFragmentAbsorber extrae fragmentos de texto del documento para editar. +1. Reasignar una Standard Font. Una vez que el absorber haya recopilado todos los fragments, iterar a través de ellos y aplicar una fuente consistente. +1. Guarda el PDF limpio. ```python -// Para ejemplos completos y archivos de datos, por favor visita https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); - -Document doc = new Document(); -Page page = doc.Pages.Add(); - -MarginInfo marginInfo = new MarginInfo(); -marginInfo.Top = 90; -marginInfo.Bottom = 50; -marginInfo.Left = 50; -marginInfo.Right = 50; -// Asignar la instancia de marginInfo a la propiedad Margin de sec1.PageInfo -page.PageInfo.Margin = marginInfo; - -HeaderFooter hfFirst = new HeaderFooter(); -page.Header = hfFirst; -hfFirst.Margin.Left = 50; -hfFirst.Margin.Right = 50; - -// Instanciar un párrafo de texto que almacenará el contenido a mostrar como encabezado -TextFragment t1 = new TextFragment("título del informe"); -t1.TextState.Font = FontRepository.FindFont("Arial"); -t1.TextState.FontSize = 16; -t1.TextState.ForegroundColor = Aspose.Pdf.Color.Black; -t1.TextState.FontStyle = FontStyles.Bold; -t1.TextState.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center; -t1.TextState.LineSpacing = 5f; -hfFirst.Paragraphs.Add(t1); - -TextFragment t2 = new TextFragment("Nombre del Informe"); -t2.TextState.Font = FontRepository.FindFont("Arial"); -t2.TextState.ForegroundColor = Aspose.Pdf.Color.Black; -t2.TextState.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center; -t2.TextState.LineSpacing = 5f; -t2.TextState.FontSize = 12; -hfFirst.Paragraphs.Add(t2); - -// Crear un objeto HeaderFooter para la sección -HeaderFooter hfFoot = new HeaderFooter(); -// Establecer el objeto HeaderFooter para pie de página impar y par -page.Footer = hfFoot; -hfFoot.Margin.Left = 50; -hfFoot.Margin.Right = 50; - -// Agregar un párrafo de texto que contenga el número de página actual del total de páginas -TextFragment t3 = new TextFragment("Generado en fecha de prueba"); -TextFragment t4 = new TextFragment("nombre del informe "); -TextFragment t5 = new TextFragment("Página $p de $P"); - -// Instanciar un objeto tabla -Table tab2 = new Table(); - -// Agregar la tabla en la colección de párrafos de la sección deseada -hfFoot.Paragraphs.Add(tab2); - -// Establecer los anchos de columna de la tabla -tab2.ColumnWidths = "165 172 165"; - -// Crear filas en la tabla y luego celdas en las filas -Row row3 = tab2.Rows.Add(); - -row3.Cells.Add(); -row3.Cells.Add(); -row3.Cells.Add(); - -// Establecer la alineación vertical del texto como centrado -row3.Cells[0].Alignment = Aspose.Pdf.HorizontalAlignment.Left; -row3.Cells[1].Alignment = Aspose.Pdf.HorizontalAlignment.Center; -row3.Cells[2].Alignment = Aspose.Pdf.HorizontalAlignment.Right; - -row3.Cells[0].Paragraphs.Add(t3); -row3.Cells[1].Paragraphs.Add(t4); -row3.Cells[2].Paragraphs.Add(t5); - -// Sec1.Paragraphs.Add(New Text("Aspose.Total for Java es una compilación de cada componente Java ofrecido por Aspose. Se compila en un#$NL" + "diario para asegurar que contiene las versiones más actualizadas de cada uno de nuestros componentes Java. #$NL " + "Usando Aspose.Total for Java los desarrolladores pueden crear una amplia gama de aplicaciones. #$NL #$NL #$NP" + "Aspose.Total for Java es una compilación de cada componente Java ofrecido por Aspose. Se compila en un#$NL" + "diario para asegurar que contiene las versiones más actualizadas de cada uno de nuestros componentes Java. #$NL " + "Usando Aspose.Total for Java los desarrolladores pueden crear una amplia gama de aplicaciones. #$NL #$NL #$NP" + "Aspose.Total for Java es una compilación de cada componente Java ofrecido por Aspose. Se compila en un#$NL" + "diario para asegurar que contiene las versiones más actualizadas de cada uno de nuestros componentes Java. #$NL " + "Usando Aspose.Total for Java los desarrolladores pueden crear una amplia gama de aplicaciones. #$NL #$NL")) -Table table = new Table(); - -table.ColumnWidths = "33% 33% 34%"; -table.DefaultCellPadding = new MarginInfo(); -table.DefaultCellPadding.Top = 10; -table.DefaultCellPadding.Bottom = 10; - -// Agregar la tabla en la colección de párrafos de la sección deseada -page.Paragraphs.Add(table); - -// Establecer el borde de celda predeterminado usando el objeto BorderInfo -table.DefaultCellBorder = new BorderInfo(BorderSide.All, 0.1f); - -// Establecer el borde de la tabla usando otro objeto BorderInfo personalizado -table.Border = new BorderInfo(BorderSide.All, 1f); - -table.RepeatingRowsCount = 1; - -// Crear filas en la tabla y luego celdas en las filas -Row row1 = table.Rows.Add(); - -row1.Cells.Add("col1"); -row1.Cells.Add("col2"); -row1.Cells.Add("col3"); -const string CRLF = "\r\n"; -for (int i = 0; i <= 10; i++) -{ - Row row = table.Rows.Add(); - row.IsRowBroken = true; - for (int c = 0; c <= 2; c++) - { - Cell c1; - if (c == 2) - c1 = row.Cells.Add("Aspose.Total for Java es una compilación de cada componente Java ofrecido por Aspose. Se compila en un" + CRLF + "diario para asegurar que contiene las versiones más actualizadas de cada uno de nuestros componentes Java. " + CRLF + "diario para asegurar que contiene las versiones más actualizadas de cada uno de nuestros componentes Java. " + CRLF + "Usando Aspose.Total for Java los desarrolladores pueden crear una amplia gama de aplicaciones."); - else - c1 = row.Cells.Add("item1" + c); - c1.Margin = new MarginInfo(); - c1.Margin.Left = 30; - c1.Margin.Top = 10; - c1.Margin.Bottom = 10; - } -} - -dataDir = dataDir + "ReplaceableSymbolsInHeaderFooter_out.pdf"; -doc.Save(dataDir); +import sys +import aspose.pdf as ap +from os import path + +def remove_unused_fonts(input_file, output_file): + # Open PDF document + document = ap.Document(input_file) + + # Initialize text edit options to remove unused fonts + options = ap.text.TextEditOptions( + ap.text.TextEditOptions.FontReplace.REMOVE_UNUSED_FONTS + ) + + # Create a TextFragmentAbsorber with the specified options + absorber = ap.text.TextFragmentAbsorber(options) + document.pages.accept(absorber) + + # Iterate through all TextFragments + for text_fragment in absorber.text_fragments: + text_fragment.text_state.font = ap.text.FontRepository.find_font( + "TimesNewRoman" + ) + + # Save the updated PDF document + document.save(output_file) ``` +## Eliminar todo el texto + +### Eliminar texto del PDF + +Elimina todo el contenido de texto de un archivo PDF manteniendo intactas las imágenes, formas y estructuras de diseño. +Al usar TextFragmentAbsorber, el código escanea eficientemente todo el documento y elimina cada fragmento de texto encontrado en cada página. -## Eliminar Fuentes No Utilizadas del Archivo PDF +1. Cargar el documento PDF. +1. Se crea un objeto TextFragmentAbsorber para detectar y manejar fragmentos de texto en el PDF. +1. Eliminar todo el contenido de texto. El método 'absorber.remove_all_text()' elimina cada elemento de texto del documento cargado, dejando intactos los componentes que no son texto. +1. Guardar el documento actualizado. -Aspose.PDF para Python a través de .NET admite la función de incrustar fuentes al crear un documento PDF, así como la capacidad de incrustar fuentes en archivos PDF existentes. A partir de Aspose.PDF para Python a través de .NET 7.3.0, también te permite eliminar fuentes duplicadas o no utilizadas de documentos PDF. +```python +import sys +import aspose.pdf as ap +from os import path + +def remove_all_text_using_absorber1(infile, outfile): + with ap.Document(infile) as document: + absorber = ap.text.TextFragmentAbsorber() + absorber.remove_all_text(document) + document.save(outfile) +``` -Para reemplazar fuentes, utiliza el siguiente enfoque: +### Eliminar todo el texto de una página específica -1. Llama a la clase [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber). -1. Llama al parámetro TextEditOptions.FontReplace.RemoveUnusedFonts de la clase TextFragmentAbsorber. (Esto elimina las fuentes que se han vuelto no utilizadas durante el reemplazo de fuentes). -1. Establece la fuente individualmente para cada fragmento de texto. +Eliminar todo el texto de una sola página de un documento PDF usando la clase TextFragmentAbsorber en Aspose.PDF. +A diferencia de la eliminación de todo el documento, este método realiza una limpieza de texto a nivel de página, eliminando texto solo de la página elegida mientras deja todas las demás páginas sin tocar. -El siguiente fragmento de código reemplaza la fuente para todos los fragmentos de texto de todas las páginas del documento y elimina las fuentes no utilizadas. +1. Cargar el archivo PDF. +1. Crear una instancia de TextFragmentAbsorber. +1. Eliminar todo el texto de la primera página. +1. Guarda el PDF modificado. ```python -// Para ejemplos completos y archivos de datos, por favor visita https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); - -// Cargar archivo PDF de origen -Document doc = new Document(dataDir + "ReplaceTextPage.pdf"); -TextFragmentAbsorber absorber = new TextFragmentAbsorber(new TextEditOptions(TextEditOptions.FontReplace.RemoveUnusedFonts)); -doc.Pages.Accept(absorber); - -// Iterar a través de todos los TextFragments -foreach (TextFragment textFragment in absorber.TextFragments) -{ - textFragment.TextState.Font = FontRepository.FindFont("Arial, Bold"); -} - -dataDir = dataDir + "RemoveUnusedFonts_out.pdf"; -// Guardar documento actualizado -doc.Save(dataDir); +import sys +import aspose.pdf as ap +from os import path + +def remove_all_text_using_absorber2(infile, outfile): + with ap.Document(infile) as document: + absorber = ap.text.TextFragmentAbsorber() + absorber.remove_all_text(document.pages[1]) + document.save(outfile) ``` +### Eliminar todo el texto de un área específica en la página PDF + +Eliminar todo el texto de una región rectangular específica en una página usando Aspose.PDF’s TextFragmentAbsorber. +En lugar de borrar una página entera, este método realiza la eliminación de texto dirigida, permitiendo un control preciso sobre qué parte de la página se ve afectada. -## Eliminar Todo el Texto del Documento PDF +1. Cargar el documento PDF. +1. Crear un TextFragmentAbsorber. +1. Definir el Área de Destino (Rectángulo). +1. Eliminar texto de la región especificada. +1. Conserve el resto del documento. +1. Guarda el PDF modificado. + +```python +import sys +import aspose.pdf as ap +from os import path + +def remove_all_text_using_absorber3(infile, outfile): + with ap.Document(infile) as document: + absorber = ap.text.TextFragmentAbsorber() + absorber.remove_all_text( + document.pages[1], ap.Rectangle(10, 200, 120, 600, True) + ) + document.save(outfile) +``` -### Eliminar Todo el Texto usando Operadores +### Eliminar todo el Texto oculto de un documento PDF -En alguna operación de texto, necesitas eliminar todo el texto del documento PDF y para eso, usualmente necesitas establecer el texto encontrado como un valor de cadena vacía. El punto es que cambiar el texto para una multitud de fragmentos de texto invoca una serie de operaciones de verificación y ajuste de posición del texto. Son esenciales en los escenarios de edición de texto. La dificultad es que no puedes determinar cuántos fragmentos de texto serán eliminados en el escenario donde se procesan en un bucle. +Eliminar todo el texto de una región rectangular específica en una página usando Aspose.PDF’s TextFragmentAbsorber. +En lugar de borrar una página entera, este método realiza la eliminación de texto dirigida, permitiendo un control preciso sobre qué parte de la página se ve afectada. -Por lo tanto, recomendamos usar otro enfoque para el escenario de eliminar todo el texto de las páginas PDF. Por favor, considera el siguiente fragmento de código que funciona muy rápido. +1. Cargar el documento PDF. +1. Crear un TextFragmentAbsorber. +1. Definir el Área de Destino (Rectángulo). +1. Eliminar texto de la región especificada. +1. Conserve el resto del documento. +1. Guarda el PDF modificado. ```python -// Para ejemplos completos y archivos de datos, por favor visita https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); - -// Abrir documento -Document pdfDocument = new Document(dataDir + "RemoveAllText.pdf"); -// Recorrer todas las páginas del documento PDF -for (int i = 1; i <= pdfDocument.Pages.Count; i++) -{ - Page page = pdfDocument.Pages[i]; - OperatorSelector operatorSelector = new OperatorSelector(new Aspose.Pdf.Operators.TextShowOperator()); - // Seleccionar todo el texto en la página - page.Contents.Accept(operatorSelector); - // Eliminar todo el texto - page.Contents.Delete(operatorSelector.Selected); -} -// Guardar el documento -pdfDocument.Save(dataDir + "RemoveAllText_out.pdf", Aspose.Pdf.SaveFormat.Pdf); +import sys +import aspose.pdf as ap +from os import path + +def remove_hidden_text(infile, outfile): + # Open PDF document + with ap.Document(infile) as document: + text_absorber = ap.text.TextFragmentAbsorber() + # This option can be used to prevent other text fragments from moving after hidden text replacement + text_absorber.text_replace_options = ap.text.TextReplaceOptions( + ap.text.TextReplaceOptions.ReplaceAdjustment.NONE + ) + document.pages.accept(text_absorber) + # Remove hidden text + for fragment in text_absorber.text_fragments: + if fragment.text_state.invisible: + fragment.text = "" + # Save PDF document + document.save(outfile) ``` +## Temas de texto relacionados - \ No newline at end of file +- [Trabajar con texto en PDF usando Python](/pdf/es/python-net/working-with-text/) +- [Agregar texto al PDF](/pdf/es/python-net/add-text-to-pdf-file/) +- [Buscar y extraer texto PDF en Python](/pdf/es/python-net/search-and-get-text-from-pdf/) +- [Formatear texto PDF en Python](/pdf/es/python-net/text-formatting-inside-pdf/) diff --git a/es/python-net/advanced-operations/working-with-text/rotate-text-inside-pdf/_index.md b/es/python-net/advanced-operations/working-with-text/rotate-text-inside-pdf/_index.md index f1a0926a0..34822d742 100644 --- a/es/python-net/advanced-operations/working-with-text/rotate-text-inside-pdf/_index.md +++ b/es/python-net/advanced-operations/working-with-text/rotate-text-inside-pdf/_index.md @@ -1,315 +1,288 @@ --- -title: Rotar Texto Dentro de PDF usando Python -linktitle: Rotar Texto Dentro de PDF +title: Rotar texto PDF en Python +linktitle: Rotar texto dentro del PDF type: docs weight: 50 url: /es/python-net/rotate-text-inside-pdf/ -description: Aprenda diferentes maneras de rotar texto en PDF. Aspose.PDF le permite rotar texto a cualquier ángulo, rotar un fragmento de texto o un párrafo completo. -lastmod: "2024-02-17" +description: Aprenda cómo rotar fragmentos de texto y párrafos dentro de documentos PDF en Python. +lastmod: "2026-05-05" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Rotar fragmentos de texto y párrafos en documentos PDF con Python +Abstract: Este artículo explica cómo rotar texto en documentos PDF usando Aspose.PDF for Python via .NET. Muestra cómo establecer la propiedad `rotation` en `TextFragment`, crear contenido rotado con `TextBuilder` y `TextParagraph`, y añadir texto rotado directamente a los párrafos de la página para diferentes escenarios de diseño. --- - - - -## Rotar Texto Dentro de un PDF usando la Propiedad de Rotación - -Usando la propiedad de Rotación de la Clase [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment), puedes rotar texto en varios ángulos. La rotación de texto se puede utilizar en diferentes escenarios de generación de documentos. Puedes especificar el ángulo de rotación en grados para rotar el texto según tu requerimiento. Por favor, revisa los siguientes diferentes escenarios, en los cuales puedes implementar la rotación de texto. - -## Implementar Rotación usando TextFragment y TextBuilder - -```csharp -// Para ejemplos completos y archivos de datos, por favor visita https://github.com/aspose-pdf/Aspose.PDF-for-.NET -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -// Inicializar objeto de documento -Document pdfDocument = new Document(); -// Obtener una página en particular -Page pdfPage = (Page)pdfDocument.Pages.Add(); -// Crear fragmento de texto -TextFragment textFragment1 = new TextFragment("texto principal"); -textFragment1.Position = new Position(100, 600); -// Establecer propiedades del texto -textFragment1.TextState.FontSize = 12; -textFragment1.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -// Crear fragmento de texto rotado -TextFragment textFragment2 = new TextFragment("texto rotado"); -textFragment2.Position = new Position(200, 600); -// Establecer propiedades del texto -textFragment2.TextState.FontSize = 12; -textFragment2.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -textFragment2.TextState.Rotation = 45; -// Crear fragmento de texto rotado -TextFragment textFragment3 = new TextFragment("texto rotado"); -textFragment3.Position = new Position(300, 600); -// Establecer propiedades del texto -textFragment3.TextState.FontSize = 12; -textFragment3.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -textFragment3.TextState.Rotation = 90; -// crear objeto TextBuilder -TextBuilder textBuilder = new TextBuilder(pdfPage); -// Añadir el fragmento de texto a la página PDF -textBuilder.AppendText(textFragment1); -textBuilder.AppendText(textFragment2); -textBuilder.AppendText(textFragment3); -// Guardar documento -pdfDocument.Save(dataDir + "TextFragmentTests_Rotated1_out.pdf"); + +Gire fragmentos de texto en un documento PDF usando Aspose.PDF for Python via .NET. Esta página muestra cómo controlar la posición y rotación del texto mediante `TextFragment`, `TextState`, y `TextBuilder`. Ajustando los ángulos de rotación, puedes crear diseños como encabezados diagonales, etiquetas verticales y anotaciones rotadas. + +## Rotar fragmentos de texto usando TextBuilder en PDF + +Crea un archivo PDF llamado `rotated_fragments.pdf` contiene tres fragmentos de texto alineados horizontalmente: + +- el primer texto está sin rotar +- el segundo está rotado 45° +- el tercero está rotado 90° + +1. Crear un nuevo documento PDF. +1. Inserte una nueva página para alojar el texto rotado. +1. Cree el primer fragmento de texto (sin rotación). +1. Cree el segundo fragmento de texto (rotación de 45°). +1. Cree el tercer fragmento de texto (rotación de 90°). +1. Agregar fragmentos de texto usando `TextBuilder`. +1. Guarde el documento. + +```python +import aspose.pdf as ap + +def rotate_text_inside_pdf_1(outfile): + # Create PDF document + with ap.Document() as document: + # Get particular page + page = document.pages.add() + # Create text fragment + text_fragment_1 = ap.text.TextFragment("main text") + text_fragment_1.position = ap.text.Position(100, 600) + # Set text properties + text_fragment_1.text_state.font_size = 12 + text_fragment_1.text_state.font = ap.text.FontRepository.find_font( + "TimesNewRoman" + ) + # Create rotated text fragment + text_fragment_2 = ap.text.TextFragment("rotated text") + text_fragment_2.position = ap.text.Position(200, 600) + # Set text properties + text_fragment_2.text_state.font_size = 12 + text_fragment_2.text_state.font = ap.text.FontRepository.find_font( + "TimesNewRoman" + ) + text_fragment_2.text_state.rotation = 45 + # Create rotated text fragment + text_fragment_3 = ap.text.TextFragment("rotated text") + text_fragment_3.position = ap.text.Position(300, 600) + # Set text properties + text_fragment_3.text_state.font_size = 12 + text_fragment_3.text_state.font = ap.text.FontRepository.find_font( + "TimesNewRoman" + ) + text_fragment_3.text_state.rotation = 90 + # create TextBuilder object + builder = ap.text.TextBuilder(page) + # Append the text fragment to the PDF page + builder.append_text(text_fragment_1) + builder.append_text(text_fragment_2) + builder.append_text(text_fragment_3) + + # Save the document + document.save(outfile) ``` +## Rotar fragmentos de texto individuales dentro de un párrafo en PDF + +Rotar fragmentos de texto individuales dentro de un párrafo. Muestra cómo crear un párrafo de varias líneas (TextParagraph) que contiene múltiples fragmentos (TextFragment), cada uno con su propio ángulo de rotación. Esta técnica es útil para crear documentos visualmente ricos que combinan texto orientado horizontal y diagonalmente — por ejemplo, encabezados estilizados, diagramas o etiquetas anotadas. + +Crea un PDF llamado `rotated_paragraph_fragments.pdf` contiene un párrafo con tres líneas de texto, cada línea rotada de manera diferente: + +- la primera línea está rotada 45° +- la segunda línea permanece horizontal (0°) +- la tercera línea está rotada -45° + +1. Crear un nuevo documento PDF. +1. Agrega una página en blanco donde aparecerá el texto rotado. +1. Cree un `TextParagraph`. +1. Crea y configura el primer fragmento de texto (+45° de rotación). +1. Crea el segundo fragmento de texto (sin rotación). +1. Crea el tercer fragmento de texto (-45° de rotación). +1. Agregar fragmentos de texto al párrafo. +1. Agregar el párrafo a la página usando `TextBuilder`. +1. Guarde el documento. + +```python +import aspose.pdf as ap -## Implementar Rotación usando TextParagraph y TextBuilder (Fragmentos Rotados) - -```csharp -// Para obtener ejemplos completos y archivos de datos, por favor visite https://github.com/aspose-pdf/Aspose.PDF-for-.NET -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -// Inicializar objeto de documento -Document pdfDocument = new Document(); -// Obtener página particular -Page pdfPage = (Page)pdfDocument.Pages.Add(); -TextParagraph paragraph = new TextParagraph(); -paragraph.Position = new Position(200, 600); -// Crear fragmento de texto -TextFragment textFragment1 = new TextFragment("texto rotado"); -// Establecer propiedades de texto -textFragment1.TextState.FontSize = 12; -textFragment1.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -// Establecer rotación -textFragment1.TextState.Rotation = 45; -// Crear fragmento de texto -TextFragment textFragment2 = new TextFragment("texto principal"); -// Establecer propiedades de texto -textFragment2.TextState.FontSize = 12; -textFragment2.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -// Crear fragmento de texto -TextFragment textFragment3 = new TextFragment("otro texto rotado"); -// Establecer propiedades de texto -textFragment3.TextState.FontSize = 12; -textFragment3.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -// Establecer rotación -textFragment3.TextState.Rotation = -45; -// Añadir los fragmentos de texto al párrafo -paragraph.AppendLine(textFragment1); -paragraph.AppendLine(textFragment2); -paragraph.AppendLine(textFragment3); -// Crear objeto TextBuilder -TextBuilder textBuilder = new TextBuilder(pdfPage); -// Añadir el párrafo de texto a la página PDF -textBuilder.AppendParagraph(paragraph); -// Guardar documento -pdfDocument.Save(dataDir + "TextFragmentTests_Rotated2_out.pdf"); +def rotate_text_inside_pdf_2(outfile): + # Create PDF document + with ap.Document() as document: + # Get particular page + page = document.pages.add() + paragraph = ap.text.TextParagraph() + paragraph.position = ap.text.Position(200, 600) + # Create text fragment + text_fragment_1 = ap.text.TextFragment("rotated text") + # Set text properties + text_fragment_1.text_state.font_size = 12 + text_fragment_1.text_state.font = ap.text.FontRepository.find_font( + "TimesNewRoman" + ) + # Set rotation + text_fragment_1.text_state.rotation = 45 + # Create text fragment + text_fragment_2 = ap.text.TextFragment("main text") + # Set text properties + text_fragment_2.text_state.font_size = 12 + text_fragment_2.text_state.font = ap.text.FontRepository.find_font( + "TimesNewRoman" + ) + # Create text fragment + text_fragment_3 = ap.text.TextFragment("another rotated text") + # Set text properties + text_fragment_3.text_state.font_size = 12 + text_fragment_3.text_state.font = ap.text.FontRepository.find_font( + "TimesNewRoman" + ) + # Set rotation + text_fragment_3.text_state.rotation = -45 + # Append the text fragments to the paragraph + paragraph.append_line(text_fragment_1) + paragraph.append_line(text_fragment_2) + paragraph.append_line(text_fragment_3) + # Create TextBuilder object + text_builder = ap.text.TextBuilder(page) + # Append the text paragraph to the PDF page + text_builder.append_paragraph(paragraph) + + # Save the document + document.save(outfile) ``` +## Rotar texto usando párrafos de página en PDF + +Esta sección muestra un método simplificado para rotar texto dentro de un PDF utilizando Aspose.PDF for Python via .NET. +A diferencia de los enfoques de bajo nivel con `TextBuilder` o `TextParagraph`, este método agrega fragmentos de texto rotados directamente a la colección de párrafos de la página (`page.paragraphs`). Es ideal cuando necesitas rotación básica de texto pero no requieres posicionamiento preciso ni estructuración de párrafos. + +Genera un archivo llamado `simple_rotated_text.pdf` contiene: + +- un fragmento de texto horizontal principal con rotación 0° +- Fragmento rotado 315° +- Fragmento rotado 270° + +1. Inicializar un nuevo documento PDF. +1. Crear una página donde se colocará el texto rotado. +1. Cree el primer fragmento de texto (sin rotación). +1. Crea el segundo fragmento de texto (rotación de 315°). +1. Crea el tercer fragmento de texto (rotación de 270°). +1. Agregar fragmentos de texto directamente a los párrafos de la página. +1. Guarde el documento PDF. + +```python +import aspose.pdf as ap + +def rotate_text_inside_pdf_3(outfile): + # Create PDF document + with ap.Document() as document: + # Get particular page + page = document.pages.add() + # Create text fragment + text_fragment_1 = ap.text.TextFragment("main text") + # Set text properties + text_fragment_1.text_state.font_size = 12 + text_fragment_1.text_state.font = ap.text.FontRepository.find_font( + "TimesNewRoman" + ) + # Create text fragment + text_fragment_2 = ap.text.TextFragment("rotated text") + # Set text properties + text_fragment_2.text_state.font_size = 12 + text_fragment_2.text_state.font = ap.text.FontRepository.find_font( + "TimesNewRoman" + ) + # Set rotation + text_fragment_2.text_state.rotation = 315 + # Create text fragment + text_fragment_3 = ap.text.TextFragment("rotated text") + # Set text properties + text_fragment_3.text_state.font_size = 12 + text_fragment_3.text_state.font = ap.text.FontRepository.find_font( + "TimesNewRoman" + ) + # Set rotation + text_fragment_3.text_state.rotation = 270 + page.paragraphs.add(text_fragment_1) + page.paragraphs.add(text_fragment_2) + page.paragraphs.add(text_fragment_3) -## Implementar Rotación usando TextFragment y Page.Paragraphs - -```csharp -// Para ejemplos completos y archivos de datos, por favor visita https://github.com/aspose-pdf/Aspose.PDF-for-.NET -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -// Inicializar objeto documento -Document pdfDocument = new Document(); -// Obtener página particular -Page pdfPage = (Page)pdfDocument.Pages.Add(); -// Crear fragmento de texto -TextFragment textFragment1 = new TextFragment("texto principal"); -// Establecer propiedades de texto -textFragment1.TextState.FontSize = 12; -textFragment1.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -// Crear fragmento de texto -TextFragment textFragment2 = new TextFragment("texto rotado"); -// Establecer propiedades de texto -textFragment2.TextState.FontSize = 12; -textFragment2.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -// Establecer rotación -textFragment2.TextState.Rotation = 315; -// Crear fragmento de texto -TextFragment textFragment3 = new TextFragment("texto rotado"); -// Establecer propiedades de texto -textFragment3.TextState.FontSize = 12; -textFragment3.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -// Establecer rotación -textFragment3.TextState.Rotation = 270; -pdfPage.Paragraphs.Add(textFragment1); -pdfPage.Paragraphs.Add(textFragment2); -pdfPage.Paragraphs.Add(textFragment3); -// Guardar documento -pdfDocument.Save(dataDir + "TextFragmentTests_Rotated3_out.pdf"); + # Save the document + document.save(outfile) ``` +## Rotar párrafos completos en un PDF + +Este ejemplo muestra la rotación avanzada de texto a nivel de párrafo en un PDF. A diferencia de la rotación a nivel de fragmento (donde cada pieza de texto se rota individualmente), este método rota párrafos enteros como bloques unificados en diferentes ángulos. +Cada párrafo contiene múltiples fragmentos de texto con estilo, y el párrafo completo se gira en ángulos específicos — permitiendo transformaciones de diseño complejas y consistentes. +Esto es ideal para diseños artísticos, marcas de agua o PDFs con mucho diseño donde se necesitan orientar secciones completas de texto en varias direcciones. + +Crea `rotated_paragraphs.pdf`, que contiene cuatro párrafos totalmente estilizados y girados: + +- cada uno rotado a un ángulo único (45°, 135°, 225° y 315°) +- cada párrafo tiene tres líneas de texto con fondos de colores, subrayado y estilo coherente + +1. Crear un nuevo documento PDF. +1. Agregar una página en blanco para contener los párrafos rotados. +1. Iterar para crear varios párrafos. +1. Crear y posicionar el párrafo. +1. Crear fragmentos de texto con formato. +1. Aplicar formato de texto. +1. Agregar fragmentos de texto al párrafo. +1. Agregar el párrafo a la página usando `TextBuilder`. +1. Repita para las cuatro rotaciones. +1. Guarde el documento PDF. + +```python +import aspose.pdf as ap + +def rotate_text_inside_pdf_4(outfile): + # Create PDF document + with ap.Document() as document: + # Get particular page + page = document.pages.add() + for i in range(4): + paragraph = ap.text.TextParagraph() + paragraph.position = ap.text.Position(200, 600) + # Specify rotation + paragraph.rotation = i * 90 + 45 + # Create text fragment + text_fragment_1 = ap.text.TextFragment("Paragraph Text") + # Create text fragment + text_fragment_1.text_state.font_size = 12 + text_fragment_1.text_state.font = ap.text.FontRepository.find_font( + "TimesNewRoman" + ) + text_fragment_1.text_state.background_color = ap.Color.light_gray + text_fragment_1.text_state.foreground_color = ap.Color.blue + # Create text fragment + text_fragment_2 = ap.text.TextFragment("Second line of text") + # Set text properties + text_fragment_2.text_state.font_size = 12 + text_fragment_2.text_state.font = ap.text.FontRepository.find_font( + "TimesNewRoman" + ) + text_fragment_2.text_state.background_color = ap.Color.light_gray + text_fragment_2.text_state.foreground_color = ap.Color.blue + # Create text fragment + text_fragment_3 = ap.text.TextFragment("And some more text...") + # Set text properties + text_fragment_3.text_state.font_size = 12 + text_fragment_3.text_state.font = ap.text.FontRepository.find_font( + "TimesNewRoman" + ) + text_fragment_3.text_state.background_color = ap.Color.light_gray + text_fragment_3.text_state.foreground_color = ap.Color.blue + text_fragment_3.text_state.underline = True + paragraph.append_line(text_fragment_1) + paragraph.append_line(text_fragment_2) + paragraph.append_line(text_fragment_3) + # Create TextBuilder object + builder = ap.text.TextBuilder(page) + # Append the text fragment to the PDF page + builder.append_paragraph(paragraph) -## Implementar Rotación usando TextParagraph y TextBuilder (Párrafo Completo Rotado) - -```csharp -// Para ejemplos completos y archivos de datos, por favor visite https://github.com/aspose-pdf/Aspose.PDF-for-.NET -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -// Inicializar objeto de documento -Document pdfDocument = new Document(); -// Obtener página particular -Page pdfPage = (Page)pdfDocument.Pages.Add(); -for (int i = 0; i < 4; i++) -{ - TextParagraph paragraph = new TextParagraph(); - paragraph.Position = new Position(200, 600); - // Especificar rotación - paragraph.Rotation = i * 90 + 45; - // Crear fragmento de texto - TextFragment textFragment1 = new TextFragment("Texto del Párrafo"); - // Crear fragmento de texto - textFragment1.TextState.FontSize = 12; - textFragment1.TextState.Font = FontRepository.FindFont("TimesNewRoman"); - textFragment1.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray; - textFragment1.TextState.ForegroundColor = Aspose.Pdf.Color.Blue; - // Crear fragmento de texto - TextFragment textFragment2 = new TextFragment("Segunda línea de texto"); - // Establecer propiedades del texto - textFragment2.TextState.FontSize = 12; - textFragment2.TextState.Font = FontRepository.FindFont("TimesNewRoman"); - textFragment2.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray; - textFragment2.TextState.ForegroundColor = Aspose.Pdf.Color.Blue; - // Crear fragmento de texto - TextFragment textFragment3 = new TextFragment("Y algo más de texto..."); - // Establecer propiedades del texto - textFragment3.TextState.FontSize = 12; - textFragment3.TextState.Font = FontRepository.FindFont("TimesNewRoman"); - textFragment3.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray; - textFragment3.TextState.ForegroundColor = Aspose.Pdf.Color.Blue; - textFragment3.TextState.Underline = true; - paragraph.AppendLine(textFragment1); - paragraph.AppendLine(textFragment2); - paragraph.AppendLine(textFragment3); - // Crear objeto TextBuilder - TextBuilder textBuilder = new TextBuilder(pdfPage); - // Añadir el fragmento de texto a la página del PDF - textBuilder.AppendParagraph(paragraph); -} -// Guardar documento -pdfDocument.Save(dataDir + "TextFragmentTests_Rotated4_out.pdf"); + # Save the document + document.save(outfile) ``` +## Temas de texto relacionados - \ No newline at end of file +- [Trabajar con texto en PDF usando Python](/pdf/es/python-net/working-with-text/) +- [Agregar texto al PDF](/pdf/es/python-net/add-text-to-pdf-file/) +- [Formatear texto PDF en Python](/pdf/es/python-net/text-formatting-inside-pdf/) +- [Reemplazar texto en PDF con Python](/pdf/es/python-net/replace-text-in-pdf/) \ No newline at end of file diff --git a/es/python-net/advanced-operations/working-with-text/seach-and-get-text-from-pdf/_index.md b/es/python-net/advanced-operations/working-with-text/seach-and-get-text-from-pdf/_index.md index 384b7dc20..207836b39 100644 --- a/es/python-net/advanced-operations/working-with-text/seach-and-get-text-from-pdf/_index.md +++ b/es/python-net/advanced-operations/working-with-text/seach-and-get-text-from-pdf/_index.md @@ -1,555 +1,430 @@ --- -title: Buscar y Obtener Texto de las Páginas de PDF -linktitle: Buscar y Obtener Texto +title: Buscar y extraer texto PDF en Python +linktitle: Buscar y obtener texto type: docs weight: 60 url: /es/python-net/search-and-get-text-from-pdf/ -description: Este artículo explica cómo usar varias herramientas para buscar y obtener texto de Aspose.PDF para .NET. -lastmod: "2024-02-17" +description: Aprenda cómo buscar, inspeccionar y extraer texto de documentos PDF en Python. +lastmod: "2026-05-05" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Busque texto en PDF e inspeccione fragmentos extraídos en Python +Abstract: Este artículo explica cómo buscar y extraer texto de documentos PDF utilizando Aspose.PDF for Python via .NET. Cubre `TextAbsorber` y `TextFragmentAbsorber`, incluyendo extracción basada en regiones, búsquedas específicas por página, coincidencia de frases y inspección de la posición del texto y las propiedades de Font. --- - - - -## Buscar y Obtener Texto de Todas las Páginas del Documento PDF - -La clase [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber) te permite encontrar texto que coincide con una frase particular en todas las páginas de un documento PDF. Para buscar texto en todo el documento, necesitas llamar al método Accept de la colección Pages. El método [Accept](https://reference.aspose.com/pdf/python-net/aspose.pdf.page/accept/methods/3) toma un objeto TextFragmentAbsorber como parámetro, el cual devuelve una colección de objetos TextFragment. Puedes iterar a través de todos los fragmentos y obtener sus propiedades como Text, Position (XIndent, YIndent), FontName, FontSize, IsAccessible, IsEmbedded, IsSubset, ForegroundColor, etc. - -El siguiente fragmento de código te muestra cómo buscar texto en todas las páginas. - -```csharp -// Para ejemplos completos y archivos de datos, por favor visita https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); - -// Abrir documento -Document pdfDocument = new Document(dataDir + "SearchAndGetTextFromAll.pdf"); - -// Crear objeto TextAbsorber para encontrar todas las instancias de la frase de búsqueda ingresada -TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("text"); - -// Aceptar el absorbedor para todas las páginas -pdfDocument.Pages.Accept(textFragmentAbsorber); - -// Obtener los fragmentos de texto extraídos -TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; - -// Iterar a través de los fragmentos -foreach (TextFragment textFragment in textFragmentCollection) -{ - - Console.WriteLine("Texto : {0} ", textFragment.Text); - Console.WriteLine("Posición : {0} ", textFragment.Position); - Console.WriteLine("XIndent : {0} ", textFragment.Position.XIndent); - Console.WriteLine("YIndent : {0} ", textFragment.Position.YIndent); - Console.WriteLine("Fuente - Nombre : {0}", textFragment.TextState.Font.FontName); - Console.WriteLine("Fuente - EsAccesible : {0} ", textFragment.TextState.Font.IsAccessible); - Console.WriteLine("Fuente - EstáIncrustada : {0} ", textFragment.TextState.Font.IsEmbedded); - Console.WriteLine("Fuente - EsSubset : {0} ", textFragment.TextState.Font.IsSubset); - Console.WriteLine("Tamaño de Fuente : {0} ", textFragment.TextState.FontSize); - Console.WriteLine("Color de Primer Plano : {0} ", textFragment.TextState.ForegroundColor); -} -``` +## Buscar texto en PDF -En caso de que necesite buscar texto dentro de cualquier página PDF en particular, especifique el número de página de la colección de páginas de la instancia del Documento y llame al método Accept contra esa página (como se muestra en la línea de código a continuación). +Buscar y extraer texto de un área rectangular definida en un documento PDF usando el `TextAbsorber` clase. Utiliza el modo de formato de texto puro para una salida limpia y sin formato, lo que es útil para extraer contenido de regiones estructuradas como encabezados, pies de página o áreas de tabla. Al combinar `TextExtractionOptions` y `TextSearchOptions` con restricciones rectangulares, puedes controlar dónde y cómo se extrae el texto. -```csharp -// Para ejemplos completos y archivos de datos, por favor visite https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// Aceptar el absorbedor para una página en particular -pdfDocument.Pages[2].Accept(textFragmentAbsorber); -``` +Utilice esta página cuando necesite auditar el contenido de texto del PDF, extraer texto para análisis o inspeccionar las posiciones y el formato de los fragmentos de texto coincidentes. -## Buscar y Obtener Segmentos de Texto de Todas las Páginas del Documento PDF - -Para buscar segmentos de texto de todas las páginas, primero necesita obtener los objetos TextFragment del documento. - TextFragmentAbsorber te permite encontrar texto que coincide con una frase particular en todas las páginas de un documento PDF. Para buscar texto en todo el documento, necesitas llamar al método Accept de la colección Pages. El método Accept toma un objeto TextFragmentAbsorber como parámetro, que devuelve una colección de objetos TextFragment. Una vez que la TextFragmentCollection se extrae del documento, necesitas recorrer esta colección y obtener TextSegmentCollection de cada objeto TextFragment. Después de eso, puedes obtener todas las propiedades del objeto TextSegment individual. El siguiente fragmento de código te muestra cómo buscar segmentos de texto en todas las páginas. - -```csharp -// Para ejemplos completos y archivos de datos, por favor visita https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); - -// Abrir documento -Document pdfDocument = new Document(dataDir + "SearchAndGetTextPage.pdf"); - -// Crear objeto TextAbsorber para encontrar todas las instancias de la frase de búsqueda de entrada -TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("Figura"); -// Aceptar el absorber para todas las páginas -pdfDocument.Pages.Accept(textFragmentAbsorber); -// Obtener los fragmentos de texto extraídos -TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; -// Recorrer los fragmentos -foreach (TextFragment textFragment in textFragmentCollection) -{ - foreach (TextSegment textSegment in textFragment.Segments) - { - Console.WriteLine("Texto : {0} ", textSegment.Text); - Console.WriteLine("Posición : {0} ", textSegment.Position); - Console.WriteLine("XIndent : {0} ", textSegment.Position.XIndent); - Console.WriteLine("YIndent : {0} ", textSegment.Position.YIndent); - Console.WriteLine("Fuente - Nombre : {0}", textSegment.TextState.Font.FontName); - Console.WriteLine("Fuente - EsAccesible : {0} ", textSegment.TextState.Font.IsAccessible); - Console.WriteLine("Fuente - EstáIncorporada : {0} ", textSegment.TextState.Font.IsEmbedded); - Console.WriteLine("Fuente - EsSubconjunto : {0} ", textSegment.TextState.Font.IsSubset); - Console.WriteLine("Tamaño de Fuente : {0} ", textSegment.TextState.FontSize); - Console.WriteLine("Color de Primer Plano : {0} ", textSegment.TextState.ForegroundColor); - } -} -``` +1. Cargue el archivo PDF usando 'ap.Document'. +1. Configurar opciones de extracción de texto. +1. Definir área de búsqueda con restricciones de rectángulo. +1. Crear y Configurar TextAbsorber. +1. Procesar todas las páginas del documento. +1. Recuperar y mostrar texto extraído. + +```python +import io +import sys +import shutil +import aspose.pdf as ap +import aspose.pydrawing as drawing +from os import path + +def text_absorber_search(input_file_path): + # Open PDF document + document = ap.Document(input_file_path) + + text_extraction_options = ap.text.TextExtractionOptions( + ap.text.TextExtractionOptions.TextFormattingMode.PURE + ) + text_search_options = ap.text.TextSearchOptions(ap.Rectangle(0, 0, 842, 250, True)) -Para buscar y obtener TextSegments de una página particular de un PDF, necesitas especificar el índice de la página particular al llamar al método Accept(..). Por favor, revisa las siguientes líneas de código. + absorber = ap.text.TextAbsorber(text_extraction_options, text_search_options) -```csharp -// Para ejemplos completos y archivos de datos, por favor visita https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// Aceptar el absorbedor para todas las páginas -pdfDocument.Pages[2].Accept(textFragmentAbsorber); + # Process all pages + document.pages.accept(absorber) + + print(f"Text fragments found: {absorber.text}") ``` -## Buscar y Obtener Texto de todas las páginas usando Expresión Regular +## Buscar texto en una página PDF específica -TextFragmentAbsorber te ayuda a buscar y recuperar texto, de todas las páginas, basado en una expresión regular. - Primero, necesitas pasar una expresión regular al constructor de TextFragmentAbsorber como la frase. Después de eso, debes establecer la propiedad TextSearchOptions del objeto TextFragmentAbsorber. Esta propiedad requiere un objeto TextSearchOptions y necesitas pasar true como parámetro a su constructor al crear nuevos objetos. Como deseas recuperar texto coincidente de todas las páginas, necesitas llamar al método Accept de la colección Pages. TextFragmentAbsorber devuelve un TextFragmentCollection que contiene todos los fragmentos que coinciden con los criterios especificados por la expresión regular. El siguiente fragmento de código te muestra cómo buscar y obtener texto de todas las páginas basado en una expresión regular. +Buscar y extraer texto de una página y región específicas en un PDF utilizando TextAbsorber de Aspose.PDF. Se dirige a la página 2 del documento y extrae solo el texto encontrado dentro de un área rectangular definida. +Al combinar TextExtractionOptions (para controlar el formato) y TextSearchOptions (para limitar el área), puedes realizar una extracción de texto precisa y específica de página de manera eficiente. -```csharp -// Para ejemplos completos y archivos de datos, por favor visita https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); +1. Cargar el documento PDF. +1. Configura las opciones de extracción de texto. +1. Restringir la extracción de texto a un área rectangular específica en la página. +1. Crear y Configurar TextAbsorber. +1. Procesar una página específica. +1. Recuperar y mostrar texto extraído. -// Abrir documento -Document pdfDocument = new Document(dataDir + "SearchRegularExpressionAll.pdf"); +```python +import io +import sys +import shutil +import aspose.pdf as ap +import aspose.pydrawing as drawing +from os import path -// Crear objeto TextAbsorber para encontrar todas las frases que coinciden con la expresión regular -TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("\\d{4}-\\d{4}"); // Como 1999-2000 +def text_absorber_search_page(input_file_path): + document = ap.Document(input_file_path) -// Establecer la opción de búsqueda de texto para especificar el uso de la expresión regular -TextSearchOptions textSearchOptions = new TextSearchOptions(true); + text_extraction_options = ap.text.TextExtractionOptions( + ap.text.TextExtractionOptions.TextFormattingMode.PURE + ) + text_search_options = ap.text.TextSearchOptions(ap.Rectangle(0, 0, 842, 250, True)) -textFragmentAbsorber.TextSearchOptions = textSearchOptions; + absorber = ap.text.TextAbsorber(text_extraction_options, text_search_options) -// Aceptar el absorbente para todas las páginas -pdfDocument.Pages.Accept(textFragmentAbsorber); + # Only page 2 + document.pages[2].accept(absorber) -// Obtener los fragmentos de texto extraídos -TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; + print(f"Text fragments found: {absorber.text}") +``` -// Recorrer los fragmentos -foreach (TextFragment textFragment in textFragmentCollection) -{ - Console.WriteLine("Texto : {0} ", textFragment.Text); - Console.WriteLine("Posición : {0} ", textFragment.Position); - Console.WriteLine("XIndent : {0} ", textFragment.Position.XIndent); - Console.WriteLine("YIndent : {0} ", textFragment.Position.YIndent); - Console.WriteLine("Fuente - Nombre : {0}", textFragment.TextState.Font.FontName); - Console.WriteLine("Fuente - EsAccesible : {0} ", textFragment.TextState.Font.IsAccessible); - Console.WriteLine("Fuente - EsIncorporada : {0} ", textFragment.TextState.Font.IsEmbedded); - Console.WriteLine("Fuente - EsSubconjunto : {0} ", textFragment.TextState.Font.IsSubset); - Console.WriteLine("Tamaño de Fuente : {0} ", textFragment.TextState.FontSize); - Console.WriteLine("Color de Primer Plano : {0} ", textFragment.TextState.ForegroundColor); -} +## Analizar y extraer propiedades detalladas de fragmentos de texto de un PDF + +A diferencia de TextAbsorber, que extrae texto sin formato, TextFragmentAbsorber proporciona información detallada y de bajo nivel sobre cada fragmento de texto, como su posición, atributos de fuente, color y detalles de incrustación. + +1. Cargar el documento PDF. +1. Inicializar TextFragmentAbsorber. +1. Procesar todas las páginas del documento. +1. Iterar a través de fragmentos de texto extraídos. +1. Imprimir información básica de texto. +1. Imprimir detalles de fuente y formato. + +```python +import io +import sys +import shutil +import aspose.pdf as ap +import aspose.pydrawing as drawing +from os import path + +def text_fragment_absorber_search(input_file_path): + document = ap.Document(input_file_path) + + absorber = ap.text.TextFragmentAbsorber() + document.pages.accept(absorber) + + for fragment in absorber.text_fragments: + print("Text:", fragment.text) + print("Position:", fragment.position) + print("XIndent:", fragment.position.x_indent) + print("YIndent:", fragment.position.y_indent) + print("Font - Name:", fragment.text_state.font.font_name) + print("Font - IsAccessible:", fragment.text_state.font.is_accessible) + print("Font - IsEmbedded:", fragment.text_state.font.is_embedded) + print("Font - IsSubset:", fragment.text_state.font.is_subset) + print("Font Size:", fragment.text_state.font_size) + print("Foreground Color:", fragment.text_state.foreground_color) ``` -```csharp -// Para ejemplos completos y archivos de datos, por favor visite https://github.com/aspose-pdf/Aspose.PDF-for-.NET -TextFragmentAbsorber textFragmentAbsorber; -// Para buscar una coincidencia exacta de una palabra, puede considerar usar una expresión regular. -textFragmentAbsorber = new TextFragmentAbsorber(@"\bWord\b", new TextSearchOptions(true)); +## Buscar una frase de texto específica en una sola página PDF + +Buscar una frase de texto específica dentro de una página de un documento PDF usando TextFragmentAbsorber. A diferencia de buscar en todo el documento, este enfoque limita la búsqueda a una sola página, lo que lo hace más eficiente para confirmar la presencia y ubicación del texto en áreas específicas como encabezados, pies de página o secciones de contenido concretas. -// Para buscar una cadena en mayúsculas o minúsculas, puede considerar usar una expresión regular. -textFragmentAbsorber = new TextFragmentAbsorber("(?i)Line", new TextSearchOptions(true)); +1. Cargar el documento PDF. +1. Inicializar TextFragmentAbsorber con frase de búsqueda. +1. Aplicar Absorber a una página específica. +1. Iterar sobre fragmentos encontrados. -// Para buscar todas las cadenas (analizar todas las cadenas) dentro del documento PDF, por favor intente usar la siguiente expresión regular. -textFragmentAbsorber = new TextFragmentAbsorber(@"[\S]+"); +```python +import io +import sys +import shutil +import aspose.pdf as ap +import aspose.pydrawing as drawing +from os import path -// Encontrar coincidencia de la cadena de búsqueda y obtener cualquier cosa después de la cadena hasta el salto de línea. -textFragmentAbsorber = new TextFragmentAbsorber(@"(?i)the ((.)*)"); +def text_fragment_absorber_search_page(input_file_path): + document = ap.Document(input_file_path) -// Por favor use la siguiente expresión regular para encontrar texto siguiendo la coincidencia del regex. -textFragmentAbsorber = new TextFragmentAbsorber(@"(?<=word).*"); + absorber = ap.text.TextFragmentAbsorber("whale") + document.pages[2].accept(absorber) -// Para buscar Hipervínculos/URL's dentro del documento PDF, por favor intente usar la siguiente expresión regular. -textFragmentAbsorber = new TextFragmentAbsorber(@"(http|ftp|https):\/\/([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?"); + for fragment in absorber.text_fragments: + print("Text:", fragment.text) + print("Position:", fragment.position) ``` +## Búsqueda secuencial de texto página por página con resultados acumulados -## Buscar Texto basado en Regex y Agregar Hipervínculo - -Si deseas agregar un hipervínculo sobre una frase de texto basada en una expresión regular, primero encuentra todas las frases que coinciden con esa expresión regular particular usando TextFragmentAbsorber y agrega un hipervínculo sobre estas frases. - -Para encontrar una frase y agregar un hipervínculo sobre ella: - -1. Pasa la expresión regular como un parámetro al constructor de TextFragmentAbsorber. -2. Crea un objeto TextSearchOptions que especifique si se usa la expresión regular o no. -3. Obtén las frases coincidentes en TextFragments. -4. Recorre las coincidencias para obtener sus dimensiones rectangulares, cambia el color de primer plano a azul (opcional - para que parezca un hipervínculo y crea un enlace usando el método CreateWebLink(..) de la clase PdfContentEditor. -5. Guarda el PDF actualizado usando el método Save del objeto Document. El siguiente fragmento de código te muestra cómo buscar texto dentro de un archivo PDF usando una expresión regular y agregar hipervínculos sobre las coincidencias. - -```csharp -// Para ejemplos completos y archivos de datos, por favor visita https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -// Crea un objeto absorber para encontrar todas las instancias de la frase de búsqueda de entrada -TextFragmentAbsorber absorber = new TextFragmentAbsorber("\\d{4}-\\d{4}"); -// Habilitar búsqueda con expresión regular -absorber.TextSearchOptions = new TextSearchOptions(true); -// Abrir documento -PdfContentEditor editor = new PdfContentEditor(); -// Vincular archivo PDF de origen -editor.BindPdf(dataDir + "SearchRegularExpressionPage.pdf"); -// Aceptar el absorbedor para la página -editor.Document.Pages[1].Accept(absorber); - -int[] dashArray = { }; -String[] LEArray = { }; -System.Drawing.Color blue = System.Drawing.Color.Blue; - -// Recorrer los fragmentos -foreach (TextFragment textFragment in absorber.TextFragments) -{ - textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Blue; - System.Drawing.Rectangle rect = new System.Drawing.Rectangle((int)textFragment.Rectangle.LLX, - (int)Math.Round(textFragment.Rectangle.LLY), (int)Math.Round(textFragment.Rectangle.Width + 2), - (int)Math.Round(textFragment.Rectangle.Height + 1)); - Enum[] actionName = new Enum[2] { Aspose.Pdf.Annotations.PredefinedAction.Document_AttachFile, Aspose.Pdf.Annotations.PredefinedAction.Document_ExtractPages }; - editor.CreateWebLink(rect, "http:// Www.aspose.com", 1, blue, actionName); - editor.CreateLine(rect, "", (float)textFragment.Rectangle.LLX + 1, (float)textFragment.Rectangle.LLY - 1, - (float)textFragment.Rectangle.URX, (float)textFragment.Rectangle.LLY - 1, 1, 1, blue, "S", dashArray, LEArray); -} - -dataDir = dataDir + "SearchTextAndAddHyperlink_out.pdf"; -editor.Save(dataDir); -editor.Close(); -``` +Buscar texto de forma incremental en varias páginas de un documento PDF usando TextFragmentAbsorber de Aspose.PDF. +A diferencia de una búsqueda de una sola página o de todo el documento, este enfoque le permite procesar las páginas secuencialmente, recopilar resultados de forma progresiva y analizar fragmentos de texto con contexto específico de la página. Este método es ideal para documentos grandes o flujos de trabajo de procesamiento progresivo. + +1. Cargar el documento PDF. +1. Inicializar TextFragmentAbsorber y establecer la frase de búsqueda. +1. Procesar primera página. Buscar solo la página 1. Imprime texto, número de página y posición. Proporcionar resultados aislados específicos de la página para mayor claridad. +1. Procesar la página siguiente secuencialmente. Ir a la página 2 y, opcionalmente, continuar a través del resto del documento. El 'absorber.visit()' asegura la acumulación de resultados de todas las páginas visitadas. Imprime los resultados de búsqueda acumulados, mostrando tanto el texto como la ubicación. +```python +import io +import sys +import shutil +import aspose.pdf as ap +import aspose.pydrawing as drawing +from os import path -## Buscar y Dibujar Rectángulo alrededor de cada Fragmento de Texto +def text_fragment_absorber_sequential_search(input_file_path): + document = ap.Document(input_file_path) -Aspose.PDF para .NET admite la función de buscar y obtener las coordenadas de cada carácter o fragmento de texto. Así que, para estar seguros de las coordenadas que se devuelven para cada carácter, podemos considerar resaltar (añadir un rectángulo) alrededor de cada carácter. + absorber = ap.text.TextFragmentAbsorber() + absorber.phrase = "whale" -En el caso de un párrafo de texto, puede considerar usar alguna expresión regular para determinar la ruptura de párrafo y dibujar un rectángulo alrededor de él. Por favor, eche un vistazo al siguiente fragmento de código. El siguiente fragmento de código obtiene las coordenadas de cada carácter y crea un rectángulo alrededor de cada carácter. + # First page + document.pages[1].accept(absorber) + for fragment in absorber.text_fragments: + print("Text:", fragment.text) + print("Page:", fragment.page.number) + print("Position:", fragment.position) -```csharp -// Para ejemplos completos y archivos de datos, por favor vaya a https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); + print("--") -// Abrir documento -Document document = new Document(dataDir + "SearchAndGetTextFromAll.pdf"); + # Continue to next page + document.pages[2].accept(absorber) + absorber.visit(document) -// Crear objeto TextAbsorber para encontrar todas las frases que coincidan con la expresión regular + for fragment in absorber.text_fragments: + print("Text:", fragment.text) + print("Page:", fragment.page.number) + print("Position:", fragment.position) +``` + +## Búsqueda de frases dirigidas dentro de un área rectangular -TextFragmentAbsorber textAbsorber = new TextFragmentAbsorber(@"[\S]+"); +Buscar una frase específica dentro de un PDF mientras se limita la búsqueda a un área rectangular específica en una sola página. +Al combinar la búsqueda de frases con restricciones espaciales, puedes localizar el contenido con precisión en regiones designadas sin escanear toda la página o el documento. Esto es especialmente útil para formularios, encabezados, pies de página o informes estructurados donde el contenido aparece en ubicaciones predecibles. -TextSearchOptions textSearchOptions = new TextSearchOptions(true); +1. Cargar el documento PDF. +1. Inicializar TextFragmentAbsorber con Phrase y Restricciones rectangulares +1. Aplicar Absorber a la página 2. Restringe el procesamiento a la página 2, reduciendo el cálculo innecesario. Garantiza que la búsqueda sea específica de la página. +1. Iterar a través de fragmentos encontrados e imprimir -textAbsorber.TextSearchOptions = textSearchOptions; +```python +import io +import sys +import shutil +import aspose.pdf as ap +import aspose.pydrawing as drawing +from os import path -document.Pages.Accept(textAbsorber); +def text_fragment_absorber_search_phrase(input_file_path): + document = ap.Document(input_file_path) -var editor = new PdfContentEditor(document); + absorber = ap.text.TextFragmentAbsorber( + "elephant", ap.text.TextSearchOptions(ap.Rectangle(0, 0, 842, 250, True)) + ) -foreach (TextFragment textFragment in textAbsorber.TextFragments) -{ - foreach (TextSegment textSegment in textFragment.Segments) - { - DrawBox(editor, textFragment.Page.Number, textSegment, System.Drawing.Color.Red); - } + document.pages[2].accept(absorber) -} -dataDir = dataDir + "SearchTextAndDrawRectangle_out.pdf"; -document.Save(dataDir); + for fragment in absorber.text_fragments: + print("Text:", fragment.text) + print("Position:", fragment.position) ``` +## Búsqueda de patrón de texto en PDF usando expresiones regulares -## Resaltar cada carácter en un documento PDF - -{{% alert color="primary" %}} - -Puede intentar buscar texto en un documento usando Aspose.PDF y obtener los resultados en línea en este [enlace](https://products.aspose.app/pdf/search) - -{{% /alert %}} - -Aspose.PDF para .NET admite la función de buscar y obtener las coordenadas de cada carácter o fragmentos de texto. Entonces, para estar seguro de las coordenadas que se devuelven para cada carácter, podemos considerar resaltar (agregar un rectángulo) alrededor de cada carácter. El siguiente fragmento de código obtiene las coordenadas de cada carácter y crea un rectángulo alrededor de cada carácter. - -```csharp -// Para ejemplos completos y archivos de datos, por favor visite https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); - -int resolution = 150; - -Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(dataDir + "input.pdf"); - -using (MemoryStream ms = new MemoryStream()) -{ - PdfConverter conv = new PdfConverter(pdfDocument); - conv.Resolution = new Resolution(resolution, resolution); - conv.GetNextImage(ms, System.Drawing.Imaging.ImageFormat.Png); - - Bitmap bmp = (Bitmap)Bitmap.FromStream(ms); - - using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp)) - { - float scale = resolution / 72f; - gr.Transform = new System.Drawing.Drawing2D.Matrix(scale, 0, 0, -scale, 0, bmp.Height); - - for (int i = 0; i < pdfDocument.Pages.Count; i++) - { -Page page = pdfDocument.Pages[1]; -// Crear objeto TextAbsorber para encontrar todas las palabras -TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(@"[\S]+"); -textFragmentAbsorber.TextSearchOptions.IsRegularExpressionUsed = true; -page.Accept(textFragmentAbsorber); -// Obtener los fragmentos de texto extraídos -TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; -// Recorrer los fragmentos -foreach (TextFragment textFragment in textFragmentCollection) -{ - if (i == 0) - { - gr.DrawRectangle( - Pens.Yellow, - (float)textFragment.Position.XIndent, - (float)textFragment.Position.YIndent, - (float)textFragment.Rectangle.Width, - (float)textFragment.Rectangle.Height); - - for (int segNum = 1; segNum <= textFragment.Segments.Count; segNum++) - { -TextSegment segment = textFragment.Segments[segNum]; - -for (int charNum = 1; charNum <= segment.Characters.Count; charNum++) -{ - CharInfo characterInfo = segment.Characters[charNum]; - - Aspose.Pdf.Rectangle rect = page.GetPageRect(true); - Console.WriteLine("TextFragment = " + textFragment.Text + " Page URY = " + rect.URY + - " TextFragment URY = " + textFragment.Rectangle.URY); - - gr.DrawRectangle( - Pens.Black, - (float)characterInfo.Rectangle.LLX, - (float)characterInfo.Rectangle.LLY, - (float)characterInfo.Rectangle.Width, - (float)characterInfo.Rectangle.Height); -} - -gr.DrawRectangle( -Pens.Green, -(float)segment.Rectangle.LLX, -(float)segment.Rectangle.LLY, -(float)segment.Rectangle.Width, -(float)segment.Rectangle.Height); - } - } -} - } - } - dataDir = dataDir + "HighlightCharacterInPDF_out.png"; - bmp.Save(dataDir, System.Drawing.Imaging.ImageFormat.Png); -} -``` +Buscar patrones de texto en un PDF usando expresiones regulares. Al habilitar el modo regex en TextFragmentAbsorber, puedes localizar patrones complejos como números, fechas, precios, coordenadas o formatos de texto personalizados. La función limita la búsqueda a una página específica, lo que la hace eficiente para la extracción dirigida de datos estructurados. +1. Cargar el documento PDF. +1. Inicializar TextFragmentAbsorber con patrón Regex. +1. Aplicar Absorber a la página 2. Limita la búsqueda a la página 2 para mayor eficiencia y precisión. Solo se analiza el texto en esta página. +1. Iterar a través de fragmentos encontrados. Imprime los fragmentos de texto coincidentes y sus coordenadas. Proporciona información de ubicación precisa para los patrones extraídos. -## Añadir y Buscar Texto Oculto +```python +import io +import sys +import shutil +import aspose.pdf as ap +import aspose.pydrawing as drawing +from os import path -A veces queremos añadir texto oculto en un documento PDF y luego buscar texto oculto y usar su posición para el post-procesamiento. Para su conveniencia, Aspose.PDF para .NET proporciona estas capacidades. Puede añadir texto oculto durante la generación del documento. También puede encontrar texto oculto utilizando TextFragmentAbsorber. Para añadir texto oculto, establezca TextState.Invisible en 'true' para el texto añadido. TextFragmentAbsorber encuentra todo el texto que coincide con el patrón (si se especifica). Es el comportamiento predeterminado que no se puede cambiar. Para verificar si el texto encontrado es realmente invisible, se puede usar la propiedad TextState.Invisible. El fragmento de código a continuación muestra cómo usar esta característica. +def text_fragment_absorber_search_regex(input_file_path): + document = ap.Document(input_file_path) -```csharp -// Para ejemplos completos y archivos de datos, por favor visite https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); + absorber = ap.text.TextFragmentAbsorber( + r"\d+\.\d+", ap.text.TextSearchOptions(is_regular_expression_used=True) + ) -//Crear documento con texto oculto -Aspose.Pdf.Document doc = new Aspose.Pdf.Document(); -Page page = doc.Pages.Add(); -TextFragment frag1 = new TextFragment("Este es un texto común."); -TextFragment frag2 = new TextFragment("Este es un texto invisible."); + document.pages[2].accept(absorber) -//Establecer propiedad de texto - invisible -frag2.TextState.Invisible = true; + for fragment in absorber.text_fragments: + print("Text:", fragment.text) + print("Position:", fragment.position) +``` -page.Paragraphs.Add(frag1); -page.Paragraphs.Add(frag2); -doc.Save(dataDir + "39400_out.pdf"); -doc.Dispose(); +## Convertir coincidencias de texto en hipervínculos en PDF utilizando TextFragmentAbsorber -//Buscar texto en el documento -doc = new Aspose.Pdf.Document(dataDir + "39400_out.pdf"); -TextFragmentAbsorber absorber = new TextFragmentAbsorber(); -absorber.Visit(doc.Pages[1]); +Buscar frases de texto específicas en un PDF y convertirlas en hipervínculos clicables. Usando TextFragmentAbsorber con patrones regex, localiza palabras objetivo y aplica estilo visual (color y subrayado) junto con enlaces interactivos. -foreach (TextFragment fragment in absorber.TextFragments) -{ - //Hacer algo con los fragmentos - Console.WriteLine("Texto '{0}' en pos {1} invisibilidad: {2} ", - fragment.Text, fragment.Position.ToString(), fragment.TextState.Invisible); -} -doc.Dispose(); -``` +1. Cargar el documento PDF. +1. Inicializar TextFragmentAbsorber con patrón Regex. +1. Aplicar Absorber a la página 1. +1. Aplicar estilo y agregar hipervínculos a coincidencias. +1. Guardar PDF modificado. +```python +import io +import sys +import shutil +import aspose.pdf as ap +import aspose.pydrawing as drawing +from os import path -## Búsqueda de texto con .NET Regex +def text_fragment_absorber_search_and_add_hyperlink(input_file_path): + document = ap.Document(input_file_path) -Aspose.PDF para .NET proporciona la capacidad de buscar documentos usando la opción estándar de Regex de .NET. El TextFragmentAbsorber se puede usar para este propósito como se muestra en el siguiente ejemplo de código. + absorber = ap.text.TextFragmentAbsorber("whale|elephant") + absorber.text_search_options = ap.text.TextSearchOptions(True) -```csharp -// Para ejemplos completos y archivos de datos, por favor visite https://github.com/aspose-pdf/Aspose.PDF-for-.NET -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); + absorber.visit(document.pages[1]) -// Crear objeto Regex para encontrar todas las palabras -System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"[\S]+"); + for fragment in absorber.text_fragments: + fragment.text_state.foreground_color = ap.Color.blue + fragment.text_state.underline = True + fragment.hyperlink = ap.WebHyperlink( + f"https://en.wikipedia.org/wiki/{fragment.text}" + ) -// Abrir documento -Aspose.Pdf.Document document = new Aspose.Pdf.Document(dataDir + "SearchTextRegex.pdf"); + output = input_file_path.replace("in.pdf", "out.pdf") + document.save(output) +``` -// Obtener una página en particular -Page page = document.Pages[1]; +## Buscar e Identificar Texto con Estilo en PDF Usando TextFragmentAbsorber -// Crear objeto TextAbsorber para encontrar todas las instancias del regex de entrada -TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(regex); -textFragmentAbsorber.TextSearchOptions.IsRegularExpressionUsed = true; +Buscar fragmentos de texto en un PDF según sus propiedades de formato en lugar de su contenido. Usando TextFragmentAbsorber, identifica texto con estilos específicos, como texto en negrita. -// Aceptar el absorber para la página -page.Accept(textFragmentAbsorber); +1. Cargar el documento PDF. +1. Inicializar TextFragmentAbsorber. +1. Aplicar Absorber a la página 1. +1. Inspeccionar fragmentos de texto según el formato. Verifica el estilo de fuente para formato en negrita. -// Obtener los fragmentos de texto extraídos -TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; +```python +import io +import sys +import shutil +import aspose.pdf as ap +import aspose.pydrawing as drawing +from os import path + +def text_fragment_absorber_search_styled_text(input_file_path): + document = ap.Document(input_file_path) + + absorber = ap.text.TextFragmentAbsorber() + absorber.text_search_options = ap.text.TextSearchOptions(True) + + absorber.visit(document.pages[1]) + + for fragment in absorber.text_fragments: + if fragment.text_state.font_style == ap.text.FontStyles.BOLD: + print(f"Bold: {fragment.text}") + if fragment.text_state.invisible: + print(f"Invisible: {fragment.text}") +``` -// Recorrer los fragmentos -foreach (TextFragment textFragment in textFragmentCollection) -{ - Console.WriteLine(textFragment.Text); -} +## Resaltado visual de texto en páginas PDF + +Esta función combina el reconocimiento de texto y la representación en un único flujo de trabajo. No solo extrae texto, sino que también lo visualiza resaltando fragmentos, segmentos y caracteres en rectángulos codificados por colores en imágenes PNG de cada página. + +Nuestro ejemplo realiza visualización avanzada de texto en un PDF mediante: + +- buscando todos los fragmentos de texto visibles usando expresiones regulares +- renderizando cada página PDF en una imagen PNG de alta resolución +- dibujando rectángulos de colores alrededor de fragmentos de texto, segmentos de texto y caracteres individuales + +1. Establecer resolución de imagen de salida. Cada página PDF se convierte en una imagen PNG de 150 DPI. +1. Abra el PDF y inicialice TextAbsorber. +1. Procesar cada página. Aplicar el absorber a cada página. Recopilar todos los fragmentos de texto detectados y sus posiciones geométricas. +1. Convertir página a flujo PNG. +1. Preparar objeto Graphics para dibujar. +1. Aplicar transformación de coordenadas. Convertir coordenadas PDF a píxeles de imagen. +1. Dibujar rectángulos para los elementos de texto. +1. Guardar el resultado. + +```python +import io +import sys +import shutil +import aspose.pdf as ap +import aspose.pydrawing as drawing +from os import path + +def text_fragment_absorber_search_and_highlight(infile): + resolution = 150 + png_device = ap.devices.PngDevice(ap.devices.Resolution(resolution, resolution)) + + # Open PDF document + document = ap.Document(infile) + absorber = ap.text.TextFragmentAbsorber(r"[\S]+") + absorber.text_search_options.is_regular_expression_used = True + + for page in document.pages: + page.accept(absorber) + stream = io.BytesIO() + png_device.process(page, stream) + with drawing.Bitmap.from_stream(stream) as bmp: + with drawing.Graphics.from_image(bmp) as gr: + scale = resolution / 72 + gr.transform = drawing.drawing2d.Matrix( + float(scale), + float(0), + float(0), + float(-scale), + float(0), + float(bmp.height), + ) + text_fragment_collection = absorber.text_fragments + # Loop through the fragments + for text_fragment in text_fragment_collection: + gr.draw_rectangle( + drawing.Pens.yellow, + float(text_fragment.position.x_indent), + float(text_fragment.position.y_indent), + float(text_fragment.rectangle.width), + float(text_fragment.rectangle.height), + ) + for seg_num in range(1, len(text_fragment.segments) + 1): + segment = text_fragment.segments[seg_num] + for char_num in range(1, len(segment.characters) + 1): + character_info = segment.characters[char_num] + rect = page.get_page_rect(True) + print( + f"TextFragment = {text_fragment.text}" + + f" Page URY = {rect.ury}" + + f" TextFragment URY = {text_fragment.rectangle.ury}" + ) + gr.draw_rectangle( + drawing.Pens.black, + float(character_info.rectangle.llx), + float(character_info.rectangle.lly), + float(character_info.rectangle.width), + float(character_info.rectangle.height), + ) + gr.draw_rectangle( + drawing.Pens.green, + float(segment.rectangle.llx), + float(segment.rectangle.lly), + float(segment.rectangle.width), + float(segment.rectangle.height), + ) + + # Save result + bmp.save( + infile.replace("_in.pdf", str(page.number) + "_out.png"), + drawing.imaging.ImageFormat.png, + ) ``` +## Temas de texto relacionados - \ No newline at end of file +- [Trabajar con texto en PDF usando Python](/pdf/es/python-net/working-with-text/) +- [Reemplazar texto en PDF mediante Python](/pdf/es/python-net/replace-text-in-pdf/) +- [Agregar información sobre herramientas al texto PDF en Python](/pdf/es/python-net/pdf-tooltip/) +- [Agregar texto al PDF](/pdf/es/python-net/add-text-to-pdf-file/) diff --git a/es/python-net/advanced-operations/working-with-text/text-formatting-inside-pdf/_index.md b/es/python-net/advanced-operations/working-with-text/text-formatting-inside-pdf/_index.md index 1b0db4746..50e6c5bf0 100644 --- a/es/python-net/advanced-operations/working-with-text/text-formatting-inside-pdf/_index.md +++ b/es/python-net/advanced-operations/working-with-text/text-formatting-inside-pdf/_index.md @@ -1,428 +1,996 @@ --- -title: Formato de Texto dentro de PDF usando Python -linktitle: Formato de Texto dentro de PDF +title: Formatear texto PDF con Python +linktitle: Formato del texto dentro de PDF type: docs -weight: 30 +weight: 70 url: /es/python-net/text-formatting-inside-pdf/ -description: Esta página explica cómo formatear texto dentro de su archivo PDF. Hay adición de sangría de línea, adición de borde de texto, adición de texto subrayado, etc. -lastmod: "2024-02-17" +description: Aprenda a formatear texto dentro de documentos PDF en Python usando opciones de espaciado, bordes, sangría y estilo. +lastmod: "2026-05-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Dé formato y estilo al texto dentro de archivos PDF con Python +Abstract: Este artículo explica cómo formatear texto en documentos PDF usando Aspose.PDF for Python via .NET. Aprenda a controlar el espaciado, la sangría, los bordes, el subrayado, los efectos de tachado y otras opciones de estilo de texto en Python. --- - - - -## Cómo agregar sangría de línea a PDF - -Aspose.PDF para .NET ofrece la propiedad SubsequentLinesIndent en la clase [TextFormattingOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textformattingoptions). Que se puede usar para especificar la sangría de línea en escenarios de generación de PDF con TextFragment y la colección de Párrafos. - -Utilice el siguiente fragmento de código para usar la propiedad: - -```csharp -// Para obtener ejemplos completos y archivos de datos, visite https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -// Crear nuevo objeto de documento -Aspose.Pdf.Document document = new Aspose.Pdf.Document(); -Aspose.Pdf.Page page = document.Pages.Add(); - -string textFragment = string.Concat(Enumerable.Repeat("A quick brown fox jumped over the lazy dog. ", 10)); - -Aspose.Pdf.Text.TextFragment text = new Aspose.Pdf.Text.TextFragment(textFragment); - -// Inicializar TextFormattingOptions para el fragmento de texto y especificar el valor de SubsequentLinesIndent -text.TextState.FormattingOptions = new Aspose.Pdf.Text.TextFormattingOptions() -{ - SubsequentLinesIndent = 20 -}; - -page.Paragraphs.Add(text); - -text = new Aspose.Pdf.Text.TextFragment("Line2"); -page.Paragraphs.Add(text); - -text = new Aspose.Pdf.Text.TextFragment("Line3"); -page.Paragraphs.Add(text); - -text = new Aspose.Pdf.Text.TextFragment("Line4"); -page.Paragraphs.Add(text); - -text = new Aspose.Pdf.Text.TextFragment("Line5"); -page.Paragraphs.Add(text); - -document.Save(dataDir + "SubsequentIndent_out.pdf"); + +## Espaciado de líneas y caracteres + +### Uso del espaciado de línea + +#### Cómo formatear texto con espaciado de línea personalizado en Python - Caso sencillo + +Aspose.PDF for Python ofrece una forma directa de controlar el diseño y la legibilidad del texto mediante ajustes del espaciado entre líneas. + +Nuestro fragmento de código muestra cómo controlar el espaciado de línea en un documento PDF. Lee texto desde un archivo, o usa un mensaje alternativo, aplica un tamaño de fuente y un espaciado de línea personalizados, y agrega el texto formateado a una nueva página de un PDF. + +1. Cree un nuevo documento PDF. +1. Cargue el texto de origen. +1. Inicialice un objeto TextFragment y asígnele el texto cargado. +1. Configure las propiedades de fuente y espaciado del texto. Estos valores determinan qué tan juntas o separadas aparecen las líneas de texto: + - Tamaño de fuente: 12 puntos + - Espaciado de línea: 16 puntos +1. Inserte el fragmento de texto formateado en la colección de párrafos de la página. +1. Guarde el documento. + +```python +import aspose.pdf as ap +import sys +from os import path + +def specify_line_spacing_simple_case(outfile): + document = ap.Document() + page = document.pages.add() + + lorem_path = path.join(DATA_DIR, "lorem.txt") + if path.exists(lorem_path): + with open(lorem_path, "r", encoding="utf-8") as f: + text = f.read() + else: + text = "Lorem ipsum text not found." + + text_fragment = ap.text.TextFragment(text) + text_fragment.text_state.font_size = 12 + text_fragment.text_state.line_spacing = 16 + page.paragraphs.add(text_fragment) + + document.save(outfile) +``` + +#### Cómo formatear texto con espaciado de línea personalizado en Python - Caso específico + +Veamos cómo aplicar distintos modos de espaciado de línea en un documento PDF usando una fuente TrueType (TTF) personalizada. +Carga texto desde un archivo, incrusta una fuente específica y representa el mismo texto dos veces en una página PDF, cada vez con un modo de espaciado de línea diferente: + +- Modo FONT_SIZE: el espaciado de línea es igual al tamaño de la fuente. +- Modo FULL_SIZE: el espaciado de línea tiene en cuenta la altura completa de la fuente, incluidos ascendentes y descendentes. + +El ejemplo muestra cómo puede variar el comportamiento del espaciado de línea según el modo seleccionado. + +1. Cree un nuevo documento PDF. +1. Especifique las rutas tanto del archivo de fuente personalizada como del archivo de texto de origen. +1. Cargue el contenido del texto. +1. Abra la fuente personalizada. +1. Cree y configure el primer TextFragment (modo FONT_SIZE). Establezca `line_spacing` en 'TextFormattingOptions.LineSpacingMode.FONT_SIZE', lo que significa que el espaciado de línea es igual al tamaño de la fuente. +1. Cree y configure el segundo TextFragment (modo FULL_SIZE). Establezca `line_spacing` en 'TextFormattingOptions.LineSpacingMode.FULL_SIZE', que usa la altura completa de la fuente. +1. Agregue ambos fragmentos de texto a la misma página PDF. +1. Guarde el documento terminado en la ubicación de salida especificada. + +```python +import aspose.pdf as ap +import sys +from os import path + +def specify_line_spacing_specific_case(outfile): + document = ap.Document() + page = document.pages.add() + + font_file = path.join(DATA_DIR, "HPSimplified.ttf") + lorem_path = path.join(DATA_DIR, "lorem.txt") + if path.exists(lorem_path): + with open(lorem_path, "r", encoding="utf-8") as f: + text = f.read() + else: + text = "Lorem ipsum text not found." + + with open(font_file, "rb") as font_stream: + font = ap.text.FontRepository.open_font(font_stream, ap.text.FontTypes.TTF) + + fragment1 = ap.text.TextFragment(text) + fragment1.text_state.font = font + fragment1.text_state.formatting_options = ap.text.TextFormattingOptions() + fragment1.text_state.formatting_options.line_spacing = ( + ap.text.TextFormattingOptions.LineSpacingMode.FONT_SIZE + ) + page.paragraphs.add(fragment1) + + fragment2 = ap.text.TextFragment(text) + fragment2.text_state.font = font + fragment2.text_state.formatting_options = ap.text.TextFormattingOptions() + fragment2.text_state.formatting_options.line_spacing = ( + ap.text.TextFormattingOptions.LineSpacingMode.FULL_SIZE + ) + page.paragraphs.add(fragment2) + + document.save(outfile) +``` + +![Documento PDF que muestra texto con espaciado de línea personalizado, con un espaciado de 16 puntos entre líneas para mejorar la legibilidad y el formato del diseño del texto](line_spacing.png) + +### Uso del espaciado entre caracteres + +#### Cómo controlar el espaciado entre caracteres en texto PDF usando la clase TextFragment + +El espaciado entre caracteres determina la distancia entre caracteres individuales en una línea de texto, lo que resulta útil para ajustar con precisión la apariencia del texto o lograr efectos tipográficos específicos. + +1. Inicialice un nuevo objeto Document y agregue una página en blanco donde colocar el texto. +1. Defina el generador de fragmentos. Implemente una función auxiliar `make_fragment(spacing)`: + - cree un TextFragment con el texto de ejemplo. + - establezca la fuente. +1. Agregue fragmentos de texto con distintos valores de espaciado. +1. Guarde el Document. + +```python +import aspose.pdf as ap +import sys +from os import path + +def character_spacing_using_text_fragment(outfile): + document = ap.Document() + page = document.pages.add() + + def make_fragment(spacing): + fragment = ap.text.TextFragment("Sample Text with character spacing") + fragment.text_state.font = ap.text.FontRepository.find_font("Arial") + fragment.text_state.font_size = 14 + fragment.text_state.character_spacing = spacing + return fragment + + page.paragraphs.add(make_fragment(2.0)) + page.paragraphs.add(make_fragment(1.0)) + page.paragraphs.add(make_fragment(0.75)) + + document.save(outfile) +``` + +![Documento PDF que muestra tres líneas de texto idéntico, Sample Text with character spacing, con un espaciado entre caracteres progresivamente más estrecho de arriba abajo: la primera línea tiene mayor separación entre letras, la línea central tiene un espaciado moderado y la línea inferior tiene el espaciado más compacto, ilustrando el efecto visual de distintos valores de espaciado entre caracteres en el formato de texto PDF](character_spacing_simple.png) + +#### Cómo controlar el espaciado entre caracteres en texto PDF usando TextParagraph y TextBuilder + +Aspose.PDF permite aplicar un espaciado entre caracteres personalizado al agregar texto a un documento PDF usando TextParagraph y TextBuilder. +Define un área específica en la página, configura el ajuste de línea y representa un fragmento de texto con el espaciado entre caracteres ajustado. + +Usar TextParagraph es ideal cuando necesita un control preciso sobre la colocación y el diseño del texto, por ejemplo al crear bloques de texto estructurados o de varias columnas. + +1. Cree un nuevo documento PDF. +1. Inicialice una instancia de TextBuilder para la página. +1. Cree y configure un TextParagraph. + - Establezca el modo de ajuste de palabras en 'TextFormattingOptions.WordWrapMode.BY_WORDS'. +1. Cree un TextFragment con espaciado entre caracteres personalizado. + - Cree un nuevo TextFragment y establezca su texto, por ejemplo, "Sample Text with character spacing". + - Especifique atributos de fuente como Arial y tamaño de fuente 14 pt. + - Aplique `character_spacing = 2.0`, lo que incrementa el espacio entre caracteres. +1. Agregue el TextFragment al TextParagraph. +1. Agregue el TextParagraph a la página. +1. Guarde el documento PDF. + +```python +import aspose.pdf as ap +import sys +from os import path + +def character_spacing_using_text_paragraph(outfile): + document = ap.Document() + page = document.pages.add() + + builder = ap.text.TextBuilder(page) + paragraph = ap.text.TextParagraph() + paragraph.rectangle = ap.Rectangle(100, 700, 500, 750, True) + paragraph.formatting_options.wrap_mode = ( + ap.text.TextFormattingOptions.WordWrapMode.BY_WORDS + ) + + fragment = ap.text.TextFragment("Sample Text with character spacing") + fragment.text_state.font = ap.text.FontRepository.find_font("Arial") + fragment.text_state.font_size = 14 + fragment.text_state.character_spacing = 2.0 + + paragraph.append_line(fragment) + builder.append_paragraph(paragraph) + document.save(outfile) +``` + +## Creación de listas + +Cuando trabaja con archivos PDF, es posible que necesite mostrar información estructurada como listas, ya sean con viñetas, numeradas o formateadas con HTML o LaTeX. +Aspose.PDF for Python via .NET proporciona varias formas flexibles de crear y formatear listas directamente dentro de sus documentos PDF, dándole un control total sobre el diseño, la fuente y el estilo. + +Este artículo muestra varios enfoques para crear listas en archivos PDF, desde el formato de texto plano hasta la representación avanzada con HTML y LaTeX. Cada método responde a un caso de uso específico, tanto si prefiere un control programático preciso como un estilo basado en marcado más cómodo. + +Al final de este artículo, sabrá cómo: + +- Crear listas numeradas y con viñetas personalizadas usando TextParagraph y TextBuilder. + +- Usar fragmentos HTML (HtmlFragment) para representar fácilmente listas `
    ` y `
      ` en archivos PDF. + +- Aprovechar fragmentos LaTeX (TeXFragment) para dar formato a listas matemáticas o científicas. + +- Controlar el ajuste del texto, los estilos de fuente y la colocación del diseño dentro de una página. + +- Entender la diferencia entre la construcción manual de listas y los enfoques guiados por marcado. + +### Crear una lista numerada + +```python +import aspose.pdf as ap +import sys +from os import path + +def create_bullet_list(outfile): + document = ap.Document() + page = document.pages.add() + items = [ + "First item in the list", + "Second item with more text to demonstrate wrapping behavior.", + "Third item", + "Fourth item", + ] + + builder = ap.text.TextBuilder(page) + paragraph = ap.text.TextParagraph() + paragraph.rectangle = ap.Rectangle(80, 200, 400, 800, True) + paragraph.formatting_options.wrap_mode = ( + ap.text.TextFormattingOptions.WordWrapMode.BY_WORDS + ) + + for item in items: + fragment = ap.text.TextFragment("• " + item) + fragment.text_state.font = ap.text.FontRepository.find_font("Times New Roman") + fragment.text_state.font_size = 12 + paragraph.append_line(fragment) + + builder.append_paragraph(paragraph) + document.save(outfile) +``` + +### Crear una lista con viñetas + +```python +import aspose.pdf as ap +import sys +from os import path + +def create_numbered_list(outfile): + document = ap.Document() + page = document.pages.add() + items = [ + "First item in the list", + "Second item with more text to demonstrate wrapping behavior.", + "Third item", + "Fourth item", + ] + + builder = ap.text.TextBuilder(page) + paragraph = ap.text.TextParagraph() + paragraph.rectangle = ap.Rectangle(80, 200, 400, 800, True) + paragraph.formatting_options.wrap_mode = ( + ap.text.TextFormattingOptions.WordWrapMode.BY_WORDS + ) + + for i, item in enumerate(items): + fragment = ap.text.TextFragment(f"{i + 1}. {item}") + fragment.text_state.font = ap.text.FontRepository.find_font("Times New Roman") + fragment.text_state.font_size = 12 + paragraph.append_line(fragment) + + builder.append_paragraph(paragraph) + document.save(outfile) +``` + +### Crear una versión HTML de una lista numerada + +Cree una lista numerada (ordenada) en un documento PDF usando fragmentos HTML. Convierte una lista de cadenas de Python en un elemento HTML `
        ` y la inserta en una página PDF como un HtmlFragment. + +Usar fragmentos HTML le permite incorporar directamente en su PDF funciones de formato basadas en HTML, como listas numeradas, negrita, cursiva y más. + +1. Cree un nuevo documento PDF y agregue una página. +1. Prepare los elementos de la lista. +1. Convierta la lista en una lista HTML ordenada. + - Use la etiqueta `
          ` para una lista numerada. + - Envuelva cada elemento con etiquetas 'li' usando una comprensión de listas. +1. Convierta la cadena HTML en un objeto HtmlFragment que pueda agregarse a la página PDF. +1. Inserte el HtmlFragment en la colección de párrafos de la página. +1. Guarde el documento PDF. + +```python +import aspose.pdf as ap +import sys +from os import path + +def create_numbered_list_html_version(outfile): + document = ap.Document() + page = document.pages.add() + items = [ + "First item in the list", + "Second item with more text to demonstrate wrapping behavior.", + "Third item", + "Fourth item", + ] + html_list = "
            " + "".join([f"
          1. {item}
          2. " for item in items]) + "
          " + html_fragment = ap.HtmlFragment(html_list) + page.paragraphs.add(html_fragment) + document.save(outfile) ``` +![Lista numerada mostrada en un documento PDF con cuatro elementos numerados automáticamente: 1. First item in the list, 2. Second item with more text to demonstrate wrapping behavior, 3. Third item, y 4. Fourth item. La lista muestra la representación de una lista ordenada con formato HTML dentro de una estructura PDF con secuencia numérica, sangría y espaciado adecuados entre los elementos](numbered_list_html.png) + +### Crear una versión HTML de una lista con viñetas + +Nuestra biblioteca muestra cómo crear una lista con viñetas (desordenada) en un documento PDF usando fragmentos HTML. Convierte una lista de cadenas de Python en un elemento HTML `
            ` y la inserta en una página PDF como un HtmlFragment. El uso de fragmentos HTML le permite aprovechar directamente en el PDF funciones de formato HTML, como listas, negrita y cursiva. + +1. Cree un nuevo documento PDF y agregue una página. +1. Prepare los elementos de la lista. +1. Convierta la lista en una lista HTML desordenada. + - Use la etiqueta `
              ` para una lista desordenada con viñetas. + - Envuelva cada elemento con etiquetas 'li' usando una comprensión de listas. +1. Cree un HtmlFragment. Convierta la cadena HTML en un objeto HtmlFragment que pueda agregarse a la página PDF. +1. Inserte el HtmlFragment en la colección de párrafos de la página. +1. Guarde el documento PDF. + +```python +import aspose.pdf as ap +import sys +from os import path + +def create_bullet_list_html_version(outfile): + document = ap.Document() + page = document.pages.add() + items = [ + "First item in the list", + "Second item with more text to demonstrate wrapping behavior.", + "Third item", + "Fourth item", + ] + html_list = "
                " + "".join([f"
              • {item}
              • " for item in items]) + "
              " + html_fragment = ap.HtmlFragment(html_list) + page.paragraphs.add(html_fragment) + document.save(outfile) +``` -## Cómo añadir un borde al texto - -El siguiente fragmento de código muestra cómo añadir un borde a un texto usando TextBuilder y configurando la propiedad DrawTextRectangleBorder de TextState: - -```csharp -// Para ejemplos completos y archivos de datos, por favor visite https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -// Crear un nuevo objeto de documento -Document pdfDocument = new Document(); -// Obtener una página en particular -Page pdfPage = (Page)pdfDocument.Pages.Add(); -// Crear un fragmento de texto -TextFragment textFragment = new TextFragment("texto principal"); -textFragment.Position = new Position(100, 600); -// Establecer propiedades del texto -textFragment.TextState.FontSize = 12; -textFragment.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray; -textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Red; -// Establecer la propiedad StrokingColor para dibujar un borde (trazo) alrededor del rectángulo de texto -textFragment.TextState.StrokingColor = Aspose.Pdf.Color.DarkRed; -// Establecer el valor de la propiedad DrawTextRectangleBorder a true -textFragment.TextState.DrawTextRectangleBorder = true; -TextBuilder tb = new TextBuilder(pdfPage); -tb.AppendText(textFragment); -// Guardar el documento -pdfDocument.Save(dataDir + "PDFWithTextBorder_out.pdf"); +![Lista con viñetas mostrada en un documento PDF con cuatro elementos: First item in the list, Second item with more text to demonstrate wrapping behavior, Third item y Fourth item. Cada elemento está precedido por una viñeta estándar y muestra la representación de una lista con formato HTML dentro de la estructura PDF con la sangría y el espaciado adecuados](bullet_list_html.png) + +### Crear una versión LaTeX de una lista con viñetas + +Cree una lista con viñetas (desordenada) en un PDF usando fragmentos LaTeX (TeXFragment). Convierte una lista de cadenas de Python en un entorno LaTeX `itemize` y la inserta en una página PDF. El uso de fragmentos LaTeX es ideal cuando desea representar fórmulas matemáticas, símbolos o listas estructuradas con un formato preciso. + +1. Cree un nuevo documento PDF y agregue una página. +1. Defina una lista de cadenas de Python que se convertirá en viñetas dentro del entorno LaTeX `itemize`. +1. Convierta la lista en un entorno LaTeX `itemize`: + - Envuelva los elementos con \begin{itemize} y \end{itemize}. + - Cada elemento recibe el prefijo \item mediante una comprensión de listas. +1. Convierta la cadena LaTeX en un objeto TeXFragment que pueda representarse en el PDF. +1. Agregue el fragmento LaTeX a la página. +1. Guarde el documento PDF. + +```python +import aspose.pdf as ap +import sys +from os import path + +def create_bullet_list_latex_version(outfile): + document = ap.Document() + page = document.pages.add() + items = [ + "First item", + "Second item with more text to demonstrate wrapping behavior.", + "Third item", + "Fourth item", + ] + tex_list = ( + "Lists are easy to create: \\begin{itemize}" + + "".join([f"\\item {i}" for i in items]) + + "\\end{itemize}" + ) + tex_fragment = ap.TeXFragment(tex_list) + page.paragraphs.add(tex_fragment) + document.save(outfile) ``` +![Lista con viñetas mostrada en PDF con formato renderizado en LaTeX y el texto Lists are easy to create:, seguido de cuatro elementos con viñetas: First item, Second item with more text to demonstrate wrapping behavior., Third item y Fourth item. La lista muestra una composición tipográfica LaTeX profesional con formato de viñetas, espaciado consistente y capacidad de ajuste de texto dentro de un diseño PDF limpio](bullet_list_latex.png) + +### Crear una versión LaTeX de una lista numerada + +Cree una lista numerada (ordenada) en un PDF usando fragmentos LaTeX (TeXFragment). Convierte una lista de cadenas de Python en un entorno LaTeX `enumerate` y la inserta en una página PDF. El uso de fragmentos LaTeX es ideal cuando desea un formato preciso, listas estructuradas o notación matemática en archivos PDF. + +1. Cree un nuevo documento PDF y agregue una página. +1. Defina una lista de cadenas de Python que se convertirá en elementos numerados dentro del entorno LaTeX `enumerate`. +1. Convierta la lista en un entorno LaTeX `enumerate`. +1. Convierta la cadena LaTeX en un objeto TeXFragment que pueda representarse en el PDF. +1. Agregue el fragmento LaTeX a la página. +1. Guarde el documento PDF. + +```python +import aspose.pdf as ap +import sys +from os import path + +def create_numbered_list_latex_version(outfile): + document = ap.Document() + page = document.pages.add() + items = [ + "First item", + "Second item with more text to demonstrate wrapping behavior.", + "Third item", + "Fourth item", + ] + tex_list = ( + "Lists are easy to create: \\begin{enumerate}" + + "".join([f"\\item {i}" for i in items]) + + "\\end{enumerate}" + ) + tex_fragment = ap.TeXFragment(tex_list) + page.paragraphs.add(tex_fragment) + document.save(outfile) +``` + +![Lista numerada mostrada en PDF con formato renderizado en LaTeX y elementos 1. First item, 2. Second item with more text to demonstrate wrapping behavior., 3. Third item y 4. Fourth item, precedidos por el texto Lists are easy to create](numbered_list_latex.png) + +## Notas al pie y notas finales -## Cómo agregar texto subrayado - -El siguiente fragmento de código te muestra cómo agregar texto subrayado mientras creas un nuevo archivo PDF. - -```csharp -// Para ejemplos completos y archivos de datos, por favor visita https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); - -// Crear objeto de documentación -Document pdfDocument = new Document(); -// Añadir página al documento PDF -pdfDocument.Pages.Add(); -// Crear TextBuilder para la primera página -TextBuilder tb = new TextBuilder(pdfDocument.Pages[1]); -// TextFragment con texto de ejemplo -TextFragment fragment = new TextFragment("Mensaje de prueba"); -// Establecer la fuente para TextFragment -fragment.TextState.Font = FontRepository.FindFont("Arial"); -fragment.TextState.FontSize = 10; -// Establecer el formato del texto como Subrayado -fragment.TextState.Underline = true; -// Especificar la posición donde se necesita colocar TextFragment -fragment.Position = new Position(10, 800); -// Añadir TextFragment al archivo PDF -tb.AppendText(fragment); - -dataDir = dataDir + "AddUnderlineText_out.pdf"; - -// Guardar el documento PDF resultante. -pdfDocument.Save(dataDir); +### Agregar notas al pie + +Las notas al pie se usan para hacer referencia a notas dentro del cuerpo de un documento colocando números consecutivos en superíndice junto al texto correspondiente. Estos números remiten a notas detalladas que normalmente aparecen con sangría y se sitúan en la parte inferior de la misma página, aportando contexto adicional, citas o comentarios. + +Agregue una nota al pie a un fragmento de texto en un documento PDF usando Aspose.PDF for Python via .NET. Las notas al pie son útiles para proporcionar información complementaria, citas o aclaraciones sin recargar el contenido principal. Este método garantiza que las notas al pie queden integradas visual y estructuralmente en el diseño del PDF. + +1. Cree un nuevo Document. +1. Cree un TextFragment con el contenido principal. +1. Agregue texto en línea. Cree otro TextFragment que continúe en el mismo párrafo. +1. Guarde el Document. + +```python +import aspose.pdf as ap +import sys +from os import path + +def add_footnote(outfile): + document = ap.Document() + page = document.pages.add() + + text_fragment = ap.text.TextFragment("This is a sample text with a footnote.") + text_fragment.text_state.font = ap.text.FontRepository.find_font("Arial") + text_fragment.text_state.font_size = 14 + text_fragment.foot_note = ap.Note("This is the footnote content.") + page.paragraphs.add(text_fragment) + + inline_text = ap.text.TextFragment( + " This is another text after footnote in the same paragraph." + ) + inline_text.is_in_line_paragraph = True + inline_text.text_state.font = ap.text.FontRepository.find_font("Arial") + inline_text.text_state.font_size = 14 + page.paragraphs.add(inline_text) + + document.save(outfile) ``` +### Agregar una nota al pie con estilo personalizado en PDF + +1. Inicialice un nuevo documento PDF y agregue una página en blanco. +1. Cree el fragmento de texto principal. +1. Cree y aplique estilo a la nota al pie: fuente, tamaño, color y estilo. +1. Inserte en la página el fragmento de texto con estilo y la nota al pie. +1. Agregue otro fragmento de texto sin nota al pie. +1. Guarde el Document. + +```python +import aspose.pdf as ap +import sys +from os import path -## Cómo agregar un borde alrededor del texto añadido +def add_footnote_custom_text_style(outfile): + document = ap.Document() + page = document.pages.add() -Tienes control sobre el aspecto del texto que añades. El ejemplo a continuación muestra cómo añadir un borde alrededor de un fragmento de texto que has añadido dibujando un rectángulo a su alrededor. Descubre más sobre la clase [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor). + text_fragment = ap.text.TextFragment("This is a sample text with a footnote.") + text_fragment.text_state.font = ap.text.FontRepository.find_font("Arial") + text_fragment.text_state.font_size = 14 -```csharp -// Para ejemplos completos y archivos de datos, por favor visita https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); + note = ap.Note("This is the footnote content with custom text style.") + note.text_state = ap.text.TextState() + note.text_state.font = ap.text.FontRepository.find_font("Times New Roman") + note.text_state.font_size = 10 + note.text_state.foreground_color = ap.Color.red + note.text_state.font_style = ap.text.FontStyles.ITALIC + text_fragment.foot_note = note -PdfContentEditor editor = new PdfContentEditor(); -editor.BindPdf(dataDir + "input.pdf"); -LineInfo lineInfo = new LineInfo(); -lineInfo.LineWidth = 2; -lineInfo.VerticeCoordinate = new float[] { 0, 0, 100, 100, 50, 100 }; -lineInfo.Visibility = true; -editor.CreatePolygon(lineInfo, 1, new System.Drawing.Rectangle(0, 0, 0, 0), ""); + page.paragraphs.add(text_fragment) -dataDir = dataDir + "AddingBorderAroundAddedText_out.pdf"; + another_text = ap.text.TextFragment(" This is another text without footnote.") + another_text.text_state.font = ap.text.FontRepository.find_font("Arial") + another_text.text_state.font_size = 14 + page.paragraphs.add(another_text) -// Guarda el documento PDF resultante. -editor.Save(dataDir); + document.save(outfile) ``` -## Cómo agregar un salto de línea +### Agregar notas al pie con símbolos personalizados en PDF -TextFragment no admite el salto de línea dentro del texto. Sin embargo, para agregar texto con salto de línea, use TextFragment con TextParagraph: +Agregue notas al pie a fragmentos de texto en un documento PDF usando Aspose.PDF for Python via .NET, con la posibilidad de personalizar el símbolo marcador de la nota al pie. -- use "\r\n" o Environment.NewLine en TextFragment en lugar de un solo "\n"; -- cree un objeto TextParagraph. Esto agregará texto con división de líneas; -- agregue el TextFragment con TextParagraph.AppendLine; -- agregue el TextParagraph con TextBuilder.AppendParagraph. -Utilice el siguiente fragmento de código. +1. Cree el documento PDF y la página. +1. Agregue el primer fragmento de texto con un símbolo de nota al pie personalizado. +1. Agregue otro fragmento de texto que continúe el párrafo sin una nota al pie. +1. Agregue un segundo fragmento de texto con una nota al pie predeterminada. +1. Guarde el Document. -```csharp -// Para ejemplos completos y archivos de datos, por favor visite https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -Aspose.Pdf.Document pdfApplicationDoc = new Aspose.Pdf.Document(); -Aspose.Pdf.Page applicationFirstPage = (Aspose.Pdf.Page)pdfApplicationDoc.Pages.Add(); +```python +import aspose.pdf as ap +import sys +from os import path -// Inicializar un nuevo TextFragment con texto que contiene los marcadores de nueva línea requeridos -Aspose.Pdf.Text.TextFragment textFragment = new Aspose.Pdf.Text.TextFragment("Applicant Name: " + Environment.NewLine + " Joe Smoe"); +def add_footnote_custom_text(outfile): + document = ap.Document() + page = document.pages.add() -// Establecer propiedades del fragmento de texto si es necesario -textFragment.TextState.FontSize = 12; -textFragment.TextState.Font = Aspose.Pdf.Text.FontRepository.FindFont("TimesNewRoman"); -textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray; -textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Red; + text_fragment = ap.text.TextFragment("This is a sample text with a footnote.") + text_fragment.text_state.font = ap.text.FontRepository.find_font("Arial") + text_fragment.text_state.font_size = 14 -// Crear un objeto TextParagraph -TextParagraph par = new TextParagraph(); + note = ap.Note("This is the footnote content with custom text style.") + note.text = "*" + text_fragment.foot_note = note + page.paragraphs.add(text_fragment) -// Agregar nuevo TextFragment al párrafo -par.AppendLine(textFragment); + another_text = ap.text.TextFragment(" This is another text without footnote.") + another_text.text_state.font = ap.text.FontRepository.find_font("Arial") + another_text.text_state.font_size = 14 + page.paragraphs.add(another_text) -// Establecer posición del párrafo -par.Position = new Aspose.Pdf.Text.Position(100, 600); + text_fragment = ap.text.TextFragment("This is a sample text with a footnote.") + text_fragment.text_state.font = ap.text.FontRepository.find_font("Arial") + text_fragment.text_state.font_size = 14 + text_fragment.foot_note = ap.Note("This is the footnote content.") + page.paragraphs.add(text_fragment) -// Crear un objeto TextBuilder -TextBuilder textBuilder = new TextBuilder(applicationFirstPage); -// Agregar el TextParagraph usando TextBuilder -textBuilder.AppendParagraph(par); + document.save(outfile) +``` + +### Agregar notas al pie con estilo de línea personalizado en PDF + +Personalice la apariencia visual de las líneas de las notas al pie en un documento PDF con la biblioteca Python. Personalizar las líneas de las notas al pie mejora la claridad visual y permite mantener coherencia de estilo en documentos como informes, artículos académicos y publicaciones anotadas. + +1. Cree un nuevo documento PDF y agregue una página. +1. Defina un estilo de línea personalizado para los conectores de notas al pie: color, ancho y patrón de guiones. +1. Agregue varios fragmentos de texto con notas al pie. +1. Guarde el documento final. + +```python +import aspose.pdf as ap +import sys +from os import path +def add_footnote_with_custom_line_style(outfile): + document = ap.Document() + page = document.pages.add() -dataDir = dataDir + "AddNewLineFeed_out.pdf"; + # Define custom line style + graph_info = ap.GraphInfo() + graph_info.line_width = 2 + graph_info.color = ap.Color.red + graph_info.dash_array = [3] + graph_info.dash_phase = 1 + page.note_line_style = graph_info -// Guardar el documento PDF resultante. -pdfApplicationDoc.Save(dataDir); + # First text fragment with footnote + text1 = ap.text.TextFragment("This is a sample text with a footnote.") + text1.foot_note = ap.Note("foot note for text 1") + page.paragraphs.add(text1) + + # Second text fragment with footnote + text2 = ap.text.TextFragment("This is yet another sample text with a footnote.") + text2.foot_note = ap.Note("foot note for text 2") + page.paragraphs.add(text2) + + document.save(outfile) ``` +### Agregar notas al pie con imagen y tabla en PDF + +¿Cómo enriquecer las notas al pie en un documento PDF incrustando imágenes, texto con estilo y tablas usando Aspose.PDF for Python via .NET? -## Cómo añadir texto tachado +1. Cree un nuevo documento PDF y agregue una página. +1. Agregue un fragmento de texto con una nota al pie adjunta. +1. Incruste una imagen, texto con estilo y una tabla dentro de la nota al pie. +1. Guarde el Document. -La clase TextState proporciona las capacidades para establecer el formato de TextFragments que se colocan dentro de un documento PDF. Puede usar esta clase para establecer el formato de texto como Negrita, Cursiva, Subrayado y, a partir de esta versión, la API ha proporcionado la capacidad para marcar el formato de texto como Tachado. Por favor, intente usar el siguiente fragmento de código para agregar un TextFragment con formato Tachado. +```python +import aspose.pdf as ap +import sys +from os import path -Por favor, use el fragmento de código completo: +def add_footnote_with_image_and_table(outfile): + document = ap.Document() + page = document.pages.add() -```csharp -// Para ejemplos completos y archivos de datos, por favor visite https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -// Abrir documento -Document pdfDocument = new Document(); -// Obtener página en particular -Page pdfPage = (Page)pdfDocument.Pages.Add(); + text = ap.text.TextFragment("This is a sample text with a footnote.") + page.paragraphs.add(text) -// Crear fragmento de texto -TextFragment textFragment = new TextFragment("main text"); -textFragment.Position = new Position(100, 600); + note = ap.Note() -// Establecer propiedades de texto -textFragment.TextState.FontSize = 12; -textFragment.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray; -textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Red; -// Establecer propiedad de Tachado -textFragment.TextState.StrikeOut = true; -// Marcar texto como Negrita -textFragment.TextState.FontStyle = FontStyles.Bold; + # Add image + image_note = ap.Image() + image_note.file = path.join(DATA_DIR, "logo.jpg") + image_note.fix_height = 20 + image_note.fix_width = 20 + note.paragraphs.add(image_note) -// Crear objeto TextBuilder -TextBuilder textBuilder = new TextBuilder(pdfPage); -// Añadir el fragmento de texto a la página PDF -textBuilder.AppendText(textFragment); + # Add text + text_note = ap.text.TextFragment("This is the footnote content.") + text_note.text_state.font_size = 20 + text_note.is_in_line_paragraph = True + note.paragraphs.add(text_note) -dataDir = dataDir + "AddStrikeOutText_out.pdf"; + # Add table + table = ap.Table() + table.rows.add().cells.add("Cell 1,1") + table.rows.add().cells.add("Cell 1,2") + note.paragraphs.add(table) -// Guardar el documento PDF resultante. -pdfDocument.Save(dataDir); + text.foot_note = note + + document.save(outfile) ``` +### Agregar notas finales a documentos PDF + +Una nota final es un tipo de cita que remite a los lectores a una sección designada al final de un documento, donde pueden encontrar la referencia completa de una cita, una idea parafraseada o contenido resumido. Al usar notas finales, se coloca un número en superíndice inmediatamente después del material referenciado, guiando al lector hacia la nota correspondiente al final del documento. -## Aplicar sombreado de gradiente al texto +Este fragmento de código muestra cómo agregar una nota final a un fragmento de texto en un documento PDF. A diferencia de las notas al pie, que aparecen cerca del texto referenciado, las notas finales suelen colocarse al final de un documento o una sección. Este método también simula un documento más largo para ilustrar cómo se comportan las notas finales en contenido extenso. -El formato de texto se ha mejorado aún más en la API para escenarios de edición de texto y ahora puede agregar texto con un espacio de color de patrón dentro del documento PDF. La clase Aspose.Pdf.Color se ha mejorado introduciendo una nueva propiedad de PatternColorSpace, que se puede usar para especificar colores de sombreado para el texto. Esta nueva propiedad agrega diferentes sombreados de gradiente al texto, por ejemplo, sombreado axial, sombreado radial (Tipo 3) como se muestra en el siguiente fragmento de código: +1. Cree el documento PDF y la página. +1. Agregue un TextFragment con una nota final. +1. Cargue contenido de texto externo. +1. Simule un documento largo. Agregue el texto cargado varias veces para simular un documento más extenso. +1. Guarde el Document. -```csharp -// Para ejemplos completos y archivos de datos, por favor vaya a https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); +```python +import aspose.pdf as ap +import sys +from os import path -using (Document pdfDocument = new Document(dataDir + "text_sample4.pdf")) -{ - TextFragmentAbsorber absorber = new TextFragmentAbsorber("Lorem ipsum"); - pdfDocument.Pages.Accept(absorber); +def add_endnote(outfile): + document = ap.Document() + page = document.pages.add() - TextFragment textFragment = absorber.TextFragments[1]; + text_fragment = ap.text.TextFragment("This is a sample text with an endnote.") + text_fragment.text_state.font = ap.text.FontRepository.find_font("Arial") + text_fragment.text_state.font_size = 14 + text_fragment.end_note = ap.Note("This is the EndNote content.") + page.paragraphs.add(text_fragment) - // Crear nuevo color con espacio de color de patrón - textFragment.TextState.ForegroundColor = new Aspose.Pdf.Color() - { - PatternColorSpace = new Aspose.Pdf.Drawing.GradientAxialShading(Color.Red, Color.Blue) - }; - textFragment.TextState.Underline = true; + lorem_path = path.join(DATA_DIR, "lorem.txt") + if path.exists(lorem_path): + with open(lorem_path, encoding="utf-8") as f: + text_content = f.read() + else: + text_content = "Lorem ipsum sample text not found." - pdfDocument.Save(dataDir + "text_out.pdf"); -} + # Simulate long text + for _ in range(5): + tf = ap.text.TextFragment(text_content) + tf.text_state.font = ap.text.FontRepository.find_font("Arial") + tf.text_state.font_size = 14 + page.paragraphs.add(tf) + + document.save(outfile) +``` + +### Agregar notas finales con texto marcador personalizado en PDF + +Agregue una nota final a un fragmento de texto en un documento PDF, con un símbolo marcador personalizado, por ejemplo, "***". Las notas finales suelen colocarse al final de un documento o una sección y son útiles para aportar contexto adicional, citas o comentarios. + +1. Cree el documento PDF y la página. +1. Agregue un fragmento de texto con estilo y una nota final. +1. Personalice el texto marcador de la nota final. +1. Cargue contenido externo desde un archivo `.txt`. +1. Simule contenido largo para ilustrar la colocación de la nota final. +1. Guarde el documento PDF. + +```python +import aspose.pdf as ap +import sys +from os import path + +def add_endnote_custom_text(outfile): + document = ap.Document() + page = document.pages.add() + + text_fragment = ap.text.TextFragment("This is a sample text with an endnote.") + text_fragment.text_state.font = ap.text.FontRepository.find_font("Arial") + text_fragment.text_state.font_size = 14 + text_fragment.end_note = ap.Note("This is the EndNote content.") + text_fragment.end_note.text = "***" + page.paragraphs.add(text_fragment) + + lorem_path = path.join(DATA_DIR, "lorem.txt") + if path.exists(lorem_path): + with open(lorem_path, encoding="utf-8") as f: + text_content = f.read() + else: + text_content = "Lorem ipsum sample text not found." + + # Simulate long text + for _ in range(5): + tf = ap.text.TextFragment(text_content) + tf.text_state.font = ap.text.FontRepository.find_font("Arial") + tf.text_state.font_size = 14 + page.paragraphs.add(tf) + + document.save(outfile) ``` +## Diseño y control de página + +### Forzar que una tabla comience en una nueva página en PDF + +Agregue contenido específico para que comience en una nueva página de un documento PDF usando Aspose.PDF for Python via .NET. +Al establecer la propiedad 'is_in_new_page', puede controlar con precisión el diseño y la estructura de la página, garantizando que determinadas secciones, como tablas, informes o resúmenes, empiecen siempre en una página nueva. Esto resulta ideal para el formato de documentos, informes listos para imprimir o la generación de salidas organizadas. ->Para aplicar un Degradado Radial, puedes establecer la propiedad ‘PatternColorSpace’ igual a ‘Aspose.Pdf.Drawing.GradientRadialShading(startingColor, endingColor)’ en el fragmento de código anterior. +1. Cree y configure una tabla. +1. Agregue datos a la tabla. +1. Fuerce una nueva página para la tabla. Esto garantiza que la tabla comience en la parte superior de una nueva página, incluso si ya existe contenido en la página actual. +1. Agregue la tabla a la página. Use 'page.paragraphs.add()' para incluir la tabla en el diseño del PDF. +1. Guarde el documento. -## Cómo alinear texto al contenido flotante +```python +import aspose.pdf as ap +import sys +from os import path -Aspose.PDF admite la configuración de la alineación del texto para los contenidos dentro de un elemento de Caja Flotante. Se pueden utilizar las propiedades de alineación de la instancia Aspose.Pdf.FloatingBox para lograr esto, como se muestra en el siguiente ejemplo de código. +def force_new_page(output_file_name): + # Create new PDF document + document = ap.Document() + page = document.pages.add() -```csharp -// Para ejemplos completos y archivos de datos, por favor visite https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// La ruta al directorio de documentos. -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); + # Create a table + table = ap.Table() + table.column_widths = "150 150 150" + table.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL) -Aspose.Pdf.Document doc = new Document(); -doc.Pages.Add(); + # Add rows with sample data + for i in range(5): + row = table.rows.add() + row.cells.add(f"Row {i + 1} - Col 1") + row.cells.add(f"Row {i + 1} - Col 2") + row.cells.add(f"Row {i + 1} - Col 3") -Aspose.Pdf.FloatingBox floatBox = new Aspose.Pdf.FloatingBox(100, 100); -floatBox.VerticalAlignment = VerticalAlignment.Bottom; -floatBox.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Right; -floatBox.Paragraphs.Add(new TextFragment("FloatingBox_bottom")); -floatBox.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, Aspose.Pdf.Color.Blue); -doc.Pages[1].Paragraphs.Add(floatBox); + # --- Key part: force table to start on a new PDF page --- + table.is_in_new_page = True -Aspose.Pdf.FloatingBox floatBox1 = new Aspose.Pdf.FloatingBox(100, 100); -floatBox1.VerticalAlignment = VerticalAlignment.Center; -floatBox1.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Right; -floatBox1.Paragraphs.Add(new TextFragment("FloatingBox_center")); -floatBox1.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, Aspose.Pdf.Color.Blue); -doc.Pages[1].Paragraphs.Add(floatBox1); + # Add table to page + page.paragraphs.add(table) -Aspose.Pdf.FloatingBox floatBox2 = new Aspose.Pdf.FloatingBox(100, 100); -floatBox2.VerticalAlignment = VerticalAlignment.Top; -floatBox2.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Right; -floatBox2.Paragraphs.Add(new TextFragment("FloatingBox_top")); -floatBox2.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, Aspose.Pdf.Color.Blue); -doc.Pages[1].Paragraphs.Add(floatBox2); + # Save the PDF + document.save(output_file_name) +``` + +### Uso de la propiedad Inline Paragraph en un PDF + +Nuestra biblioteca le permite usar la propiedad 'is_in_line_paragraph' para controlar el flujo en línea entre texto e imágenes dentro de un PDF. + +Normalmente, cuando agrega nuevos elementos, como fragmentos de texto o imágenes, cada uno comienza en una nueva línea o en un nuevo párrafo. +Al establecer `is_in_line_paragraph = True`, puede hacer que los elementos aparezcan en la misma línea o dentro del mismo párrafo, creando diseños en línea fluidos, perfectos para combinar texto e imágenes en línea, como al agregar logotipos, iconos o símbolos dentro de frases. + +El primer fragmento de texto, la imagen y el segundo fragmento de texto aparecen en la misma línea, formando un párrafo en línea continuo. +El tercer fragmento de texto comienza un nuevo párrafo, mostrando el comportamiento predeterminado de salto de línea. + +1. Cree un nuevo documento PDF. +1. Agregue el primer fragmento de texto. +1. Inserte una imagen en línea. +1. Agregue más texto en línea. +1. Agregue un nuevo párrafo. +1. Guarde el PDF. + +```python +import aspose.pdf as ap +import sys +from os import path + +def using_inline_paragraph_property(output_file_name): + # Create a PDF document + document = ap.Document() + page = document.pages.add() + + # --- First text fragment (normal paragraph) --- + fragment1 = ap.text.TextFragment("This is the first part of the paragraph. ") + fragment1.text_state.font = ap.text.FontRepository.find_font("Arial") + fragment1.text_state.font_size = 14 + page.paragraphs.add(fragment1) + + # --- Inline image (continues same paragraph flow) --- + image = ap.Image() + image.is_in_line_paragraph = True # Makes image inline with previous paragraph + image.file = path.join(DATA_DIR, "logo.jpg") + image.fix_height = 30 + image.fix_width = 30 + page.paragraphs.add(image) + + # --- Second inline text fragment (keeps same paragraph flow) --- + fragment2 = ap.text.TextFragment("This is the second part of the same paragraph.") + fragment2.is_in_line_paragraph = True + fragment2.text_state.font = ap.text.FontRepository.find_font("Arial") + fragment2.text_state.font_size = 14 + page.paragraphs.add(fragment2) + + # --- Third fragment (starts new paragraph automatically) --- + fragment3 = ap.text.TextFragment("This is a new paragraph.") + fragment3.text_state.font = ap.text.FontRepository.find_font("Arial") + fragment3.text_state.font_size = 14 + page.paragraphs.add(fragment3) + + # Save PDF + document.save(output_file_name) +``` + +### Crear un PDF de varias columnas + +Cree un diseño de varias columnas con estilo periodístico en un PDF usando Aspose.PDF for Python via .NET. +Muestra cómo combinar texto, formato HTML y gráficos dentro de un FloatingBox, permitiendo un control avanzado del diseño similar al de revistas o boletines de varias columnas. + +1. Inicialice el documento PDF. +1. Agregue una línea separadora horizontal en la parte superior. +1. Agregue un encabezado HTML con estilo. +1. Cree el FloatingBox para controlar el diseño. +1. Configure el diseño de varias columnas. +1. Agregue la información del autor. +1. Dibuje otra línea horizontal interna. +1. Agregue el texto del artículo. +1. Guarde el PDF final. + +```python +import aspose.pdf as ap +import sys +from os import path + +def create_multi_column_pdf(output_file_name): + # Create PDF document + document = ap.Document() + + # Set margins + document.page_info.margin.left = 40 + document.page_info.margin.right = 40 + + page = document.pages.add() + + # + # Draw horizontal line at the top + # + graph1 = ap.drawing.Graph(500.0, 2.0) + page.paragraphs.add(graph1) + + pos_arr = [1.0, 2.0, 500.0, 2.0] + line1 = ap.drawing.Line(pos_arr) + graph1.shapes.add(line1) + + # + # Add HTML heading text + # + html = "How to Steer Clear of money scams" + heading_text = ap.HtmlFragment(html) + page.paragraphs.add(heading_text) + + # + # Floating box: enables multi-column layout + # + box = ap.FloatingBox() + + box.column_info.column_count = 2 # Two columns + box.column_info.column_spacing = "5" # Space between columns + box.column_info.column_widths = "105 105" # Width of each column + + # + # Add title text to the FloatingBox + # + text1 = ap.text.TextFragment("By A Googler (The Official Google Blog)") + text1.text_state.font_size = 8 + text1.text_state.line_spacing = 2 + box.paragraphs.add(text1) + + text1.text_state.font_size = 10 + text1.text_state.font_style = ap.text.FontStyles.ITALIC + + # + # Add another horizontal line inside the box + # + graph2 = ap.drawing.Graph(50.0, 10.0) + + pos_arr2 = [1.0, 10.0, 100.0, 10.0] + line2 = ap.drawing.Line(pos_arr2) + graph2.shapes.add(line2) + + box.paragraphs.add(graph2) + + # + # Add long text content + # + lorem_path = path.join(DATA_DIR, "lorem.txt") + if path.exists(lorem_path): + with open(lorem_path, "r", encoding="utf-8") as f: + lorem_text = f.read() + else: + lorem_text = "Lorem ipsum text not found." + text2 = ap.text.TextFragment(lorem_text * 5) + box.paragraphs.add(text2) + + page.paragraphs.add(box) + + # Save PDF + document.save(output_file_name) +``` -doc.Save(dataDir + "FloatingBox_alignment_review_out.pdf"); +### Tabulaciones personalizadas para alinear texto en PDF + +Cree un diseño de texto similar a una tabla en un PDF usando tabulaciones personalizadas, sin depender de estructuras de tabla. +Al definir posiciones de tabulación, alineaciones y estilos de relleno, puede alinear texto con precisión entre columnas. Esto resulta útil para facturas, informes o datos de texto estructurados. + +1. Cree un nuevo documento PDF. +1. Defina tabulaciones personalizadas. +1. Use marcadores `#$TAB` en el texto. +1. Agregue texto al PDF. +1. Guarde el PDF. + +```python +import aspose.pdf as ap +import sys +from os import path + +def custom_tab_stops(output_file_name): + # Create PDF document + document = ap.Document() + page = document.pages.add() + + # Define tab stops + tab_stops = ap.text.TabStops() + + tab_stop1 = tab_stops.add(100) + tab_stop1.alignment_type = ap.text.TabAlignmentType.RIGHT + tab_stop1.leader_type = ap.text.TabLeaderType.SOLID + + tab_stop2 = tab_stops.add(200) + tab_stop2.alignment_type = ap.text.TabAlignmentType.CENTER + tab_stop2.leader_type = ap.text.TabLeaderType.DASH + + tab_stop3 = tab_stops.add(300) + tab_stop3.alignment_type = ap.text.TabAlignmentType.LEFT + tab_stop3.leader_type = ap.text.TabLeaderType.DOT + + # Create TextFragments with tab placeholders + header = ap.text.TextFragment( + "This is an example of forming table with TAB stops", tab_stops + ) + text0 = ap.text.TextFragment("#$TABHead1 #$TABHead2 #$TABHead3", tab_stops) + text1 = ap.text.TextFragment("#$TABdata11 #$TABdata12 #$TABdata13", tab_stops) + + text2 = ap.text.TextFragment("#$TABdata21 ", tab_stops) + text2.segments.append(ap.text.TextSegment("#$TAB")) + text2.segments.append(ap.text.TextSegment("data22 ")) + text2.segments.append(ap.text.TextSegment("#$TAB")) + text2.segments.append(ap.text.TextSegment("data23")) + + # Add text fragments to page + page.paragraphs.add(header) + page.paragraphs.add(text0) + page.paragraphs.add(text1) + page.paragraphs.add(text2) + + # Save PDF document + document.save(output_file_name) ``` +### Temas de texto relacionados - \ No newline at end of file +- [Trabajar con texto en PDF usando Python](/pdf/es/python-net/working-with-text/) +- [Agregar texto a PDF](/pdf/es/python-net/add-text-to-pdf-file/) +- [Rotar texto dentro de PDF usando Python](/pdf/es/python-net/rotate-text-inside-pdf/) +- [Reemplazar texto en PDF mediante Python](/pdf/es/python-net/replace-text-in-pdf/) diff --git a/es/python-net/advanced-operations/working-with-vector-graphics/_index.md b/es/python-net/advanced-operations/working-with-vector-graphics/_index.md new file mode 100644 index 000000000..ce14d8871 --- /dev/null +++ b/es/python-net/advanced-operations/working-with-vector-graphics/_index.md @@ -0,0 +1,214 @@ +--- +title: Trabajar con gráficos vectoriales en Python +linktitle: Trabajar con gráficos vectoriales +type: docs +weight: 100 +url: /es/python-net/working-with-vector-graphics/ +description: Aprende cómo extraer, mover, eliminar y copiar gráficos vectoriales entre páginas PDF usando GraphicsAbsorber en Python. +lastmod: "2026-05-07" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Utiliza GraphicsAbsorber para inspeccionar y manipular gráficos vectoriales PDF en Python. +Abstract: Este artículo explica cómo trabajar con gráficos vectoriales en Aspose.PDF for Python via .NET usando la clase GraphicsAbsorber. Aprende cómo extraer elementos vectoriales de páginas PDF, moverlos o eliminarlos, y copiar gráficos entre páginas con control de bajo nivel en flujos de trabajo de Python. +--- + +[Aspose.PDF for Python via .NET](/pdf/es/python-net/) provee el [GraphicsAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/graphicsabsorber/) clase para acceder y manipular gráficos vectoriales ya presentes en una página PDF. Llámala `visit` método en cualquier página para extraer rutas, formas y otros operadores gráficos, luego mover, eliminar o copiar esos elementos según sea necesario. + +Utilice esta página cuando necesite inspeccionar o modificar los elementos de dibujo vectorial incrustados en un PDF existente, en lugar de dibujar nuevas formas desde cero. + +## Extrayendo gráficos + +La extracción es el punto de partida para todas las tareas de gráficos vectoriales. `GraphicsAbsorber` lee la secuencia de contenido de una página y expone cada elemento gráfico con su referencia de página, posición y operadores sin procesar. + +1. Abra el documento PDF. +1. Cree un [GraphicsAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/graphicsabsorber/) instancia. +1. Llamada `visit` en la página de destino para rellenar `elements`. +1. Iterar sobre `elements` para inspeccionar la posición y los recuentos de operadores. + +```python +import aspose.pdf as ap +import sys +from os import path + +def using_graphics_absorber(infile: str): + with ap.Document(infile) as document: + with ap.vector.GraphicsAbsorber() as graphics_absorber: + page = document.pages[1] + graphics_absorber.visit(page) + for element in graphics_absorber.elements: + print(f"Page Number: {element.source_page.number}") + print(f"Position: ({element.position.x}, {element.position.y})") + print(f"Number of Operators: {element.operators.length}") +``` + +`GraphicsAbsorber` es parte de `aspose.pdf.vector` namespace y está específicamente diseñado para interactuar con gráficos vectoriales en flujos de contenido PDF. + +## Gráficos en movimiento + +Después de la extracción, establezca un nuevo `position` en cada elemento para reubicarlo en la misma página. Envuelva las actualizaciones en `suppress_update` / `resume_update` llamadas para agrupar escrituras de flujo de contenido en una sola operación y evitar repintados redundantes. + +1. Abra el documento PDF. +1. Cree un `GraphicsAbsorber` y llamar `visit` en la página de destino. +1. Llamada `suppress_update` para pausar escrituras del flujo de contenido. +1. Actualizar el `position` de cada elemento. +1. Llamada `resume_update` para confirmar todos los cambios de una vez. +1. Guarda el documento modificado. + +```python +import aspose.pdf as ap +import sys +from os import path + +def move_graphics(infile: str, outfile: str): + with ap.Document(infile) as document: + with ap.vector.GraphicsAbsorber() as graphics_absorber: + page = document.pages[1] + graphics_absorber.visit(page) + graphics_absorber.suppress_update() + for element in graphics_absorber.elements: + position = element.position + element.position = ap.Point(position.x + 150, position.y - 10) + graphics_absorber.resume_update() + document.save(outfile) +``` + +## Eliminando gráficos + +Para eliminar elementos vectoriales específicos de una página, filtre por posición o rectángulo delimitador y luego elimínelos. Aspose.PDF for Python ofrece dos enfoques dependiendo de si desea eliminar los elementos en línea o recopilarlos primero. + +### Método 1: Eliminar en línea usando límite rectangular + +Este enfoque verifica la posición de cada elemento contra un rectángulo y llama `element.remove()` directamente dentro del bucle. Utilízalo cuando quieras un código conciso y no necesites inspeccionar el conjunto eliminado después. + +1. Abra el documento PDF. +1. Cree un `GraphicsAbsorber` y llamar `visit` en la página de destino. +1. Definir el objetivo [Rectángulo](https://reference.aspose.com/pdf/python-net/aspose.pdf/rectangle/). +1. Llamada `suppress_update` para pausar escrituras del flujo de contenido. +1. Iterar `elements`, llamando `remove()` en cada elemento cuya posición caiga dentro del rectángulo. +1. Llamada `resume_update` confirmar las eliminaciones. +1. Guarda el documento modificado. + +```python +import aspose.pdf as ap +import sys +from os import path + +def remove_graphics_method_1(infile: str, outfile: str): + with ap.Document(infile) as document: + with ap.vector.GraphicsAbsorber() as graphics_absorber: + page = document.pages[1] + graphics_absorber.visit(page) + rectangle = ap.Rectangle(70, 248, 170, 252, True) + graphics_absorber.suppress_update() + for element in graphics_absorber.elements: + if rectangle.contains(element.position, False): + element.remove() + graphics_absorber.resume_update() + document.save(outfile) +``` + +### Método 2: Recopilar elementos primero, luego eliminar + +Este enfoque reúne los elementos coincidentes en un [GraphicElementCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/graphicelementcollection/) y pasa la colección a `page.delete_graphics`. Úsalo cuando necesites revisar o registrar lo que se eliminará antes de confirmar la eliminación. + +1. Abra el documento PDF. +1. Cree un `GraphicsAbsorber` y llamar `visit` en la página de destino. +1. Define el rectángulo de destino. +1. Iterar `elements` y agrega elementos coincidentes a una `GraphicElementCollection`. +1. Llamada `page.contents.suppress_update` para pausar escrituras del flujo de contenido. +1. Llamada `page.delete_graphics` con la colección. +1. Llamada `page.contents.resume_update` confirmar las eliminaciones. +1. Guarda el documento modificado. + +```python +import aspose.pdf as ap +import sys +from os import path + +def remove_graphics_method_2(infile: str, outfile: str): + with ap.Document(infile) as document: + with ap.vector.GraphicsAbsorber() as graphics_absorber: + page = document.pages[1] + rectangle = ap.Rectangle(70, 248, 170, 252, True) + graphics_absorber.visit(page) + removed_elements_collection = ap.vector.GraphicElementCollection() + for element in graphics_absorber.elements: + if rectangle.contains(element.position, False): + removed_elements_collection.add(element) + page.contents.suppress_update() + page.delete_graphics(removed_elements_collection) + page.contents.resume_update() + document.save(outfile) +``` + +## Agregar gráficos a otra página + +Los elementos vectoriales extraídos de una página pueden colocarse en cualquier otra página del mismo documento. Hay dos métodos disponibles: agregar los elementos uno por uno, o pasar toda la colección en una única llamada. + +### Método 1: Añadir elementos individualmente + +Utilice este método cuando necesite control por elemento, como filtrar o transformar elementos individuales antes de colocarlos en la página de destino. + +1. Abra el documento PDF. +1. Cree un `GraphicsAbsorber` y llamar `visit` en la página de origen. +1. Agregar una nueva página de destino al documento. +1. Llamada `page_2.contents.suppress_update` para pausar escrituras del flujo de contenido. +1. Llamada `element.add_on_page(page_2)` para cada elemento. +1. Llamada `page_2.contents.resume_update` para confirmar todas las adiciones. +1. Guarda el documento modificado. + +```python +import aspose.pdf as ap +import sys +from os import path + +def add_to_another_page_method_1(infile: str, outfile: str): + with ap.Document(infile) as document: + with ap.vector.GraphicsAbsorber() as graphics_absorber: + page_1 = document.pages[1] + page_2 = document.pages.add() + graphics_absorber.visit(page_1) + page_2.contents.suppress_update() + for element in graphics_absorber.elements: + element.add_on_page(page_2) + page_2.contents.resume_update() + document.save(outfile) +``` + +### Método 2: Añadir toda la colección de una vez + +Utiliza este método cuando quieras copiar todos los elementos extraídos a una página en una sola operación sin iterar manualmente. + +1. Abra el documento PDF. +1. Cree un `GraphicsAbsorber` y llamar `visit` en la página de origen. +1. Agregar una nueva página de destino al documento. +1. Llamada `page_2.contents.suppress_update` para pausar escrituras del flujo de contenido. +1. Llamada `page_2.add_graphics` con el completo `elements` colección. +1. Llamada `page_2.contents.resume_update` para confirmar todas las adiciones. +1. Guarda el documento modificado. + +```python +import aspose.pdf as ap +import sys +from os import path + +def add_to_another_page_method_2(infile: str, outfile: str): + with ap.Document(infile) as document: + with ap.vector.GraphicsAbsorber() as graphics_absorber: + page_1 = document.pages[1] + page_2 = document.pages.add() + graphics_absorber.visit(page_1) + page_2.contents.suppress_update() + page_2.add_graphics(graphics_absorber.elements, None) + page_2.contents.resume_update() + document.save(outfile) +``` + +## Temas relacionados + +- [Operaciones avanzadas de PDF en Python](/pdf/es/python-net/advanced-operations/) +- [Trabajar con gráficos PDF en Python](/pdf/es/python-net/working-with-graphs/) +- [Trabajar con operadores PDF en Python](/pdf/es/python-net/working-with-operators/) +- [Trabajar con páginas PDF en Python](/pdf/es/python-net/working-with-pages/) diff --git a/es/python-net/advanced-operations/zugferd/_index.md b/es/python-net/advanced-operations/zugferd/_index.md index f27ed754a..8b068cc39 100644 --- a/es/python-net/advanced-operations/zugferd/_index.md +++ b/es/python-net/advanced-operations/zugferd/_index.md @@ -4,30 +4,34 @@ linktitle: Trabajando con ZUGFeRD type: docs weight: 90 url: /es/python-net/working-with-zugferd/ -description: Aprenda a crear facturas PDF compatibles con ZUGFeRD usando Aspose.PDF para Java -lastmod: "2024-01-17" +description: Explore cómo manejar facturas ZUGFeRD en Python con Aspose.PDF para gestionar y generar facturas electrónicas. +lastmod: "2025-02-27" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Las facturas ZUGFeRD con Aspose.PDF en Python +Abstract: ZUGFeRD es un estándar de facturación electrónica utilizado predominantemente en Alemania y en otros países de la UE, diseñado para optimizar el proceso de facturación B2B mediante un formato totalmente digital. Facilita la creación, transmisión y procesamiento eficientes de facturas electrónicas, promoviendo ahorros de costos y eficiencia operativa. El formato ZUGFeRD combina de forma única un PDF legible por humanos con un XML legible por máquinas, garantizando la interoperabilidad entre diferentes plataformas de software. Este estándar cumple con los requisitos legales de archivado y cumplimiento fiscal y se alinea con el estándar europeo EN 16931. La última versión, ZUGFeRD 2.0, ofrece varios perfiles para atender diversas necesidades empresariales, proporcionando beneficios como un procesamiento más rápido, reducción de errores, mejor flujo de efectivo y un menor impacto ambiental. El artículo también menciona recursos para implementar PDFs compatibles con ZUGFeRD en Python, Java y .NET. --- -## ¿Qué es ZUGFeRD? +## Qué es ZUGFeRD -La facturación electrónica es la creación, envío, recepción y procesamiento de un documento de factura electrónica. Es completamente digital de principio a fin y ayuda a las empresas a ahorrar dinero y mejorar la eficiencia en un contexto B2B. Tanto los compradores como los vendedores pueden beneficiarse de la facturación electrónica. +La facturación electrónica consiste en crear, enviar, recibir y procesar un documento de factura electrónica. Es completamente digital de principio a fin y ayuda a las empresas a ahorrar dinero y mejorar la eficiencia en un contexto B2B. Tanto compradores como vendedores pueden beneficiarse de la facturación electrónica. -Millones de empresas están adoptando la facturación electrónica a medida que la tecnología avanza para disfrutar de sus ventajas. Sin embargo, necesitan estándares para garantizar que las facturas electrónicas puedan ser fácilmente leídas y entendidas por cualquier software, independientemente de cómo se generen. +Millones de empresas están adoptando la facturación electrónica a medida que avanza la tecnología para aprovechar sus ventajas. Sin embargo, necesitan estándares que garanticen que las facturas electrónicas puedan ser leídas y comprendidas fácilmente por cualquier software, independientemente de cómo se generen. -De los muchos formatos de datos para facturas electrónicas, el estándar ZUGFeRD se ha establecido cada vez más en los países de habla alemana y de la UE. +De entre los numerosos formatos de datos para facturas electrónicas, el estándar ZUGFeRD se ha ido consolidando cada vez más en los países de habla alemana y en la UE. -ZUGFeRD es un estándar para la facturación electrónica en Alemania. - Se refiere a "Zentraler User Guide des Forums elektronische Rechnung Deutschland", la Guía de Usuario Central del Foro para Facturación Electrónica Alemania. +ZUGFeRD es un estándar para la facturación electrónica en Alemania. Significa "Zentraler User Guide des Forums elektronische Rechnung Deutschland", la Guía Central del Foro de Facturación Electrónica de Alemania. -El formato es un híbrido que combina un documento PDF que los humanos pueden leer y un archivo de datos XML que las máquinas pueden leer. Permite el intercambio de información de facturas entre empresas y autoridades públicas de manera uniforme e interoperable. +El formato es un híbrido que combina un documento PDF que los humanos pueden leer y un archivo de datos XML que las máquinas pueden leer. Permite el intercambio de información de facturación entre empresas y autoridades públicas de manera uniforme e interoperable. -También cumple con los requisitos legales para el archivo a largo plazo y el cumplimiento fiscal. ZUGFeRD tiene diferentes versiones y perfiles que se adaptan a diferentes necesidades y escenarios. La última versión es ZUGFeRD 2.0, compatible con el estándar europeo EN 16931 para la facturación electrónica. ZUGFeRD ofrece a los usuarios muchos beneficios y ahorros de costos, como procesamiento más rápido, reducción de errores, mejora del flujo de efectivo y menor impacto ambiental. +También cumple con los requisitos legales para el archivado a largo plazo y el cumplimiento fiscal. ZUGFeRD tiene diferentes versiones y perfiles que se adaptan a distintas necesidades y escenarios. La última versión es ZUGFeRD 2.0, compatible con la norma europea EN 16931 para facturación electrónica. +ZUGFeRD ofrece a los usuarios muchos beneficios y ahorros de costos, como un procesamiento más rápido, menos errores, mejor flujo de efectivo y menor impacto ambiental. -* [Crear un PDF compatible con PDF/3-A y adjuntar una factura ZUGFeRD en Python](/pdf/es/python-net/attach-zugferd/) +* [Crear PDF compatible con PDF/3-A y adjuntar factura ZUGFeRD en Python](/pdf/es/python-net/attach-zugferd/) Ver también: -* [Crear un PDF compatible con PDF/3-A y adjuntar una factura ZUGFeRD en Java](/pdf/es/java/attach-zugferd/)* [Creando un PDF compatible con PDF/3-A y adjuntando una factura ZUGFeRD en .NET](/pdf/es/net/attach-zugferd/) \ No newline at end of file +* [Crear PDF compatible con PDF/3-A y adjuntar factura ZUGFeRD en Java](/pdf/es/java/attach-zugferd/) +* [Crear PDF compatible con PDF/3-A y adjuntar factura ZUGFeRD en .NET](/pdf/es/net/attach-zugferd/) diff --git a/es/python-net/advanced-operations/zugferd/attach-zugferd/_index.md b/es/python-net/advanced-operations/zugferd/attach-zugferd/_index.md index d7d88c67b..2333f50f0 100644 --- a/es/python-net/advanced-operations/zugferd/attach-zugferd/_index.md +++ b/es/python-net/advanced-operations/zugferd/attach-zugferd/_index.md @@ -1,58 +1,54 @@ --- -title: Creación de PDF compatible con PDF/3-A y adjuntar factura ZUGFeRD en Python -linktitle: Adjuntar ZUGFeRD al PDF +title: Crear PDF compatible con PDF/3-A y adjuntar factura ZUGFeRD en Python +linktitle: Adjuntar ZUGFeRD a PDF type: docs weight: 10 url: /es/python-net/attach-zugferd/ -description: Aprenda a generar un documento PDF con ZUGFeRD en Aspose.PDF para Python a través de .NET -lastmod: "2024-01-18" +description: Aprenda cómo generar un documento PDF con ZUGFeRD en Aspose.PDF for Python via .NET +lastmod: "2025-02-27" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo adjuntar ZUGFeRD a un documento PDF +Abstract: El artículo ofrece una guía paso a paso sobre cómo adjuntar ZUGFeRD (un formato de facturas electrónicas) a un documento PDF utilizando la biblioteca Aspose.PDF. El procedimiento comienza importando la biblioteca necesaria y configurando las rutas de directorio para los archivos de entrada y salida. Implica cargar el archivo PDF objetivo en un objeto Document y crear un objeto FileSpecification para el archivo XML de metadatos de la factura. Propiedades clave como `mime_type` y `af_relationship` se establecen para garantizar una integración adecuada de los metadatos. Luego, el archivo XML se agrega a la colección de archivos incrustados del PDF, adjuntándolo efectivamente como metadatos. Posteriormente, el documento PDF se convierte al formato PDF/A-3A, que es adecuado para archivar documentos electrónicos, antes de guardar el PDF final con el ZUGFeRD incrustado. El artículo concluye con un fragmento de código Python que demuestra la implementación de estos pasos, mostrando la integración de ZUGFeRD con un PDF para una mejor gestión documental. --- -## Adjuntar ZUGFeRD al PDF +## Adjuntar ZUGFeRD a PDF -Recomendamos seguir los siguientes pasos para adjuntar ZUGFeRD al PDF: +Recomendamos los siguientes pasos para adjuntar ZUGFeRD al PDF: -1. Importe la biblioteca Aspose.PDF y asígnele un alias de ap para mayor comodidad. +1. Importe la biblioteca Aspose.PDF y asígnele el alias ap para mayor comodidad. 1. Defina la ruta al directorio donde se encuentran los archivos PDF de entrada y salida. -1. Defina la ruta al archivo PDF que se procesará. +1. Defina la ruta al archivo PDF que será procesado. 1. Cargue el archivo PDF desde la variable de ruta y cree un objeto Document. 1. Cree un objeto FileSpecification para el archivo XML que contiene los metadatos de la factura. Use la variable de ruta y una cadena de descripción para crear el objeto FileSpecification. - -1. Establece las propiedades `mime_type` y `af_relationship` del objeto FileSpecification a `text/xml` y `ALTERNATIVE`, respectivamente. -1. Agrega el objeto fileSpecification a la colección de archivos incrustados del objeto documento. Esto adjunta el archivo XML al documento PDF como un archivo de metadatos de factura. -1. Convierte el documento PDF al formato PDF/A-3A. Usa la ruta al archivo de registro, la enumeración `PdfFormat.PDF_A_3A` y la enumeración `ConvertErrorAction.DELETE` para convertir el objeto documento. -1. Guarda el documento PDF con el ZUGFeRD adjunto. +1. Establecer el `mime_type` y el `af_relationship` propiedades del objeto FileSpecification a `text/xml` y `ALTERNATIVE`, respectivamente. +1. Añada el objeto fileSpecification a la colección de archivos incrustados del objeto document. Esto adjunta el archivo XML al documento PDF como un archivo de metadatos de factura. +1. Convertir el documento PDF al formato PDF/A-3A. Utilice la ruta al archivo de registro, el `PdfFormat.PDF_A_3A` enumeración, y el `ConvertErrorAction.DELETE` enumeración para convertir el objeto del documento. +1. Guarde el documento PDF con el ZUGFeRD adjunto. ```python +import sys +import os import aspose.pdf as ap -# Define la ruta al directorio donde se encuentran los archivos PDF de entrada y salida -_dataDir = "./" - -# Carga el archivo PDF que será procesado -path = _dataDir + "ZUGFeRD/ZUGFeRD-test.pdf" -document = ap.Document(path) - -# Crea un objeto FileSpecification para el archivo XML que contiene los metadatos de la factura -description = "Metadatos de factura conformes al estándar ZUGFeRD" -path = _dataDir + "ZUGFeRD/factur-x.xml" -fileSpecification = ap.FileSpecification(path, description) +def attach_invoice_zugferd_format(infile, invoice, outfile): + document = ap.Document(infile) -# Establece el tipo MIME y las propiedades AFRelationship del archivo incrustado -fileSpecification.mime_type = "text/xml" -fileSpecification.af_relationship = ap.AFRelationship.ALTERNATIVE + # Create a FileSpecification object for the XML file that contains the invoice metadata + description = "Invoice metadata conforming to ZUGFeRD standard" + file_specification = ap.FileSpecification(invoice, description) -# Agrega el archivo incrustado a la colección de archivos incrustados del documento PDF -document.embedded_files.add("factur",fileSpecification) + # Set the MIME type and the AFRelationship properties of the embedded file + file_specification.mime_type = "text/xml" + file_specification.af_relationship = ap.AFRelationship.ALTERNATIVE -# Convierte el documento PDF al formato PDF/A-3A -path = _dataDir + "ZUGFeRD/log.xml" -document.convert(path, ap.PdfFormat.PDF_A_3A, ap.ConvertErrorAction.DELETE) + # Add the embedded file to the PDF document's embedded files collection + document.embedded_files.add("factur", file_specification) -# Guarda el documento PDF con el ZUGFeRD adjunto -path = _dataDir + "ZUGFeRD/ZUGFeRD-res.pdf" -document.save(path) -``` \ No newline at end of file + # Convert the PDF document to the PDF/A-3A format + log_path = outfile.replace(".pdf", "_log.xml") + document.convert(log_path, ap.PdfFormat.PDF_A_3A, ap.ConvertErrorAction.DELETE) + document.save(outfile) +``` diff --git a/es/python-net/aspose_pdf-for-python-net.png b/es/python-net/aspose_pdf-for-python-net.png new file mode 100644 index 0000000000000000000000000000000000000000..0a1f34628e80106d60a2b43f9ed6493bca7228f2 GIT binary patch literal 6589 zcmV;u8A9fXP)Py3cS%G+RCr$PoqJrARsP36X9iKcqp5lOsi~M{ra+07X6CN$wp;ybt+s8`+FdW* z#dbBd-_|d!Tw`q4RA4Wqwb|xoSz76OAuIt?1SM2v5J3>d072x=oPB+tac~%B=DE!? z%rMXS2jux)&iS6V=bYzUp2MK0b`gOE|Fa~#u~WkcBdmiM485DIyel)n0L~gXvsQBO z5`)#4UuKzbatj`8(z?)0YX`c0Z6ffy>tZ8V2>&sIVKO+s6~Iubo;Y}h0W1ZaCv`yM zS8FY6E2Zj6mD9nJ8Yw@Jn;Ws{8o)Z+z}Z6_xW#K(;`o#UA0%2#TfAjc2g_TL)X>g? zQO}LyR^xLVSfHUBGM&d6UzeD(#sq+?@uh>MCVCp{&b@AN4`yt58Nl-zyK**vh65`T z&87sUes!>vMoweBxe*IzGtT}5ps&WR+?(foF9Ula-eNi;HxD{kawDd({M@Ly9av?z z1b{!Tu`3zo*|Q1exV17Apo1kRS{lp#Zp6YH4UBC95UH^%1?G8Tf_cq6sfs#SQX{3Y z-24&GPvy)&Z)MkL>`H}sz9W=3KCsrZwoc554whJieDHk1$c59bVA}z7^np8dE*SQ8 zuI6{IDO^+I$&e0~x-hHOUN9my#>%i8Ko`}m*r`G#KM7`vv1_g zn#*#ap)dp67;lc7c`d}!4b6>MbUWjGzjO`1mP}7Do1%2E{Gg8Jjf_nO zFxd~X;*~6LV0oh1w9?U--eP$rw9<{t8@cdtfc?XrM(6Hf70^ZF)s-IK_@!scg(Ufix&Ic#KlzTR9S+ooG#H1hKfU^#U04T8G;H1#m_IT$ zn**cWS&f)591GSz0n?-F1&Hiv_Ns>ku;}j-@4p3^yR$R{iy)4D|4FR4Cr)rr{!+Gn zC;UEm^gxsrm9_HCIE#z7#J!+{xOD`24+_VYmD>au2r6nZsMR8{=;xOkcB84miU*h7+uUvLc{dra z?OTpL8=5!@4WWb?sg_X)pK>qveGW&(M^`p5D4 z+MR;z&!3qg{7!PbiGy;>UL!8J|;k9Ps=}BBy?fa3Qe0cxw+LNXbO)P;pQKW5kT9% zmZs1EyS%;SBj4oH?u-8J_`AEV@QVM;1hZ+J4whIgd-3`Fh}f4o#~;N^+QFjArB)+j zcNS_YYlNT9U_H9xL7^3L9K_pY>|N?dD?b%n-Zf{602JAwu8#gqkj`KKxbRadSYr9- z+!~c=c`MyzSIE;R_W>Fv!paAMu|8tP^ylIcSn^c#+>5251H>d9fgk{=8(Mnj3ZZ+l zLtyU;Z<=}odJPE2me;lk1AFSK>|ogk;2RdagPKbgeWlfA~+rp3xNJydITyf zI^YlUq@8^rKnO1TTNwRLU7h3KCp~a0EQe1CgLi_@E<-wwZ*T+`jj8A-JtJW3Eh2S` z1QR_Yov?0U$T?_f?p7V`(9{EUq4t*v&n4$c3Fb9-HiN~}W9|XR-~D?(ko3y*C&`TO zdLcgUdVk82mU*d9Fq=9GVDZ!m-4SXy0M2jJ(qpjN{`{lC*s*o6q~hBrNJ+TnQf-U5 zEO!Q+rw>TZ(T+R4(jwawg?)S_=Uk5S1g@hG#t~@)>u?MWD(N(co-~L+;#;GTp4wZI zWr8I3y(a}(8q=)2*VJ73?hM4|*d{XPM=WX=M-1Hb{z*BUsc@QMX84;__)L-M;R7>I&NeEY8?_jHk!!1IN@Br8acT!MLOd zNs-WnL?iIz=-@r;hVpuH=-y6*9(O(7}>a-Rgwi{ljLYeo9k?;>jIYq)9sxW-Yx}7-u=Q zHlDgdnzC>==yx?QYi z*=+0zgpE{JEA2qLp|%0fj9ntBBw}EZ5n6tsxaGd78_T`&P)ob|;$S zgpZtf53H`^ZQY$?sx|{PIY52$0okih39d0)0b}rNoJf3b6VkuDdQis>7PVOR!=ZA( za-7?8*J6qFy`EY{xnMEI9*fV36V6R~53K&b0s6PzBq0>6bO%uQ7SL4HvYeiD#3B-a z&z;{6?R(N`Ke~OwQ|KN?+qTAu%`BOkUk9s=tF-)F1z!2-pHN#>+r~Lj@16l4$D2*RaJJ;zt}y>qp!AEDc?hzu z&|dfhA0Nb~7j0j23E)&_v|`-)T+^Ah1FPv0aC|mUUwkzWq1OUqJ_+Ess>}N3SGMBo ze}1dZNLy-i>#PLJTmN>I1>dz;u3D?U4*`RGeX&(r)uS`kE4QG5= zV$Pb^+=*%n7PV3r_X8y#0yQqy$!LO<))9j^(abolBNk*822vE>N-&!iddjf(z#>38 zUV)_Xl53D0b0Xy}GLS;8BCmAjaNWGWqu~1hfQw^Yg2nW-SaH1vmY65U=Xw{|Dq2Dvs%wXV8ZOB<8>%s%?fu)a`RMnrea?#0R ze6o5wvXW1D)vi2aY;}S;?ho>GY|=VdN}}dNor9mHyXe9~lPEB}@o zr+D2-2TQxk@v3FoT9dr_0P->mylU6c7zg{%$gJz-c6+Weq=ThdHEClwH$4xBc4Q!P zPZr9~Ui5+!p2lF=Tq>_ZeRVyoRx3g}grHN` zPUu#6FFJKx zstkj%dksRv>k-nIqrnDu}pE(MleMB!6Q0orD-)c;oLjBaBkzZu-1*&)RQ-j8@pzq{}Ywy`^!m+&FWw&4xMMk#)?#A|MD^# z%kR?2gZ5@S4ot(S#L)=p)m^qT9W2=)6IZA;@4$&CdcfLvyST8QOBlPDF=9<;bh*iP z`LoodgC#Xm66MPGeSlL-?*chg%ulH(s!P?d;kz*UecSDo&PfMLVYJVz$;O3`ZcwP*e$;y0wgbc8yjus$8&!H? zYYxt=*6&xe$1;3+GKRg{av4Z(v1F1~`CS2WpX~>Zjxsgdw|MWLXJE+Eam|I)!IDwm z^~Gh#e&iCYwL@fR1&`=;s|wL`${?Y@I#@F5Jy_oWrG_Z9-*Jrj)HZ>tgC#L)g{H4j zvgHnm(!nd%@3AZlTrfrlO9}#wWu-WJZ#B?3Sc-UX%Y^)Z$o<#oU`e4McS#Z|zSi%o zmJ%zH=@yxaOX)GK#QpM=j?_YVTdu}@3dd*n0eJA-mE!Ff+U@CJIYjp4Z};Q!_mj1X zbx_&W!Mal272jqe_XY8l{Gg&kMPYTYt^_aZ7pbT(YCTp^5!;|v)xiRAIr{`o{zm%) zq`^d*4isD#|FrStS3kCfz$tR|;#L=nh7@i%|!w zIRwhTkEL~GIodz<;&xn2`k8E(!&d=4)Spfl^-DLJ(Op5Fz-p`jLNxe1gx+F_R*!pu zjA@5pt?_(Vz?C*#4NR?;mSY_nJRg6o3J%RS#f ztAiyyo-HKHccmcjj}sMYw~dQ7K z;*+{_y4%s{Vnc@xmclAKx!^Ng&bUXRcH5|lfmON#pt-Mzb**8cX$zXZa8B;JL>(-J zb)0qo4%8R7J}0NpoKMs|fkjZ|udro9cx!cl%Ra7hmq}M$q7IhAD$SU-8`hfX3bk!& zU2d}dynM{P8LDKt(-Q91>fC{KG1<2K{PDAMj0 z4fJ^c=uYYkpjZD39|M(S@=BtLrHNFf(-E#%pPy1GIw|0eyba((w=5fPy!!{%y=B>UTcSIw6gj?8zA{Pf#fdi({9lgQX;b zNJaWY>c_e$(vH{wbiH~Q*w!6p0VjWFGe=#^&Hqtkx`mRbwL*H!JG}y+pUz3?C(P;X z(7w2?gQckcvXLG$1YpX*8u~KOYeq}Q<$Hj<@F<32Fy+BV6`P94~tN$xK=lxxpH-v7ZmI&&WyEACWL zMqSla1USlAbZT#{g5&>SWk0eLwRuhhC9T2{RCZ6Ws8nfRTviYk{|C#m@Jm#t{zO69 zbQO;g;K?j1O+o)JEv)_zR>A6B_+hK-?`ldbqb}tt0*w8eMW%Rp*Wp!1{ts5k=42H9 z#RvO~gO0!TEGpGuZ;p4%@Bd(3OwPcm#ZI%FGJ~LG9Z;qVm*R#npyQRzuNBDvokMh& zR%sz0mJg*miR}zM;kavbps~nQu^obR;u~)VWn)swW z?*vwxCk~Wu2l8KQofDcxr=x0e5=}SIg0}O8q*85gM6u{pr`t@WDvQhce~U$B$bM)y zY76A=aL{@#Nj$zz65O_l&#~nq=;?5)lBE2=>S-30s%-sLVm<={tn>fefugtN@5%Dj zxk8D-7Q~zvtd+D@j{XEtWlo-R#Ixws1#+@2S2i%fYOKt`(HZi;s^vGasmO zSe{eUVo`UPso*#O!%tac>X&k|Emt-$z@kzeov{~}fxrRl^0D1GIamGwUh4=3 zntiMF5q8VL&01$WaKHjC;>aDR!0RKm4oW+=UxYd~mQ6}2)4Gg-1Qt-VVLQ%m3am4R zTGyZ)`%VoeN80=44K%QT zA3olWf;aV6OEwGaX%>~@qp!gMfd>`^^w>RLq2aj^%;MiMW!uni}D3F zSQN3GC-~ zq6i+DQVibEzb%957rq(KV3BD)__)32(zYM4>dsuo_YW%j#)DrF;gw7@po_7$uV&Xh z<+%NTMWwu$REkqCYIeHUD^;(h5hEMK#-$W#=|ZaQ_5~J|`fPkY&TSkbH302K&cJSC z<5Ld!OL^KKSQOdwAD%$bpM&UbLw+-hN;~Q=P_>`8LRS&JxGxi@mbUk6e$Rn-h}7y+ zL~1~7pDmU>B9$peU|BRA;N8^($v<`3A@KT1Ec$SRKjzOhSe>s=!u9X?&w*7nk*mtc zg!$R7;0?ponDHxJ&bG1W6u(|^a1E9rEF0tY-r!fkRFj#y!eZq8UjeF*`*iDwnk>85 zZQB`jsbymPaLjuE9&M#CC^iLsX9d>fNMfZv|H1b-o6rlqJ`g8Tv%s*9MW)7!71JM{ zGk$2|>tNi)VK>nIdIZ;v0NT$Og^o;}{{LgB%D8f?fIn1&$2=4O>}~M+bu9XDwcqFV zN(LD}6f*$~sctjOP>9fL(_rlBlfBYD4O~s$Oz=7luDAC}DaygI4juX1?54EyUa{yy zBaD3U!!ZO_I~afXFmhVC;%EY6Z^K|+$Hu3bwQ{4iT^m^6#Y}|(`?PkZ+xHLwj(uR* z4UVt0{JfB_>OcU?)@n@{3(j_dp`Wju>wd5u;GcsV_ps;#x$P+)&0q;|eREqkbZ%M& zjz<)I=&U_O#=B*qZ>g66xB$-0FyLcY8^2`Hhv|cI?J~6h%dv#~@Wh$me5l@n$*gzI vFMy*2Mq>%AyaZt=VK-`jq+Mn%H5dOc^mvfbWDqkG00000NkvXXu0mjfgYDo! literal 0 HcmV?d00001 diff --git a/es/python-net/aspose_pdf-for-python-net.svg b/es/python-net/aspose_pdf-for-python-net.svg new file mode 100644 index 000000000..92b7ff53e --- /dev/null +++ b/es/python-net/aspose_pdf-for-python-net.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/es/python-net/basic-operations/_index.md b/es/python-net/basic-operations/_index.md index 70abf5021..54bf48f30 100644 --- a/es/python-net/basic-operations/_index.md +++ b/es/python-net/basic-operations/_index.md @@ -1,27 +1,24 @@ --- -title: "Operaciones básicas con documentos PDF" -linktitle: "Operaciones básicas" +title: Operaciones básicas con documentos PDF +linktitle: Operaciones básicas type: docs weight: 60 url: /es/python-net/basic-operations/ -lastmod: "2025-02-27" -description: "La sección de operaciones básicas describe las posibilidades de abrir y guardar documentos PDF utilizando Aspose.PDF for Python via .NET." +lastmod: "2026-05-08" +description: La sección de operaciones básicas describe las posibilidades de abrir y guardar documentos PDF utilizando Aspose.PDF for Python via .NET. sitemap: - changefreq: "monthly" - priority: 0.5 + changefreq: "monthly" + priority: 0.5 TechArticle: true -AlternativeHeadline: "Visión general de operaciones básicas con PDF usando Python" -Abstract: > - El artículo ofrece una visión general de las operaciones básicas para manejar documentos PDF usando Aspose.PDF for Python. - Cubre tres tareas fundamentales: crear, abrir y guardar archivos PDF dentro de un entorno Python. - La sección "Create PDF Document" detalla el proceso de generación de un archivo PDF usando Python. - La sección "Open PDF Document" explora varios métodos para acceder a documentos PDF en una aplicación Python. - Por último, la sección "Save PDF Document" explica diversas técnicas para guardar un documento PDF. - Cada sección enlaza a artículos más detallados que guían a los usuarios a través de estas operaciones esenciales de PDF. +AlternativeHeadline: Resumen de operaciones básicas con PDF usando Python +Abstract: 'El artículo proporciona una visión general de las operaciones básicas para manejar documentos PDF usando Aspose.PDF for Python via .NET. Cubre tres tareas fundamentales: crear, abrir y guardar archivos PDF dentro de un entorno Python. La sección "Crear documento PDF" detalla el proceso de generar un archivo PDF usando Python. La sección "Abrir documento PDF" explora varios métodos para acceder a documentos PDF en una aplicación Python. Finalmente, la sección "Guardar documento PDF" explica diversas técnicas para guardar un documento PDF. Cada sección enlaza a artículos más detallados que guían a los usuarios a través de estas operaciones esenciales de PDF.' --- -**Operaciones básicas** sección describe la primera y más sencilla operación con documentos PDF en Aspose.PDF for Python: +La sección de **Operaciones básicas** describe las operaciones iniciales y más sencillas con documentos PDF en Aspose.PDF for Python via .NET: - [Crear documento PDF](/pdf/es/python-net/create-document/) - este artículo describe cómo crear un archivo PDF usando Python. -- [Abrir documento PDF](/pdf/es/python-net/open-pdf-document/) - este artículo describe varias formas de abrir un documento PDF en aplicación Python. -- [Guardar documento PDF](/pdf/es/python-net/save-pdf-document/) - este artículo describe varias formas de guardar un documento PDF. +- [Abrir documento PDF](/pdf/es/python-net/open-pdf-document/) - este artículo describe diversas maneras de abrir un documento PDF en una aplicación Python. +- [Guardar documento PDF](/pdf/es/python-net/save-pdf-document/) - este artículo describe diversas maneras de guardar un documento PDF. +- [Combinar PDF](/pdf/es/python-net/merge-pdf/) - combinar varios archivos PDF en un solo documento PDF usando Python. +- [Dividir PDF](/pdf/es/python-net/split-pdf/) - dividir las páginas PDF en archivos PDF individuales en sus aplicaciones Python. +- [Proteger archivo PDF](/pdf/es/python-net/protect-pdf-file/) - proteger sus archivos PDF con Aspose.PDF for Python via .NET. diff --git a/es/python-net/basic-operations/create/_index.md b/es/python-net/basic-operations/create/_index.md index f2866a714..d9fff20b2 100644 --- a/es/python-net/basic-operations/create/_index.md +++ b/es/python-net/basic-operations/create/_index.md @@ -5,37 +5,35 @@ type: docs weight: 10 url: /es/python-net/create-document/ description: Esta página describe cómo crear un documento PDF desde cero con la biblioteca Aspose.PDF for Python via .NET. -TechArticle: true -AlternativeHeadline: Generación de archivos PDF con Aspose.PDF for Python -Abstract: > - En el desarrollo de software, generar archivos PDF programáticamente es un requisito común, particularmente para crear informes y otros documentos. Escribir código personalizado para esta tarea puede ser ineficiente y consumir mucho tiempo. En su lugar, los desarrolladores pueden utilizar **Aspose.PDF for Python via .NET**, una solución robusta para crear archivos PDF usando Python. El proceso implica crear un objeto `Document`, agregar un objeto `Page` a la colección `Pages` del documento, insertar un `TextFragment` en la colección `paragraphs` de la página y luego guardar el documento. Un fragmento de código de muestra en Python demuestra estos pasos, mostrando la facilidad con la que se pueden generar archivos PDF utilizando Aspose.PDF. +lastmod: "2026-05-08" +TechArticle: true +AlternativeHeadline: Generar archivos PDF con Aspose.PDF for Python +Abstract: En el desarrollo de software, generar archivos PDF programáticamente es un requisito común, particularmente para crear informes y otros documentos. Escribir código personalizado para esta tarea puede ser ineficiente y consumir mucho tiempo. En su lugar, los desarrolladores pueden utilizar **Aspose.PDF for Python via .NET**, una solución robusta para crear archivos PDF usando Python. El proceso implica crear un objeto `Document`, agregar un objeto `Page` a la colección `Pages` del documento, insertar un `TextFragment` en la colección `paragraphs` de la página y luego guardar el documento. Un fragmento de código Python de ejemplo demuestra estos pasos, mostrando la facilidad con la que se pueden generar archivos PDF usando Aspose.PDF. --- -Para los desarrolladores, existen muchos escenarios en los que se vuelve necesario generar archivos PDF de forma programática. Puede que necesite generar informes PDF y otros archivos PDF en su software de forma programática. Es bastante largo e ineficiente escribir su propio código y funciones desde cero. Para crear un archivo PDF con Python, hay una mejor solución: **Aspose.PDF for Python via .NET**. +Para los desarrolladores, existen muchos escenarios en los que se vuelve necesario generar archivos PDF de forma programática. Puede que necesite generar informes PDF y otros archivos PDF en su software de manera programática. Es bastante largo e ineficiente escribir su propio código y funciones desde cero. Para crear un archivo PDF con Python, hay una solución mejor: **Aspose.PDF for Python via .NET**. ## Cómo crear un archivo PDF usando Python -Para crear un archivo PDF usingPython, se pueden usar los siguientes pasos. +Para crear un archivo PDF usando Python, se pueden usar los siguientes pasos. -1. Crear un objeto de [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase -1. Agregar un [Página](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) objeto a la [Páginas](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties) colección del objeto Document -1. Agregar [FragmentoDeTexto](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/) a [párrafos](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) colección de la página +1. Crear un objeto de la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) +1. Agregar un objeto [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) a la colección [Pages](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties) del objeto `Document` +1. Agregar [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/) a la colección [paragraphs](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) de la página 1. Guardar el documento PDF resultante ```python - - import aspose.pdf as ap - - # Initialize document object - document = ap.Document() - # Add page - page = document.pages.add() - # Initialize textfragment object - text_fragment = ap.text.TextFragment("Hello,world!") - # Add text fragment to new page - page.paragraphs.add(text_fragment) - # Save updated PDF - document.save("output.pdf") +import aspose.pdf as ap + +# Initialize document object +document = ap.Document() +# Add page +page = document.pages.add() +# Add text to new page +page.paragraphs.add(ap.text.TextFragment("Hello World!")) +# Define output file path +output_pdf = "output.pdf" +# Save updated PDF +output_pdf = "output.pdf" +document.save(output_pdf) ``` - - diff --git a/es/python-net/basic-operations/merge-pdf/_index.md b/es/python-net/basic-operations/merge-pdf/_index.md index 3d55bf463..cfb4befcc 100644 --- a/es/python-net/basic-operations/merge-pdf/_index.md +++ b/es/python-net/basic-operations/merge-pdf/_index.md @@ -4,15 +4,14 @@ linktitle: Combinar archivos PDF type: docs weight: 50 url: /es/python-net/merge-pdf-documents/ -description: Aprenda cómo combinar varios archivos PDF en un único documento en Python. -lastmod: "2026-04-15" +description: Aprenda cómo combinar varios archivos PDF en un solo documento en Python. +lastmod: "2026-05-08" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Combinar páginas PDF usando Python -Abstract: > - Este artículo aborda la necesidad común de combinar varios archivos PDF en un único documento, un proceso valioso para organizar y optimizar el almacenamiento y la compartición de contenido PDF. Explora el uso de Aspose.PDF for Python via .NET para combinar eficientemente archivos PDF, reconociendo que combinar PDFs en Python puede ser un desafío sin bibliotecas de terceros. El artículo brinda una guía paso a paso para concatenar archivos PDF: crear un nuevo documento, combinar los archivos y guardar el documento combinado. Un fragmento de código muestra la implementación usando Aspose.PDF, resaltando la capacidad de la biblioteca para simplificar el proceso de combinación. Además, presenta Aspose.PDF Merger, una herramienta en línea para combinar PDFs, que permite a los usuarios explorar la funcionalidad en un entorno web. +Abstract: 'Este artículo aborda la necesidad común de combinar varios archivos PDF en un solo documento, un proceso valioso para organizar y optimizar el almacenamiento y la compartición de contenido PDF. Explora el uso de Aspose.PDF for Python via .NET para combinar eficazmente archivos PDF, reconociendo que combinar PDFs en Python puede ser un desafío sin bibliotecas de terceros. El artículo proporciona una guía paso a paso para concatenar archivos PDF: crear un nuevo documento, combinar los archivos y guardar el documento combinado. Un fragmento de código demuestra la implementación usando Aspose.PDF, resaltando la capacidad de la biblioteca para simplificar el proceso de combinación. Además, presenta Aspose.PDF Merger, una herramienta en línea para combinar PDFs, que permite a los usuarios explorar la funcionalidad en un entorno web.' --- ## Combinar archivos PDF usando Python y DOM @@ -39,7 +38,6 @@ def merge_two_documents(infile1, infile2, outfile): ## Ejemplo en vivo -[Aspose.PDF Fusionador](https://products.aspose.app/pdf/merger) es una aplicación web gratuita en línea que le permite investigar cómo funciona la funcionalidad de fusión de presentaciones. - -[![Aspose.PDF Fusionador](merger.png)](https://products.aspose.app/pdf/merger) +[Aspose.PDF Merger](https://products.aspose.app/pdf/merger) es una aplicación web gratuita en línea que le permite comprobar cómo funciona la combinación de archivos PDF. +[![Aspose.PDF Merger](merger.png)](https://products.aspose.app/pdf/merger) diff --git a/es/python-net/basic-operations/opening/_index.md b/es/python-net/basic-operations/opening/_index.md index 0c89437be..11d8dd87e 100644 --- a/es/python-net/basic-operations/opening/_index.md +++ b/es/python-net/basic-operations/opening/_index.md @@ -5,38 +5,40 @@ type: docs weight: 20 url: /es/python-net/open-pdf-document/ description: Aprenda cómo abrir un archivo PDF en Python con la biblioteca Aspose.PDF for Python via .NET. Puede abrir un PDF existente, un documento desde un flujo y un documento PDF cifrado. -lastmod: "2025-02-27" +lastmod: "2026-05-08" sitemap: changefreq: "monthly" priority: 0.7 TechArticle: true AlternativeHeadline: Abrir documentos PDF usando la biblioteca Aspose.PDF en Python -Abstract: > - Este artículo proporciona una guía sobre cómo abrir documentos PDF existentes usando la biblioteca Aspose.PDF en Python. Describe tres métodos para lograrlo: abrir un PDF especificando el nombre del archivo, abrir un PDF desde un flujo y abrir un PDF cifrado proporcionando una contraseña. Cada método incluye un fragmento de código que demuestra cómo utilizar la biblioteca Aspose.PDF para acceder al PDF y mostrar el número de páginas que contiene. Estos ejemplos ilustran la flexibilidad y funcionalidad de Aspose.PDF para manejar diferentes escenarios de acceso a archivos PDF. +Abstract: 'Este artículo proporciona una guía sobre cómo abrir documentos PDF existentes utilizando la biblioteca Aspose.PDF en Python. Describe tres métodos para lograrlo: abrir un PDF especificando el nombre del archivo, abrir un PDF desde un flujo y abrir un PDF cifrado proporcionando una contraseña. Cada método incluye un fragmento de código que demuestra cómo utilizar la biblioteca Aspose.PDF para acceder al PDF e imprimir el número de páginas que contiene. Estos ejemplos ilustran la flexibilidad y funcionalidad de Aspose.PDF para manejar diferentes escenarios de acceso a archivos PDF.' --- ## Abrir documento PDF existente -Hay varias formas de abrir un documento. La forma más sencilla es especificar un nombre de archivo. +Hay varias formas de abrir un documento. La más fácil es especificar un nombre de archivo. ```python import aspose.pdf as ap -# Open document -document = ap.Document(input_pdf) -print("Pages: " + str(len(document.pages))) +def open_document_from_file(infile): + + # Open document + document = ap.Document(infile) + print("Pages: " + str(len(document.pages))) ``` ## Abrir documento PDF existente desde el flujo ```python import aspose.pdf as ap +import io -input_pdf = DIR_INPUT + "sample.pdf" -stream = io.FileIO(input_pdf, "r") -# Open document -document = ap.Document(stream) -print("Pages: " + str(len(document.pages))) +def open_document_from_stream(infile): + with io.FileIO(infile, "r") as stream: + # Open document + document = ap.Document(stream) + print("Pages: " + str(len(document.pages))) ``` ## Abrir documento PDF cifrado @@ -44,7 +46,9 @@ print("Pages: " + str(len(document.pages))) ```python import aspose.pdf as ap -# Open document -document = ap.Document(input_pdf, password) -print("Pages: " + str(len(document.pages))) +def open_document_encrypted(infile): + password = "P@ssw0rd" + # Open document + document = ap.Document(infile, password) + print("Pages: " + str(len(document.pages))) ``` diff --git a/es/python-net/basic-operations/protect/_index.md b/es/python-net/basic-operations/protect/_index.md index 2968edd99..a4bbfc71a 100644 --- a/es/python-net/basic-operations/protect/_index.md +++ b/es/python-net/basic-operations/protect/_index.md @@ -4,33 +4,30 @@ linktitle: Cifrar y descifrar archivo PDF type: docs weight: 70 url: /es/python-net/protect-pdf-file/ -description: Aprende cómo cifrar archivos, descifrar PDFs protegidos y cambiar contraseñas en Python. -lastmod: "2026-04-15" +description: Aprenda cómo cifrar archivos, descifrar PDFs protegidos y cambiar contraseñas en Python. +lastmod: "2026-05-05" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Establecer permisos de PDF y gestionar el cifrado en Python -Abstract: > - Esta página de documentación explica cómo establecer privilegios de documento, aplicar cifrado y descifrar archivos PDF usando Aspose.PDF for Python. Guía a los desarrolladores a través de la configuración de contraseñas de usuario y de propietario, definiendo restricciones de acceso (como imprimir, copiar o editar). Los ejemplos de código ilustran cómo proteger contenido sensible y gestionar la seguridad de PDF de manera eficaz dentro de aplicaciones Python, garantizando un acceso controlado y la confidencialidad de los datos. +Abstract: Esta página explica cómo establecer privilegios de documento, aplicar cifrado, descifrar archivos PDF y cambiar contraseñas utilizando Aspose.PDF for Python via .NET. Cubre la configuración de contraseñas de usuario y propietario, la definición de restricciones de acceso (como imprimir, copiar y editar), y la gestión de la seguridad de PDF en aplicaciones Python. --- ## Cifrar PDF con contraseña y permisos -Aspose.PDF for Python muestra cómo asegurar un documento PDF usando cifrado basado en contraseña: +Utilice Aspose.PDF for Python via .NET para proteger un documento PDF con cifrado basado en contraseña y permisos restringidos. -1. Cargar el documento PDF. -1. Crear un objeto de permisos. -1. Permitir permisos específicos. -1. Establecer contraseñas de usuario y propietario. -1. Seleccionar el algoritmo de cifrado. -1. Aplicar cifrado al documento. -1. Guardar el PDF cifrado. +1. Cargue el documento PDF. +1. Cree un objeto de permisos `DocumentPrivilege`. +1. Habilite los permisos requeridos. +1. Establezca las contraseñas de usuario y de propietario. +1. Elija el algoritmo de cifrado. +1. Aplique el cifrado al documento. +1. Guarde el PDF cifrado. ```python import aspose.pdf as ap -import sys -from os import path def encrypt_password(infile, outfile): """ @@ -66,19 +63,17 @@ def encrypt_password(infile, outfile): ## Cifrar PDF con permisos completos -Encripta un documento PDF mientras permite permisos de acceso completo usando Aspose.PDF for Python. El ejemplo utiliza cifrado RC4 de 128 bits, lo que garantiza una seguridad básica manteniendo la compatibilidad con lectores PDF más antiguos. +Cifre un documento PDF mientras permite permisos de acceso completo usando Aspose.PDF for Python via .NET. Este ejemplo usa cifrado RC4 de 128 bits para compatibilidad con visores PDF más antiguos. -1. Cargar el documento PDF. -1. Define contraseñas de usuario y propietario. -1. Establece permisos de acceso completo. -1. Seleccionar el algoritmo de cifrado. -1. Llama al método encrypt() con contraseñas, permisos y algoritmo. -1. Guardar el PDF cifrado. +1. Cargue el documento PDF. +1. Defina las contraseñas de usuario y propietario. +1. Establezca permisos de acceso completo. +1. Elija el algoritmo de cifrado. +1. Llame a `encrypt()` con contraseñas, permisos y algoritmo. +1. Guarde el PDF cifrado. ```python import aspose.pdf as ap -import sys -from os import path def encrypt_pdf_file(infile, outfile): """ @@ -110,16 +105,14 @@ def encrypt_pdf_file(infile, outfile): ## Descifrar archivo PDF usando la contraseña del propietario -Para eliminar la protección por contraseña y restaurar el acceso completo: +Para eliminar la protección con contraseña y restaurar el acceso completo: -1. Cargue el PDF encriptado usando la contraseña correcta ('password' es la contraseña de usuario o de propietario). -1. Elimine toda la protección con contraseña y los ajustes de encriptación del documento. -1. Guarde el PDF ahora sin protección en el archivo de salida especificado. +1. Cargue el PDF cifrado usando la contraseña correcta (usuario o propietario). +1. Elimine toda la protección con contraseña y los ajustes de cifrado del documento. +1. Guarde el PDF ahora desprotegido en el archivo de salida especificado. ```python import aspose.pdf as ap -import sys -from os import path def decrypt_pdf_file(infile, outfile): """ @@ -145,16 +138,14 @@ def decrypt_pdf_file(infile, outfile): ## Cambiar la contraseña de un archivo PDF -Actualizar las credenciales de seguridad (contraseñas de usuario y propietario) de un documento PDF mientras se preservan su contenido y estructura. +Actualice las credenciales de seguridad (contraseñas de usuario y propietario) de un documento PDF mientras preserva su contenido y estructura. -1. Abra el PDF utilizando la contraseña de propietario existente ('owner'), que otorga acceso total, incluida la posibilidad de cambiar la configuración de seguridad. -1. Reemplace las contraseñas antiguas con una nueva contraseña de usuario ('newuser') y una nueva contraseña de propietario ('newowner'). +1. Abra el PDF usando la contraseña de propietario existente, que brinda acceso completo a la configuración de seguridad. +1. Reemplace las contraseñas antiguas por una nueva contraseña de usuario y una nueva contraseña de propietario. 1. Guarde el PDF con la configuración de contraseñas actualizada. ```python import aspose.pdf as ap -import sys -from os import path def change_password(infile, outfile): """ @@ -179,21 +170,19 @@ def change_password(infile, outfile): ``` -## Determinar la contraseña correcta del array +## Determinar la contraseña correcta de una lista -En algunos escenarios, es posible que necesite identificar la contraseña correcta de una lista de posibles candidatos para acceder a un PDF protegido. El fragmento de código a continuación muestra cómo comprobar si un archivo PDF está protegido con contraseña y luego intentar desbloquearlo iterando a través de una lista predefinida de contraseñas utilizando Aspose.PDF for Python via .NET. +En algunos escenarios, es posible que necesite identificar la contraseña correcta de una lista de candidatos para acceder a un PDF protegido. El fragmento a continuación verifica si un archivo PDF está cifrado y luego intenta abrirlo iterando a través de una lista predefinida de contraseñas. El proceso incluye: -1. Usando PdfFileInfo para detectar si el PDF está encriptado. -1. Abra el PDF con cada contraseña usando ap.Document(). -1. Si tiene éxito, imprime el número de páginas. -1. Si no, captura la excepción y reporta la contraseña fallida. +1. Use `PdfFileInfo` para detectar si el PDF está cifrado. +1. Abra el PDF con cada contraseña usando `ap.Document()`. +1. Si tiene éxito, imprima el número de páginas. +1. Si no, captura la excepción e informa la contraseña fallida. ```python import aspose.pdf as ap -import sys -from os import path def determine_correct_password_from_list(infile): """ diff --git a/es/python-net/basic-operations/saving/_index.md b/es/python-net/basic-operations/saving/_index.md index b7f2bd916..e5f7ad29c 100644 --- a/es/python-net/basic-operations/saving/_index.md +++ b/es/python-net/basic-operations/saving/_index.md @@ -5,56 +5,64 @@ type: docs weight: 30 url: /es/python-net/save-pdf-document/ description: Aprenda cómo guardar un archivo PDF en Python con la biblioteca Aspose.PDF for Python via .NET. Guarde el documento PDF en el sistema de archivos, en un flujo y en aplicaciones web. -lastmod: "2025-02-27" +lastmod: "2026-05-08" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Guardar documentos PDF usando la biblioteca Aspose.PDF en Python -Abstract: > - El artículo proporciona orientación sobre cómo guardar documentos PDF usando la biblioteca Aspose.PDF en Python. Describe tres métodos principales para guardar PDFs: al sistema de archivos, a un flujo y en formatos específicos como PDF/A o PDF/X. El método `save()` de la clase `Document` es central para estas operaciones. Para guardar un PDF en el sistema de archivos, se puede crear o manipular un documento, como añadir una nueva página, y luego guardarlo directamente en una ruta. Para guardar en un flujo, las sobrecargas del método `Save` permiten escribir un documento a un objeto de flujo. Además, el artículo explica cómo guardar documentos en los formatos PDF/A o PDF/X, que son estándares para el archivado a largo plazo y el intercambio de gráficos, respectivamente. Este proceso requiere preparar el documento con el método `convert` antes de guardarlo. Los fragmentos de código Python proporcionados demuestran cada enfoque, ilustrando la aplicación práctica de estos métodos. +Abstract: 'El artículo ofrece orientación sobre cómo guardar documentos PDF usando la biblioteca Aspose.PDF en Python. Describe tres métodos principales para guardar PDFs: en el sistema de archivos, en un flujo y en formatos específicos como PDF/A o PDF/X. El método `save()` de la clase `Document` es fundamental para estas operaciones. Para guardar un PDF en el sistema de archivos, se puede crear o manipular un documento, por ejemplo añadiendo una nueva página, y luego guardarlo directamente en una ruta. Para guardar en un flujo, las sobrecargas del método `Save` permiten escribir un documento en un objeto de flujo. Además, el artículo explica cómo guardar documentos en los formatos PDF/A o PDF/X, que son estándares para archivado a largo plazo e intercambio de gráficos, respectivamente. Este proceso requiere preparar el documento con el método `convert` antes de guardarlo. Los fragmentos de código Python proporcionados demuestran cada enfoque, ilustrando la aplicación práctica de estos métodos.' --- ## Guardar documento PDF en el sistema de archivos -Puede guardar el documento PDF creado o manipulado en el sistema de archivos usando [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método de [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase. +Puede guardar el documento PDF creado o manipulado en el sistema de archivos usando el método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) de la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). ```python import aspose.pdf as ap -document = ap.Document(input_pdf) -# make some manipation, i.g add new empty page -document.pages.add() -document.save(output_pdf) +def save_document_to_file(infile, outfile): + document = ap.Document(infile) + # make some manipulation, e.g. add new empty page + document.pages.add() + document.save(outfile) ``` -## Guardar documento PDF en stream +## Guardar documento PDF en un flujo -También puedes guardar el documento PDF creado o manipulado en un flujo utilizando sobrecargas de `Save` métodos. +También puede guardar el documento PDF creado o manipulado en un flujo usando las sobrecargas del método `save()`. ```python import aspose.pdf as ap +import io -document = ap.Document(input_pdf) -# make some manipation, i.g add new empty page -document.pages.add() -document.save(io.FileIO(output_pdf, "w")) +def save_document_to_stream(infile, outfile): + document = ap.Document(infile) + # make some manipulation, e.g. add new empty page + document.pages.add() + with io.FileIO(outfile, 'w') as stream: + document.save(stream) ``` ## Guardar formato PDF/A o PDF/X -PDF/A es una versión estandarizada por ISO del Formato de Documento Portátil (PDF) para su uso en archivado y preservación a largo plazo de documentos electrónicos. -PDF/A difiere del PDF en que prohíbe características no adecuadas para el archivado a largo plazo, como el enlace de fuentes (en contraste con la incrustación de fuentes) y el cifrado. Los requisitos ISO para los visores de PDF/A incluyen directrices de gestión de color, soporte de fuentes incrustadas y una interfaz de usuario para la lectura de anotaciones incrustadas. +Puede guardar fácilmente un documento en una versión específica de PDF, como PDF/A o PDF/X. En este caso, debemos llamar al método `convert` antes de guardar el documento. -PDF/X es un subconjunto del estándar ISO PDF. El propósito de PDF/X es facilitar el intercambio de gráficos, y por lo tanto tiene una serie de requisitos relacionados con la impresión que no se aplican a los archivos PDF estándar. +PDF/A es una versión estandarizada por ISO del Formato de Documento Portátil (PDF) para su uso en el archivado y la preservación a largo plazo de documentos electrónicos. +PDF/A difiere del PDF en que prohíbe características no adecuadas para el archivado a largo plazo, como la vinculación de fuentes (en lugar de la incrustación de fuentes) y el cifrado. Los requisitos ISO para los visualizadores de PDF/A incluyen directrices de gestión del color, soporte de fuentes incrustadas y una interfaz de usuario para leer anotaciones incrustadas. -En ambos casos, el [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) el método se utiliza para almacenar los documentos, mientras que los documentos deben estar preparados usando el [convertir](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método. +PDF/X es un subconjunto del estándar ISO PDF. El propósito de PDF/X es facilitar el intercambio de gráficos, y por ello tiene una serie de requisitos relacionados con la impresión que no se aplican a los archivos PDF estándar. + +En ambos casos, el método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) se utiliza para almacenar los documentos, mientras que los documentos deben prepararse usando el método [convert](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods). ```python import aspose.pdf as ap +import io + -document = ap.Document(input_pdf) -document.pages.add() -document.convert(output_log, ap.PdfFormat.PDF_X_3, ap.ConvertErrorAction.DELETE) -document.save(output_pdf) +def save_document_as_standard(infile, outfile, logfile): + document = ap.Document(infile) + document.pages.add() + document.convert(logfile, ap.PdfFormat.PDF_X_3, ap.ConvertErrorAction.DELETE) + document.save(outfile) ``` diff --git a/es/python-net/basic-operations/split-pdf/_index.md b/es/python-net/basic-operations/split-pdf/_index.md index 19ac61fbb..7579df5ae 100644 --- a/es/python-net/basic-operations/split-pdf/_index.md +++ b/es/python-net/basic-operations/split-pdf/_index.md @@ -4,50 +4,51 @@ linktitle: Dividir archivos PDF type: docs weight: 60 url: /es/python-net/split-pdf-document/ -description: Aprende cómo dividir páginas PDF en archivos PDF separados en Python. +description: Aprenda cómo dividir páginas PDF en archivos PDF separados en Python. lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 TechArticle: true AlternativeHeadline: Dividir páginas PDF usando Python -Abstract: El artículo analiza el proceso de dividir páginas PDF en archivos individuales usando Python, resaltando la utilidad de esta función para gestionar documentos PDF extensos. Hace referencia al Aspose.PDF Splitter, una herramienta en línea diseñada para demostrar la funcionalidad de división de PDF. El artículo ofrece un método detallado para lograr esto en aplicaciones Python, que implica iterar a través de las páginas de un documento PDF mediante la colección `PageCollection` del objeto `Document`. Para cada página, se crea un nuevo objeto `Document`, se añade la página a este, y el nuevo archivo PDF se guarda utilizando el método `save()`. Un fragmento de código Python adjunto ilustra este proceso, mostrando los pasos necesarios para dividir un documento PDF en archivos separados al iterar por sus páginas y guardar cada una como un PDF individual. +Abstract: El artículo analiza el proceso de dividir páginas PDF en archivos individuales usando Python, destacando la utilidad de esta función para gestionar documentos PDF grandes. Hace referencia al Aspose.PDF Splitter, una herramienta en línea diseñada para demostrar la funcionalidad de división de PDF. El artículo proporciona un método detallado para lograrlo en aplicaciones Python, que implica iterar a través de las páginas de un documento PDF mediante la `PageCollection` del objeto `Document`. Para cada página, se crea un nuevo objeto `Document`, se añade la página a este, y el nuevo archivo PDF se guarda usando el método `save()`. Un fragmento de código Python adjunto ilustra este proceso, mostrando los pasos necesarios para dividir un documento PDF en archivos separados al iterar por sus páginas y guardar cada una como un PDF individual. --- -Dividir páginas PDF puede ser una característica útil para quienes desean separar un archivo grande en páginas individuales o en grupos de páginas. +Dividir páginas PDF puede ser una función útil para quienes necesitan separar un archivo grande en páginas individuales o grupos de páginas. -Utilice este flujo de trabajo cuando necesite dividir PDFs grandes en archivos de una sola página o en conjuntos de documentos más pequeños para distribución, revisión o procesamiento posterior. +Utilice este flujo de trabajo cuando necesite dividir documentos PDF grandes en archivos de una sola página o en conjuntos más pequeños para distribución, revisión o procesamiento posterior. ## Ejemplo en vivo -[Aspose.PDF Splitter](https://products.aspose.app/pdf/splitter) es una aplicación web gratuita en línea que le permite ver cómo funciona la funcionalidad de división de PDFs. +[Aspose.PDF Splitter](https://products.aspose.app/pdf/splitter) es una aplicación web gratuita en línea que le permite comprobar cómo funciona la división de archivos PDF. [![Aspose Split PDF](splitter.png)](https://products.aspose.app/pdf/splitter) -Este artículo muestra cómo dividir páginas PDF en archivos PDF individuales en sus aplicaciones Python. Para dividir páginas PDF en archivos PDF de una sola página usando Python, se pueden seguir los siguientes pasos: +Este tema muestra cómo dividir páginas de PDF en archivos PDF individuales en sus aplicaciones Python. Para dividir páginas de PDF en archivos PDF de una sola página usando Python, se pueden seguir los siguientes pasos: -1. Recorra las páginas del documento PDF mediante la colección `PageCollection` del objeto `Document`. -2. Para cada iteración, cree un nuevo objeto `Document` y añada la página individual al documento vacío. -3. Guarde el nuevo PDF usando el método `save()`. +1. Recorra las páginas del documento PDF mediante la colección [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) del objeto [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) +1. Para cada iteración, cree un nuevo objeto `Document` y agregue el objeto [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) al documento vacío +1. Guarde el nuevo PDF usando el método [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) ## Dividir PDF en varios archivos o PDFs separados en Python -El siguiente fragmento de código Python le muestra cómo dividir las páginas de un PDF en archivos PDF individuales. +El siguiente fragmento de código Python muestra cómo dividir las páginas PDF en archivos PDF individuales. ```python -import aspose.pdf as ap -# Open document -document = ap.Document(input_pdf) + import aspose.pdf as ap -page_count = 1 + # Open document + document = ap.Document(input_pdf) -# Loop through all the pages -for pdfPage in document.pages: - new_document = ap.Document() - new_document.pages.add(pdfPage) - new_document.save(output_path + "_page_" + str(page_count) + ".pdf") - page_count = page_count + 1 + page_count = 1 + + # Loop through all the pages + for pdfPage in document.pages: + new_document = ap.Document() + new_document.pages.add(pdfPage) + new_document.save(output_path + "_page_" + str(page_count) + ".pdf") + page_count = page_count + 1 ``` ## Temas relacionados del documento @@ -55,4 +56,4 @@ for pdfPage in document.pages: - [Trabajar con documentos PDF en Python](/pdf/es/python-net/working-with-documents/) - [Combinar archivos PDF en Python](/pdf/es/python-net/merge-pdf-documents/) - [Optimizar archivos PDF en Python](/pdf/es/python-net/optimize-pdf/) -- [Manipular documentos PDF en Python](/pdf/es/python-net/manipulate-pdf-document/) \ No newline at end of file +- [Manipular documentos PDF en Python](/pdf/es/python-net/manipulate-pdf-document/) diff --git a/es/python-net/converting/_index.md b/es/python-net/converting/_index.md index 92b047404..857a33524 100644 --- a/es/python-net/converting/_index.md +++ b/es/python-net/converting/_index.md @@ -1,79 +1,76 @@ --- -title: Convertir documentos PDF usando Python +title: Convertir documentos PDF en Python linktitle: Convertir documento PDF type: docs weight: 70 url: /es/python-net/converting/ -lastmod: "2025-02-27" -description: Aprenda cómo convertir PDFs a otros formatos en Python (NET) con Aspose.PDF para un procesamiento de documentos simplificado. +lastmod: "2026-05-11" +description: Aprenda cómo convertir documentos PDF a Word, Excel, PowerPoint, HTML, imágenes, PDF/A y otros formatos en Python con Aspose.PDF for Python via .NET. sitemap: changefreq: "monthly" priority: 0.8 -TechArticle: true -AlternativeHeadline: Convertir PDF y otros formatos con Python -Abstract: > - Esta sección muestra cómo convertir documentos PDF a Word, Excel, PowerPoint, HTML, imágenes y otros formatos con Aspose.PDF for Python via .NET. También reúne guías para convertir HTML, imágenes y otros tipos de archivo a PDF con ejemplos de código y opciones de conversión. +TechArticle: true +AlternativeHeadline: Cómo convertir documentos PDF usando Python +Abstract: Este artículo presenta **Aspose.PDF for Python**, una solución robusta para convertir documentos PDF a varios formatos usando Python. Python, un lenguaje de programación orientado a objetos versátil, se utiliza ampliamente para desarrollar prototipos de software y aplicaciones de procesamiento de datos. El artículo enfatiza la capacidad de Aspose.PDF para convertir PDFs con fines de edición, abarcando una amplia gama de documentos que incluyen texto, imágenes, hipervínculos y más. La biblioteca admite la conversión hacia y desde formatos populares como Microsoft Word, Excel y PowerPoint, así como HTML y varios formatos de imagen. También permite la conversión a formatos especializados como EPUB, Markdown y PDF/A para archivado a largo plazo. El artículo proporciona enlaces a guías detalladas sobre cómo realizar estas conversiones programáticamente con Python, presentando fragmentos de código para mayor claridad. Además, los usuarios pueden explorar opciones de conversión en línea mediante Aspose PDF Apps. Esta visión integral demuestra la versatilidad y facilidad de uso de Aspose.PDF para manejar tareas de conversión de documentos en Python. --- ¿Quieres convertir PDF a otros formatos usando Python? **Aspose.PDF for Python** es la mejor solución para convertir documentos PDF. Recuerda que Python es un lenguaje de programación orientado a objetos que se utiliza para desarrollar prototipos de software para aplicaciones web y procesamiento de datos. Ahora aprendamos cómo puedes convertir PDF a texto usando Python. -Los archivos PDF pueden contener no solo texto sino también imágenes, botones clicables, hipervínculos, fuentes incrustadas, firmas, sellos, etc. Los usuarios que están convirtiendo un archivo PDF a otro formato están interesados en hacerlo para poder editar el contenido del PDF. -**Nuestra Aspose.PDF for Python** library permite convertir tus documentos PDF a los formatos más populares y viceversa, de forma exitosa, rápida y sencilla. +Los archivos PDF pueden contener no solo texto sino también imágenes, botones clicables, hipervínculos, fuentes incrustadas, firmas, sellos, etc. Los usuarios que convierten un archivo PDF a otro formato están interesados en hacerlo para poder editar el contenido del PDF. +**Nuestra Aspose.PDF for Python** biblioteca le permite convertir sus documentos PDF de forma exitosa, rápida y sencilla a los formatos más populares y viceversa. ## Cómo usar Aspose.PDF para la conversión La siguiente sección describe las opciones más populares para convertir documentos PDF. -Después de aprender los ejemplos de código, entenderás que la biblioteca Aspose.PDF for Python via .NET ofrece soluciones bastante universales que te ayudarán a resolver las tareas de conversión de documentos. -Aspose.PDF admite la mayor cantidad de formatos de documentos populares, tanto para cargar como para guardar. +Después de aprender los ejemplos de código, comprenderá que la biblioteca Aspose.PDF for Python via .NET ofrece soluciones bastante universales que le ayudarán a resolver las tareas de conversión de documentos. +Aspose.PDF admite la mayor cantidad de formatos de documento populares, tanto para cargar como para guardar. Observe que la sección actual describe solo conversiones populares. -Para obtener una lista completa de los formatos compatibles, consulte la sección [Formatos de archivo compatibles con Aspose.PDF](https://docs.aspose.com/pdf/python-net/supported-file-formats/). +Para obtener una lista completa de los formatos compatibles, consulte la sección [Aspose.PDF Formatos de archivo compatibles](https://docs.aspose.com/pdf/python-net/supported-file-formats/). -Aspose.PDF for Python via .NET permite convertir documentos PDF a varios formatos y también convertir desde otros formatos a PDF. Además, puede comprobar la calidad de la conversión de Aspose.PDF y ver los resultados en línea con la Aspose.PDF converter app. Aprenda las secciones de conversión de documentos con fragmentos de código. +Aspose.PDF for Python via .NET permite convertir documentos PDF a varios formatos y también convertir desde otros formatos a PDF. Además, puede comprobar la calidad de la conversión de Aspose.PDF y ver los resultados en línea con la aplicación Aspose.PDF converter app. Aprenda las secciones de conversión de documentos con fragmentos de código. -Los documentos de Word son los más versátiles y editables posibles. Convertir PDF a Word manualmente es una tarea que consume mucho tiempo. En este artículo, aprenderá cómo convertir PDF a Word de forma programática en Python. +Los documentos de Word son los más versátiles y editables posibles. Convertir PDF a Word manualmente es una tarea que consume mucho tiempo. En este artículo, aprenderá cómo convertir PDF a Word programáticamente en Python. -- [Convertir PDF a Microsoft Word](/pdf/python-net/convert-pdf-to-word/) - puedes convertir tu documento PDF al formato Word con Python +- [Convertir PDF a Microsoft Word](/pdf/es/python-net/convert-pdf-to-word/) - puedes convertir tu documento PDF al formato Word con Python -Los formatos numéricos son necesarios no solo para que los datos en la tabla sean más fáciles de leer, sino también para que la tabla sea más fácil de usar. Por supuesto, si necesitas convertir esos datos de un documento PDF al formato Excel, usa nuestra biblioteca Aspose.PDF. +Los formatos de número son necesarios no solo para que los datos en la tabla sean más fáciles de leer, sino también para que la tabla sea más fácil de usar. Por supuesto, si necesitas convertir dichos datos de un documento PDF al formato Excel, utiliza nuestra biblioteca Aspose.PDF. -- [Convertir PDF a Microsoft Excel](/pdf/python-net/convert-pdf-to-excel/) - esta sección describe cómo convertir un documento PDF a XLSX, ODS, CSV y SpreadSheetML +- [Convertir PDF a Microsoft Excel](/pdf/es/python-net/convert-pdf-to-excel/) - esta sección describe cómo convertir un documento PDF a XLSX, ODS, CSV y SpreadSheetML -El formato PowerPoint se utiliza para crear diversas presentaciones. Los archivos PPT contienen un gran número de diapositivas o páginas que contienen diversa información. +El formato PowerPoint se utiliza para crear diversas presentaciones. Los archivos PPT contienen una gran cantidad de diapositivas o páginas con diversa información. -- [Convertir PDF a Microsoft PowerPoint](/pdf/python-net/convert-pdf-to-powerpoint/) - aquí estamos hablando de convertir PDF a PowerPoint siguiendo el proceso de conversión. +- [Convertir PDF a Microsoft PowerPoint](/pdf/es/python-net/convert-pdf-to-powerpoint/) - aquí estamos hablando de convertir PDF a PowerPoint siguiendo el proceso de conversión. HyperText Markup Language es un lenguaje de descripción de documentos hipertexto, un lenguaje estándar para crear páginas web. Con Aspose.PDF for Python puedes convertir fácilmente documentos HTML y viceversa. -- [Convertir formato HTML a archivo PDF](/pdf/python-net/convert-html-to-pdf/) - artículo sobre diferentes aspectos de la conversión de HTML a PDF. -- [Convertir archivo PDF a formato HTML](/pdf/python-net/convert-pdf-to-html/) - convierta sus documentos PDF a archivos HTML como páginas separadas o como una página única. +- [Convertir formato HTML a archivo PDF](/pdf/es/python-net/convert-html-to-pdf/) - artículo sobre diferentes aspectos de la conversión de HTML a PDF. +- [Convertir archivo PDF a formato HTML](/pdf/es/python-net/convert-pdf-to-html/) - convierta sus documentos PDF a archivos HTML como páginas separadas o como una página simgle. -Hay muchos formatos de imagen que necesitan convertirse a PDF para diferentes propósitos. Aspose.PDF permite los formatos de imagen más populares y viceversa. +Existen muchos formatos de imagen que deben convertirse a PDF para diferentes propósitos. Aspose.PDF permite los formatos de imagen más populares y viceversa. -- [Convertir PDF a varios formatos de imágenes](/pdf/python-net/convert-pdf-to-images-format/) - convierta páginas PDF como imágenes en JPEG, PNG y otros formatos. +- [Convertir PDF a varios formatos de imágenes](/pdf/es/python-net/convert-pdf-to-images-format/) - convierta páginas PDF como imágenes en JPEG, PNG y otros formatos. Esta sección incluye formatos como: EPUB, Markdown, PCL, XPS, LATex/TeX, Texto y PostScript. -- [Convertir archivo PDF a otros formatos](/pdf/python-net/convert-pdf-to-other-files/) - este tema describe la forma de convertir documentos PDF a varios formatos. +- [Convertir archivo PDF a otros formatos](/pdf/es/python-net/convert-pdf-to-other-files/) - este tema describe la forma de convertir documentos PDF a varios formatos. -PDF/A es una versión de PDF diseñada para el archivo a largo plazo de documentos electrónicos. -Si honestamente, externamente, es muy difícil determinar si es PDF o PDF/A. Para verificar este archivo, se utilizan validadores. Consulte los siguientes artículos para una conversión de calidad de PDF a PDF/A y viceversa. +PDF/A es una versión de PDF diseñada para el archivado a largo plazo de documentos electrónicos. +Si honestamente, externamente, es muy difícil determinar si es PDF o PDF/A. Para comprobar este archivo, se utilizan validadores. Consulte los siguientes artículos para una conversión de calidad de PDF a PDF/A y viceversa. -- [Convertir PDF a formatos PDF/A](/pdf/python-net/convert-pdf-to-pdfa/) - La biblioteca Python de Aspose.PDF tiene una forma fácil de convertir PDF a PDF/A. +- [Convertir formatos de imágenes a archivo PDF](/pdf/es/python-net/convert-images-format-to-pdf/) - Aspose.PDF le permite convertir diferentes formatos de imágenes a archivo PDF. -- [Convertir formatos de imágenes a archivo PDF](/pdf/python-net/convert-images-format-to-pdf/) - Aspose.PDF le permite convertir diferentes formatos de imágenes a un archivo PDF. +- [Convertir otros formatos de archivo a PDF](/pdf/es/python-net/convert-other-files-to-pdf/) - este tema describe la conversión con varios formatos como EPUB, XPS, Postscript, texto y otros. -- [Convertir otros formatos de archivo a PDF](/pdf/python-net/convert-other-files-to-pdf/) - este tema describe la conversión con varios formatos como EPUB, XPS, Postscript, texto y otros. +- [Convertir PDF/x a PDF](/pdf/es/python-net/convert-pdf_x-to-pdf/) - este tema describe la conversión de PDF/UA y PDF/A a PDF. -- [Convertir PDF/x a PDF](/pdf/python-net/convert-pdf_x-to-pdf/) - este tema describe la conversión de PDF/UA y PDF/A a PDF. - -- [Convertir PDF a PDF/x](/pdf/python-net/convert-pdf-to-pdf_x/) - este tema describe la conversión de PDF a formatos PDF/A, PDF/E y PDF/X. +- [Convertir PDF a PDF/x](/pdf/es/python-net/convert-pdf-to-pdf_x/) - este tema describe la conversión de PDF a los formatos PDF/A, PDF/E y PDF/X. ## Intenta convertir archivos PDF en línea {{% alert color="success" %}} -Puedes probar la funcionalidad de conversión utilizando nuestras aplicaciones Aspose PDF: +Puedes probar la funcionalidad de conversión usando nuestras aplicaciones Aspose PDF: [![Aplicación Aspose PDF](app.png)](https://products.aspose.app/pdf/conversion) {{% /alert %}} diff --git a/es/python-net/converting/convert-html-to-pdf/_index.md b/es/python-net/converting/convert-html-to-pdf/_index.md index a267ce443..d960b9802 100644 --- a/es/python-net/converting/convert-html-to-pdf/_index.md +++ b/es/python-net/converting/convert-html-to-pdf/_index.md @@ -4,15 +4,14 @@ linktitle: Convertir HTML a archivo PDF type: docs weight: 40 url: /es/python-net/convert-html-to-pdf/ -lastmod: "2026-04-14" -description: Aprenda cómo convertir contenido HTML y MHTML a PDF en Python con Aspose.PDF for Python via .NET, incluyendo configuraciones de medios, reglas CSS, fuentes incrustadas y estructura lógica. +lastmod: "2026-05-11" +description: Aprende cómo convertir HTML y MHTML a PDF en Python con Aspose.PDF for Python via .NET, incluyendo configuraciones de medios CSS, fuentes incrustadas y salida de PDF etiquetado. sitemap: changefreq: "monthly" priority: 0.8 -TechArticle: true -AlternativeHeadline: Convertir HTML y MHTML a PDF con Python -Abstract: > - Esta guía explica cómo convertir archivos HTML y MHTML a PDF con Aspose.PDF for Python via .NET. Aprenderá a controlar la renderización con tipos de medios, reglas CSS, fuentes incrustadas, salida en una sola página y estructura lógica para PDF accesibles. +TechArticle: true +AlternativeHeadline: Cómo convertir HTML a PDF en Python con Aspose.PDF +Abstract: Este artículo explica cómo convertir archivos HTML y MHTML a PDF utilizando Aspose.PDF for Python via .NET. Cubre el flujo de trabajo básico de HTML a PDF y muestra cómo controlar la renderización con tipos de medios, prioridad de reglas de página CSS, fuentes incrustadas, salida de una sola página y generación de estructura lógica para PDFs etiquetados accesibles. --- ## Conversión de HTML a PDF con Python @@ -23,8 +22,8 @@ Abstract: > El siguiente ejemplo de Python muestra el flujo de trabajo básico para convertir un documento HTML a PDF. -1. Crea una instancia de [HtmlLoadOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/htmlloadoptions/) clase. -1. Inicializar un [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) objeto con el archivo HTML fuente. +1. Crear una instancia de la [HtmlLoadOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/htmlloadoptions/) clase. +1. Inicializar un [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) objeto con el archivo HTML de origen. 1. Guarde el documento PDF de salida llamando `document.save()`. ```python @@ -41,22 +40,28 @@ document.save(path_outfile) print(infile + " converted into " + outfile) ``` +## Conversiones relacionadas + +- [Convertir PDF a HTML](/pdf/es/python-net/convert-pdf-to-html/) cuando necesitas una salida lista para la web a partir de archivos PDF existentes. +- [Convertir otros formatos de archivo a PDF](/pdf/es/python-net/convert-other-files-to-pdf/) para flujos de trabajo de conversión de EPUB, XPS, texto y PostScript. +- [Convertir imágenes a PDF](/pdf/es/python-net/convert-images-format-to-pdf/) cuando su contenido fuente es basado en imágenes en lugar de marcado HTML. + {{% alert color="success" %}} **Intenta convertir HTML a PDF en línea** -Aspose presenta la aplicación en línea gratuita ["HTML a PDF"](https://products.aspose.app/html/en/conversion/html-to-pdf), donde puedes probar la calidad de la conversión y la salida. +Aspose presenta la aplicación en línea ["HTML a PDF"](https://products.aspose.app/html/en/conversion/html-to-pdf), donde puedes probar la calidad de conversión y la salida. -[![Conversión de HTML a PDF con Aspose.PDF usando la aplicación gratuita](html.png)](https://products.aspose.app/html/en/conversion/html-to-pdf) +[![Conversión de Aspose.PDF de HTML a PDF usando la aplicación](html.png)](https://products.aspose.app/html/en/conversion/html-to-pdf) {{% /alert %}} -## Convertir HTML a PDF usando el tipo de medio +## Convertir HTML a PDF usando tipo de medio Este ejemplo muestra cómo convertir un archivo HTML a PDF utilizando opciones de renderizado específicas. -1. Crea una instancia de [HtmlLoadOptions()](https://reference.aspose.com/pdf/python-net/aspose.pdf/htmlloadoptions/) clase. -1. Establecer `html_media_type` para aplicar reglas CSS destinadas a diseños de pantalla o impresión, como `HtmlMediaType.SCREEN` o `HtmlMediaType.PRINT`. +1. Crear una instancia de la [HtmlLoadOptions()](https://reference.aspose.com/pdf/python-net/aspose.pdf/htmlloadoptions/) clase. +1. Establecer `html_media_type` para aplicar reglas CSS destinadas a pantallas o a diseños de impresión, como `HtmlMediaType.SCREEN` o `HtmlMediaType.PRINT`. 1. Cargar el HTML en un `ap.Document` usando las opciones de carga. -1. Guarde el documento como PDF. +1. Guarde el documento como un PDF. ```python from os import path @@ -74,12 +79,12 @@ print(infile + " converted into " + outfile) ## Prioriza el CSS `@page` regla durante la conversión de HTML a PDF -Algunos documentos usan [el `@page` regla](https://developer.mozilla.org/en-US/docs/Web/CSS/@page) para el diseño de página. Si esos estilos entran en conflicto con otras configuraciones, puedes controlar la prioridad con `is_priority_css_page_rule`. +Algunos documentos usan [el `@page` regla](https://developer.mozilla.org/en-US/docs/Web/CSS/@page) para maquetación de página. Si esos estilos entran en conflicto con otras configuraciones, puedes controlar la prioridad con `is_priority_css_page_rule`. -1. Crea una instancia de [HtmlLoadOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/htmlloadoptions/) clase. -1. Establecer `is_priority_css_page_rule = False` para permitir que otros estilos tengan prioridad sobre `@page` reglas. +1. Crear una instancia de la [HtmlLoadOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/htmlloadoptions/) clase. +1. Establecer `is_priority_css_page_rule = False` para que otros estilos tengan prioridad sobre `@page` reglas. 1. Cargar el HTML en un `ap.Document` con las opciones configuradas. -1. Guarde el documento como PDF. +1. Guarde el documento como un PDF. ```python from os import path @@ -97,12 +102,12 @@ print(infile + " converted into " + outfile) ## Convertir HTML a PDF con fuentes incrustadas -Este ejemplo muestra cómo convertir un archivo HTML a PDF mientras se incrustan fuentes. Si necesitas que el PDF de salida preserve la tipografía original de manera más fiable, establece `is_embed_fonts` a `True`. +Este ejemplo muestra cómo convertir un archivo HTML a PDF mientras se incrustan fuentes. Si necesita que el PDF de salida preserve la tipografía original, establezca `is_embed_fonts` a `True`. 1. Crear `HtmlLoadOptions()` para configurar la conversión de HTML a PDF. -1. Establecer `is_embed_fonts = True` para incrustar las fuentes usadas en el HTML directamente en el PDF. +1. Establecer `is_embed_fonts = True` incrustar las fuentes utilizadas en el HTML directamente en el PDF. 1. Cargar el HTML en un `ap.Document` con estas opciones. -1. Guarde el documento como PDF. +1. Guarde el documento como un PDF. ```python from os import path @@ -123,9 +128,9 @@ print(infile + " converted into " + outfile) Este ejemplo muestra cómo convertir un archivo HTML en un PDF de una sola página usando Aspose.PDF for Python via .NET. Utilice el `is_render_to_single_page` propiedad cuando deseas que todo el contenido HTML se renderice en una sola página continua. 1. Crear una instancia de `HtmlLoadOptions()` para configurar el proceso de conversión. -1. Activar `is_render_to_single_page` para renderizar todo el contenido HTML en una sola página. +1. Habilitar `is_render_to_single_page` para renderizar todo el contenido HTML en una página. 1. Cargue el documento con las opciones configuradas en un `ap.Document`. -1. Guarde el resultado como un archivo PDF. +1. Guarda el resultado como un archivo PDF. ```python from os import path @@ -143,18 +148,18 @@ doc.save(path_outfile) ## Crear estructura lógica a partir de etiquetas HTML -La estructura lógica, también llamada PDF etiquetado, conserva la jerarquía semántica del HTML original, como encabezados, párrafos y listas. Esto hace que el PDF resultante sea más accesible, buscable y adecuado para flujos de trabajo de documentos estructurados. +Estructura lógica, también llamada Tagged PDF, preserva la jerarquía semántica del HTML original, como encabezados, párrafos y listas. Esto hace que el PDF resultante sea más accesible, buscable y adecuado para flujos de trabajo de documentos estructurados. -Al habilitar la estructura lógica durante la conversión, el DOM HTML se mapea a un árbol de etiquetas PDF en lugar de renderizarse solo como contenido visual. +Al habilitar la estructura lógica durante la conversión, el HTML DOM se asigna a un árbol de etiquetas PDF en lugar de renderizarse solo como contenido visual. Para cumplir con los requisitos de accesibilidad, un PDF debe incluir elementos de estructura lógica que definan el orden de lectura, proporcionen texto alternativo para los lectores de pantalla y preserven la jerarquía del contenido. > La calidad de la estructura lógica en el PDF de salida depende directamente de la calidad del marcado HTML original. Un HTML mal estructurado o inválido puede resultar en un etiquetado incompleto o inexacto en el PDF convertido. -1. Crea una instancia de HtmlLoadOptions para controlar cómo se convierte el HTML. -1. Active el etiquetado semántico para que el PDF contenga elementos estructurados. +1. Cree una instancia de HtmlLoadOptions para controlar cómo se convierte el HTML. +1. Active la etiquetación semántica para que el PDF contenga elementos estructurados. 1. Abra el archivo HTML usando las opciones configuradas. -1. Guarda el PDF estructurado. +1. Guardar el PDF estructurado. ```python import aspose.pdf as ap @@ -179,8 +184,8 @@ Este ejemplo muestra cómo convertir un archivo MHT o MHTML en un documento PDF 1. Crear una instancia de `ap.MhtLoadOptions()` para configurar el procesamiento de archivos MHTML. 1. Establezca varios parámetros, como el tamaño de página. -1. Inicialice el documento con el archivo de entrada y las opciones de carga configuradas. -1. Guarda el documento resultante como un PDF. +1. Inicializa el documento con el archivo de entrada y las opciones de carga configuradas. +1. Guarde el documento resultante como un PDF. ```python from os import path diff --git a/es/python-net/converting/convert-images-format-to-pdf/_index.md b/es/python-net/converting/convert-images-format-to-pdf/_index.md index 641a9d4f1..b639a9aac 100644 --- a/es/python-net/converting/convert-images-format-to-pdf/_index.md +++ b/es/python-net/converting/convert-images-format-to-pdf/_index.md @@ -1,21 +1,26 @@ --- -title: Convertir varios formatos de imágenes a PDF en Python +title: Convertir formatos de imagen a PDF en Python linktitle: Convertir imágenes a PDF type: docs weight: 60 url: /es/python-net/convert-images-format-to-pdf/ -lastmod: "2025-09-01" -description: Convertir varios formatos de imágenes, como BMP, CGM, DICOM, PNG, TIFF, EMF y SVG, a PDF usando Python. +lastmod: "2026-05-11" +description: Aprenda cómo convertir BMP, CGM, DICOM, PNG, TIFF, EMF, SVG y otros formatos de imagen a PDF en Python con Aspose.PDF for Python via .NET. sitemap: changefreq: "monthly" priority: 0.5 -TechArticle: true -AlternativeHeadline: Convertir imágenes a PDF con Python -Abstract: > - Esta página explica cómo convertir formatos de imagen como BMP, CGM, DICOM, EMF, GIF, PNG, SVG y TIFF a PDF con Aspose.PDF for Python via .NET. Incluye los pasos principales, opciones de carga y ejemplos de código para cada flujo de conversión. +TechArticle: true +AlternativeHeadline: Cómo convertir imágenes a PDF en Python +Abstract: Este artículo ofrece una guía completa sobre cómo convertir varios formatos de imagen a PDF usando Python, aprovechando específicamente la biblioteca Aspose.PDF library for Python via .NET. El artículo cubre una variedad de formatos de imagen, incluidos BMP, CGM, DICOM, EMF, GIF, PNG, SVG y TIFF. Cada sección detalla los pasos necesarios para realizar la conversión, proporcionando fragmentos de código para ilustrar el proceso. Por ejemplo, convertir BMP a PDF implica crear un nuevo documento PDF, definir la ubicación de la imagen, insertar la imagen y guardar el documento. De manera similar, para formatos como CGM, DICOM y otros, se describen opciones de carga específicas y pasos de procesamiento. El artículo también destaca las ventajas de usar Aspose.PDF para estas tareas, como su compatibilidad con diferentes métodos de codificación y la capacidad de procesar imágenes de un solo cuadro y de varios cuadros. --- -## Conversiones de Imágenes Python a PDF +## Conversiones relacionadas + +- [Convertir PDF a formatos de imagen](/pdf/es/python-net/convert-pdf-to-images-format/) cuando necesites el flujo de trabajo inverso. +- [Convertir HTML a PDF](/pdf/es/python-net/convert-html-to-pdf/) para contenido web y fuentes MHTML. +- [Convertir otros formatos de archivo a PDF](/pdf/es/python-net/convert-other-files-to-pdf/) para EPUB, XPS, texto y otras entradas que no son imágenes. + +## Conversiones de imágenes a PDF con Python **Aspose.PDF for Python via .NET** permite convertir diferentes formatos de imágenes a archivos PDF. Nuestra biblioteca muestra fragmentos de código para convertir los formatos de imagen más populares, como - BMP, CGM, DICOM, EMF, JPG, PNG, SVG y formatos TIFF. @@ -23,7 +28,7 @@ Abstract: > Convertir archivos BMP a documento PDF usando la biblioteca **Aspose.PDF for Python via .NET**. -BMP Las imágenes son archivos que tienen extensión. BMP representa archivos de imagen Bitmap que se utilizan para almacenar imágenes digitales bitmap. Estas imágenes son independientes del adaptador gráfico y también se denominan formato bitmap independiente del dispositivo (DIB). +BMP las imágenes son archivos con extensión. BMP representa archivos de imagen bitmap que se utilizan para almacenar imágenes digitales bitmap. Estas imágenes son independientes del adaptador gráfico y también se llaman formato de archivo bitmap independiente del dispositivo (DIB). Puedes convertir archivos BMP a PDF con Aspose.PDF for Python via .NET API. Por lo tanto, puedes seguir los siguientes pasos para convertir imágenes BMP: @@ -37,21 +42,16 @@ Pasos para convertir BMP a PDF en Python: Así, el siguiente fragmento de código sigue estos pasos y muestra cómo convertir BMP a PDF usando Python: ```python +import aspose.pdf as ap +from os import path +import sys - from io import FileIO - from os import path - import os - import shutil - import aspose.pdf as apdf - import inspect - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = apdf.Document() - rectangle = apdf.Rectangle(0, 0, 595, 842, True) # A4 size in points - page.add_image(path_infile, rectangle) - document.save(path_outfile) +def convert_BMP_to_PDF(infile, outfile): + document = ap.Document() + page = document.pages.add() + rectangle = ap.Rectangle(0, 0, 595, 842, True) # A4 size in points + page.add_image(infile, rectangle) + document.save(outfile) print(infile + " converted into " + outfile) ``` @@ -59,18 +59,18 @@ Así, el siguiente fragmento de código sigue estos pasos y muestra cómo conver {{% alert color="success" %}} **Intenta convertir BMP a PDF en línea** -Aspose le presenta una aplicación gratuita en línea ["BMP a PDF"](https://products.aspose.app/pdf/conversion/bmp-to-pdf/), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose le presenta la aplicación en línea ["BMP a PDF"](https://products.aspose.app/pdf/conversion/bmp-to-pdf/), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. -[![Conversión BMP a PDF con Aspose.PDF usando una App Gratuita](bmp_to_pdf.png)](https://products.aspose.app/pdf/conversion/bmp-to-pdf/) +[![Aspose.PDF Conversión BMP a PDF usando la aplicación](bmp_to_pdf.png)](https://products.aspose.app/pdf/conversion/bmp-to-pdf/) {{% /alert %}} ## Convertir CGM a PDF -Convertir un CGM (Computer Graphics Metafile) a PDF (u otro formato compatible) utilizando Aspose.PDF for Python via .NET. +Convertir un CGM (Computer Graphics Metafile) a PDF (u otro formato compatible) usando Aspose.PDF for Python via .NET. -CGM es una extensión de archivo para un formato Metarchivo de Gráficos por Computadora utilizado comúnmente en CAD (diseño asistido por computadora) y aplicaciones de gráficos de presentación. CGM es un formato de gráficos vectoriales que admite tres métodos de codificación diferentes: binario (mejor para la velocidad de lectura del programa), basado en caracteres (produce el tamaño de archivo más pequeño y permite transferencias de datos más rápidas) o codificación en texto claro (permite a los usuarios leer y modificar el archivo con un editor de texto). +CGM es una extensión de archivo para un formato Computer Graphics Metafile comúnmente utilizado en aplicaciones CAD (diseño asistido por computadora) y de gráficos de presentación. CGM es un formato de gráficos vectoriales que admite tres métodos de codificación diferentes: binario (mejor para la velocidad de lectura del programa), basado en caracteres (produce el tamaño de archivo más pequeño y permite transferencias de datos más rápidas) o codificación en texto claro (permite a los usuarios leer y modificar el archivo con un editor de texto). -Ver el siguiente fragmento de código para convertir archivos CGM a formato PDF. +Verifique el siguiente fragmento de código para convertir archivos CGM al formato PDF. Pasos para convertir CGM a PDF en Python: @@ -80,22 +80,15 @@ Pasos para convertir CGM a PDF en Python: 1. Mensaje de conversión de impresión ```python +import aspose.pdf as ap +from os import path +import sys - from io import FileIO - from os import path - import os - import shutil - import aspose.pdf as apdf - import inspect +def convert_CGM_to_PDF(infile, outfile): + options = ap.CgmLoadOptions() + document = ap.Document(infile, options) + document.save(outfile) - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - options = apdf.CgmLoadOptions() - - # Open PDF document - document = apdf.Document(path_infile, options) - document.save(path_outfile) print(infile + " converted into " + outfile) ``` @@ -103,41 +96,30 @@ Pasos para convertir CGM a PDF en Python: DICOM format es el estándar de la industria médica para la creación, almacenamiento, transmisión y visualización de imágenes médicas digitales y documentos de pacientes examinados. -**Aspose.PDF for Python** le permite convertir imágenes DICOM y SVG, pero por razones técnicas, para agregar imágenes necesita especificar el tipo de archivo que se añadirá al PDF. +**Aspose.PDF for Python** permite convertir imágenes DICOM y SVG, pero por razones técnicas al agregar imágenes se necesita especificar el tipo de archivo que se añadirá al PDF. El siguiente fragmento de código muestra cómo convertir archivos DICOM al formato PDF con Aspose.PDF. Debe cargar la imagen DICOM, colocar la imagen en una página de un archivo PDF y guardar la salida como PDF. Utilizamos la biblioteca adicional pydicom para establecer las dimensiones de esta imagen. Si desea posicionar la imagen en la página, puede omitir este fragmento de código. -1. Inicializa un nuevo 'ap.Document()' y agrega una página -1. Insertar imagen DICOM. Crear un apdf.Image(), establecer su tipo a DICOM y asignar la ruta del archivo. -1. Ajustar tamaño de página. Igualar las dimensiones de la página PDF al tamaño de la imagen DICOM, eliminar márgenes. -1. Agrega la imagen a la página, guarda el documento en el archivo de salida. - -1. Cargue el archivo DICOM. +1. Cargar el archivo DICOM. 1. Extraer dimensiones de la imagen. 1. Imprimir tamaño de la imagen. -1. Cree un nuevo documento PDF. -1. Prepara la imagen DICOM para PDF. -1. Establecer el tamaño de página y los márgenes del PDF. +1. Crear un nuevo documento PDF. +1. Prepare la imagen DICOM para PDF. +1. Establecer el tamaño de página del PDF y los márgenes. 1. Añade la imagen a la página. 1. Guarda el PDF. -1. Imprimir mensaje de conversión. +1. Mensaje de conversión de impresión. ```python +import aspose.pdf as ap +from os import path +import sys - from io import FileIO - from os import path - import os - import shutil - import aspose.pdf as apdf - import inspect +def convert_DICOM_to_PDF(infile, outfile): + # Load the DICOM file import pydicom - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - # Load the DICOM file - dicom_file = pydicom.dcmread(path_infile) + dicom_file = pydicom.dcmread(infile) # Get the dimensions of the image rows = dicom_file.Rows @@ -147,14 +129,13 @@ El siguiente fragmento de código muestra cómo convertir archivos DICOM al form print(f"DICOM image size: {rows} x {columns} pixels") # Initialize new Document - document = apdf.Document() + document = ap.Document() page = document.pages.add() - image = apdf.Image() - image.file_type = apdf.ImageFileType.DICOM - image.file = path_infile + image = ap.Image() + image.file_type = ap.ImageFileType.DICOM + image.file = infile # Set page dimensions - page.page_info.height = rows page.page_info.width = columns page.page_info.margin.bottom = 0 @@ -163,127 +144,108 @@ El siguiente fragmento de código muestra cómo convertir archivos DICOM al form page.page_info.margin.left = 0 page.paragraphs.add(image) - document.save(path_outfile) + document.save(outfile) print(infile + " converted into " + outfile) ``` {{% alert color="success" %}} **Intenta convertir DICOM a PDF en línea** -Aspose le presenta una aplicación gratuita en línea ["DICOM a PDF"](https://products.aspose.app/pdf/conversion/dicom-to-pdf/), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose le presenta la aplicación en línea ["DICOM a PDF"](https://products.aspose.app/pdf/conversion/dicom-to-pdf/), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. -[![Conversión de DICOM a PDF con Aspose.PDF usando una aplicación gratuita](dicom_to_pdf.png)](https://products.aspose.app/pdf/conversion/dicom-to-pdf/) +[![Conversión de DICOM a PDF usando la aplicación Aspose.PDF](dicom_to_pdf.png)](https://products.aspose.app/pdf/conversion/dicom-to-pdf/) {{% /alert %}} ## Convertir EMF a PDF -EMF almacena imágenes gráficas de forma independiente del dispositivo. Metafiles de EMF constan de registros de longitud variable en orden cronológico que pueden renderizar la imagen almacenada después de analizarla en cualquier dispositivo de salida. +EMF almacena imágenes gráficas de forma independiente del dispositivo. Los metarchivos de EMF constan de registros de longitud variable en orden cronológico que pueden renderizar la imagen almacenada después de analizarla en cualquier dispositivo de salida. El siguiente fragmento de código muestra cómo convertir un EMF a PDF con Python: ```python - from io import FileIO - from os import path - import os - import shutil - import aspose.pdf as apdf - import inspect - import pydicom - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) +import aspose.pdf as ap +from os import path +import sys - document = apdf.Document() +def convert_EMF_to_PDF(infile, outfile): + document = ap.Document() page = document.pages.add() - rectangle = apdf.Rectangle(0, 0, 595, 842, True) # A4 size in points + rectangle = ap.Rectangle(0, 0, 595, 842, True) # A4 size in points # add image to new pdf page - page.add_image(path_infile, rectangle) + page.add_image(infile, rectangle) # Save the file into PDF format - document.save(path_outfile) + document.save(outfile) print(infile + " converted into " + outfile) ``` {{% alert color="success" %}} -**Intente convertir EMF a PDF en línea** +**Intenta convertir EMF a PDF en línea** -Aspose le presenta una aplicación gratuita en línea ["EMF a PDF"](https://products.aspose.app/pdf/conversion/emf-to-pdf/), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose le presenta la aplicación en línea ["EMF a PDF"](https://products.aspose.app/pdf/conversion/emf-to-pdf/), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. -[![Conversión de EMF a PDF usando la aplicación gratuita de Aspose.PDF](emf_to_pdf.png)](https://products.aspose.app/pdf/conversion/emf-to-pdf/) +[![Aspose.PDF Conversión de EMF a PDF usando App](emf_to_pdf.png)](https://products.aspose.app/pdf/conversion/emf-to-pdf/) {{% /alert %}} ## Convertir GIF a PDF -Convertir archivos GIF a documento PDF utilizando la biblioteca **Aspose.PDF for Python via .NET**. +Convierte archivos GIF a documento PDF usando la biblioteca **Aspose.PDF for Python via .NET**. -GIF es capaz de almacenar datos comprimidos sin pérdida de calidad en un formato de no más de 256 colores. El formato GIF independiente del hardware fue desarrollado en 1987 (GIF87a) por CompuServe para transmitir imágenes de mapa de bits a través de redes. +GIF es capaz de almacenar datos comprimidos sin pérdida de calidad en un formato de no más de 256 colores. El formato GIF independiente del hardware se desarrolló en 1987 (GIF87a) por CompuServe para transmitir imágenes bitmap a través de redes. Así, el siguiente fragmento de código sigue estos pasos y muestra cómo convertir BMP a PDF usando Python: ```python - from io import FileIO - from os import path - import os - import shutil - import aspose.pdf as apdf - import inspect - import pydicom - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) +import aspose.pdf as ap +from os import path +import sys - document = apdf.Document() +def convert_GIF_to_PDF(infile, outfile): + document = ap.Document() page = document.pages.add() - rectangle = apdf.Rectangle(0, 0, 595, 842, True) # A4 size in points - page.add_image(path_infile, rectangle) + rectangle = ap.Rectangle(0, 0, 595, 842, True) # A4 size in points + page.add_image(infile, rectangle) - document.save(path_outfile) + document.save(outfile) print(infile + " converted into " + outfile) ``` {{% alert color="success" %}} **Intenta convertir GIF a PDF en línea** -Aspose le presenta una aplicación gratuita en línea ["GIF a PDF"](https://products.aspose.app/pdf/conversion/gif-to-pdf/), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose le presenta la aplicación en línea ["GIF a PDF"](https://products.aspose.app/pdf/conversion/gif-to-pdf/), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. -[![Aspose.PDF Conversión de GIF a PDF usando la aplicación gratuita](bmp_to_pdf.png)](https://products.aspose.app/pdf/conversion/gif-to-pdf/) +[![Conversión de GIF a PDF usando la aplicación Aspose.PDF](bmp_to_pdf.png)](https://products.aspose.app/pdf/conversion/gif-to-pdf/) {{% /alert %}} ## Convertir PNG a PDF -**Aspose.PDF for Python via .NET** soporta la función de convertir imágenes PNG al formato PDF. Revisa el siguiente fragmento de código para realizar tu tarea. +**Aspose.PDF for Python via .NET** admite la función de convertir imágenes PNG a formato PDF. Consulta el siguiente fragmento de código para realizar tu tarea. PNG se refiere a un tipo de formato de archivo de imagen raster que usa compresión sin pérdida, lo que lo hace popular entre sus usuarios. -Puedes convertir una imagen PNG a PDF usando los siguientes pasos: +Puedes convertir PNG a imagen PDF usando los siguientes pasos: 1. Crear un nuevo documento PDF. -1. Definir la colocación de la imagen. +1. Definir colocación de imagen. 1. Guarda el PDF. -1. Imprimir mensaje de conversión. +1. Mensaje de conversión de impresión. Además, el fragmento de código a continuación muestra cómo convertir PNG a PDF con Python: ```python +import aspose.pdf as ap +from os import path +import sys - from io import FileIO - from os import path - import os - import shutil - import aspose.pdf as apdf - import inspect - import pydicom - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = apdf.Document() +def convert_PNG_to_PDF(infile, outfile): + document = ap.Document() page = document.pages.add() - rectangle = apdf.Rectangle(0, 0, 595, 842, True) # A4 size in points - page.add_image(path_infile, rectangle) - document.save(path_outfile) + rectangle = ap.Rectangle(0, 0, 595, 842, True) # A4 size in points + page.add_image(infile, rectangle) + document.save(outfile) print(infile + " converted into " + outfile) ``` @@ -291,9 +253,9 @@ Además, el fragmento de código a continuación muestra cómo convertir PNG a P {{% alert color="success" %}} **Intenta convertir PNG a PDF en línea** -Aspose le presenta una aplicación gratuita en línea ["PNG a PDF"](https://products.aspose.app/pdf/conversion/png-to-pdf/), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose le presenta la aplicación en línea ["PNG a PDF"](https://products.aspose.app/pdf/conversion/png-to-pdf/), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. -[![Conversión de PNG a PDF con Aspose.PDF usando aplicación gratuita](png_to_pdf.png)](https://products.aspose.app/pdf/conversion/png-to-pdf/) +[![Aspose.PDF Conversión PNG a PDF usando la aplicación](png_to_pdf.png)](https://products.aspose.app/pdf/conversion/png-to-pdf/) {{% /alert %}} ## Convertir SVG a PDF @@ -302,124 +264,96 @@ Aspose le presenta una aplicación gratuita en línea ["PNG a PDF"](https://prod Scalable Vector Graphics (SVG) es una familia de especificaciones de un formato de archivo basado en XML para gráficos vectoriales bidimensionales, tanto estáticos como dinámicos (interactivos o animados). La especificación SVG es un estándar abierto que ha sido desarrollado por el World Wide Web Consortium (W3C) desde 1999. -SVG las imágenes y sus comportamientos se definen en archivos de texto XML. Esto significa que pueden ser buscadas, indexadas, automatizadas y, si es necesario, comprimidas. Como archivos XML, las imágenes SVG pueden ser creadas y editadas con cualquier editor de texto, pero a menudo es más conveniente crearlas con programas de dibujo como Inkscape. +SVG las imágenes y sus comportamientos se definen en archivos de texto XML. Esto significa que pueden ser buscadas, indexadas, automatizadas mediante scripts y, si es necesario, comprimidas. Como archivos XML, las imágenes SVG pueden ser creadas y editadas con cualquier editor de texto, pero a menudo es más conveniente crearlas con programas de dibujo como Inkscape. {{% alert color="success" %}} **Intenta convertir el formato SVG a PDF en línea** -Aspose.PDF for Python via .NET te presenta una aplicación gratuita en línea ["SVG a PDF"](https://products.aspose.app/pdf/conversion/svg-to-pdf), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for Python via .NET le presenta una aplicación en línea ["SVG a PDF"](https://products.aspose.app/pdf/conversion/svg-to-pdf), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. -[![Conversión de SVG a PDF con la aplicación gratuita de Aspose.PDF](svg_to_pdf.png)](https://products.aspose.app/pdf/conversion/svg-to-pdf) +[![Aspose.PDF Conversión de SVG a PDF con App](svg_to_pdf.png)](https://products.aspose.app/pdf/conversion/svg-to-pdf) {{% /alert %}} El siguiente fragmento de código muestra el proceso de convertir un archivo SVG a formato PDF con Aspose.PDF for Python. ```python +import aspose.pdf as ap +from os import path +import sys - from io import FileIO - from os import path - import os - import shutil - import aspose.pdf as apdf - import inspect - import pydicom - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - load_options = apdf.SvgLoadOptions() - document = apdf.Document(path_infile, load_options) - document.save(path_outfile) +def convert_SVG_to_PDF(infile, outfile): + load_options = ap.SvgLoadOptions() + document = ap.Document(infile, load_options) + document.save(outfile) print(infile + " converted into " + outfile) ``` ## Convertir TIFF a PDF -**Aspose.PDF** formato de archivo compatible, ya sea una imagen TIFF de un solo cuadro o de varios cuadros. Significa que puedes convertir la imagen TIFF a PDF. +**Aspose.PDF** formato de archivo compatible, ya sea una imagen TIFF de un solo cuadro o de varios cuadros. Esto significa que puedes convertir la imagen TIFF a PDF. -TIFF o TIF, Tagged Image File Format, representa imágenes raster que están destinadas a usarse en una variedad de dispositivos que cumplen con este estándar de formato de archivo. La imagen TIFF puede contener varios fotogramas con diferentes imágenes. El formato de archivo Aspose.PDF también es compatible, ya sea una imagen TIFF de un solo fotograma o de varios fotogramas. +TIFF o TIF, Tagged Image File Format, representa imágenes raster que están destinadas al uso en una variedad de dispositivos que cumplen con este estándar de formato de archivo. Una imagen TIFF puede contener varios fotogramas con diferentes imágenes. El formato de archivo Aspose.PDF también es compatible, ya sea una imagen TIFF de un solo fotograma o de varios fotogramas. -Puedes convertir TIFF a PDF de la misma manera que el resto de los formatos de archivo raster gráficos: +Puedes convertir TIFF a PDF de la misma manera que el resto de formatos de archivo raster gráficos: ```python +import aspose.pdf as ap +from os import path +import sys - from io import FileIO - from os import path - import os - import shutil - import aspose.pdf as apdf - import inspect - import pydicom - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = apdf.Document() +def convert_TIFF_to_PDF(infile, outfile): + document = ap.Document() page = document.pages.add() - rectangle = apdf.Rectangle(0, 0, 595, 842, True) # A4 size in points - page.add_image(path_infile, rectangle) - document.save(path_outfile) + rectangle = ap.Rectangle(0, 0, 595, 842, True) # A4 size in points + page.add_image(infile, rectangle) + document.save(outfile) print(infile + " converted into " + outfile) ``` ## Convertir CDR a PDF -El siguiente fragmento de código muestra cómo cargar un archivo CorelDRAW (CDR) y guardarlo como PDF usando 'CdrLoadOptions' en Aspose.PDF for Python via .NET. +El siguiente fragmento de código muestra cómo cargar un archivo CorelDRAW (CDR) y guardarlo como PDF utilizando ‘CdrLoadOptions’ en Aspose.PDF for Python via .NET. -1. Cree 'CdrLoadOptions()' para configurar cómo se debe cargar el archivo CDR. -1. Inicializa un objeto Document con el archivo CDR y las opciones de carga. -1. Guarde el documento como PDF. +1. Cree 'CdrLoadOptions()' para configurar cómo debe cargarse el archivo CDR. +1. Inicialice un objeto Document con el archivo CDR y las opciones de carga. +1. Guarda el documento como un PDF. ```python +import aspose.pdf as ap +from os import path +import sys - from io import FileIO - from os import path - import os - import shutil - import aspose.pdf as apdf - import inspect - import pydicom - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - load_options = apdf.CdrLoadOptions() - document = apdf.Document(path_infile, load_options) - document.save(path_outfile) +def convert_CDR_to_PDF(infile, outfile): + load_options = ap.CdrLoadOptions() + document = ap.Document(infile, load_options) + document.save(outfile) print(infile + " converted into " + outfile) ``` ## Convertir JPEG a PDF -Este ejemplo muestra cómo convertir un archivo JPEG a PDF usando Aspose.PDF for Python via .NET. +Este ejemplo muestra cómo convertir un JPEG a un archivo PDF usando Aspose.PDF for Python via .NET. -1. Cree un nuevo documento PDF. +1. Crear un nuevo documento PDF. 1. Agregar una nueva página. -1. Define el rectángulo de ubicación (tamaño A4: 595x842 puntos). +1. Defina el rectángulo de ubicación (tamaño A4: 595x842 puntos). 1. Inserte la imagen en la página. 1. Guarda el PDF. ```python +import aspose.pdf as ap +from os import path +import sys - from io import FileIO - from os import path - import os - import shutil - import aspose.pdf as apdf - import inspect - import pydicom - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = apdf.Document() +def convert_JPEG_to_PDF(infile, outfile): + document = ap.Document() page = document.pages.add() - rectangle = apdf.Rectangle(0, 0, 595, 842, True) # A4 size in points - page.add_image(path_infile, rectangle) + rectangle = ap.Rectangle(0, 0, 595, 842, True) # A4 size in points + page.add_image(infile, rectangle) - document.save(path_outfile) + document.save(outfile) print(infile + " converted into " + outfile) ``` diff --git a/es/python-net/converting/convert-other-files-to-pdf/_index.md b/es/python-net/converting/convert-other-files-to-pdf/_index.md index 4bd1008b4..cb903c747 100644 --- a/es/python-net/converting/convert-other-files-to-pdf/_index.md +++ b/es/python-net/converting/convert-other-files-to-pdf/_index.md @@ -4,18 +4,17 @@ linktitle: Convertir otros formatos de archivo a PDF type: docs weight: 80 url: /es/python-net/convert-other-files-to-pdf/ -lastmod: "2025-09-01" -description: Este tema le muestra cómo Aspose.PDF permite convertir otros formatos de archivo, como EPUB, MD, PCL, XPS, PS, XML y LaTeX, a un documento PDF. +lastmod: "2026-05-11" +description: Aprende cómo convertir archivos EPUB, Markdown, PCL, XPS, PostScript, XML y LaTeX a PDF en Python con Aspose.PDF for Python via .NET. sitemap: changefreq: "monthly" priority: 0.5 -TechArticle: true -AlternativeHeadline: Convertir otros archivos a PDF con Python -Abstract: > - Esta guía muestra cómo convertir EPUB, Markdown, PCL, texto, XPS, PostScript, XML, XSL-FO y LaTeX/TeX a PDF con Aspose.PDF for Python via .NET. Cada sección incluye las opciones de carga necesarias y ejemplos de código para implementar la conversión. +TechArticle: true +AlternativeHeadline: Cómo convertir otros formatos de archivo a PDF en Python +Abstract: Este artículo proporciona una guía completa sobre la conversión de varios formatos de archivo a PDF usando Python, aprovechando las capacidades de Aspose.PDF for Python via .NET. El documento describe los procesos de conversión para varios formatos, incluyendo EPUB, Markdown, PCL, Text, XPS, PostScript, XML, XSL-FO y LaTeX/TeX. Cada sección ofrece fragmentos de código específicos e instrucciones para implementar estas conversiones. El artículo destaca la utilidad de las características de Aspose.PDF, como las opciones de carga adaptadas a cada tipo de archivo, para garantizar una conversión precisa y eficiente. Además, resalta la disponibilidad de aplicaciones de conversión en línea para que los usuarios exploren la funcionalidad de primera mano. La guía sirve como un recurso práctico para desarrolladores que buscan integrar capacidades de conversión a PDF en sus aplicaciones Python. --- -Este artículo explica cómo **convertir varios tipos de formatos de archivo a PDF usando Python**. Cubre los siguientes temas. +Este artículo explica cómo **convertir varios otros tipos de formatos de archivo a PDF usando Python**. Cubre los siguientes temas. ## Convertir OFD a PDF @@ -28,122 +27,65 @@ Pasos para convertir OFD a PDF en Python: 1. Guardar como PDF. ```python -from os import path +from os import path, remove import aspose.pdf as ap +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) +def convert_OFD_to_PDF(infile, outfile): + load_options = ap.OfdLoadOptions() + document = ap.Document(infile, load_options) + document.save(outfile) -load_options = ap.OfdLoadOptions() -document = ap.Document(path_infile, load_options) -document.save(path_outfile) - -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` ## Convertir LaTeX/TeX a PDF -El formato de archivo LaTeX es un formato de archivo de texto con marcado en el derivado LaTeX de la familia de lenguajes TeX y LaTeX es un formato derivado del sistema TeX. LaTeX (\u02C8le\u026At\u025Bk/lay-tek o lah-tek) es un sistema de preparación de documentos y lenguaje de marcado de documentos. Se utiliza ampliamente para la comunicación y publicación de documentos científicos en muchos campos, incluyendo matemáticas, física y ciencias de la computación. También desempeña un papel clave en la preparación y publicación de libros y artículos que contienen material multilingüe complejo, como coreano, japonés, caracteres chinos y árabe, incluidas ediciones especiales. +El formato de archivo LaTeX es un formato de archivo de texto con marcado en la derivada LaTeX de la familia de lenguajes TeX y LaTeX es un formato derivado del sistema TeX. LaTeX (\u02C8le\u026At\u025Bk/lay-tek o lah-tek) es un sistema de preparación de documentos y lenguaje de marcado de documentos. Se utiliza ampliamente para la comunicación y publicación de documentos científicos en muchos campos, incluidos matemáticas, física y ciencia de la computación. También desempeña un papel clave en la preparación y publicación de libros y artículos que contienen material multilingüe complejo, como coreano, japonés, caracteres chinos y árabe, incluidas ediciones especiales. LaTeX utiliza el programa de composición tipográfica TeX para formatear su salida, y está escrito en el lenguaje macro de TeX. {{% alert color="success" %}} **Intenta convertir LaTeX/TeX a PDF en línea** -Aspose.PDF for Python via .NET le presenta una aplicación gratuita en línea ["LaTex a PDF"](https://products.aspose.app/pdf/conversion/tex-to-pdf), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. - -[![Aspose.PDF Conversión de LaTeX/TeX a PDF con aplicación gratuita](latex.png)](https://products.aspose.app/pdf/conversion/tex-to-pdf) -{{% /alert %}} - -Pasos Convertir TEX a PDF en Python: - -1. Configure las opciones de carga de LaTeX usando LatexLoadOptions(). -1. Cargar el documento LaTeX. -1. Guardar como PDF. - -```python -from os import path -import aspose.pdf as ap - -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) - -load_options = ap.LatexLoadOptions() -document = ap.Document(path_infile, load_options) -document.save(path_outfile) - -print(infile + " converted into " + outfile) -``` -## Convertir OFD a PDF - -OFD significa Open Fixed-layout Document (a veces llamado formato Open Fixed Document). Es una norma nacional china (GB/T 33190-2016) para documentos electrónicos, introducida como una alternativa al PDF. - -Pasos para convertir OFD a PDF en Python: - -1. Configura las opciones de carga OFD usando OfdLoadOptions(). -1. Cargar el documento OFD. -1. Guardar como PDF. - -```python -from os import path -import aspose.pdf as ap - -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) - -load_options = ap.OfdLoadOptions() -document = ap.Document(path_infile, load_options) -document.save(path_outfile) - -print(infile + " converted into " + outfile) -``` - -## Convertir LaTeX/TeX a PDF - -El formato de archivo LaTeX es un formato de archivo de texto con marcas en el derivado LaTeX de la familia de lenguajes TeX y LaTeX es un formato derivado del sistema TeX. LaTeX (\u02C8le\u026At\u025Bk/lay-tek o lah-tek) es un sistema de preparación de documentos y un lenguaje de marcado de documentos. Es ampliamente utilizado para la comunicación y publicación de documentos científicos en muchos campos, incluidos matemáticas, física y ciencias de la computación. También tiene un papel destacado en la preparación y publicación de libros y artículos que contienen materiales multilingües complejos, como sánscrito y árabe, incluidas ediciones críticas. LaTeX utiliza el programa de composición tipográfica TeX para formatear su salida, y está escrito en el lenguaje de macros TeX. - -{{% alert color="success" %}} -**Intenta convertir LaTeX/TeX a PDF en línea** - -Aspose.PDF for Python via .NET le presenta una aplicación gratuita en línea ["LaTex a PDF"](https://products.aspose.app/pdf/conversion/tex-to-pdf), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for Python via .NET te presenta una aplicación en línea ["LaTex a PDF"](https://products.aspose.app/pdf/conversion/tex-to-pdf), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Aspose.PDF Conversión de LaTeX/TeX a PDF con aplicación gratuita](latex.png)](https://products.aspose.app/pdf/conversion/tex-to-pdf) +[![Aspose.PDF Conversión de LaTeX/TeX a PDF con App](latex.png)](https://products.aspose.app/pdf/conversion/tex-to-pdf) {{% /alert %}} -Pasos Convertir TEX a PDF en Python: +Pasos para convertir TEX a PDF en Python: 1. Configure las opciones de carga de LaTeX usando LatexLoadOptions(). 1. Cargar el documento LaTeX. 1. Guardar como PDF. ```python -from os import path +from os import path, remove import aspose.pdf as ap +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) +def convert_TEX_to_PDF(infile, outfile): + load_options = ap.LatexLoadOptions() + document = ap.Document(infile, load_options) + document.save(outfile) -load_options = ap.LatexLoadOptions() -document = ap.Document(path_infile, load_options) -document.save(path_outfile) - -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` ## Convertir EPUB a PDF -**Aspose.PDF for Python via .NET** permite convertir fácilmente archivos EPUB al formato PDF. +**Aspose.PDF for Python via .NET** le permite simplemente convertir archivos EPUB al formato PDF. -EPUB (abreviatura de electronic publication) es un estándar gratuito y abierto de libros electrónicos del International Digital Publishing Forum (IDPF). Los archivos tienen la extensión .epub. EPUB está diseñado para contenido refluible, lo que significa que un lector de EPUB puede optimizar el texto para un dispositivo de visualización determinado. +EPUB (abreviatura de publicación electrónica) es un estándar de libros electrónicos gratuito y abierto del International Digital Publishing Forum (IDPF). Los archivos tienen la extensión .epub. EPUB está diseñado para contenido refluible, lo que significa que un lector EPUB puede optimizar el texto para un dispositivo de visualización particular. -EPUB también admite contenido de diseño fijo. El formato está destinado como un formato único que los editores y las casas de conversión pueden usar internamente, así como para distribución y venta. Sustituye el estándar Open eBook.La versión EPUB 3 también cuenta con el respaldo del Book Industry Study Group (BISG), una asociación líder en el comercio de libros para mejores prácticas estandarizadas, investigación, información y eventos, para el empaquetado de contenido. +EPUB también admite contenido de diseño fijo. El formato está pensado como un formato único que los editores y casas de conversión pueden usar internamente, así como para distribución y venta. Reemplaza el estándar Open eBook. La versión EPUB 3 también cuenta con el respaldo del Book Industry Study Group (BISG), una asociación líder en el comercio de libros para prácticas recomendadas estandarizadas, investigación, información y eventos, para el empaquetado de contenido. {{% alert color="success" %}} **Intenta convertir EPUB a PDF en línea** -Aspose.PDF for Python via .NET le presenta una aplicación gratuita en línea ["EPUB a PDF"](https://products.aspose.app/pdf/conversion/epub-to-pdf), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for Python via .NET te presenta una aplicación en línea [“EPUB a PDF”](https://products.aspose.app/pdf/conversion/epub-to-pdf), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Aspose.PDF Conversión EPUB a PDF con aplicación gratuita](epub.png)](https://products.aspose.app/pdf/conversion/epub-to-pdf) +[![Aspose.PDF Conversión EPUB a PDF con App](epub.png)](https://products.aspose.app/pdf/conversion/epub-to-pdf) {{% /alert %}} Pasos para convertir EPUB a PDF en Python: @@ -152,20 +94,19 @@ Pasos para convertir EPUB a PDF en Python: 1. Convertir EPUB a PDF. 1. Confirmación de impresión. -El siguiente fragmento de código le muestra cómo convertir archivos EPUB a formato PDF con Python. +El siguiente fragmento de código le muestra cómo convertir archivos EPUB al formato PDF con Python. ```python -from os import path +from os import path, remove import aspose.pdf as ap +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) +def convert_EPUB_to_PDF(infile, outfile): + load_options = ap.EpubLoadOptions() + document = ap.Document(infile, load_options) -load_options = ap.EpubLoadOptions() -document = ap.Document(path_infile, load_options) - -document.save(path_outfile) -print(infile + " converted into " + outfile) + document.save(outfile) + print(infile + " converted into " + outfile) ``` ## Convertir Markdown a PDF @@ -175,9 +116,9 @@ print(infile + " converted into " + outfile) {{% alert color="success" %}} **Intenta convertir Markdown a PDF en línea** -Aspose.PDF for Python via .NET le presenta una aplicación gratuita en línea ["Markdown a PDF"](https://products.aspose.app/pdf/conversion/md-to-pdf), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for Python via .NET te presenta una aplicación en línea ["Markdown a PDF"](https://products.aspose.app/pdf/conversion/md-to-pdf), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Conversión de Markdown a PDF con Aspose.PDF y aplicación gratuita](markdown.png)](https://products.aspose.app/pdf/conversion/md-to-pdf) +[![Aspose.PDF Conversión de Markdown a PDF con App](markdown.png)](https://products.aspose.app/pdf/conversion/md-to-pdf) {{% /alert %}} Este fragmento de código de Aspose.PDF for Python via .NET ayuda a convertir archivos Markdown en PDFs, permitiendo una mejor compartición de documentos, preservación del formato y compatibilidad de impresión.o @@ -185,243 +126,214 @@ Este fragmento de código de Aspose.PDF for Python via .NET ayuda a convertir ar El siguiente fragmento de código muestra cómo usar esta funcionalidad con la biblioteca Aspose.PDF: ```python -from os import path +from os import path, remove import aspose.pdf as ap +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) - -load_options = ap.MdLoadOptions() -document = ap.Document(path_infile, load_options) -document.save(path_outfile) -print(infile + " converted into " + outfile) +def convert_MD_to_PDF(infile, outfile): + load_options = ap.MdLoadOptions() + document = ap.Document(infile, load_options) + document.save(outfile) + print(infile + " converted into " + outfile) ``` ## Convertir PCL a PDF -PCL (Printer Command Language) es un lenguaje de impresora de Hewlett-Packard desarrollado para acceder a funciones estándar de la impresora. Los niveles PCL 1 a 5e/5c son lenguajes basados en comandos que utilizan secuencias de control que se procesan e interpretan en el orden en que se reciben. A nivel de consumidor, las corrientes de datos PCL son generadas por un controlador de impresión. La salida PCL también puede ser generada fácilmente por aplicaciones personalizadas. +PCL (Printer Command Language) es un lenguaje de impresora de Hewlett-Packard desarrollado para acceder a funciones estándar de la impresora. Los niveles 1 a 5e/5c de PCL son lenguajes basados en comandos que utilizan secuencias de control que se procesan e interpretan en el orden en que se reciben. A nivel de consumidor, los flujos de datos PCL son generados por un controlador de impresión. La salida PCL también puede generarse fácilmente mediante aplicaciones personalizadas. {{% alert color="success" %}} **Intenta convertir PCL a PDF en línea** -Aspose.PDF para .NET le presenta una aplicación gratuita en línea ["PCL a PDF"](https://products.aspose.app/pdf/conversion/pcl-to-pdf), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for for .NET le presenta su aplicación en línea ["PCL a PDF"](https://products.aspose.app/pdf/conversion/pcl-to-pdf), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Aspose.PDF Conversión de PCL a PDF con aplicación gratuita](pcl_to_pdf.png)](https://products.aspose.app/pdf/conversion/pcl-to-pdf) +[![Aspose.PDF Conversión de PCL a PDF con App](pcl_to_pdf.png)](https://products.aspose.app/pdf/conversion/pcl-to-pdf) {{% /alert %}} -Para permitir la conversión de PCL a PDF, Aspose.PDF tiene la clase [`PclLoadOptions`](https://reference.aspose.com/pdf/net/aspose.pdf/pclloadoptions) que se usa para inicializar el objeto LoadOptions. Más adelante, este objeto se pasa como argumento durante la inicialización del objeto Document y ayuda al motor de renderizado PDF a determinar el formato de entrada del documento fuente. +Para permitir la conversión de PCL a PDF, Aspose.PDF tiene la clase [`PclLoadOptions`](https://reference.aspose.com/pdf/net/aspose.pdf/pclloadoptions) que se utiliza para inicializar el objeto LoadOptions. Más adelante, este objeto se pasa como argumento durante la inicialización del objeto Document y ayuda al motor de renderizado de PDF a determinar el formato de entrada del documento fuente. -El siguiente fragmento de código muestra el proceso de convertir un archivo PCL al formato PDF. +El siguiente fragmento de código muestra el proceso de convertir un archivo PCL a formato PDF. -Pasos para Convertir PCL a PDF en Python: +Pasos para convertir PCL a PDF en Python: 1. Opciones de carga para PCL usando PclLoadOptions(). 1. Cargar el documento. 1. Guardar como PDF. ```python -from os import path +from os import path, remove import aspose.pdf as ap +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) +def convert_PCL_to_PDF(infile, outfile): + load_options = ap.PclLoadOptions() + load_options.supress_errors = True -load_options = ap.PclLoadOptions() -load_options.supress_errors = True + document = ap.Document(infile, load_options) + document.save(outfile) -document = ap.Document(path_infile, load_options) -document.save(path_outfile) - -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` ## Convertir texto preformateado a PDF -**Aspose.PDF for Python via .NET** soporta la función de convertir archivos de texto plano y texto preformateado a formato PDF. +**Aspose.PDF for Python via .NET** soporta la función de convertir texto plano y archivos de texto preformateado al formato PDF. -Convertir texto a PDF significa añadir fragmentos de texto a la página PDF. En cuanto a los archivos de texto, estamos tratando con 2 tipos de texto: preformateado (por ejemplo, 25 líneas con 80 caracteres por línea) y texto sin formato (texto plano). Según nuestras necesidades, podemos controlar esta adición nosotros mismos o confiarla a los algoritmos de la biblioteca. +Convertir texto a PDF significa añadir fragmentos de texto a la página del PDF. En cuanto a los archivos de texto, tratamos con 2 tipos de texto: preformateado (por ejemplo, 25 líneas con 80 caracteres por línea) y texto no formateado (texto plano). Dependiendo de nuestras necesidades, podemos controlar esta adición nosotros mismos o confiarla a los algoritmos de la biblioteca. {{% alert color="success" %}} **Intenta convertir TEXT a PDF en línea** -Aspose.PDF for Python via .NET le presenta una aplicación gratuita en línea ["Texto a PDF"](https://products.aspose.app/pdf/conversion/txt-to-pdf), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for Python via .NET te presenta una aplicación en línea ["Texto a PDF"](https://products.aspose.app/pdf/conversion/txt-to-pdf), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Aspose.PDF Conversión de TEXTO a PDF con aplicación gratuita](text_to_pdf.png)](https://products.aspose.app/pdf/conversion/txt-to-pdf) +[![Aspose.PDF Conversión TEXT a PDF con App](text_to_pdf.png)](https://products.aspose.app/pdf/conversion/txt-to-pdf) {{% /alert %}} -Pasos Convertir TEXT a PDF en Python: +Pasos Convertir TEXTO a PDF en Python: 1. Lea el archivo de texto de entrada línea por línea. -1. Configure una fuente monoespaciada (Courier New) para una alineación de texto consistente. -1. Crea un nuevo documento PDF y agrega la primera página con márgenes personalizados y configuraciones de fuente. -1. Iterar a través de las líneas del archivo de texto Para simular Typewriter, usamos la fuente \u0027monospace_font\u0027 y tamaño 12. -1. Limite la creación de páginas a 4 páginas. -1. Guarde el PDF final en la ruta especificada. +1. Configure una fuente monoespaciada (Courier New) para una alineación de texto coherente. +1. Cree un nuevo PDF Document y añada la primera página con márgenes personalizados y configuraciones de Font. +1. Iterar a través de líneas del archivo de texto Para simular la máquina de escribir, usamos la fuente 'monospace_font' y tamaño 12. +1. Limitar la creación de páginas a 4 páginas. +1. Guarda el PDF final en la ruta especificada. ```python -from os import path +from os import path, remove import aspose.pdf as ap +import sys + +def convert_TXT_to_PDF(infile, outfile): + with open(infile, "r") as file: + lines = file.readlines() + + monospace_font = ap.text.FontRepository.find_font("Courier New") + + document = ap.Document() + page = document.pages.add() + + page.page_info.margin.left = 20 + page.page_info.margin.right = 10 + page.page_info.default_text_state.font = monospace_font + page.page_info.default_text_state.font_size = 12 + count = 1 + for line in lines: + if line != "" and line[0] == "\x0c": + page = document.pages.add() + page.page_info.margin.left = 20 + page.page_info.margin.right = 10 + page.page_info.default_text_state.font = monospace_font + page.page_info.default_text_state.font_size = 12 + count = count + 1 + else: + text = ap.text.TextFragment(line) + page.paragraphs.add(text) + + if count == 4: + break + + document.save(outfile) -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) - -with open(path_infile, "r") as file: - lines = file.readlines() - -monospace_font = ap.text.FontRepository.find_font("Courier New") - -document = ap.Document() -page = document.pages.add() - -page.page_info.margin.left = 20 -page.page_info.margin.right = 10 -page.page_info.default_text_state.font = monospace_font -page.page_info.default_text_state.font_size = 12 -count = 1 -for line in lines: - if line != "" and line[0] == "\x0c": - page = document.pages.add() - page.page_info.margin.left = 20 - page.page_info.margin.right = 10 - page.page_info.default_text_state.font = monospace_font - page.page_info.default_text_state.font_size = 12 - count = count + 1 - else: - text = ap.text.TextFragment(line) - page.paragraphs.add(text) - - if count == 4: - break - -document.save(path_outfile) - -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` ## Convertir PostScript a PDF -Este ejemplo demuestra cómo convertir un archivo PostScript en un documento PDF usando Aspose.PDF for Python via .NET. +Este ejemplo muestra cómo convertir un archivo PostScript en un documento PDF usando Aspose.PDF for Python via .NET. -1. Cree una instancia de 'PsLoadOptions' para interpretar correctamente el archivo PS. +1. Crea una instancia de 'PsLoadOptions' para interpretar correctamente el archivo PS. 1. Cargue el archivo 'PostScript' en un objeto Document usando las opciones de carga. 1. Guarde el documento en formato PDF en la ruta de salida deseada. ```python -from os import path +from os import path, remove import aspose.pdf as ap +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) - -load_options = ap.PsLoadOptions() +def convert_PS_to_PDF(infile, outfile): + load_options = ap.PsLoadOptions() -document = ap.Document(path_infile, load_options) -document.save(path_outfile) + document = ap.Document(infile, load_options) + document.save(outfile) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` ## Convertir XPS a PDF -**Aspose.PDF for Python via .NET** admite la función de conversión XPS archivos a formato PDF. Consulta este artículo para resolver tus tareas. +**Aspose.PDF for Python via .NET** admite la función de conversión XPS archivos al formato PDF. Consulta este artículo para resolver tus tareas. -El tipo de archivo XPS está asociado principalmente con la XML Paper Specification de Microsoft Corporation. La XML Paper Specification (XPS), anteriormente con el nombre en código Metro y que incorpora el concepto de marketing Next Generation Print Path (NGPP), es la iniciativa de Microsoft para integrar la creación y visualización de documentos en su sistema operativo Windows. +El tipo de archivo XPS está principalmente asociado con la XML Paper Specification de Microsoft Corporation. La XML Paper Specification (XPS), anteriormente denominada con el nombre en código Metro y que engloba el concepto de marketing Next Generation Print Path (NGPP), es la iniciativa de Microsoft para integrar la creación y visualización de documentos en su sistema operativo Windows. El siguiente fragmento de código muestra el proceso de convertir un archivo XPS al formato PDF con Python. ```python -from os import path +from os import path, remove import aspose.pdf as ap +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) +def convert_XPS_to_PDF(infile, outfile): + load_options = ap.XpsLoadOptions() + document = ap.Document(infile, load_options) + document.save(outfile) -load_options = ap.XpsLoadOptions() -document = ap.Document(path_infile, load_options) -document.save(path_outfile) - -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` {{% alert color="success" %}} **Intenta convertir el formato XPS a PDF en línea** -Aspose.PDF for Python via .NET le presenta una aplicación en línea gratuita ["XPS a PDF"](https://products.aspose.app/pdf/conversion/xps-to-pdf/), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for Python via .NET te presenta una aplicación en línea ["XPS a PDF"](https://products.aspose.app/pdf/conversion/xps-to-pdf/), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Conversión de XPS a PDF con Aspose.PDF y aplicación gratuita](xps_to_pdf.png)](https://products.aspose.app/pdf/conversion/xps-to-pdf/) +[![Aspose.PDF Conversión de XPS a PDF con la aplicación](xps_to_pdf.png)](https://products.aspose.app/pdf/conversion/xps-to-pdf/) {{% /alert %}} ## Convertir XSL-FO a PDF -El siguiente fragmento de código se puede usar para convertir un XSLFO al formato PDF con Aspose.PDF for Python via .NET: +El siguiente fragmento de código puede usarse para convertir un XSLFO al formato PDF con Aspose.PDF for Python via .NET: ```python -from os import path +from os import path, remove import aspose.pdf as ap +import sys -path_xsltfile = path.join(self.data_dir, xsltfile) -path_xmlfile = path.join(self.data_dir, xmlfile) -path_outfile = path.join(self.data_dir, "python", outfile) +def convert_XSLFO_to_PDF(xsltfile, xmlfile, outfile): + load_options = ap.XslFoLoadOptions(xsltfile) + load_options.parsing_errors_handling_type = ( + ap.XslFoLoadOptions.ParsingErrorsHandlingTypes.THROW_EXCEPTION_IMMEDIATELY + ) + document = ap.Document(xmlfile, load_options) + document.save(outfile) -load_options = ap.XslFoLoadOptions(path_xsltfile) -load_options.parsing_errors_handling_type = ( - ap.XslFoLoadOptions.ParsingErrorsHandlingTypes.ThrowExceptionImmediately -) -document = ap.Document(path_xmlfile, load_options) -document.save(path_outfile) - -print(xmlfile + " converted into " + outfile) + print(xmlfile + " converted into " + outfile) ``` ## Convertir XML con XSLT a PDF -Este ejemplo muestra cómo convertir un archivo XML en un PDF transformándolo primero en HTML mediante una plantilla XSLT y luego cargando el HTML en Aspose.PDF. +Este ejemplo muestra cómo convertir un archivo XML en un PDF al transformarlo primero en HTML usando una plantilla XSLT y luego cargar el HTML en Aspose.PDF. -1. Crea una instancia de 'HtmlLoadOptions' para configurar la conversión de HTML a PDF. +1. Cree una instancia de 'HtmlLoadOptions' para configurar la conversión de HTML a PDF. 1. Cargue el archivo HTML transformado en un objeto Document de Aspose.PDF. -1. Guarde el documento como PDF en la ruta de salida especificada. -1. Eliminar el archivo HTML temporal después de una conversión exitosa. +1. Guarde el documento como un PDF en la ruta de salida especificada. +1. Elimine el archivo HTML temporal tras una conversión exitosa. ```python -from os import path +from os import path, remove import aspose.pdf as ap +import sys +def convert_XSLFO_to_PDF(xsltfile, xmlfile, outfile): + load_options = ap.XslFoLoadOptions(xsltfile) + load_options.parsing_errors_handling_type = ( + ap.XslFoLoadOptions.ParsingErrorsHandlingTypes.THROW_EXCEPTION_IMMEDIATELY + ) + document = ap.Document(xmlfile, load_options) + document.save(outfile) -def transform_xml_to_html(xml_file, xslt_file, html_file): - from lxml import etree - - """ - Transform XML to HTML using XSLT and return as a stream - """ - # Parse XML document - xml_doc = etree.parse(xml_file) - - # Parse XSLT stylesheet - xslt_doc = etree.parse(xslt_file) - transform = etree.XSLT(xslt_doc) - - # Apply transformation - result = transform(xml_doc) - - # Save result to HTML file - with open(html_file, "w", encoding="utf-8") as f: - f.write(str(result)) - - -def convert_XML_to_PDF(template, infile, outfile): - path_infile = path.join(data_dir, infile) - path_outfile = path.join(data_dir, "python", outfile) - path_template = path.join(data_dir, template) - path_temp_file = path.join(data_dir, "temp.html") - - load_options = ap.HtmlLoadOptions() - transform_xml_to_html(path_infile, path_template, path_temp_file) - - document = ap.Document(path_temp_file, load_options) - document.save(path_outfile) + print(xmlfile + " converted into " + outfile) +``` - if path.exists(path_temp_file): - os.remove(path_temp_file) +## Conversiones relacionadas - print(infile + " converted into " + outfile) -``` +- [Convertir HTML a PDF](/pdf/es/python-net/convert-html-to-pdf/) para escenarios de conversión de HTML y MHTML. +- [Convertir formatos de imagen a PDF](/pdf/es/python-net/convert-images-format-to-pdf/) cuando tus entradas son PNG, JPEG, TIFF, SVG u otras imágenes. +- [Convertir PDF a otros formatos](/pdf/es/python-net/convert-pdf-to-other-files/) si también necesitas conversiones inversas como PDF a EPUB, Markdown o texto. diff --git a/es/python-net/converting/convert-pdf-to-excel/_index.md b/es/python-net/converting/convert-pdf-to-excel/_index.md index 64b9cd093..e74641c4c 100644 --- a/es/python-net/converting/convert-pdf-to-excel/_index.md +++ b/es/python-net/converting/convert-pdf-to-excel/_index.md @@ -4,34 +4,35 @@ linktitle: Convertir PDF a Excel type: docs weight: 20 url: /es/python-net/convert-pdf-to-excel/ -lastmod: "2025-09-27" -description: Convierta PDFs a hojas de cálculo de Excel sin esfuerzo con Aspose.PDF for Python via .NET. Siga esta guía para conversiones precisas de PDF a XLSX. +lastmod: "2026-05-11" +description: Aprenda cómo convertir archivos PDF a Excel en Python con Aspose.PDF for Python via .NET, incluyendo XLS, XLSX, CSV, ODS y salida de una sola hoja de cálculo. sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true -AlternativeHeadline: Convertir PDF a Excel y hojas de cálculo -Abstract: > - Esta página explica cómo convertir PDF a XLS, XLSX, CSV y ODS con Aspose.PDF for Python via .NET. También muestra opciones para controlar columnas vacías, combinar datos en menos hojas y ajustar la salida de Excel según el contenido del PDF. +TechArticle: true +AlternativeHeadline: Cómo convertir PDF a Excel en Python +Abstract: Este artículo ofrece una guía completa sobre la conversión de archivos PDF a varios formatos de Excel usando Python, específicamente con la biblioteca Aspose.PDF for Python via .NET. Detalla los procesos de conversión a los formatos XLS, XLSX, CSV y ODS. El documento explica los pasos necesarios para convertir PDF a XLS y XLSX, resaltando la creación de instancias de Document y ExcelSaveOptions, y el uso del método Document.Save() para especificar los formatos de salida. El artículo también discute características como controlar la inserción de columnas en blanco y minimizar la cantidad de hojas de cálculo durante la conversión. Además, proporciona ejemplos de conversión de PDFs a hojas de cálculo Excel individuales y a otros formatos como CSV y ODS, enfatizando la flexibilidad y funcionalidad de Aspose.PDF. También se menciona una herramienta en línea para la conversión de PDF a XLSX, que permite a los usuarios explorar la calidad de la conversión. El artículo concluye con una lista de temas relacionados y fragmentos de código para ayudar a comprender e implementar estas conversiones de forma programática. --- -## Conversión de PDF a EXCEL mediante Python +## Convertir PDF a Excel (XML de hoja de cálculo 2003) -**Aspose.PDF for Python via .NET** admite la función de convertir archivos PDF a formatos Excel y CSV. +**Aspose.PDF for Python via .NET** soporta la función de convertir archivos PDF a formatos Excel y CSV. -Aspose.PDF for Python via .NET es un componente de manipulación de PDF, hemos introducido una función que convierte archivos PDF a libros de Excel (archivos XLSX). Durante esta conversión, las páginas individuales del archivo PDF se convierten en hojas de Excel. +Aspose.PDF for Python via .NET es un componente de manipulación de PDF, hemos introducido una función que renderiza archivos PDF a libros de Excel (archivos XLSX). Durante esta conversión, las páginas individuales del archivo PDF se convierten en hojas de cálculo de Excel. + +Utilice esta página cuando necesite extraer contenido PDF orientado a tablas o al estilo de informes a formatos de hoja de cálculo para ordenar, filtrar o realizar análisis posteriores. {{% alert color="success" %}} **Intenta convertir PDF a Excel en línea** -Aspose.PDF te presenta una aplicación en línea gratuita ["PDF a XLSX"](https://products.aspose.app/pdf/conversion/pdf-to-xlsx), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF le presenta la aplicación en línea ["PDF a XLSX"](https://products.aspose.app/pdf/conversion/pdf-to-xlsx), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Aspose.PDF Conversión de PDF a Excel con aplicación gratuita](pdf_to_xlsx.png)](https://products.aspose.app/pdf/conversion/pdf-to-xlsx) +[![Aspose.PDF Conversión PDF a Excel con App](pdf_to_xlsx.png)](https://products.aspose.app/pdf/conversion/pdf-to-xlsx) {{% /alert %}} El siguiente fragmento de código muestra el proceso para convertir un archivo PDF a formato XLS o XLSX con Aspose.PDF for Python via .NET. -Pasos: Convertir un archivo PDF a formato Excel (XML Spreadsheet 2003) +Pasos: Convertir un archivo PDF a un formato Excel (XML Spreadsheet 2003) 1. Cargar el documento PDF. 1. Configurar opciones de guardado de Excel usando [ExcelSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/). @@ -39,19 +40,20 @@ Pasos: Convertir un archivo PDF a formato Excel (XML Spreadsheet 2003) ```python from os import path -import aspose.pdf as apdf - -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) +import aspose.pdf as ap +import sys -document = apdf.Document(path_infile) -save_options = apdf.ExcelSaveOptions() -save_options.format = apdf.ExcelSaveOptions.ExcelFormat.XML_SPREAD_SHEET2003 -document.save(path_outfile, save_options) +def convert_pdf_to_excel_spread_sheet2003(infile, outfile): + document = ap.Document(infile) + save_options = ap.ExcelSaveOptions() + save_options.format = ap.ExcelSaveOptions.ExcelFormat.XML_SPREAD_SHEET2003 + document.save(outfile, save_options) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` +## Convertir PDF a Excel 2007+ (XLSX) + Pasos: Convertir un archivo PDF a formato XLSX (Excel 2007+) 1. Cargar el documento PDF. @@ -60,89 +62,86 @@ Pasos: Convertir un archivo PDF a formato XLSX (Excel 2007+) ```python from os import path -import aspose.pdf as apdf - -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) +import aspose.pdf as ap +import sys -document = apdf.Document(path_infile) -save_options = apdf.ExcelSaveOptions() -save_options.format = apdf.ExcelSaveOptions.ExcelFormat.XLSX -document.save(path_outfile, save_options) +def convert_pdf_to_excel_2007(infile, outfile): + document = ap.Document(infile) + save_options = ap.ExcelSaveOptions() + save_options.format = ap.ExcelSaveOptions.ExcelFormat.XLSX + document.save(outfile, save_options) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` ## Convertir PDF a XLS con columna de control -Al convertir un PDF al formato XLS, se agrega una columna en blanco al archivo de salida como primera columna. La \u0027ExcelSaveOptions class\u0027 \u0027insert_blank_column_at_first\u0027 opción se usa para controlar esta columna. Su valor predeterminado es true. +Al convertir un PDF a formato XLS, se agrega una columna en blanco al archivo de salida como primera columna. En la clase ‘ExcelSaveOptions’ la opción ‘insert_blank_column_at_first’ se utiliza para controlar esta columna. Su valor predeterminado es true. ```python from os import path -import aspose.pdf as apdf - -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) +import aspose.pdf as ap +import sys -document = apdf.Document(path_infile) -save_options = apdf.ExcelSaveOptions() -save_options.format = apdf.ExcelSaveOptions.ExcelFormat.XLSX -save_options.insert_blank_column_at_first = True -document.save(path_outfile, save_options) +def convert_pdf_to_excel_2007_control_column(infile, outfile): + document = ap.Document(infile) + save_options = ap.ExcelSaveOptions() + save_options.format = ap.ExcelSaveOptions.ExcelFormat.XLSX + save_options.insert_blank_column_at_first = True + document.save(outfile, save_options) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` -## Convertir PDF a una única hoja de Excel +## Convertir PDF a una sola hoja de Excel -Aspose.PDF for Python via .NET muestra cómo convertir un PDF a un archivo Excel (.xlsx), con la opción ‘minimize_the_number_of_worksheets’ habilitada. +Aspose.PDF for Python via .NET muestra cómo convertir un PDF a un archivo de Excel (.xlsx), con la opción 'minimize_the_number_of_worksheets' habilitada. -Pasos: Convertir PDF a XLS o XLSX en una hoja única con Python +Pasos: Convertir PDF a XLS o XLSX en una sola hoja de cálculo en Python 1. Cargar el documento PDF. 1. Configurar opciones de guardado de Excel usando [ExcelSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/). -1. La opción 'minimize_the_number_of_worksheets' reduce el número de hojas de Excel combinando páginas PDF en menos hojas de cálculo (p. ej., una hoja de cálculo para todo el documento si es posible). +1. La opción 'minimize_the_number_of_worksheets' reduce la cantidad de hojas de Excel al combinar páginas PDF en menos hojas de cálculo (p., ej., una hoja de cálculo para todo el documento si es posible). 1. Guarda el archivo convertido. ```python from os import path -import aspose.pdf as apdf - -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) +import aspose.pdf as ap +import sys -document = apdf.Document(path_infile) -save_options = apdf.ExcelSaveOptions() -save_options.format = apdf.ExcelSaveOptions.ExcelFormat.XLSX -save_options.minimize_the_number_of_worksheets = True -document.save(path_outfile, save_options) +def convert_pdf_to_excel_2007_single_excel_worksheet(infile, outfile): + document = ap.Document(infile) + save_options = ap.ExcelSaveOptions() + save_options.format = ap.ExcelSaveOptions.ExcelFormat.XLSX + save_options.minimize_the_number_of_worksheets = True + document.save(outfile, save_options) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` -## Convertir archivo PDF a un archivo Excel en formato XLSM +## Convertir PDF a Excel 2007 con macros habilitadas (XLSM) -Este ejemplo de Python muestra cómo convertir un archivo PDF en un archivo Excel en formato XLSM (Libro de Excel con macros habilitadas). +Este ejemplo en Python muestra cómo convertir un archivo PDF en un archivo Excel en formato XLSM (Libro de Excel con macros habilitadas). ```python from os import path -import aspose.pdf as apdf +import aspose.pdf as ap +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) +def convert_pdf_to_excel_2007_macro(infile, outfile): + document = ap.Document(infile) + save_options = ap.ExcelSaveOptions() + save_options.format = ap.ExcelSaveOptions.ExcelFormat.XLSM + document.save(outfile, save_options) -document = apdf.Document(path_infile) -save_options = apdf.ExcelSaveOptions() -save_options.format = apdf.ExcelSaveOptions.ExcelFormat.XLSM -document.save(path_outfile, save_options) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` ## Convertir a otros formatos de hoja de cálculo -### Convertir a CSV +### Convertir PDF a CSV -La función 'convert_pdf_to_excel_2007_csv' realiza la misma operación que antes, pero esta vez el formato de destino es CSV (Valores Separados por Comas) en lugar de XLSM. +La función 'convert_pdf_to_excel_2007_csv' realiza la misma operación que antes, pero esta vez el formato de destino es CSV (Valores separados por comas) en lugar de XLSM. Pasos: Convertir PDF a CSV en Python @@ -152,42 +151,44 @@ Pasos: Convertir PDF a CSV en Python ```python from os import path -import aspose.pdf as apdf - +import aspose.pdf as ap +import sys def convert_pdf_to_excel_2007_csv(infile, outfile): - path_infile = path.join(data_dir, infile) - path_outfile = path.join(data_dir, "python", outfile) - - document = apdf.Document(path_infile) - save_options = apdf.ExcelSaveOptions() - save_options.format = apdf.ExcelSaveOptions.ExcelFormat.CSV - document.save(path_outfile, save_options) + document = ap.Document(infile) + save_options = ap.ExcelSaveOptions() + save_options.format = ap.ExcelSaveOptions.ExcelFormat.CSV + document.save(outfile, save_options) print(infile + " converted into " + outfile) ``` -### Convertir a ODS +### Convertir PDF a ODS Pasos: Convertir PDF a ODS en Python 1. Crear una instancia de [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) objeto con el documento PDF de origen. 1. Crear una instancia de [ExcelSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/) con **ExcelSaveOptions.ExcelFormat.ODS** -1. Guárdalo en formato **ODS** llamando [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método y pasándolo [ExcelSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/). +1. Guárdelo en formato **ODS** llamando [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método y pasarlo [ExcelSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/). -La conversión al formato ODS se realiza de la misma manera que los demás formatos. +La conversión al formato ODS se realiza de la misma manera que todos los demás formatos. ```python from os import path -import aspose.pdf as apdf +import aspose.pdf as ap +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) +def convert_pdf_to_ods(infile, outfile): + document = ap.Document(infile) + save_options = ap.ExcelSaveOptions() + save_options.format = ap.ExcelSaveOptions.ExcelFormat.ODS + document.save(outfile, save_options) -document = apdf.Document(path_infile) -save_options = apdf.ExcelSaveOptions() -save_options.format = apdf.ExcelSaveOptions.ExcelFormat.ODS -document.save(path_outfile, save_options) - -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` + +## Conversiones relacionadas + +- [Convertir PDF a Word](/pdf/es/python-net/convert-pdf-to-word/) si tu prioridad es el flujo de texto editable en lugar de la estructura de la hoja de cálculo. +- [Convertir PDF a HTML](/pdf/es/python-net/convert-pdf-to-html/) cuando necesites una salida compatible con el navegador. +- [Convertir PDF a otros formatos](/pdf/es/python-net/convert-pdf-to-other-files/) para EPUB, Markdown, texto, XPS y flujos de trabajo de exportación relacionados. \ No newline at end of file diff --git a/es/python-net/converting/convert-pdf-to-html/_index.md b/es/python-net/converting/convert-pdf-to-html/_index.md index e4e4e0f1e..9b502cf51 100644 --- a/es/python-net/converting/convert-pdf-to-html/_index.md +++ b/es/python-net/converting/convert-pdf-to-html/_index.md @@ -4,237 +4,245 @@ linktitle: Convertir PDF a formato HTML type: docs weight: 50 url: /es/python-net/convert-pdf-to-html/ -lastmod: "2025-09-27" -description: Este tema le muestra cómo convertir un archivo PDF al formato HTML con la biblioteca Aspose.PDF for Python via .NET. +lastmod: "2026-05-11" +description: Aprenda cómo convertir PDF a HTML en Python con Aspose.PDF for Python via .NET, incluyendo salida de varias páginas, imágenes externas, manejo de SVG y renderizado de HTML en capas. sitemap: changefreq: "monthly" priority: 0.8 -TechArticle: true -AlternativeHeadline: Convertir PDF a HTML con Python -Abstract: > - Esta guía muestra cómo convertir documentos PDF a HTML con Aspose.PDF for Python via .NET. Incluye el flujo básico de conversión, el uso de HtmlSaveOptions y ejemplos para generar salida HTML reutilizable a partir de un PDF. +TechArticle: true +AlternativeHeadline: Cómo convertir PDF a HTML en Python +Abstract: Este artículo ofrece una guía completa sobre la conversión de archivos PDF a HTML usando Python, específicamente a través de la biblioteca Aspose.PDF for Python via .NET. Describe los pasos necesarios para lograr esta conversión programáticamente, resaltando la creación de un objeto `Document` a partir del PDF de origen y el uso de `HtmlSaveOptions` para guardar el documento en formato HTML. El artículo incluye un fragmento de código Python conciso que demuestra el proceso de conversión. Además, presenta una herramienta en línea, la aplicación "PDF a HTML" de Aspose.PDF, para que los usuarios exploren la funcionalidad y la calidad de la conversión. El artículo está estructurado para abarcar varios temas relacionados, garantizando una comprensión profunda del uso de Python para la conversión de PDF a HTML. --- ## Convertir PDF a HTML -**Aspose.PDF for Python via .NET** proporciona muchas funciones para convertir varios formatos de archivo en documentos PDF y convertir archivos PDF en varios formatos de salida. Este artículo explica cómo convertir un archivo PDF en HTML. Puedes usar solo un par de líneas de código Python para convertir PDF a HTML. Puede que necesites convertir PDF a HTML si deseas crear un sitio web o agregar contenido a un foro en línea. Una forma de convertir PDF a HTML es usar Python programáticamente. +**Aspose.PDF for Python via .NET** proporciona muchas funcionalidades para convertir varios formatos de archivo en documentos PDF y convertir archivos PDF en varios formatos de salida. Este artículo explica cómo convertir un archivo PDF en HTML. Puedes usar solo un par de líneas de código Python para convertir PDF a HTML. Es posible que necesites convertir PDF a HTML si deseas crear un sitio web o añadir contenido a un foro en línea. Una forma de convertir PDF a HTML es usar Python de forma programática. {{% alert color="success" %}} **Intenta convertir PDF a HTML en línea** -Aspose.PDF for Python le presenta una aplicación gratuita en línea ["PDF a HTML"](https://products.aspose.app/pdf/conversion/pdf-to-html), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for Python le presenta una aplicación en línea ["PDF a HTML"](https://products.aspose.app/pdf/conversion/pdf-to-html), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Aspose.PDF Conversión PDF a HTML con Aplicación Gratuita](pdf_to_html.png)](https://products.aspose.app/pdf/conversion/pdf-to-html) +[![Aspose.PDF Conversión de PDF a HTML con App](pdf_to_html.png)](https://products.aspose.app/pdf/conversion/pdf-to-html) {{% /alert %}} Pasos: Convertir PDF a HTML en Python 1. Crear una instancia de [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) objeto con el documento PDF de origen. -1. Guárdalo en [HtmlSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/htmlsaveoptions/) al llamar [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método. +1. Guárdalo en [HtmlSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/htmlsaveoptions/) llamando [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método. ```python +import aspose.pdf as ap from os import path -import aspose.pdf as apdf +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) -document = apdf.Document(path_infile) -save_options = apdf.HtmlSaveOptions() -document.save(path_outfile, save_options) +def convert_PDF_to_HTML(infile, outfile): + document = ap.Document(infile) + save_options = ap.HtmlSaveOptions() + document.save(outfile, save_options) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` -### Convertir PDF a HTML guardando las imágenes en la carpeta especificada +## Conversiones relacionadas -Esta función convierte un archivo PDF a formato HTML utilizando Aspose.PDF for Python via .NET. Todas las imágenes extraídas se almacenan en una carpeta especificada en lugar de incrustarse en el archivo HTML. +- [Convertir HTML a PDF](/pdf/es/python-net/convert-html-to-pdf/) cuando necesitas el flujo de trabajo inverso de web a documento. +- [Convertir PDF a Word](/pdf/es/python-net/convert-pdf-to-word/) si la salida de documento editable es más útil que HTML. +- [Convertir PDF a formatos de imagen](/pdf/es/python-net/convert-pdf-to-images-format/) para escenarios de exportación raster. -1. Configurar opciones de guardado HTML. +### Convertir PDF a HTML guardando imágenes en la carpeta especificada + +Esta función convierte un archivo PDF a formato HTML usando Aspose.PDF for Python via .NET. Todas las imágenes extraídas se almacenan en una carpeta especificada en lugar de incrustarse en el archivo HTML. + +1. Configura las opciones de guardado de HTML. 1. Guardar como HTML con imágenes externas. ```python +import aspose.pdf as ap from os import path -import aspose.pdf as apdf +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) -document = apdf.Document(path_infile) -save_options = apdf.HtmlSaveOptions() -save_options.special_folder_for_all_images = self.data_dir -document.save(path_outfile, save_options) +def convert_PDF_to_HTML_storing_images(infile, outfile): + document = ap.Document(infile) + save_options = ap.HtmlSaveOptions() + images_path = path.join(path.dirname(infile), "images") + save_options.special_folder_for_all_images = images_path + document.save(outfile, save_options) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` ### Convertir PDF a HTML multipágina -Esta función convierte un archivo PDF en HTML multipágina, donde cada página del PDF se exporta como un archivo HTML separado. Esto hace que la salida sea más fácil de navegar y reduce el tiempo de carga para PDFs grandes. +Esta función convierte un archivo PDF en HTML de varias páginas, donde cada página del PDF se exporta como un archivo HTML separado. Esto hace que la salida sea más fácil de navegar y reduce el tiempo de carga para PDFs grandes. 1. Cargue el PDF de origen usando 'ap.Document'. -1. Crea 'HtmlSaveOptions' y 'establezca split_into_pages'. +1. Crea 'HtmlSaveOptions' y establece `split_into_pages`. 1. Guarde el documento como HTML con las páginas divididas en archivos separados. 1. Imprime un mensaje de confirmación. ```python +import aspose.pdf as ap from os import path -import aspose.pdf as apdf +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) -document = apdf.Document(path_infile) -save_options = apdf.HtmlSaveOptions() -save_options.split_into_pages = True -document.save(path_outfile, save_options) +def convert_PDF_to_HTML_multi_page(infile, outfile): + document = ap.Document(infile) + save_options = ap.HtmlSaveOptions() + save_options.split_into_pages = True + document.save(outfile, save_options) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` -### Convertir PDF a HTML guardando imágenes SVG en una carpeta especificada +### Convertir PDF a HTML guardando las imágenes SVG en la carpeta especificada Esta función convierte un PDF a formato HTML mientras almacena todas las imágenes como archivos SVG en una carpeta especificada, en lugar de incrustarlas directamente en el HTML. 1. Cargue el PDF de origen usando 'ap.Document'. -1. Crea 'HtmlSaveOptions' y 'set special_folder_for_svg_images' en la carpeta de destino. +1. Crea 'HtmlSaveOptions' y establece `special_folder_for_svg_images' en la carpeta de destino. 1. Guarde el documento como HTML con imágenes SVG externas. 1. Imprime un mensaje de confirmación. ```python +import aspose.pdf as ap from os import path -import aspose.pdf as apdf +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) -document = apdf.Document(path_infile) -save_options = apdf.HtmlSaveOptions() -save_options.special_folder_for_svg_images = self.data_dir -document.save(path_outfile, save_options) +def convert_PDF_to_HTML_storing_svg(infile, outfile): + document = ap.Document(infile) + save_options = ap.HtmlSaveOptions() + images_path = path.join(path.dirname(infile), "svg_images") + save_options.special_folder_for_svg_images = images_path + document.save(outfile, save_options) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` ### Convertir PDF a HTML y guardar imágenes SVG comprimidas -Este fragmento convierte un PDF a formato HTML, almacenando todas las imágenes como archivos SVG en una carpeta especificada y comprimiéndolas para reducir el tamaño del archivo. +Este fragmento convierte un PDF al formato HTML, almacenando todas las imágenes como archivos SVG en una carpeta especificada y comprimiéndolas para reducir el tamaño del archivo. 1. Cargue el documento PDF usando 'ap.Document'. 1. Crear 'HtmlSaveOptions' y: - Establezca 'special_folder_for_svg_images' para almacenar imágenes SVG externamente. - - Habilite 'compress_svg_graphics_if_any' para comprimir imágenes SVG. + - Habilitar 'compress_svg_graphics_if_any' para comprimir imágenes SVG. 1. Guarde el documento como HTML con imágenes SVG externas comprimidas. 1. Imprime un mensaje de confirmación. ```python +import aspose.pdf as ap from os import path -import aspose.pdf as apdf +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) -document = apdf.Document(path_infile) -save_options = apdf.HtmlSaveOptions() -save_options.special_folder_for_svg_images = self.data_dir -save_options.compress_svg_graphics_if_any = True -document.save(path_outfile, save_options) +def convert_PDF_to_HTML_compress_svg(infile, outfile): + document = ap.Document(infile) + save_options = ap.HtmlSaveOptions() + images_path = path.join(path.dirname(infile), "svg_images") + save_options.special_folder_for_svg_images = images_path + save_options.compress_svg_graphics_if_any = True + document.save(outfile, save_options) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` -### Convertir PDF a HTML con control de imágenes ráster incrustadas +### Convertir PDF a HTML con control de imágenes raster incrustadas -Este fragmento convierte un PDF al formato HTML, incrustando imágenes raster como fondos de página PNG. Este enfoque preserva la calidad de la imagen y el diseño de la página dentro del HTML. +Este fragmento convierte un PDF a formato HTML, incrustando imágenes raster como fondos de página PNG. Este enfoque preserva la calidad de la imagen y el diseño de la página dentro del HTML. 1. Cargue el documento PDF usando 'ap.Document'. -1. Cree 'HtmlSaveOptions' y 'set raster_images_saving_mode' a 'AS_EMBEDDED_PARTS_OF_PNG_PAGE_BACKGROUND'. +1. Cree "HtmlSaveOptions" y establezca "raster_images_saving_mode" a "AS_EMBEDDED_PARTS_OF_PNG_PAGE_BACKGROUND". 1. Guarde el documento como HTML con imágenes raster incrustadas. 1. Imprime un mensaje de confirmación. ```python +import aspose.pdf as ap from os import path -import aspose.pdf as apdf +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) -document = apdf.Document(path_infile) -save_options = apdf.HtmlSaveOptions() -save_options.raster_images_saving_mode = apdf.HtmlSaveOptions.RasterImagesSavingModes.AS_EMBEDDED_PARTS_OF_PNG_PAGE_BACKGROUND -document.save(path_outfile, save_options) +def convert_PDF_to_HTML_PNG_background(infile, outfile): + document = ap.Document(infile) + save_options = ap.HtmlSaveOptions() + save_options.raster_images_saving_mode = ap.HtmlSaveOptions.RasterImagesSavingModes.AS_EMBEDDED_PARTS_OF_PNG_PAGE_BACKGROUND + document.save(outfile, save_options) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` -### Convertir PDF a página HTML de contenido solo del cuerpo +### Convertir PDF a página HTML solo con el contenido del cuerpo -Esta función convierte un PDF a formato HTML, generando contenido 'solo cuerpo' sin etiquetas adicionales 'html' o 'head', y divide la salida en páginas separadas. +Esta función convierte un PDF al formato HTML, generando contenido 'body-only' sin etiquetas adicionales 'html' o 'head', y divide la salida en páginas separadas. 1. Cargue el documento PDF usando 'ap.Document'. -1. Crear 'HtmlSaveOptions' y configurar: +1. Crea 'HtmlSaveOptions' y configura: - 'html_markup_generation_mode = WRITE_ONLY_BODY_CONTENT' para generar solo el contenido del 'body'. - - 'split_into_pages' para crear archivos HTML separados para cada página PDF. + - 'split_into_pages' para crear archivos HTML separados para cada página de PDF. 1. Guarde el documento como HTML con las opciones especificadas. 1. Imprime un mensaje de confirmación. ```python +import aspose.pdf as ap from os import path -import aspose.pdf as apdf - -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) -document = apdf.Document(path_infile) -save_options = apdf.HtmlSaveOptions() -save_options.html_markup_generation_mode = ( - apdf.HtmlSaveOptions.HtmlMarkupGenerationModes.WRITE_ONLY_BODY_CONTENT -) -save_options.split_into_pages = True -document.save(path_outfile, save_options) - -print(infile + " converted into " + outfile) +import sys + +def convert_PDF_to_HTML_body_content(infile, outfile): + document = ap.Document(infile) + save_options = ap.HtmlSaveOptions() + save_options.html_markup_generation_mode = ( + ap.HtmlSaveOptions.HtmlMarkupGenerationModes.WRITE_ONLY_BODY_CONTENT + ) + save_options.split_into_pages = True + document.save(outfile, save_options) + + print(infile + " converted into " + outfile) ``` ### Convertir PDF a HTML con renderizado de texto transparente -Esta función convierte un PDF a formato HTML, renderizando todo el texto como transparente, incluidos los textos con sombra, lo que preserva la fidelidad visual mientras permite una estilización flexible en el HTML de salida. +Esta función convierte un PDF a formato HTML, renderizando todo el texto como transparente, incluidos los textos con sombra, lo que conserva la fidelidad visual mientras permite un estilo flexible en el HTML de salida. 1. Cargue el documento PDF usando 'ap.Document'. -1. Crear 'HtmlSaveOptions' y configurar: +1. Crea 'HtmlSaveOptions' y configura: - 'save_transparent_texts' para renderizar texto normal como transparente. - 'save_shadowed_texts_as_transparent_texts' para renderizar texto sombreado como transparente. -1. Guarda el documento como HTML con renderizado de texto transparente. +1. Guarde el documento como HTML con renderizado de texto transparente. 1. Imprime un mensaje de confirmación. ```python +import aspose.pdf as ap from os import path -import aspose.pdf as apdf +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) -document = apdf.Document(path_infile) -save_options = apdf.HtmlSaveOptions() -save_options.save_transparent_texts = True -save_options.save_shadowed_texts_as_transparent_texts = True -document.save(path_outfile, save_options) +def convert_PDF_to_HTML_transparent_text_rendering(infile, outfile): + document = ap.Document(infile) + save_options = ap.HtmlSaveOptions() + save_options.save_transparent_texts = True + save_options.save_shadowed_texts_as_transparent_texts = True + document.save(outfile, save_options) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` ### Convertir PDF a HTML con renderizado de capas de documento -Esta función convierte un PDF a formato HTML, preservando las capas del documento al convertir el contenido marcado en capas separadas en el HTML de salida. Esto permite que los elementos en capas (como anotaciones, fondos y superposiciones) se representen con precisión. +Esta función convierte un PDF al formato HTML, preservando las capas del documento al convertir el contenido marcado en capas separadas en el HTML de salida. Esto permite que los elementos en capas (como anotaciones, fondos y superposiciones) se rendericen con precisión. 1. Cargue el documento PDF usando 'ap.Document'. -1. Crea 'HtmlSaveOptions' y habilita 'convert_marked_content_to_layers' para preservar capas. -1. Guarda el documento como HTML con contenido en capas. +1. Cree 'HtmlSaveOptions' y habilite 'convert_marked_content_to_layers' para preservar capas. +1. Guarde el documento como HTML con contenido en capas. 1. Imprime un mensaje de confirmación. ```python +import aspose.pdf as ap from os import path -import aspose.pdf as apdf +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) -document = apdf.Document(path_infile) -save_options = apdf.HtmlSaveOptions() -save_options.convert_marked_content_to_layers = True -document.save(path_outfile, save_options) +def convert_PDF_to_HTML_document_layers_rendering(infile, outfile): + document = ap.Document(infile) + save_options = ap.HtmlSaveOptions() + save_options.convert_marked_content_to_layers = True + document.save(outfile, save_options) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` diff --git a/es/python-net/converting/convert-pdf-to-images-format/_index.md b/es/python-net/converting/convert-pdf-to-images-format/_index.md index c47ced3e2..95b4b1002 100644 --- a/es/python-net/converting/convert-pdf-to-images-format/_index.md +++ b/es/python-net/converting/convert-pdf-to-images-format/_index.md @@ -1,126 +1,129 @@ --- -title: Convertir PDF a diferentes formatos de imagen en Python +title: Convertir PDF a formatos de imagen en Python linktitle: Convertir PDF a imágenes type: docs weight: 70 url: /es/python-net/convert-pdf-to-images-format/ -lastmod: "2025-09-27" -description: Explore cómo convertir páginas PDF en imágenes como PNG, JPEG o TIFF usando Aspose.PDF en Python via .NET. +lastmod: "2026-05-08" +description: Aprenda cómo renderizar páginas PDF como archivos TIFF, BMP, EMF, JPEG, PNG, GIF y SVG en Python con Aspose.PDF for Python via .NET. sitemap: changefreq: "monthly" priority: 0.5 -TechArticle: true -AlternativeHeadline: Convertir PDF a imágenes con Python -Abstract: > - Esta página describe cómo convertir páginas PDF a TIFF, BMP, EMF, JPG, PNG, GIF y SVG con Aspose.PDF for Python via .NET. Aprenderá a usar los enfoques Device y SaveOptions para exportar páginas individuales o documentos completos con el formato de imagen adecuado. +TechArticle: true +AlternativeHeadline: Convierta páginas PDF a TIFF, PNG, JPEG, GIF, BMP, EMF y SVG en Python +Abstract: Este artículo explica cómo convertir archivos PDF a formatos de imagen comunes con Aspose.PDF for Python via .NET. Cubre la exportación de TIFF a nivel de documento con `TiffDevice`, la generación de imágenes raster por página con subclases de `ImageDevice` como `BmpDevice`, `JpegDevice`, `PngDevice`, `GifDevice` y `EmfDevice`, y la exportación vectorial a SVG con `SvgSaveOptions`. Cada sección incluye los pasos principales y ejemplos de Python necesarios para guardar el contenido PDF como salida de imagen. --- -## Python Convertir PDF a Imagen +## Convertir PDF a imágenes en Python -**Aspose.PDF for Python** utiliza varios enfoques para convertir PDF a imagen. En términos generales, utilizamos dos enfoques: conversión mediante el enfoque Device y conversión mediante SaveOption. Esta sección le mostrará cómo convertir documentos PDF a formatos de imagen como BMP, JPEG, GIF, PNG, EMF, TIFF y SVG utilizando uno de esos enfoques. +**Aspose.PDF for Python via .NET** admite varias formas de convertir el contenido de PDF a imágenes. En la práctica, la mayoría de los flujos de trabajo utilizan una de dos opciones: -Hay varias clases en la biblioteca que le permiten usar un dispositivo virtual para transformar imágenes. DocumentDevice está orientado a la conversión del documento completo, pero ImageDevice, a una página en particular. +- el enfoque Device para renderizar páginas PDF a formatos de imagen raster +- el enfoque SaveOptions para exportar contenido PDF a SVG + +Este artículo muestra cómo convertir archivos PDF a TIFF, BMP, EMF, JPEG, PNG, GIF y SVG. + +La biblioteca incluye múltiples clases de renderizado. `DocumentDevice` está diseñado para la conversión de todo el documento, mientras `ImageDevice` apunta a páginas individuales. ## Convertir PDF usando la clase DocumentDevice -**Aspose.PDF for Python** hace posible convertir páginas de PDF a imágenes TIFF. +Use `DocumentDevice` cuando desee renderizar todo el PDF en un único archivo TIFF de varias páginas. -El [TiffDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/) (basado en DocumentDevice) la clase permite convertir páginas PDF a imágenes TIFF. Esta clase proporciona un método llamado [proceso](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/#methods) que le permite convertir todas las páginas de un archivo PDF en una sola imagen TIFF. +La clase [TiffDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/) se basa en `DocumentDevice` y proporciona el método [process](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/#methods) para convertir todas las páginas de un archivo PDF en una sola salida TIFF. {{% alert color="success" %}} **Intenta convertir PDF a TIFF en línea** -Aspose.PDF for Python via .NET le presenta la aplicación gratuita en línea ["PDF a TIFF"](https://products.aspose.app/pdf/conversion/pdf-to-tiff), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for Python via .NET le presenta una aplicación en línea ["PDF a TIFF"](https://products.aspose.app/pdf/conversion/pdf-to-tiff), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Conversión de PDF a TIFF con Aspose.PDF con aplicación gratuita](pdf_to_tiff.png)](https://products.aspose.app/pdf/conversion/pdf-to-tiff) +[![Conversión de PDF a TIFF con Aspose.PDF y App](pdf_to_tiff.png)](https://products.aspose.app/pdf/conversion/pdf-to-tiff) {{% /alert %}} -### Convertir páginas PDF a una imagen TIFF +### Convertir páginas PDF a una sola imagen TIFF -Aspose.PDF for Python explique cómo convertir todas las páginas de un archivo PDF en una única imagen TIFF: +Aspose.PDF for Python via .NET puede renderizar cada página de un archivo PDF en una imagen TIFF. Pasos: Convertir PDF a TIFF en Python -1. Crear un objeto del [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase. -1. Crear [ConfiguraciónTiff](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffsettings/) y [TiffDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/) objetos -1. Llame al [proceso](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/#methods) método para convertir el documento PDF a TIFF. -1. Para establecer las propiedades del archivo de salida, use el [ConfiguraciónTiff](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffsettings/) clase. +1. Cargue el PDF de origen con la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Cree los objetos [TiffSettings](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffsettings/) y [TiffDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/). +1. Configure las opciones TIFF, como la compresión, la profundidad de color y el manejo de páginas en blanco. +1. Llame al método [process](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/#methods) para escribir el archivo TIFF. -El siguiente fragmento de código muestra cómo convertir todas las páginas del PDF a una única imagen TIFF. +El siguiente fragmento de código muestra cómo convertir todas las páginas del PDF en una sola imagen TIFF. ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - from os import path - import aspose.pdf as apdf - from io import FileIO - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) +def convert_PDF_to_TIFF(infile, outfile): + document = ap.Document(infile) - document = apdf.Document(path_infile) - - resolution = apdf.devices.Resolution(300) - tiffSettings = apdf.devices.TiffSettings() - tiffSettings.compression = apdf.devices.CompressionType.LZW - tiffSettings.depth = apdf.devices.ColorDepth.DEFAULT + resolution = ap.devices.Resolution(300) + tiffSettings = ap.devices.TiffSettings() + tiffSettings.compression = ap.devices.CompressionType.LZW + tiffSettings.depth = ap.devices.ColorDepth.DEFAULT tiffSettings.skip_blank_pages = False - tiffDevice = apdf.devices.TiffDevice(resolution, tiffSettings) - tiffDevice.process(document, path_outfile) + tiffDevice = ap.devices.TiffDevice(resolution, tiffSettings) + tiffDevice.process(document, f"{outfile}.tiff") print(infile + " converted into " + outfile) ``` ## Convertir PDF usando la clase ImageDevice -`ImageDevice` es el ancestro de `BmpDevice`, `JpegDevice`, `GifDevice`, `PngDevice` y `EmfDevice`. +Use `ImageDevice` cuando necesite una salida página por página en un formato de imagen rasterizada. -- El [BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) Clase permite convertir páginas PDF a BMP imágenes. -- El [Dispositivo EMF](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/emfdevice/) Clase permite convertir páginas PDF a EMF imágenes. -- El [JpegDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/jpegdevice/) class le permite convertir páginas PDF a imágenes JPEG. -- El [PngDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/pngdevice/) Clase permite convertir páginas PDF a PNG imágenes. -- El [GifDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/gifdevice/) Clase permite convertir páginas PDF a GIF imágenes. +`ImageDevice` es la clase base para `BmpDevice`, `JpegDevice`, `GifDevice`, `PngDevice`, y `EmfDevice`. -Echemos un vistazo a cómo convertir una página PDF a una imagen. +- La clase [BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) permite convertir páginas PDF en imágenes BMP. +- La clase [EmfDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/emfdevice/) permite convertir páginas PDF en imágenes EMF. +- La clase [JpegDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/jpegdevice/) permite convertir páginas PDF en imágenes JPEG. +- La clase [PngDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/pngdevice/) permite convertir páginas PDF en imágenes PNG. +- La clase [GifDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/gifdevice/) permite convertir páginas PDF en imágenes GIF. -[BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) la clase proporciona un método llamado [proceso](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/#methods) lo que le permite convertir una página específica del archivo PDF al formato de imagen BMP. Las otras clases tienen el mismo método. Por lo tanto, si necesitamos convertir una página PDF a una imagen, simplemente instanciamos la clase requerida. +El flujo de trabajo es el mismo para cada formato: cargar el documento, crear el dispositivo apropiado, luego procesar la página requerida. -Los siguientes pasos y fragmento de código en Python muestran esta posibilidad: +[BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) expone el método [process](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/#methods) para renderizar una página específica como BMP. Las demás clases de `ImageDevice` siguen el mismo patrón, por lo que puede cambiar el formato cambiando la clase del dispositivo. - - [Convertir PDF a BMP en Python](#python-pdf-to-image) - - [Convertir PDF a EMF en Python](#python-pdf-to-image) - - [Convertir PDF a JPG en Python](#python-pdf-to-image) - - [Convertir PDF a PNG en Python](#python-pdf-to-image) - - [Convertir PDF a GIF en Python](#python-pdf-to-image) +Los siguientes enlaces y ejemplos de código muestran cómo renderizar páginas PDF a formatos de imagen comunes: + +- [Convertir PDF a BMP en Python](#convertir-pdf-a-bmp) +- [Convertir PDF a EMF en Python](#convertir-pdf-a-emf) +- [Convertir PDF a JPEG en Python](#convertir-pdf-a-jpeg) +- [Convertir PDF a PNG en Python](#convertir-pdf-a-png) +- [Convertir PDF a GIF en Python](#convertir-pdf-a-gif) Pasos: PDF a Imagen (BMP, EMF, JPG, PNG, GIF) en Python -1. Cargar el archivo PDF usando [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase. -1. Crear una instancia de la subclase de [Dispositivo de imagen](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/imagedevice/) es decir - * [BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) (para convertir PDF a BMP) - * [Dispositivo EMF](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/emfdevice/) (para convertir PDF a Emf) - * [JpegDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/jpegdevice/) (para convertir PDF a JPG) - * [PngDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/pngdevice/) (para convertir PDF a PNG) - * [GifDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/gifdevice/) (para convertir PDF a GIF) -1. Llame al [ImageDevice.process()](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/imagedevice/#methods) método para realizar la conversión de PDF a Imagen. +1. Cargue el archivo PDF con la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Cree una instancia de la subclase requerida de [ImageDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/imagedevice/): + - [BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) (para convertir PDF a BMP) + - [EmfDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/emfdevice/) (para convertir PDF a EMF) + - [JpegDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/jpegdevice/) (para convertir PDF a JPG) + - [PngDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/pngdevice/) (para convertir PDF a PNG) + - [GifDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/gifdevice/) (para convertir PDF a GIF) +1. Recorre las páginas que deseas exportar. +1. Llama al [ImageDevice.process()](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/imagedevice/#methods) método para guardar cada página como una imagen. ### Convertir PDF a BMP ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - from os import path - import aspose.pdf as apdf - from io import FileIO - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = apdf.Document(path_infile) - resolution = apdf.devices.Resolution(300) - device = apdf.devices.BmpDevice(resolution) +def convert_PDF_to_BMP(infile, outfile): + document = ap.Document(infile) + resolution = ap.devices.Resolution(300) + device = ap.devices.BmpDevice(resolution) page_count = 1 while page_count <= len(document.pages): - image_stream = FileIO(path_outfile + str(page_count) + "_out.bmp", "w") + image_stream = FileIO(outfile + str(page_count) + "_out.bmp", "w") device.process(document.pages[page_count], image_stream) image_stream.close() page_count = page_count + 1 @@ -131,20 +134,18 @@ Pasos: PDF a Imagen (BMP, EMF, JPG, PNG, GIF) en Python ### Convertir PDF a EMF ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - from os import path - import aspose.pdf as apdf - from io import FileIO - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = apdf.Document(path_infile) - resolution = apdf.devices.Resolution(300) - device = apdf.devices.EmfDevice(resolution) +def convert_PDF_to_EMF(infile, outfile): + document = ap.Document(infile) + resolution = ap.devices.Resolution(300) + device = ap.devices.EmfDevice(resolution) page_count = 1 while page_count <= len(document.pages): - image_stream = FileIO(path_outfile + str(page_count) + "_out.emf", "w") + image_stream = FileIO(outfile + str(page_count) + "_out.emf", "w") device.process(document.pages[page_count], image_stream) image_stream.close() page_count = page_count + 1 @@ -155,21 +156,19 @@ Pasos: PDF a Imagen (BMP, EMF, JPG, PNG, GIF) en Python ### Convertir PDF a JPEG ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - from os import path - import aspose.pdf as apdf - from io import FileIO - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = apdf.Document(path_infile) - resolution = apdf.devices.Resolution(300) - device = apdf.devices.JpegDevice(resolution) +def convert_PDF_to_JPEG(infile, outfile): + document = ap.Document(infile) + resolution = ap.devices.Resolution(300) + device = ap.devices.JpegDevice(resolution) page_count = 1 while page_count <= len(document.pages): - image_stream = FileIO(path_outfile + str(page_count) + "_out.jpeg", "w") + image_stream = FileIO(outfile + str(page_count) + "_out.jpeg", "w") device.process(document.pages[page_count], image_stream) image_stream.close() page_count = page_count + 1 @@ -177,45 +176,37 @@ Pasos: PDF a Imagen (BMP, EMF, JPG, PNG, GIF) en Python print(infile + " converted into " + outfile) ``` - ### Convertir PDF a PNG ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - from os import path - import aspose.pdf as apdf - from io import FileIO - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = apdf.Document(path_infile) - resolution = apdf.devices.Resolution(300) +def convert_PDF_to_PNG(infile, outfile): + document = ap.Document(infile) + resolution = ap.devices.Resolution(300) - device = apdf.devices.PngDevice(resolution) + device = ap.devices.PngDevice(resolution) page_count = 1 while page_count <= len(document.pages): - image_stream = FileIO(path_outfile + str(page_count) + "_out.png", "w") + image_stream = FileIO(outfile + str(page_count) + "_out.png", "w") device.process(document.pages[page_count], image_stream) image_stream.close() page_count = page_count + 1 - - print(infile + " converted into " + outfile) ``` ### Convertir PDF a PNG con fuente predeterminada ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - from os import path - import aspose.pdf as ap - from io import FileIO - - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = ap.Document(path_infile) +def convert_PDF_to_PNG_with_default_font(infile, outfile): + document = ap.Document(infile) resolution = ap.devices.Resolution(300) rendering_options = ap.RenderingOptions() @@ -226,31 +217,27 @@ Pasos: PDF a Imagen (BMP, EMF, JPG, PNG, GIF) en Python page_count = 1 while page_count <= len(document.pages): - image_stream = FileIO(path_outfile + str(page_count) + "_out.png", "w") + image_stream = FileIO(outfile + str(page_count) + "_out.png", "w") device.process(document.pages[page_count], image_stream) image_stream.close() page_count = page_count + 1 - - print(infile + " converted into " + outfile) ``` ### Convertir PDF a GIF ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - from os import path - import aspose.pdf as apdf - from io import FileIO - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = apdf.Document(path_infile) - resolution = apdf.devices.Resolution(300) - device = apdf.devices.GifDevice(resolution) +def convert_PDF_to_GIF(infile, outfile): + document = ap.Document(infile) + resolution = ap.devices.Resolution(300) + device = ap.devices.GifDevice(resolution) page_count = 1 while page_count <= len(document.pages): - image_stream = FileIO(path_outfile + str(page_count) + "_out.gif", "w") + image_stream = FileIO(outfile + str(page_count) + "_out.gif", "w") device.process(document.pages[page_count], image_stream) image_stream.close() page_count = page_count + 1 @@ -261,56 +248,59 @@ Pasos: PDF a Imagen (BMP, EMF, JPG, PNG, GIF) en Python {{% alert color="success" %}} **Intenta convertir PDF a PNG en línea** -Como ejemplo de cómo funcionan nuestras aplicaciones gratuitas, por favor revisa la siguiente función. +Como ejemplo de cómo funcionan nuestras aplicaciones, por favor revise la siguiente característica. -Aspose.PDF para Python te presenta una aplicación en línea gratuita ["PDF a PNG"](https://products.aspose.app/pdf/conversion/pdf-to-png), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for Python le presenta la aplicación en línea ["PDF a PNG"](https://products.aspose.app/pdf/conversion/pdf-to-png), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Cómo convertir PDF a PNG usando una aplicación gratuita](pdf_to_png.png)](https://products.aspose.app/pdf/conversion/pdf-to-png) +[![Cómo convertir PDF a PNG usando App](pdf_to_png.png)](https://products.aspose.app/pdf/conversion/pdf-to-png) {{% /alert %}} ## Convertir PDF usando la clase SaveOptions -Esta parte del artículo te muestra cómo convertir PDF a SVG usando Python y la clase SaveOptions. +Use `SaveOptions` cuando desee exportar contenido PDF a SVG. {{% alert color="success" %}} **Intenta convertir PDF a SVG en línea** -Aspose.PDF for Python via .NET le presenta la aplicación gratuita en línea ["PDF a SVG"](https://products.aspose.app/pdf/conversion/pdf-to-svg), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for Python via .NET le presenta una aplicación en línea ["PDF a SVG"](https://products.aspose.app/pdf/conversion/pdf-to-svg), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Aspose.PDF Conversión de PDF a SVG con la aplicación gratuita](pdf_to_svg.png)](https://products.aspose.app/pdf/conversion/pdf-to-svg) +[![Aspose.PDF Conversión de PDF a SVG con App](pdf_to_svg.png)](https://products.aspose.app/pdf/conversion/pdf-to-svg) {{% /alert %}} -**Scalable Vector Graphics (SVG)** es una familia de especificaciones de un formato de archivo basado en XML para gráficos vectoriales bidimensionales, tanto estáticos como dinámicos (interactivos o animados). La especificación SVG es un estándar abierto que ha sido desarrollado por el World Wide Web Consortium (W3C) desde 1999. +**Gráficos vectoriales escalables (SVG)** es un formato basado en XML para gráficos vectoriales bidimensionales. Debido a que SVG sigue siendo vectorial, es útil cuando necesita una salida escalable para la web, la interfaz de usuario o flujos de trabajo de diseño. -Las imágenes SVG y sus comportamientos se definen en archivos de texto XML. Esto significa que pueden ser buscadas, indexadas, programadas y, si es necesario, comprimidas. Como archivos XML, las imágenes SVG pueden ser creadas y editadas con cualquier editor de texto, pero a menudo es más conveniente crearlas con programas de dibujo como Inkscape. +Los archivos SVG son de texto, permiten búsquedas y son fáciles de posprocesar en otras herramientas. -Aspose.PDF for Python soporta la función de convertir imágenes SVG a formato PDF y también ofrece la capacidad de convertir archivos PDF a formato SVG. Para cumplir con este requisito, el [SvgSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/svgsaveoptions/) la clase ha sido introducida en el espacio de nombres Aspose.PDF. Instancie un objeto de SvgSaveOptions y páselo como segundo argumento a la [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método. +Aspose.PDF for Python via .NET puede convertir SVG a PDF y también exportar páginas PDF a SVG. Para la conversión de PDF a SVG, cree un objeto [SvgSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/svgsaveoptions/) y páselo al método [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods). -El siguiente fragmento de código muestra los pasos para convertir un archivo PDF a formato SVG con Python. +Los siguientes pasos muestran cómo convertir un archivo PDF a SVG con Python. Pasos: Convertir PDF a SVG en Python -1. Crear un objeto del [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) clase. -1. Crear [SvgSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/svgsaveoptions/) objeto con la configuración necesaria. -1. Llame al [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método y pásalo [SvgSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/svgsaveoptions/) objeto convierte el documento PDF a SVG. +1. Cargue el PDF de origen con la clase [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Cree un objeto [SvgSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/svgsaveoptions/) y configure las opciones necesarias. +1. Llame al método [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) con la instancia de `SvgSaveOptions` para escribir la salida SVG. ### Convertir PDF a SVG ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - from os import path - import aspose.pdf as apdf - from io import FileIO - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) +def convert_PDF_to_SVG(infile, outfile): + document = ap.Document(infile) - document = apdf.Document(path_infile) - - save_options = apdf.SvgSaveOptions() + save_options = ap.SvgSaveOptions() save_options.compress_output_to_zip_archive = False save_options.treat_target_file_name_as_directory = True - document.save(path_outfile, save_options) - print(infile + " converted into " + outfile) + document.save(f"{outfile}.svg", save_options) ``` + +## Conversiones relacionadas + +- [Convertir formatos de imagen a PDF](/pdf/es/python-net/convert-images-format-to-pdf/) cuando necesites reconstruir PDFs a partir de JPG, PNG, TIFF, SVG o de otras fuentes de imágenes. +- [Convertir PDF a HTML](/pdf/es/python-net/convert-pdf-to-html/) para una salida compatible con el navegador en lugar de imágenes raster. +- [Convertir PDF a otros formatos](/pdf/es/python-net/convert-pdf-to-other-files/) para flujos de trabajo de exportación de EPUB, Markdown, texto y XPS. diff --git a/es/python-net/converting/convert-pdf-to-other-files/_index.md b/es/python-net/converting/convert-pdf-to-other-files/_index.md index 0ddf17d56..4124a7290 100644 --- a/es/python-net/converting/convert-pdf-to-other-files/_index.md +++ b/es/python-net/converting/convert-pdf-to-other-files/_index.md @@ -1,18 +1,17 @@ --- -title: Convertir PDF a EPUB, LaTeX, Texto, XPS en Python +title: Convertir PDF a EPUB, Texto, XPS y más en Python linktitle: Convertir PDF a otros formatos type: docs weight: 90 url: /es/python-net/convert-pdf-to-other-files/ -lastmod: "2025-09-27" -description: Este tema le muestra cómo convertir archivos PDF a otros formatos de archivo como EPUB, LaTeX, Texto, XPS, etc., usando Python. +lastmod: "2026-05-11" +description: Aprenda cómo convertir archivos PDF a EPUB, LaTeX, Markdown, texto, XPS y MobiXML en Python con Aspose.PDF for Python via .NET. sitemap: changefreq: "monthly" priority: 0.8 -TechArticle: true -AlternativeHeadline: Convertir PDF a EPUB, texto, XPS y más -Abstract: > - Esta guía explica cómo convertir archivos PDF a EPUB, LaTeX/TeX, texto, XPS y XML con Aspose.PDF for Python via .NET. Reúne ejemplos de código y opciones de guardado para exportar contenido PDF a otros formatos reutilizables. +TechArticle: true +AlternativeHeadline: Cómo convertir PDF a otros formatos en Python +Abstract: El artículo ofrece una guía completa sobre la conversión de archivos PDF a varios formatos utilizando Aspose.PDF for Python. Cubre la conversión de PDFs a formatos EPUB, LaTeX/TeX, Texto, XPS y XML. Cada sección comienza con una invitación a probar las aplicaciones en línea proporcionadas por Aspose para convertir PDFs a los formatos correspondientes, resaltando la facilidad de uso y la calidad de estas herramientas. --- ## Convertir PDF a EPUB @@ -20,43 +19,48 @@ Abstract: > {{% alert color="success" %}} **Intenta convertir PDF a EPUB en línea** -Aspose.PDF for Python le presenta aplicación en línea gratuita ["PDF a EPUB"](https://products.aspose.app/pdf/conversion/pdf-to-epub), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for Python le presenta una aplicación en línea ["PDF a EPUB"](https://products.aspose.app/pdf/conversion/pdf-to-epub), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Conversión de PDF a EPUB con la aplicación gratuita de Aspose.PDF](pdf_to_epub.png)](https://products.aspose.app/pdf/conversion/pdf-to-epub) +[![Aspose.PDF Conversión de PDF a EPUB con App](pdf_to_epub.png)](https://products.aspose.app/pdf/conversion/pdf-to-epub) {{% /alert %}} -EPUB es un estándar de libro electrónico gratuito y abierto del International Digital Publishing Forum (IDPF). Los archivos tienen la extensión .epub. -EPUB está diseñado para contenido refluible, lo que significa que un lector EPUB puede optimizar el texto para un dispositivo de pantalla concreto. EPUB también admite contenido de diseño fijo. El formato está pensado como un único formato que los editores y casas de conversión pueden usar internamente, así como para la distribución y venta. Reemplaza el estándar Open eBook. +EPUB es un estándar gratuito y abierto de libros electrónicos del International Digital Publishing Forum (IDPF). Los archivos tienen la extensión .epub. +EPUB está diseñado para contenido refluible, lo que significa que un lector EPUB puede optimizar el texto para un dispositivo de visualización particular. EPUB también admite contenido de diseño fijo. El formato está pensado como un único formato que los editores y casas de conversión pueden utilizar internamente, así como para distribución y venta. Reemplaza el estándar Open eBook. -Aspose.PDF for Python también admite la función de convertir documentos PDF al formato EPUB. Aspose.PDF for Python tiene una clase llamada ‘EpubSaveOptions’ que puede usarse como el segundo argumento para [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método, para generar un archivo EPUB. +Aspose.PDF for Python también admite la función de convertir documentos PDF al formato EPUB. Aspose.PDF for Python tiene una clase llamada \u0027EpubSaveOptions\u0027 que puede usarse como el segundo argumento para [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método, para generar un archivo EPUB. Por favor, intente usar el siguiente fragmento de código para cumplir con este requisito con Python. ```python -from os import path import aspose.pdf as ap +from os import path +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) - -document = ap.Document(path_infile) -save_options = ap.EpubSaveOptions() -save_options.content_recognition_mode = ap.EpubSaveOptions.RecognitionMode.FLOW -document.save(path_outfile, save_options) +def convert_PDF_to_EPUB(infile, outfile): + document = ap.Document(infile) + save_options = ap.EpubSaveOptions() + save_options.content_recognition_mode = ap.EpubSaveOptions.RecognitionMode.FLOW + document.save(outfile, save_options) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` +## Conversiones relacionadas + +- [Convertir PDF a Word](/pdf/es/python-net/convert-pdf-to-word/) para salida de documento de oficina editable. +- [Convertir PDF a HTML](/pdf/es/python-net/convert-pdf-to-html/) para salida orientada al navegador. +- [Convertir PDF a PDF/A, PDF/E y PDF/X](/pdf/es/python-net/convert-pdf-to-pdf_x/) para flujos de trabajo de conversión archivísticos y compatibles con normas. + ## Convertir PDF a LaTeX/TeX -**Aspose.PDF for Python via .NET** admite la conversión de PDF a LaTeX/TeX. -El formato de archivo LaTeX es un formato de archivo de texto con un marcado especial y se usa en el sistema de preparación de documentos basado en TeX para la composición tipográfica de alta calidad. +**Aspose.PDF for Python via .NET** soporta la conversión de PDF a LaTeX/TeX. +El formato de archivo LaTeX es un formato de archivo de texto con marcado especial y se utiliza en el sistema de preparación de documentos basado en TeX para una composición tipográfica de alta calidad. {{% alert color="success" %}} **Intenta convertir PDF a LaTeX/TeX en línea** -Aspose.PDF for Python le presenta aplicación en línea gratuita ["PDF a LaTeX"](https://products.aspose.app/pdf/conversion/pdf-to-tex), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for Python le presenta una aplicación en línea ["PDF a LaTeX"](https://products.aspose.app/pdf/conversion/pdf-to-tex), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Aspose.PDF Conversión PDF a LaTeX/TeX con aplicación gratuita](pdf_to_latex.png)](https://products.aspose.app/pdf/conversion/pdf-to-tex) +[![Aspose.PDF Conversión PDF a LaTeX/TeX con App](pdf_to_latex.png)](https://products.aspose.app/pdf/conversion/pdf-to-tex) {{% /alert %}} Para convertir archivos PDF a TeX, Aspose.PDF tiene la clase [LaTeXSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/latexsaveoptions/) que proporciona la propiedad OutDirectoryPath para guardar imágenes temporales durante el proceso de conversión. @@ -64,106 +68,101 @@ Para convertir archivos PDF a TeX, Aspose.PDF tiene la clase [LaTeXSaveOptions]( El siguiente fragmento de código muestra el proceso de convertir archivos PDF al formato TEX con Python. ```python -from os import path import aspose.pdf as ap +from os import path +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) - -document = ap.Document(path_infile) -save_options = ap.LaTeXSaveOptions() +def convert_PDF_to_TeX(infile, outfile): + document = ap.Document(infile) + save_options = ap.LaTeXSaveOptions() + document.save(outfile, save_options) -document.save(path_outfile, save_options) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` ## Convertir PDF a texto -**Aspose.PDF for Python** soporta la conversión de todo el documento PDF y de una sola página a un archivo de texto. Puedes convertir un documento PDF a un archivo TXT usando la clase \u0027TextDevice\u0027. El siguiente fragmento de código explica cómo extraer los textos de todas las páginas. +**Aspose.PDF for Python** admite la conversión de un documento PDF completo y de una sola página a un archivo de texto. Puedes convertir un documento PDF a un archivo TXT usando la clase 'TextDevice'. El siguiente fragmento de código explica cómo extraer los textos de todas las páginas. ```python -from os import path import aspose.pdf as ap +from os import path +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) - -document = ap.Document(path_infile) -device = ap.devices.TextDevice() -device.process(document.pages[1], path_outfile) +def convert_PDF_to_TXT(infile, outfile): + document = ap.Document(infile) + device = ap.devices.TextDevice() + device.process(document.pages[1], outfile) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` {{% alert color="success" %}} **Intenta convertir Convert PDF a Texto en línea** -Aspose.PDF for Python le presenta aplicación en línea gratuita ["PDF a Texto"](https://products.aspose.app/pdf/conversion/pdf-to-txt), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for Python le presenta una aplicación en línea ["PDF a Texto"](https://products.aspose.app/pdf/conversion/pdf-to-txt), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Aspose.PDF Conversión de PDF a Texto con la Aplicación Gratuita](pdf_to_text.png)](https://products.aspose.app/pdf/conversion/pdf-to-txt) +[![Conversión de PDF a Texto con App de Aspose.PDF](pdf_to_text.png)](https://products.aspose.app/pdf/conversion/pdf-to-txt) {{% /alert %}} ## Convertir PDF a XPS -**Aspose.PDF for Python** ofrece la posibilidad de convertir archivos PDF al formato XPS. Intentemos usar el fragmento de código presentado para convertir archivos PDF al formato XPS con Python. +**Aspose.PDF for Python** brinda la posibilidad de convertir archivos PDF al formato XPS. Intentemos usar el fragmento de código presentado para convertir archivos PDF al formato XPS con Python. {{% alert color="success" %}} **Intenta convertir PDF a XPS en línea** -Aspose.PDF for Python le presenta aplicación en línea gratuita ["PDF a XPS"](https://products.aspose.app/pdf/conversion/pdf-to-xps), donde puedes intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for Python le presenta una aplicación en línea ["PDF a XPS"](https://products.aspose.app/pdf/conversion/pdf-to-xps), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Aspose.PDF Conversión de PDF a XPS con aplicación gratuita](pdf_to_xps.png)](https://products.aspose.app/pdf/conversion/pdf-to-xps) +[![Aspose.PDF Conversión de PDF a XPS con App](pdf_to_xps.png)](https://products.aspose.app/pdf/conversion/pdf-to-xps) {{% /alert %}} El tipo de archivo XPS está asociado principalmente con la XML Paper Specification de Microsoft Corporation. La XML Paper Specification (XPS), anteriormente con el nombre en código Metro y que engloba el concepto de marketing Next Generation Print Path (NGPP), es la iniciativa de Microsoft para integrar la creación y visualización de documentos en el sistema operativo Windows. -Para convertir archivos PDF a XPS, Aspose.PDF tiene la clase [OpcionesDeGuardadoXps](https://reference.aspose.com/pdf/python-net/aspose.pdf/xpssaveoptions/) que se usa como segundo argumento para el [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método para generar el archivo XPS. +Para convertir archivos PDF a XPS, Aspose.PDF tiene la clase [OpcionesDeGuardadoXps](https://reference.aspose.com/pdf/python-net/aspose.pdf/xpssaveoptions/) que se utiliza como el segundo argumento para el [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método para generar el archivo XPS. El siguiente fragmento de código muestra el proceso de convertir un archivo PDF al formato XPS. ```python -from os import path import aspose.pdf as ap +from os import path +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) - -document = ap.Document(path_infile) -save_options = ap.XpsSaveOptions() -save_options.use_new_imaging_engine = True -document.save(path_outfile, save_options) +def convert_PDF_to_XPS(infile, outfile): + document = ap.Document(infile) + save_options = ap.XpsSaveOptions() + save_options.use_new_imaging_engine = True + document.save(outfile, save_options) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` ## Convertir PDF a MD -Aspose.PDF tiene la clase ‘MarkdownSaveOptions()’, que convierte un documento PDF al formato Markdown (MD) mientras preserva imágenes y recursos. +Aspose.PDF tiene la clase ‘MarkdownSaveOptions()’, que convierte un documento PDF al formato Markdown (MD) mientras preserva las imágenes y los recursos. -1. Carga el PDF de origen usando 'ap.Document'. +1. Cargue el PDF de origen usando 'ap.Document'. 1. Crea una instancia de 'MarkdownSaveOptions'. 1. Establezca 'resources_directory_name' a 'images' – las imágenes extraídas se almacenarán en esta carpeta. -1. Guarde el documento Markdown convertido usando las opciones configuradas. -1. Imprime un mensaje de confirmación después de la conversión. +1. Guarda el documento Markdown convertido usando las opciones configuradas. +1. Imprima un mensaje de confirmación después de la conversión. ```python -from os import path import aspose.pdf as ap +from os import path +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) - -document = ap.Document(path_infile) -save_options = ap.MarkdownSaveOptions() -# save_options.extract_vector_graphics = True -save_options.resources_directory_name = "images" -save_options.use_image_html_tag = True -document.save(path_outfile, save_options) +def convert_PDF_to_MD(infile, outfile): + document = ap.Document(infile) + save_options = ap.MarkdownSaveOptions() + save_options.resources_directory_name = "images" + save_options.use_image_html_tag = True + document.save(outfile, save_options) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` -Un archivo Markdown con texto e imágenes vinculadas almacenadas en la carpeta de imágenes especificada. +Un archivo Markdown con texto e imágenes enlazadas almacenadas en la carpeta de imágenes especificada. ## Convertir PDF a MobiXML @@ -174,14 +173,13 @@ Este método convierte un documento PDF al formato MOBI (MobiXML), que se usa co 1. Imprima un mensaje de confirmación una vez que la conversión haya finalizado. ```python -from os import path import aspose.pdf as ap +from os import path +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) - -document = ap.Document(path_infile) -document.save(path_outfile, ap.SaveFormat.MOBI_XML) +def convert_PDF_to_MobiXML(infile, outfile): + document = ap.Document(infile) + document.save(outfile, ap.SaveFormat.MOBI_XML) -print(infile + " converted into " + outfile) + print(infile + " converted into " + outfile) ``` diff --git a/es/python-net/converting/convert-pdf-to-pdfx/_index.md b/es/python-net/converting/convert-pdf-to-pdfx/_index.md index bbcd6c43f..3fe600c37 100644 --- a/es/python-net/converting/convert-pdf-to-pdfx/_index.md +++ b/es/python-net/converting/convert-pdf-to-pdfx/_index.md @@ -1,88 +1,75 @@ --- -title: Convertir PDF a formatos PDF/x en Python -linktitle: Convertir PDF a formatos PDF/x +title: Convertir PDF a PDF/A, PDF/E y PDF/X en Python +linktitle: Convertir PDF a PDF/A, PDF/E y PDF/X type: docs weight: 120 url: /es/python-net/convert-pdf-to-pdf_x/ -lastmod: "2025-09-27" -description: Este tema le muestra cómo convertir PDF a formatos PDF/x utilizando Aspose.PDF for Python via .NET. +lastmod: "2026-05-11" +description: Aprenda cómo convertir archivos PDF a PDF/A, PDF/E y PDF/X en Python con Aspose.PDF for Python via .NET para flujos de trabajo de archivado, accesibilidad e impresión. sitemap: changefreq: "monthly" priority: 0.8 -TechArticle: true -AlternativeHeadline: Convertir PDF a PDF/A, PDF/E y PDF/X -Abstract: > - Esta página muestra cómo convertir documentos PDF a estándares PDF/A, PDF/E y PDF/X con Aspose.PDF for Python via .NET. Incluye ejemplos para validación, archivado y preparación de archivos PDF para flujos de impresión y conformidad. +TechArticle: true +AlternativeHeadline: Cómo convertir PDF a formatos PDF/x +Abstract: El artículo ofrece una guía completa sobre cómo convertir PDF a formatos PDF/A, PDF/E y PDF/X utilizando Aspose.PDF for Python. --- **PDF a formato PDF/x significa la capacidad de convertir PDF a formatos adicionales, a saber PDF/A, PDF/E y PDF/X.** ## Convertir PDF a PDF/A -**Aspose.PDF for Python** permite convertir un archivo PDF a un PDF/A archivo PDF conforme. Antes de hacerlo, el archivo debe ser validado. Este tema explica cómo. +**Aspose.PDF for Python** permite convertir un archivo PDF a un PDF/A Archivo PDF conforme. Antes de hacerlo, el archivo debe ser validado. Este tema explica cómo. {{% alert color="primary" %}} -Por favor, tenga en cuenta que seguimos Adobe Preflight para validar la conformidad PDF/A. Todas las herramientas del mercado tienen su propia “representación” de la conformidad PDF/A. Por favor, consulte este artículo sobre herramientas de validación PDF/A para referencia. Elegimos productos de Adobe para verificar cómo Aspose.PDF produce archivos PDF porque Adobe está en el centro de todo lo relacionado con PDF. +Tenga en cuenta que seguimos Adobe Preflight para validar la conformidad PDF/A. Todas las herramientas del mercado tienen su propia “representación” de la conformidad PDF/A. Por favor, consulte este artículo sobre herramientas de validación PDF/A como referencia. Elegimos productos de Adobe para verificar cómo Aspose.PDF produce archivos PDF porque Adobe está en el centro de todo lo relacionado con PDF. {{% /alert %}} -Convierta el archivo usando el método Convert de la clase Document. Antes de convertir el PDF a un archivo compatible con PDF/A, valide el PDF usando el método Validate. El resultado de la validación se almacena en un archivo XML y luego este resultado también se pasa al método Convert. También puede especificar la acción para los elementos que no pueden convertirse usando la enumeración ConvertErrorAction. +Convierta el archivo usando el método Convert de la clase Document. Antes de convertir el PDF a un archivo compatible con PDF/A, valide el PDF usando el método Validate. El resultado de la validación se almacena en un archivo XML y luego ese resultado también se pasa al método Convert. También puede especificar la acción para los elementos que no pueden convertirse usando la enumeración ConvertErrorAction. {{% alert color="success" %}} **Intenta convertir PDF a PDF/A en línea** -Aspose.PDF for Python le presenta una aplicación gratuita en línea ["PDF a PDF/A-1A"](https://products.aspose.app/pdf/conversion/pdf-to-pdfa1a), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for Python le presenta una aplicación en línea ["PDF a PDF/A-1A"](https://products.aspose.app/pdf/conversion/pdf-to-pdfa1a), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Aspose.PDF Conversión de PDF a PDF/A con App gratuita](pdf_to_pdfa.png)](https://products.aspose.app/pdf/conversion/pdf-to-pdfa1a) +[![Aspose.PDF Conversión PDF a PDF/A con App](pdf_to_pdfa.png)](https://products.aspose.app/pdf/conversion/pdf-to-pdfa1a) {{% /alert %}} -El método 'document.validate()' valida si un archivo PDF cumple con el estándar PDF/A-1B (una versión estandarizada por ISO de PDF diseñada para archivado a largo plazo). Los resultados de la validación se guardan en un archivo de registro. - -1. Cargue el documento PDF usando 'ap.Document'. -1. Llame al método validate con el nivel de cumplimiento objetivo (ap.PdfFormat.PDF_A_1B). -1. Los resultados de la validación se escriben en el archivo de registro especificado. - -```python -path_infile = path.join(self.data_dir, infile) -path_logfile = path.join(self.data_dir, "python", outfile) - -document = ap.Document(path_infile) -document.validate(path_logfile, ap.PdfFormat.PDF_A_1B) -``` +El método 'document.validate()' valida si un archivo PDF cumple con el estándar PDF/A-1B (una versión estandarizada por ISO de PDF diseñada para el archivo a largo plazo). Los resultados de la validación se guardan en un archivo de registro. ### Convertir PDF a PDF/A-1B -El siguiente fragmento de código muestra cómo convertir archivos PDF al formato PDF/A-1B: +El siguiente fragmento de código muestra cómo convertir archivos PDF a formato PDF/A-1B: 1. Cargue el documento PDF usando 'ap.Document'. 1. Llame al método convert con los siguientes parámetros: - - Ruta del archivo de registro - almacena los detalles del proceso de conversión y las verificaciones de cumplimiento. - - Formato de destino - 'ap.PdfFormat.PDF_A_1B' (estándar de archivo). + - Ruta del archivo de registro - almacena los detalles del proceso de conversión y de las comprobaciones de cumplimiento. + - Formato de destino - 'ap.PdfFormat.PDF_A_1B' (estándar de archivado). - Acción de error - 'ap.ConvertErrorAction.DELETE' — elimina automáticamente los elementos que impiden el cumplimiento. 1. Guarde el archivo convertido compatible con PDF/A en la ruta de salida. ```python -from os import path import aspose.pdf as ap - -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) - -document = ap.Document(path_infile) -document.convert( - self.data_dir + "pdf_pdfa.log", - ap.PdfFormat.PDF_A_1B, - ap.ConvertErrorAction.DELETE, -) -document.save(path_outfile) - -print(infile + " converted into " + outfile) +from os import path +import sys + +def convert_PDF_to_PDFA(infile, outfile): + """Convert PDF to PDF/A-1B format.""" + + document = ap.Document(infile) + document.convert( + outfile.replace(".pdf", "-log.xml"), + ap.PdfFormat.PDF_A_1B, + ap.ConvertErrorAction.DELETE, + ) + document.save(outfile) + print(infile + " converted into " + outfile) ``` ### Convertir PDF a PDF 2.0 y PDF/A-4 -Este ejemplo demuestra cómo convertir un documento PDF en formatos estandarizados más recientes: PDF 2.0 y PDF/A-4. +Este ejemplo muestra cómo convertir un documento PDF a formatos estandarizados más recientes: PDF 2.0 y PDF/A-4. Ambas conversiones ayudan a garantizar el cumplimiento de las especificaciones modernas y los requisitos de archivo. 1. Cargue el documento de entrada usando ap.Document. @@ -90,185 +77,164 @@ Ambas conversiones ayudan a garantizar el cumplimiento de las especificaciones m - Ruta del archivo de registro para los detalles de conversión. - Formato de destino - 'ap.PdfFormat.V_2_0'. - Acción de error - 'ap.ConvertErrorAction.DELETE' para eliminar elementos no conformes. -1. Realice una segunda conversión a PDF/A-4 usando el mismo método, asegurándose de que el archivo también cumpla con los estándares de archivo. -1. Guarda el documento resultante en la ruta de salida especificada. +1. Realice una segunda conversión a PDF/A-4 usando el mismo método, asegurándose de que el archivo también cumpla con los estándares de archivado. +1. Guarde el documento resultante en la ruta de salida especificada. ```python -from os import path import aspose.pdf as ap +from os import path +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) -path_logfile = path_outfile.replace(".pdf", "_log.xml") - -document = ap.Document(path_infile) -document.convert(path_logfile, ap.PdfFormat.V_2_0, ap.ConvertErrorAction.DELETE) - -document.convert(path_logfile, ap.PdfFormat.PDF_A_4, ap.ConvertErrorAction.DELETE) -document.save(path_outfile) +def convert_PDF_to_PDFA4(infile, outfile): + logfile = outfile.replace(".pdf", "_log.xml") -print(infile + " converted into " + outfile) + document = ap.Document(infile) + document.convert(logfile, ap.PdfFormat.V_2_0, ap.ConvertErrorAction.DELETE) + document.convert(logfile, ap.PdfFormat.PDF_A_4, ap.ConvertErrorAction.DELETE) + document.save(outfile) ``` ### Convertir PDF a PDF/A-3A con archivos incrustados -El siguiente fragmento de código demuestra cómo incrustar archivos externos en un PDF y luego convertir el PDF al formato PDF/A-3A, que admite archivos adjuntos y es adecuado para el archivado a largo plazo con contenido incrustado. +El siguiente fragmento de código muestra cómo incrustar archivos externos en un PDF y luego convertir el PDF al formato PDF/A-3A, que admite archivos adjuntos y es adecuado para el archivado a largo plazo con contenido incrustado. 1. Cargue el PDF de entrada usando 'ap.Document'. -1. Cree un objeto 'FileSpecification' que apunte al archivo a incrustar (p. ej., "aspose-logo.jpg") con una descripción. +1. Cree un objeto 'FileSpecification' que apunte al archivo a incrustar (p. ej., "aspose-logo.jpg") con una descripción. 1. Agrega la especificación de archivo a la colección 'embedded_files' del PDF. 1. Convertir el documento a PDF/A-3A usando 'document.convert', especificando: - Ruta del archivo de registro. - Formato de destino - 'ap.PdfFormat.PDF_A_3A'. - Acción de error - 'ap.ConvertErrorAction.DELETE' para eliminar elementos no conformes. -1. Guarda el PDF convertido en la ruta de salida. +1. Guarde el PDF convertido en la ruta de salida. 1. Imprime un mensaje de confirmación. ```python -from os import path import aspose.pdf as ap - -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) -path_logfile = path_outfile.replace(".pdf", "_log.xml") - -document = ap.Document(path_infile) - -fileSpecification = ap.FileSpecification( - self.data_dir + "aspose-logo.jpg", "Large Image file" -) -document.embedded_files.add(fileSpecification) -document.convert(path_logfile, ap.PdfFormat.PDF_A_3A, ap.ConvertErrorAction.DELETE) -document.save(path_outfile) -print(infile + " converted into " + outfile) +from os import path +import sys + +def convert_PDF_to_PDFA_with_attachment(infile, attachement_file, outfile): + logfile = outfile.replace(".pdf", "-log.xml") + document = ap.Document(infile) + + fileSpecification = ap.FileSpecification(attachement_file, "Large Image file") + document.embedded_files.add(fileSpecification) + document.convert( + logfile, ap.PdfFormat.PdfFormat.PDF_A_3A, ap.ConvertErrorAction.DELETE + ) + document.save(outfile) ``` ### Convertir PDF a PDF/A-1B con sustitución de fuentes -Esta función convierte un PDF al formato PDF/A-1B mientras maneja fuentes faltantes sustituyéndolas por otras disponibles. Esto garantiza que el PDF convertido mantenga la consistencia visual y cumpla con los estándares de archivo. +Esta función convierte un PDF al formato PDF/A-1B mientras maneja fuentes faltantes sustituyéndolas por las disponibles. Esto garantiza que el PDF convertido permanezca visualmente consistente y cumpla con los estándares de archivado. 1. Cargue el PDF usando 'ap.Document'. 1. Convertir el PDF a PDF/A-1B usando 'document.convert', especificando: - Ruta del archivo de registro. - Formato de destino - 'ap.PdfFormat.PDF_A_1B'. - Acción de error - 'ap.ConvertErrorAction.DELETE' para eliminar elementos no conformes. -1. Guarda el PDF convertido en la ruta de salida. +1. Guarde el PDF convertido en la ruta de salida. 1. Imprime un mensaje de confirmación. ```python -from os import path import aspose.pdf as ap +from os import path +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) -path_logfile = path_outfile.replace(".pdf", "_log.xml") - -try: - ap.text.FontRepository.find_font("AgencyFB") +def convert_PDF_to_PDFA_replace_missing_fonts(infile, outfile): + logfile = outfile.replace(".pdf", "-log.xml") + try: + ap.text.FontRepository.find_font("AgencyFB") -except ap.FontNotFoundException: - font_substitution = ap.text.SimpleFontSubstitution("AgencyFB", "Arial") - ap.text.FontRepository.Substitutions.append(font_substitution) + except ap.FontNotFoundException: + font_substitution = ap.text.SimpleFontSubstitution("AgencyFB", "Arial") + ap.text.FontRepository.Substitutions.append(font_substitution) -document = ap.Document(path_infile) -document.convert(path_logfile, ap.PdfFormat.PDF_A_1B, ap.ConvertErrorAction.DELETE) -document.save(path_outfile) -print(infile + " converted into " + outfile) + document = ap.Document(infile) + document.convert(logfile, ap.PdfFormat.PDF_A_1B, ap.ConvertErrorAction.DELETE) + document.save(outfile) ``` ### Convertir PDF a PDF/A-1B con etiquetado automático -Esta función convierte un documento PDF al formato PDF/A-1B mientras etiqueta automáticamente el contenido para accesibilidad y consistencia estructural. El etiquetado automático mejora la usabilidad del documento para lectores de pantalla y garantiza una estructura semántica adecuada. +Esta función convierte un documento PDF al formato PDF/A-1B mientras etiqueta automáticamente el contenido para accesibilidad y consistencia estructural. El etiquetado automático mejora la usabilidad del documento para los lectores de pantalla y garantiza una estructura semántica adecuada. 1. Cargue el PDF usando 'ap.Document'. 1. Crear 'PdfFormatConversionOptions' especificando: - Ruta del archivo de registro. - Formato de destino - 'ap.PdfFormat.PDF_A_1B'. - Acción de error - 'ap.ConvertErrorAction.DELETE' para eliminar elementos no conformes. -1. Configurar 'AutoTaggingSettings': +1. Configura 'AutoTaggingSettings': - Habilitar 'enable_auto_tagging = True'. - Establezca 'heading_recognition_strategy = AUTO' para detectar automáticamente los encabezados. -1. Asigne la configuración de etiquetado automático a las opciones de conversión. +1. Asignar la configuración de autoetiquetado a las opciones de conversión. 1. Convierta el PDF usando 'document.convert(options)'. -1. Guarda el PDF convertido en la ruta de salida. +1. Guarde el PDF convertido en la ruta de salida. 1. Imprime un mensaje de confirmación. ```python -from os import path import aspose.pdf as ap +from os import path +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) -path_logfile = path_outfile.replace(".pdf", "_log.xml") +def convert_PDF_to_PDFA_with_automatic_tagging(infile, outfile): + logfile = outfile.replace(".pdf", "-log.xml") -document = ap.Document(path_infile) -options = ap.PdfFormatConversionOptions( - path_logfile, ap.PdfFormat.PDF_A_1B, ap.ConvertErrorAction.DELETE -) + document = ap.Document(infile) + options = ap.PdfFormatConversionOptions( + logfile, ap.PdfFormat.PDF_A_1B, ap.ConvertErrorAction.DELETE + ) -auto_tagging_settings = ap.AutoTaggingSettings() -auto_tagging_settings.enable_auto_tagging = True + auto_tagging_settings = ap.AutoTaggingSettings() + auto_tagging_settings.enable_auto_tagging = True -auto_tagging_settings.heading_recognition_strategy = ap.HeadingRecognitionStrategy.AUTO + auto_tagging_settings.heading_recognition_strategy = ( + ap.HeadingRecognitionStrategy.AUTO + ) -options.auto_tagging_settings = auto_tagging_settings -document.convert(options) -document.save(path_outfile) -print(infile + " converted into " + outfile) + options.auto_tagging_settings = auto_tagging_settings + document.convert(options) + document.save(outfile) + print(infile + " converted into " + outfile) ``` ## Convertir PDF a PDF/E -Este fragmento valida si un documento PDF cumple con la norma PDF/E-1, que es una norma ISO diseñada para documentos de ingeniería y técnicos. Los resultados de la validación se guardan en un archivo de registro. - -1. Cargue el documento PDF usando 'ap.Document'. -1. Llame al método validate, especificando: - - Ruta del archivo de registro para almacenar los resultados de validación. - - Formato objetivo - 'ap.PdfFormat.PDF_E_1'. -1. Los resultados de la validación se guardan en el archivo de registro para su revisión. - -```python -path_infile = path.join(self.data_dir, infile) -path_logfile = path.join(self.data_dir, "python", outfile) - -document = ap.Document(path_infile) -document.validate(path_logfile, ap.PdfFormat.PDF_E_1) -``` - -El siguiente ejemplo muestra cómo convertir un PDF al formato PDF/E-1, que es una norma ISO diseñada para la ingeniería y la documentación técnica. Este formato conserva la disposición precisa, los gráficos y los metadatos requeridos para los flujos de trabajo de ingeniería. +Este fragmento de código muestra cómo convertir un documento PDF al formato PDF/E-1, que es un estándar ISO adaptado para la ingeniería y la documentación técnica. Este formato preserva el diseño preciso, los gráficos y los metadatos necesarios para los flujos de trabajo de ingeniería. 1. Cargue el PDF de origen usando 'ap.Document'. 1. Crear 'PdfFormatConversionOptions' especificando: - Ruta del archivo de registro para rastrear problemas de conversión. - - Formato objetivo - 'ap.PdfFormat.PDF_E_1'. + - Formato de destino - 'ap.PdfFormat.PDF_E_1'. - Acción de error - 'ap.ConvertErrorAction.DELETE' para eliminar elementos no conformes. 1. Convierta el PDF usando 'document.convert(options)'. -1. Guarde el PDF convertido en la ruta de salida especificada. +1. Guarda el PDF convertido en la ruta de salida especificada. 1. Imprime un mensaje de confirmación. ```python -from os import path import aspose.pdf as ap +from os import path +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) -path_logfile = path_outfile.replace(".pdf", "_log.xml") +def convert_PDF_to_PDF_E(infile, outfile): + logfile = outfile.replace(".pdf", "-log.xml") -document = ap.Document(path_infile) -options = ap.PdfFormatConversionOptions( - path_logfile, ap.PdfFormat.PDF_E_1, ap.ConvertErrorAction.DELETE -) + document = ap.Document(infile) + options = ap.PdfFormatConversionOptions( + logfile, ap.PdfFormat.PDF_E_1, ap.ConvertErrorAction.DELETE + ) -document.convert(options) + document.convert(options) -# Save PDF document -document.save(path_outfile) -print(infile + " converted into " + outfile) + # Save PDF document + document.save(outfile) + print(infile + " converted into " + outfile) ``` ## Convertir PDF a PDF/X -El siguiente fragmento de código convierte un documento PDF al formato PDF/X-4, que es una norma ISO comúnmente utilizada en la industria de la impresión y la publicación. PDF/X-4 garantiza la precisión del color, mantiene la transparencia e incrusta perfiles ICC para una salida consistente en todos los dispositivos. +El siguiente fragmento de código convierte un documento PDF al formato PDF/X-4, que es una norma ISO utilizada comúnmente en la industria de impresión y publicación. PDF/X-4 garantiza la precisión del color, mantiene la transparencia e incrusta perfiles ICC para una salida constante en diferentes dispositivos. 1. Cargue el PDF de origen usando 'ap.Document'. 1. Crear 'PdfFormatConversionOptions' especificando: @@ -278,30 +244,37 @@ El siguiente fragmento de código convierte un documento PDF al formato PDF/X-4, 1. Proporcione el **archivo de perfil ICC** para la gestión del color a través de 'icc_profile_file_name'. 1. Especifique un **OutputIntent** con un identificador de condición (p.ej., "FOGRA39") para los requisitos de impresión. 1. Convierta el PDF usando 'document.convert()'. -1. Guarde el PDF convertido en la ruta de salida especificada. +1. Guarda el PDF convertido en la ruta de salida especificada. 1. Imprime un mensaje de confirmación. ```python -from os import path import aspose.pdf as ap +from os import path +import sys -path_infile = path.join(self.data_dir, infile) -path_outfile = path.join(self.data_dir, "python", outfile) -path_logfile = path_outfile.replace(".pdf", "_log.xml") +def convert_PDF_to_PDF_X(infile, outfile): + logfile = outfile.replace(".pdf", "-log.xml") -document = ap.Document(path_infile) -options = ap.PdfFormatConversionOptions( - path_logfile, ap.PdfFormat.PDF_X_4, ap.ConvertErrorAction.DELETE -) + document = ap.Document(infile) + options = ap.PdfFormatConversionOptions( + logfile, ap.PdfFormat.PDF_X_4, ap.ConvertErrorAction.DELETE + ) -# Provide the name of the external ICC profile file (optional) -options.icc_profile_file_name = path.join(self.data_dir, "ISOcoated_v2_eci.icc") -# Provide an output condition identifier and other necessary OutputIntent properties (optional) -options.output_intent = ap.OutputIntent("FOGRA39") + # Provide the name of the external ICC profile file (optional) + options.icc_profile_file_name = path.join( + path.dirname(infile), "ISOcoated_v2_eci.icc" + ) + # Provide an output condition identifier and other necessary OutputIntent properties (optional) + options.output_intent = ap.OutputIntent("FOGRA39") -document.convert(options) + document.convert(options) -# Save PDF document -document.save(path_outfile) -print(infile + " converted into " + outfile) + # Save PDF document + document.save(outfile) + print(infile + " converted into " + outfile) ``` + +## Conversiones relacionadas + +- [Convertir PDF a Word](/pdf/es/python-net/convert-pdf-to-word/) para flujos de trabajo de contenido editable después de la validación de estándares. +- [Convertir PDF a HTML](/pdf/es/python-net/convert-pdf-to-html/) cuando tu salida objetivo está lista para la web en lugar de PDF basado en estándares. diff --git a/es/python-net/converting/convert-pdf-to-powerpoint/_index.md b/es/python-net/converting/convert-pdf-to-powerpoint/_index.md index e4cda49bb..bb80575f6 100644 --- a/es/python-net/converting/convert-pdf-to-powerpoint/_index.md +++ b/es/python-net/converting/convert-pdf-to-powerpoint/_index.md @@ -4,28 +4,29 @@ linktitle: Convertir PDF a PowerPoint type: docs weight: 30 url: /es/python-net/convert-pdf-to-powerpoint/ -description: Aprenda cómo convertir fácilmente PDFs a presentaciones de PowerPoint usando Aspose.PDF for Python via .NET. Guía paso a paso para una transformación sin problemas de PDF a PPTX. -lastmod: "2025-09-27" +description: Aprenda cómo convertir archivos PDF a PowerPoint en Python con Aspose.PDF for Python via .NET, incluyendo diapositivas PPTX editables y salida de diapositivas basadas en imágenes. +lastmod: "2026-05-11" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true -AlternativeHeadline: Convertir PDF a PPTX con Python -Abstract: > - Esta guía explica cómo convertir archivos PDF a presentaciones PowerPoint PPTX con Aspose.PDF for Python via .NET. También muestra cómo exportar páginas como diapositivas de imagen y cómo ajustar la resolución de salida durante la conversión. +TechArticle: true +AlternativeHeadline: Cómo convertir PDF a PowerPoint en Python +Abstract: Este artículo proporciona una guía completa sobre la conversión de archivos PDF a presentaciones de PowerPoint usando Python, centrada específicamente en el formato PPTX. Introduce el uso de Aspose.PDF for Python via .NET, que facilita el proceso de conversión al permitir que las páginas PDF se transformen en diapositivas individuales en un archivo PPTX. El artículo describe los pasos necesarios para la conversión, incluyendo la creación de instancias de las clases Document y PptxSaveOptions y la utilización del método Save. Además, destaca una funcionalidad para convertir PDFs a PPTX con diapositivas como imágenes al establecer una propiedad específica en PptxSaveOptions. Se proporcionan fragmentos de código para ilustrar el proceso de conversión. El artículo también hace referencia a una aplicación en línea para probar la función de conversión de PDF a PPTX, ofreciendo a los usuarios una experiencia práctica. Además, enumera varios temas y funcionalidades relacionadas disponibles en este contexto, enfatizando la versatilidad y el enfoque programático para manejar conversiones de PDF a PowerPoint usando Python. --- ## Conversión de PDF a PowerPoint y PPTX con Python **Aspose.PDF for Python via .NET** le permite rastrear el progreso de la conversión de PDF a PPTX. -Tenemos una API llamada Aspose.Slides que ofrece la funcionalidad de crear así como manipular presentaciones PPT/PPTX. Esta API también proporciona la funcionalidad de convertir PPTX archivos al formato PDF. Durante esta conversión, las páginas individuales del archivo PDF se convierten en diapositivas separadas en el archivo PPTX. +Tenemos una API llamada Aspose.Slides que ofrece la funcionalidad de crear así como manipular presentaciones PPT/PPTX. Esta API también proporciona la funcionalidad de convertir. PPTX archivos al formato PDF. Durante esta conversión, las páginas individuales del archivo PDF se convierten en diapositivas separadas en el archivo PPTX. -Durante la conversión de PDF a PPTX, el texto se renderiza como Texto donde puede seleccionarlo/actualizarlo. Tenga en cuenta que, para convertir archivos PDF al formato PPTX, Aspose.PDF proporciona una clase llamada [PptxSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/). Se pasa un objeto de la clase PptxSaveOptions como segundo argumento a la [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods). El siguiente fragmento de código muestra el proceso de conversión de archivos PDF al formato PPTX. +Durante la conversión de PDF a PPTX, el texto se renderiza como Texto donde puedes seleccionar/actualizarlo. Ten en cuenta que, para convertir archivos PDF al formato PPTX, Aspose.PDF proporciona una clase llamada [PptxSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/). Un objeto de la clase PptxSaveOptions se pasa como segundo argumento a la [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods)El siguiente fragmento de código muestra el proceso para convertir archivos PDF al formato PPTX. + +Esta conversión es especialmente útil cuando deseas reutilizar informes PDF, presentaciones de diapositivas o folletos en archivos de presentación editables. ## Conversión simple de PDF a PowerPoint usando Python y Aspose.PDF for Python via .NET -Para convertir PDF a PPTX, Aspose.PDF for Python aconseja usar los siguientes pasos de código. +Para convertir PDF a PPTX, Aspose.PDF for Python recomienda usar los siguientes pasos de código. Pasos: Convertir PDF a PowerPoint en Python @@ -34,18 +35,14 @@ Pasos: Convertir PDF a PowerPoint en Python 1. Llama al [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) método. ```python - - from os import path - import aspose.pdf as apdf - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = apdf.Document(path_infile) - save_options = apdf.PptxSaveOptions() - document.save(path_outfile, save_options) - - print(infile + " converted into " + outfile) +import aspose.pdf as ap +from os import path +import sys + +def convert_PDF_to_PPTX(infile, outfile): + document = ap.Document(infile) + save_options = ap.PptxSaveOptions() + document.save(outfile, save_options) ``` ## Convertir PDF a PPTX con diapositivas como imágenes @@ -53,53 +50,52 @@ Pasos: Convertir PDF a PowerPoint en Python {{% alert color="success" %}} **Intenta convertir PDF a PowerPoint en línea** -Aspose.PDF le presenta una aplicación gratuita en línea ["PDF a PPTX"](https://products.aspose.app/pdf/conversion/pdf-to-pptx), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF le presenta una aplicación en línea ["PDF a PPTX"](https://products.aspose.app/pdf/conversion/pdf-to-pptx), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Aspose.PDF Conversión de PDF a PPTX con aplicación gratuita](pdf_to_pptx.png)](https://products.aspose.app/pdf/conversion/pdf-to-pptx) +[![Aspose.PDF Conversión PDF a PPTX con App](pdf_to_pptx.png)](https://products.aspose.app/pdf/conversion/pdf-to-pptx) {{% /alert %}} -En caso de que necesite convertir un PDF buscable a PPTX como imágenes en lugar de texto seleccionable, Aspose.PDF ofrece dicha función a través de [PptxSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/) clase. Para lograr esto, establezca la propiedad [slides_as_images](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/#properties) de [PptxSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/) clase a 'true' como se muestra en el siguiente ejemplo de código. +En caso de que necesite convertir un PDF buscable a PPTX como imágenes en lugar de texto seleccionable, Aspose.PDF ofrece esa característica a través de [PptxSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/) clase. Para lograr esto, establezca la propiedad [diapositivas_como_imágenes](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/#properties) de [PptxSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/) clase a 'true' como se muestra en el siguiente ejemplo de código. ```python +import aspose.pdf as ap +from os import path +import sys - from os import path - import aspose.pdf as apdf - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) +def convert_PDF_to_PPTX_slides_as_images(infile, outfile): - document = apdf.Document(path_infile) - save_options = apdf.PptxSaveOptions() + document = ap.Document(infile) + save_options = ap.PptxSaveOptions() save_options.slides_as_images = True - document.save(path_outfile, save_options) - - print(infile + " converted into " + outfile) + document.save(outfile, save_options) ``` -## Convertir PDF a PPTX con Resolución de Imagen Personalizada +## Convertir PDF a PPTX con resolución de imagen personalizada Este método convierte un documento PDF en un archivo PowerPoint (PPTX) mientras establece una resolución de imagen personalizada (300 DPI) para una mejor calidad. -1. Cargue el PDF en un objeto 'ap.Document' . -1. Cree una instancia de 'PptxSaveOptions' . -1. Establezca la propiedad 'image_resolution' a 300 DPI para una renderización de alta calidad. +1. Cargue el PDF en un objeto 'ap.Document' object. +1. Cree una instancia de 'PptxSaveOptions'. +1. Establezca la propiedad 'image_resolution' en 300 DPI para una renderización de alta calidad. 1. Guarde el PDF como un archivo PPTX usando las opciones de guardado definidas. ```python +import aspose.pdf as ap +from os import path +import sys - from os import path - import aspose.pdf as apdf - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = apdf.Document(path_infile) - save_options = apdf.PptxSaveOptions() +def convert_PDF_to_PPTX_image_resolution(infile, outfile): + document = ap.Document(infile) + save_options = ap.PptxSaveOptions() save_options.image_resolution = 300 - document.save(path_outfile, save_options) - - print(infile + " converted into " + outfile) + document.save(outfile, save_options) ``` + +## Conversiones relacionadas + +- [Convertir PDF a Word](/pdf/es/python-net/convert-pdf-to-word/) para la salida de documentos editables en lugar de diapositivas. +- [Convertir PDF a Excel](/pdf/es/python-net/convert-pdf-to-excel/) cuando el PDF de origen contiene datos empresariales con muchas tablas. +- [Convertir PDF a HTML](/pdf/es/python-net/convert-pdf-to-html/) para flujos de trabajo de publicación listos para el navegador. \ No newline at end of file diff --git a/es/python-net/converting/convert-pdf-to-word/_index.md b/es/python-net/converting/convert-pdf-to-word/_index.md index 890b25829..64b7f8857 100644 --- a/es/python-net/converting/convert-pdf-to-word/_index.md +++ b/es/python-net/converting/convert-pdf-to-word/_index.md @@ -1,46 +1,45 @@ --- -title: Convertir PDF a documentos Microsoft Word en Python +title: Convertir PDF a Word en Python linktitle: Convertir PDF a Word type: docs weight: 10 url: /es/python-net/convert-pdf-to-word/ -lastmod: "2025-09-27" -description: Aprenda cómo convertir documentos PDF al formato Word en Python usando Aspose.PDF para una edición de documentos sencilla. +lastmod: "2026-05-11" +description: Aprenda cómo convertir archivos PDF a DOC y DOCX en Python con Aspose.PDF for Python via .NET para facilitar la edición y reutilización de documentos. sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true -AlternativeHeadline: Convertir PDF a Word DOC y DOCX -Abstract: > - Esta página muestra cómo convertir documentos PDF a formatos Word DOC y DOCX con Aspose.PDF for Python via .NET. También explica cómo usar DocSaveOptions para ajustar el reconocimiento y obtener documentos editables con mejor estructura. +TechArticle: true +AlternativeHeadline: Cómo convertir PDF a Word en Python +Abstract: Este artículo ofrece una guía completa sobre la conversión de archivos PDF a formatos de Microsoft Word (DOC y DOCX) utilizando Python, específicamente con la biblioteca Aspose.PDF. Describe las ventajas de convertir PDFs a documentos Word editables, lo que permite una manipulación más fácil del contenido, como texto, tablas e imágenes. El artículo detalla el proceso de conversión de PDF a DOC (formato Word 97-2003) y DOCX, con fragmentos de código que demuestran estas conversiones mediante Python. El proceso implica crear un objeto `Document` a partir del PDF y guardarlo en el formato deseado utilizando el método `save()` y la enumeración `SaveFormat`. Además, introduce la clase `DocSaveOptions`, que permite una mayor personalización del proceso de conversión, como especificar modos de reconocimiento. El artículo también destaca las aplicaciones en línea proporcionadas por Aspose.PDF para probar la calidad y funcionalidad de la conversión. El contenido incluye una visión estructurada y enlaces a las secciones correspondientes para cada formato. --- ## Convertir PDF a DOC -Una de las funciones más populares es la conversión de PDF a Microsoft Word DOC, lo que facilita la gestión de contenido. **Aspose.PDF for Python via .NET** le permite convertir archivos PDF no solo a DOC sino también a formato DOCX, de manera fácil y eficiente. +Una de las características más populares es la conversión de PDF a Microsoft Word DOC, lo que hace que la gestión de contenidos sea más fácil. **Aspose.PDF for Python via .NET** le permite convertir archivos PDF no solo a DOC sino también al formato DOCX, de manera fácil y eficiente. -El [DocSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/docsaveoptions/) la clase proporciona numerosas propiedades que mejoran el proceso de conversión de archivos PDF a formato DOC. Entre estas propiedades, Mode le permite especificar el modo de reconocimiento para el contenido PDF. Puede especificar cualquier valor de la enumeración RecognitionMode para esta propiedad. Cada uno de estos valores tiene beneficios y limitaciones específicos: +Utilice la conversión a Word cuando necesite revisar texto, reutilizar contenido en flujos de trabajo de oficina, o trasladar contenido PDF a documentos editables DOC o DOCX. + +El [DocSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/docsaveoptions/) La clase proporciona numerosas propiedades que mejoran el proceso de conversión de archivos PDF a formato DOC. Entre estas propiedades, Mode le permite especificar el modo de reconocimiento para el contenido PDF. Puede especificar cualquier valor de la enumeración RecognitionMode para esta propiedad. Cada uno de estos valores tiene beneficios y limitaciones específicas: Pasos: Convertir PDF a DOC en Python -1. Cargue el PDF en un objeto 'ap.Document'. -1. Crea una instancia de 'DocSaveOptions'. -1. Establece la propiedad format a 'DocFormat.DOC' para asegurar que la salida esté en formato .doc (formato Word antiguo). -1. Guarda el PDF como un documento Word usando las opciones de guardado especificadas. +1. Cargue el PDF en un objeto 'ap.Document' object. +1. Cree una instancia de 'DocSaveOptions'. +1. Establezca la propiedad format a 'DocFormat.DOC' para garantizar que la salida esté en formato .doc (formato Word antiguo). +1. Guarde el PDF como un documento Word usando las opciones de guardado especificadas. 1. Imprime un mensaje de confirmación. ```python +from os import path +import aspose.pdf as ap +import sys - from os import path - import aspose.pdf as apdf - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = apdf.Document(path_infile) - save_options = apdf.DocSaveOptions() - save_options.format = apdf.DocSaveOptions.DocFormat.DOC - document.save(path_outfile, save_options) +def convert_PDF_to_DOC(infile, outfile): + document = ap.Document(infile) + save_options = ap.DocSaveOptions() + save_options.format = ap.DocSaveOptions.DocFormat.DOC + document.save(outfile, save_options) print(infile + " converted into " + outfile) ``` @@ -48,48 +47,67 @@ Pasos: Convertir PDF a DOC en Python {{% alert color="success" %}} **Intenta convertir PDF a DOC en línea** -Aspose.PDF for Python te presenta una aplicación gratuita en línea ["PDF a DOC"](https://products.aspose.app/pdf/conversion/pdf-to-doc), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for Python le presenta una aplicación en línea ["PDF a DOC"](https://products.aspose.app/pdf/conversion/pdf-to-doc), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Convertir PDF a DOC](/pdf/net/images/pdf_to_word.png)](https://products.aspose.app/pdf/conversion/pdf-to-doc) +[![Convertir PDF a DOC](/pdf/es/net/images/pdf_to_word.png)](https://products.aspose.app/pdf/conversion/pdf-to-doc) {{% /alert %}} ## Convertir PDF a DOCX -Aspose.PDF for Python API le permite leer y convertir documentos PDF a DOCX usando Python a través de .NET. DOCX es un formato bien conocido para documentos de Microsoft Word cuya estructura se cambió de binario simple a una combinación de archivos XML y binarios. Los archivos DOCX pueden abrirse con Word 2007 y versiones posteriores, pero no con las versiones anteriores de MS Word que admiten extensiones de archivo DOC. +Aspose.PDF for Python API le permite leer y convertir documentos PDF a DOCX usando Python a través de .NET. DOCX es un formato bien conocido para documentos de Microsoft Word cuya estructura cambió de binario simple a una combinación de archivos XML y binarios. Los archivos DOCX pueden abrirse con Word 2007 y versiones posteriores, pero no con las versiones anteriores de MS Word que admiten extensiones de archivo DOC. -El siguiente fragmento de código Python muestra el proceso de conversión de un archivo PDF al formato DOCX. +El siguiente fragmento de código Python muestra el proceso de convertir un archivo PDF a formato DOCX. Pasos: Convertir PDF a DOCX en Python 1. Cargue el PDF de origen usando 'ap.Document'. -1. Cree una instancia de 'DocSaveOptions'. -1. Establezca la propiedad format a 'DocFormat.DOC_X' para generar un archivo .docx (formato Word moderno). +1. Crear una instancia de 'DocSaveOptions'. +1. Establezca la propiedad format en 'DocFormat.DOC_X' para generar un archivo .docx (formato Word moderno). 1. Guarde el PDF como un archivo DOCX con las opciones de guardado configuradas. 1. Imprima un mensaje de confirmación después de la conversión. ```python +from os import path +import aspose.pdf as ap +import sys + +def convert_PDF_to_DOCX(infile, outfile): + document = ap.Document(infile) + save_options = ap.DocSaveOptions() + save_options.format = ap.DocSaveOptions.DocFormat.DOC_X + document.save(outfile, save_options) +``` - from os import path - import aspose.pdf as apdf - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) +## Convertir PDF a DOCX con Reconocimiento de Diseño Avanzado - document = apdf.Document(path_infile) - save_options = apdf.DocSaveOptions() - save_options.format = apdf.DocSaveOptions.DocFormat.DOC_X - document.save(path_outfile, save_options) +Convertir un documento PDF a un archivo DOCX (Word) usando Python y Aspose.PDF con configuraciones de reconocimiento avanzadas. Utiliza el modo de flujo mejorado para preservar la estructura del documento, haciendo que la salida sea más editable y más cercana al diseño original. - print(infile + " converted into " + outfile) +```python +from os import path +import aspose.pdf as ap +import sys + +def convert_PDF_to_DOCX_advanced(infile, outfile): + document = ap.Document(infile) + save_options = ap.DocSaveOptions() + save_options.format = ap.DocSaveOptions.DocFormat.DOC_X + save_options.mode = ap.DocSaveOptions.RecognitionMode.ENHANCED_FLOW + document.save(outfile, save_options) ``` -El [DocSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/docsaveoptions/) class tiene una propiedad llamada Format que brinda la capacidad de especificar el formato del documento resultante, es decir, DOC o DOCX. Para convertir un archivo PDF a formato DOCX, pase el valor Docx de la enumeración DocSaveOptions.DocFormat. +El [DocSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/docsaveoptions/) class tiene una propiedad llamada Format que brinda la capacidad de especificar el formato del documento resultante, es decir, DOC o DOCX. Para convertir un archivo PDF al formato DOCX, pase el valor Docx del enumerado DocSaveOptions.DocFormat. {{% alert color="warning" %}} **Intenta convertir PDF a DOCX en línea** -Aspose.PDF for Python te presenta una aplicación gratuita en línea ["PDF a Word"](https://products.aspose.app/pdf/conversion/pdf-to-docx), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. +Aspose.PDF for Python le presenta una aplicación en línea ["PDF a Word"](https://products.aspose.app/pdf/conversion/pdf-to-docx), donde puede intentar investigar la funcionalidad y la calidad con la que funciona. -[![Aplicación gratuita Aspose.PDF Conversión PDF a Word](/pdf/net/images/pdf_to_word.png)](https://products.aspose.app/pdf/conversion/pdf-to-docx) +[![Aspose.PDF Conversión PDF a Word App](/pdf/es/net/images/pdf_to_word.png)](https://products.aspose.app/pdf/conversion/pdf-to-docx) {{% /alert %}} + +## Conversiones relacionadas + +- [Convertir PDF a Excel](/pdf/es/python-net/convert-pdf-to-excel/) para exportaciones orientadas a hojas de cálculo. +- [Convertir PDF a PowerPoint](/pdf/es/python-net/convert-pdf-to-powerpoint/) cuando necesitas diapositivas de presentación en lugar de salida de procesamiento de texto. +- [Convertir PDF a HTML](/pdf/es/python-net/convert-pdf-to-html/) para la publicación web y flujos de trabajo de contenido basados en el navegador. diff --git a/es/python-net/converting/convert-pdfx-to-pdf/_index.md b/es/python-net/converting/convert-pdfx-to-pdf/_index.md index cd58f236e..ebe6a6b24 100644 --- a/es/python-net/converting/convert-pdfx-to-pdf/_index.md +++ b/es/python-net/converting/convert-pdfx-to-pdf/_index.md @@ -1,62 +1,69 @@ --- -title: Convertir PDF/x a formatos PDF en Python -linktitle: Convertir PDF/x a formatos PDF +title: Convertir PDF/A y PDF/UA a PDF en Python +linktitle: Convertir PDF/A y PDF/UA a PDF type: docs weight: 120 url: /es/python-net/convert-pdf_x-to-pdf/ -lastmod: "2025-09-27" -description: Este tema le muestra cómo convertir PDF/x a formatos PDF usando Aspose.PDF for Python via .NET. +lastmod: "2026-05-11" +description: Aprenda cómo eliminar el cumplimiento de PDF/A y PDF/UA de archivos PDF en Python con Aspose.PDF for Python via .NET y guardarlos como documentos PDF estándar. sitemap: changefreq: "monthly" priority: 0.8 -TechArticle: true -AlternativeHeadline: Convertir PDF/A y PDF/UA a PDF estándar -Abstract: > - Esta guía explica cómo convertir documentos PDF/A y PDF/UA a archivos PDF estándar con Aspose.PDF for Python via .NET. Incluye ejemplos básicos para abrir archivos compatibles y guardarlos nuevamente en formato PDF regular. +TechArticle: true +AlternativeHeadline: Cómo convertir PDF/A y PDF/UA a PDF estándar en Python +Abstract: Este artículo explica cómo eliminar el cumplimiento de PDF/A y PDF/UA de documentos PDF basados en estándares mediante Aspose.PDF for Python via .NET. Cubre escenarios en los que puede necesitar un PDF estándar en lugar de un archivo de archivo o con restricciones de accesibilidad, y muestra cómo guardar el resultado después de eliminar los metadatos y restricciones de cumplimiento. --- -**PDF/x a formato PDF significa la capacidad de convertir PDF/UA y PDF/A a archivo PDF.** +Utilice esta página cuando necesite convertir un PDF basado en estándares, como PDF/A o PDF/UA, de nuevo a un documento PDF normal para edición, procesamiento o redistribución posteriores. + +Los PDFs que cumplen con los estándares son útiles para flujos de trabajo de archivo, impresión y accesibilidad, pero en algunos casos puede que necesite eliminar ese cumplimiento antes de integrar el archivo en otros sistemas o canalizaciones. Aspose.PDF for Python via .NET le permite hacerlo programáticamente y luego guardar el resultado como un archivo PDF estándar. ## Convertir PDF/A a PDF +Este ejemplo elimina los metadatos y restricciones de cumplimiento de PDF/A de un PDF para que el documento pueda guardarse nuevamente como un archivo PDF normal. + 1. Cargue el documento PDF usando 'ap.Document'. -1. Llame a 'remove_pdfa_compliance()' para eliminar todas las configuraciones de cumplimiento y metadatos relacionados con PDF/A. +1. Llame a 'remove_pdfa_compliance()' para eliminar todas las configuraciones y metadatos de cumplimiento relacionados con PDF/A. 1. Guarde el PDF resultante en la ruta de salida. ```python +import aspose.pdf as ap +from os import path +import sys - from os import path - import aspose.pdf as ap - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = ap.Document(path_infile) +def convert_PDFA_to_PDF(infile, outfile): + document = ap.Document(infile) document.remove_pdfa_compliance() - document.save(path_outfile) - - print(infile + " converted into " + outfile) + document.save(outfile) ``` -## Eliminando el cumplimiento PDF/UA +## Eliminando cumplimiento PDF/UA -Esta función demuestra un proceso de conversión de dos pasos: primero elimina el cumplimiento PDF/UA (Accesibilidad Universal), y luego convierte el PDF resultante al formato PDF/A-1B con etiquetado automático para accesibilidad y estructura semántica. +Este ejemplo demuestra cómo eliminar el cumplimiento relacionado con PDF/UA para que el documento pueda guardarse como un PDF estándar para flujos de trabajo que no son específicos de accesibilidad. 1. Cargue el documento PDF usando 'ap.Document()'. 1. Llame a 'document.remove_pdfa_compliance()' para eliminar cualquier restricción o configuración de cumplimiento PDF/A. 1. Guarde el PDF modificado en 'path_outfile'. ```python +import aspose.pdf as ap +from os import path +import sys + +def convert_PDFUA_to_PDF(infile, outfile): + document = ap.Document(infile) + document.remove_pdf_ua_compliance() + document.save(outfile) +``` - from os import path - import aspose.pdf as ap +## Cuándo usar este flujo de trabajo - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) +- Elimine la configuración de cumplimiento antes de enviar un documento a una cadena de herramientas que no requiera restricciones de PDF/A o PDF/UA. +- Simplifique el procesamiento de documentos posterior cuando los metadatos de archivo o de accesibilidad ya no sean necesarios. +- Normaliza los PDFs de entrada antes de exportarlos a otros formatos. - document = ap.Document(path_infile) - document.remove_pdfa_compliance() - document.save(path_outfile) +## Conversiones relacionadas - print(infile + " converted into " + outfile) -``` +- [Convertir PDF a PDF/A, PDF/E y PDF/X](/pdf/es/python-net/convert-pdf-to-pdf_x/) si necesitas el flujo de trabajo opuesto y deseas crear PDFs compatibles con estándares. +- [Convertir PDF a Word](/pdf/es/python-net/convert-pdf-to-word/) para una salida de documento editable después de eliminar las restricciones de cumplimiento. +- [Convertir PDF a HTML](/pdf/es/python-net/convert-pdf-to-html/) para una salida compatible con navegadores a partir de archivos PDF estándar. diff --git a/es/python-net/faq/_index.md b/es/python-net/faq/_index.md new file mode 100644 index 000000000..38983b1f2 --- /dev/null +++ b/es/python-net/faq/_index.md @@ -0,0 +1,16 @@ +--- +title: Preguntas frecuentes +linktitle: Preguntas frecuentes +type: docs +weight: 140 +url: /es/python-net/faq/ +description: Aquí puedes encontrar respuestas a las Preguntas frecuentes para la biblioteca Aspose.PDF for Python via .NET. +lastmod: "2026-05-11" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: false +--- + +

              ¿Qué formatos admite Aspose.PDF for Python via .NET?

              Aspose.PDF for Python via .NET admite formatos de archivo populares como PDF, TXT, HTML, PCL, XML, XPS, EPUB, TEX y formatos de imagen. Para obtener más detalles, visite la página .

              ¿Qué funciones de IA admite Aspose.PDF for Python via .NET?

              Sí, la biblioteca tiene clientes API integrados para OpenAI y Llama. Permiten realizar solicitudes API y crear copilotos de IA. Puedes encontrar ejemplos en página.

              ¿Cuántos archivos puedo combinar en PDF de una vez?

              Puedes combinar una cantidad ilimitada de archivos en PDF de una sola vez.

              ¿Cómo insertar una imagen en PDF?

              Para insertar una imagen en un PDF usando Aspose.PDF for Python via .NET, puedes encontrar .

              ¿Cómo editar el texto en PDF?

              Para editar el texto en un PDF usando Aspose.PDF for Python via .NET, puedes encontrar .

              ¿Cómo agregar números de página al archivo PDF?

              Para agregar números de página a un PDF usando Aspose.PDF for Python via .NET, puedes encontrar .

              ¿Cómo crear un fondo para documentos PDF?

              Para crear un fondo para un documento PDF usando Aspose.PDF for Python via .NET, puedes encontrar .

              ¿Cómo asegurar el documento PDF?

              Para proteger un documento PDF usando Aspose.PDF for Python via .NET, puedes encontrar .

              ¿Cómo agregar texto en negrita en una anotación resaltada en una página PDF?

              Para agregar texto en negrita en una anotación resaltada, puedes encontrar .

              ¿Cómo validar un PDF etiquetado?

              Para validar un documento PDF etiquetado, puedes encontrar .

              ¿Cómo implementar búsqueda con expresiones regulares para TextFragmentAbsorber?

              Para usar expresiones regulares con el `TextFragmentAbsorber` clase en Aspose.PDF for Python via .NET, puedes encontrar .

              ¿Cómo crear un documento PDF/A válido a menos que se proporcione la fuente faltante o su sustitución?

              Para crear un documento PDF/A válido, puedes encontrar .

              Veo errores en el registro de conversión PDF/A. ¿Significa eso que el documento no se convirtió con éxito?

              No, Aspose.PDF registra todos los problemas que encontró, incluidos los que fueron corregidos automáticamente. Si todas las entradas en el registro están marcadas como Convertable=True, todos los problemas fueron solucionados y el documento se convirtió con éxito. Solo las entradas con Convertable=False indican el error de conversión.

              ¿Cómo crear un documento PDF/A válido si el registro de conversión contiene errores de “Font not embedded”?

              Si un registro de conversión PDF/A contiene entradas de error “Font not embedded” marcadas como Convertable=False, significa que el documento original incluye fuentes que faltan tanto en el propio documento como en la máquina donde se realiza la conversión. Verifique para aprender cómo reemplazar fuentes faltantes.

              ¿Por qué Aspose.PDF no convierte un documento a PDF/A con la opción ConvertErrorAction.None?

              La opción ConvertErrorAction.None evita que Aspose.PDF elimine elementos del documento, incluso si esos elementos están prohibidos por la norma PDF/A. Como resultado, puede ser imposible convertir un documento usando el modo ConvertErrorAction.None. Utilice esta opción cuando no desee que Aspose.PDF elimine automáticamente los elementos prohibidos del documento, especialmente si planea revisar el registro de conversión y corregir manualmente los problemas del documento. Otro escenario para usar esta opción es cuando su documento ya cumple mayormente o completamente con PDF/A, y desea evitar cambios innecesarios. Las versiones de PDF/A más permisivas (p. ej., PDF/A-2 o PDF/A-3) tienen más probabilidades de convertirse con éxito usando la opción ConvertErrorAction.None. Sin embargo, para las normas PDF/A-1a y PDF/A-1b, se recomienda generalmente usar la opción ConvertErrorAction.Delete.

              ¿Aspose.PDF for Python via .NET soporta Linux?

              Sí, Aspose.PDF for Python via .NET admite ejecutarse en entornos Linux. Puede usar la versión Python via .NET Core o posterior, que es multiplataforma y puede usarse en Windows, macOS y Linux.

              ¿Dónde están sus ejemplos de Python via .NET?

              Puedes comprobar todos ellos en .

              + diff --git a/es/python-net/get-started/_index.md b/es/python-net/get-started/_index.md index 03a848fc0..3eb595909 100644 --- a/es/python-net/get-started/_index.md +++ b/es/python-net/get-started/_index.md @@ -4,48 +4,48 @@ linktitle: Comenzar type: docs weight: 30 url: /es/python-net/get-started/ -description: Esta sección describe los principios básicos del trabajo de Aspose.PDF para Python a través de .NET. La biblioteca de Python admite una amplia variedad de funciones. +description: Aprenda cómo comenzar con Aspose.PDF for Python via .NET para crear, editar, convertir, validar y extraer contenido de documentos PDF. is_node: true -lastmod: "2022-12-20" +lastmod: "2026-05-11" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 --- ## ¿Qué es un archivo PDF? -PDF fue creado por Adobe en la década de 1990 para lograr dos cosas. La primera es que deberías poder abrir los documentos en cualquier hardware o sistema operativo, sin necesidad de tener la aplicación utilizada para crearlos; todo lo que necesitas es un lector de PDF, y hoy en día la mayoría de los navegadores web cumplen ese requisito. La segunda es que donde quiera que abras un PDF, el diseño del documento debería verse igual. +PDF fue creado por Adobe en la década de 1990 para lograr dos objetivos. El primero es que deberías poder abrir los documentos en cualquier hardware o sistema operativo, sin necesidad de tener la aplicación utilizada para crearlos—todo lo que necesitas es un lector de PDF, y hoy en día la mayoría de los navegadores web cumplen con ese requisito. El segundo es que, donde sea que abras un PDF, el diseño del documento debe verse igual. -Sin embargo, no basta con solo abrir tu documento. Al trabajar con PDF, te enfrentarás a la necesidad de crear dicho documento de nuevo, editarlo o convertirlo al formato que necesites. +Aspose.PDF for Python via .NET le ayuda a ir más allá de simplemente abrir archivos PDF. Puede usar la biblioteca para crear PDFs desde cero, editar documentos existentes, extraer contenido, validar el cumplimiento de normas y convertir PDFs a otros formatos en aplicaciones Python. -## ¿Por qué usar Aspose.PDF para Python a través de .NET? +## ¿Por qué usar Aspose.PDF for Python via .NET? -Usar Aspose.PDF para Python a través de .NET en tu proyecto te ofrece los siguientes beneficios: +Usar Aspose.PDF for Python via .NET en su proyecto le brinda los siguientes beneficios: -- amplia variedad de funciones -- basado en Aspose.PDF para .NET -- conveniencia y facilidad de uso +- Una amplia gama de funciones de procesamiento de PDF +- Acceso al probado motor Aspose.PDF for .NET desde Python +- Una API práctica para tareas comunes de creación, edición, análisis y conversión de documentos -## Amplia variedad de funciones +## Tareas comunes de PDF que puede automatizar -- Soporta la mayoría de los estándares PDF establecidos y especificaciones PDF. -- [Agregar, buscar, extraer y reemplazar texto en archivos PDF](). -- [Agregar/eliminar, extraer y reemplazar imágenes](). -- [Insertar, eliminar, dividir páginas PDF](). -- [Establecer y obtener metadatos XMP](). -- [Validar (PDF/A-1a, PDF/A-1b)](). -- Trabajar con [marcadores](), [anotaciones](), [formularios PDF](), [sellos](), [marcas de agua]() y más. +- Compatibilidad con estándares y especificaciones de PDF de uso amplio +- [Agregar, buscar, extraer y reemplazar texto en archivos PDF](/pdf/es/python-net/working-with-text/) +- [Agregar, eliminar, extraer y reemplazar imágenes](/pdf/es/python-net/working-with-images/) +- [Insertar, eliminar, extraer y gestionar páginas PDF](/pdf/es/python-net/working-with-pages/) +- [Establecer y guardar metadatos XMP](/pdf/es/python-net/save-metadata-with-xmp/) +- [Validar documentos PDF para cumplimiento PDF/A-1a y PDF/A-1b](/pdf/es/python-net/manipulate-pdf-document/) +- Trabajar con [marcadores](/pdf/es/python-net/bookmarks/), [anotaciones](/pdf/es/python-net/annotations/), [formularios PDF](/pdf/es/python-net/working-with-forms/), [sellos](/pdf/es/python-net/stamping/), y [marcas de agua](/pdf/es/python-net/add-watermarks/) -## Funciones de Conversión +## Funciones de conversión de documentos - [Convertir PDF a Word, Excel y PowerPoint](/pdf/es/python-net/convert-pdf-to-word/). - [Convertir PDF a formatos de imágenes](/pdf/es/python-net/convert-pdf-to-images-format/). -- [Convertir archivo PDF a formato HTML y viceversa](/pdf/es//python-net/convert-pdf-to-html/). -- [Convertir PDF a EPUB, Texto, XPS, etc.](/pdf/es/python-net/convert-pdf-to-other-files/). -- Convertir EPUB, Markdown, Texto, XPS, PostScript, XML, LaTex a PDF +- [Convertir archivos PDF a HTML y convertir HTML a PDF](/pdf/es/python-net/convert-pdf-to-html/). +- [Convertir PDF a EPUB, Texto, XPS, etc](/pdf/es/python-net/convert-pdf-to-other-files/). +- [Convertir EPUB, Markdown, Texto, XPS, PostScript, XML, LaTex a PDF](/pdf/es/python-net/convert-other-files-to-pdf/) +## Comience con estos tutoriales -### Aprende más sobre: +- ["Hello, World" ejemplo de Python](/pdf/es/python-net/hello-world-example/) +- [Cree un documento PDF complejo](/pdf/es/python-net/complex-pdf-example/) -- [Ejemplo "Hola, Mundo" en Python](/pdf/es/python-net/hello-world-example/) -- [PDF Complejo](/pdf/es/python-net/complex-pdf-example/) \ No newline at end of file diff --git a/es/python-net/get-started/complex-pdf/_index.md b/es/python-net/get-started/complex-pdf/_index.md index b84c22667..292655d29 100644 --- a/es/python-net/get-started/complex-pdf/_index.md +++ b/es/python-net/get-started/complex-pdf/_index.md @@ -4,59 +4,65 @@ linktitle: Creando un PDF complejo type: docs weight: 30 url: /es/python-net/complex-pdf-example/ -description: Aspose.PDF para Python a través de .NET te permite crear documentos más complejos que contienen imágenes, fragmentos de texto y tablas en un solo documento. -lastmod: "2022-12-22" +description: Aspose.PDF for Python via .NET le permite crear documentos más complejos que contienen imágenes, fragmentos de texto y tablas en un solo documento. +lastmod: "2025-02-27" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Crear un PDF complejo usando Python +Abstract: 'Este artículo amplía el proceso básico de creación de PDF demostrado en el ejemplo "Hello, World" al ilustrar cómo crear un documento PDF más complejo usando Python y Aspose.PDF. El documento de ejemplo se desarrolla para una empresa ficticia de servicio de ferris de pasajeros e incluye una imagen, dos fragmentos de texto (un encabezado y un párrafo) y una tabla. El proceso implica varios pasos: instanciar un objeto `Document` para crear un PDF vacío, agregar una `Page` y luego insertar una `Image` en la página. Se crea un `TextFragment` para el encabezado utilizando la fuente Arial con un tamaño de 24 pt y alineación centrada, que luego se añade a los párrafos de la página. Se añade un segundo `TextFragment` para la descripción, usando la fuente Times New Roman con un tamaño de 14 pt y alineación izquierda. A continuación, se crea una tabla y se formatea con anchos de columna específicos, bordes y relleno. La tabla incluye una fila de encabezado con celdas resaltadas y múltiples filas de datos generadas mediante iteración' --- -El ejemplo de [Hola, Mundo](/pdf/es/python-net/hello-world-example/) mostró pasos simples para crear un documento PDF usando Python y Aspose.PDF. En este artículo, echaremos un vistazo a la creación de un documento más complejo con Aspose.PDF para Python. Como ejemplo, tomaremos un documento de una empresa ficticia que opera servicios de ferry de pasajeros. Nuestro documento contendrá una imagen, dos fragmentos de texto (encabezado y párrafo), y una tabla. +El [Hola, Mundo](/pdf/es/python-net/hello-world-example/) El ejemplo mostró pasos simples para crear un documento PDF usando Python y Aspose.PDF. En este artículo, veremos la creación de un documento más complejo con Aspose.PDF for Python. Como ejemplo, tomaremos un documento de una empresa ficticia que opera servicios de ferris de pasajeros. Nuestro documento contendrá una imagen, dos fragmentos de texto (encabezado y párrafo) y una tabla. -Si creamos un documento desde cero, debemos seguir ciertos pasos: +Si creamos un documento desde cero, necesitamos seguir ciertos pasos: -1. Instanciar un objeto [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). En este paso crearemos un documento PDF vacío con algunos metadatos pero sin páginas. -1. Añadir una [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) al objeto documento. Así que, ahora nuestro documento tendrá una página. -1. Añadir una [Image](https://reference.aspose.com/pdf/python-net/aspose.pdf/image/) a la Página. -1. Crear un [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf/texfragment/) para el encabezado. Para el encabezado usaremos la fuente Arial con tamaño de fuente 24pt y alineación centrada. -1. Añadir el encabezado a los [paragraphs](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) de la página. -1. Crear un [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf/texfragment/) para la descripción. Para la descripción usaremos la fuente Arial con tamaño de fuente 24pt y alineación centrada. -1. Añadir (descripción) a los Párrafos de la página. -1. Crear una tabla, añadir propiedades de la tabla. - -1. Añadir (table) a la página [paragraphs](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties). +1. Instanciar un [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) objeto. En este paso crearemos un documento PDF vacío con algunos metadatos pero sin páginas. +1. Agregar un [Página](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) al objeto del documento. Así, ahora nuestro documento tendrá una página. +1. Agregar un [Imagen](https://reference.aspose.com/pdf/python-net/aspose.pdf/image/) a la página. +1. Crear un [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf/texfragment/) para el encabezado. Para el encabezado utilizaremos la fuente Arial con tamaño de fuente de 24 pt y alineación centrada. +1. Añadir encabezado a la página [párrafos](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties). +1. Crear un [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf/texfragment/) para la descripción. Para la descripción utilizaremos la fuente Arial con tamaño de fuente de 24 pt y alineación centrada. +1. Añadir descripción a la página Párrafos. +1. Crear y dar estilo a la tabla. Establecer ancho de columna, bordes, relleno y fuente. +1. Agregar tabla a la página [párrafos](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties). 1. Guardar un documento "Complex.pdf". ```python +from datetime import timedelta +import aspose.pdf as ap + - import aspose.pdf as ap +def run_complex(self): - # Inicializar objeto de documento + # Initialize document object document = ap.Document() - # Añadir página + # Add page page = document.pages.add() - # Añadir imagen - page.add_image(image_file, ap.Rectangle(20, 730, 120, 830, True)) + # Add image + imageFileName = self.data_dir + "logo.png" + page.add_image(imageFileName, ap.Rectangle(20, 730, 120, 830, True)) - # Añadir encabezado - header = ap.text.TextFragment("Nuevas rutas de ferry en otoño 2020") + # Add Header + header = ap.text.TextFragment("New ferry routes in Fall 2029") header.text_state.font = ap.text.FontRepository.find_font("Arial") header.text_state.font_size = 24 header.horizontal_alignment = ap.HorizontalAlignment.CENTER header.position = ap.text.Position(130, 720) page.paragraphs.add(header) - # Añadir descripción - descriptionText = "Los visitantes deben comprar boletos en línea y los boletos están limitados a 5,000 por día. \ - El servicio de ferry está operando a media capacidad y en un horario reducido. Espere filas." + # Add description + descriptionText = "Visitors must buy tickets online and tickets are limited to 5,000 per day. \ + Ferry service is operating at half capacity and on a reduced schedule. Expect lineups." description = ap.text.TextFragment(descriptionText) description.text_state.font = ap.text.FontRepository.find_font("Times New Roman") description.text_state.font_size = 14 description.horizontal_alignment = ap.HorizontalAlignment.LEFT page.paragraphs.add(description) - # Añadir tabla + # Add table table = ap.Table() table.column_widths = "200" @@ -67,13 +73,15 @@ Si creamos un documento desde cero, debemos seguir ciertos pasos: table.default_cell_text_state.font = ap.text.FontRepository.find_font("Helvetica") headerRow = table.rows.add() - headerRow.cells.add("Sale de la ciudad") - headerRow.cells.add("Sale de la isla") + headerRow.cells.add("Departs City") + headerRow.cells.add("Departs Island") i = 0 while i < headerRow.cells.count: headerRow.cells[i].background_color = ap.Color.gray - headerRow.cells[i].default_cell_text_state.foreground_color = ap.Color.white_smoke + headerRow.cells[ + i + ].default_cell_text_state.foreground_color = ap.Color.white_smoke i += 1 time = timedelta(hours=6, minutes=0) @@ -89,5 +97,5 @@ Si creamos un documento desde cero, debemos seguir ciertos pasos: page.paragraphs.add(table) - document.save(output_pdf) -``` \ No newline at end of file + document.save(self.data_dir + "Complex.pdf") +``` diff --git a/es/python-net/get-started/hello-world-example/_index.md b/es/python-net/get-started/hello-world-example/_index.md index ac79475b5..055afb786 100644 --- a/es/python-net/get-started/hello-world-example/_index.md +++ b/es/python-net/get-started/hello-world-example/_index.md @@ -1,42 +1,59 @@ --- -title: Ejemplo de Hola Mundo usando Python -linktitle: Ejemplo de Hola Mundo +title: Ejemplo de Hello World usando Python +linktitle: Ejemplo Hello World type: docs weight: 20 url: /es/python-net/hello-world-example/ -description: Esta muestra demuestra cómo crear un documento PDF simple con el texto Hola Mundo usando Aspose.PDF para Python a través de .NET. -lastmod: "2022-12-22" +description: Este ejemplo muestra cómo crear un documento PDF simple con el texto Hello World usando Aspose.PDF for Python via .NET. +lastmod: "2025-02-27" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Ejemplo Hello World vía Python +Abstract: Este artículo proporciona un ejemplo Hello World usando la biblioteca Aspose.PDF for Python via .NET para crear un documento PDF. El ejemplo muestra los pasos básicos de uso de la API Aspose.PDF generando un PDF con el texto "Hello World!". El proceso implica instanciar un objeto `Document`, agregar un `Page`, crear un objeto `TextFragment`, establecer propiedades de texto como el tamaño y color de la fuente, y usar un `TextBuilder` para añadir el texto a la página. El PDF resultante se guarda como "HelloWorld_out.pdf". El artículo incluye un fragmento de código Python completo que ilustra estos pasos, sirviendo como una guía introductoria al uso de la biblioteca. --- -Un ejemplo de "Hola Mundo" muestra la sintaxis más simple y el programa más sencillo en cualquier lenguaje de programación dado. Los desarrolladores son introducidos a la sintaxis básica del lenguaje de programación aprendiendo cómo imprimir "Hola Mundo" en la pantalla del dispositivo. Por lo tanto, tradicionalmente comenzaremos nuestro conocimiento de nuestra biblioteca desde ahí. +Un ejemplo "Hello World" muestra la sintaxis más simple y el programa más sencillo en cualquier lenguaje de programación. A los desarrolladores se les introduce la sintaxis básica del lenguaje aprendiendo a imprimir "Hello World" en la pantalla del dispositivo. Por lo tanto, tradicionalmente comenzaremos nuestro acercamiento a la biblioteca con él. -En este artículo, estamos creando un documento PDF que contiene el texto "Hola Mundo!". Después de instalar **Aspose.PDF para Python a través de .NET** en tu entorno, puedes ejecutar el siguiente ejemplo de código para ver cómo funciona la API de Aspose.PDF. +En este artículo, estamos creando un documento PDF que contiene el texto "Hello World!". Después de instalar **Aspose.PDF for Python via .NET** en tu entorno, puedes ejecutar el siguiente ejemplo de código para ver cómo funciona la API de Aspose.PDF. El siguiente fragmento de código sigue estos pasos: -1. Instanciar un objeto [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) -1. Añadir una [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) al objeto documento -1. Crear un objeto [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/) -1. Añadir TextFragment a la colección de [paragraphs](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) de la página -1. [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) documento PDF resultante +1. Instanciar un [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) objeto +1. Agregar un [Página](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) al objeto de documento +1. Crear un [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/) objeto +1. Establecer colores de texto +1. Crear un Text Builder +1. Agregar [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/) a la Page +1. [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) documento PDF resultante -El siguiente fragmento de código es un programa "Hello World" para demostrar el funcionamiento de Aspose.PDF para Python a través de .NET API. +El siguiente fragmento de código es un programa "Hello World" que demuestra la funcionalidad de Aspose.PDF for Python via the .NET API. ```python +from datetime import timedelta +import aspose.pdf as ap - import aspose.pdf as ap - # Inicializar objeto documento +def run_simple(self): + # Initialize document object document = ap.Document() - # Añadir página + # Add page page = document.pages.add() - # Inicializar objeto textfragment - text_fragment = ap.text.TextFragment("Hello,world!") - # Añadir fragmento de texto a la nueva página - page.paragraphs.add(text_fragment) - # Guardar PDF actualizado - document.save("output.pdf") -``` \ No newline at end of file + # Add text to new page + textFragment = ap.text.TextFragment("Hello, world!") + textFragment.position = ap.text.Position(100, 600) + + textFragment.text_state.font_size = 12 + textFragment.text_state.font = ap.text.FontRepository.find_font("TimesNewRoman") + textFragment.text_state.background_color = ap.Color.blue + textFragment.text_state.foreground_color = ap.Color.yellow + + # Create TextBuilder object + textBuilder = ap.text.TextBuilder(page) + + # Append the text fragment to the PDF page + textBuilder.append_text(textFragment) + + document.save(self.data_dir + "HelloWorld_out.pdf") +``` diff --git a/es/python-net/overview/_index.md b/es/python-net/overview/_index.md index 934e33e96..79104a331 100644 --- a/es/python-net/overview/_index.md +++ b/es/python-net/overview/_index.md @@ -1,39 +1,41 @@ --- -title: Overview -linktitle: Overview +title: Visión general +linktitle: Visión general type: docs weight: 20 url: /es/python-net/overview/ -lastmod: "2022-12-20" -description: Descripción general de las características clave y formatos compatibles de Aspose.PDF para Python a través de .NET, manual de instalación y licenciamiento de la biblioteca. +lastmod: "2025-02-20" +description: Descripción general de las características clave y los formatos compatibles de Aspose.PDF for Python via .NET, manual de instalación y licenciamiento de la biblioteca. sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Descripción general de las características clave de Aspose.PDF for Python +Abstract: Aspose.PDF for Python via .NET es una API completa de procesamiento de PDF diseñada para que los desarrolladores manipulen documentos PDF sin depender de Microsoft Office ni de la automatización de Adobe Acrobat. La biblioteca admite una amplia gama de funcionalidades, incluida la conformidad con los estándares y especificaciones PDF establecidos, la capacidad de leer y exportar PDFs en varios formatos de imagen como BMP, GIF, JPEG y PNG, y la posibilidad de establecer información básica del documento como autor y creador. También permite la configuración de las propiedades de página PDF, como ancho, alto, cropbox y bleedbox, así como características como numeración de páginas, niveles de marcadores y tamaños de página. Los usuarios pueden manipular texto, párrafos, encabezados, hipervínculos, gráficos y adjuntos dentro de los PDFs. Además, Aspose.PDF for Python ofrece capacidades de conversión eficientes desde formatos como EPUB, Markdown, Text, XPS, PostScript, XML y LaTex a PDF, y viceversa, garantizando alto rendimiento y calidad. --- -_Esta página es una descripción general de las características de Aspose.PDF para Python._ +_Esta página es una descripción general de las características de Aspose.PDF for Python._ -**Aspose.PDF para Python a través de .NET**, API de procesamiento de PDF que permite a los desarrolladores trabajar con documentos PDF sin necesitar Microsoft Office® o Adobe Acrobat Automation. Consulte las páginas de destino de [Aspose.PDF para Python](https://products.aspose.com/pdf/python-net/) para una descripción más detallada de las características y posibilidades de la biblioteca. +**Aspose.PDF for Python via .NET**, API de procesamiento de PDF que permite a los desarrolladores trabajar con documentos PDF sin necesidad de Microsoft Office® o la automatización de Adobe Acrobat. Consulte las páginas de destino de [Aspose.PDF for Python](https://products.aspose.com/pdf/python-net/) para obtener una descripción más detallada de las características y posibilidades de la biblioteca. -Aspose.PDF para Python admite una amplia variedad de funciones como: +Aspose.PDF for Python admite una amplia variedad de funciones, como: -- Soporte para la mayoría de los estándares PDF establecidos y especificaciones PDF. -- Capacidad para leer y exportar PDFs en múltiples formatos de imagen, incluyendo BMP, GIF, JPEG y PNG. -- Establecer información básica (por ejemplo. - autor, creador) del documento PDF. -- Configurar propiedades de la página PDF (por ejemplo, ancho, alto, cropbox, bleedbox, etc.). -- Establecer numeración de páginas, nivel de marcadores, tamaños de página, etc. -- Capacidad para trabajar con texto, párrafos, encabezados, hipervínculos, gráficos, archivos adjuntos, etc. +- Soporta la mayoría de los estándares PDF establecidos y las especificaciones PDF. +- Capacidad para leer y exportar PDFs en múltiples formatos de imagen, incluidos BMP, GIF, JPEG y PNG. +- Establezca información básica (p. ej., autor, creador) del documento PDF. +- Configure las propiedades de página PDF (p. ej., ancho, alto, cropbox, bleedbox, etc.). +- Establezca la numeración de páginas, el nivel de marcadores, los tamaños de página, etc. +- Capacidad para trabajar con texto, párrafos, encabezados, hipervínculos, gráficos, archivos adjuntos, etc. -Además, Aspose.PDF para Python a través de .NET se puede aplicar para convertir fácilmente EPUB, Markdown, Texto, XPS, PostScript, XML, LaTex a PDF y convertir PDF a varios formatos de documentos con excelente rendimiento y buena calidad. +Además, Aspose.PDF for Python via .NET se puede utilizar para convertir fácilmente EPUB, Markdown, Texto, XPS, PostScript, XML, LaTex a PDF y convertir PDF a varios formatos de documento con un excelente rendimiento y buena calidad. -Prueba nuestras [Aplicaciones en Línea Gratis](https://products.aspose.app/pdf/applications) que demuestran algunas de las funcionalidades más populares de Aspose.PDF. +Pruebe nuestro [Aplicaciones gratuitas en línea](https://products.aspose.app/pdf/applications) demostrando algunas de las funcionalidades más populares de Aspose.PDF. -Aprende más sobre: +Más información sobre: -- [Formatos de Archivo Soportados](/pdf/es/python-net/supported-file-formats/) -- [Características Clave de Aspose.PDF](/pdf/es/python-net/key-features/) -- [Requisitos del Sistema](/pdf/es/python-net/system-requirements/) -- [Instalación](/pdf/es/python-net/installation/) -- [Licenciamiento](/pdf/es/python-net/licensing/) -- [Soporte Técnico](/pdf/es/python-net/technical-support/) \ No newline at end of file +- [Formatos de archivo compatibles](/pdf/es/python-net/supported-file-formats/) +- [Características clave de Aspose.PDF](/pdf/es/python-net/key-features/) +- [Requisitos del sistema](/pdf/es/python-net/system-requirements/) +- [Instalación](/pdf/es/python-net/installation/) +- [Licenciamiento](/pdf/es/python-net/licensing/) +- [Soporte técnico](/pdf/es/python-net/technical-support/) diff --git a/es/python-net/overview/installation/_index.md b/es/python-net/overview/installation/_index.md index ba59b23a3..8266c4f2b 100644 --- a/es/python-net/overview/installation/_index.md +++ b/es/python-net/overview/installation/_index.md @@ -1,44 +1,51 @@ --- -title: Cómo instalar Aspose.PDF para Python +title: Cómo instalar Aspose.PDF for Python linktitle: Instalación type: docs weight: 40 url: /es/python-net/installation/ -description: Esta sección muestra una descripción del producto e instrucciones para instalar Aspose.PDF para Python. -lastmod: "2022-12-21" +description: Encuentre instrucciones paso a paso para instalar Aspose.PDF for Python y .NET y comenzar a trabajar con documentos PDF. +lastmod: "2025-02-21" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Instalando Aspose.PDF for Python +Abstract: Aspose.PDF for Python via .NET es una biblioteca integral diseñada para integrar capacidades de procesamiento de PDF en aplicaciones Python, compatible con sistemas de 32 bits y 64 bits. Esta biblioteca admite una amplia gama de tareas de procesamiento de documentos, incluyendo la manipulación de texto y páginas, el procesamiento de formularios, la gestión de metadatos y la administración de anotaciones, marcadores, marcas de agua y fuentes personalizadas. Es adecuada para su uso en varios sistemas operativos donde está instalado Python 3.5 o posterior. La biblioteca puede evaluarse descargando una versión de prueba, que pasa a un estado con licencia mediante las adiciones de código apropiadas. La versión de prueba conserva la funcionalidad completa pero incluye una marca de agua de evaluación y limita las interacciones de elementos de colección a cuatro. Los usuarios pueden solicitar una licencia temporal de 30 días para evitar estas limitaciones. Aspose.PDF for Python via .NET puede instalarse mediante pip, garantizando un fácil acceso a las versiones más recientes. --- {{% alert color="primary" %}} -**Aspose.PDF para Python vía .NET** es una biblioteca que permite a los desarrolladores agregar capacidades de procesamiento de PDF a sus aplicaciones. La API se puede utilizar para crear aplicaciones de 32 y 64 bits para generar, leer, convertir y manipular archivos PDF sin usar Adobe Acrobat. +**Aspose.PDF for Python via .NET** es una biblioteca que permite a los desarrolladores agregar capacidades de procesamiento de PDF a sus aplicaciones. La API puede usarse para crear aplicaciones de 32 bits y 64 bits para generar, leer, convertir y manipular archivos PDF sin usar Adobe Acrobat. {{% /alert %}} ## Descripción del producto -**Aspose.PDF para Python** permite realizar una serie de tareas de procesamiento de documentos, como el procesamiento de formularios, obtener y establecer información de metadatos, manipulación de texto y páginas, gestión de anotaciones, agregar o eliminar marcadores y marcas de agua, adjuntos, manejo de fuentes personalizadas y mucho más. +**Aspose.PDF for Python** permite realizar una variedad de tareas de procesamiento de documentos, como el procesamiento de formularios, obtener y establecer información de metadatos, manipulación de texto y páginas, gestión de anotaciones, agregar o eliminar marcadores y marcas de agua, adjuntos, manejo de fuentes personalizadas y mucho más. -**Aspose.PDF for Python** se puede utilizar para desarrollar aplicaciones Python de 32 bits y 64 bits para diferentes sistemas operativos (como Windows y Linux) donde esté instalado Python 3.5 o posterior. +**Aspose.PDF for Python** puede usarse para desarrollar aplicaciones Python de 32 bits y 64 bits para diferentes sistemas operativos (como Windows y Linux) donde se tenga Python 3.5 o posterior instalado. -# Instalación +## Instalación -## Evaluar Aspose.PDF para Python a través de .NET +## Evalúe Aspose.PDF for Python via .NET -Puedes descargar fácilmente Aspose.PDF para Python para su evaluación. La descarga de evaluación es la misma que la descarga comprada. La versión de evaluación simplemente se convierte en licenciada cuando añades unas pocas líneas de código para aplicar la licencia. +Puede descargar fácilmente Aspose.PDF for Python para evaluación. La descarga de evaluación es la misma que la descarga comprada. La versión de evaluación simplemente se licencia cuando agrega unas pocas líneas de código para aplicar la licencia. -Puedes descargar [Aspose.PDF para Python](https://releases.aspose.com/pdf/pythonnet/) para su evaluación. La descarga de evaluación es la misma que la descarga comprada. La versión de evaluación se convierte en licenciada cuando añades unas pocas líneas de código para [solicitar la licencia](/pdf/es/python-net/licensing/). +Puede descargar [Aspose.PDF for Python](https://releases.aspose.com/pdf/pythonnet/) para evaluación. La descarga de evaluación es la misma que la descarga comprada. La versión de evaluación se licencia cuando agrega unas pocas líneas de código para [aplicar la licencia](/pdf/es/python-net/licensing/). -La versión de evaluación de Aspose.PDF (sin una licencia especificada) proporciona la funcionalidad completa del producto, pero tiene dos limitaciones: inserta una marca de agua de evaluación, y solo se pueden ver/editar cuatro elementos de cualquier colección. -{{% alert color="success" %}} +La versión de evaluación de Aspose.PDF (sin una licencia especificada) ofrece la funcionalidad completa del producto, pero tiene dos limitaciones: inserta una marca de agua de evaluación y solo se pueden ver/editar cuatro elementos de cualquier colección. -Si desea probar Aspose.PDF para Python sin las limitaciones de la versión de evaluación, también puede solicitar una Licencia Temporal de 30 días. Por favor, consulte [¿Cómo obtener una Licencia Temporal?](https://purchase.aspose.com/temporary-license) +{{% alert color="primary" %}} + +Si deseas probar Aspose.PDF for Python sin las limitaciones de la versión de evaluación, también puedes solicitar una Licencia Temporal de 30 días. Por favor, consulta [¿Cómo obtener una Licencia Temporal?](https://purchase.aspose.com/temporary-license) {{% /alert %}} -## Instalación de Aspose.PDF para Python a través de .NET +## Instalación de Aspose.PDF for Python via .NET + +Puedes usar fácilmente aspose-pdf para Python desde el enlace para descarga directa [pip](https://pypi.org/project/aspose-pdf/). +Ejecuta 'pip install aspose-pdf' para obtener el paquete. Si ya tienes Aspose.PDF for Python y deseas obtener la última versión, ejecuta 'pip install --upgrade aspose-pdf'. + + -Puede usar fácilmente aspose-pdf para Python desde el enlace para descarga directa [pip](https://pypi.org/project/aspose-pdf/). -Ejecute 'pip install aspose-pdf' para obtener el paquete. Si ya tiene Aspose.PDF para Python y desea obtener la última versión, por favor ejecute 'pip install --upgrade aspose-pdf'. \ No newline at end of file diff --git a/es/python-net/overview/key-features/_index.md b/es/python-net/overview/key-features/_index.md index ce73720ae..255cebe4b 100644 --- a/es/python-net/overview/key-features/_index.md +++ b/es/python-net/overview/key-features/_index.md @@ -1,92 +1,109 @@ --- -title: Características Clave de Aspose.PDF para Python -linktitle: Características Clave +title: Características clave de Aspose.PDF for Python +linktitle: Características clave type: docs weight: 20 url: /es/python-net/key-features/ -description: Aspose.PDF para Python a través de .NET demuestra sus características generales. Muestra las versiones de PDF soportadas y todas las manipulaciones que podemos hacer con PDF. -lastmod: "2022-12-21" +description: Aspose.PDF for Python via .NET destaca sus características principales, incluyendo versiones de PDF compatibles y opciones disponibles de manipulación de PDF. +lastmod: "2025-02-21" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Características generales de Aspose.PDF for Python +Abstract: Aspose.PDF for Python via .NET es una biblioteca robusta que ofrece amplias funcionalidades para gestionar y manipular documentos PDF. Soporta estándares PDF establecidos y facilita la lectura y exportación de PDFs a varios formatos de imagen como BMP, GIF, JPEG y PNG. Los usuarios pueden configurar las propiedades del documento, los atributos de la página y gestionar texto, párrafos, hipervínculos, gráficos y anexos. La biblioteca sobresale en capacidades de conversión, permitiendo una transformación fluida de PDFs a formatos Word, Excel, PowerPoint y HTML, entre otros, al mismo tiempo que convierte diversos formatos de vuelta a PDF. --- -## Características Generales +## Características generales -- Soporta la mayoría de los estándares PDF establecidos y especificaciones PDF. -- Capacidad para leer y exportar PDFs en múltiples formatos de imagen, incluyendo BMP, GIF, JPEG y PNG. -- Establecer información básica (por ejemplo, autor, creador) del documento PDF. -- Configurar propiedades de la página PDF (por ejemplo, ancho, alto, cropbox, bleedbox, etc.). -- Establecer numeración de páginas, nivel de marcadores, tamaños de página, etc. -- Capacidad para trabajar con texto, párrafos, encabezados, hipervínculos, gráficos, adjuntos, etc. +- Soporta la mayoría de los estándares PDF establecidos y las especificaciones PDF. +- Capacidad para leer y exportar PDFs en múltiples formatos de imagen, incluidos BMP, GIF, JPEG y PNG. +- Establezca información básica (p. ej., autor, creador) del documento PDF. +- Configure las propiedades de página PDF (p. ej., ancho, alto, cropbox, bleedbox, etc.). +- Establezca la numeración de páginas, el nivel de marcadores, los tamaños de página, etc. +- Capacidad para trabajar con texto, párrafos, encabezados, hipervínculos, gráficos, archivos adjuntos, etc. -## Características de Conversión +## Estándares PDF compatibles -La biblioteca Aspose.PDF para Python a través de .NET le permite convertir sus documentos PDF a los formatos más populares y viceversa de manera exitosa, rápida y fácil. +- ISO 32000-1 (PDF 1.2, PDF 1.3, PDF 1.4, PDF 1.5, PDF 1.6, PDF 1.7). +- ISO 32000-2 (PDF 2.0). +- ISO 19005 (PDF/A), ISO 15930 (PDF/X), ISO 24517 (PDF/E), ISO 14289 (PDF/UA). + +## Funciones de conversión + +La biblioteca Aspose.PDF for Python via .NET le permite convertir sus documentos PDF de manera exitosa, rápida y fácil a los formatos más populares y viceversa. - Convertir PDF a Word, Excel y PowerPoint. - Convertir PDF a formatos de imágenes. -- Convertir archivo PDF a formato HTML y viceversa. +- Convertir archivo PDF al formato HTML y viceversa. - Convertir PDF a EPUB, Texto, XPS, etc. - Convertir EPUB, Markdown, Texto, XPS, PostScript, XML, LaTex a PDF. -## Versiones de PDF compatibles +## Versiones PDF compatibles -Aspose.PDF para Python soporta las versiones PDF 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, y 2.0. +Aspose.PDF for Python admite versiones PDF 1.2, 1.3, 1.4, 1.5, 1.6, 1.7 y 2.0. ## Texto - Extraer texto de las páginas. - Buscar texto en las páginas. - Reemplazar texto. -- Añadir texto en el archivo PDF. +- Agregar texto en archivo PDF. + +## Fonts + +- 14 core fonts. +- Type 1 fonts. +- TrueType fonts. +- Type 3 fonts. +- CJK fonts. +- Compatibilidad con Unicode. ## Imágenes -- Añadir imagen en el archivo PDF. +- Agregar imagen en archivo PDF. - Eliminar imágenes. - Reemplazar imágenes. - Extraer imágenes. -- Conversión de PDF a formato de imagen. +- Conversión de formato PDF a Imagen. ## Adjuntos -- Añadir adjunto. +- Agregar adjunto. - Eliminar adjuntos. ## Página -- Insertar páginas en PDF. -- Eliminar páginas en PDF. +- Insertar páginas PDF. +- Eliminar páginas PDF. - Dividir PDF en páginas individuales. -- Mover un grupo de páginas de un documento PDF a otro +- Mover un conjunto de páginas de un documento PDF a otro - Mover una página a una nueva ubicación en el documento PDF actual -- Cambiar tamaño de página de PDF -- Cambiar orientación de la página +- Cambiar el tamaño de la página PDF +- Cambiar la orientación de la página - Obtener propiedades de la página - Obtener número de páginas -- Obtener cuenta de páginas +- Obtener recuento de páginas - Obtener una página en particular ## Documento - Crear archivo PDF -- Abrir documento PDF existente desde el flujo +- Abrir documento PDF existente desde flujo - Abrir documento PDF existente - - Configuración de propiedades preestablecidas del cuadro de diálogo de impresión -- Agregar TOC a un PDF existente -- Agregar TOC a un PDF existente +- Agregar TOC a PDF existente +- Agregar TOC a PDF existente - Personalizar números de página al agregar TOC -- Establecer fecha de caducidad del PDF +- Establecer fecha de expiración del PDF - Aplanar PDF rellenable - Optimizar documento PDF para la web -- Reducir tamaño del PDF +- Reducir tamaño PDF - Reducir o comprimir todas las imágenes - Eliminar objetos no utilizados -- Enlazar flujos duplicados +- Vincular flujos duplicados - Eliminar flujos no utilizados -- Desincrustar fuentes +- Desincorporar fuentes - Obtener propiedades del visor de documentos. - Establecer propiedades del visor de documentos. - Validar (PDF/A-1a, PDF/A-1b). @@ -101,7 +118,7 @@ Aspose.PDF para Python soporta las versiones PDF 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, y - Obtener marcadores. - Obtener marcadores secundarios. - Modificar marcadores. -- Marcadores expandidos al ver el documento. +- Marcadores ampliados al ver el documento. ## Anotaciones @@ -116,1041 +133,16 @@ Aspose.PDF para Python soporta las versiones PDF 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, y - Modificar campos. - Rellenar campos. - Obtener valores de campos. +- Soporte para XFA (Formularios basados en XML) y AcroForms (Formularios estándar). -## Sello y Marca de Agua +## Sello y marca de agua - Agregar sello de texto. - Agregar sello de imagen. - Agregar sello de página PDF. +## Abrir documento PDF cifrado - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Open encrypted PDF document -- Cifrar PDF. -- Descifrar PDF. -- Modificar contraseña. \ No newline at end of file +- Cifrar PDF. +- Descifrar PDF. +- Modificar contraseña. diff --git a/es/python-net/overview/licensing/_index.md b/es/python-net/overview/licensing/_index.md index 5170523a5..6ab4a7caa 100644 --- a/es/python-net/overview/licensing/_index.md +++ b/es/python-net/overview/licensing/_index.md @@ -1,32 +1,36 @@ --- -title: Aspose PDF License -linktitle: Licensing and limitations +title: Licencia Aspose PDF +linktitle: Licenciamiento y limitaciones type: docs weight: 50 url: /es/python-net/licensing/ -description: Aspose. PDF para Python invita a sus clientes a obtener una licencia Clásica. Así como utilizar una licencia limitada para explorar mejor el producto. -lastmod: "2022-12-21" +description: Aspose.PDF for Python invita a sus clientes a obtener una licencia Classic. Así como usar una licencia limitada para explorar mejor el producto. +lastmod: "2025-02-21" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Licenciamiento de Aspose.PDF for Python +Abstract: El artículo analiza las limitaciones y opciones de licenciamiento para Aspose.PDF for Python. Destaca que la versión de evaluación permite probar la funcionalidad completa pero agrega una marca de agua a los PDFs generados, mostrando "Evaluation Only" junto con información de derechos de autor. Para los usuarios que deseen probar sin estas limitaciones, está disponible una Licencia Temporal de 30 días. El artículo también explica cómo implementar una licencia classic cargándola desde un archivo o flujo, recomendando colocar el archivo de licencia en el mismo directorio que el archivo Aspose.PDF.dll y establecer la licencia usando la clase `Aspose.Pdf.License`. Se proporcionan fragmentos de código para ilustrar el proceso de licenciamiento. --- ## Limitación de una versión de evaluación -Queremos que nuestros clientes prueben a fondo nuestros componentes antes de comprarlos, por lo que la versión de evaluación le permite usarlo como lo haría normalmente. +Queremos que nuestros clientes prueben nuestros componentes a fondo antes de comprar, por lo que la versión de evaluación le permite usarlo como lo haría normalmente. -- **PDF creado con una marca de agua de evaluación.** La versión de evaluación de Aspose.PDF para Python proporciona toda la funcionalidad del producto, pero todas las páginas en los documentos PDF generados están marcadas con agua con "Solo Evaluación. Creado con Aspose.PDF. Copyright 2002-2020 Aspose Pty Ltd" en la parte superior. +- **PDF creado con una marca de agua de evaluación.** La versión de evaluación de Aspose.PDF for Python proporciona la funcionalidad completa del producto, pero todas las páginas en los documentos PDF generados llevan una marca de agua con "Evaluation Only. Created with Aspose.PDF. Copyright 2002-2020 Aspose Pty Ltd" en la parte superior. ->Si desea probar Aspose.PDF sin las limitaciones de la versión de evaluación, también puede solicitar una Licencia Temporal de 30 días. - ## Licencia clásica +>Si desea probar Aspose.PDF sin las limitaciones de la versión de evaluación, también puede solicitar una Licencia Temporal de 30 días. Por favor, consulte a [¿Cómo obtener una Licencia Temporal?](https://purchase.aspose.com/temporary-license) -La licencia se puede cargar desde un archivo o un objeto de flujo. La forma más fácil de establecer una licencia es colocar el archivo de licencia en la misma carpeta que el archivo Aspose.PDF.dll y especificar el nombre del archivo sin una ruta, como se muestra en el ejemplo a continuación. +## Licencia clásica -Si utiliza cualquier otro componente de Aspose para Python junto con Aspose.PDF para Python, por favor especifique el espacio de nombres para License como [Aspose.Pdf.License class](). +La licencia se puede cargar desde un archivo o un objeto de flujo. La forma más sencilla de establecer una licencia es colocar el archivo de licencia en la misma carpeta que el archivo Aspose.PDF.dll y especificar el nombre del archivo sin ruta, como se muestra en el ejemplo a continuación. + +Si utiliza cualquier otro componente Aspose para Python junto con Aspose.PDF for Python, por favor especifique el espacio de nombres para License como [Clase Aspose.Pdf.License](). ```python license_file = LICENSE_FILE license = ap.License() license.set_license(license_file) -``` \ No newline at end of file +``` diff --git a/es/python-net/overview/supported-file-formats/_index.md b/es/python-net/overview/supported-file-formats/_index.md index 8e34b2530..17204d802 100644 --- a/es/python-net/overview/supported-file-formats/_index.md +++ b/es/python-net/overview/supported-file-formats/_index.md @@ -1,46 +1,51 @@ --- -title: Formatos de Archivo Soportados -linktitle: Formatos de Archivo Soportados +title: Formatos de archivo compatibles +linktitle: Formatos de archivo compatibles type: docs weight: 10 url: /es/python-net/supported-file-formats/ -description: Esta página muestra qué formatos de archivo Aspose.PDF para Python a través de .NET puede cargar y guardar. -lastmod: "2022-12-22" +description: Esta página muestra qué Aspose.PDF for Python via .NET puede cargar y guardar formatos de archivo. +lastmod: "2025-02-22" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Cargar y guardar formatos de archivo con Aspose.PDF for Python +Abstract: Este artículo proporciona una tabla completa que detalla los formatos de archivo que Aspose.PDF for Python puede manejar. Describe las capacidades de la biblioteca para cargar y guardar varios tipos de documentos, ofreciendo información sobre su versatilidad para gestionar diferentes formatos de archivo. Los formatos cubiertos incluyen tipos conocidos como PDF, EPUB, HTML y XML, los cuales pueden ser tanto cargados como guardados por la biblioteca. También admite formatos de imagen como JPEG, PNG y TIFF para ambas operaciones. Sin embargo, algunos formatos como CGM, MHT, PCL, PS, XSLFO y MD solo están disponibles para carga, mientras que otros como XLS, XLSX, PPTX, DOC, DOCX y MobiXML están disponibles únicamente para guardado. Esta tabla sirve como una guía práctica para los usuarios que desean comprender la compatibilidad de formatos de Aspose.PDF for Python, resaltando tanto sus fortalezas como sus limitaciones en el soporte de formatos de documento e imagen. --- La siguiente tabla indica los formatos de archivo que Aspose.PDF Python puede cargar y guardar. -|**Format**|**Descripción**|**Cargar**|**Guardar**|**Observaciones**| +|**Formato**|**Descripción**|**Cargar**|**Guardar**|**Observaciones**| | :- | :- | :- | :- | :- | |[PDF](https://docs.fileformat.com/pdf/)|Formato de Documento Portátil|{{< emoticons/tick >}}|{{< emoticons/tick >}} | | |[CGM](https://docs.fileformat.com/page-description-language/cgm/)|Metarchivo de Gráficos por Computadora para gráficos vectoriales 2D|{{< emoticons/tick >}}| | | |[EPUB](https://docs.fileformat.com/ebook/epub/)|Formato de archivo de libro electrónico|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | |[HTML](https://docs.fileformat.com/web/html/)|Formato HTML|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | - |[TeX](https://docs.fileformat.com/page-description-language/tex/)|Formato de archivo de composición tipográfica LaTex|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | -|[MHT](https://docs.fileformat.com/web/mhtml/)|Documento MHTML|{{< emoticons/tick >}}| | | -|[PCL](https://docs.fileformat.com/page-description-language/pcl/)|Archivos de Lenguaje de Control de Impresora|{{< emoticons/tick >}}| | | -|[PS](https://docs.fileformat.com/page-description-language/ps/)|Archivos Postscript|{{< emoticons/tick >}}| | | -|[SVG](https://docs.fileformat.com/page-description-language/svg/)|Gráficos Vectoriales Escalables (un formato de imagen vectorial basado en XML)|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | -|[XML](https://docs.fileformat.com/web/xml/)|Formato XML|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | -|[XPS](https://docs.fileformat.com/page-description-language/xps/)|Documentos XPS|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | -|[XSLFO](https://docs.fileformat.com/page-description-language/xslfo/)|XSL-FO es parte del archivo XSL que se usa para la transformación y el formato de datos XML|{{< emoticons/tick >}}| | | - -|[MD](https://docs.fileformat.com/word-processing/md/)|Formato Markdown|{{< emoticons/tick >}}| | | -|[XLS](https://docs.fileformat.com/spreadsheet/xls/)|Guarda el documento en el formato de hoja de cálculo de Microsoft Excel| |{{< emoticons/tick >}}| | -|[XLSX](https://docs.fileformat.com/spreadsheet/xlsx/)|Guarda el documento en el formato de Microsoft Excel 2007| |{{< emoticons/tick >}}| | -|[PPTX](https://docs.fileformat.com/presentation/pptx/)|Guarda el documento en el formato de presentaciones de Microsoft PowerPoint| |{{< emoticons/tick >}}| | -|[DOC](https://docs.fileformat.com/word-processing/doc/)|Guarda el documento en el formato de Microsoft Word| |{{< emoticons/tick >}}| | -|[DOCX](https://docs.fileformat.com/word-processing/docx/)|Guarda el documento en el formato de Microsoft Word| |{{< emoticons/tick >}}| | -|[MobiXML](https://docs.fileformat.com/ebook/mobi/)|Guarda el documento en el formato estándar de eBook MobiXML| |{{< emoticons/tick >}}| | -|[JPEG](https://docs.fileformat.com/image/jpeg/)|Guarda el documento en el formato JPEG|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | - +|[MHT](https://docs.fileformat.com/web/mhtml/)|Documento MHTML|{{< emoticons/tick >}}| | | +|[PCL](https://docs.fileformat.com/page-description-language/pcl/)|Archivos de lenguaje de control de impresora|{{< emoticons/tick >}}| | | +|[PS](https://docs.fileformat.com/page-description-language/ps/)|Archivos Postscript|{{< emoticons/tick >}}| | | +|[SVG](https://docs.fileformat.com/page-description-language/svg/)|Gráficos vectoriales escalables (un formato de imagen vectorial basado en XML)|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | +|[XML](https://docs.fileformat.com/web/xml/)|Formato XML|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | +|[XPS](https://docs.fileformat.com/page-description-language/xps/)|Documentos XPS|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | +|[XSLFO](https://docs.fileformat.com/page-description-language/xslfo/)|XSL-FO es parte del archivo XSL que se usa para la transformación y el formato de datos XML|{{< emoticons/tick >}}| | | +|[MD](https://docs.fileformat.com/word-processing/md/)|Formato Markdown|{{< emoticons/tick >}}| | | +|[XLS](https://docs.fileformat.com/spreadsheet/xls/)|Guarda el documento en la hoja de cálculo de Microsoft Excel| |{{< emoticons/tick >}}| | +|[XLSX](https://docs.fileformat.com/spreadsheet/xlsx/)|Guarda el documento en el formato Microsoft Excel 2007| |{{< emoticons/tick >}}| | +|[PPTX](https://docs.fileformat.com/presentation/pptx/)|Guarda el documento en el formato Microsoft PowerPoint Presentations| |{{< emoticons/tick >}}| | +|[XLSM](https://docs.fileformat.com/spreadsheet/xlsm/)|Guarda el documento en el formato XLSM, que es un tipo de archivos de hoja de cálculo que admiten macros.||{{< emoticons/tick >}} | | +|[DOC](https://docs.fileformat.com/word-processing/doc/)|Guarda el documento en el formato Microsoft Word| |{{< emoticons/tick >}}| | +|[DOCX](https://docs.fileformat.com/word-processing/docx/)|Guarda el documento en el formato Microsoft Word| |{{< emoticons/tick >}}| | +|[OFD](https://en.wikipedia.org/wiki/OFD)|El formato OFD se refiere a “Open Fixed-layout Document”, establecido como el estándar nacional de China para el almacenamiento de archivos electrónicos, utilizado como una alternativa al popular formato PDF.|{{< emoticons/tick >}}| | | +|[DJVU](https://docs.fileformat.com/image/djvu/)|DjVu es un formato de archivo gráfico destinado a documentos escaneados y libros, desarrollado por AT&T Labs|{{< emoticons/tick >}}| | | +|[CDR](https://docs.fileformat.com/image/cdr/)|Un archivo CDR es un archivo de imagen de dibujo vectorial que se crea de forma nativa con CorelDRAW|{{< emoticons/tick >}}| | | +|[MobiXML](https://docs.fileformat.com/ebook/mobi/)|Guarda el documento en formato estándar eBook MobiXML| |{{< emoticons/tick >}}| | +|[JPEG](https://docs.fileformat.com/image/jpeg/)|Guarda el documento en formato JPEG|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | |[EMF](https://docs.fileformat.com/image/emf/)|Formato de metarchivo mejorado (EMF)|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | |[PNG](https://docs.fileformat.com/image/png/)|Guarda el documento en formato PNG|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | |[BMP](https://docs.fileformat.com/image/bmp/)|Guarda el documento en formato BMP|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | |[GIF](https://docs.fileformat.com/image/gif/)|Formato de Intercambio Gráfico| |{{< emoticons/tick >}}| | -|[TIFF](https://docs.fileformat.com/image/tiff/)|Guarda el documento como imagen TIFF de página única o múltiple|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | -|[Text](https://docs.fileformat.com/word-processing/txt/)|Guarda el documento en formato de texto|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | \ No newline at end of file +|[TIFF](https://docs.fileformat.com/image/tiff/)|Guarda el documento como imagen TIFF de una sola página o de varias páginas|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | +|[Texto](https://docs.fileformat.com/word-processing/txt/)|Guardar el documento en formato de texto|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | + diff --git a/es/python-net/overview/system-requirements/_index.md b/es/python-net/overview/system-requirements/_index.md index a6fbd7048..02e5a02c2 100644 --- a/es/python-net/overview/system-requirements/_index.md +++ b/es/python-net/overview/system-requirements/_index.md @@ -1,30 +1,33 @@ --- -title: Requisitos del Sistema -linktitle: Requisitos del Sistema +title: Requisitos del sistema +linktitle: Requisitos del sistema type: docs weight: 30 url: /es/python-net/system-requirements/ -description: Esta sección lista los sistemas operativos compatibles que un desarrollador necesita para trabajar exitosamente con Aspose.PDF para Python. -lastmod: "2022-12-22" +description: Esta sección enumera los sistemas operativos compatibles que un desarrollador necesita para trabajar con éxito con Aspose.PDF for Python. +lastmod: "2025-02-22" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Sistemas operativos compatibles de Aspose.PDF for Python via .NET +Abstract: Aspose.PDF for Python via .NET es una API de procesamiento de PDF diseñada para que los desarrolladores gestionen documentos PDF sin necesidad de Microsoft Office o Adobe Acrobat Automation. Admite el desarrollo de aplicaciones Python de 32 bits y 64 bits en varios sistemas operativos, incluidos Windows y Linux, donde está instalado Python 3.5 o posterior. La API es compatible con varias versiones de Windows, desde Windows XP hasta Windows 11, y con las principales distribuciones de Linux como Ubuntu, OpenSUSE y CentOS. Para los sistemas Linux, los requisitos específicos incluyen bibliotecas de tiempo de ejecución GCC-6, dependencias del .NET Core Runtime (sin necesitar el runtime en sí), y la compilación pymalloc de Python para las versiones 3.5-3.7. Además, se necesita una biblioteca libpython compartida, lo que podría requerir ajustes de configuración para el reconocimiento correcto de la ruta de la biblioteca. --- -## Descripción General +## Visión general -Aspose.PDF para Python a través de .NET, API de procesamiento de PDF que permite a los desarrolladores trabajar con documentos PDF sin necesidad de Microsoft Office® o Adobe Acrobat Automation. Aspose.PDF para Python puede ser utilizado para desarrollar aplicaciones Python de 32 bits y 64 bits para diferentes sistemas operativos (como Windows y Linux) donde Python 3.5 o posterior está instalado. +Aspose.PDF for Python via .NET, API de procesamiento de PDF que permite a los desarrolladores trabajar con documentos PDF sin necesitar Microsoft Office® o Adobe Acrobat Automation. Aspose.PDF for Python puede usarse para desarrollar aplicaciones Python de 32 bits y 64 bits para diferentes sistemas operativos (como Windows y Linux) donde Python 3.5 o posterior está instalado. -## Sistema Operativo Compatible +## Sistema operativo compatible ### Windows - Windows 2003 Server - Windows 2008 Server - Windows 2012 Server -- Windows 2012 R2 Server -- Windows 2016 Server -- Windows 2019 Server +- Servidor Windows 2012 R2 +- Servidor Windows 2016 +- Servidor Windows 2019 - Windows XP - Windows Vista - Windows 7 @@ -39,13 +42,14 @@ Aspose.PDF para Python a través de .NET, API de procesamiento de PDF que permit - CentOS - y otros -## Requisitos del Sistema para Linux Objetivo +## Requisitos del sistema para Linux de destino -- Bibliotecas de tiempo de ejecución de GCC-6 (o posteriores). +- Bibliotecas de tiempo de ejecución GCC-6 (o posteriores). -- Dependencias del entorno de ejecución de .NET Core. NO es necesario instalar el entorno de ejecución de .NET Core en sí. +- Dependencias del tiempo de ejecución de .NET Core. Instalar el propio tiempo de ejecución de .NET Core NO es necesario. + +- Para Python 3.5-3.7: se necesita la compilación pymalloc de Python. La opción de compilación --with-pymalloc de Python está habilitada por defecto. Normalmente, la compilación pymalloc de Python se marca con el sufijo m en el nombre de archivo. + +- Biblioteca compartida libpython de Python. La opción de compilación de Python --enable-shared está desactivada por defecto, algunas distribuciones de Python no incluyen la biblioteca compartida libpython. En algunas plataformas Linux, la biblioteca compartida libpython puede instalarse usando el gestor de paquetes, por ejemplo: sudo apt-get install libpython3.7. El problema común es que la biblioteca libpython se instala en una ubicación diferente a la ubicación estándar del sistema para bibliotecas compartidas. El problema puede resolverse usando las opciones de compilación de Python para establecer rutas de biblioteca alternativas al compilar Python, o resolverse creando un enlace simbólico al archivo de biblioteca libpython en la ubicación estándar del sistema para bibliotecas compartidas. Normalmente, el nombre del archivo de la biblioteca compartida libpython es libpythonX.Ym.so.1.0 para Python 3.5-3.7, o libpythonX.Y.so.1.0 para Python 3.8 o posterior (por ejemplo: libpython3.7m.so.1.0, libpython3.9.so.1.0). -- Para Python 3.5-3.7: Se necesita la compilación pymalloc de Python. La opción de compilación --with-pymalloc de Python está habilitada por defecto. Normalmente, la compilación pymalloc de Python está marcada con el sufijo m en el nombre del archivo. -- Biblioteca compartida de Python libpython. - La opción de compilación de Python --enable-shared está desactivada por defecto, algunas distribuciones de Python no contienen la biblioteca compartida libpython. Para algunas plataformas Linux, la biblioteca compartida libpython se puede instalar utilizando el gestor de paquetes, por ejemplo: sudo apt-get install libpython3.7. El problema común es que la biblioteca libpython está instalada en una ubicación diferente a la ubicación estándar del sistema para bibliotecas compartidas. El problema se puede solucionar utilizando las opciones de compilación de Python para establecer rutas de bibliotecas alternativas al compilar Python, o solucionarlo creando un enlace simbólico al archivo de la biblioteca libpython en la ubicación estándar del sistema para bibliotecas compartidas. Típicamente, el nombre del archivo de la biblioteca compartida libpython es libpythonX.Ym.so.1.0 para Python 3.5-3.7, o libpythonX.Y.so.1.0 para Python 3.8 o posterior (por ejemplo: libpython3.7m.so.1.0, libpython3.9.so.1.0). \ No newline at end of file diff --git a/es/python-net/overview/technical-support/_index.md b/es/python-net/overview/technical-support/_index.md index dc6da9269..3b0c75336 100644 --- a/es/python-net/overview/technical-support/_index.md +++ b/es/python-net/overview/technical-support/_index.md @@ -1,30 +1,35 @@ --- -title: Aspose.PDF para Python Soporte -linktitle: Soporte Técnico +title: Soporte de Aspose.PDF for Python +linktitle: Soporte técnico type: docs weight: 60 url: /es/python-net/technical-support/ -description: Esta página ofrece recomendaciones para resolver sus tareas de manera rápida y efectiva utilizando Aspose.PDF para Python. -lastmod: "2021-06-05" +description: Esta página brinda recomendaciones para resolver rápida y eficazmente sus tareas utilizando Aspose.PDF for Python. +lastmod: "2025-02-05" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Soporte técnico de Aspose.PDF for Python +Abstract: Aspose.PDF ofrece soporte técnico gratuito a través de sus varios canales, siendo la fuente principal los Aspose.Forums, en particular la sección del foro Aspose.PDF donde los usuarios pueden publicar consultas y recibir respuestas rápidas. Es importante señalar que Aspose no ofrece soporte técnico por teléfono, y las llamadas telefónicas están limitadas a consultas de ventas y compras. Debido a posibles diferencias de zona horaria, los tiempos de respuesta pueden variar. Para garantizar una resolución eficiente de los problemas, se aconseja a los usuarios verificar primero que están utilizando la última versión de Aspose.PDF consultando los [Aspose.PDF for Python Downloads](https://pypi.org/project/aspose-pdf/). Además, los usuarios deben revisar las discusiones existentes en el foro, la documentación y las referencias de la API para ver si su problema ya ha sido abordado. Al publicar una pregunta, se recomienda incluir el documento original y cualquier fragmento de código problemático, que puede comprimirse en un archivo zip para mayor comodidad. Todos los archivos subidos son accesibles solo para el usuario y los desarrolladores de Aspose, garantizando privacidad y seguridad. --- Aspose.PDF le permite utilizar soporte técnico gratuito para todos sus productos. Si tiene preguntas sobre Aspose.PDF, consulte el siguiente artículo: -- La fuente de soporte más popular es [Aspose.Forums](https://forum.aspose.com/). En la sección del [foro de Aspose.PDF](https://forum.aspose.com/c/pdf/10), puede hacer su pregunta y obtener una respuesta lo antes posible. +- La fuente de soporte más popular es [Aspose.Forums](https://forum.aspose.com/). En el [foro Aspose.PDF](https://forum.aspose.com/c/pdf/10) sección, puedes hacer tu pregunta y obtener una respuesta lo antes posible. -- Debe saber que Aspose no proporciona soporte técnico por teléfono. Puede llamar solo para preguntas de ventas y compras. +- Debes saber que Aspose no brinda soporte técnico por teléfono. Llamar sólo está disponible para preguntas de ventas y compras. -- Por favor recuerde que tenemos diferencias de zona horaria, esto puede afectar la rapidez de las respuestas hacia usted. +- Por favor recuerde que tenemos diferencias de zona horaria, esto puede afectar la velocidad de las respuestas para usted. Si necesita ayuda con un problema con Aspose.PDF, siga las siguientes recomendaciones para asegurarse de que se resuelva de la manera más eficiente: -- En primer lugar, verifique que esté utilizando la última versión de Aspose.PDF antes de reportar el problema, consulte [Descargas de Aspose.PDF para Python](https://pypi.org/project/aspose-pdf/) para obtener información sobre la última versión. +- En primer lugar, compruebe que está utilizando la última versión de Aspose.PDF antes de informar del problema, vea [Descargas de Aspose.PDF para Python](https://pypi.org/project/aspose-pdf/) para averiguar la última versión. -- Quizás la solución a su problema ya ha sido discutida y tiene una solución; para ello, estudie el foro y la documentación, verifique la Referencia de API antes de reportar el problema. +- Quizás la solución a su problema ya haya sido discutida y tenga una solución; para ello, revise el foro y la documentación, consulte la API Reference antes de informar del problema. + +- Cuando formule su pregunta, incluya el documento original y, si es posible, un fragmento de su código que cause el problema. Puede comprimir estos archivos en un solo documento si son varios. + +- No se preocupe, solo usted y los desarrolladores de Aspose tienen acceso a los archivos sticky. -- Cuando formule su pregunta, incluya el documento original y, posiblemente, un fragmento de su código que cause el problema. Puede comprimir estos archivos en un solo documento si hay varios. -- No se preocupe, solo usted y los desarrolladores de Aspose tienen acceso a los archivos confidenciales. \ No newline at end of file diff --git a/es/python-net/parsing/_index.md b/es/python-net/parsing/_index.md index 45027036f..97df01060 100644 --- a/es/python-net/parsing/_index.md +++ b/es/python-net/parsing/_index.md @@ -1,14 +1,24 @@ --- -title: Parse PDF documents -linktitle: Parse PDF documents +title: Analizar documentos PDF +linktitle: Analizar documentos PDF type: docs weight: 80 url: /es/python-net/parsing/ -description: ¿Quieres analizar documentos PDF? Descubre varios métodos de extracción de datos PDF con Aspose.PDF para Python via .NET. -lastmod: "2021-06-05" +description: ¿Quieres analizar documentos PDF? Descubre varios métodos de extracción de datos PDF con Aspose.PDF for Python via .NET. +lastmod: "2025-02-05" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Analiza archivos PDF con Aspose.PDF for Python +Abstract: El artículo Parse PDF profundiza en las diversas metodologías para extraer diferentes tipos de información de archivos PDF. Destaca varias operaciones clave y guías. --- -**Parse PDF** documentos es un término relacionado con la extracción de varios tipos de información de un archivo PDF. Esta sección cubre cómo: \ No newline at end of file +**Parse PDF** documentos es un término relacionado con la extracción de varios tipos de información de un archivo PDF. Esta sección cubre cómo: + +- [Extraer texto de PDF](/pdf/es/python-net/extract-text-from-pdf/). El análisis o extracción de texto es la operación más popular con PDFs listos. Aprenderás sobre el análisis de texto de un documento completo, una página específica o una región particular en una página. +- [Extraer imágenes de PDF](/pdf/es/python-net/extract-images-from-the-pdf-file/). La extracción de imágenes hace lo mismo para imágenes que la operación anterior para texto. +- [Extraer fuentes de PDF](/pdf/es/python-net/extract-fonts-from-pdf/). La extracción de fuentes es una operación específica con fuentes en PDFs. +- [Extraer datos del formulario](/pdf/es/python-net/extract-data-from-acroform/). Si tienes un montón de documentos PDF con Formularios, probablemente necesites obtener los datos de esos formularios. Este artículo te ayudará a comprender cómo extraer datos de AcroForms con Aspose.PDF for Python via .NET. +- [Extraer datos de una tabla](/pdf/es/python-net/extract-data-from-table-in-pdf/). Obtener datos de la tabla en un documento PDF. +- [Extraer datos vectoriales de PDF](/pdf/es/python-net/extract-vector-data-from-pdf/). Puedes obtener los datos vectoriales (ruta, polígono, polilínea), como posición, color, ancho de línea, etc. diff --git a/es/python-net/parsing/extract-data-from-acroform/_index.md b/es/python-net/parsing/extract-data-from-acroform/_index.md new file mode 100644 index 000000000..1875f31b0 --- /dev/null +++ b/es/python-net/parsing/extract-data-from-acroform/_index.md @@ -0,0 +1,197 @@ +--- +title: Extraer datos de AcroForm usando Python +linktitle: Extraer datos de AcroForm +type: docs +weight: 50 +url: /es/python-net/extract-data-from-acroform/ +description: Aspose.PDF facilita la extracción de datos de campos de formulario de archivos PDF. Aprende cómo extraer datos de AcroForms y guardarlos en formato JSON, XML o FDF. +lastmod: "2025-03-13" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo extraer datos de AcroForm mediante Python +Abstract: El artículo proporciona una guía completa sobre el uso de Aspose.PDF for Python para gestionar campos de formulario dentro de documentos PDF. Detalla varios métodos para extraer, manipular y exportar datos de formularios desde PDFs. El artículo comienza demostrando cómo extraer los valores de los campos de formulario y almacenarlos en un diccionario, para luego generar los datos en formato JSON. Además, ilustra la exportación de datos de formulario directamente a archivos JSON, mejorando las capacidades de serialización de datos. Asimismo, el artículo cubre la exportación de datos de formulario a otros formatos como XML, FDF (Forms Data Format) y XFDF, que son útiles para el intercambio de datos y el almacenamiento estructurado de información. Cada sección incluye fragmentos de código Python para ayudar en la comprensión e implementación. En conjunto, el artículo sirve como un recurso práctico para desarrolladores que desean integrar la manipulación de formularios PDF en sus aplicaciones Python. +--- + +## Extraer campos de formulario del documento PDF + +[Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form) del `aspose.pdf.facades` namespace proporciona una forma sencilla de leer los datos de los campos AcroForm sin abrir el modelo de objeto del documento completo. Iterar sobre `form.field_names` para obtener el nombre de cada campo presente en el formulario, luego llame `form.get_field(name)` para recuperar su valor actual. + +1. Construir un `Form` objeto pasando la ruta del archivo de entrada. +1. Iterar sobre `form.field_names` enumerar todos los nombres de campo. +1. Llamar `form.get_field(name)` para cada nombre y almacena el resultado en un diccionario. + +```python + + import aspose.pdf as apdf + from io import FileIO + from os import path + import json + from aspose.pycore import cast, is_assignable + + path_infile = self.dataDir + infile + form = apdf.facades.Form(path_infile) + + form_values = {} + # Get values from all fields + for formField in form.field_names: + # Analyze names and values if needed + form_values[formField] = form.get_field(formField) + + print(form_values) +``` + +## Recuperar valor del campo de formulario por título + +Cuando sabes el nombre exacto del campo (title) definido en el formulario PDF, puedes obtener su valor directamente con `form.get_field(name)` sin iterar sobre toda la colección de campos. Este es el enfoque más rápido cuando solo se necesitan campos específicos. + +1. Construir un [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form) objeto con la ruta del archivo de entrada. +1. Llamar `form.get_field("FieldName")` usando el título exacto del campo tal como aparece en el PDF. +1. Utilice el valor de cadena devuelto según sea necesario en su aplicación. + +```python + + import aspose.pdf as apdf + + form = apdf.facades.Form(path_infile) + + # Retrieve a single field value by its name + value = form.get_field("FirstName") + print(value) +``` + +## Extraer campos de formulario del documento PDF a JSON + +Hay dos maneras de exportar datos de AcroForm a JSON. La primera utiliza la funcionalidad incorporada `export_json` método en [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form), que serializa todos los datos de campo directamente a un flujo de archivo en una sola llamada. + +1. Construir un `Form` objeto con la ruta del archivo de entrada. +1. Abra el archivo de salida como un flujo binario usando `FileIO`. +1. Llamar `form.export_json(stream, True)` para escribir la salida JSON. + +```python + + import aspose.pdf as apdf + from io import FileIO + from os import path + + path_infile = path.join(self.dataDir, infile) + path_outfile = path.join(self.dataDir, outfile) + + form = apdf.facades.Form(path_infile) + with FileIO(path_outfile, "w") as json_file: + form.export_json(json_file, True) +``` + +El segundo enfoque crea un diccionario de Python a partir de `field_names` y `get_field`, luego lo serializa con `json.dumps`. Utilice esto cuando necesite transformar o filtrar los datos antes de escribirlos. + +1. Iterar sobre `form.field_names` y rellenar un diccionario con los valores de los campos. +1. Serializa el diccionario con `json.dumps(form_data, indent=4)`. +1. Escribe la cadena JSON resultante en el archivo de salida. + +```python + + import aspose.pdf as apdf + from os import path + import json + + path_infile = path.join(self.dataDir, infile) + path_outfile = path.join(self.dataDir, outfile) + + form = apdf.facades.Form(path_infile) + form_data = {} + # Get values from all fields + for formField in form.field_names: + form_data[formField] = form.get_field(formField) + + # Serialize to JSON + json_string = json.dumps(form_data, indent=4) + print(json_string) + + with open(path_outfile, "w", encoding="utf-8") as json_file: + json_file.write(json_string) +``` + +## Extraer datos a XML desde un archivo PDF + +La exportación de XML es útil para integrar los datos de formularios PDF con sistemas que consumen feeds XML estructurados o esquemas. El [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form) la clase proporciona `export_xml` para manejar la conversión en un solo paso. + +1. Crear un `Form` instancia y enlaza el PDF con `form.bind_pdf(path)`. +1. Abra el archivo de salida como un flujo binario. +1. Llamar `form.export_xml(stream)` para escribir todos los datos de los campos como XML. + +```python + + import aspose.pdf as apdf + from io import FileIO + from os import path + + path_infile = path.join(self.dataDir, infile) + path_outfile = path.join(self.dataDir, outfile) + + # Create Form object + form = apdf.facades.Form() + + # Bind PDF document + form.bind_pdf(path_infile) + + # Export data to XML file + with FileIO(path_outfile, "w") as f: + form.export_xml(f) +``` + +## Exportar datos a FDF desde un archivo PDF + +FDF (Forms Data Format) es el formato de intercambio estándar para los datos de AcroForm y es ampliamente compatible con los visualizadores de PDF y las herramientas de procesamiento. Usar `export_fdf` en el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form) clase para producir un archivo FDF independiente que pueda importarse de nuevo al PDF original o a otro formulario compatible. + +1. Crear un `Form` instancia y vincula el PDF de origen con `form.bind_pdf(path)`. +1. Abra el archivo de salida como un flujo binario. +1. Llamar `form.export_fdf(stream)` para escribir los datos FDF. + +```python + + import aspose.pdf as apdf + from io import FileIO + from os import path + + path_infile = path.join(self.dataDir, infile) + path_outfile = path.join(self.dataDir, outfile) + + # Create Form object + form = apdf.facades.Form() + + # Bind PDF document + form.bind_pdf(path_infile) + + # Export form data to an FDF file + with FileIO(path_outfile, "w") as f: + form.export_fdf(f) +``` + +## Exportar datos a XFDF desde un archivo PDF + +XFDF (Formato de Datos de Formularios XML) es el sucesor basado en XML de FDF y está mejor adaptado para su uso en servicios web y canalizaciones de datos modernas. Al igual que FDF, un archivo XFDF puede importarse de nuevo en un formulario PDF compatible. Usar `export_xfdf` en el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form) clase para generar la salida. + +1. Crear un `Form` instancia y vincula el PDF de origen con `form.bind_pdf(path)`. +1. Abra el archivo de salida como un flujo binario. +1. Llamar `form.export_xfdf(stream)` para escribir los datos XFDF. + +```python + + import aspose.pdf as apdf + from io import FileIO + from os import path + + path_infile = path.join(self.dataDir, infile) + path_outfile = path.join(self.dataDir, outfile) + + # Create Form object + form = apdf.facades.Form() + + # Bind PDF document + form.bind_pdf(path_infile) + + # Export form data to an XFDF file + with FileIO(path_outfile, "w") as f: + form.export_xfdf(f) +``` diff --git a/es/python-net/parsing/extract-data-from-tables/_index.md b/es/python-net/parsing/extract-data-from-tables/_index.md new file mode 100644 index 000000000..fe1089c8b --- /dev/null +++ b/es/python-net/parsing/extract-data-from-tables/_index.md @@ -0,0 +1,139 @@ +--- +title: Extraer datos de una tabla en PDF con Python +linktitle: Extraer datos de una tabla +type: docs +weight: 40 +url: /es/python-net/extract-data-from-table-in-pdf/ +description: Aprenda cómo extraer datos de tablas de archivos PDF con Aspose.PDF for Python y exportar los resultados para un procesamiento posterior. +lastmod: "2025-03-13" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo extraer datos de una tabla en PDF mediante Python +Abstract: Este artículo explica cómo extraer y procesar datos de tablas de documentos PDF con Aspose.PDF for Python. Muestra cómo escanear cada página con TableAbsorber, leer filas y celdas de las tablas detectadas, limitar la extracción a una región anotada específica y exportar el contenido PDF a formato CSV para su uso en herramientas de hoja de cálculo y procesamiento posterior. +--- + +## Extraer tablas de PDF programáticamente + +Usar [TableAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/) para detectar tablas en cada página de un [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). Después de visitar una página, itera a través de `table_list`, luego recorre cada fila y celda para reconstruir el contenido de la tabla en un formato de texto legible. + +1. Abra el PDF como un `Document`. +1. Iterar a través de las páginas en `document.pages`. +1. Crear un `TableAbsorber` para cada página y llame `visit(page)`. +1. Recorre las tablas, filas y celdas detectadas. +1. Lee fragmentos de texto de cada celda y ensambla la salida de la fila extraída. + +```python +import aspose.pdf as apdf +from os import path + +path_infile = path.join(self.dataDir, infile) + +# Open PDF document +document = apdf.Document(path_infile) + +# Iterate through each page in the document +for page in document.pages: + absorber = apdf.text.TableAbsorber() + absorber.visit(page) + + for table in absorber.table_list: + print("Table") + for row in table.row_list: + row_text = [] + for cell in row.cell_list: + cell_text = [] + for fragment in cell.text_fragments: + cell_text.append("".join(seg.text for seg in fragment.segments)) + row_text.append("|".join(cell_text)) + print("|".join(row_text)) +``` + +## Extraer tabla en área específica de la página PDF + +Si necesita extraer solo tablas ubicadas dentro de una región marcada, combine [TableAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/) con un [SquareAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/squareannotation/). En este ejemplo, el rectángulo de anotación se usa como límite, y solo se procesan las tablas que están completamente contenidas dentro de esa región. + +1. Abra el PDF como un `Document`. +1. Seleccione la página de destino. +1. Encuentre la anotación cuadrada que marca la región de interés. +1. Crear un `TableAbsorber` y visite la página. +1. Compara cada rectángulo de tabla detectado con el rectángulo de anotación. +1. Procesa sólo las tablas que estén completamente dentro del área marcada. + +```python +import aspose.pdf as apdf +from os import path + +# The path to the documents directory +path_infile = path.join(self.dataDir, infile) + +# Open PDF document +document = apdf.Document(path_infile) + +# Get the first page (index starts from 1 in Aspose.PDF) +page = document.pages[1] + +# Find the first square annotation +square_annotation = next( + ( + ann + for ann in page.annotations + if ann.annotation_type == apdf.annotations.AnnotationType.SQUARE + ), + None, +) + +if square_annotation is None: + print("No square annotation found.") + return + +# Initialize the TableAbsorber +absorber = apdf.text.TableAbsorber() +absorber.visit(page) + +# Iterate through tables on the page +for table in absorber.table_list: + table_rect = table.rectangle + annotation_rect = square_annotation.rect + + # Check if the table is inside the annotation region + is_in_region = ( + annotation_rect.llx < table_rect.llx + and annotation_rect.lly < table_rect.lly + and annotation_rect.urx > table_rect.urx + and annotation_rect.ury > table_rect.ury + ) + + if is_in_region: + for row in table.row_list: + row_text = [] + for cell in row.cell_list: + cell_text = [] + for fragment in cell.text_fragments: + cell_text.append("".join(seg.text for seg in fragment.segments)) + row_text.append("|".join(cell_text)) + print("|".join(row_text)) +``` + +## Exportar datos de tabla de PDF a CSV + +Cuando necesites los datos extraídos en un formato compatible con hojas de cálculo, guarda el PDF usando [ExcelSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/) y establezca el formato de salida en CSV. El archivo resultante se puede abrir en Excel, Google Sheets o importarse en flujos de trabajo de análisis. + +1. Abra el PDF de origen como un [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Crear un `ExcelSaveOptions` instancia. +1. Establecer `excel_save.format` a `ExcelSaveOptions.ExcelFormat.CSV`. +1. Guarde el documento en la ruta CSV de destino. + +```python +import aspose.pdf as apdf +from os import path + +path_infile = path.join(self.dataDir, infile) +path_outfile = path.join(self.dataDir, outfile) + +document = apdf.Document(path_infile) +excel_save = apdf.ExcelSaveOptions() +excel_save.format = apdf.ExcelSaveOptions.ExcelFormat.CSV +document.save(path_outfile, excel_save) +``` diff --git a/es/python-net/parsing/extract-fonts-from-pdf/_index.md b/es/python-net/parsing/extract-fonts-from-pdf/_index.md new file mode 100644 index 000000000..9f921db6f --- /dev/null +++ b/es/python-net/parsing/extract-fonts-from-pdf/_index.md @@ -0,0 +1,37 @@ +--- +title: Extraer fuentes de PDF mediante Python +linktitle: Extraer fuentes de PDF +type: docs +weight: 30 +url: /es/python-net/extract-fonts-from-pdf/ +description: Utilice la biblioteca Aspose.PDF for Python para extraer todas las fuentes incrustadas de su documento PDF. +lastmod: "2026-04-16" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo extraer fuentes de PDF usando Python +Abstract: Este artículo explica cómo inspeccionar las fuentes utilizadas en un documento PDF con Aspose.PDF for Python. Muestra cómo abrir un PDF con la clase Document, llamar a `font_utilities.get_all_fonts()` para obtener los objetos de fuente disponibles y recorrer los resultados para leer los nombres de las fuentes para análisis, auditoría o flujos de trabajo de procesamiento de documentos. +--- + +Usar [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) para abrir el PDF y llamar `font_utilities.get_all_fonts()` para recuperar todo lo disponible [Font](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/font/) objetos referenciados por el documento. Esto es útil al auditar fuentes incrustadas, verificar la disponibilidad de fuentes antes de la conversión o analizar los recursos del documento. + +1. Abra el PDF de origen como un `Document`. +1. Llamar `document.font_utilities.get_all_fonts()` para obtener la colección de fuentes. +1. Iterar a través de lo devuelto `Font` objetos. +1. Leer e imprimir cada `font.font_name` valor. + +```python + + import aspose.pdf as apdf + from os import path + + path_infile = path.join(self.dataDir, infile) + + # Open PDF document + document = apdf.Document(path_infile) + + fonts = document.font_utilities.get_all_fonts() + for font in fonts: + print(font.font_name) +``` diff --git a/es/python-net/parsing/extract-images-from-pdf/_index.md b/es/python-net/parsing/extract-images-from-pdf/_index.md new file mode 100644 index 000000000..07de251e4 --- /dev/null +++ b/es/python-net/parsing/extract-images-from-pdf/_index.md @@ -0,0 +1,37 @@ +--- +title: Extraer imágenes de PDF usando Python +linktitle: Extraer imágenes de PDF +type: docs +weight: 20 +url: /es/python-net/extract-images-from-the-pdf-file/ +description: Aprenda cómo extraer imágenes incrustadas de archivos PDF con Aspose.PDF for Python. +lastmod: "2026-04-16" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Cómo extraer imágenes de PDF vía Python +Abstract: Este artículo explica cómo extraer imágenes incrustadas de un documento PDF con Aspose.PDF for Python. Cubre la apertura del PDF de origen con la clase Document, el acceso a una imagen de la colección de recursos de la página y la guardación de la XImage extraída en un archivo externo para reutilizarla, inspeccionarla o procesarla posteriormente. +--- + +Usar [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) para abrir el PDF, luego acceder a los recursos de la página para recuperar una [XImage](https://reference.aspose.com/pdf/python-net/aspose.pdf/ximage/) objeto y guárdelo como un archivo separado. Este enfoque es útil cuando necesita reutilizar imágenes, inspeccionar los recursos extraídos o crear flujos de trabajo de procesamiento de imágenes a partir del contenido PDF. + +1. Abra el PDF como un `Document`. +1. Acceda al recurso de imagen de la página objetivo. +1. Recuperar lo requerido `XImage` de la colección de imágenes de la página. +1. Guarde la imagen extraída en un archivo de salida. + +```python + + import aspose.pdf as apdf + from io import FileIO + from os import path + + path_infile = path.join(self.dataDir, infile) + path_outfile = path.join(self.dataDir, outfile) + + document = apdf.Document(path_infile) + xImage = document.pages[1].resources.images[1] + with FileIO(path_outfile, "w") as output_image: + xImage.save(output_image) +``` diff --git a/es/python-net/parsing/extract-text-from-pdf/_index.md b/es/python-net/parsing/extract-text-from-pdf/_index.md new file mode 100644 index 000000000..a1ef8130b --- /dev/null +++ b/es/python-net/parsing/extract-text-from-pdf/_index.md @@ -0,0 +1,19 @@ +--- +title: Extraer texto de PDF usando Python +linktitle: Extraer texto de PDF +type: docs +weight: 10 +url: /es/python-net/extract-text-from-pdf/ +description: Esta sección contiene artículos sobre la extracción de texto de documentos PDF utilizando Aspose.PDF en Python. +lastmod: "2025-11-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +## Artículos en esta sección + +- [Extracción básica de texto](/pdf/es/python-net/basic-text-extraction/) +- [Extracción basada en regiones](/pdf/es/python-net/region-based-extraction/) +- [Extracción de texto de PDFs de varias columnas](/pdf/es/python-net/text-extraction-from-multi‑column-pdf/) +- [Anotaciones y Texto Especial](/pdf/es/python-net/annotations-and-special-text/) \ No newline at end of file diff --git a/es/python-net/parsing/extract-text-from-pdf/annotations-and-special-text/_index.md b/es/python-net/parsing/extract-text-from-pdf/annotations-and-special-text/_index.md new file mode 100644 index 000000000..2b00bea43 --- /dev/null +++ b/es/python-net/parsing/extract-text-from-pdf/annotations-and-special-text/_index.md @@ -0,0 +1,161 @@ +--- +title: Anotaciones y Texto Especial usando Python +linktitle: Anotaciones y Texto Especial +type: docs +weight: 40 +url: /es/python-net/annotation-and-special-text/ +description: Aprenda cómo extraer texto de anotaciones de sello, texto resaltado y contenido de superíndice/subíndice en documentos PDF usando Aspose.PDF for Python. +lastmod: "2025-11-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +## Extraer Texto de Anotaciones de Sello + +Usar [TextAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textabsorber) para extraer texto incrustado en un [StampAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/stampannotation) flujo de apariencia. Esto es útil cuando el contenido del sello se renderiza como un XObject de formulario en lugar de almacenarse como texto plano. + +1. Abrir el [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document). +1. Acceder a la anotación de destino desde `page.annotations`. +1. Verifique que es un `StampAnnotation`, luego recupere su apariencia normal XForm. +1. Pasar el XForm a `TextAbsorber.visit()` para extraer el texto incrustado. + +```python +import os +import aspose.pdf as ap + + +def extract_text_from_stamp(infile, page_number, annotation_index, outfile): + """ + Extracts text from a stamp annotation on a given page in a PDF document. + Args: + infile (str): Path to the input PDF file. + page_number (int): 1-based index of the page containing the stamp. + annotation_index (int): 1-based index of the annotation in that page. + outfile (str): Path to the output text file where extracted text will be saved. + """ + document = ap.Document(infile) + try: + page = document.pages[page_number] + annot = page.annotations[annotation_index] + # Ensure it's a StampAnnotation + if isinstance(annot, ap.annotations.StampAnnotation): + # Get normal appearance XForm of the stamp + xform = annot.appearance["N"] + absorber = ap.text.TextAbsorber() + absorber.visit(xform) + extracted = absorber.text + with open(outfile, "w", encoding="utf-8") as f: + f.write(extracted) + finally: + document.close() +``` + +## Extraer texto resaltado + +Iterar sobre las anotaciones de una página y usar [HighlightAnnotation.get_marked_text()](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/highlightannotation) para leer los fragmentos de texto cubiertos por cada resaltado. La colección de anotaciones de la página está basada en 1. + +1. Abrir el [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document) y seleccione la página de destino. +1. Recorrer `page.annotations`. +1. Usar `is_assignable` para filtrar [HighlightAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/highlightannotation) instancias. +1. Convierta la anotación y llame `get_marked_text()` para recuperar el contenido resaltado. + +```python +def extract_highlight_text(infile): + """ + Extract text from highlight annotations. + + Args: + infile (str): Input PDF filename + + Returns: + None + + Example: + extract_highlight_text("sample.pdf") + + Note: + Prints marked text from each highlight annotation on first page. + """ + document = ap.Document(infile) + page = document.pages[1] + + for annotation in page.annotations: + if is_assignable(annotation, ap.annotations.HighlightAnnotation): + highlight_annotation = cast(ap.annotations.HighlightAnnotation, annotation) + print(highlight_annotation.get_marked_text()) +``` + +## Extraer texto en superíndice y subíndice + +Los superíndices y subíndices aparecen con frecuencia en fórmulas, expresiones matemáticas y nombres de compuestos químicos. Aspose.PDF for Python via .NET admite extraer este contenido a través [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber), que detecta metadatos de posicionamiento a nivel de carácter. + +1. Abrir el [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document). +1. Crear un `TextFragmentAbsorber` instancia. +1. Llamar `document.pages[page_number].accept(absorber)` para escanear la página objetivo. +1. Recuperar el texto extraído completo de `absorber.text`. +1. Escriba el resultado en un archivo y cierre el documento. + +```python +import os +import aspose.pdf as ap + + +def extract_super_sub_text(infile, outfile, page_number=1): + """ + Extract text (including superscript/subscript) from a specified page of a PDF and write to a text file. + Args: + infile (str): Path to input PDF file. + outfile (str): Path to output text file. + page_number (int): 1‑based index of the page to extract. + """ + document = ap.Document(infile) + try: + absorber = ap.text.TextFragmentAbsorber() + # Accept only the specific page for extraction + document.pages[page_number].accept(absorber) + extracted_text = absorber.text + with open(outfile, "w", encoding="utf-8") as f: + f.write(extracted_text) + finally: + document.close() +``` + +## Iterar a través de fragmentos de texto para detectar superíndice/subíndice + +Para la inspección por fragmento, iterar sobre `absorber.text_fragments` y leer el `text_state.superscript` y `text_state.subscript` banderas booleanas en cada [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment). + +1. Abrir el [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document) y crear un [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber). +1. Aceptar el absorber en la página de destino para poblar `absorber.text_fragments`. +1. Para cada fragmento, lea `fragment.text`, `fragment.text_state.superscript`, y `fragment.text_state.subscript`. +1. Escriba los resultados en el archivo de salida y cierre el documento. + +```python +import os +import aspose.pdf as ap + + +def extract_super_sub_details(infile, outfile, page_number=1): + """ + Extract details of each text fragment on a page, identifying superscript and subscript items. + Args: + infile (str): Path to input PDF file. + outfile (str): Path to output text file. + page_number (int): 1‑based page index. + """ + document = ap.Document(infile) + try: + absorber = ap.text.TextFragmentAbsorber() + document.pages[page_number].accept(absorber) + + with open(outfile, "w", encoding="utf-8") as f: + for fragment in absorber.text_fragments: + text = fragment.text + is_sup = fragment.text_state.superscript # True if superscript + is_sub = fragment.text_state.subscript # True if subscript + f.write( + f"Text: '{text}' | Superscript: {is_sup} | Subscript: {is_sub}\n" + ) + finally: + document.close() +``` diff --git a/es/python-net/parsing/extract-text-from-pdf/basic-text-extraction/_index.md b/es/python-net/parsing/extract-text-from-pdf/basic-text-extraction/_index.md new file mode 100644 index 000000000..d31540354 --- /dev/null +++ b/es/python-net/parsing/extract-text-from-pdf/basic-text-extraction/_index.md @@ -0,0 +1,78 @@ +--- +title: Extracción básica de texto usando Python +linktitle: Extracción básica de texto +type: docs +weight: 10 +url: /es/python-net/basic-text-extraction/ +description: Aprende cómo extraer texto de documentos PDF usando Aspose.PDF for Python — de todas las páginas a la vez o de una página específica. +lastmod: "2025-11-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +## Extraer texto de todas las páginas de un documento PDF + +Usar [TextAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textabsorber) para capturar todo el texto de cada página de un documento PDF y escribirlo en un archivo de texto. Este enfoque es adecuado para convertir PDFs a texto indexable, ejecutar análisis de contenido o preparar texto para la indexación y el procesamiento posterior. + +1. Abrir el documento PDF usando [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document). +1. Crear un `TextAbsorber` instancia. +1. Llamar `document.pages.accept(text_absorber)` para escanear todas las páginas. +1. Recuperar el texto extraído de `text_absorber.text`. +1. Escribe el resultado en un archivo de texto de salida. + +```python +import os +import aspose.pdf as ap + + +def extract_text_from_all_pages(infile, outfile): + """ + Extract all text from every page of the PDF and write to an output text file. + Args: + infile (str): Path to input PDF file. + outfile (str): Path to output text file. + """ + # Open the PDF document + document = ap.Document(infile) + # Create a TextAbsorber to extract text + text_absorber = ap.text.TextAbsorber() + # Accept the absorber for all pages + document.pages.accept(text_absorber) + # Get extracted text + extracted_text = text_absorber.text + # Write the text to an output file + with open(outfile, "w", encoding="utf-8") as tw: + tw.write(extracted_text) +``` + +## Extraer texto de una página particular + +Aplicar [TextAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textabsorber) a una sola página para aislar y guardar el texto de esa sección de un documento de varias páginas. Esto es útil cuando solo necesitas contenido de una página — por ejemplo, una factura, una sección de informe o un resumen de formulario. + +1. Abrir el documento PDF usando [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document). +1. Crear un `TextAbsorber` instancia. +1. Llamar `accept` en la página de destino: `document.pages[page_number].accept(text_absorber)`. +1. Recupera el texto extraído y escríbelo en un archivo. + +```python +import os +import aspose.pdf as ap + + +def extract_text_from_page(infile, outfile, page_number): + """ + Extract text from a specific page number of the PDF. + Args: + infile (str): Path to input PDF file. + outfile (str): Path to output text file. + page_number (int): 1-based page index to extract. + """ + document = ap.Document(infile) + text_absorber = ap.text.TextAbsorber() + # Accept the absorber on only the specified page + document.pages[page_number].accept(text_absorber) + extracted_text = text_absorber.text + with open(outfile, "w", encoding="utf-8") as tw: + tw.write(extracted_text) +``` diff --git a/es/python-net/parsing/extract-text-from-pdf/region-based-extraction/_index.md b/es/python-net/parsing/extract-text-from-pdf/region-based-extraction/_index.md new file mode 100644 index 000000000..ad071530c --- /dev/null +++ b/es/python-net/parsing/extract-text-from-pdf/region-based-extraction/_index.md @@ -0,0 +1,140 @@ +--- +title: Extracción basada en regiones usando Python +linktitle: Extracción basada en regiones +type: docs +weight: 20 +url: /es/python-net/region-based-extraction/ +description: Aprenda cómo extraer texto de una región de página específica o de la estructura de párrafos en documentos PDF con Aspose.PDF for Python. +lastmod: "2026-04-16" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +## Extraer texto de una región específica de una página + +Usar [TextAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textabsorber/) junto con un [Rectángulo](https://reference.aspose.com/pdf/python-net/aspose.pdf/rectangle/) para limitar la extracción a un área específica de una página. Este enfoque es útil para la extracción por zonas de encabezados, pies de página, celdas de tabla, campos de formulario, facturas u otras regiones de diseño fijo donde la posición del texto se conoce de antemano. + +1. Abra el PDF de origen como un [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Crear un `TextAbsorber` instancia. +1. Configurar `text_search_options` para limitar la extracción a un rectángulo. +1. Acepta el absorber en la página objetivo. +1. Escribe el texto extraído en un archivo de salida. + +```python +import aspose.pdf as ap + + +def extract_text_from_region(infile, page_number, rect_coords, outfile): + """ + Extract text from a specified rectangular region on a given page. + Args: + infile (str): Path to input PDF file. + page_number (int): 1-based index of the page. + rect_coords (tuple): (llx, lly, urx, ury) coordinates of the rectangle. + outfile (str): Output text file path. + """ + document = ap.Document(infile) + try: + absorber = ap.text.TextAbsorber() + # Set options to restrict search to the rectangle + absorber.text_search_options.limit_to_page_bounds = True + llx, lly, urx, ury = rect_coords + absorber.text_search_options.rectangle = ap.Rectangle(llx, lly, urx, ury, True) + # Accept on the specific page + document.pages[page_number].accept(absorber) + extracted_text = absorber.text + with open(outfile, "w", encoding="utf-8") as tw: + tw.write(extracted_text) + finally: + document.close() +``` + +## Extraer párrafos iterando a través de ellos + +Usar [ParagraphAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/paragraphabsorber/) cuando necesitas extracción consciente de párrafos en lugar de texto plano de página. A diferencia de [TextAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textabsorber/) o [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber/), esta API organiza la salida por página, sección y párrafo, lo que es útil para el análisis de texto, la exportación estructurada y el procesamiento sensible al diseño. + +1. Abra el PDF de origen como un [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Crear un `ParagraphAbsorber` instancia. +1. Llamar `absorber.visit(document)` para analizar todas las páginas. +1. Iterar a través de `page_markups`, luego a través de cada sección y párrafo. +1. Leer los fragmentos de texto de cada párrafo y escribir el resultado en un archivo. + +```python +import aspose.pdf as ap + + +def extract_paragraphs_from_pdf(infile, outfile): + """ + Extract all paragraphs from a PDF document, and write each paragraph’s text into an output file. + Args: + infile (str): Path to input PDF file. + outfile (str): Path to output text file. + """ + document = ap.Document(infile) + try: + absorber = ap.text.ParagraphAbsorber() + absorber.visit(document) + + with open(outfile, "w", encoding="utf-8") as tw: + for page_markup in absorber.page_markups: + for sec_idx, section in enumerate(page_markup.sections, start=1): + for para_idx, paragraph in enumerate(section.paragraphs, start=1): + # Concatenate all fragments/lines in the paragraph + parts = [] + for line in paragraph.lines: + for fragment in line: + parts.append(fragment.text) + parts.append("\r\n") + paragraph_text = "".join(parts) + tw.write( + f"Page {page_markup.number}, Section {sec_idx}, Paragraph {para_idx}:\n" + ) + tw.write(paragraph_text + "\n") + finally: + document.close() +``` + +## Extraer párrafos con renderizado de polígono delimitador + +También puede usar [ParagraphAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/paragraphabsorber/) para inspeccionar la geometría de los párrafos. Además de extraer texto, este enfoque registra el rectángulo de cada sección y el polígono del párrafo, lo cual es útil para el mapeo de diseño, el análisis de documentos, herramientas de accesibilidad o el post-procesamiento dependiente de regiones. + +1. Abra el PDF de origen como un [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Crear un `ParagraphAbsorber` instancia. +1. Visita la página objetivo. +1. Leer el marcado de la página desde `absorber.page_markups`. +1. Itera a través de secciones y párrafos para capturar la geometría y el texto. +1. Escribe los datos de rectángulo, polígono y texto en el archivo de salida. + +```python +import aspose.pdf as ap + + +def extract_paragraphs_with_geometry(infile, outfile): + """ + Extract paragraphs and record geometry info (rectangle / polygon) for each paragraph in a PDF. + Args: + infile (str): Path to input PDF file. + outfile (str): Path to output text file. + """ + document = ap.Document(infile) + try: + absorber = ap.text.ParagraphAbsorber() + absorber.visit(document.pages[1]) # Visit page 2 (pages are 1-indexed) + + page_markup = absorber.page_markups[0] + with open(outfile, "w", encoding="utf-8") as tw: + for sec_idx, section in enumerate(page_markup.sections, start=1): + tw.write(f"Section {sec_idx}: rectangle = {section.rectangle}\n") + for para_idx, paragraph in enumerate(section.paragraphs, start=1): + tw.write(f" Paragraph {para_idx}: polygon = {paragraph.points}\n") + # Concatenate paragraph text + parts = [] + for line in paragraph.lines: + for fragment in line: + parts.append(fragment.text) + parts.append("\r\n") + tw.write(" Text: " + "".join(parts) + "\n\n") + finally: + document.close() +``` diff --git a/es/python-net/parsing/extract-text-from-pdf/text-extraction-from-multi-column-pdf/_index.md b/es/python-net/parsing/extract-text-from-pdf/text-extraction-from-multi-column-pdf/_index.md new file mode 100644 index 000000000..8c7558b45 --- /dev/null +++ b/es/python-net/parsing/extract-text-from-pdf/text-extraction-from-multi-column-pdf/_index.md @@ -0,0 +1,88 @@ +--- +title: Mejorar la extracción de texto de PDFs de varias columnas +linktitle: Extracción de texto de PDFs de varias columnas +type: docs +weight: 30 +url: /es/python-net/text-extraction-from-multi-column-pdf/ +description: Aprenda técnicas para mejorar la extracción de texto de diseños PDF multicolumna con Aspose.PDF for Python. +lastmod: "2026-04-16" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +## Reduzca el tamaño de Font manualmente y luego extraiga + +En algunos diseños de varias columnas, reducir el tamaño de Font de los fragmentos de texto antes de la extracción puede mejorar el orden de lectura y reducir los problemas de superposición. Esta técnica puede ayudar con documentos con formato ajustado como revistas, artículos de investigación, folletos o informes con columnas de texto densas. + +1. Cargue el PDF. +1. Usar [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber/) para recopilar los fragmentos de texto. +1. Reduce el tamaño de la fuente de cada fragmento, luego guarda y vuelve a abrir el documento. +1. Usar [TextAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textabsorber/) para extraer el texto. +1. Escribe el texto extraído en un archivo de salida. + +```python +import io +import aspose.pdf as ap + + +def extract_text_reduce_font(infile, outfile, reduce_ratio=0.7): + """ + Extract text from a multi-column PDF by first reducing font size of all text fragments. + Args: + infile (str): Path to input PDF. + outfile (str): Output text file. + reduce_ratio (float): Ratio to reduce font size (e.g., 0.7 = 70%). + """ + doc = ap.Document(infile) + + frag_absorber = ap.text.TextFragmentAbsorber() + doc.pages.accept(frag_absorber) + for frag in frag_absorber.text_fragments: + frag.text_state.font_size = frag.text_state.font_size * reduce_ratio + # Save to memory stream and reopen (to apply changes) + ms = io.BytesIO() + doc.save(ms) + ms.seek(0) + doc2 = ap.Document(ms) + text_absorber = ap.text.TextAbsorber() + doc2.pages.accept(text_absorber) + extracted_text = text_absorber.text + with open(outfile, "w", encoding="utf-8") as tw: + tw.write(extracted_text) +``` + +## Extraer texto con factor de escala + +Otra opción para la extracción de múltiples columnas es configurar [TextExtractionOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textextractionoptions/) con un factor de escala. Ajustar el factor de escala puede mejorar la interpretación de fragmentos muy compactos y ayudar a preservar un orden de lectura más preciso en diseños densos, tablas o documentos basados en columnas. + +1. Cargue el PDF. +1. Crear un [TextAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textabsorber/). +1. Configurar `TextExtractionOptions.scale_factor`. +1. Asigne las opciones de extracción al absorbente. +1. Extraiga el texto de la página y escriba el resultado en un archivo de salida. + +```python +import aspose.pdf as ap + + +def extract_text_scale_factor(infile, outfile, scale_factor=0.5): + """ + Extract text from a PDF with multi-column layout using scale factor. + Args: + infile (str): Input PDF path. + outfile (str): Output text file path. + scale_factor (float): Scale factor between 0.1 and 1.0 or 0 for auto-scaling. + """ + doc = ap.Document(infile) + text_absorber = ap.text.TextAbsorber() + ext_opts = ap.text.TextExtractionOptions( + ap.text.TextExtractionOptions.TextFormattingMode.PURE + ) + ext_opts.scale_factor = scale_factor + text_absorber.extraction_options = ext_opts + doc.pages.accept(text_absorber) + extracted_text = text_absorber.text + with open(outfile, "w", encoding="utf-8") as tw: + tw.write(extracted_text) +``` diff --git a/es/python-net/parsing/extract-vector-data-from-pdf/_index.md b/es/python-net/parsing/extract-vector-data-from-pdf/_index.md new file mode 100644 index 000000000..ea3560ce1 --- /dev/null +++ b/es/python-net/parsing/extract-vector-data-from-pdf/_index.md @@ -0,0 +1,178 @@ +--- +title: Extraer datos vectoriales de un archivo PDF usando Python +linktitle: Extraer datos vectoriales de PDF +type: docs +weight: 80 +url: /es/python-net/extract-vector-data-from-pdf/ +description: Aspose.PDF facilita la extracción de datos vectoriales de un archivo PDF. Puedes obtener los datos vectoriales (ruta, polígono, polilínea), como posición, color, ancho de línea, etc. +lastmod: "2026-04-16" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +## Acceder a datos vectoriales de un documento PDF + +Usar [GraphicsAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/graphicsabsorber/) para inspeccionar elementos gráficos vectoriales en una página de un [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). Después de visitar la página objetivo, itere a través de los elementos extraídos para examinar propiedades como los límites rectangulares, posiciones y operadores de dibujo. + +1. Abra el PDF de origen como un `Document`. +1. Crear un `GraphicsAbsorber` instancia. +1. Llamar `gr_absorber.visit(page)` en la página de destino. +1. Leer los elementos extraídos de `gr_absorber.elements`. +1. Itere a través de los elementos y escriba sus propiedades en un archivo de salida. + +```python +import aspose.pdf as ap + + +def extract_graphics_elements(infile, outfile): + """ + Extract vector graphic elements from a specified page of a PDF and log basic element properties. + Args: + infile (str): Path to input PDF file. + outfile (str): Path to output text file for logging element info. + """ + document = ap.Document(infile) + try: + gr_absorber = ap.vector.GraphicsAbsorber() + # Visit page 2 (pages collection is 1-indexed; document.pages[1] is the second page) + gr_absorber.visit(document.pages[1]) + + elements = gr_absorber.elements + with open(outfile, "w", encoding="utf-8") as f: + for idx, elem in enumerate(elements, start=1): + # Basic properties + rect = elem.rectangle + pos = elem.position + ops_count = len(elem.operators) + f.write( + f"Element {idx}: Rectangle = {rect}, Position = {pos}, Operators = {ops_count}\n" + ) + finally: + document.close() +``` + +## Guardar gráficos vectoriales de una página en un archivo SVG + +Exportar gráficos vectoriales de una página PDF a SVG para preservar rutas y formas escalables fuera del PDF original. Este método es útil para reutilizar arte vectorial en flujos de trabajo web, de diseño o de publicación. + +1. Cargar el documento PDF. +1. Acceda a la página objetivo. +1. Llamar `page.try_save_vector_graphics()` para exportar las rutas vectoriales de la página a SVG. +1. Cierre el documento. + +```python +import aspose.pdf as ap + + +def save_vector_graphics_to_svg(infile, svg_outfile): + """ + Save vector graphics from a specified page of a PDF document into an SVG file. + Args: + infile (str): Path to input PDF file. + svg_outfile (str): Path to output SVG file. + """ + document = ap.Document(infile) + try: + page = document.pages[1] + # Try to save vector graphics into SVG + page.try_save_vector_graphics(svg_outfile) + finally: + document.close() +``` + +### Extraer cada subruta a un SVG separado + +Cuando una página contiene múltiples rutas vectoriales independientes, use [SvgExtractionOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/svgextractionoptions/) con [SvgExtractor](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/svgextractor/) para escribir cada subruta en un archivo SVG separado. + +1. Cargue el PDF. +1. Crear `SvgExtractionOptions` y establecer `extract_every_subpath_to_svg`. +1. Accede a la primera página del documento. +1. Instanciar `SvgExtractor` con las opciones. +1. Llamar `extractor.extract()` escribir archivos SVG separados para cada subruta vectorial. +1. Cierre el documento. + +```python +import aspose.pdf as ap + + +def extract_subpaths_to_svgs(infile, output_dir): + """ + Extract each vector sub-path on a PDF page into separate SVG files using extraction options. + Args: + infile (str): Input PDF file path. + output_dir (str): Directory path where SVG files will be saved. + """ + document = ap.Document(infile) + try: + options = ap.vector.SvgExtractionOptions() + options.extract_every_subpath_to_svg = True + + page = document.pages[1] + extractor = ap.vector.SvgExtractor(options) + extractor.extract(page, output_dir) + finally: + document.close() +``` + +### Extraer una lista de elementos a una sola imagen + +Extraer varios elementos vectoriales de una página PDF y guardarlos como una única imagen SVG combinada. Esto es útil cuando deseas preservar la relación visual entre formas agrupadas, diagramas o fragmentos de dibujo. + +1. Abra el PDF usando [Documento](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Seleccione una página y prepare una lista de elementos vectoriales. +1. Usar [SvgExtractor](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/svgextractor/) para combinar esos elementos en un solo SVG. +1. Guarde el archivo de salida. + +```python +import aspose.pdf as ap + + +def extract_list_of_elements_to_single_image(infile, outfile): + """ + Extracts multiple vector graphic elements from a PDF page and saves them as a single SVG image. + Args: + infile (str): Path to the input PDF file. + outfile (str): Path to the output SVG file. + """ + document = ap.Document(infile) + try: + page = document.pages[1] + svg_extractor = ap.vector.SvgExtractor() + elements = [] # Fill this list with specific graphic elements as needed + svg_extractor.extract(elements, page, outfile) + finally: + document.close() +``` + +### Extraer un solo elemento + +Extrae un elemento vectorial específico de un PDF y guárdalo como un archivo SVG individual. Esto es útil para aislar logotipos, íconos o formas independientes de páginas vectoriales más complejas. + +1. Crear un [GraphicsAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/graphicsabsorber/) para capturar datos vectoriales. +1. Visite una página específica para recopilar sus elementos vectoriales. +1. Seleccione un elemento objetivo, como un [XFormPlacement](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/xformplacement/). +1. Guarda ese único elemento en un archivo SVG. + +```python +import aspose.pdf as ap + + +def extract_single_vector_element(infile, outfile): + """ + Extracts a specific vector graphic element (e.g., an XFormPlacement) from a PDF page and saves it as an SVG file. + Args: + infile (str): Path to the input PDF file. + outfile (str): Path to the output SVG file. + """ + document = ap.Document(infile) + try: + graphics_absorber = ap.vector.GraphicsAbsorber() + page = document.pages[1] + graphics_absorber.visit(page) + xform_placement = graphics_absorber.elements[1] + if isinstance(xform_placement, ap.vector.XFormPlacement): + xform_placement.elements[2].save_to_svg(outfile) + finally: + document.close() +``` diff --git a/es/python-net/whatsnew/_index.md b/es/python-net/whatsnew/_index.md index 56c79f51b..3b21224d4 100644 --- a/es/python-net/whatsnew/_index.md +++ b/es/python-net/whatsnew/_index.md @@ -4,342 +4,1166 @@ linktitle: Qué hay de nuevo type: docs weight: 10 url: /es/python-net/whatsnew/ -description: En esta página se presentan las características nuevas más populares en Aspose.PDF para Python a través de .NET que se han introducido en lanzamientos recientes. +description: En esta página se presentan las funciones nuevas más populares en Aspose.PDF for Python via .NET que se han introducido en versiones recientes. sitemap: changefreq: "monthly" priority: 0.8 -lastmod: "2021-12-24" +lastmod: "2025-02-24" +TechArticle: false --- -## Qué hay de nuevo en Aspose.PDF 23.12 +## Novedades de Aspose.PDF 26.3 -A partir de Aspose.PDF 23.12, se agregó soporte a las nuevas características de conversión: +En **Aspose.PDF for Python via .NET** 26.3, hemos añadido: -- Implementar conversión de PDF a Markdown +Compresión sin pérdida de flujos de imagen durante la optimización de PDF. La propiedad OptimizationOptions.CompressAllContentStreams ahora también comprime los flujos XObject de imagen elegibles con FlateDecode, ayudando a reducir el tamaño del archivo mientras se mantiene la calidad de la imagen intacta. ```python +import aspose.pdf as ap + + +def optimize_pdf_with_loss_less_image_stream_recompression(infile, outfile): + with ap.Document(infile) as document: + optimize_options = ap.optimization.OptimizationOptions() + optimize_options.subset_fonts = True + optimize_options.allow_reuse_page_content = True + optimize_options.compress_objects = True + optimize_options.link_duplicate_streams = True + optimize_options.remove_unused_objects = True + optimize_options.remove_unused_streams = True + # Compress content streams and eligible image streams + optimize_options.compress_all_content_streams = True + # Optimize PDF document + document.optimize_resources(optimize_options) + # Save optimized PDF document + document.save(outfile) +``` + +La recompresión de imágenes ahora coincide con la configuración ImageCompressionOptions.Encoding seleccionada durante la optimización, asegurando resultados más consistentes al usar Jpeg2000 o Flate, junto con el cambio de tamaño de imágenes, los límites de resolución y los controles de calidad. + +```python +import aspose.pdf as ap + + +def optimize_pdf_images_with_selected_encoding(infile, outfile): + # Open PDF document + with ap.Document(infile) as pdf: + # Configure optimization options + optimize_options = ap.optimization.OptimizationOptions() + optimize_options.allow_reuse_page_content = False + optimize_options.compress_objects = True + optimize_options.link_duplicate_streams = False + optimize_options.remove_unused_objects = True + optimize_options.remove_unused_streams = True + optimize_options.image_compression_options.compress_images = True + optimize_options.image_compression_options.resize_images = True + optimize_options.image_compression_options.max_resolution = 130 + optimize_options.image_compression_options.image_quality = 100 + optimize_options.image_compression_options.encoding = ( + ap.optimization.ImageEncoding.FLATE + ) + optimize_options.image_compression_options.version = ( + ap.optimization.ImageCompressionVersion.MIXED + ) + + # Optimize PDF document resources + pdf.optimize_resources(optimize_options) + # Save optimized PDF document + pdf.save(outfile) +``` + +Compatibilidad para renderizar comentarios al guardar documentos PDF como imágenes o HTML, ayudando a preservar el marcado de revisión visible al exportar documentos anotados para compartir fuera de los visores PDF. - import aspose.pdf as ap +```python +import aspose.pdf as ap + + +def render_comments_to_image_and_html(infile, outfile, output_png): + # Open PDF document + with ap.Document(infile) as document: + # Save the first page to PNG with comments rendered + device = ap.devices.PngDevice() + device.process(document.pages[1], output_png) + # Save the first page to HTML with comments rendered + options = ap.HtmlSaveOptions() + options.explicit_list_of_saved_pages = [1] + options.use_z_order = True + document.save(outfile, options) +``` - input_pdf_path = DIR_INPUT + "input.pdf" - markdown_output_file_path = DIR_OUTPUT + "output_md_file.md" +Rendimiento mejorado de renderizado de PDF a TIFF para escenarios de rasterización de alto volumen, especialmente al exportar páginas a imágenes TIFF bitonales. - doc = ap.Document(input_pdf_path) - save_options = ap.pdftomarkdown.MarkdownSaveOptions() - save_options.resources_directory_name = "images" - doc.save(markdown_output_file_path, save_options) +```python +import aspose.pdf as ap + + +def convert_pdf_to_tiff(infile, data_dir): + # Open PDF document + with ap.Document(infile) as document: + # Create Resolution object + resolution = ap.devices.Resolution(300) + + # Create TiffSettings object + tiff_settings = ap.devices.TiffSettings() + tiff_settings.compression = ap.devices.CompressionType.CCITT4 + tiff_settings.shape = ap.devices.ShapeType.NONE + tiff_settings.skip_blank_pages = False + tiff_settings.depth = ap.devices.ColorDepth.FORMAT_1BPP + + # Create TIFF device + tiff_device = ap.devices.TiffDevice(resolution, tiff_settings) + for i in range(1, len(document.pages) + 1): + target_file_name = data_dir + "Asposeout-" + str(i) + ".tif" + tiff_device.process(document, i, i, target_file_name) ``` -- Implementar conversión de OFD a PDF +## ¿Qué hay de nuevo en Aspose.PDF 26.2? + +Aspose.PDF 26.2 introduce soporte para la conversión de RTF a PDF. Esta característica permite a los desarrolladores convertir directamente documentos Rich Text Format (RTF) en archivos PDF. + +RTF es un formato de documento ampliamente compatible y multiplataforma, desarrollado originalmente por Microsoft. Está diseñado para permitir el intercambio de documentos entre diferentes aplicaciones de procesamiento de texto, conservando el formato básico como fuentes, colores, texto en negrita y cursiva, así como imágenes incrustadas. ```python +import aspose.pdf as ap - import aspose.pdf as ap - input_path = DIR_INPUT + "input.ofd" - output_path = DIR_OUTPUT + "output.pdf" - document = ap.Document(input_path, ap.OfdLoadOptions()) - document.save(output_path) +def convert_rtf_to_pdf(infile, outfile): + # Initialize RTF load options + options = ap.RtfLoadOptions() + # Open RTF document + with ap.Document(infile, options) as document: + # Save PDF document + document.save(outfile) ``` +Este fragmento de código muestra cómo insertar una tabla después del contenido existente en una página PDF usando Aspose.PDF for Python. + +El script abre un documento PDF existente y calcula el cuadro delimitador del contenido actual en la primera página. Utilizando esta información, encuentra dónde termina el contenido existente y posiciona una nueva tabla debajo del último elemento, dejando un margen especificado antes de que la tabla comience. -El soporte para Python 3.6 ha sido descontinuado. +Luego se crea una tabla y se llena con múltiples filas y columnas usando un bucle. Después de configurar la estructura y el contenido de la tabla, la tabla se agrega a la colección de párrafos de la página. Finalmente, el documento actualizado se guarda como un nuevo archivo PDF. -## Novedades en Aspose.PDF 23.11 +```python +import aspose.pdf as ap + + +def add_table_after_last_element(infile, outfile): + # Load source PDF document + with ap.Document(infile) as document: + # Initializes a new instance of the Table + table = ap.Table() + # Determine the existing content area on the page + content_area_lly = document.pages[1].calculate_content_b_box().lly + top_margin = 20 + # Add the table after the existing content, with the 20pt margin before the table. + table.top = document.pages[1].rect.height - (content_area_lly - top_margin) + # Set the top margin for the new pages added. + document.page_info.margin.top = top_margin + # Create a loop to add 10 rows + for row_count in range(1, 11): + # Add row to table + row = table.rows.add() + # Add table cells + row.cells.add("Column (" + str(row_count) + ", 1)") + row.cells.add("Column (" + str(row_count) + ", 2)") + row.cells.add("Column (" + str(row_count) + ", 3)") + + # Add table object to first page of input document + document.pages[1].paragraphs.add(table) + # Save updated document containing table object + document.save(outfile) +``` -Desde la versión 23.11 es posible eliminar el texto oculto. Se puede usar el siguiente fragmento de código: +Detectar y eliminar texto invisible de un documento PDF usando Aspose.PDF para Python: ```python +import aspose.pdf as ap + + +def remove_invisible_text(infile, outfile): + with ap.Document(infile) as pdf_doc: + for page in pdf_doc.pages: + absorber = ap.text.TextFragmentAbsorber() + page.accept(absorber) + fragments_to_remove = [ + x + for x in absorber.text_fragments + if ( + x.text_state.invisible + or x.text_state.rendering_mode + == ap.text.TextRenderingMode.INVISIBLE + or ( + x.text_state.foreground_color is not None + and x.text_state.foreground_color.a == 0 + ) + ) + ] + for fragment in fragments_to_remove: + absorber.text_fragments.remove( + fragment + ) # Now properly removes text from document + pdf_doc.save(outfile) +``` - import aspose.pdf as ap +## ¿Qué hay de nuevo en Aspose.PDF 26.1? - document = ap.Document(input_file) - text_absorber = ap.text.TextFragmentAbsorber() - # Esta opción se puede usar para evitar que otros fragmentos de texto se muevan después de la sustitución del texto oculto. - text_absorber.text_replace_options = ap.text.TextReplaceOptions(ap.text.TextReplaceOptions.ReplaceAdjustment.NONE) - document.pages.accept(text_absorber) +En **Aspose.PDF for Python via .NET** 26.1, hemos añadido: - for fragment in text_absorber.text_fragments: - if fragment.text_state.invisible: - fragment.text = '' +1. Mejoras de rendimiento – se resolvió el bajo rendimiento al agregar texto a los documentos y los problemas de rendimiento en general. +1. Precisión mejorada en la renderización – se corrigió la falta de texto vertical en el lado izquierdo de los PDF y se corrigió la renderización de caracteres chinos durante la conversión de PDF a PNG. +1. Conversión HTML mejorada – la API ahora respeta el color de línea en la conversión HTML a PDF y ha corregido los problemas de superposición de texto en la conversión XFA a Standard. +1. Correcciones de errores para la estructura del documento – NumberingStyle ahora funciona correctamente con objetos Heading, y PDF‑a‑HTML ahora conserva el color del texto resaltado. - document.save(output_file) -``` +## ¿Qué hay de nuevo en Aspose.PDF 25.12? -## Novedades en Aspose.PDF 23.8 +Convierta un documento HTML en un PDF mientras preserva la información de la estructura lógica. El PDF resultante es más adecuado para la accesibilidad, el etiquetado y el procesamiento posterior que depende del contenido estructurado del documento. -Desde la versión 23.8 se admite añadir la detección de Actualizaciones Incrementales. +```python +import aspose.pdf as ap + + +def convert_html_to_pdf_with_logical_structure(self, infile, outfile): + # Initialize HtmlLoadOptions + options = ap.HtmlLoadOptions() + # Convert HTML markup to PDF logical structure elements + options.create_logical_structure = True + # Open PDF document + with ap.Document(infile, options) as document: + # Save PDF document + document.save(outfile) +``` -Se ha añadido la función para detectar Actualizaciones Incrementales en un documento PDF. - Esta función devuelve 'true' si un documento fue guardado con actualizaciones incrementales; de lo contrario, devuelve 'false'. +Analiza un PDF firmado digitalmente para identificar y reportar el contenido que no está cubierto por firmas. Úsalo para validar la integridad del documento, auditar PDFs firmados y detectar modificaciones posteriores a la firma. ```python +import aspose.pdf as ap + + +def extract_unsigned_content(self, infile): + # Open PDF document + with ap.Document(infile) as document: + # Create an instance of PdfFileSignature for working with signatures in the document + with ap.facades.PdfFileSignature(document) as signature: + # Create an instance of UnsignedContentAbsorber + unsigned_content = ap.security.UnsignedContentAbsorber(signature) + # Try to get unsigned content + result = unsigned_content.try_get_content() + # Print information about unsigned content + print(result.message) + print(result.coverage) + print(result.unsigned_content.pages.length) + print(result.unsigned_content.forms.length) +``` - import aspose.pdf as ap +## Qué hay de nuevo en Aspose.PDF 25.11 - doc = ap.Document(file_path) - updated = doc.has_incremental_update() - print(updated) +Esta función compara una página específica de dos documentos PDF y produce una diferencia visual lado a lado. Al personalizar las opciones de comparación y los colores, resalta los cambios significativos mientras ignora las diferencias insignificantes, como los espacios en blanco. + +```python +import aspose.pdf as ap + + +def comparing_specific_pages(self, infile1, infile2, outfile): + # Open PDF documents + with ap.Document(infile1) as document1: + with ap.Document(infile2) as document2: + options = ap.comparison.SideBySideComparisonOptions() + options.additional_change_marks = True + options.comparison_mode = ap.comparison.ComparisonMode.IGNORE_SPACES + options.delete_color = ap.Color.dark_gray + options.insert_color = ap.Color.light_yellow + # Compare + ap.comparison.SideBySidePdfComparer.compare( + document1.pages[1], document2.pages[1], outfile, options + ) ``` -Además, la versión 23.8 admite formas de trabajar con campos de casillas de verificación anidadas. Muchos formularios PDF rellenables tienen campos de casillas de verificación que actúan como grupos de radio: +Eliminando datos ocultos y rasterizando páginas en la versión 25.11. + +```python +import aspose.pdf as ap + + +def clear_hidden_data(self, infile, outfile): + # Open PDF document + with ap.Document(infile) as document: + # Create preconfigured “all-enabled” options (except conversion to images): + options = ap.security.hiddendatasanitization.HiddenDataSanitizationOptions.all() + # Additionally enable page conversion to images with a specified DPI: + options.convert_pages_to_images = True + options.image_dpi = 200 + # Create the sanitizer with the specified options + sanitizer = ap.security.hiddendatasanitization.HiddenDataSanitizer(options) + # Sanitize the document + sanitizer.sanitize(document) + # Save the sanitized PDF document + document.save(outfile) +``` -- Crear campo de casilla de verificación de múltiples valores: +Optimización de recursos con subconjunto de fuentes y compresión de flujos de contenido versión 25.11. ```python +import aspose.pdf as ap + + +def optimize_resources_with_font_subsetting(self, infile, outfile): + # Open PDF document + with ap.Document(infile) as document: + # Configure optimization options + optimize_options = ap.optimization.OptimizationOptions() + optimize_options.subset_fonts = True + optimize_options.allow_reuse_page_content = True + optimize_options.compress_objects = True + optimize_options.link_duplicate_streams = True + optimize_options.remove_unused_objects = True + optimize_options.remove_unused_streams = True + optimize_options.compress_all_content_streams = True + # Optimize PDF document + document.optimize_resources(optimize_options) + # Save the optimized PDF document + document.save(outfile) + # Display file size reduction + original_file = os.path.getsize(infile) + optimized_file = os.path.getsize(outfile) + print( + f"Original file size: {original_file} bytes. Optimized file size: {optimized_file} bytes." + ) +``` - import aspose.pdf as ap - - document = ap.Document() - page = document.pages.add() - checkbox = ap.forms.CheckboxField(page, ap.Rectangle(50, 50, 70, 70, True)) - # Establecer el valor de la primera opción del grupo de casillas - checkbox.export_value = "option 1" - # Añadir nueva opción justo debajo de las existentes - checkbox.add_option("option 2") - # Añadir nueva opción en el rectángulo dado - checkbox.add_option("option 3", ap.Rectangle(100, 100, 120, 120, True)) - document.form.add(checkbox) - # Seleccionar la casilla añadida - checkbox.value = "option 2" - document.save(DIR_OUTPUT + "checkbox_group.pdf") +## Qué hay de nuevo en Aspose.PDF 25.10 + +Control mejorado de visibilidad de capas PDF – esta versión introduce la capacidad de definir programáticamente el estado de visibilidad inicial de las capas PDF y bloquearlas para evitar cambios de visibilidad en los visores PDF. + +Una nueva propiedad 'layer.default_state' permite establecer la visibilidad predeterminada de una capa como visible u oculta mediante la propiedad DefaultState. Esto brinda un control detallado para gestionar documentos PDF con capas complejas y un comportamiento de visibilidad de usuario predecible. + +```python +import aspose.pdf as ap + + +def manage_layer_visibility(self, infile, outfile): + # Create a new PDF document + with ap.Document() as document: + # Add a page to the document + page = document.pages.add() + page.set_page_size(500, 500) + # Load an image from a file stream + with io.FileIO(infile, "r") as stream: + # Create a new layer with an ID and a name + layer = ap.Layer("1", "testlayer") + # Set the initial visibility state of the layer to hidden + layer.default_state = ap.DefaultState.HIDDEN + # Add the image to the page's resources + image_name = page.resources.images.add(stream) + # Add operators to the layer's contents to display the image + layer.contents.append(ap.operators.GSave()) + layer.contents.append(ap.operators.ConcatenateMatrix(500, 0, 0, 500, 0, 0)) + layer.contents.append(ap.operators.Do(image_name)) + layer.contents.append(ap.operators.GRestore()) + # Lock the layer to prevent its visibility from being changed in the PDF viewer + layer.lock() + # Add the layer to the page + page.layers.append(layer) + # Save the PDF document + document.save(outfile) ``` -- Obtener y establecer el valor de un checkbox de múltiples valores: +## ¿Qué hay de nuevo en Aspose.PDF 25.9? + +La versión 25.9 introduce una mayor accesibilidad, un soporte de cumplimiento mejorado y nuevas capacidades de API para trabajar con imágenes etiquetadas y estándares de documentos. + +1. Convertir PDFs al formato PDF/E-1. +1. Agregar imágenes etiquetadas desde flujos de memoria. + +### Convertir PDF a formato PDF/E-1 + +En la versión 25.9 de la biblioteca Aspose.PDF for Python, la conversión al formato PDF/E-1 está disponible. Puede encontrar más información sobre este formato en el [Documentación de formatos de archivo](https://docs.fileformat.com/pdf/e/). ```python +import aspose.pdf as ap + + +def convert_pdf_to_pdf_e(self, infile, outfile): + """PDF/E-1 Standard Support: Added the capability to convert PDF files to the PDF/E-1 format and to validate + the output files for compliance with the standard.""" + + path_infile = self.data_dir + infile + path_outfile = self.data_dir + outfile + + # Open PDF document + with ap.Document(path_infile) as document: + # Set up the PDF/E-1 format with PdfFormatConversionOptions + options = ap.PdfFormatConversionOptions( + ap.PdfFormat.PDF_E_1, ap.ConvertErrorAction.DELETE + ) + # Convert to PDF/E-1 compliant document + document.convert(options) + # Save PDF document + document.save(path_outfile) +``` - import aspose.pdf as ap - - doc = ap.Document("example.pdf") - form = doc.form - checkbox = cast(ap.forms.CheckboxField, form.fields[0]) - - # Los valores permitidos pueden ser recuperados de la colección AllowedStates - # Establecer el valor del checkbox usando la propiedad Value - checkbox.value = checkbox.allowed_states[0] - checkbox_value = checkbox.value # el valor previamente establecido, por ejemplo, "opción 1" - # El valor debe ser cualquier elemento de AllowedStates - checkbox.value = "opción 2" - checkbox_value = checkbox.value # opción 2 - # Desmarcar las cajas estableciendo Value en "Off" o estableciendo Checked en falso - checkbox.value = "Off" - # o, alternativamente: - # checkbox.checked = False - checkbox_value = checkbox.value # Off +### Agregar imágenes etiquetadas desde un flujo + +Agregar imágenes etiquetadas desde un flujo en PDF. La versión 25.9 admite accesibilidad mejorada en documentos PDF al agregar una imagen desde un flujo de memoria y etiquetarla con texto alternativo. + +```python +import aspose.pdf as ap + + +def add_tagged_image_from_stream(self, image_file, outfile): + """Enhanced Accessibility for Tagged Images: possible to add alternative text to images loaded from a memory stream.""" + + path_image = self.data_dir + image_file + path_outfile = self.data_dir + outfile + + # Create the PDF document + with ap.Document() as document: + page = document.pages.add() + # Tag the document for accessibility + tagged_content = document.tagged_content + tagged_content.set_title("Tagged Image from Stream") + tagged_content.set_language("en-US") + # Add an image from a stream to the page + image_stream = io.FileIO(path_image, "r") + page.add_image(image_stream, ap.Rectangle(100, 600, 300, 800, True), None, True) + # Get the added image and set its alternative text + img = page.resources.images[1] + img.try_set_alternative_text("Aspose Logo", page) + # Save the document + document.save(path_outfile) ``` -- Actualizar el estado del checkbox al hacer clic el usuario: +## ¿Qué hay de nuevo en Aspose.PDF 25.8? + +Esta actualización agrega más flexibilidad en la gestión del diseño y la seguridad de los documentos. + +1. Crear tablas de contenido etiquetadas (TOC). +1. Redimensionar páginas PDF con escalado de contenido. +1. Aplicar bordes discontinuos a las tablas. + +### Crear Tabla de Contenidos Etiquetada (TOC) + +Generar automáticamente índices de contenido accesibles (TOC) en PDFs etiquetados. Crear un índice de contenido totalmente accesible (TOC) en un PDF permite a los lectores navegar por el documento de manera eficiente y garantiza el cumplimiento de PDF/UA-1 para la accesibilidad. ```python +import aspose.pdf as ap + + +def create_pdf_with_toc_page(self, outfile): + """ + Supports generating fully accessible Tagged Table of Contents (TOC) pages with proper navigation to + corresponding sections, ensuring PDF/UA-1 compliance. + """ + + path_outfile = self.data_dir + outfile + + # Create the PDF document + with ap.Document() as document: + # Get tagged content for the PDF structure + content = document.tagged_content + root_element = content.root_element + content.set_language("en-US") + # Add the table of contents (TOC) page + toc_page = document.pages.add() + toc_page.toc_info = ap.TocInfo() + # Create a TOC structure element + toc_element = content.create_toc_element() + # Add the TOC element to the document structure tree + root_element.append_child(toc_element, True) + # Add a content page + document.pages.add() + # Create a header element and set its text + header = content.create_header_element(1) + header.set_text("1. Header") + # Add the header to the document structure + root_element.append_child(header, True) + # Create a TOC item (TOCI) element + toci = content.create_toci_element() + # Add the TOCI element to the TOC element + toc_element.append_child(toci, True) + # Add an entry to the TOC page and link it to the TOCI element + header.add_entry_to_toc_page(toc_page, toci) + # Add a logical reference to the header within the TOCI element + toci.add_ref(header) + # Save PDF document + document.save(path_outfile) +``` + +### Redimensionar páginas con escalado de contenido - import aspose.pdf as ap - from aspose.pycore import cast - - input_file = DIR_INPUT + "input.pdf" - document = ap.Document(input_file) - point = ap.Point(62,462) # por ejemplo, las coordenadas de un clic del ratón - # Opción 1: revisar las anotaciones en la página - page = document.pages[5] - for annotation in page.annotations: - if(annotation.rect.contains(point)): - widget = cast(ap.annotations.WidgetAnnotation, annotation) - checkbox = cast(ap.forms.CheckboxField, widget.parent) - if(annotation.active_state == "Off"): - checkbox.value = widget.get_checked_state_name() - else: - checkbox.value = "Off" - break - # Opción 2: revisar los campos en el AcroForm - for widget in document.form: - field = cast(ap.forms.Field, widget) - if(field == None): - continue - checkBoxFound = False - for annotation in field: - if(annotation.rect.contains(point)): - checkBoxFound = True - if(annotation.active_state=="Off"): - annotation.parent.value = annotation.get_checked_state_name() - else: - annotation.parent.value = "Off" - if(checkBoxFound): - break +Cambiar el tamaño de las páginas PDF mientras se preserva el diseño y se escala proporcionalmente el contenido. Al trabajar con PDFs, puede que necesite redimensionar las páginas o escalar el contenido para ajustarlo a nuevas dimensiones. + +```python +import aspose.pdf as ap + + +def resize_page( + self, document, page_number, target_width, target_height, width, height, outfile +): + """ + Resize and scale page content using PdfFileEditor.ResizeContents. + + A high-level helper that scales and/or resizes the rendered content streams of one or more pages + without performing a full content reflow. Use this to make existing page contents larger or smaller, + fit content into a different page box, or uniformly scale content for printing or display. + + Parameters (recommended) + ------------------------ + pdf_editor : Aspose.Pdf.Facades.PdfFileEditor + The PdfFileEditor instance that exposes the ResizeContents API. + page_numbers : int | Iterable[int] | slice, optional + Page index (1-based) or collection of page indices to process. If omitted or None, all pages + in the document are processed. + scale : float, optional + Uniform scale factor to apply to content (e.g., 0.5 reduces content to 50%). Mutually exclusive + with target_width/target_height unless keep_aspect_ratio is explicitly handled. + target_width : float, optional + Desired content width in PDF points (1 point = 1/72 inch). When provided, content will be scaled + to match this width (subject to keep_aspect_ratio and fit_mode). + target_height : float, optional + Desired content height in PDF points. + keep_aspect_ratio : bool, default True + If True, preserve the original aspect ratio when scaling to a target width or height. + fit_mode : {'fit', 'fill', 'stretch'}, default 'fit' + 'fit' — scale so content fits entirely inside the target box, preserving aspect ratio; + 'fill' — scale so the target box is completely covered (may crop content); + 'stretch' — scale independently in X and Y (may distort). + margins : tuple(float, float, float, float), optional + (left, top, right, bottom) margins in points to preserve inside the target box. + preserve_annotations : bool, default True + When True, attempt to preserve annotations/forms/interactive elements; some annotations may + require special handling after scaling. + preserve_transparency : bool, default True + Preserve transparency settings of page contents where possible. + + Returns + ------- + bool + True if the operation completed successfully. Some implementations operate in-place and may + return a status rather than a new document object. + + Raises + ------ + ValueError + If parameters are invalid (e.g., scale <= 0 or both scale and conflicting target dimensions). + IOError + If input/output streams cannot be read or written. + PdfProcessingError + If the PDF content streams cannot be interpreted or transformed by the editor. + + Notes + ----- + - All size and margin values are in PDF points (1/72 inch). Convert from inches or millimeters + before calling if necessary. + - This API scales content streams and their transform matrices; it does not reflow text or rebuild + page layout. Text encoded as vectors will scale; text drawn by layout engines may not reflow. + - Complex page objects such as XObjects, forms, and annotations may require additional post-processing. + - For raster-output use-cases (images/screenshots), consider exporting to an image at a target DPI + instead of scaling content streams. + - When targeting printing, compute target page size in points from the physical paper size and DPI. + + Example (conceptual) + -------------------- + # Scale pages 1-3 to 50%: + editor = PdfFileEditor(input_stream, output_stream) + editor.ResizeContents(page_numbers=[1,2,3], scale=0.5) + editor.Save() + + # Fit page content into a letter-sized box while preserving aspect ratio: + editor.ResizeContents(page_numbers=None, target_width=612, target_height=792, fit_mode='fit') + + See also + -------- + PdfFileEditor.ResizeContents : Low-level API that performs content scaling and transform adjustments. + """ + + path_outfile = self.data_dir + outfile + + margin_width = (target_width - width) / 2 + margin_height = (target_height - height) / 2 + + # Set the parameters + param = ap.facades.PdfFileEditor.ContentsResizeParameters.page_resize(width, height) + param.top_margin = ap.facades.PdfFileEditor.ContentsResizeValue.units(margin_height) + param.bottom_margin = ap.facades.PdfFileEditor.ContentsResizeValue.units( + margin_height + ) + param.left_margin = ap.facades.PdfFileEditor.ContentsResizeValue.units(margin_width) + param.right_margin = ap.facades.PdfFileEditor.ContentsResizeValue.units( + margin_width + ) + param.change_media_box = True + + # Do resize + ap.facades.PdfFileEditor().resize_contents(document, [page_number], param) + + document.save(path_outfile) ``` +### Aplicar bordes discontinuos a tablas + +Agrega tablas con estilos de borde personalizados usando líneas discontinuas. Este ejemplo muestra cómo aplicar estilos de borde personalizados—como líneas discontinuas o punteadas—a tablas en un documento PDF usando Aspose.PDF for Python via .NET. + +```python +import aspose.pdf as ap + -## Qué hay de nuevo en Aspose.PDF 23.7 +def create_table_with_dashed_border(self, outfile): + """Support style for table borders, allowing you to set dashed, dotted, or custom border styles for tables.""" -Desde la versión 23.7 se admite agregar la extracción de formas: + path_outfile = self.data_dir + outfile + + # Create the PDF document + with ap.Document() as document: + page = document.pages.add() + table = ap.Table() + graph_info = ap.GraphInfo() + graph_info.dash_array = [10, 10] + graph_info.dash_phase = 5 + graph_info.line_width = 3 + table.border = ap.BorderInfo(ap.BorderSide.BOX, graph_info) + row = table.rows.add() + row.cells.add("Dashed border cell") + + page.paragraphs.add(table) + + document.save(path_outfile) +``` + +## ¿Qué hay de nuevo en Aspose.PDF 25.7? + +El lanzamiento 25.7 se centra en un mejor soporte de anotaciones, ajuste de texto y gestión de firmas digitales. + +1. Ajustar texto dentro de formas. +1. Cifrar PDFs usando un certificado público. +1. Añadir anotaciones de nube y polígono. + +### Cifrar PDFs con un certificado público + +Proteja sus PDFs con cifrado basado en certificados públicos. El cifrado con certificados públicos permite que los PDFs se cifren para destinatarios específicos, garantizando que solo los poseedores de las claves privadas correspondientes puedan abrir y leer el documento. ```python +import aspose.pdf as ap + + +def pub_sec_encryption(self, outfile, pub_cert, crypto_algorithm): + """Support for public certificate encryption, allowing PDFs to be encrypted so that only specified certificate + holders can open the document.""" - import aspose.pdf as ap + # The path to the recipient certificate + path_outfile = self.data_dir + outfile + path_cert = self.data_dir + pub_cert - input1_file = DIR_INPUT + "input_1.pdf" - input2_file = DIR_INPUT + "input_2.pdf" + # Create the PDF document + with ap.Document() as document: + # Add an info + document.info.title = "TestTitle" + document.info.author = "TestAuthor" - source = ap.Document(input1_file) - dest = ap.Document(input2_file) + # Add a page and add some text + page = document.pages.add() + text = ap.text.TextFragment("Hello World!") + page.paragraphs.add(text) - graphic_absorber = ap.vector.GraphicsAbsorber() - graphic_absorber.visit(source.pages[1]) - area = ap.Rectangle(90, 250, 300, 400, True) - dest.pages[1].add_graphics(graphic_absorber.elements, area) + # Load certificate + with open(path_cert, "rb") as f: + cert_data = f.read() + + # Encrypt the PDF document + document.encrypt(ap.Permissions.PRINT_DOCUMENT, crypto_algorithm, [cert_data]) + + # Save the PDF document. A private key certificate must be installed in the storage to open the document + # by Adobe Acrobat. + document.save(path_outfile) ``` -También se admite la capacidad de detectar desbordamiento al agregar texto: +### Ajustar texto dentro de un rectángulo + +Escalar automáticamente el texto para que quepa dentro de un rectángulo definido. Al actualizar o expandir texto en un PDF, puede exceder los límites del párrafo original. ```python +import re +import aspose.pdf as ap + + +def fit_text_into_rectangle(self, infile, outfile): + """New functionality to fit expanded text content within the bounds of a paragraph’s original rectangle, + adjusting font size and spacing automatically.""" + + path_infile = self.data_dir + infile + path_outfile = self.data_dir + outfile + + # Open PDF document + with ap.Document(path_infile) as document: + # Extract the paragraph text (or provide the specific text you want to replace) + text_absorber = ap.text.TextAbsorber() + text_absorber.visit(document) + paragraph_text = text_absorber.text + paragraph_text = paragraph_text.replace("\n", " ") + + # Search for the text fragment + searchable_content = re.sub(" ", r"\\s+", paragraph_text) + text_fragment_absorber = ap.text.TextFragmentAbsorber( + searchable_content, ap.text.TextSearchOptions(True) + ) + document.pages.accept(text_fragment_absorber) + text_fragment = text_fragment_absorber.text_fragments[1] + # Use the text fragment’s rectangle as the target replacement area + text_fragment.replace_options.rectangle = text_fragment.rectangle + # Enable font size reduction to fit the text within the specified area + text_fragment.replace_options.font_size_adjustment_action = ( + ap.text.TextReplaceOptions.FontSizeAdjustment.SHRINK_TO_FIT + ) + # Optionally adjust spacing to justify the text width + text_fragment.replace_options.replace_adjustment_action = ( + ap.text.TextReplaceOptions.ReplaceAdjustment.ADJUST_SPACE_WIDTH + ) + # Duplicate the paragraph content and assign it to the text fragment + text_fragment.text = paragraph_text + " " + paragraph_text + # Save PDF document + document.save(path_outfile) +``` + +### Agregar anotaciones de polígono en nube + +Mejore los flujos de trabajo de revisión de PDF con anotaciones estilo nube o polígono. Las anotaciones de polígono le permiten resaltar o enfatizar áreas específicas en un PDF utilizando formas geométricas. - import aspose.pdf as ap - - output_file = DIR_OUTPUT + "output.pdf" - doc = ap.Document() - paragraph_content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nisl tortor, efficitur sed cursus in, lobortis vitae nulla. Quisque rhoncus, felis sed dictum semper, est tellus finibus augue, ut feugiat enim risus eget tortor. Nulla finibus velit nec ante gravida sollicitudin. Morbi sollicitudin vehicula facilisis. Vestibulum ac convallis erat. Ut eget varius sem. Nam varius pharetra lorem, id ullamcorper justo auctor ac. Integer quis erat vitae lacus mollis volutpat eget et eros. Donec a efficitur dolor. Maecenas non dapibus nisi, ut pellentesque elit. Sed pellentesque rhoncus ante, a consectetur ligula viverra vel. Integer eget bibendum ante. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Curabitur elementum, sem a auctor vulputate, ante libero iaculis dolor, vitae facilisis dolor lorem at orci. Sed laoreet dui id nisi accumsan, id posuere diam accumsan." - fragment = ap.text.TextFragment(paragraph_content) - rectangle = ap.Rectangle(100, 600, 500, 700, False) - paragraph = ap.text.TextParagraph() - paragraph.vertical_alignment = ap.VerticalAlignment.TOP - paragraph.formatting_options.wrap_mode = ap.text.TextFormattingOptions.WordWrapMode.BY_WORDS - paragraph.rectangle = rectangle - is_fit_rectangle = fragment.text_state.is_fit_rectangle(paragraph_content, rectangle) - - while is_fit_rectangle == False: - fragment.text_state.font_size -= 0.5 - is_fit_rectangle = fragment.text_state.is_fit_rectangle(paragraph_content, rectangle) - - paragraph.append_line(fragment) - builder = ap.text.TextBuilder(doc.pages.add()) - builder.append_paragraph(paragraph) - doc.save(output_file) +```python +import aspose.pdf as ap + + +def add_cloud_polygon_annotation(self, outfile): + """The ability to apply “Cloudy” border effects to polygon annotations for enhanced visual appearance.""" + + path_outfile = self.data_dir + outfile + + # Create the PDF document + with ap.Document() as document: + page = document.pages.add() + # Add Cloud Polygon (rectangle) + left = 100.0 + top = 270.0 + right = 420.0 + bottom = 80.0 + cloud_polygon = ap.annotations.PolygonAnnotation( + page, + ap.Rectangle(left, top, right, bottom, True), + [ + ap.Point(left, top), + ap.Point(right, top), + ap.Point(right, bottom), + ap.Point(left, bottom), + ], + ) + cloud_polygon.color = ap.Color.blue + border = ap.annotations.Border(cloud_polygon) + border.width = 3 + border.effect = ap.annotations.BorderEffect.CLOUDY + cloud_polygon.border = border + page.annotations.append(cloud_polygon) + # Add another Cloud Polygon + cloud_polygon = ap.annotations.PolygonAnnotation( + page, + ap.Rectangle(400, 400, 580, 600, True), + [ + ap.Point(400, 450), + ap.Point(450, 300), + ap.Point(520, 300), + ap.Point(580, 500), + ap.Point(500, 600), + ], + ) + cloud_polygon.color = ap.Color.dark_green + cloud_polygon.interior_color = ap.Color.aqua + border = ap.annotations.Border(cloud_polygon) + border.width = 3 + border.effect = ap.annotations.BorderEffect.CLOUDY + cloud_polygon.border = border + page.annotations.append(cloud_polygon) + # Save PDF document + document.save(path_outfile) ``` +## ¿Qué hay de nuevo en Aspose.PDF 25.6? + +Las características principales de esta versión: + +1. Compatibilidad con texto alternativo de imagen. +1. Acceso a la información de licencia. +1. Anotaciones de texto libre con estilo. +1. Apariencia personalizable de la firma digital. -## Qué hay de nuevo en Aspose.PDF 23.6 +### Soporte de texto alternativo de imagen -Soporte para la capacidad de establecer el título de la página HTML, Epub: +Establecer y recuperar el texto alternativo para imágenes para mejorar la accesibilidad en lectores de pantalla. ```python +import aspose.pdf as ap + + +def get_set_alternative_text_for_image(self, infile, outfile): + """To get and set the alternative text for images""" + + path_infile = self.data_dir + infile + path_outfile = self.data_dir + outfile + + # Open PDF document + with ap.Document(path_infile) as document: + # Alternative text to be given to the image + alt_text = "Alternative text for image" + # Image for which alternative text will be set and get + x_image = document.pages[1].resources.images[1] + # Try to set alternative text for an image + result = x_image.try_set_alternative_text(alt_text, document.pages[1]) + # If set is successful, then get the alternative text for the image + if result: + alt_texts = x_image.get_alternative_text(document.pages[1]) + # Save PDF document + document.save(path_outfile) +``` + +### Acceso a la información de licencia - import aspose.pdf as ap +Recuperar metadatos detallados de licencia (usuario con licencia, fecha de vencimiento) a través de LicenseInfo. - input_pdf = DIR_INPUT + "input.pdf" - output_html = DIR_OUTPUT + "output_title.html" - options = ap.HtmlSaveOptions() - options.fixed_layout = True - options.raster_images_saving_mode = ap.HtmlSaveOptions.RasterImagesSavingModes.AS_EMBEDDED_PARTS_OF_PNG_PAGE_BACKGROUND - options.parts_embedding_mode = ap.HtmlSaveOptions.PartsEmbeddingModes.EMBED_ALL_INTO_HTML - options.title = "NUEVA PÁGINA Y TÍTULO" # <-- esto se añadió +```python +import aspose.pdf as ap - document = ap.Document(input_pdf) - document.save(output_html, options) + +def get_license_info_example(self, infile): + """A new way to access license information programmatically through the LicenseInfo property of the License class""" + + path_infile = self.data_dir + infile + + # Initialize license object + lic = ap.License() + # Set license + lic.set_license(path_infile) + # Get license info. + lic_license_info = lic.license_info + print(lic_license_info.licensed_to) + print(lic_license_info.subscription_expiry) ``` -## Qué hay de nuevo en Aspose.PDF 23.5 +### Anotaciones de texto libre con estilo -Desde la versión 23.5 se soporta añadir la opción RedactionAnnotation FontSize. Use el siguiente fragmento de código para resolver esta tarea: +Utilice SetTextStyle para aplicar estilos como negrita, cursiva, subrayado, o para eliminar el formato existente del texto de la anotación. ```python +import aspose.pdf as ap + + +def add_free_annotation_and_set_styles(self, outfile): + """Extended formatting capabilities for annotation text through the SetTextStyle method family of the + FreeTextAnnotation class""" + + path_outfile = self.data_dir + outfile + + # Open PDF document + with ap.Document() as document: + # Add new page + page = document.pages.add() + # Instantiate DefaultAppearance object + default_appearance = ap.annotations.DefaultAppearance( + "Arial", 16, drawing.Color.blue + ) + # Create annotation + free_text = ap.annotations.FreeTextAnnotation( + page, ap.Rectangle(20, 600, 400, 650, True), default_appearance + ) + # Specify the contents of annotation + free_text.contents = "Text of FreeTextAnnotation with different styles" + # Add annotation to annotations collection of page + page.annotations.append(free_text) + # Set styles for annotation text + free_text.set_text_style(0, 4, ap.annotations.RichTextFontStyles.ITALIC) + free_text.set_text_style( + 8, + 26, + ap.annotations.RichTextFontStyles.UNDERLINE + | ap.annotations.RichTextFontStyles.BOLD, + ) + free_text.set_text_style(27, 86, ap.annotations.RichTextFontStyles.BOLD) + free_text.set_text_style( + 42, + 45, + ap.annotations.RichTextFontStyles.CLEAR_EXISTING + | ap.annotations.RichTextFontStyles.UNDERLINE, + ) + # Save PDF document + document.save(path_outfile) +``` + +### Apariencia Personalizable de Firma Digital + +Agrega imágenes, cambia fuentes y superpone gráficos de firma sobre el contenido de fondo para mejorar la marca o la consistencia del diseño. - import aspose.pdf as ap - - doc = ap.Document(DIR_INPUT + "input.pdf") - # Crear instancia de RedactionAnnotation para una región específica de la página - annot = ap.annotations.RedactionAnnotation(doc.pages[1], ap.Rectangle(367, 756.919982910156, 420, 823.919982910156, True)) - annot.fill_color = ap.Color.black - annot.border_color = ap.Color.yellow - annot.color = ap.Color.blue - # Texto a imprimir en la anotación de redacción - annot.overlay_text = "(Desconocido)" - annot.text_alignment = ap.HorizontalAlignment.CENTER - # Repetir texto de superposición sobre la anotación de redacción - annot.repeat = False - # ¡Nueva propiedad aquí! - annot.font_size = 20 - # Añadir anotación a la colección de anotaciones de la primera página - doc.pages[1].annotations.add(annot, False) - # Aplana la anotación y redacta el contenido de la página (es decir, elimina texto e imagen - # Bajo la anotación redactada) - annot.redact() - out_file = DIR_OUTPUT + "RedactPage_out.pdf" - doc.save(out_file) +```python +import aspose.pdf as ap + + +def customization_features_for_digital_sign( + self, infile, outfile, image_file, pfx_file +): + """Enhanced digital signature appearance allowing signature images to appear over background text.""" + + path_infile = self.data_dir + infile + path_outfile = self.data_dir + outfile + path_image = self.data_dir + image_file + path_pfx = self.data_dir + pfx_file + + with ap.facades.PdfFileSignature() as pdf_file_signature: + # Bind PDF document + pdf_file_signature.bind_pdf(path_infile) + # Create a rectangle for signature location + rect = drawing.Rectangle(10, 10, 300, 50) + # Create any of the three signature types + signature = ap.forms.PKCS7Detached(path_pfx, "12345") + # Create signature appearance + signature_custom_appearance = ap.forms.SignatureCustomAppearance() + signature_custom_appearance.font_size = 6 + signature_custom_appearance.font_family_name = "Times New Roman" + signature_custom_appearance.digital_signed_label = "Signed by:" + signature_custom_appearance.is_foreground_image = True + # Set signature appearance + signature.custom_appearance = signature_custom_appearance + # Set signature appearance + pdf_file_signature.signature_appearance = path_image + pdf_file_signature.sign(1, True, rect, signature) + # Save PDF document + pdf_file_signature.save(path_outfile) ``` +## Qué hay de nuevo en Aspose.PDF 25.5 + +La última actualización de Aspose.PDF introduce varias mejoras potentes que mejoran la accesibilidad, la compatibilidad y la seguridad de los documentos. Los desarrolladores ahora pueden extraer certificados digitales directamente de archivos PDF firmados, lo que permite verificaciones avanzadas y controles de cumplimiento. -El soporte para Python 3.5 ha sido descontinuado. Se ha agregado soporte para Python 3.11. +1. Extraer certificados de firmas PDF. +1. Crear listas ordenadas estructuradas en PDF etiquetados. +1. Verificar firmas con certificados de clave pública. +1. Convertir formularios XFA dinámicos a PDFs AcroForm. +1. Reemplazo de fuentes en PDF - Conversión a XPS. -## Qué hay de nuevo en Aspose.PDF 23.3 +### Extraer certificados de firmas PDF -La versión 23.3 introdujo soporte para agregar una resolución a una imagen. Se pueden usar dos métodos para resolver este problema: +Recuperar certificados incrustados utilizando 'extract_certificate()'. ```python +import aspose.pdf as ap + + +def extract_certificate(self, infile): + path_infile = self.data_dir + infile + + # Open PDF document + with ap.Document(path_infile) as document: + with ap.facades.PdfFileSignature(document) as signature: + # Get signature names + signature_names = signature.get_signature_names(True) + for signature_name in signature_names: + # Extract certificate + certificate = [] + if signature.try_extract_certificate(signature_name, certificate): + print(certificate[0] is not None) +``` - import aspose.pdf as ap +### Crear listas ordenadas estructuradas en PDFs etiquetados - input_file = DIR_INPUT + "input.jpg" - table = ap.Table() - table.column_widths = "600" - image = ap.Image() - image.is_apply_resolution = True - image.file = input_file - for i in range(0, 2): - row = table.rows.add() - cell = row.cells.add() - cell.paragraphs.add(image) +Generar listas numeradas accesibles (con elementos anidados) dentro de documentos etiquetados. - page.paragraphs.add(table) +```python +import aspose.pdf as ap + + +def create_ordered_list(self, outfile): + path_outfile = self.data_dir + outfile + + # Create or open PDF document + with ap.Document() as document: + content = document.tagged_content + root_element = content.root_element + content.set_language("en-US") + root_list = content.create_list_element() + span_for_lbl_1 = content.create_span_element() + span_for_lbl_1.set_text("1. ") + position_settings = ap.tagged.PositionSettings() + position_settings.is_in_line_paragraph = True + span_for_lbl_1.adjust_position(position_settings) + span_for_body_1 = content.create_span_element() + span_for_body_1.set_text("bread") + span_for_body_1.adjust_position(position_settings) + lbl_1 = content.create_list_lbl_element() + lbl_1.append_child(span_for_body_1, True) + l_body_1 = content.create_list_l_body_element() + l_body_1.append_child(span_for_lbl_1, True) + li_1 = content.create_list_li_element() + li_1.append_child(lbl_1, True) + li_1.append_child(l_body_1, True) + root_list.append_child(li_1, True) + span_for_lbl_2 = content.create_span_element() + span_for_lbl_2.set_text("2. ") + span_for_body_2 = content.create_span_element() + span_for_body_2.set_text("milk") + span_for_body_2.adjust_position(position_settings) + lbl_2 = content.create_list_lbl_element() + lbl_2.append_child(span_for_lbl_2, True) + l_body_2 = content.create_list_l_body_element() + l_body_2.append_child(span_for_body_2, True) + li_2 = content.create_list_li_element() + li_2.append_child(lbl_2, True) + li_2.append_child(l_body_2, True) + root_list.append_child(li_2, True) + nested_list_depth_1 = content.create_list_element() + span_for_lbl_3_1 = content.create_span_element() + span_for_lbl_3_1.set_text("3.1. ") + position_settings_lbl_3_1 = ap.tagged.PositionSettings() + position_settings_lbl_3_1.is_in_line_paragraph = False + margin_info = ap.MarginInfo() + margin_info.left = 50 + position_settings_lbl_3_1.margin = margin_info + span_for_lbl_3_1.adjust_position(position_settings_lbl_3_1) + span_for_body_3_1 = content.create_span_element() + span_for_body_3_1.set_text("apples") + span_for_body_3_1.adjust_position(position_settings) + lbl_3_1 = content.create_list_lbl_element() + lbl_3_1.append_child(span_for_lbl_3_1, True) + l_body_3_1 = content.create_list_l_body_element() + l_body_3_1.append_child(span_for_body_3_1, True) + li_3_1 = content.create_list_li_element() + li_3_1.append_child(lbl_3_1, True) + li_3_1.append_child(l_body_3_1, True) + nested_list_depth_1.append_child(li_3_1, True) + span_for_lbl_3_2 = content.create_span_element() + span_for_lbl_3_2.set_text("3.2. ") + span_for_lbl_3_2.adjust_position(position_settings_lbl_3_1) + span_for_body_3_2 = content.create_span_element() + span_for_body_3_2.set_text("banana") + span_for_body_3_2.adjust_position(position_settings) + lbl_3_2 = content.create_list_lbl_element() + lbl_3_2.append_child(span_for_lbl_3_2, True) + l_body_3_2 = content.create_list_l_body_element() + l_body_3_2.append_child(span_for_body_3_2, True) + li_3_2 = content.create_list_li_element() + li_3_2.append_child(lbl_3_2, True) + li_3_2.append_child(l_body_3_2, True) + nested_list_depth_1.append_child(li_3_2, True) + span_for_lbl_3 = content.create_span_element() + span_for_lbl_3.set_text("3. ") + span_for_body_3 = content.create_span_element() + span_for_body_3.set_text("fruits") + span_for_body_3.adjust_position(position_settings) + lbl_3 = content.create_list_lbl_element() + lbl_3.append_child(span_for_lbl_3, True) + l_body_3 = content.create_list_l_body_element() + l_body_3.append_child(span_for_body_3, True) + li_3 = content.create_list_li_element() + li_3.append_child(lbl_3, True) + li_3.append_child(l_body_3, True) + l_body_3.append_child(nested_list_depth_1, True) + root_list.append_child(li_3, True) + root_element.append_child(root_list, True) + # Save Tagged PDF Document + document.save(path_outfile) ``` -La imagen se colocará con resolución escalada o puede establecer propiedades de AnchoFijo o AltoFijo en combinación con IsApplyResolution +### Verificar firmas con certificados de clave pública -## Qué hay de nuevo en Aspose.PDF 23.1 +Validar firmas digitales usando certificados de clave pública externos. -Desde la versión 23.1 se admite la creación de anotaciones PrinterMark. +```python +import aspose.pdf as ap -Las marcas de impresora son símbolos gráficos o texto añadidos a una página para ayudar al personal de producción a identificar componentes de un trabajo de múltiples placas y mantener una salida consistente durante la producción. - Ejemplos comúnmente utilizados en la industria de la impresión incluyen: -- Objetivos de registro para alinear placas -- Rampas grises y barras de color para medir colores y densidades de tinta -- Marcas de corte que muestran dónde se debe recortar el medio de salida +def verify_with_public_key_certificate1(self, certificate, infile): + path_infile = self.data_dir + infile -Mostraremos el ejemplo de la opción con barras de color para medir colores y densidades de tinta. Hay una clase abstracta básica PrinterMarkAnnotation y de ella una clase hija ColorBarAnnotation, que ya implementa estas franjas. Vamos a ver el ejemplo: + # Create an instance of PdfFileSignature for working with signatures in the document + with ap.facades.PdfFileSignature(path_infile) as file_sign: + # Get a list of signatures + signature_names = file_sign.get_signature_names(True) + # Verify the signature with the given name. + return file_sign.verify_signature(signature_names[0], certificate) +``` -```python +### Convertir formularios XFA dinámicos a PDF AcroForm + +Estandarizar formularios XFA con 'ignore_needs_rendering'. - import aspose.pdf as ap - - out_file = DIR_OUTPUT + "ColorBarTest.pdf" - doc = ap.Document() - page = doc.pages.add() - page.trim_box = ap.Rectangle(20, 20, 580, 820, True) - add_annotations(page) - doc.save(out_file) - - -def add_annotations(page: ap.Page): - rect_black = ap.Rectangle(100, 300, 300, 320, True) - rect_cyan = ap.Rectangle(200, 600, 260, 690, True) - rect_magenta = ap.Rectangle(10, 650, 140, 670, True) - color_bar_black = ap.annotations.ColorBarAnnotation(page, rect_black, ap.annotations.ColorsOfCMYK.BLACK) - color_bar_cyan = ap.annotations.ColorBarAnnotation(page, rect_cyan, ap.annotations.ColorsOfCMYK.CYAN) - color_ba_magenta = ap.annotations.ColorBarAnnotation(page, rect_magenta, ap.annotations.ColorsOfCMYK.BLACK) - color_ba_magenta.color_of_cmyk = ap.annotations.ColorsOfCMYK.MAGENTA - color_bar_yellow = ap.annotations.ColorBarAnnotation(page, ap.Rectangle(400, 250, 450, 700, True), ap.annotations.ColorsOfCMYK.YELLOW) - page.annotations.add(color_bar_black, False) - page.annotations.add(color_bar_cyan, False) - page.annotations.add(color_ba_magenta, False) - page.annotations.add(color_bar_yellow, False) +```python +import aspose.pdf as ap + + +def convert_xfa_form_with_ignore_needs_rendering(self, infile, outfile): + path_infile = self.data_dir + infile + path_outfile = self.data_dir + outfile + + # Load dynamic XFA form + with ap.Document(path_infile) as document: + # check if XFA is present & if rendering should be overwritten + if not document.form.needs_rendering and document.form.has_xfa: + document.form.ignore_needs_rendering = True + # Set the form fields type as standard AcroForm + document.form.type = ap.forms.FormType.STANDARD + # Save the resultant PDF + document.save(path_outfile) ``` -También se admite la extracción de imágenes vectoriales. Intenta usar el siguiente código para detectar y extraer gráficos vectoriales: + +### Reemplazo de fuentes en PDF - Conversión XPS + +Sustituir fuentes faltantes por una alternativa predeterminada (p. ej., “Courier New”). ```python +import aspose.pdf as ap + + +def replace_font_when_converting_pdf_to_xps(self, infile, outfile): + path_infile = self.data_dir + infile + path_outfile = self.data_dir + outfile + + # Create XpsSaveOptions instance + xps_save_options = ap.XpsSaveOptions() + # use_embedded_true_type_fonts option specifies whether to use embedded TrueType fonts + xps_save_options.use_embedded_true_type_fonts = False + # The specified default font will be used if the embedded font name cannot be found in the system + xps_save_options.default_font = "Courier New" + # Open PDF document + doc = ap.Document(path_infile) + # Save the resultant XPS + doc.save(path_outfile, xps_save_options) +``` + +## ¿Qué hay de nuevo en Aspose.PDF 25.4? + +### Etiquetado automático durante la conversión a PDF/A - import aspose.pdf as ap +Convertir PDFs a PDF/A-1b con creación automática de estructura lógica para mejorar la accesibilidad. - input_pdf = DIR_INPUT + "input.pdf" - output_pdf = DIR_OUTPUT + "output.svg" - doc = ap.Document(input_pdf) - doc.pages[1].try_save_vector_graphics(output_pdf) -``` \ No newline at end of file +```python +import aspose.pdf as ap + + +def convert_to_pdfa_with_automatic_tagging(self, infile, outfile, outlogfile): + path_infile = self.data_dir + infile + path_outfile = self.data_dir + outfile + path_outlogfile = self.data_dir + outlogfile + + # Open PDF document + with ap.Document(path_infile) as document: + # Create conversion options + options = ap.PdfFormatConversionOptions( + path_outlogfile, ap.PdfFormat.PDF_A_1B, ap.ConvertErrorAction.DELETE + ) + # Create auto-tagging settings + # aspose.pdf.AutoTaggingSettings.default may be used to set the same settings as given below + auto_tagging_settings = ap.AutoTaggingSettings() + # Enable auto-tagging during the conversion process + auto_tagging_settings.enable_auto_tagging = True + # Use the heading recognition strategy that's optimal for the given document structure + auto_tagging_settings.heading_recognition_strategy = ( + ap.HeadingRecognitionStrategy.AUTO + ) + # Assign auto-tagging settings to be used during the conversion process + options.auto_tagging_settings = auto_tagging_settings + # During the conversion, the document logical structure will be automatically created + document.convert(options) + # Save PDF document + document.save(path_outfile) +``` diff --git a/es/python-net/working-with-facades/_index.md b/es/python-net/working-with-facades/_index.md new file mode 100644 index 000000000..61d5f55bb --- /dev/null +++ b/es/python-net/working-with-facades/_index.md @@ -0,0 +1,60 @@ +--- +title: Trabajando con PDF Facades +linktitle: Trabajando con PDF Facades +type: docs +weight: 100 +url: /es/python-net/working-with-facades/ +description: Aprenda cómo usar Aspose.PDF Facades en Python via .NET para editar contenido PDF, administrar formularios y anotaciones, aplicar seguridad, firmar archivos, estampar páginas, imprimir documentos y examinar los metadatos PDF. +is_node: true +lastmod: "2026-05-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Utilice PDF Facades en Python via .NET para formularios, firmas, seguridad, sellos y procesamiento de archivos. +Abstract: Esta sección explica cómo usar Aspose.PDF Facades para Python via .NET para manejar flujos de trabajo PDF comunes con APIs simplificadas. Aprenda cómo combinar y dividir archivos, editar contenido, administrar anotaciones y formularios, aplicar seguridad, firmar documentos, añadir sellos, imprimir PDFs y recuperar información de archivos. +--- + +Aspose.PDF Facades es un conjunto de clases auxiliares en Aspose.PDF para Python via .NET que le permite realizar operaciones PDF comunes sin trabajar directamente con el modelo de objeto de documento de bajo nivel. + +Esta sección cubre las principales clases fachada que puede usar para editar contenido PDF, administrar formularios, añadir anotaciones, aplicar seguridad, firmar archivos, trabajar con sellos, imprimir documentos y recuperar información de archivos PDF en aplicaciones Python. + +Si necesita una API práctica para tareas cotidianas de procesamiento de PDF, como combinar documentos, completar formularios, aplicar permisos o firmar archivos, la Facades API proporciona una forma simplificada de crear esos flujos de trabajo. + +## Por qué usar Facades en Aspose.PDF for Python via .NET + +Los PDF Facades ofrecen una capa de API simplificada para flujos de trabajo de documentos comunes. Son útiles cuando necesita realizar operaciones prácticas de PDF rápidamente, como combinar archivos, completar formularios, estampar páginas o aplicar firmas digitales, sin trabajar directamente con el modelo de objeto de documento completo. + +Son especialmente útiles para escenarios de automatización donde se desean APIs concisas y orientadas a tareas para la edición de PDF, gestión de formularios, actualizaciones de anotaciones, seguridad de documentos y flujos de trabajo de salida en Python. + +## Clases principales de fachada PDF + +En esta sección, aprenderá cómo trabajar con estas clases de fachada: + +- [Dividir, combinar y procesar archivos PDF con **PdfFileEditor**](/pdf/es/python-net/pdffileeditor-class/). +- [Editar contenido PDF con **PdfContentEditor**](/pdf/es/python-net/pdfcontenteditor-class/). +- [Gestionar anotaciones y comentarios PDF con **PdfAnnotationEditor**](/pdf/es/python-net/pdfannotationeditor-class/). +- [Firmar archivos PDF con certificados usando **PdfFileSignature**](/pdf/es/python-net/pdffilesignature-class/). +- [Agregar, actualizar y eliminar campos de formulario con **FormEditor**](/pdf/es/python-net/formeditor-class/). +- [Acceder a los metadatos PDF y los detalles del archivo con **PdfFileInfo**](/pdf/es/python-net/pdffileinfo-class/). +- [Cifre, descifre y establezca privilegios del documento con **PdfFileSecurity**](/pdf/es/python-net/pdffilesecurity-class/). +- [Agregue sellos de página e imagen con **PdfFileStamp**](/pdf/es/python-net/pdffilestamp-class/). +- [Imprima documentos PDF con **PdfViewer**](/pdf/es/python-net/pdfviewer-class/). +- [Trabaje con datos AcroForm usando **Form**](/pdf/es/python-net/form-class/). +- [Aplique sellos a documentos PDF con **Stamp**](/pdf/es/python-net/stamp-class/). + +## Flujos de trabajo populares de fachada PDF + +Utilice estas API de fachada cuando necesite automatizar tareas comunes de PDF en Python: + +- Fusiona, divide y reorganiza archivos PDF para flujos de trabajo de procesamiento de documentos. +- Rellene formularios PDF interactivos, actualice campos y extraiga valores de los formularios. +- Agregue anotaciones, comentarios y sellos a páginas PDF existentes. +- Aplique cifrado, permisos y firmas digitales para asegurar documentos. +- Inspeccione los metadatos PDF y las propiedades del archivo antes de archivarlos, imprimirlos o entregarlos. + +## Tareas comunes de PDF cubiertas en esta sección + +Utilice los artículos de esta sección para gestionar flujos de trabajo prácticos de PDF, como el rellenado de formularios, la gestión de campos, la edición de anotaciones, la manipulación de archivos adjuntos, la sustitución de texto, el procesamiento de páginas, la seguridad PDF y las operaciones de firma en Python. + +Para explorar APIs específicas, comience con los enlaces de clase anteriores y luego pase a los artículos basados en tareas de esta sección para obtener ejemplos paso a paso. diff --git a/es/python-net/working-with-facades/form/_index.md b/es/python-net/working-with-facades/form/_index.md new file mode 100644 index 000000000..61af7f171 --- /dev/null +++ b/es/python-net/working-with-facades/form/_index.md @@ -0,0 +1,22 @@ +--- +title: Clase Form +linktitle: Clase Form +type: docs +weight: 140 +url: /es/python-net/form-class/ +description: Esta sección explica cómo trabajar con Aspose.PDF Facades usando la Clase Form. +lastmod: "2025-11-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Trabaje con datos de formulario PDF y campos AcroForm en Python usando la clase Form +Abstract: Esta sección explica cómo usar la fachada Form en Aspose.PDF for Python via .NET para manejar formularios PDF interactivos. Aprenda cómo exportar e importar datos de formulario, rellenar diferentes tipos de campo, gestionar campos existentes, trabajar con campos de botón e imágenes, y leer valores de formulario programáticamente. +--- + +- [Exportación de datos de formulario](/pdf/es/python-net/exporting-form-data/) +- [Importación de datos de formulario](/pdf/es/python-net/importing-form-data/) +- [Rellenar campos de Form](/pdf/es/python-net/filling-form-fields/) +- [Campos de botones e imágenes](/pdf/es/python-net/button-fields-and-images/) +- [Gestión de campos de formulario](/pdf/es/python-net/managing-form-fields/) +- [Lectura de valores del formulario](/pdf/es/python-net/reading-form-values/) diff --git a/es/python-net/working-with-facades/form/button-fields-and-images/_index.md b/es/python-net/working-with-facades/form/button-fields-and-images/_index.md new file mode 100644 index 000000000..cf556a8b3 --- /dev/null +++ b/es/python-net/working-with-facades/form/button-fields-and-images/_index.md @@ -0,0 +1,86 @@ +--- +title: Campos de botones e imágenes +linktitle: Campos de botones e imágenes +type: docs +weight: 40 +url: /es/python-net/button-fields-and-images/ +description: Este ejemplo muestra cómo gestionar campos de botones en un formulario PDF utilizando la API Aspose.PDF Facades. +lastmod: "2026-02-19" +TechArticle: true +AlternativeHeadline: Agregar apariencia de imagen a campos de botones & leer banderas de envío +Abstract: Los formularios PDF a menudo incluyen botones interactivos que pueden desencadenar acciones JavaScript o enviar los datos del formulario. Puedes mejorar visualmente los campos de botones añadiendo imágenes como su apariencia y, mediante programación, inspeccionar su comportamiento de envío. +--- + +## Agregar apariencia de imagen a campos de botones + +Este fragmento de código explica cómo agregar una apariencia de imagen a un campo de botón existente en un formulario PDF. La operación mejora la presentación visual de un botón PDF al reemplazar su apariencia predeterminada con una imagen personalizada. + +1. Crear un objeto Form. +1. Vincular el archivo PDF al objeto Form. +1. Agregar imagen al campo de botón. + + - Determine la ruta al archivo de imagen asociado con el PDF + - Abra la imagen en modo binario como image_stream. + - Llame a fill_image_field() con el nombre de campo de botón totalmente calificado. + +1. Guardar el PDF actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Add image appearance to button fields +def add_image_appearance_to_button_fields(infile, outfile): + """Add image appearance to button fields in a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Add image appearance to button fields by providing the field name and image stream + image_path = infile.replace(".pdf", ".jpg") + with open(image_path, "rb") as image_stream: + pdf_form.fill_image_field("Image1_af_image", image_stream) + + # Save updated PDF + pdf_form.save(outfile) +``` + +## Obtener banderas de envío + +La biblioteca de Python le ayuda a recuperar las banderas de envío de un botón de envío en un formulario PDF utilizando la API Aspose.PDF Facades. Las banderas de envío definen el comportamiento de un botón de envío, como si envía todo el formulario, incluye anotaciones o envía en formato FDF, XFDF, PDF o HTML. + +1. Crear un objeto Form. +1. Llame a get_submit_flags() en el objeto form usando el nombre completo del botón de envío. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def get_submit_flags(infile, outfile): + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + flags = pdf_form.get_submit_flags("Submit1_af_submit") + + print(f"Submit flags: {flags}") +``` diff --git a/es/python-net/working-with-facades/form/exporting-form-data/_index.md b/es/python-net/working-with-facades/form/exporting-form-data/_index.md new file mode 100644 index 000000000..0eae54010 --- /dev/null +++ b/es/python-net/working-with-facades/form/exporting-form-data/_index.md @@ -0,0 +1,15 @@ +--- +title: Exportación de datos de formulario +linktitle: Exportación de datos de formulario +type: docs +weight: 10 +url: /es/python-net/exporting-form-data/ +description: Este artículo demuestra cómo exportar los datos de formulario PDF a varios formatos estructurados utilizando Aspose.PDF for Python via .NET. Proporciona ejemplos prácticos de extracción de valores de campos de formulario de AcroForms estándar y PDFs basados en XFA, y de guardarlos como archivos XML, FDF, XFDF y JSON con Aspose.PDF Facades usando Form Class. +lastmod: "2026-02-19" +--- + +- [Exportar a FDF](/pdf/es/python-net/export-to-fdf/) +- [Exportar a XFDF](/pdf/es/python-net/export-to-xfdf/) +- [Exportar a JSON](/pdf/es/python-net/export-to-json/) +- [Exportar a XML](/pdf/es/python-net/export-to-xml/) +- [Extraer datos XFA](/pdf/es/python-net/extract-xfa-data/) \ No newline at end of file diff --git a/es/python-net/working-with-facades/form/exporting-form-data/export-to-fdf/_index.md b/es/python-net/working-with-facades/form/exporting-form-data/export-to-fdf/_index.md new file mode 100644 index 000000000..245c32840 --- /dev/null +++ b/es/python-net/working-with-facades/form/exporting-form-data/export-to-fdf/_index.md @@ -0,0 +1,43 @@ +--- +title: Exportar a FDF +linktitle: Exportar a FDF +type: docs +weight: 10 +url: /es/python-net/export-to-fdf/ +description: Este ejemplo explica cómo exportar datos de campos de formulario PDF a un archivo FDF (Forms Data Format) utilizando Aspose.PDF for Python via .NET. Demuestra cómo acceder a los datos de formularios interactivos a través de la fachada Form, vincular un documento PDF de origen y guardar los valores extraídos en un flujo FDF. +lastmod: "2026-02-19" +--- + +FDF es un formato liviano diseñado específicamente para almacenar y transferir datos de formularios PDF sin incrustar el documento completo. En este ejemplo, un [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) objeto se inicializa desde el [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) módulo, lo que permite a los desarrolladores interactuar con los campos AcroForm y exportar sus valores. + +1. Cree una instancia de pdf_facades.Form() para trabajar con los campos de formulario PDF. +1. Llama a 'bind_pdf()' para adjuntar el documento PDF que contiene el formulario. +1. Utiliza 'open(')' para crear un flujo binario escribible para el archivo FDF. +1. Exportar datos del formulario. Llama a 'export_fdf()' para extraer y guardar todos los valores de los campos del formulario. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Export Data to FDF +def export_form_data_to_fdf(infile, outfile): + """Export PDF form data to FDF file.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Create FDF file stream + with open(outfile, "wb") as fdf_output_stream: + # Export form data to FDF file + pdf_form.export_fdf(fdf_output_stream) +``` diff --git a/es/python-net/working-with-facades/form/exporting-form-data/export-to-json/_index.md b/es/python-net/working-with-facades/form/exporting-form-data/export-to-json/_index.md new file mode 100644 index 000000000..64df19e0c --- /dev/null +++ b/es/python-net/working-with-facades/form/exporting-form-data/export-to-json/_index.md @@ -0,0 +1,43 @@ +--- +title: Exportar a JSON +linktitle: Exportar a JSON +type: docs +weight: 30 +url: /es/python-net/export-to-json/ +description: Este ejemplo muestra cómo exportar los valores de los campos de formulario PDF a un archivo JSON usando Aspose.PDF for Python via .NET. Explica cómo cargar un formulario PDF, acceder a sus campos mediante la fachada Form y guardar los datos extraídos en un formato JSON estructurado. +lastmod: "2026-02-19" +--- + +JSON es un formato de datos ampliamente utilizado que permite el intercambio fluido entre aplicaciones y servicios. En este ejemplo, el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) objeto del [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) módulo se utiliza para enlazar un archivo PDF y exportar sus valores de campo de formulario a una estructura JSON legible. + +1. Inicializa pdf_facades.Form() para trabajar con los campos de formulario. +1. Utilice 'bind_pdf()' para adjuntar el documento PDF de origen. +1. Cree un flujo escribible usando 'FileIO()'. +1. Llame a 'export_json()' para extraer los valores de los campos del formulario y guardarlos en JSON formateado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Export Data to JSON +def export_form_to_json(infile, outfile): + """Export PDF form field values to JSON file.""" + # Create Form object + form = pdf_facades.Form() + + # Bind PDF document + form.bind_pdf(infile) + + # Create JSON file stream + with FileIO(outfile, "w") as json_stream: + # Export form field values to JSON + form.export_json(json_stream, indented=True) +``` diff --git a/es/python-net/working-with-facades/form/exporting-form-data/export-to-xfdf/_index.md b/es/python-net/working-with-facades/form/exporting-form-data/export-to-xfdf/_index.md new file mode 100644 index 000000000..813867706 --- /dev/null +++ b/es/python-net/working-with-facades/form/exporting-form-data/export-to-xfdf/_index.md @@ -0,0 +1,43 @@ +--- +title: Exportar a XFDF +linktitle: Exportar a XFDF +type: docs +weight: 20 +url: /es/python-net/export-to-xfdf/ +description: Este ejemplo muestra cómo exportar los datos de los campos de formulario PDF a un archivo XFDF (XML Forms Data Format) utilizando Aspose.PDF for Python via .NET. Demuestra cómo cargar un formulario PDF, acceder a sus campos a través de la fachada Form, y guardar los valores extraídos en un flujo XFDF. +lastmod: "2026-02-19" +--- + +XFDF es una representación XML de los datos de formulario PDF que permite a los desarrolladores transferir los valores de los campos de formulario de forma independiente del documento original. En este ejemplo, el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) objeto de [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) se utiliza para vincular el PDF fuente y exportar sus datos a un archivo XFDF estructurado. + +1. Inicialice pdf_facades.Form() para gestionar los datos del formulario PDF. +1. Llame a 'bind_pdf()' para adjuntar el documento PDF de origen. +1. Utilice 'open()' para crear un flujo binario escribible. +1. Exportar datos del formulario. Llame a 'export_xfdf()' para extraer y guardar los valores de los campos del formulario en formato XFDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Export Data to XFDF +def export_pdf_form_to_xfdf(infile, outfile): + """Export PDF form data to XFDF file.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Create XFDF file stream + with open(outfile, "wb") as xfdf_output_stream: + # Export form data to XFDF file + pdf_form.export_xfdf(xfdf_output_stream) +``` diff --git a/es/python-net/working-with-facades/form/exporting-form-data/export-to-xml/_index.md b/es/python-net/working-with-facades/form/exporting-form-data/export-to-xml/_index.md new file mode 100644 index 000000000..dc2eb58bc --- /dev/null +++ b/es/python-net/working-with-facades/form/exporting-form-data/export-to-xml/_index.md @@ -0,0 +1,43 @@ +--- +title: Exportar a XML +linktitle: Exportar a XML +type: docs +weight: 40 +url: /es/python-net/export-to-xml/ +description: Este ejemplo demuestra cómo exportar los datos de formulario PDF a un archivo XML usando Aspose.PDF for Python via .NET. Muestra cómo cargar un documento PDF, acceder a sus campos de formulario a través del Form facade y guardar los datos extraídos como XML estructurado usando Form Class. +lastmod: "2026-02-19" +--- + +Exportar datos de formulario permite a los desarrolladores reutilizar la información almacenada en PDF AcroForms sin copiar manualmente los valores de los campos. En este ejemplo, un [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) objeto se crea a partir de aspose.pdf. En el módulo facades, el PDF de origen se vincula a él, y los datos del formulario se escriben en un flujo XML. + +1. Cree un Form Object. Inicialice pdf_facades.Form() para acceder y gestionar los campos del formulario. +1. Use \u0027bind_pdf()\u0027 para adjuntar el documento PDF de origen a la instancia Form. +1. Crea un flujo de archivo escribible usando 'FileIO()'. +1. Llame a 'export_xml()' para extraer todos los valores de los campos del formulario y escribirlos en el archivo XML. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Export Data to XML +def export_pdf_form_data_to_xml(infile, datafile): + """Export PDF form data to XML file.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Open XML file as stream + with FileIO(datafile, "w") as xml_output_stream: + # Export data from PDF form fields to XML + pdf_form.export_xml(xml_output_stream) +``` diff --git a/es/python-net/working-with-facades/form/exporting-form-data/extract-xfa-data/_index.md b/es/python-net/working-with-facades/form/exporting-form-data/extract-xfa-data/_index.md new file mode 100644 index 000000000..69f639f24 --- /dev/null +++ b/es/python-net/working-with-facades/form/exporting-form-data/extract-xfa-data/_index.md @@ -0,0 +1,42 @@ +--- +title: Extraer datos XFA +linktitle: Extraer datos XFA +type: docs +weight: 50 +url: /es/python-net/extract-xfa-data/ +description: Este ejemplo explica cómo extraer datos de formulario XFA de un archivo PDF usando Aspose.PDF for Python via .NET. Demuestra cómo vincular un documento PDF basado en XFA a la fachada Form y exportar su estructura de datos interna a un flujo de archivo. +lastmod: "2026-02-19" +--- + +Los formularios XFA (XML Forms Architecture) difieren de los AcroForms tradicionales porque sus datos se almacenan como XML dentro del PDF. En este ejemplo, el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) objeto del [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) módulo se utiliza para vincular el PDF y extraer sus datos XFA directamente a un archivo. + +1. Cree una instancia de pdf_facades.Form() para gestionar los datos del formulario. +1. Llame a 'bind_pdf()' para adjuntar el PDF de origen que contiene formularios XFA. +1. Utilice 'FileIO()' para crear un flujo de archivo con capacidad de escritura. +1. Llame a 'extract_xfa_data()' para exportar los datos XML XFA incrustados. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Extract XFA Data +def export_xfa_data(infile, outfile): + """Export XFA form data.""" + # Create Form object + form = pdf_facades.Form() + + # Bind PDF document + form.bind_pdf(infile) + + with FileIO(outfile, "w") as stream: + # Export embedded XFA XML data to the output stream + form.extract_xfa_data(stream) +``` diff --git a/es/python-net/working-with-facades/form/filling-form-fields/_index.md b/es/python-net/working-with-facades/form/filling-form-fields/_index.md new file mode 100644 index 000000000..4d6f255b6 --- /dev/null +++ b/es/python-net/working-with-facades/form/filling-form-fields/_index.md @@ -0,0 +1,16 @@ +--- +title: Rellenar campos de Form +linktitle: Rellenar campos de Form +type: docs +weight: 30 +url: /es/python-net/filling-form-fields/ +description: Este artículo demuestra cómo rellenar programáticamente los campos de formulario PDF usando Aspose.PDF for Python via .NET. Cubre técnicas prácticas para poblar diferentes tipos de elementos de formulario interactivos, incluyendo campos de texto, casillas de verificación, botones de opción, listas desplegables, campos de código de barras y pares nombre‑valor mapeados dinámicamente. Al usar la fachada Form, los desarrolladores pueden vincular un documento PDF, actualizar los valores de los campos mediante llamadas simples a la API y guardar el archivo modificado automáticamente. +lastmod: "2026-02-19" +--- + +- [Rellenar campos de texto](/pdf/es/python-net/fill-text-fields/) +- [Rellenar campos de casilla de verificación](/pdf/es/python-net/fill-check-box-fields/) +- [Rellenar campos de botones de radio](/pdf/es/python-net/fill-radio-button-fields/) +- [Rellenar cuadro de lista](/pdf/es/python-net/fill-list-box/) +- [Rellenar campos de código de barras](/pdf/es/python-net/fill-barcode-fields/) +- [Rellenar campos por nombre y valor](/pdf/es/python-net/fill-fields-by-name-and-value/) diff --git a/es/python-net/working-with-facades/form/filling-form-fields/fill-barcode-fields/_index.md b/es/python-net/working-with-facades/form/filling-form-fields/fill-barcode-fields/_index.md new file mode 100644 index 000000000..be3d490ad --- /dev/null +++ b/es/python-net/working-with-facades/form/filling-form-fields/fill-barcode-fields/_index.md @@ -0,0 +1,44 @@ +--- +title: Rellenar campos de código de barras +linktitle: Rellenar campos de código de barras +type: docs +weight: 50 +url: /es/python-net/fill-barcode-fields/ +description: Este ejemplo muestra cómo rellenar programáticamente campos de código de barras en un formulario PDF utilizando Aspose.PDF for Python via .NET. Demuestra cómo enlazar un documento PDF, asignar un valor a un campo de código de barras y guardar el archivo actualizado. +lastmod: "2026-02-19" +--- + +Los campos de código de barras en formularios PDF permiten que la información codificada se almacene y se muestre visualmente como códigos de barras. En este ejemplo, el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) fachada del [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) módulo se utiliza para acceder a los campos del formulario y asignar un valor de código de barras. Una vez que los datos se rellenan, el PDF se guarda con el contenido de código de barras actualizado. + +1. Inicializa 'pdf_facades.Form()' para gestionar interacciones con formularios PDF. +1. Llama a 'bind_pdf()' para adjuntar el PDF que contiene campos de código de barras. +1. Usa 'fill_field()' para asignar un valor de código de barras. +1. Guarda el Documento actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Fill Barcode Fields +def fill_barcode_fields(infile, outfile): + """Fill barcode fields in PDF form.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill barcode fields by name + pdf_form.fill_field("product_barcode", "123456789012") + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/es/python-net/working-with-facades/form/filling-form-fields/fill-check-box-fields/_index.md b/es/python-net/working-with-facades/form/filling-form-fields/fill-check-box-fields/_index.md new file mode 100644 index 000000000..a883ec0f2 --- /dev/null +++ b/es/python-net/working-with-facades/form/filling-form-fields/fill-check-box-fields/_index.md @@ -0,0 +1,45 @@ +--- +title: Rellenar campos de casilla de verificación +linktitle: Rellenar campos de casilla de verificación +type: docs +weight: 20 +url: /es/python-net/fill-check-box-fields/ +description: Este ejemplo demuestra cómo rellenar programáticamente campos de casilla de verificación en un formulario PDF utilizando Aspose.PDF for Python via .NET. Muestra cómo vincular un documento PDF, actualizar los valores de las casillas de verificación por nombre de campo y guardar el archivo modificado. +lastmod: "2026-02-19" +--- + +La casilla de verificación se usa comúnmente en formularios PDF para representar opciones binarias, como suscripciones o confirmaciones de acuerdos. En este ejemplo, la [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) fachada de [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) se utiliza para acceder a los campos del formulario y establecer sus valores en un estado seleccionado. Después de actualizar las casillas de verificación, el PDF rellenado se guarda como un nuevo documento. + +1. Inicializa \u0027pdf_facades.Form()\u0027 para gestionar interacciones con los campos del formulario. +1. Utilice 'bind_pdf()' para adjuntar el PDF de origen que contiene campos de casilla de verificación. +1. Llame a 'fill_field()' para marcar campos como 'subscribe_newsletter' y 'accept_terms' como seleccionados. +1. Guarda el Documento actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Fill Check Box Fields +def fill_check_box_fields(infile, outfile): + """Fill check box fields in PDF form.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill check box fields by name + pdf_form.fill_field("subscribe_newsletter", "Yes") + pdf_form.fill_field("accept_terms", "Yes") + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/es/python-net/working-with-facades/form/filling-form-fields/fill-fields-by-name-and-value/_index.md b/es/python-net/working-with-facades/form/filling-form-fields/fill-fields-by-name-and-value/_index.md new file mode 100644 index 000000000..b5efa2c54 --- /dev/null +++ b/es/python-net/working-with-facades/form/filling-form-fields/fill-fields-by-name-and-value/_index.md @@ -0,0 +1,51 @@ +--- +title: Rellenar campos por nombre y valor +linktitle: Rellenar campos por nombre y valor +type: docs +weight: 60 +url: /es/python-net/fill-fields-by-name-and-value/ +description: Este artículo muestra cómo rellenar dinámicamente múltiples campos de formulario PDF por nombre y valor usando Aspose.PDF for Python via .NET. En lugar de establecer cada campo individualmente, utiliza una estructura de diccionario para mapear los nombres de los campos a sus valores y los completa en un bucle. +lastmod: "2026-02-19" +--- + +Rellenar campos de formulario usando una colección de nombre‑valor permite a los desarrolladores crear soluciones escalables y flexibles para la automatización de formularios PDF. En este ejemplo, el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) fachada de [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) se utiliza para vincular un documento PDF e iterar a través de un diccionario de datos de campos. Cada entrada se aplica usando el ’fill_field method’, lo que permite actualizaciones masivas eficientes de los campos de formulario. + +1. Inicializa ’pdf_facades.Form()’ para trabajar con campos de formulario interactivos. +1. Utilice 'bind_pdf()' para adjuntar el documento PDF de origen. +1. Crea un diccionario que contenga los nombres de los campos y los valores que deseas insertar. +1. Itera a través del diccionario y llama a 'fill_field()' para cada entrada. +1. Guarda el Documento actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Fill Fields by Name and Value +def fill_fields_by_name_and_value(infile, outfile): + """Fill PDF form fields by name and value.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill fields by name and value + fields = { + "name": "Jane Smith", + "address": "456 Elm St, Othertown, USA", + "email": "jane.smith@example.com", + } + for field_name, value in fields.items(): + pdf_form.fill_field(field_name, value) + + # Save updated PDF using outfile + pdf_form.save(outfile) +``` diff --git a/es/python-net/working-with-facades/form/filling-form-fields/fill-list-box/_index.md b/es/python-net/working-with-facades/form/filling-form-fields/fill-list-box/_index.md new file mode 100644 index 000000000..c4a28ad7a --- /dev/null +++ b/es/python-net/working-with-facades/form/filling-form-fields/fill-list-box/_index.md @@ -0,0 +1,44 @@ +--- +title: Rellenar cuadro de lista +linktitle: Rellenar cuadro de lista +type: docs +weight: 40 +url: /es/python-net/fill-list-box/ +description: Este ejemplo demuestra cómo rellenar programáticamente campos de cuadro de lista y de selección múltiple en un formulario PDF utilizando Aspose.PDF for Python via .NET. Muestra cómo enlazar un documento PDF, seleccionar valores dentro de un campo de formulario basado en listas y guardar el archivo actualizado. +lastmod: "2026-02-19" +--- + +Los campos de cuadro de lista y de selección múltiple permiten a los usuarios elegir uno o varios valores de un conjunto de opciones predefinido. En este ejemplo, el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) fachada de [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) se utiliza para acceder al formulario PDF y asignar un valor seleccionado al campo favorite_colors. Una vez que se selecciona la opción deseada, el documento actualizado se guarda. + +1. Inicializa 'pdf_facades.Form()' para gestionar y actualizar los campos del formulario. +1. Llama a 'bind_pdf()' para adjuntar el PDF origen que contiene campos de cuadro de lista o de selección múltiple. +1. Utilice 'fill_field()' para seleccionar un valor de las opciones disponibles. +1. Guarda el Documento actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Fill List Box / Multi-Select Fields +def fill_list_box_fields(infile, outfile): + """Fill list box and multi-select fields in PDF form.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill list box / multi-select fields by name + pdf_form.fill_field("favorite_colors", "Red") + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/es/python-net/working-with-facades/form/filling-form-fields/fill-radio-button-fields/_index.md b/es/python-net/working-with-facades/form/filling-form-fields/fill-radio-button-fields/_index.md new file mode 100644 index 000000000..45d7e52e8 --- /dev/null +++ b/es/python-net/working-with-facades/form/filling-form-fields/fill-radio-button-fields/_index.md @@ -0,0 +1,45 @@ +--- +title: Rellenar campos de botones de radio +linktitle: Rellenar campos de botones de radio +type: docs +weight: 30 +url: /es/python-net/fill-radio-button-fields/ +description: Este ejemplo demuestra cómo rellenar programáticamente campos de botones de radio en un formulario PDF usando Aspose.PDF for Python via .NET. Muestra cómo vincular un documento PDF, seleccionar una opción de botón de radio por índice y guardar el archivo actualizado. +lastmod: "2026-02-19" +--- + +Los botones de radio permiten a los usuarios seleccionar una única opción de un grupo predefinido, como campos de género o de preferencia. En este ejemplo, el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) fachada del [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) módulo se utiliza para vincular el PDF de origen y asignar una opción seleccionada mediante su valor de índice. Una vez elegida la opción deseada, el documento modificado se guarda. + +1. Inicializa pdf_facades.Form() para gestionar los campos de formulario PDF. +1. Llama a 'bind_pdf()' para adjuntar el PDF que contiene campos de botones de radio. +1. Use 'fill_field()' para seleccionar la primera opción (índice 0). +1. Guarde el PDF actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Fill Radio Button Fields +def fill_radio_button_fields(infile, outfile): + """Fill radio button fields in PDF form.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill radio button fields by name + pdf_form.fill_field("gender", 0) # Select male option (index 0) + # pdf_form.fill_field("gender", 1) # Select female option (index 1) + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/es/python-net/working-with-facades/form/filling-form-fields/fill-text-fields/_index.md b/es/python-net/working-with-facades/form/filling-form-fields/fill-text-fields/_index.md new file mode 100644 index 000000000..749459ff4 --- /dev/null +++ b/es/python-net/working-with-facades/form/filling-form-fields/fill-text-fields/_index.md @@ -0,0 +1,46 @@ +--- +title: Rellenar campos de texto +linktitle: Rellenar campos de texto +type: docs +weight: 10 +url: /es/python-net/fill-text-fields/ +description: Este ejemplo muestra cómo rellenar automáticamente campos de texto en un formulario PDF usando Aspose.PDF for Python via .NET. Muestra cómo cargar un documento PDF, rellenar campos de formulario específicos por nombre y guardar el archivo actualizado. +lastmod: "2026-02-19" +--- + +Rellenar programáticamente campos de texto permite a las aplicaciones reutilizar plantillas PDF e insertar contenido dinámico sin edición manual. En este ejemplo, el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) fachada de [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) se utiliza para enlazar un formulario PDF y actualizar varios campos como nombre, dirección y correo electrónico. Después de asignar los valores, el PDF modificado se guarda como un nuevo documento. + +1. Inicialice 'pdf_facades.Form()' para gestionar operaciones de campos de formulario. +1. Utilice 'bind_pdf()' para adjuntar el PDF de entrada que contiene campos de texto. +1. Llame a 'fill_field()' para insertar datos en campos como nombre, dirección y correo electrónico. +1. Guarde el PDF actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Fill Text Fields +def fill_text_fields(infile, outfile): + """Fill text fields in PDF form.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill text fields by name + pdf_form.fill_field("name", "John Doe") + pdf_form.fill_field("address", "123 Main St, Anytown, USA") + pdf_form.fill_field("email", "john.doe@example.com") + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/es/python-net/working-with-facades/form/importing-form-data/_index.md b/es/python-net/working-with-facades/form/importing-form-data/_index.md new file mode 100644 index 000000000..74317149d --- /dev/null +++ b/es/python-net/working-with-facades/form/importing-form-data/_index.md @@ -0,0 +1,15 @@ +--- +title: Importación de datos de formulario +linktitle: Importación de datos de formulario +type: docs +weight: 20 +url: /es/python-net/importing-form-data/ +description: Esta sección muestra cómo importar y reemplazar datos de formulario PDF desde varios formatos externos utilizando Aspose.PDF for Python via .NET. Incluye ejemplos prácticos de cómo rellenar campos de formulario PDF a partir de archivos XML, FDF, XFDF y JSON, así como reemplazar conjuntos de datos XFA existentes. Al usar la fachada Form, los desarrolladores pueden vincular un documento PDF, cargar datos estructurados mediante flujos de archivo y actualizar automáticamente los campos del formulario sin edición manual. +lastmod: "2026-02-19" +--- + +- [Importar datos FDF](/pdf/es/python-net/import-fdf-data/) +- [Importar datos XFDF](/pdf/es/python-net/import-xfdf-data/) +- [Importar datos JSON](/pdf/es/python-net/import-json-data/) +- [Importar datos XML](/pdf/es/python-net/import-xml-data/) +- [Reemplazar datos XFA](/pdf/es/python-net/replace-xfa-data/) diff --git a/es/python-net/working-with-facades/form/importing-form-data/import-fdf-data/_index.md b/es/python-net/working-with-facades/form/importing-form-data/import-fdf-data/_index.md new file mode 100644 index 000000000..005d73a66 --- /dev/null +++ b/es/python-net/working-with-facades/form/importing-form-data/import-fdf-data/_index.md @@ -0,0 +1,46 @@ +--- +title: Importar datos FDF +linktitle: Importar datos FDF +type: docs +weight: 10 +url: /es/python-net/import-fdf-data/ +description: Este ejemplo muestra cómo importar datos de formulario desde un archivo FDF a un formulario PDF usando Aspose.PDF for Python via .NET. Muestra cómo vincular un documento PDF, leer los valores de los campos del formulario desde un flujo FDF y rellenar automáticamente los campos correspondientes. +lastmod: "2026-02-19" +--- + +FDF (Forms Data Format) es un formato ligero utilizado para almacenar y transferir los valores de los campos de formularios PDF sin incluir todo el documento. En este ejemplo, el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) fachada de [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) se utiliza para cargar un formulario PDF e importar datos de campos desde un archivo FDF externo. Después del proceso de importación, el PDF actualizado se guarda como un archivo nuevo. + +1. Inicializa pdf_facades.Form() para trabajar con campos de formulario PDF interactivos. +1. Llama a 'bind_pdf()' para adjuntar la plantilla del formulario PDF. +1. Utilice 'open()' para leer el archivo FDF en modo binario. +1. Llame a 'import_fdf()' para rellenar los campos PDF con datos del archivo FDF. +1. Guarde el PDF actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Import Data from FDF +def import_fdf_to_pdf_form(infile, datafile, outfile): + """Import form data from FDF file into PDF form fields.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Open FDF file as stream + with open(datafile, "rb") as fdf_input_stream: + pdf_form.import_fdf(fdf_input_stream) + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/es/python-net/working-with-facades/form/importing-form-data/import-json-data/_index.md b/es/python-net/working-with-facades/form/importing-form-data/import-json-data/_index.md new file mode 100644 index 000000000..e9aa679af --- /dev/null +++ b/es/python-net/working-with-facades/form/importing-form-data/import-json-data/_index.md @@ -0,0 +1,47 @@ +--- +title: Importar datos JSON +linktitle: Importar datos JSON +type: docs +weight: 30 +url: /es/python-net/import-json-data/ +description: Este ejemplo muestra cómo importar datos de campos de formulario desde un archivo JSON a un formulario PDF usando Aspose.PDF for Python via .NET. Demuestra cómo vincular un documento PDF, leer datos JSON estructurados a través de un flujo de archivo y rellenar automáticamente los campos de formulario coincidentes. +lastmod: "2026-02-19" +--- + +JSON se utiliza ampliamente para almacenar y transferir datos estructurados entre sistemas. En este ejemplo, el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) fachada del [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) el módulo se utiliza para vincular un formulario PDF e importar valores de campos desde un archivo JSON externo. Después del proceso de importación, el documento actualizado se guarda como un nuevo PDF. + +1. Inicializar pdf_facades.Form() para interactuar con los campos de formulario PDF. +1. Llama a 'bind_pdf()' para adjuntar la plantilla del formulario PDF. +1. Usar 'FileIO()' para leer el archivo JSON que contiene los valores del formulario. +1. Llame a 'import_json()' para rellenar los campos PDF usando pares clave‑valor JSON. +1. Guarde el PDF actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Import from JSON +def import_json_to_pdf_form(infile, datafile, outfile): + """Import form data from JSON file into PDF form fields.""" + # Create Form object + form = pdf_facades.Form() + + # Bind PDF document + form.bind_pdf(infile) + + # Open JSON file as stream + with FileIO(datafile, "r") as json_stream: + # Import data from JSON into PDF form fields + form.import_json(json_stream) + + # Save updated PDF + form.save(outfile) +``` diff --git a/es/python-net/working-with-facades/form/importing-form-data/import-xfdf-data/_index.md b/es/python-net/working-with-facades/form/importing-form-data/import-xfdf-data/_index.md new file mode 100644 index 000000000..ed32d4471 --- /dev/null +++ b/es/python-net/working-with-facades/form/importing-form-data/import-xfdf-data/_index.md @@ -0,0 +1,47 @@ +--- +title: Importar datos XFDF +linktitle: Importar datos XFDF +type: docs +weight: 20 +url: /es/python-net/import-xfdf-data/ +description: Este ejemplo muestra cómo importar datos de formulario desde un archivo XFDF a un formulario PDF usando Aspose.PDF for Python via .NET. Muestra cómo enlazar un documento PDF, leer datos XFDF basados en XML mediante un flujo de archivo y rellenar automáticamente los campos de formulario coincidentes. La importación de datos XFDF permite un intercambio de datos de formulario eficiente y admite flujos de trabajo de documentos automatizados que dependen de formatos XML estructurados. +lastmod: "2026-02-19" +--- + +XFDF (Formato de Datos de Formularios XML) es una representación XML de los datos de formularios PDF diseñada para la interoperabilidad y el intercambio de datos. En este ejemplo, el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) fachada del [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) módulo se utiliza para enlazar un formulario PDF e importar valores de campos desde un archivo XFDF externo. Después de importar los datos, el PDF actualizado se guarda como un nuevo documento. + +1. Inicializar pdf_facades.Form() para interactuar con los campos de formulario PDF. +1. Llama a 'bind_pdf()' para adjuntar la plantilla del formulario PDF. +1. Use 'open()' para leer el archivo XFDF. +1. Llame a 'import_xfdf()' para rellenar los campos PDF con valores del archivo XFDF. +1. Guarda el Documento actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Import Data from XFDF +def import_data_from_xfdf(infile, datafile, outfile): + """Import form data from XFDF file into PDF form fields.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Open XFDF file as stream + with open(datafile, "rb") as xfdf_input_stream: + # Import data from XFDF into PDF form fields + pdf_form.import_xfdf(xfdf_input_stream) + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/es/python-net/working-with-facades/form/importing-form-data/import-xml-data/_index.md b/es/python-net/working-with-facades/form/importing-form-data/import-xml-data/_index.md new file mode 100644 index 000000000..e44317b20 --- /dev/null +++ b/es/python-net/working-with-facades/form/importing-form-data/import-xml-data/_index.md @@ -0,0 +1,47 @@ +--- +title: Importar datos XML +linktitle: Importar datos XML +type: docs +weight: 40 +url: /es/python-net/import-xml-data/ +description: Este ejemplo muestra cómo importar datos de formulario desde un archivo XML a los campos de formulario PDF utilizando Aspose.PDF for Python via .NET. Muestra cómo vincular un documento PDF, leer datos XML estructurados a través de un flujo de archivo y rellenar automáticamente los campos de formulario correspondientes. +lastmod: "2026-02-19" +--- + +XML se usa comúnmente para almacenar datos de formulario estructurados, lo que lo convierte en un formato práctico para transferir valores entre sistemas. En este ejemplo, el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) fachada de [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) se usa para cargar un formulario PDF y aplicar valores de campo directamente desde un archivo XML. Después de importar los datos, el PDF actualizado se guarda como un nuevo documento. + +1. Inicializar pdf_facades.Form() para interactuar con los campos de formulario PDF. +1. Llama a 'bind_pdf()' para adjuntar la plantilla del formulario PDF. +1. Use 'FileIO()' para acceder al archivo XML que contiene los datos del formulario. +1. Llama a 'import_xml()' para rellenar los campos PDF con valores del archivo XML. +1. Guarde el PDF actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Import data from XML +def import_xml_to_pdf_fields(infile, datafile, outfile): + """Import form data from XML file into PDF form fields.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Open XML file as stream + with FileIO(datafile, "r") as xml_input_stream: + # Import data from XML into PDF form fields + pdf_form.import_xml(xml_input_stream) + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/es/python-net/working-with-facades/form/importing-form-data/replace-xfa-data/_index.md b/es/python-net/working-with-facades/form/importing-form-data/replace-xfa-data/_index.md new file mode 100644 index 000000000..fdcd1f12f --- /dev/null +++ b/es/python-net/working-with-facades/form/importing-form-data/replace-xfa-data/_index.md @@ -0,0 +1,47 @@ +--- +title: Reemplazar datos XFA +linktitle: Reemplazar datos XFA +type: docs +weight: 50 +url: /es/python-net/replace-xfa-data/ +description: Este ejemplo demuestra cómo reemplazar los datos de formulario XFA existentes en un PDF utilizando Aspose.PDF for Python via .NET. Muestra cómo vincular un documento PDF basado en XFA, cargar nuevos datos desde un archivo XFA externo y actualizar el contenido del formulario de forma programática. +lastmod: "2026-02-19" +--- + +Los formularios XFA (XML Forms Architecture) almacenan sus datos en formato XML dentro de la estructura PDF. En este ejemplo, el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) fachada del [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) módulo se utiliza para vincular un PDF y reemplazar su conjunto de datos XFA existente usando una secuencia XML externa. Después de aplicar los nuevos datos, el PDF actualizado se guarda como un archivo separado. + +1. Inicialice pdf_facades.Form() para gestionar los datos del formulario XFA. +1. Llame 'bind_pdf()' para adjuntar el PDF que contiene formularios XFA. +1. Utilice 'FileIO()' para leer el archivo XML XFA. +1. Llame a 'set_xfa_data()' para actualizar el PDF con nuevo contenido XFA. +1. Guarda el Documento actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Replace from XFA data +def replace_xfa_data(infile, datafile, outfile): + """Import form data from XFA file into PDF form fields.""" + # Create Form object + form = pdf_facades.Form() + + # Bind PDF document + form.bind_pdf(infile) + + # Open XFA file as stream + with FileIO(datafile, "r") as xfa_stream: + # Import data from XFA into PDF form fields + form.set_xfa_data(xfa_stream) + + # Save updated PDF + form.save(outfile) +``` diff --git a/es/python-net/working-with-facades/form/managing-form-fields/_index.md b/es/python-net/working-with-facades/form/managing-form-fields/_index.md new file mode 100644 index 000000000..cc4c967b6 --- /dev/null +++ b/es/python-net/working-with-facades/form/managing-form-fields/_index.md @@ -0,0 +1,13 @@ +--- +title: Gestión de campos de formulario +linktitle: Gestión de campos de formulario +type: docs +weight: 50 +url: /es/python-net/managing-form-fields/ +description: Esta sección muestra cómo gestionar y modificar los campos de formulario PDF usando Aspose.PDF for Python via .NET. Cubre ejemplos prácticos de aplanar campos específicos, aplanar todos los campos de formulario y renombrar campos existentes programáticamente. Al usar la fachada Form, los desarrolladores pueden enlazar un documento PDF, ajustar el comportamiento de los campos y guardar el archivo actualizado con los cambios permanentes aplicados. +lastmod: "2026-02-19" +--- + +- [Aplanar campos específicos](/pdf/es/python-net/flatten-specific-fields/) +- [Aplanar todos los campos](/pdf/es/python-net/flatten-all-fields/) +- [Renombrar campos de formulario](/pdf/es/python-net/rename-form-fields/) \ No newline at end of file diff --git a/es/python-net/working-with-facades/form/managing-form-fields/flatten-all-fields/_index.md b/es/python-net/working-with-facades/form/managing-form-fields/flatten-all-fields/_index.md new file mode 100644 index 000000000..8150f17d1 --- /dev/null +++ b/es/python-net/working-with-facades/form/managing-form-fields/flatten-all-fields/_index.md @@ -0,0 +1,44 @@ +--- +title: Aplanar todos los campos +linktitle: Aplanar todos los campos +type: docs +weight: 10 +url: /es/python-net/flatten-all-fields/ +description: Este ejemplo demuestra cómo aplanar todos los campos de formulario en un PDF usando Aspose.PDF for Python via .NET. Muestra cómo vincular un documento PDF, convertir cada elemento de formulario interactivo en contenido estático de página y guardar el archivo finalizado. +lastmod: "2026-02-19" +--- + +Aplanar elimina la interactividad de los formularios PDF al combinar los valores de los campos directamente en el diseño del documento. En este ejemplo, el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) fachada de [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) se usa para vincular el PDF de origen y aplicar el método flatten_all_fields(), que convierte todos los campos en contenido no editable. + +1. Inicializar pdf_facades.Form() para interactuar con los campos de formulario PDF. +1. Llame a 'bind_pdf()' para adjuntar el documento de origen. +1. Llame a 'flatten_all_fields()' para convertir todos los campos interactivos en contenido estático. +1. Guarda el Documento actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Flatten all fields +def flatten_all_fields(infile, outfile): + """Flatten all fields in a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Flatten all fields in the PDF document + pdf_form.flatten_all_fields() + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/es/python-net/working-with-facades/form/managing-form-fields/flatten-specific-fields/_index.md b/es/python-net/working-with-facades/form/managing-form-fields/flatten-specific-fields/_index.md new file mode 100644 index 000000000..5e606caca --- /dev/null +++ b/es/python-net/working-with-facades/form/managing-form-fields/flatten-specific-fields/_index.md @@ -0,0 +1,48 @@ +--- +title: Aplanar campos específicos +linktitle: Aplanar campos específicos +type: docs +weight: 20 +url: /es/python-net/flatten-specific-fields/ +description: Esta sección muestra cómo gestionar y modificar los campos de formulario PDF usando Aspose.PDF for Python via .NET. Incluye ejemplos prácticos de aplanado de campos específicos, aplanado de todos los campos de formulario y renombrado de campos existentes de forma programática. +lastmod: "2026-02-19" +--- + +Gestionar los campos de formulario es una parte importante de los flujos de trabajo de procesamiento de PDF. Aplanar los campos elimina la interactividad al convertir los elementos del formulario en contenido de página regular, mientras que renombrar los campos ayuda a estandarizar las convenciones de nomenclatura para un manejo de datos más sencillo. + +1. Inicializa pdf_facades.Form() para acceder y gestionar los campos de formulario PDF. +1. Utiliza \u0027bind_pdf()\u0027 para adjuntar el documento de entrada. +1. Proporciona los nombres de los campos y llama a \u0027flatten_field()\u0027 para convertir los campos seleccionados en contenido estático. +1. Llame a 'flatten_all_fields()' para eliminar la interactividad de cada campo de formulario. +1. Defina los nombres de campo antiguos y nuevos y aplique 'rename_field()'. +1. Guarde el PDF actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Flatten specific fields +def flatten_specific_fields(infile, outfile): + """Flatten specific fields in a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Flatten specific fields by their names + fields_to_flatten = ["First Name", "Last Name"] + for field_name in fields_to_flatten: + pdf_form.flatten_field(field_name) + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/es/python-net/working-with-facades/form/managing-form-fields/rename-form-fields/_index.md b/es/python-net/working-with-facades/form/managing-form-fields/rename-form-fields/_index.md new file mode 100644 index 000000000..3f41da5d8 --- /dev/null +++ b/es/python-net/working-with-facades/form/managing-form-fields/rename-form-fields/_index.md @@ -0,0 +1,47 @@ +--- +title: Renombrar campos de formulario +linktitle: Renombrar campos de formulario +type: docs +weight: 30 +url: /es/python-net/rename-form-fields/ +description: Este ejemplo demuestra cómo renombrar campos de formulario en un documento PDF usando Aspose.PDF for Python via .NET. Muestra cómo enlazar un formulario PDF, actualizar los nombres de los campos existentes programáticamente y guardar el archivo modificado. Renombrar los campos ayuda a estandarizar las estructuras de los formularios, mejorar el mapeo de datos y simplificar la integración con flujos de trabajo automatizados o sistemas externos. +lastmod: "2026-02-19" +--- + +Renombrar campos de formulario es útil al alinear los formularios PDF con convenciones de nombres internas o al preparar documentos para el procesamiento de datos estructurados. En este ejemplo, el [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) fachada del [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) módulo se utiliza para enlazar el PDF de origen y aplicar una asignación que reemplaza los nombres de campo antiguos por los nuevos. Después de actualizar los identificadores de los campos, el documento se guarda con los cambios aplicados. + +1. Inicializar pdf_facades.Form() para interactuar con los campos de formulario PDF. +1. Llame a 'bind_pdf()' para adjuntar el documento PDF. +1. Cree una lista de tuplas que contengan los nombres de campo antiguos y sus nuevos nombres correspondientes. +1. Itera a través del mapeo y llama a 'rename_field()' para cada entrada. +1. Guarda el Documento actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Rename form fields +def rename_form_fields(infile, outfile): + """Rename form fields in a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Rename form fields by providing a mapping of old names to new names + field_renaming_map = [("First Name", "NewFirstName"), ("Last Name", "NewLastName")] + for old_name, new_name in field_renaming_map: + pdf_form.rename_field(old_name, new_name) + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/es/python-net/working-with-facades/form/reading-form-values/_index.md b/es/python-net/working-with-facades/form/reading-form-values/_index.md new file mode 100644 index 000000000..94b10b78e --- /dev/null +++ b/es/python-net/working-with-facades/form/reading-form-values/_index.md @@ -0,0 +1,16 @@ +--- +title: Lectura de valores del formulario +linktitle: Lectura de valores del formulario +type: docs +weight: 60 +url: /es/python-net/reading-form-values/ +description: Esta sección explica cómo leer valores de formulario con Aspose.PDF Facades usando la Clase Form. +lastmod: "2026-02-19" +--- + +- [Obtener valores de campo](/pdf/es/python-net/get-field-values/) +- [Obtener opciones de botón de radio](/pdf/es/python-net/get-radio-button-options/) +- [Obtener nombres de campos obligatorios](/pdf/es/python-net/get-required-field-names/) +- [Obtener valores de texto enriquecido](/pdf/es/python-net/get-rich-text-values/) +- [Obtener fachadas de campo](/pdf/es/python-net/get-field-facades/) +- [Resolver nombres completos de campos](/pdf/es/python-net/resolve-full-field-names/) \ No newline at end of file diff --git a/es/python-net/working-with-facades/form/reading-form-values/get-field-facades/_index.md b/es/python-net/working-with-facades/form/reading-form-values/get-field-facades/_index.md new file mode 100644 index 000000000..1ddc5ce68 --- /dev/null +++ b/es/python-net/working-with-facades/form/reading-form-values/get-field-facades/_index.md @@ -0,0 +1,44 @@ +--- +title: Obtener fachadas de campo +linktitle: Obtener fachadas de campo +type: docs +weight: 10 +url: /es/python-net/get-field-facades/ +description: Este ejemplo demuestra cómo leer los valores de campos de formulario específicos de un documento PDF usando la API Aspose.PDF Facades. +lastmod: "2026-02-19" +--- + +Los formularios PDF contienen campos donde los usuarios pueden ingresar datos, como cuadros de texto, casillas de verificación o botones de radio. Para procesar estos formularios programáticamente, a menudo es necesario obtener los valores actuales de estos campos. + +1. Crear un objeto Form. +1. Vincular el documento PDF al objeto de formulario. +1. Obtener valores de campos. + +```python + + from io import FileIO + import sys + from os import path + import aspose.pdf as ap + import aspose.pdf.facades as pdf_facades + + sys.path.append(path.join(path.dirname(__file__), "..")) + + from config import set_license, initialize_data_dir + + + # Get field values + def get_field_values(infile): + """Get field values from a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Get field values by their names + field_names = ["First Name", "Last Name"] + for field_name in field_names: + value = pdf_form.get_field(field_name) + print(f"Value of '{field_name}': {value}") +``` \ No newline at end of file diff --git a/es/python-net/working-with-facades/form/reading-form-values/get-field-values/_index.md b/es/python-net/working-with-facades/form/reading-form-values/get-field-values/_index.md new file mode 100644 index 000000000..fb2962fd1 --- /dev/null +++ b/es/python-net/working-with-facades/form/reading-form-values/get-field-values/_index.md @@ -0,0 +1,44 @@ +--- +title: Obtener valores de campo +linktitle: Obtener valores de campo +type: docs +weight: 50 +url: /es/python-net/get-field-values/ +description: Recuperando valores de campo de un formulario PDF con Aspose.PDF Facades usando la clase Form. +lastmod: "2026-02-19" +--- + +Este fragmento de código muestra cómo recuperar los valores actuales de los campos de formulario de un documento PDF usando la API Aspose.PDF Facades. El [get_field()](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/#methods) método le permite acceder programáticamente a los datos ingresados en campos de texto, casillas de verificación, botones de opción y otros elementos AcroForm. + +1. Vincule el PDF a un objeto Form. +1. Especifique los nombres de los campos que desea leer. +1. Recupere el valor de cada campo usando get_field(). + +```python + + from io import FileIO + import sys + from os import path + import aspose.pdf as ap + import aspose.pdf.facades as pdf_facades + + sys.path.append(path.join(path.dirname(__file__), "..")) + + from config import set_license, initialize_data_dir + + + # Get field values + def get_field_values(infile): + """Get field values from a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Get field values by their names + field_names = ["First Name", "Last Name"] + for field_name in field_names: + value = pdf_form.get_field(field_name) + print(f"Value of '{field_name}': {value}") +``` \ No newline at end of file diff --git a/es/python-net/working-with-facades/form/reading-form-values/get-radio-button-options/_index.md b/es/python-net/working-with-facades/form/reading-form-values/get-radio-button-options/_index.md new file mode 100644 index 000000000..db6a990f5 --- /dev/null +++ b/es/python-net/working-with-facades/form/reading-form-values/get-radio-button-options/_index.md @@ -0,0 +1,43 @@ +--- +title: Obtener opciones de botón de radio +linktitle: Obtener opciones de botón de radio +type: docs +weight: 20 +url: /es/python-net/get-radio-button-options/ +description: Este artículo demuestra cómo recuperar el valor actualmente seleccionado de un campo de botón de radio en un documento PDF usando la API Aspose.PDF Facades. +lastmod: "2026-02-19" +--- + +Los campos de botón de radio en formularios PDF son controles agrupados donde solo se puede seleccionar una opción a la vez. Cada grupo tiene un nombre de campo, y cada opción tiene un valor correspondiente. + +1. Crear un objeto Form. +1. Vincular el documento PDF. +1. Recuperar la opción de botón de radio seleccionada. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Get radio button options +def get_radio_button_options(infile): + """Get radio button options from a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Get radio button options by their names + field_names = ["WorkType"] + for field_name in field_names: + options = pdf_form.get_button_option_current_value(field_name) + print(f"Options for '{field_name}': {options}") +``` diff --git a/es/python-net/working-with-facades/form/reading-form-values/get-required-field-names/_index.md b/es/python-net/working-with-facades/form/reading-form-values/get-required-field-names/_index.md new file mode 100644 index 000000000..ca4759f4b --- /dev/null +++ b/es/python-net/working-with-facades/form/reading-form-values/get-required-field-names/_index.md @@ -0,0 +1,42 @@ +--- +title: Obtener nombres de campos obligatorios +linktitle: Obtener nombres de campos obligatorios +type: docs +weight: 30 +url: /es/python-net/get-required-field-names/ +description: Este ejemplo muestra cómo identificar y obtener los nombres de los campos obligatorios de formulario en un documento PDF utilizando la API Aspose.PDF Facades. +lastmod: "2026-02-19" +--- + +Los formularios PDF pueden contener campos obligatorios que los usuarios deben completar antes de enviarlos. Estos campos suelen marcarse como obligatorios en las propiedades del formulario. + +1. Crear un objeto Form. +1. Vincular el documento PDF. +1. Acceda a todos los nombres de campo usando 'pdf_form.field_names'. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Get required field names +def get_required_field_names(infile): + """Get required field names from a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Get required field names + for field in pdf_form.field_names: + if pdf_form.is_required_field(field): + print(f"Required field: {field}") +``` diff --git a/es/python-net/working-with-facades/form/reading-form-values/get-rich-text-values/_index.md b/es/python-net/working-with-facades/form/reading-form-values/get-rich-text-values/_index.md new file mode 100644 index 000000000..da0d09a47 --- /dev/null +++ b/es/python-net/working-with-facades/form/reading-form-values/get-rich-text-values/_index.md @@ -0,0 +1,43 @@ +--- +title: Obtener valores de texto enriquecido +linktitle: Obtener valores de texto enriquecido +type: docs +weight: 40 +url: /es/python-net/get-rich-text-values/ +description: Esta sección explica cómo recuperar el contenido de texto enriquecido de un campo de formulario en un documento PDF usando la API Aspose.PDF Facades. A diferencia de los campos de texto simple, los campos de texto enriquecido pueden contener contenido con formato, como texto en negrita, diferentes fuentes, colores y estilo de párrafo. +lastmod: "2026-02-19" +--- + +Los formularios PDF pueden incluir campos de texto que admiten formato de texto enriquecido. Estos campos pueden almacenar contenido con atributos de estilo además de valores de texto simple. + +1. Crear un objeto Form. +1. Vincular el documento PDF. +1. Recuperar valores de texto enriquecido. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Get rich text values +def get_rich_text_values(infile): + """Get rich text values from a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Get rich text values by their names + field_names = ["Summary"] + for field_name in field_names: + rich_text_value = pdf_form.get_rich_text(field_name) + print(f"Rich text value of '{field_name}': {rich_text_value}") +``` diff --git a/es/python-net/working-with-facades/form/reading-form-values/resolve-full-field-names/_index.md b/es/python-net/working-with-facades/form/reading-form-values/resolve-full-field-names/_index.md new file mode 100644 index 000000000..b8942795d --- /dev/null +++ b/es/python-net/working-with-facades/form/reading-form-values/resolve-full-field-names/_index.md @@ -0,0 +1,43 @@ +--- +title: Resolver nombres completos de campos +linktitle: Resolver nombres completos de campos +type: docs +weight: 60 +url: /es/python-net/resolve-full-field-names/ +description: Este ejemplo muestra cómo obtener los nombres totalmente calificados de los campos de formulario en un documento PDF usando la API Aspose.PDF Facades. +lastmod: "2026-02-19" +--- + +En los formularios PDF, los campos pueden organizarse jerárquicamente, especialmente cuando se utilizan subformularios. Cada campo tiene un nombre corto y un nombre totalmente calificado. El nombre totalmente calificado representa la ruta completa del campo dentro de la jerarquía del formulario y es requerido por muchos métodos de la API que manipulan o leen datos de formularios. + +1. Crear un objeto Form. +1. Vincular el documento PDF. +1. Acceder a todos los nombres de campos de formulario. +1. Cada nombre totalmente calificado del campo\u0027s se resuelve usando get_full_field_name(). + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Resolve full field names +def resolve_full_field_names(infile): + """Resolve full field names in a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Resolve full field names + for field in pdf_form.field_names: + name = pdf_form.get_full_field_name(field) + print(f"Full field name: {name}") +``` diff --git a/es/python-net/working-with-facades/formeditor/_index.md b/es/python-net/working-with-facades/formeditor/_index.md new file mode 100644 index 000000000..677ff7f8f --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/_index.md @@ -0,0 +1,26 @@ +--- +title: Clase FormEditor +linktitle: Clase FormEditor +type: docs +weight: 100 +url: /es/python-net/formeditor-class/ +description: Aprenda cómo usar la clase FormEditor en Aspose.PDF for Python via .NET para crear campos de formulario, modificar campos existentes, personalizar la apariencia de los campos y añadir scripts o acciones de envío. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Cree y edite campos de formulario PDF en Python con la clase FormEditor +Abstract: Esta sección explica cómo usar la fachada FormEditor en Aspose.PDF for Python via .NET para crear y actualizar formularios PDF interactivos. Aprenda cómo crear campos de formulario, personalizar la apariencia de los campos, modificar campos existentes y añadir scripts o acciones de envío de forma programática. +--- + +El `FormEditor` La clase en Aspose.PDF Facades está diseñada para crear y actualizar campos de formulario PDF interactivos. Le ayuda a construir estructuras de formulario, ajustar las propiedades de los campos, cambiar la configuración de apariencia y adjuntar comportamiento interactivo, como scripts y acciones de envío, en aplicaciones Python. + +## Tareas comunes de FormEditor + +Utilice los siguientes tutoriales para trabajar con las principales capacidades de `FormEditor` fachada: + +- [Agregar scripts y acciones de envío](/pdf/es/python-net/adding-scripts-and-submit-actions/) +- [Personalización de la apariencia del campo](/pdf/es/python-net/customizing-field-appearance/) +- [Modificando campos de formulario](/pdf/es/python-net/modifying-form-fields/) +- [Creando campo de formulario](/pdf/es/python-net/creating-form-field) diff --git a/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md b/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md new file mode 100644 index 000000000..6100f595c --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md @@ -0,0 +1,22 @@ +--- +title: Agregar scripts y acciones de envío +linktitle: Agregar scripts y acciones de envío +type: docs +weight: 40 +url: /es/python-net/adding-scripts-and-submit-actions/ +description: Usando Aspose.PDF for Python, los desarrolladores pueden automatizar estas acciones sin editar manualmente el PDF. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar y gestionar scripts de campos de formulario PDF y acciones de envío en Python +Abstract: Aprende cómo agregar, modificar o eliminar programáticamente acciones de JavaScript para campos de formulario PDF, y configurar URLs de envío usando Aspose.PDF for Python. Esta guía explica cómo adjuntar scripts a los campos, actualizar scripts existentes, eliminar acciones de campo y establecer URLs para la presentación del formulario, habilitando formularios PDF dinámicos e interactivos. +--- + +- [Agregar script de campo](/pdf/es/python-net/add-field-script/) +- [Establecer script de campo](/pdf/es/python-net/set-field-script/) +- [Eliminar acción de campo](/pdf/es/python-net/remove-field-action/) +- [Establecer URL de envío](/pdf/es/python-net/set-submit-url/) +- [Establecer bandera de envío](/pdf/es/python-net/set-submit-flag/) + diff --git a/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md b/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md new file mode 100644 index 000000000..187520c01 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md @@ -0,0 +1,57 @@ +--- +title: Agregar script de campo +linktitle: Agregar script de campo +type: docs +weight: 10 +url: /es/python-net/add-field-script/ +description: Los formularios PDF interactivos pueden incluir JavaScript para automatizar acciones cuando los usuarios interactúan con los campos del formulario. Usando Aspose.PDF for Python, los desarrolladores pueden adjuntar fácilmente scripts a los elementos del formulario, como botones o campos de texto. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar acciones JavaScript a los campos de formulario PDF usando Python +Abstract: Este artículo explica cómo abrir un formulario PDF, asignar código JavaScript a un campo de formulario específico, agregar acciones de script adicionales y guardar el documento actualizado. El ejemplo usa la clase FormEditor de la API Aspose.PDF Facades para manipular el comportamiento del formulario programáticamente. +--- + +## Agregar acciones JavaScript a los campos de formulario PDF usando Python + +Este fragmento de código le permite agregar acciones JavaScript a un campo de formulario PDF existente usando la biblioteca Aspose.PDF for Python. Abre un documento PDF, asigna una acción JavaScript a un campo de formulario y agrega un script que se ejecuta cuando se activa el campo. Finalmente, el PDF actualizado se guarda como un nuevo archivo. +Usando el [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) clase de la [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) módulo, puede adjuntar programáticamente JavaScript a los campos de formulario existentes: + +1. Abra un formulario PDF existente. +1. Establezca una acción JavaScript para un campo específico. +1. Añade otra acción JavaScript al mismo campo. +1. Guarda el documento PDF modificado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_field_script(input_file_name, output_file_name): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + + # Open input PDF file + form_editor.bind_pdf(input_file_name) + + # Set JavaScript action for the field + form_editor.set_field_script( + "Script_Demo_Button", "app.alert('Script 1 has been executed');" + ) + + # Add JavaScript action to the field + form_editor.add_field_script( + "Script_Demo_Button", "app.alert('Script 2 has been executed');" + ) + + # Save output PDF file + form_editor.save(output_file_name) +``` diff --git a/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md b/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md new file mode 100644 index 000000000..f47ed65d8 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md @@ -0,0 +1,51 @@ +--- +title: Eliminar acción de campo +linktitle: Eliminar acción de campo +type: docs +weight: 20 +url: /es/python-net/remove-field-action/ +description: Eliminar JavaScript de los campos de formulario puede ser útil al modificar formularios PDF interactivos, desactivar acciones asignadas previamente o limpiar documentos que contienen scripts innecesarios. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Eliminar acciones de JavaScript de los campos de formulario PDF usando Python +Abstract: Con Aspose.PDF for Python, los desarrolladores pueden eliminar programáticamente las acciones de JavaScript adjuntas a los campos de formulario. Este artículo explica cómo abrir un formulario PDF existente, eliminar el script asociado a un campo específico utilizando la clase FormEditor, verificar la operación y guardar el documento modificado. +--- + +Los formularios PDF a menudo contienen acciones de JavaScript que se ejecutan cuando los usuarios interactúan con elementos del formulario, como botones o campos de entrada. En algunos casos, estos scripts deben eliminarse para simplificar el comportamiento del formulario, mejorar la seguridad o actualizar la lógica del formulario. Elimine una acción de JavaScript de un campo de formulario en un documento PDF usando Aspose.PDF for Python. El código abre un formulario PDF existente, localiza un campo específico, elimina su acción de JavaScript asociada y guarda el documento actualizado como un nuevo archivo PDF. + +Usando el [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) clase de la [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/), puede eliminar acciones de JavaScript de campos específicos en un formulario PDF existente: + +1. Abra un formulario PDF existente. +1. Ubique un campo de formulario llamado 'Script_Demo_Button'. +1. Elimine la acción JavaScript asociada a ese campo. +1. Verifique si la eliminación fue exitosa. +1. Guarde el documento PDF actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def remove_field_script(input_file_name, output_file_name): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + + # Open input PDF file + form_editor.bind_pdf(input_file_name) + + # Remove JavaScript action from the field + if not form_editor.remove_field_action("Script_Demo_Button"): + raise Exception("Failed to remove field script") + + # Save output PDF file + form_editor.save(output_file_name) +``` diff --git a/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md b/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md new file mode 100644 index 000000000..cbac29512 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md @@ -0,0 +1,60 @@ +--- +title: Establecer script de campo +linktitle: Establecer script de campo +type: docs +weight: 30 +url: /es/python-net/set-field-script/ +description: Este fragmento de código muestra cómo asignar una acción JavaScript a un campo de formulario en un documento PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Establecer acciones JavaScript para campos de formulario PDF usando Python +Abstract: Este artículo explica cómo abrir un documento PDF, asignar código JavaScript a un campo de formulario, actualizar el script usando la clase FormEditor y guardar el archivo modificado. El ejemplo demuestra cómo los scripts existentes pueden ser sobrescritos para modificar el comportamiento de los campos de formulario. +--- + +Los formularios PDF interactivos a menudo dependen de JavaScript para realizar tareas como mostrar alertas, validar la entrada o activar comportamientos dinámicos del formulario. Con Aspose.PDF for Python, los desarrolladores pueden gestionar programáticamente estos scripts. + +El ejemplo primero agrega una acción JavaScript al campo y luego la reemplaza con otro script usando el método 'set_field_script'. Este enfoque permite a los desarrolladores controlar o actualizar el comportamiento interactivo de los elementos de formulario PDF, como botones o campos de entrada. + +El FormField usado en este ejemplo se llama 'Script_Demo_Button', que típicamente representa un botón que ejecuta el script asignado cuando se activa. + +Usando el [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) clase de la [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) Módulo, los desarrolladores pueden gestionar programáticamente acciones JavaScript asociadas con FormFields: + +1. Abra un documento de formulario PDF existente. +1. Agregue una acción JavaScript a un FormField. +1. Establezca (reemplace) la acción JavaScript con un script nuevo. +1. Guarda el documento PDF modificado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_field_script(input_file_name, output_file_name): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + + # Open input PDF file + form_editor.bind_pdf(input_file_name) + + # Add JavaScript action to the field + form_editor.add_field_script( + "Script_Demo_Button", "app.alert('Script 1 has been executed');" + ) + + # Set JavaScript action for the field + form_editor.set_field_script( + "Script_Demo_Button", "app.alert('Script 2 has been executed');" + ) + + # Save output PDF file + form_editor.save(output_file_name) +``` diff --git a/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md b/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md new file mode 100644 index 000000000..6548d293a --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md @@ -0,0 +1,47 @@ +--- +title: Establecer bandera de envío +linktitle: Establecer bandera de envío +type: docs +weight: 50 +url: /es/python-net/set-submit-flag/ +description: Aprenda cómo establecer programáticamente una bandera de envío para un botón de formulario PDF usando Aspose.PDF for Python. Esto permite que el botón envíe los datos del formulario en un formato específico, como XFDF, cuando es pulsado por un usuario. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Establecer bandera de envío para un botón de formulario PDF usando Aspose.PDF for Python +Abstract: Los formularios PDF pueden configurarse para enviar datos del formulario a un servidor o punto final en diferentes formatos. Al establecer una bandera de envío en un campo de botón, los desarrolladores pueden definir cómo se envían los datos. Este tutorial muestra cómo usar la clase FormEditor para establecer una bandera de envío en un botón de envío existente en un documento PDF y guardar el archivo actualizado. +--- + +Los formularios PDF a menudo incluyen botones de envío para enviar la entrada del usuario a un servidor. La bandera de envío determina el formato de datos enviado (p. ej., XFDF, FDF, HTML). + +1. Vincular un documento PDF. +1. Acceda a un botón de envío existente. +1. Establezca el indicador de envío para el formato deseado. +1. Guarde el documento PDF actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_submit_flag(input_file_name, output_file_name): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + + # Open input PDF file + form_editor.bind_pdf(input_file_name) + + # Set submit flag for the form + form_editor.set_submit_flag("Script_Demo_Button", ap.facades.SubmitFormFlag.XFDF) + + # Save output PDF file + form_editor.save(output_file_name) +``` diff --git a/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md b/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md new file mode 100644 index 000000000..868ba15de --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md @@ -0,0 +1,57 @@ +--- +title: Establecer URL de envío +linktitle: Establecer URL de envío +type: docs +weight: 40 +url: /es/python-net/set-submit-url/ +description: Este ejemplo muestra cómo configurar una acción de envío para un campo de botón en un formulario PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Establecer una URL de envío para un botón de formulario PDF usando Python +Abstract: Este artículo explica cómo abrir un formulario PDF existente, definir una URL de envío para un campo de botón usando la clase FormEditor, verificar que la operación se haya realizado con éxito y guardar el documento PDF actualizado. +--- + +Los formularios PDF pueden diseñarse para enviar sus datos a un servidor web cuando un usuario hace clic en un botón de envío. Usando Aspose.PDF for Python, los desarrolladores pueden configurar programáticamente una acción de envío para los campos del formulario. +Al establecer una URL de envío, el formulario puede enviar los datos ingresados por el usuario a un servidor cuando se hace clic en el botón. Esta funcionalidad es útil para flujos de trabajo donde los formularios PDF deben enviar información a aplicaciones web, bases de datos o servicios de procesamiento. + +Usando el [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) clase de la [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) Módulo, los desarrolladores pueden asignar programáticamente una URL de envío a un campo de botón en un formulario PDF existente. + +1. Abra un formulario PDF existente. +1. Localice un campo de botón llamado Script_Demo_Button. +1. Asigne una URL donde se enviarán los datos del formulario. +1. Verifique que la acción se haya aplicado correctamente. +1. Guarde el documento PDF actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_submit_url(input_file_name, output_file_name): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + + # Set license + set_license() + + # Open input PDF file + form_editor.bind_pdf(input_file_name) + + # Set submit URL for the button + if not form_editor.set_submit_url( + "Script_Demo_Button", "http://www.example.com/submit" + ): + raise Exception("Failed to set submit URL") + + # Save output PDF file + form_editor.save(output_file_name) +``` diff --git a/es/python-net/working-with-facades/formeditor/creating-form-field/_index.md b/es/python-net/working-with-facades/formeditor/creating-form-field/_index.md new file mode 100644 index 000000000..0468a9140 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/creating-form-field/_index.md @@ -0,0 +1,22 @@ +--- +title: Creando campo de formulario +linktitle: Creando campo de formulario +type: docs +weight: 50 +url: /es/python-net/creating-form-field/ +description: Este artículo muestra cómo crear campos de formulario interactivos en documentos PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Crear campos de formulario PDF en Python +Abstract: 'Los formularios PDF permiten a los usuarios ingresar o seleccionar datos directamente dentro de un documento. Con Aspose.PDF, los desarrolladores pueden crear programáticamente una variedad de campos de formulario: CheckBox para selecciones booleanas, ComboBox para listas desplegables, ListBox para listas de selección múltiple, RadioButton para opciones exclusivas, TextBox para entrada de texto y SubmitButton para enviar los datos del formulario. Este enfoque unificado simplifica la creación de PDFs interactivos, garantizando una ubicación precisa, un estilo coherente y compatibilidad con el procesamiento automatizado y la gestión de la entrada del usuario.' +--- + +- [Crear campo CheckBox](/pdf/es/python-net/create-checkbox-field/) +- [Crear campo ComboBox](/pdf/es/python-net/create-combobox-field/) +- [Crear campo ListBox](/pdf/es/python-net/create-listbox-field/) +- [Crear campo RadioButton](/pdf/es/python-net/create-radiobutton-field/) +- [Crear botón de envío](/pdf/es/python-net/create-submit-button/) +- [Crear campo TextBox](/pdf/es/python-net/create-textbox-field/) \ No newline at end of file diff --git a/es/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md b/es/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md new file mode 100644 index 000000000..d71d1f9fa --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md @@ -0,0 +1,55 @@ +--- +title: Crear campo CheckBox +linktitle: Crear campo CheckBox +type: docs +weight: 10 +url: /es/python-net/create-checkbox-field/ +description: Aprenda cómo agregar programáticamente un campo de formulario checkbox a un documento PDF usando Aspose.PDF for Python. Esta guía demuestra cómo usar la clase FormEditor para insertar un checkbox interactivo en un archivo PDF existente y guardar el documento actualizado. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Crear un campo Checkbox en un PDF usando Aspose.PDF for Python +Abstract: Los campos de formulario interactivos permiten a los usuarios completar e interactuar con documentos PDF de forma digital. En este tutorial, aprenderá cómo agregar un campo checkbox a un PDF usando la API de Aspose.PDF para Python. El ejemplo muestra cómo vincular un documento PDF existente, crear un campo de formulario checkbox en coordenadas especificadas y guardar el archivo modificado. +--- + +Los formularios PDF se utilizan ampliamente para recopilar la entrada del usuario en documentos como solicitudes, encuestas y acuerdos. Un campo checkbox permite a los usuarios seleccionar o deseleccionar una opción dentro de un formulario. + +Usando Aspose.PDF for Python, los desarrolladores pueden manipular formularios PDF programáticamente. The [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) La clase proporciona métodos para agregar, editar y gestionar campos de formulario dentro de un documento PDF. + +1. Cargar un archivo PDF existente. +1. Llame al método 'add_field()' con el parámetro 'FieldType.CHECK_BOX' para crear la casilla de verificación y especificar su posición. +1. Defina el nombre del campo, el título y la posición. +1. Guarde el documento PDF actualizado. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def create_checkbox_field(infile, outfile): + """Create CheckBox field in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add CheckBox field to PDF form + pdf_form_editor.add_field( + pdf_facades.FieldType.CHECK_BOX, + "checkbox1", + "Check Box 1", + 1, + 240, + 498, + 256, + 514, + ) + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md b/es/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md new file mode 100644 index 000000000..6d414e9c5 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md @@ -0,0 +1,50 @@ +--- +title: Crear campo ComboBox +linktitle: Crear campo ComboBox +type: docs +weight: 20 +url: /es/python-net/create-combobox-field/ +description: Verifique cómo agregar programáticamente un campo ComboBox (lista desplegable) a un documento PDF usando Aspose.PDF for Python. Este ejemplo muestra cómo insertar un campo de formulario ComboBox, añadir elementos seleccionables y guardar el archivo PDF actualizado. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Crear un campo ComboBox en un PDF usando Aspose.PDF for Python +Abstract: Los campos de formulario interactivos hacen que los PDFs sean más dinámicos y fáciles de usar. Un campo ComboBox permite a los usuarios seleccionar una opción de una lista desplegable predefinida. En este tutorial, aprenderá cómo crear un ComboBox en un PDF usando la clase FormEditor en Aspose.PDF for Python, poblarlo con opciones y guardar el documento modificado. +--- + +Los formularios PDF se utilizan ampliamente para recopilar información estructurada en documentos digitales como solicitudes, encuestas y formularios de registro. Un campo ComboBox ofrece una manera conveniente para que los usuarios elijan de una lista de valores predefinidos mientras se mantiene el formulario compacto y organizado. + +El [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) La clase permite crear y gestionar diferentes tipos de campos, incluidos los cuadros de texto, casillas de verificación, botones de radio y listas desplegables. + +1. Cargar un documento PDF existente. +1. Agregar un campo ComboBox con el método 'add_field()' y el parámetro 'FieldType.COMBO_BOX'. +1. Utilizar el método 'add_list_item()' para insertar opciones seleccionables en la lista desplegable. +1. Guarde el documento PDF actualizado. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def create_combobox_field(infile, outfile): + """Create ComboBox field in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add ComboBox field to PDF form + pdf_form_editor.add_field( + pdf_facades.FieldType.COMBO_BOX, "combobox1", "Australia", 1, 230, 498, 350, 514 + ) + pdf_form_editor.add_list_item("combobox1", ["Australia", "Australia"]) + pdf_form_editor.add_list_item("combobox1", ["New Zealand", "New Zealand"]) + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md b/es/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md new file mode 100644 index 000000000..f7635b092 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md @@ -0,0 +1,50 @@ +--- +title: Crear campo ListBox +linktitle: Crear campo ListBox +type: docs +weight: 30 +url: /es/python-net/create-listbox-field/ +description: Aprenda cómo agregar programáticamente un campo de formulario ListBox a un documento PDF usando Aspose.PDF for Python. Esta guía muestra cómo insertar un campo ListBox, definir los elementos seleccionables y guardar el archivo PDF actualizado. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Crear un campo ListBox en un PDF usando Aspose.PDF for Python +Abstract: Los formularios PDF permiten a los usuarios interactuar con los documentos seleccionando opciones, ingresando datos y enviando información de forma digital. Un campo ListBox permite a los usuarios elegir uno o varios valores de una lista visible de opciones. En este tutorial, aprenderá cómo crear un campo ListBox en un PDF utilizando la clase FormEditor en Aspose.PDF for Python y rellenarlo con elementos predefinidos. +--- + +Los formularios PDF se utilizan comúnmente para solicitudes, encuestas y documentos de registro. Un campo ListBox muestra múltiples opciones simultáneamente, facilitando a los usuarios revisar y seleccionar elementos de una lista. + +El [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) La clase proporciona funcionalidad para agregar diferentes tipos de campos interactivos, incluidos los elementos ListBox. + +1. Cargar un documento PDF existente. +1. Definir una lista de opciones seleccionables. +1. Agregar un campo ListBox a una página específica. +1. Establecer un valor seleccionado predeterminado. +1. Guarde el documento PDF actualizado. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def create_listbox_field(infile, outfile): + """Create ListBox field in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add ListBox field to PDF form + pdf_form_editor.items = ["Australia", "New Zealand", "Malaysia"] + pdf_form_editor.add_field( + pdf_facades.FieldType.LIST_BOX, "listbox1", "Australia", 1, 230, 398, 350, 514 + ) + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md b/es/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md new file mode 100644 index 000000000..e6a90c7d5 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md @@ -0,0 +1,50 @@ +--- +title: Crear campo RadioButton +linktitle: Crear campo RadioButton +type: docs +weight: 40 +url: /es/python-net/create-radiobutton-field/ +description: Aprenda cómo agregar programáticamente un campo de formulario de botón de opción a un documento PDF utilizando Aspose.PDF for Python. Este ejemplo muestra cómo crear un grupo de botones de opción, definir opciones seleccionables y guardar el archivo PDF actualizado. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Crear un campo de botón de opción en un PDF usando Aspose.PDF for Python +Abstract: Los botones de opción se utilizan comúnmente en formularios PDF para permitir a los usuarios seleccionar una opción de un grupo predefinido de elecciones. En este tutorial, aprenderá cómo crear un campo de botón de opción en un PDF usando la clase FormEditor en Aspose.PDF for Python. El ejemplo muestra cómo definir los elementos del botón de opción, establecer una selección predeterminada y guardar el documento actualizado. +--- + +Los formularios PDF interactivos permiten a los usuarios proporcionar entradas estructuradas directamente dentro de un documento. Un campo de botón de opción es útil cuando los usuarios deben elegir solo una opción entre varias, como seleccionar un país, género o preferencia. + +El [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) La clase proporciona métodos para crear diferentes tipos de campos, incluidos cuadros de texto, casillas de verificación, cuadros combinados, listas desplegables y botones de opción + +1. Cargar un documento PDF existente. +1. Definir una lista de opciones de botones de radio. +1. Agregar un campo de botón de radio a una página específica. +1. Establecer un valor seleccionado predeterminado. +1. Guarda el documento PDF modificado. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def create_radiobutton_field(infile, outfile): + """Create RadioButton field in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add RadioButton field to PDF form + pdf_form_editor.items = ["Australia", "New Zealand", "Malaysia"] + pdf_form_editor.add_field( + pdf_facades.FieldType.RADIO, "radiobutton1", "Malaysia", 1, 240, 498, 256, 514 + ) + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md b/es/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md new file mode 100644 index 000000000..d711c345e --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md @@ -0,0 +1,55 @@ +--- +title: Crear botón de envío +linktitle: Crear botón de envío +type: docs +weight: 50 +url: /es/python-net/create-submit-button/ +description: Aprenda cómo agregar un botón de envío a un documento PDF de forma programática usando Aspose.PDF for Python. Este tutorial demuestra cómo crear un botón que envía los datos del formulario a una URL especificada y guarda el PDF actualizado. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Crear un botón de envío en un PDF usando Aspose.PDF for Python +Abstract: Los botones de envío en formularios PDF permiten a los usuarios enviar los datos del formulario directamente a un servidor o punto final. En esta guía, aprenderá cómo agregar un campo de botón de envío a un PDF usando la clase FormEditor en Aspose.PDF for Python. El ejemplo muestra cómo configurar el nombre del botón, la etiqueta, la URL de destino y la posición, y luego guardar el documento PDF actualizado. +--- + +Los formularios PDF interactivos a menudo requieren que los usuarios envíen sus entradas para su procesamiento, como el envío de resultados de encuestas, formularios de solicitud o datos de retroalimentación. Un campo de botón de envío proporciona esta funcionalidad al vincular el botón a un punto final web. + +El [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) class permite agregar botones, casillas de verificación, botones de opción, campos de texto y otros controles de formulario. + +1. Cargar un documento PDF existente. +1. Agregar un campo de botón de envío a una página específica. +1. Establecer la etiqueta del botón y la URL de envío de destino. +1. Guardar el PDF actualizado con el nuevo botón. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def create_submit_button(infile, outfile): + """Create Submit Button in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add Submit Button to PDF form + pdf_form_editor.add_submit_btn( + "submitbtn1", + 1, + "Submit Button", + "http://example.com/submit", + 100, + 450, + 200, + 470, + ) + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md b/es/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md new file mode 100644 index 000000000..2e25882d9 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md @@ -0,0 +1,51 @@ +--- +title: Crear campo TextBox +linktitle: Crear campo TextBox +type: docs +weight: 60 +url: /es/python-net/create-textbox-field/ +description: Aprenda cómo agregar programáticamente campos TextBox a un documento PDF usando Aspose.PDF for Python. Este tutorial muestra cómo insertar múltiples campos de texto, establecer valores predeterminados y guardar el documento PDF actualizado. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Crear campos TextBox en un PDF usando Aspose.PDF for Python +Abstract: Los campos TextBox en formularios PDF permiten a los usuarios introducir y editar texto, haciendo que los documentos sean interactivos y fáciles de usar. En este tutorial, aprenderá cómo crear campos de formulario TextBox en un PDF usando la clase FormEditor en Aspose.PDF for Python. El ejemplo demuestra cómo agregar múltiples campos, especificar valores predeterminados y guardar el PDF modificado. +--- + +Los formularios PDF a menudo requieren la entrada de texto por parte de los usuarios, como nombres, direcciones o comentarios. Los campos TextBox habilitan esta funcionalidad al proporcionar campos editables directamente dentro del documento PDF. + +El [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) class permite agregar campos de texto, casillas de verificación, botones de radio, listas desplegables, combo boxes y botones, facilitando la creación de PDFs interactivos. + +1. Cargar un documento PDF existente. +1. Agregar varios campos TextBox para la entrada del usuario. +1. Establecer valores predeterminados para cada campo. +1. Guarde el documento PDF actualizado. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def create_textbox_field(infile, outfile): + """Create TextBox field in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add TextBox field to PDF form + pdf_form_editor.add_field( + pdf_facades.FieldType.TEXT, "first_name", "Alexander", 1, 50, 570, 150, 590 + ) + pdf_form_editor.add_field( + pdf_facades.FieldType.TEXT, "last_name", "Smith", 1, 235, 570, 330, 590 + ) + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md b/es/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md new file mode 100644 index 000000000..4013432bb --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md @@ -0,0 +1,24 @@ +--- +title: Personalización de la apariencia del campo +linktitle: Personalización de la apariencia del campo +type: docs +weight: 30 +url: /es/python-net/customizing-field-appearance/ +description: Usando Aspose.PDF for Python, los desarrolladores pueden personalizar completamente la apariencia y el comportamiento de los campos programáticamente. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Personaliza la apariencia de los campos de formulario PDF en Python - Alineación, colores, límites y atributos +Abstract: Aprenda cómo personalizar la apariencia y el comportamiento de los campos de formulario PDF usando Aspose.PDF for Python. Esta guía cubre la decoración de los campos con colores y bordes, la configuración de la alineación horizontal y vertical, el control de la visibilidad, el ajuste de los atributos del campo, la configuración de los números de comb y los límites de caracteres, y la obtención de información sobre la apariencia del campo. Estas técnicas ayudan a los desarrolladores a crear formularios PDF visualmente consistentes y fáciles de usar. +--- + +- [Decorar Campo](/pdf/es/python-net/decorate-field/) +- [Establecer alineación de campo](/pdf/es/python-net/set-field-alignment/) +- [Establecer alineación vertical del campo](/pdf/es/python-net/set-field-alignment-vertical/) +- [Establecer apariencia del campo](/pdf/es/python-net/set-field-appearance/) +- [Establecer número de comb del campo](/pdf/es/python-net/set-field-comb-number/) +- [Establecer límite de campo](/pdf/es/python-net/set-field-limit/) +- [Obtener apariencia del campo](/pdf/es/python-net/get-field-appearance/) + diff --git a/es/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md b/es/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md new file mode 100644 index 000000000..7b01ebe65 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md @@ -0,0 +1,56 @@ +--- +title: Decorar Campo +linktitle: Decorar Campo +type: docs +weight: 10 +url: /es/python-net/decorate-field/ +description: Este ejemplo demuestra cómo personalizar la apariencia de un campo de formulario en un documento PDF usando Aspose.PDF para Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Decorar campos de formulario PDF con colores personalizados y alineación usando Python +Abstract: Este artículo explica cómo abrir un documento PDF, configurar opciones de estilo usando la clase FormFieldFacade, aplicar esas configuraciones a un campo de formulario y guardar el PDF actualizado. El ejemplo demuestra cómo decorar un campo llamado "First Name" con colores personalizados y alineación de texto centrada. +--- + +Los formularios PDF a menudo requieren personalización visual para mejorar la usabilidad y crear un diseño coherente. Con Aspose.PDF para Python, los desarrolladores pueden decorar programáticamente los campos de formulario estableciendo propiedades como colores, bordes y alineación de texto. + +Usando el [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) y [FormFieldFacade](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formfieldfacade/) clases que los desarrolladores pueden modificar fácilmente la apariencia de los campos de formulario para mejorar la legibilidad, resaltar los campos obligatorios o cumplir con los requisitos de marca. + +1. Abra un documento PDF existente. +1. Cree un objeto FormEditor para manipular los campos de formulario. +1. Defina el estilo visual usando FormFieldFacade. +1. Aplique el estilo a un campo de formulario específico. +1. Guarde el documento actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def decorate_field(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + form_editor.facade = pdf_facades.FormFieldFacade() + form_editor.facade.background_color = ap_pydrawing.Color.red + form_editor.facade.text_color = ap_pydrawing.Color.blue + form_editor.facade.border_color = ap_pydrawing.Color.green + form_editor.facade.alignment = pdf_facades.FormFieldFacade.ALIGN_CENTER + form_editor.decorate_field("First Name") + + # Save updated document + form_editor.save(outfile) +``` + diff --git a/es/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md b/es/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md new file mode 100644 index 000000000..d531639c8 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md @@ -0,0 +1,46 @@ +--- +title: Obtener apariencia del campo +linktitle: Obtener apariencia del campo +type: docs +weight: 20 +url: /es/python-net/get-field-appearance/ +description: Este artículo explica cómo abrir un PDF, acceder a un campo de formulario, obtener sus configuraciones de apariencia y mostrarlas. El ejemplo demuestra la obtención de la apariencia de un campo llamado "Last Name". +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Recuperar la apariencia del campo de formulario PDF usando Python +Abstract: Este ejemplo demuestra cómo recuperar las propiedades visuales de apariencia de un campo de formulario en un documento PDF usando Aspose.PDF for Python. El código abre un PDF existente, accede a un campo de formulario específico e imprime los detalles de su apariencia, incluyendo el color de fondo, el color del texto, el color del borde y la alineación. +--- + +Los campos de formulario en documentos PDF tienen propiedades visuales como el color de fondo, el color del texto, el color del borde y la alineación. Con Aspose.PDF for Python, los desarrolladores pueden inspeccionar programáticamente estas configuraciones de apariencia usando el [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) clase. + +1. Abra un documento PDF existente. +1. Cree un objeto FormEditor. +1. Recupere la información de apariencia de un campo específico. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def get_field_appearance(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Get field appearance + appearance = form_editor.get_field_appearance("Last Name") + print("Field Appearance: " + str(appearance)) +``` diff --git a/es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md b/es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md new file mode 100644 index 000000000..1cf9c7c10 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md @@ -0,0 +1,57 @@ +--- +title: Establecer alineación vertical del campo +linktitle: Establecer alineación vertical del campo +type: docs +weight: 40 +url: /es/python-net/set-field-alignment-vertical/ +description: Este ejemplo muestra cómo establecer la alineación vertical de un campo de formulario en un documento PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Establecer alineación vertical para campos de formulario PDF usando Python +Abstract: Este artículo explica cómo abrir un PDF, establecer la alineación vertical de un campo usando la clase FormEditor y guardar el PDF actualizado. El ejemplo establece la alineación vertical de un campo llamado "First Name" en la parte inferior del área del campo. +--- + +Los campos de formulario PDF pueden contener texto que necesita una alineación vertical adecuada para una apariencia coherente y profesional. Usando Aspose.PDF for Python, los desarrolladores pueden modificar programáticamente la alineación vertical de los campos de formulario. +La alineación vertical permite a los desarrolladores controlar si el texto del campo aparece en la parte superior, central o inferior del cuadro delimitador del campo, mejorando el diseño y la legibilidad de los datos del formulario. + +Usando el [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) clase y el [FormFieldFacade](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formfieldfacade/) constantes, los desarrolladores pueden ajustar la alineación vertical programáticamente para lograr un diseño de formulario coherente: + +1. Abra un documento PDF existente. +1. Cree un objeto FormEditor. +1. Establezca la alineación vertical de un campo llamado "First Name" en la parte inferior. +1. Guarde el documento modificado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_field_alignment_vertical(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Attempt to set vertical alignment of the "First Name" field to bottom + if form_editor.set_field_alignment_v( + "First Name", pdf_facades.FormFieldFacade.ALIGN_BOTTOM + ): + # Save updated document + form_editor.save(outfile) + else: + raise Exception( + "Failed to set field vertical alignment. Field may not support vertical alignment." + ) +``` diff --git a/es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md b/es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md new file mode 100644 index 000000000..30867748b --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md @@ -0,0 +1,56 @@ +--- +title: Establecer alineación de campo +linktitle: Establecer alineación de campo +type: docs +weight: 30 +url: /es/python-net/set-field-alignment/ +description: Este ejemplo muestra cómo establecer la alineación del texto de un campo de formulario en un documento PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Establecer alineación de texto para campos de formulario PDF usando Python +Abstract: Este artículo explica cómo abrir un documento PDF, establecer la alineación de un campo específico usando la clase FormEditor y guardar el PDF actualizado. El ejemplo establece la alineación del texto de un campo llamado "First Name" al centro. +--- + +Los campos de formulario PDF a menudo requieren una alineación de texto personalizada para mantener un diseño consistente y profesional. Usando Aspose.PDF for Python, los desarrolladores pueden establecer programáticamente la alineación del contenido de texto de un campo de formulario. + +El [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) clase, en combinación con el [FormFieldFacade](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formfieldfacade/) constantes, permite a los desarrolladores modificar la alineación de los campos de formulario existentes de forma programática. + +1. Abra un documento PDF existente. +1. Cree un objeto FormEditor. +1. Establece la alineación de un campo llamado "First Name" al centro. +1. Guarde el documento modificado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_field_alignment(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Set field alignment to center + if form_editor.set_field_alignment( + "First Name", pdf_facades.FormFieldFacade.ALIGN_CENTER + ): + # Save updated document + form_editor.save(outfile) + else: + raise Exception( + "Failed to set field alignment. Field may not support alignment." + ) +``` diff --git a/es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md b/es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md new file mode 100644 index 000000000..c2569a184 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md @@ -0,0 +1,56 @@ +--- +title: Establecer apariencia del campo +linktitle: Establecer apariencia del campo +type: docs +weight: 50 +url: /es/python-net/set-field-appearance/ +description: Este ejemplo demuestra cómo cambiar la apariencia visual de un campo de formulario PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Establecer apariencia del campo de formulario PDF usando Python +Abstract: Este artículo explica cómo abrir un PDF, establecer la apariencia de un campo de formulario usando la clase FormEditor, y guardar el documento actualizado. El ejemplo establece la apariencia de un campo llamado "First Name" como invisible usando la bandera AnnotationFlags.INVISIBLE. +--- + +Los campos de formulario PDF soportan banderas de apariencia que controlan la visibilidad, la imprimibilidad y la interactividad. Usando Aspose.PDF for Python, los desarrolladores pueden modificar programáticamente estas banderas para campos de formulario específicos. + +Usando el [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) clase, los desarrolladores pueden modificar estas banderas para ocultar, mostrar o personalizar el comportamiento de los campos de formulario en un PDF interactivo. + +1. Abra un documento PDF existente. +1. Cree un objeto FormEditor. +1. Establezca la apariencia del campo llamado "First Name" como invisible. +1. Guarde el documento actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_field_appearance(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Set field appearance to invisible + if not form_editor.set_field_appearance( + "First Name", ap.annotations.AnnotationFlags.INVISIBLE + ): + raise Exception( + "Failed to set field appearance. Field may not support appearance flags." + ) + + # Save updated document + form_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md b/es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md new file mode 100644 index 000000000..a613669a9 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md @@ -0,0 +1,51 @@ +--- +title: Establecer número de comb del campo +linktitle: Establecer número de comb del campo +type: docs +weight: 70 +url: /es/python-net/set-field-comb-number/ +description: Este ejemplo muestra cómo establecer un número de comb para un campo de formulario PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Establecer número de comb para campos de formulario PDF usando Python +Abstract: Con Aspose.PDF for Python, los desarrolladores pueden establecer programáticamente el número de casillas (número de comb) para un campo de formulario y forzar una entrada de longitud fija. Este artículo muestra cómo establecer el número de comb para un campo llamado "PIN". +--- + +El número de comb define cómo el contenido del campo se divide en casillas equidistantes, a menudo usado para códigos PIN, números de serie u otros campos de entrada de longitud fija. El código abre un PDF existente, establece el número de comb para un campo y guarda el documento modificado. + +El [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) La clase proporciona el método ‘set_field_comb_number’ para definir el número de casillas (caracteres) en un campo de formulario. + +1. Abra un formulario PDF existente. +1. Crea un objeto FormEditor. +1. Establece el número de comb de un campo llamado "PIN" a 5. +1. Guarde el documento actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_field_comb_number(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Set field comb number to 5 + form_editor.set_field_comb_number("PIN", 5) + + # Save updated document + form_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md b/es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md new file mode 100644 index 000000000..cad5f1a85 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md @@ -0,0 +1,54 @@ +--- +title: Establecer límite de campo +linktitle: Establecer límite de campo +type: docs +weight: 80 +url: /es/python-net/set-field-limit/ +description: Este ejemplo muestra cómo establecer un límite máximo de caracteres para un campo de formulario en un documento PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Establecer límite máximo de caracteres para campos de formulario PDF usando Python +Abstract: Este ejemplo demuestra cómo establecer el límite de caracteres para un campo llamado "Last Name" a 10 caracteres, asegurando que los usuarios no puedan ingresar más que el límite especificado. +--- + +Los campos de formulario en documentos PDF pueden requerir restricciones de entrada para mantener un formato adecuado. Usando Aspose.PDF for Python, los desarrolladores pueden programar la configuración de un número máximo de caracteres para un campo. + +El [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) La clase proporciona el método 'set_field_limit' para definir la longitud máxima de entrada para un campo. + +1. Abra un formulario PDF existente. +1. Cree un objeto FormEditor. +1. Establezca el límite máximo de caracteres para el campo "Last Name". +1. Guarde el PDF actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_field_limit(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Set field limit to 10 + if not form_editor.set_field_limit("Last Name", 10): + raise Exception( + "Failed to set field limit. Field may not support specified limit." + ) + + # Save updated document + form_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md b/es/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md new file mode 100644 index 000000000..85bab5678 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md @@ -0,0 +1,25 @@ +--- +title: Modificando campos de formulario +linktitle: Modificando campos de formulario +type: docs +weight: 20 +url: /es/python-net/modifying-form-fields/ +description: Usando Aspose.PDF for Python, puedes modificar campos de formulario de manera eficiente mediante programación con la clase FormEditor. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 'Modificar campos de formulario PDF en Python: agregar, mover, copiar, renombrar y eliminar campos' +Abstract: Aprende cómo modificar los campos de formulario PDF existentes usando Aspose.PDF for Python. Esta guía explica cómo gestionar los elementos del formulario añadiendo o eliminando elementos de lista, moviendo campos, eliminándolos o renombrándolos, convirtiendo campos de una sola línea en multilinea, y copiando campos dentro de documentos o entre ellos. Estas técnicas ayudan a los desarrolladores a actualizar dinámicamente los formularios PDF y adaptarlos a requisitos empresariales cambiantes sin recrear toda la estructura del formulario. +--- + +- [Agregar elemento a la lista](/pdf/es/python-net/add-list-item/) +- [Eliminar elemento de la lista](/pdf/es/python-net/del-list-item/) +- [Mover campo](/pdf/es/python-net/move-field/) +- [Eliminar campo](/pdf/es/python-net/remove-field/) +- [Renombrar campo](/pdf/es/python-net/rename-field/) +- [De único a múltiple](/pdf/es/python-net/single-to-multiple/) +- [Copiar campo interno](/pdf/es/python-net/copy-inner-field/) +- [Copiar campo externo](/pdf/es/python-net/copy-outer-field/) + diff --git a/es/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md b/es/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md new file mode 100644 index 000000000..a13ba9ebd --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md @@ -0,0 +1,46 @@ +--- +title: Agregar elemento a la lista +linktitle: Agregar elemento a la lista +type: docs +weight: 10 +url: /es/python-net/add-list-item/ +description: Este ejemplo muestra cómo agregar elementos a un campo de formulario de cuadro de lista en un documento PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar elementos a los campos de cuadro de lista PDF usando Python +Abstract: Este artículo muestra cómo abrir un documento PDF, añadir elementos a un campo de cuadro de lista llamado "Country", y guardar el documento actualizado. +--- + +Los campos de cuadro de lista en los PDF permiten a los usuarios seleccionar una o varias opciones de un conjunto predefinido. Usando Aspose.PDF for Python, los desarrolladores pueden agregar programáticamente nuevos elementos a estos campos. El [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) la clase proporciona el método ‘add_list_item’ para añadir elementos a un campo de cuadro de lista existente. + +1. Abra un formulario PDF existente. +1. Cree un objeto FormEditor. +1. Vincular el PDF al FormEditor. +1. Agregar elementos al campo de lista "Country". +1. Guarde el documento actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_list_item(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Add list item to list box field + form_editor.add_list_item("Country", ["New Zealand", "New Zealand"]) + # Save updated document + form_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md b/es/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md new file mode 100644 index 000000000..2cee43383 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md @@ -0,0 +1,72 @@ +--- +title: Copiar campo interno +linktitle: Copiar campo interno +type: docs +weight: 20 +url: /es/python-net/copy-inner-field/ +description: Copiar campos de formulario PDF a una nueva posición usando Python con Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Copiar campos de formulario PDF a una nueva posición usando Python +Abstract: Este ejemplo demuestra cómo copiar un campo de formulario existente a una nueva posición en un documento PDF usando Aspose.PDF for Python. El código abre un PDF, duplica un campo a una página y coordenadas especificadas, y guarda el documento actualizado. +--- + +Los formularios PDF a menudo requieren duplicar campos mientras se mantiene el formato y comportamiento original. Usando Aspose.PDF for Python, los desarrolladores pueden copiar un campo existente a una nueva posición en la misma u otra página de forma programática. + +Este artículo explica cómo copiar un campo llamado ‘First Name’ a un nuevo campo llamado ‘First Name Copy’ en la página 2 en coordenadas específicas (x=200, y=600), generando un PDF con el campo recién posicionado. + +1. Abra un formulario PDF existente. +1. Cree un objeto FormEditor. +1. Vincula el documento PDF al FormEditor. +1. Copia el campo ‘First Name’ a un nuevo campo ‘First Name Copy’ en la página 2 en las coordenadas (200, 600). +1. Guarde el documento actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def copy_inner_field(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Copies an existing field to a new position specified by both page number and ordinates. + # A new document will be produced, which contains everything the source document has except for the newly copied field. + form_editor.copy_inner_field("First Name", "First Name Copy", 2, 200, 600) + # Save updated document + form_editor.save(outfile) +``` + +**Tenga en cuenta:** + +La firma del método 'copy_inner_field' se ve así: + +```python +copy_inner_field(original_field_name, new_field_name, page_number, x, y) +``` + +- 'original_field_name' – el campo que desea duplicar. +- 'new_field_name' – el nombre del nuevo campo. +- 'page_number' – la página en la que aparecerá el nuevo campo. +- x, y – coordenadas en esa página. + +Se espera que page_number sea un entero positivo que corresponda a una página existente en el PDF (indexación basada en 1). + +Si pasa un parámetro negativo, p. ej.: + +```python +form_editor.copy_inner_field("First Name", "First Name Copy", -1, 200, 600) +``` + +El programa entonces restablecerá los parámetros anteriores. diff --git a/es/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md b/es/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md new file mode 100644 index 000000000..026b7edd7 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md @@ -0,0 +1,80 @@ +--- +title: Copiar campo externo +linktitle: Copiar campo externo +type: docs +weight: 30 +url: /es/python-net/copy-outer-field/ +description: Este ejemplo muestra cómo copiar un campo de formulario de un documento PDF a otro usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Copiar campos de formulario PDF de otro documento usando Python +Abstract: Este artículo explica cómo crear un nuevo documento PDF, copiar el campo "First Name" de un PDF de origen a la página 1 en las coordenadas (200, 600), y guardar el documento de destino actualizado. +--- + +A veces, los formularios PDF requieren reutilizar campos de un documento en otro. Usando Aspose.PDF for Python, los desarrolladores pueden copiar programáticamente los campos de formulario de un PDF de origen a un PDF de destino. + +El [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) la clase proporciona el método 'copy_outer_field', que copia un campo de un documento de origen a un documento de destino en una página y coordenadas especificadas. + +El código crea un nuevo PDF (destino), agrega una página y luego copia un campo de un PDF existente (origen) al documento de destino en coordenadas especificadas. + +1. Crear un nuevo documento PDF de destino. +1. Agregue al menos una página al PDF de destino. +1. Guarde el documento de destino vacío. +1. Cree un objeto FormEditor y vincúlelo al PDF de destino. +1. Copie el campo 'First Name' del PDF fuente a la página 1 en (200, 600). +1. Guardar el PDF de destino actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def copy_outer_field(infile, outfile): + # Since copy_outer_field() method needs to copy field from source document to target document, we need to create a new document as target document first. + doc = ap.Document() + doc.pages.add() + doc.save(outfile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(outfile) + # Copies an existing field to a new position specified by both page number and ordinates. + # A new document will be produced, which contains everything the source document has except for the newly copied field. + form_editor.copy_outer_field(infile, "First Name", 1, 200, 600) + # Save updated document + form_editor.save(outfile) +``` + +**Tenga en cuenta:** + +La firma del método 'copy_outer_field' se ve así: + +```python +copy_outer_field(original_field_name, new_field_name, page_number, x, y) +``` + +- 'original_field_name' – el campo que desea duplicar. +- 'new_field_name' – el nombre del nuevo campo. +- 'page_number' – la página en la que aparecerá el nuevo campo. +- x, y – coordenadas en esa página. + +Se espera que page_number sea un entero positivo que corresponda a una página existente en el PDF (indexación basada en 1). + +Si pasa un parámetro negativo, p. ej.: + +```python +form_editor.copy_outer_field("First Name", "First Name Copy", 1, -200, 600) +``` + +El programa entonces restablecerá los parámetros anteriores. diff --git a/es/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md b/es/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md new file mode 100644 index 000000000..eb7764cb4 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md @@ -0,0 +1,51 @@ +--- +title: Eliminar elemento de la lista +linktitle: Eliminar elemento de la lista +type: docs +weight: 40 +url: /es/python-net/del-list-item/ +description: +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Eliminar elementos de los campos de cuadro de lista PDF usando Python +Abstract: Este ejemplo muestra cómo eliminar un elemento de un campo de formulario de cuadro de lista en un documento PDF usando Aspose.PDF for Python. El código abre un PDF existente, elimina un elemento específico de un campo de cuadro de lista y guarda el documento actualizado. +--- + +Los campos de cuadro de lista en los PDF permiten a los usuarios seleccionar una o varias opciones predefinidas. Usando Aspose.PDF for Python, los desarrolladores pueden eliminar programáticamente elementos de estos campos. + +Este artículo explica cómo eliminar el elemento 'UK' de un campo de cuadro de lista llamado 'Country', asegurando que el campo solo contenga las opciones deseadas. + +El [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) La clase proporciona el método 'del_list_item' para eliminar un elemento específico de un campo de cuadro de lista. + +1. Abra un formulario PDF existente. +1. Cree un objeto FormEditor. +1. Vincula el documento PDF al FormEditor. +1. Eliminar el elemento "UK" del campo de lista "Country". +1. Guarde el documento actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def del_list_item(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Delete list item from list box field + form_editor.del_list_item("Country", "UK") + # Save updated document + form_editor.save(outfile) +``` + diff --git a/es/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md b/es/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md new file mode 100644 index 000000000..b6b07d3be --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md @@ -0,0 +1,48 @@ +--- +title: Mover campo +linktitle: Mover campo +type: docs +weight: 50 +url: /es/python-net/move-field/ +description: Mover un campo de formulario existente a una posición diferente en un documento PDF. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Mover un campo de formulario PDF a una nueva posición usando Python +Abstract: Este ejemplo demuestra cómo mover un campo de formulario existente a una posición diferente en un documento PDF usando Aspose.PDF for Python. El código abre un PDF existente, reubica el campo de formulario especificado a nuevas coordenadas y guarda el documento actualizado. +--- + +Los formularios PDF a menudo requieren ajustes de diseño después de su creación. Usando Aspose.PDF for Python, los desarrolladores pueden mover campos de formulario existentes a una nueva posición sin recrearlos. + +Este ejemplo muestra cómo reposicionar el campo "Country" especificando nuevas coordenadas para su ubicación dentro de la página. El [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) La clase proporciona el método move_field para reubicar campos dentro de una página PDF. + +1. Abra el formulario PDF existente. +1. Cree un objeto FormEditor. +1. Vincula el documento PDF al FormEditor. +1. Mueva el campo 'Country' a una nueva posición usando coordenadas. +1. Guarde el documento modificado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def move_field(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Move field to new page + form_editor.move_field("Country", 200, 600, 280, 620) + # Save updated document + form_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md b/es/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md new file mode 100644 index 000000000..847006e37 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md @@ -0,0 +1,48 @@ +--- +title: Eliminar campo +linktitle: Eliminar campo +type: docs +weight: 60 +url: /es/python-net/remove-field/ +description: Este ejemplo muestra cómo eliminar el campo ‘Country’ de un formulario PDF usando el método ‘remove_field’ de la clase ‘FormEditor’. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Eliminar un campo de formulario de un documento PDF usando Python +Abstract: Este ejemplo demuestra cómo eliminar un campo de formulario existente de un documento PDF usando Aspose.PDF for Python. El código carga un archivo PDF, elimina el campo especificado usando la clase FormEditor y guarda el documento actualizado. +--- + +Los formularios PDF pueden contener campos que ya no son necesarios debido a cambios de diseño o actualizaciones del flujo de trabajo. Con Aspose.PDF for Python, los desarrolladores pueden eliminar fácilmente campos de formulario específicos de forma programática. + +El [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) La clase en Aspose.PDF proporciona el método ‘remove_field’, que permite a los desarrolladores eliminar un campo de formulario por su nombre. + +1. Cargar el documento PDF. +1. Cree un objeto FormEditor. +1. Vincular el PDF al FormEditor. +1. Eliminar el campo de formulario especificado. +1. Guarde el documento actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def remove_field(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Remove field from document + form_editor.remove_field("Country") + # Save updated document + form_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md b/es/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md new file mode 100644 index 000000000..c5bddb3f5 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md @@ -0,0 +1,49 @@ +--- +title: Renombrar campo +linktitle: Renombrar campo +type: docs +weight: 70 +url: /es/python-net/rename-field/ +description: Renombrar un campo de formulario existente en un documento PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Renombrar un campo de formulario PDF usando Python +Abstract: Este ejemplo muestra cómo renombrar un campo de formulario existente en un documento PDF usando Aspose.PDF for Python. El código abre un PDF de entrada, cambia el nombre de un campo de formulario especificado utilizando la clase FormEditor y guarda el documento actualizado. +--- + +Los formularios PDF a menudo dependen de los nombres de los campos para scripting, automatización y procesamiento de datos. Usando Aspose.PDF for Python, los desarrolladores pueden renombrar campos existentes sin recrearlos ni alterar el diseño del formulario. + +El [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) La clase proporciona el método 'rename_field', que permite a los desarrolladores cambiar el nombre de un campo existente mientras se preservan su posición, valor y apariencia. + +1. Cargar el formulario PDF existente. +1. Crear una instancia de FormEditor. +1. Vincular el documento PDF al editor. +1. Renombrar el campo objetivo. +1. Guarde el PDF actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def rename_field(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Rename field in document + form_editor.rename_field("City", "Town") + # Save updated document + form_editor.save(outfile) +``` + diff --git a/es/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md b/es/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md new file mode 100644 index 000000000..418f01ec3 --- /dev/null +++ b/es/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md @@ -0,0 +1,49 @@ +--- +title: Campo de una sola línea a campo de varias líneas +linktitle: Campo de una sola línea a campo de varias líneas +type: docs +weight: 80 +url: /es/python-net/single-to-multiple/ +description: Convierta un campo de texto de una sola línea en un campo de varias líneas en un documento PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Convierta un Campo de Texto de una Sola Línea a un Campo de Varias Líneas en un PDF usando Python +Abstract: Este ejemplo muestra cómo convertir un campo de texto de una sola línea en un campo de varias líneas en un documento PDF usando Aspose.PDF for Python. El código carga un formulario PDF existente, modifica el campo especificado para permitir múltiples líneas de texto y guarda el documento actualizado. +--- + +Los formularios PDF a veces contienen campos de texto diseñados para entrada de una sola línea, lo que puede no ser suficiente para ciertos tipos de datos. Con Aspose.PDF for Python, los desarrolladores pueden convertir fácilmente dichos campos en campos de texto de varias líneas sin recrearlos. + +Usando el [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) class, los desarrolladores pueden modificar los campos de texto existentes sin afectar su posición u otras propiedades. + +1. Cargue el documento PDF existente. +1. Crear una instancia de FormEditor. +1. Vincular el documento PDF al editor. +1. Convierta el campo seleccionado a varias líneas. +1. Guarde el documento actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def single2multiple(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Change a single-lined text field to a multiple-lined one + form_editor.single_2_multiple("City") + # Save updated document + form_editor.save(outfile) +``` + diff --git a/es/python-net/working-with-facades/pdfannotationeditor/_index.md b/es/python-net/working-with-facades/pdfannotationeditor/_index.md new file mode 100644 index 000000000..03a7ed26b --- /dev/null +++ b/es/python-net/working-with-facades/pdfannotationeditor/_index.md @@ -0,0 +1,22 @@ +--- +title: Clase PdfAnnotationEditor +linktitle: Clase PdfAnnotationEditor +type: docs +weight: 40 +url: /es/python-net/pdfannotationeditor-class/ +description: Aprenda cómo usar la clase PdfAnnotationEditor en Aspose.PDF for Python via .NET para trabajar con anotaciones PDF, comentarios y marcado de forma programática. +lastmod: "2026-02-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Edite anotaciones y comentarios PDF en Python con PdfAnnotationEditor +Abstract: Esta sección presenta la clase PdfAnnotationEditor en Aspose.PDF for Python via .NET para flujos de trabajo PDF relacionados con anotaciones. Utilice esta fachada para gestionar anotaciones PDF, comentarios y marcado de forma programática mientras trabaja con documentos existentes en aplicaciones Python. +--- + +El `PdfAnnotationEditor` La clase en Aspose.PDF Facades está destinada a trabajar con anotaciones PDF y marcado basado en comentarios sin editar manualmente la estructura de bajo nivel de un documento. Proporciona una forma simplificada de manejar flujos de trabajo de anotaciones en Python via .NET cuando necesitas inspeccionar o actualizar archivos PDF existentes. + +## Para qué se usa PdfAnnotationEditor + +Utilice esta fachada cuando su flujo de trabajo PDF incluya anotaciones, comentarios de revisión u otros elementos de marcado que necesiten ser gestionados programáticamente. A medida que esta sección se expanda, debería servir como página de inicio para tutoriales relacionados con anotaciones construidos alrededor del `PdfAnnotationEditor` clase. + diff --git a/es/python-net/working-with-facades/pdfcontenteditor/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/_index.md new file mode 100644 index 000000000..2c11fcfce --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/_index.md @@ -0,0 +1,32 @@ +--- +title: Clase PdfContentEditor +linktitle: Clase PdfContentEditor +type: docs +weight: 30 +url: /es/python-net/pdfcontenteditor-class/ +description: Aprenda cómo usar la clase PdfContentEditor en Aspose.PDF for Python via .NET para editar contenido PDF, gestionar anotaciones y adjuntos, trabajar con enlaces, imágenes, texto, multimedia, sellos y preferencias del visor. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Edite contenido PDF y elementos interactivos en Python con PdfContentEditor +Abstract: Esta sección explica cómo usar la clase PdfContentEditor en Aspose.PDF for Python via .NET para flujos de trabajo a nivel de contenido PDF. Aprenda cómo gestionar anotaciones, adjuntos, acciones de documento, marcas de dibujo, imágenes, enlaces, multimedia, sellos, reemplazo de texto y preferencias del visor de forma programática. +--- + +El `PdfContentEditor` La clase en Aspose.PDF Facades está diseñada para tareas de edición a nivel de contenido en documentos PDF existentes. Proporciona una API simplificada para actualizar elementos interactivos, reemplazar texto, trabajar con adjuntos y enlaces, y ajustar el comportamiento del documento en aplicaciones Python vía .NET. + +## Qué puede hacer con PdfContentEditor + +Utilice esta sección para explorar las principales áreas de edición de contenido PDF compatibles con el `PdfContentEditor` fachada: + +- [Trabaje con anotaciones usando PdfContentEditor](/pdf/es/python-net/annotations/) +- [Administre los adjuntos PDF con PdfContentEditor](/pdf/es/python-net/attachments/) +- [Configure acciones de documento con PdfContentEditor](/pdf/es/python-net/document-actions/) +- [Agregue anotaciones de dibujo con PdfContentEditor](/pdf/es/python-net/drawing-annotations/) +- [Realice operaciones de imagen con PdfContentEditor](/pdf/es/python-net/image-operations/) +- [Manipular enlaces y navegación con PdfContentEditor](/pdf/es/python-net/links-and-navigation/) +- [Agregar o administrar contenido multimedia con PdfContentEditor](/pdf/es/python-net/multimedia/) +- [Administrar sellos PDF con PdfContentEditor](/pdf/es/python-net/stamps-management/) +- [Reemplazar y actualizar texto con PdfContentEditor](/pdf/es/python-net/text-operations/) +- [Cambiar preferencias del visor con PdfContentEditor](/pdf/es/python-net/viewer-preferences/) diff --git a/es/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md new file mode 100644 index 000000000..9796861ae --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md @@ -0,0 +1,18 @@ +--- +title: Anotaciones +linktitle: Anotaciones +type: docs +weight: 10 +url: /es/python-net/annotations/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +- [Agregar anotaciones de texto](/pdf/es/python-net/add-text-annotation/) +- [Agregar anotaciones de texto libre](/pdf/es/python-net/add-free-text-annotation/) +- [Agregar anotaciones de marcado](/pdf/es/python-net/add-markup-annotation/) +- [Agregar anotaciones emergentes](/pdf/es/python-net/add-popup-annotation/) +- [Agregar anotación de caret](/pdf/es/python-net/add-caret-annotation/) diff --git a/es/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md new file mode 100644 index 000000000..da308fd97 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md @@ -0,0 +1,59 @@ +--- +title: Agregar anotación de caret +linktitle: Agregar anotación de caret +type: docs +weight: 10 +url: /es/python-net/add-caret-annotation/ +description: Este ejemplo carga un PDF existente, agrega una anotación de caret a la primera página y guarda el documento modificado. La anotación incluye un símbolo de caret rojo y texto de comentario descriptivo. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar anotación de caret a un PDF usando Python +Abstract: Este ejemplo muestra cómo agregar una anotación de caret a un documento PDF usando Aspose.PDF for Python via the Facades API. El ejemplo muestra cómo enlazar un archivo PDF, definir la ubicación de la anotación usando rectángulos, configurar las propiedades del caret y guardar el documento actualizado. +--- + +Las anotaciones de caret se utilizan comúnmente para indicar inserciones de texto o comentarios editoriales en un documento. Con PdfContentEditor, puedes agregar anotaciones de caret de forma programática especificando el número de página, los límites de la anotación, el área de llamada, el símbolo, el texto de la nota y el color. + +1. Crear el [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) objeto. +1. Vincular el PDF de entrada. +1. Definir los parámetros de la anotación Caret: + - Número de página donde se añadirá la anotación + - Caret rectangle (posición de la anotación) + - Rectángulo de llamada (área de texto) + - Símbolo (por ejemplo "P") + - Texto de anotación + - Color de anotación +1. Agregar la anotación de cursor. +1. Guardar el documento actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_caret_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add caret annotation to page 1 + content_editor.create_caret( + 1, + apd.Rectangle(350, 400, 10, 10), + apd.Rectangle(300, 380, 115, 15), + "P", + "This is a caret annotation", + apd.Color.red, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md new file mode 100644 index 000000000..2cd6c817a --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md @@ -0,0 +1,48 @@ +--- +title: Agregar anotaciones de texto libre +linktitle: Agregar anotaciones de texto libre +type: docs +weight: 20 +url: /es/python-net/add-free-text-annotation/ +description: Este ejemplo carga un archivo PDF existente, agrega una anotación de texto libre a la primera página en una posición definida y guarda el documento modificado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar anotación de texto libre a un PDF usando Python +Abstract: Este ejemplo demuestra cómo insertar una anotación de texto libre en un documento PDF usando Aspose.PDF para Python a través de la API Facades. Muestra cómo vincular un PDF, definir la ubicación de la anotación, agregar texto personalizado y guardar el documento actualizado. +--- + +Las anotaciones de texto libre le permiten colocar texto visible directamente en una página PDF sin requerir comentarios emergentes. Usando PdfContentEditor, puede especificar el rectángulo de la anotación, el texto mostrado y la página objetivo. + +1. Crear el [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) objeto. +1. Vincular el PDF de entrada. +1. Defina la posición de la anotación. +1. Agregar la anotación de texto libre. +1. Guardar el documento actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_free_text_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add free text annotation to page 1 + content_editor.create_free_text( + apd.Rectangle(200, 480, 150, 25), "This is a free text annotation", 1 + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md new file mode 100644 index 000000000..bbf860b73 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md @@ -0,0 +1,73 @@ +--- +title: Agregar anotaciones de marcado +linktitle: Agregar anotaciones de marcado +type: docs +weight: 30 +url: /es/python-net/add-markup-annotation/ +description: Este ejemplo enlaza un PDF de entrada, agrega cuatro anotaciones de marcado diferentes a la primera página y guarda el documento actualizado. Cada anotación muestra un estilo y color de marcado diferentes. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar anotaciones de marcado de resaltado, subrayado, tachado y ondulado en un PDF usando Python +Abstract: Este ejemplo muestra cómo agregar múltiples anotaciones de marcado—resaltado, subrayado, tachado y ondulado—a un documento PDF usando Aspose.PDF for Python via the Facades API. El ejemplo muestra cómo definir áreas de anotación, especificar tipos de marcado, aplicar colores y guardar el documento modificado. +--- + +Las anotaciones de marcado se utilizan para enfatizar o revisar texto dentro de un PDF. Con PdfContentEditor, puedes aplicar programáticamente diferentes estilos de marcado especificando un área rectangular, texto de comentario, tipo de marcado, número de página y color. + +1. Crear el [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) objeto. +1. Vincular el PDF de entrada. +1. Definir rectángulos de anotación. +1. Agregar anotaciones de marcado. +1. Guardar el documento actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_markup_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add markup annotation to page 1 + content_editor.create_markup( + apd.Rectangle(120, 440, 200, 20), + "This is a highlight annotation", + 0, + 1, + apd.Color.yellow, + ) + content_editor.create_markup( + apd.Rectangle(110, 542, 200, 20), + "This is a underline annotation", + 1, + 1, + apd.Color.yellow, + ) + content_editor.create_markup( + apd.Rectangle(120, 568, 200, 20), + "This is a strikeout annotation", + 2, + 1, + apd.Color.orange_red, + ) + content_editor.create_markup( + apd.Rectangle(110, 598, 200, 20), + "This is a squiggly annotation", + 3, + 1, + apd.Color.dark_blue, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md new file mode 100644 index 000000000..7d8dc9a7b --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md @@ -0,0 +1,51 @@ +--- +title: Agregar anotaciones emergentes +linktitle: Agregar anotaciones emergentes +type: docs +weight: 40 +url: /es/python-net/add-popup-annotation/ +description: Este ejemplo carga un PDF, agrega una anotación emergente a la primera página y guarda el documento modificado. La anotación emergente está configurada para ser visible de forma predeterminada y muestra el texto de comentario especificado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar anotaciones emergentes a un PDF usando Python +Abstract: Este ejemplo muestra cómo insertar una anotación emergente en un documento PDF usando Aspose.PDF for Python via the Facades API. Explica cómo definir el área de la anotación emergente, establecer el texto de la anotación, controlar la visibilidad y guardar el documento actualizado. +--- + +Las anotaciones emergentes son útiles para agregar comentarios, explicaciones o notas interactivas en archivos PDF. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puedes crear anotaciones emergentes programáticamente especificando la ubicación, el contenido, la visibilidad y el número de página. + +1. Crea el objeto PdfContentEditor. +1. Vincular el PDF de entrada. +1. Define el rectángulo de la anotación Popup. +1. Añade la anotación Popup. +1. Guardar el documento actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_popup_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add popup annotation to page 1 + content_editor.create_popup( + apd.Rectangle(220, 520, 180, 80), + "This is a popup annotation", + True, + 1, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/annotations/add-text-annotation/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/annotations/add-text-annotation/_index.md new file mode 100644 index 000000000..735d48770 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/annotations/add-text-annotation/_index.md @@ -0,0 +1,62 @@ +--- +title: Agregar anotaciones de texto +linktitle: Agregar anotaciones de texto +type: docs +weight: 50 +url: /es/python-net/add-text-annotation/ +description: Agregar anotaciones de texto a un documento PDF utilizando la clase PdfContentEditor en Aspose.PDF for Python via .NET. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar anotaciones de texto en Python +Abstract: Aprenda cómo agregar anotaciones de texto a un documento PDF utilizando la clase PdfContentEditor en Aspose.PDF for Python via .NET. Este ejemplo muestra cómo colocar una anotación de texto en una posición específica, definir su título y contenidos, y guardar el archivo PDF actualizado. +--- + +Este artículo muestra cómo agregar una anotación de texto a un documento PDF utilizando la [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) clase en Aspose.PDF. + +Las anotaciones de texto le permiten adjuntar comentarios, notas o información adicional a partes específicas de una página PDF. Estas anotaciones pueden aparecer como íconos y ser ampliadas por los usuarios al ver el documento. + +En este ejemplo: + +- Se carga un documento PDF en el PdfContentEditor. +- Se agrega una anotación de texto en una posición específica de la página. +- La anotación incluye un título, contenido, tipo de ícono y configuraciones de visibilidad. +- El documento modificado se guarda en un nuevo archivo. + +1. Crear un objeto PdfContentEditor. +1. Vincular el documento PDF de entrada. +1. Definir la posición de la anotación. +1. Agregar anotación de texto. +1. Guardar el PDF actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_text_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add text annotation to page 1 + content_editor.create_text( + apd.Rectangle(100, 400, 50, 50), + "Text Annotation", + "This is a text annotation", + True, + "Insert", + 1, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md new file mode 100644 index 000000000..57af42004 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md @@ -0,0 +1,18 @@ +--- +title: Adjuntos +linktitle: Adjuntos +type: docs +weight: 20 +url: /es/python-net/attachments/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +- [Agregar archivo adjunto](/pdf/es/python-net/add-attachment/) +- [Agregar adjunto desde la ruta](/pdf/es/python-net/add-attachment-from-path/) +- [Agregar anotación de archivo adjunto](/pdf/es/python-net/add-file-attachment-annotation/) +- [Agregar anotación de adjunto de archivo desde flujo](/pdf/es/python-net/add-file-attachment-annotation-from-stream/) +- [Eliminar archivos adjuntos](/pdf/es/python-net/remove-attachments/) diff --git a/es/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment-from-path/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment-from-path/_index.md new file mode 100644 index 000000000..a9301999e --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment-from-path/_index.md @@ -0,0 +1,48 @@ +--- +title: Agregar adjunto desde la ruta +linktitle: Agregar adjunto desde la ruta +type: docs +weight: 20 +url: /es/python-net/add-attachment-from-path/ +description: Este ejemplo vincula un PDF de entrada, adjunta un archivo externo usando su ruta de archivo y guarda el PDF modificado con el adjunto incorporado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Adjuntar archivos a un PDF usando sobrecarga de ruta de archivo en Python +Abstract: Este ejemplo muestra cómo adjuntar archivos externos a un documento PDF usando la sobrecarga de ruta de archivo de \u0027add_document_attachment()\u0027 en Aspose.PDF for Python a través de la API Facades. Simplifica la adición de adjuntos sin abrir manualmente un flujo de archivo. +--- + +El PDF puede incluir archivos incrustados como documentos, hojas de cálculo o imágenes para referencia o distribución. La sobrecarga de ruta de archivo de \u0027add_document_attachment()\u0027 le permite agregar adjuntos directamente desde una ruta de archivo, eliminando la necesidad de abrir el archivo manualmente. + +1. Crear el [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) objeto. +1. Vincular el PDF de entrada. +1. Agregar el adjunto usando la ruta de archivo. +1. Guardar el documento actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_attachment_from_path(infile, attachment_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add attachment using file-path overload + content_editor.add_document_attachment( + attachment_file, + "Attachment added using file path overload.", + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment/_index.md new file mode 100644 index 000000000..2c9622793 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment/_index.md @@ -0,0 +1,51 @@ +--- +title: Agregar archivo adjunto +linktitle: Agregar archivo adjunto +type: docs +weight: 10 +url: /es/python-net/add-attachment/ +description: Este ejemplo enlaza un PDF de entrada, adjunta un archivo externo a la primera página y guarda el PDF modificado con el archivo adjunto incrustado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar archivos adjuntos a un PDF usando Python +Abstract: Este ejemplo muestra cómo adjuntar archivos externos a un documento PDF usando Aspose.PDF for Python a través de la API Facades. Demuestra cómo enlazar un PDF, agregar archivos adjuntos con descripciones y guardar el documento actualizado. +--- + +Los archivos adjuntos en PDFs le permiten incluir documentos suplementarios, imágenes u otros recursos directamente dentro del PDF. Con [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puede adjuntar archivos a páginas específicas de forma programática, establecer el nombre del adjunto y proporcionar una descripción. + +1. Crea el objeto PdfContentEditor. +1. Vincular el PDF de entrada. +1. Abra el archivo de adjunto. +1. Agregue el adjunto al PDF. +1. Guardar el documento actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_attachment(infile, attachment_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add attachment to page 1 + with open(attachment_file, "rb") as attachment_stream: + content_editor.add_document_attachment( + attachment_stream, + path.basename(attachment_file), + "This is a sample attachment for demonstration purposes.", + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md new file mode 100644 index 000000000..e60816718 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md @@ -0,0 +1,52 @@ +--- +title: Agregar anotación de archivo adjunto +linktitle: Agregar anotación de archivo adjunto +type: docs +weight: 30 +url: /es/python-net/add-file-attachment-annotation/ +description: El ejemplo asocia un PDF de entrada, agrega una anotación de archivo adjunto a la primera página usando la ruta del archivo y guarda el documento actualizado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar anotaciones de archivo adjunto a un PDF usando Python +Abstract: Este ejemplo muestra cómo crear una anotación de archivo adjunto en un PDF usando una ruta de archivo con Aspose.PDF for Python via the Facades API. Muestra cómo definir la ubicación de la anotación, establecer el texto de descripción, elegir un tipo de ícono y guardar el documento modificado. +--- + +Las anotaciones de archivo adjunto le permiten incrustar archivos externos como íconos interactivos en una página PDF. Usando la sobrecarga de ruta de archivo, puede adjuntar archivos directamente desde el disco sin abrir manualmente los flujos. Este método también le permite personalizar el ícono de la anotación y proporcionar una descripción para los usuarios. + +1. Crear el [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) objeto. +1. Vincular el PDF de entrada. +1. Defina el rectángulo de la anotación. +1. Agregar la anotación de adjunto de archivo. +1. Guardar el documento actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_file_attachment_annotation(infile, attachment_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Create file attachment annotation on page 1 + content_editor.create_file_attachment( + apd.Rectangle(100, 520, 20, 20), + "Attachment annotation contents", + attachment_file, + 1, + "PushPin", + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md new file mode 100644 index 000000000..298084ff3 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md @@ -0,0 +1,58 @@ +--- +title: Agregar anotación de archivo adjunto desde flujo +linktitle: Agregar anotación de archivo adjunto desde flujo +type: docs +weight: 40 +url: /es/python-net/add-file-attachment-annotation-from-stream/ +description: El ejemplo carga un PDF, lee un archivo externo en un flujo de memoria, agrega una anotación de archivo adjunto a la primera página y guarda el documento modificado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar anotaciones de archivo adjunto a un PDF desde un flujo en Python +Abstract: Este ejemplo demuestra cómo crear una anotación de archivo adjunto en un PDF usando un flujo de archivo con Aspose.PDF for Python via the Facades API. Muestra cómo especificar la posición de la anotación, establecer una descripción, incluir un valor de opacidad y guardar el documento modificado. +--- + +Las anotaciones de archivo adjunto permiten incrustar archivos como iconos interactivos dentro de una página PDF. Usando un enfoque basado en flujos, puedes adjuntar archivos dinámicamente sin depender de una ruta de archivo física. Este método también admite la personalización de la apariencia de la anotación, incluida la opacidad. + +1. Crear el objeto PdfContentEditor. +1. Vincular el PDF de entrada. +1. Leer el archivo adjunto como un flujo. +1. Agregar la anotación de archivo adjunto. +1. Guarda el Documento actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_file_attachment_annotation_from_stream(infile, attachment_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + with open(attachment_file, "rb") as source_stream: + attachment_stream = BytesIO(source_stream.read()) + + # Create file attachment annotation using stream+opacity overload + content_editor.create_file_attachment( + apd.Rectangle(130, 520, 20, 20), + "Attachment annotation from stream", + attachment_stream, + path.basename(attachment_file), + 1, + "Tag", + 0.75, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md new file mode 100644 index 000000000..1ab32d771 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md @@ -0,0 +1,45 @@ +--- +title: Eliminar archivos adjuntos +linktitle: Eliminar archivos adjuntos +type: docs +weight: 50 +url: /es/python-net/remove-attachments/ +description: Este ejemplo vincula un PDF de entrada, elimina todos los archivos adjuntos y guarda el PDF modificado sin ningún archivo incrustado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Eliminar todos los archivos adjuntos de un PDF usando Python +Abstract: Este ejemplo demuestra cómo eliminar todos los archivos adjuntos de un documento PDF usando Aspose.PDF for Python via the Facades API. Muestra cómo vincular un PDF, eliminar los adjuntos incrustados y guardar el documento actualizado. +--- + +Los PDFs pueden contener adjuntos como documentos, imágenes u otros archivos. Hay escenarios en los que necesita limpiar un PDF de todos los adjuntos por motivos de seguridad, privacidad o distribución. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puede eliminar programáticamente todos los adjuntos incrustados en un documento. + +1. Crea el objeto PdfContentEditor. +1. Vincular el PDF de entrada. +1. Eliminar todos los adjuntos. +1. Guardar el documento actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def remove_attachments(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Remove all attachments from document + content_editor.delete_attachments() + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md new file mode 100644 index 000000000..3ac484703 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md @@ -0,0 +1,16 @@ +--- +title: Acciones del documento +linktitle: Acciones del documento +type: docs +weight: 40 +url: /es/python-net/document-actions/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +- [Agregar acción de marcador](/pdf/es/python-net/add-bookmark-action/) +- [Agregar acción de documento](/pdf/es/python-net/add-document-action/) +- [Eliminar acción de apertura](/pdf/es/python-net/remove-open-action/) \ No newline at end of file diff --git a/es/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md new file mode 100644 index 000000000..8a47872e7 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md @@ -0,0 +1,53 @@ +--- +title: Agregar acción de marcador +linktitle: Agregar acción de marcador +type: docs +weight: 10 +url: /es/python-net/add-bookmark-action/ +description: Este ejemplo vincula un PDF de entrada, crea un marcador etiquetado "PdfContentEditor Bookmark" que navega a la página 1 y guarda el documento actualizado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Crear un marcador con acción de navegación en un PDF usando Python +Abstract: Este ejemplo muestra cómo agregar un marcador con una acción de navegación a un documento PDF usando Aspose.PDF for Python via the Facades API. Muestra cómo configurar el texto del marcador, su apariencia y una acción que dirige a los usuarios a una página específica. +--- + +Los marcadores proporcionan una navegación rápida dentro de los documentos PDF. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puedes crear marcadores programáticamente y asignar acciones como navegar a una página. También puedes personalizar la apariencia del marcador, incluyendo opciones de color y estilo como negrita o cursiva. + +1. Crea el objeto PdfContentEditor. +1. Vincular el PDF de entrada. +1. Definir propiedades del marcador. +1. Asignar acción al marcador. +1. Guardar el documento actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_bookmark_action(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add a bookmark action to navigate to page 1 + content_editor.create_bookmarks_action( + "PdfContentEditor Bookmark", + apd.Color.blue, + True, + False, + "", + "GoTo", + "1", + ) + # Save updated document + content_editor.save(outfile) +``` \ No newline at end of file diff --git a/es/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md new file mode 100644 index 000000000..fed1fe6e9 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md @@ -0,0 +1,47 @@ +--- +title: Agregar acción de documento +linktitle: Agregar acción de documento +type: docs +weight: 20 +url: /es/python-net/add-document-action/ +description: Este ejemplo agrega una alerta de JavaScript que aparece cuando se abre el PDF. El script está adjunto al evento de apertura del documento y se ejecuta automáticamente en los visores de PDF compatibles. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar acción de JavaScript de apertura de documento a un PDF usando Python +Abstract: Este ejemplo muestra cómo agregar una acción de JavaScript a nivel de documento que se activa cuando se abre un PDF. Usando Aspose.PDF for Python via the Facades API, el ejemplo muestra cómo vincular un documento, asignar una acción de evento de apertura y guardar el PDF actualizado. +--- + +Las acciones a nivel de documento le permiten definir comportamientos que se ejecutan automáticamente cuando ocurren ciertos eventos, como la apertura de un PDF. Con [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puede adjuntar código JavaScript a estos eventos. Esto puede usarse para notificaciones, lógica de validación o flujos de trabajo interactivos. + +1. Crea el objeto PdfContentEditor. +1. Vincular el PDF de entrada. +1. Agregar acción a nivel de documento. +1. Guardar el documento actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_document_action(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add JavaScript action for document open event + content_editor.add_document_additional_action( + content_editor.DOCUMENT_OPEN, + "app.alert('Document opened with PdfContentEditor action');", + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md new file mode 100644 index 000000000..0b7b0e7c6 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md @@ -0,0 +1,46 @@ +--- +title: Eliminar acción de apertura +linktitle: Eliminar acción de apertura +type: docs +weight: 30 +url: /es/python-net/remove-open-action/ +description: Este ejemplo carga un PDF existente, elimina la acción de apertura y guarda el documento limpio. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Eliminar la acción de apertura de documento de un PDF usando Python +Abstract: Este ejemplo muestra cómo eliminar una acción de apertura de documento de un PDF usando Aspose.PDF para Python a través de la API Facades. Muestra cómo enlazar un PDF, limpiar la acción de apertura y guardar el documento actualizado. +--- + +Los documentos PDF pueden contener acciones que se ejecutan automáticamente al abrir el archivo, como alertas de JavaScript, comandos de navegación u otros comportamientos. En algunos escenarios, es posible que necesite eliminar estas acciones por razones de seguridad, cumplimiento o experiencia del usuario. + +Usando PdfContentEditor, puede eliminar fácilmente la acción de apertura del documento y garantizar que el PDF se abra sin ejecutar ningún comportamiento automático. + +1. Crea el objeto PdfContentEditor. +1. Vincular el PDF de entrada. +1. Eliminar la acción de apertura del documento. +1. Guardar el documento actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def remove_open_action(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Remove open action from the document + content_editor.remove_document_open_action() + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md new file mode 100644 index 000000000..13deb13c6 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md @@ -0,0 +1,19 @@ +--- +title: Anotaciones de dibujo +linktitle: Anotaciones de dibujo +type: docs +weight: 50 +url: /es/python-net/drawing-annotations/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +- [Agregar anotación de línea](/pdf/es/python-net/add-line-annotation/) +- [Agregar anotación cuadrada](/pdf/es/python-net/add-square-annotation/) +- [Agregar anotación de círculo](/pdf/es/python-net/add-circle-annotation/) +- [Agregar anotación de polígono](/pdf/es/python-net/add-polygon-annotation/) +- [Agregar anotación de polilínea](/pdf/es/python-net/add-polyline-annotation/) +- [Agregar anotación de curva](/pdf/es/python-net/add-curve-annotation/) diff --git a/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md new file mode 100644 index 000000000..03f869031 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md @@ -0,0 +1,50 @@ +--- +title: Agregar anotación de círculo +linktitle: Agregar anotación de círculo +type: docs +weight: 10 +url: /es/python-net/add-circle-annotation/ +description: Este ejemplo enlaza un PDF de entrada, crea una anotación de círculo en la primera página y guarda el documento modificado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar anotación de círculo a un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo demuestra cómo agregar una anotación de círculo a un documento PDF usando Aspose.PDF for Python a través de la API Facades. Muestra cómo definir los límites de la anotación, establecer el texto del contenido, configurar el color y la apariencia, y guardar el documento actualizado. +--- + +Las anotaciones de círculo son útiles para resaltar áreas de interés en un documento PDF. Con [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puedes crear formas circulares especificando el rectángulo que define los límites del círculo, junto con el texto de la anotación, el color, las opciones de relleno, el número de página y el ancho del borde. + +1. Crea el objeto PdfContentEditor. +1. Vincular el PDF de entrada. +1. Definir los límites del círculo. +1. Agregar la anotación de círculo. +1. Guardar el documento actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_circle_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + # Create CircleAnnotation object + rect = apd.Rectangle(300, 300, 400, 400) + contents = "This is circle annotation" + content_editor.create_square_circle(rect, contents, apd.Color.blue, False, 1, 3) + + # Save output PDF file + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md new file mode 100644 index 000000000..b9b67ba01 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md @@ -0,0 +1,56 @@ +--- +title: Agregar anotación de curva +linktitle: Agregar anotación de curva +type: docs +weight: 20 +url: /es/python-net/add-curve-annotation/ +description: Este ejemplo enlaza un PDF de entrada, dibuja una curva discontinua en la primera página y guarda el documento modificado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar anotación de curva a un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo demuestra cómo agregar una anotación de curva a un documento PDF usando Aspose.PDF for Python via the Facades API. Muestra cómo definir los vértices de la curva, el estilo de borde, los límites de la anotación, el contenido de texto y guardar el documento actualizado. +--- + +Las anotaciones de curva se utilizan para resaltar rutas o formas irregulares en un PDF, proporcionando énfasis visual o señalando áreas importantes. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puedes dibujar curvas especificando una secuencia de vértices, estilo de borde, visibilidad, rectángulo de anotación y texto descriptivo. + +1. Crea el objeto PdfContentEditor. +1. Vincular el PDF onput. +1. Configure las propiedades de la Curve. +1. Dibuje la anotación de la Curve. +1. Guardar el documento actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_curve_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + line_info = pdf_facades.LineInfo() + line_info.border_style = 1 # 1 - Dashed + line_info.vertice_coordinate = [120, 520, 160, 560, 220, 540, 280, 580] + line_info.visibility = True + content_editor.draw_curve( + line_info, + 1, + apd.Rectangle(110, 510, 220, 100), + "This is curve annotation", + ) + + # Save output PDF file + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md new file mode 100644 index 000000000..84dcaa3d9 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md @@ -0,0 +1,63 @@ +--- +title: Agregar anotación de línea +linktitle: Agregar anotación de línea +type: docs +weight: 30 +url: /es/python-net/add-line-annotation/ +description: Este ejemplo asocia un PDF de entrada, dibuja una anotación de línea roja con terminaciones de línea cuadradas y guarda el PDF modificado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar anotación de línea a un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo demuestra cómo agregar una anotación de línea a un documento PDF usando Aspose.PDF for Python a través de la API Facades. Explica cómo definir los puntos de inicio y fin de la línea, los límites del rectángulo, las propiedades de apariencia y guardar el documento actualizado. +--- + +Las anotaciones de línea son útiles para enfatizar texto, resaltar relaciones o llamar la atención sobre áreas específicas en un PDF. Con [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puedes crear programáticamente anotaciones de línea especificando los puntos de inicio y fin, el rectángulo delimitador, el color, el estilo de borde y las terminaciones de línea. + +1. Crear el objeto PdfContentEditor. +1. Vincular el PDF de entrada. +1. Definir propiedades de la anotación de línea. +1. Agregar la anotación de línea. +1. Guarda el Documento actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_line_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + # Create LineAnnotation object + rect = apd.Rectangle(100, 100, 200, 200) + contents = "This is line annotation" + content_editor.create_line( + rect, + contents, + 100, + 100, + 200, + 200, + 1, + 1, + apd.Color.red, + "Solid", + [3, 2], + ["Square"], + ) + + # Save output PDF file + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md new file mode 100644 index 000000000..0d58456c8 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md @@ -0,0 +1,55 @@ +--- +title: Agregar anotación de polígono +linktitle: Agregar anotación de polígono +type: docs +weight: 40 +url: /es/python-net/add-polygon-annotation/ +description: Este ejemplo vincula un PDF de entrada, dibuja un polígono sólido en la primera página y guarda el documento modificado con una anotación. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar anotación de polígono a un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo muestra cómo agregar una anotación de polígono a un documento PDF usando Aspose.PDF for Python via the Facades API. Demuestra cómo definir los vértices del polígono, el estilo del borde, los límites de la anotación, el texto descriptivo y guardar el documento actualizado. +--- + +Las anotaciones de polígono se utilizan para resaltar áreas o formas irregulares en un PDF, proporcionando énfasis visual o marcando regiones específicas. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puedes crear polígonos especificando las coordenadas de los vértices, el estilo del borde, el número de página y el rectángulo de la anotación. + +1. Crea el objeto PdfContentEditor. +1. Vincular el PDF de entrada. +1. Configura las propiedades del polígono. +1. Añade la anotación Polygon. +1. Guardar el documento actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_polygon_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + line_info = pdf_facades.LineInfo() + line_info.border_style = 0 # 0 - Solid + line_info.vertice_coordinate = [100, 200, 150, 260, 220, 220, 200, 160] + content_editor.create_polygon( + line_info, + 1, + apd.Rectangle(90, 150, 150, 120), + "This is polygon annotation", + ) + + # Save output PDF file + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md new file mode 100644 index 000000000..14ef2318b --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md @@ -0,0 +1,55 @@ +--- +title: Agregar anotación de polilínea +linktitle: Agregar anotación de polilínea +type: docs +weight: 50 +url: /es/python-net/add-polyline-annotation/ +description: El ejemplo enlaza un PDF de entrada, crea una polilínea sólida en la primera página y guarda el documento modificado con una anotación. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar anotación de polilínea a un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo muestra cómo agregar una anotación de polilínea a un documento PDF usando Aspose.PDF for Python via the Facades API. Muestra cómo definir una secuencia de vértices, estilo de borde, rectángulo de anotación, texto y guardar el documento actualizado. +--- + +Las anotaciones de polilínea le permiten resaltar una serie de segmentos de línea conectados en un PDF. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puede dibujar una polilínea especificando las coordenadas de los vértices, el estilo de borde, el número de página y los límites de la anotación. Esto es útil para representar visualmente rutas, tendencias o conexiones en diagramas y documentos. + +1. Crear el objeto PdfContentEditor. +1. Vincular el PDF de entrada. +1. Configure las propiedades de la polilínea. +1. Agregue la anotación de polilínea. +1. Guarda el Documento actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_polyline_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + line_info = pdf_facades.LineInfo() + line_info.border_style = 0 # 0 - Solid + line_info.vertice_coordinate = [120, 420, 180, 460, 230, 430, 290, 470] + content_editor.create_poly_line( + line_info, + 1, + apd.Rectangle(110, 410, 200, 90), + "This is polyline annotation", + ) + + # Save output PDF file + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md new file mode 100644 index 000000000..5c4eb1d82 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md @@ -0,0 +1,50 @@ +--- +title: Agregar anotación cuadrada +linktitle: Agregar anotación cuadrada +type: docs +weight: 60 +url: /es/python-net/add-square-annotation/ +description: Este ejemplo enlaza un PDF de entrada, añade una anotación cuadrada azul rellena en la primera página y guarda el documento modificado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar anotación cuadrada a un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo muestra cómo agregar una anotación cuadrada a un documento PDF usando Aspose.PDF for Python a través de la API Facades. Demuestra cómo definir el rectángulo de la anotación, el contenido de texto, el color, las opciones de relleno y guardar el documento actualizado. +--- + +Las anotaciones cuadradas se usan comúnmente para resaltar áreas de interés, marcar secciones importantes o proporcionar indicaciones visuales en un documento PDF. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puedes crear anotaciones cuadradas (o circulares) especificando el rectángulo delimitador, el texto de contenido, el color del borde, la opción de relleno, el número de página y el ancho del borde. + +1. Crear el objeto PdfContentEditor. +1. Vincular el PDF de entrada. +1. Definir la anotación Square. +1. Agregar la anotación Square. +1. Guarda el Documento actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_square_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + # Create SquareAnnotation object + rect = apd.Rectangle(100, 300, 200, 400) + contents = "This is square annotation" + content_editor.create_square_circle(rect, contents, apd.Color.blue, True, 1, 3) + + # Save output PDF file + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md new file mode 100644 index 000000000..43ffcacab --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md @@ -0,0 +1,16 @@ +--- +title: Operaciones de imagen +linktitle: Operaciones de imagen +type: docs +weight: 60 +url: /es/python-net/image-operations/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +- [Reemplazar imágenes en PDF](/pdf/es/python-net/replace-image/) +- [Eliminar imágenes de PDF](/pdf/es/python-net/delete-images/) +- [Eliminar todas las imágenes del PDF](/pdf/es/python-net/delete-all-images/) \ No newline at end of file diff --git a/es/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md new file mode 100644 index 000000000..ad67506dc --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md @@ -0,0 +1,45 @@ +--- +title: Eliminar todas las imágenes del PDF +linktitle: Eliminar todas las imágenes del PDF +type: docs +weight: 10 +url: /es/python-net/delete-all-images/ +description: Eliminar todas las imágenes de un documento PDF usando Aspose.PDF for Python via the Facades API. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Eliminar todas las imágenes de un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo demuestra cómo eliminar todas las imágenes de un documento PDF usando Aspose.PDF for Python via the Facades API. Muestra cómo enlazar un PDF, eliminar todas las imágenes incrustadas y guardar el documento actualizado. +--- + +Los documentos PDF a menudo contienen imágenes para ilustraciones, marca o decoración. Puede haber casos en los que necesite eliminar todas las imágenes de un PDF, como reducir el tamaño del archivo, proteger imágenes sensibles o preparar una versión solo de texto. + +Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/)", puede eliminar programáticamente todas las imágenes de un PDF, asegurando que el documento solo contenga contenido textual. Este ejemplo enlaza un PDF de entrada, elimina todas las imágenes y guarda el archivo modificado." + +1. Crear el objeto PdfContentEditor. +1. Vincular el PDF de entrada. +1. Eliminar todas las imágenes. +1. Guarda el Documento actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def delete_all_image(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Delete all images from the document + content_editor.delete_image() + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md new file mode 100644 index 000000000..e56cc983a --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md @@ -0,0 +1,45 @@ +--- +title: Eliminar imágenes de PDF +linktitle: Eliminar imágenes de PDF +type: docs +weight: 20 +url: /es/python-net/delete-images/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Eliminar imágenes específicas de una página PDF usando PdfContentEditor en Python +Abstract: Este ejemplo muestra cómo eliminar imágenes específicas de un documento PDF usando Aspose.PDF for Python via the Facades API. Muestra cómo seleccionar imágenes en una página específica y guardar el documento actualizado. +--- + +A veces, puede que desee eliminar solo ciertas imágenes de un PDF en lugar de borrar todos los elementos visuales. Con [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puede eliminar imágenes seleccionadas especificando el número de página y el índice de la imagen. + +Este fragmento de código enlaza un PDF de entrada, elimina la segunda imagen en la página 1 y guarda el PDF modificado, dejando intactas las demás imágenes. + +1. Cree una instancia de PdfContentEditor. +1. Enlace el documento PDF de entrada. +1. Elimine imágenes específicas de una página designada. +1. Guarde el documento PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def delete_images(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Delete image on page 1 + content_editor.delete_image(1, [2]) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md new file mode 100644 index 000000000..9ebc8e02f --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md @@ -0,0 +1,43 @@ +--- +title: Reemplazar imágenes en PDF +linktitle: Reemplazar imágenes en PDF +type: docs +weight: 30 +url: /es/python-net/replace-image/ +description: Este ejemplo enlaza un PDF de entrada, reemplaza la primera imagen en la página 1 con una imagen nueva y guarda el documento modificado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Reemplazar una imagen en un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo muestra cómo reemplazar una imagen existente en un documento PDF usando Aspose.PDF for Python via the Facades API. Demuestra cómo seleccionar una imagen específica en una página y reemplazarla con una imagen nueva, luego guardar el PDF actualizado. +--- + +Los PDFs a menudo contienen imágenes que pueden necesitar ser actualizadas o reemplazadas, como logotipos, diagramas o fotos. Con [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puede reemplazar una imagen específica en una página dada proporcionando el número de página, el índice de la imagen y la ruta del archivo de la nueva imagen. + +1. Cree una instancia de PdfContentEditor. +1. Enlace el documento PDF de entrada. +1. Reemplazar una imagen específica en una página dada. +1. Guarde el documento PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def replace_image(infile, image_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Replace image on page 1 + content_editor.replace_image(1, 1, image_file) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md new file mode 100644 index 000000000..24365872b --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md @@ -0,0 +1,20 @@ +--- +title: Enlaces y navegación +linktitle: Enlaces y navegación +type: docs +weight: 70 +url: /es/python-net/links-and-navigation/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +- [Agregar enlace web](/pdf/es/python-net/add-web-link/) +- [Agregar enlace local](/pdf/es/python-net/add-local-link/) +- [Agregar enlace de documento PDF](/pdf/es/python-net/add-pdf-document-link/) +- [Agregar enlace JavaScript](/pdf/es/python-net/add-javascript-link/) +- [Agregar enlace de aplicación](/pdf/es/python-net/add-application-link/) +- [Agregar enlace de acción personalizada](/pdf/es/python-net/add-custom-action-link/) +- [Extraer enlaces](/pdf/es/python-net/extract-links/) diff --git a/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md new file mode 100644 index 000000000..ef30b693a --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md @@ -0,0 +1,54 @@ +--- +title: Agregar enlace de aplicación +linktitle: Agregar enlace de aplicación +type: docs +weight: 10 +url: /es/python-net/add-application-link/ +description: Este ejemplo enlaza un PDF de entrada, agrega un enlace de lanzamiento de aplicación en la primera página y guarda el documento modificado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar un enlace de lanzamiento de aplicación a un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo demuestra cómo agregar un enlace de lanzamiento de aplicación a un documento PDF usando Aspose.PDF for Python via the Facades API. Muestra cómo crear un área clicable que abre una aplicación especificada al hacer clic y guardar el PDF actualizado. +--- + +Los PDF pueden incluir elementos interactivos como enlaces que lanzan aplicaciones externas. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puede definir una región rectangular en una página que, al hacer clic, abre un archivo ejecutable específico. + +1. Cree una instancia de PdfContentEditor. +1. Enlace el documento PDF de entrada. +1. Defina un área rectangular para el enlace clicable. +1. Especifique la ruta de la aplicación a lanzar. +1. Establezca el color del enlace. +1. Guarde el documento PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as apd +import aspose.pdf as ap + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_application_link(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add application launch link + content_editor.create_application_link( + apd.Rectangle(180, 530, 260, 20), + "notepad.exe", + 1, + apd.Color.purple, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md new file mode 100644 index 000000000..4ce4966de --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md @@ -0,0 +1,55 @@ +--- +title: Agregar enlace de acción personalizada +linktitle: Agregar enlace de acción personalizada +type: docs +weight: 20 +url: /es/python-net/add-custom-action-link/ +description: Este ejemplo enlaza un PDF de entrada, agrega un enlace de acción personalizada en la primera página y guarda el documento modificado. Se utiliza una lista de acciones vacía por simplicidad, pero las implementaciones reales pueden incluir acciones reales. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar un enlace de acción personalizada a un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo muestra cómo agregar un enlace de acción personalizada a un documento PDF usando Aspose.PDF for Python via the Facades API. Demuestra cómo crear un área clicable en una página, asignar una acción personalizada y guardar el documento actualizado. +--- + +Los enlaces de acción personalizada le permiten definir áreas interactivas en un PDF que pueden desencadenar acciones específicas al hacer clic, como ejecutar scripts, navegar páginas o ejecutar comandos específicos de la aplicación. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puede crear un enlace de acción personalizada especificando la página, el rectángulo, el color y las acciones. + +1. Cree una instancia de PdfContentEditor. +1. Enlace el documento PDF de entrada. +1. Defina un rectángulo para el enlace clicable. +1. Especifique el número de página y el color del enlace. +1. Asigne acciones personalizadas (vacías en este ejemplo). +1. Guarde el documento PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as apd +import aspose.pdf as ap + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_custom_action_link(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add custom action link. Empty action list keeps the sample runnable + # without requiring additional enum lookups. + content_editor.create_custom_action_link( + apd.Rectangle(200, 500, 260, 20), + 1, + apd.Color.dark_red, + [], + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md new file mode 100644 index 000000000..29b2e3dee --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md @@ -0,0 +1,54 @@ +--- +title: Agregar enlace JavaScript +linktitle: Agregar enlace JavaScript +type: docs +weight: 30 +url: /es/python-net/add-javascript-link/ +description: Este ejemplo enlaza un PDF de entrada, agrega un enlace JavaScript que desencadena una alerta al hacer clic y guarda el documento modificado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar un enlace JavaScript a un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo demuestra cómo agregar un enlace JavaScript a un documento PDF usando Aspose.PDF for Python via the Facades API. Muestra cómo crear un área clicable que ejecuta código JavaScript al hacer clic y guardar el PDF actualizado. +--- + +Los enlaces JavaScript en los PDF permiten funcionalidades interactivas como mostrar alertas, realizar cálculos o modificar dinámicamente el contenido del documento. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puede definir un rectángulo clicable en una página y asociarlo con código JavaScript personalizado. + +1. Cree una instancia de PdfContentEditor. +1. Enlace el documento PDF de entrada. +1. Defina un rectángulo para el enlace JavaScript clickable. +1. Especifique el número de página y el color del enlace. +1. Asigne código JavaScript para ejecutar al hacer clic. +1. Guarde el documento PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as apd +import aspose.pdf as ap + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_javascript_link(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add JavaScript link action + content_editor.create_java_script_link( + "app.alert('PdfContentEditor JavaScript link');", + apd.Rectangle(160, 560, 260, 20), + 1, + apd.Color.orange, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md new file mode 100644 index 000000000..7aebae73f --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md @@ -0,0 +1,54 @@ +--- +title: Agregar enlace local +linktitle: Agregar enlace local +type: docs +weight: 40 +url: /es/python-net/add-local-link/ +description: Este ejemplo enlaza un PDF de entrada, agrega un enlace local de color rojo en la página 1 que apunta a la página 1 y guarda el documento modificado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar un enlace local a un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo muestra cómo agregar un enlace local a un documento PDF usando Aspose.PDF for Python a través de la API Facades. Demuestra cómo crear un área clickeable que navegue a otra página dentro del mismo PDF y guardar el documento actualizado. +--- + +Los enlaces locales en los PDFs permiten una navegación rápida entre páginas dentro del mismo documento. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puedes definir un rectángulo clickeable que vincula una página a otra, mejorando la usabilidad y la navegación del documento. + +1. Cree una instancia de PdfContentEditor. +1. Enlace el documento PDF de entrada. +1. Defina un rectángulo para el enlace local clicable. +1. Especifique la página de origen y la página de destino. +1. Establezca el color del enlace. +1. Guarde el documento PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as apd +import aspose.pdf as ap + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_local_link(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add a local link on page 1 to destination page 1 + content_editor.create_local_link( + apd.Rectangle(120, 620, 220, 20), + 1, + 1, + apd.Color.red, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md new file mode 100644 index 000000000..62b74f207 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md @@ -0,0 +1,55 @@ +--- +title: Agregar enlace de documento PDF +linktitle: Agregar enlace de documento PDF +type: docs +weight: 50 +url: /es/python-net/add-pdf-document-link/ +description: Este ejemplo enlaza un PDF de entrada, agrega un enlace de color verde a una página en otro PDF y guarda el documento modificado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar un enlace de documento PDF usando PdfContentEditor en Python +Abstract: Este ejemplo muestra cómo agregar un enlace a otro documento PDF usando Aspose.PDF for Python via the Facades API. Muestra cómo crear un área clicable que abre un PDF diferente y guardar el documento actualizado. +--- + +Los enlaces de documentos PDF permiten a los usuarios navegar de un PDF a otro sin problemas. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puedes definir un rectángulo clicable que enlaza a una página en un archivo PDF diferente, haciendo que tus documentos sean interactivos y conectados. + +1. Cree una instancia de PdfContentEditor. +1. Enlace el documento PDF de entrada. +1. Defina un rectángulo para el enlace clicable. +1. Especifique el archivo PDF vinculado, la página de origen y la página de destino. +1. Establezca el color del enlace. +1. Guarde el documento PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as apd +import aspose.pdf as ap + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_pdf_document_link(infile, linked_pdf, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add link to another PDF document + content_editor.create_pdf_document_link( + apd.Rectangle(140, 590, 240, 20), + linked_pdf, + 1, + 1, + apd.Color.green, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md new file mode 100644 index 000000000..da7db8d7d --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md @@ -0,0 +1,53 @@ +--- +title: Agregar enlace web +linktitle: Agregar enlace web +type: docs +weight: 60 +url: /es/python-net/add-web-link/ +description: Este ejemplo enlaza un PDF de entrada, agrega una anotación de enlace web azul en la página 1 que apunta a la página del producto PDF de Python de Aspose, y guarda el documento modificado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar un enlace web a un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo demuestra cómo agregar un enlace web a un documento PDF usando Aspose.PDF for Python a través de la API Facades. Muestra cómo crear un área clicable en una página que abre una URL especificada en un navegador web y guardar el documento actualizado. +--- + +Los enlaces web en los PDFs permiten a los usuarios navegar directamente a recursos en línea, sitios web o documentación. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puedes definir un área rectangular en una página PDF que, al hacer clic, abre una URL en el navegador web predeterminado. + +1. Crea una instancia de PdfContentEditor. +1. Vincula el documento PDF de entrada. +1. Defina un rectángulo para el enlace web clicable. +1. Especifique la URL, el número de página y el color del enlace. +1. Guarda el documento PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as apd +import aspose.pdf as ap + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_web_link(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add a web link annotation to page 1 + content_editor.create_web_link( + apd.Rectangle(100, 650, 200, 20), + "https://products.aspose.com/pdf/python-net/", + 1, + apd.Color.blue, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md new file mode 100644 index 000000000..5f5d320f8 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md @@ -0,0 +1,61 @@ +--- +title: Extraer enlaces +linktitle: Extraer enlaces +type: docs +weight: 70 +url: /es/python-net/extract-links/ +description: Este ejemplo enlaza un PDF de entrada, extrae todos los enlaces y muestra sus coordenadas y URIs (si están disponibles). +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Extraer enlaces de un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo demuestra cómo extraer todos los enlaces de un documento PDF usando Aspose.PDF for Python a través de la API Facades. Muestra cómo identificar y recuperar enlaces web u otros enlaces accionables incrustados en el PDF. +--- + +Los PDF a menudo contienen elementos interactivos como enlaces web, enlaces de documento y acciones personalizadas. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puedes extraer programáticamente todas las anotaciones de enlace de un PDF. Esto te permite inspeccionar o procesar los enlaces, por ejemplo, validar URL o analizar patrones de navegación en un documento. + +1. Crea una instancia de PdfContentEditor. +1. Vincula el documento PDF de entrada. +1. Extraiga todos los enlaces usando 'extract_link()'. +1. Itere sobre los enlaces extraídos. +1. Compruebe si un enlace es una LinkAnnotation y si su acción es una GoToURIAction. +1. Imprima las coordenadas del rectángulo y el URI. +1. Muestre un mensaje si no se encuentran enlaces. + +```python +import aspose.pdf.facades as pdf_facades +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as apd +import aspose.pdf as ap + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def extract_links(infile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Extract links from the document + links = content_editor.extract_link() + + count = 0 + for link in links: + count += 1 + print(f"Link {count}: {link.rect}") + if is_assignable(link, ap.annotations.LinkAnnotation): + annotation = cast(ap.annotations.LinkAnnotation, link) + if is_assignable(annotation.action, ap.annotations.GoToURIAction): + action = cast(ap.annotations.GoToURIAction, annotation.action) + print(f" URI: {action.uri}") + + if count == 0: + print("No links found") +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md new file mode 100644 index 000000000..0b7dec67f --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md @@ -0,0 +1,15 @@ +--- +title: Multimedia +linktitle: Multimedia +type: docs +weight: 80 +url: /es/python-net/multimedia/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +- [Agregar anotación de película](/pdf/es/python-net/add-movie-annotation/) +- [Agregar anotación de sonido](/pdf/es/python-net/add-sound-annotation/) diff --git a/es/python-net/working-with-facades/pdfcontenteditor/multimedia/add-movie-annotation/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/multimedia/add-movie-annotation/_index.md new file mode 100644 index 000000000..12b4235d6 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/multimedia/add-movie-annotation/_index.md @@ -0,0 +1,46 @@ +--- +title: Agregar anotación de película +linktitle: Agregar anotación de película +type: docs +weight: 10 +url: /es/python-net/add-movie-annotation/ +description: Este ejemplo enlaza un PDF de entrada, agrega una anotación de película en la página 1 y guarda el PDF actualizado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar una anotación de película a un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo muestra cómo incrustar una película (video) en un documento PDF usando Aspose.PDF para Python a través de la API Facades. Demuestra cómo agregar una anotación clicable que reproduce un video directamente dentro del PDF. +--- + +Las anotaciones de película en los PDF le permiten incrustar contenido multimedia, como videos, en sus documentos. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puede definir un rectángulo en una página donde aparecerá el video. Al hacer clic, el video puede reproducirse directamente desde el PDF, haciendo sus documentos más interactivos y atractivos. + +1. Crea una instancia de PdfContentEditor. +1. Vincula el documento PDF de entrada. +1. Definir un rectángulo para la anotación de película. +1. Especificar el archivo de video para incrustar. +1. Asignar el número de página para la anotación. +1. Guarda el documento PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_movie_annotation(infile, movie_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add movie annotation to page 1 + content_editor.create_movie(apd.Rectangle(80, 500, 220, 120), movie_file, 1) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/multimedia/add-sound-annotation/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/multimedia/add-sound-annotation/_index.md new file mode 100644 index 000000000..75c484cdb --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/multimedia/add-sound-annotation/_index.md @@ -0,0 +1,47 @@ +--- +title: Agregar anotación de sonido +linktitle: Agregar anotación de sonido +type: docs +weight: 20 +url: /es/python-net/add-sound-annotation/ +description: Este ejemplo vincula un PDF de entrada, agrega una anotación de sonido en la página 1 y guarda el PDF modificado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar una anotación de sonido a un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo muestra cómo incrustar audio en un documento PDF usando Aspose.PDF for Python a través de la API Facades. Demuestra cómo agregar una anotación de sonido clickeable que reproduzca un archivo de audio directamente dentro del PDF. +--- + +Las anotaciones de sonido en los PDF le permiten agregar contenido de audio, como notas de voz, música o efectos de sonido a sus documentos. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puede definir un pequeño rectángulo clickeable en una página que reproduce un archivo de audio especificado al activarse. + +1. Crea una instancia de PdfContentEditor. +1. Vincula el documento PDF de entrada. +1. Definir un rectángulo para la anotación de sonido. +1. Especifique el archivo de audio, el nombre de la anotación, el número de página y la tasa de muestreo. +1. Guarda el documento PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_sound_annotation(infile, sound_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add sound annotation to page 1 + content_editor.create_sound( + apd.Rectangle(80, 450, 30, 30), sound_file, "Speaker", 1, "8000" + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md new file mode 100644 index 000000000..2269b7a1c --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md @@ -0,0 +1,23 @@ +--- +title: Gestión de sellos +linktitle: Gestión de sellos +type: docs +weight: 90 +url: /es/python-net/stamps-management/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +- [Agregar sello de goma](/pdf/es/python-net/add-rubber-stamp/) +- [Eliminar sello por índice](/pdf/es/python-net/delete-stamp-by-index/) +- [Administrar Sello por ID](/pdf/es/python-net/manage-stamp-by-id/) +- [Eliminar sello por IDs](/pdf/es/python-net/delete-stamp-by-ids-examples/) +- [Mover Sello Por Índice](/pdf/es/python-net/move-stamp-by-index/) +- [Mover Sello por ID](/pdf/es/python-net/move-stamp-by-id-example/) +- [Crear sello de goma con archivo de apariencia](/pdf/es/python-net/create-rubber-stamp-with-appearance-file/) +- [Crear sello de goma con flujo de apariencia](/pdf/es/python-net/create-rubber-stamp-with-appearance-stream/) +- [Eliminar sellos globalmente](/pdf/es/python-net/delete-stamps-globally/) +- [Listar sellos](/pdf/es/python-net/list-stamps/) diff --git a/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md new file mode 100644 index 000000000..32b5a9725 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md @@ -0,0 +1,53 @@ +--- +title: Agregar sello de goma +linktitle: Agregar sello de goma +type: docs +weight: 10 +url: /es/python-net/add-rubber-stamp/ +description: Este ejemplo enlaza un PDF de entrada, agrega un sello de goma verde “Approved” a las primeras cuatro páginas y guarda el documento modificado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar una anotación de sello de goma a un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo muestra cómo agregar una anotación de sello de goma a un documento PDF usando Aspose.PDF for Python via the Facades API. Los sellos de goma le permiten marcar visualmente las páginas con aprobaciones, revisiones o etiquetas personalizadas. +--- + +Las anotaciones de sello de goma se usan comúnmente en PDFs para indicar aprobación, estado de revisión u otras notas. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puede definir un rectángulo para el sello, establecer su texto y comentarios, elegir un color y aplicarlo a varias páginas de un documento. + +1. Crea una instancia de PdfContentEditor. +1. Vincula el documento PDF de entrada. +1. Recorrer las páginas 1–34. +1. Agregar una anotación de sello de goma con texto personalizado, comentarios y color. +1. Guarda el documento PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_rubber_stamp(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + for i in range(1, 5): + content_editor.create_rubber_stamp( + i, + apd.Rectangle(120, 450, 180, 60), + "Approved", + "Approved by reviewer", + apd.Color.green, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md new file mode 100644 index 000000000..75f88f95c --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md @@ -0,0 +1,53 @@ +--- +title: Crear sello de goma con archivo de apariencia +linktitle: Crear sello de goma con archivo de apariencia +type: docs +weight: 20 +url: /es/python-net/create-rubber-stamp-with-appearance-file/ +description: El ejemplo enlaza un PDF de entrada, crea un sello de goma en la página 1 usando un archivo de imagen como apariencia del sello, y guarda el PDF actualizado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Crear un sello de goma con apariencia personalizada en un PDF usando PdfContentEditor +Abstract: Este ejemplo muestra cómo agregar una anotación de sello de goma con una apariencia personalizada (imagen) a un documento PDF usando Aspose.PDF for Python via the Facades API. Los sellos personalizados le permiten incluir logotipos, firmas o elementos visuales de marca como parte del sello. +--- + +Las anotaciones de sello de goma pueden personalizarse no solo con texto sino también usando un archivo de imagen como su apariencia. Este enfoque es útil para agregar logotipos de la empresa, sellos de firma o cualquier indicación visual a sus páginas PDF. + +1. Crear un [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) instancia. +1. Vincula el documento PDF de entrada. +1. Defina un rectángulo para el sello. +1. Utilice un archivo de imagen personalizado para definir la apariencia del sello de caucho. +1. Establezca el texto y el color del sello. +1. Guarda el documento PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def create_rubber_stamp_with_appearance_file(infile, image_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Create rubber stamp using appearance_file overload (image path) + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(100, 400, 200, 60), + "Stamp with custom appearance", + apd.Color.dark_green, + image_file, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md new file mode 100644 index 000000000..31f0584be --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md @@ -0,0 +1,53 @@ +--- +title: Crear Sello de Goma con Flujo de Apariencia +linktitle: Crear Sello de Goma con Flujo de Apariencia +type: docs +weight: 30 +url: /es/python-net/create-rubber-stamp-with-appearance-stream/ +description: Este ejemplo carga un PDF, crea un sello de goma en la página 1 usando un archivo de imagen para su apariencia, y guarda el documento modificado. ✨ +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Crear un Sello de Goma con Apariencia de Imagen Personalizada Usando PdfContentEditor en Python +Abstract: Este ejemplo muestra cómo crear una anotación de sello de goma con una apariencia de imagen personalizada en un PDF usando Aspose.PDF for Python via the Facades API. Este enfoque le permite aplicar sellos con marca o visualmente ricos, como logotipos, sellos o firmas. +--- + +Las anotaciones de sello de goma pueden personalizarse usando un archivo de imagen externo. En lugar de depender solo de sellos basados en texto, puede definir una apariencia visual (por ejemplo, el logotipo de la empresa o una insignia de aprobación) y colocarla en una página. + +1. Crear un [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) instancia. +1. Vincula el documento PDF de entrada. +1. Defina un rectángulo para la ubicación del sello. +1. Utilice un archivo de imagen como apariencia del sello. +1. Aplique configuraciones de texto y color. +1. Guarda el documento PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def create_rubber_stamp_with_appearance_file(infile, image_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Create rubber stamp using appearance_file overload (image path) + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(100, 400, 200, 60), + "Stamp with custom appearance", + apd.Color.dark_green, + image_file, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md new file mode 100644 index 000000000..2866d8fd8 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md @@ -0,0 +1,69 @@ +--- +title: Eliminar sello por ID +linktitle: Eliminar sello por ID +type: docs +weight: 85 +url: /es/python-net/delete-stamp-by-ids-examples/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Eliminar sellos de caucho por ID único o múltiple en un PDF usando PdfContentEditor +Abstract: Este ejemplo muestra cómo eliminar anotaciones de sellos de caucho de un PDF basándose en sus IDs únicos usando Aspose.PDF for Python via the Facades API. Cubre tanto la eliminación por una sola ID como la eliminación por múltiples IDs. +--- + +Al trabajar con PDFs que contienen múltiples sellos, a menudo es necesario eliminar sellos específicos sin afectar a los demás. Usando la eliminación basada en ID, puedes controlar con precisión qué sellos eliminar: + +- 'delete_stamp_by_id(stamp_id, page_number)' – elimina un solo sello por su ID en una página específica +- 'delete_stamp_by_ids(page_number, stamp_ids)' – elimina varios sellos por sus IDs en una página dada + +1. Crear un [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) instancia. +1. Vincula el documento PDF de entrada. +1. Añade dos sellos de goma con IDs distintos. +1. Elimina sellos utilizando tanto el método de eliminación por ID único como el de eliminación por varios IDs. +1. Guardar el PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def delete_stamp_by_ids_examples(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + # Create two stamps on page 1 so they can be deleted by ID + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(120, 320, 180, 60), + "Draft", + "Delete by single ID", + apd.Color.orange, + ) + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(120, 250, 180, 60), + "Draft", + "Delete by multiple IDs", + apd.Color.orange, + ) + + # Delete by single ID overload and by IDs overload + content_editor.delete_stamp_by_id(1, 1) + content_editor.delete_stamp_by_ids(1, [2]) + + # Save updated document + content_editor.save(outfile) +``` + diff --git a/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md new file mode 100644 index 000000000..ca3fa06a7 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md @@ -0,0 +1,64 @@ +--- +title: Mover sello por índice +linktitle: Mover sello por índice +type: docs +weight: 50 +url: /es/python-net/move-stamp-by-index/ +description: Este ejemplo crea dos sellos de caucho en la página 2. Después de eso, un sello puede ser movido especificando su índice y nuevas coordenadas. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Mover un sello de caucho por índice en un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo demuestra cómo reposicionar una anotación de sello de caucho en un PDF usando su índice con Aspose.PDF for Python via the Facades API. Muestra cómo agregar varios sellos y luego mover uno de ellos según su orden en la página. +--- + +Cuando existen varios sellos de caucho en una página, puedes mover uno específico usando su índice. El método move_stamp() permite reposicionar anotaciones según su secuencia, lo cual es útil cuando no rastreas los IDs de los sellos pero conoces su orden. + +1. Crear un [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) instancia. +1. Vincula el documento PDF de entrada. +1. Agregar dos anotaciones de sello de caucho en la misma página. +1. Demostrar cómo mover un sello usando su índice. +1. Guarda el documento PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def move_stamp_by_index(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + content_editor.create_rubber_stamp( + 2, + apd.Rectangle(200, 380, 180, 60), + "Draft", + "Draft stamp for ID-based operations", + apd.Color.orange, + ) + + content_editor.create_rubber_stamp( + 2, + apd.Rectangle(200, 480, 180, 60), + "Draft", + "Draft stamp for ID-based operations", + apd.Color.orange, + ) + content_editor.save(outfile) + + # Move first stamp on page 1 by index + # content_editor.move_stamp(1, 1, 10, 10) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md new file mode 100644 index 000000000..dd997363a --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md @@ -0,0 +1,60 @@ +--- +title: Eliminar sellos globalmente +linktitle: Eliminar sellos globalmente +type: docs +weight: 60 +url: /es/python-net/delete-stamps-globally/ +description: Este ejemplo demuestra cómo eliminar anotaciones de sellos de goma globalmente en todas las páginas de un PDF usando Aspose.PDF for Python via the Facades API. Muestra cómo quitar los sellos por ID sin especificar páginas individuales. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Eliminar sellos de goma globalmente en un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo demuestra cómo eliminar anotaciones de sellos de goma globalmente en todas las páginas de un PDF usando Aspose.PDF for Python via the Facades API. Muestra cómo quitar los sellos por ID sin especificar páginas individuales. +--- + +Al trabajar con múltiples páginas, es posible que necesite eliminar ciertos sellos en todo el documento. Los métodos \u0027delete_stamp_by_id()\u0027 y \u0027delete_stamp_by_ids()\u0027 le permiten eliminar sellos globalmente por sus identificadores, eliminando la necesidad de iterar manualmente a través de cada página. + +1. Crear un [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) instancia. +1. Vincula el documento PDF de entrada. +1. Agregar sellos de goma a múltiples páginas. +1. Eliminar sellos globalmente usando sus IDs. +1. Guarda el documento PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def delete_stamps_globally(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + # Add stamps across multiple pages so global deletion is meaningful + for page in range(1, 5): + content_editor.create_rubber_stamp( + page, + apd.Rectangle(120, 500, 180, 60), + "Draft", + "Stamp for global deletion", + apd.Color.gray, + ) + + # delete_stamp_by_id without page number removes stamp ID from all pages + content_editor.delete_stamp_by_id(1) + # delete_stamp_by_ids without page number removes a list of IDs from all pages + content_editor.delete_stamp_by_ids([2, 3]) + + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md new file mode 100644 index 000000000..ebf3d9076 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md @@ -0,0 +1,53 @@ +--- +title: Listar Sellos +linktitle: Listar Sellos +type: docs +weight: 70 +url: /es/python-net/list-stamps/ +description: Este ejemplo carga un PDF, recupera todos los sellos de la página 1, los imprime y muestra un mensaje si no se encuentran sellos. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Listar anotaciones de sellos de goma en un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo muestra cómo recuperar y listar anotaciones de sellos de goma de un documento PDF usando Aspose.PDF for Python a través de la API Facades. Demuestra cómo acceder a los sellos en una página específica y mostrar sus detalles. +--- + +Cuando se trabaja con PDFs anotados, puede ser necesario inspeccionar los sellos de goma existentes antes de modificarlos o eliminarlos. El método 'get_stamps()' permite recuperar todos los sellos colocados en una página determinada. Luego puede iterar a través de los resultados y procesarlos programáticamente. + +1. Crear un [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) instancia. +1. Vincula el documento PDF de entrada. +1. Recuperar todos los sellos de la página 1. +1. Iterar a través de la colección de sellos. +1. Imprimir cada sello. +1. Mostrar un mensaje si no existen sellos. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def list_stamps(infile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # List all stamps on page 1 + stamps = content_editor.get_stamps(1) + + count = 0 + for stamp in stamps: + count += 1 + print(f"Stamp {count}: {stamp}") + + if count == 0: + print("No stamps found") +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md new file mode 100644 index 000000000..a34949d3f --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md @@ -0,0 +1,71 @@ +--- +title: Administrar Sello por ID +linktitle: Administrar Sello por ID +type: docs +weight: 95 +url: /es/python-net/manage-stamp-by-id/ +description: Cómo manipular anotaciones de sello de goma en un PDF por sus IDs únicos usando Aspose.PDF for Python +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Administrar sellos de goma por ID en un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo demuestra cómo manipular anotaciones de sello de goma en un PDF por sus IDs únicos usando Aspose.PDF for Python a través de la API Facades. Puedes ocultar o mostrar sellos específicos en determinadas páginas sin afectar a otros sellos. +--- + +En PDFs con múltiples sellos de goma, puede ser útil controlar sellos individuales basándose en su ID. Los métodos 'hide_stamp_by_id()' y 'show_stamp_by_id()' permiten un control selectivo de la visibilidad. Este ejemplo muestra cómo: + +- Agregar múltiples sellos con IDs únicos +- Ocultar un sello en una página específica +- Mostrar un sello en otra página + +Al usar operaciones basadas en ID, evitas rastrear sellos por posición de página u otros atributos. + +1. Crear un [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) instancia. +1. Vincula el documento PDF de entrada. +1. Agregar sellos de goma con IDs específicos. +1. Ocultar y mostrar sellos según sus IDs y números de página. +1. Guarda el documento PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def manage_stamp_by_id(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(200, 380, 180, 60), + "Draft", + "Draft stamp for ID-based operations", + apd.Color.orange, + ) + + content_editor.create_rubber_stamp( + 2, + apd.Rectangle(200, 480, 180, 60), + "Draft", + "Draft stamp for ID-based operations", + apd.Color.orange, + ) + + # Apply ID-based stamp operations + content_editor.hide_stamp_by_id(1, 1) + content_editor.show_stamp_by_id(1, 2) + + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md new file mode 100644 index 000000000..72851e9e0 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md @@ -0,0 +1,56 @@ +--- +title: Mover sello por ID +linktitle: Mover sello por ID +type: docs +weight: 80 +url: /es/python-net/move-stamp-by-id-example/ +description: En este ejemplo, se agrega un sello de goma a la página 1 y luego se mueve a una nueva posición usando su ID antes de guardar el documento actualizado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Mover un sello de goma por ID en un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo demuestra cómo reposicionar una anotación de sello de goma existente en un PDF usando Aspose.PDF for Python a través de la API Facades. Muestra cómo crear un sello y luego moverlo programáticamente usando su ID. +--- + +Después de agregar una anotación de sello de goma a un PDF, es posible que necesite ajustar su posición. El método ‘move_stamp_by_id()’ le permite reubicar un sello basado en su identificador, sin recrearlo. Esto es útil en flujos de trabajo automatizados donde la colocación del sello debe ajustarse dinámicamente. + +1. Crear un [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) instancia. +1. Vincula el documento PDF de entrada. +1. Agregar una anotación de sello de goma. +1. Mueve el sello usando su ID. +1. Guarda el documento PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def move_stamp_by_id_example(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(300, 420, 180, 60), + "Approved", + "Move this stamp by ID", + apd.Color.green, + ) + + # Move stamp by ID overload + content_editor.move_stamp_by_id(1, 1, 240, 360) + + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md new file mode 100644 index 000000000..96daf9854 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md @@ -0,0 +1,71 @@ +--- +title: Mover Sello Por Índice +linktitle: Mover Sello Por Índice +type: docs +weight: 90 +url: /es/python-net/move-stamp-by-index/ +description: Cómo reposicionar anotaciones de sello de goma en un PDF usando su índice en una página con Aspose.PDF for Python +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Mover sellos de goma en un PDF usando posicionamiento basado en índices +Abstract: Este ejemplo muestra cómo reposicionar anotaciones de sello de goma en un PDF usando su índice en una página con Aspose.PDF for Python a través de la API Facades. Destaca la creación de varios sellos y su preparación para operaciones de movimiento. +--- + +En la edición de PDF, puede ser necesario ajustar la posición de los sellos de goma existentes. Este fragmento de código muestra cómo: + +- Agregar varios sellos en la misma página +- Prepararlos para reposicionarlos usando su índice +- Opcionalmente mover un sello especificando su página, índice y nuevas coordenadas + +El método 'move_stamp(page_number, stamp_index, new_x, new_y)' puede reposicionar los sellos de manera precisa. + +1. Crear un [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) objeto. +1. Vincula el PDF al editor. +1. Añade varios sellos de goma a una página. +1. Guarda el documento antes de realizar operaciones de movimiento. +1. Mover un sello específico por su índice. +1. Guarde el PDF actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def move_stamp_by_index(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + content_editor.create_rubber_stamp( + 2, + apd.Rectangle(200, 380, 180, 60), + "Draft", + "Draft stamp for ID-based operations", + apd.Color.orange, + ) + + content_editor.create_rubber_stamp( + 2, + apd.Rectangle(200, 480, 180, 60), + "Draft", + "Draft stamp for ID-based operations", + apd.Color.orange, + ) + content_editor.save(outfile) + + # Move first stamp on page 1 by index + # content_editor.move_stamp(1, 1, 10, 10) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md new file mode 100644 index 000000000..c40735b2b --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md @@ -0,0 +1,18 @@ +--- +title: Operaciones de texto +linktitle: Operaciones de texto +type: docs +weight: 100 +url: /es/python-net/text-operations/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +- [Reemplazar texto simple](/pdf/es/python-net/replace-text-simple/) +- [Reemplazar texto Regex](/pdf/es/python-net/replace-text-regex/) +- [Reemplazar texto en la página](/pdf/es/python-net/replace-text-on-page/) +- [Reemplazar texto con estado](/pdf/es/python-net/replace-text-with-state/) +- [Reemplazar texto en la página con estado](/pdf/es/python-net/replace-text-on-page-with-state/) diff --git a/es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md new file mode 100644 index 000000000..590d957b4 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md @@ -0,0 +1,54 @@ +--- +title: Reemplazar texto en la página con estado +linktitle: Reemplazar texto en la página con estado +type: docs +weight: 20 +url: /es/python-net/replace-text-on-page-with-state/ +description: En este ejemplo, todas las apariciones de la palabra "software" en la página 1 se reemplazan por "SOFTWARE PAGE 1", usando texto rojo con un tamaño de fuente de 12. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Reemplazar texto con formato personalizado en una página específica usando PdfContentEditor en Python +Abstract: Este ejemplo muestra cómo reemplazar texto en una página específica de un PDF mientras se aplica formato personalizado usando Aspose.PDF for Python via the Facades API. Muestra cómo controlar el tamaño y el color de la fuente durante el reemplazo de texto. +--- + +A veces, reemplazar texto en un PDF también requiere cambios de formato como color o tamaño de fuente. Usando TextState, puedes definir propiedades de estilo y aplicarlas durante el reemplazo. Esto te permite resaltar el texto modificado o imponer un formato consistente en los documentos. + +1. Crear un [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) instancia. +1. Vincula el documento PDF de entrada. +1. Define un TextState con formato personalizado. +1. Configura la estrategia de reemplazo. +1. Reemplaza texto en una página específica. +1. Guarda el documento PDF actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def replace_text_on_page_with_state(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + text_state = ap.text.TextState() + text_state.foreground_color = ap.Color.red + text_state.font_size = 12 + + # Replace text on a specific page with explicit text formatting + content_editor.replace_text_strategy.replace_scope = ( + pdf_facades.ReplaceTextStrategy.Scope.REPLACE_ALL + ) + content_editor.replace_text("software", 1, "SOFTWARE PAGE 1", text_state) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md new file mode 100644 index 000000000..9b2c439d0 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md @@ -0,0 +1,48 @@ +--- +title: Reemplazar texto en la página +linktitle: Reemplazar texto en la página +type: docs +weight: 10 +url: /es/python-net/replace-text-on-page/ +description: En este ejemplo, la primera aparición de la palabra "PDF" se reemplaza con "Page 1 Replaced Text" utilizando un tamaño de fuente especificado. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Reemplazar texto en una página específica usando PdfContentEditor en Python +Abstract: Este ejemplo demuestra cómo reemplazar texto en un documento PDF usando Aspose.PDF for Python a través de la API de Facades. Muestra cómo reemplazar la primera aparición de texto en una página y guardar el documento actualizado. +--- + +El reemplazo de texto es un requisito común al actualizar documentos PDF. Usando [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puedes buscar texto específico y reemplazarlo con contenido nuevo. La propiedad 'replace_text_strategy' permite controlar cuántas apariciones se reemplazan. + +1. Crea una instancia de PdfContentEditor. +1. Vincula el documento PDF de entrada. +1. Configurar la estrategia de reemplazo de texto. +1. Reemplazar el texto objetivo. +1. Guarda el documento PDF actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def replace_text_on_page(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Replace text on page 1 + content_editor.replace_text_strategy.replace_scope = ( + pdf_facades.ReplaceTextStrategy.Scope.REPLACE_FIRST + ) + content_editor.replace_text("PDF", "Page 1 Replaced Text", 14) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md new file mode 100644 index 000000000..92a9b0945 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md @@ -0,0 +1,49 @@ +--- +title: Reemplazar texto Regex +linktitle: Reemplazar texto Regex +type: docs +weight: 30 +url: /es/python-net/replace-text-regex/ +description: En este ejemplo, todos los números de cuatro dígitos en el documento se reemplazan con el marcador "[NUMBER]". Esto es útil para ocultar datos sensibles, normalizar contenido o anonimizar documentos. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Reemplazar texto usando expresiones regulares con PdfContentEditor en Python +Abstract: Este ejemplo muestra cómo reemplazar texto en un PDF usando expresiones regulares con Aspose.PDF for Python a través de la API Facades. Demuestra cómo buscar patrones y reemplazar todas las coincidencias en todo el documento. +--- + +Las expresiones regulares permiten un reemplazo de texto flexible basado en patrones en lugar de cadenas fijas. Al habilitar el soporte de regex en 'replace_text_strategy', puedes coincidir contenido dinámico como números, fechas o cadenas formateadas. + +1. Crear un [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) instancia. +1. Enlace el documento PDF de entrada. +1. Configura la estrategia de reemplazo para usar regex. +1. Reemplazar patrones coincidentes en todo el documento. +1. Guarde el documento PDF actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def replace_text_regex(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Replace text in the whole document + content_editor.replace_text_strategy.replace_scope = ( + pdf_facades.ReplaceTextStrategy.Scope.REPLACE_ALL + ) + content_editor.replace_text_strategy.is_regular_expression_used = True + content_editor.replace_text(r"\d{4}", "[NUMBER]") + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md new file mode 100644 index 000000000..8aa0a1668 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md @@ -0,0 +1,48 @@ +--- +title: Reemplazar texto simple +linktitle: Reemplazar texto simple +type: docs +weight: 40 +url: /es/python-net/replace-text-simple/ +description: En este ejemplo, todas las apariciones de "23" se sustituyen por "XXXIII " en todo el documento. Esto demuestra un reemplazo de cadena sencillo sin formato personalizado ni expresiones regulares. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Reemplazar texto en todo un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo demuestra cómo reemplazar texto en todo un documento PDF utilizando Aspose.PDF for Python via the Facades API. Reemplaza todas las apariciones de una cadena especificada con texto nuevo. +--- + +El reemplazo de texto simple es útil al actualizar valores repetidos en un documento. Con [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), puedes definir un alcance de reemplazo y sustituir texto globalmente en todas las páginas. + +1. Crear un [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) instancia. +1. Enlace el documento PDF de entrada. +1. Configura el alcance de reemplazo para todas las ocurrencias. +1. Reemplazar el texto objetivo. +1. Guarde el documento PDF actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def replace_text_simple(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Replace text in the whole document + content_editor.replace_text_strategy.replace_scope = ( + pdf_facades.ReplaceTextStrategy.Scope.REPLACE_ALL + ) + content_editor.replace_text("33", "XXXIII ") + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md new file mode 100644 index 000000000..4e95e5c08 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md @@ -0,0 +1,54 @@ +--- +title: Reemplazar texto con estado +linktitle: Reemplazar texto con estado +type: docs +weight: 50 +url: /es/python-net/replace-text-with-state/ +description: En este ejemplo, todas las ocurrencias de "software" se reemplazan por "SOFTWARE" y se formatean en azul con un tamaño de fuente de 14. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Reemplazar texto con formato personalizado en un PDF usando PdfContentEditor en Python +Abstract: Este ejemplo demuestra cómo reemplazar texto en un documento PDF mientras se aplica formato personalizado usando Aspose.PDF for Python a través de la API Facades. Muestra cómo controlar el color del texto y el tamaño de fuente durante el reemplazo. +--- + +Al actualizar texto en un PDF, puede que desees que el contenido de reemplazo destaque. Usando un objeto TextState, puedes definir estilos como el color y el tamaño de fuente, y luego aplicarlos a todo el texto reemplazado. + +1. Crear un [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) instancia. +1. Enlace el documento PDF de entrada. +1. Define un TextState con formato personalizado. +1. Configurar el alcance del reemplazo. +1. Reemplazar texto en todo el documento. +1. Guarde el documento PDF actualizado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def replace_text_with_state(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + text_state = ap.text.TextState() + text_state.foreground_color = ap.Color.blue + text_state.font_size = 14 + + # Replace text with explicit text formatting + content_editor.replace_text_strategy.replace_scope = ( + pdf_facades.ReplaceTextStrategy.Scope.REPLACE_ALL + ) + content_editor.replace_text("software", "SOFTWARE", text_state) + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md new file mode 100644 index 000000000..eb94ec406 --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md @@ -0,0 +1,16 @@ +--- +title: Preferencias del visor +linktitle: Preferencias del visor +type: docs +weight: 110 +url: /es/python-net/viewer-preferences/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + + +- [Cambiar Preferencias del Visor de PDF](/pdf/es/python-net/change-viewer-preferences/) +- [Obtener preferencias del visor de PDF](/pdf/es/python-net/get-viewer-preferences/) diff --git a/es/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md new file mode 100644 index 000000000..77bebef7a --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md @@ -0,0 +1,76 @@ +--- +title: Cambiar preferencias del visor PDF +linktitle: Cambiar preferencias del visor PDF +type: docs +weight: 10 +url: /es/python-net/change-viewer-preferences/ +description: Este módulo demuestra cómo ajustar la configuración del visor de un documento PDF usando Aspose.PDF for Python. +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Personalizar la experiencia del visor PDF con Python +Abstract: Controla cómo se muestra tu documento PDF al abrirse modificando programáticamente las preferencias del visor. Esta funcionalidad te permite adaptar la interfaz de usuario y el diseño, garantizando una experiencia de visualización coherente. +--- + +Los archivos PDF tienen preferencias de visor incorporadas que controlan aspectos como la disposición de página, la visibilidad de la barra de herramientas y el comportamiento de la ventana. Con este script, puedes: + +- Inspeccionar las preferencias actuales del visor de un PDF. +- Modificar opciones de diseño (p. ej., una página, una columna, dos columnas). +- Alternar elementos de la interfaz de usuario, como barra de herramientas, barra de menús o visualización del título. +- Guardar el PDF con las preferencias actualizadas para una experiencia de visualización controlada. + +1. Definir banderas de ViewerPreference. +1. Obtener las preferencias de ViewerPreference actuales. +1. Modificar preferencias. +1. Aplicar Preferencias Actualizadas. +1. Guarda el PDF. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from enum import IntFlag +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Define ViewerPreference flags +class ViewerPreference(IntFlag): + HIDE_TOOLBAR = 1 + HIDE_MENUBAR = 2 + HIDE_WINDOW_UI = 4 + FIT_WINDOW = 8 + CENTER_WINDOW = 16 + DISPLAY_DOC_TITLE = 32 + NON_FULL_SCREEN_PAGE_MODE_USE_NONE = 64 + NON_FULL_SCREEN_PAGE_MODE_USE_OUTLINES = 128 + NON_FULL_SCREEN_PAGE_MODE_USE_THUMBS = 256 + NON_FULL_SCREEN_PAGE_MODE_USE_OC = 512 + DIRECTION_L2R = 1024 + DISPLAY_DOC_TITLE_IN_TITLE_BAR = 2048 + PAGE_LAYOUT_SINGLE_PAGE = 4096 + PAGE_LAYOUT_ONE_COLUMN = 8192 + PAGE_LAYOUT_TWO_COLUMN_LEFT = 16384 + PAGE_LAYOUT_TWO_COLUMN_RIGHT = 32768 + PAGE_LAYOUT_TWO_PAGE_LEFT = 65536 + PAGE_LAYOUT_TWO_PAGE_RIGHT = 131072 + + +def change_viewer_preferences(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + # Get current viewer preference and toggle single-page layout + current_preference = ViewerPreference(content_editor.get_viewer_preference()) + updated_preference = current_preference | ViewerPreference.PAGE_LAYOUT_SINGLE_PAGE + content_editor.change_viewer_preference(int(updated_preference)) + + # Save updated document + content_editor.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md new file mode 100644 index 000000000..cdfb6f63a --- /dev/null +++ b/es/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md @@ -0,0 +1,46 @@ +--- +title: Obtener preferencias del visor PDF +linktitle: Obtener preferencias del visor PDF +type: docs +weight: 20 +url: /es/python-net/get-viewer-preferences/ +description: Cómo leer y modificar las preferencias del visor PDF programáticamente usando Aspose.PDF para Python +lastmod: "2026-03-20" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Administrar las preferencias del visor PDF con Aspose.PDF en Python +Abstract: Esta guía muestra cómo leer y modificar las preferencias del visor PDF programáticamente usando Aspose.PDF para Python. Las preferencias del visor controlan cómo se muestra un PDF al abrirse en un visor PDF, como abrir con marcadores, ocultar barras de herramientas o usar un diseño de una sola página. +--- + +Aspose.PDF proporciona herramientas para acceder y actualizar las preferencias del visor PDF. Estas preferencias definen la disposición inicial y el comportamiento de presentación de un documento PDF en los lectores PDF. Esto incluye opciones como habilitar la vista de marcadores, ocultar barras de menús o especificar modos de diseño de página. Usando PdfContentEditor, puedes recuperar las preferencias existentes, verificar banderas específicas y actualizarlas según sea necesario. + +1. Definir banderas de ViewerPreference. +1. Inicializar [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) y Vincular PDF. +1. Obtener las preferencias de ViewerPreference actuales. +1. Verificar banderas específicas. +1. Mostrar preferencias actuales. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from enum import IntFlag +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def get_viewer_preferences(infile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Read current viewer preference flags + viewer_preference = ViewerPreference(content_editor.get_viewer_preference()) + if viewer_preference & ViewerPreference.PAGE_MODE_USE_OUTLINES: + print("PageModeUseOutlines is enabled") + print(f"Current viewer preference: {viewer_preference}") +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/_index.md b/es/python-net/working-with-facades/pdffileeditor/_index.md new file mode 100644 index 000000000..fe8420ee8 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/_index.md @@ -0,0 +1,31 @@ +--- +title: Clase PdfFileEditor +linktitle: Clase PdfFileEditor +type: docs +weight: 10 +url: /es/python-net/pdffileeditor-class/ +description: Explore cómo editar y manipular archivos PDF usando la clase PDFFileEditor en Python con Aspose.PDF. +lastmod: "2026-01-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Edite páginas PDF, fusione archivos y divida documentos con PdfFileEditor en Python +Abstract: Aprenda cómo usar la clase PdfFileEditor en Aspose.PDF for Python via .NET para manipular páginas PDF y la estructura del documento. Esta sección cubre cambios en el diseño de página, gestión de páginas, fusión de PDF, división de documentos y flujos de trabajo de imposición de cuadernillos o N-Up. +--- + +Trabajar con documentos PDF incluye varias funciones. Gestionar las páginas de un archivo PDF es una parte importante de este trabajo. 'aspose.pdf.facades' proporciona el `PdfFileEditor` clase para este propósito. + +La clase PdfFileEditor contiene los métodos que ayudan a manipular páginas individuales; esta clase no edita ni manipula el contenido de una página. Puede insertar una nueva página, eliminar una página existente, dividir las páginas o especificar la imposición de las páginas usando PdfFileEditor. + +## Qué puedes hacer con PdfFileEditor + +Las características proporcionadas por esta clase pueden agruparse en flujos de trabajo de edición de páginas, imposición de PDF y división de documentos. Estos artículos muestran cómo reorganizar páginas, combinar varios PDF, preparar archivos para impresión y extraer secciones de documentos existentes sin editar manualmente el archivo fuente. + +## Tutoriales de PdfFileEditor + +- [Diseño de página y márgenes](/pdf/es/python-net/page-layout-and-margins/) +- [Gestión de páginas](/pdf/es/python-net/page-management/) +- [Concatenar o combinar archivos PDF](/pdf/es/python-net/page-merging/) +- [Dividir documentos PDF](/pdf/es/python-net/splitting-pdf-documents/) +- [Diseño de folleto y N-Up](/pdf/es/python-net/booklet-and-nup-layout/) diff --git a/es/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md b/es/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md new file mode 100644 index 000000000..b4e631d58 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md @@ -0,0 +1,22 @@ +--- +title: Diseño de folleto y N-Up +linktitle: Diseño de folleto y N-Up +type: docs +weight: 10 +url: /es/python-net/booklet-and-nup-layout/ +description: Preparar PDFs para impresión a menudo requiere reorganizar páginas en diseños específicos, como folletos o cuadrículas N-Up. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Crear diseños de folleto y N-Up para documentos PDF en Python +Abstract: Aprenda a transformar los diseños de página PDF usando Aspose.PDF for Python. Esta guía explica cómo generar documentos estilo folleto y crear diseños N-Up que colocan múltiples páginas en una sola hoja. Estas técnicas ayudan a optimizar los documentos para impresión, reducir el consumo de papel y crear salidas PDF compactas. +--- + +Las funciones de folleto y N-Up ayudan a preparar documentos PDF para impresión y presentación compacta de páginas. Estos flujos de trabajo reorganizan el orden de las páginas o colocan múltiples páginas de origen en una sola hoja, lo que es útil para folletos, borradores y salida de folleto listo para imprimir. + +## Tutoriales de transformación de diseños + +- [Crear documento PDF N-Up](/pdf/es/python-net/create-n-up-pdf-document/) +- [Crear folleto PDF](/pdf/es/python-net/create-pdf-booklet/) diff --git a/es/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md b/es/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md new file mode 100644 index 000000000..6843c115d --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md @@ -0,0 +1,85 @@ +--- +title: Crear documento PDF N-Up +linktitle: Crear documento PDF N-Up +type: docs +weight: 10 +url: /es/python-net/create-n-up-pdf-document/ +description: Aprenda cómo crear un documento PDF N-Up mientras maneja de forma segura posibles errores usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Crear un diseño PDF N-Up en Python +Abstract: Aprenda cómo generar un diseño PDF N-Up usando Aspose.PDF for Python. Este ejemplo demuestra cómo combinar varias páginas de un documento PDF en una sola página usando el método 'make_n_up' o 'try_make_n_up' de la clase PdfFileEditor. +--- + +Un diseño N-Up coloca varias páginas de un documento PDF en una sola página en formato de cuadrícula. Este diseño se utiliza a menudo para imprimir presentaciones, folletos o informes donde se pueden ver varias páginas a la vez. + +Con Aspose.PDF for Python, los desarrolladores pueden crear rápidamente un documento N-Up especificando el número de filas y columnas que determinan cuántas páginas originales aparecen en cada página de salida. + +En este fragmento de código, el método 'make_n_up' de la [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) clase organiza las páginas del PDF de entrada en una cuadrícula de 2 × 2, lo que significa que cuatro páginas originales aparecen en una sola página en el documento de salida. + +En el ejemplo mostrado, el diseño utiliza 2 filas y 2 columnas, produciendo cuatro páginas por hoja: + +1. Abra el archivo PDF de origen. +1. Cree una instancia de PdfFileEditor. +1. Especifique el número de filas y columnas para el diseño N-Up. +1. Genere un nuevo PDF con las páginas combinadas. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Create N-Up PDF Document +def create_nup_pdf_document(infile, outfile): + # Create NUpMaker object + nup_maker = pdf_facades.PdfFileEditor() + # Make N-Up layout from input PDF file and save to output PDF file + nup_maker.make_n_up( + FileIO(infile), FileIO(outfile, "w"), 2, 2 + ) # 2 rows and 2 columns for N-Up layout +``` + +Aspose.PDF for Python via .NET le permite generar diseños N-Up con la clase PdfFileEditor. El método 'try_make_n_up' funciona de manera similar a make_n_up, pero en lugar de lanzar una excepción cuando una operación falla, devuelve un valor booleano que indica si el proceso tuvo éxito. + +El diseño N-Up organiza varias páginas PDF en una sola página mediante una cuadrícula definida por filas y columnas. + +El método 'try_make_n_up' ofrece una forma más segura de realizar esta operación porque: + +- Devuelve True si el diseño se crea correctamente +- Devuelve False si la operación falla +- No interrumpe la ejecución del programa con excepciones + +En el ejemplo a continuación, el documento se organiza usando una cuadrícula de 2 × 2, lo que coloca cuatro páginas originales en cada página de salida. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Create N-Up PDF Document +def try_create_nup_pdf_document(infile, outfile): + # Create NUpMaker object + nup_maker = pdf_facades.PdfFileEditor() + # Make N-Up layout from input PDF file and save to output PDF file + if not nup_maker.try_make_n_up(FileIO(infile), FileIO(outfile, "w"), 2, 2): + print("Failed to create N-Up PDF document.") +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md b/es/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md new file mode 100644 index 000000000..233e22a8e --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md @@ -0,0 +1,82 @@ +--- +title: Crear folleto PDF +linktitle: Crear folleto PDF +type: docs +weight: 20 +url: /es/python-net/create-pdf-booklet/ +description: Generar un PDF con estilo de folleto a partir de un documento existente usando Aspose.PDF para Python +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Crear un folleto PDF a partir de un PDF existente usando Python +Abstract: Aprenda cómo generar un PDF con estilo de folleto a partir de un documento existente usando Aspose.PDF para Python. Este ejemplo muestra cómo utilizar la clase PdfFileEditor para reorganizar las páginas de modo que puedan imprimirse y plegarse como un folleto. El método ordena automáticamente las páginas para producir un diseño de folleto correcto. +--- + +Crear documentos con estilo de folleto es un requisito común al preparar PDFs para impresión. En un diseño de folleto, las páginas se reorganizan de modo que, al imprimirse y plegarse, aparezcan en el orden correcto. + +Usando Aspose.PDF para Python, los desarrolladores pueden convertir fácilmente un PDF estándar en un folleto usando el [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) class. El método \u0027make_booklet\u0027 reorganiza automáticamente las páginas del documento de entrada y genera un nuevo PDF optimizado para la impresión de folletos. + +1. Abra un documento PDF existente. +1. Cree una instancia de PdfFileEditor. +1. Utiliza el método make_booklet para reorganizar las páginas. +1. Guarda la salida como un archivo PDF listo para folleto. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Create PDF Booklet +def create_pdf_booklet(infile, outfile): + # Create BookletMaker object + booklet_maker = pdf_facades.PdfFileEditor() + # Make booklet from input PDF file and save to output PDF file + booklet_maker.make_booklet(FileIO(infile), FileIO(outfile, "w")) +``` + +Este fragmento de código muestra cómo usar el método ‘try_make_booklet’ de la [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) clase para reorganizar páginas para la impresión de folletos sin lanzar excepciones si la operación falla. + +Un diseño de folleto reorganiza las páginas de modo que, al imprimir y doblar, el documento se lea en el orden correcto. Automatizar este proceso garantiza resultados consistentes y elimina la necesidad de reorganizar manualmente las páginas. + +El método ‘try_make_booklet’ funciona de manera similar a ‘make_booklet’, pero con una diferencia importante: + +- 'make_booklet' lanza una excepción si la operación falla. +- 'try_make_booklet' devuelve True o False, permitiendo a los desarrolladores gestionar los errores de forma más segura. + +1. Abra un documento PDF existente. +1. Cree una instancia de PdfFileEditor. +1. Intentar crear el folleto. +1. Manejar el resultado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def try_create_pdf_booklet(infile, outfile): + # Create BookletMaker object + booklet_maker = pdf_facades.PdfFileEditor() + # Make booklet from input PDF file and save to output PDF file + # The try_make_booklet method is like the make_booklet method, + # except the try_make_booklet method does not throw an exception if the operation fails. + if not booklet_maker.try_make_booklet(FileIO(infile), FileIO(outfile, "w")): + print("Failed to create booklet.") +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md b/es/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md new file mode 100644 index 000000000..f18e0b7a4 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md @@ -0,0 +1,19 @@ +--- +title: Diseño de página y márgenes +linktitle: Diseño de página y márgenes +type: docs +weight: 20 +url: /es/python-net/page-layout-and-margins/ +description: Gestionar el diseño de las páginas PDF es una parte importante de los flujos de trabajo de procesamiento de documentos. Los desarrolladores a menudo necesitan ajustar los márgenes, redimensionar el contenido de la página o insertar saltos de página para garantizar que los documentos cumplan con los requisitos de formato o los estándares de impresión. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Editar el diseño de página PDF en Python - Añadir márgenes, redimensionar contenido e insertar saltos de página +Abstract: Aprenda cómo modificar los diseños de página PDF usando Aspose.PDF for Python. Esta guía explica cómo añadir márgenes a páginas específicas, redimensionar el contenido de las páginas e insertar saltos de página de forma programática. Estas funciones permiten a los desarrolladores ajustar el formato del documento, mejorar la legibilidad y preparar los PDFs para impresión o diseños estructurados. +--- + +- [Agregar márgenes a las páginas PDF](/pdf/es/python-net/add-margins-to-pdf-pages/) +- [Redimensionar el contenido de las páginas PDF](/pdf/es/python-net/resize-pdf-page-contents/) +- [Agregar saltos de página en PDF](/pdf/es/python-net/add-page-breaks-in-pdf/) \ No newline at end of file diff --git a/es/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md b/es/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md new file mode 100644 index 000000000..00266efe8 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md @@ -0,0 +1,52 @@ +--- +title: Agregar márgenes a las páginas PDF +linktitle: Agregar márgenes a las páginas PDF +type: docs +weight: 10 +url: /es/python-net/add-margins-to-pdf-pages/ +description: Agregar márgenes personalizados a páginas seleccionadas de un PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar márgenes personalizados a páginas PDF específicas en Python +Abstract: Aprenda cómo agregar márgenes personalizados a páginas seleccionadas de un PDF usando Aspose.PDF for Python. Este ejemplo muestra cómo expandir los límites de la página especificando márgenes superior, inferior, izquierdo y derecho para páginas individuales, haciendo que los PDFs sean más imprimibles o visualmente consistentes. +--- + +Agregar márgenes a las páginas PDF puede mejorar la legibilidad, preparar documentos para impresión o asignar espacio para anotaciones. Usando Aspose.PDF for Python, los desarrolladores pueden agregar márgenes a páginas específicas de un PDF de forma programática sin modificar el diseño del contenido. + +En este fragmento de código, el [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) class se usa para añadir márgenes de 0.5 pulgadas a las páginas 1 y 3 del documento de entrada. Los márgenes se definen en puntos (1 pulgada = 72 puntos) y se aplican individualmente a la izquierda, derecha, arriba y abajo de cada página. + +1. Abra el documento PDF de origen. +1. Cree una instancia de 'PdfFileEditor'. +1. Defina los márgenes y las páginas a modificar. +1. Aplique los márgenes usando el método 'add_margins'. +1. Guarde el PDF actualizado en el archivo de salida. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Add Margins to PDF Pages +def add_margins_to_pdf_pages(infile, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + # Define the margins to be added (in points) + left_margin = 36 # 0.5 inch + right_margin = 36 # 0.5 inch + top_margin = 36 # 0.5 inch + bottom_margin = 36 # 0.5 inch + + pdf_editor.add_margins( + infile, outfile, [1, 3], left_margin, right_margin, top_margin, bottom_margin + ) +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md b/es/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md new file mode 100644 index 000000000..7a62359de --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md @@ -0,0 +1,48 @@ +--- +title: Agregar saltos de página en PDF +linktitle: Agregar saltos de página en PDF +type: docs +weight: 20 +url: /es/python-net/add-page-breaks-in-pdf/ +description: Insertar saltos de página en un documento PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar saltos de página a páginas PDF programáticamente en Python +Abstract: Aprenda cómo insertar saltos de página en un documento PDF usando Aspose.PDF for Python. Este ejemplo demuestra cómo dividir una página en una posición vertical especificada, permitiendo a los desarrolladores reorganizar el contenido y crear páginas adicionales de forma dinámica. +--- + +Los saltos de página son útiles cuando necesita dividir páginas PDF largas en varias páginas o controlar cómo se distribuye el contenido a lo largo de un documento. Usando Aspose.PDF for Python, los desarrolladores pueden insertar saltos de página en posiciones específicas sin editar manualmente el PDF. + +Este artículo muestra cómo usar el método 'add_page_break' de [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) clase para insertar un salto de página en una coordenada vertical definida en una página seleccionada. El método crea una nueva página y mueve el contenido que está debajo del punto de salto a esa página. + +1. Crear un objeto PdfFileEditor. +1. Definir la posición del salto de página. +1. Insertar el salto de página. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Add Page Breaks in PDF +def add_page_breaks_in_pdf(infile, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.add_page_break( + infile, + outfile, + [ + pdf_facades.PdfFileEditor.PageBreak(1, 400), + ], + ) +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md b/es/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md new file mode 100644 index 000000000..e6bcded49 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md @@ -0,0 +1,51 @@ +--- +title: Redimensionar el contenido de las páginas PDF +linktitle: Redimensionar el contenido de las páginas PDF +type: docs +weight: 30 +url: /es/python-net/resize-pdf-page-contents/ +description: Redimensionar el contenido de páginas PDF específicas usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Redimensionar el contenido de páginas PDF programáticamente en Python +Abstract: Aprende cómo redimensionar el contenido de páginas PDF específicas usando Aspose.PDF for Python. Este ejemplo demuestra cómo ajustar el ancho y la altura del contenido de la página mientras se preserva la estructura del documento, facilitando la optimización de diseños para impresión o visualización. +--- + +Ajustar el tamaño del contenido de una página PDF es a menudo necesario al preparar documentos para impresión, encajar contenido en un diseño específico o estandarizar formatos de página en todo un documento. Con Aspose.PDF for Python, los desarrolladores pueden redimensionar el contenido de páginas seleccionadas programáticamente sin editar manualmente el documento. + +Este artículo muestra cómo usar el método 'resize_contents' de [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) clase para modificar las dimensiones del contenido de la página para páginas específicas en un archivo PDF. Al especificar el ancho y la altura objetivo, el contenido de las páginas seleccionadas se redimensiona en consecuencia. + +1. Crear un objeto PdfFileEditor. +1. Redimensionar contenidos de la página. + +Parámetros: + +- [1, 3] – lista de números de página cuyo contenido será redimensionado. +- 400 – el nuevo ancho del contenido de la página (en puntos). +- 750 – la nueva altura del contenido de la página (en puntos). + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Resize PDF Page Contents +def resize_pdf_page_contents(infile, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + + if not pdf_editor.resize_contents( + FileIO(infile), FileIO(outfile, "w"), [1, 3], 400, 750 + ): + raise Exception("Failed to resize PDF page contents.") +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/page-managment/_index.md b/es/python-net/working-with-facades/pdffileeditor/page-managment/_index.md new file mode 100644 index 000000000..f792237c9 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/page-managment/_index.md @@ -0,0 +1,26 @@ +--- +title: Gestión de páginas +linktitle: Gestión de páginas +type: docs +weight: 30 +url: /es/python-net/page-management/ +description: Gestionar páginas PDF de forma programática permite a los desarrolladores modificar documentos sin edición manual. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Gestionar páginas PDF programáticamente en Python - Extraer, Eliminar, Insertar y Anexar +Abstract: Aprenda a realizar operaciones a nivel de página en documentos PDF usando Aspose.PDF for Python. Esta guía muestra cómo extraer páginas específicas, eliminar páginas no deseadas, insertar páginas de otro PDF y anexar páginas a un documento existente, lo que permite una gestión de páginas PDF eficiente y automatizada. +--- + +Las tareas de gestión de páginas son fundamentales en muchos flujos de trabajo PDF. Con Aspose.PDF for Python, puede reorganizar la estructura del documento, eliminar páginas innecesarias y combinar contenido de múltiples PDFs mientras mantiene intacto el contenido original de la página. + +## Operaciones comunes de gestión de páginas + +Utilice los siguientes tutoriales para manejar las tareas de edición a nivel de página más comunes con `PdfFileEditor`: + +- [Extraer páginas de PDF](/pdf/es/python-net/extract-pages-from-pdf/) +- [Eliminar páginas de PDF](/pdf/es/python-net/delete-pages-from-pdf/) +- [Insertar páginas en PDF](/pdf/es/python-net/insert-pages-into-pdf/) +- [Agregar páginas al PDF](/pdf/es/python-net/append-pages-to-pdf/) diff --git a/es/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md b/es/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md new file mode 100644 index 000000000..2dc1b140a --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md @@ -0,0 +1,43 @@ +--- +title: Agregar páginas al PDF +linktitle: Agregar páginas al PDF +type: docs +weight: 10 +url: /es/python-net/append-pages-to-pdf/ +description: Agregar páginas de un documento PDF a otro usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar páginas de un PDF a otro en Python +Abstract: Aprenda cómo agregar páginas de un documento PDF a otro usando Aspose.PDF for Python. Este ejemplo demuestra cómo usar la clase PdfFileEditor para combinar páginas de varios PDFs y crear un documento de salida único. +--- + +Combinar páginas de diferentes documentos PDF es un requisito común en los flujos de trabajo de procesamiento de documentos. Usando Aspose.PDF for Python, los desarrolladores pueden agregar fácilmente páginas de uno o más archivos PDF a un documento existente. + +Este fragmento de código muestra cómo usar el método append de [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) clase para agregar páginas seleccionadas de otro archivo PDF al final de un PDF de origen. Al especificar el rango de páginas, los desarrolladores pueden controlar exactamente qué páginas se incluyen en el documento final. + +1. Crear un objeto PdfFileEditor. +1. Agregar páginas de otro PDF. + +Las páginas especificadas del documento PDF secundario se añaden al final del PDF original, creando un archivo de salida combinado. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +# Append Pages to PDF +def append_pages_to_pdf(infile, sample_file, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + # Append pages from the specified PDF document to the end of the source PDF document + pdf_editor.append(infile, [sample_file], 1, 2, outfile) +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md b/es/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md new file mode 100644 index 000000000..4d3280c1d --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md @@ -0,0 +1,47 @@ +--- +title: Eliminar páginas de PDF +linktitle: Eliminar páginas de PDF +type: docs +weight: 20 +url: /es/python-net/delete-pages-from-pdf/ +description: Eliminar páginas seleccionadas de un documento PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Eliminar páginas específicas de un documento PDF en Python +Abstract: Aprenda cómo eliminar páginas seleccionadas de un documento PDF usando Aspose.PDF for Python. Este ejemplo demuestra cómo eliminar páginas específicas de un archivo PDF existente de forma programática, creando un nuevo documento sin las páginas eliminadas. +--- + +A veces los documentos PDF contienen páginas innecesarias o sensibles que deben eliminarse. Usando Aspose.PDF for Python, los desarrolladores pueden eliminar programáticamente páginas específicas de un PDF sin editar manualmente el archivo. + +Nuestro ejemplo muestra cómo usar el método delete de [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) clase para eliminar páginas de un documento PDF. Al especificar los números de página a borrar, puedes crear un nuevo PDF que excluya las páginas no deseadas. Esta funcionalidad es útil para limpiar informes, eliminar información confidencial o preparar extractos de documentos personalizados. + +1. Crear un objeto PdfFileEditor. +1. Definir páginas a eliminar. +1. Eliminar las páginas. + +```python + + import aspose.pdf as ap + import aspose.pdf.facades as pdf_facades + + import sys + from os import path + + sys.path.append(path.join(path.dirname(__file__), "..")) + from config import set_license, initialize_data_dir + + + # Delete Pages from PDF + def delete_pages_from_pdf(infile, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + + # Define the page numbers to be deleted (1-based index) + pages_to_delete = [2, 4] + + # Delete the specified pages from the PDF document + pdf_editor.delete(infile, pages_to_delete, outfile) +``` \ No newline at end of file diff --git a/es/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md b/es/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md new file mode 100644 index 000000000..76e8a477c --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md @@ -0,0 +1,46 @@ +--- +title: Extraer páginas de PDF +linktitle: Extraer páginas de PDF +type: docs +weight: 30 +url: /es/python-net/extract-pages-from-pdf/ +description: Extraer páginas seleccionadas de un documento PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Extraer páginas específicas de un documento PDF en Python +Abstract: Aprende cómo extraer páginas seleccionadas de un documento PDF usando Aspose.PDF for Python. Este ejemplo muestra cómo crear un nuevo PDF que contenga solo las páginas que necesitas, habilitando la creación personalizada de documentos y la manipulación a nivel de página. +--- + +Extraer páginas de un PDF es útil cuando necesitas crear un subconjunto de un documento, compartir solo contenido específico o reorganizar PDFs para presentaciones, informes o impresión. Usando Aspose.PDF for Python, los desarrolladores pueden extraer programáticamente páginas de un archivo PDF y guardarlas como un nuevo documento. + +Aprende cómo usar el método extract de la [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) clase. Al especificar una lista de páginas a extraer, puedes generar un nuevo PDF que contenga solo las páginas seleccionadas mientras se preserva el contenido y el formato original. + +1. Crear un objeto PdfFileEditor. +1. Definir páginas a extraer. +1. Extraer las páginas. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +# Extract Pages from PDF +def extract_pages_from_pdf(infile, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + + # Define the page numbers to be extracted (1-based index) + pages_to_extract = [1, 4, 3] + + # Extract the specified pages from the PDF document and save to a new PDF document + pdf_editor.extract(infile, pages_to_extract, outfile) +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md b/es/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md new file mode 100644 index 000000000..83ce02b90 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md @@ -0,0 +1,45 @@ +--- +title: Insertar páginas en PDF +linktitle: Insertar páginas en PDF +type: docs +weight: 40 +url: /es/python-net/insert-pages-into-pdf/ +description: Insertar páginas de un PDF a otro usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Insertar páginas de otro PDF en un PDF existente en Python +Abstract: Aprenda cómo insertar páginas de un PDF a otro usando Aspose.PDF for Python. Este ejemplo demuestra cómo agregar páginas seleccionadas de un PDF secundario en una posición específica del documento original, creando un PDF combinado con una colocación precisa de páginas. +--- + +Insertar páginas en un PDF existente es un requisito común al combinar documentos, agregar contenido o reorganizar informes. Usando Aspose.PDF for Python, los desarrolladores pueden insertar páginas de un PDF a otro de forma programática en una ubicación especificada. + +Este artículo muestra cómo usar el método insert del [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) clase. Al especificar los números de página a insertar y la ubicación de destino, puedes combinar contenido de diferentes PDFs manteniendo el formato y la estructura originales. + +1. Crear un objeto PdfFileEditor. +1. Define la posición de inserción y las páginas. +1. Insertar páginas. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +# Insert Pages into PDF +def insert_pages_into_pdf(infile, sample_file, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + + # Define the page number where new pages will be inserted (1-based index) + insert_page_number = 2 + + pdf_editor.insert(infile, insert_page_number, sample_file, [1, 2], outfile) +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/page-merging/_index.md b/es/python-net/working-with-facades/pdffileeditor/page-merging/_index.md new file mode 100644 index 000000000..c3377f50d --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/page-merging/_index.md @@ -0,0 +1,23 @@ +--- +title: Combinar archivos PDF +linktitle: Combinar archivos PDF +type: docs +weight: 40 +url: /es/python-net/page-merging/ +description: Combinar documentos PDF es un requisito común en flujos de trabajo automatizados, generación de informes y gestión de documentos. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Combinar archivos PDF en Python - Unir dos o varios PDFs con Aspose.PDF +Abstract: Aprenda cómo concatenar archivos PDF de forma programática usando Aspose.PDF for Python. Esta guía muestra métodos para combinar dos o varios PDFs, gestionar un gran número de archivos, optimizar la salida y concatenar formularios PDF con sufijos únicos para evitar conflictos de nombres. +--- + +- [Concatenar dos archivos PDF](/pdf/es/python-net/concatenate-two-files/) +- [Concatenar varios archivos PDF](/pdf/es/python-net/concatenate-pdf-files/) +- [Intentar concatenar dos archivos PDF](/pdf/es/python-net/try-concatenate-two-files/) +- [Pruebe concatenar varios archivos PDF](/pdf/es/python-net/try-concatenate-pdf-files/) +- [Concatenar gran número de archivos PDF](/pdf/es/python-net/concatenate-large-number-files/) +- [Concatenar archivos PDF con optimización](/pdf/es/python-net/concatenate-pdf-files-with-optimization/) +- [Concatenar formularios PDF con sufijo único](/pdf/es/python-net/concatenate-pdf-forms/) \ No newline at end of file diff --git a/es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md b/es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md new file mode 100644 index 000000000..470a6b7a1 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md @@ -0,0 +1,38 @@ +--- +title: Concatenar gran número de archivos PDF +linktitle: Concatenar gran número de archivos PDF +type: docs +weight: 10 +url: /es/python-net/concatenate-large-number-files/ +description: Combinar un gran número de archivos PDF de manera eficiente usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Concatenar archivos PDF grandes en Python usando buffer de disco +Abstract: Aprenda cómo combinar un gran número de archivos PDF de manera eficiente usando Aspose.PDF for Python. Este ejemplo demuestra cómo habilitar el buffer de disco para manejar PDFs grandes sin agotar la memoria del sistema, asegurando una concatenación fluida de muchos archivos. +--- + +Al trabajar con colecciones grandes de archivos PDF, el consumo de memoria puede convertirse en un cuello de botella durante la concatenación. Usando Aspose.PDF for Python, puedes habilitar el buffer de disco en el [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) clase para combinar muchos PDFs de manera eficiente. El método concatenate combina los archivos de entrada en un único PDF mientras que el buffer de disco evita un uso elevado de memoria. Este enfoque es ideal para procesar documentos en masa, generación automática de informes o consolidar archivos PDF grandes. + +1. Crear un objeto PdfFileEditor. +1. Combina varios archivos PDF. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +def concatenate_large_number_files(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.use_disk_buffer = True # Enable disk buffering for large files + pdf_editor.concatenate(files_to_merge, output_file) +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md b/es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md new file mode 100644 index 000000000..64547fb33 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md @@ -0,0 +1,38 @@ +--- +title: Concatenar archivos PDF con optimización +linktitle: Concatenar archivos PDF con optimización +type: docs +weight: 30 +url: /es/python-net/concatenate-pdf-files-with-optimization/ +description: Concatenar varios archivos PDF en un único PDF optimizado usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Combinar archivos PDF con salida optimizada en Python +Abstract: Aprenda cómo concatenar varios archivos PDF en un único PDF optimizado usando Aspose.PDF for Python. Este ejemplo muestra cómo habilitar la optimización de tamaño para reducir el tamaño del archivo de salida mientras se preserva el contenido y el formato. +--- + +Al combinar varios PDFs, el archivo resultante puede volverse grande, especialmente si contiene imágenes o contenido complejo. Usando Aspose.PDF for Python, los desarrolladores pueden habilitar la optimización durante la concatenación para reducir el tamaño del archivo sin perder calidad. La propiedad optimize_size en el [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) clase garantiza que el PDF combinado sea compacto y eficiente, haciéndolo adecuado para compartir, almacenar o archivar. + +1. Crear un objeto PdfFileEditor y habilitar la optimización. +1. Combinar archivos PDF. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +def concatenate_pdf_files_with_optimization(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.optimize_size = True # Enable optimization for smaller output file size + pdf_editor.concatenate(files_to_merge, output_file) +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md b/es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md new file mode 100644 index 000000000..ff1b2c1df --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md @@ -0,0 +1,37 @@ +--- +title: Concatenar varios archivos PDF +linktitle: Concatenar varios archivos PDF +type: docs +weight: 20 +url: /es/python-net/concatenate-pdf-files/ +description: Combina varios archivos PDF en un solo documento usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Fusionar varios archivos PDF en un solo PDF en Python +Abstract: Aprende cómo combinar varios archivos PDF en un solo documento usando Aspose.PDF for Python. Este ejemplo muestra cómo usar el método concatenate para fusionar varios PDFs sin problemas mientras se preservan su contenido y formato. +--- + +Fusionar archivos PDF es una tarea común en la gestión de documentos, la generación de informes y los flujos de trabajo automatizados. Usando Aspose.PDF for Python, los desarrolladores pueden combinar fácilmente varios archivos PDF en un documento consolidado único. El método concatenate de la [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) clase garantiza que todas las páginas de los archivos de entrada se conserven en el resultado final, manteniendo su diseño y contenido original. Este enfoque es útil para crear informes completos, combinar formularios o archivar varios documentos de manera eficiente. + +1. Crear un objeto PdfFileEditor. +1. Combinar varios archivos PDF. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +def concatenate_pdf_files(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.concatenate(files_to_merge, output_file) +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md b/es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md new file mode 100644 index 000000000..7bf8b105a --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md @@ -0,0 +1,40 @@ +--- +title: Concatenar formularios PDF con sufijo único +linktitle: Concatenar formularios PDF con sufijo único +type: docs +weight: 50 +url: /es/python-net/concatenate-pdf-forms/ +description: Concatenar varios formularios PDF usando Aspose.PDF for Python garantizando nombres de campos de formulario únicos. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Combinar formularios PDF en Python evitando conflictos de nombres de campos +Abstract: Aprenda cómo concatenar varios formularios PDF usando Aspose.PDF for Python garantizando nombres de campos de formulario únicos. Este ejemplo muestra cómo establecer un sufijo personalizado para evitar conflictos de nombres al combinar PDFs que contienen campos de formulario interactivos. +--- + +Combinar formularios PDF puede generar conflictos si varios archivos contienen campos con el mismo nombre. Usando Aspose.PDF for Python, los desarrolladores pueden asignar un sufijo único a los campos de formulario durante la concatenación. La propiedad unique_suffix en el [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) la clase renombra automáticamente los campos conflictivos, preservando la interactividad y garantizando que todos los datos del formulario sigan funcionando. Este enfoque es ideal para combinar encuestas, solicitudes o cualquier documento PDF interactivo de forma programática. + +1. Crear un objeto PdfFileEditor y establecer un sufijo único. +1. Combinar formularios PDF. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +def concatenate_pdf_forms(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.unique_suffix = ( + "_xy_%NUM%" # Set a unique suffix to avoid form field name conflicts + ) + pdf_editor.concatenate(files_to_merge, output_file) +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md b/es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md new file mode 100644 index 000000000..3ee51f2ec --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md @@ -0,0 +1,37 @@ +--- +title: Concatenar dos archivos PDF +linktitle: Concatenar dos archivos PDF +type: docs +weight: 60 +url: /es/python-net/concatenate-two-files/ +description: Concatenar dos archivos PDF en un solo documento usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Fusionar dos archivos PDF en un único PDF en Python +Abstract: Aprenda cómo concatenar dos archivos PDF en un solo documento usando Aspose.PDF for Python. Este ejemplo demuestra cómo fusionar dos PDFs sin problemas mientras se preserva su contenido y formato original. +--- + +Combinar dos archivos PDF es una tarea común al consolidar informes, contratos o formularios. Usando Aspose.PDF for Python, puede fusionar programáticamente dos PDFs en un solo documento usando el método concatenate de la [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) clase. Esto asegura que todas las páginas de ambos archivos se incluyan en el PDF de salida mientras se mantiene el diseño, contenido y estructura originales. + +1. Crear un objeto PdfFileEditor. +1. Combinar dos archivos PDF. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +def concatenate_two_files(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.concatenate(files_to_merge[0], files_to_merge[1], output_file) +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md b/es/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md new file mode 100644 index 000000000..0b438af37 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md @@ -0,0 +1,38 @@ +--- +title: Intentar concatenar archivos PDF +linktitle: Intentar concatenar archivos PDF +type: docs +weight: 70 +url: /es/python-net/try-concatenate-pdf-files/ +description: Concatenar varios archivos PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Fusionar archivos PDF de forma segura en Python con manejo de errores +Abstract: Aprenda cómo concatenar varios archivos PDF de forma segura usando Aspose.PDF for Python. El método try_concatenate intenta fusionar los PDF sin lanzar excepciones, lo que permite a los desarrolladores manejar fallas de forma elegante. +--- + +La fusión de archivos PDF a veces puede fallar debido a archivos corruptos, formatos incompatibles u otros problemas. Usando Aspose.PDF for Python, puede utilizar el método try_concatenate del [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) clase para intentar la concatenación de forma segura. En lugar de lanzar una excepción, el método devuelve False si la operación falla, permitiendo un manejo de errores controlado en flujos de trabajo automatizados. + +1. Crear un objeto PdfFileEditor. +1. Intentar concatenar archivos PDF. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +def try_concatenate_pdf_files(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + if not pdf_editor.try_concatenate(files_to_merge, output_file): + print("Concatenation failed for the provided files.") +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md b/es/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md new file mode 100644 index 000000000..c4579323e --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md @@ -0,0 +1,40 @@ +--- +title: Intente concatenar dos archivos PDF +linktitle: Intente concatenar dos archivos PDF +type: docs +weight: 90 +url: /es/python-net/try-concatenate-two-files/ +description: Concatene dos archivos PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Fusionar de forma segura dos archivos PDF en Python sin excepciones +Abstract: Aprenda cómo concatenar de forma segura dos archivos PDF usando Aspose.PDF for Python. El método try_concatenate une los archivos sin generar excepciones, lo que permite un manejo de errores elegante en caso de que la operación falle. +--- + +Fusionar dos archivos PDF a veces puede fallar debido a corrupción del archivo, formatos incompatibles u otros problemas. Usando Aspose.PDF for Python, el método try_concatenate de la clase PdfFileEditor le permite intentar fusionar dos PDF de forma segura. Si la operación falla, devuelve False en lugar de lanzar una excepción, dándole control total sobre el manejo de errores en flujos de trabajo automatizados o procesamiento por lotes. + +1. Crear un objeto PdfFileEditor. +1. Intente fusionar dos archivos PDF. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +def try_concatenate_two_files(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + if not pdf_editor.try_concatenate( + files_to_merge[0], files_to_merge[1], output_file + ): + print("Concatenation failed for the provided files.") +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md b/es/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md new file mode 100644 index 000000000..aa9199d30 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md @@ -0,0 +1,23 @@ +--- +title: Dividir documentos PDF +linktitle: Dividir documentos PDF +type: docs +weight: 50 +url: /es/python-net/splitting-pdf-documents/ +description: Dividir PDFs es un requisito común para la gestión de documentos, la generación de informes y los flujos de trabajo de automatización. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Dividir documentos PDF en Python - Desde el principio, hasta el final, o en un solo archivo +Abstract: Aprende cómo dividir documentos PDF programáticamente usando Aspose.PDF for Python. Esta guía muestra métodos para extraer páginas desde el comienzo o el final, dividir un PDF en varios documentos, o dividirlo en PDFs de una sola página para una gestión de documentos flexible. +--- + +Dividir documentos PDF es útil cuando necesitas extraer secciones seleccionadas, distribuir páginas individuales o dividir archivos grandes en unidades más pequeñas para su almacenamiento y procesamiento. Aspose.PDF for Python proporciona varias `PdfFileEditor` métodos para manejar estos escenarios de manera eficiente. + +## Tutoriales de división de PDF + +- [Dividir PDF desde el comienzo](/pdf/es/python-net/split-pdf-from-beginning/) +- [Dividir PDF hasta el final](/pdf/es/python-net/split-pdf-to-end/) +- [Dividir PDF en páginas individuales](/pdf/es/python-net/split-pdf-into-single-pages/) diff --git a/es/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md b/es/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md new file mode 100644 index 000000000..d90185266 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md @@ -0,0 +1,38 @@ +--- +title: Dividir PDF desde el comienzo +linktitle: Dividir PDF desde el comienzo +type: docs +weight: 10 +url: /es/python-net/split-pdf-from-beginning/ +description: Divida un documento PDF desde el principio utilizando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Dividir PDF desde el Inicio en Python usando Aspose.PDF +Abstract: Aprenda cómo dividir un documento PDF desde el principio utilizando Aspose.PDF for Python. Este ejemplo demuestra la extracción de un número específico de páginas comenzando desde la primera página para crear un nuevo documento PDF. +--- + +Dividir PDFs desde el principio es útil cuando necesita las primeras páginas de un documento como un archivo separado. Usando Aspose.PDF for Python, el método split_from_first en el [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) La clase le permite extraer un número definido de páginas a partir de la página uno. Esta función es ideal para generar extractos, vistas previas o secciones más pequeñas de un PDF más grande sin editar manualmente el archivo original. + +1. Crear un objeto PdfFileEditor. +1. Dividir PDF desde la primera página. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Split PDF from Beginning +def split_pdf_from_beginning(input_pdf_path, output_pdf_path): + pdf_file_editor = pdf_facades.PdfFileEditor() + pdf_file_editor.split_from_first(input_pdf_path, 3, output_pdf_path) +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md b/es/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md new file mode 100644 index 000000000..f379cee7c --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md @@ -0,0 +1,38 @@ +--- +title: Dividir PDF en páginas individuales +linktitle: Dividir PDF en páginas individuales +type: docs +weight: 30 +url: /es/python-net/split-pdf-into-single-pages/ +description: Divida el documento PDF en PDFs de una sola página usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Dividir un PDF en páginas individuales en Python +Abstract: Aprenda cómo dividir un documento PDF en PDFs de una sola página usando Aspose.PDF for Python. Este método extrae cada página del PDF original y la guarda como un archivo separado para una gestión y procesamiento flexibles del documento. +--- + +Dividir un PDF en páginas individuales es útil para procesamiento a nivel de página, impresión o distribución de secciones de un documento individualmente. Usando Aspose.PDF for Python, el método 'split_to_pages' del [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) clase crea archivos PDF separados para cada página en el documento de origen. Este enfoque permite la extracción automatizada de páginas para archivado, revisión o compartición individual, mientras se conserva el diseño y contenido original. + +1. Crear un objeto PdfFileEditor. +1. Dividir PDF en páginas individuales. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Split PDF into Single Pages +def split_pdf_into_single_pages(input_pdf_path, output_pdf_path): + pdf_file_editor = pdf_facades.PdfFileEditor() + pdf_file_editor.split_to_pages(input_pdf_path, output_pdf_path) +``` diff --git a/es/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md b/es/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md new file mode 100644 index 000000000..3ae18db02 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md @@ -0,0 +1,38 @@ +--- +title: Dividir PDF hasta el final +linktitle: Dividir PDF hasta el final +type: docs +weight: 40 +url: /es/python-net/split-pdf-to-end/ +description: Divida un documento PDF desde una página dada hasta la última página usando Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Divida un PDF desde una página específica hasta el final en Python +Abstract: Aprenda cómo dividir un documento PDF desde una página dada hasta la última página usando Aspose.PDF for Python. Este ejemplo demuestra cómo extraer todas las páginas a partir de una página especificada para crear un nuevo archivo PDF. +--- + +Dividir un PDF desde una página específica hasta el final es útil cuando necesita la porción final de un documento como un archivo separado. Usando Aspose.PDF for Python, el método split_to_end de la [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) clase le permite extraer páginas comenzando desde cualquier número de página hasta la última página del documento. Esto es ideal para crear extractos, extraer capítulos o procesar partes de un PDF grande sin editarlo manualmente. + +1. Crear un objeto PdfFileEditor. +1. Dividir PDF desde una página específica hasta el final. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Split PDF to End +def split_pdf_to_end(input_pdf_path, output_pdf_path): + pdf_file_editor = pdf_facades.PdfFileEditor() + pdf_file_editor.split_to_end(input_pdf_path, 2, output_pdf_path) +``` diff --git a/es/python-net/working-with-facades/pdffileinfo/_index.md b/es/python-net/working-with-facades/pdffileinfo/_index.md new file mode 100644 index 000000000..2b8fe91b0 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileinfo/_index.md @@ -0,0 +1,26 @@ +--- +title: Clase PdfFileInfo +linktitle: Clase PdfFileInfo +type: docs +weight: 110 +url: /es/python-net/pdffileinfo-class/ +description: Aprenda cómo usar la clase PdfFileInfo en Aspose.PDF for Python via .NET para inspeccionar los metadatos de PDF, las propiedades del documento, los privilegios, los detalles de la versión y la información de las páginas. +lastmod: "2026-03-19" +draft: false +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Inspeccione los metadatos, propiedades e información de página de PDF en Python con PdfFileInfo +Abstract: Esta sección explica cómo usar la clase PdfFileInfo en Aspose.PDF for Python via .NET para inspeccionar los detalles del archivo PDF de forma programática. Aprenda cómo trabajar con los metadatos de PDF, las propiedades del documento, los privilegios, la información de versión y los datos a nivel de página en aplicaciones Python. +--- + +El `PdfFileInfo` La clase en Aspose.PDF Facades proporciona acceso a información de PDF a nivel de documento y de página sin requerir un análisis de bajo nivel. Es útil cuando necesitas inspeccionar los metadatos, recuperar las propiedades del documento, comprobar los privilegios o examinar las dimensiones y desplazamientos de la página en flujos de trabajo automatizados. + +## Qué puede hacer con PdfFileInfo + +Utilice los artículos en esta sección para explorar las principales capacidades de inspección de archivos del `PdfFileInfo` fachada: + +- [Administrar los metadatos PDF con PdfFileInfo](/pdf/es/python-net/pdf-metadata/) +- [Inspeccionar las propiedades del documento con PdfFileInfo](/pdf/es/python-net/document-properties/) +- [Recuperar información de la página con PdfFileInfo](/pdf/es/python-net/page-information/) diff --git a/es/python-net/working-with-facades/pdffileinfo/document-properties/_index.md b/es/python-net/working-with-facades/pdffileinfo/document-properties/_index.md new file mode 100644 index 000000000..059509311 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileinfo/document-properties/_index.md @@ -0,0 +1,19 @@ +--- +title: Propiedades del documento +linktitle: Propiedades del documento +type: docs +weight: 10 +url: /es/python-net/document-properties/ +description: Aprenda cómo acceder programáticamente a los metadatos de PDF usando Aspose.PDF for Python. Esta guía cubre cómo recuperar la versión de PDF y comprobar los privilegios del documento, incluidas los permisos para imprimir, copiar, modificar y rellenar formularios. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Obtener la versión de PDF y los privilegios del documento usando Aspose.PDF for Python +Abstract: Comprender los metadatos de un PDF es esencial para el procesamiento, el cumplimiento y la automatización de flujos de trabajo. Los números de versión de PDF indican las funciones compatibles y la compatibilidad, mientras que los privilegios del documento controlan acciones como imprimir, copiar contenido, modificar anotaciones o rellenar campos de formulario. Este tutorial demuestra cómo usar la clase PdfFileInfo en Aspose.PDF for Python. +--- + +- [Obtener versión del PDF](/pdf/es/python-net/get-pdf-version/) +- [Obtener privilegios del documento](/pdf/es/python-net/get-document-privileges/) \ No newline at end of file diff --git a/es/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md b/es/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md new file mode 100644 index 000000000..baf5267cf --- /dev/null +++ b/es/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md @@ -0,0 +1,60 @@ +--- +title: Obtener privilegios del documento +linktitle: Obtener privilegios del documento +type: docs +weight: 10 +url: /es/python-net/get-document-privileges/ +description: Aprenda cómo verificar programáticamente los privilegios de un documento PDF usando Aspose.PDF for Python. Este tutorial muestra cómo usar la clase PdfFileInfo para leer la configuración de seguridad del documento, como los permisos de impresión, copia o modificación. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Recuperar privilegios del documento PDF usando Aspose.PDF for Python +Abstract: Los documentos PDF pueden tener restricciones de seguridad que limitan acciones como imprimir, copiar, modificar o rellenar formularios. Al acceder a estos privilegios programáticamente, los desarrolladores pueden determinar qué operaciones están permitidas en un PDF. Esta guía muestra cómo usar la clase PdfFileInfo para recuperar los privilegios del documento PDF y mostrarlos en Python. +--- + +Los privilegios PDF controlan lo que los usuarios pueden y no pueden hacer con un documento. Los permisos comunes incluyen: + +- Impresión del documento +- Copiar contenido +- Modificar anotaciones o contenidos +- Rellenar campos de formulario +- Usar lectores de pantalla +- Ensambla o fusiona documentos + +Con Aspose.PDF for Python, puedes inspeccionar estas configuraciones programáticamente usando el [PdfFileInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileinfo/) clase. Esto es especialmente útil al trabajar con múltiples PDF en flujos de trabajo automatizados, verificando el cumplimiento o controlando el manejo de documentos en aplicaciones. + +1. Cargar un archivo PDF. +1. Recuperar sus privilegios de documento. +1. Mostrar qué acciones están permitidas para el documento. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def get_document_privileges(input_file_name): + pdf_metadata = pdf_facades.PdfFileInfo(input_file_name) + + privileges = pdf_metadata.get_document_privilege() + + print("Document Privileges:") + print(f" Can Print: {privileges.allow_print}") + print(f" Can Degraded Print: {privileges.allow_degraded_printing}") + print(f" Can Copy: {privileges.allow_copy}") + print(f" Can Modify Contents: {privileges.allow_modify_contents}") + print(f" Can Modify Annotations: {privileges.allow_modify_annotations}") + print(f" Can Fill In: {privileges.allow_fill_in}") + print(f" Can Screen Readers: {privileges.allow_screen_readers}") + print(f" Can Assembly: {privileges.allow_assembly}") +``` diff --git a/es/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md b/es/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md new file mode 100644 index 000000000..1f32974d4 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md @@ -0,0 +1,44 @@ +--- +title: Obtener versión del PDF +linktitle: Obtener versión del PDF +type: docs +weight: 20 +url: /es/python-net/get-pdf-version/ +description: Aprenda cómo determinar programáticamente la versión de un documento PDF usando Aspose.PDF for Python. Este tutorial demuestra cómo usar la clase PdfFileInfo para comprobar la versión PDF de un archivo. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Recuperar versión de PDF usando Aspose.PDF for Python +Abstract: Los documentos PDF tienen números de versión que indican las características y especificaciones que soportan (p. ej., 1.4, 1.7, 2.0). Conocer la versión del PDF es importante para la compatibilidad, el soporte de funcionalidades y los flujos de trabajo de procesamiento de documentos. En esta guía, aprenderá cómo recuperar la versión del PDF programáticamente usando la clase PdfFileInfo en Aspose.PDF for Python. +--- + +Las versiones de PDF definen las características y capacidades admitidas en un documento, incluidos los campos de formulario, el cifrado, las anotaciones y la compresión. Para los desarrolladores que trabajan con múltiples PDFs, comprobar la versión garantiza la compatibilidad con herramientas, bibliotecas o flujos de trabajo que procesan estos archivos. + +Usando Aspose.PDF for Python, puede inspeccionar fácilmente la versión del PDF con el [PdfFileInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileinfo/) clase. + +1. Cargar un documento PDF. +1. Obtener su versión PDF. +1. Mostrar la versión en la consola. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def get_pdf_version(input_file_name): + + pdf_metadata = pdf_facades.PdfFileInfo(input_file_name) + version = pdf_metadata.get_pdf_version() + print(f"\nPDF Version: {version}") +``` diff --git a/es/python-net/working-with-facades/pdffileinfo/page-information/_index.md b/es/python-net/working-with-facades/pdffileinfo/page-information/_index.md new file mode 100644 index 000000000..c70e6b3e5 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileinfo/page-information/_index.md @@ -0,0 +1,19 @@ +--- +title: Información de la página +linktitle: Información de la página +type: docs +weight: 20 +url: /es/python-net/page-information/ +description: Este artículo explica cómo extraer los detalles clave de diseño y posicionamiento de las páginas PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Recuperar información de la página PDF y desplazamientos +Abstract: Las páginas PDF pueden diferir en tamaño, rotación y posicionamiento interno del contenido. Las funciones Get Page Information y Get Page Offset proporcionan a los desarrolladores una vista completa del diseño de cada página. Get Page Information devuelve el ancho, la altura y la rotación de la página, mientras que Get Page Offset recupera los desplazamientos X y Y en pulgadas. Juntas, estas métodos permiten una alineación precisa de texto, imágenes, anotaciones y otros contenidos, soportando flujos de trabajo automatizados tanto de una sola página como de múltiples páginas. +--- + +- [Obtener información de la página](/pdf/es/python-net/get-page-info/) +- [Obtener desplazamiento de página](/pdf/es/python-net/get-page-offset/) diff --git a/es/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md b/es/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md new file mode 100644 index 000000000..139cf9753 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md @@ -0,0 +1,51 @@ +--- +title: Obtener información de la página +linktitle: Obtener información de la página +type: docs +weight: 10 +url: /es/python-net/get-page-info/ +description: Aprenda cómo acceder programáticamente a la información a nivel de página en un PDF usando Aspose.PDF for Python. Esta guía muestra cómo recuperar el ancho, la altura, la rotación y los desplazamientos de una página específica en un documento PDF. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Obtener información de la página PDF usando Aspose.PDF for Python +Abstract: La función extrae el ancho, la altura, la rotación y los desplazamientos horizontal (X) y vertical (Y) de una página PDF. Estas propiedades se devuelven en puntos y reflejan el tamaño físico de la página y la posición del contenido dentro del PDF. La función muestra los valores obtenidos, lo que permite a los desarrolladores comprender el diseño y la orientación de la página para una mayor manipulación de PDF. +--- + +La función utilitaria ‘get_page_information’ ayuda a los desarrolladores a comprender la estructura y el diseño de las páginas PDF. Cada página PDF puede tener diferentes dimensiones, rotación y desplazamientos internos, lo que puede afectar la ubicación del contenido o tareas de automatización. + +Incluye la recuperación de metadatos clave y la información de diseño para una página específica en un archivo PDF. La API Aspose.PDF Facades proporciona detalles como el ancho, la altura, la rotación y los desplazamientos X/Y de la página. Esta información es esencial para tareas como el análisis del diseño de página, la colocación de anotaciones o el procesamiento automatizado de PDF. + +1. Crear un objeto fachada PDF. +1. Obtener las dimensiones y el diseño de la página. +1. Imprimir o guardar los valores obtenidos. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def get_page_information(infile): + + # Get and display PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + page_width = pdf_info.get_page_width(1) + page_height = pdf_info.get_page_height(1) + page_rotation = pdf_info.get_page_rotation(1) + page_x_offset = pdf_info.get_page_x_offset(1) + page_y_offset = pdf_info.get_page_y_offset(1) + + print(f"Page Width: {page_width}") + print(f"Page Height: {page_height}") + print(f"Page Rotation: {page_rotation}") +``` diff --git a/es/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md b/es/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md new file mode 100644 index 000000000..a5a25286b --- /dev/null +++ b/es/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md @@ -0,0 +1,46 @@ +--- +title: Obtener desplazamiento de página +linktitle: Obtener desplazamiento de página +type: docs +weight: 20 +url: /es/python-net/get-page-offset/ +description: Este ejemplo demuestra cómo usar PdfFileInfo para obtener los desplazamientos X e Y de una página específica y convertirlos a pulgadas para un análisis preciso de diseño y posicionamiento. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Obtener desplazamientos de página PDF usando Python +Abstract: La función 'get_page_offsets' extrae los desplazamientos horizontal (X) y vertical (Y) de cada página en un archivo PDF. Estos desplazamientos representan la posición del contenido de la página respecto al origen del PDF's. Al convertir los puntos a pulgadas, la función proporciona mediciones precisas y legibles que pueden usarse para una colocación exacta de anotaciones, imágenes o texto. Soporta PDFs de varias páginas y está destinada a desarrolladores que trabajan en el diseño de PDF, automatización o tareas de alineación de contenido. +--- + +La función 'get_page_offsets' ofrece a los desarrolladores los desplazamientos exactos horizontal (X) y vertical (Y) de las páginas en un archivo PDF. En los documentos PDF, cada página puede tener un punto de origen interno que difiere de la esquina superior izquierda de la página, lo que puede afectar el posicionamiento del texto, imágenes, anotaciones u otro contenido. + +Al utilizar Aspose.PDF Facades, esta función extrae estos desplazamientos en puntos y los convierte a pulgadas para una interpretación fácil. Soporta PDFs de varias páginas, lo que la hace adecuada para flujos de trabajo automatizados que requieren una colocación precisa del contenido. + +1. Cree el objeto fachada PDF. +1. Obtenga el número de páginas del PDF. +1. Recorra cada página para obtener los desplazamientos. +1. Imprima o almacene los desplazamientos. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def get_page_offsets(infile): + # Get and display PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + page_x_offset = pdf_info.get_page_x_offset(1) / 72.0 + page_y_offset = pdf_info.get_page_y_offset(1) / 72.0 + print(f"Page X Offset: {page_x_offset} inches") + print(f"Page Y Offset: {page_y_offset} inches") +``` diff --git a/es/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md b/es/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md new file mode 100644 index 000000000..3835d66b4 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md @@ -0,0 +1,21 @@ +--- +title: Metadatos PDF +linktitle: Metadatos PDF +type: docs +weight: 30 +url: /es/python-net/pdf-metadata/ +description: Este artículo explica cómo acceder, modificar y guardar metadatos en documentos PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Administrar metadatos PDF en Python +Abstract: Los metadatos PDF contienen información sobre un documento, como el título, el autor, palabras clave y la fecha de creación, lo que ayuda en la catalogación, búsqueda y mantenimiento de la integridad del documento. Con Aspose.PDF, los desarrolladores pueden programáticamente Get PDF Metadata, Set PDF Metadata values, Clear PDF Metadata, y guardar los cambios ya sea en metadatos PDF estándar o en formato XMP. Este enfoque integral permite un control preciso sobre las propiedades del documento y asegura un manejo coherente a lo largo de los flujos de trabajo y aplicaciones. +--- + +- [Obtener metadatos de PDF](/pdf/es/python-net/get-pdf-metadata/) +- [Establecer metadatos PDF](/pdf/es/python-net/set-pdf-metadata/) +- [Borrar metadatos de PDF](/pdf/es/python-net/clear-pdf-metadata/) +- [Guardar metadatos con XMP](/pdf/es/python-net/save-metadata-with-xmp/) diff --git a/es/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md b/es/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md new file mode 100644 index 000000000..862559032 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md @@ -0,0 +1,47 @@ +--- +title: Borrar metadatos de PDF +linktitle: Borrar metadatos de PDF +type: docs +weight: 10 +url: /es/python-net/clear-pdf-metadata/ +description: Eliminar todos los metadatos de un documento PDF usando Aspose.PDF para Python a través de .NET. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Borrado de metadatos PDF usando Aspose.PDF para Python +Abstract: Esta guía explica cómo eliminar todos los metadatos de un documento PDF usando Aspose.PDF para Python a través de .NET. Aprenderá a borrar tanto los campos de metadatos estándar como los personalizados y a guardar el PDF sanitizado. Esto es útil para la privacidad, la seguridad o la preparación de PDFs para su publicación. +--- + +Los PDF suelen contener metadatos como título, autor, palabras clave, fechas de creación y campos personalizados. En algunos escenarios, puede querer eliminar todos los metadatos de un PDF, por ejemplo antes de su distribución o archivado. Aspose.PDF proporciona el método clear_info() para eliminar todos los metadatos fácilmente. Después de la eliminación, puede guardar el PDF usando el método save(). + +1. Cargue el archivo PDF. +1. Borrar todos los metadatos. +1. Guardar el PDF limpio. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def clear_pdf_metadata(infile, outfile): + + # Get PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + + # Clear PDF metadata + pdf_info.clear_info() + + # Save updated metadata + pdf_info.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md b/es/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md new file mode 100644 index 000000000..4ec5078d6 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md @@ -0,0 +1,59 @@ +--- +title: Obtener metadatos de PDF +linktitle: Obtener metadatos de PDF +type: docs +weight: 20 +url: /es/python-net/get-pdf-metadata/ +description: Extraer y mostrar metadatos de documentos PDF usando Aspose.PDF for Python. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Recuperar metadatos de PDF usando Aspose.PDF for Python. +Abstract: Esta guía muestra cómo extraer y mostrar metadatos de documentos PDF usando Aspose.PDF for Python. Aprenderá a acceder a propiedades estándar de PDF como título, autor, palabras clave, fechas de creación/modificación, así como a campos de metadatos personalizados. Además, la guía cubre verificaciones de la validez del PDF, encriptación y estado de portafolio. +--- + +Los documentos PDF a menudo contienen metadatos valiosos que describen el contenido del documento, la autoría y los permisos. Aspose.PDF proporciona una API conveniente para recuperar tanto propiedades de metadatos estándar como personalizadas. Este fragmento de código muestra cómo usar el [PdfFileInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileinfo/) clase para inspeccionar archivos PDF programáticamente, incluyendo ejemplos paso a paso en Python. + +1. Cargue el archivo PDF. +1. Recuperar metadatos estándar. +1. Verificar el estado y la seguridad del PDF. +1. Recuperar metadatos personalizados. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def get_pdf_metadata(infile): + + # Get and display PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + print(f"Subject: {pdf_info.subject}") + print(f"Title: {pdf_info.title}") + print(f"Keywords: {pdf_info.keywords}") + print(f"Creator: {pdf_info.creator}") + print(f"Creation Date: {pdf_info.creation_date}") + print(f"Modification Date: {pdf_info.mod_date}") + + # Check PDF status + print(f"Is Valid PDF: {pdf_info.is_pdf_file}") + print(f"Is Encrypted: {pdf_info.is_encrypted}") + print(f"Has Open Password: {pdf_info.has_open_password}") + print(f"Has Edit Password: {pdf_info.has_edit_password}") + print(f"Is Portfolio: {pdf_info.has_collection}") + + # Retrieve and display a specific custom attribute + reviewer = pdf_info.get_meta_info("Reviewer") + print(f"Reviewer: {reviewer if reviewer else 'No Reviewer metadata found.'}") +``` diff --git a/es/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md b/es/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md new file mode 100644 index 000000000..de5447fe6 --- /dev/null +++ b/es/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md @@ -0,0 +1,50 @@ +--- +title: Guardar metadatos con XMP +linktitle: Guardar metadatos con XMP +type: docs +weight: 30 +url: /es/python-net/save-metadata-with-xmp/ +description: Guardar metadatos PDF usando XMP con Aspose.PDF for Python via .NET +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Guardar metadatos PDF con XMP usando Aspose.PDF for Python +Abstract: Esta guía demuestra cómo guardar metadatos PDF usando XMP (Extensible Metadata Platform) con Aspose.PDF for Python via .NET. XMP garantiza que tanto los metadatos estándar como los personalizados se incrusten en un formato XML estandarizado dentro del PDF, mejorando la compatibilidad entre aplicaciones y flujos de trabajo. +--- + +Los metadatos PDF pueden almacenarse de múltiples maneras, y XMP es el método moderno y estandarizado para incrustar metadatos dentro de un archivo PDF. Usando Aspose.PDF, puedes actualizar campos estándar como Title, Subject, Keywords y Creator, y luego guardarlos en formato XMP para garantizar una mayor compatibilidad y una preparación para el futuro. Este método se recomienda sobre los métodos heredados de almacenamiento de metadatos. + +1. Cargue el archivo PDF. +1. Establecer campos de metadatos estándar. +1. Guardar metadatos en formato XMP. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def save_info_with_xmp(infile, outfile): + + # Get PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + + # Set PDF metadata + pdf_info.subject = "Aspose PDF for Python via .NET" + pdf_info.title = "Aspose PDF for Python via .NET" + pdf_info.keywords = "Aspose, PDF, Python, .NET" + pdf_info.creator = "Aspose Team" + + # Save updated metadata + pdf_info.save_new_info_with_xmp(outfile) +``` diff --git a/es/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md b/es/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md new file mode 100644 index 000000000..7c7aa001a --- /dev/null +++ b/es/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md @@ -0,0 +1,56 @@ +--- +title: Establecer metadatos PDF +linktitle: Establecer metadatos PDF +type: docs +weight: 50 +url: /es/python-net/set-pdf-metadata/ +description: Modificar y guardar metadatos en documentos PDF usando Aspose.PDF for Python via .NET. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Actualizando metadatos PDF usando Aspose.PDF for Python +Abstract: Esta guía explica cómo modificar y guardar metadatos en documentos PDF usando Aspose.PDF for Python via .NET. Demuestra cómo actualizar propiedades estándar de PDF como título, asunto, palabras clave y creador, así como campos de metadatos personalizados. Al final, podrás actualizar programáticamente los metadatos PDF y guardar los cambios. +--- + +Los documentos PDF pueden contener tanto metadatos estándar (Title, Subject, Keywords, Creator, Author) como metadatos personalizados almacenados como propiedades XMP. Aspose.PDF proporciona una API simple para modificar estas propiedades en Python. Esta guía cubre cómo actualizar estos campos y guardar el archivo PDF modificado usando el [PdfFileInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileinfo/) clase. + +1. Cargue el archivo PDF. +1. Actualizar metadatos estándar. +1. Agregar o actualizar metadatos personalizados. +1. Guardar los metadatos actualizados. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_pdf_metadata(infile, outfile): + + # Get PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + + # Set PDF metadata + pdf_info.subject = "Aspose PDF for Python via .NET" + pdf_info.title = "Aspose PDF for Python via .NET" + pdf_info.keywords = "Aspose, PDF, Python, .NET" + pdf_info.creator = "Aspose Team" + + pdf_info.set_meta_info("CustomKey", "CustomValue") + + # pdf_info.save_new_info(outfile) + # Is obsolete, use save() method instead + + # Save updated metadata + pdf_info.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdffilesecurity/_index.md b/es/python-net/working-with-facades/pdffilesecurity/_index.md new file mode 100644 index 000000000..cc3ed5e26 --- /dev/null +++ b/es/python-net/working-with-facades/pdffilesecurity/_index.md @@ -0,0 +1,26 @@ +--- +title: Clase PdfFileSecurity +linktitle: Clase PdfFileSecurity +type: docs +weight: 125 +url: /es/python-net/pdffilesecurity-class/ +description: Aprenda cómo usar la clase PdfFileSecurity en Aspose.PDF for Python via .NET para cifrar y descifrar PDFs, cambiar contraseñas y controlar los privilegios del documento. +lastmod: "2026-03-18" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Cifre, descifre y controle los permisos de PDF en Python con PdfFileSecurity +Abstract: Esta sección explica cómo usar la clase PdfFileSecurity en Aspose.PDF for Python via .NET para asegurar documentos PDF de forma programática. Aprenda cómo cifrar y descifrar archivos PDF, cambiar contraseñas y configurar los privilegios y permisos del documento en aplicaciones Python. +--- + +El `PdfFileSecurity` La clase en Aspose.PDF Facades se usa para proteger documentos PDF y controlar cómo los usuarios pueden interactuar con ellos. Soporta flujos de trabajo de seguridad comunes, como cifrado basado en contraseña, descifrado, rotación de contraseñas y gestión de permisos para imprimir, copiar y editar. + +## Qué puedes hacer con PdfFileSecurity + +Utilice los artículos en esta sección para explorar las principales tareas de seguridad de PDF compatibles con el `PdfFileSecurity` fachada: + +- [Cifrar archivos PDF con PdfFileSecurity](/pdf/es/python-net/encrypt-pdf-file/) +- [Descifrar archivos PDF con PdfFileSecurity](/pdf/es/python-net/decrypt-pdf-file/) +- [Cambiar contraseñas de PDF con PdfFileSecurity](/pdf/es/python-net/change-password/) +- [Establecer privilegios de PDF con PdfFileSecurity](/pdf/es/python-net/set-privileges/) diff --git a/es/python-net/working-with-facades/pdffilesecurity/change-password/_index.md b/es/python-net/working-with-facades/pdffilesecurity/change-password/_index.md new file mode 100644 index 000000000..1696e70e1 --- /dev/null +++ b/es/python-net/working-with-facades/pdffilesecurity/change-password/_index.md @@ -0,0 +1,155 @@ +--- +title: Cambiar la contraseña del archivo PDF +linktitle: Cambiar la contraseña del archivo PDF +type: docs +weight: 10 +url: /es/python-net/change-password/ +description: Cambiar las contraseñas de usuario y propietario de un documento PDF protegido utilizando Aspose.PDF for Python via .NET. +lastmod: "2026-03-18" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Actualizar contraseñas de PDF +Abstract: Aprenda cómo cambiar tanto las contraseñas de usuario como de propietario en un archivo PDF protegido utilizando Aspose.PDF for Python via .NET. Este ejemplo muestra cómo actualizar de forma segura las credenciales de acceso mientras se mantiene el cifrado y los permisos existentes intactos. +--- + +## Cambiar contraseña de usuario y propietario + +En muchos casos, es posible que necesite actualizar las contraseñas de un PDF protegido sin cambiar su configuración de seguridad actual. Esto puede ser útil al rotar credenciales, transferir la propiedad o mejorar la seguridad del documento. + +El método \u0027change_password\u0027 de [PdfFileSecurity](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesecurity/) la clase le permite: + +- Actualizar la contraseña del usuario (necesaria para abrir el documento) +- Actualizar la contraseña del propietario (utilizada para controlar los permisos) +- Mantener la configuración actual de cifrado y permisos + +1. Cree un objeto 'PdfFileSecurity'. +1. Vincular el PDF de entrada. +1. Cambie contraseñas con el método 'change_password()'. +1. Guarde el PDF actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Change User and Owner Password +def change_user_and_owner_password(infile, outfile): + """Change user and owner passwords while keeping existing security settings.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Change passwords + file_security.change_password( + "owner_password", "new_user_password", "new_owner_password" + ) + + # Save updated PDF + file_security.save(outfile) +``` + +## Cambiar la contraseña y restablecer la seguridad + +Al trabajar con documentos PDF seguros, simplemente cambiar las contraseñas puede no ser suficiente. También puede ser necesario ajustar los permisos, como los de impresión, copia o edición. + +Aprenda cómo actualizar las contraseñas de usuario y propietario mientras restablece la configuración de seguridad PDF con Aspose.PDF for Python via .NET. Este ejemplo muestra cómo redefinir los permisos del documento y la fuerza de cifrado junto con nuevas credenciales de acceso. + +1. Cree un objeto 'PdfFileSecurity'. +1. Vincular el PDF de entrada. +1. Cree un objeto 'DocumentPrivilege' y configure las acciones permitidas. +1. Cambie las contraseñas y restablezca la seguridad. +1. Guarde el PDF actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Change Password and Reset Security +def change_password_and_reset_security(infile, outfile): + """Change passwords and reset document security settings.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define new privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + + # Change passwords and reset security + file_security.change_password( + "owner_password", + "new_user_password", + "new_owner_password", + privilege, + pdf_facades.KeySize.X128, + ) + + # Save updated PDF + file_security.save(outfile) +``` + +## Intentar cambiar la contraseña sin excepción + +En algunos flujos de trabajo, especialmente en procesamiento por lotes o sistemas automatizados, es importante evitar excepciones que puedan interrumpir la ejecución. En lugar de lanzar errores, puede preferir una operación segura que informe el éxito o el fracaso. + +El método 'try_change_password' de [PdfFileSecurity](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesecurity/) clase proporciona esta funcionalidad mediante: + +1. Cree un objeto 'PdfFileSecurity'. +1. Cargue el documento PDF usando el método 'bind_pdf()'. +1. Intentar cambiar contraseñas. +1. Verificar el resultado. +1. Guarde el PDF actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Try Change Password Without Exception +def try_change_password_without_exception(infile, outfile): + """Attempt to change passwords without throwing an exception on failure.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Attempt to change passwords + result = file_security.try_change_password( + "owner_password", "new_user_password", "new_owner_password" + ) + + # Save only if operation succeeded + if result: + file_security.save(outfile) + else: + print("Password change failed. Check owner password or document security.") +``` diff --git a/es/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md b/es/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md new file mode 100644 index 000000000..c5b52ce2f --- /dev/null +++ b/es/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md @@ -0,0 +1,92 @@ +--- +title: Descifrar archivo PDF +linktitle: Descifrar archivo PDF +type: docs +weight: 20 +url: /es/python-net/decrypt-pdf-file/ +description: Esta guía explica cómo eliminar restricciones como imprimir, copiar y editar para obtener acceso total a su documento PDF. +lastmod: "2026-03-18" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Eliminar protección con contraseña de un PDF +Abstract: Este artículo muestra cómo descifrar un archivo PDF usando una contraseña de propietario. Cubre el proceso de eliminación de restricciones de seguridad que limitan acciones como imprimir, editar o copiar contenido. Al aplicar la contraseña de propietario correcta, los usuarios pueden desbloquear el documento y recuperar el control total de sus funciones. +--- + +## Descifrar PDF con contraseña de propietario + +Descifre un documento PDF protegido con contraseña usando la contraseña de propietario con Aspose.PDF for Python via .NET. Esta operación elimina el cifrado y permite el acceso sin restricciones al documento. + +1. Cree un objeto 'PdfFileSecurity'. +1. Cargue el PDF cifrado usando el método 'bind_pdf()'. +1. Desencripte el documento. +1. Guarde el PDF desencriptado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Decrypt PDF with Owner Password +def decrypt_pdf_with_owner_password(infile, outfile): + """Decrypt a PDF document using the owner password.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Decrypt the PDF + file_security.decrypt_file("owner_password") + + # Save decrypted PDF + file_security.save(outfile) +``` + +## Intentar descifrar PDF sin excepción + +Los documentos PDF a menudo están protegidos con contraseñas para restringir el acceso y el uso. Para acceder o modificar completamente dichos documentos, puede ser necesario eliminar el cifrado. Desencripte un documento PDF asegurado usando la contraseña del propietario para eliminar el cifrado y las restricciones de acceso con Aspose.PDF for Python via .NET. + +1. Cree un objeto 'PdfFileSecurity'. +1. Vincular el PDF de entrada. +1. Desencripte el PDF. +1. Guarde el PDF de salida. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Try Decrypt PDF Without Exception +def try_decrypt_pdf_without_exception(infile, outfile): + """Attempt to decrypt a PDF without throwing an exception on failure.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Attempt to decrypt the PDF + result = file_security.try_decrypt_file("owner_password") + + # Save only if decryption was successful + if result: + file_security.save(outfile) + else: + print("Decryption failed. Check password or document security.") +``` diff --git a/es/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md b/es/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md new file mode 100644 index 000000000..7d15a351f --- /dev/null +++ b/es/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md @@ -0,0 +1,152 @@ +--- +title: Cifrar archivo PDF +linktitle: Cifrar archivo PDF +type: docs +weight: 30 +url: /es/python-net/encrypt-pdf-file/ +description: Cifre un documento PDF y configure los permisos para controlar lo que los usuarios pueden hacer con el archivo. +lastmod: "2026-03-18" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Cifre PDF y controle las acciones del usuario +Abstract: Aprenda cómo cifrar un PDF mientras define permisos específicos de usuario utilizando Aspose.PDF for Python via .NET. Esta guía muestra cómo permitir o restringir acciones como imprimir y copiar, mientras mantiene el documento seguro. +--- + +## Cifrar PDF con contraseña de usuario y de propietario + +Proteger los documentos PDF es esencial al compartir contenido sensible o restringido. El cifrado le permite proteger un documento con contraseñas y definir qué acciones pueden realizar los usuarios. Este fragmento de código muestra cómo aplicar contraseñas de usuario y propietario, junto con permisos de acceso, para asegurar un archivo PDF. + +1. Crear un objeto PdfFileSecurity. +1. Vincular el PDF de entrada. +1. Definir privilegios de documento. +1. Cifrar el PDF. +1. Guardar el PDF cifrado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Encrypt PDF with User and Owner Password +def encrypt_pdf_with_user_owner_password(infile, outfile): + """Encrypt a PDF document using user and owner passwords.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define document privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + + # Encrypt the PDF + file_security.encrypt_file( + "user_password", "owner_password", privilege, pdf_facades.KeySize.X128 + ) + + # Save encrypted PDF + file_security.save(outfile) +``` + +## Encriptar PDF con permisos + +El siguiente fragmento de código explica cómo permitir acciones seleccionadas como imprimir y copiar mientras se restringen otras. + +1. Inicializar el [PdfFileSecurity](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesecurity/) clase. +1. Vincular el PDF de entrada. +1. Configurar privilegios del documento. +1. Llamar al método 'encrypt_file()'. +1. Guardar el PDF cifrado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Encrypt PDF with Permissions +def encrypt_pdf_with_permissions(infile, outfile): + """Encrypt a PDF document and configure specific permissions.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Configure privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + privilege.allow_copy = True + + # Encrypt the PDF + file_security.encrypt_file( + "user_password", "owner_password", privilege, pdf_facades.KeySize.X128 + ) + + # Save encrypted PDF + file_security.save(outfile) +``` + +## Cifrar PDF con algoritmo de encriptación + +El cifrado de PDF no solo protege los documentos con contraseñas, sino que también permite elegir el algoritmo de cifrado y su robustez. Seleccionar el algoritmo apropiado garantiza una seguridad más fuerte para documentos sensibles. + +1. Cree un objeto PdfFileSecurity. +1. Vincular el PDF de entrada. +1. Definir privilegios de documento. +1. Cifre el PDF con el algoritmo. +1. Guardar el PDF cifrado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Encrypt PDF with Encryption Algorithm +def encrypt_pdf_with_encryption_algorithm(infile, outfile): + """Encrypt a PDF document using a specific encryption algorithm.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + + # Encrypt the PDF using AES algorithm + file_security.encrypt_file( + "user_password", + "owner_password", + privilege, + pdf_facades.KeySize.X256, + pdf_facades.Algorithm.AES, + ) + + # Save encrypted PDF + file_security.save(outfile) +``` diff --git a/es/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md b/es/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md new file mode 100644 index 000000000..f57b62444 --- /dev/null +++ b/es/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md @@ -0,0 +1,148 @@ +--- +title: Establecer privilegios en un archivo PDF existente +linktitle: Establecer privilegios en un archivo PDF existente +type: docs +weight: 40 +url: /es/python-net/set-privileges/ +description: Establezca y administre los privilegios de documentos PDF para controlar acciones del usuario como imprimir, copiar y editar. +lastmod: "2026-03-18" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Administrar permisos y controles de acceso de PDF +Abstract: Aprenda cómo controlar lo que los usuarios pueden hacer con un PDF estableciendo privilegios de documento usando Aspose.PDF for Python via .NET. Esta guía cubre la aplicación de permisos con o sin contraseñas para restringir acciones como imprimir, copiar o editar. +--- + +## Establecer privilegios de PDF sin contraseñas + +Verifique cómo aplicar privilegios de documento a un PDF sin especificar contraseñas de usuario o propietario utilizando Aspose.PDF for Python via .NET. Este fragmento de código muestra cómo controlar las acciones permitidas mientras se mantiene el documento accesible. + +1. Crear un objeto 'PdfFileSecurity'. +1. Vincular el PDF de entrada. +1. Definir privilegios del documento. +1. Llame al método 'set_privilege()' sin pasar contraseñas. +1. Guarde el PDF actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Set PDF Privileges Without Passwords +def set_pdf_privileges_without_passwords(infile, outfile): + """Set PDF privileges without specifying user and owner passwords.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + + # Apply privileges (owner password will be generated automatically) + file_security.set_privilege(privilege) + + # Save updated PDF + file_security.save(outfile) +``` + +## Establecer privilegios de PDF con contraseñas de usuario y propietario + +Para asegurar completamente un documento PDF, a menudo se necesita tanto control de acceso (contraseñas) como restricciones de uso (permisos). Al combinar estos, puedes garantizar que solo los usuarios autorizados puedan abrir el documento y realizar acciones específicas. + +Usando el método set_privilege con parámetros de contraseña, puedes: + +- Proteger el documento con una contraseña de usuario +- Definir una contraseña de propietario para control total +- Configurar acciones permitidas y restringidas +- Aplicar políticas de seguridad a nivel de documento + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Set PDF Privileges with User and Owner Passwords +def set_pdf_privileges_with_passwords(infile, outfile): + """Set PDF privileges using user and owner passwords.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + privilege.allow_copy = False + + # Apply privileges with passwords + file_security.set_privilege("user_password", "owner_password", privilege) + + # Save updated PDF + file_security.save(outfile) +``` + +## Intenta establecer privilegios de PDF sin excepción + +Este fragmento de código explica cómo controlar el acceso y restringir acciones como copiar, mientras se permiten otras como imprimir. + +1. Cree un objeto 'PdfFileSecurity'. +1. Carga el PDF de origen usando el método 'bind_pdf()'. +1. Definir privilegios del documento. +1. Aplicar privilegios con contraseñas. +1. Guarde el PDF actualizado. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Try Set PDF Privileges Without Exception +def try_set_pdf_privileges_without_exception(infile, outfile): + """Attempt to set PDF privileges without throwing an exception on failure.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + + # Attempt to apply privileges + result = file_security.try_set_privilege( + "user_password", "owner_password", privilege + ) + + # Save only if operation succeeded + if result: + file_security.save(outfile) + else: + print("Setting privileges failed. Check passwords or document state.") +``` diff --git a/es/python-net/working-with-facades/pdffilesignature/_index.md b/es/python-net/working-with-facades/pdffilesignature/_index.md new file mode 100644 index 000000000..aec6cc274 --- /dev/null +++ b/es/python-net/working-with-facades/pdffilesignature/_index.md @@ -0,0 +1,83 @@ +--- +title: Clase PdfFileSignature +linktitle: Clase PdfFileSignature +type: docs +weight: 60 +url: /es/python-net/pdffilesignature-class/ +description: Explore como agregar, verificar y quitar firmas digitales de documentos PDF en Python usando la clase PDFFileSignature con Aspose.PDF. +lastmod: "2026-01-05" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +- [Firma de PDF](/pdf/python-net/pdf-signing/) +- [Certificacion de PDF](/pdf/python-net/pdf-certification/) +- [Administracion de firmas](/pdf/python-net/signature-management/) +- [Verificacion de firmas](/pdf/python-net/signature-verification/) +- [Informacion de firmas](/pdf/python-net/signature-information/) +- [Comprobaciones de integridad de firmas](/pdf/python-net/signature-integrity-checks/) +- [Revision y permisos](/pdf/python-net/revision-permissions/) +- [Extraccion de firmas](/pdf/python-net/signature-extraction/) +- [Administracion de derechos de uso](/pdf/python-net/usage-rights-management/) + +## Preparar auxiliares de firma digital PDF + +Antes de aplicar una firma digital a un PDF, es una buena practica configurar un conjunto de funciones auxiliares reutilizables. Estas funciones encapsulan tareas comunes, como inicializar el controlador de firmas, definir la ubicacion visual de la firma y configurar la firma basada en certificados, para que la logica principal de firma se mantenga limpia, coherente y facil de mantener. + +### Que consigue esta configuracion + +Esta capa auxiliar prepara todo lo necesario para un flujo de trabajo de firma fluido: + +- Inicializa un objeto PdfFileSignature y lo enlaza a un documento +- Define donde aparecera la firma en la pagina +- Carga y aplica un certificado de firma +- Crea un objeto de firma PKCS#7 reutilizable con metadatos +- Personaliza el aspecto visual de la firma + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd + + +DEFAULT_CERTIFICATE_PASSWORD = "Aspose2021" +DEFAULT_SIGNATURE_NAME = "Signature1" + + +def create_pdf_file_signature(infile): + pdf_signature = pdf_facades.PdfFileSignature() + pdf_signature.bind_pdf(infile) + return pdf_signature + + +def create_signature_rectangle(): + return apd.Rectangle(10, 10, 200, 60) + + +def configure_signature_certificate( + pdf_signature, certificate_path, certificate_password=DEFAULT_CERTIFICATE_PASSWORD +): + pdf_signature.set_certificate(certificate_path, certificate_password) + + +def create_pkcs7_signature( + certificate_path, certificate_password=DEFAULT_CERTIFICATE_PASSWORD +): + signature = ap.forms.PKCS7(certificate_path, certificate_password) + signature.reason = "Document approval" + signature.contact_info = "qa@example.com" + signature.location = "New York, USA" + signature.authority = "Aspose.PDF Example" + return signature + + +def create_custom_signature_appearance(): + appearance = ap.forms.SignatureCustomAppearance() + appearance.font_family_name = "Arial" + appearance.font_size = 10 + appearance.show_contact_info = True + appearance.show_location = True + appearance.show_reason = True + return appearance +``` diff --git a/es/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md b/es/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md new file mode 100644 index 000000000..3fc73eff8 --- /dev/null +++ b/es/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md @@ -0,0 +1,86 @@ +--- +title: Certificación PDF +linktitle: Certificación PDF +type: docs +weight: 30 +url: /es/python-net/pdf-certification/ +description: Aprenda cómo certificar documentos PDF en Python usando PdfFileSignature y DocMDPSignature con diferentes permisos de modificación del documento. +lastmod: "2026-04-02" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Certifique documentos PDF con permisos DocMDP en Python +Abstract: Este artículo explica cómo certificar documentos PDF con Aspose.PDF for Python via .NET usando la fachada PdfFileSignature. Muestra cómo crear una DocMDPSignature, aplicar la certificación con permisos de llenado de formularios y bloquear un documento con un nivel de certificación sin cambios. +--- + +Aspose.PDF for Python via .NET le permite certificar documentos PDF aplicando una firma a nivel de documento con [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/). La certificación es diferente de una firma de aprobación estándar porque define qué cambios, si los hay, están permitidos después de que el documento ha sido certificado. + +Este artículo muestra dos flujos de trabajo de certificación comunes: + +1. Certificar un PDF y permitir el relleno de formularios después de la certificación. +1. Certificar un PDF y evitar cualquier cambio posterior. + +## Certificar un PDF para rellenar formularios + +Utilice este enfoque cuando el documento deba permanecer certificado pero los usuarios aún necesiten completar formularios interactivos o continuar firmando el archivo. El `FILLING_IN_FORMS` El nivel de permiso permite esos cambios controlados mientras se mantiene la certificación válida. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def certify_pdf_with_mdp_signature(infile, outfile, certificate_path): + pdf_signature = create_pdf_file_signature(infile) + try: + doc_mdp_signature = create_doc_mdp_signature( + certificate_path, + ap.forms.DocMDPAccessPermissions.FILLING_IN_FORMS, + reason="Certified for form filling and signing", + ) + pdf_signature.certify( + 1, + "Certified for form filling and signing", + "security@example.com", + "New York, USA", + True, + create_signature_rectangle(), + doc_mdp_signature, + ) + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` + +## Aplicar certificación a nivel de documento sin permitir cambios + +Utilice este modo cuando el documento certificado debe permanecer sin cambios después de la certificación. El `NO_CHANGES` el nivel de permiso es apropiado para PDFs finalizados donde cualquier modificación posterior debería invalidar el estado de certificación. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def apply_document_level_certification(infile, outfile, certificate_path): + pdf_signature = create_pdf_file_signature(infile) + try: + doc_mdp_signature = create_doc_mdp_signature( + certificate_path, + ap.forms.DocMDPAccessPermissions.NO_CHANGES, + reason="Certified with no further changes allowed", + ) + pdf_signature.certify( + 1, + "Certified with no further changes allowed", + "security@example.com", + "New York, USA", + True, + create_signature_rectangle(), + doc_mdp_signature, + ) + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` diff --git a/es/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md b/es/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md new file mode 100644 index 000000000..39ceb838f --- /dev/null +++ b/es/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md @@ -0,0 +1,183 @@ +--- +title: Firmar documentos PDF +linktitle: Firmar documentos PDF +type: docs +weight: 10 +url: /es/python-net/pdf-signing/ +description: Aprenda cómo firmar documentos PDF en Python usando PdfFileSignature con firmas digitales basadas en certificado, con nombre y visibles. +lastmod: "2026-04-14" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Firmar documentos PDF con firmas digitales en Python +Abstract: Este artículo muestra cómo firmar documentos PDF con Aspose.PDF for Python via .NET usando la fachada PdfFileSignature. Cubre la configuración de certificados, la firma con parámetros básicos, la firma con un objeto PKCS7, la asignación de un nombre de firma y la aplicación de una apariencia de firma visible. +--- + +Aspose.PDF for Python via .NET proporciona la [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/) fachada para aplicar firmas digitales a documentos PDF existentes. Usando un archivo de certificado, puedes firmar un documento programáticamente, colocar la firma en una página, asignar metadatos de la firma y personalizar cómo se muestra la firma. + +Este artículo demuestra varios flujos de trabajo de firma comunes: + +1. Crear y vincular un `PdfFileSignature` objeto al PDF de entrada. +1. Configure el certificado de firma. +1. Aplique una firma digital a la página objetivo. +1. Opcionalmente asigne un nombre de firma y una apariencia visible. +1. Guarde el PDF firmado. + +## Preparar auxiliares reutilizables de firma + +Antes de aplicar una firma digital a un PDF, es útil configurar un pequeño conjunto de funciones auxiliares reutilizables. Estas ayudas inicializan el manejador de firmas, definen el área visible de la firma, configuran el certificado y crean objetos de firma PKCS#7 reutilizables, de modo que los ejemplos de firma a continuación sean autocontenidos y más fáciles de seguir. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd + + +DEFAULT_CERTIFICATE_PASSWORD = "Aspose2021" +DEFAULT_SIGNATURE_NAME = "Signature1" + + +def create_pdf_file_signature(infile): + pdf_signature = pdf_facades.PdfFileSignature() + pdf_signature.bind_pdf(infile) + return pdf_signature + + +def create_signature_rectangle(): + return apd.Rectangle(10, 10, 200, 60) + + +def configure_signature_certificate( + pdf_signature, certificate_path, certificate_password=DEFAULT_CERTIFICATE_PASSWORD +): + pdf_signature.set_certificate(certificate_path, certificate_password) + + +def create_pkcs7_signature( + certificate_path, certificate_password=DEFAULT_CERTIFICATE_PASSWORD +): + signature = ap.forms.PKCS7(certificate_path, certificate_password) + signature.reason = "Document approval" + signature.contact_info = "qa@example.com" + signature.location = "New York, USA" + signature.authority = "Aspose.PDF Example" + return signature + + +def create_custom_signature_appearance(): + appearance = ap.forms.SignatureCustomAppearance() + appearance.font_family_name = "Arial" + appearance.font_size = 10 + appearance.show_contact_info = True + appearance.show_location = True + appearance.show_reason = True + return appearance +``` + +## Firmar un PDF con parámetros de certificado básicos + +Este enfoque configura el certificado directamente en el `PdfFileSignature` objeto. Es útil cuando deseas un flujo de firma sencillo con metadatos de firma estándar y sin una gestión separada del objeto de firma. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def sign_pdf_with_basic_parameters(infile, outfile, certificate_path): + pdf_signature = create_pdf_file_signature(infile) + try: + configure_signature_certificate(pdf_signature, certificate_path) + pdf_signature.sign( + 1, + "Document approval", + "qa@example.com", + "New York, USA", + False, + create_signature_rectangle(), + ) + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` + +## Firmar un PDF con un objeto PKCS7 + +Usa un `PKCS7` objeto cuando necesita preparar la firma primero y luego pasarla a la llamada de firma. Este patrón le brinda más control sobre la configuración de la firma y es una buena base para flujos de trabajo más avanzados. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def sign_pdf_with_certificate_object(infile, outfile, certificate_path): + pdf_signature = create_pdf_file_signature(infile) + try: + signature = create_pkcs7_signature(certificate_path) + pdf_signature.sign(1, False, create_signature_rectangle(), signature) + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` + +## Firmar un PDF con una firma nombrada + +Si el flujo de trabajo de su documento depende de un nombre de campo de firma predefinido, pase ese nombre a `sign()`. Esto hace que sea más fácil referenciar la firma más tarde para validación, procesamiento o integración con un flujo de aprobación. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def sign_pdf_with_named_signature(infile, outfile, certificate_path): + pdf_signature = create_pdf_file_signature(infile) + try: + signature = create_pkcs7_signature(certificate_path) + signature.reason = "Approved by signing workflow" + pdf_signature.sign( + 1, + DEFAULT_SIGNATURE_NAME, + "Approved by signing workflow", + "qa@example.com", + "New York, USA", + True, + create_signature_rectangle(), + signature, + ) + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` + +## Aplicar una firma visible + +Puede hacer que la firma sea visible en la página PDF asignando una apariencia personalizada al `PKCS7` objeto. Esto es útil cuando el documento de salida debe mostrar detalles de aprobación, como la razón, la ubicación y la información de contacto a los usuarios finales. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def apply_visible_signature(infile, outfile, certificate_path): + pdf_signature = create_pdf_file_signature(infile) + try: + signature = create_pkcs7_signature(certificate_path) + signature.reason = "Visible approval signature" + signature.custom_appearance = create_custom_signature_appearance() + pdf_signature.sign( + 1, + "Visible approval signature", + "qa@example.com", + "New York, USA", + True, + create_signature_rectangle(), + signature, + ) + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` diff --git a/es/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md b/es/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md new file mode 100644 index 000000000..435bcaa5b --- /dev/null +++ b/es/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md @@ -0,0 +1,82 @@ +--- +title: Revisión y Permisos +linktitle: Revisión y Permisos +type: docs +weight: 40 +url: /es/python-net/revision-permissions/ +description: Aprende cómo inspeccionar revisiones de firmas, revisiones de documentos y permisos de certificación en archivos PDF utilizando PdfFileSignature en Python. +lastmod: "2026-04-02" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Leer datos de revisión de firma PDF y permisos de acceso en Python +Abstract: Este artículo explica cómo inspeccionar la información de revisión y permisos en archivos PDF firmados o certificados con Aspose.PDF for Python via .NET. Muestra cómo obtener el número de revisión de una firma, contar el total de revisiones del documento y leer los permisos de acceso de un PDF certificado. +--- + +Aspose.PDF for Python via .NET proporciona la [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/) fachada para trabajar con documentos PDF firmados y certificados. Además de agregar firmas, también puedes inspeccionar los metadatos de la firma para entender cuántas revisiones contiene un documento y qué cambios están permitidos después de la certificación. + +Este ejemplo demuestra tres tareas comunes de inspección: + +1. Obtener el número de revisión de una firma existente. +1. Obtener el número total de revisiones en un documento firmado. +1. Lea los permisos de acceso de un PDF certificado. + +## Obtenga el número de revisión de una firma + +Utilice este enfoque cuando un PDF ya contiene una o más firmas y necesite identificar la revisión asociada a una firma específica. El ejemplo resuelve el primer nombre de firma disponible y luego llama `get_revision()`. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def get_signature_revision(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + signature_revision = pdf_signature.get_revision(sign_name) + print(f"Signature Revision for '{sign_name}': {signature_revision}") + finally: + pdf_signature.close() +``` + +## Obtener el número total de revisiones del documento + +Usar `get_total_revision()` cuando necesitas saber cuántas revisiones se almacenan en el PDF firmado. Esto es útil para comprobar si el documento ha pasado por múltiples actualizaciones después de que se aplicó la firma original. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def get_total_document_revisions(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + total_revisions = pdf_signature.get_total_revision() + print(f"Total Document Revisions: {total_revisions}") + finally: + pdf_signature.close() +``` + +## Obtener permisos de acceso de un PDF certificado + +Los documentos certificados pueden definir qué cambios están permitidos después de la certificación. Usar `get_access_permissions()` para inspeccionar ese nivel de permiso y determinar si el documento permite no realizar cambios, rellenar formularios u otras modificaciones controladas. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def get_access_permissions(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + access_permissions = pdf_signature.get_access_permissions() + print(f"Access Permissions: {access_permissions}") + finally: + pdf_signature.close() +``` + diff --git a/es/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md b/es/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md new file mode 100644 index 000000000..6115059d0 --- /dev/null +++ b/es/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md @@ -0,0 +1,63 @@ +--- +title: Extracción de firma +linktitle: Extracción de firma +type: docs +weight: 50 +url: /es/python-net/signature-extraction/ +description: Aprenda cómo extraer una imagen de firma y el certificado de firma de un PDF firmado usando PdfFileSignature en Python. +lastmod: "2026-04-02" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Extraer imagen de firma y certificado de PDF en Python +Abstract: Este artículo explica cómo extraer datos relacionados con firmas de documentos PDF firmados con Aspose.PDF for Python via .NET. Muestra cómo leer la primera firma disponible, exportar su imagen y guardar el flujo del certificado asociado en un archivo de salida. +--- + +Aspose.PDF for Python via .NET proporciona el [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/) fachada para inspeccionar y extraer datos de documentos PDF firmados. Después de que un PDF ha sido firmado, puedes usarla para exportar recursos de firma como la imagen de firma visual y el certificado asociado a la firma. + +Este ejemplo demuestra dos tareas comunes de extracción: + +1. Extraer la imagen visual asociada a una firma. +1. Extraer el certificado de firma de un PDF firmado. + +## Extraer una imagen de firma + +Utiliza este método cuando el PDF contiene una firma visible y deseas exportar sus datos de imagen. El ejemplo abre el documento firmado, obtiene el primer nombre de firma disponible, extrae el flujo de la imagen y lo escribe en un archivo. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def extract_signature_image(infile, outfile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + signature_image = pdf_signature.extract_image(sign_name) + write_stream_data(signature_image, outfile) + finally: + pdf_signature.close() +``` + +## Extraer un certificado de firma + +Usar `extract_certificate()` cuando necesites los datos del certificado adjuntos a una firma. Esto es útil para inspección, flujos de trabajo de validación o para almacenar el certificado del firmante por separado del documento PDF. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def extract_signature_certificate(infile, outfile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + signature_certificate = pdf_signature.extract_certificate(sign_name) + write_stream_data(signature_certificate, outfile) + finally: + pdf_signature.close() +``` + diff --git a/es/python-net/working-with-facades/pdffilesignature/signature-information/_index.md b/es/python-net/working-with-facades/pdffilesignature/signature-information/_index.md new file mode 100644 index 000000000..1a43a47e6 --- /dev/null +++ b/es/python-net/working-with-facades/pdffilesignature/signature-information/_index.md @@ -0,0 +1,111 @@ +--- +title: Informacion de firmas +linktitle: Informacion de firmas +type: docs +weight: 60 +url: /es/python-net/signature-information/ +description: Aprenda a leer nombres de firmas, detalles del firmante, marcas de tiempo y metadatos de firmas de archivos PDF firmados usando PdfFileSignature en Python. +lastmod: "2026-04-02" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Leer detalles de firmas de documentos PDF en Python +Abstract: Este articulo explica como inspeccionar metadatos de firmas en documentos PDF firmados con Aspose.PDF for Python via .NET. Muestra como listar nombres de firmas, leer detalles del firmante, obtener la fecha y hora de firma, y extraer el motivo y la ubicacion de la firma. +--- + +Aspose.PDF for Python via .NET proporciona la fachada [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/) para inspeccionar firmas digitales en documentos PDF. Despues de que un documento se ha firmado, puede usarla para leer los nombres de las firmas y recuperar metadatos como el nombre del firmante, la informacion de contacto, la hora de firma, el motivo y la ubicacion. + +Este ejemplo demuestra cuatro tareas comunes de informacion de firmas: + +1. Listar todos los nombres de firma en un PDF firmado. +1. Leer los detalles del firmante para una firma seleccionada. +1. Obtener la fecha y hora de firma. +1. Leer el motivo y la ubicacion de la firma. + +## Obtener nombres de firmas + +Use este metodo cuando un PDF pueda contener una o varias firmas y desee inspeccionar que entradas de firma estan disponibles. El ejemplo abre el documento e imprime la lista devuelta por `get_sign_names()`. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def get_signature_names(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + signature_names = list_signature_names(pdf_signature) + print(f"Signature Names: {signature_names}") + finally: + pdf_signature.close() +``` + +## Obtener detalles del firmante + +Una vez que conoce el nombre de la firma, puede recuperar metadatos especificos del firmante. Este ejemplo lee el nombre del firmante y la informacion de contacto para la primera firma disponible en el documento. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def get_signer_details(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + signer_name = pdf_signature.get_signer_name(sign_name) + contact_info = pdf_signature.get_contact_info(sign_name) + print( + f"Signer Details for '{sign_name}': " + f"signer_name={signer_name}, contact_info={contact_info}" + ) + finally: + pdf_signature.close() +``` + +## Obtener la fecha y hora de la firma + +Use `get_date_time()` para determinar cuando se aplico una firma especifica. Esto resulta util para auditorias y para mostrar el historial de firmas en flujos de trabajo de documentos. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def get_signature_date_and_time(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + signature_date = pdf_signature.get_date_time(sign_name) + print(f"Signature Date and Time for '{sign_name}': {signature_date}") + finally: + pdf_signature.close() +``` + +## Obtener el motivo y la ubicacion de la firma + +Las firmas digitales tambien pueden almacenar metadatos descriptivos, como el motivo y la ubicacion de la firma. Este ejemplo recupera ambos valores para la firma seleccionada y los imprime juntos. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def get_signature_reason_and_location(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + signature_reason = pdf_signature.get_reason(sign_name) + signature_location = pdf_signature.get_location(sign_name) + print( + f"Signature Reason and Location for '{sign_name}': " + f"reason={signature_reason}, location={signature_location}" + ) + finally: + pdf_signature.close() +``` diff --git a/es/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md b/es/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md new file mode 100644 index 000000000..464985495 --- /dev/null +++ b/es/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md @@ -0,0 +1,63 @@ +--- +title: Comprobaciones de Integridad de Firma +linktitle: Comprobaciones de Integridad de Firma +type: docs +weight: 70 +url: /es/python-net/signature-integrity-checks/ +description: Aprenda cómo comprobar si una firma PDF cubre todo el documento y valide la integridad del documento firmado usando PdfFileSignature en Python. +lastmod: "2026-04-02" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Validar la cobertura e integridad de la firma PDF en Python +Abstract: Este artículo explica cómo inspeccionar la integridad de la firma digital en documentos PDF firmados con Aspose.PDF for Python via .NET. Muestra cómo verificar si una firma cubre todo el documento y cómo validar la integridad del contenido firmado. +--- + +Aspose.PDF for Python via .NET proporciona el [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/) fachada para validar documentos PDF firmados. Después de que un archivo ha sido firmado, puedes usarla para comprobar si la firma se aplica al documento completo y si el contenido firmado sigue siendo válido. + +Este ejemplo muestra dos comprobaciones de integridad comunes: + +1. Comprueba si una firma cubre todo el documento. +1. Valida la integridad del contenido PDF firmado. + +## Comprueba si una firma cubre todo el documento + +Usar `covers_whole_document()` cuando necesita confirmar que la firma se aplica a todo el PDF y no solo a una parte de su contenido. El ejemplo lee el primer nombre de firma disponible y verifica su cobertura. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def check_signature_coverage(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + covers_document = pdf_signature.covers_whole_document(sign_name) + print(f"Signature '{sign_name}' covers the whole document: {covers_document}") + finally: + pdf_signature.close() +``` + +## Validar la integridad del documento + +Usar `verify_signed()` para confirmar que el contenido del documento firmado no ha sido alterado después de que se aplicó la firma. Este método ayuda a verificar si el documento sigue siendo válido para la firma seleccionada. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def validate_document_integrity(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + is_valid = pdf_signature.verify_signed(sign_name) + print(f"Document integrity for '{sign_name}' is valid: {is_valid}") + finally: + pdf_signature.close() +``` + diff --git a/es/python-net/working-with-facades/pdffilesignature/signature-management/_index.md b/es/python-net/working-with-facades/pdffilesignature/signature-management/_index.md new file mode 100644 index 000000000..b36b03b07 --- /dev/null +++ b/es/python-net/working-with-facades/pdffilesignature/signature-management/_index.md @@ -0,0 +1,62 @@ +--- +title: Administracion de firmas +linktitle: Administracion de firmas +type: docs +weight: 80 +url: /es/python-net/signature-management/ +description: Aprenda a quitar firmas digitales de documentos PDF y, opcionalmente, limpiar campos de firma usando PdfFileSignature en Python. +lastmod: "2026-04-02" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Quitar firmas PDF y limpiar campos de firma en Python +Abstract: Este articulo explica como administrar firmas digitales existentes en documentos PDF con Aspose.PDF for Python via .NET. Muestra como quitar una firma de un PDF y como quitar una firma junto con su campo de firma asociado. +--- + +Aspose.PDF for Python via .NET proporciona la fachada [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/) para trabajar con firmas digitales existentes en documentos PDF. Ademas de leer y validar firmas, tambien puede quitarlas cuando un flujo de trabajo requiere actualizar el contenido firmado o limpiar el campo de firma. + +Este ejemplo demuestra dos tareas comunes de administracion de firmas: + +1. Quitar una firma de un documento PDF. +1. Quitar una firma y limpiar el campo de firma asociado. + +## Quitar una firma de un PDF + +Use `remove_signature()` cuando desee eliminar la firma seleccionada del documento y conservar la estructura del campo de firma subyacente. El ejemplo abre el PDF firmado, resuelve el nombre de la firma, la quita y guarda el archivo de salida actualizado. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def remove_signature_from_pdf(infile, outfile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + pdf_signature.remove_signature(sign_name) + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` + +## Quitar una firma y limpiar el campo + +Use la sobrecarga con el indicador adicional `True` cuando desee quitar la firma y tambien limpiar el campo de firma relacionado. Esto es util cuando el campo no debe permanecer en el documento despues de que la firma se haya eliminado. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def remove_signature_with_field_cleanup(infile, outfile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + pdf_signature.remove_signature(sign_name, True) + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` diff --git a/es/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md b/es/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md new file mode 100644 index 000000000..bdd81c322 --- /dev/null +++ b/es/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md @@ -0,0 +1,61 @@ +--- +title: Verificación de firmas +linktitle: Verificación de firmas +type: docs +weight: 90 +url: /es/python-net/signature-verification/ +description: Aprenda a verificar firmas digitales y a comprobar si un PDF contiene firmas usando PdfFileSignature en Python. +lastmod: "2026-04-02" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Verificar firmas PDF en Python +Abstract: Este artículo explica cómo verificar firmas digitales en documentos PDF con Aspose.PDF for Python via .NET. Muestra cómo validar una firma existente y cómo comprobar si un PDF contiene alguna firma. +--- + +Aspose.PDF for Python via .NET proporciona el [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/) fachada para validar documentos PDF firmados. Después de que un PDF ha sido firmado, puede usarla para confirmar que una firma es válida y detectar si el documento contiene entradas de firmas. + +Este ejemplo muestra dos tareas comunes de verificación: + +1. Verifique que una firma existente de PDF sea válida. +1. Compruebe si un PDF contiene alguna firma. + +## Verificar una firma de PDF + +Usar `verify_signature()` cuando necesitas validar una firma específica en el documento. El ejemplo resuelve el primer nombre de firma disponible y verifica si esa firma es válida. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def verify_pdf_signature(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + is_valid = pdf_signature.verify_signature(sign_name) + print(f"Signature '{sign_name}' is valid: {is_valid}") + finally: + pdf_signature.close() +``` + +## Verifique si un PDF contiene firmas + +Usar `contains_signature()` cuando solo necesitas saber si el PDF incluye alguna firma. Esto es útil como una verificación rápida antes de ejecutar una lógica de verificación o extracción más detallada. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def check_if_pdf_contains_signatures(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + contains_signatures = pdf_signature.contains_signature() + print(f"PDF contains signatures: {contains_signatures}") + finally: + pdf_signature.close() +``` diff --git a/es/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md b/es/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md new file mode 100644 index 000000000..f0d707e10 --- /dev/null +++ b/es/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md @@ -0,0 +1,63 @@ +--- +title: Administracion de derechos de uso +linktitle: Administracion de derechos de uso +type: docs +weight: 100 +url: /es/python-net/usage-rights-management/ +description: Aprenda a detectar y quitar derechos de uso de documentos PDF usando PdfFileSignature en Python. +lastmod: "2026-04-02" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Quitar derechos de uso de PDF en Python +Abstract: Este articulo explica como inspeccionar y quitar derechos de uso de documentos PDF con Aspose.PDF for Python via .NET. Muestra como comprobar si un PDF contiene derechos de uso y como guardar una nueva version del documento despues de quitar esos derechos. +--- + +Aspose.PDF for Python via .NET proporciona la fachada [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/) para trabajar con PDF firmados y configuraciones relacionadas de derechos de uso. En algunos flujos de trabajo, puede que necesite inspeccionar si un documento contiene derechos de uso y quitarlos antes de guardar una version actualizada del archivo. + +Este ejemplo demuestra una tarea comun de administracion de derechos de uso: + +1. Comprobar si un PDF contiene derechos de uso. +1. Quitar los derechos de uso del documento. +1. Guardar el archivo PDF actualizado. + +## Comprobar si el PDF contiene derechos de uso + +Antes de quitar derechos de uso, el ejemplo comprueba el estado actual del documento llamando a `contains_usage_rights()`. Esto le permite confirmar si los derechos de uso estan presentes antes de realizar cambios. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def check_usage_rights(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + had_usage_rights = pdf_signature.contains_usage_rights() + print(f"PDF contains usage rights: {had_usage_rights}") + finally: + pdf_signature.close() +``` + +## Quitar derechos de uso del PDF + +Use `remove_usage_rights()` cuando el documento ya no deba conservar su configuracion existente de derechos de uso. El ejemplo comprueba el estado inicial, quita los derechos y guarda el PDF actualizado en un nuevo archivo. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def remove_usage_rights(infile, outfile): + pdf_signature = create_pdf_file_signature(infile) + try: + had_usage_rights = pdf_signature.contains_usage_rights() + print(f"PDF contains usage rights before removal: {had_usage_rights}") + pdf_signature.remove_usage_rights() + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` diff --git a/es/python-net/working-with-facades/pdffilestamp/_index.md b/es/python-net/working-with-facades/pdffilestamp/_index.md new file mode 100644 index 000000000..4923123a1 --- /dev/null +++ b/es/python-net/working-with-facades/pdffilestamp/_index.md @@ -0,0 +1,26 @@ +--- +title: Clase PdfFileStamp +linktitle: Clase PdfFileStamp +type: docs +weight: 155 +url: /es/python-net/pdffilestamp-class/ +description: Aprenda a usar la clase PdfFileStamp en Aspose.PDF for Python via .NET para agregar encabezados, pies de pagina, numeros de pagina y sellos a documentos PDF. +lastmod: "2026-04-14" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Agregar encabezados, pies de pagina, numeros de pagina y sellos a PDF en Python con PdfFileStamp +Abstract: Esta seccion explica como usar la fachada PdfFileStamp en Aspose.PDF for Python via .NET para agregar contenido repetido a documentos PDF. Aprenda a colocar encabezados, pies de pagina, numeros de pagina y sellos en paginas PDF mediante programacion en aplicaciones Python. +--- + +La clase `PdfFileStamp` en Aspose.PDF Facades esta disenada para agregar contenido visual repetido a paginas PDF. Es util cuando necesita aplicar encabezados, pies de pagina, numeros de pagina o sellos en un documento sin editar manualmente cada pagina. + +## Que puede hacer con PdfFileStamp + +Use los articulos de esta seccion para explorar las tareas principales de sellado admitidas por la fachada `PdfFileStamp`: + +- [Agregar pies de pagina a paginas PDF con PdfFileStamp](/pdf/python-net/add-footer/) +- [Agregar encabezados a paginas PDF con PdfFileStamp](/pdf/python-net/add-header/) +- [Agregar numeros de pagina a documentos PDF con PdfFileStamp](/pdf/python-net/page-number/) +- [Agregar sellos a paginas PDF con PdfFileStamp](/pdf/python-net/add-stamp/) diff --git a/es/python-net/working-with-facades/pdffilestamp/add-footer/_index.md b/es/python-net/working-with-facades/pdffilestamp/add-footer/_index.md new file mode 100644 index 000000000..fa1440d9f --- /dev/null +++ b/es/python-net/working-with-facades/pdffilestamp/add-footer/_index.md @@ -0,0 +1,85 @@ +--- +title: Agregar pie de pagina a PDF +linktitle: Agregar pie de pagina a PDF +type: docs +weight: 10 +url: /es/python-net/add-footer/ +description: Aprenda a agregar pies de pagina de texto e imagen a paginas PDF usando PdfFileStamp en Python. +lastmod: "2026-04-13" +TechArticle: true +AlternativeHeadline: Agregar pies de pagina de texto e imagen a PDF en Python +Abstract: Este articulo explica como agregar contenido de pie de pagina a documentos PDF con Aspose.PDF for Python via .NET usando la fachada PdfFileStamp. Muestra como agregar un pie de pagina de texto, colocar un pie de pagina de imagen y aplicar margenes personalizados antes de guardar el PDF actualizado. +--- + +Aspose.PDF for Python via .NET proporciona la fachada [PdfFileStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilestamp/) para agregar contenido repetido a paginas PDF. Puede usarla para colocar texto o imagenes de pie de pagina en la parte inferior de cada pagina y ajustar los margenes del pie de pagina para controlar la ubicacion. + +## Agregar un pie de pagina de texto + +Use `add_footer()` con un objeto `FormattedText` cuando desee colocar el mismo texto de pie de pagina en todas las paginas del PDF. El segundo argumento establece el margen inferior usado para colocar el pie de pagina. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_text_footer(infile: str, outfile: str) -> None: + """Add a text footer with a bottom margin.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + text = pdf_facades.FormattedText("Sample Footer") + pdf_stamper.add_footer(text, 20) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Agregar un pie de pagina de imagen + +Use `add_footer()` con un flujo de imagen cuando el pie de pagina deba mostrar un logotipo u otra imagen en lugar de texto. El ejemplo abre el archivo de imagen como un flujo binario y lo coloca en la parte inferior de cada pagina. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_image_footer(infile: str, image_file: str, outfile: str) -> None: + """Add an image footer with a bottom margin.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + pdf_stamper.add_footer(image_file, 20) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Agregar un pie de pagina con margenes personalizados + +Use la sobrecarga con tres valores de margen cuando necesite mas control sobre la ubicacion del pie de pagina. En este ejemplo, el pie de pagina se agrega con margenes inferior, izquierdo y derecho personalizados. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_footer_with_margins(infile: str, outfile: str) -> None: + """Add a text footer with bottom, left, and right margins.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + text = pdf_facades.FormattedText("This footer has margins on all sides.") + pdf_stamper.add_footer(text, 20, 20, 20) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` diff --git a/es/python-net/working-with-facades/pdffilestamp/add-header/_index.md b/es/python-net/working-with-facades/pdffilestamp/add-header/_index.md new file mode 100644 index 000000000..97f3c8084 --- /dev/null +++ b/es/python-net/working-with-facades/pdffilestamp/add-header/_index.md @@ -0,0 +1,98 @@ +--- +title: Agregar encabezado a PDF +linktitle: Agregar encabezado a PDF +type: docs +weight: 20 +url: /es/python-net/add-header/ +description: Aprenda a agregar encabezados de texto e imagen a paginas PDF usando PdfFileStamp en Python. +lastmod: "2026-04-13" +TechArticle: true +AlternativeHeadline: Agregar encabezados de texto e imagen a PDF en Python +Abstract: Este articulo explica como agregar contenido de encabezado a documentos PDF con Aspose.PDF for Python via .NET usando la fachada PdfFileStamp. Muestra como agregar un encabezado de texto, colocar un encabezado de imagen y aplicar margenes personalizados antes de guardar el PDF actualizado. +--- + +Aspose.PDF for Python via .NET proporciona la fachada [PdfFileStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilestamp/) para agregar contenido repetido a paginas PDF. Puede usarla para colocar texto o imagenes de encabezado en la parte superior de cada pagina y ajustar los margenes del encabezado para controlar la ubicacion. + +## Agregar un encabezado de texto + +Use `add_header()` con un objeto `FormattedText` cuando desee colocar el mismo texto de encabezado en todas las paginas del PDF. El segundo argumento define el margen superior para el encabezado. + +```python +import sys +from os import path + +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_text_header(infile: str, outfile: str) -> None: + """Add a text header with a top margin.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + text = pdf_facades.FormattedText("Sample Header") + pdf_stamper.add_header(text, 20) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Agregar un encabezado de imagen + +Use `add_header()` con un archivo de imagen o un flujo de imagen cuando el encabezado deba mostrar un logotipo u otro grafico. Esto es util para disenos de documentos con marca. + +```python +import sys +from os import path + +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_image_header(infile: str, image_file: str, outfile: str) -> None: + """Add an image header with a top margin.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + pdf_stamper.add_header(image_file, 20) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Agregar un encabezado con margenes personalizados + +Use la sobrecarga con tres valores de margen cuando necesite mas control sobre la ubicacion del encabezado. En este ejemplo, el encabezado se agrega con margenes superior, izquierdo y derecho personalizados. + +```python +import sys +from os import path + +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_header_with_margins(infile: str, outfile: str) -> None: + """Add a text header with top, left, and right margins.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + text = pdf_facades.FormattedText( + text="Sample Header", + text_color=ap_pydrawing.Color.blue, + font_name="Arial", + text_encoding=pdf_facades.EncodingType.WINANSI, + embedded=True, + font_size=12.0, + ) + pdf_stamper.add_header(text, 20, 20, 20) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` diff --git a/es/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md b/es/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md new file mode 100644 index 000000000..1bd681717 --- /dev/null +++ b/es/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md @@ -0,0 +1,123 @@ +--- +title: Agregar numero de pagina a PDF +linktitle: Agregar numero de pagina a PDF +type: docs +weight: 30 +url: /es/python-net/page-number/ +description: Aprenda a agregar numeros de pagina a documentos PDF usando PdfFileStamp en Python. +lastmod: "2026-04-13" +TechArticle: true +AlternativeHeadline: Agregar numeros de pagina a PDF en Python +Abstract: Este articulo explica como agregar numeros de pagina a documentos PDF con Aspose.PDF for Python via .NET usando la fachada PdfFileStamp. Muestra como agregar numeros de pagina con la ubicacion predeterminada, colocarlos en coordenadas personalizadas y controlar la alineacion y los margenes. +--- + +Aspose.PDF for Python via .NET proporciona la fachada [PdfFileStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilestamp/) para agregar contenido repetido a paginas PDF. Puede usarla para insertar numeros de pagina con la ubicacion predeterminada, colocarlos en coordenadas especificas o controlar su alineacion y margenes. + +## Agregar numeros de pagina con la ubicacion predeterminada + +Use `add_page_number()` sin argumentos adicionales de posicion cuando desee agregar numeros de pagina en la ubicacion predeterminada. Esta es la forma mas sencilla de numerar todas las paginas del documento. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_page_numbers_default(infile: str, outfile: str) -> None: + """Add centered page numbers to the bottom of each page.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + pdf_stamper.add_page_number("Page #") + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Agregar numeros de pagina en coordenadas personalizadas + +Use la sobrecarga basada en coordenadas cuando necesite que los numeros de pagina aparezcan en una posicion X e Y especifica en cada pagina. Este enfoque es util cuando el diseno del documento requiere una ubicacion personalizada. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_page_numbers_at_coordinates(infile: str, outfile: str) -> None: + """Add page numbers at explicit X/Y coordinates.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + pdf_stamper.add_page_number("Page #", 300, 20) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Agregar numeros de pagina con alineacion y margenes + +Use la sobrecarga con argumentos de posicion y margen cuando necesite mas control sobre donde aparecen los numeros de pagina. En este ejemplo, los numeros se alinean en el area superior derecha de la pagina con margenes explicitos. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_page_numbers_with_position_and_margins(infile: str, outfile: str) -> None: + """Add page numbers using a predefined position and page margins.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + pdf_stamper.add_page_number( + "Page #", + pdf_facades.PdfFileStamp.POS_BOTTOM_RIGHT, + 10, + 10, + 10, + 10, + ) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Agregar numeros de pagina con estilo romano + +La funcion 'add_page_numbers_with_roman_style' muestra como mejorar un documento PDF agregando numeros de pagina con numeros romanos en mayusculas. Aprovecha la clase PdfFileStamp de Aspose.PDF para aplicar una numeracion coherente en todas las paginas. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_page_numbers_with_roman_style(infile: str, outfile: str) -> None: + """Add page numbers with a custom start value and Roman numbering.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + pdf_stamper.numbering_style = ap.NumberingStyle.NUMERALS_ROMAN_UPPERCASE + pdf_stamper.starting_number = 42 + pdf_stamper.add_page_number("Page #", pdf_facades.PdfFileStamp.POS_UPPER_RIGHT) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` diff --git a/es/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md b/es/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md new file mode 100644 index 000000000..b7f71d4ec --- /dev/null +++ b/es/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md @@ -0,0 +1,47 @@ +--- +title: Agregar sello a PDF +linktitle: Agregar sello a PDF +type: docs +weight: 40 +url: /es/python-net/add-stamp/ +description: Aprenda a agregar un sello a paginas PDF usando PdfFileStamp en Python. +lastmod: "2026-04-13" +TechArticle: true +AlternativeHeadline: Agregar sellos de texto a PDF en Python +Abstract: Este articulo explica como agregar contenido de sello a documentos PDF con Aspose.PDF for Python via .NET usando la fachada PdfFileStamp. Muestra como crear un sello, colocarlo en la pagina, controlar la rotacion y la opacidad, y guardar el PDF actualizado. +--- + +Aspose.PDF for Python via .NET proporciona la fachada [PdfFileStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilestamp/) para agregar contenido repetido a paginas PDF. Ademas de encabezados, pies de pagina y numeros de pagina, puede usarla para colocar sellos basados en texto en cada pagina de un documento. + +## Agregar el sello a un PDF + +Despues de configurar el sello, enlace el PDF de entrada a `PdfFileStamp`, agregue el sello y guarde el archivo de salida. Esto aplica el sello configurado en todo el documento. + +```python +import sys +from os import path + +import aspose.pdf.facades as pdf_facades + +CURRENT_DIR = path.dirname(__file__) +EXAMPLES_DIR = path.abspath(path.join(CURRENT_DIR, "..", "..")) +if EXAMPLES_DIR not in sys.path: + sys.path.insert(0, EXAMPLES_DIR) + +from config import initialize_data_dir, set_license + + +def add_stamp_to_pdf(infile: str, image_file: str, outfile: str) -> None: + """Add an image stamp to a PDF file.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + + stamp = pdf_facades.Stamp() + stamp.bind_image(image_file) + + pdf_stamper.add_stamp(stamp) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` diff --git a/es/python-net/working-with-facades/pdfviewer/_index.md b/es/python-net/working-with-facades/pdfviewer/_index.md new file mode 100644 index 000000000..7c6bbb3fa --- /dev/null +++ b/es/python-net/working-with-facades/pdfviewer/_index.md @@ -0,0 +1,116 @@ +--- +title: Clase PdfViewer +linktitle: Clase PdfViewer +type: docs +weight: 135 +url: /es/python-net/pdfviewer-class/ +description: Aprenda cómo usar la clase PdfViewer en Aspose.PDF for Python via .NET para decodificar todas las páginas PDF, decodificar una página específica y examinar los metadatos PDF relacionados con el visor. +lastmod: "2026-05-11" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Decodifique páginas PDF y examine los datos del visor en Python con PdfViewer +Abstract: Este artículo explica cómo usar la fachada PdfViewer en Aspose.PDF for Python via .NET para tareas de decodificación de páginas e inspección relacionadas con el visor. Aprenda cómo decodificar todas las páginas PDF, renderizar una página específica y examinar propiedades como el número de páginas, el tipo de coordenadas y la resolución. +--- + +Aspose.PDF for Python via .NET proporciona el [PdfViewer](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfviewer/) fachada para trabajar con la visualización de PDF y escenarios de decodificación de páginas. Un caso de uso común es convertir páginas PDF en objetos de imagen que luego pueden guardarse en el disco. + +## Crea un asistente PdfViewer reutilizable + +Antes de decodificar páginas o leer propiedades relacionadas con el visor, cree un pequeño asistente que inicialice y devuelva un `PdfViewer` instancia. Esto mantiene los ejemplos a continuación autocontenidos y deja claro cómo se crea el objeto viewer antes de que se vincule a un documento PDF. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + + +def _create_viewer() -> pdf_facades.PdfViewer: + """Create a PdfViewer configured for decoding examples.""" + viewer = pdf_facades.PdfViewer() + viewer.coordinate_type = ap.PageCoordinateType.MEDIA_BOX + viewer.resolution = 150 + viewer.scale_factor = 1.0 + viewer.show_hidden_areas = False + return viewer +``` + +## Decodificar todas las páginas PDF + +Usar `decode_all_pages()` cuando deseas convertir cada página del PDF en una imagen separada. Las imágenes de página devueltas pueden guardarse una por una en un directorio de salida. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def decode_all_pages(infile: str, output_dir: str) -> None: + """Decode all pages of a PDF document into image files.""" + viewer = _create_viewer() + try: + viewer.open_pdf_file(infile) + decoded_pages = viewer.decode_all_pages() + + for index, page_image in enumerate(decoded_pages, start=1): + image_path = path.join(output_dir, f"decode_all_pages_{index}.png") + page_image.save(image_path) + finally: + viewer.close_pdf_file() +``` + +## Decodificar una página PDF específica + +Usar `decode_page()` cuando solo necesitas una página del documento. Esto es útil al generar vistas previas, miniaturas o exportaciones específicas de página. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def decode_specific_page(infile: str, outfile: str, page_number: int = 1) -> None: + """Decode a specific PDF page into an image file.""" + viewer = _create_viewer() + try: + viewer.bind_pdf(infile) + page_image = viewer.decode_page(page_number) + page_image.save(outfile) + + finally: + viewer.close() +``` + +## Inspeccionar metadatos PDF + +El `inspect_pdf_metadata` La función demuestra cómo abrir un documento PDF y recuperar metadatos básicos relacionados con el visor usando Aspose.PDF. Se centra en extraer información que describe cómo se interpreta y muestra el documento, en lugar de su contenido. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def inspect_pdf_metadata(infile: str) -> None: + """Open a PDF and print page-count related viewer metadata.""" + viewer = _create_viewer() + try: + viewer.open_pdf_file(infile) + print(f"Page count: {viewer.page_count}") + print(f"Coordinate type: {viewer.coordinate_type}") + print(f"Resolution: {viewer.resolution}") + finally: + viewer.close_pdf_file() +``` diff --git a/es/python-net/working-with-facades/stamp/_index.md b/es/python-net/working-with-facades/stamp/_index.md new file mode 100644 index 000000000..2386dfd6c --- /dev/null +++ b/es/python-net/working-with-facades/stamp/_index.md @@ -0,0 +1,229 @@ +--- +title: Clase Stamp +linktitle: Clase Stamp +type: docs +weight: 150 +url: /es/python-net/stamp-class/ +description: Aprenda cómo trabajar con la clase Stamp para agregar sellos de imagen, PDF y basados en texto a documentos PDF en Python. +lastmod: "2026-04-13" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +Aspose.PDF for Python via .NET proporciona el [Sello](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/stamp/) clase para colocar contenido visual reutilizable en páginas PDF. Un sello puede basarse en texto, una imagen o incluso una página de otro PDF, y puede posicionarse, rotarse, estilizarse y limitarse a páginas específicas. + +Este artículo muestra varios flujos de trabajo comunes de sellos: + +1. Crea recursos de texto reutilizables para sellos basados en texto. +1. Agregar sellos de imagen y de página PDF. +1. Agregar sellos de texto con estilo. +1. Limitar un sello a páginas seleccionadas. +1. Configure un sello de imagen de fondo. + +El ejemplo usa dos funciones auxiliares: una crea texto formateado para sellos basados en texto, y la otra crea un `TextState` objeto utilizado para dar estilo a los sellos de texto. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as drawing + +from config import initialize_data_dir, set_license + + +def _create_text_logo(text: str) -> pdf_facades.FormattedText: + """Create formatted text for text stamp examples.""" + return pdf_facades.FormattedText( + text, + drawing.Color.blue, + drawing.Color.light_gray, + pdf_facades.FontStyle.HELVETICA_BOLD, + pdf_facades.EncodingType.WINANSI, + True, + 14, + ) + + +def _create_text_state() -> ap.text.TextState: + """Create a text state used to style text stamps.""" + text_state = ap.text.TextState() + text_state.foreground_color = ap.Color.dark_blue + text_state.font_size = 16 + text_state.font_style = ap.text.FontStyles.BOLD + return text_state +``` + +## Agregar una marca de imagen + +Usar `bind_image()` cuando el sello debe mostrar una imagen como un logo, insignia o ícono. Después de enlazar la imagen, puedes establecer el ID del sello y el origen antes de añadirlo al documento. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as drawing + +from config import initialize_data_dir, set_license + + +def add_image_stamp(infile: str, image_file: str, outfile: str) -> None: + """Add an image stamp to the PDF.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + + stamp = pdf_facades.Stamp() + stamp.bind_image(image_file) + stamp.stamp_id = 1 + stamp.set_origin(36, 520) + + pdf_stamper.add_stamp(stamp) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Agregar una página PDF como sello + +Usar `bind_pdf()` cuando deseas usar una página de otro archivo PDF como contenido del sello. Esto es útil para superposiciones, como aprobaciones, plantillas o elementos visuales preconstruidos almacenados en un documento separado. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as drawing + +from config import initialize_data_dir, set_license + + +def add_pdf_page_as_stamp(infile: str, stamp_pdf: str, outfile: str) -> None: + """Add the first page of another PDF as a stamp.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + + stamp = pdf_facades.Stamp() + stamp.bind_pdf(stamp_pdf, 1) + stamp.page_number = 1 + stamp.set_origin(36, 250) + + pdf_stamper.add_stamp(stamp) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Agregar una marca de texto con estado de texto + +Usar `bind_logo()` junto con `bind_text_state()` cuando deseas crear un sello basado en texto con estilo de fuente personalizado. Este enfoque es útil para marcas de aprobación, etiquetas y anotaciones específicas del flujo de trabajo. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as drawing + +from config import initialize_data_dir, set_license + + +def add_text_stamp_with_text_state(infile: str, outfile: str) -> None: + """Add a text stamp and style it with a TextState object.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + + stamp = pdf_facades.Stamp() + stamp.bind_logo(_create_text_logo("Approved by signing workflow")) + stamp.bind_text_state(_create_text_state()) + stamp.set_origin(36, 700) + stamp.rotation = 15.0 + + pdf_stamper.add_stamp(stamp) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Agregar un sello a páginas específicas + +Si el sello no debe aparecer en cada página, asigne los números de página de destino a la `pages` propiedad. Este ejemplo agrega un ImageStamp solo a la primera página. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as drawing + +from config import initialize_data_dir, set_license + + +def add_stamp_to_specific_pages(infile: str, image_file: str, outfile: str) -> None: + """Add an image stamp only to the selected pages.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + + stamp = pdf_facades.Stamp() + stamp.bind_image(image_file) + stamp.pages = [1] + stamp.set_origin(400, 40) + stamp.set_image_size(120, 60) + + pdf_stamper.add_stamp(stamp) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Agregar una marca de imagen de fondo + +Utiliza un sello de fondo cuando la imagen debe aparecer detrás del contenido de la página. También puedes controlar la opacidad, rotación, calidad, tamaño y posición del sello para crear efectos estilo marca de agua. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as drawing + +from config import initialize_data_dir, set_license + + +def add_background_image_stamp(infile: str, image_file: str, outfile: str) -> None: + """Add a rotated background image stamp with opacity and quality settings.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + + stamp = pdf_facades.Stamp() + stamp.bind_image(image_file) + stamp.is_background = True + stamp.opacity = 0.35 + stamp.quality = 90 + stamp.rotation = 45.0 + stamp.set_image_size(160, 80) + stamp.set_origin(200, 300) + + pdf_stamper.add_stamp(stamp) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Temas relacionados con Facades + +- [Trabajando con fachadas PDF en Python](/pdf/es/python-net/working-with-facades/) +- [Agregar encabezados, pies de página y sellos con PdfFileStamp](/pdf/es/python-net/pdffilestamp-class/) +- [Agregar un sello de página a archivos PDF en Python](/pdf/es/python-net/add-stamp/) diff --git a/ru/python-net/_index.md b/ru/python-net/_index.md index 3a6e874e4..f90262499 100644 --- a/ru/python-net/_index.md +++ b/ru/python-net/_index.md @@ -1,7 +1,7 @@ --- title: Документация -linktitle: Aspose.PDF для Python через .NET -second_title: Aspose.PDF для Python через .NET +linktitle: Aspose.PDF for Python via .NET +second_title: Aspose.PDF for Python via .NET type: docs weight: 40 url: /ru/python-net/ @@ -9,13 +9,13 @@ is_root: true lastmod: "2022-10-24" description: Узнайте, как использовать Aspose.PDF Python через .NET для создания приложений для обработки PDF-документов на любой платформе с использованием Python. Ознакомьтесь с учебниками, примерами кода и многим другим. sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 --- -![Логотип Aspose.PDF для Python через .NET](aspose_pdf-for-python-net.png) +![Логотип Aspose.PDF for Python via .NET](aspose_pdf-for-python-net.png) -

              Добро пожаловать в Aspose.PDF для Python через .NET

              +## Добро пожаловать в Aspose.PDF for Python via .NET {{% alert color="primary" %}} @@ -24,7 +24,7 @@ Aspose.PDF — это компонент .NET, созданный для тог {{% /alert %}} -

              Главы

              +## Главы - [Что нового](/pdf/ru/python-net/whatsnew/) - [Обзор](/pdf/ru/python-net/overview/) @@ -36,14 +36,14 @@ Aspose.PDF — это компонент .NET, созданный для тог - [Витрины](/pdf/ru/python-net/showcases/) - [Примечания к выпуску](https://releases.aspose.com/pdf/pythonnet/release-notes/) -

              Ресурсы Aspose.PDF для Python через .NET

              +## Ресурсы Aspose.PDF for Python via .NET Ниже приведены ссылки на некоторые полезные ресурсы, которые могут понадобиться для выполнения ваших задач. -- [Aspose.PDF для Python через .NET Возможности](/pdf/ru/python-net/key-features/) -- [Aspose.PDF для Python через .NET Примечания к выпуску](https://releases.aspose.com/pdf/pythonnet/release-notes/) -- [Aspose.PDF для Python через .NET Страница продукта](https://products.aspose.com/pdf/python-net/) -- [Скачать Aspose.PDF для Python через .NET](https://releases.aspose.com/pdf/pythonnet/) -- [Установить пакет Aspose.PDF для Python через .NET NuGet](https://www.nuget.org/packages/Aspose.PDF/) -- [Aspose.PDF для Python через .NET Руководство по API](https://reference.aspose.com/pdf/net)! -- [Aspose.PDF для Python через .NET Форум бесплатной поддержки](https://forum.aspose.com/c/pdf/10) -- [Aspose.PDF для Python через .NET Платная поддержка](https://helpdesk.aspose.com/) \ No newline at end of file + +- [Aspose.PDF for Python via .NET Возможности](/pdf/ru/python-net/key-features/) +- [Aspose.PDF for Python via .NET Примечания к выпуску](https://releases.aspose.com/pdf/pythonnet/release-notes/) +- [Aspose.PDF for Python via .NET Страница продукта](https://products.aspose.com/pdf/python-net/) +- [Скачать Aspose.PDF for Python via .NET](https://releases.aspose.com/pdf/pythonnet/) +- [Aspose.PDF for Python via .NET Руководство по API](https://reference.aspose.com/pdf/net)! +- [Aspose.PDF for Python via .NET Форум бесплатной поддержки](https://forum.aspose.com/c/pdf/10) +- [Aspose.PDF for Python via .NET Платная поддержка](https://helpdesk.aspose.com/) \ No newline at end of file diff --git a/ru/python-net/advanced-operations/_index.md b/ru/python-net/advanced-operations/_index.md index 14fe22a25..72724cdca 100644 --- a/ru/python-net/advanced-operations/_index.md +++ b/ru/python-net/advanced-operations/_index.md @@ -4,10 +4,10 @@ linktitle: Advanced operations type: docs weight: 90 url: /ru/python-net/advanced-operations/ -description: Aspose.PDF для Python через .NET может выполнять простые и легкие задачи, а также справляться с более сложными целями. Ознакомьтесь со следующим разделом для продвинутых пользователей и разработчиков. +description: Aspose.PDF for Python via .NET может выполнять простые и легкие задачи, а также справляться с более сложными целями. Ознакомьтесь со следующим разделом для продвинутых пользователей и разработчиков. lastmod: "2023-04-17" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 --- +Аннотации в PDF являются интерактивными элементами, позволяющими добавлять заметки, выделять текст, рисовать фигуры, прикреплять файлы и запускать действия непосредственно на странице. Они полезны для процессов рецензирования, совместной работы, навигации и разметки документов. -Annotations in PDFs are interactive elements that allow you to add notes, highlight text, draw shapes, attach files, and perform other actions that improve browsing, interactivity, and interaction. +Aspose.PDF for Python via .NET поддерживает широкий спектр сценариев аннотирования, включая заметки и всплывающие аннотации, разметку текста, ссылки и кнопки, фигуры, водяные знаки, мультимедийные аннотации, а также рабочие процессы импорта или экспорта аннотаций. -Аннотации в PDF являются интерактивными элементами, которые позволяют добавлять заметки, выделять текст, рисовать фигуры, прикреплять файлы и выполнять другие действия, которые улучшают просмотр, интерактивность и взаимодействие. +Используйте этот раздел, чтобы выбрать рабочий процесс аннотирования, соответствующий вашей задаче, независимо от того, нужно ли вам создавать новые аннотации, просматривать существующие, удалять их или перемещать между PDF‑документами. -The Aspose.PDF for Python Library supports various types of annotations, including text annotations (such as text, and popup annotation), highlights annotations (such as text markup), figures annotations( such as circle, polyline, polygon, line, and ink), multimedia annotations ( there are screen, sound, widget, and 3D) and more. +## Темы аннотирования -Библиотека Aspose.PDF для Python поддерживает различные виды аннотаций, включая текстовые аннотации (такие как текстовые и всплывающие аннотации), аннотации выделения (такие как разметка текста), аннотации фигур (такие как круг, полилиния, полигон, линия и чернила), мультимедиа аннотации (такие как экран, звук, виджет и 3D) и другие. +Используйте этот раздел, когда вам нужно добавить, получить, обновить, удалить или перенести аннотации в PDF‑файлах с помощью Python. Ниже приведённые ссылки охватывают как основные рабочие процессы аннотирования, так и сгруппированные семейства аннотаций, используемые в документации. -Annotations can be used to comment, review, mark documents, provide feedback, or add additional information. Annotations allow to establish cooperation, facilitate communication, and improve understanding of the content of documents. They enhance collaboration, improve communication, and make PDF documents more dynamic and engaging for users. +Вы можете использовать следующие темы: -Аннотации могут использоваться для комментирования, рецензирования, маркировки документов, предоставления обратной связи или добавления дополнительной информации. Аннотации позволяют устанавливать сотрудничество, облегчать коммуникацию и улучшать понимание содержимого документов. Они усиливают сотрудничество, улучшают коммуникацию и делают PDF-документы более динамичными и увлекательными для пользователей. +- [Добавление, удаление и получение аннотации](/pdf/ru/python-net/add-delete-and-get-annotation/) - начните здесь с основных групповых категорий аннотаций и основных процессов создания, инспекции и удаления. +- [Импорт и экспорт аннотаций](/pdf/ru/python-net/import-export-annotations/) - копировать аннотации из одного PDF‑документа в другой PDF‑файл. -You are able to do the following: +### Группы аннотаций -Вы можете выполнить следующие действия: +Руководство по групповым аннотациям включает следующие подтемы: -- [Add, Delete and Get Annotation](/pdf/ru/python-net/add-delete-and-get-annotation/) - this section explains how to work with all types of allowed annotations. - -- [Добавить, удалить и получить аннотацию](/pdf/ru/python-net/add-delete-and-get-annotation/) - этот раздел объясняет, как работать со всеми типами разрешенных аннотаций. - - \ No newline at end of file +- [Текстовые аннотации](/pdf/ru/python-net/text-based-Annotations/) - работать с аннотациями свободного текста, выделения, подчеркивания, волнистой линии и зачеркивания. +- [Разметочные аннотации](/pdf/ru/python-net/markup-annotations/) - добавлять или просматривать заметки, каретку и заменяющие аннотации, используемые в сценариях рецензирования. +- [Интерактивные аннотации](/pdf/ru/python-net/interactive-annotations/) - создавать аннотации ссылок, кнопки навигации и кнопки печати. +- [Фигурные аннотации](/pdf/ru/python-net/shape-annotations/) - используйте аннотации линии, квадрата, круга, многоугольника и полилинии. +- [Медийные аннотации](/pdf/ru/python-net/media-annotations/) - добавьте аннотации звука, экрана, интерактивных медиа и 3D. +- [Аннотации безопасности](/pdf/ru/python-net/security-annotations/) - работайте с аннотациями вложения файлов, редактирования и другими аннотациями, ориентированными на защиту. +- [Аннотации водяных знаков](/pdf/ru/python-net/watermark-annotations/) - добавлять и управлять элементами водяных знаков на основе аннотаций. +Аннотации особенно полезны для рецензирования документов, совместной работы, разметки контента и интерактивной навигации. Начните с группового обзора, когда хотите просмотреть поддерживаемые типы аннотаций, или перейдите непосредственно к конкретной теме, если уже знаете необходимый рабочий процесс. diff --git a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md index 703f8a6b6..e396ef757 100644 --- a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md +++ b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md @@ -1,99 +1,34 @@ --- -title: Добавление, удаление и получение аннотации с использованием Python +title: Добавление, удаление и получение PDF‑аннотаций в Python linktitle: Добавление, удаление и получение аннотации type: docs weight: 20 url: /ru/python-net/add-delete-and-get-annotation/ -description: С помощью Aspose.PDF для Python вы можете добавлять, удалять и получать аннотации из вашего PDF файла. Проверьте все списки аннотаций для решения вашей задачи. -lastmod: "2023-02-17" +description: С помощью Aspose.PDF for Python вы можете добавлять, удалять и получать аннотации из вашего PDF‑файла. Просмотрите все списки аннотаций, чтобы решить задачу. +lastmod: "2026-05-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Как управлять аннотациями в PDF с помощью Python +Abstract: Аннотации в PDF‑документах повышают взаимодействие с пользователем, позволяя добавлять различные элементы, такие как заметки, подсветка текста, фигуры и вложения файлов. Эти возможности улучшают восприятие документа и его интерактивность. Библиотека Aspose.PDF for Python классифицирует аннотации на несколько групп — Текстовые аннотации, Аннотации‑выделения, Фигурные аннотации, Липкие аннотации и Дополнительные аннотации, каждая из которых выполняет различные функции, обогащая взаимодействие с документом и его удобство использования. --- - +Аннотации в PDF‑документах — это элементы, позволяющие пользователям размещать контент в документе определённым образом. С их помощью можно добавлять различные типы заметок, выделять текст, рисовать фигуры, прикреплять файлы и выполнять другие действия, улучшающие просмотр, интерактивность и взаимодействие в документе. -**Что такое аннотации в PDF-документах?** +Эта страница группирует основные типы аннотаций, поддерживаемые в этой части документации, чтобы вы могли быстро перейти к нужному рабочему процессу. -Аннотации в PDF-документах — это элементы, которые позволяют пользователям размещать контент определенным образом в документе. Аннотации могут использоваться для добавления различных типов заметок, выделения текста, рисования фигур, прикрепления файлов и выполнения других действий, которые улучшают просмотр, интерактивность и взаимодействие внутри документа. +Мы объединили различные типы аннотаций, доступные для библиотеки Aspose.PDF for Python в группы: -Мы объединили различные виды аннотаций, доступные для библиотеки Aspose.PDF для Python, в группы: +- [Интерактивные аннотации](/pdf/ru/python-net/interactive-annotations/) +- [Аннотации разметки](/pdf/ru/python-net/markup-annotations/) +- [Медиа‑аннотации](/pdf/ru/python-net/media-annotations/) +- [Аннотации безопасности](/pdf/ru/python-net/security-annotations/) +- [Фигурные аннотации](/pdf/ru/python-net/shape-annotations/) +- [Текстовые аннотации](/pdf/ru/python-net/text-based-Annotations/) +- [Аннотации водяных знаков](/pdf/ru/python-net/watermark-annotations/) -- [Импорт и экспорт аннотаций](/pdf/python-net/import-export-annotations/) -- [Интерактивные аннотации](/pdf/python-net/interactive-annotations/) -- [Аннотации разметки](/pdf/python-net/markup-annotations/) -- [Аннотации медиафайлов](/pdf/python-net/media-annotations/) -- [Аннотации безопасности](/pdf/python-net/security-annotations/) -- [Аннотации фигур](/pdf/python-net/shape-annotations/) -- [Аннотации текста](/pdf/python-net/text-based-Annotations/) -- [Аннотации водяных знаков](/pdf/python-net/watermark-annotations/) +## Связанные темы аннотаций -## Связанные темы аннотирования - -- [Обзор Аннотаций PDF](/pdf/python-net/annotations/) для родительского раздела и концепций аннотирования. -- [Аннотации к тексту в формате PDF](/pdf/python-net/text-annotation/) для рабочих процессов аннотирования в стиле заметок и на основе текста. -- [Аннотации к рисункам в формате PDF](/pdf/python-net/figures-annotation/) для аннотаций на основе фигур, таких как круги, многоугольники и линии. \ No newline at end of file +- [Обзор аннотаций PDF](/pdf/ru/python-net/annotations/) для родительского раздела и концепций аннотаций. +- [Импорт и экспорт аннотаций](/pdf/ru/python-net/import-export-annotations/) diff --git a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/import-export-annotations/_index.md b/ru/python-net/advanced-operations/annotations/import-export-annotations/_index.md similarity index 100% rename from ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/import-export-annotations/_index.md rename to ru/python-net/advanced-operations/annotations/import-export-annotations/_index.md diff --git a/ru/python-net/advanced-operations/working-with-forms/acroforms/remove-form/_index.md b/ru/python-net/advanced-operations/working-with-forms/acroforms/remove-form/_index.md index 696af8e73..c603a6cef 100644 --- a/ru/python-net/advanced-operations/working-with-forms/acroforms/remove-form/_index.md +++ b/ru/python-net/advanced-operations/working-with-forms/acroforms/remove-form/_index.md @@ -7,7 +7,7 @@ url: /ru/python-net/remove-form/ description: Удалить объекты форм со страниц PDF, используя Aspose.PDF for Python via .NET, включая полную очистку и целевое удаление. lastmod: "2026-04-28" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 TechArticle: true AlternativeHeadline: Удалить формы из PDF с помощью Aspose.PDF for Python via .NET diff --git a/ru/python-net/advanced-operations/working-with-forms/xfa-forms/_index.md b/ru/python-net/advanced-operations/working-with-forms/xfa-forms/_index.md index 1dbced90a..d57ba3037 100644 --- a/ru/python-net/advanced-operations/working-with-forms/xfa-forms/_index.md +++ b/ru/python-net/advanced-operations/working-with-forms/xfa-forms/_index.md @@ -7,7 +7,7 @@ url: /ru/python-net/xfa-forms/ description: Aspose.PDF for Python via .NET API позволяет работать с полями XFA и XFA Acroform в PDF-документе. lastmod: "2025-02-17" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 --- diff --git a/ru/python-net/advanced-operations/working-with-images/_index.md b/ru/python-net/advanced-operations/working-with-images/_index.md index 5fa6146af..50e718d34 100644 --- a/ru/python-net/advanced-operations/working-with-images/_index.md +++ b/ru/python-net/advanced-operations/working-with-images/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Добавление, извлечение, замена и Abstract: В этом разделе объясняется, как работать с изображениями в PDF‑документах с использованием Aspose.PDF for Python via .NET. Узнайте, как добавлять изображения в существующие PDF, удалять или заменять встроенные изображения, извлекать изображения со страниц и проверять свойства размещения изображений в Python‑процессах. --- -Aspose.PDF для Python через .NET предоставляет полный набор инструментов для работы с изображениями в существующих PDF-документах. +Aspose.PDF for Python via .NET предоставляет полный набор инструментов для работы с изображениями в существующих PDF-документах. Используйте этот раздел для вставки новых изображений, удаления или замены встроенных изображений, извлечения содержимого изображений и проверки деталей размещения изображений на странице. diff --git a/ru/python-net/advanced-operations/working-with-pages/_index.md b/ru/python-net/advanced-operations/working-with-pages/_index.md index c8a1b03ad..8fb65d3ef 100644 --- a/ru/python-net/advanced-operations/working-with-pages/_index.md +++ b/ru/python-net/advanced-operations/working-with-pages/_index.md @@ -16,7 +16,7 @@ Abstract: В этом разделе объясняется, как работа Этот раздел используется, когда вам необходимо выполнять операции с PDF-файлами на уровне страниц в Python. -С помощью **Aspose.PDF для Python через .NET** вы можете вставлять, удалять, перемещать, извлекать, поворачивать, изменять размер и обрезать страницы, а также применять верхние и нижние колонтитулы, номера страниц, водяные знаки и штампы для процессов верстки и проверки. +С помощью **Aspose.PDF for Python via .NET** вы можете вставлять, удалять, перемещать, извлекать, поворачивать, изменять размер и обрезать страницы, а также применять верхние и нижние колонтитулы, номера страниц, водяные знаки и штампы для процессов верстки и проверки. ## Рассматриваемые задачи для страниц diff --git a/ru/python-net/advanced-operations/working-with-pages/change-page-size/_index.md b/ru/python-net/advanced-operations/working-with-pages/change-page-size/_index.md index da469fea9..6d706bf85 100644 --- a/ru/python-net/advanced-operations/working-with-pages/change-page-size/_index.md +++ b/ru/python-net/advanced-operations/working-with-pages/change-page-size/_index.md @@ -7,7 +7,7 @@ url: /ru/python-net/change-page-size/ description: Узнайте, как читать и изменять размеры страниц PDF в Python. lastmod: "2026-04-15" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 TechArticle: true AlternativeHeadline: Изменение размера страницы с помощью Python diff --git a/ru/python-net/advanced-operations/working-with-tables/integrate-table-in-existing-pdf-document/_index.md b/ru/python-net/advanced-operations/working-with-tables/integrate-table-in-existing-pdf-document/_index.md index a5cf59662..abae82a35 100644 --- a/ru/python-net/advanced-operations/working-with-tables/integrate-table-in-existing-pdf-document/_index.md +++ b/ru/python-net/advanced-operations/working-with-tables/integrate-table-in-existing-pdf-document/_index.md @@ -7,7 +7,7 @@ url: /ru/python-net/integrate-table/ description: Узнайте, как интегрировать PDF‑таблицы с источниками данных, такими как базы данных и pandas DataFrames, на Python. lastmod: "2026-04-17" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 TechArticle: true AlternativeHeadline: Интегрировать PDF‑таблицы с базами данных и DataFrames с помощью Python diff --git a/ru/python-net/advanced-operations/working-with-tables/manipulate-tables-in-existing-pdf/_index.md b/ru/python-net/advanced-operations/working-with-tables/manipulate-tables-in-existing-pdf/_index.md index 6c65e3321..018636359 100644 --- a/ru/python-net/advanced-operations/working-with-tables/manipulate-tables-in-existing-pdf/_index.md +++ b/ru/python-net/advanced-operations/working-with-tables/manipulate-tables-in-existing-pdf/_index.md @@ -7,7 +7,7 @@ url: /ru/python-net/manipulating-tables/ description: Узнайте, как просматривать и изменять таблицы в существующих PDF‑документах с помощью Python. lastmod: "2026-04-27" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 TechArticle: true AlternativeHeadline: Измените существующие таблицы PDF с помощью Python diff --git a/ru/python-net/advanced-operations/working-with-text/rotate-text-inside-pdf/_index.md b/ru/python-net/advanced-operations/working-with-text/rotate-text-inside-pdf/_index.md index c18925795..3f62fb740 100644 --- a/ru/python-net/advanced-operations/working-with-text/rotate-text-inside-pdf/_index.md +++ b/ru/python-net/advanced-operations/working-with-text/rotate-text-inside-pdf/_index.md @@ -11,7 +11,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Как повернуть текст в PDF с помощью Python -Abstract: Статья предоставляет подробное руководство о том, как вращать текст в PDF‑документе с использованием библиотеки Aspose.PDF для Python через .NET. В ней описывается использование свойства `Rotation` класса `TextFragment` для выполнения вращения текста под различными углами, что полезно в различных сценариях генерации документов. Демонстрируется создание фрагментов текста с указанными углами вращения и их добавление на страницу PDF с помощью `TextBuilder`. Показано, как добавлять повернутые фрагменты текста к `TextParagraph` и затем добавлять абзац на страницу PDF. Показано, как добавить повернутые фрагменты текста непосредственно в коллекцию абзацев страницы. Объясняется вращение целого абзаца с несколькими фрагментами текста. +Abstract: Статья предоставляет подробное руководство о том, как вращать текст в PDF‑документе с использованием библиотеки Aspose.PDF for Python via .NET. В ней описывается использование свойства `Rotation` класса `TextFragment` для выполнения вращения текста под различными углами, что полезно в различных сценариях генерации документов. Демонстрируется создание фрагментов текста с указанными углами вращения и их добавление на страницу PDF с помощью `TextBuilder`. Показано, как добавлять повернутые фрагменты текста к `TextParagraph` и затем добавлять абзац на страницу PDF. Показано, как добавить повернутые фрагменты текста непосредственно в коллекцию абзацев страницы. Объясняется вращение целого абзаца с несколькими фрагментами текста. --- Повернуть фрагменты текста в PDF‑документе с помощью Aspose.PDF for Python via .NET. Он показывает, как точно контролировать позицию и вращение отдельных текстовых элементов, комбинируя классы 'TextFragment', 'TextState' и 'TextBuilder'. Регулируя угол вращения для каждого фрагмента текста, вы можете создавать визуально динамичные макеты, такие как диагональные заголовки, вертикальные метки или повернутые аннотации. diff --git a/ru/python-net/basic-operations/_index.md b/ru/python-net/basic-operations/_index.md index aa2a0a26d..c043c2b29 100644 --- a/ru/python-net/basic-operations/_index.md +++ b/ru/python-net/basic-operations/_index.md @@ -5,7 +5,7 @@ type: docs weight: 60 url: /ru/python-net/basic-operations/ lastmod: "2025-02-27" -description: Раздел базовых операций описывает возможности открытия и сохранения PDF-документов с помощью Aspose.PDF для Python через .NET. +description: Раздел базовых операций описывает возможности открытия и сохранения PDF-документов с помощью Aspose.PDF for Python via .NET. sitemap: changefreq: "monthly" priority: 0.5 diff --git a/ru/python-net/basic-operations/merge-pdf/_index.md b/ru/python-net/basic-operations/merge-pdf/_index.md index 1f9ab75f4..c6ddaa1ce 100644 --- a/ru/python-net/basic-operations/merge-pdf/_index.md +++ b/ru/python-net/basic-operations/merge-pdf/_index.md @@ -11,7 +11,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Объединение страниц PDF с помощью Python -Abstract: В этой статье рассматривается распространённая необходимость объединения нескольких PDF-файлов в один документ — процесс, ценный для организации и оптимизации хранения и передачи PDF-содержимого. В ней исследуется использование Aspose.PDF для Python через .NET для эффективного объединения PDF-файлов, признавая, что объединение PDF в Python может быть сложным без сторонних библиотек. Статья содержит пошаговое руководство по объединению PDF-файлов — создание нового документа, объединение файлов и сохранение объединённого документа. Фрагмент кода демонстрирует реализацию с помощью Aspose.PDF, подчёркивая способность библиотеки упростить процесс объединения. Кроме того, представлен онлайн-инструмент Aspose.PDF Merger для объединения PDF, позволяющий пользователям изучить функциональность в веб-среде. +Abstract: В этой статье рассматривается распространённая необходимость объединения нескольких PDF-файлов в один документ — процесс, ценный для организации и оптимизации хранения и передачи PDF-содержимого. В ней исследуется использование Aspose.PDF for Python via .NET для эффективного объединения PDF-файлов, признавая, что объединение PDF в Python может быть сложным без сторонних библиотек. Статья содержит пошаговое руководство по объединению PDF-файлов — создание нового документа, объединение файлов и сохранение объединённого документа. Фрагмент кода демонстрирует реализацию с помощью Aspose.PDF, подчёркивая способность библиотеки упростить процесс объединения. Кроме того, представлен онлайн-инструмент Aspose.PDF Merger для объединения PDF, позволяющий пользователям изучить функциональность в веб-среде. --- ## Объединение PDF-файлов с помощью Python и DOM diff --git a/ru/python-net/converting/convert-pdf-to-images-format/_index.md b/ru/python-net/converting/convert-pdf-to-images-format/_index.md index b47de1d4b..f5a5f3dc3 100644 --- a/ru/python-net/converting/convert-pdf-to-images-format/_index.md +++ b/ru/python-net/converting/convert-pdf-to-images-format/_index.md @@ -4,122 +4,126 @@ linktitle: Конвертировать PDF в изображения type: docs weight: 70 url: /ru/python-net/convert-pdf-to-images-format/ -lastmod: "2026-04-14" -description: Узнайте, как преобразовать страницы PDF в изображения, такие как PNG, JPEG или TIFF, используя Aspose.PDF в Python через .NET. +lastmod: "2026-05-08" +description: Узнайте, как рендерить страницы PDF в файлы TIFF, BMP, EMF, JPEG, PNG, GIF и SVG в Python с помощью Aspose.PDF for Python via .NET. sitemap: changefreq: "monthly" priority: 0.5 TechArticle: true -AlternativeHeadline: Как конвертировать PDF в форматы изображений в Python -Abstract: Эта статья предоставляет исчерпывающее руководство по конвертации PDF‑файлов в различные форматы изображений с использованием Python, в частности с помощью библиотеки Aspose.PDF for Python. Документ описывает методы преобразования PDF в форматы изображений, включая TIFF, BMP, EMF, JPG, PNG, GIF и SVG. Рассмотрены два основных подхода к конвертации — использование подхода Device и SaveOption. Подход Device предполагает использование классов, таких как `DocumentDevice` и `ImageDevice`, для конвертации всего документа или отдельных страниц. Предоставлены подробные шаги и примеры кода на Python для преобразования страниц PDF в различные форматы, такие как TIFF с использованием `TiffDevice`, а также BMP, EMF, JPEG, PNG и GIF с помощью соответствующих классов устройств (`BmpDevice`, `EmfDevice`, `JpegDevice`, `PngDevice`, `GifDevice`). Для конвертации в SVG вводится класс `SvgSaveOptions`. В статье также отмечены онлайн‑инструменты для тестирования этих конвертаций. +AlternativeHeadline: Преобразуйте страницы PDF в TIFF, PNG, JPEG, GIF, BMP, EMF и SVG в Python. +Abstract: В этой статье объясняется, как преобразовать файлы PDF в распространённые форматы изображений с помощью Aspose.PDF for Python via .NET. В ней рассматривается экспорт TIFF на уровне всего документа с использованием `TiffDevice`, генерация растровых изображений постранично с помощью подклассов `ImageDevice`, таких как `BmpDevice`, `JpegDevice`, `PngDevice`, `GifDevice` и `EmfDevice`, а также векторный экспорт в SVG с использованием `SvgSaveOptions`. Каждый раздел содержит основные шаги и примеры на Python, необходимые для сохранения содержимого PDF в виде изображений. --- -## Python конвертировать PDF в изображение +## Преобразование PDF в изображения в Python -**Aspose.PDF for Python** использует несколько подходов для преобразования PDF в изображение. Как правило, мы используем два подхода: преобразование с использованием подхода Device и преобразование с использованием SaveOption. В этом разделе будет показано, как преобразовать документы PDF в форматы изображений, такие как BMP, JPEG, GIF, PNG, EMF, TIFF и SVG, используя один из этих подходов. +**Aspose.PDF for Python via .NET** поддерживает несколько способов конвертации содержимого PDF в изображения. На практике большинство рабочих процессов использует один из двух вариантов: -В библиотеке есть несколько классов, позволяющих использовать виртуальное устройство для преобразования изображений. DocumentDevice ориентирован на преобразование всего документа, а ImageDevice — на отдельную страницу. +- подход Device для рендеринга страниц PDF в растровые форматы изображений +- подход SaveOptions для экспорта содержимого PDF в SVG -## Преобразовать PDF, используя класс DocumentDevice +В этой статье показано, как конвертировать PDF‑файлы в TIFF, BMP, EMF, JPEG, PNG, GIF и SVG. -**Aspose.PDF for Python** делает возможным конвертировать страницы PDF в изображения TIFF. +Библиотека включает несколько классов рендеринга. `DocumentDevice` разработан для конвертации всего документа, в то время как `ImageDevice` нацелено на отдельные страницы. -[TiffDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/) (based on DocumentDevice) класс позволяет конвертировать страницы PDF в изображения TIFF. Этот класс предоставляет метод с именем [process](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/#methods) что позволяет преобразовать все страницы PDF‑файла в одно изображение TIFF. +## Преобразовать PDF с помощью класса DocumentDevice + +Используйте `DocumentDevice`, если хотите вывести весь PDF в один многостраничный TIFF-файл. + +Класс [TiffDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/) основан на `DocumentDevice` и предоставляет метод [process](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/#methods) для преобразования всех страниц PDF-файла в один TIFF-файл. {{% alert color="success" %}} **Попробуйте конвертировать PDF в TIFF онлайн** -Aspose.PDF for Python via .NET представляет вам онлайн-приложение ["PDF в TIFF"](https://products.aspose.app/pdf/conversion/pdf-to-tiff), где вы можете попытаться исследовать, как работает функция и качество. +Aspose.PDF for Python via .NET представляет вам онлайн‑приложение ["PDF в TIFF"](https://products.aspose.app/pdf/conversion/pdf-to-tiff), где вы можете попытаться изучить функциональность и качество его работы. -[![Aspose.PDF конвертация PDF в TIFF с приложением](pdf_to_tiff.png)](https://products.aspose.app/pdf/conversion/pdf-to-tiff) +[![Конвертация PDF в TIFF с приложением Aspose.PDF](pdf_to_tiff.png)](https://products.aspose.app/pdf/conversion/pdf-to-tiff) {{% /alert %}} ### Преобразовать страницы PDF в одно изображение TIFF -Aspose.PDF for Python объясняет, как преобразовать все страницы PDF‑файла в одно изображение TIFF: +Aspose.PDF for Python via .NET может рендерить каждую страницу PDF‑файла в одно TIFF‑изображение. Шаги: Конвертировать PDF в TIFF в Python -1. Создайте объект [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) класс. -1. Создать [TiffSettings](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffsettings/) и [TiffDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/) объекты -1. Вызовите [process](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/#methods) метод конвертации PDF‑документа в TIFF. -1. Чтобы установить свойства выходного файла, используйте [TiffSettings](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffsettings/) класс. +1. Загрузите исходный PDF с помощью класса [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Создайте объекты [TiffSettings](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffsettings/) и [TiffDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/). +1. Настройте параметры TIFF, такие как сжатие, глубина цвета и обработка пустых страниц. +1. Вызовите метод [process](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/#methods), чтобы записать TIFF-файл. Следующий фрагмент кода показывает, как преобразовать все страницы PDF в одно изображение TIFF. ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - from os import path - import aspose.pdf as apdf - from io import FileIO - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) +def convert_PDF_to_TIFF(infile, outfile): + document = ap.Document(infile) - document = apdf.Document(path_infile) - - resolution = apdf.devices.Resolution(300) - tiffSettings = apdf.devices.TiffSettings() - tiffSettings.compression = apdf.devices.CompressionType.LZW - tiffSettings.depth = apdf.devices.ColorDepth.DEFAULT + resolution = ap.devices.Resolution(300) + tiffSettings = ap.devices.TiffSettings() + tiffSettings.compression = ap.devices.CompressionType.LZW + tiffSettings.depth = ap.devices.ColorDepth.DEFAULT tiffSettings.skip_blank_pages = False - tiffDevice = apdf.devices.TiffDevice(resolution, tiffSettings) - tiffDevice.process(document, path_outfile) + tiffDevice = ap.devices.TiffDevice(resolution, tiffSettings) + tiffDevice.process(document, f"{outfile}.tiff") print(infile + " converted into " + outfile) ``` -## Преобразовать PDF с помощью класса ImageDevice +## Конвертировать PDF с использованием класса ImageDevice -`ImageDevice` является предком для `BmpDevice`, `JpegDevice`, `GifDevice`, `PngDevice` и `EmfDevice`. +Используйте `ImageDevice`, если вам нужен постраничный вывод в растровом формате. -- [BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) класс позволяет вам конвертировать страницы PDF в BMP изображения. -- [EmfDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/emfdevice/) класс позволяет вам конвертировать страницы PDF в EMF изображения. -- [JpegDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/jpegdevice/) класс позволяет конвертировать страницы PDF в изображения JPEG. -- [PngDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/pngdevice/) класс позволяет вам конвертировать страницы PDF в PNG изображения. -- [GifDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/gifdevice/) класс позволяет вам конвертировать страницы PDF в GIF изображения. +`ImageDevice` является базовым классом для `BmpDevice`, `JpegDevice`, `GifDevice`, `PngDevice`, и `EmfDevice`. -Давайте посмотрим, как преобразовать страницу PDF в изображение. +- Класс [BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) позволяет преобразовывать страницы PDF в BMP-изображения. +- Класс [EmfDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/emfdevice/) позволяет преобразовывать страницы PDF в изображения EMF. +- Класс [JpegDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/jpegdevice/) позволяет преобразовывать страницы PDF в изображения JPEG. +- Класс [PngDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/pngdevice/) позволяет преобразовывать страницы PDF в изображения PNG. +- Класс [GifDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/gifdevice/) позволяет преобразовывать страницы PDF в изображения GIF. -[BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) класс предоставляет метод с именем [process](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/#methods) что позволяет конвертировать отдельную страницу PDF‑файла в формат изображения BMP. Другие классы имеют тот же метод. Поэтому, если нам нужно преобразовать страницу PDF в изображение, мы просто создаём экземпляр необходимого класса. +Рабочий процесс одинаков для каждого формата: загрузите документ, создайте соответствующее устройство, затем обработайте требуемую страницу. -Следующие шаги и фрагмент кода на Python демонстрируют эту возможность: +[BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) предоставляет метод [process](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/#methods) для рендеринга конкретной страницы в BMP. Остальные классы `ImageDevice` работают по тому же шаблону, поэтому формат можно сменить, просто заменив класс устройства. -- [Конвертировать PDF в BMP на Python](#python-pdf-to-image) -- [Конвертировать PDF в EMF на Python](#python-pdf-to-image) -- [Преобразовать PDF в JPG с помощью Python](#python-pdf-to-image) -- [Конвертировать PDF в PNG на Python](#python-pdf-to-image) -- [Конвертировать PDF в GIF на Python](#python-pdf-to-image) +Следующие примеры показывают, как рендерить страницы PDF в распространённые форматы изображений: + +- Конвертация PDF в BMP +- Конвертация PDF в EMF +- Конвертация PDF в JPEG +- Конвертация PDF в PNG +- Конвертация PDF в GIF Шаги: PDF в изображение (BMP, EMF, JPG, PNG, GIF) на Python -1. Загрузите PDF‑файл, используя [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) класс. -1. Создать экземпляр подкласса [ImageDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/imagedevice/) т. е. - * [BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) (для преобразования PDF в BMP) - * [EmfDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/emfdevice/) (для конвертации PDF в Emf) - * [JpegDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/jpegdevice/) (для конвертации PDF в JPG) - * [PngDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/pngdevice/) (для преобразования PDF в PNG) - * [GifDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/gifdevice/) (для преобразования PDF в GIF) -1. Вызовите[ImageDevice.process()](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/imagedevice/#methods) метод для выполнения преобразования PDF в изображение. +1. Загрузите PDF-файл с помощью класса [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Создайте экземпляр нужного подкласса [ImageDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/imagedevice/): + - [BmpDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) (для конвертации PDF в BMP) + - [EmfDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/emfdevice/) (для конвертации PDF в EMF) + - [JpegDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/jpegdevice/) (для конвертации PDF в JPG) + - [PngDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/pngdevice/) (для преобразования PDF в PNG) + - [GifDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/gifdevice/) (для преобразования PDF в GIF) +1. Переберите страницы, которые вы хотите экспортировать. +1. Вызовите метод [ImageDevice.process()](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/imagedevice/#methods), чтобы сохранить каждую страницу как изображение. -### Конвертировать PDF в BMP +### Преобразовать PDF в BMP ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - from os import path - import aspose.pdf as apdf - from io import FileIO - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = apdf.Document(path_infile) - resolution = apdf.devices.Resolution(300) - device = apdf.devices.BmpDevice(resolution) +def convert_PDF_to_BMP(infile, outfile): + document = ap.Document(infile) + resolution = ap.devices.Resolution(300) + device = ap.devices.BmpDevice(resolution) page_count = 1 while page_count <= len(document.pages): - image_stream = FileIO(path_outfile + str(page_count) + "_out.bmp", "w") + image_stream = FileIO(outfile + str(page_count) + "_out.bmp", "w") device.process(document.pages[page_count], image_stream) image_stream.close() page_count = page_count + 1 @@ -130,45 +134,41 @@ Aspose.PDF for Python объясняет, как преобразовать вс ### Конвертировать PDF в EMF ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - from os import path - import aspose.pdf as apdf - from io import FileIO - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = apdf.Document(path_infile) - resolution = apdf.devices.Resolution(300) - device = apdf.devices.EmfDevice(resolution) +def convert_PDF_to_EMF(infile, outfile): + document = ap.Document(infile) + resolution = ap.devices.Resolution(300) + device = ap.devices.EmfDevice(resolution) page_count = 1 while page_count <= len(document.pages): - image_stream = FileIO(path_outfile + str(page_count) + "_out.emf", "w") + image_stream = FileIO(outfile + str(page_count) + "_out.emf", "w") device.process(document.pages[page_count], image_stream) image_stream.close() page_count = page_count + 1 print(infile + " converted into " + outfile) -``` +``` -### Преобразовать PDF в JPEG +### Конвертировать PDF в JPEG ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - from os import path - import aspose.pdf as apdf - from io import FileIO - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = apdf.Document(path_infile) - resolution = apdf.devices.Resolution(300) - device = apdf.devices.JpegDevice(resolution) +def convert_PDF_to_JPEG(infile, outfile): + document = ap.Document(infile) + resolution = ap.devices.Resolution(300) + device = ap.devices.JpegDevice(resolution) page_count = 1 while page_count <= len(document.pages): - image_stream = FileIO(path_outfile + str(page_count) + "_out.jpeg", "w") + image_stream = FileIO(outfile + str(page_count) + "_out.jpeg", "w") device.process(document.pages[page_count], image_stream) image_stream.close() page_count = page_count + 1 @@ -179,41 +179,34 @@ Aspose.PDF for Python объясняет, как преобразовать вс ### Конвертировать PDF в PNG ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - from os import path - import aspose.pdf as apdf - from io import FileIO - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = apdf.Document(path_infile) - resolution = apdf.devices.Resolution(300) +def convert_PDF_to_PNG(infile, outfile): + document = ap.Document(infile) + resolution = ap.devices.Resolution(300) - device = apdf.devices.PngDevice(resolution) + device = ap.devices.PngDevice(resolution) page_count = 1 while page_count <= len(document.pages): - image_stream = FileIO(path_outfile + str(page_count) + "_out.png", "w") + image_stream = FileIO(outfile + str(page_count) + "_out.png", "w") device.process(document.pages[page_count], image_stream) image_stream.close() page_count = page_count + 1 - - print(infile + " converted into " + outfile) ``` ### Конвертировать PDF в PNG с шрифтом по умолчанию ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - from os import path - import aspose.pdf as ap - from io import FileIO - - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = ap.Document(path_infile) +def convert_PDF_to_PNG_with_default_font(infile, outfile): + document = ap.Document(infile) resolution = ap.devices.Resolution(300) rendering_options = ap.RenderingOptions() @@ -224,31 +217,27 @@ Aspose.PDF for Python объясняет, как преобразовать вс page_count = 1 while page_count <= len(document.pages): - image_stream = FileIO(path_outfile + str(page_count) + "_out.png", "w") + image_stream = FileIO(outfile + str(page_count) + "_out.png", "w") device.process(document.pages[page_count], image_stream) image_stream.close() page_count = page_count + 1 - - print(infile + " converted into " + outfile) ``` ### Конвертировать PDF в GIF ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - from os import path - import aspose.pdf as apdf - from io import FileIO - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) - - document = apdf.Document(path_infile) - resolution = apdf.devices.Resolution(300) - device = apdf.devices.GifDevice(resolution) +def convert_PDF_to_GIF(infile, outfile): + document = ap.Document(infile) + resolution = ap.devices.Resolution(300) + device = ap.devices.GifDevice(resolution) page_count = 1 while page_count <= len(document.pages): - image_stream = FileIO(path_outfile + str(page_count) + "_out.gif", "w") + image_stream = FileIO(outfile + str(page_count) + "_out.gif", "w") device.process(document.pages[page_count], image_stream) image_stream.close() page_count = page_count + 1 @@ -261,60 +250,57 @@ Aspose.PDF for Python объясняет, как преобразовать вс В качестве примера того, как работают наши приложения, пожалуйста, проверьте следующую функцию. -Aspose.PDF for Python предоставляет вам онлайн‑приложение ["PDF в PNG"](https://products.aspose.app/pdf/conversion/pdf-to-png), где вы можете попытаться исследовать, как работает функция и качество. +Aspose.PDF for Python представляет вам онлайн‑приложение ["PDF в PNG"](https://products.aspose.app/pdf/conversion/pdf-to-png), где вы можете попытаться изучить функциональность и качество его работы. -[![Как конвертировать PDF в PNG с помощью приложения](pdf_to_png.png)](https://products.aspose.app/pdf/conversion/pdf-to-png) +[![Как конвертировать PDF в PNG с помощью App](pdf_to_png.png)](https://products.aspose.app/pdf/conversion/pdf-to-png) {{% /alert %}} -## Преобразовать PDF с использованием класса SaveOptions +## Конвертировать PDF с использованием класса SaveOptions -Эта часть статьи показывает, как конвертировать PDF в SVG используя Python и класс SaveOptions. +Используйте `SaveOptions`, если хотите экспортировать содержимое PDF в SVG. {{% alert color="success" %}} -**Попробуйте преобразовать PDF в SVG онлайн** +**Попробуйте конвертировать PDF в SVG онлайн** -Aspose.PDF for Python via .NET представляет вам онлайн приложение ["PDF в SVG"](https://products.aspose.app/pdf/conversion/pdf-to-svg), где вы можете попытаться исследовать, как работает функция и качество. +Aspose.PDF for Python via .NET представляет вам онлайн‑приложение ["PDF в SVG"](https://products.aspose.app/pdf/conversion/pdf-to-svg), где вы можете попытаться изучить функциональность и качество его работы. -[![Конвертация PDF в SVG с приложением Aspose.PDF](pdf_to_svg.png)](https://products.aspose.app/pdf/conversion/pdf-to-svg) +[![Aspose.PDF Конвертация PDF в SVG с приложением](pdf_to_svg.png)](https://products.aspose.app/pdf/conversion/pdf-to-svg) {{% /alert %}} -**Scalable Vector Graphics (SVG)** — это семейство спецификаций XML‑формата файлов для двумерной векторной графики, как статической, так и динамической (интерактивной или анимированной). Спецификация SVG является открытым стандартом, который разрабатывается Консорциумом Всемирной паутины (W3C) с 1999 года. +**Scalable Vector Graphics (SVG)** — это основанный на XML формат двумерной векторной графики. Поскольку SVG остаётся векторным, он полезен, когда вам нужен масштабируемый вывод для веба, пользовательского интерфейса или дизайнерских рабочих процессов. -SVG‑изображения и их поведение определяются в текстовых файлах XML. Это означает, что их можно искать, индексировать, использовать в скриптах и, при необходимости, сжимать. Как файлы XML, SVG‑изображения можно создавать и редактировать с помощью любого текстового редактора, но часто удобнее создавать их в графических программах, таких как Inkscape. +Файлы SVG являются текстовыми, пригодными для поиска и их легко постобрабатывать в других инструментах. -Aspose.PDF for Python поддерживает функцию конвертации SVG‑изображения в формат PDF и также предлагает возможность конвертировать PDF‑файлы в формат SVG. Чтобы выполнить это требование, the [SvgSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/svgsaveoptions/) класс был введён в пространство имён Aspose.PDF. Создайте объект SvgSaveOptions и передайте его в качестве второго аргумента к [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) метод. +Aspose.PDF for Python via .NET может как конвертировать SVG в PDF, так и экспортировать страницы PDF в SVG. Для конвертации PDF в SVG создайте объект [SvgSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/svgsaveoptions/) и передайте его в метод [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods). -Следующий фрагмент кода показывает шаги по преобразованию PDF‑файла в формат SVG с помощью Python. +Следующие шаги показывают, как преобразовать файл PDF в SVG с помощью Python. -Шаги: Конвертировать PDF в SVG на Python +Шаги: Преобразовать PDF в SVG с помощью Python -1. Создайте объект [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) класс. -1. Создать [SvgSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/svgsaveoptions/) объект с необходимыми настройками. -1. Вызовите [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) метод и передать его [SvgSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/svgsaveoptions/) объект преобразует PDF документ в SVG. +1. Загрузите исходный PDF с помощью класса [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. Создайте объект [SvgSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/svgsaveoptions/) и настройте нужные параметры. +1. Вызовите метод [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) с экземпляром `SvgSaveOptions`, чтобы записать выходной SVG-файл. ### Конвертировать PDF в SVG ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - from os import path - import aspose.pdf as apdf - from io import FileIO - - path_infile = path.join(self.data_dir, infile) - path_outfile = path.join(self.data_dir, "python", outfile) +def convert_PDF_to_SVG(infile, outfile): + document = ap.Document(infile) - document = apdf.Document(path_infile) - - save_options = apdf.SvgSaveOptions() + save_options = ap.SvgSaveOptions() save_options.compress_output_to_zip_archive = False save_options.treat_target_file_name_as_directory = True - document.save(path_outfile, save_options) - print(infile + " converted into " + outfile) + document.save(f"{outfile}.svg", save_options) ``` ## Связанные преобразования -- [Конвертировать форматы изображений в PDF](/pdf/ru/python-net/convert-images-format-to-pdf/) когда вам нужно воссоздавать PDF из JPG, PNG, TIFF, SVG или других источников изображений. -- [Конвертировать PDF в HTML](/pdf/ru/python-net/convert-pdf-to-html/) для вывода, удобного для браузера, вместо растровых изображений. -- [Конвертировать PDF в другие форматы](/pdf/ru/python-net/convert-pdf-to-other-files/) для рабочих процессов экспорта EPUB, Markdown, текста и XPS. +- [Конвертировать форматы изображений в PDF](/pdf/ru/python-net/convert-images-format-to-pdf/) когда вам нужно воссоздать PDF из JPG, PNG, TIFF, SVG или других источников изображений. +- [Преобразовать PDF в HTML](/pdf/ru/python-net/convert-pdf-to-html/) для вывода, удобного для браузера, вместо растровых изображений. +- [Конвертировать PDF в другие форматы](/pdf/ru/python-net/convert-pdf-to-other-files/) для рабочих процессов экспорта в EPUB, Markdown, текст и XPS. diff --git a/ru/python-net/get-started/_index.md b/ru/python-net/get-started/_index.md index 110961fb1..2b92ea002 100644 --- a/ru/python-net/get-started/_index.md +++ b/ru/python-net/get-started/_index.md @@ -4,11 +4,11 @@ linktitle: Get Started type: docs weight: 30 url: /ru/python-net/get-started/ -description: Этот раздел описывает основные принципы работы Aspose.PDF для Python через .NET. Библиотека Python поддерживает широкий спектр функций. +description: Этот раздел описывает основные принципы работы Aspose.PDF for Python via .NET. Библиотека Python поддерживает широкий спектр функций. is_node: true lastmod: "2022-12-20" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 --- @@ -18,9 +18,9 @@ PDF был создан Adobe в 1990-х годах для достижения Однако, недостаточно просто открыть ваш документ. Работая с PDF, вы столкнетесь с необходимостью создать такой документ заново, отредактировать его или преобразовать в нужный вам формат. -## Почему использовать Aspose.PDF для Python через .NET? +## Почему использовать Aspose.PDF for Python via .NET? -Использование Aspose.PDF для Python через .NET в вашем проекте дает вам следующие преимущества: +Использование Aspose.PDF for Python via .NET в вашем проекте дает вам следующие преимущества: - широкий спектр функций - на основе Aspose.PDF для .NET diff --git a/ru/python-net/get-started/complex-pdf/_index.md b/ru/python-net/get-started/complex-pdf/_index.md index 213d36dc8..7a8cbebf4 100644 --- a/ru/python-net/get-started/complex-pdf/_index.md +++ b/ru/python-net/get-started/complex-pdf/_index.md @@ -4,10 +4,10 @@ linktitle: Создание сложного PDF type: docs weight: 30 url: /ru/python-net/complex-pdf-example/ -description: Aspose.PDF для Python через .NET позволяет создавать более сложные документы, содержащие изображения, текстовые фрагменты и таблицы в одном документе. +description: Aspose.PDF for Python via .NET позволяет создавать более сложные документы, содержащие изображения, текстовые фрагменты и таблицы в одном документе. lastmod: "2022-12-22" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 --- diff --git a/ru/python-net/get-started/hello-world-example/_index.md b/ru/python-net/get-started/hello-world-example/_index.md index 0a563d2cd..f58ddffec 100644 --- a/ru/python-net/get-started/hello-world-example/_index.md +++ b/ru/python-net/get-started/hello-world-example/_index.md @@ -4,7 +4,7 @@ linktitle: Пример Hello World type: docs weight: 20 url: /ru/python-net/hello-world-example/ -description: Этот пример демонстрирует, как создать простой PDF-документ с текстом Hello World, используя Aspose.PDF для Python через .NET. +description: Этот пример демонстрирует, как создать простой PDF-документ с текстом Hello World, используя Aspose.PDF for Python via .NET. lastmod: "2022-12-22" sitemap: changefreq: "monthly" @@ -13,7 +13,7 @@ sitemap: Пример "Hello World" показывает самый простой синтаксис и самую простую программу на любом языке программирования. Разработчики знакомятся с основным синтаксисом языка программирования, изучая, как вывести "Hello World" на экран устройства. Поэтому мы традиционно начнем наше знакомство с нашей библиотекой с него. -В этой статье мы создаем PDF-документ, содержащий текст "Hello World!". После установки **Aspose.PDF для Python через .NET** в вашей среде, вы можете выполнить следующий пример кода, чтобы увидеть, как работает API Aspose.PDF. +В этой статье мы создаем PDF-документ, содержащий текст "Hello World!". После установки **Aspose.PDF for Python via .NET** в вашей среде, вы можете выполнить следующий пример кода, чтобы увидеть, как работает API Aspose.PDF. Следующий фрагмент кода выполняет следующие шаги: @@ -23,7 +23,7 @@ sitemap: 1. Добавьте TextFragment в коллекцию [paragraphs](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) страницы 1. [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) полученный PDF-документ -Следующий фрагмент кода представляет собой программу "Hello World", демонстрирующую работу Aspose.PDF для Python через .NET API. +Следующий фрагмент кода представляет собой программу "Hello World", демонстрирующую работу Aspose.PDF for Python via .NET API. ```python diff --git a/ru/python-net/overview/_index.md b/ru/python-net/overview/_index.md index 7ab85b0d6..c52f3b7cc 100644 --- a/ru/python-net/overview/_index.md +++ b/ru/python-net/overview/_index.md @@ -5,15 +5,15 @@ type: docs weight: 20 url: /ru/python-net/overview/ lastmod: "2022-12-20" -description: Обзор ключевых функций и поддерживаемых форматов Aspose.PDF для Python через .NET, руководство по установке и лицензированию библиотеки. +description: Обзор ключевых функций и поддерживаемых форматов Aspose.PDF for Python via .NET, руководство по установке и лицензированию библиотеки. sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 --- _Эта страница представляет собой обзор функций Aspose.PDF для Python._ -**Aspose.PDF для Python через .NET**, API обработки PDF, который позволяет разработчикам работать с PDF-документами без необходимости в Microsoft Office® или Adobe Acrobat Automation. Ознакомьтесь с целевыми страницами [Aspose.PDF для Python](https://products.aspose.com/pdf/python-net/) для более детального описания функций и возможностей библиотеки. +**Aspose.PDF for Python via .NET**, API обработки PDF, который позволяет разработчикам работать с PDF-документами без необходимости в Microsoft Office® или Adobe Acrobat Automation. Ознакомьтесь с целевыми страницами [Aspose.PDF для Python](https://products.aspose.com/pdf/python-net/) для более детального описания функций и возможностей библиотеки. Aspose.PDF для Python поддерживает широкий спектр функций, таких как: @@ -25,7 +25,7 @@ Aspose.PDF для Python поддерживает широкий спектр ф - Установка нумерации страниц, уровня закладок, размеров страниц и т.д. - Возможность работы с текстом, абзацами, заголовками, гиперссылками, графиками, вложениями и т.д. -Кроме того, Aspose.PDF для Python через .NET может быть использован для легкого преобразования EPUB, Markdown, Text, XPS, PostScript, XML, LaTex в PDF и конвертации PDF в различные форматы документов с отличной производительностью и хорошим качеством. +Кроме того, Aspose.PDF for Python via .NET может быть использован для легкого преобразования EPUB, Markdown, Text, XPS, PostScript, XML, LaTex в PDF и конвертации PDF в различные форматы документов с отличной производительностью и хорошим качеством. Попробуйте наши [Бесплатные Онлайн Приложения](https://products.aspose.app/pdf/applications), демонстрирующие некоторые из самых популярных функций Aspose.PDF. diff --git a/ru/python-net/overview/installation/_index.md b/ru/python-net/overview/installation/_index.md index f8bc6f806..8423e3d6b 100644 --- a/ru/python-net/overview/installation/_index.md +++ b/ru/python-net/overview/installation/_index.md @@ -7,7 +7,7 @@ url: /ru/python-net/installation/ description: В этом разделе представлено описание продукта и инструкции по установке Aspose.PDF для Python. lastmod: "2022-12-21" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 --- @@ -25,7 +25,7 @@ sitemap: # Установка -## Оценка Aspose.PDF для Python через .NET +## Оценка Aspose.PDF for Python via .NET Вы можете легко скачать Aspose.PDF для Python для оценки. Версия для оценки аналогична купленной версии. Версия для оценки становится лицензированной, когда вы добавляете несколько строк кода для применения лицензии. @@ -40,6 +40,6 @@ sitemap: {{% /alert %}} -## Установка Aspose.PDF для Python через .NET +## Установка Aspose.PDF for Python via .NET Вы можете легко использовать aspose-pdf для Python, перейдя по ссылке для прямой загрузки [pip](https://pypi.org/project/aspose-pdf/). Запустите 'pip install aspose-pdf', чтобы загрузить пакет. Если у вас уже установлен Aspose.PDF для Python и вы хотите получить последнюю версию, пожалуйста, выполните 'pip install --upgrade aspose-pdf'. \ No newline at end of file diff --git a/ru/python-net/overview/key-features/_index.md b/ru/python-net/overview/key-features/_index.md index e22b36352..0146aebf0 100644 --- a/ru/python-net/overview/key-features/_index.md +++ b/ru/python-net/overview/key-features/_index.md @@ -4,10 +4,10 @@ linktitle: Основные функции type: docs weight: 20 url: /ru/python-net/key-features/ -description: Aspose.PDF для Python через .NET демонстрирует свои общие функции. Показывает поддерживаемые версии PDF и все манипуляции, которые мы можем делать с PDF. +description: Aspose.PDF for Python via .NET демонстрирует свои общие функции. Показывает поддерживаемые версии PDF и все манипуляции, которые мы можем делать с PDF. lastmod: "2022-12-21" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 --- @@ -22,7 +22,7 @@ sitemap: ## Функции конверсии -Библиотека Aspose.PDF для Python через .NET позволяет успешно, быстро и легко конвертировать ваши PDF-документы в наиболее популярные форматы и наоборот. +Библиотека Aspose.PDF for Python via .NET позволяет успешно, быстро и легко конвертировать ваши PDF-документы в наиболее популярные форматы и наоборот. - Конвертировать PDF в Word, Excel и PowerPoint. - Конвертировать PDF в форматы изображений. diff --git a/ru/python-net/overview/supported-file-formats/_index.md b/ru/python-net/overview/supported-file-formats/_index.md index afb68c9ce..70807360e 100644 --- a/ru/python-net/overview/supported-file-formats/_index.md +++ b/ru/python-net/overview/supported-file-formats/_index.md @@ -4,10 +4,10 @@ linktitle: Поддерживаемые форматы файлов type: docs weight: 10 url: /ru/python-net/supported-file-formats/ -description: Эта страница показывает, какие форматы файлов Aspose.PDF для Python через .NET может загружать и сохранять. +description: Эта страница показывает, какие форматы файлов Aspose.PDF for Python via .NET может загружать и сохранять. lastmod: "2022-12-22" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 --- diff --git a/ru/python-net/overview/system-requirements/_index.md b/ru/python-net/overview/system-requirements/_index.md index 22aa4d07d..62e531116 100644 --- a/ru/python-net/overview/system-requirements/_index.md +++ b/ru/python-net/overview/system-requirements/_index.md @@ -7,13 +7,13 @@ url: /ru/python-net/system-requirements/ description: Этот раздел перечисляет поддерживаемые операционные системы, которые необходимы разработчику для успешной работы с Aspose.PDF для Python. lastmod: "2022-12-22" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 --- ## Overview -Aspose.PDF для Python через .NET, API для обработки PDF, который позволяет разработчикам работать с PDF-документами без необходимости в Microsoft Office® или Adobe Acrobat Automation. Aspose.PDF для Python можно использовать для разработки 32-битных и 64-битных приложений на Python для различных операционных систем (таких как Windows и Linux), на которых установлена версия Python 3.5 или выше. +Aspose.PDF for Python via .NET, API для обработки PDF, который позволяет разработчикам работать с PDF-документами без необходимости в Microsoft Office® или Adobe Acrobat Automation. Aspose.PDF для Python можно использовать для разработки 32-битных и 64-битных приложений на Python для различных операционных систем (таких как Windows и Linux), на которых установлена версия Python 3.5 или выше. ## Supported Operating System diff --git a/ru/python-net/overview/technical-support/_index.md b/ru/python-net/overview/technical-support/_index.md index 693ce0ec6..526df0024 100644 --- a/ru/python-net/overview/technical-support/_index.md +++ b/ru/python-net/overview/technical-support/_index.md @@ -7,7 +7,7 @@ url: /ru/python-net/technical-support/ description: Эта страница дает рекомендации для быстрого и качественного решения ваших задач с использованием Aspose.PDF для Python. lastmod: "2021-06-05" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 --- diff --git a/ru/python-net/parsing/_index.md b/ru/python-net/parsing/_index.md index 4e070b07c..664b2d9f7 100644 --- a/ru/python-net/parsing/_index.md +++ b/ru/python-net/parsing/_index.md @@ -4,7 +4,7 @@ linktitle: Разбор PDF документов type: docs weight: 80 url: /ru/python-net/parsing/ -description: Хотите разобрать PDF документы? Узнайте о различных методах извлечения данных из PDF с помощью Aspose.PDF для Python через .NET. +description: Хотите разобрать PDF документы? Узнайте о различных методах извлечения данных из PDF с помощью Aspose.PDF for Python via .NET. lastmod: "2021-06-05" sitemap: changefreq: "monthly" diff --git a/ru/python-net/working-with-facades/_index.md b/ru/python-net/working-with-facades/_index.md index 762626be3..51ba4647f 100644 --- a/ru/python-net/working-with-facades/_index.md +++ b/ru/python-net/working-with-facades/_index.md @@ -4,24 +4,24 @@ linktitle: Работа с фасадами PDF type: docs weight: 100 url: /python-net/working-with-facades/ -description: Узнайте, как использовать фасады Aspose.PDF в Aspose.PDF для Python через .NET для редактирования содержимого PDF, управления формами и аннотациями, применения защиты, подписания файлов, добавления штампов, печати документов и просмотра метаданных PDF. +description: Узнайте, как использовать фасады Aspose.PDF в Aspose.PDF for Python via .NET для редактирования содержимого PDF, управления формами и аннотациями, применения защиты, подписания файлов, добавления штампов, печати документов и просмотра метаданных PDF. is_node: true lastmod: "2026-05-08" sitemap: changefreq: "monthly" priority: 0.7 TechArticle: true -AlternativeHeadline: Используйте PDF Facades в Aspose.PDF для Python через .NET для работы с формами, подписями, защитой, штампами и PDF-файлами -Abstract: В этом разделе объясняется, как использовать Aspose.PDF Facades в Aspose.PDF для Python через .NET для выполнения типовых задач обработки PDF с помощью упрощённых API. Узнайте, как объединять и разделять файлы, редактировать содержимое, управлять аннотациями и формами, применять защиту, подписывать документы, добавлять штампы, печатать PDF и получать сведения о файлах. +AlternativeHeadline: Используйте PDF Facades в Aspose.PDF for Python via .NET для работы с формами, подписями, защитой, штампами и PDF-файлами +Abstract: В этом разделе объясняется, как использовать Aspose.PDF Facades в Aspose.PDF for Python via .NET для выполнения типовых задач обработки PDF с помощью упрощённых API. Узнайте, как объединять и разделять файлы, редактировать содержимое, управлять аннотациями и формами, применять защиту, подписывать документы, добавлять штампы, печатать PDF и получать сведения о файлах. --- -Aspose.PDF Facades — это набор вспомогательных классов в Aspose.PDF для Python через .NET, позволяющих выполнять типовые операции с PDF без непосредственной работы с низкоуровневой объектной моделью документа. +Aspose.PDF Facades — это набор вспомогательных классов в Aspose.PDF for Python via .NET, позволяющих выполнять типовые операции с PDF без непосредственной работы с низкоуровневой объектной моделью документа. В этом разделе рассматриваются основные классы фасадов, которые можно использовать для редактирования содержимого PDF, управления формами, добавления аннотаций, применения защиты, подписания файлов, работы со штампами, печати документов и получения сведений о PDF-файлах в приложениях Python. Если вам нужен практический API для повседневных задач обработки PDF, таких как объединение документов, заполнение форм, назначение разрешений или подпись файлов, API фасадов предоставляет упрощённый способ создания таких рабочих потоков. -## Зачем использовать фасады в Aspose.PDF для Python через .NET +## Зачем использовать фасады в Aspose.PDF for Python via .NET PDF-фасады предоставляют упрощённый слой API для типовых рабочих процессов с документами. Они полезны, когда необходимо быстро выполнять практические операции с PDF, такие как объединение файлов, заполнение форм, штамповка страниц или применение цифровых подписей, без непосредственной работы с полной моделью объекта документа. From ad00ffe31eccd62b84245fe86bc18eb61ab723f7 Mon Sep 17 00:00:00 2001 From: AnHolub <68945813+AnHolub@users.noreply.github.com> Date: Thu, 14 May 2026 14:02:00 +0300 Subject: [PATCH 04/13] Facades (#581) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Update Spanish documentation for basic PDF operations, including creating, opening, saving, merging, splitting, and protecting PDF files using Aspose.PDF for Python. * Add text-based and watermark annotation documentation for Python - Created a comprehensive guide on adding, inspecting, and deleting text-based annotations in PDF documents using Aspose.PDF for Python via .NET. - Included examples for free text, highlight, underline, squiggly, and strikeout annotations. - Added documentation for watermark annotations, covering addition, inspection, and deletion processes. * Add documentation for working with PDF actions and links in Python - Created a comprehensive guide on working with PDF actions, including adding, updating, and removing document, page, and form actions using Aspose.PDF for Python. - Introduced sections on creating, extracting, and updating links in PDF documents, detailing how to manage hyperlinks programmatically. - Included code examples for various link actions such as GoTo, GoToRemote, and GoToURI, along with methods for updating link appearances and destinations. - Enhanced navigation and interactivity in PDFs through practical examples and clear explanations. * Add documentation for integrating, manipulating, and removing tables in PDF using Python - Introduced a new article on integrating tables from data sources into existing PDF documents. - Updated the article on manipulating tables in existing PDFs to enhance clarity and structure. - Added a section on removing tables from existing PDFs, including methods for single and multiple table removal. - Created a new article on working with vector graphics in PDFs, detailing extraction, movement, deletion, and copying of vector elements. * Remove outdated documentation on PDF annotations including highlights, import/export, sticky notes, and text annotations in Spanish. * Remove obsolete pages in working-with-text section * Update PDF annotations documentation for Python: revise content, add import/export section, and update last modified dates. * Actualiza la documentación para la conversión de PDF a PowerPoint y Word en Python, mejorando descripciones, ejemplos de código y enlaces a aplicaciones en línea. Cambia el enfoque de PDF/x a PDF/A y PDF/UA, proporcionando ejemplos claros para eliminar el cumplimiento de estándares y guardar como PDF estándar. Se ajustan las fechas de última modificación y se mejora la claridad del contenido. * Add SVG image for Aspose PDF for Python via .NET documentation * Update Spanish documentation for vector graphics and ZUGFeRD operations in Aspose.PDF for Python. Improved descriptions, fixed grammatical issues, and enhanced clarity in code examples. Added TechArticle and Abstract metadata for ZUGFeRD topics. * Add documentation for extracting data from PDF using Aspose.PDF for Python via .NET - Created articles for extracting tables, fonts, images, and text from PDF documents. - Included methods for region-based text extraction and handling special text formats like superscripts and subscripts. - Added techniques for improving text extraction from multi-column PDFs. - Documented vector data extraction methods, including saving graphics to SVG. - Updated the "What's New" page to reflect recent changes in the documentation. * Update last modified dates and improve abstract formatting across multiple documentation files for Aspose.PDF for Python. * Remove Spanish documentation for working with headings in PDF * Update PDF to image conversion documentation for Aspose.PDF in Python via .NET - Revised descriptions and abstracts to clarify the conversion of PDF pages to various image formats including TIFF, BMP, EMF, JPEG, PNG, GIF, and SVG. - Enhanced section headings and content structure for better readability and understanding. - Updated code examples for converting PDF to TIFF, BMP, EMF, JPEG, PNG, GIF, and SVG to reflect best practices and improved clarity. - Corrected links and references to ensure accuracy and consistency throughout the documentation. - Added alerts for online conversion tools to encourage user engagement and testing. * Updated brand name * Update sitemap values * Add translated files (ES) * Add linktitle to various PDF-related documentation pages for improved navigation - Added linktitle to the following pages: - Crear folleto PDF - Diseño de página y márgenes - Agregar márgenes a las páginas PDF - Agregar saltos de página en PDF - Redimensionar el contenido de las páginas PDF - Gestión de páginas - Agregar páginas al PDF - Eliminar páginas de PDF - Extraer páginas de PDF - Insertar páginas en PDF - Combinar archivos PDF - Concatenar gran número de archivos PDF - Concatenar archivos PDF con optimización - Concatenar varios archivos PDF - Concatenar formularios PDF con sufijo único - Concatenar dos archivos PDF - Intentar concatenar archivos PDF - Intente concatenar dos archivos PDF - Dividir documentos PDF - Dividir PDF desde el comienzo - Dividir PDF en páginas individuales - Dividir PDF hasta el final - Clase PdfFileInfo - Propiedades del documento - Obtener privilegios del documento - Obtener versión del PDF - Información de la página - Obtener información de la página - Obtener desplazamiento de página - Metadatos PDF - Borrar metadatos de PDF - Obtener metadatos de PDF - Guardar metadatos con XMP - Establecer metadatos PDF - Clase PdfFileSecurity - Cambiar la contraseña del archivo PDF - Descifrar archivo PDF - Cifrar archivo PDF - Establecer privilegios en un archivo PDF existente - Clase PdfFileSignature - Certificación PDF - Firmar documentos PDF - Revisión y Permisos - Extracción de firma - Informacion de firmas - Comprobaciones de Integridad de Firma - Administracion de firmas - Verificación de firmas - Administracion de derechos de uso - Clase PdfFileStamp - Agregar pie de pagina a PDF - Agregar encabezado a PDF - Agregar numero de pagina a PDF - Agregar sello a PDF - Clase PdfViewer - Clase Stamp * update content * add ru pages * add linktitles --------- Co-authored-by: Andriy Andruhovski --- .codex-temp.json | 12 + en/python-net/_index.md | 2 +- ru/python-net/_index.md | 4 +- .../markup-annotations/_index.md | 2 +- .../working-with-facades/form/_index.md | 22 ++ .../form/button-fields-and-images/_index.md | 84 +++++++ .../form/exporting-form-data/_index.md | 15 ++ .../export-to-fdf/_index.md | 43 ++++ .../export-to-json/_index.md | 43 ++++ .../export-to-xfdf/_index.md | 43 ++++ .../export-to-xml/_index.md | 43 ++++ .../extract-xfa-data/_index.md | 42 ++++ .../form/filling-form-fields/_index.md | 16 ++ .../fill-barcode-fields/_index.md | 44 ++++ .../fill-check-box-fields/_index.md | 45 ++++ .../fill-fields-by-name-and-value/_index.md | 51 ++++ .../fill-list-box/_index.md | 44 ++++ .../fill-radio-button-fields/_index.md | 45 ++++ .../fill-text-fields/_index.md | 46 ++++ .../form/importing-form-data/_index.md | 15 ++ .../import-fdf-data/_index.md | 46 ++++ .../import-json-data/_index.md | 47 ++++ .../import-xfdf-data/_index.md | 47 ++++ .../import-xml-data/_index.md | 47 ++++ .../replace-xfa-data/_index.md | 47 ++++ .../form/managing-form-fields/_index.md | 13 + .../flatten-all-fields/_index.md | 44 ++++ .../flatten-specific-fields/_index.md | 48 ++++ .../rename-form-fields/_index.md | 47 ++++ .../form/reading-form-values/_index.md | 16 ++ .../get-field-facades/_index.md | 44 ++++ .../get-field-values/_index.md | 44 ++++ .../get-radio-button-options/_index.md | 43 ++++ .../get-required-field-names/_index.md | 42 ++++ .../get-rich-text-values/_index.md | 43 ++++ .../resolve-full-field-names/_index.md | 43 ++++ .../working-with-facades/formeditor/_index.md | 26 ++ .../_index.md | 22 ++ .../add-field-script/_index.md | 57 +++++ .../remove-field-action/_index.md | 51 ++++ .../set-field-script/_index.md | 60 +++++ .../set-submit-flag/_index.md | 47 ++++ .../set-submit-url/_index.md | 57 +++++ .../formeditor/creating-form-field/_index.md | 22 ++ .../create-checkbox-field/_index.md | 55 +++++ .../create-combobox-field/_index.md | 50 ++++ .../create-listbox-field/_index.md | 50 ++++ .../create-radiobutton-field/_index.md | 50 ++++ .../create-submit-button/_index.md | 55 +++++ .../create-textbox-field/_index.md | 50 ++++ .../customizing-field-appearance/_index.md | 24 ++ .../decorate-field/_index.md | 56 +++++ .../get-field-appearance/_index.md | 46 ++++ .../set-field-alignment-vertical/_index.md | 57 +++++ .../set-field-alignment/_index.md | 56 +++++ .../set-field-appearance/_index.md | 56 +++++ .../set-field-comb-number/_index.md | 51 ++++ .../set-field-limit/_index.md | 54 +++++ .../modifying-form-fields/_index.md | 25 ++ .../add-list-item/_index.md | 46 ++++ .../copy-inner-field/_index.md | 72 ++++++ .../copy-outer-field/_index.md | 80 ++++++ .../del-list-item/_index.md | 51 ++++ .../move-field/_index.md | 48 ++++ .../remove-field/_index.md | 48 ++++ .../rename-field/_index.md | 49 ++++ .../single-to-multiple/_index.md | 49 ++++ .../pdfannotationeditor/_index.md | 22 ++ .../pdfcontenteditor/_index.md | 32 +++ .../pdfcontenteditor/annotations/_index.md | 18 ++ .../add-caret-annotation/_index.md | 59 +++++ .../add-free-text-annotation/_index.md | 48 ++++ .../add-markup-annotation/_index.md | 73 ++++++ .../add-popup-annotation/_index.md | 51 ++++ .../annotations/add-text-annotation/_index.md | 62 +++++ .../pdfcontenteditor/attachments/_index.md | 18 ++ .../add-attachment-from-path/_index.md | 48 ++++ .../attachments/add-attachment/_index.md | 51 ++++ .../add-file-attachment-annotation/_index.md | 52 ++++ .../_index.md | 58 +++++ .../attachments/remove-attachments/_index.md | 45 ++++ .../document-actions/_index.md | 16 ++ .../add-bookmark-action/_index.md | 53 ++++ .../add-document-action/_index.md | 47 ++++ .../remove-open-action/_index.md | 46 ++++ .../drawing-annotations/_index.md | 19 ++ .../add-circle-annotation/_index.md | 50 ++++ .../add-curve-annotation/_index.md | 56 +++++ .../add-line-annotation/_index.md | 63 +++++ .../add-polygon-annotation/_index.md | 55 +++++ .../add-polyline-annotation/_index.md | 55 +++++ .../add-square-annotation/_index.md | 50 ++++ .../image-operations/_index.md | 16 ++ .../delete-all-images/_index.md | 45 ++++ .../image-operations/delete-images/_index.md | 45 ++++ .../image-operations/replace-image/_index.md | 43 ++++ .../links-and-navigation/_index.md | 20 ++ .../add-application-link/_index.md | 54 +++++ .../add-custom-action-link/_index.md | 55 +++++ .../add-javascript-link/_index.md | 54 +++++ .../add-local-link/_index.md | 54 +++++ .../add-pdf-document-link/_index.md | 55 +++++ .../add-web-link/_index.md | 53 ++++ .../extract-links/_index.md | 61 +++++ .../pdfcontenteditor/multimedia/_index.md | 15 ++ .../multimedia/add-movie-annotation/_index.md | 46 ++++ .../multimedia/add-sound-annotation/_index.md | 47 ++++ .../stamps-management/_index.md | 23 ++ .../add-rubber-stamp/_index.md | 53 ++++ .../_index.md | 53 ++++ .../_index.md | 53 ++++ .../delete-stamp-by-ids-examples/_index.md | 69 ++++++ .../delete-stamp-by-index/_index.md | 64 +++++ .../delete-stamps-globally/_index.md | 60 +++++ .../stamps-management/list-stamps/_index.md | 53 ++++ .../manage-stamp-by-id/_index.md | 71 ++++++ .../move-stamp-by-id-example/_index.md | 56 +++++ .../move-stamp-by-index/_index.md | 71 ++++++ .../text-operations/_index.md | 18 ++ .../replace-text-on-page-with-state/_index.md | 54 +++++ .../replace-text-on-page/_index.md | 48 ++++ .../replace-text-regex/_index.md | 49 ++++ .../replace-text-simple/_index.md | 48 ++++ .../replace-text-with-state/_index.md | 54 +++++ .../viewer-preferences/_index.md | 16 ++ .../change-viewer-preferences/_index.md | 76 ++++++ .../get-viewer-preferences/_index.md | 46 ++++ .../pdffileeditor/_index.md | 31 +++ .../booklet-and-nup-layout/_index.md | 22 ++ .../create-n-up-pdf-document/_index.md | 85 +++++++ .../create-pdf-booklet/_index.md | 82 +++++++ .../page-layout-and-margins/_index.md | 19 ++ .../add-margins-to-pdf-pages/_index.md | 52 ++++ .../add-page-breaks-in-pdf/_index.md | 48 ++++ .../resize-pdf-page-contents/_index.md | 51 ++++ .../pdffileeditor/page-managment/_index.md | 26 ++ .../append-pages-to-pdf/_index.md | 43 ++++ .../delete-pages-from-pdf/_index.md | 47 ++++ .../extract-pages-from-pdf/_index.md | 46 ++++ .../insert-pages-into-pdf/_index.md | 45 ++++ .../pdffileeditor/page-merging/_index.md | 23 ++ .../concatenate-large-number-files/_index.md | 38 +++ .../_index.md | 38 +++ .../concatenate-pdf-files/_index.md | 37 +++ .../concatenate-pdf-forms/_index.md | 40 +++ .../concatenate-two-files/_index.md | 37 +++ .../try-concatenate-pdf-files/_index.md | 38 +++ .../try-concatenate-two-files/_index.md | 40 +++ .../splitting-pdf-documents/_index.md | 23 ++ .../split-pdf-from-beginning/_index.md | 38 +++ .../split-pdf-into-single-pages/_index.md | 38 +++ .../split-pdf-to-end/_index.md | 38 +++ .../pdffileinfo/_index.md | 26 ++ .../pdffileinfo/document-properties/_index.md | 19 ++ .../get-document-privileges/_index.md | 60 +++++ .../get-pdf-version/_index.md | 44 ++++ .../pdffileinfo/page-information/_index.md | 19 ++ .../page-information/get-page-info/_index.md | 51 ++++ .../get-page-offset/_index.md | 46 ++++ .../pdffileinfo/pdf-metadata/_index.md | 21 ++ .../pdf-metadata/clear-pdf-metadata/_index.md | 47 ++++ .../pdf-metadata/get-pdf-metadata/_index.md | 59 +++++ .../save-metadata-with-xmp/_index.md | 50 ++++ .../pdf-metadata/set-pdf-metadata/_index.md | 56 +++++ .../pdffilesecurity/_index.md | 26 ++ .../pdffilesecurity/change-password/_index.md | 155 ++++++++++++ .../decrypt-pdf-file/_index.md | 92 +++++++ .../encrypt-pdf-file/_index.md | 152 ++++++++++++ .../pdffilesecurity/set-privileges/_index.md | 148 +++++++++++ .../pdffilesignature/_index.md | 83 +++++++ .../pdf-certification/_index.md | 86 +++++++ .../pdffilesignature/pdf-signing/_index.md | 183 ++++++++++++++ .../revision-permissions/_index.md | 82 +++++++ .../signature-extraction/_index.md | 63 +++++ .../signature-information/_index.md | 112 +++++++++ .../signature-integrity-checks/_index.md | 63 +++++ .../signature-management/_index.md | 62 +++++ .../signature-verification/_index.md | 61 +++++ .../usage-rights-management/_index.md | 63 +++++ .../pdffilestamp/_index.md | 26 ++ .../pdffilestamp/add-footer/_index.md | 85 +++++++ .../pdffilestamp/add-header/_index.md | 98 ++++++++ .../pdffilestamp/add-page-number/_index.md | 123 ++++++++++ .../pdffilestamp/add-stamp/_index.md | 47 ++++ .../working-with-facades/stamp/_index.md | 229 ++++++++++++++++++ 185 files changed, 9245 insertions(+), 4 deletions(-) create mode 100644 .codex-temp.json create mode 100644 ru/python-net/working-with-facades/form/_index.md create mode 100644 ru/python-net/working-with-facades/form/button-fields-and-images/_index.md create mode 100644 ru/python-net/working-with-facades/form/exporting-form-data/_index.md create mode 100644 ru/python-net/working-with-facades/form/exporting-form-data/export-to-fdf/_index.md create mode 100644 ru/python-net/working-with-facades/form/exporting-form-data/export-to-json/_index.md create mode 100644 ru/python-net/working-with-facades/form/exporting-form-data/export-to-xfdf/_index.md create mode 100644 ru/python-net/working-with-facades/form/exporting-form-data/export-to-xml/_index.md create mode 100644 ru/python-net/working-with-facades/form/exporting-form-data/extract-xfa-data/_index.md create mode 100644 ru/python-net/working-with-facades/form/filling-form-fields/_index.md create mode 100644 ru/python-net/working-with-facades/form/filling-form-fields/fill-barcode-fields/_index.md create mode 100644 ru/python-net/working-with-facades/form/filling-form-fields/fill-check-box-fields/_index.md create mode 100644 ru/python-net/working-with-facades/form/filling-form-fields/fill-fields-by-name-and-value/_index.md create mode 100644 ru/python-net/working-with-facades/form/filling-form-fields/fill-list-box/_index.md create mode 100644 ru/python-net/working-with-facades/form/filling-form-fields/fill-radio-button-fields/_index.md create mode 100644 ru/python-net/working-with-facades/form/filling-form-fields/fill-text-fields/_index.md create mode 100644 ru/python-net/working-with-facades/form/importing-form-data/_index.md create mode 100644 ru/python-net/working-with-facades/form/importing-form-data/import-fdf-data/_index.md create mode 100644 ru/python-net/working-with-facades/form/importing-form-data/import-json-data/_index.md create mode 100644 ru/python-net/working-with-facades/form/importing-form-data/import-xfdf-data/_index.md create mode 100644 ru/python-net/working-with-facades/form/importing-form-data/import-xml-data/_index.md create mode 100644 ru/python-net/working-with-facades/form/importing-form-data/replace-xfa-data/_index.md create mode 100644 ru/python-net/working-with-facades/form/managing-form-fields/_index.md create mode 100644 ru/python-net/working-with-facades/form/managing-form-fields/flatten-all-fields/_index.md create mode 100644 ru/python-net/working-with-facades/form/managing-form-fields/flatten-specific-fields/_index.md create mode 100644 ru/python-net/working-with-facades/form/managing-form-fields/rename-form-fields/_index.md create mode 100644 ru/python-net/working-with-facades/form/reading-form-values/_index.md create mode 100644 ru/python-net/working-with-facades/form/reading-form-values/get-field-facades/_index.md create mode 100644 ru/python-net/working-with-facades/form/reading-form-values/get-field-values/_index.md create mode 100644 ru/python-net/working-with-facades/form/reading-form-values/get-radio-button-options/_index.md create mode 100644 ru/python-net/working-with-facades/form/reading-form-values/get-required-field-names/_index.md create mode 100644 ru/python-net/working-with-facades/form/reading-form-values/get-rich-text-values/_index.md create mode 100644 ru/python-net/working-with-facades/form/reading-form-values/resolve-full-field-names/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/creating-form-field/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md create mode 100644 ru/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md create mode 100644 ru/python-net/working-with-facades/pdfannotationeditor/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-text-annotation/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment-from-path/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/multimedia/add-movie-annotation/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/multimedia/add-sound-annotation/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md create mode 100644 ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/page-managment/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/page-merging/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileinfo/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileinfo/document-properties/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileinfo/page-information/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md create mode 100644 ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilesecurity/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilesecurity/change-password/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilesignature/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilesignature/signature-information/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilesignature/signature-management/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilestamp/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilestamp/add-footer/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilestamp/add-header/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md create mode 100644 ru/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md create mode 100644 ru/python-net/working-with-facades/stamp/_index.md diff --git a/.codex-temp.json b/.codex-temp.json new file mode 100644 index 000000000..501965719 --- /dev/null +++ b/.codex-temp.json @@ -0,0 +1,12 @@ +{ + "generatedAtUtc": "2026-05-14T08:25:54.6786942Z", + "inputRoot": "D:\\Work\\Hugo\\Deploy\\Aspose.PDF-Documentation\\en\\python-net\\working-with-facades\\pdfcontenteditor\\stamps-management", + "outputRoot": "D:\\Work\\Hugo\\Deploy\\Aspose.PDF-Documentation\\ru\\python-net\\pdfcontenteditor\\stamps-management", + "totalFiles": 11, + "translatedCount": 11, + "skippedCount": 0, + "failureCount": 0, + "validationWarningCount": 0, + "failures": [], + "validationWarnings": [] +} \ No newline at end of file diff --git a/en/python-net/_index.md b/en/python-net/_index.md index eeee35c80..75bb0f2e0 100644 --- a/en/python-net/_index.md +++ b/en/python-net/_index.md @@ -22,7 +22,7 @@ Abstract: Aspose.PDF for Python via .NET is a versatile component designed for d {{% alert color="primary" %}} -Aspose.PDF is a .NET component built to allow developers to create PDF documents, whether simple or complex, on the fly programmatically. Aspose.PDF for Python via .NET allows developers to insert tables, graphs, images, hyperlinks, custom fonts - and more - into PDF documents. Moreover, it is also possible to compress PDF documents. Aspose.PDF for Python via .NET provides excellent security features to develop secure PDF documents. And the most distinct feature of Aspose.PDF for Python via .NET is that it supports the creation of PDF documents through both an API and from XML templates. +Aspose.PDF for Python via .NET allows developers to create PDF documents, whether simple or complex, on the fly programmatically. Aspose.PDF for Python via .NET allows developers to insert tables, graphs, images, hyperlinks, custom fonts - and more - into PDF documents. Moreover, it is also possible to compress PDF documents. Aspose.PDF for Python via .NET provides excellent security features to develop secure PDF documents. And the most distinct feature of Aspose.PDF for Python via .NET is that it supports the creation of PDF documents through both an API and from XML templates. {{% /alert %}} diff --git a/ru/python-net/_index.md b/ru/python-net/_index.md index f90262499..c18494b54 100644 --- a/ru/python-net/_index.md +++ b/ru/python-net/_index.md @@ -19,8 +19,8 @@ sitemap: {{% alert color="primary" %}} -Aspose.PDF — это компонент .NET, созданный для того, чтобы позволить разработчикам программно создавать PDF-документы, будь то простые или сложные, на лету. - Aspose.PDF for Python via .NET позволяет разработчикам вставлять таблицы, графики, изображения, гиперссылки, шрифты - и многое другое - в PDF документы. Более того, также возможно сжимать PDF документы. Aspose.PDF for Python via .NET предоставляет отличные функции безопасности для разработки защищенных PDF документов. И наиболее отличительной особенностью Aspose.PDF for Python via .NET является то, что он поддерживает создание PDF документов как через API, так и из XML шаблонов. +Aspose.PDF for Python via .NET позволяет разработчикам программно создавать PDF-документы, будь то простые или сложные, на лету. +Aspose.PDF for Python via .NET позволяет разработчикам вставлять таблицы, графики, изображения, гиперссылки, шрифты - и многое другое - в PDF документы. Более того, также возможно сжимать PDF документы. Aspose.PDF for Python via .NET предоставляет отличные функции безопасности для разработки защищенных PDF документов. И наиболее отличительной особенностью Aspose.PDF for Python via .NET является то, что он поддерживает создание PDF документов как через API, так и из XML шаблонов. {{% /alert %}} diff --git a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/markup-annotations/_index.md b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/markup-annotations/_index.md index d5ff43c1e..931b0d3db 100644 --- a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/markup-annotations/_index.md +++ b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/markup-annotations/_index.md @@ -19,7 +19,7 @@ Abstract: Эта статья объясняет, как создавать, п Пример скрипта демонстрирует три распространённых рабочего процесса аннотаций: - текстовые аннотации для комментариев в виде заметок -- аннотации каретки для маркеров вставки +- аннотации курсора для маркеров вставки - заменить аннотации для разметки замены текста ## Текстовые аннотации diff --git a/ru/python-net/working-with-facades/form/_index.md b/ru/python-net/working-with-facades/form/_index.md new file mode 100644 index 000000000..ed1a9c1ec --- /dev/null +++ b/ru/python-net/working-with-facades/form/_index.md @@ -0,0 +1,22 @@ +--- +title: Класс Form +linktitle: Класс Form +type: docs +weight: 140 +url: /python-net/form-class/ +description: В этом разделе объясняется, как работать с фасадами Aspose.PDF, используя класс Form. +lastmod: "2025-11-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Работа с данными PDF-формы и полями AcroForm в Python с использованием класса Form +Abstract: В этом разделе объясняется, как использовать фасад Form в Aspose.PDF для Python via .NET для работы с интерактивными PDF‑формами. Узнайте, как экспортировать и импортировать данные формы, заполнять различные типы полей, управлять существующими полями, работать с полями‑кнопками и изображениями, а также программно считывать значения полей формы. +--- + +- [Экспорт данных Form](/pdf/ru/python-net/exporting-form-data/) +- [Импорт данных Form](/pdf/ru/python-net/importing-form-data/) +- [Заполнение полей Form](/pdf/ru/python-net/filling-form-fields/) +- [Поля кнопок и изображения](/pdf/ru/python-net/button-fields-and-images/) +- [Управление полями Form](/pdf/ru/python-net/managing-form-fields/) +- [Чтение значений Form](/pdf/ru/python-net/reading-form-values/) diff --git a/ru/python-net/working-with-facades/form/button-fields-and-images/_index.md b/ru/python-net/working-with-facades/form/button-fields-and-images/_index.md new file mode 100644 index 000000000..0d1568154 --- /dev/null +++ b/ru/python-net/working-with-facades/form/button-fields-and-images/_index.md @@ -0,0 +1,84 @@ +--- +title: Поля кнопок и изображения +linktitle: Поля кнопок и изображения +type: docs +weight: 40 +url: /python-net/button-fields-and-images/ +description: В этом примере демонстрируется, как управлять полями кнопок в PDF‑форме с использованием API Aspose.PDF Facades. +lastmod: "2026-02-19" +TechArticle: true +AlternativeHeadline: Добавление изображения к полям кнопок и чтение флагов отправки +Abstract: PDF‑формы часто содержат интерактивные кнопки, которые либо вызывают действия JavaScript, либо отправляют данные формы. Вы можете визуально улучшить поля кнопок, добавив изображения в качестве их внешнего вида, и программно проверять их поведение при отправке. +--- + +## Добавить изображение к полям кнопок + +Этот фрагмент кода объясняет, как добавить изображение в качестве внешнего вида к существующему полю кнопки в PDF‑форме. Операция улучшает визуальное представление PDF‑кнопки, заменяя её внешний вид по умолчанию пользовательским изображением. + +1. Создайте объект Form. +1. Привяжите PDF‑файл к объекту Form. +1. Добавьте изображение в поле Button Field. + - Определите путь к файлу изображения, связанному с PDF + - Откройте изображение в бинарном режиме как image_stream. + - Вызовите fill_image_field() с полностью квалифицированным именем поля кнопки. +1. Сохраните обновлённый PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Add image appearance to button fields +def add_image_appearance_to_button_fields(infile, outfile): + """Add image appearance to button fields in a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Add image appearance to button fields by providing the field name and image stream + image_path = infile.replace(".pdf", ".jpg") + with open(image_path, "rb") as image_stream: + pdf_form.fill_image_field("Image1_af_image", image_stream) + + # Save updated PDF + pdf_form.save(outfile) +``` + +## Получить флаги отправки + +Библиотека Python помогает получить флаги отправки кнопки отправки в PDF‑форме, используя API Aspose.PDF Facades. Флаги отправки определяют поведение кнопки отправки, например, отправляет ли она всю форму, включает ли аннотации или отправляет данные в формате FDF, XFDF, PDF или HTML. + +1. Создайте объект Form. +1. Вызовите get_submit_flags() у объекта формы, используя полностью квалифицированное имя кнопки отправки. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def get_submit_flags(infile, outfile): + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + flags = pdf_form.get_submit_flags("Submit1_af_submit") + + print(f"Submit flags: {flags}") +``` diff --git a/ru/python-net/working-with-facades/form/exporting-form-data/_index.md b/ru/python-net/working-with-facades/form/exporting-form-data/_index.md new file mode 100644 index 000000000..317eca0f1 --- /dev/null +++ b/ru/python-net/working-with-facades/form/exporting-form-data/_index.md @@ -0,0 +1,15 @@ +--- +title: Экспорт данных Form +linktitle: Экспорт данных Form +type: docs +weight: 10 +url: /python-net/exporting-form-data/ +description: В этой статье демонстрируется, как экспортировать данные формы PDF в несколько структурированных форматов с использованием Aspose.PDF for Python via .NET. Она предоставляет практические примеры извлечения значений полей формы из стандартных AcroForms и PDF на основе XFA и сохранения их как файлов XML, FDF, XFDF и JSON с помощью фасадов Aspose.PDF, используя Form Class. +lastmod: "2026-02-19" +--- + +- [Экспорт в FDF](/pdf/ru/python-net/export-to-fdf/) +- [Экспорт в XFDF](/pdf/ru/python-net/export-to-xfdf/) +- [Экспорт в JSON](/pdf/ru/python-net/export-to-json/) +- [Экспорт в XML](/pdf/ru/python-net/export-to-xml/) +- [Извлечь данные XFA](/pdf/ru/python-net/extract-xfa-data/) \ No newline at end of file diff --git a/ru/python-net/working-with-facades/form/exporting-form-data/export-to-fdf/_index.md b/ru/python-net/working-with-facades/form/exporting-form-data/export-to-fdf/_index.md new file mode 100644 index 000000000..eccc87354 --- /dev/null +++ b/ru/python-net/working-with-facades/form/exporting-form-data/export-to-fdf/_index.md @@ -0,0 +1,43 @@ +--- +title: Экспорт в FDF +linktitle: Экспорт в FDF +type: docs +weight: 10 +url: /python-net/export-to-fdf/ +description: Этот пример объясняет, как экспортировать данные полей формы PDF в файл FDF (Forms Data Format) с использованием Aspose.PDF for Python via .NET. Он демонстрирует, как получить доступ к интерактивным данным формы через фасад Form, привязать исходный PDF‑документ и сохранить извлечённые значения в поток FDF. +lastmod: "2026-02-19" +--- + +FDF — это облегченный формат, специально предназначенный для хранения и передачи данных формы PDF без включения полного документа. В этом примере, a [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) объект инициализируется из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) модуль, позволяющий разработчикам взаимодействовать с полями AcroForm и экспортировать их значения. + +1. Создайте экземпляр pdf_facades.Form() для работы с полями формы PDF. +1. Вызовите 'bind_pdf()', чтобы присоединить PDF‑документ, содержащий форму. +1. Используйте 'open(')', чтобы создать двоичный поток с правом записи для файла FDF. +1. Экспортируйте данные формы. Вызовите 'export_fdf()', чтобы извлечь и сохранить все значения полей формы. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Export Data to FDF +def export_form_data_to_fdf(infile, outfile): + """Export PDF form data to FDF file.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Create FDF file stream + with open(outfile, "wb") as fdf_output_stream: + # Export form data to FDF file + pdf_form.export_fdf(fdf_output_stream) +``` diff --git a/ru/python-net/working-with-facades/form/exporting-form-data/export-to-json/_index.md b/ru/python-net/working-with-facades/form/exporting-form-data/export-to-json/_index.md new file mode 100644 index 000000000..0225dbd78 --- /dev/null +++ b/ru/python-net/working-with-facades/form/exporting-form-data/export-to-json/_index.md @@ -0,0 +1,43 @@ +--- +title: Экспорт в JSON +linktitle: Экспорт в JSON +type: docs +weight: 30 +url: /python-net/export-to-json/ +description: В этом примере демонстрируется, как экспортировать значения полей формы PDF в файл JSON с использованием Aspose.PDF for Python via .NET. Описывается, как загрузить форму PDF, получить доступ к её полям через фасад Form и сохранить извлечённые данные в структурированном формате JSON. +lastmod: "2026-02-19" +--- + +JSON — это широко используемый формат данных, обеспечивающий беспрепятственный обмен данными между приложениями и сервисами. В этом примере объект [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) из модуля [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) используется для привязки PDF-файла и экспорта значений полей формы в удобочитаемую структуру JSON. + +1. Инициализируйте pdf_facades.Form() для работы с полями формы. +1. Используйте 'bind_pdf()' для прикрепления исходного PDF‑документа. +1. Создайте поток для записи, используя 'FileIO()'. +1. Вызовите 'export_json()', чтобы извлечь значения полей формы и сохранить их в отформатированном JSON. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Export Data to JSON +def export_form_to_json(infile, outfile): + """Export PDF form field values to JSON file.""" + # Create Form object + form = pdf_facades.Form() + + # Bind PDF document + form.bind_pdf(infile) + + # Create JSON file stream + with FileIO(outfile, "w") as json_stream: + # Export form field values to JSON + form.export_json(json_stream, indented=True) +``` diff --git a/ru/python-net/working-with-facades/form/exporting-form-data/export-to-xfdf/_index.md b/ru/python-net/working-with-facades/form/exporting-form-data/export-to-xfdf/_index.md new file mode 100644 index 000000000..14f1f5155 --- /dev/null +++ b/ru/python-net/working-with-facades/form/exporting-form-data/export-to-xfdf/_index.md @@ -0,0 +1,43 @@ +--- +title: Экспорт в XFDF +linktitle: Экспорт в XFDF +type: docs +weight: 20 +url: /python-net/export-to-xfdf/ +description: В этом примере показано, как экспортировать данные полей формы PDF в файл XFDF (XML Forms Data Format) с использованием Aspose.PDF for Python via .NET. Он демонстрирует, как загрузить форму PDF, получить доступ к её полям через фасад Form и сохранить извлечённые значения в поток XFDF. +lastmod: "2026-02-19" +--- + +XFDF — это XML-представление данных PDF-форм, позволяющее разработчикам передавать значения полей формы независимо от исходного документа. В этом примере объект [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) используется для привязки исходного PDF-файла и экспорта его данных в структурированный файл XFDF. + +1. Инициализируйте pdf_facades.Form() для управления данными формы PDF. +1. Вызовите 'bind_pdf()', чтобы прикрепить исходный PDF‑документ. +1. Используйте 'open()', чтобы создать двоичный поток с возможностью записи. +1. Экспортируйте данные формы. Вызовите 'export_xfdf()', чтобы извлечь и сохранить значения полей формы в формате XFDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Export Data to XFDF +def export_pdf_form_to_xfdf(infile, outfile): + """Export PDF form data to XFDF file.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Create XFDF file stream + with open(outfile, "wb") as xfdf_output_stream: + # Export form data to XFDF file + pdf_form.export_xfdf(xfdf_output_stream) +``` diff --git a/ru/python-net/working-with-facades/form/exporting-form-data/export-to-xml/_index.md b/ru/python-net/working-with-facades/form/exporting-form-data/export-to-xml/_index.md new file mode 100644 index 000000000..ea86c8bc9 --- /dev/null +++ b/ru/python-net/working-with-facades/form/exporting-form-data/export-to-xml/_index.md @@ -0,0 +1,43 @@ +--- +title: Экспорт в XML +linktitle: Экспорт в XML +type: docs +weight: 40 +url: /python-net/export-to-xml/ +description: В этом примере демонстрируется, как экспортировать данные формы PDF в файл XML с использованием Aspose.PDF for Python via .NET. Показано, как загрузить PDF‑документ, получить доступ к полям формы через фасад Form и сохранить извлечённые данные в виде структурированного XML с использованием класса Form. +lastmod: "2026-02-19" +--- + +Экспорт данных формы позволяет разработчикам повторно использовать информацию, хранящуюся в PDF AcroForms, без ручного копирования значений полей. В этом примере, a [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) объект создаётся из aspose.pdf. В модуле facades исходный PDF привязывается к нему, и данные формы записываются в поток XML. + +1. Создайте объект Form. Инициализируйте pdf_facades.Form() для доступа и управления полями формы. +1. Используйте 'bind_pdf()' для привязки исходного PDF‑документа к экземпляру Form. +1. Создайте поток записываемого файла, используя 'FileIO()'. +1. Вызовите 'export_xml()', чтобы извлечь все значения полей формы и записать их в XML‑файл. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Export Data to XML +def export_pdf_form_data_to_xml(infile, datafile): + """Export PDF form data to XML file.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Open XML file as stream + with FileIO(datafile, "w") as xml_output_stream: + # Export data from PDF form fields to XML + pdf_form.export_xml(xml_output_stream) +``` diff --git a/ru/python-net/working-with-facades/form/exporting-form-data/extract-xfa-data/_index.md b/ru/python-net/working-with-facades/form/exporting-form-data/extract-xfa-data/_index.md new file mode 100644 index 000000000..941d5aa0a --- /dev/null +++ b/ru/python-net/working-with-facades/form/exporting-form-data/extract-xfa-data/_index.md @@ -0,0 +1,42 @@ +--- +title: Извлечь данные XFA +linktitle: Извлечь данные XFA +type: docs +weight: 50 +url: /python-net/extract-xfa-data/ +description: В этом примере объясняется, как извлечь данные форм XFA из PDF‑файла с использованием Aspose.PDF for Python via .NET. Он демонстрирует, как привязать PDF‑документ на основе XFA к фасаду Form и экспортировать его внутреннюю структуру данных в поток файла. +lastmod: "2026-02-19" +--- + +Формы XFA (XML Forms Architecture) отличаются от традиционных AcroForm, потому что их данные хранятся в виде XML внутри PDF. В этом примере [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) объект из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) модуля используется для привязки PDF и извлечения его данных XFA непосредственно в файл. + +1. Создайте экземпляр pdf_facades.Form() для управления данными формы. +1. Вызовите 'bind_pdf()', чтобы присоединить исходный PDF, содержащий формы XFA. +1. Используйте 'FileIO()' для создания записываемого файлового потока. +1. Вызовите функцию 'extract_xfa_data()' для экспорта встроенных XML-данных XFA. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Extract XFA Data +def export_xfa_data(infile, outfile): + """Export XFA form data.""" + # Create Form object + form = pdf_facades.Form() + + # Bind PDF document + form.bind_pdf(infile) + + with FileIO(outfile, "w") as stream: + # Export embedded XFA XML data to the output stream + form.extract_xfa_data(stream) +``` diff --git a/ru/python-net/working-with-facades/form/filling-form-fields/_index.md b/ru/python-net/working-with-facades/form/filling-form-fields/_index.md new file mode 100644 index 000000000..cd0ebb7af --- /dev/null +++ b/ru/python-net/working-with-facades/form/filling-form-fields/_index.md @@ -0,0 +1,16 @@ +--- +title: Заполнение полей Form +linktitle: Заполнение полей Form +type: docs +weight: 30 +url: /python-net/filling-form-fields/ +description: В этой статье демонстрируется, как программно заполнять поля PDF‑формы с использованием Aspose.PDF for Python via .NET. Описываются практические методы заполнения различных типов интерактивных элементов формы, включая текстовые поля, флажки, переключатели, списки, поля штрих‑кода и динамически сопоставляемые пары имя–значение. С помощью фасада Form разработчики могут привязать документ PDF, обновлять значения полей через простые вызовы API и автоматически сохранять изменённый файл. +lastmod: "2026-02-19" +--- + +- [Заполнить текстовые поля](/pdf/ru/python-net/fill-text-fields/) +- [Заполнить поля флажков](/pdf/ru/python-net/fill-check-box-fields/) +- [Заполнить поля радиокнопок](/pdf/ru/python-net/fill-radio-button-fields/) +- [Заполнить List Box](/pdf/ru/python-net/fill-list-box/) +- [Заполнить поля штрихкода](/pdf/ru/python-net/fill-barcode-fields/) +- [Заполнять поля по имени и значению](/pdf/ru/python-net/fill-fields-by-name-and-value/) diff --git a/ru/python-net/working-with-facades/form/filling-form-fields/fill-barcode-fields/_index.md b/ru/python-net/working-with-facades/form/filling-form-fields/fill-barcode-fields/_index.md new file mode 100644 index 000000000..b438692a7 --- /dev/null +++ b/ru/python-net/working-with-facades/form/filling-form-fields/fill-barcode-fields/_index.md @@ -0,0 +1,44 @@ +--- +title: Заполнить поля штрихкода +linktitle: Заполнить поля штрихкода +type: docs +weight: 50 +url: /python-net/fill-barcode-fields/ +description: Этот пример демонстрирует, как программно заполнять поля штрихкода в PDF‑форме с использованием Aspose.PDF for Python via .NET. Он показывает, как привязать PDF‑документ, задать значение полю штрихкода и сохранить обновлённый файл. +lastmod: "2026-02-19" +--- + +Поля штрихкода в PDF‑формах позволяют сохранять закодированную информацию и визуально отображать её в виде штрихкодов. В этом примере [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) фасад из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) модуля используется для доступа к полям формы и назначениям штрихкода. После заполнения данных PDF сохраняется с обновлённым содержимым штрихкода. + +1. Инициализируйте 'pdf_facades.Form()', чтобы управлять взаимодействиями с PDF‑формой. +1. Вызовите 'bind_pdf()', чтобы прикрепить PDF, содержащий поля штрих-кода. +1. Используйте 'fill_field()', чтобы назначить значение штрих-кода. +1. Сохраните обновлённый Document. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Fill Barcode Fields +def fill_barcode_fields(infile, outfile): + """Fill barcode fields in PDF form.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill barcode fields by name + pdf_form.fill_field("product_barcode", "123456789012") + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/form/filling-form-fields/fill-check-box-fields/_index.md b/ru/python-net/working-with-facades/form/filling-form-fields/fill-check-box-fields/_index.md new file mode 100644 index 000000000..4f3b974e7 --- /dev/null +++ b/ru/python-net/working-with-facades/form/filling-form-fields/fill-check-box-fields/_index.md @@ -0,0 +1,45 @@ +--- +title: Заполнить поля флажков +linktitle: Заполнить поля флажков +type: docs +weight: 20 +url: /python-net/fill-check-box-fields/ +description: В этом примере демонстрируется, как программно заполнять поля флажков в PDF-форме с использованием Aspose.PDF for Python via .NET. Показано, как привязать PDF‑документ, обновить значения флажков по имени поля и сохранить изменённый файл. +lastmod: "2026-02-19" +--- + +Флажок часто используется в PDF-формах для представления бинарных выборов, таких как подписка или подтверждение согласия. В этом примере [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) фасад из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) используется для доступа к полям формы и установки их значений в выбранное состояние. После обновления флажков заполненный PDF сохраняется как новый документ. + +1. Инициализируйте 'pdf_facades.Form()' для управления взаимодействиями с полями формы. +1. Используйте 'bind_pdf()', чтобы присоединить исходный PDF, содержащий поля флажков. +1. Вызовите 'fill_field()', чтобы отметить поля, такие как 'subscribe_newsletter' и 'accept_terms', как выбранные. +1. Сохраните обновлённый Document. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Fill Check Box Fields +def fill_check_box_fields(infile, outfile): + """Fill check box fields in PDF form.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill check box fields by name + pdf_form.fill_field("subscribe_newsletter", "Yes") + pdf_form.fill_field("accept_terms", "Yes") + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/form/filling-form-fields/fill-fields-by-name-and-value/_index.md b/ru/python-net/working-with-facades/form/filling-form-fields/fill-fields-by-name-and-value/_index.md new file mode 100644 index 000000000..1b601205c --- /dev/null +++ b/ru/python-net/working-with-facades/form/filling-form-fields/fill-fields-by-name-and-value/_index.md @@ -0,0 +1,51 @@ +--- +title: Заполнять поля по имени и значению +linktitle: Заполнять поля по имени и значению +type: docs +weight: 60 +url: /python-net/fill-fields-by-name-and-value/ +description: В этой статье демонстрируется, как динамически заполнять несколько полей формы PDF по имени и значению с использованием Aspose.PDF for Python via .NET. Вместо того чтобы задавать каждое поле отдельно, используется структура словаря для сопоставления имен полей со значениями и их заполнения в цикле. +lastmod: "2026-02-19" +--- + +Заполнение полей формы с использованием коллекции имя‑значение позволяет разработчикам создавать масштабируемые и гибкие решения для автоматизации форм PDF. В этом примере [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) фасад из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) используется для привязки PDF‑документа и перебора словаря данных полей. Каждая запись применяется с помощью метода ‘fill_field’, что обеспечивает эффективное обновление полей формы. + +1. Инициализируйте 'pdf_facades.Form()', чтобы работать с интерактивными полями формы. +1. Используйте 'bind_pdf()' для прикрепления исходного PDF‑документа. +1. Создайте словарь, содержащий имена полей и значения, которые вы хотите вставить. +1. Итерируйте по словарю и вызывайте 'fill_field()' для каждой записи. +1. Сохраните обновлённый Document. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Fill Fields by Name and Value +def fill_fields_by_name_and_value(infile, outfile): + """Fill PDF form fields by name and value.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill fields by name and value + fields = { + "name": "Jane Smith", + "address": "456 Elm St, Othertown, USA", + "email": "jane.smith@example.com", + } + for field_name, value in fields.items(): + pdf_form.fill_field(field_name, value) + + # Save updated PDF using outfile + pdf_form.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/form/filling-form-fields/fill-list-box/_index.md b/ru/python-net/working-with-facades/form/filling-form-fields/fill-list-box/_index.md new file mode 100644 index 000000000..25dd5d918 --- /dev/null +++ b/ru/python-net/working-with-facades/form/filling-form-fields/fill-list-box/_index.md @@ -0,0 +1,44 @@ +--- +title: Заполнить List Box +linktitle: Заполнить List Box +type: docs +weight: 40 +url: /python-net/fill-list-box/ +description: В этом примере демонстрируется, как программно заполнять поля списка и множественного выбора в PDF‑форме с использованием Aspose.PDF for Python via .NET. Показано, как привязать PDF‑документ, выбрать значения в форме поля списка и сохранить обновлённый файл. +lastmod: "2026-02-19" +--- + +Поля List Box с множественным выбором позволяют пользователям выбирать одно или несколько значений из заранее заданного набора вариантов. В этом примере [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) фасад из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) используется для доступа к PDF‑форме и назначения выбранного значения полю favorite_colors. После выбора нужного варианта обновлённый документ сохраняется. + +1. Инициализируйте 'pdf_facades.Form()' для управления и обновления полей формы. +1. Вызовите 'bind_pdf()' для привязки исходного PDF, содержащего поля list box или множественного выбора. +1. Используйте 'fill_field()' для выбора значения из доступных вариантов. +1. Сохраните обновлённый Document. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Fill List Box / Multi-Select Fields +def fill_list_box_fields(infile, outfile): + """Fill list box and multi-select fields in PDF form.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill list box / multi-select fields by name + pdf_form.fill_field("favorite_colors", "Red") + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/form/filling-form-fields/fill-radio-button-fields/_index.md b/ru/python-net/working-with-facades/form/filling-form-fields/fill-radio-button-fields/_index.md new file mode 100644 index 000000000..666728965 --- /dev/null +++ b/ru/python-net/working-with-facades/form/filling-form-fields/fill-radio-button-fields/_index.md @@ -0,0 +1,45 @@ +--- +title: Заполнить поля радиокнопок +linktitle: Заполнить поля радиокнопок +type: docs +weight: 30 +url: /python-net/fill-radio-button-fields/ +description: В этом примере демонстрируется, как программно заполнять поля радиокнопок в PDF‑форме с использованием Aspose.PDF for Python via .NET. Показано, как привязать PDF‑документ, выбрать вариант радиокнопки по индексу и сохранить обновлённый файл. +lastmod: "2026-02-19" +--- + +Переключатели позволяют пользователям выбирать один вариант из предопределенной группы, например, поля пола или предпочтений. В этом примере фасад [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) из модуля [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) используется для привязки исходного PDF-файла и присвоения выбранного варианта по его индексному значению. После выбора нужного варианта измененный документ сохраняется. + +1. Инициализируйте pdf_facades.Form() для управления полями PDF‑формы. +1. Вызовите 'bind_pdf()', чтобы прикрепить PDF, содержащий поля радиокнопок. +1. Используйте 'fill_field()', чтобы выбрать первый вариант (индекс 0). +1. Сохраните обновлённый PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Fill Radio Button Fields +def fill_radio_button_fields(infile, outfile): + """Fill radio button fields in PDF form.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill radio button fields by name + pdf_form.fill_field("gender", 0) # Select male option (index 0) + # pdf_form.fill_field("gender", 1) # Select female option (index 1) + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/form/filling-form-fields/fill-text-fields/_index.md b/ru/python-net/working-with-facades/form/filling-form-fields/fill-text-fields/_index.md new file mode 100644 index 000000000..8b689b464 --- /dev/null +++ b/ru/python-net/working-with-facades/form/filling-form-fields/fill-text-fields/_index.md @@ -0,0 +1,46 @@ +--- +title: Заполнить текстовые поля +linktitle: Заполнить текстовые поля +type: docs +weight: 10 +url: /python-net/fill-text-fields/ +description: Этот пример демонстрирует, как автоматически заполнять текстовые поля в PDF‑форме, используя Aspose.PDF for Python via .NET. Он показывает, как загрузить PDF‑документ, заполнить конкретные поля формы по имени и сохранить обновлённый файл. +lastmod: "2026-02-19" +--- + +Программное заполнение текстовых полей позволяет приложениям повторно использовать PDF‑шаблоны и вставлять динамический контент без ручного редактирования. В этом примере [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) фасад из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) используется для привязки PDF‑формы и обновления нескольких полей, таких как имя, адрес и электронная почта. После чего изменённый PDF сохраняется как новый документ. + +1. Инициализируйте 'pdf_facades.Form()' для управления операциями с полями формы. +1. Используйте 'bind_pdf()' для прикрепления входного PDF, содержащего текстовые поля. +1. Вызовите 'fill_field()', чтобы вставить данные в поля, такие как имя, адрес и электронная почта. +1. Сохраните обновлённый PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Fill Text Fields +def fill_text_fields(infile, outfile): + """Fill text fields in PDF form.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Fill text fields by name + pdf_form.fill_field("name", "John Doe") + pdf_form.fill_field("address", "123 Main St, Anytown, USA") + pdf_form.fill_field("email", "john.doe@example.com") + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/form/importing-form-data/_index.md b/ru/python-net/working-with-facades/form/importing-form-data/_index.md new file mode 100644 index 000000000..f643bcf1c --- /dev/null +++ b/ru/python-net/working-with-facades/form/importing-form-data/_index.md @@ -0,0 +1,15 @@ +--- +title: Импорт данных Form +linktitle: Импорт данных Form +type: docs +weight: 20 +url: /python-net/importing-form-data/ +description: В этом разделе демонстрируется, как импортировать и заменять данные формы PDF из нескольких внешних форматов с использованием Aspose.PDF for Python via .NET. Рассматриваются практические примеры заполнения полей формы PDF данными из файлов XML, FDF, XFDF и JSON, а также замена существующих наборов данных XFA. С помощью фасада Form разработчики могут привязать PDF‑документ, загрузить структурированные данные через файловые потоки и автоматически обновлять поля формы без ручного редактирования. +lastmod: "2026-02-19" +--- + +- [Импортировать данные FDF](/pdf/ru/python-net/import-fdf-data/) +- [Импортировать данные XFDF](/pdf/ru/python-net/import-xfdf-data/) +- [Импортировать JSON-данные](/pdf/ru/python-net/import-json-data/) +- [Импорт данных XML](/pdf/ru/python-net/import-xml-data/) +- [Заменить данные XFA](/pdf/ru/python-net/replace-xfa-data/) diff --git a/ru/python-net/working-with-facades/form/importing-form-data/import-fdf-data/_index.md b/ru/python-net/working-with-facades/form/importing-form-data/import-fdf-data/_index.md new file mode 100644 index 000000000..d45ea80b5 --- /dev/null +++ b/ru/python-net/working-with-facades/form/importing-form-data/import-fdf-data/_index.md @@ -0,0 +1,46 @@ +--- +title: Импортировать данные FDF +linktitle: Импортировать данные FDF +type: docs +weight: 10 +url: /python-net/import-fdf-data/ +description: В этом примере демонстрируется, как импортировать данные формы из файла FDF в PDF‑форму с использованием Aspose.PDF for Python via .NET. Показано, как привязать PDF‑документ, считать значения полей формы из потока FDF и автоматически заполнить соответствующие поля. +lastmod: "2026-02-19" +--- + +FDF (Forms Data Format) — это легковесный формат, используемый для хранения и передачи значений полей PDF‑формы без включения всего документа. В этом примере the [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) фасад из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) используется для загрузки PDF‑формы и импорта данных полей из внешнего файла FDF. После процесса импорта обновлённый PDF сохраняется как новый файл. + +1. Инициализируйте pdf_facades.Form() для работы с интерактивными полями PDF‑формы. +1. Вызовите 'bind_pdf()' для присоединения шаблона PDF‑формы. +1. Используйте 'open()' для чтения FDF‑файла в бинарном режиме. +1. Вызовите 'import_fdf()' для заполнения полей PDF данными из FDF‑файла. +1. Сохраните обновлённый PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Import Data from FDF +def import_fdf_to_pdf_form(infile, datafile, outfile): + """Import form data from FDF file into PDF form fields.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Open FDF file as stream + with open(datafile, "rb") as fdf_input_stream: + pdf_form.import_fdf(fdf_input_stream) + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/form/importing-form-data/import-json-data/_index.md b/ru/python-net/working-with-facades/form/importing-form-data/import-json-data/_index.md new file mode 100644 index 000000000..a42bd54e3 --- /dev/null +++ b/ru/python-net/working-with-facades/form/importing-form-data/import-json-data/_index.md @@ -0,0 +1,47 @@ +--- +title: Импортировать JSON-данные +linktitle: Импортировать JSON-данные +type: docs +weight: 30 +url: /python-net/import-json-data/ +description: В этом примере демонстрируется, как импортировать данные полей формы из файла JSON в PDF-форму, используя Aspose.PDF for Python via .NET. Показано, как привязать PDF-документ, прочитать структурированные JSON-данные через поток файла и автоматически заполнить соответствующие поля формы. +lastmod: "2026-02-19" +--- + +JSON широко используется для хранения и передачи структурированных данных между системами. В этом примере, [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) фасад из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) модуля используется для привязки PDF-формы и импорта значений полей из внешнего файла JSON. После процесса импорта обновлённый документ сохраняется как новый PDF. + +1. Инициализируйте pdf_facades.Form() для работы с полями PDF-формы. +1. Вызовите 'bind_pdf()' для присоединения шаблона PDF‑формы. +1. Используйте 'FileIO()' для чтения файла JSON, содержащего значения полей формы. +1. Вызовите 'import_json()', чтобы заполнить поля PDF, используя пары ключ‑значение JSON. +1. Сохраните обновлённый PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Import from JSON +def import_json_to_pdf_form(infile, datafile, outfile): + """Import form data from JSON file into PDF form fields.""" + # Create Form object + form = pdf_facades.Form() + + # Bind PDF document + form.bind_pdf(infile) + + # Open JSON file as stream + with FileIO(datafile, "r") as json_stream: + # Import data from JSON into PDF form fields + form.import_json(json_stream) + + # Save updated PDF + form.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/form/importing-form-data/import-xfdf-data/_index.md b/ru/python-net/working-with-facades/form/importing-form-data/import-xfdf-data/_index.md new file mode 100644 index 000000000..92c09f9cc --- /dev/null +++ b/ru/python-net/working-with-facades/form/importing-form-data/import-xfdf-data/_index.md @@ -0,0 +1,47 @@ +--- +title: Импортировать данные XFDF +linktitle: Импортировать данные XFDF +type: docs +weight: 20 +url: /python-net/import-xfdf-data/ +description: В этом примере демонстрируется, как импортировать данные формы из файла XFDF в форму PDF с использованием Aspose.PDF for Python via .NET. Показано, как привязать документ PDF, читать XML‑основанные данные XFDF через файловый поток и автоматически заполнять соответствующие поля формы. Импорт данных XFDF обеспечивает эффективный обмен данными форм и поддерживает автоматизированные рабочие процессы с документами, которые опираются на структурированные форматы XML. +lastmod: "2026-02-19" +--- + +XFDF (XML Forms Data Format) — это XML‑представление данных формы PDF, разработанное для совместимости и обмена данными. В этом примере [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) фасад из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) модуля используется для привязки формы PDF и импорта значений полей из внешнего файла XFDF. После импорта данных обновлённый PDF сохраняется как новый документ. + +1. Инициализируйте pdf_facades.Form() для работы с полями PDF-формы. +1. Вызовите 'bind_pdf()' для присоединения шаблона PDF‑формы. +1. Используйте 'open()' для чтения файла XFDF. +1. Вызовите 'import_xfdf()', чтобы заполнить поля PDF значениями из файла XFDF. +1. Сохраните обновлённый Document. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Import Data from XFDF +def import_data_from_xfdf(infile, datafile, outfile): + """Import form data from XFDF file into PDF form fields.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Open XFDF file as stream + with open(datafile, "rb") as xfdf_input_stream: + # Import data from XFDF into PDF form fields + pdf_form.import_xfdf(xfdf_input_stream) + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/form/importing-form-data/import-xml-data/_index.md b/ru/python-net/working-with-facades/form/importing-form-data/import-xml-data/_index.md new file mode 100644 index 000000000..52165432a --- /dev/null +++ b/ru/python-net/working-with-facades/form/importing-form-data/import-xml-data/_index.md @@ -0,0 +1,47 @@ +--- +title: Импорт данных XML +linktitle: Импорт данных XML +type: docs +weight: 40 +url: /python-net/import-xml-data/ +description: В этом примере демонстрируется, как импортировать данные формы из XML‑файла в поля формы PDF с использованием Aspose.PDF for Python via .NET. Показано, как привязать документ PDF, прочитать структурированные XML‑данные через файловый поток и автоматически заполнить соответствующие поля формы. +lastmod: "2026-02-19" +--- + +XML часто используется для хранения структурированных данных формы, что делает его практичным форматом для передачи значений между системами. В этом примере [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) фасад из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) используется для загрузки формы PDF и применения значений полей непосредственно из XML‑файла. После импорта данных обновлённый PDF сохраняется как новый документ. + +1. Инициализируйте pdf_facades.Form() для работы с полями PDF-формы. +1. Вызовите 'bind_pdf()' для присоединения шаблона PDF‑формы. +1. Используйте 'FileIO()' для доступа к XML‑файлу, содержащему данные формы. +1. Вызовите 'import_xml()' для заполнения полей PDF значениями из XML‑файла. +1. Сохраните обновлённый PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Import data from XML +def import_xml_to_pdf_fields(infile, datafile, outfile): + """Import form data from XML file into PDF form fields.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Open XML file as stream + with FileIO(datafile, "r") as xml_input_stream: + # Import data from XML into PDF form fields + pdf_form.import_xml(xml_input_stream) + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/form/importing-form-data/replace-xfa-data/_index.md b/ru/python-net/working-with-facades/form/importing-form-data/replace-xfa-data/_index.md new file mode 100644 index 000000000..a0e0201ab --- /dev/null +++ b/ru/python-net/working-with-facades/form/importing-form-data/replace-xfa-data/_index.md @@ -0,0 +1,47 @@ +--- +title: Заменить данные XFA +linktitle: Заменить данные XFA +type: docs +weight: 50 +url: /python-net/replace-xfa-data/ +description: В этом примере показано, как заменить существующие данные формы XFA в PDF с использованием Aspose.PDF for Python via .NET. Он демонстрирует, как привязать PDF‑документ на основе XFA, загрузить новые данные из внешнего файла XFA и программно обновить содержимое формы. +lastmod: "2026-02-19" +--- + +Формы XFA (XML Forms Architecture) хранят свои данные в формате XML внутри структуры PDF. В этом примере, [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) фасад из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) модуля используется для привязки PDF и замены его существующего набора данных XFA с использованием внешнего XML‑потока. После применения новых данных обновлённый PDF сохраняется как отдельный файл. + +1. Инициализируйте pdf_facades.Form() для управления данными формы XFA. +1. Вызовите функцию 'bind_pdf()', чтобы прикрепить PDF-файл, содержащий формы XFA. +1. Используйте 'FileIO()' для чтения XML‑файла XFA. +1. Вызовите 'set_xfa_data()' для обновления PDF новым содержимым XFA. +1. Сохраните обновлённый Document. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Replace from XFA data +def replace_xfa_data(infile, datafile, outfile): + """Import form data from XFA file into PDF form fields.""" + # Create Form object + form = pdf_facades.Form() + + # Bind PDF document + form.bind_pdf(infile) + + # Open XFA file as stream + with FileIO(datafile, "r") as xfa_stream: + # Import data from XFA into PDF form fields + form.set_xfa_data(xfa_stream) + + # Save updated PDF + form.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/form/managing-form-fields/_index.md b/ru/python-net/working-with-facades/form/managing-form-fields/_index.md new file mode 100644 index 000000000..a48ae4e82 --- /dev/null +++ b/ru/python-net/working-with-facades/form/managing-form-fields/_index.md @@ -0,0 +1,13 @@ +--- +title: Управление полями формы +linktitle: Управление полями формы +type: docs +weight: 50 +url: /python-net/managing-form-fields/ +description: В этом разделе демонстрируется, как управлять и изменять поля формы PDF с помощью Aspose.PDF for Python via .NET. Описываются практические примеры сплющивания отдельных полей, сплющивания всех полей формы и программного переименования существующих полей. С помощью фасада Form разработчики могут привязать документ PDF, настроить поведение полей и сохранить обновлённый файл с применёнными постоянными изменениями. +lastmod: "2026-02-19" +--- + +- [Уплощение конкретных полей](/pdf/ru/python-net/flatten-specific-fields/) +- [Сгладить все поля](/pdf/ru/python-net/flatten-all-fields/) +- [Переименовать поля формы](/pdf/ru/python-net/rename-form-fields/) \ No newline at end of file diff --git a/ru/python-net/working-with-facades/form/managing-form-fields/flatten-all-fields/_index.md b/ru/python-net/working-with-facades/form/managing-form-fields/flatten-all-fields/_index.md new file mode 100644 index 000000000..8bc942dbd --- /dev/null +++ b/ru/python-net/working-with-facades/form/managing-form-fields/flatten-all-fields/_index.md @@ -0,0 +1,44 @@ +--- +title: Сгладить все поля +linktitle: Сгладить все поля +type: docs +weight: 10 +url: /python-net/flatten-all-fields/ +description: В этом примере демонстрируется, как сгладить все поля формы в PDF, используя Aspose.PDF for Python via .NET. Показано, как привязать PDF‑документ, преобразовать каждый интерактивный элемент формы в статическое содержимое страницы и сохранить окончательный файл. +lastmod: "2026-02-19" +--- + +Сглаживание удаляет интерактивность из PDF‑форм, объединяя значения полей напрямую в макет документа. В этом примере [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) фасад из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) используется для привязки исходного PDF и применения метода flatten_all_fields(), который преобразует все поля в нередактируемое содержимое. + +1. Инициализируйте pdf_facades.Form() для работы с полями PDF-формы. +1. Вызовите 'bind_pdf()', чтобы присоединить исходный документ. +1. Вызовите 'flatten_all_fields()', чтобы преобразовать все интерактивные поля в статическое содержимое. +1. Сохраните обновлённый Document. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Flatten all fields +def flatten_all_fields(infile, outfile): + """Flatten all fields in a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Flatten all fields in the PDF document + pdf_form.flatten_all_fields() + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/form/managing-form-fields/flatten-specific-fields/_index.md b/ru/python-net/working-with-facades/form/managing-form-fields/flatten-specific-fields/_index.md new file mode 100644 index 000000000..9a5d3d21f --- /dev/null +++ b/ru/python-net/working-with-facades/form/managing-form-fields/flatten-specific-fields/_index.md @@ -0,0 +1,48 @@ +--- +title: Уплощение конкретных полей +linktitle: Уплощение конкретных полей +type: docs +weight: 20 +url: /python-net/flatten-specific-fields/ +description: В этом разделе демонстрируется, как управлять и изменять поля форм PDF с помощью Aspose.PDF for Python via .NET. Он содержит практические примеры уплощения конкретных полей, уплощения всех полей формы и программного переименования существующих полей. +lastmod: "2026-02-19" +--- + +Управление полями форм является важной частью рабочих процессов обработки PDF. Уплощение полей удаляет интерактивность, преобразуя элементы формы в обычное содержимое страницы, тогда как переименование полей помогает стандартизировать правила именования для более удобной обработки данных. + +1. Инициализируйте pdf_facades.Form() для доступа к полям форм PDF и их управления. +1. Используйте 'bind_pdf()' для присоединения входного документа. +1. Укажите имена полей и вызовите 'flatten_field()' для преобразования выбранных полей в статическое содержимое. +1. Вызовите 'flatten_all_fields()', чтобы удалить интерактивность у каждого поля формы. +1. Определите старые и новые имена полей и примените 'rename_field()'. +1. Сохраните обновлённый PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Flatten specific fields +def flatten_specific_fields(infile, outfile): + """Flatten specific fields in a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Flatten specific fields by their names + fields_to_flatten = ["First Name", "Last Name"] + for field_name in fields_to_flatten: + pdf_form.flatten_field(field_name) + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/form/managing-form-fields/rename-form-fields/_index.md b/ru/python-net/working-with-facades/form/managing-form-fields/rename-form-fields/_index.md new file mode 100644 index 000000000..f135e529d --- /dev/null +++ b/ru/python-net/working-with-facades/form/managing-form-fields/rename-form-fields/_index.md @@ -0,0 +1,47 @@ +--- +title: Переименовать поля формы +linktitle: Переименовать поля формы +type: docs +weight: 30 +url: /python-net/rename-form-fields/ +description: Это пример демонстрирует, как переименовать поля формы в PDF‑документе с помощью Aspose.PDF for Python via .NET. Показано, как привязать PDF‑форму, программно обновить существующие имена полей и сохранить изменённый файл. Переименование полей помогает стандартизировать структуру формы, улучшить сопоставление данных и упростить интеграцию с автоматизированными рабочими процессами или внешними системами. +lastmod: "2026-02-19" +--- + +Переименование полей формы полезно при согласовании PDF‑форм с внутренними правилами именования или подготовке документов для обработки структурированных данных. В этом примере, [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) фасад из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) модуля используется для привязки исходного PDF и применения сопоставления, которое заменяет старые имена полей новыми. После обновления идентификаторов полей документ сохраняется с применёнными изменениями. + +1. Инициализируйте pdf_facades.Form() для работы с полями PDF-формы. +1. Вызовите 'bind_pdf()', чтобы присоединить PDF‑документ. +1. Создайте список кортежей, содержащих старые имена полей и их соответствующие новые имена. +1. Итерируйте по отображению и вызывайте 'rename_field()' для каждой записи. +1. Сохраните обновлённый Document. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Rename form fields +def rename_form_fields(infile, outfile): + """Rename form fields in a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Rename form fields by providing a mapping of old names to new names + field_renaming_map = [("First Name", "NewFirstName"), ("Last Name", "NewLastName")] + for old_name, new_name in field_renaming_map: + pdf_form.rename_field(old_name, new_name) + + # Save updated PDF + pdf_form.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/form/reading-form-values/_index.md b/ru/python-net/working-with-facades/form/reading-form-values/_index.md new file mode 100644 index 000000000..0aaa2cde8 --- /dev/null +++ b/ru/python-net/working-with-facades/form/reading-form-values/_index.md @@ -0,0 +1,16 @@ +--- +title: Чтение значений Form +linktitle: Чтение значений Form +type: docs +weight: 60 +url: /python-net/reading-form-values/ +description: В этом разделе объясняется, как читать значения Form с помощью Aspose.PDF Facades, используя класс Form. +lastmod: "2026-02-19" +--- + +- [Получить значения полей](/pdf/ru/python-net/get-field-values/) +- [Получить варианты радиокнопок](/pdf/ru/python-net/get-radio-button-options/) +- [Получить имена обязательных полей](/pdf/ru/python-net/get-required-field-names/) +- [Получить значения Rich Text](/pdf/ru/python-net/get-rich-text-values/) +- [Получить фасады полей](/pdf/ru/python-net/get-field-facades/) +- [Получить полные имена полей](/pdf/ru/python-net/resolve-full-field-names/) \ No newline at end of file diff --git a/ru/python-net/working-with-facades/form/reading-form-values/get-field-facades/_index.md b/ru/python-net/working-with-facades/form/reading-form-values/get-field-facades/_index.md new file mode 100644 index 000000000..df7fde35e --- /dev/null +++ b/ru/python-net/working-with-facades/form/reading-form-values/get-field-facades/_index.md @@ -0,0 +1,44 @@ +--- +title: Получить фасады полей +linktitle: Получить фасады полей +type: docs +weight: 10 +url: /python-net/get-field-facades/ +description: В этом примере демонстрируется, как считать значения конкретных полей формы из PDF‑документа с помощью Aspose.PDF Facades API. +lastmod: "2026-02-19" +--- + +PDF‑формы содержат поля, в которые пользователи могут вводить данные, например текстовые поля, флажки или переключатели. Для программной обработки этих форм часто необходимо получить текущие значения этих полей. + +1. Создайте объект Form. +1. Привяжите PDF‑документ к объекту формы. +1. Получите значения полей. + +```python + + from io import FileIO + import sys + from os import path + import aspose.pdf as ap + import aspose.pdf.facades as pdf_facades + + sys.path.append(path.join(path.dirname(__file__), "..")) + + from config import set_license, initialize_data_dir + + + # Get field values + def get_field_values(infile): + """Get field values from a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Get field values by their names + field_names = ["First Name", "Last Name"] + for field_name in field_names: + value = pdf_form.get_field(field_name) + print(f"Value of '{field_name}': {value}") +``` \ No newline at end of file diff --git a/ru/python-net/working-with-facades/form/reading-form-values/get-field-values/_index.md b/ru/python-net/working-with-facades/form/reading-form-values/get-field-values/_index.md new file mode 100644 index 000000000..a44fbff22 --- /dev/null +++ b/ru/python-net/working-with-facades/form/reading-form-values/get-field-values/_index.md @@ -0,0 +1,44 @@ +--- +title: Получить значения полей +linktitle: Получить значения полей +type: docs +weight: 50 +url: /python-net/get-field-values/ +description: Извлечение значений полей из PDF-формы с помощью Aspose.PDF Facades, используя класс Form. +lastmod: "2026-02-19" +--- + +Этот фрагмент кода показывает, как получить текущие значения полей формы из PDF-документа с помощью API Aspose.PDF Facades. Следующий [get_field()](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/#methods) метод позволяет программно получать доступ к данным, введённым в текстовые поля, флажки, переключатели и другие элементы AcroForm. + +1. Привяжите PDF к объекту Form. +1. Укажите имена полей, которые вы хотите прочитать. +1. Получите значение каждого поля, используя get_field(). + +```python + + from io import FileIO + import sys + from os import path + import aspose.pdf as ap + import aspose.pdf.facades as pdf_facades + + sys.path.append(path.join(path.dirname(__file__), "..")) + + from config import set_license, initialize_data_dir + + + # Get field values + def get_field_values(infile): + """Get field values from a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Get field values by their names + field_names = ["First Name", "Last Name"] + for field_name in field_names: + value = pdf_form.get_field(field_name) + print(f"Value of '{field_name}': {value}") +``` \ No newline at end of file diff --git a/ru/python-net/working-with-facades/form/reading-form-values/get-radio-button-options/_index.md b/ru/python-net/working-with-facades/form/reading-form-values/get-radio-button-options/_index.md new file mode 100644 index 000000000..90b67d574 --- /dev/null +++ b/ru/python-net/working-with-facades/form/reading-form-values/get-radio-button-options/_index.md @@ -0,0 +1,43 @@ +--- +title: Получить варианты радиокнопок +linktitle: Получить варианты радиокнопок +type: docs +weight: 20 +url: /python-net/get-radio-button-options/ +description: В этой статье демонстрируется, как получить текущее выбранное значение поля радиокнопки в PDF‑документе с помощью API Aspose.PDF Facades. +lastmod: "2026-02-19" +--- + +Поля радиокнопок в PDF‑формах являются сгруппированными элементами управления, где одновременно может быть выбрана только одна опция. Каждая группа имеет имя поля, а каждая опция имеет соответствующее значение. + +1. Создайте объект Form. +1. Привяжите PDF Document. +1. Получите выбранную опцию радиокнопки. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Get radio button options +def get_radio_button_options(infile): + """Get radio button options from a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Get radio button options by their names + field_names = ["WorkType"] + for field_name in field_names: + options = pdf_form.get_button_option_current_value(field_name) + print(f"Options for '{field_name}': {options}") +``` diff --git a/ru/python-net/working-with-facades/form/reading-form-values/get-required-field-names/_index.md b/ru/python-net/working-with-facades/form/reading-form-values/get-required-field-names/_index.md new file mode 100644 index 000000000..a581130e6 --- /dev/null +++ b/ru/python-net/working-with-facades/form/reading-form-values/get-required-field-names/_index.md @@ -0,0 +1,42 @@ +--- +title: Получить имена обязательных полей +linktitle: Получить имена обязательных полей +type: docs +weight: 30 +url: /python-net/get-required-field-names/ +description: Этот пример демонстрирует, как идентифицировать и получить имена обязательных полей формы в PDF-документе с использованием API Aspose.PDF Facades. +lastmod: "2026-02-19" +--- + +PDF-формы могут содержать обязательные поля, которые пользователи должны заполнить перед отправкой. Эти поля обычно помечены как обязательные в свойствах формы. + +1. Создайте объект Form. +1. Привяжите PDF Document. +1. Получите все имена полей можно с помощью 'pdf_form.field_names'. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Get required field names +def get_required_field_names(infile): + """Get required field names from a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Get required field names + for field in pdf_form.field_names: + if pdf_form.is_required_field(field): + print(f"Required field: {field}") +``` diff --git a/ru/python-net/working-with-facades/form/reading-form-values/get-rich-text-values/_index.md b/ru/python-net/working-with-facades/form/reading-form-values/get-rich-text-values/_index.md new file mode 100644 index 000000000..a23eb1dd9 --- /dev/null +++ b/ru/python-net/working-with-facades/form/reading-form-values/get-rich-text-values/_index.md @@ -0,0 +1,43 @@ +--- +title: Получить значения Rich Text +linktitle: Получить значения Rich Text +type: docs +weight: 40 +url: /python-net/get-rich-text-values/ +description: Этот раздел объясняет, как получить содержимое Rich Text поля формы в PDF‑документе с помощью API Aspose.PDF Facades. В отличие от обычных текстовых полей, поля Rich Text могут содержать форматированный контент, такой как полужирный текст, различные шрифты, цвета и стили абзацев. +lastmod: "2026-02-19" +--- + +PDF‑формы могут включать текстовые поля, поддерживающие форматирование Rich Text. Эти поля могут хранить содержимое со стилевыми атрибутами в дополнение к обычным текстовым значениям. + +1. Создайте объект Form. +1. Привяжите PDF Document. +1. Получите значения Rich Text. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Get rich text values +def get_rich_text_values(infile): + """Get rich text values from a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Get rich text values by their names + field_names = ["Summary"] + for field_name in field_names: + rich_text_value = pdf_form.get_rich_text(field_name) + print(f"Rich text value of '{field_name}': {rich_text_value}") +``` diff --git a/ru/python-net/working-with-facades/form/reading-form-values/resolve-full-field-names/_index.md b/ru/python-net/working-with-facades/form/reading-form-values/resolve-full-field-names/_index.md new file mode 100644 index 000000000..17e00137a --- /dev/null +++ b/ru/python-net/working-with-facades/form/reading-form-values/resolve-full-field-names/_index.md @@ -0,0 +1,43 @@ +--- +title: Получить полные имена полей +linktitle: Получить полные имена полей +type: docs +weight: 60 +url: /python-net/resolve-full-field-names/ +description: Этот пример демонстрирует, как получить полностью квалифицированные имена полей формы в PDF‑документе с использованием Aspose.PDF Facades API. +lastmod: "2026-02-19" +--- + +В PDF‑формах поля могут быть организованы иерархически, особенно когда используются подформы. Каждое поле имеет короткое имя и полностью квалифицированное имя. Полностью квалифицированное имя представляет собой полный путь поля внутри иерархии формы и требуется многими методами API, которые манипулируют или читают данные формы. + +1. Создайте объект Form. +1. Привяжите PDF Document. +1. Получите все имена полей формы +1. Полностью квалифицированное имя каждого поля определяется с помощью get_full_field_name(). + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Resolve full field names +def resolve_full_field_names(infile): + """Resolve full field names in a PDF document.""" + # Create Form object + pdf_form = pdf_facades.Form() + + # Bind PDF document + pdf_form.bind_pdf(infile) + + # Resolve full field names + for field in pdf_form.field_names: + name = pdf_form.get_full_field_name(field) + print(f"Full field name: {name}") +``` diff --git a/ru/python-net/working-with-facades/formeditor/_index.md b/ru/python-net/working-with-facades/formeditor/_index.md new file mode 100644 index 000000000..d71699925 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/_index.md @@ -0,0 +1,26 @@ +--- +title: Класс FormEditor +linktitle: Класс FormEditor +type: docs +weight: 100 +url: /python-net/formeditor-class/ +description: Узнайте, как использовать класс FormEditor в Aspose.PDF for Python via .NET для создания полей формы, изменения существующих полей, настройки внешнего вида полей и добавления скриптов или действий отправки. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Создавайте и редактируйте PDF‑поля формы в Python с помощью класса FormEditor. +Abstract: В этом разделе объясняется, как использовать фасад FormEditor в Aspose.PDF for Python via .NET для создания и обновления интерактивных PDF‑форм. Узнайте, как программно создавать поля формы, настраивать их внешний вид, изменять существующие поля и добавлять скрипты или действия отправки. +--- + +Следующий `FormEditor` Класс в Aspose.PDF Facades предназначен для создания и обновления интерактивных полей формы PDF. Он помогает строить структуру формы, настраивать свойства полей, изменять параметры внешнего вида и прикреплять интерактивное поведение, такое как скрипты и действия отправки, в приложениях Python. + +## Общие задачи FormEditor + +Используйте следующие учебники для работы с основными возможностями данного `FormEditor`: + +- [Добавление сценариев и действий отправки](/pdf/ru/python-net/adding-scripts-and-submit-actions/) +- [Настройка внешнего вида полей](/pdf/ru/python-net/customizing-field-appearance/) +- [Изменение полей формы](/pdf/ru/python-net/modifying-form-fields/) +- [Создание поля формы](/pdf/ru/python-net/creating-form-field) diff --git a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md new file mode 100644 index 000000000..3ecc5396a --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md @@ -0,0 +1,22 @@ +--- +title: Добавление сценариев и действий отправки +linktitle: Добавление сценариев и действий отправки +type: docs +weight: 40 +url: /python-net/adding-scripts-and-submit-actions/ +description: С помощью Aspose.PDF for Python разработчики могут автоматизировать эти действия без ручного редактирования PDF. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавление и управление скриптами полей формы PDF и действиями отправки в Python +Abstract: Узнайте, как программно добавлять, изменять или удалять действия JavaScript для полей формы PDF и настраивать URL‑адреса отправки с помощью Aspose.PDF for Python. Это руководство объясняет, как прикреплять скрипты к полям, обновлять существующие скрипты, удалять действия полей и задавать URL‑адреса для отправки формы, обеспечивая динамические и интерактивные PDF‑формы. +--- + +- [Добавить скрипт поля](/pdf/ru/python-net/add-field-script/) +- [Установить скрипт поля](/pdf/ru/python-net/set-field-script/) +- [Удалить действие поля](/pdf/ru/python-net/remove-field-action/) +- [Установить URL отправки](/pdf/ru/python-net/set-submit-url/) +- [Установить флаг отправки](/pdf/ru/python-net/set-submit-flag/) + diff --git a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md new file mode 100644 index 000000000..7601805c4 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md @@ -0,0 +1,57 @@ +--- +title: Добавить скрипт поля +linktitle: Добавить скрипт поля +type: docs +weight: 10 +url: /python-net/add-field-script/ +description: Интерактивные PDF‑формы могут включать JavaScript для автоматизации действий, когда пользователи взаимодействуют с полями формы. С помощью Aspose.PDF for Python разработчики могут легко прикреплять скрипты к элементам формы, таким как кнопки или текстовые поля. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить действия JavaScript к полям PDF‑формы с помощью Python +Abstract: В этой статье объясняется, как открыть PDF‑форму, назначить код JavaScript конкретному полю формы, добавить дополнительные действия скрипта и сохранить обновленный документ. В примере используется класс FormEditor из API Aspose.PDF Facades для программного управления поведением формы. +--- + +## Добавить действия JavaScript к полям PDF‑формы с помощью Python + +Этот фрагмент кода позволяет добавить действия JavaScript к существующему полю PDF‑формы с использованием библиотеки Aspose.PDF for Python. Он открывает PDF‑документ, назначает действие JavaScript полю формы и добавляет скрипт, который выполняется при срабатывании поля. В конце обновлённый PDF сохраняется в новый файл. +Используя [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) класс из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) модуля, вы можете программно привязать JavaScript к существующим полям формы: + +1. Откройте существующую PDF-форму. +1. Установите действие JavaScript для конкретного поля. +1. Добавьте другое действие JavaScript к тому же полю. +1. Сохраните изменённый PDF‑документ. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_field_script(input_file_name, output_file_name): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + + # Open input PDF file + form_editor.bind_pdf(input_file_name) + + # Set JavaScript action for the field + form_editor.set_field_script( + "Script_Demo_Button", "app.alert('Script 1 has been executed');" + ) + + # Add JavaScript action to the field + form_editor.add_field_script( + "Script_Demo_Button", "app.alert('Script 2 has been executed');" + ) + + # Save output PDF file + form_editor.save(output_file_name) +``` diff --git a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md new file mode 100644 index 000000000..3cd47c8d5 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md @@ -0,0 +1,51 @@ +--- +title: Удалить действие поля +linktitle: Удалить действие поля +type: docs +weight: 20 +url: /python-net/remove-field-action/ +description: Удаление JavaScript из полей формы может быть полезным при изменении интерактивных PDF‑форм, отключении ранее назначенных действий или очистке документов, содержащих ненужные скрипты. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Удалить действия JavaScript из полей PDF‑формы с помощью Python +Abstract: С помощью Aspose.PDF for Python разработчики могут программно удалять действия JavaScript, привязанные к полям формы. В этой статье объясняется, как открыть существующую PDF‑форму, удалить скрипт, связанный с конкретным полем, используя класс FormEditor, проверить операцию и сохранить изменённый документ. +--- + +PDF‑формы часто содержат действия JavaScript, которые выполняются, когда пользователи взаимодействуют с элементами формы, такими как кнопки или поля ввода. В некоторых случаях эти скрипты необходимо удалить, чтобы упростить поведение формы, повысить безопасность или обновить логику формы. Удалите действие JavaScript из поля формы в PDF‑документе с помощью Aspose.PDF for Python. Код открывает существующую PDF‑форму, находит конкретное поле, удаляет связанное с ним действие JavaScript и сохраняет обновлённый документ как новый PDF‑файл. + +Используя [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) класс из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/), вы можете удалить действия JavaScript из конкретных полей в существующей PDF‑форме: + +1. Откройте существующую PDF-форму. +1. Найдите поле формы с именем 'Script_Demo_Button'. +1. Удалите действие JavaScript, связанное с этим полем. +1. Проверьте, было ли удаление успешным. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def remove_field_script(input_file_name, output_file_name): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + + # Open input PDF file + form_editor.bind_pdf(input_file_name) + + # Remove JavaScript action from the field + if not form_editor.remove_field_action("Script_Demo_Button"): + raise Exception("Failed to remove field script") + + # Save output PDF file + form_editor.save(output_file_name) +``` diff --git a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md new file mode 100644 index 000000000..a755b884d --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md @@ -0,0 +1,60 @@ +--- +title: Установить скрипт поля +linktitle: Установить скрипт поля +type: docs +weight: 30 +url: /python-net/set-field-script/ +description: Этот фрагмент кода показывает, как назначить действие JavaScript полю формы в PDF‑документе с использованием Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Установить действия JavaScript для полей формы PDF с использованием Python +Abstract: В этой статье объясняется, как открыть PDF‑документ, назначить код JavaScript полю формы, обновить скрипт с помощью класса FormEditor и сохранить изменённый файл. Пример демонстрирует, как существующие скрипты могут быть переопределены для изменения поведения полей формы. +--- + +Интерактивные PDF‑формы часто полагаются на JavaScript для выполнения таких задач, как отображение предупреждений, проверка ввода или запуск динамического поведения формы. С помощью Aspose.PDF for Python разработчики могут программно управлять этими скриптами. + +В примере сначала добавляется действие JavaScript к полю, а затем оно заменяется другим скриптом с помощью метода 'set_field_script'. Такой подход позволяет разработчикам контролировать или обновлять интерактивное поведение элементов PDF‑формы, таких как кнопки или поля ввода. + +Поле формы, используемое в этом примере, называется 'Script_Demo_Button', которое обычно представляет кнопку, выполняющую назначенный скрипт при срабатывании. + +Используя [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) класс из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) модуля, разработчики могут программно управлять действиями JavaScript, связанными с полями формы: + +1. Откройте существующий документ PDF-формы. +1. Добавьте действие JavaScript к полю формы. +1. Установите (замените) действие JavaScript новым скриптом. +1. Сохраните изменённый PDF‑документ. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_field_script(input_file_name, output_file_name): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + + # Open input PDF file + form_editor.bind_pdf(input_file_name) + + # Add JavaScript action to the field + form_editor.add_field_script( + "Script_Demo_Button", "app.alert('Script 1 has been executed');" + ) + + # Set JavaScript action for the field + form_editor.set_field_script( + "Script_Demo_Button", "app.alert('Script 2 has been executed');" + ) + + # Save output PDF file + form_editor.save(output_file_name) +``` diff --git a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md new file mode 100644 index 000000000..80f5676f5 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md @@ -0,0 +1,47 @@ +--- +title: Установить флаг отправки +linktitle: Установить флаг отправки +type: docs +weight: 50 +url: /python-net/set-submit-flag/ +description: Узнайте, как программно установить флаг отправки для кнопки формы PDF, используя Aspose.PDF for Python. Это позволяет кнопке отправлять данные формы в определённом формате, например XFDF, при нажатии пользователем. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Установить флаг отправки для кнопки формы PDF с помощью Aspose.PDF for Python +Abstract: Формы PDF можно настроить для отправки данных формы на сервер или конечную точку в разных форматах. Устанавливая флаг отправки у поля‑кнопки, разработчики могут определить способ отправки данных. В этом руководстве показано, как использовать класс FormEditor для установки флага отправки у существующей кнопки отправки в документе PDF и сохранить обновлённый файл. +--- + +Формы PDF часто включают кнопки отправки для передачи ввода пользователя на сервер. Флаг отправки определяет формат отправляемых данных (например, XFDF, FDF, HTML). + +1. Привязажите документ PDF. +1. Получите доступ к существующей кнопке отправки. +1. Установите флаг отправки для требуемого формата. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_submit_flag(input_file_name, output_file_name): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + + # Open input PDF file + form_editor.bind_pdf(input_file_name) + + # Set submit flag for the form + form_editor.set_submit_flag("Script_Demo_Button", ap.facades.SubmitFormFlag.XFDF) + + # Save output PDF file + form_editor.save(output_file_name) +``` diff --git a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md new file mode 100644 index 000000000..f49d62958 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md @@ -0,0 +1,57 @@ +--- +title: Установить URL отправки +linktitle: Установить URL отправки +type: docs +weight: 40 +url: /python-net/set-submit-url/ +description: В этом примере показано, как настроить действие отправки для поля кнопки в PDF‑форме с использованием Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Установить URL отправки для кнопки PDF‑формы с помощью Python +Abstract: В этой статье объясняется, как открыть существующую PDF‑форму, определить URL отправки для поля кнопки с использованием класса FormEditor, проверить успешность операции и сохранить обновлённый PDF‑документ. +--- + +PDF‑формы могут быть спроектированы для отправки своих данных на веб‑сервер при нажатии пользователем кнопки отправки. С помощью Aspose.PDF for Python разработчики могут программно настроить действие отправки для полей формы. +Установив URL отправки, форма может отправлять введённые пользователем данные на сервер при нажатии кнопки. Эта функция полезна для рабочих процессов, когда PDF‑формы должны отправлять информацию в веб‑приложения, базы данных или службы обработки. + +Используя [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) класс из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) модуля, разработчики могут программно назначать URL-адрес отправки для поля кнопки в существующей PDF-форме. + +1. Откройте существующую PDF-форму. +1. Найдите поле кнопки с именем Script_Demo_Button. +1. Назначьте URL-адрес, куда будут отправляться данные формы. +1. Проверьте, что действие было успешно применено. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_submit_url(input_file_name, output_file_name): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + + # Set license + set_license() + + # Open input PDF file + form_editor.bind_pdf(input_file_name) + + # Set submit URL for the button + if not form_editor.set_submit_url( + "Script_Demo_Button", "http://www.example.com/submit" + ): + raise Exception("Failed to set submit URL") + + # Save output PDF file + form_editor.save(output_file_name) +``` diff --git a/ru/python-net/working-with-facades/formeditor/creating-form-field/_index.md b/ru/python-net/working-with-facades/formeditor/creating-form-field/_index.md new file mode 100644 index 000000000..80afbc573 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/creating-form-field/_index.md @@ -0,0 +1,22 @@ +--- +title: Создание поля формы +linktitle: Создание поля формы +type: docs +weight: 50 +url: /python-net/creating-form-field/ +description: В этой статье демонстрируется, как создавать интерактивные поля формы в PDF‑документах с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Создание полей формы PDF в Python +Abstract: PDF‑формы позволяют пользователям вводить или выбирать данные непосредственно в документе. С помощью Aspose.PDF разработчики могут программно создавать различные поля формы — CheckBox для логических выборов, ComboBox для раскрывающихся списков, ListBox для многовыборных списков, RadioButton для взаимно исключающих вариантов, TextBox для ввода текста и SubmitButton для отправки данных формы. Такой единый подход упрощает создание интерактивных PDF, обеспечивая точное размещение, единообразный стиль и совместимость с автоматической обработкой и обработкой пользовательского ввода. +--- + +- [Создать поле CheckBox](/pdf/ru/python-net/create-checkbox-field/) +- [Создать поле ComboBox](/pdf/ru/python-net/create-combobox-field/) +- [Создать поле ListBox](/pdf/ru/python-net/create-listbox-field/) +- [Создать поле RadioButton](/pdf/ru/python-net/create-radiobutton-field/) +- [Создать Submit Button](/pdf/ru/python-net/create-submit-button/) +- [Создать поле TextBox](/pdf/ru/python-net/create-textbox-field/) \ No newline at end of file diff --git a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md new file mode 100644 index 000000000..b88ef6cf1 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md @@ -0,0 +1,55 @@ +--- +title: Создать поле CheckBox +linktitle: Создать поле CheckBox +type: docs +weight: 10 +url: /python-net/create-checkbox-field/ +description: Узнайте, как программно добавить поле формы‑чекбокс в документ PDF с помощью Aspose.PDF for Python. Это руководство демонстрирует, как использовать класс FormEditor для вставки интерактивного чекбокса в существующий файл PDF и сохранения обновлённого документа. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Создать поле Checkbox в PDF с использованием Aspose.PDF for Python +Abstract: Интерактивные поля формы позволяют пользователям заполнять и взаимодействовать с PDF‑документами в цифровом виде. В этом учебном руководстве вы узнаете, как добавить поле чекбокса в PDF с помощью Aspose.PDF Python API. Пример показывает, как привязать существующий PDF‑документ, создать поле формы‑чекбокс в указанных координатах и сохранить изменённый файл. +--- + +PDF‑формы широко используются для сбора пользовательских данных в документах, таких как заявки, опросы и соглашения. Поле чекбокса позволяет пользователям выбирать или снимать выбор варианта в форме. + +С помощью Aspose.PDF for Python разработчики могут программно управлять PDF‑формами. Этот [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) класс предоставляет методы для добавления, редактирования и управления полями формы в PDF‑документе. + +1. Загрузите существующий PDF‑файл. +1. Вызовите метод 'add_field()' с параметром 'FieldType.CHECK_BOX', чтобы создать флажок и указать его позицию. +1. Определите имя поля, подпись и позицию. +1. Сохраните обновлённый PDF‑документ. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def create_checkbox_field(infile, outfile): + """Create CheckBox field in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add CheckBox field to PDF form + pdf_form_editor.add_field( + pdf_facades.FieldType.CHECK_BOX, + "checkbox1", + "Check Box 1", + 1, + 240, + 498, + 256, + 514, + ) + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md new file mode 100644 index 000000000..a8670fd6c --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md @@ -0,0 +1,50 @@ +--- +title: Создать поле ComboBox +linktitle: Создать поле ComboBox +type: docs +weight: 20 +url: /python-net/create-combobox-field/ +description: Проверьте, как программно добавить поле ComboBox (выпадающий список) в документ PDF с помощью Aspose.PDF for Python. Этот пример демонстрирует, как вставить поле ComboBox, добавить выбираемые элементы и сохранить обновлённый файл PDF. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Создать поле ComboBox в PDF с использованием Aspose.PDF for Python +Abstract: Интерактивные поля формы делают PDF более динамичными и удобными для пользователя. Поле ComboBox позволяет пользователям выбирать вариант из заранее определённого выпадающего списка. В этом учебном пособии вы узнаете, как создать ComboBox в PDF с помощью класса FormEditor в Aspose.PDF for Python, заполнить его вариантами и сохранить изменённый документ. +--- + +PDF-формы широко используются для сбора структурированной информации в цифровых документах, таких как заявки, опросы и регистрационные формы. Поле ComboBox предоставляет удобный способ для пользователей выбирать из списка заранее определённых значений, одновременно сохраняя форму компактной и организованной. + +Следующий [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) класс позволяет создавать и управлять различными типами полей, включая текстовые поля, флажки, переключатели и раскрывающиеся списки. + +1. Загрузите существующий PDF‑документ. +1. Добавьте поле ComboBox с помощью метода 'add_field()' и параметра 'FieldType.COMBO_BOX'. +1. Используйте метод 'add_list_item()', чтобы вставить варианты выбора в раскрывающийся список. +1. Сохраните обновлённый PDF‑документ. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def create_combobox_field(infile, outfile): + """Create ComboBox field in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add ComboBox field to PDF form + pdf_form_editor.add_field( + pdf_facades.FieldType.COMBO_BOX, "combobox1", "Australia", 1, 230, 498, 350, 514 + ) + pdf_form_editor.add_list_item("combobox1", ["Australia", "Australia"]) + pdf_form_editor.add_list_item("combobox1", ["New Zealand", "New Zealand"]) + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md new file mode 100644 index 000000000..c7fe33996 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md @@ -0,0 +1,50 @@ +--- +title: Создать поле ListBox +linktitle: Создать поле ListBox +type: docs +weight: 30 +url: /python-net/create-listbox-field/ +description: Узнайте, как программно добавить поле формы ListBox в документ PDF с использованием Aspose.PDF for Python. Это руководство показывает, как вставить поле ListBox, определить выбираемые элементы и сохранить обновлённый файл PDF. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Создать поле ListBox в PDF с использованием Aspose.PDF for Python +Abstract: PDF‑формы позволяют пользователям взаимодействовать с документами, выбирая варианты, вводя данные и отправляя информацию в цифровом виде. Поле ListBox даёт возможность выбирать одно или несколько значений из видимого списка вариантов. В этом руководстве вы узнаете, как создать поле ListBox в PDF с помощью класса FormEditor в Aspose.PDF for Python и заполнить его предопределёнными элементами. +--- + +PDF‑формы часто используются в заявках, опросах и регистрационных документах. Поле ListBox отображает несколько вариантов одновременно, облегчая пользователям просмотр и выбор элементов из списка. + +Следующий [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) класс предоставляет функциональность для добавления различных типов интерактивных полей, включая элементы ListBox. + +1. Загрузите существующий PDF‑документ. +1. Определите список выбираемых вариантов. +1. Добавьте поле ListBox на конкретную страницу. +1. Установите значение по умолчанию. +1. Сохраните обновлённый PDF‑документ. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def create_listbox_field(infile, outfile): + """Create ListBox field in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add ListBox field to PDF form + pdf_form_editor.items = ["Australia", "New Zealand", "Malaysia"] + pdf_form_editor.add_field( + pdf_facades.FieldType.LIST_BOX, "listbox1", "Australia", 1, 230, 398, 350, 514 + ) + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md new file mode 100644 index 000000000..3fee63753 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md @@ -0,0 +1,50 @@ +--- +title: Создать поле RadioButton +linktitle: Создать поле RadioButton +type: docs +weight: 40 +url: /python-net/create-radiobutton-field/ +description: Узнайте, как программно добавить поле радиокнопки в PDF‑документ с помощью Aspose.PDF for Python. Этот пример демонстрирует, как создать группу радиокнопок, определить варианты выбора и сохранить обновлённый PDF‑файл. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Создать поле радиокнопки в PDF с использованием Aspose.PDF for Python +Abstract: Радиокнопки часто используются в PDF‑формах, позволяя пользователям выбирать одну опцию из предопределённой группы вариантов. В этом руководстве вы узнаете, как создать поле радиокнопки в PDF, используя класс FormEditor в Aspose.PDF for Python. Пример показывает, как определить элементы радиокнопок, установить выбор по умолчанию и сохранить обновлённый документ. +--- + +Интерактивные PDF‑формы позволяют пользователям предоставлять структурированные данные непосредственно в документе. Поле радиокнопки полезно, когда пользователям необходимо выбрать только одну опцию из нескольких, например, при выборе страны, пола или предпочтения. + +Следующий [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) класс предоставляет методы для создания различных типов полей, включая текстовые поля, флажки, раскрывающиеся списки, списки и радиокнопки. + +1. Загрузите существующий PDF‑документ. +1. Определите список вариантов переключателей. +1. Добавьте поле переключателя на определённую страницу. +1. Установите значение по умолчанию. +1. Сохраните изменённый PDF‑документ. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def create_radiobutton_field(infile, outfile): + """Create RadioButton field in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add RadioButton field to PDF form + pdf_form_editor.items = ["Australia", "New Zealand", "Malaysia"] + pdf_form_editor.add_field( + pdf_facades.FieldType.RADIO, "radiobutton1", "Malaysia", 1, 240, 498, 256, 514 + ) + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md new file mode 100644 index 000000000..9d4d0f845 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md @@ -0,0 +1,55 @@ +--- +title: Создать кнопку отправки +linktitle: Создать кнопку отправки +type: docs +weight: 50 +url: /python-net/create-submit-button/ +description: Узнайте, как программно добавить кнопку отправки в документ PDF с помощью Aspose.PDF for Python. Этот учебный материал демонстрирует, как создать кнопку, которая отправляет данные формы на указанный URL, и сохранить обновлённый PDF. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Создать кнопку отправки в PDF с использованием Aspose.PDF for Python +Abstract: Кнопки отправки в PDF-формах позволяют пользователям отправлять данные формы непосредственно на сервер или конечную точку. В этом руководстве вы узнаете, как добавить поле кнопки отправки в PDF с помощью класса FormEditor в Aspose.PDF for Python. Пример показывает, как настроить имя кнопки, её подпись, целевой URL и позицию, а затем сохранить обновлённый документ PDF. +--- + +Интерактивные PDF-формы часто требуют от пользователей отправки их ввода для обработки, например, отправки результатов опросов, заявок или отзывов. Поле кнопки отправки предоставляет эту функцию, связывая кнопку с веб‑конечной точкой. + +Класс [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) позволяет добавлять кнопки, флажки, переключатели, текстовые поля и другие элементы управления формой. + +1. Загрузите существующий PDF‑документ. +1. Добавьте поле кнопки Submit на конкретную страницу. +1. Установите метку кнопки и целевой URL-адрес отправки. +1. Сохраните обновлённый PDF с новой кнопкой. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def create_submit_button(infile, outfile): + """Create Submit Button in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add Submit Button to PDF form + pdf_form_editor.add_submit_btn( + "submitbtn1", + 1, + "Submit Button", + "http://example.com/submit", + 100, + 450, + 200, + 470, + ) + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md new file mode 100644 index 000000000..73f3e4c10 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md @@ -0,0 +1,50 @@ +--- +title: Создать поле TextBox +linktitle: Создать поле TextBox +type: docs +weight: 60 +url: /python-net/create-textbox-field/ +description: Узнайте, как программно добавить поля TextBox в документ PDF с помощью Aspose.PDF for Python. Этот учебник показывает, как вставить несколько текстовых полей, задать значения по умолчанию и сохранить обновлённый документ PDF. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Создать поля TextBox в PDF с использованием Aspose.PDF for Python +Abstract: Поля TextBox в формах PDF позволяют пользователям вводить и редактировать текст, делая документы интерактивными и удобными. В этом учебнике вы узнаете, как создавать поля формы TextBox в PDF с помощью класса FormEditor в Aspose.PDF for Python. Пример демонстрирует добавление нескольких полей, указание значений по умолчанию и сохранение изменённого PDF. +--- + +Формы PDF часто требуют ввода текста от пользователей, например имён, адресов или комментариев. Поля TextBox обеспечивают эту функциональность, предоставляя редактируемые поля непосредственно в документе PDF. +Класс [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) позволяет добавлять текстовые поля, флажки, переключатели, списковые поля, комбинированные поля и кнопки, упрощая создание интерактивных PDF. + +1. Загрузите существующий PDF‑документ. +1. Добавьте несколько полей TextBox для ввода пользователем. +1. Установите значения по умолчанию для каждого поля. +1. Сохраните обновлённый PDF‑документ. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def create_textbox_field(infile, outfile): + """Create TextBox field in PDF document.""" + pdf_form_editor = pdf_facades.FormEditor() + pdf_form_editor.bind_pdf(infile) + + # Add TextBox field to PDF form + pdf_form_editor.add_field( + pdf_facades.FieldType.TEXT, "first_name", "Alexander", 1, 50, 570, 150, 590 + ) + pdf_form_editor.add_field( + pdf_facades.FieldType.TEXT, "last_name", "Smith", 1, 235, 570, 330, 590 + ) + + # Save updated PDF document with form fields + pdf_form_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md new file mode 100644 index 000000000..9a8409b4a --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md @@ -0,0 +1,24 @@ +--- +title: Настройка внешнего вида полей +linktitle: Настройка внешнего вида полей +type: docs +weight: 30 +url: /python-net/customizing-field-appearance/ +description: Используя Aspose.PDF for Python, разработчики могут полностью настраивать внешний вид и поведение полей программно. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Настройка внешнего вида полей PDF-формы в Python — выравнивание, цвета, ограничения и атрибуты +Abstract: Узнайте, как настраивать внешний вид и поведение полей PDF-форм с помощью Aspose.PDF for Python. Это руководство охватывает оформление полей цветами и рамками, установку горизонтального и вертикального выравнивания, управление видимостью, настройку атрибутов полей, установку количества ячеек (comb) и ограничений по количеству символов, а также получение информации о внешнем виде полей. Эти техники помогают разработчикам создавать визуально согласованные и удобные для пользователя PDF-формы. +--- + +- [Украсить поле](/pdf/ru/python-net/decorate-field/) +- [Установить выравнивание поля](/pdf/ru/python-net/set-field-alignment/) +- [Установить вертикальное выравнивание поля](/pdf/ru/python-net/set-field-alignment-vertical/) +- [Установить внешний вид поля](/pdf/ru/python-net/set-field-appearance/) +- [Установить количество ячеек поля](/pdf/ru/python-net/set-field-comb-number/) +- [Установить ограничение поля](/pdf/ru/python-net/set-field-limit/) +- [Получить внешний вид поля](/pdf/ru/python-net/get-field-appearance/) + diff --git a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md new file mode 100644 index 000000000..0cd803ebe --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md @@ -0,0 +1,56 @@ +--- +title: Украсьте поле +linktitle: Украсьте поле +type: docs +weight: 10 +url: /python-net/decorate-field/ +description: В этом примере демонстрируется, как настроить внешний вид поля формы в PDF‑документе с использованием Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Украсьте PDF Form Fields с пользовательскими цветами и выравниванием, используя Python +Abstract: В этой статье объясняется, как открыть PDF‑документ, настроить параметры стилей с помощью класса FormFieldFacade, применить эти настройки к полю формы и сохранить обновлённый PDF. В примере демонстрируется, как украсить поле с именем 'First Name' с пользовательскими цветами и центрированным выравниванием текста. +--- + +PDF‑формы часто требуют визуальной настройки для улучшения удобства использования и создания согласованного дизайна. С помощью Aspose.PDF for Python разработчики могут программно украшать поля формы, устанавливая свойства, такие как цвета, границы и выравнивание текста. + +Используйте [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) и [FormFieldFacade](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formfieldfacade/) классы, позволяющие разработчикам легко изменять внешний вид полей формы для повышения читаемости, выделения обязательных полей или соответствия требованиям бренда. + +1. Откройте существующий PDF‑документ. +1. Создайте объект FormEditor для манипулирования полями формы. +1. Определите визуальный стиль с использованием FormFieldFacade. +1. Примените стиль к конкретному полю формы. +1. Сохраните обновлённый документ. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def decorate_field(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + form_editor.facade = pdf_facades.FormFieldFacade() + form_editor.facade.background_color = ap_pydrawing.Color.red + form_editor.facade.text_color = ap_pydrawing.Color.blue + form_editor.facade.border_color = ap_pydrawing.Color.green + form_editor.facade.alignment = pdf_facades.FormFieldFacade.ALIGN_CENTER + form_editor.decorate_field("First Name") + + # Save updated document + form_editor.save(outfile) +``` + diff --git a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md new file mode 100644 index 000000000..a5df487c0 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md @@ -0,0 +1,46 @@ +--- +title: Получить внешний вид поля +linktitle: Получить внешний вид поля +type: docs +weight: 20 +url: /python-net/get-field-appearance/ +description: В этой статье объясняется, как открыть PDF, получить доступ к полю формы, извлечь его настройки внешнего вида и отобразить их. Пример демонстрирует извлечение внешнего вида поля с именем 'Last Name'. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Получить внешний вид поля формы PDF с использованием Python +Abstract: В этом примере показано, как получить свойства визуального оформления поля формы в PDF‑документе с помощью Aspose.PDF for Python. Код открывает существующий PDF, получает доступ к определённому полю формы и выводит детали его оформления, включая цвет фона, цвет текста, цвет рамки и выравнивание. +--- + +Поля формы в PDF‑документах имеют визуальные свойства, такие как цвет фона, цвет текста, цвет рамки и выравнивание. С помощью Aspose.PDF for Python разработчики могут программно проверять эти настройки оформления, используя [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) класс. + +1. Откройте существующий PDF‑документ. +1. Создайте объект FormEditor. +1. Получите информацию о внешнем виде конкретного поля. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def get_field_appearance(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Get field appearance + appearance = form_editor.get_field_appearance("Last Name") + print("Field Appearance: " + str(appearance)) +``` diff --git a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md new file mode 100644 index 000000000..a6ad5a15e --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md @@ -0,0 +1,57 @@ +--- +title: Установить вертикальное выравнивание поля +linktitle: Установить вертикальное выравнивание поля +type: docs +weight: 40 +url: /python-net/set-field-alignment-vertical/ +description: Этот пример демонстрирует, как установить вертикальное выравнивание поля формы в PDF‑документе с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Установить вертикальное выравнивание полей формы PDF с помощью Python +Abstract: В этой статье объясняется, как открыть PDF, установить вертикальное выравнивание поля с помощью класса FormEditor и сохранить обновлённый PDF. Пример устанавливает вертикальное выравнивание поля с именем 'First Name' в нижнюю часть области поля. +--- + +PDF‑поля формы могут содержать текст, которому требуется правильное вертикальное выравнивание для согласованного и профессионального вида. С помощью Aspose.PDF for Python разработчики могут программно изменять вертикальное выравнивание полей формы. +Вертикальное выравнивание позволяет разработчикам контролировать, будет ли текст поля располагаться в верхней, центральной или нижней части ограничивающего поля, улучшая макет и читаемость данных формы. + +Используя [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) класс и [FormFieldFacade](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formfieldfacade/) константы, разработчики могут программно регулировать вертикальное выравнивание, чтобы достичь согласованного расположения формы: + +1. Откройте существующий PDF‑документ. +1. Создайте объект FormEditor. +1. Установите вертикальное выравнивание поля с именем 'First Name' в нижнее положение. +1. Сохраните изменённый документ. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_field_alignment_vertical(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Attempt to set vertical alignment of the "First Name" field to bottom + if form_editor.set_field_alignment_v( + "First Name", pdf_facades.FormFieldFacade.ALIGN_BOTTOM + ): + # Save updated document + form_editor.save(outfile) + else: + raise Exception( + "Failed to set field vertical alignment. Field may not support vertical alignment." + ) +``` diff --git a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md new file mode 100644 index 000000000..d4d476224 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md @@ -0,0 +1,56 @@ +--- +title: Установить выравнивание поля +linktitle: Установить выравнивание поля +type: docs +weight: 30 +url: /python-net/set-field-alignment/ +description: В этом примере показано, как установить выравнивание текста в поле формы в PDF‑документе с использованием Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Установить выравнивание текста для полей формы PDF с помощью Python +Abstract: В этой статье объясняется, как открыть PDF‑документ, установить выравнивание определённого поля с использованием класса FormEditor и сохранить обновлённый PDF. В примере выравнивание текста поля с именем 'First Name' устанавливается по центру. +--- + +Полям формы PDF часто требуется пользовательское выравнивание текста для поддержания единообразного и профессионального оформления. С помощью Aspose.PDF for Python разработчики могут программно задавать выравнивание текстового содержимого поля формы. + +Класс [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) в сочетании с [FormFieldFacade](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formfieldfacade/) константы, позволяют разработчикам программно изменять выравнивание существующих полей формы. + +1. Откройте существующий PDF‑документ. +1. Создать объект FormEditor. +1. Установите выравнивание поля с именем 'First Name' по центру. +1. Сохраните изменённый документ. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_field_alignment(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Set field alignment to center + if form_editor.set_field_alignment( + "First Name", pdf_facades.FormFieldFacade.ALIGN_CENTER + ): + # Save updated document + form_editor.save(outfile) + else: + raise Exception( + "Failed to set field alignment. Field may not support alignment." + ) +``` diff --git a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md new file mode 100644 index 000000000..d8c905d22 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md @@ -0,0 +1,56 @@ +--- +title: Установить внешний вид поля +linktitle: Установить внешний вид поля +type: docs +weight: 50 +url: /python-net/set-field-appearance/ +description: В этом примере показано, как изменить визуальный внешний вид поля формы PDF с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Установить внешний вид поля формы PDF с использованием Python +Abstract: В этой статье объясняется, как открыть PDF, установить внешний вид поля формы с использованием класса FormEditor и сохранить обновлённый документ. В примере внешний вид поля с именем 'First Name' задаётся как невидимый с помощью флага AnnotationFlags.INVISIBLE. +--- + +Поля формы PDF поддерживают флаги внешнего вида, которые контролируют видимость, печатаемость и интерактивность. С помощью Aspose.PDF for Python разработчики могут программно изменять эти флаги для конкретных полей формы. + +Используя [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) класс, разработчики могут изменять флаги, чтобы скрывать, показывать или настраивать поведение полей формы в интерактивном PDF. + +1. Откройте существующий PDF‑документ. +1. Создайте объект FormEditor. +1. Установите внешний вид поля с именем 'First Name' в невидимое. +1. Сохраните обновлённый документ. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_field_appearance(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Set field appearance to invisible + if not form_editor.set_field_appearance( + "First Name", ap.annotations.AnnotationFlags.INVISIBLE + ): + raise Exception( + "Failed to set field appearance. Field may not support appearance flags." + ) + + # Save updated document + form_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md new file mode 100644 index 000000000..2ed31db77 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md @@ -0,0 +1,51 @@ +--- +title: Установить количество ячеек поля +linktitle: Установить количество ячеек поля +type: docs +weight: 70 +url: /python-net/set-field-comb-number/ +description: В этом примере демонстрируется, как установить количество ячеек (comb number) для поля формы PDF с использованием Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Установить количество ячеек (comb number) для полей формы PDF с использованием Python +Abstract: С помощью Aspose.PDF for Python разработчики могут программно установить количество ячеек (comb number) для поля формы, чтобы обеспечить ввод фиксированной длины. В этой статье демонстрируется установка количества ячеек для поля с именем "PIN". +--- + +Количество ячеек определяет, как содержимое поля разбивается на равномерно расположенные ячейки, часто используется для PIN‑кодов, серийных номеров или других полей ввода фиксированной длины. Код открывает существующий PDF, устанавливает количество ячеек для поля и сохраняет изменённый документ. + +Класс [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) предоставляет метод ‘set_field_comb_number’, позволяющий задать количество ячеек (символов) в поле формы. + +1. Откройте существующую PDF-форму. +1. Создайте объект FormEditor. +1. Установите число comb поля с именем "PIN" равным 5. +1. Сохраните обновлённый документ. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_field_comb_number(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Set field comb number to 5 + form_editor.set_field_comb_number("PIN", 5) + + # Save updated document + form_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md new file mode 100644 index 000000000..df1c69aab --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md @@ -0,0 +1,54 @@ +--- +title: Установить ограничение поля +linktitle: Установить ограничение поля +type: docs +weight: 80 +url: /python-net/set-field-limit/ +description: Этот пример показывает, как установить максимальное ограничение количества символов для поля формы в PDF-документе с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Установить максимальное ограничение символов для полей формы PDF с использованием Python +Abstract: Этот пример демонстрирует установку ограничения символов для поля с именем 'Last Name' до 10 символов, гарантируя, что пользователи не смогут ввести более указанного лимита. +--- + +Поля формы в PDF-документах могут потребовать ограничений ввода для поддержания правильного форматирования. С помощью Aspose.PDF for Python разработчики могут программно задать максимальное количество символов для поля. + +Класс [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) предоставляет метод 'set_field_limit' для определения максимальной длины ввода для поля. + +1. Откройте существующую PDF-форму. +1. Создайте объект FormEditor. +1. Установите максимальный лимит символов для поля 'Last Name'. +1. Сохраните обновлённый PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_field_limit(infile, outfile): + # Open document + doc = ap.Document(infile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor(doc) + + # Set field limit to 10 + if not form_editor.set_field_limit("Last Name", 10): + raise Exception( + "Failed to set field limit. Field may not support specified limit." + ) + + # Save updated document + form_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md new file mode 100644 index 000000000..a1b98554f --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md @@ -0,0 +1,25 @@ +--- +title: Изменение полей формы +linktitle: Изменение полей формы +type: docs +weight: 20 +url: /python-net/modifying-form-fields/ +description: Используя Aspose.PDF for Python, вы можете эффективно изменять поля формы программно с помощью класса FormEditor. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Изменение полей формы PDF в Python — добавление, перемещение, копирование, переименование и удаление полей +Abstract: Узнайте, как изменять существующие поля формы PDF с помощью Aspose.PDF for Python. Это руководство объясняет, как управлять элементами формы, добавляя или удаляя пункты списка, перемещая поля, удаляя или переименовывая их, преобразуя однострочные поля в многострочные и копируя поля внутри документов или между документами. Эти приёмы помогают разработчикам динамически обновлять формы PDF и адаптировать их к меняющимся бизнес‑требованиям без необходимости воссоздавать всю структуру формы. +--- + +- [Добавить элемент списка](/pdf/ru/python-net/add-list-item/) +- [Удалить элемент списка](/pdf/ru/python-net/del-list-item/) +- [Переместить поле](/pdf/ru/python-net/move-field/) +- [Удалить поле](/pdf/ru/python-net/remove-field/) +- [Переименовать поле](/pdf/ru/python-net/rename-field/) +- [Однострочное поле в многострочное поле](/pdf/ru/python-net/single-to-multiple/) +- [Скопировать внутреннее поле](/pdf/ru/python-net/copy-inner-field/) +- [Копировать внешнее поле](/pdf/ru/python-net/copy-outer-field/) + diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md new file mode 100644 index 000000000..e4508953e --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md @@ -0,0 +1,46 @@ +--- +title: Добавить элемент списка +linktitle: Добавить элемент списка +type: docs +weight: 10 +url: /python-net/add-list-item/ +description: В этом примере демонстрируется, как добавить элементы в поле списка формы в PDF‑документе с использованием Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавление элементов в поля списка PDF с использованием Python +Abstract: В этой статье показано, как открыть PDF‑документ, добавить элементы в поле списка с именем "Country" и сохранить обновлённый документ. +--- + +Поля списка в PDF позволяют пользователям выбирать одну или несколько опций из предопределённого набора. С помощью Aspose.PDF for Python разработчики могут программно добавлять новые элементы в эти поля. Класс [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) предоставляет метод 'add_list_item' для добавления элементов в существующее поле списка. + +1. Откройте существующую PDF-форму. +1. Создайте объект FormEditor. +1. Привяжите PDF к FormEditor. +1. Добавьте элементы в поле списка 'Country'. +1. Сохраните обновлённый документ. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_list_item(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Add list item to list box field + form_editor.add_list_item("Country", ["New Zealand", "New Zealand"]) + # Save updated document + form_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md new file mode 100644 index 000000000..981219964 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md @@ -0,0 +1,72 @@ +--- +title: Скопировать внутреннее поле +linktitle: Скопировать внутреннее поле +type: docs +weight: 20 +url: /python-net/copy-inner-field/ +description: Скопировать поля формы PDF в новое положение с помощью Python, используя Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Скопировать поля формы PDF в новое положение с помощью Python +Abstract: В этом примере демонстрируется, как скопировать существующее поле формы в новое положение в PDF-документе с использованием Aspose.PDF for Python. Код открывает PDF, дублирует поле на указанную страницу и координаты и сохраняет обновлённый документ. +--- + +PDF-формы часто требуют дублирования полей при сохранении оригинального форматирования и поведения. С помощью Aspose.PDF for Python разработчики могут программно копировать существующее поле в новое положение на той же или другой странице. + +В этой статье объясняется, как скопировать поле с именем 'First Name' в новое поле под названием 'First Name Copy' на странице 2 с конкретными координатами (x=200, y=600), создавая PDF с новым расположенным полем. + +1. Откройте существующую PDF-форму. +1. Создайте объект FormEditor. +1. Привяжите PDF‑документ к FormEditor. +1. Скопируйте поле 'First Name' в новое поле 'First Name Copy' на странице 2 с координатами (200, 600). +1. Сохраните обновлённый документ. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def copy_inner_field(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Copies an existing field to a new position specified by both page number and ordinates. + # A new document will be produced, which contains everything the source document has except for the newly copied field. + form_editor.copy_inner_field("First Name", "First Name Copy", 2, 200, 600) + # Save updated document + form_editor.save(outfile) +``` + +**Обратите внимание:** + +Подпись метода 'copy_inner_field' выглядит так: + +```python +copy_inner_field(original_field_name, new_field_name, page_number, x, y) +``` + +- 'original_field_name' – поле, которое вы хотите дублировать. +- 'new_field_name' – имя нового поля. +- 'page_number' – страница, на которой появится новое поле. +- x, y – координаты на этой странице. + +Ожидается, что page_number будет положительным целым числом, соответствующим существующей странице в PDF (нумерация с 1). + +Если передать отрицательный параметр, например: + +```python +form_editor.copy_inner_field("First Name", "First Name Copy", -1, 200, 600) +``` + +Программа затем сбросит параметры к предыдущим. diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md new file mode 100644 index 000000000..a65ec7fb9 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md @@ -0,0 +1,80 @@ +--- +title: Копировать внешнее поле +linktitle: Копировать внешнее поле +type: docs +weight: 30 +url: /python-net/copy-outer-field/ +description: В этом примере демонстрируется, как скопировать поле формы из одного PDF‑документа в другой, используя Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Копировать PDF‑поля формы из другого документа, используя Python +Abstract: В этой статье объясняется, как создать новый PDF‑документ, скопировать поле 'First Name' из исходного PDF на страницу 1 с координатами (200, 600) и сохранить обновлённый целевой документ. +--- + +Иногда PDF‑формы требуют повторного использования полей из одного документа в другом. С помощью Aspose.PDF for Python разработчики могут программно копировать поля формы из исходного PDF в целевой PDF. + +Класс [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) предоставляет метод 'copy_outer_field', который копирует поле из исходного документа в целевой документ на указанной странице и координатах. + +Код создает новый PDF (целевой), добавляет страницу, а затем копирует поле из существующего PDF (исходного) в целевой документ на заданных координатах. + +1. Создайте новый целевой PDF‑документ. +1. Добавьте как минимум одну страницу в целевой PDF. +1. Сохраните пустой целевой документ. +1. Создайте объект FormEditor и привяжите его к целевому PDF. +1. Скопируйте поле 'First Name' из исходного PDF на страницу 1 в координаты (200, 600). +1. Сохраните обновлённый целевой PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def copy_outer_field(infile, outfile): + # Since copy_outer_field() method needs to copy field from source document to target document, we need to create a new document as target document first. + doc = ap.Document() + doc.pages.add() + doc.save(outfile) + + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(outfile) + # Copies an existing field to a new position specified by both page number and ordinates. + # A new document will be produced, which contains everything the source document has except for the newly copied field. + form_editor.copy_outer_field(infile, "First Name", 1, 200, 600) + # Save updated document + form_editor.save(outfile) +``` + +**Обратите внимание:** + +Сигнатура метода 'copy_outer_field' выглядит так: + +```python +copy_outer_field(original_field_name, new_field_name, page_number, x, y) +``` + +- 'original_field_name' – поле, которое вы хотите дублировать. +- 'new_field_name' – имя нового поля. +- 'page_number' – страница, на которой появится новое поле. +- x, y – координаты на этой странице. + +Ожидается, что page_number будет положительным целым числом, соответствующим существующей странице в PDF (нумерация с 1). + +Если передать отрицательный параметр, например: + +```python +form_editor.copy_outer_field("First Name", "First Name Copy", 1, -200, 600) +``` + +Программа затем сбросит параметры к предыдущим. diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md new file mode 100644 index 000000000..eb133610d --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md @@ -0,0 +1,51 @@ +--- +title: Удалить элемент списка +linktitle: Удалить элемент списка +type: docs +weight: 40 +url: /python-net/del-list-item/ +description: +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Удалить элементы из полей списка PDF, используя Python +Abstract: В этом примере показано, как удалить элемент из поля списка формы в PDF‑документе с использованием Aspose.PDF for Python. Код открывает существующий PDF, удаляет определённый элемент из поля списка и сохраняет обновлённый документ. +--- + +Поля списка в PDF позволяют пользователям выбирать один или несколько предопределённых вариантов. С помощью Aspose.PDF for Python разработчики могут программно удалять элементы из этих полей. + +В этой статье объясняется, как удалить элемент 'UK' из поля списка с именем 'Country', гарантируя, что поле содержит только необходимые варианты. + +Класс [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) предоставляет метод 'del_list_item' для удаления конкретного элемента из поля списка. + +1. Откройте существующую PDF-форму. +1. Создайте объект FormEditor. +1. Привяжите PDF‑документ к FormEditor. +1. Удалить элемент 'UK' из поля списка 'Country'. +1. Сохраните обновлённый документ. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def del_list_item(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Delete list item from list box field + form_editor.del_list_item("Country", "UK") + # Save updated document + form_editor.save(outfile) +``` + diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md new file mode 100644 index 000000000..64c58029a --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md @@ -0,0 +1,48 @@ +--- +title: Переместить поле +linktitle: Переместить поле +type: docs +weight: 50 +url: /python-net/move-field/ +description: Переместить существующее поле формы в другое место в PDF‑документе. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Переместить поле формы PDF в новое положение с использованием Python +Abstract: В этом примере демонстрируется, как переместить существующее поле формы в другое место в PDF‑документе с использованием Aspose.PDF for Python. Код открывает существующий PDF, перемещает указанное поле формы к новым координатам и сохраняет обновленный документ. +--- + +PDF‑формы часто требуют корректировки макета после создания. С помощью Aspose.PDF for Python разработчики могут перемещать существующие поля формы в новое положение без их восстановления. + +В этом примере показано, как переместить поле "Country", указав новые координаты его расположения на странице. Класс [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) предоставляет метод move_field для перемещения полей внутри страницы PDF. + +1. Откройте существующую PDF-форму. +1. Создайте объект FormEditor. +1. Привяжите PDF‑документ к FormEditor. +1. Переместите поле 'Country' в новое положение, используя координаты. +1. Сохраните изменённый документ. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def move_field(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Move field to new page + form_editor.move_field("Country", 200, 600, 280, 620) + # Save updated document + form_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md new file mode 100644 index 000000000..8a8df650c --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md @@ -0,0 +1,48 @@ +--- +title: Удалить поле +linktitle: Удалить поле +type: docs +weight: 60 +url: /python-net/remove-field/ +description: Этот пример показывает, как удалить поле 'Country' из PDF-формы с помощью метода 'remove_field' класса 'FormEditor'. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Удалить поле формы из PDF-документа с помощью Python +Abstract: Этот пример демонстрирует, как удалить существующее поле формы из PDF-документа с использованием Aspose.PDF for Python. Код загружает PDF-файл, удаляет указанное поле с помощью класса FormEditor и сохраняет обновлённый документ. +--- + +PDF-формы могут содержать поля, которые больше не нужны из‑за изменений дизайна или обновлений рабочего процесса. С Aspose.PDF for Python разработчики могут легко программно удалять отдельные поля формы. + +Класс [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) в Aspose.PDF предоставляет метод 'remove_field', который позволяет разработчикам удалять поле формы по его имени. + +1. Загрузите PDF‑документ. +1. Создайте объект FormEditor. +1. Привяжите PDF к FormEditor. +1. Удалите указанное поле формы. +1. Сохраните обновлённый документ. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def remove_field(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Remove field from document + form_editor.remove_field("Country") + # Save updated document + form_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md new file mode 100644 index 000000000..bbb022941 --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md @@ -0,0 +1,49 @@ +--- +title: Переименовать поле +linktitle: Переименовать поле +type: docs +weight: 70 +url: /python-net/rename-field/ +description: Переименуйте существующее поле формы в PDF‑документе с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Переименование поля PDF‑формы с использованием Python +Abstract: Этот пример демонстрирует, как переименовать существующее поле формы в PDF‑документе с помощью Aspose.PDF for Python. Код открывает входной PDF, изменяет имя указанного поля формы с использованием класса FormEditor и сохраняет обновлённый документ. +--- + +PDF‑формы часто полагаются на имена полей для скриптов, автоматизации и обработки данных. С помощью Aspose.PDF for Python разработчики могут переименовывать существующие поля без их воссоздания или изменения макета формы. + +Класс [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) предоставляет метод 'rename_field', который позволяет разработчикам изменить имя существующего поля, сохраняя его позицию, значение и внешний вид. + +1. Загрузите существующую PDF-форму. +1. Создайте экземпляр FormEditor. +1. Привяжите PDF‑документ к редактору. +1. Переименуйте целевое поле. +1. Сохраните обновлённый PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def rename_field(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Rename field in document + form_editor.rename_field("City", "Town") + # Save updated document + form_editor.save(outfile) +``` + diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md new file mode 100644 index 000000000..39cc6005e --- /dev/null +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md @@ -0,0 +1,49 @@ +--- +title: Однострочное поле в многострочное поле +linktitle: Однострочное поле в многострочное поле +type: docs +weight: 80 +url: /python-net/single-to-multiple/ +description: Преобразовать однострочное текстовое поле в многострочное поле в PDF‑документе с использованием Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Преобразовать однострочное текстовое поле в многострочное поле в PDF с использованием Python +Abstract: В этом примере демонстрируется, как преобразовать однострочное текстовое поле в многострочное поле в PDF‑документе с использованием Aspose.PDF for Python. Код загружает существующую PDF‑форму, изменяет указанное поле, позволяя вводить несколько строк текста, и сохраняет обновлённый документ. +--- + +PDF‑формы иногда содержат текстовые поля, предназначенные для ввода одной строки, что может быть недостаточно для некоторых типов данных. С помощью Aspose.PDF for Python разработчики могут легко преобразовать такие поля в многострочные текстовые поля без их воссоздания. + +Используя [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) класс, разработчики могут изменять существующие текстовые поля, не влияя на их положение или другие свойства. + +1. Загрузите существующий PDF-документ. +1. Создайте экземпляр FormEditor. +1. Привяжите PDF‑документ к редактору. +1. Преобразовать выбранное поле в многострочное. +1. Сохраните обновлённый документ. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def single2multiple(infile, outfile): + # Create FormEditor object + form_editor = pdf_facades.FormEditor() + # Bind document to FormEditor + form_editor.bind_pdf(infile) + # Change a single-lined text field to a multiple-lined one + form_editor.single_2_multiple("City") + # Save updated document + form_editor.save(outfile) +``` + diff --git a/ru/python-net/working-with-facades/pdfannotationeditor/_index.md b/ru/python-net/working-with-facades/pdfannotationeditor/_index.md new file mode 100644 index 000000000..56548c649 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfannotationeditor/_index.md @@ -0,0 +1,22 @@ +--- +title: Класс PdfAnnotationEditor +linktitle: Класс PdfAnnotationEditor +type: docs +weight: 40 +url: /python-net/pdfannotationeditor-class/ +description: Узнайте, как использовать класс PdfAnnotationEditor в Aspose.PDF for Python via .NET для работы с PDF‑аннотациями, комментариями и разметкой программно. +lastmod: "2026-02-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Редактировать PDF‑аннотации и комментарии в Python с помощью PdfAnnotationEditor +Abstract: Этот раздел представляет класс PdfAnnotationEditor в Aspose.PDF for Python via .NET для рабочих процессов PDF, связанных с аннотациями. Используйте этот фасад для программного управления PDF‑аннотациями, комментариями и разметкой при работе с существующими документами в приложениях на Python. +--- + +`PdfAnnotationEditor` к+ласс в Aspose.PDF Facades предназначен для работы с PDF‑аннотациями и разметкой на основе комментариев без необходимости вручную редактировать низкоуровневую структуру документа. Он предоставляет упрощённый способ обработки процессов аннотирования в Python via .NET, когда требуется просматривать или обновлять существующие PDF‑файлы. + +## Для чего используется PdfAnnotationEditor + +Используйте этот фасад, когда ваш процесс работы с PDF включает аннотации, комментарии по обзору или другие элементы разметки, которые необходимо управлять программно. По мере расширения этого раздела он должен служить целевой страницей для учебных материалов, связанных с аннотациями, построенных вокруг `PdfAnnotationEditor` класс. + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/_index.md new file mode 100644 index 000000000..b9e367049 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/_index.md @@ -0,0 +1,32 @@ +--- +title: Класс PdfContentEditor +linktitle: Класс PdfContentEditor +type: docs +weight: 30 +url: /python-net/pdfcontenteditor-class/ +description: Узнайте, как использовать класс PdfContentEditor в Aspose.PDF for Python via .NET для редактирования содержимого PDF, управления аннотациями и вложениями, работы со ссылками, изображениями, текстом, мультимедиа, штампами и настройками просмотра. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Редактировать содержимое PDF и интерактивные элементы в Python с PdfContentEditor +Abstract: В этом разделе объясняется, как использовать класс PdfContentEditor в Aspose.PDF for Python via .NET для рабочих процессов на уровне содержимого PDF. Узнайте, как программно управлять аннотациями, вложениями, действиями документа, рисованием разметки, изображениями, ссылками, мультимедиа, штампами, заменой текста и настройками просмотра. +--- + +`PdfContentEditor` Класс в Aspose.PDF Facades предназначен для задач редактирования на уровне содержимого в существующих PDF‑документах. Он предоставляет упрощённый API для обновления интерактивных элементов, замены текста, работы с вложениями и ссылками, а также настройки поведения документа в приложениях Python via .NET. + +## Что можно сделать с PdfContentEditor + +Используйте этот раздел, чтобы изучить основные области редактирования содержимого PDF, поддерживаемые `PdfContentEditor` фасад: + +- [Работайте с аннотациями, используя PdfContentEditor](/pdf/ru/python-net/annotations/) +- [Управляйте вложениями PDF с помощью PdfContentEditor](/pdf/ru/python-net/attachments/) +- [Настройте действия документа с помощью PdfContentEditor](/pdf/ru/python-net/document-actions/) +- [Добавляйте графические аннотации с PdfContentEditor](/pdf/ru/python-net/drawing-annotations/) +- [Осуществляйте операции с изображениями с PdfContentEditor](/pdf/ru/python-net/image-operations/) +- [Обрабатывайте ссылки и навигацию с помощью PdfContentEditor](/pdf/ru/python-net/links-and-navigation/) +- [Добавляйте или управляйте мультимедийным контентом с помощью PdfContentEditor](/pdf/ru/python-net/multimedia/) +- [Управляйте PDF‑штампами с помощью PdfContentEditor](/pdf/ru/python-net/stamps-management/) +- [Заменяйте и обновляйте текст с помощью PdfContentEditor](/pdf/ru/python-net/text-operations/) +- [Изменяйте настройки просмотра с помощью PdfContentEditor](/pdf/ru/python-net/viewer-preferences/) diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md new file mode 100644 index 000000000..0f2353a10 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md @@ -0,0 +1,18 @@ +--- +title: Аннотации +linktitle: Аннотации +type: docs +weight: 10 +url: /python-net/annotations/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [Добавить текстовые аннотации](/pdf/ru/python-net/add-text-annotation/) +- [Добавить свободные текстовые аннотации](/pdf/ru/python-net/add-free-text-annotation/) +- [Добавить аннотации разметки](/pdf/ru/python-net/add-markup-annotation/) +- [Добавить всплывающие аннотации](/pdf/ru/python-net/add-popup-annotation/) +- [Добавить аннотацию в виде курсора](/pdf/ru/python-net/add-caret-annotation/) diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md new file mode 100644 index 000000000..1331c5b94 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md @@ -0,0 +1,59 @@ +--- +title: Добавить аннотации в виде курсора +linktitle: Добавить аннотации в виде курсора +type: docs +weight: 10 +url: /python-net/add-caret-annotation/ +description: В этом примере загружается существующий PDF, добавляется аннотация в виде курсора на первую страницу и сохраняется изменённый документ. Аннотация включает красный символ курсора и пояснительный текст комментария. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить аннотации в виде курсора в PDF с помощью Python +Abstract: В этом примере демонстрируется, как добавить аннотации в виде курсора в документ PDF с использованием Aspose.PDF for Python через Facades API. Пример показывает, как привязать файл PDF, определить расположение аннотации с помощью прямоугольников, настроить свойства курсора и сохранить обновлённый документ. +--- + +Аннотации в виде курсора обычно используются для указания вставок текста или редакционных комментариев в документе. С помощью PdfContentEditor можно программно добавлять аннотации в виде курсора, указывая номер страницы, границы аннотации, область выноски, символ, текст заметки и цвет. + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) объект. +1. Привяжите входной PDF. +1. Определите параметры аннотации Caret: + - Номер страницы, где будет добавлена аннотация + - Прямоугольник Caret (позиция аннотации) + - Прямоугольник выноски (текстовая область) + - Символ (например "P") + - Текст аннотации + - Цвет аннотации +1. Добавьте аннотацию в виде курсора. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_caret_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add caret annotation to page 1 + content_editor.create_caret( + 1, + apd.Rectangle(350, 400, 10, 10), + apd.Rectangle(300, 380, 115, 15), + "P", + "This is a caret annotation", + apd.Color.red, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md new file mode 100644 index 000000000..613be9c61 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md @@ -0,0 +1,48 @@ +--- +title: Добавить свободные текстовые аннотации +linktitle: Добавить свободные текстовые аннотации +type: docs +weight: 20 +url: /python-net/add-free-text-annotation/ +description: В этом примере загружается существующий PDF‑файл, добавляется свободная текстовая аннотация на первую страницу в заданном положении и сохраняется изменённый документ. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить свободную текстовую аннотацию в PDF с помощью Python +Abstract: В этом примере демонстрируется, как вставить свободную текстовую аннотацию в PDF‑документ с использованием Aspose.PDF for Python через Facades API. Показывается, как привязать PDF, определить размещение аннотации, добавить пользовательский текст и сохранить обновлённый документ. +--- + +Свободные текстовые аннотации позволяют размещать видимый текст непосредственно на странице PDF без необходимости всплывающих комментариев. С помощью PdfContentEditor можно указать прямоугольник аннотации, отображаемый текст и целевую страницу. + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) объект. +1. Привяжите входной PDF. +1. Определите позицию аннотации. +1. Добавьте аннотацию свободного текста. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_free_text_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add free text annotation to page 1 + content_editor.create_free_text( + apd.Rectangle(200, 480, 150, 25), "This is a free text annotation", 1 + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md new file mode 100644 index 000000000..edef5755b --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md @@ -0,0 +1,73 @@ +--- +title: Добавить аннотации разметки +linktitle: Добавить аннотации разметки +type: docs +weight: 30 +url: /python-net/add-markup-annotation/ +description: В этом примере привязывается входной PDF, добавляются четыре разных разметочных аннотации на первую страницу и сохраняется обновлённый документ. Каждая аннотация демонстрирует иной стиль разметки и цвет. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить выделения, подчёркивания, зачеркивания и волнистые аннотации разметки в PDF с помощью Python +Abstract: В этом примере демонстрируется, как добавить несколько разметочных аннотаций — выделение, подчёркивание, зачеркивание и волнистую — в документ PDF с использованием Aspose.PDF for Python via the Facades API. Пример показывает, как определить области аннотаций, указать типы разметки, применить цвета и сохранить изменённый документ. +--- + +Аннотации разметки используются для выделения или рецензирования текста в PDF. С помощью PdfContentEditor можно программно применять различные стили разметки, указывая область прямоугольника, текст комментария, тип разметки, номер страницы и цвет. + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) объект. +1. Привяжите входной PDF. +1. Определите прямоугольники аннотаций. +1. Добавьте разметку аннотаций. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_markup_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add markup annotation to page 1 + content_editor.create_markup( + apd.Rectangle(120, 440, 200, 20), + "This is a highlight annotation", + 0, + 1, + apd.Color.yellow, + ) + content_editor.create_markup( + apd.Rectangle(110, 542, 200, 20), + "This is a underline annotation", + 1, + 1, + apd.Color.yellow, + ) + content_editor.create_markup( + apd.Rectangle(120, 568, 200, 20), + "This is a strikeout annotation", + 2, + 1, + apd.Color.orange_red, + ) + content_editor.create_markup( + apd.Rectangle(110, 598, 200, 20), + "This is a squiggly annotation", + 3, + 1, + apd.Color.dark_blue, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md new file mode 100644 index 000000000..5f2c3b4c1 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md @@ -0,0 +1,51 @@ +--- +title: Добавить всплывающие аннотации +linktitle: Добавить всплывающие аннотации +type: docs +weight: 40 +url: /python-net/add-popup-annotation/ +description: В этом примере загружается PDF, добавляется всплывающая аннотация на первую страницу и сохраняется изменённый документ. Всплывающая аннотация установлена видимой по умолчанию и отображает указанный текст комментария. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить всплывающие аннотации в PDF с использованием Python +Abstract: В этом примере показано, как вставить всплывающую аннотацию в PDF‑документ, используя Aspose.PDF for Python via the Facades API. Объясняется, как определить область всплывающей аннотации, установить текст аннотации, управлять видимостью и сохранить обновлённый документ. +--- + +Всплывающие аннотации полезны для добавления комментариев, пояснений или интерактивных заметок в PDF‑файлах. С помощью [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете создавать всплывающие аннотации программно, указывая местоположение, содержание, видимость и номер страницы. + +1. Создайте объект PdfContentEditor. +1. Привяжите входной PDF. +1. Определите прямоугольник всплывающей аннотации. +1. Добавьте всплывающую аннотацию. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_popup_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add popup annotation to page 1 + content_editor.create_popup( + apd.Rectangle(220, 520, 180, 80), + "This is a popup annotation", + True, + 1, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-text-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-text-annotation/_index.md new file mode 100644 index 000000000..2fcda3ec1 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-text-annotation/_index.md @@ -0,0 +1,62 @@ +--- +title: Добавить текстовые аннотации +linktitle: Добавить текстовые аннотации +type: docs +weight: 50 +url: /python-net/add-text-annotation/ +description: Добавьте текстовые аннотации в PDF‑документ с помощью класса PdfContentEditor в Aspose.PDF for Python via .NET. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить текстовые аннотации в Python +Abstract: Узнайте, как добавить текстовые аннотации в PDF‑документ с помощью класса PdfContentEditor в Aspose.PDF for Python via .NET. Этот пример демонстрирует, как разместить текстовую аннотацию в определённом месте, задать её заголовок и содержимое, а также сохранить обновлённый PDF‑файл. +--- + +В этой статье показано, как добавить текстовую аннотацию в PDF‑документ с помощью [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) класса в Aspose.PDF. + +Текстовые аннотации позволяют прикреплять комментарии, заметки или дополнительную информацию к определённым частям страницы PDF. Такие аннотации могут отображаться в виде значков и расширяться пользователями при просмотре документа. + +В этом примере: + +- PDF‑документ загружается в PdfContentEditor. +- Текстовая аннотация добавляется в определённую позицию на странице. +- Аннотация включает заголовок, содержимое, тип значка и настройки видимости. +- Изменённый документ сохраняется в новый файл. + +1. Создайте объект PdfContentEditor. +1. Привяжите входной PDF Document. +1. Определите позицию аннотации. +1. Добавьте аннотацию Text. +1. Сохраните обновлённый PDF. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_text_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add text annotation to page 1 + content_editor.create_text( + apd.Rectangle(100, 400, 50, 50), + "Text Annotation", + "This is a text annotation", + True, + "Insert", + 1, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md new file mode 100644 index 000000000..603c4932c --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md @@ -0,0 +1,18 @@ +--- +title: Вложения +linktitle: Вложения +type: docs +weight: 20 +url: /python-net/attachments/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [Добавить вложение](/pdf/ru/python-net/add-attachment/) +- [Добавить вложение из пути](/pdf/ru/python-net/add-attachment-from-path/) +- [Добавить аннотацию вложения файла](/pdf/ru/python-net/add-file-attachment-annotation/) +- [Добавить аннотацию вложения файла из потока](/pdf/ru/python-net/add-file-attachment-annotation-from-stream/) +- [Удалить вложения](/pdf/ru/python-net/remove-attachments/) diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment-from-path/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment-from-path/_index.md new file mode 100644 index 000000000..828e0995a --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment-from-path/_index.md @@ -0,0 +1,48 @@ +--- +title: Добавить вложение из пути +linktitle: Добавить вложение из пути +type: docs +weight: 20 +url: /python-net/add-attachment-from-path/ +description: В этом примере связывается входной PDF, прикрепляется внешний файл с использованием его пути к файлу и сохраняется измененный PDF с встроенным вложением. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Прикрепление файлов к PDF с использованием перегрузки пути к файлу в Python +Abstract: В этом примере показано, как прикреплять внешние файлы к документу PDF с использованием перегрузки пути к файлу функции 'add_document_attachment()' в Aspose.PDF for Python via the Facades API. Это упрощает добавление вложений без ручного открытия файлового потока. +--- + +PDF может включать встроенные файлы, такие как документы, электронные таблицы или изображения, для справки или распространения. Перегрузка пути к файлу функции 'add_document_attachment()' позволяет добавлять вложения напрямую из пути к файлу, исключая необходимость открывать файл вручную. + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) объект. +1. Привяжите входной PDF. +1. Добавьте вложение, используя путь к файлу. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_attachment_from_path(infile, attachment_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add attachment using file-path overload + content_editor.add_document_attachment( + attachment_file, + "Attachment added using file path overload.", + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment/_index.md new file mode 100644 index 000000000..9ccd7d0ab --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment/_index.md @@ -0,0 +1,51 @@ +--- +title: Добавить вложение +linktitle: Добавить вложение +type: docs +weight: 10 +url: /python-net/add-attachment/ +description: В этом примере происходит привязка входного PDF, прикрепление внешнего файла к первой странице и сохранение изменённого PDF с встроенным вложением. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавление файловых вложений в PDF с использованием Python +Abstract: В этом примере показано, как прикреплять внешние файлы к документу PDF с помощью Aspose.PDF for Python via the Facades API. Он демонстрирует, как привязать PDF, добавить вложения с описаниями и сохранить обновлённый документ. +--- + +Файловые вложения в PDF позволяют включать дополнительные документы, изображения или другие ресурсы непосредственно в PDF. С [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете программно прикреплять файлы к конкретным страницам, задавать имя вложения и предоставлять описание. + +1. Создайте объект PdfContentEditor. +1. Привяжите входной PDF. +1. Откройте файл вложения. +1. Добавьте вложение в PDF. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_attachment(infile, attachment_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add attachment to page 1 + with open(attachment_file, "rb") as attachment_stream: + content_editor.add_document_attachment( + attachment_stream, + path.basename(attachment_file), + "This is a sample attachment for demonstration purposes.", + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md new file mode 100644 index 000000000..41aab0da8 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md @@ -0,0 +1,52 @@ +--- +title: Добавить аннотацию вложения файла +linktitle: Добавить аннотацию вложения файла +type: docs +weight: 30 +url: /python-net/add-file-attachment-annotation/ +description: В примере привязывается входной PDF, добавляется аннотация вложения файла на первую страницу с использованием пути к файлу и сохраняется обновлённый документ. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить аннотации вложения файлов в PDF с использованием Python +Abstract: В этом примере демонстрируется, как создать аннотацию вложения файла в PDF, используя путь к файлу с Aspose.PDF for Python via the Facades API. Показано, как определить расположение аннотации, установить текст описания, выбрать тип значка и сохранить изменённый документ. +--- + +Аннотации вложения файлов позволяют встраивать внешние файлы в виде интерактивных значков на страницу PDF. Используя перегрузку с путём к файлу, вы можете прикреплять файлы непосредственно с диска без необходимости вручную открывать потоки. Этот метод также позволяет настроить значок аннотации и предоставить описание для пользователей. + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) объект. +1. Привяжите входной PDF. +1. Определите прямоугольник аннотации. +1. Добавьте аннотацию вложения файла. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_file_attachment_annotation(infile, attachment_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Create file attachment annotation on page 1 + content_editor.create_file_attachment( + apd.Rectangle(100, 520, 20, 20), + "Attachment annotation contents", + attachment_file, + 1, + "PushPin", + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md new file mode 100644 index 000000000..f7251e290 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md @@ -0,0 +1,58 @@ +--- +title: Добавить аннотацию вложения файла из потока +linktitle: Добавить аннотацию вложения файла из потока +type: docs +weight: 40 +url: /python-net/add-file-attachment-annotation-from-stream/ +description: В примере загружается PDF, читается внешний файл в поток памяти, добавляется аннотация вложения файла на первую страницу и сохраняется изменённый документ. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить аннотации вложения файлов в PDF из потока на Python +Abstract: Этот пример демонстрирует, как создать аннотацию вложения файла в PDF, используя поток файла с Aspose.PDF for Python via the Facades API. Он показывает, как указать позицию аннотации, задать описание, включить значение непрозрачности и сохранить изменённый документ. +--- + +Аннотации вложения файлов позволяют встраивать файлы в виде интерактивных значков на странице PDF. При использовании потокового подхода вы можете динамически прикреплять файлы без привязки к физическому пути файла. Этот метод также поддерживает настройку внешнего вида аннотации, включая непрозрачность. + +1. Создайте объект PdfContentEditor. +1. Привяжите входной PDF. +1. Прочитайте файл вложения как поток. +1. Добавьте аннотацию вложения файла. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_file_attachment_annotation_from_stream(infile, attachment_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + with open(attachment_file, "rb") as source_stream: + attachment_stream = BytesIO(source_stream.read()) + + # Create file attachment annotation using stream+opacity overload + content_editor.create_file_attachment( + apd.Rectangle(130, 520, 20, 20), + "Attachment annotation from stream", + attachment_stream, + path.basename(attachment_file), + 1, + "Tag", + 0.75, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md new file mode 100644 index 000000000..ecf71b424 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md @@ -0,0 +1,45 @@ +--- +title: Удалить вложения +linktitle: Удалить вложения +type: docs +weight: 50 +url: /python-net/remove-attachments/ +description: В этом примере происходит привязка входного PDF, удаляются все вложения и сохраняется изменённый PDF без встроенных файлов. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Удалить все вложения из PDF с использованием Python +Abstract: В этом примере показано, как удалить все вложения файлов из PDF‑документа с использованием Aspose.PDF for Python via the Facades API. Он демонстрирует, как привязать PDF, удалить встроенные вложения и сохранить обновлённый документ. +--- + +PDF‑файлы могут содержать вложения, такие как документы, изображения или другие файлы. Существуют ситуации, когда необходимо очистить PDF от всех вложений в целях безопасности, конфиденциальности или распространения. Используя [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете программно удалить все встроенные вложения в документе. + +1. Создайте объект PdfContentEditor. +1. Привяжите входной PDF. +1. Удалите все вложения. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def remove_attachments(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Remove all attachments from document + content_editor.delete_attachments() + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md new file mode 100644 index 000000000..43c638722 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md @@ -0,0 +1,16 @@ +--- +title: Действия с документом +linktitle: Действия с документом +type: docs +weight: 40 +url: /python-net/document-actions/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [Добавить действие закладки](/pdf/ru/python-net/add-bookmark-action/) +- [Добавить действие Document](/pdf/ru/python-net/add-document-action/) +- [Удалить действие при открытии](/pdf/ru/python-net/remove-open-action/) \ No newline at end of file diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md new file mode 100644 index 000000000..17e6eb9fa --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md @@ -0,0 +1,53 @@ +--- +title: Добавить действие закладки +linktitle: Добавить действие закладки +type: docs +weight: 10 +url: /python-net/add-bookmark-action/ +description: В этом примере привязывается входной PDF, создаётся закладка с меткой "PdfContentEditor Bookmark", которая переходит к странице 1, и сохраняется обновлённый документ. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Создать закладку с действием навигации в PDF с помощью Python +Abstract: В этом примере демонстрируется, как добавить закладку с действием навигации в PDF‑документ с использованием Aspose.PDF for Python via the Facades API. Показано, как настроить текст закладки, её внешний вид и действие, которое перенаправляет пользователей на определённую страницу. +--- + +Закладки обеспечивают быстрый переход внутри PDF‑документов. Используя [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете программно создавать закладки и назначать действия, такие как переход к странице. Вы также можете настраивать внешний вид закладки, включая цвет и варианты стиля, такие как полужирный или курсив. + +1. Создайте объект PdfContentEditor. +1. Привяжите входной PDF. +1. Определите свойства закладки. +1. Назначьте действие закладки. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_bookmark_action(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add a bookmark action to navigate to page 1 + content_editor.create_bookmarks_action( + "PdfContentEditor Bookmark", + apd.Color.blue, + True, + False, + "", + "GoTo", + "1", + ) + # Save updated document + content_editor.save(outfile) +``` \ No newline at end of file diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md new file mode 100644 index 000000000..182c40cf1 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md @@ -0,0 +1,47 @@ +--- +title: Добавить действие Document +linktitle: Добавить действие Document +type: docs +weight: 20 +url: /python-net/add-document-action/ +description: В этом примере добавляется предупреждающее сообщение JavaScript, которое появляется при открытии PDF. Скрипт привязан к событию открытия документа и автоматически выполняется в поддерживаемых PDF‑просмотрщиках. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить действие Document Open JavaScript к PDF с использованием Python +Abstract: В этом примере демонстрируется, как добавить действие JavaScript уровня Document, которое срабатывает при открытии PDF. С использованием Aspose.PDF for Python via the Facades API пример показывает, как привязать Document, назначить действие события открытия и сохранить обновлённый PDF. +--- + +Действия на уровне документа позволяют определять поведение, которое автоматически выполняется при возникновении определенных событий, например, при открытии PDF-файла. С помощью [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) вы можете прикрепить к этим событиям код JavaScript. Это можно использовать для уведомлений, логики проверки или интерактивных рабочих процессов. + +1. Создайте объект PdfContentEditor. +1. Привяжите входной PDF. +1. Добавьте действие уровня документа. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_document_action(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add JavaScript action for document open event + content_editor.add_document_additional_action( + content_editor.DOCUMENT_OPEN, + "app.alert('Document opened with PdfContentEditor action');", + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md new file mode 100644 index 000000000..e66a2392a --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md @@ -0,0 +1,46 @@ +--- +title: Удалить действие при открытии +linktitle: Удалить действие при открытии +type: docs +weight: 30 +url: /python-net/remove-open-action/ +description: В этом примере загружается существующий PDF, удаляется действие при открытии и сохраняется очищенный документ. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Удалить действие открытия документа из PDF с использованием Python +Abstract: В этом примере демонстрируется, как удалить действие открытия документа из PDF с использованием Aspose.PDF for Python via the Facades API. Показано, как привязать PDF, очистить действие при открытии и сохранить обновлённый документ. +--- + +PDF‑документы могут содержать действия, которые автоматически выполняются при открытии файла, такие как JavaScript‑оповещения, команды навигации или другие поведения. В некоторых сценариях может потребоваться удалить эти действия по соображениям безопасности, соответствия требованиям или удобства пользователя. + +С помощью PdfContentEditor вы можете легко удалить действие открытия документа и обеспечить, чтобы PDF открывался без выполнения какого-либо автоматического поведения. + +1. Создайте объект PdfContentEditor. +1. Привяжите входной PDF. +1. Удалите действие открытия документа. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def remove_open_action(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Remove open action from the document + content_editor.remove_document_open_action() + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md new file mode 100644 index 000000000..597e75b16 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md @@ -0,0 +1,19 @@ +--- +title: Рисование аннотаций +linktitle: Рисование аннотаций +type: docs +weight: 50 +url: /python-net/drawing-annotations/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [Добавить аннотации линий](/pdf/ru/python-net/add-line-annotation/) +- [Добавить аннотации квадрата](/pdf/ru/python-net/add-square-annotation/) +- [Добавить аннотации круга](/pdf/ru/python-net/add-circle-annotation/) +- [Добавить аннотации полигон](/pdf/ru/python-net/add-polygon-annotation/) +- [Добавить аннотации полилиний](/pdf/ru/python-net/add-polyline-annotation/) +- [Добавить аннотации кривой](/pdf/ru/python-net/add-curve-annotation/) diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md new file mode 100644 index 000000000..942f44113 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md @@ -0,0 +1,50 @@ +--- +title: Добавить круговую аннотацию +linktitle: Добавить круговую аннотацию +type: docs +weight: 10 +url: /python-net/add-circle-annotation/ +description: В этом примере привязывается входной PDF, создаётся круговая аннотация на первой странице и сохраняется изменённый документ. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить круговую аннотацию в PDF с помощью PdfContentEditor на Python +Abstract: В этом примере демонстрируется, как добавить круговую аннотацию в PDF‑документ с использованием Aspose.PDF for Python через API фасадов. Показано, как определить границы аннотации, задать текст содержимого, настроить цвет и внешний вид, а также сохранить обновлённый документ. +--- + +Круговые аннотации полезны для выделения областей интереса в PDF‑документе. С помощью [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете создавать круглые формы, указывая прямоугольник, определяющий границы круга, а также текст аннотации, цвет, параметры заливки, номер страницы и ширину рамки. + +1. Создайте объект PdfContentEditor. +1. Привязать входной PDF. +1. Определить границы круга. +1. Добавить аннотацию круга. +1. Сохранить обновлённый Document. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_circle_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + # Create CircleAnnotation object + rect = apd.Rectangle(300, 300, 400, 400) + contents = "This is circle annotation" + content_editor.create_square_circle(rect, contents, apd.Color.blue, False, 1, 3) + + # Save output PDF file + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md new file mode 100644 index 000000000..560342354 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md @@ -0,0 +1,56 @@ +--- +title: Добавить аннотацию кривой +linktitle: Добавить аннотацию кривой +type: docs +weight: 20 +url: /python-net/add-curve-annotation/ +description: В этом примере привязывается входной PDF, рисуется пунктирная кривая на первой странице и сохраняется изменённый документ. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить аннотацию кривой в PDF с помощью PdfContentEditor на Python +Abstract: В этом примере демонстрируется, как добавить аннотацию кривой в PDF‑документ с использованием Aspose.PDF for Python через Facades API. Показано, как определить вершины кривой, стиль границы, границы аннотации, текстовое содержание и сохранить обновлённый документ. +--- + +Аннотации кривой используются для выделения нерегулярных путей или форм в PDF, обеспечивая визуальное акцентирование или маркировку важных областей. Используя [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете рисовать кривые, задавая последовательность вершин, стиль границы, видимость, прямоугольник аннотации и описательный текст. + +1. Создайте объект PdfContentEditor. +1. Привяжите onput PDF. +1. Настройте свойства Curve. +1. Нарисуйте аннотацию Curve. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_curve_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + line_info = pdf_facades.LineInfo() + line_info.border_style = 1 # 1 - Dashed + line_info.vertice_coordinate = [120, 520, 160, 560, 220, 540, 280, 580] + line_info.visibility = True + content_editor.draw_curve( + line_info, + 1, + apd.Rectangle(110, 510, 220, 100), + "This is curve annotation", + ) + + # Save output PDF file + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md new file mode 100644 index 000000000..36936036d --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md @@ -0,0 +1,63 @@ +--- +title: Добавить аннотацию линий +linktitle: Добавить аннотацию линий +type: docs +weight: 30 +url: /python-net/add-line-annotation/ +description: В этом примере привязывается входной PDF, рисуется красная аннотация с квадратными окончаниями линии и сохраняется изменённый PDF. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить аннотацию линий в PDF с помощью PdfContentEditor на Python +Abstract: В этом примере демонстрируется, как добавить аннотацию линий в PDF‑документ с использованием Aspose.PDF for Python через Facades API. Он объясняет, как определить начальную и конечную точки линии, границы прямоугольника, свойства отображения и сохранить обновлённый документ. +--- + +Аннотации линий полезны для акцентирования текста, выделения взаимосвязей или привлечения внимания к определённым областям в PDF. С [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете программно создавать аннотации линий, указывая начальные и конечные точки, ограничивающий прямоугольник, цвет, стиль границы и окончания линий. + +1. Создайте объект PdfContentEditor. +1. Привяжите входной PDF. +1. Определите свойства аннотации линии. +1. Добавьте аннотацию линии. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_line_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + # Create LineAnnotation object + rect = apd.Rectangle(100, 100, 200, 200) + contents = "This is line annotation" + content_editor.create_line( + rect, + contents, + 100, + 100, + 200, + 200, + 1, + 1, + apd.Color.red, + "Solid", + [3, 2], + ["Square"], + ) + + # Save output PDF file + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md new file mode 100644 index 000000000..325ea0536 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md @@ -0,0 +1,55 @@ +--- +title: Добавить аннотацию полигога +linktitle: Добавить аннотацию полигога +type: docs +weight: 40 +url: /python-net/add-polygon-annotation/ +description: В этом примере привязывается входной PDF, рисуется сплошной полигон на первой странице и сохраняется изменённый документ с аннотацией. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить аннотацию полигона в PDF с использованием PdfContentEditor в Python +Abstract: В этом примере демонстрируется, как добавить аннотацию полигона в PDF‑документ с использованием Aspose.PDF for Python через Facades API. Показано, как определить вершины полигона, стиль границы, границы аннотации, описательный текст и сохранить обновлённый документ. +--- + +Аннотации полигона используются для выделения неправильных областей или форм в PDF, обеспечивая визуальное акцентирование или маркировку конкретных регионов. Используя [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете создавать полигоны, указывая координаты вершин, стиль границы, номер страницы и прямоугольник аннотации. + +1. Создайте объект PdfContentEditor. +1. Привяжите входной PDF. +1. Настройте свойства Polygon. +1. Добавьте аннотацию Polygon. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_polygon_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + line_info = pdf_facades.LineInfo() + line_info.border_style = 0 # 0 - Solid + line_info.vertice_coordinate = [100, 200, 150, 260, 220, 220, 200, 160] + content_editor.create_polygon( + line_info, + 1, + apd.Rectangle(90, 150, 150, 120), + "This is polygon annotation", + ) + + # Save output PDF file + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md new file mode 100644 index 000000000..3e962db01 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md @@ -0,0 +1,55 @@ +--- +title: Добавить аннотацию полилиний +linktitle: Добавить аннотацию полилиний +type: docs +weight: 50 +url: /python-net/add-polyline-annotation/ +description: В примере привязывается входной PDF, создаётся сплошная полилиния на первой странице и сохраняется изменённый документ с аннотацией. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить аннотацию полилиний в PDF с помощью PdfContentEditor на Python +Abstract: Этот пример демонстрирует, как добавить аннотацию полилиний в документ PDF, используя Aspose.PDF for Python через API Facades. Он показывает, как определить последовательность вершин, стиль границы, прямоугольник аннотации, текст и сохранить обновлённый документ. +--- + +Аннотации полилиний позволяют выделять серию соединённых отрезков линий в PDF. Используя [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/)", вы можете нарисовать полилинию, указав координаты вершин, стиль границы, номер страницы и границы аннотации. Это полезно для визуального представления путей, тенденций или соединений в диаграммах и документах. + +1. Создайте объект PdfContentEditor. +1. Привяжите входной PDF. +1. Настройте свойства Polyline. +1. Добавьте аннотацию Polyline. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_polyline_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + line_info = pdf_facades.LineInfo() + line_info.border_style = 0 # 0 - Solid + line_info.vertice_coordinate = [120, 420, 180, 460, 230, 430, 290, 470] + content_editor.create_poly_line( + line_info, + 1, + apd.Rectangle(110, 410, 200, 90), + "This is polyline annotation", + ) + + # Save output PDF file + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md new file mode 100644 index 000000000..71baf6db2 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md @@ -0,0 +1,50 @@ +--- +title: Добавить аннотацию квадрата +linktitle: Добавить аннотацию квадрата +type: docs +weight: 60 +url: /python-net/add-square-annotation/ +description: В этом примере связывается входной PDF, добавляется заполненная синяя аннотация квадрата на первой странице и сохраняется изменённый документ. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить аннотацию квадрата в PDF с использованием PdfContentEditor в Python +Abstract: В этом примере демонстрируется, как добавить аннотацию квадрата в PDF‑документ, используя Aspose.PDF for Python via the Facades API. Показано, как определить прямоугольник аннотации, текстовое содержимое, цвет, параметры заливки и сохранить обновлённый документ. +--- + +Аннотации квадрата обычно используются для выделения интересующих областей, пометок важных разделов или предоставления визуальных подсказок в PDF‑документе. Используя [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете создавать аннотации квадрата, указывая ограничивающий прямоугольник, текст содержимого, цвет границы, параметр заливки, номер страницы и ширину границы. + +1. Создайте объект PdfContentEditor. +1. Привяжите входной PDF. +1. Определите квадратную аннотацию. +1. Добавьте квадратную аннотацию. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_square_annotation(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind input PDF file + content_editor.bind_pdf(infile) + + # Create SquareAnnotation object + rect = apd.Rectangle(100, 300, 200, 400) + contents = "This is square annotation" + content_editor.create_square_circle(rect, contents, apd.Color.blue, True, 1, 3) + + # Save output PDF file + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md new file mode 100644 index 000000000..bc8835577 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md @@ -0,0 +1,16 @@ +--- +title: Операции с изображениями +linktitle: Операции с изображениями +type: docs +weight: 60 +url: /python-net/image-operations/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [Заменить изображения в PDF](/pdf/ru/python-net/replace-image/) +- [Удалить изображения из PDF](/pdf/ru/python-net/delete-images/) +- [Удалить все изображения из PDF](/pdf/ru/python-net/delete-all-images/) \ No newline at end of file diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md new file mode 100644 index 000000000..7e847d8de --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md @@ -0,0 +1,45 @@ +--- +title: Удалить все изображения из PDF +linktitle: Удалить все изображения из PDF +type: docs +weight: 10 +url: /python-net/delete-all-images/ +description: Удалить все изображения из PDF‑документа с помощью Aspose.PDF for Python через Facades API. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Удалить все изображения из PDF с использованием PdfContentEditor в Python +Abstract: Этот пример демонстрирует, как удалить все изображения из PDF‑документа с помощью Aspose.PDF for Python через Facades API. Он показывает, как привязать PDF, удалить все встроенные изображения и сохранить обновлённый документ. +--- + +PDF‑документы часто содержат изображения для иллюстраций, брендинга или декора. Может возникнуть необходимость удалить все изображения из PDF, например, чтобы уменьшить размер файла, защитить конфиденциальные визуальные материалы или подготовить версию только с текстом. + +Используя [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете программно удалить все изображения из PDF, обеспечивая, что документ содержит только текстовое содержимое. В этом примере привязывается входной PDF, удаляются все изображения и сохраняется изменённый файл. + +1. Создайте объект PdfContentEditor. +1. Привяжите входной PDF. +1. Удалите все изображения. +1. Сохраните обновлённый Document. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def delete_all_image(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Delete all images from the document + content_editor.delete_image() + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md new file mode 100644 index 000000000..6f8f57046 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md @@ -0,0 +1,45 @@ +--- +title: Удалить изображения из PDF +linktitle: Удалить изображения из PDF +type: docs +weight: 20 +url: /python-net/delete-images/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Удалить определённые изображения со страницы PDF с помощью PdfContentEditor на Python +Abstract: Этот пример демонстрирует, как удалить конкретные изображения из PDF‑документа с использованием Aspose.PDF for Python через Facades API. Он показывает, как выбрать изображения на определённой странице и сохранить обновлённый документ. +--- + +Иногда вы можете захотеть удалить только определённые изображения из PDF, а не очищать все визуальные элементы. С [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете удалить выбранные изображения, указав номер страницы и индекс изображения. + +Этот фрагмент кода привязывает входной PDF, удаляет второе изображение на странице 1 и сохраняет изменённый PDF, оставляя остальные изображения нетронутыми. + +1. Создайте экземпляр PdfContentEditor. +1. Привяжите входной PDF‑документ. +1. Удалите определённые изображения с указанной страницы. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def delete_images(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Delete image on page 1 + content_editor.delete_image(1, [2]) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md new file mode 100644 index 000000000..950596469 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md @@ -0,0 +1,43 @@ +--- +title: Заменить изображения в PDF +linktitle: Заменить изображения в PDF +type: docs +weight: 30 +url: /python-net/replace-image/ +description: В этом примере привязывается входной PDF, заменяется первое изображение на странице 1 новым изображением и сохраняется измененный документ. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Заменить изображение в PDF с помощью PdfContentEditor в Python +Abstract: В этом примере демонстрируется, как заменить существующее изображение в PDF‑документе с использованием Aspose.PDF for Python через Facades API. Показано, как выбрать конкретное изображение на странице и заменить его новым изображением, а затем сохранить обновлённый PDF. +--- + +PDF‑файлы часто содержат изображения, которые могут потребоваться обновить или заменить, такие как логотипы, схемы или фотографии. С [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете заменить конкретное изображение на заданной странице, указав номер страницы, индекс изображения и путь к файлу нового изображения. + +1. Создайте экземпляр PdfContentEditor. +1. Привяжите входной PDF‑документ. +1. Замените конкретное изображение на указанной странице. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def replace_image(infile, image_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Replace image on page 1 + content_editor.replace_image(1, 1, image_file) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md new file mode 100644 index 000000000..3249148dc --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md @@ -0,0 +1,20 @@ +--- +title: Ссылки и навигация +linktitle: Ссылки и навигация +type: docs +weight: 70 +url: /python-net/links-and-navigation/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [Добавить веб‑ссылку](/pdf/ru/python-net/add-web-link/) +- [Добавить локальную ссылку](/pdf/ru/python-net/add-local-link/) +- [Добавить ссылку на PDF‑документ](/pdf/ru/python-net/add-pdf-document-link/) +- [Добавить JavaScript‑ссылку](/pdf/ru/python-net/add-javascript-link/) +- [Добавить ссылку на приложение](/pdf/ru/python-net/add-application-link/) +- [Добавить пользовательскую ссылку действия](/pdf/ru/python-net/add-custom-action-link/) +- [Извлечение ссылок](/pdf/ru/python-net/extract-links/) diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md new file mode 100644 index 000000000..a18e4d01d --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md @@ -0,0 +1,54 @@ +--- +title: Добавить ссылку на приложение +linktitle: Добавить ссылку на приложение +type: docs +weight: 10 +url: /python-net/add-application-link/ +description: В этом примере привязывается входной PDF, добавляется ссылка для запуска приложения на первой странице и сохраняется изменённый документ. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавьте ссылку для запуска приложения в PDF с помощью PdfContentEditor на Python +Abstract: В этом примере показано, как добавить ссылку для запуска приложения в PDF‑документ, используя Aspose.PDF for Python через API Facades. Демонстрируется создание области, по которой можно щёлкнуть, чтобы открыть указанное приложение, и сохранение обновлённого PDF. +--- + +PDF может включать интерактивные элементы, такие как ссылки, которые запускают внешние приложения. Используя [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете определить прямоугольную область на странице, которая при щелчке открывает конкретный исполняемый файл. + +1. Создайте экземпляр PdfContentEditor. +1. Привяжите входной PDF‑документ. +1. Определите прямоугольную область для кликабельной ссылки. +1. Укажите путь к приложению, которое нужно запустить. +1. Установите цвет ссылки. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf.facades as pdf_facades +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as apd +import aspose.pdf as ap + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_application_link(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add application launch link + content_editor.create_application_link( + apd.Rectangle(180, 530, 260, 20), + "notepad.exe", + 1, + apd.Color.purple, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md new file mode 100644 index 000000000..f115f9aea --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md @@ -0,0 +1,55 @@ +--- +title: Добавить пользовательскую ссылку действия +linktitle: Добавить пользовательскую ссылку действия +type: docs +weight: 20 +url: /python-net/add-custom-action-link/ +description: В этом примере привязывается входной PDF, добавляется пользовательская ссылка действия на первой странице и сохраняется изменённый документ. Для простоты используется пустой список действий, но в реальных реализациях могут быть включены фактические действия. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить пользовательскую ссылку действия в PDF с использованием PdfContentEditor на Python +Abstract: Этот пример демонстрирует, как добавить пользовательскую ссылку действия в документ PDF с использованием Aspose.PDF for Python via the Facades API. Показано, как создать область, по которой можно кликнуть, на странице, назначить пользовательское действие и сохранить обновлённый документ. +--- + +Пользовательские ссылки действия позволяют определять интерактивные области в PDF, которые могут запускать определённые действия при щелчке, такие как выполнение скриптов, навигация по страницам или выполнение команд, специфичных для приложения. Используя [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете создать пользовательскую ссылку действия, указав страницу, прямоугольник, цвет и действия. + +1. Создайте экземпляр PdfContentEditor. +1. Привяжите входной PDF‑документ. +1. Определите прямоугольник для кликабельной ссылки. +1. Укажите номер страницы и цвет ссылки. +1. Назначьте пользовательские действия (пусто в этом примере). +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf.facades as pdf_facades +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as apd +import aspose.pdf as ap + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_custom_action_link(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add custom action link. Empty action list keeps the sample runnable + # without requiring additional enum lookups. + content_editor.create_custom_action_link( + apd.Rectangle(200, 500, 260, 20), + 1, + apd.Color.dark_red, + [], + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md new file mode 100644 index 000000000..f2f56df87 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md @@ -0,0 +1,54 @@ +--- +title: Добавить JavaScript‑ссылку +linktitle: Добавить JavaScript‑ссылку +type: docs +weight: 30 +url: /python-net/add-javascript-link/ +description: В этом примере привязывается входной PDF, добавляется JavaScript‑ссылка, которая вызывает предупреждение при щелчке, и сохраняется изменённый документ. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить JavaScript‑ссылку в PDF с помощью PdfContentEditor на Python +Abstract: Этот пример демонстрирует, как добавить JavaScript‑ссылку в PDF‑документ с использованием Aspose.PDF for Python через API фасадов. Он показывает, как создать кликабельную область, которая выполняет JavaScript‑код при щелчке, и сохранить обновлённый PDF. +--- + +JavaScript‑ссылки в PDF позволяют реализовать интерактивный функционал, такой как отображение предупреждений, выполнение вычислений или динамическое изменение содержимого документа. Используя [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете определить кликабельный прямоугольник на странице и связать его с пользовательским JavaScript‑кодом. + +1. Создайте экземпляр PdfContentEditor. +1. Привяжите входной PDF‑документ. +1. Определите прямоугольник для кликабельной JavaScript‑ссылки. +1. Укажите номер страницы и цвет ссылки. +1. Назначьте JavaScript‑код, который будет выполнен при клике. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf.facades as pdf_facades +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as apd +import aspose.pdf as ap + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_javascript_link(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add JavaScript link action + content_editor.create_java_script_link( + "app.alert('PdfContentEditor JavaScript link');", + apd.Rectangle(160, 560, 260, 20), + 1, + apd.Color.orange, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md new file mode 100644 index 000000000..2ffb10280 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md @@ -0,0 +1,54 @@ +--- +title: Добавить локальную ссылку +linktitle: Добавить локальную ссылку +type: docs +weight: 40 +url: /python-net/add-local-link/ +description: В этом примере привязывается входной PDF, добавляется локальная ссылка красного цвета на странице 1 и сохраняется изменённый документ. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить локальную ссылку в PDF с помощью PdfContentEditor на Python +Abstract: В этом примере демонстрируется, как добавить локальную ссылку в PDF‑документ с использованием Aspose.PDF for Python через Facades API. Показано, как создать щелкаемую область, которая переходит на другую страницу внутри того же PDF, и сохранить обновлённый документ. +--- + +Локальные ссылки в PDF позволяют быстро перемещаться между страницами в рамках одного документа. С помощью [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), можно определить щелкаемый прямоугольник, который связывает одну страницу с другой, улучшая удобство использования и навигацию по документу. + +1. Создайте экземпляр PdfContentEditor. +1. Привяжите входной PDF‑документ. +1. Определите прямоугольник для кликабельной локальной ссылки. +1. Укажите исходную страницу и страницу назначения. +1. Установите цвет ссылки. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf.facades as pdf_facades +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as apd +import aspose.pdf as ap + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_local_link(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add a local link on page 1 to destination page 1 + content_editor.create_local_link( + apd.Rectangle(120, 620, 220, 20), + 1, + 1, + apd.Color.red, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md new file mode 100644 index 000000000..d358fd6ca --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md @@ -0,0 +1,55 @@ +--- +title: Добавить ссылку на PDF‑документ +linktitle: Добавить ссылку на PDF‑документ +type: docs +weight: 50 +url: /python-net/add-pdf-document-link/ +description: В этом примере привязывается входной PDF, добавляется ссылка зелёного цвета на страницу в другом PDF и сохраняется изменённый документ. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить ссылку на PDF‑документ с помощью PdfContentEditor в Python +Abstract: В этом примере демонстрируется, как добавить ссылку на другой PDF‑документ с использованием Aspose.PDF for Python через API Facades. Показано, как создать кликабельную область, открывающую другой PDF, и сохранить обновлённый документ. +--- + +Ссылки в PDF‑документах позволяют пользователям беспрепятственно перемещаться от одного PDF к другому. С помощью [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете определить кликабельный прямоугольник, который ссылается на страницу в другом PDF‑файле, делая ваши документы интерактивными и связанными. + +1. Создайте экземпляр PdfContentEditor. +1. Привяжите входной PDF‑документ. +1. Определите прямоугольник для кликабельной ссылки. +1. Укажите связанный PDF‑файл, исходную страницу и страницу назначения. +1. Установите цвет ссылки. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf.facades as pdf_facades +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as apd +import aspose.pdf as ap + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_pdf_document_link(infile, linked_pdf, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add link to another PDF document + content_editor.create_pdf_document_link( + apd.Rectangle(140, 590, 240, 20), + linked_pdf, + 1, + 1, + apd.Color.green, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md new file mode 100644 index 000000000..c38764f29 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md @@ -0,0 +1,53 @@ +--- +title: Добавить веб‑ссылку +linktitle: Добавить веб‑ссылку +type: docs +weight: 60 +url: /python-net/add-web-link/ +description: В этом примере привязывается входной PDF, добавляется синяя аннотация веб‑ссылки на странице 1, указывающая на страницу продукта Aspose Python PDF, и сохраняется изменённый документ. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить веб‑ссылку в PDF с помощью PdfContentEditor на Python +Abstract: В этом примере демонстрируется, как добавить веб‑ссылку в PDF‑документ с использованием Aspose.PDF for Python через API Facades. Показано, как создать кликабельную область на странице, которая открывает указанный URL в веб‑браузере, и сохранить обновлённый документ. +--- + +Веб‑ссылки в PDF позволяют пользователям переходить напрямую к онлайн‑ресурсам, веб‑сайтам или документации. С помощью [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете определить прямоугольную область на странице PDF, которая при щелчке открывает URL в браузере по умолчанию. + +1. Создайте экземпляр PdfContentEditor. +1. Привяжите входной PDF‑документ. +1. Определите прямоугольник для кликабельной веб‑ссылки. +1. Укажите URL, номер страницы и цвет ссылки. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf.facades as pdf_facades +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as apd +import aspose.pdf as ap + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_web_link(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add a web link annotation to page 1 + content_editor.create_web_link( + apd.Rectangle(100, 650, 200, 20), + "https://products.aspose.com/pdf/python-net/", + 1, + apd.Color.blue, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md new file mode 100644 index 000000000..3d3fc6ea6 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md @@ -0,0 +1,61 @@ +--- +title: Извлечение ссылок +linktitle: Извлечение ссылок +type: docs +weight: 70 +url: /python-net/extract-links/ +description: В этом примере привязывается входной PDF, извлекаются все ссылки и выводятся их координаты и URI (если доступны). +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Извлечение ссылок из PDF с помощью PdfContentEditor в Python +Abstract: Этот пример демонстрирует, как извлечь все ссылки из PDF‑документа с использованием Aspose.PDF for Python via the Facades API. Он показывает, как идентифицировать и получить веб‑ссылки или другие интерактивные ссылки, встроенные в PDF. +--- + +PDF часто содержат интерактивные элементы, такие как веб‑ссылки, ссылки на документы и пользовательские действия. Используя [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете программно извлекать все аннотации ссылок из PDF. Это позволяет проверять или обрабатывать ссылки, например, для валидации URL‑адресов или анализа схем навигации в документе. + +1. Создайте экземпляр PdfContentEditor. +1. Привяжите входной PDF‑документ. +1. Извлеките все ссылки, используя 'extract_link()'. +1. Переберите извлечённые ссылки. +1. Проверьте, является ли ссылка LinkAnnotation и является ли её действие GoToURIAction. +1. Выведите координаты прямоугольника и URI. +1. Отобразите сообщение, если ссылки не найдены. + +```python +import aspose.pdf.facades as pdf_facades +from aspose.pycore import cast, is_assignable +import aspose.pydrawing as apd +import aspose.pdf as ap + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def extract_links(infile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Extract links from the document + links = content_editor.extract_link() + + count = 0 + for link in links: + count += 1 + print(f"Link {count}: {link.rect}") + if is_assignable(link, ap.annotations.LinkAnnotation): + annotation = cast(ap.annotations.LinkAnnotation, link) + if is_assignable(annotation.action, ap.annotations.GoToURIAction): + action = cast(ap.annotations.GoToURIAction, annotation.action) + print(f" URI: {action.uri}") + + if count == 0: + print("No links found") +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md new file mode 100644 index 000000000..4c43a6588 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md @@ -0,0 +1,15 @@ +--- +title: Мультимедиа +linktitle: Мультимедиа +type: docs +weight: 80 +url: /python-net/multimedia/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [Добавить аннотацию с фильмом](/pdf/ru/python-net/add-movie-annotation/) +- [Добавить звуковую аннотацию](/pdf/ru/python-net/add-sound-annotation/) diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/add-movie-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/add-movie-annotation/_index.md new file mode 100644 index 000000000..0b862da49 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/add-movie-annotation/_index.md @@ -0,0 +1,46 @@ +--- +title: Добавить аннотацию с фильмом +linktitle: Добавить аннотацию с фильмом +type: docs +weight: 10 +url: /python-net/add-movie-annotation/ +description: В этом примере привязывается входной PDF, добавляется аннотация с фильмом на странице 1 и сохраняется обновлённый PDF. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить аннотацию с фильмом в PDF с использованием PdfContentEditor на Python +Abstract: В этом примере демонстрируется, как встроить фильм (видео) в документ PDF с использованием Aspose.PDF for Python via the Facades API. Показано, как добавить кликабельную аннотацию, которая воспроизводит видео непосредственно внутри PDF. +--- + +Аннотации с фильмом в PDF позволяют внедрять мультимедийный контент, такой как видео, в ваши документы. С помощью [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете определить прямоугольник на странице, где будет отображаться видео. При клике видео может воспроизводиться непосредственно из PDF, делая ваши документы более интерактивными и привлекательными. + +1. Создайте экземпляр PdfContentEditor. +1. Привяжите входной PDF‑документ. +1. Определите прямоугольник для аннотации фильма. +1. Укажите видеофайл для встраивания. +1. Назначьте номер страницы для аннотации. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_movie_annotation(infile, movie_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add movie annotation to page 1 + content_editor.create_movie(apd.Rectangle(80, 500, 220, 120), movie_file, 1) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/add-sound-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/add-sound-annotation/_index.md new file mode 100644 index 000000000..567961aa1 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/add-sound-annotation/_index.md @@ -0,0 +1,47 @@ +--- +title: Добавить звуковую аннотацию +linktitle: Добавить звуковую аннотацию +type: docs +weight: 20 +url: /python-net/add-sound-annotation/ +description: В этом примере привязывается входной PDF, добавляется звуковая аннотация на странице 1 и сохраняется изменённый PDF. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить звуковую аннотацию в PDF с помощью PdfContentEditor в Python +Abstract: В этом примере показывается, как встроить аудио в документ PDF с использованием Aspose.PDF for Python через API Facades. Показано, как добавить кликабельную звуковую аннотацию, которая воспроизводит аудиофайл непосредственно в PDF. +--- + +Звуковые аннотации в PDF позволяют добавлять аудиоконтент, такой как голосовые заметки, музыка или звуковые эффекты, в ваши документы. Используя [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете определить небольшой кликабельный прямоугольник на странице, который воспроизводит указанный аудиофайл при активации. + +1. Создайте экземпляр PdfContentEditor. +1. Привяжите входной PDF‑документ. +1. Определите прямоугольник для звуковой аннотации. +1. Укажите аудиофайл, имя аннотации, номер страницы и частоту дискретизации. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_sound_annotation(infile, sound_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Add sound annotation to page 1 + content_editor.create_sound( + apd.Rectangle(80, 450, 30, 30), sound_file, "Speaker", 1, "8000" + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md new file mode 100644 index 000000000..375328f4c --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md @@ -0,0 +1,23 @@ +--- +title: Управление штампами +linktitle: Управление штампами +type: docs +weight: 90 +url: /python-net/stamps-management/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [Добавить штамп](/pdf/ru/python-net/add-rubber-stamp/) +- [Удалить штамп по индексу](/pdf/ru/python-net/delete-stamp-by-index/) +- [Управление штампом по идентификатору](/pdf/ru/python-net/manage-stamp-by-id/) +- [Удалить штамп по ID](/pdf/ru/python-net/delete-stamp-by-ids-examples/) +- [Переместить штамп по индексу](/pdf/ru/python-net/move-stamp-by-index/) +- [Переместить штамп по ID](/pdf/ru/python-net/move-stamp-by-id-example/) +- [Создать резиновый штамп с файлом внешнего вида](/pdf/ru/python-net/create-rubber-stamp-with-appearance-file/) +- [Создать резиновую печать с потоком отображения](/pdf/ru/python-net/create-rubber-stamp-with-appearance-stream/) +- [Удалить штампы глобально](/pdf/ru/python-net/delete-stamps-globally/) +- [Список штампов](/pdf/ru/python-net/list-stamps/) diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md new file mode 100644 index 000000000..0bb547d38 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md @@ -0,0 +1,53 @@ +--- +title: Добавить штамп +linktitle: Добавить штамп +type: docs +weight: 10 +url: /python-net/add-rubber-stamp/ +description: В этом примере привязывает входной PDF, добавляет зелёный “Approved” штамп на первые четыре страницы и сохраняет изменённый документ. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить аннотацию штампа к PDF с использованием PdfContentEditor в Python +Abstract: В этом примере демонстрируется, как добавить аннотацию штампа к PDF‑документу с использованием Aspose.PDF for Python via the Facades API. Штампы позволяют визуально помечать страницы одобрениями, отзывами или пользовательскими метками. +--- + +Аннотации штампов часто используются в PDF для указания одобрения, статуса обзора или других заметок. Используя [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете определить прямоугольник для штампа, установить его текст и комментарии, выбрать цвет и применить его к нескольким страницам документа. + +1. Создайте экземпляр PdfContentEditor. +1. Привяжите входной PDF‑документ. +1. Пройдите по страницам 1–4. +1. Добавьте аннотацию штампа с пользовательским текстом, комментариями и цветом. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def add_rubber_stamp(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + for i in range(1, 5): + content_editor.create_rubber_stamp( + i, + apd.Rectangle(120, 450, 180, 60), + "Approved", + "Approved by reviewer", + apd.Color.green, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md new file mode 100644 index 000000000..cc4a2da20 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md @@ -0,0 +1,53 @@ +--- +title: Создать резиновый штамп с файлом внешнего вида +linktitle: Создать резиновый штамп с файлом внешнего вида +type: docs +weight: 20 +url: /python-net/create-rubber-stamp-with-appearance-file/ +description: В этом примере привязывается входной PDF, создаётся резиновый штамп на странице 1 с использованием файлового изображения в качестве внешнего вида штампа, и сохраняется обновлённый PDF. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Создать резиновый штамп с пользовательским внешним видом в PDF с использованием PdfContentEditor +Abstract: В этом примере демонстрируется, как добавить аннотацию резинового штампа с пользовательским внешним видом (изображение) в документ PDF, используя Aspose.PDF for Python via the Facades API. Пользовательские штампы позволяют включать логотипы, подписи или фирменные визуальные элементы в качестве части штампа. +--- + +Аннотации резинового штампа можно настраивать не только с помощью текста, но и используя файл изображения в качестве их внешнего вида. Такой подход полезен для добавления логотипов компании, подписных штампов или любого визуального индикатора на страницы вашего PDF. + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) экземпляр. +1. Привяжите входной PDF‑документ. +1. Определите прямоугольник для печати. +1. Используйте пользовательский файл изображения, чтобы определить внешний вид резиновой печати. +1. Установите текст и цвет печати. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def create_rubber_stamp_with_appearance_file(infile, image_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Create rubber stamp using appearance_file overload (image path) + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(100, 400, 200, 60), + "Stamp with custom appearance", + apd.Color.dark_green, + image_file, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md new file mode 100644 index 000000000..d60e92670 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md @@ -0,0 +1,53 @@ +--- +title: Создать резиновую печать с потоком отображения +linktitle: Создать резиновую печать с потоком отображения +type: docs +weight: 30 +url: /python-net/create-rubber-stamp-with-appearance-stream/ +description: В этом примере загружается PDF, на странице 1 создаётся резиновая печать, использующая файл изображения для её отображения, и сохраняется изменённый документ. ✨ +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Создать резиновую печать с пользовательским изображением в виде отображения с использованием PdfContentEditor в Python +Abstract: В этом примере показано, как создать аннотацию резиновой печати с пользовательским изображением в PDF, используя Aspose.PDF for Python via the Facades API. Этот подход позволяет применять фирменные или визуально насыщенные печати, такие как логотипы, печати или подписи. +--- + +Аннотации резиновых печатей можно настроить с использованием внешнего файла изображения. Вместо того чтобы полагаться только на текстовые печати, вы можете задать визуальное отображение (например, логотип компании или значок одобрения) и разместить его на странице. + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) экземпляр. +1. Привяжите входной PDF‑документ. +1. Определите прямоугольник для размещения печати. +1. Используйте файл изображения в качестве внешнего вида штампа. +1. Примените настройки текста и цвета. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def create_rubber_stamp_with_appearance_file(infile, image_file, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Create rubber stamp using appearance_file overload (image path) + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(100, 400, 200, 60), + "Stamp with custom appearance", + apd.Color.dark_green, + image_file, + ) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md new file mode 100644 index 000000000..08392222a --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md @@ -0,0 +1,69 @@ +--- +title: Удалить штамп по ID +linktitle: Удалить штамп по ID +type: docs +weight: 85 +url: /python-net/delete-stamp-by-ids-examples/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Удалить резиновые штампы по одному или нескольким ID в PDF с использованием PdfContentEditor +Abstract: Этот пример демонстрирует, как удалить аннотации резиновых штампов из PDF на основе их уникальных ID с использованием Aspose.PDF for Python via the Facades API. Он охватывает как удаление по одному ID, так и удаление по нескольким ID. +--- + +При работе с PDF, содержащими несколько штампов, часто необходимо удалить конкретные штампы, не затрагивая остальные. С удалением на основе ID вы можете точно контролировать, какие штампы удалить: + +- 'delete_stamp_by_id(stamp_id, page_number)' – удаляет один штамп по его ID на определённой странице +- 'delete_stamp_by_ids(page_number, stamp_ids)' – удаляет несколько штампов по их ID на указанной странице + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) экземпляр. +1. Привяжите входной PDF‑документ. +1. Добавьте две резиновые печати с разными идентификаторами. +1. Удаляйте печати, используя как методы удаления по одному идентификатору, так и методы удаления по нескольким идентификаторам. +1. Сохраните обновлённый PDF. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def delete_stamp_by_ids_examples(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + # Create two stamps on page 1 so they can be deleted by ID + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(120, 320, 180, 60), + "Draft", + "Delete by single ID", + apd.Color.orange, + ) + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(120, 250, 180, 60), + "Draft", + "Delete by multiple IDs", + apd.Color.orange, + ) + + # Delete by single ID overload and by IDs overload + content_editor.delete_stamp_by_id(1, 1) + content_editor.delete_stamp_by_ids(1, [2]) + + # Save updated document + content_editor.save(outfile) +``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md new file mode 100644 index 000000000..96abde65c --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md @@ -0,0 +1,64 @@ +--- +title: Переместить штамп по индексу +linktitle: Переместить штамп по индексу +type: docs +weight: 50 +url: /python-net/move-stamp-by-index/ +description: В этом примере создаются два резиновых штампа на странице 2. После этого штамп можно переместить, указав его индекс и новые координаты. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Переместить резиновый штамп по индексу в PDF с использованием PdfContentEditor в Python +Abstract: В этом примере показывается, как изменить позицию аннотации резинового штампа в PDF, используя её индекс с Aspose.PDF for Python через Facades API. Он демонстрирует, как добавить несколько штампов, а затем переместить один из них, опираясь на их порядок на странице. +--- + +Когда на странице присутствует несколько резиновых штампов, вы можете переместить конкретный, указав его индекс. Метод move_stamp() позволяет изменять позицию аннотаций согласно их последовательности, что полезно, если вы не отслеживаете идентификаторы штампов, а знаете их порядок. + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) экземпляр. +1. Привяжите входной PDF‑документ. +1. Добавьте две аннотации резинового штампа на одной странице. +1. Продемонстрируйте, как переместить штамп, используя его индекс. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def move_stamp_by_index(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + content_editor.create_rubber_stamp( + 2, + apd.Rectangle(200, 380, 180, 60), + "Draft", + "Draft stamp for ID-based operations", + apd.Color.orange, + ) + + content_editor.create_rubber_stamp( + 2, + apd.Rectangle(200, 480, 180, 60), + "Draft", + "Draft stamp for ID-based operations", + apd.Color.orange, + ) + content_editor.save(outfile) + + # Move first stamp on page 1 by index + # content_editor.move_stamp(1, 1, 10, 10) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md new file mode 100644 index 000000000..bf05e8be6 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md @@ -0,0 +1,60 @@ +--- +title: Удалить штампы глобально +linktitle: Удалить штампы глобально +type: docs +weight: 60 +url: /python-net/delete-stamps-globally/ +description: Этот пример демонстрирует, как удалить аннотации «резиновый штамп» глобально на всех страницах PDF с использованием Aspose.PDF for Python via the Facades API. Он показывает, как удалять штампы по идентификатору без указания отдельных страниц. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Глобальное удаление резиновых штампов в PDF с использованием PdfContentEditor в Python +Abstract: Этот пример демонстрирует, как удалить аннотации «резиновый штамп» глобально на всех страницах PDF с использованием Aspose.PDF for Python via the Facades API. Он показывает, как удалять штампы по идентификатору без указания отдельных страниц. +--- + +При работе с несколькими страницами может потребоваться удалить определённые штампы по всему документу. Методы ‘delete_stamp_by_id()’ и ‘delete_stamp_by_ids()’ позволяют удалять штампы глобально по их идентификаторам, устраняя необходимость проходить каждую страницу вручную. + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) экземпляр. +1. Привяжите входной PDF‑документ. +1. Добавьте резиновые штампы на несколько страниц. +1. Глобально удалять штампы, используя их идентификаторы. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def delete_stamps_globally(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + # Add stamps across multiple pages so global deletion is meaningful + for page in range(1, 5): + content_editor.create_rubber_stamp( + page, + apd.Rectangle(120, 500, 180, 60), + "Draft", + "Stamp for global deletion", + apd.Color.gray, + ) + + # delete_stamp_by_id without page number removes stamp ID from all pages + content_editor.delete_stamp_by_id(1) + # delete_stamp_by_ids without page number removes a list of IDs from all pages + content_editor.delete_stamp_by_ids([2, 3]) + + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md new file mode 100644 index 000000000..f31c177a6 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md @@ -0,0 +1,53 @@ +--- +title: Список штампов +linktitle: Список штампов +type: docs +weight: 70 +url: /python-net/list-stamps/ +description: Этот пример загружает PDF, извлекает все штампы со страницы 1, выводит их и отображает сообщение, если штампы не найдены. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Список аннотаций резиновых штампов в PDF с использованием PdfContentEditor в Python +Abstract: Этот пример демонстрирует, как извлечь и перечислить аннотации резиновых штампов из PDF‑документа с использованием Aspose.PDF for Python via the Facades API. Он показывает, как получить доступ к штампам на определенной странице и отобразить их детали. +--- + +При работе с аннотированными PDF вам может потребоваться проверить существующие резиновые штампы перед их изменением или удалением. Метод 'get_stamps()' позволяет получить все штампы, размещённые на конкретной странице. Затем вы можете пройтись по результатам и обработать их программно. + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) экземпляр. +1. Привяжите входной PDF‑документ. +1. Извлеките все штампы со страницы 1. +1. Переберите коллекцию штампов. +1. Выведите каждый штамп. +1. Отобразите сообщение, если штампы отсутствуют. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def list_stamps(infile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # List all stamps on page 1 + stamps = content_editor.get_stamps(1) + + count = 0 + for stamp in stamps: + count += 1 + print(f"Stamp {count}: {stamp}") + + if count == 0: + print("No stamps found") +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md new file mode 100644 index 000000000..53ba20aa0 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md @@ -0,0 +1,71 @@ +--- +title: Управление штампом по идентификатору +linktitle: Управление штампом по идентификатору +type: docs +weight: 95 +url: /python-net/manage-stamp-by-id/ +description: Как манипулировать аннотациями резиновых штампов в PDF по их уникальным ID с использованием Aspose.PDF for Python +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Управление резиновыми штампами по ID в PDF с помощью PdfContentEditor на Python +Abstract: Этот пример демонстрирует, как манипулировать аннотациями резиновых штампов в PDF по их уникальным ID с использованием Aspose.PDF for Python через Facades API. Вы можете скрывать или показывать конкретные штампы на определённых страницах, не затрагивая другие штампы. +--- + +В PDF с несколькими резиновыми штампами может быть полезно управлять отдельными штампами на основе их ID. Методы ‘hide_stamp_by_id()’ и ‘show_stamp_by_id()’ позволяют избирательно контролировать видимость. Этот пример показывает, как: + +- Добавить несколько штампов с уникальными ID +- Скрыть печать на определённой странице +- Показать печать на другой странице + +Используя операции на основе ID, вы избегаете отслеживания печатей по позиции страницы или другим атрибутам. + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) экземпляр. +1. Привяжите входной PDF‑документ. +1. Добавьте печати с конкретными идентификаторами. +1. Скрывайте и показывайте печати в зависимости от их идентификаторов и номеров страниц. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def manage_stamp_by_id(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(200, 380, 180, 60), + "Draft", + "Draft stamp for ID-based operations", + apd.Color.orange, + ) + + content_editor.create_rubber_stamp( + 2, + apd.Rectangle(200, 480, 180, 60), + "Draft", + "Draft stamp for ID-based operations", + apd.Color.orange, + ) + + # Apply ID-based stamp operations + content_editor.hide_stamp_by_id(1, 1) + content_editor.show_stamp_by_id(1, 2) + + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md new file mode 100644 index 000000000..7184443fa --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md @@ -0,0 +1,56 @@ +--- +title: Переместить штамп по ID +linktitle: Переместить штамп по ID +type: docs +weight: 80 +url: /python-net/move-stamp-by-id-example/ +description: В этом примере резиновая печать добавляется на страницу 1, а затем перемещается в новое положение с помощью её ID перед сохранением обновленного документа. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Переместить резиновую печать по ID в PDF с использованием PdfContentEditor на Python +Abstract: Этот пример демонстрирует, как изменить позицию существующей аннотации резиновой печати в PDF с помощью Aspose.PDF for Python через Facades API. Показано, как создать печать, а затем переместить её программно, используя её ID. +--- + +После добавления аннотации резиновой печати в PDF может понадобиться скорректировать её позицию. Метод 'move_stamp_by_id()' позволяет переместить конкретную печать, указав её уникальный идентификатор, что обеспечивает точный контроль над расположением без необходимости отслеживать её индекс или другие атрибуты. + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) экземпляр. +1. Привяжите входной PDF‑документ. +1. Добавьте аннотацию резиновой печати. +1. Переместите штамп, используя его ID. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def move_stamp_by_id_example(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + content_editor.create_rubber_stamp( + 1, + apd.Rectangle(300, 420, 180, 60), + "Approved", + "Move this stamp by ID", + apd.Color.green, + ) + + # Move stamp by ID overload + content_editor.move_stamp_by_id(1, 1, 240, 360) + + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md new file mode 100644 index 000000000..500429f6d --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md @@ -0,0 +1,71 @@ +--- +title: Переместить штамп по индексу +linktitle: Переместить штамп по индексу +type: docs +weight: 90 +url: /python-net/move-stamp-by-index/ +description: Как переместить аннотации резиновых печатей в PDF, используя их индекс на странице с Aspose.PDF for Python +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Переместить резиновые печати в PDF, используя позиционирование по индексу +Abstract: Этот пример демонстрирует, как переместить аннотации резиновых печатей в PDF, используя их индекс на странице с Aspose.PDF for Python через Facades API. Он подчеркивает создание нескольких печатей и их подготовку к операциям перемещения. +--- + +При редактировании PDF может потребоваться скорректировать положение существующих резиновых печатей. Этот фрагмент кода показывает, как: + +- Добавить несколько печатей на одной странице +- Подготовить их к перемещению, используя их индекс +- Опционально переместить штамп, указав его страницу, индекс и новые координаты + +Метод 'move_stamp(page_number, stamp_index, new_x, new_y)' может точно переместить штампы. + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) object. +1. Привяжите PDF к редактору. +1. Добавьте несколько каучуковых штампов на страницу. +1. Сохраните документ перед выполнением операций перемещения. +1. Переместите определённый штамп по его индексу. +1. Сохраните обновлённый PDF. + +```python +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd +from io import BytesIO +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def move_stamp_by_index(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + content_editor.create_rubber_stamp( + 2, + apd.Rectangle(200, 380, 180, 60), + "Draft", + "Draft stamp for ID-based operations", + apd.Color.orange, + ) + + content_editor.create_rubber_stamp( + 2, + apd.Rectangle(200, 480, 180, 60), + "Draft", + "Draft stamp for ID-based operations", + apd.Color.orange, + ) + content_editor.save(outfile) + + # Move first stamp on page 1 by index + # content_editor.move_stamp(1, 1, 10, 10) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md new file mode 100644 index 000000000..b31730ff8 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md @@ -0,0 +1,18 @@ +--- +title: Операции с текстом +linktitle: Операции с текстом +type: docs +weight: 100 +url: /python-net/text-operations/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [Простая замена текста](/pdf/ru/python-net/replace-text-simple/) +- [Замена текста с использованием RegEx](/pdf/ru/python-net/replace-text-regex/) +- [Заменить текст на странице](/pdf/ru/python-net/replace-text-on-page/) +- [Заменить текст с использованием state](/pdf/ru/python-net/replace-text-with-state/) +- [Заменить текст на странице с помощью state](/pdf/ru/python-net/replace-text-on-page-with-state/) diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md new file mode 100644 index 000000000..ac5709a33 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md @@ -0,0 +1,54 @@ +--- +title: Заменить текст на странице с помощью state +linktitle: Заменить текст на странице с помощью state +type: docs +weight: 20 +url: /python-net/replace-text-on-page-with-state/ +description: В этом примере все "software" на странице 1 заменяются на "SOFTWARE PAGE 1", используя красный текст с размером шрифта 12. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Заменить текст с пользовательским форматированием на конкретной странице с помощью PdfContentEditor в Python +Abstract: Этот пример демонстрирует, как заменить текст на определённой странице PDF, применяя пользовательское форматирование с использованием Aspose.PDF for Python через Facades API. Он показывает, как контролировать размер шрифта и цвет при замене текста. +--- + +Иногда замена текста в PDF также требует изменения форматирования, например цвета или размера шрифта. С помощью TextState вы можете определить свойства оформления и применить их во время замены. Это позволяет выделять изменённый текст или обеспечивать единообразное форматирование во всех документах. + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) экземпляр. +1. Привяжите входной PDF‑документ. +1. Определите TextState с пользовательским форматированием. +1. Настройте стратегию замены. +1. Замените текст на конкретной странице. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def replace_text_on_page_with_state(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + text_state = ap.text.TextState() + text_state.foreground_color = ap.Color.red + text_state.font_size = 12 + + # Replace text on a specific page with explicit text formatting + content_editor.replace_text_strategy.replace_scope = ( + pdf_facades.ReplaceTextStrategy.Scope.REPLACE_ALL + ) + content_editor.replace_text("software", 1, "SOFTWARE PAGE 1", text_state) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md new file mode 100644 index 000000000..2016dec04 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md @@ -0,0 +1,48 @@ +--- +title: Заменить текст на странице +linktitle: Заменить текст на странице +type: docs +weight: 10 +url: /python-net/replace-text-on-page/ +description: В этом примере "PDF" заменяется на "Page 1 Replaced Text" с использованием указанного размера шрифта. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Заменить текст на конкретной странице с помощью PdfContentEditor в Python +Abstract: Этот пример демонстрирует, как заменить текст в PDF‑документе с использованием Aspose.PDF for Python через Facades API. Показано, как заменить первое вхождение текста на странице и сохранить обновлённый документ. +--- + +Замена текста является распространённым требованием при обновлении PDF‑документов. С помощью [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете искать определённый текст и заменять его новым содержимым. Свойство ‘replace_text_strategy’ позволяет контролировать, сколько вхождений будет заменено. + +1. Создайте экземпляр PdfContentEditor. +1. Привяжите входной PDF‑документ. +1. Настройте стратегию замены текста. +1. Замените целевой текст. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def replace_text_on_page(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Replace text on page 1 + content_editor.replace_text_strategy.replace_scope = ( + pdf_facades.ReplaceTextStrategy.Scope.REPLACE_FIRST + ) + content_editor.replace_text("PDF", "Page 1 Replaced Text", 14) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md new file mode 100644 index 000000000..1353c7a68 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md @@ -0,0 +1,49 @@ +--- +title: Замена текста с использованием RegEx +linktitle: Замена текста с использованием RegEx +type: docs +weight: 30 +url: /python-net/replace-text-regex/ +description: В этом примере все четырёхзначные числа в документе заменяются плейсхолдером "[NUMBER]". Это полезно для маскирования конфиденциальных данных, нормализации содержимого или анонимизации документов. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Замена текста с помощью регулярных выражений с PdfContentEditor в Python +Abstract: Этот пример демонстрирует, как заменить текст в PDF с помощью регулярных выражений, используя Aspose.PDF for Python через Facades API. Он показывает, как искать шаблоны и заменять все совпадения по всему документу. +--- + +Регулярные выражения позволяют гибко заменять текст на основе шаблонов, а не фиксированных строк. Включив поддержку regex в 'replace_text_strategy', вы можете сопоставлять динамичное содержимое, такое как числа, даты или отформатированные строки. + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) экземпляр. +1. Привяжите входной PDF‑документ. +1. Настройте стратегию замены для использования regex. +1. Заменить совпадающие шаблоны во всем документе. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def replace_text_regex(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Replace text in the whole document + content_editor.replace_text_strategy.replace_scope = ( + pdf_facades.ReplaceTextStrategy.Scope.REPLACE_ALL + ) + content_editor.replace_text_strategy.is_regular_expression_used = True + content_editor.replace_text(r"\d{4}", "[NUMBER]") + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md new file mode 100644 index 000000000..33df3dba3 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md @@ -0,0 +1,48 @@ +--- +title: Простая замена текста +linktitle: Простая замена текста +type: docs +weight: 40 +url: /python-net/replace-text-simple/ +description: В этом примере все вхождения "33" заменяются на "XXXIII " во всём документе. Это демонстрирует простую замену строк без пользовательского форматирования или регулярных выражений. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Замена текста в PDF с использованием PdfContentEditor в Python +Abstract: В этом примере демонстрируется, как заменить текст по всему PDF‑документу, используя Aspose.PDF for Python через Facades API. Он заменяет все вхождения указанной строки новым текстом. +--- + +Простая замена текста полезна при обновлении повторяющихся значений в документе. С [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/), вы можете определить область замены и заменить текст глобально на всех страницах. + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) экземпляр. +1. Привяжите входной PDF‑документ. +1. Настройте область замены для всех вхождений. +1. Замените целевой текст. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def replace_text_simple(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Replace text in the whole document + content_editor.replace_text_strategy.replace_scope = ( + pdf_facades.ReplaceTextStrategy.Scope.REPLACE_ALL + ) + content_editor.replace_text("33", "XXXIII ") + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md new file mode 100644 index 000000000..00e6d9436 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md @@ -0,0 +1,54 @@ +--- +title: Заменить текст с использованием state +linktitle: Заменить текст с использованием state +type: docs +weight: 50 +url: /python-net/replace-text-with-state/ +description: В этом примере все вхождения "software" заменяются на "SOFTWARE" и форматируются синим цветом размером шрифта 14. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Заменить текст с пользовательским форматированием в PDF с помощью PdfContentEditor на Python +Abstract: Этот пример демонстрирует, как заменить текст в PDF‑документе, применяя пользовательское форматирование с помощью Aspose.PDF for Python через Facades API. Показано, как управлять цветом текста и размером шрифта при замене. +--- + +При обновлении текста в PDF вы можете захотеть, чтобы заменяемый контент выделялся. Используя объект TextState, можно задать стиль, например цвет и размер шрифта, а затем применить его ко всему замененному тексту. + +1. Создайте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) экземпляр. +1. Привяжите входной PDF‑документ. +1. Определите TextState с пользовательским форматированием. +1. Настройте область замены. +1. Замените текст по всему документу. +1. Сохраните обновлённый PDF‑документ. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def replace_text_with_state(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + text_state = ap.text.TextState() + text_state.foreground_color = ap.Color.blue + text_state.font_size = 14 + + # Replace text with explicit text formatting + content_editor.replace_text_strategy.replace_scope = ( + pdf_facades.ReplaceTextStrategy.Scope.REPLACE_ALL + ) + content_editor.replace_text("software", "SOFTWARE", text_state) + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md new file mode 100644 index 000000000..05ab44a68 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md @@ -0,0 +1,16 @@ +--- +title: Настройки просмотра +linktitle: Настройки просмотра +type: docs +weight: 110 +url: /python-net/viewer-preferences/ +description: +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + + +- [Изменить параметры просмотра PDF](/pdf/ru/python-net/change-viewer-preferences/) +- [Получить настройки просмотра PDF](/pdf/ru/python-net/get-viewer-preferences/) diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md new file mode 100644 index 000000000..4f8fab0eb --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md @@ -0,0 +1,76 @@ +--- +title: Изменить параметры просмотра PDF +linktitle: Изменить параметры просмотра PDF +type: docs +weight: 10 +url: /python-net/change-viewer-preferences/ +description: Этот модуль демонстрирует, как настроить параметры просмотра PDF‑документа с помощью Aspose.PDF for Python. +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Настройте просмотр PDF с помощью Python +Abstract: Управляйте тем, как ваш PDF‑документ отображается при открытии, программно изменяя параметры просмотра. Эта возможность позволяет настроить пользовательский интерфейс и макет, обеспечивая единообразный опыт просмотра. +--- + +Файлы PDF имеют встроенные параметры просмотра, которые управляют такими аспектами, как расположение страниц, видимость панели инструментов и поведение окна. С помощью этого скрипта вы можете: + +- Проверьте текущие параметры просмотра PDF. +- Изменить параметры макета (например, одностраничный, одноколоночный, двухколоночный). +- Переключать элементы интерфейса, такие как панель инструментов, строка меню или отображение заголовка. +- Сохранить PDF с обновлёнными настройками для контролируемого просмотра. + +1. Определите ViewerPreference Flags. +1. Получите текущие Viewer Preferences. +1. Измените настройки. +1. Примените обновлённые настройки. +1. Сохраните PDF. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from enum import IntFlag +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Define ViewerPreference flags +class ViewerPreference(IntFlag): + HIDE_TOOLBAR = 1 + HIDE_MENUBAR = 2 + HIDE_WINDOW_UI = 4 + FIT_WINDOW = 8 + CENTER_WINDOW = 16 + DISPLAY_DOC_TITLE = 32 + NON_FULL_SCREEN_PAGE_MODE_USE_NONE = 64 + NON_FULL_SCREEN_PAGE_MODE_USE_OUTLINES = 128 + NON_FULL_SCREEN_PAGE_MODE_USE_THUMBS = 256 + NON_FULL_SCREEN_PAGE_MODE_USE_OC = 512 + DIRECTION_L2R = 1024 + DISPLAY_DOC_TITLE_IN_TITLE_BAR = 2048 + PAGE_LAYOUT_SINGLE_PAGE = 4096 + PAGE_LAYOUT_ONE_COLUMN = 8192 + PAGE_LAYOUT_TWO_COLUMN_LEFT = 16384 + PAGE_LAYOUT_TWO_COLUMN_RIGHT = 32768 + PAGE_LAYOUT_TWO_PAGE_LEFT = 65536 + PAGE_LAYOUT_TWO_PAGE_RIGHT = 131072 + + +def change_viewer_preferences(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + + # Get current viewer preference and toggle single-page layout + current_preference = ViewerPreference(content_editor.get_viewer_preference()) + updated_preference = current_preference | ViewerPreference.PAGE_LAYOUT_SINGLE_PAGE + content_editor.change_viewer_preference(int(updated_preference)) + + # Save updated document + content_editor.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md new file mode 100644 index 000000000..aa3a78b81 --- /dev/null +++ b/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md @@ -0,0 +1,46 @@ +--- +title: Получить настройки просмотра PDF +linktitle: Получить настройки просмотра PDF +type: docs +weight: 20 +url: /python-net/get-viewer-preferences/ +description: Как программно считывать и изменять настройки просмотра PDF с использованием Aspose.PDF for Python +lastmod: "2026-03-20" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Управление настройками просмотра PDF с помощью Aspose.PDF в Python +Abstract: В этом руководстве демонстрируется, как программно считывать и изменять настройки просмотра PDF с использованием Aspose.PDF for Python. Настройки просмотра определяют, как PDF отображается при открытии в PDF‑просмотрщике, например, с открытыми оглавлениями, скрытыми панелями инструментов или в режиме одиночной страницы. +--- + +Aspose.PDF предоставляет инструменты для доступа к настройкам просмотра PDF и их обновления. Эти настройки определяют начальное расположение и поведение представления PDF‑документа. Это включает такие варианты, как включение представления оглавления, скрытие строк меню или указание режимов расположения страниц. С помощью PdfContentEditor вы можете получить существующие настройки, проверить отдельные флаги и при необходимости обновить их. + +1. Определите ViewerPreference Flags. +1. Инициализируйте [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) и привяжите PDF. +1. Получите текущие Viewer Preferences. +1. Проверьте конкретные флаги. +1. Отобразите текущие настройки. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from enum import IntFlag +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def get_viewer_preferences(infile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + # Read current viewer preference flags + viewer_preference = ViewerPreference(content_editor.get_viewer_preference()) + if viewer_preference & ViewerPreference.PAGE_MODE_USE_OUTLINES: + print("PageModeUseOutlines is enabled") + print(f"Current viewer preference: {viewer_preference}") +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/_index.md b/ru/python-net/working-with-facades/pdffileeditor/_index.md new file mode 100644 index 000000000..b7edd291b --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/_index.md @@ -0,0 +1,31 @@ +--- +title: Класс PdfFileEditor +linktitle: Класс PdfFileEditor +type: docs +weight: 10 +url: /python-net/pdffileeditor-class/ +description: Изучите, как редактировать и управлять PDF‑файлами с помощью класса PDFFileEditor на Python с Aspose.PDF. +lastmod: "2026-01-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Редактируйте страницы PDF, объединяйте файлы и разделяйте документы с помощью PdfFileEditor на Python +Abstract: Узнайте, как использовать класс PdfFileEditor в Aspose.PDF для Python через .NET для управления страницами PDF и структурой документа. Этот раздел охватывает изменение макета страниц, управление страницами, объединение PDF, разделение документов, а также процессы создания брошюр или N‑Up импозиции. +--- + +Работа с PDF‑документами включает различные функции. Управление страницами PDF‑файла является важной частью этой задачи. 'aspose.pdf.facades' предоставляет `PdfFileEditor` класс для этой цели. + +Класс PdfFileEditor содержит методы, помогающие управлять отдельными страницами; этот класс не редактирует и не изменяет содержимое страницы. Вы можете вставить новую страницу, удалить существующую, разделить страницы или задать их импозицию с помощью PdfFileEditor. + +## Что вы можете сделать с PdfFileEditor + +Функции, предоставляемые этим классом, могут быть сгруппированы в редактирование страниц, импозицию PDF и рабочие процессы разделения документов. Эти статьи показывают, как переставлять страницы, объединять несколько PDF, готовить файлы к печати и извлекать разделы из существующих документов без ручного редактирования исходного файла. + +## Руководства по PdfFileEditor + +- [Разметка страниц и поля](/pdf/ru/python-net/page-layout-and-margins/) +- [Управление страницами](/pdf/ru/python-net/page-management/) +- [Объединить или конкатенировать PDF‑файлы](/pdf/ru/python-net/page-merging/) +- [Разделить PDF документы](/pdf/ru/python-net/splitting-pdf-documents/) +- [Брошюра и N-Up макет](/pdf/ru/python-net/booklet-and-nup-layout/) diff --git a/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md b/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md new file mode 100644 index 000000000..461be7415 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md @@ -0,0 +1,22 @@ +--- +title: Брошюра и N-Up макет +linktitle: Брошюра и N-Up макет +type: docs +weight: 10 +url: /python-net/booklet-and-nup-layout/ +description: Подготовка PDF‑файлов к печати часто требует переорганизации страниц в определённые макеты, такие как брошюры или N-Up сетки. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Создание брошюрных и N-Up макетов для PDF‑документов на Python +Abstract: Узнайте, как преобразовать макеты страниц PDF с помощью Aspose.PDF for Python. Это руководство объясняет, как создавать документы в стиле брошюры и создавать N-Up макеты, размещающие несколько страниц на одном листе. Эти техники помогают оптимизировать документы для печати, снизить расход бумаги и создавать компактные PDF‑выводы. +--- + +Функции брошюры и N-Up помогают подготовить PDF‑документы к печати и компактному представлению страниц. Эти рабочие процессы переупорядочивают порядок страниц или размещают несколько исходных страниц на одном листе, что полезно для раздаточных материалов, черновиков и готового к печати брошюрного вывода. + +## Учебники по преобразованию макетов + +- [Создать N-Up PDF документ](/pdf/ru/python-net/create-n-up-pdf-document/) +- [Создать PDF‑буклет](/pdf/ru/python-net/create-pdf-booklet/) diff --git a/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md b/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md new file mode 100644 index 000000000..ca9168aba --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md @@ -0,0 +1,85 @@ +--- +title: Создать N-Up PDF документ +linktitle: Создать N-Up PDF документ +type: docs +weight: 10 +url: /python-net/create-n-up-pdf-document/ +description: Узнайте, как создать N-Up PDF документ, безопасно обрабатывая потенциальные ошибки, используя Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Создать N-Up PDF Layout в Python +Abstract: Узнайте, как сгенерировать N-Up PDF layout, используя Aspose.PDF for Python. Этот пример демонстрирует, как объединить несколько страниц PDF‑документа на одну страницу, используя метод «make_n_up» или «try_make_n_up» класса PdfFileEditor. +--- + +N-Up layout размещает несколько страниц PDF‑документа на одной странице в виде сетки. Такой макет часто используется для печати презентаций, раздаточных материалов или отчётов, когда необходимо просмотреть сразу несколько страниц. + +С помощью Aspose.PDF for Python разработчики могут быстро создать N-Up документ, указав количество строк и столбцов, определяющих, сколько оригинальных страниц будет размещено на каждой выходной странице. + +В этом фрагменте кода метод 'make_n_up' класса [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) располагает страницы входного PDF в сетке 2 × 2, что означает, что четыре оригинальные страницы появляются на одной странице в выходном документе. + +В показанном примере макет использует 2 строки и 2 столбца, получая четыре страницы на листе: + +1. Откройте исходный PDF‑файл. +1. Создайте экземпляр PdfFileEditor. +1. Укажите количество строк и столбцов для компоновки N‑Up. +1. Создайте новый PDF с объединёнными страницами. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Create N-Up PDF Document +def create_nup_pdf_document(infile, outfile): + # Create NUpMaker object + nup_maker = pdf_facades.PdfFileEditor() + # Make N-Up layout from input PDF file and save to output PDF file + nup_maker.make_n_up( + FileIO(infile), FileIO(outfile, "w"), 2, 2 + ) # 2 rows and 2 columns for N-Up layout +``` + +Aspose.PDF for Python via .NET позволяет генерировать N-Up макеты с помощью класса PdfFileEditor. Метод 'try_make_n_up' работает аналогично make_n_up, но вместо того чтобы возбуждать исключение при неудачной операции, он возвращает логическое значение, указывающее, успешно ли процесс завершён. + +Макет N-Up располагает несколько страниц PDF на одной странице, используя сетку, определённую строками и столбцами. + +Метод 'try_make_n_up' предоставляет более безопасный способ выполнения этой операции, потому что: + +- Он возвращает True, если макет успешно создан +- Он возвращает False, если операция не удалась +- Он не прерывает выполнение программы исключениями + +В примере ниже документ располагается с использованием сетки 2 × 2, что размещает четыре оригинальные страницы на каждой выходной странице. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Create N-Up PDF Document +def try_create_nup_pdf_document(infile, outfile): + # Create NUpMaker object + nup_maker = pdf_facades.PdfFileEditor() + # Make N-Up layout from input PDF file and save to output PDF file + if not nup_maker.try_make_n_up(FileIO(infile), FileIO(outfile, "w"), 2, 2): + print("Failed to create N-Up PDF document.") +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md b/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md new file mode 100644 index 000000000..901361dc5 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md @@ -0,0 +1,82 @@ +--- +title: Создать PDF‑буклет +linktitle: Создать PDF‑буклет +type: docs +weight: 20 +url: /python-net/create-pdf-booklet/ +description: Создать PDF‑буклет из существующего документа с использованием Aspose.PDF for Python +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Создать PDF‑буклет из существующего PDF с помощью Python +Abstract: Узнайте, как создать PDF‑буклет из существующего документа, используя Aspose.PDF for Python. В этом примере показано, как использовать класс PdfFileEditor для перестановки страниц, чтобы их можно было печатать и складывать в виде буклета. Метод автоматически упорядочивает страницы, создавая корректную компоновку буклета. +--- + +Создание документов в виде буклета является обычным требованием при подготовке PDF для печати. В макете буклета страницы переставляются таким образом, чтобы после печати и складывания они находились в правильном порядке. + +С помощью Aspose.PDF for Python разработчики могут легко преобразовать обычный PDF в буклет, используя [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) класс. Метод 'make_booklet' автоматически переупорядочивает страницы входного документа и создает новый PDF, оптимизированный для печати в виде книжки. + +1. Откройте существующий PDF‑документ. +1. Создайте экземпляр PdfFileEditor. +1. Используйте метод make_booklet для переупорядочивания страниц. +1. Сохраните результат как PDF‑файл, готовый к печати в виде книжки. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Create PDF Booklet +def create_pdf_booklet(infile, outfile): + # Create BookletMaker object + booklet_maker = pdf_facades.PdfFileEditor() + # Make booklet from input PDF file and save to output PDF file + booklet_maker.make_booklet(FileIO(infile), FileIO(outfile, "w")) +``` + +Этот фрагмент кода показывает, как использовать метод 'try_make_booklet' [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) класса для перестановки страниц при печати буклета без генерации исключений, если операция завершится с ошибкой. + +Макет буклета переставляет страницы так, что после печати и сгибания документ читается в правильном порядке. Автоматизация этого процесса обеспечивает постоянные результаты и устраняет необходимость ручного переставления страниц. + +Метод 'try_make_booklet' работает аналогично 'make_booklet', но с важным отличием: + +- 'make_booklet' генерирует исключение, если операция не удалась. +- 'try_make_booklet' возвращает True или False, позволяя разработчикам более безопасно обрабатывать ошибки. + +1. Откройте существующий PDF‑документ. +1. Создайте экземпляр PdfFileEditor. +1. Создайте буклет. +1. Обработайте результат. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def try_create_pdf_booklet(infile, outfile): + # Create BookletMaker object + booklet_maker = pdf_facades.PdfFileEditor() + # Make booklet from input PDF file and save to output PDF file + # The try_make_booklet method is like the make_booklet method, + # except the try_make_booklet method does not throw an exception if the operation fails. + if not booklet_maker.try_make_booklet(FileIO(infile), FileIO(outfile, "w")): + print("Failed to create booklet.") +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md new file mode 100644 index 000000000..643e1cb93 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md @@ -0,0 +1,19 @@ +--- +title: Разметка страниц и поля +linktitle: Разметка страниц и поля +type: docs +weight: 20 +url: /python-net/page-layout-and-margins/ +description: Управление разметкой страниц PDF является важной частью рабочих процессов обработки документов. Разработчикам часто требуется корректировать поля, изменять размер содержимого страницы или вставлять разрывы страниц, чтобы гарантировать соответствие документов требованиям форматирования или печати. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Редактирование разметки страниц PDF на Python — добавление полей, изменение размера содержимого и вставка разрывов страниц +Abstract: Узнайте, как изменять разметку страниц PDF с помощью Aspose.PDF for Python. Это руководство объясняет, как добавлять поля к определённым страницам, изменять размер содержимого страниц и программно вставлять разрывы страниц. Эти возможности позволяют разработчикам настраивать форматирование документов, улучшать читаемость и готовить PDF к печати или к структурированным макетам. +--- + +- [Добавить поля к страницам PDF](/pdf/ru/python-net/add-margins-to-pdf-pages/) +- [Изменить размер содержимого страниц PDF](/pdf/ru/python-net/resize-pdf-page-contents/) +- [Добавить разрывы страниц в PDF](/pdf/ru/python-net/add-page-breaks-in-pdf/) \ No newline at end of file diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md new file mode 100644 index 000000000..21b838e89 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md @@ -0,0 +1,52 @@ +--- +title: Добавить поля к страницам PDF +linktitle: Добавить поля к страницам PDF +type: docs +weight: 10 +url: /python-net/add-margins-to-pdf-pages/ +description: Добавить пользовательские поля к выбранным страницам PDF с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавить пользовательские поля к определённым страницам PDF в Python +Abstract: Узнайте, как добавить пользовательские поля к выбранным страницам PDF, используя Aspose.PDF for Python. Этот пример демонстрирует, как расширить границы страницы, указывая верхние, нижние, левый и правый поля для отдельных страниц, делая PDF более пригодными для печати или визуально согласованными. +--- + +Добавление полей к страницам PDF может улучшить читаемость, подготовить документы к печати или выделить место для аннотаций. С помощью Aspose.PDF for Python разработчики могут программно добавлять поля к определённым страницам PDF, не изменяя расположение содержимого. + +В этом фрагменте кода, the [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) Класс используется для добавления полдюймовых полей к страницам 1 и 3 входного документа. Поля задаются в пунктах (1 дюйм = 72 пункта) и применяются индивидуально к левому, правому, верхнему и нижнему краю каждой страницы. + +1. Откройте исходный PDF-документ. +1. Создайте экземпляр 'PdfFileEditor'. +1. Определите поля и страницы для изменения. +1. Примените поля, используя метод 'add_margins'. +1. Сохраните обновлённый PDF в выходной файл. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Add Margins to PDF Pages +def add_margins_to_pdf_pages(infile, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + # Define the margins to be added (in points) + left_margin = 36 # 0.5 inch + right_margin = 36 # 0.5 inch + top_margin = 36 # 0.5 inch + bottom_margin = 36 # 0.5 inch + + pdf_editor.add_margins( + infile, outfile, [1, 3], left_margin, right_margin, top_margin, bottom_margin + ) +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md new file mode 100644 index 000000000..07331e7c1 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md @@ -0,0 +1,48 @@ +--- +title: Добавить разрывы страниц в PDF +linktitle: Добавить разрывы страниц в PDF +type: docs +weight: 20 +url: /python-net/add-page-breaks-in-pdf/ +description: Вставьте разрывы страниц в документ PDF с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Программно добавить разрывы страниц в PDF-страницы на Python +Abstract: Узнайте, как вставить разрывы страниц в документ PDF с помощью Aspose.PDF for Python. Этот пример демонстрирует, как разделить страницу в указанной вертикальной позиции, позволяя разработчикам реорганизовать содержимое и динамически создавать дополнительные страницы. +--- + +Разрывы страниц полезны, когда необходимо разделить длинные страницы PDF на несколько страниц или контролировать распределение содержимого по документу. С помощью Aspose.PDF for Python разработчики могут вставлять разрывы страниц в конкретных позициях без ручного редактирования PDF. + +Эта статья показывает, как использовать метод 'add_page_break' [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) класс для вставки разрыва страницы на заданной вертикальной координате выбранной страницы. Метод создает новую страницу и перемещает содержимое ниже точки разрыва на эту страницу. + +1. Создайте объект PdfFileEditor. +1. Определите позицию разрыва страницы. +1. Вставьте разрыв страницы. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Add Page Breaks in PDF +def add_page_breaks_in_pdf(infile, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.add_page_break( + infile, + outfile, + [ + pdf_facades.PdfFileEditor.PageBreak(1, 400), + ], + ) +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md new file mode 100644 index 000000000..500309836 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md @@ -0,0 +1,51 @@ +--- +title: Изменить размер содержимого страниц PDF +linktitle: Изменить размер содержимого страниц PDF +type: docs +weight: 30 +url: /python-net/resize-pdf-page-contents/ +description: Измените размер содержимого определённых страниц PDF с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Программное изменение размера содержимого страниц PDF на Python +Abstract: Узнайте, как изменить размер содержимого определённых страниц PDF с помощью Aspose.PDF for Python. В этом примере демонстрируется, как скорректировать ширину и высоту содержимого страницы, сохраняя структуру документа, что облегчает оптимизацию макетов для печати или просмотра. +--- + +Регулировка размера содержимого страниц PDF часто необходима при подготовке документов к печати, размещении контента в определённом макете или стандартизации форматов страниц в документе. С помощью Aspose.PDF for Python разработчики могут программно изменять размер содержимого выбранных страниц без ручного редактирования документа. + +В этой статье показывается, как использовать метод 'resize_contents' [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) класс для изменения размеров содержимого страницы для конкретных страниц PDF‑файла. Указывая целевую ширину и высоту, содержимое выбранных страниц изменяется соответственно. + +1. Создайте объект PdfFileEditor. +1. Измените размер содержимого страниц. + +Параметры: + +- [1, 3] – список номеров страниц, содержимое которых будет изменено. +- 400 – новая ширина содержимого страницы (в пунктах). +- 750 – новая высота содержимого страницы (в пунктах). + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Resize PDF Page Contents +def resize_pdf_page_contents(infile, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + + if not pdf_editor.resize_contents( + FileIO(infile), FileIO(outfile, "w"), [1, 3], 400, 750 + ): + raise Exception("Failed to resize PDF page contents.") +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-managment/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-managment/_index.md new file mode 100644 index 000000000..f34d70cf9 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/page-managment/_index.md @@ -0,0 +1,26 @@ +--- +title: Управление страницами +linktitle: Управление страницами +type: docs +weight: 30 +url: /python-net/page-management/ +description: Программное управление страницами PDF позволяет разработчикам изменять документы без ручного редактирования. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Программное управление страницами PDF в Python — извлечение, удаление, вставка и добавление +Abstract: Узнайте, как выполнять операции на уровне страниц в PDF‑документах с помощью Aspose.PDF for Python. Это руководство демонстрирует, как извлекать конкретные страницы, удалять ненужные страницы, вставлять страницы из другого PDF и добавлять страницы к существующему документу, обеспечивая эффективное и автоматизированное управление страницами PDF. +--- + +Задачи управления страницами являются центральными во многих рабочих процессах с PDF. С помощью Aspose.PDF for Python вы можете реорганизовать структуру документа, удалить ненужные страницы и объединить содержимое нескольких PDF, сохраняя оригинальное содержимое страниц нетронутым. + +## Распространённые операции управления страницами + +Используйте следующие руководства, чтобы выполнять наиболее распространённые задачи редактирования на уровне страниц с `PdfFileEditor`: + +- [Извлечь страницы из PDF](/pdf/ru/python-net/extract-pages-from-pdf/) +- [Удалить страницы из PDF](/pdf/ru/python-net/delete-pages-from-pdf/) +- [Вставить страницы в PDF](/pdf/ru/python-net/insert-pages-into-pdf/) +- [Добавить страницы в PDF](/pdf/ru/python-net/append-pages-to-pdf/) diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md new file mode 100644 index 000000000..a16ca3f6a --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md @@ -0,0 +1,43 @@ +--- +title: Добавить страницы в PDF +linktitle: Добавить страницы в PDF +type: docs +weight: 10 +url: /python-net/append-pages-to-pdf/ +description: Добавьте страницы из одного PDF‑документа в другой с использованием Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавление страниц из одного PDF в другой на Python +Abstract: Узнайте, как добавить страницы из одного PDF‑документа в другой с помощью Aspose.PDF for Python. В этом примере демонстрируется, как использовать класс PdfFileEditor для объединения страниц из нескольких PDF и создания единого выходного документа. +--- + +Объединение страниц из разных PDF‑документов является распространенной задачей в рабочих процессах обработки документов. С помощью Aspose.PDF for Python разработчики могут легко добавлять страницы из одного или нескольких PDF‑файлов в существующий документ. + +Этот фрагмент кода показывает, как использовать метод append в [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) классе для добавления выбранных страниц из другого PDF‑файла в конец исходного PDF. Указывая диапазон страниц, разработчики могут точно контролировать, какие страницы включаются в окончательный документ. + +1. Создайте объект PdfFileEditor. +1. Добавьте страницы из другого PDF. + +Указанные страницы из вторичного PDF‑документа добавляются в конец оригинального PDF, создавая объединённый выходной файл. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +# Append Pages to PDF +def append_pages_to_pdf(infile, sample_file, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + # Append pages from the specified PDF document to the end of the source PDF document + pdf_editor.append(infile, [sample_file], 1, 2, outfile) +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md new file mode 100644 index 000000000..6623f72e6 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md @@ -0,0 +1,47 @@ +--- +title: Удалить страницы из PDF +linktitle: Удалить страницы из PDF +type: docs +weight: 20 +url: /python-net/delete-pages-from-pdf/ +description: Удалить выбранные страницы из PDF-документа с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Удалить конкретные страницы из PDF-документа на Python +Abstract: Узнайте, как удалить выбранные страницы из PDF-документа с помощью Aspose.PDF for Python. Этот пример демонстрирует, как программно удалить конкретные страницы из существующего PDF‑файла, создав новый документ без удалённых страниц. +--- + +Иногда PDF-документы содержат ненужные или конфиденциальные страницы, которые необходимо удалить. С помощью Aspose.PDF for Python разработчики могут программно удалять конкретные страницы из PDF, не редактируя файл вручную. + +Наш пример показывает, как использовать метод delete в [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) классе для удаления страниц из PDF‑документа. Указывая номера страниц для удаления, вы можете создать новый PDF, который исключает нежелательные страницы. Эта функция полезна для очистки отчетов, удаления конфиденциальной информации или подготовки пользовательских извлечений документов. + +1. Создайте объект PdfFileEditor. +1. Определите страницы для удаления. +1. Удалите страницы. + +```python + + import aspose.pdf as ap + import aspose.pdf.facades as pdf_facades + + import sys + from os import path + + sys.path.append(path.join(path.dirname(__file__), "..")) + from config import set_license, initialize_data_dir + + + # Delete Pages from PDF + def delete_pages_from_pdf(infile, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + + # Define the page numbers to be deleted (1-based index) + pages_to_delete = [2, 4] + + # Delete the specified pages from the PDF document + pdf_editor.delete(infile, pages_to_delete, outfile) +``` \ No newline at end of file diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md new file mode 100644 index 000000000..f117c1d14 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md @@ -0,0 +1,46 @@ +--- +title: Извлечение страниц из PDF +linktitle: Извлечение страниц из PDF +type: docs +weight: 30 +url: /python-net/extract-pages-from-pdf/ +description: Извлечь выбранные страницы из PDF‑документа с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Извлечение определённых страниц из PDF‑документа на Python +Abstract: Узнайте, как извлечь выбранные страницы из PDF‑документа с помощью Aspose.PDF for Python. В этом примере показано, как создать новый PDF, содержащий только необходимые вам страницы, позволяя создавать пользовательские документы и выполнять манипуляции на уровне страниц. +--- + +Извлечение страниц из PDF полезно, когда необходимо создать подмножество документа, поделиться только определённым содержимым или реорганизовать PDF‑файлы для презентаций, отчетов или печати. С помощью Aspose.PDF for Python разработчики могут программно извлекать страницы из PDF‑файла и сохранять их как новый документ. + +Узнайте, как использовать метод extract в [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) классе. Указывая список страниц для извлечения, вы можете создать новый PDF, содержащий только выбранные страницы, при этом сохраняется оригинальное содержание и форматирование. + +1. Создайте объект PdfFileEditor. +1. Определите страницы для извлечения. +1. Извлеките страницы. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +# Extract Pages from PDF +def extract_pages_from_pdf(infile, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + + # Define the page numbers to be extracted (1-based index) + pages_to_extract = [1, 4, 3] + + # Extract the specified pages from the PDF document and save to a new PDF document + pdf_editor.extract(infile, pages_to_extract, outfile) +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md new file mode 100644 index 000000000..e96a593db --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md @@ -0,0 +1,45 @@ +--- +title: Вставить страницы в PDF +linktitle: Вставить страницы в PDF +type: docs +weight: 40 +url: /python-net/insert-pages-into-pdf/ +description: Вставьте страницы из одного PDF в другой с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Вставить страницы из другого PDF в существующий PDF на Python +Abstract: Узнайте, как вставлять страницы из одного PDF в другой с использованием Aspose.PDF for Python. В этом примере демонстрируется, как добавить выбранные страницы из вторичного PDF в определённое место оригинального документа, создавая объединённый PDF с точным размещением страниц. +--- + +Вставка страниц в существующий PDF является распространённой задачей при объединении документов, добавлении содержимого или реорганизации отчётов. С помощью Aspose.PDF for Python разработчики могут программно вставлять страницы из одного PDF в другой в указанном месте. + +Эта статья показывает, как использовать метод insert в [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) классе. Указывая номера страниц для вставки и целевое местоположение, вы можете объединять содержимое разных PDF, сохраняя оригинальное форматирование и структуру. + +1. Создайте объект PdfFileEditor. +1. Определите позицию вставки и страницы. +1. Вставьте страницы. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +# Insert Pages into PDF +def insert_pages_into_pdf(infile, sample_file, outfile): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + + # Define the page number where new pages will be inserted (1-based index) + insert_page_number = 2 + + pdf_editor.insert(infile, insert_page_number, sample_file, [1, 2], outfile) +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-merging/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-merging/_index.md new file mode 100644 index 000000000..213e776f3 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/page-merging/_index.md @@ -0,0 +1,23 @@ +--- +title: Объединить PDF-файлы +linktitle: Объединить PDF-файлы +type: docs +weight: 40 +url: /python-net/page-merging/ +description: Объединение PDF‑документов является распространенной задачей в автоматизированных рабочих процессах, генерации отчетов и управлении документами. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Объедините PDF‑файлы в Python — объединяйте два или несколько PDF с помощью Aspose.PDF +Abstract: Узнайте, как программно объединять PDF‑файлы с помощью Aspose.PDF for Python. В этом руководстве демонстрируются методы объединения двух и более PDF, обработка большого количества файлов, оптимизация вывода и объединение PDF‑форм с уникальными суффиксами для предотвращения конфликтов имён. +--- + +- [Объединить два PDF-файла](/pdf/ru/python-net/concatenate-two-files/) +- [Объединить несколько PDF-файлов](/pdf/ru/python-net/concatenate-pdf-files/) +- [Попробовать объединить два PDF-файла](/pdf/ru/python-net/try-concatenate-two-files/) +- [Попытка объединить несколько PDF‑файлов](/pdf/ru/python-net/try-concatenate-pdf-files/) +- [Объединить большое количество PDF‑файлов](/pdf/ru/python-net/concatenate-large-number-files/) +- [Объединить PDF-файлов с оптимизацией](/pdf/ru/python-net/concatenate-pdf-files-with-optimization/) +- [Объединить PDF‑формы с уникальным суффиксом](/pdf/ru/python-net/concatenate-pdf-forms/) \ No newline at end of file diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md new file mode 100644 index 000000000..aca4d0573 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md @@ -0,0 +1,38 @@ +--- +title: Объединить большое количество PDF‑файлов +linktitle: Объединить большое количество PDF‑файлов +type: docs +weight: 10 +url: /python-net/concatenate-large-number-files/ +description: Эффективно объединять большое количество PDF‑файлов с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Объединение больших PDF‑файлов в Python с использованием буферизации на диск +Abstract: Узнайте, как эффективно объединять большое количество PDF‑файлов с помощью Aspose.PDF for Python. Этот пример демонстрирует, как включить буферизацию на диск для обработки больших PDF‑файлов без исчерпания памяти системы, обеспечивая плавное объединение множества файлов. +--- + +С помощью Aspose.PDF for Python вы можете включить буферизацию на диск в [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) классе для эффективного объединения множества PDF‑файлов. Метод concatenate объединяет входные файлы в один PDF, при этом буфер на диске предотвращает большое потребление памяти. Такой подход идеален для обработки массовых документов, автоматической генерации отчетов или консолидирования больших архивов PDF. + +1. Создайте объект PdfFileEditor. +1. Объедините несколько PDF файлов. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +def concatenate_large_number_files(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.use_disk_buffer = True # Enable disk buffering for large files + pdf_editor.concatenate(files_to_merge, output_file) +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md new file mode 100644 index 000000000..3ae81b349 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md @@ -0,0 +1,38 @@ +--- +title: Объединение PDF-файлов с оптимизацией +linktitle: Объединение PDF-файлов с оптимизацией +type: docs +weight: 30 +url: /python-net/concatenate-pdf-files-with-optimization/ +description: Объедините несколько PDF-файлов в один оптимизированный PDF с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Объединение PDF-файлов с оптимизированным выводом в Python +Abstract: Узнайте, как объединять несколько PDF-файлов в один оптимизированный PDF с помощью Aspose.PDF for Python. Этот пример демонстрирует, как включить оптимизацию размера, чтобы уменьшить размер выходного файла, сохраняя при этом содержимое и форматирование. +--- + +При объединении нескольких PDF-файлов получающийся файл может стать крупным, особенно если он содержит изображения или сложный контент. С помощью Aspose.PDF for Python разработчики могут включить оптимизацию во время объединения, чтобы уменьшить размер файла без потери качества. Свойство optimize_size в [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) классе гарантирует, что объединённый PDF является компактным и эффективным, что делает его подходящим для обмена, хранения или архивирования. + +1. Создайте объект PdfFileEditor и включите оптимизацию. +1. Объедините PDF-файлы. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +def concatenate_pdf_files_with_optimization(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.optimize_size = True # Enable optimization for smaller output file size + pdf_editor.concatenate(files_to_merge, output_file) +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md new file mode 100644 index 000000000..d23f3e764 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md @@ -0,0 +1,37 @@ +--- +title: Объединить несколько PDF-файлов +linktitle: Объединить несколько PDF-файлов +type: docs +weight: 20 +url: /python-net/concatenate-pdf-files/ +description: Объедините несколько PDF-файлов в один документ с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Объединить несколько PDF-файлов в один PDF на Python +Abstract: Узнайте, как объединить несколько PDF-файлов в один документ с помощью Aspose.PDF for Python. В этом примере демонстрируется, как использовать метод concatenate для слияния нескольких PDF-файлов при сохранении их содержимого и форматирования. +--- + +Объединение PDF-файлов является распространённой задачей в управлении документами, отчётности и автоматизированных рабочих процессах. С помощью Aspose.PDF for Python разработчики могут легко комбинировать несколько PDF-файлов в единый консолидированный документ. Метод concatenate класса [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) гарантирует, что все страницы из входных файлов сохраняются в конечном результате, поддерживая их оригинальное расположение и содержание. Этот подход полезен для создания всесторонних отчётов, объединения форм или эффективного архивирования нескольких документов. + +1. Создайте объект PdfFileEditor. +1. Объедините несколько PDF‑файлов. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +def concatenate_pdf_files(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.concatenate(files_to_merge, output_file) +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md new file mode 100644 index 000000000..b5fbc0fb3 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md @@ -0,0 +1,40 @@ +--- +title: Объединить PDF‑формы с уникальным суффиксом +linktitle: Объединить PDF‑формы с уникальным суффиксом +type: docs +weight: 50 +url: /python-net/concatenate-pdf-forms/ +description: Объедините несколько PDF‑форм, используя Aspose.PDF for Python, обеспечивая уникальность имён полей формы. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Объединяйте PDF‑формы в Python, избегая конфликтов имён полей. +Abstract: Узнайте, как объединять несколько PDF‑форм, используя Aspose.PDF for Python, обеспечивая уникальность имён полей формы. Этот пример демонстрирует, как задать пользовательский суффикс для предотвращения конфликтов имён при объединении PDF, содержащих интерактивные поля формы. +--- + +Объединение PDF‑форм может привести к конфликтам, если несколько файлов содержат поля с одинаковыми именами. С помощью Aspose.PDF for Python разработчики могут задавать уникальный суффикс полям формы во время объединения. Свойство unique_suffix в [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) классе автоматически переименовывает конфликтующие поля, сохраняя интерактивность и гарантируя, что все данные формы остаются работоспособными. Этот подход идеален для программного комбинирования опросов, заявок или любых интерактивных PDF‑документов. + +1. Создайте объект PdfFileEditor и задайте уникальный суффикс. +1. Объедините PDF-формы. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +def concatenate_pdf_forms(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.unique_suffix = ( + "_xy_%NUM%" # Set a unique suffix to avoid form field name conflicts + ) + pdf_editor.concatenate(files_to_merge, output_file) +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md new file mode 100644 index 000000000..ce5801179 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md @@ -0,0 +1,37 @@ +--- +title: Объединить два PDF-файла +linktitle: Объединить два PDF-файла +type: docs +weight: 60 +url: /python-net/concatenate-two-files/ +description: Объедините два PDF-файла в один документ с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Объединить два PDF-файла в один PDF на Python +Abstract: Узнайте, как объединить два PDF-файла в один документ с помощью Aspose.PDF for Python. Этот пример демонстрирует, как без проблем объединить два PDF, сохраняя их исходное содержание и форматирование. +--- + +Объединение двух PDF-файлов — обычная задача при объединении отчётов, контрактов или форм. С помощью Aspose.PDF for Python вы можете программно объединять два PDF в один документ, используя метод concatenate класса [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/). Это гарантирует, что все страницы из обоих файлов будут включены в результирующий PDF, при сохранении исходного макета, содержимого и структуры. + +1. Создайте объект PdfFileEditor. +1. Объедините два PDF‑файла. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +def concatenate_two_files(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + pdf_editor.concatenate(files_to_merge[0], files_to_merge[1], output_file) +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md new file mode 100644 index 000000000..65991dd03 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md @@ -0,0 +1,38 @@ +--- +title: Объединить PDF-файлы +linktitle: Объединить PDF-файлы +type: docs +weight: 70 +url: /python-net/try-concatenate-pdf-files/ +description: Объедините несколько PDF-файлов с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Безопасное объединение PDF-файлов в Python с обработкой ошибок +Abstract: Узнайте, как безопасно конкатенировать несколько PDF-файлов с помощью Aspose.PDF for Python. Метод try_concatenate пытается объединить PDF без выбрасывания исключений, позволяя разработчикам аккуратно обрабатывать ошибки. +--- + +Объединение PDF-файлов иногда может завершаться неудачей из‑за повреждённых файлов, несовместимых форматов или других проблем. С помощью Aspose.PDF for Python вы можете использовать метод try_concatenate класса [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) класса для безопасного выполнения конкатенации. Вместо выбрасывания исключения метод возвращает False, если операция не удалась, обеспечивая контролируемую обработку ошибок в автоматизированных рабочих процессах. + +1. Создайте объект PdfFileEditor. +1. Обьедините PDF-файлы. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +def try_concatenate_pdf_files(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + if not pdf_editor.try_concatenate(files_to_merge, output_file): + print("Concatenation failed for the provided files.") +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md new file mode 100644 index 000000000..de077c590 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md @@ -0,0 +1,40 @@ +--- +title: Попробуйте объединить два PDF-файла +linktitle: Попробуйте объединить два PDF-файла +type: docs +weight: 90 +url: /python-net/try-concatenate-two-files/ +description: Объедините два PDF-файла с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Безопасно объединять два PDF-файла в Python без исключений +Abstract: Узнайте, как безопасно объединять два PDF-файла с помощью Aspose.PDF for Python. Метод try_concatenate объединяет файлы без выброса исключений, позволяя гибко обрабатывать ошибки в случае сбоя операции. +--- + +Объединение двух PDF-файлов иногда может завершаться неудачей из‑за повреждения файлов, несовместимых форматов или других проблем. При использовании Aspose.PDF for Python метод try_concatenate класса PdfFileEditor позволяет попытаться безопасно объединить два PDF‑файла. Если операция не удаётся, он возвращает False вместо исключения, предоставляя полный контроль над обработкой ошибок в автоматизированных рабочих процессах или пакетной обработке. + +1. Создайте объект PdfFileEditor. +1. Попытка объединить два PDF-файла. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) +from config import set_license, initialize_data_dir + + +def try_concatenate_two_files(files_to_merge, output_file): + # Create a PdfFileEditor object + pdf_editor = pdf_facades.PdfFileEditor() + if not pdf_editor.try_concatenate( + files_to_merge[0], files_to_merge[1], output_file + ): + print("Concatenation failed for the provided files.") +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md b/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md new file mode 100644 index 000000000..ec6f199d3 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md @@ -0,0 +1,23 @@ +--- +title: Разделить PDF документы +linktitle: Разделить PDF документы +type: docs +weight: 50 +url: /python-net/splitting-pdf-documents/ +description: Разделение PDF является типичной потребностью для управления документами, отчетности и автоматизации процессов. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Разделить PDF документы в Python — с начала, до конца или в отдельный файл +Abstract: Узнайте, как программно разбивать PDF‑документы с помощью Aspose.PDF for Python. Это руководство демонстрирует методы извлечения страниц с начала или с конца, разделения PDF на несколько документов или разбивки его на одностраничные PDF для гибкого управления документами. +--- + +Разделение PDF‑документов полезно, когда необходимо извлечь выбранные разделы, распределить отдельные страницы или разбить большие файлы на более мелкие единицы для хранения и обработки. Aspose.PDF for Python предоставляет несколько `PdfFileEditor` методов для эффективного решения этих сценариев. + +## Учебные руководства по разделению PDF + +- [Разделить PDF с начала](/pdf/ru/python-net/split-pdf-from-beginning/) +- [Разделить PDF до конца](/pdf/ru/python-net/split-pdf-to-end/) +- [Разделить PDF на отдельные страницы](/pdf/ru/python-net/split-pdf-into-single-pages/) diff --git a/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md b/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md new file mode 100644 index 000000000..444a83e59 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md @@ -0,0 +1,38 @@ +--- +title: Разделить PDF с начала +linktitle: Разделить PDF с начала +type: docs +weight: 10 +url: /python-net/split-pdf-from-beginning/ +description: Разделите документ PDF с начала, используя Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Разделить PDF с начала в Python с использованием Aspose.PDF +Abstract: Узнайте, как разделить документ PDF с начала, используя Aspose.PDF for Python. Этот пример демонстрирует извлечение определённого количества страниц, начиная с первой, для создания нового PDF‑документа. +--- + +Разделение PDF‑файлов с начала полезно, когда вам нужны первые несколько страниц документа как отдельный файл. С использованием Aspose.PDF for Python метод split_from_first в [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) классе позволяет извлекать заданное количество страниц, начиная с первой. Эта функция идеальна для создания отрывков, предварительных просмотров или меньших разделов большого PDF без ручного редактирования исходного файла. + +1. Создайте объект PdfFileEditor. +1. Разделите PDF с первой страницы. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Split PDF from Beginning +def split_pdf_from_beginning(input_pdf_path, output_pdf_path): + pdf_file_editor = pdf_facades.PdfFileEditor() + pdf_file_editor.split_from_first(input_pdf_path, 3, output_pdf_path) +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md b/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md new file mode 100644 index 000000000..687ccabce --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md @@ -0,0 +1,38 @@ +--- +title: Разделить PDF на отдельные страницы +linktitle: Разделить PDF на отдельные страницы +type: docs +weight: 30 +url: /python-net/split-pdf-into-single-pages/ +description: Разделить документ PDF на отдельные одностраничные PDF с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Разделить PDF на отдельные страницы в Python +Abstract: Узнайте, как разделить документ PDF на отдельные одностраничные PDF с помощью Aspose.PDF for Python. Этот метод извлекает каждую страницу из оригинального PDF и сохраняет её в отдельный файл для гибкого управления документами и обработки. +--- + +Разделение PDF на отдельные страницы полезно для обработки на уровне страниц, печати или распределения разделов документа по отдельности. Используя Aspose.PDF for Python, метод 'split_to_pages' класса [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) создаёт отдельные PDF‑файлы для каждой страницы исходного документа. Такой подход позволяет автоматически извлекать страницы для архивирования, рецензирования или индивидуального распространения, сохраняя оригинальное расположение и содержание. + +1. Создайте объект PdfFileEditor. +1. Разделите PDF на отдельные страницы. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Split PDF into Single Pages +def split_pdf_into_single_pages(input_pdf_path, output_pdf_path): + pdf_file_editor = pdf_facades.PdfFileEditor() + pdf_file_editor.split_to_pages(input_pdf_path, output_pdf_path) +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md b/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md new file mode 100644 index 000000000..3b6c0f22f --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md @@ -0,0 +1,38 @@ +--- +title: Разделить PDF до конца +linktitle: Разделить PDF до конца +type: docs +weight: 40 +url: /python-net/split-pdf-to-end/ +description: Разделить документ PDF, начиная с указанной страницы и до последней страницы, используя Aspose.PDF for Python. +lastmod: "2026-03-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Разделить PDF с определённой страницы до конца на Python +Abstract: Узнайте, как разделить документ PDF, начиная с указанной страницы и до последней, используя Aspose.PDF for Python. Этот пример демонстрирует извлечение всех страниц, начиная с заданной, для создания нового файла PDF. +--- + +Разделение PDF с определённой страницы до конца полезно, когда вам нужна последняя часть документа как отдельный файл. Используя Aspose.PDF for Python, метод split_to_end класса [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) позволяет извлекать страницы, начиная с любого номера страницы, до последней страницы документа. Это идеально подходит для создания отрывков, извлечения глав или обработки частей большого PDF без ручного редактирования. + +1. Создайте объект PdfFileEditor. +1. Разделите PDF с определённой страницы до конца. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Split PDF to End +def split_pdf_to_end(input_pdf_path, output_pdf_path): + pdf_file_editor = pdf_facades.PdfFileEditor() + pdf_file_editor.split_to_end(input_pdf_path, 2, output_pdf_path) +``` diff --git a/ru/python-net/working-with-facades/pdffileinfo/_index.md b/ru/python-net/working-with-facades/pdffileinfo/_index.md new file mode 100644 index 000000000..3ab240cab --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileinfo/_index.md @@ -0,0 +1,26 @@ +--- +title: Класс PdfFileInfo +linktitle: Класс PdfFileInfo +type: docs +weight: 110 +url: /python-net/pdffileinfo-class/ +description: Узнайте, как использовать класс PdfFileInfo в Aspose.PDF for Python via .NET для проверки метаданных PDF, свойств документа, привилегий, деталей версии и информации о страницах. +lastmod: "2026-03-19" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Проверьте метаданные PDF, свойства и информацию о страницах в Python с помощью PdfFileInfo +Abstract: В этом разделе объясняется, как использовать класс PdfFileInfo в Aspose.PDF for Python via .NET для программной проверки деталей PDF‑файла. Узнайте, как работать с метаданными PDF, свойствами документа, привилегиями, информацией о версии и данными уровня страниц в приложениях на Python. +--- + +`PdfFileInfo` Класс в Aspose.PDF Facades предоставляет доступ к информации уровня документа и уровня страницы PDF без необходимости низкоуровневого парсинга. Он полезен, когда требуется проверять метаданные, получать свойства документа, проверять привилегии или изучать размеры страниц и смещения в автоматических рабочих процессах. + +## Что вы можете сделать с PdfFileInfo + +Используйте статьи в этом разделе, чтобы исследовать основные возможности инспекции файлов `PdfFileInfo` фасад: + +- [Управляйте метаданными PDF с помощью PdfFileInfo](/pdf/ru/python-net/pdf-metadata/) +- [Проверьте свойства документа с помощью PdfFileInfo](/pdf/ru/python-net/document-properties/) +- [Получите информацию о страницах с помощью PdfFileInfo](/pdf/ru/python-net/page-information/) diff --git a/ru/python-net/working-with-facades/pdffileinfo/document-properties/_index.md b/ru/python-net/working-with-facades/pdffileinfo/document-properties/_index.md new file mode 100644 index 000000000..8c5997a6c --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileinfo/document-properties/_index.md @@ -0,0 +1,19 @@ +--- +title: Свойства документа +linktitle: Свойства документа +type: docs +weight: 10 +url: /python-net/document-properties/ +description: Узнайте, как программно получать метаданные PDF с помощью Aspose.PDF for Python. Это руководство охватывает получение версии PDF и проверку привилегий документа, включая разрешения на печать, копирование, изменение и заполнение форм. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Получить версию PDF и привилегии документа с помощью Aspose.PDF for Python +Abstract: Понимание метаданных PDF имеет решающее значение для обработки, соответствия требованиям и автоматизации рабочих процессов. Номера версий PDF указывают поддерживаемые функции и совместимость, тогда как привилегии документа контролируют действия, такие как печать, копирование содержимого, изменение аннотаций или заполнение полей формы. Эта статья демонстрирует, как использовать класс PdfFileInfo в Aspose.PDF for Python. +--- + +- [Получить версию PDF](/pdf/ru/python-net/get-pdf-version/) +- [Получить привилегии документа](/pdf/ru/python-net/get-document-privileges/) \ No newline at end of file diff --git a/ru/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md b/ru/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md new file mode 100644 index 000000000..ecae0ecb5 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md @@ -0,0 +1,60 @@ +--- +title: Получить привилегии документа +linktitle: Получить привилегии документа +type: docs +weight: 10 +url: /python-net/get-document-privileges/ +description: Узнайте, как программно проверять привилегии PDF‑документа с помощью Aspose.PDF for Python. Этот учебный материал демонстрирует, как использовать класс PdfFileInfo для чтения настроек безопасности документа, таких как печать, копирование или изменение разрешений. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Получить привилегии PDF‑документа с помощью Aspose.PDF for Python +Abstract: PDF‑документы могут иметь ограничения безопасности, ограничивающие такие действия, как печать, копирование, изменение или заполнение форм. Получая эти привилегии программно, разработчики могут определить, какие операции разрешены для PDF. В этом руководстве показано, как использовать класс PdfFileInfo для получения привилегий документа PDF и их отображения в Python. +--- + +Привилегии PDF определяют, что пользователи могут и чего не могут делать с документом. Общие разрешения включают: + +- Печать документа +- Копирование контента +- Изменение аннотаций или содержимого +- Заполнение полей формы +- Использование скринридеров +- Сборка или объединение документов + +С помощью Aspose.PDF for Python вы можете программно проверять эти настройки, используя [PdfFileInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileinfo/) класс. Это особенно полезно при работе с несколькими PDF в автоматизированных рабочих процессах, проверке соответствия или управлении обработкой документов в приложениях. + +1. Загрузите PDF-файл. +1. Получите права доступа к документу. +1. Отобразите, какие действия разрешены для документа. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def get_document_privileges(input_file_name): + pdf_metadata = pdf_facades.PdfFileInfo(input_file_name) + + privileges = pdf_metadata.get_document_privilege() + + print("Document Privileges:") + print(f" Can Print: {privileges.allow_print}") + print(f" Can Degraded Print: {privileges.allow_degraded_printing}") + print(f" Can Copy: {privileges.allow_copy}") + print(f" Can Modify Contents: {privileges.allow_modify_contents}") + print(f" Can Modify Annotations: {privileges.allow_modify_annotations}") + print(f" Can Fill In: {privileges.allow_fill_in}") + print(f" Can Screen Readers: {privileges.allow_screen_readers}") + print(f" Can Assembly: {privileges.allow_assembly}") +``` diff --git a/ru/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md b/ru/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md new file mode 100644 index 000000000..356b3fa1b --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md @@ -0,0 +1,44 @@ +--- +title: Получить версию PDF +linktitle: Получить версию PDF +type: docs +weight: 20 +url: /python-net/get-pdf-version/ +description: Узнайте, как программно определить версию PDF‑документа с помощью Aspose.PDF for Python. Этот учебник демонстрирует, как использовать класс PdfFileInfo для проверки версии PDF файла. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Получить версию PDF с помощью Aspose.PDF for Python +Abstract: PDF‑документы имеют номера версий, которые указывают на поддерживаемые функции и спецификации (например, 1.4, 1.7, 2.0). Знание версии PDF важно для совместимости, поддержки функций и процессов обработки документов. В этом руководстве вы узнаете, как программно получить версию PDF с помощью класса PdfFileInfo в Aspose.PDF for Python. +--- + +Версии PDF определяют функции и возможности, поддерживаемые в документе, включая поля формы, шифрование, аннотации и сжатие. Для разработчиков, работающих с несколькими PDF‑файлами, проверка версии обеспечивает совместимость с инструментами, библиотеками или процессами, которые обрабатывают эти файлы. + +С помощью Aspose.PDF for Python вы можете легко проверить версию PDF с помощью [PdfFileInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileinfo/) класса. + +1. Загрузите PDF-документ. +1. Получите версию PDF. +1. Отобразите версию в консоли. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def get_pdf_version(input_file_name): + + pdf_metadata = pdf_facades.PdfFileInfo(input_file_name) + version = pdf_metadata.get_pdf_version() + print(f"\nPDF Version: {version}") +``` diff --git a/ru/python-net/working-with-facades/pdffileinfo/page-information/_index.md b/ru/python-net/working-with-facades/pdffileinfo/page-information/_index.md new file mode 100644 index 000000000..17f005ed4 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileinfo/page-information/_index.md @@ -0,0 +1,19 @@ +--- +title: Информация о странице +linktitle: Информация о странице +type: docs +weight: 20 +url: /python-net/page-information/ +description: В этой статье объясняется, как извлечь ключевые сведения о макете и позиционировании из PDF‑страниц с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Получить информацию о PDF‑странице в Python с помощью Aspose.PDF +Abstract: PDF‑страницы могут различаться по размеру, повороту и внутреннему позиционированию содержимого. Функции Get Page Information и Get Page Offset предоставляют разработчикам полный обзор макета каждой страницы. Get Page Information возвращает ширину, высоту и угол поворота страницы, в то время как Get Page Offset извлекает смещения X и Y в дюймах. Вместе эти методы позволяют точно выравнивать текст, изображения, аннотации и другое содержимое, поддерживая как одностраничные, так и многостраничные автоматизированные рабочие процессы. +--- + +- [Получить информацию о странице](/pdf/ru/python-net/get-page-info/) +- [Получить смещение страницы](/pdf/ru/python-net/get-page-offset/) diff --git a/ru/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md b/ru/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md new file mode 100644 index 000000000..036fce700 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md @@ -0,0 +1,51 @@ +--- +title: Получить информацию о странице +linktitle: Получить информацию о странице +type: docs +weight: 10 +url: /python-net/get-page-info/ +description: Узнайте, как программно получать информацию о странице в PDF с помощью Aspose.PDF for Python. В этом руководстве показывается, как получить ширину, высоту, поворот и смещения конкретной страницы в PDF‑документе. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Получение информации о странице PDF с помощью Aspose.PDF for Python +Abstract: Функция извлекает ширину, высоту, угол поворота и горизонтальные (X) и вертикальные (Y) смещения страницы PDF. Эти свойства возвращаются в пунктах и отражают физический размер страницы и позиционирование содержимого внутри PDF. Функция выводит полученные значения, позволяя разработчикам понять раскладку и ориентацию страницы для дальнейшей обработки PDF. +--- + +Утилитная функция ‘get_page_information’ помогает разработчикам понять структуру и раскладку страниц PDF. Каждая страница PDF может иметь разные размеры, поворот и внутренние смещения, которые могут влиять на размещение содержимого или задачи автоматизации. + +Она позволяет извлекать ключевые метаданные и информацию о раскладке конкретной страницы в PDF‑файле. API Aspose.PDF Facades предоставляет детали, такие как ширина, высота, поворот страницы и смещения X/Y. Эта информация важна для задач, таких как анализ раскладки страниц, размещение аннотаций или автоматизированная обработка PDF. + +1. Создайте объект фасада PDF. +1. Получите размеры страницы и её разметку. +1. Выведите или сохраните полученные значения. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def get_page_information(infile): + + # Get and display PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + page_width = pdf_info.get_page_width(1) + page_height = pdf_info.get_page_height(1) + page_rotation = pdf_info.get_page_rotation(1) + page_x_offset = pdf_info.get_page_x_offset(1) + page_y_offset = pdf_info.get_page_y_offset(1) + + print(f"Page Width: {page_width}") + print(f"Page Height: {page_height}") + print(f"Page Rotation: {page_rotation}") +``` diff --git a/ru/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md b/ru/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md new file mode 100644 index 000000000..6dc73a73f --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md @@ -0,0 +1,46 @@ +--- +title: Получить смещение страницы +linktitle: Получить смещение страницы +type: docs +weight: 20 +url: /python-net/get-page-offset/ +description: Этот пример демонстрирует, как использовать PdfFileInfo для получения смещений по осям X и Y конкретной страницы и преобразования их в дюймы для точного анализа макета и позиционирования. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Получить смещения страниц PDF с помощью Python +Abstract: Функция 'get_page_offsets' извлекает горизонтальные (X) и вертикальные (Y) смещения каждой страницы в PDF‑файле. Эти смещения представляют позицию содержимого страницы относительно начала PDF. Преобразуя пункты в дюймы, функция предоставляет точные, легко читаемые измерения, которые могут быть использованы для точного размещения аннотаций, изображений или текста. Она поддерживает многостраничные PDF и предназначена для разработчиков, работающих над макетом PDF, автоматизацией или выравниванием контента. +--- + +Функция 'get_page_offsets' предоставляет разработчикам точные горизонтальные (X) и вертикальные (Y) смещения страниц в PDF‑файле. В PDF‑документах каждая страница может иметь внутреннюю точку начала, отличающуюся от верхнего левого угла страницы, что может влиять на позиционирование текста, изображений, аннотаций или другого содержимого. + +Используя Aspose.PDF Facades, эта функция извлекает эти смещения в пунктах и преобразует их в дюймы для удобного восприятия. Она поддерживает многостраничные PDF, что делает её подходящей для автоматизированных рабочих процессов, требующих точного размещения контента. + +1. Создайте объект фасада PDF. +1. Получите количество страниц в PDF. +1. Пройдите по каждой странице, чтобы получить смещения. +1. Выведите или сохраните смещения. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def get_page_offsets(infile): + # Get and display PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + page_x_offset = pdf_info.get_page_x_offset(1) / 72.0 + page_y_offset = pdf_info.get_page_y_offset(1) / 72.0 + print(f"Page X Offset: {page_x_offset} inches") + print(f"Page Y Offset: {page_y_offset} inches") +``` diff --git a/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md new file mode 100644 index 000000000..4a69ac947 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md @@ -0,0 +1,21 @@ +--- +title: Метаданные PDF +linktitle: Метаданные PDF +type: docs +weight: 30 +url: /python-net/pdf-metadata/ +description: В этой статье объясняется, как получить доступ к метаданным, изменять их и сохранять в PDF‑документах с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Управление метаданными PDF в Python +Abstract: Метаданные PDF содержат информацию о документе, такую как заголовок, автор, ключевые слова и дата создания, что помогает в каталогизации, поиске и поддержании целостности документа. С помощью Aspose.PDF разработчики могут программно выполнить - Get PDF Metadata, Set PDF Metadata values, Clear PDF Metadata и сохранять изменения либо в стандартных метаданных PDF, либо в формате XMP. Этот всесторонний подход обеспечивает точный контроль над свойствами документа и гарантирует согласованную обработку в рамках рабочих процессов и приложений. +--- + +- [Получить метаданные PDF](/pdf/ru/python-net/get-pdf-metadata/) +- [Установить метаданные PDF](/pdf/ru/python-net/set-pdf-metadata/) +- [Очистить метаданные PDF](/pdf/ru/python-net/clear-pdf-metadata/) +- [Сохранить метаданные с помощью XMP](/pdf/ru/python-net/save-metadata-with-xmp/) diff --git a/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md new file mode 100644 index 000000000..9ed61ff90 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md @@ -0,0 +1,47 @@ +--- +title: Очистить метаданные PDF +linktitle: Очистить метаданные PDF +type: docs +weight: 10 +url: /python-net/clear-pdf-metadata/ +description: Удалите все метаданные из PDF‑документа с помощью Aspose.PDF for Python via .NET. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Очистка метаданных PDF с использованием Aspose.PDF for Python +Abstract: В этом руководстве объясняется, как удалить все метаданные из PDF‑документа с помощью Aspose.PDF for Python via .NET. Вы научитесь очищать как стандартные, так и пользовательские поля метаданных и сохранять очищенный PDF. Это полезно для обеспечения конфиденциальности, безопасности или подготовки PDF‑файлов к публичному выпуску. +--- + +PDF часто содержат метаданные, такие как заголовок, автор, ключевые слова, даты создания и пользовательские поля. В некоторых сценариях вы можете захотеть удалить все метаданные из PDF, например перед распространением или архивированием. Aspose.PDF предоставляет метод clear_info() для простого удаления всех метаданных. После очистки вы можете сохранить PDF, используя метод save(). + +1. Загрузите PDF‑файл. +1. Очистите все метаданные. +1. Сохраните чистый PDF. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def clear_pdf_metadata(infile, outfile): + + # Get PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + + # Clear PDF metadata + pdf_info.clear_info() + + # Save updated metadata + pdf_info.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md new file mode 100644 index 000000000..13f555dcb --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md @@ -0,0 +1,59 @@ +--- +title: Получить метаданные PDF +linktitle: Получить метаданные PDF +type: docs +weight: 20 +url: /python-net/get-pdf-metadata/ +description: Извлекать и отображать метаданные из PDF‑документов с помощью Aspose.PDF for Python. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Получение метаданных PDF с использованием Aspose.PDF for Python. +Abstract: В этом руководстве демонстрируется, как извлекать и отображать метаданные из PDF‑документов с помощью Aspose.PDF for Python. Вы узнаете, как получать доступ к стандартным свойствам PDF, таким как заголовок, автор, ключевые слова, даты создания/изменения, а также к пользовательским полям метаданных. Кроме того, руководство охватывает проверки действительности PDF, шифрования и статуса портфеля. +--- + +PDF‑документы часто содержат ценные метаданные, описывающие содержание документа, авторство и права доступа. Aspose.PDF предоставляет удобный API для получения как стандартных, так и пользовательских свойств метаданных. Этот фрагмент кода показывает, как использовать [PdfFileInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileinfo/) класс для программного анализа PDF‑файлов, включая пошаговые примеры на Python. + +1. Загрузите PDF‑файл. +1. Получите стандартные метаданные. +1. Проверьте статус PDF и безопасность. +1. Получите пользовательские метаданные. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def get_pdf_metadata(infile): + + # Get and display PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + print(f"Subject: {pdf_info.subject}") + print(f"Title: {pdf_info.title}") + print(f"Keywords: {pdf_info.keywords}") + print(f"Creator: {pdf_info.creator}") + print(f"Creation Date: {pdf_info.creation_date}") + print(f"Modification Date: {pdf_info.mod_date}") + + # Check PDF status + print(f"Is Valid PDF: {pdf_info.is_pdf_file}") + print(f"Is Encrypted: {pdf_info.is_encrypted}") + print(f"Has Open Password: {pdf_info.has_open_password}") + print(f"Has Edit Password: {pdf_info.has_edit_password}") + print(f"Is Portfolio: {pdf_info.has_collection}") + + # Retrieve and display a specific custom attribute + reviewer = pdf_info.get_meta_info("Reviewer") + print(f"Reviewer: {reviewer if reviewer else 'No Reviewer metadata found.'}") +``` diff --git a/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md new file mode 100644 index 000000000..be28f4b4f --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md @@ -0,0 +1,50 @@ +--- +title: Сохранить метаданные с помощью XMP +linktitle: Сохранить метаданные с помощью XMP +type: docs +weight: 30 +url: /python-net/save-metadata-with-xmp/ +description: Сохранить метаданные PDF, используя XMP с Aspose.PDF for Python via .NET +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Сохранение метаданных PDF с XMP с помощью Aspose.PDF for Python +Abstract: Это руководство демонстрирует, как сохранить метаданные PDF, используя XMP (Extensible Metadata Platform) с Aspose.PDF for Python via .NET. XMP гарантирует, что как стандартные, так и пользовательские метаданные встраиваются в стандартизированный формат XML внутри PDF, улучшая совместимость между приложениями и рабочими процессами. +--- + +Метаданные PDF могут храниться разными способами, и XMP является современным стандартизированным методом встраивания метаданных в файл PDF. Используя Aspose.PDF, вы можете обновлять стандартные поля, такие как Title, Subject, Keywords и Creator, а затем сохранять их в формате XMP, чтобы обеспечить более широкую совместимость и будущую защиту. Этот метод рекомендуется вместо устаревших способов хранения метаданных. + +1. Загрузите PDF‑файл. +1. Установите стандартные поля метаданных. +1. Сохраните метаданные в формате XMP. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def save_info_with_xmp(infile, outfile): + + # Get PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + + # Set PDF metadata + pdf_info.subject = "Aspose PDF for Python via .NET" + pdf_info.title = "Aspose PDF for Python via .NET" + pdf_info.keywords = "Aspose, PDF, Python, .NET" + pdf_info.creator = "Aspose Team" + + # Save updated metadata + pdf_info.save_new_info_with_xmp(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md new file mode 100644 index 000000000..03f702dac --- /dev/null +++ b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md @@ -0,0 +1,56 @@ +--- +title: Установить метаданные PDF +linktitle: Установить метаданные PDF +type: docs +weight: 50 +url: /python-net/set-pdf-metadata/ +description: Изменять и сохранять метаданные в PDF‑документах с помощью Aspose.PDF for Python via .NET. +lastmod: "2026-03-05" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Обновление метаданных PDF с использованием Aspose.PDF for Python +Abstract: Это руководство объясняет, как изменять и сохранять метаданные в PDF‑документах с помощью Aspose.PDF for Python via .NET. В нём демонстрируется, как обновлять стандартные свойства PDF, такие как название, тема, ключевые слова и создатель, а также пользовательские поля метаданных. По завершении вы сможете программно обновлять метаданные PDF и сохранять внесённые изменения. +--- + +PDF‑документы могут содержать как стандартные метаданные (Title, Subject, Keywords, Creator, Author), так и пользовательские метаданные, сохранённые как свойства XMP. Aspose.PDF предоставляет простой API для изменения этих свойств в Python. Это руководство охватывает обновление этих полей и сохранение изменённого PDF‑файла с использованием [PdfFileInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileinfo/) класса. + +1. Загрузите PDF‑файл. +1. Обновите стандартные метаданные. +1. Добавьте или обновите пользовательские метаданные. +1. Сохраните обновленные метаданные. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +from io import FileIO + +import sys +from os import path + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +def set_pdf_metadata(infile, outfile): + + # Get PDF information + pdf_info = pdf_facades.PdfFileInfo(infile) + + # Set PDF metadata + pdf_info.subject = "Aspose PDF for Python via .NET" + pdf_info.title = "Aspose PDF for Python via .NET" + pdf_info.keywords = "Aspose, PDF, Python, .NET" + pdf_info.creator = "Aspose Team" + + pdf_info.set_meta_info("CustomKey", "CustomValue") + + # pdf_info.save_new_info(outfile) + # Is obsolete, use save() method instead + + # Save updated metadata + pdf_info.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdffilesecurity/_index.md b/ru/python-net/working-with-facades/pdffilesecurity/_index.md new file mode 100644 index 000000000..524a8bc91 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilesecurity/_index.md @@ -0,0 +1,26 @@ +--- +title: Класс PdfFileSecurity +linktitle: Класс PdfFileSecurity +type: docs +weight: 125 +url: /python-net/pdffilesecurity-class/ +description: Узнайте, как использовать класс PdfFileSecurity в Aspose.PDF for Python via .NET для шифрования и дешифрования PDF, изменения паролей и управления привилегиями документа. +lastmod: "2026-03-18" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Шифруйте, дешифруйте и управляйте разрешениями PDF в Python с помощью PdfFileSecurity +Abstract: В этом разделе объясняется, как использовать класс PdfFileSecurity в Aspose.PDF for Python via .NET для программного обеспечения защиты PDF‑документов. Узнайте, как шифровать и дешифровать файлы PDF, менять пароли и настраивать привилегии и разрешения документов в приложениях на Python. +--- + +Этот `PdfFileSecurity` класс в Aspose.PDF Facades используется для защиты PDF‑документов и управления тем, как пользователи взаимодействуют с ними. Он поддерживает общие сценарии безопасности, такие как шифрование на основе пароля, дешифрование, ротация паролей и управление разрешениями для печати, копирования и редактирования. + +## Что вы можете сделать с PdfFileSecurity + +Используйте статьи в этом разделе, чтобы изучить основные задачи безопасности PDF, поддерживаемые `PdfFileSecurity` фасад: + +- [Шифрование PDF-файлов с помощью PdfFileSecurity](/pdf/ru/python-net/encrypt-pdf-file/) +- [Расшифровка PDF-файлов с помощью PdfFileSecurity](/pdf/ru/python-net/decrypt-pdf-file/) +- [Изменение паролей PDF с помощью PdfFileSecurity](/pdf/ru/python-net/change-password/) +- [Установка привилегий PDF с помощью PdfFileSecurity](/pdf/ru/python-net/set-privileges/) diff --git a/ru/python-net/working-with-facades/pdffilesecurity/change-password/_index.md b/ru/python-net/working-with-facades/pdffilesecurity/change-password/_index.md new file mode 100644 index 000000000..ad9b56de2 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilesecurity/change-password/_index.md @@ -0,0 +1,155 @@ +--- +title: Изменить пароль PDF‑файла +linktitle: Изменить пароль PDF‑файла +type: docs +weight: 10 +url: /python-net/change-password/ +description: Изменить пользовательский и владелецский пароли защищённого PDF‑документа с помощью Aspose.PDF for Python via .NET. +lastmod: "2026-03-18" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Обновить пароли PDF +Abstract: Узнайте, как изменить как пользовательский, так и пароль владельца в защищённом PDF‑файле с помощью Aspose.PDF for Python via .NET. Этот пример демонстрирует, как безопасно обновить учётные данные доступа, сохраняя существующее шифрование и разрешения нетронутыми. +--- + +## Изменить пароль пользователя и владельца + +Во многих случаях вам может потребоваться обновить пароли защищённого PDF без изменения текущих настроек безопасности. Это может быть полезно при смене учетных данных, передаче прав собственности или повышении безопасности документа. + +Метод 'change_password' класса [PdfFileSecurity](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesecurity/) класс позволяет: + +- Обновить пароль пользователя (необходим для открытия документа) +- Обновить пароль владельца (используется для управления правами) +- Сохранить текущие настройки шифрования и прав + +1. Создайте объект 'PdfFileSecurity'. +1. Привяжите входной PDF. +1. Измените пароли с помощью метода 'change_password()'. +1. Сохраните обновлённый PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Change User and Owner Password +def change_user_and_owner_password(infile, outfile): + """Change user and owner passwords while keeping existing security settings.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Change passwords + file_security.change_password( + "owner_password", "new_user_password", "new_owner_password" + ) + + # Save updated PDF + file_security.save(outfile) +``` + +## Изменить пароль и сбросить безопасность + +При работе с защищёнными PDF‑документами простая смена паролей может быть недостаточной. Возможно, также потребуется изменить разрешения, такие как печать, копирование или права на редактирование. + +Узнайте, как обновить пользовательский и владелецкий пароли, одновременно сбрасывая параметры безопасности PDF с помощью Aspose.PDF for Python via .NET. Этот пример показывает, как переопределить разрешения документа и уровень шифрования вместе с новыми учётными данными доступа. + +1. Создайте объект 'PdfFileSecurity'. +1. Привяжите входной PDF. +1. Создайте объект 'DocumentPrivilege' и настройте разрешённые действия. +1. Смените пароли и сбросьте безопасность. +1. Сохраните обновлённый PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Change Password and Reset Security +def change_password_and_reset_security(infile, outfile): + """Change passwords and reset document security settings.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define new privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + + # Change passwords and reset security + file_security.change_password( + "owner_password", + "new_user_password", + "new_owner_password", + privilege, + pdf_facades.KeySize.X128, + ) + + # Save updated PDF + file_security.save(outfile) +``` + +## Попробовать изменить пароль без исключения + +В некоторых рабочих процессах, особенно при пакетной обработке или в автоматизированных системах, важно избегать исключений, которые могут прервать выполнение. Вместо выбрасывания ошибок вы можете предпочесть безопасную операцию, которая сообщает об успехе или неудаче. + +Метод 'try_change_password' [PdfFileSecurity](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesecurity/) класс предоставляет эту функциональность следующим образом: + +1. Создайте объект 'PdfFileSecurity'. +1. Загрузите PDF‑документ, используя метод 'bind_pdf()'. +1. Попытка изменить пароли. +1. Проверьте результат. +1. Сохраните обновлённый PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Try Change Password Without Exception +def try_change_password_without_exception(infile, outfile): + """Attempt to change passwords without throwing an exception on failure.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Attempt to change passwords + result = file_security.try_change_password( + "owner_password", "new_user_password", "new_owner_password" + ) + + # Save only if operation succeeded + if result: + file_security.save(outfile) + else: + print("Password change failed. Check owner password or document security.") +``` diff --git a/ru/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md b/ru/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md new file mode 100644 index 000000000..f2c5f5de7 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md @@ -0,0 +1,92 @@ +--- +title: Расшифровать PDF-файл +linktitle: Расшифровать PDF-файл +type: docs +weight: 20 +url: /python-net/decrypt-pdf-file/ +description: Это руководство объясняет, как удалить ограничения, такие как печать, копирование и редактирование, чтобы получить полный доступ к вашему PDF‑документу. +lastmod: "2026-03-18" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Удалить защиту паролем из PDF +Abstract: В этой статье демонстрируется, как расшифровать PDF‑файл с помощью пароля владельца. Описывается процесс удаления ограничений безопасности, которые ограничивают такие действия, как печать, редактирование или копирование содержимого. При вводе правильного пароля владельца пользователи могут разблокировать документ и восстановить полный контроль над его функциями. +--- + +## Расшифровать PDF с паролем владельца + +Расшифровать защищённый паролем PDF‑документ, используя пароль владельца с Aspose.PDF for Python via .NET. Эта операция удаляет шифрование и обеспечивает неограниченный доступ к документу. + +1. Создайте объект 'PdfFileSecurity'. +1. Загрузите зашифрованный PDF, используя метод 'bind_pdf()'. +1. Расшифруйте Document. +1. Сохраните расшифрованный PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Decrypt PDF with Owner Password +def decrypt_pdf_with_owner_password(infile, outfile): + """Decrypt a PDF document using the owner password.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Decrypt the PDF + file_security.decrypt_file("owner_password") + + # Save decrypted PDF + file_security.save(outfile) +``` + +## Попробуйте расшифровать PDF без исключения + +PDF‑документы часто защищаются паролями, чтобы ограничить доступ и использование. Чтобы полностью получить доступ к таким документам или изменить их, может потребоваться удалить шифрование. Расшифруйте защищённый PDF‑документ, используя пароль владельца, чтобы удалить шифрование и ограничения доступа, с помощью Aspose.PDF for Python via .NET. + +1. Создайте объект 'PdfFileSecurity'. +1. Привяжите входной PDF. +1. Расшифровать PDF. +1. Сохранить выходной PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Try Decrypt PDF Without Exception +def try_decrypt_pdf_without_exception(infile, outfile): + """Attempt to decrypt a PDF without throwing an exception on failure.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Attempt to decrypt the PDF + result = file_security.try_decrypt_file("owner_password") + + # Save only if decryption was successful + if result: + file_security.save(outfile) + else: + print("Decryption failed. Check password or document security.") +``` diff --git a/ru/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md b/ru/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md new file mode 100644 index 000000000..077dfd075 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md @@ -0,0 +1,152 @@ +--- +title: Зашифровать PDF-файл +linktitle: Зашифровать PDF-файл +type: docs +weight: 30 +url: /python-net/encrypt-pdf-file/ +description: Зашифровать PDF-документ и настроить разрешения, чтобы контролировать, что пользователи могут делать с файлом. +lastmod: "2026-03-18" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Зашифровать PDF и управлять действиями пользователей +Abstract: Узнайте, как зашифровать PDF, определяя конкретные разрешения пользователей с помощью Aspose.PDF for Python via .NET. Это руководство показывает, как разрешать или ограничивать действия, такие как печать и копирование, при сохранении безопасности документа. +--- + +## Зашифровать PDF с паролем пользователя и паролем владельца + +Защита PDF‑документов важна при обмене конфиденциальным или ограниченным содержимым. Шифрование позволяет защитить документ паролями и определить, какие действия разрешено выполнять пользователям. Этот фрагмент кода показывает, как применить пароли пользователя и владельца вместе с правами доступа для защиты PDF‑файла. + +1. Создайте объект PdfFileSecurity. +1. Привяжите входной PDF. +1. Определите привилегии документа. +1. Зашифруйте PDF. +1. Сохраните зашифрованный PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Encrypt PDF with User and Owner Password +def encrypt_pdf_with_user_owner_password(infile, outfile): + """Encrypt a PDF document using user and owner passwords.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define document privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + + # Encrypt the PDF + file_security.encrypt_file( + "user_password", "owner_password", privilege, pdf_facades.KeySize.X128 + ) + + # Save encrypted PDF + file_security.save(outfile) +``` + +## Зашифровать PDF с разрешениями + +Следующий фрагмент кода объясняет, как разрешить выбранные действия, такие как печать и копирование, ограничивая остальные. + +1. Инициализировать [PdfFileSecurity](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesecurity/) класс. +1. Привязать входной PDF. +1. Настройте привилегии документа. +1. Вызовите метод 'encrypt_file()'. +1. Сохранить зашифрованный PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Encrypt PDF with Permissions +def encrypt_pdf_with_permissions(infile, outfile): + """Encrypt a PDF document and configure specific permissions.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Configure privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + privilege.allow_copy = True + + # Encrypt the PDF + file_security.encrypt_file( + "user_password", "owner_password", privilege, pdf_facades.KeySize.X128 + ) + + # Save encrypted PDF + file_security.save(outfile) +``` + +## Зашифровать PDF с помощью алгоритма шифрования + +Шифрование PDF не только защищает документы паролями, но и позволяет выбирать алгоритм шифрования и его стойкость. Выбор подходящего алгоритма обеспечивает более высокий уровень безопасности конфиденциальных документов. + +1. Создать объект PdfFileSecurity. +1. Привязать входной PDF. +1. Определить привилегии документа. +1. Зашифровать PDF с помощью алгоритма. +1. Сохранить зашифрованный PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Encrypt PDF with Encryption Algorithm +def encrypt_pdf_with_encryption_algorithm(infile, outfile): + """Encrypt a PDF document using a specific encryption algorithm.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + + # Encrypt the PDF using AES algorithm + file_security.encrypt_file( + "user_password", + "owner_password", + privilege, + pdf_facades.KeySize.X256, + pdf_facades.Algorithm.AES, + ) + + # Save encrypted PDF + file_security.save(outfile) +``` diff --git a/ru/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md b/ru/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md new file mode 100644 index 000000000..49991fe26 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md @@ -0,0 +1,148 @@ +--- +title: Установить привилегии для существующего PDF‑файла +linktitle: Установить привилегии для существующего PDF‑файла +type: docs +weight: 40 +url: /python-net/set-privileges/ +description: Установите и управляйте привилегиями PDF‑документа, чтобы контролировать действия пользователей, такие как печать, копирование и редактирование. +lastmod: "2026-03-18" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Управление разрешениями PDF и контролем доступа +Abstract: Узнайте, как контролировать действия пользователей с PDF, устанавливая привилегии документа с помощью Aspose.PDF for Python via .NET. Это руководство охватывает применение разрешений с паролем или без него для ограничения таких действий, как печать, копирование или редактирование. +--- + +## Установить привилегии PDF без паролей + +Посмотрите, как применить привилегии к документу PDF без указания паролей пользователя или владельца, используя Aspose.PDF for Python via .NET. Этот фрагмент кода демонстрирует, как контролировать разрешённые действия, сохраняя документ доступным. + +1. Создайте объект 'PdfFileSecurity'. +1. Привяжите входной PDF. +1. Определите привилегии документа. +1. Вызовите метод 'set_privilege()' без передачи паролей. +1. Сохраните обновлённый PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Set PDF Privileges Without Passwords +def set_pdf_privileges_without_passwords(infile, outfile): + """Set PDF privileges without specifying user and owner passwords.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + + # Apply privileges (owner password will be generated automatically) + file_security.set_privilege(privilege) + + # Save updated PDF + file_security.save(outfile) +``` + +## Установить привилегии PDF с паролями пользователя и владельца + +Для полной защиты PDF‑документа часто требуется как контроль доступа (пароли), так и ограничения использования (разрешения). Объединив их, вы можете гарантировать, что только уполномоченные пользователи смогут открыть документ и выполнить определённые действия. + +Используя метод set_privilege с параметрами пароля, вы можете: + +- Защитите документ пользовательским паролем +- Задайте пароль владельца для полного контроля +- Настройте разрешённые и ограниченные действия +- Применяйте политики безопасности на уровне документа + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Set PDF Privileges with User and Owner Passwords +def set_pdf_privileges_with_passwords(infile, outfile): + """Set PDF privileges using user and owner passwords.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + privilege.allow_copy = False + + # Apply privileges with passwords + file_security.set_privilege("user_password", "owner_password", privilege) + + # Save updated PDF + file_security.save(outfile) +``` + +## Попробуйте установить привилегии PDF без исключений + +Этот фрагмент кода объясняет, как контролировать доступ и ограничивать действия, такие как копирование, при этом разрешая другие, например печать. + +1. Создайте объект 'PdfFileSecurity'. +1. Загрузите исходный PDF, используя метод 'bind_pdf()'. +1. Определить привилегии документа. +1. Применить привилегии с паролями. +1. Сохраните обновлённый PDF. + +```python +from io import FileIO +import sys +from os import path +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +sys.path.append(path.join(path.dirname(__file__), "..")) + +from config import set_license, initialize_data_dir + + +# Try Set PDF Privileges Without Exception +def try_set_pdf_privileges_without_exception(infile, outfile): + """Attempt to set PDF privileges without throwing an exception on failure.""" + # Create PdfFileSecurity object + file_security = pdf_facades.PdfFileSecurity() + + # Bind PDF document + file_security.bind_pdf(infile) + + # Define privileges + privilege = pdf_facades.DocumentPrivilege.forbid_all + privilege.allow_print = True + + # Attempt to apply privileges + result = file_security.try_set_privilege( + "user_password", "owner_password", privilege + ) + + # Save only if operation succeeded + if result: + file_security.save(outfile) + else: + print("Setting privileges failed. Check passwords or document state.") +``` diff --git a/ru/python-net/working-with-facades/pdffilesignature/_index.md b/ru/python-net/working-with-facades/pdffilesignature/_index.md new file mode 100644 index 000000000..c17a3c94c --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilesignature/_index.md @@ -0,0 +1,83 @@ +--- +title: Класс PdfFileSignature +linktitle: Класс PdfFileSignature +type: docs +weight: 60 +url: /python-net/pdffilesignature-class/ +description: Узнайте, как добавлять, проверять и удалять цифровые подписи из PDF‑документов в Python, используя класс PdfFileSignature с Aspose.PDF. +lastmod: "2026-01-05" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [Подписание PDF](/pdf/ru/python-net/pdf-signing/) +- [Сертификация PDF](/pdf/ru/python-net/pdf-certification/) +- [Управление подписями](/pdf/ru/python-net/signature-management/) +- [Проверка подписи](/pdf/ru/python-net/signature-verification/) +- [Информация о подписи](/pdf/ru/python-net/signature-information/) +- [Проверки целостности подписи](/pdf/ru/python-net/signature-integrity-checks/) +- [Редакция и разрешения](/pdf/ru/python-net/revision-permissions/) +- [Извлечение подписи](/pdf/ru/python-net/signature-extraction/) +- [Управление правами использования](/pdf/ru/python-net/usage-rights-management/) + +## Подготовка вспомогательных функций для цифровой подписи PDF + +Перед применением цифровой подписи к PDF рекомендуется создать набор переиспользуемых вспомогательных функций. Эти функции инкапсулируют общие задачи — такие как инициализация обработчика подписи, определение визуального размещения подписи и настройка подписи на основе сертификата — чтобы основная логика подписи оставалась чистой, согласованной и легко обслуживаемой. + +### Что достигает эта настройка + +Этот вспомогательный слой готовит всё необходимое для плавного рабочего процесса подписи: + +- Инициализирует объект PdfFileSignature и привязывает его к документу +- Определяет, где подпись будет отображаться на странице +- Загружает и применяет сертификат подписи +- Создаёт переиспользуемый объект подписи PKCS#7 с метаданными +- Настраивает, как подпись выглядит визуально + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd + + +DEFAULT_CERTIFICATE_PASSWORD = "Aspose2021" +DEFAULT_SIGNATURE_NAME = "Signature1" + + +def create_pdf_file_signature(infile): + pdf_signature = pdf_facades.PdfFileSignature() + pdf_signature.bind_pdf(infile) + return pdf_signature + + +def create_signature_rectangle(): + return apd.Rectangle(10, 10, 200, 60) + + +def configure_signature_certificate( + pdf_signature, certificate_path, certificate_password=DEFAULT_CERTIFICATE_PASSWORD +): + pdf_signature.set_certificate(certificate_path, certificate_password) + + +def create_pkcs7_signature( + certificate_path, certificate_password=DEFAULT_CERTIFICATE_PASSWORD +): + signature = ap.forms.PKCS7(certificate_path, certificate_password) + signature.reason = "Document approval" + signature.contact_info = "qa@example.com" + signature.location = "New York, USA" + signature.authority = "Aspose.PDF Example" + return signature + + +def create_custom_signature_appearance(): + appearance = ap.forms.SignatureCustomAppearance() + appearance.font_family_name = "Arial" + appearance.font_size = 10 + appearance.show_contact_info = True + appearance.show_location = True + appearance.show_reason = True + return appearance +``` diff --git a/ru/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md b/ru/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md new file mode 100644 index 000000000..1a2b38d36 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md @@ -0,0 +1,86 @@ +--- +title: Сертификация PDF +linktitle: Сертификация PDF +type: docs +weight: 30 +url: /python-net/pdf-certification/ +description: Узнайте, как сертифицировать PDF‑документы в Python с помощью PdfFileSignature и DocMDPSignature с различными разрешениями на изменение документа. +lastmod: "2026-04-02" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Сертифицировать PDF‑документы с разрешениями DocMDP в Python +Abstract: В этой статье объясняется, как сертифицировать PDF‑документы с помощью Aspose.PDF for Python via .NET, используя фасад PdfFileSignature. Показано, как создать DocMDPSignature, применить сертификацию с разрешениями на заполнение форм и заблокировать документ на уровне сертификации «без изменений». +--- + +Aspose.PDF for Python via .NET позволяет вам сертифицировать PDF‑документы, применяя подпись уровня документа с [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/). Сертификация отличается от обычной подписи одобрения, потому что она определяет, какие изменения, если они допускаются, разрешены после того, как документ был сертифицирован. + +В этой статье демонстрируются два типичных рабочего процесса сертификации: + +1. Сертифицировать PDF и разрешить заполнение форм после сертификации. +1. Сертифицировать PDF и предотвратить любые дальнейшие изменения. + +## Сертифицировать PDF для заполнения форм + +Используйте этот подход, когда документ должен оставаться сертифицированным, но пользователям всё ещё необходимо заполнять интерактивные формы или продолжать подписывать файл. The `FILLING_IN_FORMS` Уровень разрешения позволяет вносить эти контролируемые изменения, при этом сохраняя сертификат действительным. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def certify_pdf_with_mdp_signature(infile, outfile, certificate_path): + pdf_signature = create_pdf_file_signature(infile) + try: + doc_mdp_signature = create_doc_mdp_signature( + certificate_path, + ap.forms.DocMDPAccessPermissions.FILLING_IN_FORMS, + reason="Certified for form filling and signing", + ) + pdf_signature.certify( + 1, + "Certified for form filling and signing", + "security@example.com", + "New York, USA", + True, + create_signature_rectangle(), + doc_mdp_signature, + ) + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` + +## Применить сертификацию на уровне документа без разрешения на изменения + +Используйте этот режим, когда сертифицированный документ должен оставаться неизменным после сертификации. The `NO_CHANGES` уровень разрешения подходит для окончательных PDF, где любое последующее изменение должно аннулировать состояние сертификации. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def apply_document_level_certification(infile, outfile, certificate_path): + pdf_signature = create_pdf_file_signature(infile) + try: + doc_mdp_signature = create_doc_mdp_signature( + certificate_path, + ap.forms.DocMDPAccessPermissions.NO_CHANGES, + reason="Certified with no further changes allowed", + ) + pdf_signature.certify( + 1, + "Certified with no further changes allowed", + "security@example.com", + "New York, USA", + True, + create_signature_rectangle(), + doc_mdp_signature, + ) + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` diff --git a/ru/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md b/ru/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md new file mode 100644 index 000000000..409fc684a --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md @@ -0,0 +1,183 @@ +--- +title: Подписать PDF документы +linktitle: Подписать PDF документы +type: docs +weight: 10 +url: /python-net/pdf-signing/ +description: Узнайте, как подписывать PDF документы в Python с помощью PdfFileSignature, используя цифровые подписи, основанные на сертификате, именованные и видимые. +lastmod: "2026-04-14" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Подписать PDF документы цифровыми подписями в Python +Abstract: В этой статье показано, как подписывать PDF документы с помощью Aspose.PDF for Python via .NET, используя фасад PdfFileSignature. Описывается настройка сертификата, подпись с базовыми параметрами, подпись с объектом PKCS7, назначение имени подписи и применение видимого оформления подписи. +--- + +Aspose.PDF for Python via .NET предоставляет [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/) фасад для применения цифровых подписей к существующим PDF‑документам. Используя файл сертификата, вы можете подписать документ программно, разместить подпись на странице, назначить метаданные подписи и настроить отображение подписи. + +В этой статье демонстрируются несколько типичных рабочих процессов подписи: + +1. Создайте и привязать a `PdfFileSignature` объект во входном PDF. +1. Настройте сертификат подписи. +1. Примените цифровую подпись к целевой странице. +1. При необходимости задайте имя подписи и её видимый вид. +1. Сохраните подписанный PDF. + +## Подготовьте переиспользуемые вспомогательные функции подписания + +Прежде чем применять цифровую подпись к PDF, полезно создать небольшую группу переиспользуемых вспомогательных функций. Эти функции инициализируют обработчик подписи, определяют видимую область подписи, настраивают сертификат и создают переиспользуемые объекты подписи PKCS#7, чтобы примеры подписания ниже оставались автономными и их было проще понять. + +```python +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as apd + + +DEFAULT_CERTIFICATE_PASSWORD = "Aspose2021" +DEFAULT_SIGNATURE_NAME = "Signature1" + + +def create_pdf_file_signature(infile): + pdf_signature = pdf_facades.PdfFileSignature() + pdf_signature.bind_pdf(infile) + return pdf_signature + + +def create_signature_rectangle(): + return apd.Rectangle(10, 10, 200, 60) + + +def configure_signature_certificate( + pdf_signature, certificate_path, certificate_password=DEFAULT_CERTIFICATE_PASSWORD +): + pdf_signature.set_certificate(certificate_path, certificate_password) + + +def create_pkcs7_signature( + certificate_path, certificate_password=DEFAULT_CERTIFICATE_PASSWORD +): + signature = ap.forms.PKCS7(certificate_path, certificate_password) + signature.reason = "Document approval" + signature.contact_info = "qa@example.com" + signature.location = "New York, USA" + signature.authority = "Aspose.PDF Example" + return signature + + +def create_custom_signature_appearance(): + appearance = ap.forms.SignatureCustomAppearance() + appearance.font_family_name = "Arial" + appearance.font_size = 10 + appearance.show_contact_info = True + appearance.show_location = True + appearance.show_reason = True + return appearance +``` + +## Подписать PDF с базовыми параметрами сертификата + +Этот подход настраивает сертификат напрямую на `PdfFileSignature` объект. Это полезно, когда вам нужен простой процесс подписи со стандартными метаданными подписи и без отдельного управления объектом подписи. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def sign_pdf_with_basic_parameters(infile, outfile, certificate_path): + pdf_signature = create_pdf_file_signature(infile) + try: + configure_signature_certificate(pdf_signature, certificate_path) + pdf_signature.sign( + 1, + "Document approval", + "qa@example.com", + "New York, USA", + False, + create_signature_rectangle(), + ) + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` + +## Подписать PDF с объектом PKCS7 + +Использовать `PKCS7` объект, когда вам нужно сначала подготовить подпись, а затем передать её в вызов подписи. Этот шаблон даёт вам больший контроль над настройками подписи и является хорошей основой для более сложных рабочих процессов. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def sign_pdf_with_certificate_object(infile, outfile, certificate_path): + pdf_signature = create_pdf_file_signature(infile) + try: + signature = create_pkcs7_signature(certificate_path) + pdf_signature.sign(1, False, create_signature_rectangle(), signature) + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` + +## Подписать PDF с именованной подписью + +Если ваш рабочий процесс с документом зависит от заранее определенного имени поля подписи, передайте это имя в `sign()`. Это упрощает последующее обращение к подписи для проверки, обработки или интеграции с процессом утверждения. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def sign_pdf_with_named_signature(infile, outfile, certificate_path): + pdf_signature = create_pdf_file_signature(infile) + try: + signature = create_pkcs7_signature(certificate_path) + signature.reason = "Approved by signing workflow" + pdf_signature.sign( + 1, + DEFAULT_SIGNATURE_NAME, + "Approved by signing workflow", + "qa@example.com", + "New York, USA", + True, + create_signature_rectangle(), + signature, + ) + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` + +## Применить видимую подпись + +Вы можете сделать подпись видимой на странице PDF, присвоив ей пользовательский внешний вид `PKCS7` объекта. Это полезно, когда выходной документ должен отображать детали одобрения, такие как причина, место и контактная информация для конечных пользователей. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def apply_visible_signature(infile, outfile, certificate_path): + pdf_signature = create_pdf_file_signature(infile) + try: + signature = create_pkcs7_signature(certificate_path) + signature.reason = "Visible approval signature" + signature.custom_appearance = create_custom_signature_appearance() + pdf_signature.sign( + 1, + "Visible approval signature", + "qa@example.com", + "New York, USA", + True, + create_signature_rectangle(), + signature, + ) + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` diff --git a/ru/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md b/ru/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md new file mode 100644 index 000000000..39fc4c5a0 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md @@ -0,0 +1,82 @@ +--- +title: Ревизия и разрешения +linktitle: Ревизия и разрешения +type: docs +weight: 40 +url: /python-net/revision-permissions/ +description: Узнайте, как проверять ревизии подписей, ревизии документов и разрешения на сертификацию в PDF‑файлах с помощью PdfFileSignature в Python. +lastmod: "2026-04-02" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Чтение данных о ревизиях подписи PDF и разрешениях доступа в Python +Abstract: В этой статье объясняется, как проверять информацию о ревизиях и разрешениях в подписанных или сертифицированных PDF‑файлах с помощью Aspose.PDF for Python via .NET. Показано, как получить номер ревизии подписи, подсчитать общее количество ревизий документа и считывать разрешения доступа из сертифицированного PDF. +--- + +Aspose.PDF for Python via .NET предоставляет [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/) фасад для работы с подписанными и заверенными PDF‑документами. Помимо добавления подписей, вы также можете просматривать метаданные подписи, чтобы понять, сколько ревизий содержит документ и какие изменения разрешены после сертификации. + +В этом примере демонстрируются три типовых задачи инспекции: + +1. Получить номер ревизии для существующей подписи. +1. Получить общее количество ревизий в подписанном документе. +1. Прочитать разрешения доступа из сертифицированного PDF. + +## Получить номер ревизии подписи + +Используйте этот подход, когда PDF уже содержит одну или несколько подписей, и вам необходимо определить ревизию, связанную с конкретной подписью. Пример получает имя первой доступной подписи и затем вызывает `get_revision()`. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def get_signature_revision(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + signature_revision = pdf_signature.get_revision(sign_name) + print(f"Signature Revision for '{sign_name}': {signature_revision}") + finally: + pdf_signature.close() +``` + +## Получить общее количество ревизий документа + +Использовать `get_total_revision()` когда вам нужно узнать, сколько ревизий хранится в подписанном PDF. Это полезно для проверки того, прошёл ли документ через несколько обновлений после применения оригинальной подписи. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def get_total_document_revisions(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + total_revisions = pdf_signature.get_total_revision() + print(f"Total Document Revisions: {total_revisions}") + finally: + pdf_signature.close() +``` + +## Получить разрешения доступа из сертифицированного PDF + +Сертифицированные документы могут определять, какие изменения разрешены после сертификации. Использовать `get_access_permissions()` проверить этот уровень разрешений и определить, разрешает ли документ отсутствие изменений, заполнение форм или другие контролируемые модификации. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def get_access_permissions(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + access_permissions = pdf_signature.get_access_permissions() + print(f"Access Permissions: {access_permissions}") + finally: + pdf_signature.close() +``` + diff --git a/ru/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md b/ru/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md new file mode 100644 index 000000000..1b59683ea --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md @@ -0,0 +1,63 @@ +--- +title: Извлечение подписи +linktitle: Извлечение подписи +type: docs +weight: 50 +url: /python-net/signature-extraction/ +description: Узнайте, как извлечь изображение подписи и сертификат подписи из подписанного PDF, используя PdfFileSignature в Python. +lastmod: "2026-04-02" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Извлечение изображения подписи и сертификата из PDF в Python +Abstract: В этой статье объясняется, как извлекать данные, связанные с подписью, из подписанных PDF‑документов с помощью Aspose.PDF for Python via .NET. Показано, как прочитать первую доступную подпись, экспортировать её изображение и сохранить связанный поток сертификата в выходной файл. +--- + +Aspose.PDF for Python via .NET предоставляет [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/) фасад для проверки и извлечения данных из подписанных PDF‑документов. После подписания PDF вы можете использовать его для экспорта ресурсов подписи, таких как визуальное изображение подписи и сертификат, связанный с подписью. + +В этом примере демонстрируются два распространённых задания по извлечению: + +1. Извлечь визуальное изображение, связанное с подписью. +1. Извлечь сертификат подписи из подписанного PDF. + +## Извлечь изображение подписи + +Используйте этот метод, когда PDF содержит видимую подпись и вы хотите экспортировать данные её изображения. В примере открывается подписанный документ, получается первое доступное имя подписи, извлекается поток изображения и записывается в файл. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def extract_signature_image(infile, outfile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + signature_image = pdf_signature.extract_image(sign_name) + write_stream_data(signature_image, outfile) + finally: + pdf_signature.close() +``` + +## Извлечь сертификат подписи + +Используйте `extract_certificate()` когда вам нужны данные сертификата, прикреплённые к подписи. Это полезно для проверки, процессов валидации или отдельного хранения сертификата подписывающего от PDF‑документа. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def extract_signature_certificate(infile, outfile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + signature_certificate = pdf_signature.extract_certificate(sign_name) + write_stream_data(signature_certificate, outfile) + finally: + pdf_signature.close() +``` + diff --git a/ru/python-net/working-with-facades/pdffilesignature/signature-information/_index.md b/ru/python-net/working-with-facades/pdffilesignature/signature-information/_index.md new file mode 100644 index 000000000..24e517ca3 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilesignature/signature-information/_index.md @@ -0,0 +1,112 @@ +--- +title: Информация о подписи +linktitle: Информация о подписи +type: docs +weight: 60 +url: /python-net/signature-information/ +description: Узнайте, как читать имена подписей, данные подписанта, метки времени и метаданные подписи из подписанных PDF‑файлов с помощью PdfFileSignature в Python. +lastmod: "2026-04-02" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Чтение деталей подписи из PDF‑документов в Python +Abstract: В этой статье объясняется, как просматривать метаданные подписи в подписанных PDF‑документах с помощью Aspose.PDF for Python via .NET. Показано, как вывести список имён подписей, прочитать данные подписанта, получить дату и время подписи, а также извлечь причину и место подписи. +--- + +Aspose.PDF for Python via .NET предоставляет [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/) фасад для инспектирования цифровых подписей в PDF‑документах. После подписания документа вы можете использовать его для чтения имён подписей и получения метаданных, таких как имя подписанта, контактная информация, время подписи, причина и место. + +Этот пример демонстрирует четыре распространённых задачи по работе с информацией о подписи: + +1. Перечислите все имена подписей в подписанном PDF. +1. Прочитайте детали подписанта для выбранной подписи. +1. Получите дату и время подписи. +1. Прочитайте причину и место подписи. + +## Получить имена подписей + +Используйте этот метод, когда PDF может содержать одну или несколько подписей, и вы хотите проверить, какие записи подписи доступны. Пример открывает документ и выводит список, возвращённый `get_sign_names()`. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def get_signature_names(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + signature_names = list_signature_names(pdf_signature) + print(f"Signature Names: {signature_names}") + finally: + pdf_signature.close() +``` + +## Получить сведения о подписанте + +Как только вы узнаете название подписи, вы можете получить метаданные, специфичные для подписанта. В этом примере читаются имя подписанта и контактная информация для первой доступной подписи в документе. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def get_signer_details(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + signer_name = pdf_signature.get_signer_name(sign_name) + contact_info = pdf_signature.get_contact_info(sign_name) + print( + f"Signer Details for '{sign_name}': " + f"signer_name={signer_name}, contact_info={contact_info}" + ) + finally: + pdf_signature.close() +``` + +## Получить дату и время подписи + +Используйте `get_date_time()` чтобы определить, когда была применена конкретная подпись. Это полезно для аудита и отображения истории подписей в рабочих процессах с документами. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def get_signature_date_and_time(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + signature_date = pdf_signature.get_date_time(sign_name) + print(f"Signature Date and Time for '{sign_name}': {signature_date}") + finally: + pdf_signature.close() +``` + +## Получить причину подписи и местоположение + +Цифровые подписи также могут хранить описательные метаданные, такие как причина подписи и место её создания. В этом примере оба значения извлекаются для выбранной подписи и выводятся вместе. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def get_signature_reason_and_location(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + signature_reason = pdf_signature.get_reason(sign_name) + signature_location = pdf_signature.get_location(sign_name) + print( + f"Signature Reason and Location for '{sign_name}': " + f"reason={signature_reason}, location={signature_location}" + ) + finally: + pdf_signature.close() +``` + diff --git a/ru/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md b/ru/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md new file mode 100644 index 000000000..9fa16be78 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md @@ -0,0 +1,63 @@ +--- +title: Проверки целостности подписи +linktitle: Проверки целостности подписи +type: docs +weight: 70 +url: /python-net/signature-integrity-checks/ +description: Узнайте, как проверить, охватывает ли подпись PDF весь документ, и подтвердить целостность подписанного документа с помощью PdfFileSignature в Python. +lastmod: "2026-04-02" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Проверка охвата подписи PDF и её целостности в Python +Abstract: В этой статье объясняется, как проверять целостность цифровой подписи в подписанных PDF‑документах с помощью Aspose.PDF for Python via .NET. Показано, как проверить, охватывает ли подпись весь документ, и как подтвердить целостность подписанного содержимого. +--- + +Aspose.PDF for Python via .NET предоставляет [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/) фасад для проверки подписанных PDF‑документов. После того как файл подписан, вы можете использовать его, чтобы проверить, применяется ли подпись ко всему документу и всё ли ещё действительна подписанная информация. + +В этом примере демонстрируются два распространённых контроля целостности: + +1. Проверьте, покрывает ли подпись весь документ. +1. Проверьте целостность подписанного содержимого PDF. + +## Проверьте, покрывает ли подпись весь документ + +Использовать `covers_whole_document()` когда необходимо подтвердить, что подпись применяется к полному PDF, а не только к части его содержимого. Пример считывает первое доступное имя подписи и проверяет её охват. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def check_signature_coverage(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + covers_document = pdf_signature.covers_whole_document(sign_name) + print(f"Signature '{sign_name}' covers the whole document: {covers_document}") + finally: + pdf_signature.close() +``` + +## Проверка целостности документа + +Используйте `verify_signed()` чтобы подтвердить, что содержимое подписанного документа не было изменено после применения подписи. Этот метод помогает проверить, остается ли документ действительным для выбранной подписи. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def validate_document_integrity(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + is_valid = pdf_signature.verify_signed(sign_name) + print(f"Document integrity for '{sign_name}' is valid: {is_valid}") + finally: + pdf_signature.close() +``` + diff --git a/ru/python-net/working-with-facades/pdffilesignature/signature-management/_index.md b/ru/python-net/working-with-facades/pdffilesignature/signature-management/_index.md new file mode 100644 index 000000000..493236ccc --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilesignature/signature-management/_index.md @@ -0,0 +1,62 @@ +--- +title: Управление подписями +linktitle: Управление подписями +type: docs +weight: 80 +url: /python-net/signature-management/ +description: Узнайте, как удалять цифровые подписи из PDF‑документов и при необходимости очищать поля подписи, используя PdfFileSignature в Python. +lastmod: "2026-04-02" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Удаление подписей PDF и очистка полей подписи в Python +Abstract: В этой статье объясняется, как управлять существующими цифровыми подписями в PDF‑документах с помощью Aspose.PDF for Python via .NET. Показано, как удалить подпись из PDF и как удалить подпись вместе с соответствующим полем подписи. +--- + +Aspose.PDF for Python via .NET предоставляет [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/) Фасад для работы с существующими цифровыми подписями в PDF‑документах. Помимо чтения и проверки подписей, вы также можете удалять их, когда процесс требует обновления подписанного содержимого или очистки поля подписи. + +Этот пример демонстрирует две распространённые задачи управления подписями: + +1. Удалить подпись из PDF‑документа. +1. Удалить подпись и очистить связанное поле подписи. + +## Удалить подпись из PDF + +Используйте `remove_signature()` когда вы хотите удалить выбранную подпись из документа, сохраняя при этом структуру поля подписи. В примере открывается подписанный PDF, определяется имя подписи, удаляется и сохраняется обновлённый выходной файл. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def remove_signature_from_pdf(infile, outfile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + pdf_signature.remove_signature(sign_name) + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` + +## Удалить подпись и очистить поле + +Используйте перегрузку с дополнительным `True` флаг, когда вы хотите удалить подпись и также очистить связанное поле подписи. Это полезно, когда поле не должно оставаться в документе после удаления подписи. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def remove_signature_with_field_cleanup(infile, outfile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + pdf_signature.remove_signature(sign_name, True) + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` diff --git a/ru/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md b/ru/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md new file mode 100644 index 000000000..929246d33 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md @@ -0,0 +1,61 @@ +--- +title: Проверка подписи +linktitle: Проверка подписи +type: docs +weight: 90 +url: /python-net/signature-verification/ +description: Узнайте, как проверять цифровые подписи и проверять, содержит ли PDF подписи, используя PdfFileSignature в Python. +lastmod: "2026-04-02" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Проверка подписей PDF в Python +Abstract: В этой статье объясняется, как проверять цифровые подписи в PDF‑документах с помощью Aspose.PDF for Python via .NET. Показано, как подтвердить существующую подпись и как проверить, содержит ли PDF какие‑либо подписи. +--- + +Aspose.PDF for Python via .NET предоставляет [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/) фасад для проверки подписанных PDF‑документов. После того как PDF был подписан, вы можете использовать его, чтобы подтвердить, что подпись действительна, и обнаружить, содержит ли документ какие‑либо записи о подписи. + +В этом примере демонстрируются две распространённые задачи проверки: + +1. Проверьте, действительна ли существующая подпись PDF. +1. Проверьте, содержит ли PDF какие-либо подписи. + +## Проверить подпись PDF + +Используйте `verify_signature()` когда вам нужно проверить конкретную подпись в документе. Пример определяет первое доступное имя подписи и проверяет, действительна ли эта подпись. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def verify_pdf_signature(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + sign_name = require_signature_name(pdf_signature) + is_valid = pdf_signature.verify_signature(sign_name) + print(f"Signature '{sign_name}' is valid: {is_valid}") + finally: + pdf_signature.close() +``` + +## Проверьте, содержит ли PDF подписи + +Используйте `contains_signature()` когда вам нужно лишь узнать, содержит ли PDF какие-либо подписи вообще. Это полезно как быстрая проверка перед запуском более детальной проверки или извлечения логики. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def check_if_pdf_contains_signatures(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + contains_signatures = pdf_signature.contains_signature() + print(f"PDF contains signatures: {contains_signatures}") + finally: + pdf_signature.close() +``` diff --git a/ru/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md b/ru/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md new file mode 100644 index 000000000..63db6e156 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md @@ -0,0 +1,63 @@ +--- +title: Управление правами использования +linktitle: Управление правами использования +type: docs +weight: 100 +url: /python-net/usage-rights-management/ +description: Узнайте, как обнаруживать и удалять права использования из PDF‑документов с помощью PdfFileSignature в Python. +lastmod: "2026-04-02" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Удаление прав использования PDF в Python +Abstract: В этой статье объясняется, как проверять и удалять права использования из PDF‑документов с помощью Aspose.PDF for Python via .NET. Показано, как проверить, содержит ли PDF права использования, и как сохранить новую версию документа после их удаления. +--- + +Aspose.PDF for Python via .NET предоставляет [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/) фасад для работы с подписанными PDF и связанными настройками прав использования. В некоторых рабочих процессах вам может потребоваться проверить, содержит ли документ права использования, и удалить их перед сохранением обновлённой версии файла. + +Этот пример демонстрирует одну распространённую задачу управления правами использования: + +1. Проверьте, содержит ли PDF права использования. +1. Удалите права использования из документа. +1. Сохраните обновлённый PDF‑файл. + +## Проверьте, содержит ли PDF права использования + +Перед удалением прав использования пример проверяет текущее состояние документа, вызывая `contains_usage_rights()`. Это позволяет вам подтвердить, присутствуют ли права использования, прежде чем вносить изменения. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def check_usage_rights(infile): + pdf_signature = create_pdf_file_signature(infile) + try: + had_usage_rights = pdf_signature.contains_usage_rights() + print(f"PDF contains usage rights: {had_usage_rights}") + finally: + pdf_signature.close() +``` + +## Удалить права использования из PDF + +Используйте `remove_usage_rights()` когда документ больше не должен сохранять свои текущие настройки прав использования. Пример проверяет начальное состояние, удаляет права и сохраняет обновлённый PDF в новый файл. + +```python +import aspose.pdf.facades as pdf_facades +import sys +from os import path + + +def remove_usage_rights(infile, outfile): + pdf_signature = create_pdf_file_signature(infile) + try: + had_usage_rights = pdf_signature.contains_usage_rights() + print(f"PDF contains usage rights before removal: {had_usage_rights}") + pdf_signature.remove_usage_rights() + pdf_signature.save(outfile) + finally: + pdf_signature.close() +``` diff --git a/ru/python-net/working-with-facades/pdffilestamp/_index.md b/ru/python-net/working-with-facades/pdffilestamp/_index.md new file mode 100644 index 000000000..7fe19c3e0 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilestamp/_index.md @@ -0,0 +1,26 @@ +--- +title: Класс PdfFileStamp +linktitle: Класс PdfFileStamp +type: docs +weight: 155 +url: /python-net/pdffilestamp-class/ +description: Узнайте, как использовать класс PdfFileStamp в Aspose.PDF for Python via .NET для добавления заголовков, колонтитулов, номеров страниц и штампов в PDF‑документы. +lastmod: "2026-04-14" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: Добавьте заголовки, колонтитулы, номера страниц и штампы в PDF в Python с помощью PdfFileStamp +Abstract: В этом разделе объясняется, как использовать фасад PdfFileStamp в Aspose.PDF for Python via .NET для добавления повторяющегося контента в PDF‑документы. Узнайте, как программно размещать заголовки, колонтитулы, номера страниц и штампы на страницах PDF в приложениях Python. +--- + +Этот `PdfFileStamp` класс в Aspose.PDF Facades предназначен для добавления повторяющегося визуального контента на страницы PDF. Он полезен, когда нужно применить заголовки, колонтитулы, номера страниц или штампы во всём документе без ручного редактирования каждой страницы. + +## Что вы можете сделать с PdfFileStamp + +Используйте статьи в этом разделе, чтобы исследовать основные задачи штамповки, поддерживаемые `PdfFileStamp` фасад: + +- [Добавьте нижние колонтитулы к страницам PDF с помощью PdfFileStamp](/pdf/ru/python-net/add-footer/) +- [Добавьте верхние колонтитулы к страницам PDF с помощью PdfFileStamp](/pdf/ru/python-net/add-header/) +- [Добавьте номера страниц в документы PDF с помощью PdfFileStamp](/pdf/ru/python-net/page-number/) +- [Добавьте штампы на страницы PDF с помощью PdfFileStamp](/pdf/ru/python-net/add-stamp/) diff --git a/ru/python-net/working-with-facades/pdffilestamp/add-footer/_index.md b/ru/python-net/working-with-facades/pdffilestamp/add-footer/_index.md new file mode 100644 index 000000000..ae693db36 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilestamp/add-footer/_index.md @@ -0,0 +1,85 @@ +--- +title: Добавить нижний колонтитул в PDF +linktitle: Добавить нижний колонтитул в PDF +type: docs +weight: 10 +url: /python-net/add-footer/ +description: Узнайте, как добавить текстовые и графические нижние колонтитулы на страницы PDF с помощью PdfFileStamp в Python. +lastmod: "2026-04-13" +TechArticle: true +AlternativeHeadline: Добавить текстовые и графические нижние колонтитулы в PDF на Python +Abstract: В этой статье объясняется, как добавить содержимое нижнего колонтитула в документы PDF с помощью Aspose.PDF for Python via .NET, используя фасад PdfFileStamp. Показано, как добавить текстовый нижний колонтитул, разместить графический нижний колонтитул и применить пользовательские отступы нижнего колонтитула перед сохранением обновлённого PDF. +--- + +Aspose.PDF for Python via .NET предоставляет [PdfFileStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilestamp/) фасад для добавления повторяющегося контента на страницы PDF. Вы можете использовать его для размещения текста или изображений в нижнем колонтитуле внизу каждой страницы и настроить отступы нижнего колонтитула для управления размещением. + +## Добавить текстовый нижний колонтитул + +Используйте `add_footer()` с `FormattedText` объект, когда вы хотите разместить одинаковый текстовый нижний колонтитул на каждой странице PDF. Второй аргумент задает отступ снизу, используемый для размещения нижнего колонтитула. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_text_footer(infile: str, outfile: str) -> None: + """Add a text footer with a bottom margin.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + text = pdf_facades.FormattedText("Sample Footer") + pdf_stamper.add_footer(text, 20) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Добавить изображение в нижний колонтитул + +Используйте `add_footer()` с потоковым изображением, когда нижний колонтитул должен отображать логотип или другое изображение вместо текста. В примере файл изображения открывается как бинарный поток и размещается внизу каждой страницы. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_image_footer(infile: str, image_file: str, outfile: str) -> None: + """Add an image footer with a bottom margin.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + pdf_stamper.add_footer(image_file, 20) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Добавьте нижний колонтитул с пользовательскими отступами + +Используйте перегрузку с тремя значениями отступов, когда вам нужен больший контроль над размещением нижнего колонтитула. В этом примере нижний колонтитул добавляется с пользовательскими нижними, левыми и правыми отступами. + +```python +import sys +from os import path +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_footer_with_margins(infile: str, outfile: str) -> None: + """Add a text footer with bottom, left, and right margins.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + text = pdf_facades.FormattedText("This footer has margins on all sides.") + pdf_stamper.add_footer(text, 20, 20, 20) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` diff --git a/ru/python-net/working-with-facades/pdffilestamp/add-header/_index.md b/ru/python-net/working-with-facades/pdffilestamp/add-header/_index.md new file mode 100644 index 000000000..4f831c26c --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilestamp/add-header/_index.md @@ -0,0 +1,98 @@ +--- +title: Добавить заголовок в PDF +linktitle: Добавить заголовок в PDF +type: docs +weight: 20 +url: /python-net/add-header/ +description: Узнайте, как добавить текстовые и графические заголовки на страницы PDF, используя PdfFileStamp в Python. +lastmod: "2026-04-13" +TechArticle: true +AlternativeHeadline: Добавить текстовые и графические заголовки в PDF на Python. +Abstract: В этой статье объясняется, как добавить содержимое заголовка в PDF‑документы с помощью Aspose.PDF for Python via .NET, используя фасад PdfFileStamp. Показано, как добавить текстовый заголовок, разместить заголовок‑изображение и применить пользовательские отступы заголовка перед сохранением обновлённого PDF. +--- + +Aspose.PDF for Python via .NET предоставляет [PdfFileStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilestamp/) фасад для добавления повторяющегося контента на страницы PDF. Вы можете использовать его для размещения текста заголовка или изображений в верхней части каждой страницы и настройки отступов заголовка для контроля позиционирования. + +## Добавить текстовый заголовок + +Используйте `add_header()` с `FormattedText` объект, когда вы хотите разместить один и тот же текст заголовка на каждой странице PDF. Второй аргумент определяет верхний отступ для заголовка. + +```python +import sys +from os import path + +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_text_header(infile: str, outfile: str) -> None: + """Add a text header with a top margin.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + text = pdf_facades.FormattedText("Sample Header") + pdf_stamper.add_header(text, 20) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Добавить заголовок с изображением + +Используйте `add_header()` с файлом изображения или потоком изображения, когда в заголовке должен отображаться логотип или другая графика. Это полезно для фирменных макетов документов. + +```python +import sys +from os import path + +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_image_header(infile: str, image_file: str, outfile: str) -> None: + """Add an image header with a top margin.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + pdf_stamper.add_header(image_file, 20) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Добавьте заголовок с пользовательскими отступами + +Используйте перегрузку с тремя значениями отступов, когда вам требуется больший контроль над размещением заголовка. В этом примере заголовок добавлен с пользовательскими верхним, левым и правым отступами. + +```python +import sys +from os import path + +import aspose.pydrawing as ap_pydrawing +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_header_with_margins(infile: str, outfile: str) -> None: + """Add a text header with top, left, and right margins.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + text = pdf_facades.FormattedText( + text="Sample Header", + text_color=ap_pydrawing.Color.blue, + font_name="Arial", + text_encoding=pdf_facades.EncodingType.WINANSI, + embedded=True, + font_size=12.0, + ) + pdf_stamper.add_header(text, 20, 20, 20) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` diff --git a/ru/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md b/ru/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md new file mode 100644 index 000000000..aac9aae31 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md @@ -0,0 +1,123 @@ +--- +title: Добавить номер страницы в PDF +linktitle: Добавить номер страницы в PDF +type: docs +weight: 30 +url: /python-net/page-number/ +description: Узнайте, как добавить номера страниц в PDF-документы с помощью PdfFileStamp в Python. +lastmod: "2026-04-13" +TechArticle: true +AlternativeHeadline: Добавить номера страниц в PDF на Python +Abstract: В этой статье объясняется, как добавить номера страниц в PDF-документы с помощью Aspose.PDF for Python via .NET, используя фасад PdfFileStamp. Показано, как добавить номера страниц с расположением по умолчанию, разместить их в пользовательских координатах и управлять выравниванием и полями. +--- + +Aspose.PDF for Python via .NET предоставляет [PdfFileStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilestamp/) Facade для добавления повторяющегося контента на страницы PDF. Вы можете использовать её для вставки номеров страниц с размещением по умолчанию, позиционирования их в определённых координатах или управления их выравниванием и отступами. + +## Добавить номера страниц с размещением по умолчанию + +Используйте `add_page_number()` без дополнительных аргументов позиции, когда вы хотите, чтобы номера страниц добавлялись в месте по умолчанию. Это самый простой способ пронумеровать каждую страницу в документе. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_page_numbers_default(infile: str, outfile: str) -> None: + """Add centered page numbers to the bottom of each page.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + pdf_stamper.add_page_number("Page #") + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Добавить номера страниц в пользовательских координатах + +Используйте перегрузку на основе координат, когда вам нужно, чтобы номера страниц отображались в конкретных позициях X и Y на каждой странице. Такой подход полезен, когда макет документа требует пользовательского размещения. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_page_numbers_at_coordinates(infile: str, outfile: str) -> None: + """Add page numbers at explicit X/Y coordinates.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + pdf_stamper.add_page_number("Page #", 300, 20) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Добавьте номера страниц с выравниванием и полями + +Используйте перегрузку с аргументами позиции и полей, когда вам нужен более точный контроль над тем, где отображаются номера страниц. В этом примере номера выровнены по верхнему правому углу страницы с явно заданными полями. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_page_numbers_with_position_and_margins(infile: str, outfile: str) -> None: + """Add page numbers using a predefined position and page margins.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + pdf_stamper.add_page_number( + "Page #", + pdf_facades.PdfFileStamp.POS_BOTTOM_RIGHT, + 10, + 10, + 10, + 10, + ) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Добавить нумерацию страниц в римском стиле + +Функция 'add_page_numbers_with_roman_style' демонстрирует, как улучшить PDF‑документ, добавив нумерацию страниц с использованием заглавных римских цифр. Она использует класс PdfFileStamp из Aspose.PDF для применения последовательной нумерации на всех страницах. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades + +from config import initialize_data_dir, set_license + + +def add_page_numbers_with_roman_style(infile: str, outfile: str) -> None: + """Add page numbers with a custom start value and Roman numbering.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + pdf_stamper.numbering_style = ap.NumberingStyle.NUMERALS_ROMAN_UPPERCASE + pdf_stamper.starting_number = 42 + pdf_stamper.add_page_number("Page #", pdf_facades.PdfFileStamp.POS_UPPER_RIGHT) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` diff --git a/ru/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md b/ru/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md new file mode 100644 index 000000000..f4d44f2e2 --- /dev/null +++ b/ru/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md @@ -0,0 +1,47 @@ +--- +title: Добавить штамп в PDF +linktitle: Добавить штамп в PDF +type: docs +weight: 40 +url: /python-net/add-stamp/ +description: Узнайте, как добавить штамп на страницы PDF, используя PdfFileStamp в Python. +lastmod: "2026-04-13" +TechArticle: true +AlternativeHeadline: Добавить текстовые штампы в PDF на Python +Abstract: В этой статье объясняется, как добавить содержимое штампа в PDF‑документы с помощью Aspose.PDF for Python via .NET, используя фасад PdfFileStamp. Показано, как создать штамп, разместить его на странице, управлять вращением и прозрачностью, а также сохранить обновлённый PDF. +--- + +Aspose.PDF for Python via .NET предоставляет [PdfFileStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilestamp/) Фасад для добавления повторяющегося контента на страницы PDF. Помимо заголовков, нижних колонтитулов и номеров страниц, его можно использовать для размещения текстовых штампов на каждой странице документа. + +## Добавить штамп в PDF + +После настройки штампа привяжите входной PDF к `PdfFileStamp`, добавить штамп, и сохранить выходной файл. Это применяет настроенный штамп по всему документу. + +```python +import sys +from os import path + +import aspose.pdf.facades as pdf_facades + +CURRENT_DIR = path.dirname(__file__) +EXAMPLES_DIR = path.abspath(path.join(CURRENT_DIR, "..", "..")) +if EXAMPLES_DIR not in sys.path: + sys.path.insert(0, EXAMPLES_DIR) + +from config import initialize_data_dir, set_license + + +def add_stamp_to_pdf(infile: str, image_file: str, outfile: str) -> None: + """Add an image stamp to a PDF file.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + + stamp = pdf_facades.Stamp() + stamp.bind_image(image_file) + + pdf_stamper.add_stamp(stamp) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` diff --git a/ru/python-net/working-with-facades/stamp/_index.md b/ru/python-net/working-with-facades/stamp/_index.md new file mode 100644 index 000000000..b8c26fd77 --- /dev/null +++ b/ru/python-net/working-with-facades/stamp/_index.md @@ -0,0 +1,229 @@ +--- +title: Класс Stamp +linktitle: Класс Stamp +type: docs +weight: 150 +url: /python-net/stamp-class/ +description: Узнайте, как работать с классом Stamp, чтобы добавлять штампы изображений, PDF и текстовые штампы в PDF‑документы на Python. +lastmod: "2026-04-13" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +Aspose.PDF for Python via .NET предоставляет [Stamp](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/stamp/) класс для размещения переиспользуемого визуального контента на страницах PDF. Штамп может быть основан на тексте, изображении или даже на странице из другого PDF, и его можно позиционировать, вращать, стилизовать и ограничивать конкретными страницами. + +В этой статье демонстрируются несколько распространённых рабочих процессов штампов: + +1. Создайте переиспользуемые текстовые ресурсы для текстовых штампов. +1. Добавьте штампы изображения и страницы PDF. +1. Добавьте стилизованные текстовые штампы. +1. Ограничьте штамп выбранными страницами. +1. Настройте штамп с фоновым изображением. + +В примере используются две вспомогательные функции: одна создает отформатированный текст для текстовых штампов, а другая создает `TextState` объект, используемый для стилизации текстовых штампов. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as drawing + +from config import initialize_data_dir, set_license + + +def _create_text_logo(text: str) -> pdf_facades.FormattedText: + """Create formatted text for text stamp examples.""" + return pdf_facades.FormattedText( + text, + drawing.Color.blue, + drawing.Color.light_gray, + pdf_facades.FontStyle.HELVETICA_BOLD, + pdf_facades.EncodingType.WINANSI, + True, + 14, + ) + + +def _create_text_state() -> ap.text.TextState: + """Create a text state used to style text stamps.""" + text_state = ap.text.TextState() + text_state.foreground_color = ap.Color.dark_blue + text_state.font_size = 16 + text_state.font_style = ap.text.FontStyles.BOLD + return text_state +``` + +## Добавить штамп изображения + +Используйте `bind_image()` когда штамп должен отображать изображение, такое как логотип, значок или иконка. После привязки изображения вы можете установить идентификатор штампа и его исходную точку перед добавлением его в документ. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as drawing + +from config import initialize_data_dir, set_license + + +def add_image_stamp(infile: str, image_file: str, outfile: str) -> None: + """Add an image stamp to the PDF.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + + stamp = pdf_facades.Stamp() + stamp.bind_image(image_file) + stamp.stamp_id = 1 + stamp.set_origin(36, 520) + + pdf_stamper.add_stamp(stamp) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Добавить страницу PDF в качестве штампа + +Используйте `bind_pdf()` когда вы хотите использовать страницу из другого PDF‑файла в качестве содержимого штампа. Это полезно для наложений, таких как утверждения, шаблоны или заранее созданные визуальные элементы, хранящиеся в отдельном документе. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as drawing + +from config import initialize_data_dir, set_license + + +def add_pdf_page_as_stamp(infile: str, stamp_pdf: str, outfile: str) -> None: + """Add the first page of another PDF as a stamp.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + + stamp = pdf_facades.Stamp() + stamp.bind_pdf(stamp_pdf, 1) + stamp.page_number = 1 + stamp.set_origin(36, 250) + + pdf_stamper.add_stamp(stamp) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Добавить TextStamp с текстовым состоянием + +Используйте `bind_logo()` вместе с `bind_text_state()` когда вы хотите создать текстовую печать с пользовательским оформлением шрифта. Этот подход полезен для отметок одобрения, меток и аннотаций, специфичных для рабочего процесса. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as drawing + +from config import initialize_data_dir, set_license + + +def add_text_stamp_with_text_state(infile: str, outfile: str) -> None: + """Add a text stamp and style it with a TextState object.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + + stamp = pdf_facades.Stamp() + stamp.bind_logo(_create_text_logo("Approved by signing workflow")) + stamp.bind_text_state(_create_text_state()) + stamp.set_origin(36, 700) + stamp.rotation = 15.0 + + pdf_stamper.add_stamp(stamp) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Добавить штамп на определённые страницы + +Если штамп не должен отображаться на каждой странице, назначьте целевые номера страниц `pages` свойство. В этом примере добавляется штамп изображения только на первую страницу. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as drawing + +from config import initialize_data_dir, set_license + + +def add_stamp_to_specific_pages(infile: str, image_file: str, outfile: str) -> None: + """Add an image stamp only to the selected pages.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + + stamp = pdf_facades.Stamp() + stamp.bind_image(image_file) + stamp.pages = [1] + stamp.set_origin(400, 40) + stamp.set_image_size(120, 60) + + pdf_stamper.add_stamp(stamp) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Добавить фоновый ImageStamp + +Используйте фоновый штамп, когда изображение должно располагаться позади содержимого страницы. Вы также можете управлять непрозрачностью штампа, его поворотом, качеством, размером и положением, чтобы создать эффекты в стиле водяного знака. + +```python +import sys +from os import path + +import aspose.pdf as ap +import aspose.pdf.facades as pdf_facades +import aspose.pydrawing as drawing + +from config import initialize_data_dir, set_license + + +def add_background_image_stamp(infile: str, image_file: str, outfile: str) -> None: + """Add a rotated background image stamp with opacity and quality settings.""" + pdf_stamper = pdf_facades.PdfFileStamp() + try: + pdf_stamper.bind_pdf(infile) + + stamp = pdf_facades.Stamp() + stamp.bind_image(image_file) + stamp.is_background = True + stamp.opacity = 0.35 + stamp.quality = 90 + stamp.rotation = 45.0 + stamp.set_image_size(160, 80) + stamp.set_origin(200, 300) + + pdf_stamper.add_stamp(stamp) + pdf_stamper.save(outfile) + finally: + pdf_stamper.close() +``` + +## Связанные темы фасадов + +- [Работа с фасадами PDF в Python](/pdf/ru/python-net/working-with-facades/) +- [Добавьте заголовки, нижние колонтитулы и штампы с помощью PdfFileStamp](/pdf/ru/python-net/pdffilestamp-class/) +- [Добавьте штамп страницы в PDF‑файлы с помощью Python](/pdf/ru/python-net/add-stamp/) From 71af69e750f5644f3ac08459409b6d0865be9f3f Mon Sep 17 00:00:00 2001 From: Andriy Andruhovski Date: Thu, 14 May 2026 14:15:06 +0300 Subject: [PATCH 05/13] Update URLs in Russian documentation for PdfFileInfo, PdfFileSecurity, PdfFileSignature, and PdfFileStamp classes to include language prefix. Adjust descriptions and links for better navigation and consistency across the documentation. --- .../ru-step-style/scripts/check_ru_steps.py | 1 + .../media-annotations/_index.md | 2 +- .../shape-annotations/_index.md | 2 +- .../advanced-operations/artifacts/_index.md | 2 +- .../artifacts/add-bates-numbering/_index.md | 2 +- .../artifacts-header-footer/_index.md | 2 +- .../artifacts/counting-artifacts/_index.md | 2 +- .../compare-pdf-documents/_index.md | 2 +- .../links/_index.md | 2 +- .../links/extract-links/_index.md | 2 +- .../links/update-links/_index.md | 2 +- .../securing-and-signing/_index.md | 2 +- .../digitally-sign-pdf-file/_index.md | 2 +- .../extract-signature-info/_index.md | 5 +++-- .../set-privileges/_index.md | 2 +- .../_index.md | 2 +- .../create-pdf-document/_index.md | 2 +- .../manipulate-pdf-document/_index.md | 2 +- .../merge-pdf/_index.md | 2 +- .../working-with-graphs/arc/_index.md | 4 ++-- .../checking-shape-bounds/_index.md | 3 ++- .../working-with-graphs/circle/_index.md | 4 ++-- .../working-with-graphs/curve/_index.md | 4 ++-- .../working-with-graphs/ellipse/_index.md | 3 ++- .../working-with-graphs/line/_index.md | 3 ++- .../working-with-graphs/rectangle/_index.md | 4 ++-- .../add-image-to-existing-pdf-file/_index.md | 3 ++- .../delete-images-from-pdf-file/_index.md | 4 ++-- .../extract-images-from-pdf-file/_index.md | 3 ++- .../_index.md | 3 ++- .../_index.md | 3 ++- .../_index.md | 4 ++-- .../working-with-pages/rotate-pages/_index.md | 2 +- .../working-with-text/_index.md | 2 +- .../seach-and-get-text-from-pdf/_index.md | 2 +- .../text-formatting-inside-pdf/_index.md | 2 +- .../advanced-operations/zugferd/_index.md | 2 +- .../zugferd/attach-zugferd/_index.md | 2 +- ru/python-net/basic-operations/_index.md | 2 +- .../basic-operations/create/_index.md | 2 +- .../basic-operations/merge-pdf/_index.md | 2 +- .../basic-operations/protect/_index.md | 2 +- .../basic-operations/saving/_index.md | 2 +- .../converting/convert-html-to-pdf/_index.md | 5 +++-- .../convert-images-format-to-pdf/_index.md | 5 +++-- .../convert-other-files-to-pdf/_index.md | 5 +++-- .../converting/convert-pdf-to-excel/_index.md | 6 ++--- .../converting/convert-pdf-to-html/_index.md | 3 ++- .../convert-pdf-to-other-files/_index.md | 5 +++-- .../converting/convert-pdf-to-pdfx/_index.md | 5 +++-- .../convert-pdf-to-powerpoint/_index.md | 6 ++--- .../converting/convert-pdf-to-word/_index.md | 5 +++-- .../converting/convert-pdfx-to-pdf/_index.md | 5 +++-- ru/python-net/get-started/_index.md | 4 ++-- .../overview/technical-support/_index.md | 22 +++++++++---------- ru/python-net/whatsnew/_index.md | 2 +- ru/python-net/working-with-facades/_index.md | 3 ++- .../working-with-facades/form/_index.md | 3 ++- .../form/button-fields-and-images/_index.md | 3 ++- .../form/exporting-form-data/_index.md | 4 ++-- .../export-to-fdf/_index.md | 3 ++- .../export-to-json/_index.md | 3 ++- .../export-to-xfdf/_index.md | 3 ++- .../export-to-xml/_index.md | 3 ++- .../extract-xfa-data/_index.md | 3 ++- .../form/filling-form-fields/_index.md | 3 ++- .../fill-barcode-fields/_index.md | 3 ++- .../fill-check-box-fields/_index.md | 3 ++- .../fill-fields-by-name-and-value/_index.md | 3 ++- .../fill-list-box/_index.md | 3 ++- .../fill-radio-button-fields/_index.md | 3 ++- .../fill-text-fields/_index.md | 3 ++- .../form/importing-form-data/_index.md | 3 ++- .../import-fdf-data/_index.md | 3 ++- .../import-json-data/_index.md | 3 ++- .../import-xfdf-data/_index.md | 3 ++- .../import-xml-data/_index.md | 3 ++- .../replace-xfa-data/_index.md | 3 ++- .../form/managing-form-fields/_index.md | 4 ++-- .../flatten-all-fields/_index.md | 3 ++- .../flatten-specific-fields/_index.md | 3 ++- .../rename-form-fields/_index.md | 3 ++- .../form/reading-form-values/_index.md | 4 ++-- .../get-field-facades/_index.md | 4 ++-- .../get-field-values/_index.md | 4 ++-- .../get-radio-button-options/_index.md | 3 ++- .../get-required-field-names/_index.md | 3 ++- .../get-rich-text-values/_index.md | 3 ++- .../resolve-full-field-names/_index.md | 3 ++- .../working-with-facades/formeditor/_index.md | 3 ++- .../_index.md | 3 ++- .../add-field-script/_index.md | 3 ++- .../remove-field-action/_index.md | 3 ++- .../set-field-script/_index.md | 3 ++- .../set-submit-flag/_index.md | 3 ++- .../set-submit-url/_index.md | 3 ++- .../formeditor/creating-form-field/_index.md | 4 ++-- .../create-checkbox-field/_index.md | 3 ++- .../create-combobox-field/_index.md | 3 ++- .../create-listbox-field/_index.md | 3 ++- .../create-radiobutton-field/_index.md | 3 ++- .../create-submit-button/_index.md | 3 ++- .../create-textbox-field/_index.md | 3 ++- .../customizing-field-appearance/_index.md | 3 ++- .../decorate-field/_index.md | 3 ++- .../get-field-appearance/_index.md | 3 ++- .../set-field-alignment-vertical/_index.md | 3 ++- .../set-field-alignment/_index.md | 3 ++- .../set-field-appearance/_index.md | 3 ++- .../set-field-comb-number/_index.md | 3 ++- .../set-field-limit/_index.md | 3 ++- .../modifying-form-fields/_index.md | 3 ++- .../add-list-item/_index.md | 3 ++- .../copy-inner-field/_index.md | 3 ++- .../copy-outer-field/_index.md | 3 ++- .../del-list-item/_index.md | 3 ++- .../move-field/_index.md | 3 ++- .../remove-field/_index.md | 3 ++- .../rename-field/_index.md | 3 ++- .../single-to-multiple/_index.md | 3 ++- .../pdfannotationeditor/_index.md | 3 ++- .../pdfcontenteditor/_index.md | 3 ++- .../pdfcontenteditor/annotations/_index.md | 3 ++- .../add-caret-annotation/_index.md | 3 ++- .../add-free-text-annotation/_index.md | 3 ++- .../add-markup-annotation/_index.md | 3 ++- .../add-popup-annotation/_index.md | 3 ++- .../annotations/add-text-annotation/_index.md | 3 ++- .../pdfcontenteditor/attachments/_index.md | 3 ++- .../add-attachment-from-path/_index.md | 3 ++- .../attachments/add-attachment/_index.md | 3 ++- .../add-file-attachment-annotation/_index.md | 3 ++- .../_index.md | 3 ++- .../attachments/remove-attachments/_index.md | 3 ++- .../document-actions/_index.md | 4 ++-- .../add-bookmark-action/_index.md | 4 ++-- .../add-document-action/_index.md | 3 ++- .../remove-open-action/_index.md | 3 ++- .../drawing-annotations/_index.md | 3 ++- .../add-circle-annotation/_index.md | 3 ++- .../add-curve-annotation/_index.md | 3 ++- .../add-line-annotation/_index.md | 3 ++- .../add-polygon-annotation/_index.md | 3 ++- .../add-polyline-annotation/_index.md | 3 ++- .../add-square-annotation/_index.md | 3 ++- .../image-operations/_index.md | 4 ++-- .../delete-all-images/_index.md | 3 ++- .../image-operations/delete-images/_index.md | 3 ++- .../image-operations/replace-image/_index.md | 3 ++- .../links-and-navigation/_index.md | 3 ++- .../add-application-link/_index.md | 3 ++- .../add-custom-action-link/_index.md | 3 ++- .../add-javascript-link/_index.md | 3 ++- .../add-local-link/_index.md | 3 ++- .../add-pdf-document-link/_index.md | 3 ++- .../add-web-link/_index.md | 3 ++- .../extract-links/_index.md | 3 ++- .../pdfcontenteditor/multimedia/_index.md | 3 ++- .../multimedia/add-movie-annotation/_index.md | 3 ++- .../multimedia/add-sound-annotation/_index.md | 3 ++- .../stamps-management/_index.md | 3 ++- .../add-rubber-stamp/_index.md | 3 ++- .../_index.md | 3 ++- .../_index.md | 3 ++- .../delete-stamp-by-ids-examples/_index.md | 3 ++- .../delete-stamp-by-index/_index.md | 3 ++- .../delete-stamps-globally/_index.md | 3 ++- .../stamps-management/list-stamps/_index.md | 3 ++- .../manage-stamp-by-id/_index.md | 3 ++- .../move-stamp-by-id-example/_index.md | 3 ++- .../move-stamp-by-index/_index.md | 3 ++- .../text-operations/_index.md | 3 ++- .../replace-text-on-page-with-state/_index.md | 3 ++- .../replace-text-on-page/_index.md | 3 ++- .../replace-text-regex/_index.md | 3 ++- .../replace-text-simple/_index.md | 3 ++- .../replace-text-with-state/_index.md | 3 ++- .../viewer-preferences/_index.md | 3 ++- .../change-viewer-preferences/_index.md | 3 ++- .../get-viewer-preferences/_index.md | 3 ++- .../pdffileeditor/_index.md | 3 ++- .../booklet-and-nup-layout/_index.md | 3 ++- .../create-n-up-pdf-document/_index.md | 3 ++- .../create-pdf-booklet/_index.md | 3 ++- .../page-layout-and-margins/_index.md | 4 ++-- .../add-margins-to-pdf-pages/_index.md | 3 ++- .../add-page-breaks-in-pdf/_index.md | 3 ++- .../resize-pdf-page-contents/_index.md | 3 ++- .../pdffileeditor/page-managment/_index.md | 3 ++- .../append-pages-to-pdf/_index.md | 3 ++- .../delete-pages-from-pdf/_index.md | 4 ++-- .../extract-pages-from-pdf/_index.md | 3 ++- .../insert-pages-into-pdf/_index.md | 3 ++- .../pdffileeditor/page-merging/_index.md | 4 ++-- .../concatenate-large-number-files/_index.md | 3 ++- .../_index.md | 3 ++- .../concatenate-pdf-files/_index.md | 3 ++- .../concatenate-pdf-forms/_index.md | 3 ++- .../concatenate-two-files/_index.md | 3 ++- .../try-concatenate-pdf-files/_index.md | 3 ++- .../try-concatenate-two-files/_index.md | 3 ++- .../splitting-pdf-documents/_index.md | 3 ++- .../split-pdf-from-beginning/_index.md | 3 ++- .../split-pdf-into-single-pages/_index.md | 3 ++- .../split-pdf-to-end/_index.md | 3 ++- .../pdffileinfo/_index.md | 3 ++- .../pdffileinfo/document-properties/_index.md | 4 ++-- .../get-document-privileges/_index.md | 3 ++- .../get-pdf-version/_index.md | 3 ++- .../pdffileinfo/page-information/_index.md | 3 ++- .../page-information/get-page-info/_index.md | 3 ++- .../get-page-offset/_index.md | 3 ++- .../pdffileinfo/pdf-metadata/_index.md | 3 ++- .../pdf-metadata/clear-pdf-metadata/_index.md | 3 ++- .../pdf-metadata/get-pdf-metadata/_index.md | 3 ++- .../save-metadata-with-xmp/_index.md | 3 ++- .../pdf-metadata/set-pdf-metadata/_index.md | 3 ++- .../pdffilesecurity/_index.md | 3 ++- .../pdffilesecurity/change-password/_index.md | 3 ++- .../decrypt-pdf-file/_index.md | 3 ++- .../encrypt-pdf-file/_index.md | 3 ++- .../pdffilesecurity/set-privileges/_index.md | 3 ++- .../pdffilesignature/_index.md | 3 ++- .../pdf-certification/_index.md | 3 ++- .../pdffilesignature/pdf-signing/_index.md | 3 ++- .../revision-permissions/_index.md | 3 ++- .../signature-extraction/_index.md | 3 ++- .../signature-information/_index.md | 3 ++- .../signature-integrity-checks/_index.md | 3 ++- .../signature-management/_index.md | 3 ++- .../signature-verification/_index.md | 3 ++- .../usage-rights-management/_index.md | 3 ++- .../pdffilestamp/_index.md | 3 ++- .../pdffilestamp/add-footer/_index.md | 3 ++- .../pdffilestamp/add-header/_index.md | 3 ++- .../pdffilestamp/add-page-number/_index.md | 3 ++- .../pdffilestamp/add-stamp/_index.md | 3 ++- .../working-with-facades/stamp/_index.md | 3 ++- 238 files changed, 465 insertions(+), 279 deletions(-) diff --git a/.agents/skills/ru-step-style/scripts/check_ru_steps.py b/.agents/skills/ru-step-style/scripts/check_ru_steps.py index 2a3bc80a2..66e0feae4 100644 --- a/.agents/skills/ru-step-style/scripts/check_ru_steps.py +++ b/.agents/skills/ru-step-style/scripts/check_ru_steps.py @@ -19,6 +19,7 @@ "Загрузить": "Загрузите", "Извлечь": "Извлеките", "Преобразовать": "Преобразуйте", + "Привязать": "Привяжите", "Удалить": "Удалите", "Обновить": "Обновите", "Вызвать": "Вызовите", diff --git a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md index f57ab271c..697b8ff12 100644 --- a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md +++ b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-21" sitemap: changefreq: "monthly" priority: 0.5 -TechArticle: true +TechArticle: true AlternativeHeadline: Работайте с мультимедийными и rich media аннотациями PDF в Python. Abstract: В этой статье объясняется, как создавать и управлять медиа‑аннотациями в PDF‑документах с помощью Aspose.PDF for Python via .NET. В ней рассматриваются аннотации звука, 3D‑аннотации, аннотации экрана, аннотации rich media, а также методы перечисления или удаления мультимедийных аннотаций со страницы PDF. --- diff --git a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md index 16e049159..6b0218cd5 100644 --- a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md +++ b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-21" sitemap: changefreq: "monthly" priority: 0.5 -TechArticle: true +TechArticle: true AlternativeHeadline: Работайте с геометрическими PDF‑аннотациями в Python. Abstract: В этой статье объясняется, как создавать, читать и удалять аннотации фигур в PDF‑документах с использованием Aspose.PDF for Python via .NET. Описываются аннотации линий, квадратов, кругов, полигонов и полилиний, при этом каждый рабочий процесс разбит на небольшие шаги и содержит полные примеры кода. --- diff --git a/ru/python-net/advanced-operations/artifacts/_index.md b/ru/python-net/advanced-operations/artifacts/_index.md index 3e5106b9d..edb68dc0a 100644 --- a/ru/python-net/advanced-operations/artifacts/_index.md +++ b/ru/python-net/advanced-operations/artifacts/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Добавление фоновых изображений, водяных знаков и артефактов нумерации Bates в Python Abstract: В этой статье объясняется, как работать с артефактами PDF в Aspose.PDF for Python via .NET. Узнайте, что такое артефакты, почему они важны для доступности и верстки документа, а также как добавлять фоновые изображения, применять водяные знаки, добавлять нумерацию Bates и проверять типы артефактов в PDF‑файлах с помощью Python. --- diff --git a/ru/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md b/ru/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md index cc641476f..e6a6ac195 100644 --- a/ru/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md +++ b/ru/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Добавить нумерацию Бейтса с помощью Python Abstract: Нумерация Бейтса является критической функцией в юридических, медицинских и бизнес‑процессах работы с документами, обеспечивая уникальный последовательный идентификатор для каждой страницы набора, что повышает надёжность ссылок. В этой статье показано, как Aspose.PDF for Python via .NET упрощает автоматизацию нумерации Бейтса с помощью гибкого API. С помощью класса BatesNArtifact разработчики могут настроить поведение нумерации — включая количество цифр, префиксы, суффиксы, выравнивание и отступы — и применить её программно ко всему документу. Представлено несколько подходов, от прямого применения артефакта до конфигурации на основе делегатов, предлагающих как статический, так и динамический контроль. Кроме того, API поддерживает полное удаление номеров Бейтса одним вызовом метода, обеспечивая полное управление жизненным циклом артефактов нумерации. Чёткие пошаговые примеры кода демонстрируют, как добавить, настроить и удалить нумерацию Бейтса, делая это руководство практическим ресурсом для разработчиков, желающих оптимизировать процессы обработки документов. --- diff --git a/ru/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md b/ru/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md index e858bad45..40b4cf464 100644 --- a/ru/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md +++ b/ru/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-21" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Как добавлять, настраивать и удалять заголовки и нижние колонтитулы PDF с использованием Python Abstract: Управление колонтитулами — это распространённое требование при работе с PDF‑документами в бизнесе, издательском деле и автоматизированных рабочих процессах. В этой статье демонстрируется, как с помощью Aspose.PDF for Python добавить профессиональные колонтитулы с пользовательским оформлением, таким как шрифт, размер, цвет и выравнивание. Также показывается, как обнаруживать и удалять существующие артефакты нумерации страниц, такие как колонтитулы, на странице PDF. Благодаря переиспользуемым функциям и понятным примерам разработчики могут быстро интегрировать эти возможности в системы обработки документов для брендирования, отчётности или очистки файлов. --- diff --git a/ru/python-net/advanced-operations/artifacts/counting-artifacts/_index.md b/ru/python-net/advanced-operations/artifacts/counting-artifacts/_index.md index 0d787d9b5..005b7f0cc 100644 --- a/ru/python-net/advanced-operations/artifacts/counting-artifacts/_index.md +++ b/ru/python-net/advanced-operations/artifacts/counting-artifacts/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Подсчёт артефактов в PDF с использованием Python Abstract: Артефакты разметки страниц, такие как водяные знаки, фоны, заголовки и колонтитулы, обычно используются в PDF‑документах для обеспечения структуры, брендинга и идентификации. Этот пример демонстрирует, как программно просматривать и подсчитывать эти артефакты с помощью Aspose.PDF for Python via .NET. Фильтруя артефакты на странице и группируя их по подтипу, разработчики могут быстро анализировать состав документа и проверять наличие определённых элементов. Приведённый код иллюстрирует, как открыть PDF, извлечь артефакты разметки страниц с первой страницы, подсчитать каждый подтип и вывести результаты, предлагая практический подход к аудиту и проверке документов. --- diff --git a/ru/python-net/advanced-operations/compare-pdf-documents/_index.md b/ru/python-net/advanced-operations/compare-pdf-documents/_index.md index aeb8b5fbc..d8a826f75 100644 --- a/ru/python-net/advanced-operations/compare-pdf-documents/_index.md +++ b/ru/python-net/advanced-operations/compare-pdf-documents/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Сравните страницы PDF и полные документы с визуальным выводом различий в Python Abstract: В этой статье объясняется, как сравнивать PDF‑документы в Aspose.PDF for Python via .NET. Узнайте, как сравнивать отдельные страницы или целые PDF‑файлы с выводом рядом, а также как использовать графические методы сравнения для создания отчетов о различиях в виде изображений или PDF‑документов. --- diff --git a/ru/python-net/advanced-operations/navigation-and-interaction/links/_index.md b/ru/python-net/advanced-operations/navigation-and-interaction/links/_index.md index 8055b4a26..ac331c364 100644 --- a/ru/python-net/advanced-operations/navigation-and-interaction/links/_index.md +++ b/ru/python-net/advanced-operations/navigation-and-interaction/links/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Создание, извлечение и обновление PDF‑ссылок в Python Abstract: Руководство Aspose.PDF for Python via .NET по работе со ссылками предоставляет всесторонний обзор того, как разработчики могут программно управлять гиперссылками и элементами навигации в PDF‑документах с помощью Python. В нём рассматриваются основные операции, такие как создание внутренних и внешних ссылок, обновление назначений и внешнего вида ссылок, а также извлечение существующих ссылок. --- diff --git a/ru/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md b/ru/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md index 958c4ac18..0640e418e 100644 --- a/ru/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md +++ b/ru/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Как извлечь ссылки из PDF Abstract: Руководство Aspose.PDF for Python via .NET по извлечению ссылок объясняет, как программно получать аннотации гиперссылок из PDF‑документов с помощью Python. Документация включает практические примеры кода и подчёркивает, как эту функцию можно использовать для таких задач, как аудит ссылок, анализ навигации или создание интерактивных возможностей документа. Независимо от того, работаете ли вы с одностраничными PDF или обрабатываете большие партии, это руководство предлагает ясный и эффективный подход к извлечению гиперссылок. --- diff --git a/ru/python-net/advanced-operations/navigation-and-interaction/links/update-links/_index.md b/ru/python-net/advanced-operations/navigation-and-interaction/links/update-links/_index.md index eb6d8ca3d..84cc9b41e 100644 --- a/ru/python-net/advanced-operations/navigation-and-interaction/links/update-links/_index.md +++ b/ru/python-net/advanced-operations/navigation-and-interaction/links/update-links/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Как обновить ссылки в PDF Abstract: Руководство Aspose.PDF for Python via .NET по обновлению ссылок проводит разработчиков через процесс изменения поведения гиперссылок внутри PDF‑документов с использованием Python. Оно объясняет, как изменить назначения ссылок, чтобы они указывали на конкретные страницы, внешние веб‑сайты или даже другие PDF‑файлы. Документация также охватывает, как настроить внешний вид аннотаций ссылок, включая цвет текста, и предоставляет практические примеры кода для каждого сценария. Если вы исправляете устаревшие URL‑адреса или улучшаете навигацию, этот ресурс предлагает понятный и эффективный подход к программному управлению ссылками. --- diff --git a/ru/python-net/advanced-operations/securing-and-signing/_index.md b/ru/python-net/advanced-operations/securing-and-signing/_index.md index 0add4d858..4e5e62d00 100644 --- a/ru/python-net/advanced-operations/securing-and-signing/_index.md +++ b/ru/python-net/advanced-operations/securing-and-signing/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Подписывайте, шифруйте, дешифруйте и защищайте PDF‑документы в Python Abstract: Этот раздел объясняет, как защищать и подписывать PDF‑документы с использованием Aspose.PDF for Python via .NET. Узнайте, как применять цифровые подписи, использовать смарт‑карты и сертификаты, извлекать информацию о подписи и управлять шифрованием PDF, паролями и правами доступа в Python. --- diff --git a/ru/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md b/ru/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md index 7797491d3..1bf66c406 100644 --- a/ru/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md +++ b/ru/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Подписывайте цифровой подписью PDF‑файлы с помощью Python. Abstract: Это руководство объясняет, как подписывать цифровой подписью PDF‑документы с помощью Aspose.PDF for Python via .NET. В нём подробно описан процесс применения стандартных и продвинутых цифровых подписей, использование сертификатов (PFX и PKCS#12) и настройка внешнего вида и поведения подписи. Документация содержит примеры кода, демонстрирующие, как подписывать существующие PDF, добавлять метки времени и проверять валидность подписи. Это позволяет разработчикам обеспечивать подлинность, целостность документов и соответствие стандартам цифровой подписи в их Python‑приложениях. --- diff --git a/ru/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md b/ru/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md index c39ffd1ff..61169df4d 100644 --- a/ru/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md +++ b/ru/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md @@ -3,13 +3,13 @@ title: Извлечь информацию о подписи из PDF на Pytho linktitle: Извлечь детали из подписи type: docs weight: 20 -url: /python-net/extract-image-and-signature-information/ +url: /ru/python-net/extract-image-and-signature-information/ description: Узнайте, как извлекать изображения подписей, сертификаты и детали цифровой подписи из PDF‑файлов на Python. lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Извлекайте изображения подписей и детали сертификатов из PDF‑файлов на Python. Abstract: В этой статье объясняется, как извлекать изображения и информацию о цифровой подписи из PDF‑документов с помощью Aspose.PDF for Python. Узнайте, как получать изображения подписи, извлекать данные сертификата, проверять алгоритмы подписи и обнаруживать скомпрометированные подписи в подписанных PDF‑файлах. --- @@ -168,3 +168,4 @@ def check(infile: str) -> None: - [Электронно подписывать PDF-файлы на Python](/pdf/ru/python-net/digitally-sign-pdf-file/) - [Подписать PDF‑документы со смарт‑карты в Python](/pdf/ru/python-net/sign-pdf-document-from-smart-card/) - [Шифрование и дешифрование PDF‑файлов в Python](/pdf/ru/python-net/set-privileges-encrypt-and-decrypt-pdf-file/) + diff --git a/ru/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md b/ru/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md index 82b627251..3a5e2c3de 100644 --- a/ru/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md +++ b/ru/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Установите разрешения PDF и управляйте шифрованием в Python. Abstract: Эта страница документации объясняет, как задать привилегии документа, применить шифрование и расшифровать PDF‑файлы с помощью Aspose.PDF for Python. Она направляет разработчиков через настройку пользовательских и владельческих паролей, определение ограничений доступа (например, печать, копирование или редактирование). Примеры кода демонстрируют, как защищать конфиденциальный контент и эффективно управлять безопасностью PDF в приложениях Python, обеспечивая контролируемый доступ и конфиденциальность данных. --- diff --git a/ru/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md b/ru/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md index c833d18cd..4f939224f 100644 --- a/ru/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md +++ b/ru/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Подписать PDF‑документы со смарт‑карты на Python Abstract: Это руководство объясняет, как цифрово подписывать PDF‑документы с использованием смарт‑карты и Aspose.PDF for Python via .NET. В нём показано, как получить доступ к сертификатам, хранящимся на аппаратных устройствах (например, USB‑токенах или смарт‑картах) через хранилище сертификатов Windows, и использовать их для подписи PDF‑файлов. Документация включает примеры кода, демонстрирующие, как найти нужный сертификат, настроить свойства подписи и встроить цифровую подпись в PDF. Это обеспечивает безопасную подпись, поддерживаемую аппаратным обеспечением, в соответствии с требованиями стандартов цифровой подписи, подходящую для высокодоверительных корпоративных и юридических процессов. --- diff --git a/ru/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md b/ru/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md index 8eef0701d..cc342c284 100644 --- a/ru/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md +++ b/ru/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Создать PDF файл с Python Abstract: Aspose.PDF for Python via .NET — это универсальный API, предназначенный для разработчиков, позволяющий манипулировать PDF‑файлами в Python‑приложениях, ориентированных на платформу .NET. Он позволяет пользователям легко создавать, загружать, изменять и конвертировать PDF‑документы. В этой статье представлено пошаговое руководство по созданию простого PDF‑файла с помощью Aspose.PDF. Процесс включает инициализацию объекта `Document`, добавление `Page` в документ, вставку `TextFragment` в абзацы страницы и сохранение файла в формате PDF. Включённый фрагмент кода на Python демонстрирует эти шаги, создавая PDF‑документ, содержащий текст "Hello World!". Этот API упрощает работу с PDF при минимальном количестве кода, повышая производительность разработчиков, работающих с PDF в среде .NET. --- diff --git a/ru/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md b/ru/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md index a4d33509e..1925b8d0e 100644 --- a/ru/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md +++ b/ru/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Руководство по работе с PDF‑документами с использованием Python Abstract: Эта статья предоставляет комплексное руководство по манипулированию PDF‑документами с использованием Python, конкретно с библиотекой Aspose.PDF. В ней рассматриваются несколько функций, включая проверку PDF‑документов на соответствие PDF/A-1a и PDF/A-1b с помощью метода `validate` класса `Document`. Также подробно описывается, как добавить, настроить и управлять оглавлением (Table of Contents (TOC)) в PDF‑файлах, например установка различных TabLeaderTypes, скрытие номеров страниц и настройка нумерации страниц с префиксом. Кроме того, статья объясняет, как установить дату истечения срока действия PDF‑документа, внедрив JavaScript для ограничения доступа, и как уплощать заполняемые формы в PDF, делая их не редактируемыми. Каждый раздел сопровождается фрагментами кода, демонстрирующими реализацию этих возможностей с использованием Aspose.PDF в Python. --- diff --git a/ru/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md b/ru/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md index f9ac0a90b..510bd1f1d 100644 --- a/ru/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md +++ b/ru/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Объединяйте страницы PDF с помощью Python Abstract: В этой статье рассматривается распространённая необходимость объединения нескольких PDF‑файлов в один документ, процесс, полезный для организации, оптимизации хранения и совместного использования PDF‑контента. Описывается использование Aspose.PDF for Python via .NET для эффективного сочетания PDF‑файлов, с учётом того, что объединение PDF в Python может быть сложным без сторонних библиотек. Статья представляет пошаговое руководство по конкатенации PDF‑файлов — создание нового документа, объединение файлов и сохранение объединённого документа. Фрагмент кода демонстрирует реализацию с использованием Aspose.PDF, подчёркивая возможность библиотеки упростить процесс объединения. Кроме того, представляется Aspose.PDF Merger — онлайн‑инструмент для объединения PDF, позволяющий пользователям исследовать функциональность в веб‑среде. --- diff --git a/ru/python-net/advanced-operations/working-with-graphs/arc/_index.md b/ru/python-net/advanced-operations/working-with-graphs/arc/_index.md index 1edf077ec..51696c733 100644 --- a/ru/python-net/advanced-operations/working-with-graphs/arc/_index.md +++ b/ru/python-net/advanced-operations/working-with-graphs/arc/_index.md @@ -3,7 +3,7 @@ title: Добавить объекты дуг в PDF на Python linktitle: Добавить дугу type: docs weight: 10 -url: /python-net/add-arc/ +url: /ru/python-net/add-arc/ description: Узнайте, как рисовать и заливать формы дуг в PDF‑файлах на Python. lastmod: "2026-04-16" sitemap: @@ -92,4 +92,4 @@ def add_arc_filled(outfile: str): - [Работа с графами PDF в Python](/pdf/ru/python-net/working-with-graphs/) - [Добавление круговых фигур в PDF с помощью Python](/pdf/ru/python-net/add-circle/) - [Добавить кривые формы в PDF на Python](/pdf/ru/python-net/add-curve/) -- [Добавить линейные формы в PDF на Python](/pdf/ru/python-net/add-line/) \ No newline at end of file +- [Добавить линейные формы в PDF на Python](/pdf/ru/python-net/add-line/) diff --git a/ru/python-net/advanced-operations/working-with-graphs/checking-shape-bounds/_index.md b/ru/python-net/advanced-operations/working-with-graphs/checking-shape-bounds/_index.md index 524023a41..7459a9fec 100644 --- a/ru/python-net/advanced-operations/working-with-graphs/checking-shape-bounds/_index.md +++ b/ru/python-net/advanced-operations/working-with-graphs/checking-shape-bounds/_index.md @@ -3,7 +3,7 @@ title: Проверка границ фигур в графах PDF с Python linktitle: Проверить границы фигур type: docs weight: 70 -url: /python-net/aspose-pdf-drawing-graph-shapes-bounds-check/ +url: /ru/python-net/aspose-pdf-drawing-graph-shapes-bounds-check/ description: Узнайте, как проверять границы фигур в коллекциях графов PDF с помощью Python. lastmod: "2026-04-16" sitemap: @@ -70,3 +70,4 @@ def check_shape_bounds(outfile: str): - [Добавить прямоугольные фигуры в PDF в Python](/pdf/ru/python-net/add-rectangle/) - [Добавить линейные фигуры в PDF в Python](/pdf/ru/python-net/add-line/) - [Добавить эллиптические фигуры в PDF в Python](/pdf/ru/python-net/add-ellipse/) + diff --git a/ru/python-net/advanced-operations/working-with-graphs/circle/_index.md b/ru/python-net/advanced-operations/working-with-graphs/circle/_index.md index 6fc5e8c14..d422c288a 100644 --- a/ru/python-net/advanced-operations/working-with-graphs/circle/_index.md +++ b/ru/python-net/advanced-operations/working-with-graphs/circle/_index.md @@ -3,7 +3,7 @@ title: Добавить круглые формы в PDF на Python linktitle: Добавить круг type: docs weight: 20 -url: /python-net/add-circle/ +url: /ru/python-net/add-circle/ description: Узнайте, как рисовать и заполнять формы кругов в PDF‑файлах на Python. lastmod: "2026-04-16" sitemap: @@ -81,4 +81,4 @@ def add_circle_filled(outfile: str): - [Работа с графиками PDF в Python](/pdf/ru/python-net/working-with-graphs/) - [Добавление дуговых фигур в PDF на Python](/pdf/ru/python-net/add-arc/) - [Добавить эллипсные фигуры в PDF на Python](/pdf/ru/python-net/add-ellipse/) -- [Добавить прямоугольные фигуры в PDF на Python](/pdf/ru/python-net/add-rectangle/) \ No newline at end of file +- [Добавить прямоугольные фигуры в PDF на Python](/pdf/ru/python-net/add-rectangle/) diff --git a/ru/python-net/advanced-operations/working-with-graphs/curve/_index.md b/ru/python-net/advanced-operations/working-with-graphs/curve/_index.md index f8b2c7510..9c7b66f95 100644 --- a/ru/python-net/advanced-operations/working-with-graphs/curve/_index.md +++ b/ru/python-net/advanced-operations/working-with-graphs/curve/_index.md @@ -3,7 +3,7 @@ title: Добавить кривые формы в PDF на Python linktitle: Добавить кривую type: docs weight: 30 -url: /python-net/add-curve/ +url: /ru/python-net/add-curve/ description: Узнайте, как рисовать и заполнять кривые формы в PDF‑файлах на Python. lastmod: "2026-04-16" sitemap: @@ -82,4 +82,4 @@ def add_curve_filled(outfile: str): - [Работа с графиками PDF в Python](/pdf/ru/python-net/working-with-graphs/) - [Добавление дуговых фигур в PDF с помощью Python](/pdf/ru/python-net/add-arc/) - [Добавить линейные формы в PDF на Python](/pdf/ru/python-net/add-line/) -- [Добавить эллиптические формы в PDF на Python](/pdf/ru/python-net/add-ellipse/) \ No newline at end of file +- [Добавить эллиптические формы в PDF на Python](/pdf/ru/python-net/add-ellipse/) diff --git a/ru/python-net/advanced-operations/working-with-graphs/ellipse/_index.md b/ru/python-net/advanced-operations/working-with-graphs/ellipse/_index.md index 3ad8152a3..2911bd490 100644 --- a/ru/python-net/advanced-operations/working-with-graphs/ellipse/_index.md +++ b/ru/python-net/advanced-operations/working-with-graphs/ellipse/_index.md @@ -3,7 +3,7 @@ title: Добавить эллиптические формы в PDF на Python linktitle: Добавить эллипс type: docs weight: 60 -url: /python-net/add-ellipse/ +url: /ru/python-net/add-ellipse/ description: Узнайте, как рисовать, заполнять и подписывать эллиптические формы в PDF‑файлах на Python. lastmod: "2026-04-16" sitemap: @@ -111,3 +111,4 @@ def add_text_inside_ellipse(outfile: str): - [Добавить формы круга в PDF в Python](/pdf/ru/python-net/add-circle/) - [Добавить формы кривой в PDF в Python](/pdf/ru/python-net/add-curve/) - [Добавьте прямоугольные фигуры в PDF на Python](/pdf/ru/python-net/add-rectangle/) + diff --git a/ru/python-net/advanced-operations/working-with-graphs/line/_index.md b/ru/python-net/advanced-operations/working-with-graphs/line/_index.md index 52449ffd7..3fd3e7ce3 100644 --- a/ru/python-net/advanced-operations/working-with-graphs/line/_index.md +++ b/ru/python-net/advanced-operations/working-with-graphs/line/_index.md @@ -3,7 +3,7 @@ title: Добавить линейные фигуры в PDF на Python linktitle: Добавить линию type: docs weight: 40 -url: /python-net/add-line/ +url: /ru/python-net/add-line/ description: Узнайте, как рисовать линейные фигуры и стилизованные линии в PDF‑файлах на Python. lastmod: "2026-04-16" sitemap: @@ -107,3 +107,4 @@ def draw_line_across_page(outfile: str): - [Добавить кривые формы в PDF в Python](/pdf/ru/python-net/add-curve/) - [Добавить прямоугольные формы в PDF в Python](/pdf/ru/python-net/add-rectangle/) - [Проверьте границы фигур в графиках PDF с помощью Python](/pdf/ru/python-net/aspose-pdf-drawing-graph-shapes-bounds-check/) + diff --git a/ru/python-net/advanced-operations/working-with-graphs/rectangle/_index.md b/ru/python-net/advanced-operations/working-with-graphs/rectangle/_index.md index 36cd68527..1b86e960d 100644 --- a/ru/python-net/advanced-operations/working-with-graphs/rectangle/_index.md +++ b/ru/python-net/advanced-operations/working-with-graphs/rectangle/_index.md @@ -3,7 +3,7 @@ title: Добавить прямоугольные фигуры в PDF на Pyth linktitle: Добавить прямоугольник type: docs weight: 50 -url: /python-net/add-rectangle/ +url: /ru/python-net/add-rectangle/ description: Узнайте, как рисовать и заполнять прямоугольные фигуры в PDF‑файлах с помощью Python. lastmod: "2026-04-16" sitemap: @@ -192,4 +192,4 @@ def control_z_order_of_rectangle(outfile: str): - [Работайте с графиками PDF в Python](/pdf/ru/python-net/working-with-graphs/) - [Проверьте границы фигур в PDF‑графиках с помощью Python](/pdf/ru/python-net/aspose-pdf-drawing-graph-shapes-bounds-check/) - [Добавить линейные фигуры в PDF с помощью Python](/pdf/ru/python-net/add-line/) -- [Добавьте эллипсные формы в PDF с помощью Python](/pdf/ru/python-net/add-ellipse/) \ No newline at end of file +- [Добавьте эллипсные формы в PDF с помощью Python](/pdf/ru/python-net/add-ellipse/) diff --git a/ru/python-net/advanced-operations/working-with-images/add-image-to-existing-pdf-file/_index.md b/ru/python-net/advanced-operations/working-with-images/add-image-to-existing-pdf-file/_index.md index d1b3c6b44..b991a8b44 100644 --- a/ru/python-net/advanced-operations/working-with-images/add-image-to-existing-pdf-file/_index.md +++ b/ru/python-net/advanced-operations/working-with-images/add-image-to-existing-pdf-file/_index.md @@ -3,7 +3,7 @@ title: Добавить изображение в PDF с помощью Python linktitle: Добавить изображение type: docs weight: 10 -url: /python-net/add-image-to-existing-pdf-file/ +url: /ru/python-net/add-image-to-existing-pdf-file/ description: Узнайте, как добавить изображения в существующие PDF‑файлы с помощью Python. lastmod: "2026-05-05" TechArticle: true @@ -157,3 +157,4 @@ def add_image_to_pdf_with_flate_compression(image_file, outfile): - [Замена изображений в существующих PDF-файлах](/pdf/ru/python-net/replace-image-in-existing-pdf-file/) - [Удалить изображения из PDF файлов](/pdf/ru/python-net/delete-images-from-pdf-file/) - [Извлечь изображения из PDF файлов](/pdf/ru/python-net/extract-images-from-pdf-file/) + diff --git a/ru/python-net/advanced-operations/working-with-images/delete-images-from-pdf-file/_index.md b/ru/python-net/advanced-operations/working-with-images/delete-images-from-pdf-file/_index.md index a6c94c8f7..4d16a16e6 100644 --- a/ru/python-net/advanced-operations/working-with-images/delete-images-from-pdf-file/_index.md +++ b/ru/python-net/advanced-operations/working-with-images/delete-images-from-pdf-file/_index.md @@ -3,7 +3,7 @@ title: Удалить изображения из PDF‑файла с помощ linktitle: Удалить изображения type: docs weight: 20 -url: /python-net/delete-images-from-pdf-file/ +url: /ru/python-net/delete-images-from-pdf-file/ description: Узнайте, как удалить конкретные или все изображения из PDF‑файлов с помощью Python. lastmod: "2026-05-05" TechArticle: true @@ -55,4 +55,4 @@ def delete_all_images_from_page(infile, outfile, page_number): - [Работа с изображениями в PDF с использованием Python](/pdf/ru/python-net/working-with-images/) - [Замена изображений в существующих PDF‑файлах](/pdf/ru/python-net/replace-image-in-existing-pdf-file/) - [Извлечение изображений из PDF‑файлов](/pdf/ru/python-net/extract-images-from-pdf-file/) -- [Добавление изображений в существующие PDF‑файлы](/pdf/ru/python-net/add-image-to-existing-pdf-file/) \ No newline at end of file +- [Добавление изображений в существующие PDF‑файлы](/pdf/ru/python-net/add-image-to-existing-pdf-file/) diff --git a/ru/python-net/advanced-operations/working-with-images/extract-images-from-pdf-file/_index.md b/ru/python-net/advanced-operations/working-with-images/extract-images-from-pdf-file/_index.md index e29b03e06..381ea3024 100644 --- a/ru/python-net/advanced-operations/working-with-images/extract-images-from-pdf-file/_index.md +++ b/ru/python-net/advanced-operations/working-with-images/extract-images-from-pdf-file/_index.md @@ -3,7 +3,7 @@ title: Извлечение изображений из PDF-файла с пом linktitle: Извлечь изображения type: docs weight: 30 -url: /python-net/extract-images-from-pdf-file/ +url: /ru/python-net/extract-images-from-pdf-file/ description: Узнайте, как извлекать встроенные изображения из PDF‑файлов с помощью Python. lastmod: "2026-05-05" TechArticle: true @@ -67,3 +67,4 @@ def extract_image_from_specific_region(infile, outfile): - [Замена изображений в существующих PDF-файлах](/pdf/ru/python-net/replace-image-in-existing-pdf-file/) - [Удаление изображений из PDF-файлов](/pdf/ru/python-net/delete-images-from-pdf-file/) - [Добавление изображений в существующие PDF-файлы](/pdf/ru/python-net/add-image-to-existing-pdf-file/) + diff --git a/ru/python-net/advanced-operations/working-with-images/replace-image-in-existing-pdf-file/_index.md b/ru/python-net/advanced-operations/working-with-images/replace-image-in-existing-pdf-file/_index.md index f192768fd..682ce8ec3 100644 --- a/ru/python-net/advanced-operations/working-with-images/replace-image-in-existing-pdf-file/_index.md +++ b/ru/python-net/advanced-operations/working-with-images/replace-image-in-existing-pdf-file/_index.md @@ -3,7 +3,7 @@ title: Заменить изображение в существующем PDF linktitle: Заменить изображение type: docs weight: 70 -url: /python-net/replace-image-in-existing-pdf-file/ +url: /ru/python-net/replace-image-in-existing-pdf-file/ description: Узнайте, как заменять встроенные изображения в существующих PDF‑файлах с помощью Python. lastmod: "2026-05-05" TechArticle: true @@ -68,3 +68,4 @@ def replace_image_with_absorber(infile, image_file, outfile): - [Удалить изображения из PDF‑файлов](/pdf/ru/python-net/delete-images-from-pdf-file/) - [Извлечь изображения из PDF‑файлов](/pdf/ru/python-net/extract-images-from-pdf-file/) - [Добавить изображения в существующие PDF‑файлы](/pdf/ru/python-net/add-image-to-existing-pdf-file/) + diff --git a/ru/python-net/advanced-operations/working-with-images/search-and-get-images-from-pdf-document/_index.md b/ru/python-net/advanced-operations/working-with-images/search-and-get-images-from-pdf-document/_index.md index d17960629..07f69db9a 100644 --- a/ru/python-net/advanced-operations/working-with-images/search-and-get-images-from-pdf-document/_index.md +++ b/ru/python-net/advanced-operations/working-with-images/search-and-get-images-from-pdf-document/_index.md @@ -3,7 +3,7 @@ title: Получать и искать изображения в PDF linktitle: Получать и искать изображения type: docs weight: 40 -url: /python-net/search-and-get-images-from-pdf-document/ +url: /ru/python-net/search-and-get-images-from-pdf-document/ description: Узнайте, как искать и проверять изображения в PDF‑документах с помощью Python. lastmod: "2026-04-17" TechArticle: true @@ -234,3 +234,4 @@ def extract_image_alt_text(infile): - [Извлечь изображения из PDF‑файлов](/pdf/ru/python-net/extract-images-from-pdf-file/) - [Заменить изображения в существующих PDF‑файлах](/pdf/ru/python-net/replace-image-in-existing-pdf-file/) - [Добавить изображения в существующие PDF-файлы](/pdf/ru/python-net/add-image-to-existing-pdf-file/) + diff --git a/ru/python-net/advanced-operations/working-with-pages/adding-headers-and-footers-of-pdf-file/_index.md b/ru/python-net/advanced-operations/working-with-pages/adding-headers-and-footers-of-pdf-file/_index.md index 8147905a3..97c0644f9 100644 --- a/ru/python-net/advanced-operations/working-with-pages/adding-headers-and-footers-of-pdf-file/_index.md +++ b/ru/python-net/advanced-operations/working-with-pages/adding-headers-and-footers-of-pdf-file/_index.md @@ -3,7 +3,7 @@ title: Добавить колонтитулы в PDF в Python linktitle: Добавление колонтитулов в PDF type: docs weight: 50 -url: /python-net/add-headers-and-footers-of-pdf-file/ +url: /ru/python-net/add-headers-and-footers-of-pdf-file/ description: Узнайте, как добавить верхние и нижние колонтитулы в PDF‑файлы с помощью Python, используя текст, изображения и структурированное содержимое. lastmod: "2026-05-05" sitemap: @@ -340,4 +340,4 @@ def add_header_and_footer_as_latex(input_file, output_file): - [Работа со страницами PDF в Python](/pdf/ru/python-net/working-with-pages/) - [Добавить номера страниц в PDF с помощью Python](/pdf/ru/python-net/add-page-number/) - [Поставить штамп на страницы PDF в Python](/pdf/ru/python-net/stamping/) -- [Форматировать PDF‑документы в Python](/pdf/ru/python-net/formatting-pdf-document/) \ No newline at end of file +- [Форматировать PDF‑документы в Python](/pdf/ru/python-net/formatting-pdf-document/) diff --git a/ru/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md b/ru/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md index e447f2796..8a3ca18f9 100644 --- a/ru/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md +++ b/ru/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Как вращать страницы в PDF с помощью Python Abstract: В этой статье представлено руководство о том, как программно обновлять или менять ориентацию страниц в существующем PDF‑файле с использованием Python. С помощью Aspose.PDF for Python via .NET пользователи могут легко переключаться между альбомной и книжной ориентацией, регулируя свойства MediaBox страницы. В статье включён фрагмент кода на Python, демонстрирующий, как проходить по страницам PDF‑документа, изменять размеры и позиции их MediaBox и при необходимости корректировать CropBox. Кроме того, объясняется, как установить угол поворота страниц с помощью метода ‘rotate’, чтобы достичь нужной ориентации. Процесс завершается сохранением обновлённого PDF‑файла. --- diff --git a/ru/python-net/advanced-operations/working-with-text/_index.md b/ru/python-net/advanced-operations/working-with-text/_index.md index 8917220a6..cbe5eecba 100644 --- a/ru/python-net/advanced-operations/working-with-text/_index.md +++ b/ru/python-net/advanced-operations/working-with-text/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-17" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Добавляйте, форматируйте, ищите, заменяйте и вращайте текст PDF в Python Abstract: В этом разделе объясняется, как работать с текстом в PDF‑документах с использованием Aspose.PDF for Python via .NET. Узнайте, как добавлять и форматировать текст, создавать подсказки и плавающие текстовые макеты, искать и извлекать текст, заменять существующий текст и вращать текстовые элементы в Python‑рабочих процессах. --- diff --git a/ru/python-net/advanced-operations/working-with-text/seach-and-get-text-from-pdf/_index.md b/ru/python-net/advanced-operations/working-with-text/seach-and-get-text-from-pdf/_index.md index 772494056..2bfdc6b25 100644 --- a/ru/python-net/advanced-operations/working-with-text/seach-and-get-text-from-pdf/_index.md +++ b/ru/python-net/advanced-operations/working-with-text/seach-and-get-text-from-pdf/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-17" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Как выполнять поиск и получать текст со страниц в PDF Abstract: Статья предоставляет подробное исследование возможностей извлечения и манипуляции текстом в PDF‑документах с использованием библиотеки Aspose.PDF for Python via .NET. В ней представляется класс TextFragmentAbsorber, который позволяет разработчикам выполнять поиск по всему документу или по конкретным страницам для заданных фраз или шаблонов регулярных выражений. Страница описывает различные практические сценарии — такие как получение текстового содержимого, определение его позиции (включая координаты и значения отступов) и извлечение свойств шрифта, например имени, размера, статуса встраивания и цвета, — из найденных текстовых фрагментов. Подробные примеры кода демонстрируют процесс пошагово, упрощая разработчикам интеграцию возможностей поиска текста в их приложения. --- diff --git a/ru/python-net/advanced-operations/working-with-text/text-formatting-inside-pdf/_index.md b/ru/python-net/advanced-operations/working-with-text/text-formatting-inside-pdf/_index.md index e97e29088..ce3f4e42d 100644 --- a/ru/python-net/advanced-operations/working-with-text/text-formatting-inside-pdf/_index.md +++ b/ru/python-net/advanced-operations/working-with-text/text-formatting-inside-pdf/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-17" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Форматирование и стилизация текста внутри PDF-файлов с помощью Python Abstract: В этой статье объясняется, как форматировать текст в PDF-документах с помощью Aspose.PDF for Python via .NET. Вы узнаете, как управлять межстрочным и межсимвольным интервалом, отступами, границами, подчёркиванием, зачёркиванием и другими параметрами стилизации текста на Python. --- diff --git a/ru/python-net/advanced-operations/zugferd/_index.md b/ru/python-net/advanced-operations/zugferd/_index.md index 38e7f0845..002dc2386 100644 --- a/ru/python-net/advanced-operations/zugferd/_index.md +++ b/ru/python-net/advanced-operations/zugferd/_index.md @@ -9,7 +9,7 @@ lastmod: "2025-02-27" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Счета ZUGFeRD с Aspose.PDF в Python Abstract: ZUGFeRD — это стандарт электронных счетов, преимущественно используемый в Германии и других странах ЕС, предназначенный для оптимизации процесса B2B‑выставления счетов через полностью цифровой формат. Он упрощает эффективное создание, передачу и обработку электронных счетов, способствуя экономии затрат и повышению операционной эффективности. Формат ZUGFeRD уникально сочетает человекочитаемый PDF с машинно‑читаемым XML, обеспечивая совместимость между различными программными платформами. Этот стандарт соответствует юридическим требованиям по архивированию и налоговому соответствию и соответствует европейскому стандарту EN 16931. Последняя версия, ZUGFeRD 2.0, предлагает различные профили для удовлетворения разнообразных бизнес‑потребностей, предоставляя такие преимущества, как более быстрая обработка, уменьшение ошибок, улучшенный денежный поток и меньшее влияние на окружающую среду. В статье также упоминаются ресурсы для реализации PDF, совместимых с ZUGFeRD, на Python, Java и .NET. --- diff --git a/ru/python-net/advanced-operations/zugferd/attach-zugferd/_index.md b/ru/python-net/advanced-operations/zugferd/attach-zugferd/_index.md index 1b91bff98..c09eb6c2a 100644 --- a/ru/python-net/advanced-operations/zugferd/attach-zugferd/_index.md +++ b/ru/python-net/advanced-operations/zugferd/attach-zugferd/_index.md @@ -9,7 +9,7 @@ lastmod: "2025-02-27" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Как прикрепить ZUGFeRD к PDF‑документу Abstract: В статье представлено пошаговое руководство по прикреплению ZUGFeRD (формата электронных счетов) к PDF‑документу с использованием библиотеки Aspose.PDF. Процедура начинается с импорта необходимой библиотеки и настройки путей к каталогам входных и выходных файлов. Затем целевой PDF‑файл загружается в объект Document, а для XML‑файла метаданных счета создаётся объект FileSpecification. Ключевые свойства, такие как `mime_type` и `af_relationship`, устанавливаются для обеспечения правильной интеграции метаданных. XML‑файл затем добавляется в коллекцию встроенных файлов PDF, эффективно прикрепляя его в качестве метаданных. Далее PDF‑документ конвертируется в формат PDF/A-3A, который подходит для архивного хранения электронных документов, после чего сохраняется окончательный PDF с вложенным ZUGFeRD. В статье завершается фрагментом кода на Python, демонстрирующим реализацию этих шагов и показывающим интеграцию ZUGFeRD с PDF для улучшенного управления документами. --- diff --git a/ru/python-net/basic-operations/_index.md b/ru/python-net/basic-operations/_index.md index c043c2b29..2c6c0de03 100644 --- a/ru/python-net/basic-operations/_index.md +++ b/ru/python-net/basic-operations/_index.md @@ -9,7 +9,7 @@ description: Раздел базовых операций описывает в sitemap: changefreq: "monthly" priority: 0.5 -TechArticle: true +TechArticle: true AlternativeHeadline: Обзор базовых операций с PDF с использованием Python Abstract: В статье представлен обзор базовых операций по работе с PDF-документами с использованием Aspose.PDF для Python. Рассматриваются три основные задачи - создание, открытие и сохранение PDF-файлов в среде Python. Раздел "Создание PDF-документа" подробно описывает процесс создания PDF-файла с помощью Python. Раздел "Открытие PDF-документа" рассматривает различные способы доступа к PDF-документам в приложении Python. Наконец, раздел "Сохранение PDF-документа" объясняет различные методы сохранения PDF-документа. Каждый раздел содержит ссылки на более подробные статьи, которые проведут пользователей через эти основные операции с PDF. --- diff --git a/ru/python-net/basic-operations/create/_index.md b/ru/python-net/basic-operations/create/_index.md index 136f1508d..f33b4905c 100644 --- a/ru/python-net/basic-operations/create/_index.md +++ b/ru/python-net/basic-operations/create/_index.md @@ -6,7 +6,7 @@ weight: 10 url: /ru/python-net/create-document/ description: Эта страница описывает, как создать PDF документ с нуля с помощью библиотеки Aspose.PDF for Python via .NET. lastmod: "2026-05-07" -TechArticle: true +TechArticle: true AlternativeHeadline: Создание PDF файлов с помощью Aspose.PDF for Python Abstract: В разработке программного обеспечения генерация PDF файлов программным способом является распространённой потребностью, особенно при создании отчётов и других документов. Написание пользовательского кода для этой задачи может быть неэффективным и занимать много времени. Вместо этого разработчики могут использовать **Aspose.PDF for Python via .NET**, надёжное решение для создания PDF файлов с помощью Python. Процесс включает создание объекта `Document`, добавление объекта `Page` в коллекцию `Pages` документа, вставку `TextFragment` в коллекцию `paragraphs` страницы и последующее сохранение документа. Пример фрагмента кода на Python демонстрирует эти шаги, показывая простоту генерации PDF файлов с использованием Aspose.PDF. --- diff --git a/ru/python-net/basic-operations/merge-pdf/_index.md b/ru/python-net/basic-operations/merge-pdf/_index.md index c6ddaa1ce..8eb828036 100644 --- a/ru/python-net/basic-operations/merge-pdf/_index.md +++ b/ru/python-net/basic-operations/merge-pdf/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Объединение страниц PDF с помощью Python Abstract: В этой статье рассматривается распространённая необходимость объединения нескольких PDF-файлов в один документ — процесс, ценный для организации и оптимизации хранения и передачи PDF-содержимого. В ней исследуется использование Aspose.PDF for Python via .NET для эффективного объединения PDF-файлов, признавая, что объединение PDF в Python может быть сложным без сторонних библиотек. Статья содержит пошаговое руководство по объединению PDF-файлов — создание нового документа, объединение файлов и сохранение объединённого документа. Фрагмент кода демонстрирует реализацию с помощью Aspose.PDF, подчёркивая способность библиотеки упростить процесс объединения. Кроме того, представлен онлайн-инструмент Aspose.PDF Merger для объединения PDF, позволяющий пользователям изучить функциональность в веб-среде. --- diff --git a/ru/python-net/basic-operations/protect/_index.md b/ru/python-net/basic-operations/protect/_index.md index 46762e619..297ab3e8a 100644 --- a/ru/python-net/basic-operations/protect/_index.md +++ b/ru/python-net/basic-operations/protect/_index.md @@ -9,7 +9,7 @@ lastmod: "2026-04-15" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Устанавливайте разрешения PDF и управляйте шифрованием в Python Abstract: Эта страница документации объясняет, как установить привилегии документа, применить шифрование и расшифровать PDF‑файлы с использованием Aspose.PDF for Python. Она направляет разработчиков в настройке пользовательских и владельческих паролей, определении ограничений доступа (например, печати, копирования или редактирования). Примеры кода демонстрируют, как защитить конфиденциальный контент и эффективно управлять безопасностью PDF в приложениях Python, обеспечивая контролируемый доступ и конфиденциальность данных. --- diff --git a/ru/python-net/basic-operations/saving/_index.md b/ru/python-net/basic-operations/saving/_index.md index 20e1fcab0..1a8e8c7c1 100644 --- a/ru/python-net/basic-operations/saving/_index.md +++ b/ru/python-net/basic-operations/saving/_index.md @@ -9,7 +9,7 @@ lastmod: "2025-02-27" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Сохранение PDF‑документов с использованием библиотеки Aspose.PDF в Python Abstract: Статья предоставляет рекомендации по сохранению PDF‑документов с использованием библиотеки Aspose.PDF в Python. В ней описываются три основных метода сохранения PDF — в файловую систему, в поток и в специфических форматах, таких как PDF/A или PDF/X. Метод `save()` класса `Document` является центральным для этих операций. Чтобы сохранить PDF в файловую систему, документ может быть создан или изменён, например, добавив новую страницу, и затем сохранён непосредственно по указанному пути. При сохранении в поток перегрузки метода `Save` позволяют записать документ в объект потока. Кроме того, статья объясняет, как сохранять документы в форматах PDF/A или PDF/X, которые являются стандартами для долгосрочного архивирования и обмена графикой соответственно. Этот процесс требует подготовки документа с помощью метода `convert` перед сохранением. Приведённые фрагменты кода на Python демонстрируют каждый подход, илстрируя практическое применение этих методов. --- diff --git a/ru/python-net/converting/convert-html-to-pdf/_index.md b/ru/python-net/converting/convert-html-to-pdf/_index.md index 28a612b12..9061631a9 100644 --- a/ru/python-net/converting/convert-html-to-pdf/_index.md +++ b/ru/python-net/converting/convert-html-to-pdf/_index.md @@ -3,13 +3,13 @@ title: Конвертировать HTML в PDF с помощью Python linktitle: Конвертировать HTML в PDF‑файл type: docs weight: 40 -url: /python-net/convert-html-to-pdf/ +url: /ru/python-net/convert-html-to-pdf/ lastmod: "2026-04-14" description: Узнайте, как преобразовать HTML и MHTML в PDF на Python с помощью Aspose.PDF for Python via .NET, включая настройки CSS media, встроенные шрифты и вывод Tagged PDF. sitemap: changefreq: "monthly" priority: 0.8 -TechArticle: true +TechArticle: true AlternativeHeadline: Как преобразовать HTML в PDF на Python с помощью Aspose.PDF Abstract: Эта статья объясняет, как преобразовать файлы HTML и MHTML в PDF с использованием Aspose.PDF for Python via .NET. Она охватывает базовый процесс преобразования HTML в PDF и показывает, как управлять рендерингом с помощью медиа‑типов, приоритета правил CSS page, встроенных шрифтов, вывода в один лист и генерации логической структуры для доступных помеченных PDF. --- @@ -163,3 +163,4 @@ def convert_MHTML_to_PDF(infile, outfile): document.save(outfile) print(infile + " converted into " + outfile) ``` + diff --git a/ru/python-net/converting/convert-images-format-to-pdf/_index.md b/ru/python-net/converting/convert-images-format-to-pdf/_index.md index fda4d3096..de166217d 100644 --- a/ru/python-net/converting/convert-images-format-to-pdf/_index.md +++ b/ru/python-net/converting/convert-images-format-to-pdf/_index.md @@ -3,13 +3,13 @@ title: Конвертировать форматы изображений в PDF linktitle: Конвертировать изображения в PDF type: docs weight: 60 -url: /python-net/convert-images-format-to-pdf/ +url: /ru/python-net/convert-images-format-to-pdf/ lastmod: "2026-04-14" description: Узнайте, как конвертировать BMP, CGM, DICOM, PNG, TIFF, EMF, SVG и другие форматы изображений в PDF на Python с помощью Aspose.PDF for Python via .NET. sitemap: changefreq: "monthly" priority: 0.5 -TechArticle: true +TechArticle: true AlternativeHeadline: Как конвертировать изображения в PDF на Python Abstract: В этой статье представлено полное руководство по конвертации различных форматов изображений в PDF с использованием Python, в частности с применением библиотеки Aspose.PDF for Python via .NET. В статье рассматривается ряд форматов изображений, включая BMP, CGM, DICOM, EMF, GIF, PNG, SVG и TIFF. Каждый раздел подробно описывает шаги, необходимые для выполнения конвертации, предоставляя фрагменты кода для иллюстрации процесса. Например, преобразование BMP в PDF включает создание нового PDF Document, определение размещения изображения, вставку изображения и сохранение документа. Аналогично для форматов, таких как CGM, DICOM и других, описываются специфические параметры загрузки и этапы обработки. Статья также подчёркивает преимущества использования Aspose.PDF для подобных задач, такие как поддержка различных методов кодирования и возможность обработки как однокадровых, так и многокадровых изображений. --- @@ -357,3 +357,4 @@ def convert_JPEG_to_PDF(infile, outfile): document.save(outfile) print(infile + " converted into " + outfile) ``` + diff --git a/ru/python-net/converting/convert-other-files-to-pdf/_index.md b/ru/python-net/converting/convert-other-files-to-pdf/_index.md index 34ccfd4fc..c9489412d 100644 --- a/ru/python-net/converting/convert-other-files-to-pdf/_index.md +++ b/ru/python-net/converting/convert-other-files-to-pdf/_index.md @@ -3,13 +3,13 @@ title: Конвертировать другие форматы файлов в linktitle: Конвертировать другие форматы файлов в PDF type: docs weight: 80 -url: /python-net/convert-other-files-to-pdf/ +url: /ru/python-net/convert-other-files-to-pdf/ lastmod: "2026-04-14" description: Узнайте, как конвертировать файлы EPUB, Markdown, PCL, XPS, PostScript, XML и LaTeX в PDF на Python с помощью Aspose.PDF for Python via .NET. sitemap: changefreq: "monthly" priority: 0.5 -TechArticle: true +TechArticle: true AlternativeHeadline: Как конвертировать другие форматы файлов в PDF на Python Abstract: В этой статье представлено всестороннее руководство по конвертации различных форматов файлов в PDF с использованием Python, используя возможности Aspose.PDF for Python via .NET. В документе описаны процессы конвертации для нескольких форматов, включая EPUB, Markdown, PCL, Text, XPS, PostScript, XML, XSL-FO и LaTeX/TeX. Каждый раздел предоставляет конкретные фрагменты кода и инструкции по реализации этих конвертаций. В статье подчеркивается полезность функций Aspose.PDF, таких как параметры загрузки, адаптированные под каждый тип файла, чтобы обеспечить точную и эффективную конвертацию. Кроме того, отмечается наличие онлайн‑приложений для конвертации, позволяющих пользователям самостоятельно опробовать функциональность. Это руководство служит практическим ресурсом для разработчиков, желающих интегрировать возможности конвертации в PDF в свои Python‑приложения. --- @@ -336,3 +336,4 @@ def convert_XSLFO_to_PDF(xsltfile, xmlfile, outfile): - [Преобразовать HTML в PDF](/pdf/ru/python-net/convert-html-to-pdf/) для сценариев преобразования HTML и MHTML. - [Конвертировать форматы изображений в PDF](/pdf/ru/python-net/convert-images-format-to-pdf/) когда ваши входные данные — PNG, JPEG, TIFF, SVG или другие изображения. - [Конвертировать PDF в другие форматы](/pdf/ru/python-net/convert-pdf-to-other-files/) если вам также нужны обратные конверсии, такие как PDF в EPUB, Markdown или текст. + diff --git a/ru/python-net/converting/convert-pdf-to-excel/_index.md b/ru/python-net/converting/convert-pdf-to-excel/_index.md index c99a3f275..c70644ead 100644 --- a/ru/python-net/converting/convert-pdf-to-excel/_index.md +++ b/ru/python-net/converting/convert-pdf-to-excel/_index.md @@ -3,13 +3,13 @@ title: Конвертировать PDF в Excel с помощью Python linktitle: Конвертировать PDF в Excel type: docs weight: 20 -url: /python-net/convert-pdf-to-excel/ +url: /ru/python-net/convert-pdf-to-excel/ lastmod: "2026-04-14" description: Узнайте, как конвертировать PDF-файлы в Excel в Python с помощью Aspose.PDF for Python via .NET, включая XLS, XLSX, CSV, ODS и вывод в виде одного листа. sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Как конвертировать PDF в Excel в Python Abstract: В этой статье представлен всесторонний руководитель по конвертации PDF‑файлов в различные форматы Excel с использованием Python, конкретно с библиотекой Aspose.PDF for Python via .NET. Описываются процессы преобразования в форматы XLS, XLSX, CSV и ODS. Документ объясняет шаги, необходимые для конвертации PDF в XLS и XLSX, выделяя создание экземпляров Document и ExcelSaveOptions, а также использование метода Document.Save() для указания выходных форматов. В статье также рассматриваются такие возможности, как контроль вставки пустых столбцов и уменьшение количества листов во время конвертации. Кроме того, приводятся примеры преобразования PDF в отдельные листы Excel и другие форматы, такие как CSV и ODS, подчёркивая гибкость и функциональность Aspose.PDF. Также упоминается онлайн‑инструмент для конвертации PDF в XLSX, позволяющий пользователям оценить качество преобразования. В заключении статьи приведён список связанных тем и фрагменты кода, помогающие лучше понять и реализовать эти конвертации программно. --- @@ -193,4 +193,4 @@ def convert_pdf_to_ods(infile, outfile): - [Конвертировать PDF в Word](/pdf/ru/python-net/convert-pdf-to-word/) если ваш приоритет — редактируемый поток текста, а не структура таблицы. - [Преобразовать PDF в HTML](/pdf/ru/python-net/convert-pdf-to-html/) когда вам нужен вывод, пригодный для браузера. -- [Конвертировать PDF в другие форматы](/pdf/ru/python-net/convert-pdf-to-other-files/) для EPUB, Markdown, текста, XPS и связанных экспортных рабочих процессов. \ No newline at end of file +- [Конвертировать PDF в другие форматы](/pdf/ru/python-net/convert-pdf-to-other-files/) для EPUB, Markdown, текста, XPS и связанных экспортных рабочих процессов. diff --git a/ru/python-net/converting/convert-pdf-to-html/_index.md b/ru/python-net/converting/convert-pdf-to-html/_index.md index dd7d280ff..253cb1ed9 100644 --- a/ru/python-net/converting/convert-pdf-to-html/_index.md +++ b/ru/python-net/converting/convert-pdf-to-html/_index.md @@ -3,7 +3,7 @@ title: Конвертировать PDF в HTML на Python linktitle: Конвертировать PDF в формат HTML type: docs weight: 50 -url: /python-net/convert-pdf-to-html/ +url: /ru/python-net/convert-pdf-to-html/ lastmod: "2026-04-14" description: Узнайте, как конвертировать PDF в HTML на Python с помощью Aspose.PDF for Python via .NET, включая многостраничный вывод, внешние изображения, обработку SVG и слоистый рендеринг HTML. sitemap: @@ -241,3 +241,4 @@ def convert_PDF_to_HTML_document_layers_rendering(infile, outfile): print(infile + " converted into " + outfile) ``` + diff --git a/ru/python-net/converting/convert-pdf-to-other-files/_index.md b/ru/python-net/converting/convert-pdf-to-other-files/_index.md index fd20650d8..6aa91f1fb 100644 --- a/ru/python-net/converting/convert-pdf-to-other-files/_index.md +++ b/ru/python-net/converting/convert-pdf-to-other-files/_index.md @@ -3,13 +3,13 @@ title: Конвертировать PDF в EPUB, Text, XPS и другие фо linktitle: Конвертировать PDF в другие форматы type: docs weight: 90 -url: /python-net/convert-pdf-to-other-files/ +url: /ru/python-net/convert-pdf-to-other-files/ lastmod: "2026-04-14" description: Узнайте, как конвертировать файлы PDF в EPUB, LaTeX, Markdown, текст, XPS и MobiXML на Python с помощью Aspose.PDF for Python via .NET. sitemap: changefreq: "monthly" priority: 0.8 -TechArticle: true +TechArticle: true AlternativeHeadline: Как конвертировать PDF в другие форматы в Python Abstract: Статья предоставляет всестороннее руководство по конвертации PDF‑файлов в различные форматы с использованием Aspose.PDF for Python. Она охватывает преобразование PDF в форматы EPUB, LaTeX/TeX, Text, XPS и XML. Каждый раздел начинается с приглашения попробовать онлайн приложения, предоставляемые Aspose для конвертации PDF в соответствующие форматы, подчёркивая простоту использования и качество этих инструментов. --- @@ -183,3 +183,4 @@ def convert_PDF_to_MobiXML(infile, outfile): print(infile + " converted into " + outfile) ``` + diff --git a/ru/python-net/converting/convert-pdf-to-pdfx/_index.md b/ru/python-net/converting/convert-pdf-to-pdfx/_index.md index 2c77ac8f3..a08f3025e 100644 --- a/ru/python-net/converting/convert-pdf-to-pdfx/_index.md +++ b/ru/python-net/converting/convert-pdf-to-pdfx/_index.md @@ -3,13 +3,13 @@ title: Конвертировать PDF в PDF/A, PDF/E и PDF/X в Python linktitle: Конвертировать PDF в PDF/A, PDF/E и PDF/X type: docs weight: 120 -url: /python-net/convert-pdf-to-pdf_x/ +url: /ru/python-net/convert-pdf-to-pdf_x/ lastmod: "2026-04-14" description: Узнайте, как конвертировать файлы PDF в PDF/A, PDF/E и PDF/X на Python с помощью Aspose.PDF for Python via .NET для архивных, доступных и печатных рабочих процессов. sitemap: changefreq: "monthly" priority: 0.8 -TechArticle: true +TechArticle: true AlternativeHeadline: Как конвертировать PDF в форматы PDF/X Abstract: Статья предоставляет полное руководство по преобразованию PDF в форматы PDF/A, PDF/E и PDF/X с помощью Aspose.PDF for Python. --- @@ -277,3 +277,4 @@ def convert_PDF_to_PDF_X(infile, outfile): - [Конвертировать PDF в Word](/pdf/ru/python-net/convert-pdf-to-word/) для рабочих процессов редактируемого контента после проверки соответствия стандартам. - [Конвертировать PDF в HTML](/pdf/ru/python-net/convert-pdf-to-html/) когда ваш целевой вывод готов к вебу, а не основан на стандартах PDF. + diff --git a/ru/python-net/converting/convert-pdf-to-powerpoint/_index.md b/ru/python-net/converting/convert-pdf-to-powerpoint/_index.md index 470e9c585..7d302f05e 100644 --- a/ru/python-net/converting/convert-pdf-to-powerpoint/_index.md +++ b/ru/python-net/converting/convert-pdf-to-powerpoint/_index.md @@ -3,13 +3,13 @@ title: Конвертировать PDF в PowerPoint на Python linktitle: Конвертировать PDF в PowerPoint type: docs weight: 30 -url: /python-net/convert-pdf-to-powerpoint/ +url: /ru/python-net/convert-pdf-to-powerpoint/ description: Узнайте, как конвертировать файлы PDF в PowerPoint на Python с помощью Aspose.PDF for Python via .NET, включая редактируемые слайды PPTX и вывод слайдов в виде изображений. lastmod: "2026-04-14" sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Как конвертировать PDF в PowerPoint на Python Abstract: Эта статья представляет собой всестороннее руководство по конвертации PDF‑файлов в презентации PowerPoint с использованием Python, с особым акцентом на формат PPTX. В ней представлено использование Aspose.PDF for Python via .NET, который упрощает процесс конвертации, позволяя преобразовывать страницы PDF в отдельные слайды в файле PPTX. В статье описаны необходимые шаги конвертации, включая создание экземпляров классов Document и PptxSaveOptions и использование метода Save. Кроме того, отмечена возможность конвертировать PDF в PPTX с слайдами в виде изображений путем установки определённого свойства в PptxSaveOptions. Приведены фрагменты кода, иллюстрирующие процесс конвертации. В статье также упомянуто онлайн‑приложение для тестирования функции конвертации PDF в PPTX, предлагающее пользователям практический опыт. Кроме того, перечислены различные связанные темы и функции, доступные в данном контексте, подчеркивающие универсальность и программный подход к работе с конвертацией PDF в PowerPoint с помощью Python. --- @@ -97,4 +97,4 @@ def convert_PDF_to_PPTX_image_resolution(infile, outfile): - [Преобразовать PDF в Word](/pdf/ru/python-net/convert-pdf-to-word/) для вывода редактируемого документа вместо слайдов. - [Преобразовать PDF в Excel](/pdf/ru/python-net/convert-pdf-to-excel/) когда исходный PDF содержит бизнес‑данные, насыщенные таблицами. -- [Преобразовать PDF в HTML](/pdf/ru/python-net/convert-pdf-to-html/) для публикационных рабочих процессов, готовых к браузеру. \ No newline at end of file +- [Преобразовать PDF в HTML](/pdf/ru/python-net/convert-pdf-to-html/) для публикационных рабочих процессов, готовых к браузеру. diff --git a/ru/python-net/converting/convert-pdf-to-word/_index.md b/ru/python-net/converting/convert-pdf-to-word/_index.md index 7f9da58bf..c82953aef 100644 --- a/ru/python-net/converting/convert-pdf-to-word/_index.md +++ b/ru/python-net/converting/convert-pdf-to-word/_index.md @@ -3,13 +3,13 @@ title: Конвертировать PDF в Word в Python linktitle: Конвертировать PDF в Word type: docs weight: 10 -url: /python-net/convert-pdf-to-word/ +url: /ru/python-net/convert-pdf-to-word/ lastmod: "2026-04-14" description: Узнайте, как конвертировать PDF‑файлы в DOC и DOCX в Python с помощью Aspose.PDF for Python via .NET для более простого редактирования и повторного использования документов. sitemap: changefreq: "monthly" priority: 0.7 -TechArticle: true +TechArticle: true AlternativeHeadline: Как конвертировать PDF в Word в Python Abstract: Эта статья предоставляет исчерпывающее руководство по конвертации PDF‑файлов в форматы Microsoft Word (DOC и DOCX) с использованием Python, в частности библиотеки Aspose.PDF. В ней изложены преимущества преобразования PDF в редактируемые документы Word, позволяющие легче манипулировать содержимым, таким как текст, таблицы и изображения. Статья подробно описывает процесс конвертации PDF в DOC (формат Word 97‑2003) и DOCX, с примерами кода, демонстрирующими эти преобразования на Python. Процесс включает создание объекта `Document` из PDF и сохранение его в нужном формате с помощью метода `save()` и перечисления `SaveFormat`. Кроме того, вводится класс `DocSaveOptions`, который позволяет дополнительно настраивать процесс конвертации, например указывать режимы распознавания. Статья также подчёркивает онлайн‑приложения, предоставляемые Aspose.PDF для тестирования качества и функциональности конвертации. Содержание включает структурированный обзор и ссылки на соответствующие разделы для каждого формата. --- @@ -111,3 +111,4 @@ Aspose.PDF for Python представляет вам онлайн прилож - [Преобразовать PDF в Excel](/pdf/ru/python-net/convert-pdf-to-excel/) для экспорта, ориентированного на электронные таблицы. - [Преобразовать PDF в PowerPoint](/pdf/ru/python-net/convert-pdf-to-powerpoint/) когда вам нужны слайды презентации вместо вывода из текстового процессора. - [Преобразовать PDF в HTML](/pdf/ru/python-net/convert-pdf-to-html/) для веб‑публикации и браузерных рабочих процессов. + diff --git a/ru/python-net/converting/convert-pdfx-to-pdf/_index.md b/ru/python-net/converting/convert-pdfx-to-pdf/_index.md index 15593b016..f1ded4ffa 100644 --- a/ru/python-net/converting/convert-pdfx-to-pdf/_index.md +++ b/ru/python-net/converting/convert-pdfx-to-pdf/_index.md @@ -3,13 +3,13 @@ title: Конвертировать PDF/A и PDF/UA в PDF с помощью Pyt linktitle: Конвертировать PDF/A и PDF/UA в PDF type: docs weight: 120 -url: /python-net/convert-pdf_x-to-pdf/ +url: /ru/python-net/convert-pdf_x-to-pdf/ lastmod: "2026-04-14" description: Узнайте, как удалить соответствие PDF/A и PDF/UA из PDF‑файлов в Python с помощью Aspose.PDF for Python via .NET и сохранить их как стандартные PDF‑документы. sitemap: changefreq: "monthly" priority: 0.8 -TechArticle: true +TechArticle: true AlternativeHeadline: Как конвертировать PDF/A и PDF/UA в стандартный PDF на Python Abstract: В этой статье объясняется, как удалить соответствие PDF/A и PDF/UA из стандартизированных PDF‑документов с использованием Aspose.PDF for Python via .NET. Описываются сценарии, когда вам может потребоваться стандартный PDF вместо архивного или ограниченного доступностью файла, а также показывается, как сохранить результат после удаления метаданных соответствия и ограничений. --- @@ -67,3 +67,4 @@ def convert_PDFUA_to_PDF(infile, outfile): - [Преобразовать PDF в PDF/A, PDF/E и PDF/X](/pdf/ru/python-net/convert-pdf-to-pdf_x/) если вам нужен обратный рабочий процесс и вы хотите создавать PDF, соответствующие стандартам. - [Преобразовать PDF в Word](/pdf/ru/python-net/convert-pdf-to-word/) для получения редактируемого документа после снятия ограничений соответствия. - [Конвертировать PDF в HTML](/pdf/ru/python-net/convert-pdf-to-html/) для вывода, удобного для браузера, из стандартных PDF-файлов. + diff --git a/ru/python-net/get-started/_index.md b/ru/python-net/get-started/_index.md index 2b92ea002..29d7d5573 100644 --- a/ru/python-net/get-started/_index.md +++ b/ru/python-net/get-started/_index.md @@ -1,12 +1,12 @@ --- -title: Get Started +title: Get Started linktitle: Get Started type: docs weight: 30 url: /ru/python-net/get-started/ description: Этот раздел описывает основные принципы работы Aspose.PDF for Python via .NET. Библиотека Python поддерживает широкий спектр функций. is_node: true -lastmod: "2022-12-20" +lastmod: "2022-12-20" sitemap: changefreq: "monthly" priority: 0.7 diff --git a/ru/python-net/overview/technical-support/_index.md b/ru/python-net/overview/technical-support/_index.md index 526df0024..915b6a3f8 100644 --- a/ru/python-net/overview/technical-support/_index.md +++ b/ru/python-net/overview/technical-support/_index.md @@ -1,14 +1,14 @@ ---- -title: Aspose.PDF для поддержки Python -linktitle: Техническая поддержка -type: docs -weight: 60 -url: /ru/python-net/technical-support/ -description: Эта страница дает рекомендации для быстрого и качественного решения ваших задач с использованием Aspose.PDF для Python. -lastmod: "2021-06-05" -sitemap: - changefreq: "monthly" - priority: 0.7 +--- +title: Aspose.PDF для поддержки Python +linktitle: Техническая поддержка +type: docs +weight: 60 +url: /ru/python-net/technical-support/ +description: Эта страница дает рекомендации для быстрого и качественного решения ваших задач с использованием Aspose.PDF для Python. +lastmod: "2021-06-05" +sitemap: + changefreq: "monthly" + priority: 0.7 --- Aspose.PDF позволяет вам использовать бесплатную техническую поддержку для всех своих продуктов. Если у вас есть вопросы по Aspose.PDF, ознакомьтесь со следующей статьей: diff --git a/ru/python-net/whatsnew/_index.md b/ru/python-net/whatsnew/_index.md index 61c91715e..5873620c2 100644 --- a/ru/python-net/whatsnew/_index.md +++ b/ru/python-net/whatsnew/_index.md @@ -9,7 +9,7 @@ sitemap: changefreq: "monthly" priority: 0.8 lastmod: "2025-02-24" -TechArticle: false +TechArticle: false --- ## Что нового в Aspose.PDF 26.3 diff --git a/ru/python-net/working-with-facades/_index.md b/ru/python-net/working-with-facades/_index.md index 51ba4647f..5592955c9 100644 --- a/ru/python-net/working-with-facades/_index.md +++ b/ru/python-net/working-with-facades/_index.md @@ -3,7 +3,7 @@ title: Работа с фасадами PDF linktitle: Работа с фасадами PDF type: docs weight: 100 -url: /python-net/working-with-facades/ +url: /ru/python-net/working-with-facades/ description: Узнайте, как использовать фасады Aspose.PDF в Aspose.PDF for Python via .NET для редактирования содержимого PDF, управления формами и аннотациями, применения защиты, подписания файлов, добавления штампов, печати документов и просмотра метаданных PDF. is_node: true lastmod: "2026-05-08" @@ -58,3 +58,4 @@ PDF-фасады предоставляют упрощённый слой API д Используйте статьи в этом разделе для работы с практическими PDF‑процессами, такими как заполнение форм, управление полями, редактирование аннотаций, обработка вложений, замена текста, обработка страниц, безопасность PDF и операции подписи в Python. Чтобы изучить конкретные API, начните с ссылок на классы выше, а затем переходите к статьям, основанным на задачах, в этом разделе, где представлены пошаговые примеры. + diff --git a/ru/python-net/working-with-facades/form/_index.md b/ru/python-net/working-with-facades/form/_index.md index ed1a9c1ec..e1d72b088 100644 --- a/ru/python-net/working-with-facades/form/_index.md +++ b/ru/python-net/working-with-facades/form/_index.md @@ -3,7 +3,7 @@ title: Класс Form linktitle: Класс Form type: docs weight: 140 -url: /python-net/form-class/ +url: /ru/python-net/form-class/ description: В этом разделе объясняется, как работать с фасадами Aspose.PDF, используя класс Form. lastmod: "2025-11-05" sitemap: @@ -20,3 +20,4 @@ Abstract: В этом разделе объясняется, как исполь - [Поля кнопок и изображения](/pdf/ru/python-net/button-fields-and-images/) - [Управление полями Form](/pdf/ru/python-net/managing-form-fields/) - [Чтение значений Form](/pdf/ru/python-net/reading-form-values/) + diff --git a/ru/python-net/working-with-facades/form/button-fields-and-images/_index.md b/ru/python-net/working-with-facades/form/button-fields-and-images/_index.md index 0d1568154..09b9305aa 100644 --- a/ru/python-net/working-with-facades/form/button-fields-and-images/_index.md +++ b/ru/python-net/working-with-facades/form/button-fields-and-images/_index.md @@ -3,7 +3,7 @@ title: Поля кнопок и изображения linktitle: Поля кнопок и изображения type: docs weight: 40 -url: /python-net/button-fields-and-images/ +url: /ru/python-net/button-fields-and-images/ description: В этом примере демонстрируется, как управлять полями кнопок в PDF‑форме с использованием API Aspose.PDF Facades. lastmod: "2026-02-19" TechArticle: true @@ -82,3 +82,4 @@ def get_submit_flags(infile, outfile): print(f"Submit flags: {flags}") ``` + diff --git a/ru/python-net/working-with-facades/form/exporting-form-data/_index.md b/ru/python-net/working-with-facades/form/exporting-form-data/_index.md index 317eca0f1..2fff6587a 100644 --- a/ru/python-net/working-with-facades/form/exporting-form-data/_index.md +++ b/ru/python-net/working-with-facades/form/exporting-form-data/_index.md @@ -3,7 +3,7 @@ title: Экспорт данных Form linktitle: Экспорт данных Form type: docs weight: 10 -url: /python-net/exporting-form-data/ +url: /ru/python-net/exporting-form-data/ description: В этой статье демонстрируется, как экспортировать данные формы PDF в несколько структурированных форматов с использованием Aspose.PDF for Python via .NET. Она предоставляет практические примеры извлечения значений полей формы из стандартных AcroForms и PDF на основе XFA и сохранения их как файлов XML, FDF, XFDF и JSON с помощью фасадов Aspose.PDF, используя Form Class. lastmod: "2026-02-19" --- @@ -12,4 +12,4 @@ lastmod: "2026-02-19" - [Экспорт в XFDF](/pdf/ru/python-net/export-to-xfdf/) - [Экспорт в JSON](/pdf/ru/python-net/export-to-json/) - [Экспорт в XML](/pdf/ru/python-net/export-to-xml/) -- [Извлечь данные XFA](/pdf/ru/python-net/extract-xfa-data/) \ No newline at end of file +- [Извлечь данные XFA](/pdf/ru/python-net/extract-xfa-data/) diff --git a/ru/python-net/working-with-facades/form/exporting-form-data/export-to-fdf/_index.md b/ru/python-net/working-with-facades/form/exporting-form-data/export-to-fdf/_index.md index eccc87354..826b784c7 100644 --- a/ru/python-net/working-with-facades/form/exporting-form-data/export-to-fdf/_index.md +++ b/ru/python-net/working-with-facades/form/exporting-form-data/export-to-fdf/_index.md @@ -3,7 +3,7 @@ title: Экспорт в FDF linktitle: Экспорт в FDF type: docs weight: 10 -url: /python-net/export-to-fdf/ +url: /ru/python-net/export-to-fdf/ description: Этот пример объясняет, как экспортировать данные полей формы PDF в файл FDF (Forms Data Format) с использованием Aspose.PDF for Python via .NET. Он демонстрирует, как получить доступ к интерактивным данным формы через фасад Form, привязать исходный PDF‑документ и сохранить извлечённые значения в поток FDF. lastmod: "2026-02-19" --- @@ -41,3 +41,4 @@ def export_form_data_to_fdf(infile, outfile): # Export form data to FDF file pdf_form.export_fdf(fdf_output_stream) ``` + diff --git a/ru/python-net/working-with-facades/form/exporting-form-data/export-to-json/_index.md b/ru/python-net/working-with-facades/form/exporting-form-data/export-to-json/_index.md index 0225dbd78..ba6adc63a 100644 --- a/ru/python-net/working-with-facades/form/exporting-form-data/export-to-json/_index.md +++ b/ru/python-net/working-with-facades/form/exporting-form-data/export-to-json/_index.md @@ -3,7 +3,7 @@ title: Экспорт в JSON linktitle: Экспорт в JSON type: docs weight: 30 -url: /python-net/export-to-json/ +url: /ru/python-net/export-to-json/ description: В этом примере демонстрируется, как экспортировать значения полей формы PDF в файл JSON с использованием Aspose.PDF for Python via .NET. Описывается, как загрузить форму PDF, получить доступ к её полям через фасад Form и сохранить извлечённые данные в структурированном формате JSON. lastmod: "2026-02-19" --- @@ -41,3 +41,4 @@ def export_form_to_json(infile, outfile): # Export form field values to JSON form.export_json(json_stream, indented=True) ``` + diff --git a/ru/python-net/working-with-facades/form/exporting-form-data/export-to-xfdf/_index.md b/ru/python-net/working-with-facades/form/exporting-form-data/export-to-xfdf/_index.md index 14f1f5155..4b6b59660 100644 --- a/ru/python-net/working-with-facades/form/exporting-form-data/export-to-xfdf/_index.md +++ b/ru/python-net/working-with-facades/form/exporting-form-data/export-to-xfdf/_index.md @@ -3,7 +3,7 @@ title: Экспорт в XFDF linktitle: Экспорт в XFDF type: docs weight: 20 -url: /python-net/export-to-xfdf/ +url: /ru/python-net/export-to-xfdf/ description: В этом примере показано, как экспортировать данные полей формы PDF в файл XFDF (XML Forms Data Format) с использованием Aspose.PDF for Python via .NET. Он демонстрирует, как загрузить форму PDF, получить доступ к её полям через фасад Form и сохранить извлечённые значения в поток XFDF. lastmod: "2026-02-19" --- @@ -41,3 +41,4 @@ def export_pdf_form_to_xfdf(infile, outfile): # Export form data to XFDF file pdf_form.export_xfdf(xfdf_output_stream) ``` + diff --git a/ru/python-net/working-with-facades/form/exporting-form-data/export-to-xml/_index.md b/ru/python-net/working-with-facades/form/exporting-form-data/export-to-xml/_index.md index ea86c8bc9..bbe6fbb04 100644 --- a/ru/python-net/working-with-facades/form/exporting-form-data/export-to-xml/_index.md +++ b/ru/python-net/working-with-facades/form/exporting-form-data/export-to-xml/_index.md @@ -3,7 +3,7 @@ title: Экспорт в XML linktitle: Экспорт в XML type: docs weight: 40 -url: /python-net/export-to-xml/ +url: /ru/python-net/export-to-xml/ description: В этом примере демонстрируется, как экспортировать данные формы PDF в файл XML с использованием Aspose.PDF for Python via .NET. Показано, как загрузить PDF‑документ, получить доступ к полям формы через фасад Form и сохранить извлечённые данные в виде структурированного XML с использованием класса Form. lastmod: "2026-02-19" --- @@ -41,3 +41,4 @@ def export_pdf_form_data_to_xml(infile, datafile): # Export data from PDF form fields to XML pdf_form.export_xml(xml_output_stream) ``` + diff --git a/ru/python-net/working-with-facades/form/exporting-form-data/extract-xfa-data/_index.md b/ru/python-net/working-with-facades/form/exporting-form-data/extract-xfa-data/_index.md index 941d5aa0a..3a90f492c 100644 --- a/ru/python-net/working-with-facades/form/exporting-form-data/extract-xfa-data/_index.md +++ b/ru/python-net/working-with-facades/form/exporting-form-data/extract-xfa-data/_index.md @@ -3,7 +3,7 @@ title: Извлечь данные XFA linktitle: Извлечь данные XFA type: docs weight: 50 -url: /python-net/extract-xfa-data/ +url: /ru/python-net/extract-xfa-data/ description: В этом примере объясняется, как извлечь данные форм XFA из PDF‑файла с использованием Aspose.PDF for Python via .NET. Он демонстрирует, как привязать PDF‑документ на основе XFA к фасаду Form и экспортировать его внутреннюю структуру данных в поток файла. lastmod: "2026-02-19" --- @@ -40,3 +40,4 @@ def export_xfa_data(infile, outfile): # Export embedded XFA XML data to the output stream form.extract_xfa_data(stream) ``` + diff --git a/ru/python-net/working-with-facades/form/filling-form-fields/_index.md b/ru/python-net/working-with-facades/form/filling-form-fields/_index.md index cd0ebb7af..ce66fac59 100644 --- a/ru/python-net/working-with-facades/form/filling-form-fields/_index.md +++ b/ru/python-net/working-with-facades/form/filling-form-fields/_index.md @@ -3,7 +3,7 @@ title: Заполнение полей Form linktitle: Заполнение полей Form type: docs weight: 30 -url: /python-net/filling-form-fields/ +url: /ru/python-net/filling-form-fields/ description: В этой статье демонстрируется, как программно заполнять поля PDF‑формы с использованием Aspose.PDF for Python via .NET. Описываются практические методы заполнения различных типов интерактивных элементов формы, включая текстовые поля, флажки, переключатели, списки, поля штрих‑кода и динамически сопоставляемые пары имя–значение. С помощью фасада Form разработчики могут привязать документ PDF, обновлять значения полей через простые вызовы API и автоматически сохранять изменённый файл. lastmod: "2026-02-19" --- @@ -14,3 +14,4 @@ lastmod: "2026-02-19" - [Заполнить List Box](/pdf/ru/python-net/fill-list-box/) - [Заполнить поля штрихкода](/pdf/ru/python-net/fill-barcode-fields/) - [Заполнять поля по имени и значению](/pdf/ru/python-net/fill-fields-by-name-and-value/) + diff --git a/ru/python-net/working-with-facades/form/filling-form-fields/fill-barcode-fields/_index.md b/ru/python-net/working-with-facades/form/filling-form-fields/fill-barcode-fields/_index.md index b438692a7..9243b4623 100644 --- a/ru/python-net/working-with-facades/form/filling-form-fields/fill-barcode-fields/_index.md +++ b/ru/python-net/working-with-facades/form/filling-form-fields/fill-barcode-fields/_index.md @@ -3,7 +3,7 @@ title: Заполнить поля штрихкода linktitle: Заполнить поля штрихкода type: docs weight: 50 -url: /python-net/fill-barcode-fields/ +url: /ru/python-net/fill-barcode-fields/ description: Этот пример демонстрирует, как программно заполнять поля штрихкода в PDF‑форме с использованием Aspose.PDF for Python via .NET. Он показывает, как привязать PDF‑документ, задать значение полю штрихкода и сохранить обновлённый файл. lastmod: "2026-02-19" --- @@ -42,3 +42,4 @@ def fill_barcode_fields(infile, outfile): # Save updated PDF pdf_form.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/form/filling-form-fields/fill-check-box-fields/_index.md b/ru/python-net/working-with-facades/form/filling-form-fields/fill-check-box-fields/_index.md index 4f3b974e7..0d0d9950e 100644 --- a/ru/python-net/working-with-facades/form/filling-form-fields/fill-check-box-fields/_index.md +++ b/ru/python-net/working-with-facades/form/filling-form-fields/fill-check-box-fields/_index.md @@ -3,7 +3,7 @@ title: Заполнить поля флажков linktitle: Заполнить поля флажков type: docs weight: 20 -url: /python-net/fill-check-box-fields/ +url: /ru/python-net/fill-check-box-fields/ description: В этом примере демонстрируется, как программно заполнять поля флажков в PDF-форме с использованием Aspose.PDF for Python via .NET. Показано, как привязать PDF‑документ, обновить значения флажков по имени поля и сохранить изменённый файл. lastmod: "2026-02-19" --- @@ -43,3 +43,4 @@ def fill_check_box_fields(infile, outfile): # Save updated PDF pdf_form.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/form/filling-form-fields/fill-fields-by-name-and-value/_index.md b/ru/python-net/working-with-facades/form/filling-form-fields/fill-fields-by-name-and-value/_index.md index 1b601205c..3523d2b20 100644 --- a/ru/python-net/working-with-facades/form/filling-form-fields/fill-fields-by-name-and-value/_index.md +++ b/ru/python-net/working-with-facades/form/filling-form-fields/fill-fields-by-name-and-value/_index.md @@ -3,7 +3,7 @@ title: Заполнять поля по имени и значению linktitle: Заполнять поля по имени и значению type: docs weight: 60 -url: /python-net/fill-fields-by-name-and-value/ +url: /ru/python-net/fill-fields-by-name-and-value/ description: В этой статье демонстрируется, как динамически заполнять несколько полей формы PDF по имени и значению с использованием Aspose.PDF for Python via .NET. Вместо того чтобы задавать каждое поле отдельно, используется структура словаря для сопоставления имен полей со значениями и их заполнения в цикле. lastmod: "2026-02-19" --- @@ -49,3 +49,4 @@ def fill_fields_by_name_and_value(infile, outfile): # Save updated PDF using outfile pdf_form.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/form/filling-form-fields/fill-list-box/_index.md b/ru/python-net/working-with-facades/form/filling-form-fields/fill-list-box/_index.md index 25dd5d918..a36fd49db 100644 --- a/ru/python-net/working-with-facades/form/filling-form-fields/fill-list-box/_index.md +++ b/ru/python-net/working-with-facades/form/filling-form-fields/fill-list-box/_index.md @@ -3,7 +3,7 @@ title: Заполнить List Box linktitle: Заполнить List Box type: docs weight: 40 -url: /python-net/fill-list-box/ +url: /ru/python-net/fill-list-box/ description: В этом примере демонстрируется, как программно заполнять поля списка и множественного выбора в PDF‑форме с использованием Aspose.PDF for Python via .NET. Показано, как привязать PDF‑документ, выбрать значения в форме поля списка и сохранить обновлённый файл. lastmod: "2026-02-19" --- @@ -42,3 +42,4 @@ def fill_list_box_fields(infile, outfile): # Save updated PDF pdf_form.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/form/filling-form-fields/fill-radio-button-fields/_index.md b/ru/python-net/working-with-facades/form/filling-form-fields/fill-radio-button-fields/_index.md index 666728965..39d4354ba 100644 --- a/ru/python-net/working-with-facades/form/filling-form-fields/fill-radio-button-fields/_index.md +++ b/ru/python-net/working-with-facades/form/filling-form-fields/fill-radio-button-fields/_index.md @@ -3,7 +3,7 @@ title: Заполнить поля радиокнопок linktitle: Заполнить поля радиокнопок type: docs weight: 30 -url: /python-net/fill-radio-button-fields/ +url: /ru/python-net/fill-radio-button-fields/ description: В этом примере демонстрируется, как программно заполнять поля радиокнопок в PDF‑форме с использованием Aspose.PDF for Python via .NET. Показано, как привязать PDF‑документ, выбрать вариант радиокнопки по индексу и сохранить обновлённый файл. lastmod: "2026-02-19" --- @@ -43,3 +43,4 @@ def fill_radio_button_fields(infile, outfile): # Save updated PDF pdf_form.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/form/filling-form-fields/fill-text-fields/_index.md b/ru/python-net/working-with-facades/form/filling-form-fields/fill-text-fields/_index.md index 8b689b464..b34f89c7e 100644 --- a/ru/python-net/working-with-facades/form/filling-form-fields/fill-text-fields/_index.md +++ b/ru/python-net/working-with-facades/form/filling-form-fields/fill-text-fields/_index.md @@ -3,7 +3,7 @@ title: Заполнить текстовые поля linktitle: Заполнить текстовые поля type: docs weight: 10 -url: /python-net/fill-text-fields/ +url: /ru/python-net/fill-text-fields/ description: Этот пример демонстрирует, как автоматически заполнять текстовые поля в PDF‑форме, используя Aspose.PDF for Python via .NET. Он показывает, как загрузить PDF‑документ, заполнить конкретные поля формы по имени и сохранить обновлённый файл. lastmod: "2026-02-19" --- @@ -44,3 +44,4 @@ def fill_text_fields(infile, outfile): # Save updated PDF pdf_form.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/form/importing-form-data/_index.md b/ru/python-net/working-with-facades/form/importing-form-data/_index.md index f643bcf1c..c5b0812f9 100644 --- a/ru/python-net/working-with-facades/form/importing-form-data/_index.md +++ b/ru/python-net/working-with-facades/form/importing-form-data/_index.md @@ -3,7 +3,7 @@ title: Импорт данных Form linktitle: Импорт данных Form type: docs weight: 20 -url: /python-net/importing-form-data/ +url: /ru/python-net/importing-form-data/ description: В этом разделе демонстрируется, как импортировать и заменять данные формы PDF из нескольких внешних форматов с использованием Aspose.PDF for Python via .NET. Рассматриваются практические примеры заполнения полей формы PDF данными из файлов XML, FDF, XFDF и JSON, а также замена существующих наборов данных XFA. С помощью фасада Form разработчики могут привязать PDF‑документ, загрузить структурированные данные через файловые потоки и автоматически обновлять поля формы без ручного редактирования. lastmod: "2026-02-19" --- @@ -13,3 +13,4 @@ lastmod: "2026-02-19" - [Импортировать JSON-данные](/pdf/ru/python-net/import-json-data/) - [Импорт данных XML](/pdf/ru/python-net/import-xml-data/) - [Заменить данные XFA](/pdf/ru/python-net/replace-xfa-data/) + diff --git a/ru/python-net/working-with-facades/form/importing-form-data/import-fdf-data/_index.md b/ru/python-net/working-with-facades/form/importing-form-data/import-fdf-data/_index.md index d45ea80b5..1500e7cff 100644 --- a/ru/python-net/working-with-facades/form/importing-form-data/import-fdf-data/_index.md +++ b/ru/python-net/working-with-facades/form/importing-form-data/import-fdf-data/_index.md @@ -3,7 +3,7 @@ title: Импортировать данные FDF linktitle: Импортировать данные FDF type: docs weight: 10 -url: /python-net/import-fdf-data/ +url: /ru/python-net/import-fdf-data/ description: В этом примере демонстрируется, как импортировать данные формы из файла FDF в PDF‑форму с использованием Aspose.PDF for Python via .NET. Показано, как привязать PDF‑документ, считать значения полей формы из потока FDF и автоматически заполнить соответствующие поля. lastmod: "2026-02-19" --- @@ -44,3 +44,4 @@ def import_fdf_to_pdf_form(infile, datafile, outfile): # Save updated PDF pdf_form.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/form/importing-form-data/import-json-data/_index.md b/ru/python-net/working-with-facades/form/importing-form-data/import-json-data/_index.md index a42bd54e3..a487cacdc 100644 --- a/ru/python-net/working-with-facades/form/importing-form-data/import-json-data/_index.md +++ b/ru/python-net/working-with-facades/form/importing-form-data/import-json-data/_index.md @@ -3,7 +3,7 @@ title: Импортировать JSON-данные linktitle: Импортировать JSON-данные type: docs weight: 30 -url: /python-net/import-json-data/ +url: /ru/python-net/import-json-data/ description: В этом примере демонстрируется, как импортировать данные полей формы из файла JSON в PDF-форму, используя Aspose.PDF for Python via .NET. Показано, как привязать PDF-документ, прочитать структурированные JSON-данные через поток файла и автоматически заполнить соответствующие поля формы. lastmod: "2026-02-19" --- @@ -45,3 +45,4 @@ def import_json_to_pdf_form(infile, datafile, outfile): # Save updated PDF form.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/form/importing-form-data/import-xfdf-data/_index.md b/ru/python-net/working-with-facades/form/importing-form-data/import-xfdf-data/_index.md index 92c09f9cc..1a3c628c6 100644 --- a/ru/python-net/working-with-facades/form/importing-form-data/import-xfdf-data/_index.md +++ b/ru/python-net/working-with-facades/form/importing-form-data/import-xfdf-data/_index.md @@ -3,7 +3,7 @@ title: Импортировать данные XFDF linktitle: Импортировать данные XFDF type: docs weight: 20 -url: /python-net/import-xfdf-data/ +url: /ru/python-net/import-xfdf-data/ description: В этом примере демонстрируется, как импортировать данные формы из файла XFDF в форму PDF с использованием Aspose.PDF for Python via .NET. Показано, как привязать документ PDF, читать XML‑основанные данные XFDF через файловый поток и автоматически заполнять соответствующие поля формы. Импорт данных XFDF обеспечивает эффективный обмен данными форм и поддерживает автоматизированные рабочие процессы с документами, которые опираются на структурированные форматы XML. lastmod: "2026-02-19" --- @@ -45,3 +45,4 @@ def import_data_from_xfdf(infile, datafile, outfile): # Save updated PDF pdf_form.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/form/importing-form-data/import-xml-data/_index.md b/ru/python-net/working-with-facades/form/importing-form-data/import-xml-data/_index.md index 52165432a..231387375 100644 --- a/ru/python-net/working-with-facades/form/importing-form-data/import-xml-data/_index.md +++ b/ru/python-net/working-with-facades/form/importing-form-data/import-xml-data/_index.md @@ -3,7 +3,7 @@ title: Импорт данных XML linktitle: Импорт данных XML type: docs weight: 40 -url: /python-net/import-xml-data/ +url: /ru/python-net/import-xml-data/ description: В этом примере демонстрируется, как импортировать данные формы из XML‑файла в поля формы PDF с использованием Aspose.PDF for Python via .NET. Показано, как привязать документ PDF, прочитать структурированные XML‑данные через файловый поток и автоматически заполнить соответствующие поля формы. lastmod: "2026-02-19" --- @@ -45,3 +45,4 @@ def import_xml_to_pdf_fields(infile, datafile, outfile): # Save updated PDF pdf_form.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/form/importing-form-data/replace-xfa-data/_index.md b/ru/python-net/working-with-facades/form/importing-form-data/replace-xfa-data/_index.md index a0e0201ab..ce9a57fa6 100644 --- a/ru/python-net/working-with-facades/form/importing-form-data/replace-xfa-data/_index.md +++ b/ru/python-net/working-with-facades/form/importing-form-data/replace-xfa-data/_index.md @@ -3,7 +3,7 @@ title: Заменить данные XFA linktitle: Заменить данные XFA type: docs weight: 50 -url: /python-net/replace-xfa-data/ +url: /ru/python-net/replace-xfa-data/ description: В этом примере показано, как заменить существующие данные формы XFA в PDF с использованием Aspose.PDF for Python via .NET. Он демонстрирует, как привязать PDF‑документ на основе XFA, загрузить новые данные из внешнего файла XFA и программно обновить содержимое формы. lastmod: "2026-02-19" --- @@ -45,3 +45,4 @@ def replace_xfa_data(infile, datafile, outfile): # Save updated PDF form.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/form/managing-form-fields/_index.md b/ru/python-net/working-with-facades/form/managing-form-fields/_index.md index a48ae4e82..06ba26a39 100644 --- a/ru/python-net/working-with-facades/form/managing-form-fields/_index.md +++ b/ru/python-net/working-with-facades/form/managing-form-fields/_index.md @@ -3,11 +3,11 @@ title: Управление полями формы linktitle: Управление полями формы type: docs weight: 50 -url: /python-net/managing-form-fields/ +url: /ru/python-net/managing-form-fields/ description: В этом разделе демонстрируется, как управлять и изменять поля формы PDF с помощью Aspose.PDF for Python via .NET. Описываются практические примеры сплющивания отдельных полей, сплющивания всех полей формы и программного переименования существующих полей. С помощью фасада Form разработчики могут привязать документ PDF, настроить поведение полей и сохранить обновлённый файл с применёнными постоянными изменениями. lastmod: "2026-02-19" --- - [Уплощение конкретных полей](/pdf/ru/python-net/flatten-specific-fields/) - [Сгладить все поля](/pdf/ru/python-net/flatten-all-fields/) -- [Переименовать поля формы](/pdf/ru/python-net/rename-form-fields/) \ No newline at end of file +- [Переименовать поля формы](/pdf/ru/python-net/rename-form-fields/) diff --git a/ru/python-net/working-with-facades/form/managing-form-fields/flatten-all-fields/_index.md b/ru/python-net/working-with-facades/form/managing-form-fields/flatten-all-fields/_index.md index 8bc942dbd..34a2d30f2 100644 --- a/ru/python-net/working-with-facades/form/managing-form-fields/flatten-all-fields/_index.md +++ b/ru/python-net/working-with-facades/form/managing-form-fields/flatten-all-fields/_index.md @@ -3,7 +3,7 @@ title: Сгладить все поля linktitle: Сгладить все поля type: docs weight: 10 -url: /python-net/flatten-all-fields/ +url: /ru/python-net/flatten-all-fields/ description: В этом примере демонстрируется, как сгладить все поля формы в PDF, используя Aspose.PDF for Python via .NET. Показано, как привязать PDF‑документ, преобразовать каждый интерактивный элемент формы в статическое содержимое страницы и сохранить окончательный файл. lastmod: "2026-02-19" --- @@ -42,3 +42,4 @@ def flatten_all_fields(infile, outfile): # Save updated PDF pdf_form.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/form/managing-form-fields/flatten-specific-fields/_index.md b/ru/python-net/working-with-facades/form/managing-form-fields/flatten-specific-fields/_index.md index 9a5d3d21f..1356ae068 100644 --- a/ru/python-net/working-with-facades/form/managing-form-fields/flatten-specific-fields/_index.md +++ b/ru/python-net/working-with-facades/form/managing-form-fields/flatten-specific-fields/_index.md @@ -3,7 +3,7 @@ title: Уплощение конкретных полей linktitle: Уплощение конкретных полей type: docs weight: 20 -url: /python-net/flatten-specific-fields/ +url: /ru/python-net/flatten-specific-fields/ description: В этом разделе демонстрируется, как управлять и изменять поля форм PDF с помощью Aspose.PDF for Python via .NET. Он содержит практические примеры уплощения конкретных полей, уплощения всех полей формы и программного переименования существующих полей. lastmod: "2026-02-19" --- @@ -46,3 +46,4 @@ def flatten_specific_fields(infile, outfile): # Save updated PDF pdf_form.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/form/managing-form-fields/rename-form-fields/_index.md b/ru/python-net/working-with-facades/form/managing-form-fields/rename-form-fields/_index.md index f135e529d..a74cac71e 100644 --- a/ru/python-net/working-with-facades/form/managing-form-fields/rename-form-fields/_index.md +++ b/ru/python-net/working-with-facades/form/managing-form-fields/rename-form-fields/_index.md @@ -3,7 +3,7 @@ title: Переименовать поля формы linktitle: Переименовать поля формы type: docs weight: 30 -url: /python-net/rename-form-fields/ +url: /ru/python-net/rename-form-fields/ description: Это пример демонстрирует, как переименовать поля формы в PDF‑документе с помощью Aspose.PDF for Python via .NET. Показано, как привязать PDF‑форму, программно обновить существующие имена полей и сохранить изменённый файл. Переименование полей помогает стандартизировать структуру формы, улучшить сопоставление данных и упростить интеграцию с автоматизированными рабочими процессами или внешними системами. lastmod: "2026-02-19" --- @@ -45,3 +45,4 @@ def rename_form_fields(infile, outfile): # Save updated PDF pdf_form.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/form/reading-form-values/_index.md b/ru/python-net/working-with-facades/form/reading-form-values/_index.md index 0aaa2cde8..cbf83512e 100644 --- a/ru/python-net/working-with-facades/form/reading-form-values/_index.md +++ b/ru/python-net/working-with-facades/form/reading-form-values/_index.md @@ -3,7 +3,7 @@ title: Чтение значений Form linktitle: Чтение значений Form type: docs weight: 60 -url: /python-net/reading-form-values/ +url: /ru/python-net/reading-form-values/ description: В этом разделе объясняется, как читать значения Form с помощью Aspose.PDF Facades, используя класс Form. lastmod: "2026-02-19" --- @@ -13,4 +13,4 @@ lastmod: "2026-02-19" - [Получить имена обязательных полей](/pdf/ru/python-net/get-required-field-names/) - [Получить значения Rich Text](/pdf/ru/python-net/get-rich-text-values/) - [Получить фасады полей](/pdf/ru/python-net/get-field-facades/) -- [Получить полные имена полей](/pdf/ru/python-net/resolve-full-field-names/) \ No newline at end of file +- [Получить полные имена полей](/pdf/ru/python-net/resolve-full-field-names/) diff --git a/ru/python-net/working-with-facades/form/reading-form-values/get-field-facades/_index.md b/ru/python-net/working-with-facades/form/reading-form-values/get-field-facades/_index.md index df7fde35e..4871eed11 100644 --- a/ru/python-net/working-with-facades/form/reading-form-values/get-field-facades/_index.md +++ b/ru/python-net/working-with-facades/form/reading-form-values/get-field-facades/_index.md @@ -3,7 +3,7 @@ title: Получить фасады полей linktitle: Получить фасады полей type: docs weight: 10 -url: /python-net/get-field-facades/ +url: /ru/python-net/get-field-facades/ description: В этом примере демонстрируется, как считать значения конкретных полей формы из PDF‑документа с помощью Aspose.PDF Facades API. lastmod: "2026-02-19" --- @@ -41,4 +41,4 @@ PDF‑формы содержат поля, в которые пользоват for field_name in field_names: value = pdf_form.get_field(field_name) print(f"Value of '{field_name}': {value}") -``` \ No newline at end of file +``` diff --git a/ru/python-net/working-with-facades/form/reading-form-values/get-field-values/_index.md b/ru/python-net/working-with-facades/form/reading-form-values/get-field-values/_index.md index a44fbff22..41624f3db 100644 --- a/ru/python-net/working-with-facades/form/reading-form-values/get-field-values/_index.md +++ b/ru/python-net/working-with-facades/form/reading-form-values/get-field-values/_index.md @@ -3,7 +3,7 @@ title: Получить значения полей linktitle: Получить значения полей type: docs weight: 50 -url: /python-net/get-field-values/ +url: /ru/python-net/get-field-values/ description: Извлечение значений полей из PDF-формы с помощью Aspose.PDF Facades, используя класс Form. lastmod: "2026-02-19" --- @@ -41,4 +41,4 @@ lastmod: "2026-02-19" for field_name in field_names: value = pdf_form.get_field(field_name) print(f"Value of '{field_name}': {value}") -``` \ No newline at end of file +``` diff --git a/ru/python-net/working-with-facades/form/reading-form-values/get-radio-button-options/_index.md b/ru/python-net/working-with-facades/form/reading-form-values/get-radio-button-options/_index.md index 90b67d574..b525bcc1f 100644 --- a/ru/python-net/working-with-facades/form/reading-form-values/get-radio-button-options/_index.md +++ b/ru/python-net/working-with-facades/form/reading-form-values/get-radio-button-options/_index.md @@ -3,7 +3,7 @@ title: Получить варианты радиокнопок linktitle: Получить варианты радиокнопок type: docs weight: 20 -url: /python-net/get-radio-button-options/ +url: /ru/python-net/get-radio-button-options/ description: В этой статье демонстрируется, как получить текущее выбранное значение поля радиокнопки в PDF‑документе с помощью API Aspose.PDF Facades. lastmod: "2026-02-19" --- @@ -41,3 +41,4 @@ def get_radio_button_options(infile): options = pdf_form.get_button_option_current_value(field_name) print(f"Options for '{field_name}': {options}") ``` + diff --git a/ru/python-net/working-with-facades/form/reading-form-values/get-required-field-names/_index.md b/ru/python-net/working-with-facades/form/reading-form-values/get-required-field-names/_index.md index a581130e6..5ab3a0f59 100644 --- a/ru/python-net/working-with-facades/form/reading-form-values/get-required-field-names/_index.md +++ b/ru/python-net/working-with-facades/form/reading-form-values/get-required-field-names/_index.md @@ -3,7 +3,7 @@ title: Получить имена обязательных полей linktitle: Получить имена обязательных полей type: docs weight: 30 -url: /python-net/get-required-field-names/ +url: /ru/python-net/get-required-field-names/ description: Этот пример демонстрирует, как идентифицировать и получить имена обязательных полей формы в PDF-документе с использованием API Aspose.PDF Facades. lastmod: "2026-02-19" --- @@ -40,3 +40,4 @@ def get_required_field_names(infile): if pdf_form.is_required_field(field): print(f"Required field: {field}") ``` + diff --git a/ru/python-net/working-with-facades/form/reading-form-values/get-rich-text-values/_index.md b/ru/python-net/working-with-facades/form/reading-form-values/get-rich-text-values/_index.md index a23eb1dd9..c77b69ed4 100644 --- a/ru/python-net/working-with-facades/form/reading-form-values/get-rich-text-values/_index.md +++ b/ru/python-net/working-with-facades/form/reading-form-values/get-rich-text-values/_index.md @@ -3,7 +3,7 @@ title: Получить значения Rich Text linktitle: Получить значения Rich Text type: docs weight: 40 -url: /python-net/get-rich-text-values/ +url: /ru/python-net/get-rich-text-values/ description: Этот раздел объясняет, как получить содержимое Rich Text поля формы в PDF‑документе с помощью API Aspose.PDF Facades. В отличие от обычных текстовых полей, поля Rich Text могут содержать форматированный контент, такой как полужирный текст, различные шрифты, цвета и стили абзацев. lastmod: "2026-02-19" --- @@ -41,3 +41,4 @@ def get_rich_text_values(infile): rich_text_value = pdf_form.get_rich_text(field_name) print(f"Rich text value of '{field_name}': {rich_text_value}") ``` + diff --git a/ru/python-net/working-with-facades/form/reading-form-values/resolve-full-field-names/_index.md b/ru/python-net/working-with-facades/form/reading-form-values/resolve-full-field-names/_index.md index 17e00137a..0bcaa6b78 100644 --- a/ru/python-net/working-with-facades/form/reading-form-values/resolve-full-field-names/_index.md +++ b/ru/python-net/working-with-facades/form/reading-form-values/resolve-full-field-names/_index.md @@ -3,7 +3,7 @@ title: Получить полные имена полей linktitle: Получить полные имена полей type: docs weight: 60 -url: /python-net/resolve-full-field-names/ +url: /ru/python-net/resolve-full-field-names/ description: Этот пример демонстрирует, как получить полностью квалифицированные имена полей формы в PDF‑документе с использованием Aspose.PDF Facades API. lastmod: "2026-02-19" --- @@ -41,3 +41,4 @@ def resolve_full_field_names(infile): name = pdf_form.get_full_field_name(field) print(f"Full field name: {name}") ``` + diff --git a/ru/python-net/working-with-facades/formeditor/_index.md b/ru/python-net/working-with-facades/formeditor/_index.md index d71699925..458016a1e 100644 --- a/ru/python-net/working-with-facades/formeditor/_index.md +++ b/ru/python-net/working-with-facades/formeditor/_index.md @@ -3,7 +3,7 @@ title: Класс FormEditor linktitle: Класс FormEditor type: docs weight: 100 -url: /python-net/formeditor-class/ +url: /ru/python-net/formeditor-class/ description: Узнайте, как использовать класс FormEditor в Aspose.PDF for Python via .NET для создания полей формы, изменения существующих полей, настройки внешнего вида полей и добавления скриптов или действий отправки. lastmod: "2026-03-05" sitemap: @@ -24,3 +24,4 @@ Abstract: В этом разделе объясняется, как исполь - [Настройка внешнего вида полей](/pdf/ru/python-net/customizing-field-appearance/) - [Изменение полей формы](/pdf/ru/python-net/modifying-form-fields/) - [Создание поля формы](/pdf/ru/python-net/creating-form-field) + diff --git a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md index 3ecc5396a..0375e718e 100644 --- a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md +++ b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md @@ -3,7 +3,7 @@ title: Добавление сценариев и действий отправ linktitle: Добавление сценариев и действий отправки type: docs weight: 40 -url: /python-net/adding-scripts-and-submit-actions/ +url: /ru/python-net/adding-scripts-and-submit-actions/ description: С помощью Aspose.PDF for Python разработчики могут автоматизировать эти действия без ручного редактирования PDF. lastmod: "2026-03-05" sitemap: @@ -20,3 +20,4 @@ Abstract: Узнайте, как программно добавлять, изм - [Установить URL отправки](/pdf/ru/python-net/set-submit-url/) - [Установить флаг отправки](/pdf/ru/python-net/set-submit-flag/) + diff --git a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md index 7601805c4..223f6e45d 100644 --- a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md +++ b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md @@ -3,7 +3,7 @@ title: Добавить скрипт поля linktitle: Добавить скрипт поля type: docs weight: 10 -url: /python-net/add-field-script/ +url: /ru/python-net/add-field-script/ description: Интерактивные PDF‑формы могут включать JavaScript для автоматизации действий, когда пользователи взаимодействуют с полями формы. С помощью Aspose.PDF for Python разработчики могут легко прикреплять скрипты к элементам формы, таким как кнопки или текстовые поля. lastmod: "2026-03-05" sitemap: @@ -55,3 +55,4 @@ def add_field_script(input_file_name, output_file_name): # Save output PDF file form_editor.save(output_file_name) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md index 3cd47c8d5..0bcdb9f20 100644 --- a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md +++ b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md @@ -3,7 +3,7 @@ title: Удалить действие поля linktitle: Удалить действие поля type: docs weight: 20 -url: /python-net/remove-field-action/ +url: /ru/python-net/remove-field-action/ description: Удаление JavaScript из полей формы может быть полезным при изменении интерактивных PDF‑форм, отключении ранее назначенных действий или очистке документов, содержащих ненужные скрипты. lastmod: "2026-03-05" sitemap: @@ -49,3 +49,4 @@ def remove_field_script(input_file_name, output_file_name): # Save output PDF file form_editor.save(output_file_name) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md index a755b884d..a821ad6cb 100644 --- a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md +++ b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md @@ -3,7 +3,7 @@ title: Установить скрипт поля linktitle: Установить скрипт поля type: docs weight: 30 -url: /python-net/set-field-script/ +url: /ru/python-net/set-field-script/ description: Этот фрагмент кода показывает, как назначить действие JavaScript полю формы в PDF‑документе с использованием Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -58,3 +58,4 @@ def set_field_script(input_file_name, output_file_name): # Save output PDF file form_editor.save(output_file_name) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md index 80f5676f5..bb3cef78c 100644 --- a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md +++ b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md @@ -3,7 +3,7 @@ title: Установить флаг отправки linktitle: Установить флаг отправки type: docs weight: 50 -url: /python-net/set-submit-flag/ +url: /ru/python-net/set-submit-flag/ description: Узнайте, как программно установить флаг отправки для кнопки формы PDF, используя Aspose.PDF for Python. Это позволяет кнопке отправлять данные формы в определённом формате, например XFDF, при нажатии пользователем. lastmod: "2026-03-05" sitemap: @@ -45,3 +45,4 @@ def set_submit_flag(input_file_name, output_file_name): # Save output PDF file form_editor.save(output_file_name) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md index f49d62958..51e862eb6 100644 --- a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md +++ b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md @@ -3,7 +3,7 @@ title: Установить URL отправки linktitle: Установить URL отправки type: docs weight: 40 -url: /python-net/set-submit-url/ +url: /ru/python-net/set-submit-url/ description: В этом примере показано, как настроить действие отправки для поля кнопки в PDF‑форме с использованием Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -55,3 +55,4 @@ def set_submit_url(input_file_name, output_file_name): # Save output PDF file form_editor.save(output_file_name) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/creating-form-field/_index.md b/ru/python-net/working-with-facades/formeditor/creating-form-field/_index.md index 80afbc573..ab59daa7e 100644 --- a/ru/python-net/working-with-facades/formeditor/creating-form-field/_index.md +++ b/ru/python-net/working-with-facades/formeditor/creating-form-field/_index.md @@ -3,7 +3,7 @@ title: Создание поля формы linktitle: Создание поля формы type: docs weight: 50 -url: /python-net/creating-form-field/ +url: /ru/python-net/creating-form-field/ description: В этой статье демонстрируется, как создавать интерактивные поля формы в PDF‑документах с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -19,4 +19,4 @@ Abstract: PDF‑формы позволяют пользователям вво - [Создать поле ListBox](/pdf/ru/python-net/create-listbox-field/) - [Создать поле RadioButton](/pdf/ru/python-net/create-radiobutton-field/) - [Создать Submit Button](/pdf/ru/python-net/create-submit-button/) -- [Создать поле TextBox](/pdf/ru/python-net/create-textbox-field/) \ No newline at end of file +- [Создать поле TextBox](/pdf/ru/python-net/create-textbox-field/) diff --git a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md index b88ef6cf1..b908357d0 100644 --- a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md +++ b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md @@ -3,7 +3,7 @@ title: Создать поле CheckBox linktitle: Создать поле CheckBox type: docs weight: 10 -url: /python-net/create-checkbox-field/ +url: /ru/python-net/create-checkbox-field/ description: Узнайте, как программно добавить поле формы‑чекбокс в документ PDF с помощью Aspose.PDF for Python. Это руководство демонстрирует, как использовать класс FormEditor для вставки интерактивного чекбокса в существующий файл PDF и сохранения обновлённого документа. lastmod: "2026-03-05" sitemap: @@ -53,3 +53,4 @@ def create_checkbox_field(infile, outfile): # Save updated PDF document with form fields pdf_form_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md index a8670fd6c..a83c116a1 100644 --- a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md +++ b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md @@ -3,7 +3,7 @@ title: Создать поле ComboBox linktitle: Создать поле ComboBox type: docs weight: 20 -url: /python-net/create-combobox-field/ +url: /ru/python-net/create-combobox-field/ description: Проверьте, как программно добавить поле ComboBox (выпадающий список) в документ PDF с помощью Aspose.PDF for Python. Этот пример демонстрирует, как вставить поле ComboBox, добавить выбираемые элементы и сохранить обновлённый файл PDF. lastmod: "2026-03-05" sitemap: @@ -48,3 +48,4 @@ def create_combobox_field(infile, outfile): # Save updated PDF document with form fields pdf_form_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md index c7fe33996..1953a8369 100644 --- a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md +++ b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md @@ -3,7 +3,7 @@ title: Создать поле ListBox linktitle: Создать поле ListBox type: docs weight: 30 -url: /python-net/create-listbox-field/ +url: /ru/python-net/create-listbox-field/ description: Узнайте, как программно добавить поле формы ListBox в документ PDF с использованием Aspose.PDF for Python. Это руководство показывает, как вставить поле ListBox, определить выбираемые элементы и сохранить обновлённый файл PDF. lastmod: "2026-03-05" sitemap: @@ -48,3 +48,4 @@ def create_listbox_field(infile, outfile): # Save updated PDF document with form fields pdf_form_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md index 3fee63753..8cd612267 100644 --- a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md +++ b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md @@ -3,7 +3,7 @@ title: Создать поле RadioButton linktitle: Создать поле RadioButton type: docs weight: 40 -url: /python-net/create-radiobutton-field/ +url: /ru/python-net/create-radiobutton-field/ description: Узнайте, как программно добавить поле радиокнопки в PDF‑документ с помощью Aspose.PDF for Python. Этот пример демонстрирует, как создать группу радиокнопок, определить варианты выбора и сохранить обновлённый PDF‑файл. lastmod: "2026-03-05" sitemap: @@ -48,3 +48,4 @@ def create_radiobutton_field(infile, outfile): # Save updated PDF document with form fields pdf_form_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md index 9d4d0f845..7548c2ed0 100644 --- a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md +++ b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md @@ -3,7 +3,7 @@ title: Создать кнопку отправки linktitle: Создать кнопку отправки type: docs weight: 50 -url: /python-net/create-submit-button/ +url: /ru/python-net/create-submit-button/ description: Узнайте, как программно добавить кнопку отправки в документ PDF с помощью Aspose.PDF for Python. Этот учебный материал демонстрирует, как создать кнопку, которая отправляет данные формы на указанный URL, и сохранить обновлённый PDF. lastmod: "2026-03-05" sitemap: @@ -53,3 +53,4 @@ def create_submit_button(infile, outfile): # Save updated PDF document with form fields pdf_form_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md index 73f3e4c10..b83330930 100644 --- a/ru/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md +++ b/ru/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md @@ -3,7 +3,7 @@ title: Создать поле TextBox linktitle: Создать поле TextBox type: docs weight: 60 -url: /python-net/create-textbox-field/ +url: /ru/python-net/create-textbox-field/ description: Узнайте, как программно добавить поля TextBox в документ PDF с помощью Aspose.PDF for Python. Этот учебник показывает, как вставить несколько текстовых полей, задать значения по умолчанию и сохранить обновлённый документ PDF. lastmod: "2026-03-05" sitemap: @@ -48,3 +48,4 @@ def create_textbox_field(infile, outfile): # Save updated PDF document with form fields pdf_form_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md index 9a8409b4a..61ec8a959 100644 --- a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md +++ b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md @@ -3,7 +3,7 @@ title: Настройка внешнего вида полей linktitle: Настройка внешнего вида полей type: docs weight: 30 -url: /python-net/customizing-field-appearance/ +url: /ru/python-net/customizing-field-appearance/ description: Используя Aspose.PDF for Python, разработчики могут полностью настраивать внешний вид и поведение полей программно. lastmod: "2026-03-05" sitemap: @@ -22,3 +22,4 @@ Abstract: Узнайте, как настраивать внешний вид и - [Установить ограничение поля](/pdf/ru/python-net/set-field-limit/) - [Получить внешний вид поля](/pdf/ru/python-net/get-field-appearance/) + diff --git a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md index 0cd803ebe..b54214965 100644 --- a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md +++ b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md @@ -3,7 +3,7 @@ title: Украсьте поле linktitle: Украсьте поле type: docs weight: 10 -url: /python-net/decorate-field/ +url: /ru/python-net/decorate-field/ description: В этом примере демонстрируется, как настроить внешний вид поля формы в PDF‑документе с использованием Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -54,3 +54,4 @@ def decorate_field(infile, outfile): form_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md index a5df487c0..863e6e4e1 100644 --- a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md +++ b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md @@ -3,7 +3,7 @@ title: Получить внешний вид поля linktitle: Получить внешний вид поля type: docs weight: 20 -url: /python-net/get-field-appearance/ +url: /ru/python-net/get-field-appearance/ description: В этой статье объясняется, как открыть PDF, получить доступ к полю формы, извлечь его настройки внешнего вида и отобразить их. Пример демонстрирует извлечение внешнего вида поля с именем 'Last Name'. lastmod: "2026-03-05" sitemap: @@ -44,3 +44,4 @@ def get_field_appearance(infile, outfile): appearance = form_editor.get_field_appearance("Last Name") print("Field Appearance: " + str(appearance)) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md index a6ad5a15e..e626036cc 100644 --- a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md +++ b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md @@ -3,7 +3,7 @@ title: Установить вертикальное выравнивание п linktitle: Установить вертикальное выравнивание поля type: docs weight: 40 -url: /python-net/set-field-alignment-vertical/ +url: /ru/python-net/set-field-alignment-vertical/ description: Этот пример демонстрирует, как установить вертикальное выравнивание поля формы в PDF‑документе с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -55,3 +55,4 @@ def set_field_alignment_vertical(infile, outfile): "Failed to set field vertical alignment. Field may not support vertical alignment." ) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md index d4d476224..916654eb0 100644 --- a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md +++ b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md @@ -3,7 +3,7 @@ title: Установить выравнивание поля linktitle: Установить выравнивание поля type: docs weight: 30 -url: /python-net/set-field-alignment/ +url: /ru/python-net/set-field-alignment/ description: В этом примере показано, как установить выравнивание текста в поле формы в PDF‑документе с использованием Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -54,3 +54,4 @@ def set_field_alignment(infile, outfile): "Failed to set field alignment. Field may not support alignment." ) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md index d8c905d22..5c76de0fd 100644 --- a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md +++ b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md @@ -3,7 +3,7 @@ title: Установить внешний вид поля linktitle: Установить внешний вид поля type: docs weight: 50 -url: /python-net/set-field-appearance/ +url: /ru/python-net/set-field-appearance/ description: В этом примере показано, как изменить визуальный внешний вид поля формы PDF с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -54,3 +54,4 @@ def set_field_appearance(infile, outfile): # Save updated document form_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md index 2ed31db77..795141621 100644 --- a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md +++ b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md @@ -3,7 +3,7 @@ title: Установить количество ячеек поля linktitle: Установить количество ячеек поля type: docs weight: 70 -url: /python-net/set-field-comb-number/ +url: /ru/python-net/set-field-comb-number/ description: В этом примере демонстрируется, как установить количество ячеек (comb number) для поля формы PDF с использованием Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -49,3 +49,4 @@ def set_field_comb_number(infile, outfile): # Save updated document form_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md index df1c69aab..84191f7bc 100644 --- a/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md +++ b/ru/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md @@ -3,7 +3,7 @@ title: Установить ограничение поля linktitle: Установить ограничение поля type: docs weight: 80 -url: /python-net/set-field-limit/ +url: /ru/python-net/set-field-limit/ description: Этот пример показывает, как установить максимальное ограничение количества символов для поля формы в PDF-документе с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -52,3 +52,4 @@ def set_field_limit(infile, outfile): # Save updated document form_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md index a1b98554f..9a4aac1c0 100644 --- a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md @@ -3,7 +3,7 @@ title: Изменение полей формы linktitle: Изменение полей формы type: docs weight: 20 -url: /python-net/modifying-form-fields/ +url: /ru/python-net/modifying-form-fields/ description: Используя Aspose.PDF for Python, вы можете эффективно изменять поля формы программно с помощью класса FormEditor. lastmod: "2026-03-05" sitemap: @@ -23,3 +23,4 @@ Abstract: Узнайте, как изменять существующие по - [Скопировать внутреннее поле](/pdf/ru/python-net/copy-inner-field/) - [Копировать внешнее поле](/pdf/ru/python-net/copy-outer-field/) + diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md index e4508953e..d84ab632a 100644 --- a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md @@ -3,7 +3,7 @@ title: Добавить элемент списка linktitle: Добавить элемент списка type: docs weight: 10 -url: /python-net/add-list-item/ +url: /ru/python-net/add-list-item/ description: В этом примере демонстрируется, как добавить элементы в поле списка формы в PDF‑документе с использованием Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -44,3 +44,4 @@ def add_list_item(infile, outfile): # Save updated document form_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md index 981219964..58463ea92 100644 --- a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md @@ -3,7 +3,7 @@ title: Скопировать внутреннее поле linktitle: Скопировать внутреннее поле type: docs weight: 20 -url: /python-net/copy-inner-field/ +url: /ru/python-net/copy-inner-field/ description: Скопировать поля формы PDF в новое положение с помощью Python, используя Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -70,3 +70,4 @@ form_editor.copy_inner_field("First Name", "First Name Copy", -1, 200, 600) ``` Программа затем сбросит параметры к предыдущим. + diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md index a65ec7fb9..c6c3e5069 100644 --- a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md @@ -3,7 +3,7 @@ title: Копировать внешнее поле linktitle: Копировать внешнее поле type: docs weight: 30 -url: /python-net/copy-outer-field/ +url: /ru/python-net/copy-outer-field/ description: В этом примере демонстрируется, как скопировать поле формы из одного PDF‑документа в другой, используя Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -78,3 +78,4 @@ form_editor.copy_outer_field("First Name", "First Name Copy", 1, -200, 600) ``` Программа затем сбросит параметры к предыдущим. + diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md index eb133610d..ddfdcf835 100644 --- a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md @@ -3,7 +3,7 @@ title: Удалить элемент списка linktitle: Удалить элемент списка type: docs weight: 40 -url: /python-net/del-list-item/ +url: /ru/python-net/del-list-item/ description: lastmod: "2026-03-05" sitemap: @@ -49,3 +49,4 @@ def del_list_item(infile, outfile): form_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md index 64c58029a..bf1950854 100644 --- a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md @@ -3,7 +3,7 @@ title: Переместить поле linktitle: Переместить поле type: docs weight: 50 -url: /python-net/move-field/ +url: /ru/python-net/move-field/ description: Переместить существующее поле формы в другое место в PDF‑документе. lastmod: "2026-03-05" sitemap: @@ -46,3 +46,4 @@ def move_field(infile, outfile): # Save updated document form_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md index 8a8df650c..bf1ea0682 100644 --- a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md @@ -3,7 +3,7 @@ title: Удалить поле linktitle: Удалить поле type: docs weight: 60 -url: /python-net/remove-field/ +url: /ru/python-net/remove-field/ description: Этот пример показывает, как удалить поле 'Country' из PDF-формы с помощью метода 'remove_field' класса 'FormEditor'. lastmod: "2026-03-05" sitemap: @@ -46,3 +46,4 @@ def remove_field(infile, outfile): # Save updated document form_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md index bbb022941..d987f8616 100644 --- a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md @@ -3,7 +3,7 @@ title: Переименовать поле linktitle: Переименовать поле type: docs weight: 70 -url: /python-net/rename-field/ +url: /ru/python-net/rename-field/ description: Переименуйте существующее поле формы в PDF‑документе с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -47,3 +47,4 @@ def rename_field(infile, outfile): form_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md index 39cc6005e..c1b90f798 100644 --- a/ru/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md +++ b/ru/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md @@ -3,7 +3,7 @@ title: Однострочное поле в многострочное поле linktitle: Однострочное поле в многострочное поле type: docs weight: 80 -url: /python-net/single-to-multiple/ +url: /ru/python-net/single-to-multiple/ description: Преобразовать однострочное текстовое поле в многострочное поле в PDF‑документе с использованием Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -47,3 +47,4 @@ def single2multiple(infile, outfile): form_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfannotationeditor/_index.md b/ru/python-net/working-with-facades/pdfannotationeditor/_index.md index 56548c649..6e1b7aaa7 100644 --- a/ru/python-net/working-with-facades/pdfannotationeditor/_index.md +++ b/ru/python-net/working-with-facades/pdfannotationeditor/_index.md @@ -3,7 +3,7 @@ title: Класс PdfAnnotationEditor linktitle: Класс PdfAnnotationEditor type: docs weight: 40 -url: /python-net/pdfannotationeditor-class/ +url: /ru/python-net/pdfannotationeditor-class/ description: Узнайте, как использовать класс PdfAnnotationEditor в Aspose.PDF for Python via .NET для работы с PDF‑аннотациями, комментариями и разметкой программно. lastmod: "2026-02-05" sitemap: @@ -20,3 +20,4 @@ Abstract: Этот раздел представляет класс PdfAnnotatio Используйте этот фасад, когда ваш процесс работы с PDF включает аннотации, комментарии по обзору или другие элементы разметки, которые необходимо управлять программно. По мере расширения этого раздела он должен служить целевой страницей для учебных материалов, связанных с аннотациями, построенных вокруг `PdfAnnotationEditor` класс. + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/_index.md index b9e367049..cde4fb435 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/_index.md @@ -3,7 +3,7 @@ title: Класс PdfContentEditor linktitle: Класс PdfContentEditor type: docs weight: 30 -url: /python-net/pdfcontenteditor-class/ +url: /ru/python-net/pdfcontenteditor-class/ description: Узнайте, как использовать класс PdfContentEditor в Aspose.PDF for Python via .NET для редактирования содержимого PDF, управления аннотациями и вложениями, работы со ссылками, изображениями, текстом, мультимедиа, штампами и настройками просмотра. lastmod: "2026-03-20" sitemap: @@ -30,3 +30,4 @@ Abstract: В этом разделе объясняется, как исполь - [Управляйте PDF‑штампами с помощью PdfContentEditor](/pdf/ru/python-net/stamps-management/) - [Заменяйте и обновляйте текст с помощью PdfContentEditor](/pdf/ru/python-net/text-operations/) - [Изменяйте настройки просмотра с помощью PdfContentEditor](/pdf/ru/python-net/viewer-preferences/) + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md index 0f2353a10..c06f1cf11 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md @@ -3,7 +3,7 @@ title: Аннотации linktitle: Аннотации type: docs weight: 10 -url: /python-net/annotations/ +url: /ru/python-net/annotations/ description: lastmod: "2026-03-20" sitemap: @@ -16,3 +16,4 @@ sitemap: - [Добавить аннотации разметки](/pdf/ru/python-net/add-markup-annotation/) - [Добавить всплывающие аннотации](/pdf/ru/python-net/add-popup-annotation/) - [Добавить аннотацию в виде курсора](/pdf/ru/python-net/add-caret-annotation/) + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md index 1331c5b94..d97372b95 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md @@ -3,7 +3,7 @@ title: Добавить аннотации в виде курсора linktitle: Добавить аннотации в виде курсора type: docs weight: 10 -url: /python-net/add-caret-annotation/ +url: /ru/python-net/add-caret-annotation/ description: В этом примере загружается существующий PDF, добавляется аннотация в виде курсора на первую страницу и сохраняется изменённый документ. Аннотация включает красный символ курсора и пояснительный текст комментария. lastmod: "2026-03-20" sitemap: @@ -57,3 +57,4 @@ def add_caret_annotation(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md index 613be9c61..08eb8c5ab 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md @@ -3,7 +3,7 @@ title: Добавить свободные текстовые аннотации linktitle: Добавить свободные текстовые аннотации type: docs weight: 20 -url: /python-net/add-free-text-annotation/ +url: /ru/python-net/add-free-text-annotation/ description: В этом примере загружается существующий PDF‑файл, добавляется свободная текстовая аннотация на первую страницу в заданном положении и сохраняется изменённый документ. lastmod: "2026-03-20" sitemap: @@ -46,3 +46,4 @@ def add_free_text_annotation(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md index edef5755b..a843c4bfa 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md @@ -3,7 +3,7 @@ title: Добавить аннотации разметки linktitle: Добавить аннотации разметки type: docs weight: 30 -url: /python-net/add-markup-annotation/ +url: /ru/python-net/add-markup-annotation/ description: В этом примере привязывается входной PDF, добавляются четыре разных разметочных аннотации на первую страницу и сохраняется обновлённый документ. Каждая аннотация демонстрирует иной стиль разметки и цвет. lastmod: "2026-03-20" sitemap: @@ -71,3 +71,4 @@ def add_markup_annotation(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md index 5f2c3b4c1..123b31537 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md @@ -3,7 +3,7 @@ title: Добавить всплывающие аннотации linktitle: Добавить всплывающие аннотации type: docs weight: 40 -url: /python-net/add-popup-annotation/ +url: /ru/python-net/add-popup-annotation/ description: В этом примере загружается PDF, добавляется всплывающая аннотация на первую страницу и сохраняется изменённый документ. Всплывающая аннотация установлена видимой по умолчанию и отображает указанный текст комментария. lastmod: "2026-03-20" sitemap: @@ -49,3 +49,4 @@ def add_popup_annotation(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-text-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-text-annotation/_index.md index 2fcda3ec1..c234577d8 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-text-annotation/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/add-text-annotation/_index.md @@ -3,7 +3,7 @@ title: Добавить текстовые аннотации linktitle: Добавить текстовые аннотации type: docs weight: 50 -url: /python-net/add-text-annotation/ +url: /ru/python-net/add-text-annotation/ description: Добавьте текстовые аннотации в PDF‑документ с помощью класса PdfContentEditor в Aspose.PDF for Python via .NET. lastmod: "2026-03-20" sitemap: @@ -60,3 +60,4 @@ def add_text_annotation(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md index 603c4932c..643dc31d3 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md @@ -3,7 +3,7 @@ title: Вложения linktitle: Вложения type: docs weight: 20 -url: /python-net/attachments/ +url: /ru/python-net/attachments/ description: lastmod: "2026-03-20" sitemap: @@ -16,3 +16,4 @@ sitemap: - [Добавить аннотацию вложения файла](/pdf/ru/python-net/add-file-attachment-annotation/) - [Добавить аннотацию вложения файла из потока](/pdf/ru/python-net/add-file-attachment-annotation-from-stream/) - [Удалить вложения](/pdf/ru/python-net/remove-attachments/) + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment-from-path/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment-from-path/_index.md index 828e0995a..ac418b1fc 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment-from-path/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment-from-path/_index.md @@ -3,7 +3,7 @@ title: Добавить вложение из пути linktitle: Добавить вложение из пути type: docs weight: 20 -url: /python-net/add-attachment-from-path/ +url: /ru/python-net/add-attachment-from-path/ description: В этом примере связывается входной PDF, прикрепляется внешний файл с использованием его пути к файлу и сохраняется измененный PDF с встроенным вложением. lastmod: "2026-03-20" sitemap: @@ -46,3 +46,4 @@ def add_attachment_from_path(infile, attachment_file, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment/_index.md index 9ccd7d0ab..925070704 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment/_index.md @@ -3,7 +3,7 @@ title: Добавить вложение linktitle: Добавить вложение type: docs weight: 10 -url: /python-net/add-attachment/ +url: /ru/python-net/add-attachment/ description: В этом примере происходит привязка входного PDF, прикрепление внешнего файла к первой странице и сохранение изменённого PDF с встроенным вложением. lastmod: "2026-03-20" sitemap: @@ -49,3 +49,4 @@ def add_attachment(infile, attachment_file, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md index 41aab0da8..17cf524d9 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md @@ -3,7 +3,7 @@ title: Добавить аннотацию вложения файла linktitle: Добавить аннотацию вложения файла type: docs weight: 30 -url: /python-net/add-file-attachment-annotation/ +url: /ru/python-net/add-file-attachment-annotation/ description: В примере привязывается входной PDF, добавляется аннотация вложения файла на первую страницу с использованием пути к файлу и сохраняется обновлённый документ. lastmod: "2026-03-20" sitemap: @@ -50,3 +50,4 @@ def add_file_attachment_annotation(infile, attachment_file, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md index f7251e290..af065c19a 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md @@ -3,7 +3,7 @@ title: Добавить аннотацию вложения файла из по linktitle: Добавить аннотацию вложения файла из потока type: docs weight: 40 -url: /python-net/add-file-attachment-annotation-from-stream/ +url: /ru/python-net/add-file-attachment-annotation-from-stream/ description: В примере загружается PDF, читается внешний файл в поток памяти, добавляется аннотация вложения файла на первую страницу и сохраняется изменённый документ. lastmod: "2026-03-20" sitemap: @@ -56,3 +56,4 @@ def add_file_attachment_annotation_from_stream(infile, attachment_file, outfile) # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md index ecf71b424..1becb7229 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md @@ -3,7 +3,7 @@ title: Удалить вложения linktitle: Удалить вложения type: docs weight: 50 -url: /python-net/remove-attachments/ +url: /ru/python-net/remove-attachments/ description: В этом примере происходит привязка входного PDF, удаляются все вложения и сохраняется изменённый PDF без встроенных файлов. lastmod: "2026-03-20" sitemap: @@ -43,3 +43,4 @@ def remove_attachments(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md index 43c638722..cefe825de 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md @@ -3,7 +3,7 @@ title: Действия с документом linktitle: Действия с документом type: docs weight: 40 -url: /python-net/document-actions/ +url: /ru/python-net/document-actions/ description: lastmod: "2026-03-20" sitemap: @@ -13,4 +13,4 @@ sitemap: - [Добавить действие закладки](/pdf/ru/python-net/add-bookmark-action/) - [Добавить действие Document](/pdf/ru/python-net/add-document-action/) -- [Удалить действие при открытии](/pdf/ru/python-net/remove-open-action/) \ No newline at end of file +- [Удалить действие при открытии](/pdf/ru/python-net/remove-open-action/) diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md index 17e6eb9fa..8b0d811c8 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md @@ -3,7 +3,7 @@ title: Добавить действие закладки linktitle: Добавить действие закладки type: docs weight: 10 -url: /python-net/add-bookmark-action/ +url: /ru/python-net/add-bookmark-action/ description: В этом примере привязывается входной PDF, создаётся закладка с меткой "PdfContentEditor Bookmark", которая переходит к странице 1, и сохраняется обновлённый документ. lastmod: "2026-03-20" sitemap: @@ -50,4 +50,4 @@ def add_bookmark_action(infile, outfile): ) # Save updated document content_editor.save(outfile) -``` \ No newline at end of file +``` diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md index 182c40cf1..2ae0531d1 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md @@ -3,7 +3,7 @@ title: Добавить действие Document linktitle: Добавить действие Document type: docs weight: 20 -url: /python-net/add-document-action/ +url: /ru/python-net/add-document-action/ description: В этом примере добавляется предупреждающее сообщение JavaScript, которое появляется при открытии PDF. Скрипт привязан к событию открытия документа и автоматически выполняется в поддерживаемых PDF‑просмотрщиках. lastmod: "2026-03-20" sitemap: @@ -45,3 +45,4 @@ def add_document_action(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md index e66a2392a..56f4e9fe5 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md @@ -3,7 +3,7 @@ title: Удалить действие при открытии linktitle: Удалить действие при открытии type: docs weight: 30 -url: /python-net/remove-open-action/ +url: /ru/python-net/remove-open-action/ description: В этом примере загружается существующий PDF, удаляется действие при открытии и сохраняется очищенный документ. lastmod: "2026-03-20" sitemap: @@ -44,3 +44,4 @@ def remove_open_action(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md index 597e75b16..0d89e7257 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md @@ -3,7 +3,7 @@ title: Рисование аннотаций linktitle: Рисование аннотаций type: docs weight: 50 -url: /python-net/drawing-annotations/ +url: /ru/python-net/drawing-annotations/ description: lastmod: "2026-03-20" sitemap: @@ -17,3 +17,4 @@ sitemap: - [Добавить аннотации полигон](/pdf/ru/python-net/add-polygon-annotation/) - [Добавить аннотации полилиний](/pdf/ru/python-net/add-polyline-annotation/) - [Добавить аннотации кривой](/pdf/ru/python-net/add-curve-annotation/) + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md index 942f44113..59ecd43f8 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md @@ -3,7 +3,7 @@ title: Добавить круговую аннотацию linktitle: Добавить круговую аннотацию type: docs weight: 10 -url: /python-net/add-circle-annotation/ +url: /ru/python-net/add-circle-annotation/ description: В этом примере привязывается входной PDF, создаётся круговая аннотация на первой странице и сохраняется изменённый документ. lastmod: "2026-03-20" sitemap: @@ -48,3 +48,4 @@ def add_circle_annotation(infile, outfile): # Save output PDF file content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md index 560342354..5ea2fb8b9 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md @@ -3,7 +3,7 @@ title: Добавить аннотацию кривой linktitle: Добавить аннотацию кривой type: docs weight: 20 -url: /python-net/add-curve-annotation/ +url: /ru/python-net/add-curve-annotation/ description: В этом примере привязывается входной PDF, рисуется пунктирная кривая на первой странице и сохраняется изменённый документ. lastmod: "2026-03-20" sitemap: @@ -54,3 +54,4 @@ def add_curve_annotation(infile, outfile): # Save output PDF file content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md index 36936036d..1e4ef2da0 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md @@ -3,7 +3,7 @@ title: Добавить аннотацию линий linktitle: Добавить аннотацию линий type: docs weight: 30 -url: /python-net/add-line-annotation/ +url: /ru/python-net/add-line-annotation/ description: В этом примере привязывается входной PDF, рисуется красная аннотация с квадратными окончаниями линии и сохраняется изменённый PDF. lastmod: "2026-03-20" sitemap: @@ -61,3 +61,4 @@ def add_line_annotation(infile, outfile): # Save output PDF file content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md index 325ea0536..1a0dd0ebc 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md @@ -3,7 +3,7 @@ title: Добавить аннотацию полигога linktitle: Добавить аннотацию полигога type: docs weight: 40 -url: /python-net/add-polygon-annotation/ +url: /ru/python-net/add-polygon-annotation/ description: В этом примере привязывается входной PDF, рисуется сплошной полигон на первой странице и сохраняется изменённый документ с аннотацией. lastmod: "2026-03-20" sitemap: @@ -53,3 +53,4 @@ def add_polygon_annotation(infile, outfile): # Save output PDF file content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md index 3e962db01..8cb92c0d1 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md @@ -3,7 +3,7 @@ title: Добавить аннотацию полилиний linktitle: Добавить аннотацию полилиний type: docs weight: 50 -url: /python-net/add-polyline-annotation/ +url: /ru/python-net/add-polyline-annotation/ description: В примере привязывается входной PDF, создаётся сплошная полилиния на первой странице и сохраняется изменённый документ с аннотацией. lastmod: "2026-03-20" sitemap: @@ -53,3 +53,4 @@ def add_polyline_annotation(infile, outfile): # Save output PDF file content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md index 71baf6db2..92007bf25 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md @@ -3,7 +3,7 @@ title: Добавить аннотацию квадрата linktitle: Добавить аннотацию квадрата type: docs weight: 60 -url: /python-net/add-square-annotation/ +url: /ru/python-net/add-square-annotation/ description: В этом примере связывается входной PDF, добавляется заполненная синяя аннотация квадрата на первой странице и сохраняется изменённый документ. lastmod: "2026-03-20" sitemap: @@ -48,3 +48,4 @@ def add_square_annotation(infile, outfile): # Save output PDF file content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md index bc8835577..63ebd2cec 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md @@ -3,7 +3,7 @@ title: Операции с изображениями linktitle: Операции с изображениями type: docs weight: 60 -url: /python-net/image-operations/ +url: /ru/python-net/image-operations/ description: lastmod: "2026-03-20" sitemap: @@ -13,4 +13,4 @@ sitemap: - [Заменить изображения в PDF](/pdf/ru/python-net/replace-image/) - [Удалить изображения из PDF](/pdf/ru/python-net/delete-images/) -- [Удалить все изображения из PDF](/pdf/ru/python-net/delete-all-images/) \ No newline at end of file +- [Удалить все изображения из PDF](/pdf/ru/python-net/delete-all-images/) diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md index 7e847d8de..5c5b6a048 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md @@ -3,7 +3,7 @@ title: Удалить все изображения из PDF linktitle: Удалить все изображения из PDF type: docs weight: 10 -url: /python-net/delete-all-images/ +url: /ru/python-net/delete-all-images/ description: Удалить все изображения из PDF‑документа с помощью Aspose.PDF for Python через Facades API. lastmod: "2026-03-20" sitemap: @@ -43,3 +43,4 @@ def delete_all_image(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md index 6f8f57046..042076161 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md @@ -3,7 +3,7 @@ title: Удалить изображения из PDF linktitle: Удалить изображения из PDF type: docs weight: 20 -url: /python-net/delete-images/ +url: /ru/python-net/delete-images/ description: lastmod: "2026-03-20" sitemap: @@ -43,3 +43,4 @@ def delete_images(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md index 950596469..ad8950bec 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md @@ -3,7 +3,7 @@ title: Заменить изображения в PDF linktitle: Заменить изображения в PDF type: docs weight: 30 -url: /python-net/replace-image/ +url: /ru/python-net/replace-image/ description: В этом примере привязывается входной PDF, заменяется первое изображение на странице 1 новым изображением и сохраняется измененный документ. lastmod: "2026-03-20" sitemap: @@ -41,3 +41,4 @@ def replace_image(infile, image_file, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md index 3249148dc..5cf4de38c 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md @@ -3,7 +3,7 @@ title: Ссылки и навигация linktitle: Ссылки и навигация type: docs weight: 70 -url: /python-net/links-and-navigation/ +url: /ru/python-net/links-and-navigation/ description: lastmod: "2026-03-20" sitemap: @@ -18,3 +18,4 @@ sitemap: - [Добавить ссылку на приложение](/pdf/ru/python-net/add-application-link/) - [Добавить пользовательскую ссылку действия](/pdf/ru/python-net/add-custom-action-link/) - [Извлечение ссылок](/pdf/ru/python-net/extract-links/) + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md index a18e4d01d..d01cd9f44 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md @@ -3,7 +3,7 @@ title: Добавить ссылку на приложение linktitle: Добавить ссылку на приложение type: docs weight: 10 -url: /python-net/add-application-link/ +url: /ru/python-net/add-application-link/ description: В этом примере привязывается входной PDF, добавляется ссылка для запуска приложения на первой странице и сохраняется изменённый документ. lastmod: "2026-03-20" sitemap: @@ -52,3 +52,4 @@ def add_application_link(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md index f115f9aea..10b0c9eb9 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md @@ -3,7 +3,7 @@ title: Добавить пользовательскую ссылку дейст linktitle: Добавить пользовательскую ссылку действия type: docs weight: 20 -url: /python-net/add-custom-action-link/ +url: /ru/python-net/add-custom-action-link/ description: В этом примере привязывается входной PDF, добавляется пользовательская ссылка действия на первой странице и сохраняется изменённый документ. Для простоты используется пустой список действий, но в реальных реализациях могут быть включены фактические действия. lastmod: "2026-03-20" sitemap: @@ -53,3 +53,4 @@ def add_custom_action_link(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md index f2f56df87..36cc99168 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md @@ -3,7 +3,7 @@ title: Добавить JavaScript‑ссылку linktitle: Добавить JavaScript‑ссылку type: docs weight: 30 -url: /python-net/add-javascript-link/ +url: /ru/python-net/add-javascript-link/ description: В этом примере привязывается входной PDF, добавляется JavaScript‑ссылка, которая вызывает предупреждение при щелчке, и сохраняется изменённый документ. lastmod: "2026-03-20" sitemap: @@ -52,3 +52,4 @@ def add_javascript_link(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md index 2ffb10280..3140a312b 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md @@ -3,7 +3,7 @@ title: Добавить локальную ссылку linktitle: Добавить локальную ссылку type: docs weight: 40 -url: /python-net/add-local-link/ +url: /ru/python-net/add-local-link/ description: В этом примере привязывается входной PDF, добавляется локальная ссылка красного цвета на странице 1 и сохраняется изменённый документ. lastmod: "2026-03-20" sitemap: @@ -52,3 +52,4 @@ def add_local_link(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md index d358fd6ca..b2e163d2d 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md @@ -3,7 +3,7 @@ title: Добавить ссылку на PDF‑документ linktitle: Добавить ссылку на PDF‑документ type: docs weight: 50 -url: /python-net/add-pdf-document-link/ +url: /ru/python-net/add-pdf-document-link/ description: В этом примере привязывается входной PDF, добавляется ссылка зелёного цвета на страницу в другом PDF и сохраняется изменённый документ. lastmod: "2026-03-20" sitemap: @@ -53,3 +53,4 @@ def add_pdf_document_link(infile, linked_pdf, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md index c38764f29..9e1085e96 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md @@ -3,7 +3,7 @@ title: Добавить веб‑ссылку linktitle: Добавить веб‑ссылку type: docs weight: 60 -url: /python-net/add-web-link/ +url: /ru/python-net/add-web-link/ description: В этом примере привязывается входной PDF, добавляется синяя аннотация веб‑ссылки на странице 1, указывающая на страницу продукта Aspose Python PDF, и сохраняется изменённый документ. lastmod: "2026-03-20" sitemap: @@ -51,3 +51,4 @@ def add_web_link(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md index 3d3fc6ea6..e525c1132 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md @@ -3,7 +3,7 @@ title: Извлечение ссылок linktitle: Извлечение ссылок type: docs weight: 70 -url: /python-net/extract-links/ +url: /ru/python-net/extract-links/ description: В этом примере привязывается входной PDF, извлекаются все ссылки и выводятся их координаты и URI (если доступны). lastmod: "2026-03-20" sitemap: @@ -59,3 +59,4 @@ def extract_links(infile): if count == 0: print("No links found") ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md index 4c43a6588..2e32c70b2 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md @@ -3,7 +3,7 @@ title: Мультимедиа linktitle: Мультимедиа type: docs weight: 80 -url: /python-net/multimedia/ +url: /ru/python-net/multimedia/ description: lastmod: "2026-03-20" sitemap: @@ -13,3 +13,4 @@ sitemap: - [Добавить аннотацию с фильмом](/pdf/ru/python-net/add-movie-annotation/) - [Добавить звуковую аннотацию](/pdf/ru/python-net/add-sound-annotation/) + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/add-movie-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/add-movie-annotation/_index.md index 0b862da49..39a922436 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/add-movie-annotation/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/add-movie-annotation/_index.md @@ -3,7 +3,7 @@ title: Добавить аннотацию с фильмом linktitle: Добавить аннотацию с фильмом type: docs weight: 10 -url: /python-net/add-movie-annotation/ +url: /ru/python-net/add-movie-annotation/ description: В этом примере привязывается входной PDF, добавляется аннотация с фильмом на странице 1 и сохраняется обновлённый PDF. lastmod: "2026-03-20" sitemap: @@ -44,3 +44,4 @@ def add_movie_annotation(infile, movie_file, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/add-sound-annotation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/add-sound-annotation/_index.md index 567961aa1..e70dd9491 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/add-sound-annotation/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/multimedia/add-sound-annotation/_index.md @@ -3,7 +3,7 @@ title: Добавить звуковую аннотацию linktitle: Добавить звуковую аннотацию type: docs weight: 20 -url: /python-net/add-sound-annotation/ +url: /ru/python-net/add-sound-annotation/ description: В этом примере привязывается входной PDF, добавляется звуковая аннотация на странице 1 и сохраняется изменённый PDF. lastmod: "2026-03-20" sitemap: @@ -45,3 +45,4 @@ def add_sound_annotation(infile, sound_file, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md index 375328f4c..589f347c0 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md @@ -3,7 +3,7 @@ title: Управление штампами linktitle: Управление штампами type: docs weight: 90 -url: /python-net/stamps-management/ +url: /ru/python-net/stamps-management/ description: lastmod: "2026-03-20" sitemap: @@ -21,3 +21,4 @@ sitemap: - [Создать резиновую печать с потоком отображения](/pdf/ru/python-net/create-rubber-stamp-with-appearance-stream/) - [Удалить штампы глобально](/pdf/ru/python-net/delete-stamps-globally/) - [Список штампов](/pdf/ru/python-net/list-stamps/) + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md index 0bb547d38..4d71050f1 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md @@ -3,7 +3,7 @@ title: Добавить штамп linktitle: Добавить штамп type: docs weight: 10 -url: /python-net/add-rubber-stamp/ +url: /ru/python-net/add-rubber-stamp/ description: В этом примере привязывает входной PDF, добавляет зелёный “Approved” штамп на первые четыре страницы и сохраняет изменённый документ. lastmod: "2026-03-20" sitemap: @@ -51,3 +51,4 @@ def add_rubber_stamp(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md index cc4a2da20..802418377 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md @@ -3,7 +3,7 @@ title: Создать резиновый штамп с файлом внешне linktitle: Создать резиновый штамп с файлом внешнего вида type: docs weight: 20 -url: /python-net/create-rubber-stamp-with-appearance-file/ +url: /ru/python-net/create-rubber-stamp-with-appearance-file/ description: В этом примере привязывается входной PDF, создаётся резиновый штамп на странице 1 с использованием файлового изображения в качестве внешнего вида штампа, и сохраняется обновлённый PDF. lastmod: "2026-03-20" sitemap: @@ -51,3 +51,4 @@ def create_rubber_stamp_with_appearance_file(infile, image_file, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md index d60e92670..7bff9a9ac 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md @@ -3,7 +3,7 @@ title: Создать резиновую печать с потоком отоб linktitle: Создать резиновую печать с потоком отображения type: docs weight: 30 -url: /python-net/create-rubber-stamp-with-appearance-stream/ +url: /ru/python-net/create-rubber-stamp-with-appearance-stream/ description: В этом примере загружается PDF, на странице 1 создаётся резиновая печать, использующая файл изображения для её отображения, и сохраняется изменённый документ. ✨ lastmod: "2026-03-20" sitemap: @@ -51,3 +51,4 @@ def create_rubber_stamp_with_appearance_file(infile, image_file, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md index 08392222a..c8c79129c 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md @@ -3,7 +3,7 @@ title: Удалить штамп по ID linktitle: Удалить штамп по ID type: docs weight: 85 -url: /python-net/delete-stamp-by-ids-examples/ +url: /ru/python-net/delete-stamp-by-ids-examples/ description: lastmod: "2026-03-20" sitemap: @@ -67,3 +67,4 @@ def delete_stamp_by_ids_examples(infile, outfile): content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md index 96abde65c..e6ead0b23 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md @@ -3,7 +3,7 @@ title: Переместить штамп по индексу linktitle: Переместить штамп по индексу type: docs weight: 50 -url: /python-net/move-stamp-by-index/ +url: /ru/python-net/move-stamp-by-index/ description: В этом примере создаются два резиновых штампа на странице 2. После этого штамп можно переместить, указав его индекс и новые координаты. lastmod: "2026-03-20" sitemap: @@ -62,3 +62,4 @@ def move_stamp_by_index(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md index bf05e8be6..538f14318 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md @@ -3,7 +3,7 @@ title: Удалить штампы глобально linktitle: Удалить штампы глобально type: docs weight: 60 -url: /python-net/delete-stamps-globally/ +url: /ru/python-net/delete-stamps-globally/ description: Этот пример демонстрирует, как удалить аннотации «резиновый штамп» глобально на всех страницах PDF с использованием Aspose.PDF for Python via the Facades API. Он показывает, как удалять штампы по идентификатору без указания отдельных страниц. lastmod: "2026-03-20" sitemap: @@ -58,3 +58,4 @@ def delete_stamps_globally(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md index f31c177a6..b3d7e3d48 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md @@ -3,7 +3,7 @@ title: Список штампов linktitle: Список штампов type: docs weight: 70 -url: /python-net/list-stamps/ +url: /ru/python-net/list-stamps/ description: Этот пример загружает PDF, извлекает все штампы со страницы 1, выводит их и отображает сообщение, если штампы не найдены. lastmod: "2026-03-20" sitemap: @@ -51,3 +51,4 @@ def list_stamps(infile): if count == 0: print("No stamps found") ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md index 53ba20aa0..9f84d4efa 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md @@ -3,7 +3,7 @@ title: Управление штампом по идентификатору linktitle: Управление штампом по идентификатору type: docs weight: 95 -url: /python-net/manage-stamp-by-id/ +url: /ru/python-net/manage-stamp-by-id/ description: Как манипулировать аннотациями резиновых штампов в PDF по их уникальным ID с использованием Aspose.PDF for Python lastmod: "2026-03-20" sitemap: @@ -69,3 +69,4 @@ def manage_stamp_by_id(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md index 7184443fa..71242d757 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md @@ -3,7 +3,7 @@ title: Переместить штамп по ID linktitle: Переместить штамп по ID type: docs weight: 80 -url: /python-net/move-stamp-by-id-example/ +url: /ru/python-net/move-stamp-by-id-example/ description: В этом примере резиновая печать добавляется на страницу 1, а затем перемещается в новое положение с помощью её ID перед сохранением обновленного документа. lastmod: "2026-03-20" sitemap: @@ -54,3 +54,4 @@ def move_stamp_by_id_example(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md index 500429f6d..ad3c778c5 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md @@ -3,7 +3,7 @@ title: Переместить штамп по индексу linktitle: Переместить штамп по индексу type: docs weight: 90 -url: /python-net/move-stamp-by-index/ +url: /ru/python-net/move-stamp-by-index/ description: Как переместить аннотации резиновых печатей в PDF, используя их индекс на странице с Aspose.PDF for Python lastmod: "2026-03-20" sitemap: @@ -69,3 +69,4 @@ def move_stamp_by_index(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md index b31730ff8..c26bdf5e0 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md @@ -3,7 +3,7 @@ title: Операции с текстом linktitle: Операции с текстом type: docs weight: 100 -url: /python-net/text-operations/ +url: /ru/python-net/text-operations/ description: lastmod: "2026-03-20" sitemap: @@ -16,3 +16,4 @@ sitemap: - [Заменить текст на странице](/pdf/ru/python-net/replace-text-on-page/) - [Заменить текст с использованием state](/pdf/ru/python-net/replace-text-with-state/) - [Заменить текст на странице с помощью state](/pdf/ru/python-net/replace-text-on-page-with-state/) + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md index ac5709a33..3bed78b73 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md @@ -3,7 +3,7 @@ title: Заменить текст на странице с помощью state linktitle: Заменить текст на странице с помощью state type: docs weight: 20 -url: /python-net/replace-text-on-page-with-state/ +url: /ru/python-net/replace-text-on-page-with-state/ description: В этом примере все "software" на странице 1 заменяются на "SOFTWARE PAGE 1", используя красный текст с размером шрифта 12. lastmod: "2026-03-20" sitemap: @@ -52,3 +52,4 @@ def replace_text_on_page_with_state(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md index 2016dec04..592f952ba 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md @@ -3,7 +3,7 @@ title: Заменить текст на странице linktitle: Заменить текст на странице type: docs weight: 10 -url: /python-net/replace-text-on-page/ +url: /ru/python-net/replace-text-on-page/ description: В этом примере "PDF" заменяется на "Page 1 Replaced Text" с использованием указанного размера шрифта. lastmod: "2026-03-20" sitemap: @@ -46,3 +46,4 @@ def replace_text_on_page(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md index 1353c7a68..080d3029a 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md @@ -3,7 +3,7 @@ title: Замена текста с использованием RegEx linktitle: Замена текста с использованием RegEx type: docs weight: 30 -url: /python-net/replace-text-regex/ +url: /ru/python-net/replace-text-regex/ description: В этом примере все четырёхзначные числа в документе заменяются плейсхолдером "[NUMBER]". Это полезно для маскирования конфиденциальных данных, нормализации содержимого или анонимизации документов. lastmod: "2026-03-20" sitemap: @@ -47,3 +47,4 @@ def replace_text_regex(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md index 33df3dba3..54eb9b07d 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md @@ -3,7 +3,7 @@ title: Простая замена текста linktitle: Простая замена текста type: docs weight: 40 -url: /python-net/replace-text-simple/ +url: /ru/python-net/replace-text-simple/ description: В этом примере все вхождения "33" заменяются на "XXXIII " во всём документе. Это демонстрирует простую замену строк без пользовательского форматирования или регулярных выражений. lastmod: "2026-03-20" sitemap: @@ -46,3 +46,4 @@ def replace_text_simple(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md index 00e6d9436..042132005 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md @@ -3,7 +3,7 @@ title: Заменить текст с использованием state linktitle: Заменить текст с использованием state type: docs weight: 50 -url: /python-net/replace-text-with-state/ +url: /ru/python-net/replace-text-with-state/ description: В этом примере все вхождения "software" заменяются на "SOFTWARE" и форматируются синим цветом размером шрифта 14. lastmod: "2026-03-20" sitemap: @@ -52,3 +52,4 @@ def replace_text_with_state(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md index 05ab44a68..373f41497 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md @@ -3,7 +3,7 @@ title: Настройки просмотра linktitle: Настройки просмотра type: docs weight: 110 -url: /python-net/viewer-preferences/ +url: /ru/python-net/viewer-preferences/ description: lastmod: "2026-03-20" sitemap: @@ -14,3 +14,4 @@ sitemap: - [Изменить параметры просмотра PDF](/pdf/ru/python-net/change-viewer-preferences/) - [Получить настройки просмотра PDF](/pdf/ru/python-net/get-viewer-preferences/) + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md index 4f8fab0eb..62c6e370a 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md @@ -3,7 +3,7 @@ title: Изменить параметры просмотра PDF linktitle: Изменить параметры просмотра PDF type: docs weight: 10 -url: /python-net/change-viewer-preferences/ +url: /ru/python-net/change-viewer-preferences/ description: Этот модуль демонстрирует, как настроить параметры просмотра PDF‑документа с помощью Aspose.PDF for Python. lastmod: "2026-03-20" sitemap: @@ -74,3 +74,4 @@ def change_viewer_preferences(infile, outfile): # Save updated document content_editor.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md index aa3a78b81..bb3f96442 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md @@ -3,7 +3,7 @@ title: Получить настройки просмотра PDF linktitle: Получить настройки просмотра PDF type: docs weight: 20 -url: /python-net/get-viewer-preferences/ +url: /ru/python-net/get-viewer-preferences/ description: Как программно считывать и изменять настройки просмотра PDF с использованием Aspose.PDF for Python lastmod: "2026-03-20" sitemap: @@ -44,3 +44,4 @@ def get_viewer_preferences(infile): print("PageModeUseOutlines is enabled") print(f"Current viewer preference: {viewer_preference}") ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/_index.md b/ru/python-net/working-with-facades/pdffileeditor/_index.md index b7edd291b..e975fc0d7 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/_index.md @@ -3,7 +3,7 @@ title: Класс PdfFileEditor linktitle: Класс PdfFileEditor type: docs weight: 10 -url: /python-net/pdffileeditor-class/ +url: /ru/python-net/pdffileeditor-class/ description: Изучите, как редактировать и управлять PDF‑файлами с помощью класса PDFFileEditor на Python с Aspose.PDF. lastmod: "2026-01-05" sitemap: @@ -29,3 +29,4 @@ Abstract: Узнайте, как использовать класс PdfFileEdit - [Объединить или конкатенировать PDF‑файлы](/pdf/ru/python-net/page-merging/) - [Разделить PDF документы](/pdf/ru/python-net/splitting-pdf-documents/) - [Брошюра и N-Up макет](/pdf/ru/python-net/booklet-and-nup-layout/) + diff --git a/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md b/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md index 461be7415..8642e35eb 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md @@ -3,7 +3,7 @@ title: Брошюра и N-Up макет linktitle: Брошюра и N-Up макет type: docs weight: 10 -url: /python-net/booklet-and-nup-layout/ +url: /ru/python-net/booklet-and-nup-layout/ description: Подготовка PDF‑файлов к печати часто требует переорганизации страниц в определённые макеты, такие как брошюры или N-Up сетки. lastmod: "2026-03-05" sitemap: @@ -20,3 +20,4 @@ Abstract: Узнайте, как преобразовать макеты стр - [Создать N-Up PDF документ](/pdf/ru/python-net/create-n-up-pdf-document/) - [Создать PDF‑буклет](/pdf/ru/python-net/create-pdf-booklet/) + diff --git a/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md b/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md index ca9168aba..4d3798cbd 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md @@ -3,7 +3,7 @@ title: Создать N-Up PDF документ linktitle: Создать N-Up PDF документ type: docs weight: 10 -url: /python-net/create-n-up-pdf-document/ +url: /ru/python-net/create-n-up-pdf-document/ description: Узнайте, как создать N-Up PDF документ, безопасно обрабатывая потенциальные ошибки, используя Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -83,3 +83,4 @@ def try_create_nup_pdf_document(infile, outfile): if not nup_maker.try_make_n_up(FileIO(infile), FileIO(outfile, "w"), 2, 2): print("Failed to create N-Up PDF document.") ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md b/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md index 901361dc5..80aaae4f7 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md @@ -3,7 +3,7 @@ title: Создать PDF‑буклет linktitle: Создать PDF‑буклет type: docs weight: 20 -url: /python-net/create-pdf-booklet/ +url: /ru/python-net/create-pdf-booklet/ description: Создать PDF‑буклет из существующего документа с использованием Aspose.PDF for Python lastmod: "2026-03-05" sitemap: @@ -80,3 +80,4 @@ def try_create_pdf_booklet(infile, outfile): if not booklet_maker.try_make_booklet(FileIO(infile), FileIO(outfile, "w")): print("Failed to create booklet.") ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md index 643e1cb93..03425d0a6 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md @@ -3,7 +3,7 @@ title: Разметка страниц и поля linktitle: Разметка страниц и поля type: docs weight: 20 -url: /python-net/page-layout-and-margins/ +url: /ru/python-net/page-layout-and-margins/ description: Управление разметкой страниц PDF является важной частью рабочих процессов обработки документов. Разработчикам часто требуется корректировать поля, изменять размер содержимого страницы или вставлять разрывы страниц, чтобы гарантировать соответствие документов требованиям форматирования или печати. lastmod: "2026-03-05" sitemap: @@ -16,4 +16,4 @@ Abstract: Узнайте, как изменять разметку страни - [Добавить поля к страницам PDF](/pdf/ru/python-net/add-margins-to-pdf-pages/) - [Изменить размер содержимого страниц PDF](/pdf/ru/python-net/resize-pdf-page-contents/) -- [Добавить разрывы страниц в PDF](/pdf/ru/python-net/add-page-breaks-in-pdf/) \ No newline at end of file +- [Добавить разрывы страниц в PDF](/pdf/ru/python-net/add-page-breaks-in-pdf/) diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md index 21b838e89..71b1b6e76 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md @@ -3,7 +3,7 @@ title: Добавить поля к страницам PDF linktitle: Добавить поля к страницам PDF type: docs weight: 10 -url: /python-net/add-margins-to-pdf-pages/ +url: /ru/python-net/add-margins-to-pdf-pages/ description: Добавить пользовательские поля к выбранным страницам PDF с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -50,3 +50,4 @@ def add_margins_to_pdf_pages(infile, outfile): infile, outfile, [1, 3], left_margin, right_margin, top_margin, bottom_margin ) ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md index 07331e7c1..ab1762627 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md @@ -3,7 +3,7 @@ title: Добавить разрывы страниц в PDF linktitle: Добавить разрывы страниц в PDF type: docs weight: 20 -url: /python-net/add-page-breaks-in-pdf/ +url: /ru/python-net/add-page-breaks-in-pdf/ description: Вставьте разрывы страниц в документ PDF с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -46,3 +46,4 @@ def add_page_breaks_in_pdf(infile, outfile): ], ) ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md index 500309836..d8d6536fa 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md @@ -3,7 +3,7 @@ title: Изменить размер содержимого страниц PDF linktitle: Изменить размер содержимого страниц PDF type: docs weight: 30 -url: /python-net/resize-pdf-page-contents/ +url: /ru/python-net/resize-pdf-page-contents/ description: Измените размер содержимого определённых страниц PDF с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -49,3 +49,4 @@ def resize_pdf_page_contents(infile, outfile): ): raise Exception("Failed to resize PDF page contents.") ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-managment/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-managment/_index.md index f34d70cf9..a7c0a3728 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/page-managment/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/page-managment/_index.md @@ -3,7 +3,7 @@ title: Управление страницами linktitle: Управление страницами type: docs weight: 30 -url: /python-net/page-management/ +url: /ru/python-net/page-management/ description: Программное управление страницами PDF позволяет разработчикам изменять документы без ручного редактирования. lastmod: "2026-03-05" sitemap: @@ -24,3 +24,4 @@ Abstract: Узнайте, как выполнять операции на уро - [Удалить страницы из PDF](/pdf/ru/python-net/delete-pages-from-pdf/) - [Вставить страницы в PDF](/pdf/ru/python-net/insert-pages-into-pdf/) - [Добавить страницы в PDF](/pdf/ru/python-net/append-pages-to-pdf/) + diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md index a16ca3f6a..96725bd9a 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md @@ -3,7 +3,7 @@ title: Добавить страницы в PDF linktitle: Добавить страницы в PDF type: docs weight: 10 -url: /python-net/append-pages-to-pdf/ +url: /ru/python-net/append-pages-to-pdf/ description: Добавьте страницы из одного PDF‑документа в другой с использованием Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -41,3 +41,4 @@ def append_pages_to_pdf(infile, sample_file, outfile): # Append pages from the specified PDF document to the end of the source PDF document pdf_editor.append(infile, [sample_file], 1, 2, outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md index 6623f72e6..136bdc6d4 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md @@ -3,7 +3,7 @@ title: Удалить страницы из PDF linktitle: Удалить страницы из PDF type: docs weight: 20 -url: /python-net/delete-pages-from-pdf/ +url: /ru/python-net/delete-pages-from-pdf/ description: Удалить выбранные страницы из PDF-документа с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -44,4 +44,4 @@ Abstract: Узнайте, как удалить выбранные страни # Delete the specified pages from the PDF document pdf_editor.delete(infile, pages_to_delete, outfile) -``` \ No newline at end of file +``` diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md index f117c1d14..7fa47a1b9 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md @@ -3,7 +3,7 @@ title: Извлечение страниц из PDF linktitle: Извлечение страниц из PDF type: docs weight: 30 -url: /python-net/extract-pages-from-pdf/ +url: /ru/python-net/extract-pages-from-pdf/ description: Извлечь выбранные страницы из PDF‑документа с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -44,3 +44,4 @@ def extract_pages_from_pdf(infile, outfile): # Extract the specified pages from the PDF document and save to a new PDF document pdf_editor.extract(infile, pages_to_extract, outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md index e96a593db..d885cbd00 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md @@ -3,7 +3,7 @@ title: Вставить страницы в PDF linktitle: Вставить страницы в PDF type: docs weight: 40 -url: /python-net/insert-pages-into-pdf/ +url: /ru/python-net/insert-pages-into-pdf/ description: Вставьте страницы из одного PDF в другой с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -43,3 +43,4 @@ def insert_pages_into_pdf(infile, sample_file, outfile): pdf_editor.insert(infile, insert_page_number, sample_file, [1, 2], outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-merging/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-merging/_index.md index 213e776f3..d07604860 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/page-merging/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/page-merging/_index.md @@ -3,7 +3,7 @@ title: Объединить PDF-файлы linktitle: Объединить PDF-файлы type: docs weight: 40 -url: /python-net/page-merging/ +url: /ru/python-net/page-merging/ description: Объединение PDF‑документов является распространенной задачей в автоматизированных рабочих процессах, генерации отчетов и управлении документами. lastmod: "2026-03-05" sitemap: @@ -20,4 +20,4 @@ Abstract: Узнайте, как программно объединять PDF - [Попытка объединить несколько PDF‑файлов](/pdf/ru/python-net/try-concatenate-pdf-files/) - [Объединить большое количество PDF‑файлов](/pdf/ru/python-net/concatenate-large-number-files/) - [Объединить PDF-файлов с оптимизацией](/pdf/ru/python-net/concatenate-pdf-files-with-optimization/) -- [Объединить PDF‑формы с уникальным суффиксом](/pdf/ru/python-net/concatenate-pdf-forms/) \ No newline at end of file +- [Объединить PDF‑формы с уникальным суффиксом](/pdf/ru/python-net/concatenate-pdf-forms/) diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md index aca4d0573..25f117f5d 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md @@ -3,7 +3,7 @@ title: Объединить большое количество PDF‑файло linktitle: Объединить большое количество PDF‑файлов type: docs weight: 10 -url: /python-net/concatenate-large-number-files/ +url: /ru/python-net/concatenate-large-number-files/ description: Эффективно объединять большое количество PDF‑файлов с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -36,3 +36,4 @@ def concatenate_large_number_files(files_to_merge, output_file): pdf_editor.use_disk_buffer = True # Enable disk buffering for large files pdf_editor.concatenate(files_to_merge, output_file) ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md index 3ae81b349..4bb1f4548 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md @@ -3,7 +3,7 @@ title: Объединение PDF-файлов с оптимизацией linktitle: Объединение PDF-файлов с оптимизацией type: docs weight: 30 -url: /python-net/concatenate-pdf-files-with-optimization/ +url: /ru/python-net/concatenate-pdf-files-with-optimization/ description: Объедините несколько PDF-файлов в один оптимизированный PDF с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -36,3 +36,4 @@ def concatenate_pdf_files_with_optimization(files_to_merge, output_file): pdf_editor.optimize_size = True # Enable optimization for smaller output file size pdf_editor.concatenate(files_to_merge, output_file) ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md index d23f3e764..5d6f8fdfb 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md @@ -3,7 +3,7 @@ title: Объединить несколько PDF-файлов linktitle: Объединить несколько PDF-файлов type: docs weight: 20 -url: /python-net/concatenate-pdf-files/ +url: /ru/python-net/concatenate-pdf-files/ description: Объедините несколько PDF-файлов в один документ с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -35,3 +35,4 @@ def concatenate_pdf_files(files_to_merge, output_file): pdf_editor = pdf_facades.PdfFileEditor() pdf_editor.concatenate(files_to_merge, output_file) ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md index b5fbc0fb3..5108038d8 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md @@ -3,7 +3,7 @@ title: Объединить PDF‑формы с уникальным суффи linktitle: Объединить PDF‑формы с уникальным суффиксом type: docs weight: 50 -url: /python-net/concatenate-pdf-forms/ +url: /ru/python-net/concatenate-pdf-forms/ description: Объедините несколько PDF‑форм, используя Aspose.PDF for Python, обеспечивая уникальность имён полей формы. lastmod: "2026-03-05" sitemap: @@ -38,3 +38,4 @@ def concatenate_pdf_forms(files_to_merge, output_file): ) pdf_editor.concatenate(files_to_merge, output_file) ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md index ce5801179..b427855d9 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md @@ -3,7 +3,7 @@ title: Объединить два PDF-файла linktitle: Объединить два PDF-файла type: docs weight: 60 -url: /python-net/concatenate-two-files/ +url: /ru/python-net/concatenate-two-files/ description: Объедините два PDF-файла в один документ с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -35,3 +35,4 @@ def concatenate_two_files(files_to_merge, output_file): pdf_editor = pdf_facades.PdfFileEditor() pdf_editor.concatenate(files_to_merge[0], files_to_merge[1], output_file) ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md index 65991dd03..313ecd038 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md @@ -3,7 +3,7 @@ title: Объединить PDF-файлы linktitle: Объединить PDF-файлы type: docs weight: 70 -url: /python-net/try-concatenate-pdf-files/ +url: /ru/python-net/try-concatenate-pdf-files/ description: Объедините несколько PDF-файлов с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -36,3 +36,4 @@ def try_concatenate_pdf_files(files_to_merge, output_file): if not pdf_editor.try_concatenate(files_to_merge, output_file): print("Concatenation failed for the provided files.") ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md b/ru/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md index de077c590..d5e876fa2 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md @@ -3,7 +3,7 @@ title: Попробуйте объединить два PDF-файла linktitle: Попробуйте объединить два PDF-файла type: docs weight: 90 -url: /python-net/try-concatenate-two-files/ +url: /ru/python-net/try-concatenate-two-files/ description: Объедините два PDF-файла с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -38,3 +38,4 @@ def try_concatenate_two_files(files_to_merge, output_file): ): print("Concatenation failed for the provided files.") ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md b/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md index ec6f199d3..30d94b073 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md @@ -3,7 +3,7 @@ title: Разделить PDF документы linktitle: Разделить PDF документы type: docs weight: 50 -url: /python-net/splitting-pdf-documents/ +url: /ru/python-net/splitting-pdf-documents/ description: Разделение PDF является типичной потребностью для управления документами, отчетности и автоматизации процессов. lastmod: "2026-03-05" sitemap: @@ -21,3 +21,4 @@ Abstract: Узнайте, как программно разбивать PDF‑ - [Разделить PDF с начала](/pdf/ru/python-net/split-pdf-from-beginning/) - [Разделить PDF до конца](/pdf/ru/python-net/split-pdf-to-end/) - [Разделить PDF на отдельные страницы](/pdf/ru/python-net/split-pdf-into-single-pages/) + diff --git a/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md b/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md index 444a83e59..692772f7a 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md @@ -3,7 +3,7 @@ title: Разделить PDF с начала linktitle: Разделить PDF с начала type: docs weight: 10 -url: /python-net/split-pdf-from-beginning/ +url: /ru/python-net/split-pdf-from-beginning/ description: Разделите документ PDF с начала, используя Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -36,3 +36,4 @@ def split_pdf_from_beginning(input_pdf_path, output_pdf_path): pdf_file_editor = pdf_facades.PdfFileEditor() pdf_file_editor.split_from_first(input_pdf_path, 3, output_pdf_path) ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md b/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md index 687ccabce..6cc6be1d7 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md @@ -3,7 +3,7 @@ title: Разделить PDF на отдельные страницы linktitle: Разделить PDF на отдельные страницы type: docs weight: 30 -url: /python-net/split-pdf-into-single-pages/ +url: /ru/python-net/split-pdf-into-single-pages/ description: Разделить документ PDF на отдельные одностраничные PDF с помощью Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -36,3 +36,4 @@ def split_pdf_into_single_pages(input_pdf_path, output_pdf_path): pdf_file_editor = pdf_facades.PdfFileEditor() pdf_file_editor.split_to_pages(input_pdf_path, output_pdf_path) ``` + diff --git a/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md b/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md index 3b6c0f22f..81e294fc3 100644 --- a/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md +++ b/ru/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md @@ -3,7 +3,7 @@ title: Разделить PDF до конца linktitle: Разделить PDF до конца type: docs weight: 40 -url: /python-net/split-pdf-to-end/ +url: /ru/python-net/split-pdf-to-end/ description: Разделить документ PDF, начиная с указанной страницы и до последней страницы, используя Aspose.PDF for Python. lastmod: "2026-03-05" sitemap: @@ -36,3 +36,4 @@ def split_pdf_to_end(input_pdf_path, output_pdf_path): pdf_file_editor = pdf_facades.PdfFileEditor() pdf_file_editor.split_to_end(input_pdf_path, 2, output_pdf_path) ``` + diff --git a/ru/python-net/working-with-facades/pdffileinfo/_index.md b/ru/python-net/working-with-facades/pdffileinfo/_index.md index 3ab240cab..5215ba94e 100644 --- a/ru/python-net/working-with-facades/pdffileinfo/_index.md +++ b/ru/python-net/working-with-facades/pdffileinfo/_index.md @@ -3,7 +3,7 @@ title: Класс PdfFileInfo linktitle: Класс PdfFileInfo type: docs weight: 110 -url: /python-net/pdffileinfo-class/ +url: /ru/python-net/pdffileinfo-class/ description: Узнайте, как использовать класс PdfFileInfo в Aspose.PDF for Python via .NET для проверки метаданных PDF, свойств документа, привилегий, деталей версии и информации о страницах. lastmod: "2026-03-19" draft: false @@ -24,3 +24,4 @@ Abstract: В этом разделе объясняется, как исполь - [Управляйте метаданными PDF с помощью PdfFileInfo](/pdf/ru/python-net/pdf-metadata/) - [Проверьте свойства документа с помощью PdfFileInfo](/pdf/ru/python-net/document-properties/) - [Получите информацию о страницах с помощью PdfFileInfo](/pdf/ru/python-net/page-information/) + diff --git a/ru/python-net/working-with-facades/pdffileinfo/document-properties/_index.md b/ru/python-net/working-with-facades/pdffileinfo/document-properties/_index.md index 8c5997a6c..621bb923c 100644 --- a/ru/python-net/working-with-facades/pdffileinfo/document-properties/_index.md +++ b/ru/python-net/working-with-facades/pdffileinfo/document-properties/_index.md @@ -3,7 +3,7 @@ title: Свойства документа linktitle: Свойства документа type: docs weight: 10 -url: /python-net/document-properties/ +url: /ru/python-net/document-properties/ description: Узнайте, как программно получать метаданные PDF с помощью Aspose.PDF for Python. Это руководство охватывает получение версии PDF и проверку привилегий документа, включая разрешения на печать, копирование, изменение и заполнение форм. lastmod: "2026-03-05" draft: false @@ -16,4 +16,4 @@ Abstract: Понимание метаданных PDF имеет решающе --- - [Получить версию PDF](/pdf/ru/python-net/get-pdf-version/) -- [Получить привилегии документа](/pdf/ru/python-net/get-document-privileges/) \ No newline at end of file +- [Получить привилегии документа](/pdf/ru/python-net/get-document-privileges/) diff --git a/ru/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md b/ru/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md index ecae0ecb5..9d04481ce 100644 --- a/ru/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md +++ b/ru/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md @@ -3,7 +3,7 @@ title: Получить привилегии документа linktitle: Получить привилегии документа type: docs weight: 10 -url: /python-net/get-document-privileges/ +url: /ru/python-net/get-document-privileges/ description: Узнайте, как программно проверять привилегии PDF‑документа с помощью Aspose.PDF for Python. Этот учебный материал демонстрирует, как использовать класс PdfFileInfo для чтения настроек безопасности документа, таких как печать, копирование или изменение разрешений. lastmod: "2026-03-05" draft: false @@ -58,3 +58,4 @@ def get_document_privileges(input_file_name): print(f" Can Screen Readers: {privileges.allow_screen_readers}") print(f" Can Assembly: {privileges.allow_assembly}") ``` + diff --git a/ru/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md b/ru/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md index 356b3fa1b..9ee765d81 100644 --- a/ru/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md +++ b/ru/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md @@ -3,7 +3,7 @@ title: Получить версию PDF linktitle: Получить версию PDF type: docs weight: 20 -url: /python-net/get-pdf-version/ +url: /ru/python-net/get-pdf-version/ description: Узнайте, как программно определить версию PDF‑документа с помощью Aspose.PDF for Python. Этот учебник демонстрирует, как использовать класс PdfFileInfo для проверки версии PDF файла. lastmod: "2026-03-05" draft: false @@ -42,3 +42,4 @@ def get_pdf_version(input_file_name): version = pdf_metadata.get_pdf_version() print(f"\nPDF Version: {version}") ``` + diff --git a/ru/python-net/working-with-facades/pdffileinfo/page-information/_index.md b/ru/python-net/working-with-facades/pdffileinfo/page-information/_index.md index 17f005ed4..364bacaba 100644 --- a/ru/python-net/working-with-facades/pdffileinfo/page-information/_index.md +++ b/ru/python-net/working-with-facades/pdffileinfo/page-information/_index.md @@ -3,7 +3,7 @@ title: Информация о странице linktitle: Информация о странице type: docs weight: 20 -url: /python-net/page-information/ +url: /ru/python-net/page-information/ description: В этой статье объясняется, как извлечь ключевые сведения о макете и позиционировании из PDF‑страниц с помощью Aspose.PDF for Python. lastmod: "2026-03-05" draft: false @@ -17,3 +17,4 @@ Abstract: PDF‑страницы могут различаться по разм - [Получить информацию о странице](/pdf/ru/python-net/get-page-info/) - [Получить смещение страницы](/pdf/ru/python-net/get-page-offset/) + diff --git a/ru/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md b/ru/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md index 036fce700..593fd844a 100644 --- a/ru/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md +++ b/ru/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md @@ -3,7 +3,7 @@ title: Получить информацию о странице linktitle: Получить информацию о странице type: docs weight: 10 -url: /python-net/get-page-info/ +url: /ru/python-net/get-page-info/ description: Узнайте, как программно получать информацию о странице в PDF с помощью Aspose.PDF for Python. В этом руководстве показывается, как получить ширину, высоту, поворот и смещения конкретной страницы в PDF‑документе. lastmod: "2026-03-05" draft: false @@ -49,3 +49,4 @@ def get_page_information(infile): print(f"Page Height: {page_height}") print(f"Page Rotation: {page_rotation}") ``` + diff --git a/ru/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md b/ru/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md index 6dc73a73f..432a1f304 100644 --- a/ru/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md +++ b/ru/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md @@ -3,7 +3,7 @@ title: Получить смещение страницы linktitle: Получить смещение страницы type: docs weight: 20 -url: /python-net/get-page-offset/ +url: /ru/python-net/get-page-offset/ description: Этот пример демонстрирует, как использовать PdfFileInfo для получения смещений по осям X и Y конкретной страницы и преобразования их в дюймы для точного анализа макета и позиционирования. lastmod: "2026-03-05" draft: false @@ -44,3 +44,4 @@ def get_page_offsets(infile): print(f"Page X Offset: {page_x_offset} inches") print(f"Page Y Offset: {page_y_offset} inches") ``` + diff --git a/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md index 4a69ac947..48c3fa6d4 100644 --- a/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md +++ b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md @@ -3,7 +3,7 @@ title: Метаданные PDF linktitle: Метаданные PDF type: docs weight: 30 -url: /python-net/pdf-metadata/ +url: /ru/python-net/pdf-metadata/ description: В этой статье объясняется, как получить доступ к метаданным, изменять их и сохранять в PDF‑документах с помощью Aspose.PDF for Python. lastmod: "2026-03-05" draft: false @@ -19,3 +19,4 @@ Abstract: Метаданные PDF содержат информацию о до - [Установить метаданные PDF](/pdf/ru/python-net/set-pdf-metadata/) - [Очистить метаданные PDF](/pdf/ru/python-net/clear-pdf-metadata/) - [Сохранить метаданные с помощью XMP](/pdf/ru/python-net/save-metadata-with-xmp/) + diff --git a/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md index 9ed61ff90..200783fe8 100644 --- a/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md +++ b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md @@ -3,7 +3,7 @@ title: Очистить метаданные PDF linktitle: Очистить метаданные PDF type: docs weight: 10 -url: /python-net/clear-pdf-metadata/ +url: /ru/python-net/clear-pdf-metadata/ description: Удалите все метаданные из PDF‑документа с помощью Aspose.PDF for Python via .NET. lastmod: "2026-03-05" draft: false @@ -45,3 +45,4 @@ def clear_pdf_metadata(infile, outfile): # Save updated metadata pdf_info.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md index 13f555dcb..0981bad33 100644 --- a/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md +++ b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md @@ -3,7 +3,7 @@ title: Получить метаданные PDF linktitle: Получить метаданные PDF type: docs weight: 20 -url: /python-net/get-pdf-metadata/ +url: /ru/python-net/get-pdf-metadata/ description: Извлекать и отображать метаданные из PDF‑документов с помощью Aspose.PDF for Python. lastmod: "2026-03-05" draft: false @@ -57,3 +57,4 @@ def get_pdf_metadata(infile): reviewer = pdf_info.get_meta_info("Reviewer") print(f"Reviewer: {reviewer if reviewer else 'No Reviewer metadata found.'}") ``` + diff --git a/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md index be28f4b4f..72bd00f13 100644 --- a/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md +++ b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md @@ -3,7 +3,7 @@ title: Сохранить метаданные с помощью XMP linktitle: Сохранить метаданные с помощью XMP type: docs weight: 30 -url: /python-net/save-metadata-with-xmp/ +url: /ru/python-net/save-metadata-with-xmp/ description: Сохранить метаданные PDF, используя XMP с Aspose.PDF for Python via .NET lastmod: "2026-03-05" draft: false @@ -48,3 +48,4 @@ def save_info_with_xmp(infile, outfile): # Save updated metadata pdf_info.save_new_info_with_xmp(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md index 03f702dac..1464d4d30 100644 --- a/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md +++ b/ru/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md @@ -3,7 +3,7 @@ title: Установить метаданные PDF linktitle: Установить метаданные PDF type: docs weight: 50 -url: /python-net/set-pdf-metadata/ +url: /ru/python-net/set-pdf-metadata/ description: Изменять и сохранять метаданные в PDF‑документах с помощью Aspose.PDF for Python via .NET. lastmod: "2026-03-05" draft: false @@ -54,3 +54,4 @@ def set_pdf_metadata(infile, outfile): # Save updated metadata pdf_info.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdffilesecurity/_index.md b/ru/python-net/working-with-facades/pdffilesecurity/_index.md index 524a8bc91..ae20579a3 100644 --- a/ru/python-net/working-with-facades/pdffilesecurity/_index.md +++ b/ru/python-net/working-with-facades/pdffilesecurity/_index.md @@ -3,7 +3,7 @@ title: Класс PdfFileSecurity linktitle: Класс PdfFileSecurity type: docs weight: 125 -url: /python-net/pdffilesecurity-class/ +url: /ru/python-net/pdffilesecurity-class/ description: Узнайте, как использовать класс PdfFileSecurity в Aspose.PDF for Python via .NET для шифрования и дешифрования PDF, изменения паролей и управления привилегиями документа. lastmod: "2026-03-18" sitemap: @@ -24,3 +24,4 @@ Abstract: В этом разделе объясняется, как исполь - [Расшифровка PDF-файлов с помощью PdfFileSecurity](/pdf/ru/python-net/decrypt-pdf-file/) - [Изменение паролей PDF с помощью PdfFileSecurity](/pdf/ru/python-net/change-password/) - [Установка привилегий PDF с помощью PdfFileSecurity](/pdf/ru/python-net/set-privileges/) + diff --git a/ru/python-net/working-with-facades/pdffilesecurity/change-password/_index.md b/ru/python-net/working-with-facades/pdffilesecurity/change-password/_index.md index ad9b56de2..001b85a01 100644 --- a/ru/python-net/working-with-facades/pdffilesecurity/change-password/_index.md +++ b/ru/python-net/working-with-facades/pdffilesecurity/change-password/_index.md @@ -3,7 +3,7 @@ title: Изменить пароль PDF‑файла linktitle: Изменить пароль PDF‑файла type: docs weight: 10 -url: /python-net/change-password/ +url: /ru/python-net/change-password/ description: Изменить пользовательский и владелецский пароли защищённого PDF‑документа с помощью Aspose.PDF for Python via .NET. lastmod: "2026-03-18" sitemap: @@ -153,3 +153,4 @@ def try_change_password_without_exception(infile, outfile): else: print("Password change failed. Check owner password or document security.") ``` + diff --git a/ru/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md b/ru/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md index f2c5f5de7..4fc6c01c2 100644 --- a/ru/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md +++ b/ru/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md @@ -3,7 +3,7 @@ title: Расшифровать PDF-файл linktitle: Расшифровать PDF-файл type: docs weight: 20 -url: /python-net/decrypt-pdf-file/ +url: /ru/python-net/decrypt-pdf-file/ description: Это руководство объясняет, как удалить ограничения, такие как печать, копирование и редактирование, чтобы получить полный доступ к вашему PDF‑документу. lastmod: "2026-03-18" sitemap: @@ -90,3 +90,4 @@ def try_decrypt_pdf_without_exception(infile, outfile): else: print("Decryption failed. Check password or document security.") ``` + diff --git a/ru/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md b/ru/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md index 077dfd075..63215fd92 100644 --- a/ru/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md +++ b/ru/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md @@ -3,7 +3,7 @@ title: Зашифровать PDF-файл linktitle: Зашифровать PDF-файл type: docs weight: 30 -url: /python-net/encrypt-pdf-file/ +url: /ru/python-net/encrypt-pdf-file/ description: Зашифровать PDF-документ и настроить разрешения, чтобы контролировать, что пользователи могут делать с файлом. lastmod: "2026-03-18" sitemap: @@ -150,3 +150,4 @@ def encrypt_pdf_with_encryption_algorithm(infile, outfile): # Save encrypted PDF file_security.save(outfile) ``` + diff --git a/ru/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md b/ru/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md index 49991fe26..bd2860ffe 100644 --- a/ru/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md +++ b/ru/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md @@ -3,7 +3,7 @@ title: Установить привилегии для существующег linktitle: Установить привилегии для существующего PDF‑файла type: docs weight: 40 -url: /python-net/set-privileges/ +url: /ru/python-net/set-privileges/ description: Установите и управляйте привилегиями PDF‑документа, чтобы контролировать действия пользователей, такие как печать, копирование и редактирование. lastmod: "2026-03-18" sitemap: @@ -146,3 +146,4 @@ def try_set_pdf_privileges_without_exception(infile, outfile): else: print("Setting privileges failed. Check passwords or document state.") ``` + diff --git a/ru/python-net/working-with-facades/pdffilesignature/_index.md b/ru/python-net/working-with-facades/pdffilesignature/_index.md index c17a3c94c..ec0a6b6b6 100644 --- a/ru/python-net/working-with-facades/pdffilesignature/_index.md +++ b/ru/python-net/working-with-facades/pdffilesignature/_index.md @@ -3,7 +3,7 @@ title: Класс PdfFileSignature linktitle: Класс PdfFileSignature type: docs weight: 60 -url: /python-net/pdffilesignature-class/ +url: /ru/python-net/pdffilesignature-class/ description: Узнайте, как добавлять, проверять и удалять цифровые подписи из PDF‑документов в Python, используя класс PdfFileSignature с Aspose.PDF. lastmod: "2026-01-05" sitemap: @@ -81,3 +81,4 @@ def create_custom_signature_appearance(): appearance.show_reason = True return appearance ``` + diff --git a/ru/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md b/ru/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md index 1a2b38d36..5ab7fb837 100644 --- a/ru/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md +++ b/ru/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md @@ -3,7 +3,7 @@ title: Сертификация PDF linktitle: Сертификация PDF type: docs weight: 30 -url: /python-net/pdf-certification/ +url: /ru/python-net/pdf-certification/ description: Узнайте, как сертифицировать PDF‑документы в Python с помощью PdfFileSignature и DocMDPSignature с различными разрешениями на изменение документа. lastmod: "2026-04-02" sitemap: @@ -84,3 +84,4 @@ def apply_document_level_certification(infile, outfile, certificate_path): finally: pdf_signature.close() ``` + diff --git a/ru/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md b/ru/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md index 409fc684a..d59f33db3 100644 --- a/ru/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md +++ b/ru/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md @@ -3,7 +3,7 @@ title: Подписать PDF документы linktitle: Подписать PDF документы type: docs weight: 10 -url: /python-net/pdf-signing/ +url: /ru/python-net/pdf-signing/ description: Узнайте, как подписывать PDF документы в Python с помощью PdfFileSignature, используя цифровые подписи, основанные на сертификате, именованные и видимые. lastmod: "2026-04-14" sitemap: @@ -181,3 +181,4 @@ def apply_visible_signature(infile, outfile, certificate_path): finally: pdf_signature.close() ``` + diff --git a/ru/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md b/ru/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md index 39fc4c5a0..19ccddd52 100644 --- a/ru/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md +++ b/ru/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md @@ -3,7 +3,7 @@ title: Ревизия и разрешения linktitle: Ревизия и разрешения type: docs weight: 40 -url: /python-net/revision-permissions/ +url: /ru/python-net/revision-permissions/ description: Узнайте, как проверять ревизии подписей, ревизии документов и разрешения на сертификацию в PDF‑файлах с помощью PdfFileSignature в Python. lastmod: "2026-04-02" sitemap: @@ -80,3 +80,4 @@ def get_access_permissions(infile): pdf_signature.close() ``` + diff --git a/ru/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md b/ru/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md index 1b59683ea..18e2f38f2 100644 --- a/ru/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md +++ b/ru/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md @@ -3,7 +3,7 @@ title: Извлечение подписи linktitle: Извлечение подписи type: docs weight: 50 -url: /python-net/signature-extraction/ +url: /ru/python-net/signature-extraction/ description: Узнайте, как извлечь изображение подписи и сертификат подписи из подписанного PDF, используя PdfFileSignature в Python. lastmod: "2026-04-02" sitemap: @@ -61,3 +61,4 @@ def extract_signature_certificate(infile, outfile): pdf_signature.close() ``` + diff --git a/ru/python-net/working-with-facades/pdffilesignature/signature-information/_index.md b/ru/python-net/working-with-facades/pdffilesignature/signature-information/_index.md index 24e517ca3..18bbb4224 100644 --- a/ru/python-net/working-with-facades/pdffilesignature/signature-information/_index.md +++ b/ru/python-net/working-with-facades/pdffilesignature/signature-information/_index.md @@ -3,7 +3,7 @@ title: Информация о подписи linktitle: Информация о подписи type: docs weight: 60 -url: /python-net/signature-information/ +url: /ru/python-net/signature-information/ description: Узнайте, как читать имена подписей, данные подписанта, метки времени и метаданные подписи из подписанных PDF‑файлов с помощью PdfFileSignature в Python. lastmod: "2026-04-02" sitemap: @@ -110,3 +110,4 @@ def get_signature_reason_and_location(infile): pdf_signature.close() ``` + diff --git a/ru/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md b/ru/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md index 9fa16be78..d6235e404 100644 --- a/ru/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md +++ b/ru/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md @@ -3,7 +3,7 @@ title: Проверки целостности подписи linktitle: Проверки целостности подписи type: docs weight: 70 -url: /python-net/signature-integrity-checks/ +url: /ru/python-net/signature-integrity-checks/ description: Узнайте, как проверить, охватывает ли подпись PDF весь документ, и подтвердить целостность подписанного документа с помощью PdfFileSignature в Python. lastmod: "2026-04-02" sitemap: @@ -61,3 +61,4 @@ def validate_document_integrity(infile): pdf_signature.close() ``` + diff --git a/ru/python-net/working-with-facades/pdffilesignature/signature-management/_index.md b/ru/python-net/working-with-facades/pdffilesignature/signature-management/_index.md index 493236ccc..52e37b806 100644 --- a/ru/python-net/working-with-facades/pdffilesignature/signature-management/_index.md +++ b/ru/python-net/working-with-facades/pdffilesignature/signature-management/_index.md @@ -3,7 +3,7 @@ title: Управление подписями linktitle: Управление подписями type: docs weight: 80 -url: /python-net/signature-management/ +url: /ru/python-net/signature-management/ description: Узнайте, как удалять цифровые подписи из PDF‑документов и при необходимости очищать поля подписи, используя PdfFileSignature в Python. lastmod: "2026-04-02" sitemap: @@ -60,3 +60,4 @@ def remove_signature_with_field_cleanup(infile, outfile): finally: pdf_signature.close() ``` + diff --git a/ru/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md b/ru/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md index 929246d33..59661dbc0 100644 --- a/ru/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md +++ b/ru/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md @@ -3,7 +3,7 @@ title: Проверка подписи linktitle: Проверка подписи type: docs weight: 90 -url: /python-net/signature-verification/ +url: /ru/python-net/signature-verification/ description: Узнайте, как проверять цифровые подписи и проверять, содержит ли PDF подписи, используя PdfFileSignature в Python. lastmod: "2026-04-02" sitemap: @@ -59,3 +59,4 @@ def check_if_pdf_contains_signatures(infile): finally: pdf_signature.close() ``` + diff --git a/ru/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md b/ru/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md index 63db6e156..304ed2f73 100644 --- a/ru/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md +++ b/ru/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md @@ -3,7 +3,7 @@ title: Управление правами использования linktitle: Управление правами использования type: docs weight: 100 -url: /python-net/usage-rights-management/ +url: /ru/python-net/usage-rights-management/ description: Узнайте, как обнаруживать и удалять права использования из PDF‑документов с помощью PdfFileSignature в Python. lastmod: "2026-04-02" sitemap: @@ -61,3 +61,4 @@ def remove_usage_rights(infile, outfile): finally: pdf_signature.close() ``` + diff --git a/ru/python-net/working-with-facades/pdffilestamp/_index.md b/ru/python-net/working-with-facades/pdffilestamp/_index.md index 7fe19c3e0..52915dc12 100644 --- a/ru/python-net/working-with-facades/pdffilestamp/_index.md +++ b/ru/python-net/working-with-facades/pdffilestamp/_index.md @@ -3,7 +3,7 @@ title: Класс PdfFileStamp linktitle: Класс PdfFileStamp type: docs weight: 155 -url: /python-net/pdffilestamp-class/ +url: /ru/python-net/pdffilestamp-class/ description: Узнайте, как использовать класс PdfFileStamp в Aspose.PDF for Python via .NET для добавления заголовков, колонтитулов, номеров страниц и штампов в PDF‑документы. lastmod: "2026-04-14" sitemap: @@ -24,3 +24,4 @@ Abstract: В этом разделе объясняется, как исполь - [Добавьте верхние колонтитулы к страницам PDF с помощью PdfFileStamp](/pdf/ru/python-net/add-header/) - [Добавьте номера страниц в документы PDF с помощью PdfFileStamp](/pdf/ru/python-net/page-number/) - [Добавьте штампы на страницы PDF с помощью PdfFileStamp](/pdf/ru/python-net/add-stamp/) + diff --git a/ru/python-net/working-with-facades/pdffilestamp/add-footer/_index.md b/ru/python-net/working-with-facades/pdffilestamp/add-footer/_index.md index ae693db36..9971a6b49 100644 --- a/ru/python-net/working-with-facades/pdffilestamp/add-footer/_index.md +++ b/ru/python-net/working-with-facades/pdffilestamp/add-footer/_index.md @@ -3,7 +3,7 @@ title: Добавить нижний колонтитул в PDF linktitle: Добавить нижний колонтитул в PDF type: docs weight: 10 -url: /python-net/add-footer/ +url: /ru/python-net/add-footer/ description: Узнайте, как добавить текстовые и графические нижние колонтитулы на страницы PDF с помощью PdfFileStamp в Python. lastmod: "2026-04-13" TechArticle: true @@ -83,3 +83,4 @@ def add_footer_with_margins(infile: str, outfile: str) -> None: finally: pdf_stamper.close() ``` + diff --git a/ru/python-net/working-with-facades/pdffilestamp/add-header/_index.md b/ru/python-net/working-with-facades/pdffilestamp/add-header/_index.md index 4f831c26c..ab75067ec 100644 --- a/ru/python-net/working-with-facades/pdffilestamp/add-header/_index.md +++ b/ru/python-net/working-with-facades/pdffilestamp/add-header/_index.md @@ -3,7 +3,7 @@ title: Добавить заголовок в PDF linktitle: Добавить заголовок в PDF type: docs weight: 20 -url: /python-net/add-header/ +url: /ru/python-net/add-header/ description: Узнайте, как добавить текстовые и графические заголовки на страницы PDF, используя PdfFileStamp в Python. lastmod: "2026-04-13" TechArticle: true @@ -96,3 +96,4 @@ def add_header_with_margins(infile: str, outfile: str) -> None: finally: pdf_stamper.close() ``` + diff --git a/ru/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md b/ru/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md index aac9aae31..9b6377ea1 100644 --- a/ru/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md +++ b/ru/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md @@ -3,7 +3,7 @@ title: Добавить номер страницы в PDF linktitle: Добавить номер страницы в PDF type: docs weight: 30 -url: /python-net/page-number/ +url: /ru/python-net/page-number/ description: Узнайте, как добавить номера страниц в PDF-документы с помощью PdfFileStamp в Python. lastmod: "2026-04-13" TechArticle: true @@ -121,3 +121,4 @@ def add_page_numbers_with_roman_style(infile: str, outfile: str) -> None: finally: pdf_stamper.close() ``` + diff --git a/ru/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md b/ru/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md index f4d44f2e2..85d3f6ee3 100644 --- a/ru/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md +++ b/ru/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md @@ -3,7 +3,7 @@ title: Добавить штамп в PDF linktitle: Добавить штамп в PDF type: docs weight: 40 -url: /python-net/add-stamp/ +url: /ru/python-net/add-stamp/ description: Узнайте, как добавить штамп на страницы PDF, используя PdfFileStamp в Python. lastmod: "2026-04-13" TechArticle: true @@ -45,3 +45,4 @@ def add_stamp_to_pdf(infile: str, image_file: str, outfile: str) -> None: finally: pdf_stamper.close() ``` + diff --git a/ru/python-net/working-with-facades/stamp/_index.md b/ru/python-net/working-with-facades/stamp/_index.md index b8c26fd77..d66a1d27c 100644 --- a/ru/python-net/working-with-facades/stamp/_index.md +++ b/ru/python-net/working-with-facades/stamp/_index.md @@ -3,7 +3,7 @@ title: Класс Stamp linktitle: Класс Stamp type: docs weight: 150 -url: /python-net/stamp-class/ +url: /ru/python-net/stamp-class/ description: Узнайте, как работать с классом Stamp, чтобы добавлять штампы изображений, PDF и текстовые штампы в PDF‑документы на Python. lastmod: "2026-04-13" sitemap: @@ -227,3 +227,4 @@ def add_background_image_stamp(infile: str, image_file: str, outfile: str) -> No - [Работа с фасадами PDF в Python](/pdf/ru/python-net/working-with-facades/) - [Добавьте заголовки, нижние колонтитулы и штампы с помощью PdfFileStamp](/pdf/ru/python-net/pdffilestamp-class/) - [Добавьте штамп страницы в PDF‑файлы с помощью Python](/pdf/ru/python-net/add-stamp/) + From 96b4f3da50df2e7f2f45ea0a4f498ebd55f1b5f7 Mon Sep 17 00:00:00 2001 From: Andriy Andruhovski Date: Thu, 14 May 2026 14:27:57 +0300 Subject: [PATCH 06/13] =?UTF-8?q?Enhance=20Russian=20step-style=20skill=20?= =?UTF-8?q?by=20adding=20a=20new=20conversion=20rule=20for=20"=D0=9F=D1=80?= =?UTF-8?q?=D0=B8=D0=B2=D1=8F=D0=B7=D0=B0=D1=82=D1=8C"=20and=20refining=20?= =?UTF-8?q?style=20constraints=20for=20clarity=20and=20consistency=20in=20?= =?UTF-8?q?documentation.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .codex/skills/ru-step-style/SKILL.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.codex/skills/ru-step-style/SKILL.md b/.codex/skills/ru-step-style/SKILL.md index fb504bafb..0418634ea 100644 --- a/.codex/skills/ru-step-style/SKILL.md +++ b/.codex/skills/ru-step-style/SKILL.md @@ -47,16 +47,17 @@ Convert infinitives to polite imperative: | Загрузить | Загрузите | | Извлечь | Извлеките | | Преобразовать | Преобразуйте | +| Привязать | Привяжите | | Удалить | Удалите | | Обновить | Обновите | | Вызвать | Вызовите | ## Style constraints -- Preserve code identifiers, API names, file paths, and Markdown links. -- Do not translate code. -- Do not rewrite headings unless they are step headings. +- Priority order: preserve technical integrity first, then preserve Markdown structure, then normalize step wording; if normalization conflicts with Markdown structure, keep Markdown structure, and if either conflicts with technical integrity, keep technical integrity. +- Preserve code identifiers, API names, file paths, and Markdown links; do not translate code. - Keep Markdown structure unchanged. +- Rewrite headings only when they explicitly number steps or describe procedural actions. - Prefer short direct instructions. - Use `вы`-style polite imperative, not informal imperative. @@ -65,5 +66,5 @@ Convert infinitives to polite imperative: When asked to fix files: 1. Scan Russian Markdown files. 2. Find numbered steps, bullet steps, and headings that describe procedural actions. -3. Rewrite only style issues. +3. Rewrite only issues related to polite imperative verbs and these style constraints. 4. Report changed files and examples of replacements. \ No newline at end of file From fea6fd5b3cc2eabd56a2ff54fac24a5dd39f64bc Mon Sep 17 00:00:00 2001 From: Andriy Andruhovski Date: Thu, 14 May 2026 14:50:43 +0300 Subject: [PATCH 07/13] =?UTF-8?q?Refactor=20section=20headings=20for=20con?= =?UTF-8?q?sistency=20and=20clarity=20across=20multiple=20documents=20in?= =?UTF-8?q?=20the=20Python=20.NET=20library.=20Changed=20"=D0=9A=D0=BE?= =?UTF-8?q?=D0=BD=D0=B2=D0=B5=D1=80=D1=82=D0=B8=D1=80=D0=BE=D0=B2=D0=B0?= =?UTF-8?q?=D1=82=D1=8C"=20to=20"=D0=9F=D1=80=D0=B5=D0=BE=D0=B1=D1=80?= =?UTF-8?q?=D0=B0=D0=B7=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5"=20in=20variou?= =?UTF-8?q?s=20sections=20related=20to=20PDF=20conversions,=20including=20?= =?UTF-8?q?EPUB,=20LaTeX/TeX,=20text,=20XPS,=20MD,=20and=20MobiXML.=20Upda?= =?UTF-8?q?ted=20similar=20headings=20in=20PDF/A,=20PDF/E,=20PDF/X,=20Powe?= =?UTF-8?q?rPoint,=20Word,=20and=20PDFX=20to=20maintain=20uniformity.=20Ad?= =?UTF-8?q?justed=20other=20headings=20related=20to=20PDF=20security,=20fo?= =?UTF-8?q?rm=20fields,=20and=20stamping=20to=20follow=20the=20same=20patt?= =?UTF-8?q?ern.=20This=20enhances=20readability=20and=20provides=20a=20coh?= =?UTF-8?q?esive=20structure=20throughout=20the=20documentation.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../create-tagged-pdf-documents/_index.md | 6 +-- .../_index.md | 2 +- .../interactive-annotations/_index.md | 30 ++++++------ .../markup-annotations/_index.md | 48 +++++++++---------- .../media-annotations/_index.md | 40 ++++++++-------- .../security-annotations/_index.md | 14 +++--- .../shape-annotations/_index.md | 48 +++++++++---------- .../text-based-annotations/_index.md | 46 +++++++++--------- .../watermark-annotations/_index.md | 18 +++---- .../import-export-annotations/_index.md | 6 +-- .../artifacts/add-backgrounds/_index.md | 8 ++-- .../artifacts/add-bates-numbering/_index.md | 4 +- .../artifacts/add-watermarks/_index.md | 6 +-- .../artifacts-header-footer/_index.md | 8 ++-- .../attachments/extract-attachment/_index.md | 4 +- .../attachments/portfolio/_index.md | 2 +- .../_index.md | 2 +- .../actions/_index.md | 4 +- .../add-and-delete-bookmark/_index.md | 8 ++-- .../get-update-expand-bookmark/_index.md | 4 +- .../links/create-links/_index.md | 2 +- .../links/extract-links/_index.md | 4 +- .../pdf-file-metadata/_index.md | 8 ++-- .../digitally-sign-pdf-file/_index.md | 4 +- .../extract-signature-info/_index.md | 4 +- .../set-privileges/_index.md | 4 +- .../_index.md | 4 +- .../working-with-documents/_index.md | 2 +- .../create-pdf-document/_index.md | 2 +- .../formatting-pdf-document/_index.md | 16 +++---- .../manipulate-pdf-document/_index.md | 14 +++--- .../merge-pdf/_index.md | 16 +++---- .../optimize-pdf-document/_index.md | 8 ++-- .../split-pdf/_index.md | 16 +++---- .../acroforms/create-form/_index.md | 16 +++---- .../acroforms/extract-form/_index.md | 4 +- .../import-export-form-data/_index.md | 18 +++---- .../acroforms/modifying-form/_index.md | 8 ++-- .../acroforms/posting-form/_index.md | 4 +- .../acroforms/remove-form/_index.md | 4 +- .../working-with-forms/xfa-forms/_index.md | 2 +- .../working-with-graphs/arc/_index.md | 4 +- .../working-with-graphs/circle/_index.md | 4 +- .../working-with-graphs/curve/_index.md | 4 +- .../working-with-graphs/ellipse/_index.md | 6 +-- .../working-with-graphs/line/_index.md | 2 +- .../working-with-graphs/rectangle/_index.md | 8 ++-- .../add-image-to-existing-pdf-file/_index.md | 8 ++-- .../delete-images-from-pdf-file/_index.md | 4 +- .../_index.md | 4 +- .../_index.md | 2 +- .../working-with-layers/_index.md | 6 +-- .../working-with-operators/_index.md | 2 +- .../working-with-pages/add-pages/_index.md | 8 ++-- .../change-page-size/_index.md | 4 +- .../working-with-pages/crop-pages/_index.md | 2 +- .../working-with-pages/delete-pages/_index.md | 4 +- .../get-and-set-page-properties/_index.md | 6 +-- .../working-with-pages/move-pages/_index.md | 2 +- .../working-with-pages/rotate-pages/_index.md | 2 +- .../_index.md | 6 +-- .../_index.md | 4 +- .../_index.md | 6 +-- .../_index.md | 2 +- .../remove-tables-from-existing-pdf/_index.md | 4 +- .../add-text-to-pdf-file/_index.md | 32 ++++++------- .../add-tooltip-to-text/_index.md | 4 +- .../replace-text-an-a-pdf/_index.md | 32 ++++++------- .../rotate-text-inside-pdf/_index.md | 2 +- .../basic-operations/opening/_index.md | 6 +-- .../basic-operations/protect/_index.md | 2 +- .../basic-operations/saving/_index.md | 6 +-- .../basic-operations/split-pdf/_index.md | 2 +- .../converting/convert-html-to-pdf/_index.md | 10 ++-- .../convert-images-format-to-pdf/_index.md | 20 ++++---- .../convert-other-files-to-pdf/_index.md | 20 ++++---- .../converting/convert-pdf-to-excel/_index.md | 16 +++---- .../converting/convert-pdf-to-html/_index.md | 16 +++---- .../convert-pdf-to-images-format/_index.md | 22 ++++----- .../convert-pdf-to-other-files/_index.md | 12 ++--- .../converting/convert-pdf-to-pdfx/_index.md | 16 +++---- .../convert-pdf-to-powerpoint/_index.md | 6 +-- .../converting/convert-pdf-to-word/_index.md | 6 +-- .../converting/convert-pdfx-to-pdf/_index.md | 2 +- ru/python-net/overview/key-features/_index.md | 2 +- ru/python-net/whatsnew/_index.md | 14 +++--- .../form/button-fields-and-images/_index.md | 4 +- .../add-field-script/_index.md | 2 +- .../pdffilesecurity/change-password/_index.md | 4 +- .../pdffilesecurity/set-privileges/_index.md | 4 +- .../pdffilesignature/pdf-signing/_index.md | 6 +-- .../revision-permissions/_index.md | 6 +-- .../signature-extraction/_index.md | 4 +- .../signature-information/_index.md | 8 ++-- .../signature-management/_index.md | 4 +- .../usage-rights-management/_index.md | 2 +- .../pdffilestamp/add-footer/_index.md | 4 +- .../pdffilestamp/add-header/_index.md | 4 +- .../pdffilestamp/add-page-number/_index.md | 6 +-- .../pdffilestamp/add-stamp/_index.md | 2 +- .../working-with-facades/stamp/_index.md | 10 ++-- 101 files changed, 445 insertions(+), 445 deletions(-) diff --git a/ru/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/_index.md b/ru/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/_index.md index 509cb48c0..d96e06234 100644 --- a/ru/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/_index.md +++ b/ru/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/_index.md @@ -272,7 +272,7 @@ def adjust_position(outfile): document.save(outfile) ``` -## Преобразовать PDF в PDF/UA-1 с автоматическим тегированием +## Преобразование PDF в PDF/UA-1 с автоматическим тегированием Этот фрагмент кода объясняет, как преобразовать стандартный PDF в файл, соответствующий требованиям PDF/UA-1 (Универсальная доступность), используя Aspose.PDF for Python via .NET. @@ -317,7 +317,7 @@ def convert_to_pdf_ua_with_automatic_tagging(infile, outfile, logfile): document.save(outfile) ``` -## Создать Tagged PDF с доступным полем подписи FormField +## Создание Tagged PDF с доступным полем подписи FormField 1. Создайте новый PDF‑документ. 1. Доступ к тегированному содержимому. @@ -364,7 +364,7 @@ def create_pdf_with_tagged_form_field(outfile): document.save(outfile) ``` -## Создать Tagged PDF со страницей оглавления (TOC) +## Создание Tagged PDF со страницей оглавления (TOC) В этом примере показано, как создать тегированный PDF‑документ со структурированной страницей оглавления (TOC) с использованием Aspose.PDF for Python via .NET. diff --git a/ru/python-net/advanced-operations/accessibility-tagged-pdf/working-with-table-in-tagged-pdfs/_index.md b/ru/python-net/advanced-operations/accessibility-tagged-pdf/working-with-table-in-tagged-pdfs/_index.md index 4ab93b5f4..44321e8c6 100644 --- a/ru/python-net/advanced-operations/accessibility-tagged-pdf/working-with-table-in-tagged-pdfs/_index.md +++ b/ru/python-net/advanced-operations/accessibility-tagged-pdf/working-with-table-in-tagged-pdfs/_index.md @@ -11,7 +11,7 @@ sitemap: priority: 0.7 --- -## Создать таблицу в Tagged PDF +## Создание таблицы в Tagged PDF Следуя приведённым выше шагам, вы можете создать семантически насыщенную, доступную таблицу в PDF‑документе, используя Aspose.PDF for Python. Полученный файл соответствует стандартам соответствия PDF/UA-1, обеспечивая совместимость со скрин‑ридерами и вспомогательными технологиями. Это идеально подходит для случаев использования, связанных с нормативным соответствием, аудитом доступности и публикацией инклюзивного контента. diff --git a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/interactive-annotations/_index.md b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/interactive-annotations/_index.md index d02d21209..fc66d3b36 100644 --- a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/interactive-annotations/_index.md +++ b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/interactive-annotations/_index.md @@ -26,7 +26,7 @@ Abstract: В этой статье объясняется, как работат ## Аннотация ссылки -### Добавить аннотацию ссылки +### Добавление аннотацию ссылки Этот пример ищет фрагмент текста на первой странице `"file"` и размещает кликабельную аннотацию ссылки над соответствующей областью текста. Когда пользователь нажимает на аннотацию, PDF открывает указанный веб‑адрес. @@ -42,7 +42,7 @@ document.pages[1].accept(text_fragment_absorber) phone_number_fragment = text_fragment_absorber.text_fragments[1] ``` -#### Создать аннотацию ссылки +#### Создание аннотацию ссылки Создать `LinkAnnotation` используя прямоугольник найденного фрагмента текста и назначая для него действие URI. @@ -53,7 +53,7 @@ link_annotation = ap.annotations.LinkAnnotation( link_annotation.action = ap.annotations.GoToURIAction("https://www.aspose.com") ``` -#### Добавить аннотацию и сохранить PDF +#### Добавление аннотацию и сохранить PDF Добавьте аннотацию на страницу и сохраните обновлённый файл. @@ -81,7 +81,7 @@ def link_add(infile, outfile): document.save(outfile) ``` -### Получить аннотацию ссылки +### Получение аннотацию ссылки Чтобы просмотреть существующие интерактивные ссылки, отфильтруйте коллекцию аннотаций на первой странице и оставьте только элементы, тип которых `LINK`. Затем пример выводит прямоугольник для каждой соответствующей аннотации. @@ -120,7 +120,7 @@ def link_get(infile, outfile): print(link_annotation.rect) ``` -### Удалить аннотацию ссылки +### Удаление аннотацию ссылки Этот рабочий процесс удаляет все аннотации ссылок с первой страницы и сохраняет очищенный PDF в новый файл. @@ -135,14 +135,14 @@ link_annotations = [ ] ``` -#### Удалить каждую аннотацию ссылки +#### Удаление каждую аннотацию ссылки ```python for link_annotation in link_annotations: document.pages[1].annotations.delete(link_annotation) ``` -#### Сохранить обновлённый документ +#### Сохранение обновлённого документа ```python document.save(outfile) @@ -167,7 +167,7 @@ def link_delete(infile, outfile): ## Виджет-аннотация -### Добавить кнопку навигации +### Добавление кнопку навигации Кнопки навигации полезны в многостраничных PDF, когда вы хотите, чтобы читатели перемещались между страницами без использования интерфейса просмотрщика. Этот пример добавляет `Previous Page` и `Next Page` кнопки к каждой странице. @@ -191,7 +191,7 @@ document = ap.Document(infile) document.pages.add() ``` -#### Создать кнопки на каждой странице +#### Создание кнопки на каждой странице Для каждой страницы создайте `ButtonField`, установить его текст и цвета, назначить предопределённое действие навигации и добавить его в форму. @@ -208,7 +208,7 @@ for page in document.pages: document.form.add(button) ``` -#### Сохранить результат +#### Сохранение результат ```python document.save(outfile) @@ -240,18 +240,18 @@ def navigation_buttons_add(infile, outfile): document.save(outfile) ``` -### Добавить кнопку печати +### Добавление кнопку печати Этот пример создает новый одностраничный PDF и размещает кнопку печати возле верхней части страницы. Нажатие кнопки вызывает предопределённое действие печати в совместимом просмотрщике PDF. -#### Создать новый PDF и добавить страницу +#### Создание нового PDF и добавление страницы ```python document = ap.Document() page = document.pages.add() ``` -#### Создать и настроить кнопку +#### Создание и настроить кнопку Определите прямоугольник кнопки, создайте `ButtonField`, установите его подпись и прикрепите действие печати. @@ -268,7 +268,7 @@ print_button.actions.on_release_mouse_btn = ap.annotations.NamedAction( ) ``` -#### Установить стили границы и фона +#### Установка стили границы и фона Пример определяет сплошную рамку и применяет пользовательские цвета, чтобы сделать кнопку видимой в документе. @@ -282,7 +282,7 @@ print_button.characteristics.border = ap.Color.blue.to_rgb() print_button.characteristics.background = ap.Color.light_blue.to_rgb() ``` -#### Добавить кнопку и сохранить PDF +#### Добавление кнопку и сохранить PDF ```python document.form.add(print_button) diff --git a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/markup-annotations/_index.md b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/markup-annotations/_index.md index 931b0d3db..a7e323230 100644 --- a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/markup-annotations/_index.md +++ b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/markup-annotations/_index.md @@ -24,17 +24,17 @@ Abstract: Эта статья объясняет, как создавать, п ## Текстовые аннотации -### Добавить текстовые аннотации +### Добавление текстовых аннотаций В этом примере создаётся текстовая аннотация на первой странице и связывается с всплывающим окном. Текстовые аннотации полезны для комментариев в стиле стикеров в процессах рецензирования. -#### Открыть исходный PDF +#### Открытие исходного PDF ```python document = ap.Document(infile) ``` -#### Создать и настроить текстовую аннотацию +#### Создание и настроить текстовую аннотацию Определите прямоугольник аннотации и задайте его заголовок, тему, содержимое, флаги отображения, цвет и значок. @@ -53,7 +53,7 @@ text_annotation.color = ap.Color.blue text_annotation.icon = ap.annotations.TextIcon.HELP ``` -#### Создать всплывающую аннотацию +#### Создание всплывающую аннотацию Создайте всплывающее окно и подключите его к текстовой аннотации. @@ -67,7 +67,7 @@ popup.open = True text_annotation.popup = popup ``` -#### Добавить аннотацию и сохранить PDF +#### Добавление аннотацию и сохранить PDF ```python document.pages[1].annotations.add(text_annotation, consider_rotation=False) @@ -105,11 +105,11 @@ def text_annotation_add(infile, outfile): document.save(outfile) ``` -### Получить текстовые аннотации +### Получение текстовые аннотации Чтобы проверить существующие текстовые аннотации, отфильтруйте коллекцию аннотаций на первой странице и оставьте только элементы, тип которых является `TEXT`. -#### Открыть документ и собрать текстовые аннотации +#### Открытие документ и собрать текстовые аннотации ```python document = ap.Document(infile) @@ -142,7 +142,7 @@ def text_annotation_get(infile, outfile): print(annotation.rect) ``` -### Удалить текстовые аннотации +### Удаление текстовые аннотации Этот рабочий процесс удаляет все текстовые аннотации с первой страницы и сохраняет изменённый PDF. @@ -157,7 +157,7 @@ text_annotations = [ ] ``` -#### Удалить аннотации и сохранить файл +#### Удаление аннотации и сохранить файл ```python for annotation in text_annotations: @@ -185,18 +185,18 @@ def text_annotation_delete(infile, outfile): ## Каретные аннотации -### Добавить аннотации каретки +### Добавление аннотации каретки Caret annotations используются для обозначения точек вставки в сценариях обзора. В этом примере добавляется caret annotation с прикреплённым всплывающим примечанием. -#### Открыть документ и получить целевую страницу +#### Открытие документ и получить целевую страницу ```python document = ap.Document(infile) page = document.pages[1] ``` -#### Создать и настроить аннотацию caret +#### Создание и настроить аннотацию caret ```python caret_annotation = ap.annotations.CaretAnnotation( @@ -241,7 +241,7 @@ def caret_annotations_add(infile, outfile): document.save(outfile) ``` -### Получить аннотации каретки +### Получение аннотации каретки Чтобы просмотреть аннотации caret, пройдитесь по аннотациям страницы и отфильтруйте по `CARET` тип аннотации. @@ -272,7 +272,7 @@ def caret_annotations_get(infile, outfile): print(annot.rect) ``` -### Удалить аннотации каретки +### Удаление аннотации каретки Этот рабочий процесс сначала собирает аннотации caret, удаляет их по одной, а затем сохраняет обновлённый файл. @@ -289,7 +289,7 @@ caret_annotations = [ ] ``` -#### Удалить аннотации и сохранить документ +#### Удаление аннотации и сохранить документ ```python for annot in caret_annotations: @@ -317,20 +317,20 @@ def caret_annotations_delete(infile, outfile): document.save(outfile) ``` -## Заменить аннотации +## Замена аннотации -### Добавить замену аннотаций +### Добавление замену аннотаций Replace annotations комбинируют аннотацию caret и сгруппированную аннотацию strikeout. Этот шаблон отмечает текст, который следует заменить, и связывает заметку о замене с зачеркиваемым содержимым. -#### Открыть документ и получить страницу +#### Открытие документ и получить страницу ```python document = ap.Document(infile) page = document.pages[1] ``` -#### Создать аннотацию caret для заменяемого текста +#### Создание аннотацию caret для заменяемого текста ```python caret_annotation = ap.annotations.CaretAnnotation( @@ -345,7 +345,7 @@ caret_annotation.popup = ap.annotations.PopupAnnotation( ) ``` -#### Создать группированную аннотацию зачеркивания +#### Создание группированную аннотацию зачеркивания Определите область зачеркивания, назначьте квадропункты и свяжите её с аннотацией каретки через `in_reply_to` и `reply_type`. @@ -365,7 +365,7 @@ strikeout_annotation.in_reply_to = caret_annotation strikeout_annotation.reply_type = ap.annotations.ReplyType.GROUP ``` -#### Добавить обе аннотации и сохранить PDF +#### Добавление обе аннотации и сохранить PDF ```python page.annotations.append(caret_annotation) @@ -412,7 +412,7 @@ def replace_annotations_add(infile, outfile): document.save(outfile) ``` -### Получить замену аннотаций +### Получение замену аннотаций Чтобы определить заменяющие аннотации, найдите аннотации-зачёркивания, сгруппированные как ответы на другую аннотацию. Пример приводит каждую аннотацию-зачёркивание перед проверкой её полей отношений. @@ -453,7 +453,7 @@ def replace_annotations_get(infile, outfile): print(f"Replace annotation rect: {sa.rect}") ``` -### Удалить замену аннотаций +### Удаление замену аннотаций Этот рабочий процесс собирает аннотации зачёркивания, используемые для замены разметки, удаляет их со страницы и сохраняет результирующий PDF. @@ -470,7 +470,7 @@ replace_annotations = [ ] ``` -#### Удалить аннотации и сохранить документ +#### Удаление аннотации и сохранить документ ```python for annot in replace_annotations: diff --git a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md index 697b8ff12..5a5f2ee8e 100644 --- a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md +++ b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md @@ -24,11 +24,11 @@ Abstract: В этой статье объясняется, как создава - добавлять и удалять аннотации rich media - просмотреть существующие мультимедийные аннотации -## Добавить звуковые аннотации +## Добавление звуковые аннотации Этот пример добавляет звуковую аннотацию на первую страницу существующего PDF и связывает её с WAV‑файлом, хранящимся в директории ввода. -### Открыть PDF и определить медиафайл +### Открытие PDF и определить медиафайл ```python media_dir = path.dirname(infile) @@ -39,7 +39,7 @@ page = document.pages[1] media_file = path.join(media_dir, "file_example_WAV_1MG.wav") ``` -### Создать и настроить звуковую аннотацию +### Создание и настроить звуковую аннотацию Установите прямоугольник аннотации, цвет, заголовок и тему. Затем добавьте всплывающую аннотацию, чтобы предоставить дополнительные детали при выборе аннотации. @@ -60,7 +60,7 @@ sound_annotation.popup = ann.PopupAnnotation( ) ``` -### Добавить аннотацию и сохранить PDF +### Добавление аннотацию и сохранить PDF ```python page.annotations.append(sound_annotation) @@ -97,11 +97,11 @@ def sound_annotation_add(infile, outfile): document.save(outfile) ``` -## Добавить 3D‑аннотации +## Добавление 3D‑аннотации Этот рабочий процесс создаёт новый PDF и встраивает 3D‑модель из файла U3D. Он также определяет предустановленные виды и настройки визуализации для 3D‑контента. -### Создать PDF‑документ и 3D‑контент +### Создание PDF‑документ и 3D‑контент ```python model_file = infile @@ -150,14 +150,14 @@ front_matrix = ap.Matrix3D( ) ``` -### Добавить именованные представления к изображению +### Добавление именованные представления к изображению ```python pdf3d_artwork.view_array.add(ann.PDF3DView(document, top_matrix, 0.188563, "Top")) pdf3d_artwork.view_array.add(ann.PDF3DView(document, front_matrix, 0.188563, "Left")) ``` -### Создать аннотацию и сохранить документ +### Создание аннотацию и сохранить документ ```python page = document.pages.add() @@ -242,11 +242,11 @@ def annotation_3d_add(infile, outfile): document.save(outfile) ``` -## Добавить аннотации экрана +## Добавление аннотации экрана Экранные аннотации позволяют прикреплять воспроизводимый медиа‑контент к странице PDF. В этом примере создаётся новый PDF и добавляется экранная аннотация на основе файла SWF. -### Создать PDF и страницу +### Создание PDF и страницу ```python media_file = infile @@ -255,7 +255,7 @@ document = ap.Document() page = document.pages.add() ``` -### Создать аннотацию экрана +### Создание аннотацию экрана ```python screen_annotation = ann.ScreenAnnotation( @@ -265,7 +265,7 @@ screen_annotation = ann.ScreenAnnotation( ) ``` -### Добавить аннотацию и сохранить PDF +### Добавление аннотацию и сохранить PDF ```python page.annotations.append(screen_annotation) @@ -293,7 +293,7 @@ def screen_annotation_with_media_add(infile, outfile): ## Аннотации Rich Media -### Добавить аннотации Rich Media +### Добавление аннотации Rich Media Аннотации Rich media могут внедрять продвинутый интерактивный контент, такой как видеоплееры с постерами, скинами и пользовательскими настройками воспроизведения. @@ -315,7 +315,7 @@ poster_name = "file_example_MP4_480_1_5MG_poster.jpg" skin_name = "SkinOverAllNoFullNoCaption.swf" ``` -### Создать аннотацию rich media +### Создание аннотацию rich media ```python rich_media_annotation = ann.RichMediaAnnotation( @@ -342,7 +342,7 @@ with open(video_path, "rb") as video_file: rich_media_annotation.set_content(video_name, video_file) ``` -### Установить поведение воспроизведения и сохранить PDF +### Установка поведение воспроизведения и сохранить PDF Аннотация настроена как видеоконтент и активируется при щелчке пользователя. @@ -402,11 +402,11 @@ def rich_media_annotations_add(infile, outfile): document.save(outfile) ``` -### Удалить аннотации Rich Media +### Удаление аннотации Rich Media Этот рабочий процесс удаляет все аннотации rich media с первой страницы существующего PDF. -### Открыть PDF и собрать аннотации с богатыми медиа +### Открытие PDF и собрать аннотации с богатыми медиа ```python document = ap.Document(infile) @@ -419,7 +419,7 @@ to_delete = [ ] ``` -### Удалить аннотации и сохранить документ +### Удаление аннотации и сохранить документ ```python for annotation in to_delete: @@ -447,11 +447,11 @@ def rich_media_annotations_delete(infile, outfile): document.save(outfile) ``` -## Получить Multimedia_annotations +## Получение Multimedia_annotations Чтобы проверить мультимедийный контент, уже сохранённый в PDF, отфильтруйте коллекцию аннотаций по типам аннотаций screen, sound и rich media. -### Открыть документ и определить целевые типы аннотаций +### Открытие документ и определить целевые типы аннотаций ```python document = ap.Document(infile) diff --git a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/security-annotations/_index.md b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/security-annotations/_index.md index 1049934c8..89dbbbf04 100644 --- a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/security-annotations/_index.md +++ b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/security-annotations/_index.md @@ -26,7 +26,7 @@ Abstract: В этой статье объясняется, как работат Этот рабочий процесс ищет совпадающий текст в документе и размещает аннотации редактирования над каждым совпадением. Он пока не удаляет содержимое; он только помечает текст для последующего редактирования. -### Открыть PDF и выполнить поиск целевого текста +### Открытие PDF и выполнить поиск целевого текста Создать `TextFragmentAbsorber` для поискового термина и включите обычные параметры текстового поиска перед сканированием всех страниц. @@ -39,7 +39,7 @@ text_fragment_absorber.text_search_options = text_search_options document.pages.accept(text_fragment_absorber) ``` -### Создать аннотации редактирования для каждого совпадения +### Создание аннотации редактирования для каждого совпадения Для каждого найденного фрагмента текста создать `RedactionAnnotation` используя прямоугольник фрагмента и настраивая его визуальный вид. @@ -59,7 +59,7 @@ for text_fragment in text_fragment_absorber.text_fragments: page.annotations.add(redaction_annotation, True) ``` -### Сохранить помеченный PDF +### Сохранение помеченный PDF ```python document.save(outfile) @@ -118,7 +118,7 @@ for redaction_annotation in redaction_annotations: cast(ap.annotations.RedactionAnnotation, redaction_annotation).redact() ``` -### Сохранить отредактированный PDF +### Сохранение отредактированный PDF ```python document.save(outfile) @@ -146,7 +146,7 @@ def apply_redaction(infile, outfile): Этот пример удаляет обнаруженную область изображения вместо текста. Он сканирует страницу в поисках размещения изображений, выбирает один прямоугольник размещения и добавляет аннотацию редактирования над этой областью. -### Открыть PDF и определить расположение изображений +### Открытие PDF и определить расположение изображений Использовать `ImagePlacementAbsorber` найти позиции изображений на первой странице. @@ -158,7 +158,7 @@ page = document.pages[1] page.accept(image_placement_absorber) ``` -### Создать аннотацию редактирования для выбранной области изображения +### Создание аннотацию редактирования для выбранной области изображения В образце используется третье обнаруженное размещение изображения и применяется тот же стиль редактирования, используемый в примере маркировки текста. @@ -173,7 +173,7 @@ redaction_annotation.text_alignment = ap.HorizontalAlignment.CENTER redaction_annotation.repeat = True ``` -### Добавить аннотацию и сохранить PDF +### Добавление аннотацию и сохранить PDF ```python page.annotations.add(redaction_annotation, True) diff --git a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md index 6b0218cd5..ff8c54c1b 100644 --- a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md +++ b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md @@ -26,17 +26,17 @@ Abstract: В этой статье объясняется, как создава ## Аннотация линий -### Добавить аннотацию линий +### Добавление аннотацию линий Этот пример добавляет аннотацию линий на первую страницу и настраивает стили стрелок, толщину линии и всплывающее окно. -#### Открыть исходный PDF +#### Открытие исходного PDF ```python document = ap.Document(infile) ``` -#### Создать и настроить аннотацию линий +#### Создание и настроить аннотацию линий ```python line_annotation = ap.annotations.LineAnnotation( @@ -95,7 +95,7 @@ def line_annotation_add(infile, outfile): document.save(outfile) ``` -### Получить аннотацию линии +### Получение аннотацию линии Чтобы проверить аннотации линий, отфильтруйте коллекцию аннотаций на первой странице и приведите каждый результат к `LineAnnotation` чтобы вы могли прочитать его начальные и конечные точки. @@ -140,7 +140,7 @@ def line_annotations_get(infile, outfile): ) ``` -### Удалить аннотацию линий +### Удаление аннотацию линий Этот процесс удаляет все аннотации линий с первой страницы и сохраняет обновлённый PDF. @@ -157,7 +157,7 @@ line_annotations = [ ] ``` -#### Удалить аннотации и сохранить PDF +#### Удаление аннотации и сохранить PDF ```python for annotation in line_annotations: @@ -187,11 +187,11 @@ def line_annotations_delete(infile, outfile): ## Аннотации квадратов и кругов -### Добавить аннотацию квадрата +### Добавление аннотацию квадрата Аннотации квадрата полезны для обозначения прямоугольных областей в документе. В этом примере создаётся аннотация квадрата с настройками границы, заливки и прозрачности. -#### Открыть PDF и создать аннотацию квадрата +#### Открытие PDF и создать аннотацию квадрата ```python document = ap.Document(infile) @@ -206,7 +206,7 @@ square_annotation.interior_color = ap.Color.blue_violet square_annotation.opacity = 0.25 ``` -#### Добавить аннотацию и сохранить PDF +#### Добавление аннотацию и сохранить PDF ```python document.pages[1].annotations.append(square_annotation) @@ -232,7 +232,7 @@ def square_annotation_add(infile, outfile): document.save(outfile) ``` -### Получить аннотацию квадрата +### Получение аннотацию квадрата Чтобы просмотреть аннотации квадрата, отфильтруйте аннотации первой страницы по `SQUARE` введите и распечатайте каждый прямоугольник. @@ -269,7 +269,7 @@ def square_annotation_get(infile, outfile): print(annotation.rect) ``` -### Удалить аннотацию квадрата +### Удаление аннотацию квадрата Этот рабочий процесс удаляет все аннотации квадрата с первой страницы и сохраняет документ. @@ -306,11 +306,11 @@ def square_annotation_delete(infile, outfile): document.save(outfile) ``` -### Добавить аннотацию круга +### Добавление аннотацию круга Аннотации круга обозначают закруглённые области в PDF. В этом примере добавляется аннотация круга с цветом заливки, непрозрачностью и всплывающей аннотацией. -#### Открыть PDF и создать аннотацию круга +#### Открытие PDF и создать аннотацию круга ```python document = ap.Document(infile) @@ -360,7 +360,7 @@ def circle_annotation_add(infile, outfile): document.save(outfile) ``` -### Получить аннотацию круга +### Получение аннотацию круга Чтобы просмотреть аннотации круга, отфильтруйте аннотации страницы по `CIRCLE` введите и выведите их прямоугольники. @@ -397,7 +397,7 @@ def circle_annotation_get(infile, outfile): print(annotation.rect) ``` -### Удалить аннотацию круга +### Удаление аннотацию круга Этот рабочий процесс удаляет все аннотации круга с первой страницы и сохраняет результирующий PDF. @@ -436,11 +436,11 @@ def circle_annotation_delete(infile, outfile): ## Аннотации многоугольников и полилиний -### Добавить аннотацию полигона +### Добавление аннотацию полигона Аннотации полигона определяют замкнутую многоточечную форму. В этом примере создаётся аннотация полигона из прямоугольника и списка точек. -#### Открыть PDF и создать аннотацию полигона +#### Открытие PDF и создать аннотацию полигона ```python document = ap.Document(infile) @@ -462,7 +462,7 @@ polygon_annotation.interior_color = ap.Color.blue_violet polygon_annotation.opacity = 0.25 ``` -#### Добавить аннотацию и сохранить PDF +#### Добавление аннотацию и сохранить PDF ```python document.pages[1].annotations.append(polygon_annotation) @@ -495,7 +495,7 @@ def polygon_annotation_add(infile, outfile): document.save(outfile) ``` -### Получить аннотацию полигона +### Получение аннотацию полигона Чтобы просмотреть аннотации полигонов, отфильтруйте аннотации первой страницы по `POLYGON` введите и распечатайте каждый прямоугольник аннотации. @@ -532,7 +532,7 @@ def polygon_annotation_get(infile, outfile): print(annotation.rect) ``` -### Удалить аннотацию полигона +### Удаление аннотацию полигона Этот рабочий процесс удаляет все аннотации полигона с первой страницы и сохраняет обновлённый PDF. @@ -569,11 +569,11 @@ def polygon_annotation_delete(infile, outfile): document.save(outfile) ``` -### Добавить аннотацию полилинии +### Добавление аннотацию полилинии Полилинейные аннотации определяют открытый путь через несколько точек. В этом примере создаётся аннотация полилинии с всплывающей заметкой. -#### Открыть PDF и создать аннотацию полилинии +#### Открытие PDF и создать аннотацию полилинии ```python document = ap.Document(infile) @@ -633,7 +633,7 @@ def polyline_annotation_add(infile, outfile): document.save(outfile) ``` -### Получить аннотацию полилиний +### Получение аннотацию полилиний Чтобы просмотреть аннотации полилиний, отфильтруйте аннотации страницы по `POLY_LINE` введите и выведите их прямоугольники. @@ -670,7 +670,7 @@ def polyline_annotation_get(infile, outfile): print(annotation.rect) ``` -### Удалить аннотацию полигонов +### Удаление аннотацию полигонов Этот рабочий процесс удаляет все аннотации полилиний с первой страницы и сохраняет результирующий PDF. diff --git a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text-based-annotations/_index.md b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text-based-annotations/_index.md index 48bbbe40a..9a73d4b0f 100644 --- a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text-based-annotations/_index.md +++ b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text-based-annotations/_index.md @@ -26,17 +26,17 @@ Abstract: В этой статье объясняется, как создава ## Аннотации FreeText -### Добавить аннотации FreeText +### Добавление аннотации FreeText Свободные текстовые аннотации позволяют размещать видимые текстовые комментарии непосредственно на странице PDF. В этом примере добавляется простая свободная текстовая аннотация на первую страницу. -#### Открыть исходный PDF +#### Открытие исходного PDF ```python document = ap.Document(infile) ``` -#### Создать и настроить аннотацию свободного текста +#### Создание и настроить аннотацию свободного текста ```python free_text_annotation = ap.annotations.FreeTextAnnotation( @@ -48,7 +48,7 @@ free_text_annotation.title = "Aspose User" free_text_annotation.color = ap.Color.light_green ``` -#### Добавить аннотацию и сохранить PDF +#### Добавление аннотацию и сохранить PDF ```python document.pages[1].annotations.append(free_text_annotation) @@ -73,7 +73,7 @@ def free_text_annotation_add(infile, outfile): document.save(outfile) ``` -### Получить аннотации FreeText +### Получение аннотации FreeText Чтобы проверить аннотации свободного текста, отфильтруйте аннотации первой страницы по `FREE_TEXT` введите и распечатайте каждый прямоугольник аннотации. @@ -110,7 +110,7 @@ def free_text_annotation_get(infile, outfile): print(annotation.rect) ``` -### Удалить аннотации FreeText +### Удаление аннотации FreeText Этот рабочий процесс удаляет все аннотации свободного текста с первой страницы и сохраняет обновлённый PDF. @@ -151,7 +151,7 @@ def free_text_annotation_delete(infile, outfile): ### Выделить аннотации -#### Добавить выделение текста +#### Добавление выделение текста Аннотации выделения подчёркивают части документа, не изменяя исходное содержимое. В этом примере добавляется аннотация выделения на первую страницу. @@ -180,7 +180,7 @@ def text_highlight_annotation_add(infile, outfile): document.save(outfile) ``` -#### Получить выделение текста +#### Получение выделение текста Чтобы проверить выделения, отфильтруйте аннотации страницы по `HIGHLIGHT` введите тип и выведите их прямоугольники. @@ -209,7 +209,7 @@ def text_highlight_annotation_get(infile, outfile): print(annotation.rect) ``` -#### Удалить выделение текста +#### Удаление выделение текста Этот рабочий процесс удаляет все аннотации выделения с первой страницы и сохраняет результирующий PDF. @@ -244,7 +244,7 @@ def text_highlight_annotation_delete(infile, outfile): ### Подчёркнутые аннотации -#### Добавить аннотации подчёркивания текста +#### Добавление аннотации подчёркивания текста Аннотации подчеркивания отмечают текст видимым подчеркиванием. В этом примере добавляется простая аннотация подчеркивания и задаются её метаданные и цвет. @@ -281,7 +281,7 @@ def text_underline_annotation_add(infile, outfile): document.save(outfile) ``` -#### Добавить подчеркивание текста в аннотации, сплющить +#### Добавление подчеркивание текста в аннотации, сплющить Если вы хотите, чтобы подчеркивание стало частью содержимого страницы, а не оставалось интерактивной аннотацией, вы можете сплющить его после добавления. @@ -322,7 +322,7 @@ def text_underline_flatten_add(infile, outfile): document.save(outfile) ``` -#### Добавить аннотации подчеркивания текста с Quad Points +#### Добавление аннотации подчеркивания текста с Quad Points Quad points позволяют задать точную отмеченную область для аннотации подчёркивания. Это полезно, когда вам нужен больший контроль, чем простой прямоугольник. @@ -367,7 +367,7 @@ def text_underline_with_quad_points_add(infile, outfile): document.save(outfile) ``` -#### Удалить аннотации подчеркивания текста +#### Удаление аннотации подчеркивания текста Этот рабочий процесс удаляет все аннотации подчеркивания с первой страницы и сохраняет обновлённый документ. @@ -400,7 +400,7 @@ def text_underline_annotation_delete(infile, outfile): document.save(outfile) ``` -#### Удалить аннотации подчеркивания текста по названию +#### Удаление аннотации подчеркивания текста по названию Этот рабочий процесс показывает, как выборочно удалять аннотации подчёркивания после проверки их заголовка. @@ -437,7 +437,7 @@ def text_underline_by_title_delete(infile, outfile): document.save(outfile) ``` -#### Получить аннотации подчеркивания текста +#### Получение аннотации подчеркивания текста Чтобы просмотреть аннотации подчеркивания, отфильтруйте аннотации первой страницы по `UNDERLINE` введите и распечатайте каждый прямоугольник. @@ -466,7 +466,7 @@ def text_underline_annotation_get(infile, outfile): print(annotation.rect) ``` -#### Получить отмеченный текст подчеркивающих анноций +#### Получение отмеченного текста подчёркивающих аннотаций Этот рабочий процесс преобразует каждую аннотацию подчеркивания в `UnderlineAnnotation` объект и извлекает помеченный текст. @@ -499,7 +499,7 @@ def text_underline_marked_text_get(infile, outfile): print(f"Marked text: {ua.get_marked_text()}") ``` -#### Получить фрагменты, отмеченные аннотациями подчёркнутого текста +#### Получение фрагменты, отмеченные аннотациями подчёркнутого текста Если вам нужен каждый отмеченный фрагмент отдельно, вы можете итерировать коллекцию, возвращаемую `get_marked_text_fragments()`. @@ -536,7 +536,7 @@ def text_underline_marked_fragments_get(infile, outfile): ### Волнистые аннотации -#### Добавить волнообразные аннотации +#### Добавление волнообразные аннотации Волнистые аннотации часто используются для выделения ошибок правописания, грамматики или областей, требующих внимания, в тексте. В данном примере добавляется волнистая аннотация на первую страницу. @@ -571,7 +571,7 @@ def text_squiggly_annotation_add(infile, outfile): document.save(outfile) ``` -#### Получить волнистые аннотации +#### Получение волнистые аннотации Чтобы просмотреть волнистые аннотации, отфильтруйте аннотации страницы по `SQUIGGLY` введите тип и выведите их прямоугольники. @@ -600,7 +600,7 @@ def text_squiggly_annotation_get(infile, outfile): print(annotation.rect) ``` -#### Удалить волнистые аннотации +#### Удаление волнистые аннотации Этот рабочий процесс удаляет все волнообразные аннотации с первой страницы и сохраняет результат. @@ -635,7 +635,7 @@ def text_squiggly_annotation_delete(infile, outfile): ### Аннотации зачеркивания -#### Добавить аннотации зачёркивания текста +#### Добавление аннотации зачёркивания текста Аннотации зачёркивания помечают текст, который следует считать удалённым или перечёркнутым. В этом примере добавляется аннотация зачёркивания, и задаются её метаданные и цвет. @@ -672,7 +672,7 @@ def text_strikeout_annotation_add(infile, outfile): document.save(outfile) ``` -#### Получить аннотации зачёркнутого текста +#### Получение аннотации зачёркнутого текста Чтобы проверить аннотации зачёркивания, отфильтруйте аннотации страниц по `STRIKE_OUT` введите тип и выведите их прямоугольники. @@ -701,7 +701,7 @@ def text_strikeout_annotation_get(infile, outfile): print(annotation.rect) ``` -#### Удалить текстовые аннотации зачёркивания +#### Удаление текстовые аннотации зачёркивания Этот рабочий процесс удаляет все аннотации типа зачеркивания с первой страницы и сохраняет обновлённый документ. diff --git a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/watermark-annotations/_index.md b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/watermark-annotations/_index.md index 82e735557..daa1430d5 100644 --- a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/watermark-annotations/_index.md +++ b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/watermark-annotations/_index.md @@ -22,18 +22,18 @@ Abstract: В этой статье объясняется, как создава - получить прямоугольники аннотаций водяного знака - удалить аннотации водяных знаков -## Добавить аннотацию водяного знака +## Добавление аннотацию водяного знака В этом примере добавляется аннотация водяного знака на первую страницу PDF‑документа. Водяной знак использует текстовое состояние для управления настройками шрифта и применяет пользовательскую непрозрачность для полупрозрачного вида. -### Открыть PDF и получить целевую страницу +### Открытие PDF и получить целевую страницу ```python document = ap.Document(infile) page = document.pages[1] ``` -### Создать аннотацию водяного знака +### Создание аннотацию водяного знака Определите прямоугольник аннотации и добавьте его в коллекцию аннотаций страницы. @@ -46,7 +46,7 @@ watermark_annotation = ap.annotations.WatermarkAnnotation( page.annotations.append(watermark_annotation) ``` -### Настроить внешний вид текста +### Настройка внешнего вида текста Создать `TextState` объект для управления цветом текста, размером шрифта и семейством шрифтов. @@ -57,7 +57,7 @@ text_state.font_size = 25 text_state.font = ap.text.FontRepository.find_font("Arial") ``` -### Установить непрозрачность и текст водяного знака +### Установка непрозрачность и текст водяного знака Пример использует 50% непрозрачности и записывает три строки текста в аннотацию водяного знака. @@ -66,7 +66,7 @@ watermark_annotation.opacity = 0.5 watermark_annotation.set_text_and_state(["HELLO", "Line 1", "Line 2"], text_state) ``` -### Сохранить PDF +### Сохранение PDF ```python document.save(outfile) @@ -97,7 +97,7 @@ def watermark_add(infile, outfile): document.save(outfile) ``` -## Получить аннотацию водяного знака +## Получение аннотацию водяного знака Чтобы просмотреть существующие аннотации водяных знаков, отфильтруйте аннотации первой страницы по `WATERMARK` введите тип и распечатайте их прямоугольники. @@ -134,7 +134,7 @@ def watermark_get(infile, outfile): print(watermark_annotation.rect) ``` -## Удалить аннотацию водяного знака +## Удаление аннотацию водяного знака Этот рабочий процесс удаляет все аннотации водяных знаков с первой страницы и сохраняет обновлённый PDF. @@ -149,7 +149,7 @@ watermark_annotations = [ ] ``` -### Удалить аннотации и сохранить PDF +### Удаление аннотации и сохранить PDF ```python for watermark_annotation in watermark_annotations: diff --git a/ru/python-net/advanced-operations/annotations/import-export-annotations/_index.md b/ru/python-net/advanced-operations/annotations/import-export-annotations/_index.md index 3295057c2..9fc6266ae 100644 --- a/ru/python-net/advanced-operations/annotations/import-export-annotations/_index.md +++ b/ru/python-net/advanced-operations/annotations/import-export-annotations/_index.md @@ -26,7 +26,7 @@ Abstract: В этой статье объясняется, как копиров source_document = ap.Document(infile) ``` -## Создать целевой PDF +## Создание целевой PDF Затем создайте пустой PDF‑документ, который будет принимать импортированные аннотации. На данном этапе целевой документ не содержит страниц. @@ -34,7 +34,7 @@ source_document = ap.Document(infile) destination_document = ap.Document() ``` -## Добавить страницу для экспортированных аннотаций +## Добавление страницу для экспортированных аннотаций Поскольку аннотации должны принадлежать странице, добавьте новую страницу в целевой документ перед копированием чего‑либо. @@ -53,7 +53,7 @@ for annot in source_document.pages[1].annotations: page.annotations.add(annot, True) ``` -## Сохранить выходной документ +## Сохранение выходного документа После того как все аннотации будут скопированы, сохраните целевой документ, чтобы создать окончательный PDF‑файл. diff --git a/ru/python-net/advanced-operations/artifacts/add-backgrounds/_index.md b/ru/python-net/advanced-operations/artifacts/add-backgrounds/_index.md index a787cceae..872349a9a 100644 --- a/ru/python-net/advanced-operations/artifacts/add-backgrounds/_index.md +++ b/ru/python-net/advanced-operations/artifacts/add-backgrounds/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Как добавить фон в PDF с помощью Pyt Abstract: Эта статья рассматривает использование фоновых изображений в PDF‑документах с помощью Aspose.PDF for Python via .NET. В ней подчеркивается возможность добавлять водяные знаки или тонкие дизайны в документы, используя класс `BackgroundArtifact`, который позволяет встраивать фоновые изображения в отдельные объекты страниц. В статье приведён практический пример кода, демонстрирующий, как реализовать эту функцию. Процесс включает создание нового PDF‑документа, добавление страницы, создание объекта `BackgroundArtifact`, установку фонового изображения и добавление фонового артефакта в коллекцию артефактов страницы. В конце изменённый документ сохраняется в виде PDF‑файла. Эта техника позволяет улучшить визуальное представление PDF‑документов. --- -## Добавить фоновое изображение в PDF +## Добавление фонового изображения в PDF Фоновые изображения могут использоваться для добавления водяного знака или другого тонкого дизайна в документы. В Aspose.PDF for Python via .NET каждый PDF‑документ представляет собой набор страниц, а каждая страница содержит набор артефактов. The [BackgroundArtifact](https://reference.aspose.com/pdf/python-net/aspose.pdf/backgroundartifact/) класс может использоваться для добавления фонового изображения к объекту страницы. @@ -44,7 +44,7 @@ def add_background_image_to_pdf(infile, imagefile, outfile): document.save(outfile) ``` -## Добавить фоновое изображение с непрозрачностью в PDF +## Добавление фонового изображения с непрозрачностью в PDF Добавить полупрозрачное фоновое изображение на страницу PDF с использованием Aspose.PDF for Python. @@ -80,7 +80,7 @@ def add_background_image_with_opacity_to_pdf(infile, imagefile, outfile): document.save(outfile) ``` -## Добавить цвет фона в PDF +## Добавление цвета фона в PDF Применить сплошной цвет фона к странице PDF с использованием Aspose.PDF for Python. @@ -106,7 +106,7 @@ def add_background_color_to_pdf(infile, outfile): document.save(outfile) ``` -## Удалить фон из PDF +## Удаление фона из PDF Удалить артефакты фона со страницы PDF с помощью Aspose.PDF for Python. Фоновые элементы в PDF часто хранятся как артефакты, и этот метод выборочно идентифицирует и удаляет только те артефакты, которые классифицированы как фоновые элементы. diff --git a/ru/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md b/ru/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md index e6a6ac195..e7704e3f6 100644 --- a/ru/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md +++ b/ru/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md @@ -68,7 +68,7 @@ def add_bates_n_artifact(infile, outfile): document.save(outfile) ``` -## Добавить нумерацию Bates с использованием артефактов пагинации +## Добавление нумерацию Bates с использованием артефактов пагинации Добавьте нумерацию Bates в PDF, используя коллекцию артефактов пагинации в Aspose.PDF for Python: @@ -96,7 +96,7 @@ def add_bates_n_artifact_pagination(infile, outfile): document.save(outfile) ``` -## Удалить нумерацию Bates +## Удаление нумерацию Bates Чтобы удалить нумерацию Bates из [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/), используйте `delete_bates_numbering()` метод на [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/): diff --git a/ru/python-net/advanced-operations/artifacts/add-watermarks/_index.md b/ru/python-net/advanced-operations/artifacts/add-watermarks/_index.md index 0867b950c..ebf55ab12 100644 --- a/ru/python-net/advanced-operations/artifacts/add-watermarks/_index.md +++ b/ru/python-net/advanced-operations/artifacts/add-watermarks/_index.md @@ -16,7 +16,7 @@ Abstract: В статье рассматривается использован Добавить артефакт водяного знака в PDF [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) используя Aspose.PDF for Python via .NET. Водяной знак — это визуальное наложение, применяемое к страницам для брендинга, безопасности или информационных целей. Пример показывает, как настроить [`TextState`](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstate/) внешний вид, позиционирование с [`HorizontalAlignment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/horizontalalignment/) и [`VerticalAlignment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/verticalalignment/), вращение и прозрачность перед применением водяного знака к [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). -## Извлечь водяные знаки из PDF +## Извлечение водяные знаки из PDF 1. Загрузите документ PDF. 1. Получите доступ к артефактам страницы. @@ -43,7 +43,7 @@ def extract_watermark_from_pdf(infile): print(f"{watermark.text} {watermark.rectangle}") ``` -## Добавить водяной знак в PDF +## Добавление водяного знака в PDF Добавьте текстовый водяной знак в PDF‑документ с помощью Aspose.PDF for Python: @@ -82,7 +82,7 @@ def add_watermark_artifact(infile, outfile): ``` -## Удалить артефакты водяных знаков со страницы PDF +## Удаление артефакты водяных знаков со страницы PDF Удалить артефакты водяного знака с конкретной страницы PDF‑документа, используя API Aspose.PDF for Python. Этот подход ориентируется на элементы водяного знака, хранящиеся как артефакты страницы (в частности, классифицированные как подтипы пагинации водяного знака), проходит их в цикле и удаляет перед сохранением обновленного документа. diff --git a/ru/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md b/ru/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md index 40b4cf464..1f5248f45 100644 --- a/ru/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md +++ b/ru/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Как добавлять, настраивать и уда Abstract: Управление колонтитулами — это распространённое требование при работе с PDF‑документами в бизнесе, издательском деле и автоматизированных рабочих процессах. В этой статье демонстрируется, как с помощью Aspose.PDF for Python добавить профессиональные колонтитулы с пользовательским оформлением, таким как шрифт, размер, цвет и выравнивание. Также показывается, как обнаруживать и удалять существующие артефакты нумерации страниц, такие как колонтитулы, на странице PDF. Благодаря переиспользуемым функциям и понятным примерам разработчики могут быстро интегрировать эти возможности в системы обработки документов для брендирования, отчётности или очистки файлов. --- -## Создать стилизованные текстовые артефакты +## Создание стилизованные текстовые артефакты Эта утилитная функция объясняет, как создать переиспользуемый текстовый артефакт для страниц PDF с использованием Aspose.PDF for Python. Она предназначена для генерации стилизованных заголовков или нижних колонтитулов с единообразным форматированием, включая настройки шрифтов, цвет, размер и выравнивание. Функция абстрагирует создание артефакта, чтобы его можно было переиспользовать для различных текстовых украшений уровня страницы. @@ -41,7 +41,7 @@ def _create_text_artifact(artifact_class, text): ``` -## Добавить заголовок в PDF +## Добавление заголовок в PDF 1. Откройте входной PDF. 1. Создайте HeaderArtifact с текстом "Sample Header". @@ -61,7 +61,7 @@ def add_header_artifact(infile, outfile): document.save(outfile) ``` -## Добавить нижний колонтитул в PDF +## Добавление нижнего колонтитула в PDF 1. Откройте входной PDF. 1. Создайте FooterArtifact с текстом "Sample Footer". @@ -81,7 +81,7 @@ def add_footer_artifact(infile, outfile): document.save(outfile) ``` -## Удалить артефакты заголовка или нижнего колонтитула +## Удаление артефакты заголовка или нижнего колонтитула 1. Откройте PDF. 1. Найдите артефакты, помеченные как заголовки или нижние колонтитулы страниц. diff --git a/ru/python-net/advanced-operations/attachments/extract-attachment/_index.md b/ru/python-net/advanced-operations/attachments/extract-attachment/_index.md index f93627e87..bde14dae9 100644 --- a/ru/python-net/advanced-operations/attachments/extract-attachment/_index.md +++ b/ru/python-net/advanced-operations/attachments/extract-attachment/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: "Полное руководство по управлен Abstract: PDF‑вложения широко используются для хранения сопутствующих документов, отчетов, изображений и других ресурсов непосредственно внутри файла PDF. В этой статье представлено полное руководство по работе с PDF‑вложениями в Python с использованием Aspose.PDF. Описывается, как внедрять внешние файлы в существующие PDF, извлекать отдельные или все вложения, просматривать метаданные, такие как размер файла и метки времени, а также восстанавливать файлы, сохранённые как аннотации FileAttachment. Каждый пример демонстрирует практические методы автоматизации процессов работы с вложениями, повышения переносимости документов и упрощения управления файлами. Независимо от того, создаёте ли вы корпоративные системы документооборота или пользовательские скрипты автоматизации, разработчики могут использовать эти методы для эффективного управления вложенными файлами в PDF‑документах. --- -## Извлечь конкретное вложение из PDF +## Извлечение конкретное вложение из PDF Извлеките один встраиваемый файл из PDF‑документа с помощью Python и Aspose.PDF. Он ищет вложение по имени, извлекает его содержимое и сохраняет как отдельный файл. Это полезно для доступа к вложенным документам, таким как отчёты, журналы или вспомогательные файлы, хранящиеся внутри PDF. @@ -57,7 +57,7 @@ def _print_file_params(params): print(f"Size: {params.size}") ``` -## Извлечь и проверить все вложения PDF +## Извлечение и проверить все вложения PDF Этот фрагмент кода демонстрирует, как извлекать все вложенные файлы из PDF‑документа с использованием Python и Aspose.PDF. Он не только сохраняет каждое вложение в указанную папку, но и выводит подробные метаданные, такие как имя файла, описание, тип MIME, контрольная сумма и метки времени. Это полезно для аудита, экспорта или обработки вложенного контента в PDF‑файлах. diff --git a/ru/python-net/advanced-operations/attachments/portfolio/_index.md b/ru/python-net/advanced-operations/attachments/portfolio/_index.md index 3a96d9e58..91c66b734 100644 --- a/ru/python-net/advanced-operations/attachments/portfolio/_index.md +++ b/ru/python-net/advanced-operations/attachments/portfolio/_index.md @@ -61,7 +61,7 @@ def create_pdf_portfolio(input_files, outfile): document.save(outfile) ``` -## Удалить файлы из PDF Portfolio +## Удаление файлы из PDF Portfolio Чтобы удалить файлы из PDF‑портфеля, попробуйте использовать следующие строки кода. diff --git a/ru/python-net/advanced-operations/attachments/removing-attachment-from-an-existing-pdf/_index.md b/ru/python-net/advanced-operations/attachments/removing-attachment-from-an-existing-pdf/_index.md index a3550258c..e965ba091 100644 --- a/ru/python-net/advanced-operations/attachments/removing-attachment-from-an-existing-pdf/_index.md +++ b/ru/python-net/advanced-operations/attachments/removing-attachment-from-an-existing-pdf/_index.md @@ -36,7 +36,7 @@ def remove_attachment(infile, outfile): document.save(outfile) ``` -## Удалить конкретное вложение по имени +## Удаление конкретное вложение по имени Если вам нужно удалить только одно вложение и оставить остальные, используйте [delete_by_key()](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/delete_by_key/) метод и передайте имя вложения. diff --git a/ru/python-net/advanced-operations/navigation-and-interaction/actions/_index.md b/ru/python-net/advanced-operations/navigation-and-interaction/actions/_index.md index a33da3269..61f483c05 100644 --- a/ru/python-net/advanced-operations/navigation-and-interaction/actions/_index.md +++ b/ru/python-net/advanced-operations/navigation-and-interaction/actions/_index.md @@ -26,7 +26,7 @@ Abstract: В этой статье рассматривается, как раб Почти все действия используют встроенные параметры, но некоторые можно настроить. Например — действия JavaScript. -## Добавить действия запуска PDF +## Добавление действия запуска PDF Добавьте действия запуска на основе JavaScript в PDF‑документ с помощью Python и Aspose.PDF. Он назначает действия ключевым событиям документа, таким как открытие, сохранение и печать, позволяя автоматически запускать URL‑адреса, когда эти события происходят в поддерживаемых PDF‑просмотрщиках. @@ -61,7 +61,7 @@ def add_launch_actions(infile, outfile): document.save(outfile) ``` -## Удаление действий из PDF Document +## Удаление действий из PDF-документа Чтобы очистить (или удалить) действия, просто установите обработчик в `None`. diff --git a/ru/python-net/advanced-operations/navigation-and-interaction/bookmarks/add-and-delete-bookmark/_index.md b/ru/python-net/advanced-operations/navigation-and-interaction/bookmarks/add-and-delete-bookmark/_index.md index 3356ff92c..9f86e9873 100644 --- a/ru/python-net/advanced-operations/navigation-and-interaction/bookmarks/add-and-delete-bookmark/_index.md +++ b/ru/python-net/advanced-operations/navigation-and-interaction/bookmarks/add-and-delete-bookmark/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Как добавить и удалить закладки Abstract: Эта статья предоставляет комплексные инструкции по управлению закладками в PDF‑документах с использованием библиотеки Aspose.PDF для Python. В ней описываются процессы добавления, изменения и удаления закладок в PDF. Статья начинается с руководства по добавлению закладки посредством создания объекта `OutlineItemCollection` и добавления его в `OutlineCollection` документа. Приводятся примеры кода, демонстрирующие создание и добавление как родительских, так и дочерних закладок, подчёркивая иерархическую связь. Кроме того, статья охватывает методы удаления всех закладок или конкретной закладки по названию. Каждый раздел содержит фрагменты кода на Python, иллюстрирующие операции, что позволяет читателям легко внедрять описанные возможности в задачи по работе с PDF. --- -## Добавить закладку в PDF‑документ +## Добавление закладку в PDF‑документ Закладки хранятся в объекте Document [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) коллекция, сама в [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) коллекция. @@ -52,7 +52,7 @@ def add_bookmark(infile, outfile): document.save(outfile) ``` -## Добавить дочернюю закладку в PDF‑документ +## Добавление дочернюю закладку в PDF‑документ Закладки могут быть вложенными, указывая иерархические отношения между родительскими и дочерними закладками. В этой статье объясняется, как добавить дочернюю закладку, то есть закладку второго уровня, в PDF. @@ -97,7 +97,7 @@ def add_child_bookmark(infile, outfile): document.save(outfile) ``` -## Удалить все закладки из PDF‑документа +## Удаление все закладки из PDF‑документа Все закладки в PDF хранятся в [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) collection. Эта статья объясняет, как удалить все закладки из PDF-файла. @@ -124,7 +124,7 @@ def delete_bookmarks(infile, outfile): document.save(outfile) ``` -## Удалить определенную закладку из PDF‑документа +## Удаление определенную закладку из PDF‑документа Чтобы удалить определённую закладку из PDF‑файла: diff --git a/ru/python-net/advanced-operations/navigation-and-interaction/bookmarks/get-update-expand-bookmark/_index.md b/ru/python-net/advanced-operations/navigation-and-interaction/bookmarks/get-update-expand-bookmark/_index.md index 1faba9e98..519dd3a1f 100644 --- a/ru/python-net/advanced-operations/navigation-and-interaction/bookmarks/get-update-expand-bookmark/_index.md +++ b/ru/python-net/advanced-operations/navigation-and-interaction/bookmarks/get-update-expand-bookmark/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Как использовать закладки в PDF с Abstract: В этой статье представлен всесторонний гид по управлению закладками в PDF‑документе с использованием библиотеки Aspose.PDF для Python. Сначала объясняется, как получить закладки из PDF‑файла через `OutlineCollection`, которая содержит все закладки, и подробно описывается доступ к атрибутам закладок через `OutlineItemCollection`. Затем в статье рассматривается процесс определения номера страницы, связанной с закладкой, с помощью `PdfBookmarkEditor`. Далее объясняется, как работать с иерархическими структурами закладок, получая дочерние закладки внутри каждого `OutlineItemCollection`. Описывается также обновление свойств закладок, демонстрируется, как изменять атрибуты закладки и сохранять изменения в PDF. Наконец, в статье рассматривается требование раскрытия закладок при просмотре документа, показывая, как задать статус открытости каждой закладки, чтобы они были раскрыты по умолчанию. К каждому разделу прилагаются фрагменты кода, предоставляющие практические примеры реализации этих функций. --- -## Получить закладки +## Получение закладки Эта [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) объекта [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) Коллекция содержит все закладки PDF‑файла. Эта статья объясняет, как получить закладки из PDF‑файла и как определить, на какой странице находится конкретная закладка. @@ -61,7 +61,7 @@ def get_bookmark_page_number(input_pdf): print(str_level_separator, "Page Action:", bookmark.action) ``` -## Получить дочерние закладки из PDF‑документа +## Получение дочерние закладки из PDF‑документа Закладки могут быть организованы в иерархическую структуру с родителями и дочерними элементами. Чтобы получить все закладки, пройдите в цикле коллекцию Outlines объекта Document. Однако, чтобы также получить дочерние закладки, также пройдите в цикле все закладки в каждом [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) объект, полученный в первом цикле. Следующие фрагменты кода показывают, как получить дочерние закладки из PDF‑документа. diff --git a/ru/python-net/advanced-operations/navigation-and-interaction/links/create-links/_index.md b/ru/python-net/advanced-operations/navigation-and-interaction/links/create-links/_index.md index ba58b9413..53896ceae 100644 --- a/ru/python-net/advanced-operations/navigation-and-interaction/links/create-links/_index.md +++ b/ru/python-net/advanced-operations/navigation-and-interaction/links/create-links/_index.md @@ -51,7 +51,7 @@ def create_link_annotation_launch_action(infile, outfile): document.save(outfile) ``` -## Создать ссылку на документ PDF в PDF‑файле +## Создание ссылку на документ PDF в PDF‑файле ### Использование GoToRemoteAction diff --git a/ru/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md b/ru/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md index 0640e418e..1aef70442 100644 --- a/ru/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md +++ b/ru/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Как извлечь ссылки из PDF Abstract: Руководство Aspose.PDF for Python via .NET по извлечению ссылок объясняет, как программно получать аннотации гиперссылок из PDF‑документов с помощью Python. Документация включает практические примеры кода и подчёркивает, как эту функцию можно использовать для таких задач, как аудит ссылок, анализ навигации или создание интерактивных возможностей документа. Независимо от того, работаете ли вы с одностраничными PDF или обрабатываете большие партии, это руководство предлагает ясный и эффективный подход к извлечению гиперссылок. --- -## Извлечь ссылки из PDF‑файла +## Извлечение ссылки из PDF‑файла Этот пример демонстрирует, как перебрать все аннотации‑ссылки на первой странице PDF с использованием Aspose.PDF for Python. Он фильтрует аннотации, чтобы определить те, которые имеют тип LinkAnnotation, безопасно приводит их тип и затем выводит их индекс страницы и прямоугольную позицию на странице. @@ -47,7 +47,7 @@ def extract_link_annotation(infile): print(f"Page: {annotation.page_index}, location: {annotation.rect}") ``` -## Извлечь гиперссылки из PDF‑файла +## Извлечение гиперссылки из PDF‑файла Этот код демонстрирует, как извлечь все объекты LinkAnnotation с первой страницы PDF‑документа с использованием Aspose.PDF for Python, а затем определить те, которые содержат действие GoToURIAction. Для каждой такой ссылки он выводит номер страницы и целевой URI. diff --git a/ru/python-net/advanced-operations/pdf-file-metadata/_index.md b/ru/python-net/advanced-operations/pdf-file-metadata/_index.md index 8e44b94a2..eba66d255 100644 --- a/ru/python-net/advanced-operations/pdf-file-metadata/_index.md +++ b/ru/python-net/advanced-operations/pdf-file-metadata/_index.md @@ -16,7 +16,7 @@ Abstract: В этой статье объясняется, как работат Используйте это руководство, когда нужно просматривать свойства документа, обновлять информацию о PDF‑файле для поиска или каталогизации, либо программно управлять XMP‑метаданными в Python. -## Получить информацию о PDF‑файле +## Получение информацию о PDF‑файле Этот фрагмент кода демонстрирует, как извлекать метаданные из PDF‑документа с использованием Aspose.PDF for Python via .NET. Получая доступ к свойству info объекта Document, он извлекает ключевую информацию, такую как автор, дата создания, ключевые слова, дата изменения, тема и название. Эта функция необходима для приложений, которым требуется каталогизация документов, оптимизация поиска или проверка свойств документа. @@ -46,7 +46,7 @@ def get_pdf_file_information(infile): print(f"Title: {doc_info.title}") ``` -## Установить информацию о PDF-файле +## Установка информацию о PDF-файле Aspose.PDF for Python via .NET позволяет задавать специфичную для файла информацию о PDF, такую как автор, дата создания, тема и заголовок. Чтобы задать эту информацию: @@ -82,7 +82,7 @@ def set_file_information(infile, outfile): document.save(outfile) ``` -## Установить XMP-метаданные в PDF-файле +## Установка XMP-метаданные в PDF-файле Этот фрагмент кода демонстрирует, как программно установить или обновить XMP‑метаданные в PDF‑документе с использованием Aspose.PDF for Python via .NET. Изменяя такие свойства, как xmp:CreateDate, xmp:Nickname и пользовательские поля, вы можете внедрять стандартизированные метаданные в свои PDF‑файлы. Такой подход особенно полезен для улучшения организации документов, облегчения их поиска и непосредственного внедрения необходимой информации в файл. @@ -113,7 +113,7 @@ def set_xmp_metadata(infile, outfile): document.save(outfile) ``` -## Вставить метаданные с префиксом +## Вставка метаданные с префиксом Некоторым разработчикам необходимо создать новое пространство имён метаданных с префиксом. Следующий фрагмент кода показывает, как вставить метаданные с префиксом. diff --git a/ru/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md b/ru/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md index 1bf66c406..f750f6d93 100644 --- a/ru/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md +++ b/ru/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Подписывайте цифровой подписью Abstract: Это руководство объясняет, как подписывать цифровой подписью PDF‑документы с помощью Aspose.PDF for Python via .NET. В нём подробно описан процесс применения стандартных и продвинутых цифровых подписей, использование сертификатов (PFX и PKCS#12) и настройка внешнего вида и поведения подписи. Документация содержит примеры кода, демонстрирующие, как подписывать существующие PDF, добавлять метки времени и проверять валидность подписи. Это позволяет разработчикам обеспечивать подлинность, целостность документов и соответствие стандартам цифровой подписи в их Python‑приложениях. --- -## Подписать PDF с помощью цифровых подписей +## Подписание PDF с помощью цифровых подписей ```python import sys @@ -146,7 +146,7 @@ def verify_signature_with_certificate_check(infile: str) -> None: print(f"Is verified: {verified}") ``` -## Добавить метку времени к цифровой подписи +## Добавление метку времени к цифровой подписи ### Как подписать цифровой подписью PDF с отметкой времени diff --git a/ru/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md b/ru/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md index 61169df4d..21e374dd9 100644 --- a/ru/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md +++ b/ru/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Извлекайте изображения подписе Abstract: В этой статье объясняется, как извлекать изображения и информацию о цифровой подписи из PDF‑документов с помощью Aspose.PDF for Python. Узнайте, как получать изображения подписи, извлекать данные сертификата, проверять алгоритмы подписи и обнаруживать скомпрометированные подписи в подписанных PDF‑файлах. --- -## Извлечь изображение из поля подписи +## Извлечение изображение из поля подписи Aspose.PDF for Python via .NET позволяет вам извлечь визуальное изображение, встроенное в [Поле подписи](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/signaturefield/). Это полезно, когда нужно отображать или архивировать внешний вид подписи без рендеринга полного PDF. @@ -62,7 +62,7 @@ def get_signatures_info(infile: str) -> None: print(signature_info.signature_name) ``` -## Извлечь цифровой сертификат из поля подписи +## Извлечение цифрового сертификата из поля подписи Используйте [extract_certificate](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/signaturefield/#methods) метод на `SignatureField` получить встроенный сертификат в виде потока байтов и сохранить его на диск для внешней проверки: diff --git a/ru/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md b/ru/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md index 3a5e2c3de..a469186e6 100644 --- a/ru/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md +++ b/ru/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md @@ -28,7 +28,7 @@ Aspose.PDF for Python via .NET дает разработчикам полный Используйте эту страницу, когда вам нужно защищать PDF‑документы паролями, ограничивать печать или копирование, менять учётные данные или проверять, зашифрован ли документ. -## Установить привилегии для существующего PDF‑файла +## Установка привилегии для существующего PDF‑файла Вы можете ограничить или разрешить определённые операции (например, печать, копирование, заполнение форм), назначая пользовательские и владелецкие пароли вместе с правами доступа. @@ -158,7 +158,7 @@ def pub_sec_encryption( document.save(path.join(path.dirname(outfile), "pubsec_decrypted_out.pdf")) ``` -## Изменить пароль PDF‑файла +## Изменение пароль PDF‑файла Обновить учетные данные безопасности (пароли пользователя и владельца) PDF‑документа, сохранив его содержимое и структуру. diff --git a/ru/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md b/ru/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md index 4f939224f..77dbad7c0 100644 --- a/ru/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md +++ b/ru/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md @@ -18,7 +18,7 @@ Aspose.PDF предоставляет надёжные возможности д Используйте этот рабочий процесс, когда ваш процесс подписи зависит от сертификатов, хранящихся в аппаратно‑защищённых устройствах, таких как смарт‑карты, USB‑токены или управляемые хранилища сертификатов. -## Подписать с помощью смарт‑карты, используя поле подписи +## Подписание с помощью смарт‑карты с использованием поля подписи Этот пример демонстрирует, как цифрово подписать PDF‑документ с использованием внешнего сертификата с помощью Aspose.PDF for Python и применить пользовательское изображение внешнего вида подписи: @@ -84,7 +84,7 @@ def verify_external_signature(infile: str) -> None: raise Exception("Not verified") ``` -## Подписать с использованием внешнего сертификата +## Подписание с использованием внешнего сертификата Этот фрагмент кода демонстрирует, как добавить и подписать поле цифровой подписи в документе PDF с помощью Aspose.PDF for Python с внешним сертификатом: diff --git a/ru/python-net/advanced-operations/working-with-documents/_index.md b/ru/python-net/advanced-operations/working-with-documents/_index.md index d9cbe3610..23b00d006 100644 --- a/ru/python-net/advanced-operations/working-with-documents/_index.md +++ b/ru/python-net/advanced-operations/working-with-documents/_index.md @@ -20,7 +20,7 @@ PDF‑документы можно просматривать и печатат Используйте этот раздел, когда вам нужно работать с полной обработкой PDF‑документов в Python, например, создавать файлы, проверять соответствие стандартам, оптимизировать размер, объединять несколько PDF‑файлов или разбивать большие документы на более мелкие. -## Охваченные задачи Document +## Охватываемые задачи документа Вы можете выполнить следующее: diff --git a/ru/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md b/ru/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md index cc342c284..f6cc8af72 100644 --- a/ru/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md +++ b/ru/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md @@ -85,7 +85,7 @@ finally: image_file.unlink(missing_ok=True) ``` -## Связанные темы Document +## Связанные темы документа - [Работа с PDF документами в Python](/pdf/ru/python-net/working-with-documents/) - [Форматировать PDF документы в Python](/pdf/ru/python-net/formatting-pdf-document/) diff --git a/ru/python-net/advanced-operations/working-with-documents/formatting-pdf-document/_index.md b/ru/python-net/advanced-operations/working-with-documents/formatting-pdf-document/_index.md index 2a8dda9a7..afc8792bd 100644 --- a/ru/python-net/advanced-operations/working-with-documents/formatting-pdf-document/_index.md +++ b/ru/python-net/advanced-operations/working-with-documents/formatting-pdf-document/_index.md @@ -18,7 +18,7 @@ Abstract: Статья предоставляет исчерпывающее р ## Форматирование PDF-документа -### Получить свойства окна документа и отображения страниц +### Получение свойства окна документа и отображения страниц Эта тема поможет вам понять, как получить свойства окна документа, приложения‑просмотрщика и как отображаются страницы. Чтобы установить эти свойства: @@ -56,7 +56,7 @@ def get_document_window(input_pdf, output_pdf): print("PageMode:", document.page_mode) ``` -### Установить свойства окна документа и отображения страницы +### Установка свойства окна документа и отображения страницы Эта тема объясняет, как задать свойства окна документа, приложения‑просмотрщика и отображения страницы. Чтобы задать эти разные свойства: @@ -152,7 +152,7 @@ def embedded_fonts_in_new_document(input_pdf, output_pdf): document.save(output_pdf) ``` -### Установить имя шрифта по умолчанию при сохранении PDF +### Установка имени шрифта по умолчанию при сохранении PDF Когда PDF‑документ содержит шрифты, которые недоступны ни в самом документе, ни на устройстве, API заменяет эти шрифты шрифтом по умолчанию. Если шрифт доступен (установлен на устройстве или встроен в документ), результирующий PDF должен использовать тот же шрифт (не должен заменяться шрифтом по умолчанию). Значение шрифта по умолчанию должно содержать название шрифта (а не путь к файлам шрифтов). Мы реализовали возможность задавать название шрифта по умолчанию при сохранении документа в PDF. Ниже приведён фрагмент кода, который можно использовать для установки шрифта по умолчанию: @@ -169,7 +169,7 @@ def set_default_font(input_pdf, output_pdf): document.save(output_pdf, save_options) ``` -### Получить все шрифты из PDF Document +### Получение всех шрифтов из PDF-документа Если вы хотите получить все шрифты из PDF‑документа, вы можете использовать [font_utilities](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties) метод, предоставленный в [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) класс. Пожалуйста, проверьте следующий фрагмент кода, чтобы получить все шрифты из существующего PDF‑документа: @@ -204,13 +204,13 @@ def improve_fonts_embedding(input_pdf, output_pdf): document.save(output_pdf) ``` -### Получить/установить коэффициент масштабирования PDF‑файла +### Получение и установка коэффициента масштабирования PDF‑файла Иногда вам нужно определить текущий коэффициент масштабирования PDF‑документа. С помощью Aspose.Pdf вы можете узнать текущее значение, а также установить его. Эта [GoToAction](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/gotoaction/) class Destination property позволяет получить значение масштабирования, связанное с PDF‑файлом. Аналогично, его можно использовать для установки коэффициента масштабирования файла. -#### Установить коэффициент масштабирования +#### Установка коэффициента масштабирования Следующий фрагмент кода демонстрирует, как установить коэффициент масштабирования PDF-файла. @@ -229,7 +229,7 @@ def set_zoom_factor(input_pdf, output_pdf): document.save(output_pdf) ``` -#### Получить коэффициент масштабирования +#### Получение коэффициента масштабирования В следующем фрагменте кода показано, как получить коэффициент масштабирования PDF‑файла. @@ -248,7 +248,7 @@ def get_zoom_factor(input_pdf, output_pdf): print("Zoom: not set") ``` -## Связанные темы Document +## Связанные темы документа - [Работа с PDF документами в Python](/pdf/ru/python-net/working-with-documents/) - [Создайте PDF-файлы в Python](/pdf/ru/python-net/create-pdf-document/) diff --git a/ru/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md b/ru/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md index 1925b8d0e..5d80c5eed 100644 --- a/ru/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md +++ b/ru/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md @@ -16,9 +16,9 @@ Abstract: Эта статья предоставляет комплексное Эта страница полезна, когда вам нужно проверять соответствие PDF требованиям, создавать или настраивать таблицу содержимого, задавать поведение истечения срока действия документа или уплощать заполняемые PDF в рабочих процессах Python. -## Манипулировать PDF документом в Python +## Манипулирование PDF-документом в Python -## Проверить PDF‑документ на соответствие стандарту PDF/A (A 1A и A 1B) +## Проверка PDF‑документа на соответствие стандарту PDF/A (A 1A и A 1B) Чтобы проверить PDF‑документ на совместимость с PDF/A‑1a или PDF/A‑1b, используйте [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) класс [validate](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) метод. Этот метод позволяет указать имя файла, в котором будет сохранён результат, и требуемый тип проверки PdfFormat enumeration : PDF_A_1A или PDF_A_1B. @@ -50,7 +50,7 @@ def validate_pdfa_standard_a1b(input_pdf, output_pdf): ## Работа с TOC -### Добавить TOC в существующий PDF +### Добавление TOC в существующий PDF TOC в PDF обозначает "Table of Contents". Это функция, позволяющая пользователям быстро перемещаться по документу, предоставляя обзор его разделов и заголовков. @@ -86,7 +86,7 @@ def add_table_of_contents(input_pdf, output_pdf): document.save(output_pdf) ``` -### Установить разный TabLeaderType для разных уровней TOC +### Установка разных TabLeaderType для разных уровней TOC Aspose.PDF for Python также позволяет устанавливать разные TabLeaderType для разных уровней TOC. Вам нужно установить [line_dash](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/#properties) свойство [TocInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/). @@ -184,7 +184,7 @@ def hide_page_numbers_in_toc(input_pdf, output_pdf): document.save(output_pdf) ``` -### Настройте номера страниц при добавлении TOC +### Настройка номеров страниц при добавлении TOC Обычно настраивают нумерацию страниц в оглавлении при добавлении оглавления в PDF‑документ. Например, может потребоваться добавить префикс перед номером страницы, такой как P1, P2, P3 и так далее. В таком случае Aspose.PDF for Python предоставляет [page_numbers_prefix](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/#properties) свойство [TocInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/) класс, который может использоваться для настройки нумерации страниц, как показано в следующем примере кода. @@ -217,7 +217,7 @@ def customize_page_numbers_in_toc(input_pdf, output_pdf): document.save(output_pdf) ``` -## Как установить дату истечения срока действия PDF +## Установка даты истечения срока действия PDF Мы применяем привилегии доступа к PDF‑файлам, чтобы определённая группа пользователей могла получать доступ к конкретным функциям/объектам PDF‑документов. Для ограничения доступа к PDF‑файлам мы обычно используем шифрование и можем иметь требование установить срок действия PDF‑файла, чтобы пользователь, получающий доступ/просматривающий документ, получил корректное уведомление о сроке истечения действия PDF‑файла. @@ -262,7 +262,7 @@ def flatten_fillable_pdf(input_pdf, output_pdf): document.save(output_pdf) ``` -## Связанные темы Document +## Связанные темы документа - [Работа с PDF документами в Python](/pdf/ru/python-net/working-with-documents/) - [Форматировать PDF документы в Python](/pdf/ru/python-net/formatting-pdf-document/) diff --git a/ru/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md b/ru/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md index 510bd1f1d..c2d65caac 100644 --- a/ru/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md +++ b/ru/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Объединяйте страницы PDF с помощь Abstract: В этой статье рассматривается распространённая необходимость объединения нескольких PDF‑файлов в один документ, процесс, полезный для организации, оптимизации хранения и совместного использования PDF‑контента. Описывается использование Aspose.PDF for Python via .NET для эффективного сочетания PDF‑файлов, с учётом того, что объединение PDF в Python может быть сложным без сторонних библиотек. Статья представляет пошаговое руководство по конкатенации PDF‑файлов — создание нового документа, объединение файлов и сохранение объединённого документа. Фрагмент кода демонстрирует реализацию с использованием Aspose.PDF, подчёркивая возможность библиотеки упростить процесс объединения. Кроме того, представляется Aspose.PDF Merger — онлайн‑инструмент для объединения PDF, позволяющий пользователям исследовать функциональность в веб‑среде. --- -## Объединить или совместить несколько PDF в один PDF на Python +## Объединение или совместить несколько PDF в один PDF на Python Объединение PDF‑файлов — очень популярный запрос среди пользователей. Это может быть полезно, когда у вас есть несколько PDF‑файлов, которые вы хотите объединить или хранить вместе как один документ. @@ -46,7 +46,7 @@ def merge_two_documents(infile1, infile2, outfile): document1.save(outfile) ``` -## Добавить диапазон страниц из одного PDF в другой +## Добавление диапазон страниц из одного PDF в другой Скопировать и добавить определённый диапазон страниц из исходного PDF‑документа в целевой PDF‑документ с использованием Aspose.PDF for Python. @@ -77,7 +77,7 @@ def _append_page_range(source_document, destination_document, start_page, end_pa destination_document.pages.add(source_document.pages[page_number]) ``` -## Объединить несколько PDF‑документов в один +## Объединение несколько PDF‑документов в один Этот фрагмент кода объясняет, как объединить несколько PDF‑файлов в один документ: @@ -107,7 +107,7 @@ def merge_multiple_documents(input_files, outfile): output_document.save(outfile) ``` -## Объединить выбранные диапазоны страниц из нескольких PDF +## Объединение выбранные диапазоны страниц из нескольких PDF 1. Загрузите исходные PDF‑документы. 1. Создайте выходной документ. @@ -134,7 +134,7 @@ def merge_selected_page_ranges(infile1, infile2, outfile): output_document.save(outfile) ``` -## Вставить один PDF в другой в определённой позиции +## Вставка один PDF в другой в определённой позиции 1. Загрузите базу и вставьте документы. 1. Создайте выходной документ. @@ -168,7 +168,7 @@ def merge_insert_document_at_position(infile1, infile2, insert_after_page, outfi output_document.save(outfile) ``` -## Объединить PDF‑файлы, чередуя страницы +## Объединение PDF‑файлы, чередуя страницы В этом примере демонстрируется, как объединить два PDF‑документа, чередуя их страницы, используя Aspose.PDF for Python. @@ -205,7 +205,7 @@ def merge_alternating_pages(infile1, infile2, outfile): output_document.save(outfile) ``` -## Объединить PDF-файлы с разделителями секций и закладками +## Объединение PDF-файлы с разделителями секций и закладками Объедините несколько PDF‑документов в один файл со структурированными разделами и навигационными закладками, используя Aspose.PDF for Python. @@ -267,7 +267,7 @@ def merge_with_section_separators_and_bookmarks(input_files, outfile): [![Aspose.PDF Merger](merger.png)](https://products.aspose.app/pdf/merger) -## Связанные темы Document +## Связанные темы документа - [Работа с PDF документами в Python](/pdf/ru/python-net/working-with-documents/) - [Разделить PDF файлы в Python](/pdf/ru/python-net/split-document/) diff --git a/ru/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md b/ru/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md index d6487e870..ad279ea21 100644 --- a/ru/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md +++ b/ru/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md @@ -33,7 +33,7 @@ PDF‑документ иногда может содержать дополни {{% /alert %}} -## Оптимизировать PDF Document для Web +## Оптимизация PDF-документа для Web Оптимизация, или линеаризация для веба, относится к процессу подготовки PDF‑файла к онлайн‑просмотру с помощью веб‑браузера. Чтобы оптимизировать файл для отображения в вебе: @@ -62,7 +62,7 @@ def optimize_pdf(infile, outfile): ) ``` -## Уменьшить размер PDF +## Уменьшение размера PDF Эта [OptimizeResources()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) метод позволяет уменьшить размер документа, устраняя лишнюю информацию. По умолчанию этот метод работает следующим образом: @@ -303,7 +303,7 @@ def flatten_forms(infile, outfile): ) ``` -### Конвертировать PDF из цветового пространства RGB в градации серого +### Преобразование PDF из цветового пространства RGB в градации серого PDF‑файл состоит из текста, изображений, вложений, аннотаций, графиков и других объектов. Вы можете столкнуться с требованием преобразовать PDF из цветового пространства RGB в градации серого, чтобы ускорить печать этих PDF‑файлов. Кроме того, при преобразовании файла в градации серого размер документа также уменьшается, но это может также привести к снижению качества документа. Эта функция в настоящее время поддерживается функцией Pre‑Flight в Adobe Acrobat, но при разговоре об автоматизации Office Aspose.PDF является окончательным решением, предоставляющим такие возможности для манипуляций с документами. Чтобы выполнить это требование, можно использовать следующий фрагмент кода. @@ -350,7 +350,7 @@ def using_flatedecode_compression(infile, outfile): doc.save(outfile) ``` -## Связанные темы Document +## Связанные темы документа - [Работа с PDF документами в Python](/pdf/ru/python-net/working-with-documents/) - [Объединить PDF файлы в Python](/pdf/ru/python-net/merge-pdf-documents/) diff --git a/ru/python-net/advanced-operations/working-with-documents/split-pdf/_index.md b/ru/python-net/advanced-operations/working-with-documents/split-pdf/_index.md index 2e72cc68a..87126dc20 100644 --- a/ru/python-net/advanced-operations/working-with-documents/split-pdf/_index.md +++ b/ru/python-net/advanced-operations/working-with-documents/split-pdf/_index.md @@ -30,7 +30,7 @@ Abstract: В статье рассматривается процесс разд 1. Для каждой итерации создавайте новый объект Document и добавляйте отдельный [Страница](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) объект в пустой документ 1. Сохраните новый PDF, используя [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) метод -## Разделить PDF на несколько файлов или отдельные PDF в Python +## Разделение PDF на несколько файлов или отдельные PDF в Python Следующий фрагмент кода на Python показывает, как разделить страницы PDF на отдельные PDF‑файлы. @@ -48,7 +48,7 @@ def split_documents(infile, outdir): new_document.save(path.join(outdir, f"Page_{page_num}.pdf")) ``` -## Разделить PDF на две равные части +## Разделение PDF на две равные части 1. Загрузите PDF-документ. 1. Определите общее количество страниц. @@ -84,7 +84,7 @@ def split_documents_into_two_parts(infile, outdir): second_document.save(path.join(outdir, "Part_2.pdf")) ``` -## Разделить PDF на несколько файлов каждые N страниц +## Разделение PDF на несколько файлов каждые N страниц Разделите PDF‑документ на несколько более мелких файлов, основываясь на фиксированном количестве страниц, с помощью Aspose.PDF for Python. @@ -122,7 +122,7 @@ def split_documents_every_n_pages(infile, outdir, pages_per_part=3): part_index += 1 ``` -## Разделить PDF по пользовательским диапазонам страниц +## Разделение PDF по пользовательским диапазонам страниц Разделите PDF‑документ на несколько файлов на основе пользовательски заданных диапазонов страниц с использованием Aspose.PDF для Python. @@ -165,7 +165,7 @@ def split_documents_by_page_ranges(infile, outdir): ) ``` -## Разделить PDF на первую страницу и оставшиеся страницы +## Разделение PDF на первую страницу и оставшиеся страницы Отделите первую страницу PDF‑документа от остальных страниц, используя Aspose.PDF for Python. @@ -206,7 +206,7 @@ def split_documents_first_page_and_rest(infile, outdir): remaining_pages_document.save(path.join(outdir, "Remaining_Pages.pdf")) ``` -## Разделить PDF на последнюю страницу и предыдущие страницы +## Разделение PDF на последнюю страницу и предыдущие страницы Извлеките последнюю страницу PDF‑документа и отделите её от остальных страниц с помощью Aspose.PDF for Python. @@ -244,7 +244,7 @@ def split_documents_last_page_and_rest(infile, outdir): document.save(path.join(outdir, "Previous_Pages.pdf")) ``` -## Разделить PDF на три части +## Разделение PDF на три части Разделите PDF-документ на три отдельные части с помощью Aspose.PDF for Python. @@ -363,7 +363,7 @@ def split_documents_odd_even_pages(infile, outdir): even_document.save(path.join(outdir, "Even_Pages.pdf")) ``` -## Связанные темы Document +## Связанные темы документа - [Работа с PDF документами в Python](/pdf/ru/python-net/working-with-documents/) - [Объединить PDF файлы в Python](/pdf/ru/python-net/merge-pdf-documents/) diff --git a/ru/python-net/advanced-operations/working-with-forms/acroforms/create-form/_index.md b/ru/python-net/advanced-operations/working-with-forms/acroforms/create-form/_index.md index ef0a54323..8130f7473 100644 --- a/ru/python-net/advanced-operations/working-with-forms/acroforms/create-form/_index.md +++ b/ru/python-net/advanced-operations/working-with-forms/acroforms/create-form/_index.md @@ -14,9 +14,9 @@ AlternativeHeadline: Как создать AcroForm в PDF, используя P Abstract: В этой статье объясняется, как создавать поля AcroForm в PDF‑документах, используя Aspose.PDF for Python via .NET. Охватывается базовое создание полей с TextBoxField, настройка внешнего вида многовидовых текстовых полей, а также дополнительные типы полей, такие как radio buttons, combo boxes, checkboxes, list boxes, signature fields и barcode fields. Эти примеры помогут вам создавать интерактивные PDF‑формы для сбора данных и автоматизации рабочих процессов с документами. --- -## Создать форму с нуля +## Создание форму с нуля -### Добавление полей формы в PDF Document +### Добавление полей формы в PDF-документ Определённый [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) класс предоставляет коллекцию с именем [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/form/) что помогает управлять полями формы в PDF‑документе. @@ -125,7 +125,7 @@ def add_text_box_field_nt(output_file_name): 1. Добавьте поле подписи 1. Добавьте поле штрих‑кода -### Добавить поле переключателя +### Добавление поле переключателя ```python import aspose.pdf as ap @@ -147,7 +147,7 @@ def add_radio_button(output_file_name): document.save(output_file_name) ``` -### Добавить поле комбобокса +### Добавление поле комбобокса ```python import aspose.pdf as ap @@ -170,7 +170,7 @@ def add_combo_box(output_file_name): document.save(output_file_name) ``` -### Добавить поле флажка +### Добавление поле флажка ```python import aspose.pdf as ap @@ -190,7 +190,7 @@ def add_checkbox_field_to_pdf(output_file_name): document.save(output_file_name) ``` -### Добавить поле списка +### Добавление поле списка ```python import aspose.pdf as ap @@ -212,7 +212,7 @@ def add_list_box_field_to_pdf(output_file_name): document.save(output_file_name) ``` -### Добавить поле подписи +### Добавление поле подписи ```python import aspose.pdf as ap @@ -230,7 +230,7 @@ def add_signature_field(output_file_name): document.save(output_file_name) ``` -### Добавить поле штрих‑кода +### Добавление поле штрих‑кода ```python import aspose.pdf as ap diff --git a/ru/python-net/advanced-operations/working-with-forms/acroforms/extract-form/_index.md b/ru/python-net/advanced-operations/working-with-forms/acroforms/extract-form/_index.md index 1275bb6ca..40f8c508a 100644 --- a/ru/python-net/advanced-operations/working-with-forms/acroforms/extract-form/_index.md +++ b/ru/python-net/advanced-operations/working-with-forms/acroforms/extract-form/_index.md @@ -14,9 +14,9 @@ AlternativeHeadline: Как получить данные формы из PDF с Abstract: В этой статье показано, как извлечь данные из полей AcroForm в PDF‑документах, используя Aspose.PDF for Python via .NET. Пример проходит по именам полей формы, считывает значения с помощью фасада Form и возвращает словарь для последующей обработки. Этот рабочий процесс полезен для формирования отчётов, проверки и интеграции с внешними системами. --- -## Извлечь данные из Form +## Извлечение данные из Form -### Получить значения всех полей в PDF‑документе +### Получение значения всех полей в PDF‑документе Чтобы прочитать значения из всех полей PDF‑документа, пройдите по именам полей формы и получите каждое значение из [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) фасад. diff --git a/ru/python-net/advanced-operations/working-with-forms/acroforms/import-export-form-data/_index.md b/ru/python-net/advanced-operations/working-with-forms/acroforms/import-export-form-data/_index.md index a9b17a8c4..910ad607f 100644 --- a/ru/python-net/advanced-operations/working-with-forms/acroforms/import-export-form-data/_index.md +++ b/ru/python-net/advanced-operations/working-with-forms/acroforms/import-export-form-data/_index.md @@ -13,7 +13,7 @@ Abstract: Этот сборник представляет собой компл Эта страница демонстрирует типовые рабочие процессы импорта и экспорта данных AcroForm с помощью Aspose.PDF for Python via .NET. Все операции используют [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) фасад. -## Импортировать данные полей формы из XML +## Импорт данные полей формы из XML Используйте этот подход для заполнения PDF-формы данными из внешнего XML. @@ -37,7 +37,7 @@ def import_data_from_xml(input_file_name, data_file_name, output_file_name): form.save(output_file_name) ``` -## Экспортировать данные полей формы в XML +## Экспорт данные полей формы в XML Этот метод экспортирует значения полей формы из PDF‑документа в XML. @@ -57,7 +57,7 @@ def export_data_to_xml(input_file_name, output_file_name): form.export_xml(f) ``` -## Импортировать данные полей формы из FDF +## Импорт данные полей формы из FDF Определённый `import_data_from_fdf` метод импортирует данные полей формы из файла FDF (Формат данных форм) в форму PDF. @@ -79,7 +79,7 @@ def import_data_from_fdf(input_file_name, data_file_name, output_file_name): form.save(output_file_name) ``` -## Экспортировать данные полей формы в FDF +## Экспорт данные полей формы в FDF В этом примере данные формы экспортируются из PDF‑документа в файл FDF. @@ -99,7 +99,7 @@ def export_data_to_fdf(input_file_name, output_file_name): form.export_fdf(f) ``` -## Импортировать данные полей формы из XFDF +## Импорт данные полей формы из XFDF Используйте этот метод для импорта данных полей формы из файла XFDF (XML Forms Data Format) в PDF-форму. @@ -121,7 +121,7 @@ def import_data_from_xfdf(input_file_name, data_file_name, output_file_name): form.save(output_file_name) ``` -## Экспортировать данные полей формы в XFDF +## Экспорт данные полей формы в XFDF Этот код экспортирует данные полей формы из PDF‑документа в файл XFDF. @@ -141,7 +141,7 @@ def export_data_to_xfdf(input_file_name, output_file_name): form.export_xfdf(f) ``` -## Импортировать данные из другого PDF +## Импорт данные из другого PDF Этот пример переносит данные полей формы из исходного PDF в целевой PDF, экспортируя XFDF в поток в памяти и импортируя его в целевую форму. @@ -170,7 +170,7 @@ def import_data_from_another_pdf(source_pdf_name, destination_pdf_name, output_f form_dest.save(output_file_name) ``` -## Извлечь поля формы в JSON +## Извлечение поля формы в JSON Этот метод экспортирует поля формы в JSON‑файл, используя `export_json()`. @@ -188,7 +188,7 @@ def extract_form_fields_to_json(input_file_name, output_file_name): form.export_json(json_file, True) ``` -## Извлечь FormField в JSON Document +## Извлечение FormField в JSON-документ Этот пример создает пользовательский JSON‑документ из имён полей формы и их значений. diff --git a/ru/python-net/advanced-operations/working-with-forms/acroforms/modifying-form/_index.md b/ru/python-net/advanced-operations/working-with-forms/acroforms/modifying-form/_index.md index 8c5ad99e1..c16d3df86 100644 --- a/ru/python-net/advanced-operations/working-with-forms/acroforms/modifying-form/_index.md +++ b/ru/python-net/advanced-operations/working-with-forms/acroforms/modifying-form/_index.md @@ -45,7 +45,7 @@ def clear_text_in_form(input_file_name, output_file_name): document.save(output_file_name) ``` -## Установить ограничение поля +## Установка ограничение поля Использовать `set_field_limit(field, limit)` из `FormEditor` определить максимальное количество символов, разрешённых в текстовом поле. @@ -65,7 +65,7 @@ def set_field_limit(input_file_name, output_file_name): form.save(output_file_name) ``` -## Получить ограничение поля +## Получение ограничение поля Вы также можете прочитать ограничение количества символов из текстового поля. @@ -86,7 +86,7 @@ def get_field_limit(input_file_name): print(f"Limit: {text_box_field.max_len}") ``` -## Установить пользовательский шрифт для поля формы +## Установка пользовательского шрифта для поля формы Этот пример задает пользовательское оформление по умолчанию для поля ввода текста, включая шрифт, размер и цвет. @@ -113,7 +113,7 @@ def set_form_field_font(input_file_name, output_file_name): document.save(output_file_name) ``` -## Удалить поля в существующей Form +## Удаление поля в существующей Form Этот код удаляет конкретное поле формы (по его имени) из PDF‑документа и сохраняет обновлённый файл, используя Aspose.PDF for Python via .NET. diff --git a/ru/python-net/advanced-operations/working-with-forms/acroforms/posting-form/_index.md b/ru/python-net/advanced-operations/working-with-forms/acroforms/posting-form/_index.md index e9ec34592..cbe05df2b 100644 --- a/ru/python-net/advanced-operations/working-with-forms/acroforms/posting-form/_index.md +++ b/ru/python-net/advanced-operations/working-with-forms/acroforms/posting-form/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Как добавить кнопки отправки и д Abstract: В этой статье показаны два подхода к добавлению функции отправки в PDF‑формы с помощью Aspose.PDF for Python via .NET. Вы можете добавить готовую кнопку отправки через FormEditor или создать пользовательское поле кнопки с SubmitFormAction для расширенного управления. Эти шаблоны помогают интегрировать PDF‑формы с конечными точками серверной обработки форм. --- -## Добавить кнопку отправки с помощью FormEditor +## Добавление кнопку отправки с помощью FormEditor Следующий фрагмент кода демонстрирует, как добавить кнопку отправки в PDF-форму с использованием класса FormEditor в Aspose.PDF for Python via .NET. Кнопка настроена на отправку данных формы по указанному URL при нажатии. @@ -34,7 +34,7 @@ def add_submit_button(input_file_name, output_file_name): editor.save() ``` -## Добавить пользовательское действие отправки +## Добавление пользовательское действие отправки Следующий фрагмент кода объясняет, как создать пользовательскую кнопку отправки в PDF-форме с использованием Aspose.PDF for Python via .NET. Кнопка настроена на отправку данных формы по указанному URL при нажатии. diff --git a/ru/python-net/advanced-operations/working-with-forms/acroforms/remove-form/_index.md b/ru/python-net/advanced-operations/working-with-forms/acroforms/remove-form/_index.md index c603a6cef..e26d2d3dc 100644 --- a/ru/python-net/advanced-operations/working-with-forms/acroforms/remove-form/_index.md +++ b/ru/python-net/advanced-operations/working-with-forms/acroforms/remove-form/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Удалить формы из PDF с помощью Aspose Abstract: В этой статье представлены два подхода к удалению элементов форм из PDF‑документов с использованием Aspose.PDF for Python via .NET. Первый метод очищает все объекты форм на выбранной странице, тогда как второй метод удаляет только соответствующие ресурсы формы Typewriter. Эти примеры помогают при очистке форм, подготовке шаблонов и процессах нормализации документов. --- -## Удалить все формы со страницы +## Удаление все формы со страницы Этот код удаляет все объекты формы со страницы, указанной `page_num` и сохраняет обновлённый документ. @@ -33,7 +33,7 @@ def remove_all_forms(input_file_name, page_num, output_file_name): document.save(output_file_name) ``` -## Удалить конкретный тип формы +## Удаление конкретного типа формы Следующий пример проходит по объектам форм на заданной странице PDF, определяет аннотации форм‑пишущих машинок, удаляет их и затем сохраняет обновлённый PDF, используя Aspose.PDF for Python via .NET. diff --git a/ru/python-net/advanced-operations/working-with-forms/xfa-forms/_index.md b/ru/python-net/advanced-operations/working-with-forms/xfa-forms/_index.md index d57ba3037..aabc318d0 100644 --- a/ru/python-net/advanced-operations/working-with-forms/xfa-forms/_index.md +++ b/ru/python-net/advanced-operations/working-with-forms/xfa-forms/_index.md @@ -11,7 +11,7 @@ sitemap: priority: 0.7 --- -## Преобразовать XFA‑в‑Acroform +## Преобразование XFA‑в‑Acroform {{% alert color="primary" %}} diff --git a/ru/python-net/advanced-operations/working-with-graphs/arc/_index.md b/ru/python-net/advanced-operations/working-with-graphs/arc/_index.md index 51696c733..d1771d8ff 100644 --- a/ru/python-net/advanced-operations/working-with-graphs/arc/_index.md +++ b/ru/python-net/advanced-operations/working-with-graphs/arc/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Добавление объекта дуги в PDF с по Abstract: Статья предоставляет подробное руководство по добавлению и настройке объектов дуг внутри PDF‑документов с использованием Aspose.PDF for Python via .NET. В ней подчеркивается возможность библиотеки включать графические элементы, такие как дуги, что имеет решающее значение для приложений, требующих динамического создания содержимого PDF, например технических схем и пользовательских иллюстраций. В статье содержатся пошаговые инструкции и фрагменты кода, демонстрирующие, как создать экземпляр `Document`, настроить объект `Drawing` с указанными размерами и свойствами границы, а также добавить объекты `Graph` и `Arc` на страницу PDF. Кроме того, рассматривается процесс заливки объектов дуг цветом, показывающий, как задать свойства заливки для дуг и линий, и в конечном итоге сохранить PDF‑документ. Приведённые примеры служат практическим руководством для разработчиков, желающих использовать Aspose.PDF для точных графических манипуляций в PDF‑файлах. --- -## Добавить объект дуги +## Добавление объект дуги Aspose.PDF for Python via .NET позволяет вам добавлять [Arc](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/arc/) фигуры в страницы PDF с использованием [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) класс. Вы можете рисовать контурные дуги и заполненные сегменты дуг для схем и технических иллюстраций. @@ -56,7 +56,7 @@ def add_arc(outfile: str): document.save(outfile) ``` -## Создать заполненный объект дуги +## Создание заполненного объекта дуги В этом примере показано, как добавить сегмент дуги, заполненный цветом. diff --git a/ru/python-net/advanced-operations/working-with-graphs/circle/_index.md b/ru/python-net/advanced-operations/working-with-graphs/circle/_index.md index d422c288a..81ab16413 100644 --- a/ru/python-net/advanced-operations/working-with-graphs/circle/_index.md +++ b/ru/python-net/advanced-operations/working-with-graphs/circle/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Рисовать формы кругов в PDF‑файл Abstract: В этой статье показано, как добавить формы кругов в PDF‑документы с помощью Aspose.PDF for Python via .NET. Описывается создание контурных кругов, заполнение кругов цветом и размещение текста внутри объектов круга. --- -## Добавить объект круга +## Добавление объект круга Aspose.PDF for Python via .NET позволяет вам добавлять [Круг](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/circle/) фигуры на страницы PDF через [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) class. Используйте круги для схем, аннотаций и простых визуальных элементов. @@ -48,7 +48,7 @@ def add_circle(outfile: str): ![Рисование круга](drawing_circle.png) -## Создать объект заполненного круга +## Создание объект заполненного круга Этот пример показывает, как добавить круг и заполнить его цветом. diff --git a/ru/python-net/advanced-operations/working-with-graphs/curve/_index.md b/ru/python-net/advanced-operations/working-with-graphs/curve/_index.md index 9c7b66f95..08ef92adb 100644 --- a/ru/python-net/advanced-operations/working-with-graphs/curve/_index.md +++ b/ru/python-net/advanced-operations/working-with-graphs/curve/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Рисуйте кривые формы в PDF‑файла Abstract: Эта статья показывает, как добавить кривые формы в PDF‑документы с помощью Aspose.PDF for Python via .NET. В ней рассматривается создание обведённых кривых, заполнение объектов кривой и отрисовка пользовательских путей кривой в контейнере Graph. --- -## Добавить объект Curve +## Добавление объект Curve Aspose.PDF for Python via .NET позволяет добавлять [Curve](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/curve/) фигуры на страницы PDF через [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) класс. @@ -50,7 +50,7 @@ def add_curve(outfile: str): ![Рисование кривой](drawing_curve.png) -## Создать объект заполненной кривой +## Создание объект заполненной кривой Этот пример показывает, как добавить объект Curve, заполненный цветом. diff --git a/ru/python-net/advanced-operations/working-with-graphs/ellipse/_index.md b/ru/python-net/advanced-operations/working-with-graphs/ellipse/_index.md index 2911bd490..6e78d29f9 100644 --- a/ru/python-net/advanced-operations/working-with-graphs/ellipse/_index.md +++ b/ru/python-net/advanced-operations/working-with-graphs/ellipse/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Рисовать эллиптические формы в P Abstract: Эта статья показывает, как добавлять формы эллипсов в PDF‑документы с помощью Aspose.PDF for Python via .NET. В ней рассматриваются контурные эллипсы, заполненные эллипсы и добавление текста внутрь объектов эллипса. --- -## Добавить объект Ellipse +## Добавление объект Ellipse Aspose.PDF for Python via .NET позволяет добавлять [Ellipse](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/ellipse/) формы в PDF‑страницы с [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) класс. Вы можете рисовать контуры эллипсов, применять цвета заливки и размещать текст внутри объектов эллипсов. @@ -43,7 +43,7 @@ def add_ellipse(outfile: str): ![Добавить эллипс](ellipse.png) -## Создать заполненный объект эллипса +## Создание заполненного объекта эллипса Следующий фрагмент кода показывает, как добавить [Ellipse](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/ellipse/) объект, заполненный цветом. @@ -71,7 +71,7 @@ def create_ellipse_filled(outfile: str): ![Заполненный Эллипс](fill_ellipse.png) -## Добавить текст внутри Эллипса +## Добавление текста внутри эллипса Aspose.PDF for Python via .NET также позволяет размещать текст внутри объектов фигур. Следующий пример добавляет текст к фигурам-эллипсам. diff --git a/ru/python-net/advanced-operations/working-with-graphs/line/_index.md b/ru/python-net/advanced-operations/working-with-graphs/line/_index.md index 3fd3e7ce3..bb1f3c4f7 100644 --- a/ru/python-net/advanced-operations/working-with-graphs/line/_index.md +++ b/ru/python-net/advanced-operations/working-with-graphs/line/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Рисовать линейные фигуры в PDF‑ф Abstract: В этой статье показано, как добавить формы линий в PDF‑документы с помощью Aspose.PDF for Python via .NET. Она охватывает создание базовых линий, настройку пунктирных стилей линий и рисование линий по всей странице. --- -## Добавить объект Line +## Добавление объект Line Aspose.PDF for Python via .NET позволяет вам добавить [Line](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/line/) формы в страницы PDF с использованием [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) класс. Вы можете управлять цветом линии, пунктирным шаблоном и размещением. diff --git a/ru/python-net/advanced-operations/working-with-graphs/rectangle/_index.md b/ru/python-net/advanced-operations/working-with-graphs/rectangle/_index.md index 1b86e960d..ebcd57a14 100644 --- a/ru/python-net/advanced-operations/working-with-graphs/rectangle/_index.md +++ b/ru/python-net/advanced-operations/working-with-graphs/rectangle/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Рисовать прямоугольные фигуры в Abstract: В этой статье показано, как добавлять прямоугольные формы в PDF-документы с помощью Aspose.PDF for Python via .NET. Охватываются контурные прямоугольники, сплошные и градиентные заливки, альфа‑прозрачность и управление порядком Z. --- -## Добавить объект Rectangle +## Добавление объект Rectangle Aspose.PDF for Python via .NET позволяет добавлять [Rectangle](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/rectangle/) формы в страницы PDF через [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) класс. Вы можете рисовать обводные прямоугольники и применять сплошные, градиентные или прозрачные заполнения. @@ -53,7 +53,7 @@ def add_rectangle(outfile: str): ![Создать прямоугольник](create_rectangle.png) -## Создать объект заполненного прямоугольника +## Создание объект заполненного прямоугольника Aspose.PDF for Python via .NET также предлагает возможность заполнять объект прямоугольника определённым цветом. @@ -80,7 +80,7 @@ def create_rectangle_filled(outfile: str): ![Заполненный прямоугольник](fill_rectangle.png) -## Добавить рисунок с градиентной заливкой +## Добавление рисунок с градиентной заливкой Aspose.PDF for Python via .NET поддерживает возможность добавлять графические объекты в PDF‑документы, и иногда требуется заполнять графические объекты градиентным цветом. @@ -110,7 +110,7 @@ def add_drawing_with_gradient_fill(outfile: str): ![Градиентный прямоугольник](gradient.png) -## Создать прямоугольник с альфа‑каналом цвета +## Создание прямоугольник с альфа‑каналом цвета Aspose.PDF for Python via .NET также поддерживает прозрачность через альфа‑канал цвета. diff --git a/ru/python-net/advanced-operations/working-with-images/add-image-to-existing-pdf-file/_index.md b/ru/python-net/advanced-operations/working-with-images/add-image-to-existing-pdf-file/_index.md index b991a8b44..2ebf60577 100644 --- a/ru/python-net/advanced-operations/working-with-images/add-image-to-existing-pdf-file/_index.md +++ b/ru/python-net/advanced-operations/working-with-images/add-image-to-existing-pdf-file/_index.md @@ -11,7 +11,7 @@ AlternativeHeadline: Добавьте изображения в существу Abstract: Эта статья показывает, как добавлять изображения в PDF‑документы с помощью Aspose.PDF for Python via .NET. В ней рассматриваются добавление изображения с фиксированными координатами, размещение изображений с использованием низкоуровневых операторов, назначение альтернативного текста для доступности и внедрение изображений с компрессией Flate. --- -## Добавить изображение в существующий PDF‑файл +## Добавление изображения в существующий PDF‑файл Этот пример показывает, как разместить изображение в фиксированной позиции на существующей странице PDF с использованием Aspose.PDF for Python via .NET. @@ -35,7 +35,7 @@ def add_image(infile, image_file, outfile): document.save(outfile) ``` -## Добавить изображение с помощью операторов +## Добавление изображения с помощью операторов Этот подход добавляет изображение с помощью низкоуровневых операторов PDF вместо высокоуровневых `add_image()` помощник. @@ -81,7 +81,7 @@ def add_image_using_operators(image_file, outfile): document.save(outfile) ``` -## Добавить изображение с альтернативным текстом +## Добавление изображения с альтернативным текстом В этом примере добавляется изображение и назначается альтернативный текст для доступности. @@ -111,7 +111,7 @@ def add_image_set_alternative_text(image_file, outfile): document.save(outfile) ``` -## Добавить изображение в PDF с использованием сжатия Flate +## Добавление изображения в PDF с использованием сжатия Flate Этот пример вставляет изображение с помощью `ImageFilterType.FLATE` сжатие. diff --git a/ru/python-net/advanced-operations/working-with-images/delete-images-from-pdf-file/_index.md b/ru/python-net/advanced-operations/working-with-images/delete-images-from-pdf-file/_index.md index 4d16a16e6..377c3175d 100644 --- a/ru/python-net/advanced-operations/working-with-images/delete-images-from-pdf-file/_index.md +++ b/ru/python-net/advanced-operations/working-with-images/delete-images-from-pdf-file/_index.md @@ -13,7 +13,7 @@ Abstract: В этой статье показано, как удалять из Используйте эту страницу, когда нужно удалить ненужную графику, уменьшить размер PDF или очистить конфиденциальный визуальный контент из документа. -## Удалить изображения из PDF‑файла +## Удаление изображения из PDF‑файла Выполните следующие шаги, чтобы удалить одно изображение со страницы: @@ -32,7 +32,7 @@ def delete_image(infile, outfile): document.save(outfile) ``` -## Удалить все изображения со страницы +## Удаление все изображения со страницы Используйте этот пример, чтобы удалить каждое изображение с конкретной страницы. diff --git a/ru/python-net/advanced-operations/working-with-images/replace-image-in-existing-pdf-file/_index.md b/ru/python-net/advanced-operations/working-with-images/replace-image-in-existing-pdf-file/_index.md index 682ce8ec3..85d7f19fa 100644 --- a/ru/python-net/advanced-operations/working-with-images/replace-image-in-existing-pdf-file/_index.md +++ b/ru/python-net/advanced-operations/working-with-images/replace-image-in-existing-pdf-file/_index.md @@ -11,7 +11,7 @@ AlternativeHeadline: Заменяйте изображения в существ Abstract: В этой статье показано, как заменять изображения в PDF‑документах с помощью Aspose.PDF for Python via .NET. Описывается замена изображения по индексу ресурса и замена конкретного найденного изображения с помощью ImagePlacementAbsorber. --- -## Заменить изображение в PDF +## Замена изображение в PDF Используйте эту страницу, когда нужно обновить логотипы, схемы или другие встроенные графические элементы в PDF без пересборки макета документа. @@ -34,7 +34,7 @@ def replace_image(infile, image_file, outfile): document.save(outfile) ``` -## Заменить конкретное изображение +## Замена конкретное изображение Этот пример заменяет конкретное расположение изображения, найденное `ImagePlacementAbsorber`. diff --git a/ru/python-net/advanced-operations/working-with-images/search-and-get-images-from-pdf-document/_index.md b/ru/python-net/advanced-operations/working-with-images/search-and-get-images-from-pdf-document/_index.md index 07f69db9a..7e626344d 100644 --- a/ru/python-net/advanced-operations/working-with-images/search-and-get-images-from-pdf-document/_index.md +++ b/ru/python-net/advanced-operations/working-with-images/search-and-get-images-from-pdf-document/_index.md @@ -110,7 +110,7 @@ def extract_image_types_from_pdf(infile): print("RGB Images = " + str(rgb)) ``` -## Извлечь подробную информацию об изображениях из PDF +## Извлечение подробной информации об изображениях из PDF Эта функция анализирует все изображения на первой странице PDF и вычисляет их масштабированные размеры и эффективное разрешение на основе графических преобразований страницы. diff --git a/ru/python-net/advanced-operations/working-with-layers/_index.md b/ru/python-net/advanced-operations/working-with-layers/_index.md index 920ebe393..415d6dc15 100644 --- a/ru/python-net/advanced-operations/working-with-layers/_index.md +++ b/ru/python-net/advanced-operations/working-with-layers/_index.md @@ -24,7 +24,7 @@ Abstract: В этой статье объясняется, как работат - Сведите многослойное содержимое в страницу. - Объедините несколько слоёв в один слой. -## Добавить слои в PDF +## Добавление слои в PDF Этот пример создает PDF с тремя уровнями. Он использует [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/), добавляет a [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/), и добавляет [`Layer`](https://reference.aspose.com/pdf/python-net/aspose.pdf/layer/) объекты к этой странице. @@ -107,7 +107,7 @@ def lock_layer(infile: str, outfile: str) -> None: print("No layers found in the document.") ``` -## Извлечь элементы слоя PDF +## Извлечение элементы слоя PDF В этом примере используется библиотека Aspose.PDF for Python via .NET для извлечения отдельных слоёв с первой страницы PDF‑документа и сохранения каждого слоя в отдельный PDF‑файл с помощью [`Layer.save()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/layer/#methods). @@ -185,7 +185,7 @@ def flatten_layers(infile: str, outfile: str) -> None: print(f"Layers flattened successfully. File saved at {outfile}") ``` -## Объединить все слои в PDF в один +## Объединение все слои в PDF в один Этот фрагмент кода использует Aspose.PDF для объединения всех слоёв на первой странице PDF в один единый слой с пользовательским именем, используя [`Page.merge_layers()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods). diff --git a/ru/python-net/advanced-operations/working-with-operators/_index.md b/ru/python-net/advanced-operations/working-with-operators/_index.md index c4af26b4c..f935ce054 100644 --- a/ru/python-net/advanced-operations/working-with-operators/_index.md +++ b/ru/python-net/advanced-operations/working-with-operators/_index.md @@ -22,7 +22,7 @@ Abstract: В этой статье объясняется, как работат Используйте эту страницу, когда вам нужен прямой контроль над потоками содержимого PDF в Python, например размещение графики в точных координатах, оборачивание изменений состояния графики или удаление конкретных операторов рисования со страницы. -## Добавить изображения с Operator Classes +## Добавление изображения с Operator Classes Используйте низкоуровневые классы операторов, когда необходимо разместить графическое содержимое изображения с высокой точностью в потоке страницы PDF, не полагаясь на высокоуровневые абстракции макета. diff --git a/ru/python-net/advanced-operations/working-with-pages/add-pages/_index.md b/ru/python-net/advanced-operations/working-with-pages/add-pages/_index.md index ae743ff46..99a6a6143 100644 --- a/ru/python-net/advanced-operations/working-with-pages/add-pages/_index.md +++ b/ru/python-net/advanced-operations/working-with-pages/add-pages/_index.md @@ -18,11 +18,11 @@ Aspose.PDF for Python via .NET предоставляет гибкие опер Используйте эту страницу, когда необходимо вставить новые пустые страницы в существующий PDF или добавить страницы в конец Document во время рабочих процессов генерации. -## Добавить или вставить страницы в PDF-файл +## Добавление или вставить страницы в PDF-файл Aspose.PDF for Python via .NET поддерживает как вставку страниц по указанному индексу, так и добавление страниц в конец PDF. -### Вставить пустую страницу в PDF‑файл +### Вставка пустую страницу в PDF‑файл Чтобы вставить пустую страницу в PDF‑файл: @@ -41,7 +41,7 @@ def insert_empty_page(input_file_name: str, output_file_name: str) -> None: document.save(output_file_name) ``` -### Добавить пустую страницу в конец PDF‑файла +### Добавление пустую страницу в конец PDF‑файла Иногда вы хотите убедиться, что документ заканчивается пустой страницей. Эта тема объясняет, как вставить пустую страницу в конец PDF‑документа. @@ -62,7 +62,7 @@ def add_empty_page_to_end(input_file_name: str, output_file_name: str) -> None: document.save(output_file_name) ``` -### Добавить страницу из другого PDF‑документа +### Добавление страницу из другого PDF‑документа С помощью Aspose.PDF for Python via .NET вы можете создать новый [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/), добавить начальную страницу, а затем импортировать страницу из другого PDF в неё. diff --git a/ru/python-net/advanced-operations/working-with-pages/change-page-size/_index.md b/ru/python-net/advanced-operations/working-with-pages/change-page-size/_index.md index 6d706bf85..6146df5b3 100644 --- a/ru/python-net/advanced-operations/working-with-pages/change-page-size/_index.md +++ b/ru/python-net/advanced-operations/working-with-pages/change-page-size/_index.md @@ -67,7 +67,7 @@ def set_page_size(input_file_name, output_file_name): document.save(output_file_name) ``` -## Получить размер страницы PDF +## Получение размер страницы PDF Этот фрагмент кода читает PDF и получает размеры (ширину и высоту) первой страницы. Он использует [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) API для извлечения границ страницы [`Rectangle`](https://reference.aspose.com/pdf/python-net/aspose.pdf/rectangle/) и выводит его размер в консоль. Это полезно для просмотра макета страницы, проверки форматов или подготовки документов к дальнейшей обработке. @@ -91,7 +91,7 @@ def get_page_size(input_file_name, output_file_name): print(f"{rectangle.width} : {rectangle.height}") ``` -### Получить размер страницы PDF до и после поворота +### Получение размер страницы PDF до и после поворота Получите размеры страницы PDF до и после применения поворота на 90°. Это демонстрирует, как поворот влияет на ширину и высоту и как использовать `get_page_rect()` с учётом или без учёта вращения. diff --git a/ru/python-net/advanced-operations/working-with-pages/crop-pages/_index.md b/ru/python-net/advanced-operations/working-with-pages/crop-pages/_index.md index 9281d7169..34d747cad 100644 --- a/ru/python-net/advanced-operations/working-with-pages/crop-pages/_index.md +++ b/ru/python-net/advanced-operations/working-with-pages/crop-pages/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Как получить доступ к свойствам Abstract: Статья предоставляет обзор того, как получить доступ к свойствам страниц и изменить их в PDF‑документе с использованием Aspose.PDF for Python. В ней описываются несколько свойств страниц, включая media box, bleed box, trim box, art box и crop box, с объяснением их роли в определении размеров и границ страницы PDF для печати и отображения. Media box представляет собой наибольший размер страницы, тогда как bleed box обеспечивает покрытие чернилами за пределами края страницы для обрезки. Trim box определяет окончательный размер документа после обрезки, а art box охватывает фактическое содержимое страницы. Crop box задаёт видимую область в Adobe Acrobat. В статье приведён фрагмент кода на Python, демонстрирующий, как установить новый crop box вместе с другими ограничителями для конкретной страницы в PDF‑документе. Визуальные примеры показывают вид страницы до и после применения обрезки, демонстрируя практическое применение изменения этих свойств. --- -## Получить свойства страниц +## Получение свойства страниц Каждая страница в PDF-файле имеет ряд свойств, таких как ширина, высота, поля обрезки, поля кадрирования и обрезки. Aspose.PDF для Python позволяет получить доступ к этим свойствам. diff --git a/ru/python-net/advanced-operations/working-with-pages/delete-pages/_index.md b/ru/python-net/advanced-operations/working-with-pages/delete-pages/_index.md index 72f02c1e7..82e762483 100644 --- a/ru/python-net/advanced-operations/working-with-pages/delete-pages/_index.md +++ b/ru/python-net/advanced-operations/working-with-pages/delete-pages/_index.md @@ -18,7 +18,7 @@ Abstract: В этой статье объясняется, как удалять Используйте этот рабочий процесс, когда вам нужно удалить ненужные страницы из PDF перед передачей, архивированием или объединением документов. -## Удалить страницу из PDF-файла +## Удаление страницу из PDF-файла Aspose.PDF for Python via .NET удаляет страницу 2 из входного PDF и сохраняет обновленный документ в новый файл. Эта функция полезна для удаления ненужных или конфиденциальных страниц без изменения остальной части документа. @@ -37,7 +37,7 @@ def delete_page(input_file_name: str, output_file_name: str) -> None: document.save(output_file_name) ``` -## Удалить несколько страниц из PDF‑документа +## Удаление несколько страниц из PDF‑документа Удаление нескольких страниц позволяет удалить набор указанных страниц за одну операцию, что эффективнее, чем удалять страницы по одной. Полученный PDF сохраняется в новый файл, при этом оригинальный документ сохраняется. diff --git a/ru/python-net/advanced-operations/working-with-pages/get-and-set-page-properties/_index.md b/ru/python-net/advanced-operations/working-with-pages/get-and-set-page-properties/_index.md index cb0a39c65..b08d8fabf 100644 --- a/ru/python-net/advanced-operations/working-with-pages/get-and-set-page-properties/_index.md +++ b/ru/python-net/advanced-operations/working-with-pages/get-and-set-page-properties/_index.md @@ -18,7 +18,7 @@ Aspose.PDF for Python via .NET позволяет читать и устанав Используйте это руководство, когда вам необходимо просмотреть метаданные страницы, определить количество страниц или обновить характеристики на уровне страницы в рамках анализа или нормализации документов. -## Получить количество страниц в PDF‑файле +## Получение количество страниц в PDF‑файле При работе с документами часто хочется знать, сколько страниц они содержат. С Aspose.PDF это занимает не более двух строк кода. @@ -42,7 +42,7 @@ def get_page_count(input_file_name): print("Page Count:", str(len(document.pages))) ``` -### Получить количество страниц без сохранения документа +### Получение количество страниц без сохранения документа Иногда мы генерируем PDF‑файлы «на лету», и во время создания PDF‑файла мы можем столкнуться с требованием (создание оглавления и т.д.) получить количество страниц PDF‑файла без сохранения файла в системе или потоке. Поэтому, чтобы удовлетворить это требование, метод [process_paragraphs()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) было введено в классе Document. Пожалуйста, ознакомьтесь со следующим фрагментом кода, который показывает шаги для получения количества страниц без сохранения документа. @@ -66,7 +66,7 @@ def get_page_count_without_saving(input_file_name): print("Number of pages in document =", str(len(document.pages))) ``` -## Получить свойства страниц +## Получение свойства страниц Каждая страница в файле PDF имеет ряд свойств, таких как ширина, высота, bleed-, crop- и trimbox. Aspose.PDF позволяет получить доступ к этим свойствам. diff --git a/ru/python-net/advanced-operations/working-with-pages/move-pages/_index.md b/ru/python-net/advanced-operations/working-with-pages/move-pages/_index.md index 7f12d7d53..3c6229eb9 100644 --- a/ru/python-net/advanced-operations/working-with-pages/move-pages/_index.md +++ b/ru/python-net/advanced-operations/working-with-pages/move-pages/_index.md @@ -76,7 +76,7 @@ def move_multiple_pages_from_one_document_to_another( src_document.save(input_file_name.replace(".pdf", "_new.pdf")) ``` -## Переместить страницу в новое место в том же PDF Document +## Перемещение страницы в новое место в том же PDF-документе Показано, как переместить определённую страницу в другое положение внутри того же документа — распространённая необходимость при реорганизации или редактировании макетов PDF. diff --git a/ru/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md b/ru/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md index 8a3ca18f9..353882046 100644 --- a/ru/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md +++ b/ru/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md @@ -18,7 +18,7 @@ Abstract: В этой статье представлено руководств Используйте эту страницу, когда нужно переключать страницы между портретной и альбомной ориентацией или применять углы поворота к существующему PDF‑контенту. -## Изменить ориентацию страницы +## Изменение ориентацию страницы Эта функция вращает каждую страницу PDF [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) на 90 градусов по часовой стрелке с помощью Aspose.PDF for Python. Это полезно для исправления проблем с ориентацией страниц, например сканированных документов, расположенных боком. Исходный PDF остаётся неизменным, а повернутая версия сохраняется как новый файл. diff --git a/ru/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/_index.md b/ru/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/_index.md index 23297d8f7..41385f21b 100644 --- a/ru/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/_index.md +++ b/ru/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/_index.md @@ -597,7 +597,7 @@ def add_latex_fragments(outfile: str) -> None: ## Расширенные возможности таблиц -### Вставить автоматические разрывы страниц в таблице PDF +### Вставка автоматических разрывов страниц в таблице PDF Создайте большую таблицу в PDF, используя Python и Aspose.PDF, с автоматическими разрывами страниц после определённого количества строк. Он формирует многострочную таблицу, применяет границы и принудительно размещает выбранные строки на новой странице для лучшего контроля макета. @@ -790,7 +790,7 @@ def add_repeating_columns(outfile: str) -> None: document.save(outfile) ``` -### Создать таблицу PDF с ячейками, содержащими повернутый текст +### Создание таблицы PDF с ячейками, содержащими повернутый текст Создайте таблицу в PDF с помощью Python и Aspose.PDF, где текст в каждой ячейке повёрнут под разными углами. Это полезно для вертикальных заголовков, креативных макетов, компактных таблиц и пользовательского форматирования отчётов. @@ -833,7 +833,7 @@ def rotated_text_table(outfile: str) -> None: document.save(outfile) ``` -## Связанные темы таблицы +## Связанные темы таблиц - [Работа с таблицами в PDF с использованием Python](/pdf/ru/python-net/working-with-tables/) - [Извлекать таблицы из PDF‑документов](/pdf/ru/python-net/extracting-table/) diff --git a/ru/python-net/advanced-operations/working-with-tables/extract-table-from-existing-pdf-document/_index.md b/ru/python-net/advanced-operations/working-with-tables/extract-table-from-existing-pdf-document/_index.md index b858fa7a2..50d593911 100644 --- a/ru/python-net/advanced-operations/working-with-tables/extract-table-from-existing-pdf-document/_index.md +++ b/ru/python-net/advanced-operations/working-with-tables/extract-table-from-existing-pdf-document/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Как извлечь таблицу из PDF с помощ Abstract: В этой статье рассматривается процесс извлечения таблиц из PDF‑документов с помощью Python, с особым использованием библиотеки Aspose.PDF for Python via .NET. Приводится пример кода, демонстрирующий, как загрузить PDF‑документ, пройтись по его страницам и использовать класс `TableAbsorber` для идентификации и извлечения данных таблицы. Код проходит по каждой таблице, строке и ячейке, собирает фрагменты текста и выводит извлечённый текст. Этот метод отмечен как мощный инструмент для задач извлечения и анализа данных, связанных с табличными данными в PDF. --- -## Извлечь таблицу из PDF +## Извлечение таблицы из PDF Извлечение таблиц из PDF с помощью Python может быть чрезвычайно полезным для извлечения и анализа данных. С библиотекой Aspose.PDF for Python via .NET вы можете эффективно работать с таблицами, встроенными в PDF‑документы, для различных задач, связанных с данными. @@ -56,7 +56,7 @@ def extract(infile: str) -> None: print(row_txt) ``` -## Связанные темы таблицы +## Связанные темы таблиц - [Работа с таблицами в PDF с использованием Python](/pdf/ru/python-net/working-with-tables/) - [Добавить таблицы в PDF с помощью Python](/pdf/ru/python-net/adding-tables/) diff --git a/ru/python-net/advanced-operations/working-with-tables/integrate-table-in-existing-pdf-document/_index.md b/ru/python-net/advanced-operations/working-with-tables/integrate-table-in-existing-pdf-document/_index.md index abae82a35..71cd45a99 100644 --- a/ru/python-net/advanced-operations/working-with-tables/integrate-table-in-existing-pdf-document/_index.md +++ b/ru/python-net/advanced-operations/working-with-tables/integrate-table-in-existing-pdf-document/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Интегрировать PDF‑таблицы с база Abstract: В этой статье объясняется, как интегрировать PDF‑таблицы с внешними источниками данных с использованием Aspose.PDF for Python via .NET. Узнайте, как создавать PDF‑таблицы из pandas DataFrames и других структурированных источников, вставлять их в документы и управлять потоками таблиц при рендеринге на несколько страниц PDF в Python. --- -## Создать PDF из DataFrame +## Создание PDF из DataFrame Функция 'create_pdf_from_dataframe' принимает DataFrame и преобразует его в таблицу внутри нового PDF. Она создаёт новый PDF‑документ, добавляет страницу, генерирует таблицу из DataFrame (используя вспомогательный метод) и сохраняет результат по указанному пути к файлу. И это не только возможно, но и очень просто. @@ -47,7 +47,7 @@ def create_pdf_from_dataframe( document.save(outfile) ``` -## Создать таблицу из DataFrame +## Создание таблицы из DataFrame Этот код преобразует DataFrame в объект Table библиотеки Aspose.PDF. Он настраивает границы таблицы, добавляет строку заголовка с именами столбцов и заполняет таблицу первыми max_rows строками из DataFrame. Полученная Table затем можно добавить в PDF‑документ. @@ -93,7 +93,7 @@ def create_table_from_dataframe(df: pd.DataFrame, max_rows: int = 20) -> ap.Tabl return table ``` -## Связанные темы таблицы +## Связанные темы таблиц - [Работа с таблицами в PDF с использованием Python](/pdf/ru/python-net/working-with-tables/) - [Добавить таблицы в PDF с помощью Python](/pdf/ru/python-net/adding-tables/) diff --git a/ru/python-net/advanced-operations/working-with-tables/manipulate-tables-in-existing-pdf/_index.md b/ru/python-net/advanced-operations/working-with-tables/manipulate-tables-in-existing-pdf/_index.md index 018636359..80bbc62bf 100644 --- a/ru/python-net/advanced-operations/working-with-tables/manipulate-tables-in-existing-pdf/_index.md +++ b/ru/python-net/advanced-operations/working-with-tables/manipulate-tables-in-existing-pdf/_index.md @@ -59,7 +59,7 @@ def replace_cell_text(infile: str, outfile: str) -> None: document.save(outfile) ``` -## Заменить существующую таблицу новой таблицей +## Замена существующую таблицу новой таблицей Вы также можете заменить обнаруженную таблицу вновь созданной. Этот подход полезен, когда необходимо изменить и структуру, и содержание. diff --git a/ru/python-net/advanced-operations/working-with-tables/remove-tables-from-existing-pdf/_index.md b/ru/python-net/advanced-operations/working-with-tables/remove-tables-from-existing-pdf/_index.md index b64bc86c8..71c295cee 100644 --- a/ru/python-net/advanced-operations/working-with-tables/remove-tables-from-existing-pdf/_index.md +++ b/ru/python-net/advanced-operations/working-with-tables/remove-tables-from-existing-pdf/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Как удалить таблицы из PDF с помощ Abstract: В этой статье рассматривается функциональность Aspose.PDF for Python via .NET, с особым акцентом на работу с таблицами в PDF‑документах. Библиотека позволяет пользователям вставлять или создавать таблицы как в новых, так и в существующих PDF‑файлах, а также манипулировать и удалять таблицы из существующих PDF. В статье представляется класс `TableAbsorber`, который играет ключевую роль в идентификации и взаимодействии с таблицами в PDF. Добавлен новый метод `remove()`, позволяющий удалять таблицы. Документ содержит два фрагмента кода — один, демонстрирующий удаление одной таблицы из PDF, и второй, показывающий удаление множества таблиц. Эти примеры подчёркивают практическое применение класса `TableAbsorber` для удаления таблиц из PDF‑документов. --- -## Удалить таблицу из PDF‑документа +## Удаление таблицу из PDF‑документа Aspose.PDF for Python позволяет удалить таблицу из PDF. Он открывает существующий PDF, обнаруживает первую таблицу на первой странице с помощью TableAbsorber, удаляет эту таблицу, используя [remove_one_table](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/#methods). После сохранения обновлённого PDF в новый файл. @@ -41,7 +41,7 @@ def remove_one_table(infile: str, outfile: str) -> None: document.save(outfile) ``` -## Удалить все таблицы из PDF‑документа +## Удаление все таблицы из PDF‑документа С помощью нашей библиотеки вы можете удалить все таблицы с конкретной страницы в PDF. Код открывает существующий PDF, обнаруживает все таблицы на второй странице с помощью TableAbsorber, перебирает обнаруженные таблицы, удаляет каждую из них и затем сохраняет изменённый PDF в новый файл. Это полезно, когда необходимо массово удалить таблицы со страницы, оставив остальное содержание PDF нетронутым. diff --git a/ru/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/_index.md b/ru/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/_index.md index 0361527bd..8d40f1967 100644 --- a/ru/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/_index.md +++ b/ru/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/_index.md @@ -23,7 +23,7 @@ Abstract: Эта статья предоставляет всеобъемлющ Aspose.PDF for Python via .NET предоставляет мощный и гибкий API для обработки текста в PDF-файлах. Независимо от того, нужны ли вам простые статические метки, богато отформатированный контент, многоязычный текст или интерактивные гиперссылки, набор инструментов позволяет сделать всё это с помощью лаконичного кода на Python. -### Добавить текст простой пример +### Добавление текста: простой пример Aspose.PDF for Python via .NET показывает, как добавить простой фрагмент текста в определённое положение на странице. Вы узнаете, как создать новый PDF‑документ, добавить страницу, вставить текст в заданных координатах и сохранить полученный файл. @@ -65,7 +65,7 @@ TextParagraph также управляет выравниванием текс Для получения дополнительной информации о Working with Text, пожалуйста, проверьте [Форматирование текста в PDF](/pdf/ru/python-net/text-formatting-inside-pdf/) и [Извлечение текста из PDF с помощью Python](/pdf/ru/python-net/extract-text-from-pdf/) разделы документации. -### Добавить текст с помощью TextParagraph +### Добавление текста с помощью TextParagraph Aspose.PDF for Python via .NET может добавить абзац текста, используя [`TextBuilder`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textbuilder/) и [`TextParagraph`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textparagraph/) с параметрами обтекания. @@ -115,7 +115,7 @@ def add_paragraph(output_file_name): ![Добавить текст с помощью TextParagraph](text_paragraph.png) -### Добавить абзацы с отступами в PDF +### Добавление абзацы с отступами в PDF Следующий фрагмент кода показывает, как создать новый PDF‑документ и добавить два абзаца текста с разными стилями отступов: @@ -168,7 +168,7 @@ def add_paragraphs_indents(output_file_name): document.save(output_file_name) ``` -### Добавить новую строку текста в PDF +### Добавление новую строку текста в PDF Aspose.PDF for Python via .NET позволяет вставлять многострочный текст в PDF‑документ, используя классы TextFragment, TextParagraph и TextBuilder. @@ -308,7 +308,7 @@ def get_text_width_dynamically(output_file): c_code += 1 ``` -### Добавить текст с гиперссылками +### Добавление текста с гиперссылками Добавьте кликабельные гиперссылки в текст PDF с использованием Aspose.PDF for Python via .NET. Наша библиотека демонстрирует, как добавить несколько текстовых сегментов внутри одного TextFragment и применить гиперссылку к конкретному сегменту, а также стилизовать текстовые сегменты индивидуально (например, цвет, курсивный шрифт). @@ -350,7 +350,7 @@ def add_text_with_hyperlink(output_file_name): ![Текстовый фрагмент, отображённый в PDF, показывающий смешанное содержание с Sample Text Fragment, за которым следует Text Segment 1, затем синяя гиперссылка с надписью Link to Aspose (ссылка на https://products.aspose.com/pdf), и заканчивается TextSegment без гиперссылки в обычном черном форматировании текста](hyperlink_text.png) -### Добавить текст справа налево (RTL) в PDF‑документ +### Добавление текста справа налево (RTL) в PDF‑документ RTL (от Right To Left) — это свойство, указывающее направление написания текста, при котором текст пишется справа налево. Aspose.PDF for Python via .NET демонстрирует, как добавить текст справа налево (RTL), например арабский или иврит, в PDF‑документ. @@ -388,7 +388,7 @@ def add_text_with_rtl_text(output_file_name): ## Стилизация текста -### Добавить текст со стилизацией шрифта +### Добавление текста со стилизацией шрифта Это более продвинутый пример, демонстрирующий стилизацию текста, настройку шрифтов и смешанный формат текста (используя субскриптные сегменты). Aspose.PDF объясняет, как применять свойства шрифта, такие как семейство шрифта, размер, цвет, полужирный, курсив и подчеркивание, к фрагменту текста. Кроме того, этот фрагмент кода демонстрирует, как использовать несколько текстовых сегментов в одном фрагменте для создания сложных текстовых выражений — например, включающих символы нижнего или верхнего индекса, часто требуемые в формулах или научных обозначениях. @@ -464,7 +464,7 @@ def add_text_with_font_styling(output_file_name): ![Текстовый фрагмент отображается с синим курсивным шрифтом Arial, содержащим текст Hello, Aspose! за которым следует математическая формула, показывающая S = a subscript 2n + a subscript 2n+1 + a subscript 2n+2, при этом основной текст синего цвета, а подстрочный — красного цвета.](styled_text.png) -## Добавить прозрачный текст +## Добавление прозрачного текста Добавьте полупрозрачные фигуры и текст в PDF-документ, используя Aspose.PDF for Python. Он создает цветной прямоугольник с частичной непрозрачностью и накладывает TextFragment с прозрачным цветом переднего плана. @@ -513,7 +513,7 @@ def add_text_transparent(output_file_name): document.save(output_file_name) ``` -### Добавить невидимый текст в PDF +### Добавление невидимого текста в PDF В этом примере показано, как создать PDF‑документ, содержащий как видимый, так и невидимый текст. Невидимый текст остаётся частью структуры документа, но скрыт от просмотра, что делает его полезным для встраивания метаданных, тегов доступности или поискового контента без изменения макета. @@ -551,7 +551,7 @@ def add_text_invisible(output_file_name): document.save(output_file_name) ``` -### Добавить текст с оформлением границы в PDF +### Добавление текста с оформлением границы в PDF Библиотека Aspose.PDF показывает, как создать PDF‑документ, содержащий стилизованный фрагмент текста с видимой границей. Метод применяет цвета фона и переднего плана, настройки шрифта и обводку (границу) вокруг прямоугольника текста для усиления визуального акцента. @@ -595,7 +595,7 @@ def add_text_border(output_file_name): document.save(output_file_name) ``` -### Добавить перечёркнутый текст в PDF +### Добавление перечёркнутого текста в PDF Добавьте форматирование зачеркивания (strikeout) к фрагменту текста в PDF‑документе. Зачеркнутый текст полезен для указания удалений, исправлений или акцента в аннотированных документах. @@ -717,7 +717,7 @@ def apply_gradient_radial_shading_to_text(output_file_name): ## HTML и LaTeX фрагменты -### Добавить HTML-текст в PDF-документ +### Добавление HTML-текст в PDF-документ Библиотека Aspose.PDF for Python via .NET позволяет вставлять контент в формате HTML в PDF‑документ с помощью класса HtmlFragment. Используя HTML‑теги, вы можете отобразить стилизованный, структурированный или похожий на формулу текст непосредственно в PDF. @@ -779,7 +779,7 @@ def add_html_fragment(output_file_name): ![Добавить HTML‑контент в PDF‑документ](html_content.png) -### Добавить HTML‑фрагмент с переопределённым состоянием текста +### Добавление HTML‑фрагмент с переопределённым состоянием текста Как мы видели в предыдущем примере, можно задавать стили непосредственно в HTML‑коде. Это имеет свои преимущества, но и некоторые недостатки. Предположим, мы работаем с HTML клиента и хотим унифицировать внешний вид нашего вывода. В этом случае мы можем переопределить стилизацию клиента, используя наш собственный TextState, как показано в следующем примере. @@ -818,7 +818,7 @@ def add_html_fragment_override_text_state(output_file_name): ![Добавить состояние переопределения текста HTML‑фрагмента](html_override.png) -### Добавить LaTeX-текст в PDF Document +### Добавление LaTeX-текста в PDF-документ Добавьте математические выражения в формате LaTeX в PDF‑документ, используя класс TeXFragment в Aspose.PDF for Python via .NET. LaTeX — мощная система наборa, широко используемая для создания научных и математических документов. С помощью TeXFragment вы можете напрямую отображать математические обозначения и символы LaTeX внутри страницы PDF. @@ -852,7 +852,7 @@ def add_text_latex_fragment(output_file_name): ## Пользовательские шрифты -### Использовать пользовательский Font из файла +### Использование пользовательского Font из файла Этот пример позволяет добавить текст в PDF‑файл, используя пользовательский шрифт OpenType в Aspose.PDF for Python via .NET. Он показывает, как создать новый PDF‑документ, точно позиционировать текст на странице и применить пользовательское форматирование, такое как тип шрифта, размер, цвет и курсивный стиль. @@ -888,7 +888,7 @@ def use_custom_font_from_file(output_file_name): ![Фрагмент текста, отображаемый в документе PDF, показывающий Hello, Aspose! отображённый синим курсивным шрифтом BriosoPro, демонстрирующий интеграцию пользовательского шрифта OpenType и возможности стилизации в форматировании текста PDF.](custom_font.png) -### Использовать пользовательский Font из потока +### Использование пользовательского Font из потока Этот фрагмент кода демонстрирует, как добавить текст в PDF‑документ, используя пользовательский встроенный шрифт OpenType (OTF) с Aspose.PDF for Python via .NET. Он показывает, как открыть файл шрифта как поток, встроить его в PDF, чтобы обеспечить доступность шрифта на разных системах, и применить форматирование текста, такое как размер шрифта, цвет и курсивный стиль. Такой подход идеален для создания визуально согласованных PDF‑файлов, сохраняющих типографику даже при совместном использовании или просмотре на устройствах без установленного шрифта. diff --git a/ru/python-net/advanced-operations/working-with-text/add-tooltip-to-text/_index.md b/ru/python-net/advanced-operations/working-with-text/add-tooltip-to-text/_index.md index c91a3c1d0..6b1313c16 100644 --- a/ru/python-net/advanced-operations/working-with-text/add-tooltip-to-text/_index.md +++ b/ru/python-net/advanced-operations/working-with-text/add-tooltip-to-text/_index.md @@ -15,7 +15,7 @@ Abstract: > В этой статье представлены два примера кода на Python для улучшения интерактивности PDF‑документов с использованием библиотеки Aspose.PDF. Первый пример демонстрирует, как добавить всплывающие подсказки к отдельным фрагментам текста в PDF, создавая невидимые элементы ButtonField над текстом и устанавливая свойство `alternate_name` в качестве подсказки. Второй пример показывает, как создать плавающие текстовые блоки, которые становятся видимыми при наведении: когда находится `TextFragment`, в его позиции создаётся скрытый `TextBoxField`, а к невидимому `ButtonField` привязываются события `HideAction` для отображения или скрытия плавающего блока. --- -## Добавить всплывающую подсказку к найденному тексту в PDF +## Добавление всплывающую подсказку к найденному тексту в PDF Этот фрагмент кода показывает, как наложить невидимый [`ButtonField`](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/buttonfield/) элементы на конкретных [`TextFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/) объекты в PDF для отображения всплывающих подсказок, когда пользователь наводит курсор на них. Он поддерживает как короткие, так и длинные сообщения всплывающих подсказок, используя `alternate_name` свойство `ButtonField`. @@ -96,7 +96,7 @@ def add_tool_tip_to_searched_text(outfile): document.save(outfile) ``` -## Создать скрытый текстовый блок, который появляется при наведении в PDF +## Создание скрытого текстового блока, который появляется при наведении в PDF Добавить интерактивный плавающий текст в документ PDF. Он накладывается как невидимый [`ButtonField`](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/buttonfield/) на целевой фразе и раскрывает скрытый [`TextBoxField`](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/textboxfield/) когда пользователь наводит на него курсор. Эта техника идеальна для контекстной помощи, аннотаций или динамического представления контента. diff --git a/ru/python-net/advanced-operations/working-with-text/replace-text-an-a-pdf/_index.md b/ru/python-net/advanced-operations/working-with-text/replace-text-an-a-pdf/_index.md index 59f5501ab..8deec534f 100644 --- a/ru/python-net/advanced-operations/working-with-text/replace-text-an-a-pdf/_index.md +++ b/ru/python-net/advanced-operations/working-with-text/replace-text-an-a-pdf/_index.md @@ -20,9 +20,9 @@ Abstract: Статья представляет собой исчерпываю Используйте эту страницу, когда вам нужно обновить значения текста, удалить нежелательный контент или применить правила замены текста на страницах PDF. -## Заменить существующий текст +## Замена существующего текста -### Заменить текст на всех страницах PDF‑документа +### Замена текст на всех страницах PDF‑документа {{% alert color="primary" %}} @@ -62,7 +62,7 @@ def replace_text_on_all_pages(infile, outfile): document.save(outfile) ``` -### Заменить текст в определённой области страницы +### Замена текст в определённой области страницы Иногда вам может понадобиться заменять текст только в определённой области страницы PDF, а не искать по всему документу — например, обновлять заголовок, нижний колонтитул или ячейку таблицы в известной позиции. @@ -99,7 +99,7 @@ def replace_text_in_particular_page_region(infile, outfile): document.save(outfile) ``` -### Изменить размер и сдвинуть текст без изменения размера шрифта +### Изменение размер и сдвинуть текст без изменения размера шрифта При замене текста в PDF иногда требуется вписать или переместить новый текст в определённую область, не изменяя размер шрифта. Aspose.PDF for Python via .NET предоставляет варианты настройки размещения текста и интервалов, при этом сохраняя исходный размер шрифта без изменений. @@ -134,7 +134,7 @@ def replace_text_and_resize_and_shift_without_changing_font_size(infile, outfile document.save(outfile) ``` -### Изменить размер и сдвинуть абзац в PDF +### Изменение размер и сдвинуть абзац в PDF При работе с PDF иногда нужно заменить или расширить абзац, при этом визуально выровнять его с макетом страницы. Aspose.PDF позволяет изменить размер ограничивающего прямоугольника абзаца и отрегулировать интервал, чтобы разместить новый текст, всё это без изменения размера шрифта. @@ -169,7 +169,7 @@ def replace_text_and_resize_and_shift_paragraph(infile, outfile): document.save(outfile) ``` -### Заменить текст и автоматически расширить шрифт, чтобы заполнить целевую область +### Замена текст и автоматически расширить шрифт, чтобы заполнить целевую область Замените текст в PDF, автоматически изменяя размер и расширяя шрифт, чтобы заполнить конкретную прямоугольную область. С помощью библиотеки Aspose.PDF for Python via .NET код динамически регулирует размер шрифта и интервалы, так чтобы новое текстовое содержимое идеально вписалось в определённый ограничивающий прямоугольник — без ручных вычислений шрифта. @@ -203,7 +203,7 @@ def replace_text_and_resize_and_expand_font(infile, outfile): document.save(outfile) ``` -### Заменить текст и вписать его в прямоугольник +### Замена текст и вписать его в прямоугольник Замените текст в PDF‑документе, при этом гарантируя, что новое содержание помещается в прямоугольную область оригинального текста, автоматически уменьшая размер шрифта при необходимости. @@ -274,7 +274,7 @@ def automatically_rearrange_page_contents(input_file, output_file): document.save(output_file) ``` -### Заменить текст на основе регулярного выражения +### Замена текст на основе регулярного выражения При работе с PDF‑документами может потребоваться заменить текст, соответствующий шаблону, а не конкретной фразе — например, номера телефонов, коды или форматы, похожие на даты. @@ -312,9 +312,9 @@ def replace_text_based_on_regex(infile, outfile): document.save(outfile) ``` -## Заменить шрифты или удалить неиспользуемые шрифты +## Замена шрифты или удалить неиспользуемые шрифты -### Заменить шрифты в существующем PDF файле +### Замена шрифты в существующем PDF файле Время от времени вам требуется стандартизировать или обновить шрифты в PDF — например, заменить устаревший или проприетарный шрифт на более доступный. Библиотека Aspose.PDF for Python via .NET позволяет программно обнаруживать и заменять шрифты, обеспечивая постоянство типографики и совместимость документа. @@ -345,7 +345,7 @@ def replace_fonts(infile, outfile): document.save(outfile) ``` -### Удалить неиспользуемые шрифты +### Удаление неиспользуемые шрифты Со временем PDF‑документы могут накапливать неиспользуемые или встроенные шрифты, которые увеличивают размер файла и замедляют обработку. Эти неиспользуемые шрифты часто остаются даже после редактирования или замены текста, особенно при работе с большими или сложными PDF. @@ -393,9 +393,9 @@ def remove_unused_fonts(input_file, output_file): document.save(output_file) ``` -## Удалить весь текст +## Удаление весь текст -### Удалить текст из PDF +### Удаление текст из PDF Удалите весь текстовый контент из PDF‑файла, сохранив изображения, фигуры и структуры макета нетронутыми. Используя TextFragmentAbsorber, код эффективно сканирует весь документ и удаляет каждый найденный на каждой странице фрагмент текста. @@ -417,7 +417,7 @@ def remove_all_text_using_absorber1(infile, outfile): document.save(outfile) ``` -### Удалить весь текст с конкретной страницы +### Удаление весь текст с конкретной страницы Удалить весь текст с одной страницы PDF‑документа с использованием класса TextFragmentAbsorber в Aspose.PDF. В отличие от полного удаления документа, этот метод выполняет очистку текста на уровне страниц, удаляя текст только с выбранной страницы, оставляя все остальные страницы нетронутыми. @@ -439,7 +439,7 @@ def remove_all_text_using_absorber2(infile, outfile): document.save(outfile) ``` -### Удалить весь текст из определённой области на странице PDF +### Удаление весь текст из определённой области на странице PDF Удалить весь текст из конкретного прямоугольного региона на странице с помощью TextFragmentAbsorber из Aspose.PDF. Вместо того чтобы очищать всю страницу, этот метод выполняет целенаправленное удаление текста, позволяя точно контролировать, какая часть страницы будет затронута. @@ -465,7 +465,7 @@ def remove_all_text_using_absorber3(infile, outfile): document.save(outfile) ``` -### Удалить весь скрытый текст из PDF‑документа +### Удаление весь скрытый текст из PDF‑документа Удалить весь текст из конкретного прямоугольного региона на странице с помощью TextFragmentAbsorber из Aspose.PDF. Вместо того чтобы очищать всю страницу, этот метод выполняет целенаправленное удаление текста, позволяя точно контролировать, какая часть страницы будет затронута. diff --git a/ru/python-net/advanced-operations/working-with-text/rotate-text-inside-pdf/_index.md b/ru/python-net/advanced-operations/working-with-text/rotate-text-inside-pdf/_index.md index 3f62fb740..8c4477f88 100644 --- a/ru/python-net/advanced-operations/working-with-text/rotate-text-inside-pdf/_index.md +++ b/ru/python-net/advanced-operations/working-with-text/rotate-text-inside-pdf/_index.md @@ -211,7 +211,7 @@ def rotate_text_inside_pdf_3(outfile): document.save(outfile) ``` -## Повернуть целые абзацы в PDF +## Поворот целые абзацы в PDF Наша библиотека демонстрирует продвинутый поворот текста на уровне абзацев в PDF. В отличие от поворота на уровне фрагментов (когда каждый фрагмент текста вращается отдельно), этот метод поворачивает целые абзацы как единые блоки под разными углами. Каждый абзац содержит несколько стилизованных текстовых фрагментов, а весь абзац вращается под определенными углами — позволяя выполнять сложные, согласованные преобразования макета. diff --git a/ru/python-net/basic-operations/opening/_index.md b/ru/python-net/basic-operations/opening/_index.md index 3ac7c0b1d..cb85713c1 100644 --- a/ru/python-net/basic-operations/opening/_index.md +++ b/ru/python-net/basic-operations/opening/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Открытие PDF‑документов с исполь Abstract: В этой статье представлено руководство по открытию существующих PDF‑документов с использованием библиотеки Aspose.PDF в Python. Описаны три способа достижения этого — открытие PDF путем указания имени файла, открытие PDF из потока и открытие зашифрованного PDF с предоставлением пароля. Каждый метод включает фрагмент кода, демонстрирующий, как использовать библиотеку Aspose.PDF для доступа к PDF и вывода количества страниц, которые он содержит. Эти примеры иллюстрируют гибкость и функциональность Aspose.PDF при работе с различными сценариями доступа к PDF‑файлам. --- -## Открыть существующий PDF‑документ +## Открытие существующего PDF‑документа Существует несколько способов открыть документ. Самый простой — указать имя файла. @@ -28,7 +28,7 @@ def open_document_from_file(infile): print("Pages: " + str(len(document.pages))) ``` -## Открыть существующий PDF документ из потока +## Открытие существующего PDF-документа из потока ```python import aspose.pdf as ap @@ -41,7 +41,7 @@ def open_document_from_stream(infile): print("Pages: " + str(len(document.pages))) ``` -## Открыть зашифрованный PDF‑документ +## Открытие зашифрованного PDF‑документа ```python import aspose.pdf as ap diff --git a/ru/python-net/basic-operations/protect/_index.md b/ru/python-net/basic-operations/protect/_index.md index 297ab3e8a..66c800fc9 100644 --- a/ru/python-net/basic-operations/protect/_index.md +++ b/ru/python-net/basic-operations/protect/_index.md @@ -142,7 +142,7 @@ def decrypt_pdf_file(infile, outfile): document.save(outfile) ``` -## Изменить пароль PDF-файла +## Изменение пароль PDF-файла Обновить учетные данные безопасности (пароли пользователя и владельца) PDF‑документа, сохраняя его содержимое и структуру. diff --git a/ru/python-net/basic-operations/saving/_index.md b/ru/python-net/basic-operations/saving/_index.md index 1a8e8c7c1..7f8dde73a 100644 --- a/ru/python-net/basic-operations/saving/_index.md +++ b/ru/python-net/basic-operations/saving/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Сохранение PDF‑документов с испо Abstract: Статья предоставляет рекомендации по сохранению PDF‑документов с использованием библиотеки Aspose.PDF в Python. В ней описываются три основных метода сохранения PDF — в файловую систему, в поток и в специфических форматах, таких как PDF/A или PDF/X. Метод `save()` класса `Document` является центральным для этих операций. Чтобы сохранить PDF в файловую систему, документ может быть создан или изменён, например, добавив новую страницу, и затем сохранён непосредственно по указанному пути. При сохранении в поток перегрузки метода `Save` позволяют записать документ в объект потока. Кроме того, статья объясняет, как сохранять документы в форматах PDF/A или PDF/X, которые являются стандартами для долгосрочного архивирования и обмена графикой соответственно. Этот процесс требует подготовки документа с помощью метода `convert` перед сохранением. Приведённые фрагменты кода на Python демонстрируют каждый подход, илстрируя практическое применение этих методов. --- -## Сохранить PDF-документ в файловую систему +## Сохранение PDF-документ в файловую систему Вы можете сохранить созданный или обработанный PDF-документ в файловую систему, используя [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) метод [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) класс. @@ -28,7 +28,7 @@ def save_document_to_file(infile, outfile): document.save(outfile) ``` -## Сохранить PDF-документ в поток +## Сохранение PDF-документ в поток Вы также можете сохранить созданный или изменённый PDF‑документ в поток, используя перегрузки `Save` методы. @@ -44,7 +44,7 @@ def save_document_to_stream(infile, outfile): document.save(stream) ``` -## Сохранить формат PDF/A или PDF/X +## Сохранение формат PDF/A или PDF/X Вы можете легко сохранить документ в конкретной версии PDF, например PDF/A или PDF/X. В этом случае нам нужно вызвать метод convert перед сохранением документа. diff --git a/ru/python-net/basic-operations/split-pdf/_index.md b/ru/python-net/basic-operations/split-pdf/_index.md index 5e0c42644..cd27ee9d9 100644 --- a/ru/python-net/basic-operations/split-pdf/_index.md +++ b/ru/python-net/basic-operations/split-pdf/_index.md @@ -30,7 +30,7 @@ Abstract: В статье рассматривается процесс разд 1. Для каждой итерации создайте новый объект Document и добавьте отдельные [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) объект в пустой документ 1. Сохраните новый PDF с помощью [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) метод -## Разделить PDF на несколько файлов или отдельные PDF в Python +## Разделение PDF на несколько файлов или отдельные PDF в Python Следующий фрагмент кода Python показывает, как разбить страницы PDF на отдельные PDF‑файлы. diff --git a/ru/python-net/converting/convert-html-to-pdf/_index.md b/ru/python-net/converting/convert-html-to-pdf/_index.md index 9061631a9..ebd73bad2 100644 --- a/ru/python-net/converting/convert-html-to-pdf/_index.md +++ b/ru/python-net/converting/convert-html-to-pdf/_index.md @@ -14,11 +14,11 @@ AlternativeHeadline: Как преобразовать HTML в PDF на Python Abstract: Эта статья объясняет, как преобразовать файлы HTML и MHTML в PDF с использованием Aspose.PDF for Python via .NET. Она охватывает базовый процесс преобразования HTML в PDF и показывает, как управлять рендерингом с помощью медиа‑типов, приоритета правил CSS page, встроенных шрифтов, вывода в один лист и генерации логической структуры для доступных помеченных PDF. --- -## Конвертация HTML в PDF с помощью Python +## Преобразование HTML в PDF с помощью Python **Aspose.PDF for Python via .NET** позволяет конвертировать существующие HTML‑документы в PDF с гибкими параметрами рендеринга. Вы можете точно настроить процесс создания вывода, чтобы он соответствовал вашим требованиям к макету, стилизации, доступности и архивированию. -## Преобразовать HTML в PDF +## Преобразование HTML в PDF Следующий пример на Python показывает основной рабочий процесс преобразования HTML‑документа в PDF. @@ -53,7 +53,7 @@ Aspose представляет онлайн‑приложение [HTML в PDF [![Aspose.PDF Конвертация HTML в PDF с помощью приложения](html.png)](https://products.aspose.app/html/en/conversion/html-to-pdf) {{% /alert %}} -## Конвертировать HTML в PDF, используя тип медиа +## Преобразование HTML в PDF с использованием типа медиа Этот пример показывает, как преобразовать HTML‑файл в PDF с использованием конкретных параметров рендеринга. @@ -97,7 +97,7 @@ def convert_HTML_to_PDF_priority_css_page_rule(infile, outfile): print(infile + " converted into " + outfile) ``` -## Конвертировать HTML в PDF с внедрёнными шрифтами +## Преобразование HTML в PDF с внедрёнными шрифтами Этот пример показывает, как преобразовать HTML‑файл в PDF с внедрением шрифтов. Если вам требуется, чтобы итоговый PDF сохранял оригинальную типографику, установите `is_embed_fonts` к `True`. @@ -141,7 +141,7 @@ def convert_HTML_to_PDF_render_content_to_same_page(infile, outfile): doc.save(outfile) ``` -## Преобразовать MHTML в PDF +## Преобразование MHTML в PDF В этом примере показано, как преобразовать файл MHT или MHTML в PDF документ, используя Aspose.PDF for Python via .NET, с конкретными размерами страниц. diff --git a/ru/python-net/converting/convert-images-format-to-pdf/_index.md b/ru/python-net/converting/convert-images-format-to-pdf/_index.md index de166217d..f90e01f98 100644 --- a/ru/python-net/converting/convert-images-format-to-pdf/_index.md +++ b/ru/python-net/converting/convert-images-format-to-pdf/_index.md @@ -24,7 +24,7 @@ Abstract: В этой статье представлено полное рук **Aspose.PDF for Python via .NET** позволяет конвертировать различные форматы изображений в PDF‑файлы. Наша библиотека демонстрирует примеры кода для преобразования самых популярных форматов изображений, таких как - BMP, CGM, DICOM, EMF, JPG, PNG, SVG и TIFF. -## Конвертировать BMP в PDF +## Преобразование BMP в PDF Преобразуйте BMP‑файлы в PDF‑документ с помощью библиотеки **Aspose.PDF for Python via .NET**. @@ -64,7 +64,7 @@ Aspose представляет вам онлайн‑приложение ["BMP [![Aspose.PDF Конвертация BMP в PDF с помощью App](bmp_to_pdf.png)](https://products.aspose.app/pdf/conversion/bmp-to-pdf/) {{% /alert %}} -## Преобразовать CGM в PDF +## Преобразование CGM в PDF Конвертировать CGM (Computer Graphics Metafile) в PDF (или другой поддерживаемый формат) с использованием Aspose.PDF for Python via .NET. @@ -92,7 +92,7 @@ def convert_CGM_to_PDF(infile, outfile): print(infile + " converted into " + outfile) ``` -## Преобразовать DICOM в PDF +## Преобразование DICOM в PDF DICOM format является отраслевым стандартом в медицинской индустрии для создания, хранения, передачи и визуализации цифровых медицинских изображений и документов обследуемых пациентов. @@ -156,7 +156,7 @@ Aspose представляет вам онлайн‑приложение ["DIC [![Aspose.PDF Конвертация DICOM в PDF с использованием приложения](dicom_to_pdf.png)](https://products.aspose.app/pdf/conversion/dicom-to-pdf/) {{% /alert %}} -## Преобразовать EMF в PDF +## Преобразование EMF в PDF EMF хранит графические изображения независимо от устройства. Метафайлы EMF состоят из записей переменной длины в хронологическом порядке, которые могут отобразить сохранённое изображение после разбора на любом выходном устройстве. @@ -188,7 +188,7 @@ Aspose представляет вам онлайн‑приложение ["EMF [![Aspose.PDF Преобразование EMF в PDF с помощью App](emf_to_pdf.png)](https://products.aspose.app/pdf/conversion/emf-to-pdf/) {{% /alert %}} -## Конвертировать GIF в PDF +## Преобразование GIF в PDF Конвертировать GIF‑файлы в PDF‑документ, используя библиотеку **Aspose.PDF for Python via .NET**. @@ -220,7 +220,7 @@ Aspose представляет вам онлайн‑приложение ["GIF [![Aspose.PDF Конвертация GIF в PDF с помощью App](bmp_to_pdf.png)](https://products.aspose.app/pdf/conversion/gif-to-pdf/) {{% /alert %}} -## Конвертировать PNG в PDF +## Преобразование PNG в PDF **Aspose.PDF for Python via .NET** поддерживает функцию конвертации PNG‑изображений в формат PDF. Посмотрите следующий фрагмент кода для выполнения вашей задачи. @@ -258,7 +258,7 @@ Aspose представляет вам онлайн‑приложение ["PNG [![Aspose.PDF Конвертация PNG в PDF с использованием приложения](png_to_pdf.png)](https://products.aspose.app/pdf/conversion/png-to-pdf/) {{% /alert %}} -## Конвертировать SVG в PDF +## Преобразование SVG в PDF **Aspose.PDF for Python via .NET** объясняет, как преобразовать изображения SVG в формат PDF и как получить размеры исходного файла SVG. @@ -289,7 +289,7 @@ def convert_SVG_to_PDF(infile, outfile): print(infile + " converted into " + outfile) ``` -## Конвертировать TIFF в PDF +## Преобразование TIFF в PDF **Aspose.PDF** поддерживается файловый формат, будь то однокадровое или многокадровое изображение TIFF. Это означает, что вы можете преобразовать изображение TIFF в PDF. @@ -312,7 +312,7 @@ def convert_TIFF_to_PDF(infile, outfile): print(infile + " converted into " + outfile) ``` -## Конвертировать CDR в PDF +## Преобразование CDR в PDF Следующий фрагмент кода показывает, как загрузить файл CorelDRAW (CDR) и сохранить его как PDF, используя 'CdrLoadOptions' в Aspose.PDF for Python via .NET. @@ -333,7 +333,7 @@ def convert_CDR_to_PDF(infile, outfile): print(infile + " converted into " + outfile) ``` -## Конвертировать JPEG в PDF +## Преобразование JPEG в PDF Этот пример показывает, как конвертировать JPEG в PDF‑файл с помощью Aspose.PDF for Python via .NET. diff --git a/ru/python-net/converting/convert-other-files-to-pdf/_index.md b/ru/python-net/converting/convert-other-files-to-pdf/_index.md index c9489412d..8c1daaff1 100644 --- a/ru/python-net/converting/convert-other-files-to-pdf/_index.md +++ b/ru/python-net/converting/convert-other-files-to-pdf/_index.md @@ -16,7 +16,7 @@ Abstract: В этой статье представлено всесторонн В этой статье объясняется, как **конвертировать различные типы файлов в PDF с использованием Python**. Она охватывает следующие темы. -## Преобразовать OFD в PDF +## Преобразование OFD в PDF OFD обозначает Open Fixed-layout Document (также называемый форматом Open Fixed Document). Это китайский национальный стандарт (GB/T 33190-2016) для электронных документов, представленный в качестве альтернативы PDF. @@ -39,7 +39,7 @@ def convert_OFD_to_PDF(infile, outfile): print(infile + " converted into " + outfile) ``` -## Конвертировать LaTeX/TeX в PDF +## Преобразование LaTeX/TeX в PDF Формат файла LaTeX — это текстовый формат файла с разметкой в производной LaTeX из семейства языков TeX, а LaTeX является производным форматом системы TeX. LaTeX (ˈleɪtæk/lay-tek или lah-tek) — это система подготовки документов и язык разметки документов. Он широко используется для коммуникации и публикации научных документов во многих областях, включая математику, физику и информатику. Он также играет ключевую роль в подготовке и публикации книг и статей, содержащих сложные многоязычные материалы, такие как корейский, японский, китайские иероглифы и арабский, включая специальные издания. @@ -72,7 +72,7 @@ def convert_TEX_to_PDF(infile, outfile): print(infile + " converted into " + outfile) ``` -## Конвертировать EPUB в PDF +## Преобразование EPUB в PDF **Aspose.PDF for Python via .NET** позволяет вам просто конвертировать файлы EPUB в формат PDF. @@ -108,7 +108,7 @@ def convert_EPUB_to_PDF(infile, outfile): print(infile + " converted into " + outfile) ``` -## Преобразовать Markdown в PDF +## Преобразование Markdown в PDF **Эта функция поддерживается версией 19.6 или более новой.** @@ -136,7 +136,7 @@ def convert_MD_to_PDF(infile, outfile): print(infile + " converted into " + outfile) ``` -## Преобразовать PCL в PDF +## Преобразование PCL в PDF PCL (Printer Command Language) — язык печати Hewlett-Packard, разработанный для доступа к стандартным функциям принтера. Уровни PCL от 1 до 5e/5c являются языками, основанными на командах, использующими управляющие последовательности, которые обрабатываются и интерпретируются в порядке их получения. На уровне конечного пользователя потоки данных PCL генерируются драйвером печати. Вывод PCL также может быть легко сгенерирован пользовательскими приложениями. @@ -173,7 +173,7 @@ def convert_PCL_to_PDF(infile, outfile): print(infile + " converted into " + outfile) ``` -## Конвертировать предварительно отформатированный текст в PDF +## Преобразование предварительно отформатированного текста в PDF **Aspose.PDF for Python via .NET** поддерживает функцию конвертации обычного текста и предварительно отформатированного текстового файла в формат PDF. @@ -235,7 +235,7 @@ def convert_TXT_to_PDF(infile, outfile): print(infile + " converted into " + outfile) ``` -## Конвертировать PostScript в PDF +## Преобразование PostScript в PDF В этом примере показано, как преобразовать файл PostScript в PDF‑документ с использованием Aspose.PDF for Python via .NET. @@ -257,7 +257,7 @@ def convert_PS_to_PDF(infile, outfile): print(infile + " converted into " + outfile) ``` -## Конвертировать XPS в PDF +## Преобразование XPS в PDF **Aspose.PDF for Python via .NET** поддерживает функцию конвертирования XPS файлы в формат PDF. Проверьте эту статью, чтобы решить ваши задачи. @@ -286,7 +286,7 @@ Aspose.PDF for Python via .NET представляет вам онлайн‑п [![Конвертация XPS в PDF с приложением Aspose.PDF](xps_to_pdf.png)](https://products.aspose.app/pdf/conversion/xps-to-pdf/) {{% /alert %}} -## Преобразовать XSL-FO в PDF +## Преобразование XSL-FO в PDF Следующий фрагмент кода можно использовать для преобразования XSLFO в формат PDF с помощью Aspose.PDF for Python via .NET: @@ -306,7 +306,7 @@ def convert_XSLFO_to_PDF(xsltfile, xmlfile, outfile): print(xmlfile + " converted into " + outfile) ``` -## Преобразовать XML с помощью XSLT в PDF +## Преобразование XML с помощью XSLT в PDF Этот пример демонстрирует, как преобразовать файл XML в PDF, сначала преобразовав его в HTML с помощью шаблона XSLT, а затем загрузив HTML в Aspose.PDF. diff --git a/ru/python-net/converting/convert-pdf-to-excel/_index.md b/ru/python-net/converting/convert-pdf-to-excel/_index.md index c70644ead..1507d8708 100644 --- a/ru/python-net/converting/convert-pdf-to-excel/_index.md +++ b/ru/python-net/converting/convert-pdf-to-excel/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Как конвертировать PDF в Excel в Python Abstract: В этой статье представлен всесторонний руководитель по конвертации PDF‑файлов в различные форматы Excel с использованием Python, конкретно с библиотекой Aspose.PDF for Python via .NET. Описываются процессы преобразования в форматы XLS, XLSX, CSV и ODS. Документ объясняет шаги, необходимые для конвертации PDF в XLS и XLSX, выделяя создание экземпляров Document и ExcelSaveOptions, а также использование метода Document.Save() для указания выходных форматов. В статье также рассматриваются такие возможности, как контроль вставки пустых столбцов и уменьшение количества листов во время конвертации. Кроме того, приводятся примеры преобразования PDF в отдельные листы Excel и другие форматы, такие как CSV и ODS, подчёркивая гибкость и функциональность Aspose.PDF. Также упоминается онлайн‑инструмент для конвертации PDF в XLSX, позволяющий пользователям оценить качество преобразования. В заключении статьи приведён список связанных тем и фрагменты кода, помогающие лучше понять и реализовать эти конвертации программно. --- -## Конвертировать PDF в Excel (Spreadsheet 2003 XML) +## Преобразование PDF в Excel (Spreadsheet 2003 XML) **Aspose.PDF for Python via .NET** поддерживает возможность конвертации PDF‑файлов в форматы Excel и CSV. @@ -52,7 +52,7 @@ def convert_pdf_to_excel_spread_sheet2003(infile, outfile): print(infile + " converted into " + outfile) ``` -## Конвертировать PDF в Excel 2007+ (XLSX) +## Преобразование PDF в Excel 2007+ (XLSX) Шаги: Конвертировать PDF‑файл в формат XLSX (Excel 2007+) @@ -76,7 +76,7 @@ def convert_pdf_to_excel_2007(infile, outfile): print(infile + " converted into " + outfile) ``` -## Конвертировать PDF в XLS с контролем столбца +## Преобразование PDF в XLS с контролем столбца При конвертации PDF в формат XLS в выходной файл добавляется пустой столбец в качестве первого столбца. Опция 'insert_blank_column_at_first' в классе 'ExcelSaveOptions' используется для управления этим столбцом. Ее значение по умолчанию — true. @@ -95,7 +95,7 @@ def convert_pdf_to_excel_2007_control_column(infile, outfile): print(infile + " converted into " + outfile) ``` -## Преобразовать PDF в один лист Excel +## Преобразование PDF в один лист Excel Aspose.PDF for Python via .NET демонстрирует, как конвертировать PDF в файл Excel (.xlsx), с включённым параметром ’minimize_the_number_of_worksheets’. @@ -121,7 +121,7 @@ def convert_pdf_to_excel_2007_single_excel_worksheet(infile, outfile): print(infile + " converted into " + outfile) ``` -## Преобразовать PDF в Excel 2007 с поддержкой макросов (XLSM) +## Преобразование PDF в Excel 2007 с поддержкой макросов (XLSM) Этот пример на Python показывает, как преобразовать файл PDF в файл Excel в формате XLSM (рабочая книга Excel с поддержкой макросов). @@ -139,9 +139,9 @@ def convert_pdf_to_excel_2007_macro(infile, outfile): print(infile + " converted into " + outfile) ``` -## Преобразовать в другие форматы электронных таблиц +## Преобразование в другие форматы электронных таблиц -### Конвертировать PDF в CSV +### Преобразование PDF в CSV Функция 'convert_pdf_to_excel_2007_csv' выполняет ту же операцию, что и раньше, но на этот раз целевой формат — CSV (значения, разделённые запятыми) вместо XLSM. @@ -165,7 +165,7 @@ def convert_pdf_to_excel_2007_csv(infile, outfile): print(infile + " converted into " + outfile) ``` -### Конвертировать PDF в ODS +### Преобразование PDF в ODS Шаги: Преобразовать PDF в ODS в Python diff --git a/ru/python-net/converting/convert-pdf-to-html/_index.md b/ru/python-net/converting/convert-pdf-to-html/_index.md index 253cb1ed9..a31987af9 100644 --- a/ru/python-net/converting/convert-pdf-to-html/_index.md +++ b/ru/python-net/converting/convert-pdf-to-html/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Как конвертировать PDF в HTML на Python Abstract: Эта статья представляет собой всестороннее руководство по конвертации PDF‑файлов в HTML с использованием Python, конкретно через библиотеку Aspose.PDF for Python via .NET. В ней описаны необходимые шаги для выполнения этой конверсии программно, с акцентом на создание объекта `Document` из исходного PDF и использование `HtmlSaveOptions` для сохранения документа в формате HTML. Статья включает краткий фрагмент кода на Python, демонстрирующий процесс конвертации. Кроме того, она представляет онлайн‑инструмент, приложение Aspose.PDF’s "PDF to HTML", позволяющее пользователям изучить функции и качество конверсии. Статья структурирована так, чтобы охватить различные связанные темы, обеспечивая полное понимание использования Python для конвертации PDF в HTML. --- -## Преобразовать PDF в HTML +## Преобразование PDF в HTML **Aspose.PDF for Python via .NET** предоставляет множество функций для преобразования различных форматов файлов в PDF‑документы и преобразования PDF‑файлов в различные форматы вывода. Эта статья рассматривает, как конвертировать PDF‑файл в HTML. Вы можете использовать всего несколько строк кода Python для преобразования PDF в HTML. Возможно, вам потребуется конвертировать PDF в HTML, если вы хотите создать веб‑сайт или добавить контент на онлайн‑форум. Один из способов преобразовать PDF в HTML — программно использовать Python. @@ -50,7 +50,7 @@ def convert_PDF_to_HTML(infile, outfile): - [Конвертировать PDF в Word](/pdf/ru/python-net/convert-pdf-to-word/) если вывод редактируемого документа полезнее, чем HTML. - [Конвертировать PDF в форматы изображений](/pdf/ru/python-net/convert-pdf-to-images-format/) для сценариев экспорта растра. -### Конвертировать PDF в HTML с сохранением изображений в указанную папку +### Преобразование PDF в HTML с сохранением изображений в указанную папку Эта функция преобразует PDF‑файл в формат HTML с использованием Aspose.PDF for Python via .NET. Все извлечённые изображения сохраняются в указанной папке вместо встраивания их в HTML‑файл. @@ -72,7 +72,7 @@ def convert_PDF_to_HTML_storing_images(infile, outfile): print(infile + " converted into " + outfile) ``` -### Преобразовать PDF в многостраничный HTML +### Преобразование PDF в многостраничный HTML Эта функция конвертирует файл PDF в многостраничный HTML, где каждая страница PDF экспортируется в отдельный HTML‑файл. Это делает вывод более удобным для навигации и уменьшает время загрузки больших PDF‑файлов. @@ -94,7 +94,7 @@ def convert_PDF_to_HTML_multi_page(infile, outfile): print(infile + " converted into " + outfile) ``` -### Преобразовать PDF в HTML с сохранением SVG‑изображений в указанную папку +### Преобразование PDF в HTML с сохранением SVG‑изображений в указанную папку Эта функция преобразует PDF в формат HTML, при этом сохраняет все изображения как файлы SVG в указанной папке, вместо того чтобы внедрять их непосредственно в HTML. @@ -145,7 +145,7 @@ def convert_PDF_to_HTML_compress_svg(infile, outfile): print(infile + " converted into " + outfile) ``` -### Преобразовать PDF в HTML с управлением встроенными растровыми изображениями +### Преобразование PDF в HTML с управлением встроенными растровыми изображениями Этот фрагмент кода преобразует PDF в формат HTML, встраивая растровые изображения в качестве фоновых PNG‑изображений страниц. Этот подход сохраняет качество изображений и макет страниц в HTML. @@ -167,7 +167,7 @@ def convert_PDF_to_HTML_PNG_background(infile, outfile): print(infile + " converted into " + outfile) ``` -### Преобразовать PDF в HTML‑страницу только с содержимым тела +### Преобразование PDF в HTML‑страницу только с содержимым тела Эта функция преобразует PDF в формат HTML, генерируя контент 'body-only' без дополнительных тегов 'html' или 'head', и разбивает вывод на отдельные страницы. @@ -194,7 +194,7 @@ def convert_PDF_to_HTML_body_content(infile, outfile): print(infile + " converted into " + outfile) ``` -### Конвертировать PDF в HTML с прозрачным отображением текста +### Преобразование PDF в HTML с прозрачным отображением текста Эта функция преобразует PDF в формат HTML, отображая весь текст как прозрачный, включая тексты с тенями, что сохраняет визуальную достоверность, позволяя при этом гибко стилизовать полученный HTML. @@ -219,7 +219,7 @@ def convert_PDF_to_HTML_transparent_text_rendering(infile, outfile): print(infile + " converted into " + outfile) ``` -### Преобразовать PDF в HTML с рендерингом слоёв документа +### Преобразование PDF в HTML с рендерингом слоёв документа Эта функция конвертирует PDF в формат HTML, сохраняет слои документа, преобразуя отмеченное содержимое в отдельные слои в результирующем HTML. Это позволяет точно отображать слоистые элементы (например, аннотации, фоновые изображения и наложения). diff --git a/ru/python-net/converting/convert-pdf-to-images-format/_index.md b/ru/python-net/converting/convert-pdf-to-images-format/_index.md index f5a5f3dc3..bc9d37aed 100644 --- a/ru/python-net/converting/convert-pdf-to-images-format/_index.md +++ b/ru/python-net/converting/convert-pdf-to-images-format/_index.md @@ -25,7 +25,7 @@ Abstract: В этой статье объясняется, как преобра Библиотека включает несколько классов рендеринга. `DocumentDevice` разработан для конвертации всего документа, в то время как `ImageDevice` нацелено на отдельные страницы. -## Преобразовать PDF с помощью класса DocumentDevice +## Преобразование PDF с помощью класса DocumentDevice Используйте `DocumentDevice`, если хотите вывести весь PDF в один многостраничный TIFF-файл. @@ -39,7 +39,7 @@ Aspose.PDF for Python via .NET представляет вам онлайн‑п [![Конвертация PDF в TIFF с приложением Aspose.PDF](pdf_to_tiff.png)](https://products.aspose.app/pdf/conversion/pdf-to-tiff) {{% /alert %}} -### Преобразовать страницы PDF в одно изображение TIFF +### Преобразование страницы PDF в одно изображение TIFF Aspose.PDF for Python via .NET может рендерить каждую страницу PDF‑файла в одно TIFF‑изображение. @@ -73,7 +73,7 @@ def convert_PDF_to_TIFF(infile, outfile): print(infile + " converted into " + outfile) ``` -## Конвертировать PDF с использованием класса ImageDevice +## Преобразование PDF с использованием класса ImageDevice Используйте `ImageDevice`, если вам нужен постраничный вывод в растровом формате. @@ -109,7 +109,7 @@ def convert_PDF_to_TIFF(infile, outfile): 1. Переберите страницы, которые вы хотите экспортировать. 1. Вызовите метод [ImageDevice.process()](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/imagedevice/#methods), чтобы сохранить каждую страницу как изображение. -### Преобразовать PDF в BMP +### Преобразование PDF в BMP ```python import aspose.pdf as ap @@ -131,7 +131,7 @@ def convert_PDF_to_BMP(infile, outfile): print(infile + " converted into " + outfile) ``` -### Конвертировать PDF в EMF +### Преобразование PDF в EMF ```python import aspose.pdf as ap @@ -153,7 +153,7 @@ def convert_PDF_to_EMF(infile, outfile): print(infile + " converted into " + outfile) ``` -### Конвертировать PDF в JPEG +### Преобразование PDF в JPEG ```python import aspose.pdf as ap @@ -176,7 +176,7 @@ def convert_PDF_to_JPEG(infile, outfile): print(infile + " converted into " + outfile) ``` -### Конвертировать PDF в PNG +### Преобразование PDF в PNG ```python import aspose.pdf as ap @@ -197,7 +197,7 @@ def convert_PDF_to_PNG(infile, outfile): page_count = page_count + 1 ``` -### Конвертировать PDF в PNG с шрифтом по умолчанию +### Преобразование PDF в PNG с шрифтом по умолчанию ```python import aspose.pdf as ap @@ -223,7 +223,7 @@ def convert_PDF_to_PNG_with_default_font(infile, outfile): page_count = page_count + 1 ``` -### Конвертировать PDF в GIF +### Преобразование PDF в GIF ```python import aspose.pdf as ap @@ -255,7 +255,7 @@ Aspose.PDF for Python представляет вам онлайн‑прило [![Как конвертировать PDF в PNG с помощью App](pdf_to_png.png)](https://products.aspose.app/pdf/conversion/pdf-to-png) {{% /alert %}} -## Конвертировать PDF с использованием класса SaveOptions +## Преобразование PDF с использованием класса SaveOptions Используйте `SaveOptions`, если хотите экспортировать содержимое PDF в SVG. @@ -281,7 +281,7 @@ Aspose.PDF for Python via .NET может как конвертировать SV 1. Создайте объект [SvgSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/svgsaveoptions/) и настройте нужные параметры. 1. Вызовите метод [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) с экземпляром `SvgSaveOptions`, чтобы записать выходной SVG-файл. -### Конвертировать PDF в SVG +### Преобразование PDF в SVG ```python import aspose.pdf as ap diff --git a/ru/python-net/converting/convert-pdf-to-other-files/_index.md b/ru/python-net/converting/convert-pdf-to-other-files/_index.md index 6aa91f1fb..e5ec93d42 100644 --- a/ru/python-net/converting/convert-pdf-to-other-files/_index.md +++ b/ru/python-net/converting/convert-pdf-to-other-files/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Как конвертировать PDF в другие ф Abstract: Статья предоставляет всестороннее руководство по конвертации PDF‑файлов в различные форматы с использованием Aspose.PDF for Python. Она охватывает преобразование PDF в форматы EPUB, LaTeX/TeX, Text, XPS и XML. Каждый раздел начинается с приглашения попробовать онлайн приложения, предоставляемые Aspose для конвертации PDF в соответствующие форматы, подчёркивая простоту использования и качество этих инструментов. --- -## Преобразовать PDF в EPUB +## Преобразование PDF в EPUB {{% alert color="success" %}} **Попробуйте конвертировать PDF в EPUB онлайн** @@ -50,7 +50,7 @@ def convert_PDF_to_EPUB(infile, outfile): - [Конвертировать PDF в HTML](/pdf/ru/python-net/convert-pdf-to-html/) для браузерного вывода. - [Конвертировать PDF в PDF/A, PDF/E и PDF/X](/pdf/ru/python-net/convert-pdf-to-pdf_x/) для архивных и соответствующих стандартам рабочих процессов конвертации. -## Преобразовать PDF в LaTeX/TeX +## Преобразование PDF в LaTeX/TeX **Aspose.PDF for Python via .NET** поддерживает преобразование PDF в LaTeX/TeX. Формат файла LaTeX — это текстовый формат файла со специальной разметкой, используемый в системе подготовки документов на основе TeX для высококачественной наборной печати. @@ -80,7 +80,7 @@ def convert_PDF_to_TeX(infile, outfile): print(infile + " converted into " + outfile) ``` -## Конвертировать PDF в текст +## Преобразование PDF в текст **Aspose.PDF for Python** поддерживает конвертацию всего PDF‑документа и отдельной страницы в текстовый файл. Вы можете конвертировать PDF‑документ в TXT‑файл, используя класс 'TextDevice'. Следующий фрагмент кода объясняет, как извлечь текст со всех страниц. @@ -105,7 +105,7 @@ Aspose.PDF for Python представляет вам онлайн прилож [![Aspose.PDF Конвертация PDF в Текст с приложением](pdf_to_text.png)](https://products.aspose.app/pdf/conversion/pdf-to-txt) {{% /alert %}} -## Конвертировать PDF в XPS +## Преобразование PDF в XPS **Aspose.PDF for Python** предоставляет возможность конвертировать PDF файлы в формат XPS. Давайте попробуем использовать представленный фрагмент кода для конвертации PDF файлов в формат XPS с помощью Python. @@ -137,7 +137,7 @@ def convert_PDF_to_XPS(infile, outfile): print(infile + " converted into " + outfile) ``` -## Преобразовать PDF в MD +## Преобразование PDF в MD Aspose.PDF имеет класс ‘MarkdownSaveOptions()’, который преобразует PDF‑документ в формат Markdown (MD), сохраняя изображения и ресурсы. @@ -164,7 +164,7 @@ def convert_PDF_to_MD(infile, outfile): Markdown‑файл с текстом и связанными изображениями, хранящимися в указанной папке images. -## Конвертировать PDF в MobiXML +## Преобразование PDF в MobiXML Этот метод преобразует документ PDF в формат MOBI (MobiXML), который обычно используется для электронных книг на устройствах Kindle. diff --git a/ru/python-net/converting/convert-pdf-to-pdfx/_index.md b/ru/python-net/converting/convert-pdf-to-pdfx/_index.md index a08f3025e..65521574c 100644 --- a/ru/python-net/converting/convert-pdf-to-pdfx/_index.md +++ b/ru/python-net/converting/convert-pdf-to-pdfx/_index.md @@ -16,7 +16,7 @@ Abstract: Статья предоставляет полное руководс **PDF в формат PDF/x означает возможность конвертировать PDF в дополнительные форматы, а именно PDF/A, PDF/E и PDF/X.** -## Конвертировать PDF в PDF/A +## Преобразование PDF в PDF/A **Aspose.PDF for Python** позволяет вам конвертировать PDF‑файл в PDF/A соответствующий файл PDF. Прежде чем это сделать, файл должен быть проверен. Эта тема объясняет, как это сделать. @@ -38,7 +38,7 @@ Aspose.PDF for Python представляет вам онлайн‑прило Метод 'document.validate()' проверяет, соответствует ли PDF‑файл стандарту PDF/A-1B (стандарту ISO для PDF, предназначенному для длительного архивирования). Результаты проверки сохраняются в файл журнала. -### Конвертировать PDF в PDF/A-1B +### Преобразование PDF в PDF/A-1B Следующий фрагмент кода показывает, как преобразовать PDF‑файлы в формат PDF/A‑1B: @@ -67,7 +67,7 @@ def convert_PDF_to_PDFA(infile, outfile): print(infile + " converted into " + outfile) ``` -### Преобразовать PDF в PDF 2.0 и PDF/A-4 +### Преобразование PDF в PDF 2.0 и PDF/A-4 В этом примере показывается, как преобразовать PDF‑документ в более новые стандартизированные форматы: PDF 2.0 и PDF/A‑4. Оба преобразования помогают обеспечить соответствие современным спецификациям и требованиям к архивированию. @@ -94,7 +94,7 @@ def convert_PDF_to_PDFA4(infile, outfile): document.save(outfile) ``` -### Конвертировать PDF в PDF/A-3A с встроенными файлами +### Преобразование PDF в PDF/A-3A с встроенными файлами Следующий фрагмент кода демонстрирует, как внедрять внешние файлы в PDF, а затем преобразовать PDF в формат PDF/A-3A, который поддерживает вложения и подходит для долгосрочного архивирования с внедренным содержимым. @@ -125,7 +125,7 @@ def convert_PDF_to_PDFA_with_attachment(infile, attachement_file, outfile): document.save(outfile) ``` -### Конвертировать PDF в PDF/A-1B с заменой шрифтов +### Преобразование PDF в PDF/A-1B с заменой шрифтов Эта функция преобразует PDF в формат PDF/A-1B, заменяя отсутствующие шрифты доступными. Это гарантирует, что преобразованный PDF останется визуально согласованным и соответствующим требованиям архивных стандартов. @@ -155,7 +155,7 @@ def convert_PDF_to_PDFA_replace_missing_fonts(infile, outfile): document.save(outfile) ``` -### Преобразовать PDF в PDF/A-1B с автоматическим тегированием +### Преобразование PDF в PDF/A-1B с автоматическим тегированием Эта функция преобразует PDF‑документ в формат PDF/A-1B, автоматически добавляя теги к содержимому для обеспечения доступности и структурной согласованности. Автоматическое тегирование улучшает удобство использования документа для программ чтения с экрана и обеспечивает правильную семантическую структуру. @@ -198,7 +198,7 @@ def convert_PDF_to_PDFA_with_automatic_tagging(infile, outfile): print(infile + " converted into " + outfile) ``` -## Конвертировать PDF в PDF/E +## Преобразование PDF в PDF/E Этот фрагмент кода демонстрирует, как преобразовать PDF‑документ в формат PDF/E-1, который является стандартом ISO, предназначенным для инженерной и технической документации. Этот формат сохраняет точный макет, графику и метаданные, необходимые для инженерных рабочих процессов. @@ -231,7 +231,7 @@ def convert_PDF_to_PDF_E(infile, outfile): print(infile + " converted into " + outfile) ``` -## Конвертировать PDF в PDF/X +## Преобразование PDF в PDF/X Следующий фрагмент кода преобразует PDF‑документ в формат PDF/X-4, который является стандартом ISO, часто используемым в полиграфии и издательской индустрии. PDF/X-4 обеспечивает точность цветов, сохраняет прозрачность и встраивает ICC‑профили для обеспечения согласованного вывода на разных устройствах. diff --git a/ru/python-net/converting/convert-pdf-to-powerpoint/_index.md b/ru/python-net/converting/convert-pdf-to-powerpoint/_index.md index 7d302f05e..501726830 100644 --- a/ru/python-net/converting/convert-pdf-to-powerpoint/_index.md +++ b/ru/python-net/converting/convert-pdf-to-powerpoint/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Как конвертировать PDF в PowerPoint на Abstract: Эта статья представляет собой всестороннее руководство по конвертации PDF‑файлов в презентации PowerPoint с использованием Python, с особым акцентом на формат PPTX. В ней представлено использование Aspose.PDF for Python via .NET, который упрощает процесс конвертации, позволяя преобразовывать страницы PDF в отдельные слайды в файле PPTX. В статье описаны необходимые шаги конвертации, включая создание экземпляров классов Document и PptxSaveOptions и использование метода Save. Кроме того, отмечена возможность конвертировать PDF в PPTX с слайдами в виде изображений путем установки определённого свойства в PptxSaveOptions. Приведены фрагменты кода, иллюстрирующие процесс конвертации. В статье также упомянуто онлайн‑приложение для тестирования функции конвертации PDF в PPTX, предлагающее пользователям практический опыт. Кроме того, перечислены различные связанные темы и функции, доступные в данном контексте, подчеркивающие универсальность и программный подход к работе с конвертацией PDF в PowerPoint с помощью Python. --- -## Конвертация PDF в PowerPoint и PPTX на Python +## Преобразование PDF в PowerPoint и PPTX на Python **Aspose.PDF for Python via .NET** позволяет отслеживать прогресс конвертации PDF в PPTX. @@ -45,7 +45,7 @@ def convert_PDF_to_PPTX(infile, outfile): document.save(outfile, save_options) ``` -## Преобразовать PDF в PPTX с слайдами в виде изображений +## Преобразование PDF в PPTX с слайдами в виде изображений {{% alert color="success" %}} **Попробуйте конвертировать PDF в PowerPoint онлайн** @@ -71,7 +71,7 @@ def convert_PDF_to_PPTX_slides_as_images(infile, outfile): document.save(outfile, save_options) ``` -## Конвертировать PDF в PPTX с пользовательским разрешением изображения +## Преобразование PDF в PPTX с пользовательским разрешением изображения Этот метод преобразует документ PDF в файл PowerPoint (PPTX), устанавливая пользовательское разрешение изображения (300 DPI) для улучшенного качества. diff --git a/ru/python-net/converting/convert-pdf-to-word/_index.md b/ru/python-net/converting/convert-pdf-to-word/_index.md index c82953aef..63785db25 100644 --- a/ru/python-net/converting/convert-pdf-to-word/_index.md +++ b/ru/python-net/converting/convert-pdf-to-word/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Как конвертировать PDF в Word в Python Abstract: Эта статья предоставляет исчерпывающее руководство по конвертации PDF‑файлов в форматы Microsoft Word (DOC и DOCX) с использованием Python, в частности библиотеки Aspose.PDF. В ней изложены преимущества преобразования PDF в редактируемые документы Word, позволяющие легче манипулировать содержимым, таким как текст, таблицы и изображения. Статья подробно описывает процесс конвертации PDF в DOC (формат Word 97‑2003) и DOCX, с примерами кода, демонстрирующими эти преобразования на Python. Процесс включает создание объекта `Document` из PDF и сохранение его в нужном формате с помощью метода `save()` и перечисления `SaveFormat`. Кроме того, вводится класс `DocSaveOptions`, который позволяет дополнительно настраивать процесс конвертации, например указывать режимы распознавания. Статья также подчёркивает онлайн‑приложения, предоставляемые Aspose.PDF для тестирования качества и функциональности конвертации. Содержание включает структурированный обзор и ссылки на соответствующие разделы для каждого формата. --- -## Преобразовать PDF в DOC +## Преобразование PDF в DOC Одна из самых популярных функций — преобразование PDF в документ Microsoft Word DOC, что упрощает управление контентом. **Aspose.PDF for Python via .NET** позволяет конвертировать PDF‑файлы не только в DOC, но и в формат DOCX, быстро и эффективно. @@ -52,7 +52,7 @@ Aspose.PDF for Python представляет вам онлайн прилож [![Преобразовать PDF в DOC](/pdf/ru/net/images/pdf_to_word.png)](https://products.aspose.app/pdf/conversion/pdf-to-doc) {{% /alert %}} -## Конвертировать PDF в DOCX +## Преобразование PDF в DOCX Aspose.PDF for Python API позволяет читать и конвертировать PDF‑документы в DOCX с помощью Python via .NET. DOCX — это широко известный формат для документов Microsoft Word, структура которого была изменена от простого бинарного к комбинации XML и бинарных файлов. Файлы Docx можно открывать в Word 2007 и последующих версиях, но не в более ранних версиях MS Word, которые поддерживают расширения файлов DOC. @@ -78,7 +78,7 @@ def convert_PDF_to_DOCX(infile, outfile): document.save(outfile, save_options) ``` -## Преобразовать PDF в DOCX с расширенным распознаванием разметки +## Преобразование PDF в DOCX с расширенным распознаванием разметки Конвертировать PDF‑документ в файл DOCX (Word) с использованием Python и Aspose.PDF с расширенными настройками распознавания. Используется режим улучшенного потока для сохранения структуры документа, делая вывод более редактируемым и ближе к исходному макету. diff --git a/ru/python-net/converting/convert-pdfx-to-pdf/_index.md b/ru/python-net/converting/convert-pdfx-to-pdf/_index.md index f1ded4ffa..2fce2c43e 100644 --- a/ru/python-net/converting/convert-pdfx-to-pdf/_index.md +++ b/ru/python-net/converting/convert-pdfx-to-pdf/_index.md @@ -18,7 +18,7 @@ Abstract: В этой статье объясняется, как удалить PDF-файлы, соответствующие стандартам, полезны для архивирования, печати и рабочих процессов по обеспечению доступности, но в некоторых случаях может потребоваться удалить это соответствие перед интеграцией файла в другие системы или конвейеры. Aspose.PDF for Python via .NET позволяет сделать это программно, а затем сохранить результат как обычный PDF-файл. -## Конвертировать PDF/A в PDF +## Преобразование PDF/A в PDF Этот пример удаляет метаданные и ограничения соответствия PDF/A из PDF, чтобы документ можно было снова сохранить как обычный PDF‑файл. diff --git a/ru/python-net/overview/key-features/_index.md b/ru/python-net/overview/key-features/_index.md index 0146aebf0..36b83f6d1 100644 --- a/ru/python-net/overview/key-features/_index.md +++ b/ru/python-net/overview/key-features/_index.md @@ -123,7 +123,7 @@ Aspose.PDF для Python поддерживает версии PDF 1.2, 1.3, 1.4 - Добавить штамп изображения. - Добавить штамп страницы PDF. -## Открыть зашифрованный документ +## Открытие зашифрованного документа - Зашифровать PDF. - Расшифровать PDF. diff --git a/ru/python-net/whatsnew/_index.md b/ru/python-net/whatsnew/_index.md index 5873620c2..a70c55279 100644 --- a/ru/python-net/whatsnew/_index.md +++ b/ru/python-net/whatsnew/_index.md @@ -373,7 +373,7 @@ def manage_layer_visibility(self, infile, outfile): 1. Конвертировать PDF-файлы в формат PDF/E-1. 1. Добавьте помечённые изображения из потоков памяти. -### Преобразовать PDF в формат PDF/E-1 +### Преобразование PDF в формат PDF/E-1 В версии 25.9 библиотеки Aspose.PDF for Python доступно преобразование формата PDF/E-1. Дополнительную информацию об этом формате можно найти на [Документация по форматам файлов](https://docs.fileformat.com/pdf/e/). @@ -400,7 +400,7 @@ def convert_pdf_to_pdf_e(self, infile, outfile): document.save(path_outfile) ``` -### Добавить Tagged Images из потока +### Добавление Tagged Images из потока Добавление помеченных изображений из потока в PDF. Версия 25.9 поддерживает расширенную доступность PDF‑документов, позволяя добавить изображение из потоковой памяти и пометить его альтернативным текстом. @@ -439,7 +439,7 @@ def add_tagged_image_from_stream(self, image_file, outfile): 1. Изменить размер страниц PDF с масштабированием содержимого. 1. Применить пунктирные границы к таблицам. -### Создать помеченное оглавление (TOC) +### Создание помеченное оглавление (TOC) Автоматически генерировать доступные оглавления (TOC) в Tagged PDF. Создание полностью доступного оглавления (TOC) в PDF позволяет читателям эффективно перемещаться по документу и обеспечивает соответствие требованиям PDF/UA-1 по доступности. @@ -722,7 +722,7 @@ def fit_text_into_rectangle(self, infile, outfile): document.save(path_outfile) ``` -### Добавить облачные полигональные аннотации +### Добавление облачные полигональные аннотации Улучшите процессы рецензирования PDF с помощью облачных или полигональных аннотаций. Полигональные аннотации позволяют выделять или подчеркивать определённые области в PDF, используя геометрические фигуры. @@ -942,7 +942,7 @@ def customization_features_for_digital_sign( 1. Преобразовать динамические формы XFA в PDF‑файлы AcroForm. 1. Замена шрифтов в PDF - конвертация в XPS. -### Извлечь сертификаты из подписей PDF +### Извлечение сертификаты из подписей PDF Получить встроенные сертификаты с помощью 'extract_certificate()'. @@ -965,7 +965,7 @@ def extract_certificate(self, infile): print(certificate[0] is not None) ``` -### Создать структурированные упорядоченные списки в Tagged PDF +### Создание структурированные упорядоченные списки в Tagged PDF Создавайте доступные нумерованные списки (с вложенными элементами) в помеченных документах. @@ -1083,7 +1083,7 @@ def verify_with_public_key_certificate1(self, certificate, infile): return file_sign.verify_signature(signature_names[0], certificate) ``` -### Преобразовать динамические формы XFA в PDF‑файлы AcroForm +### Преобразование динамические формы XFA в PDF‑файлы AcroForm Стандартизировать формы XFA с параметром 'ignore_needs_rendering'. diff --git a/ru/python-net/working-with-facades/form/button-fields-and-images/_index.md b/ru/python-net/working-with-facades/form/button-fields-and-images/_index.md index 09b9305aa..5a01fc247 100644 --- a/ru/python-net/working-with-facades/form/button-fields-and-images/_index.md +++ b/ru/python-net/working-with-facades/form/button-fields-and-images/_index.md @@ -11,7 +11,7 @@ AlternativeHeadline: Добавление изображения к полям Abstract: PDF‑формы часто содержат интерактивные кнопки, которые либо вызывают действия JavaScript, либо отправляют данные формы. Вы можете визуально улучшить поля кнопок, добавив изображения в качестве их внешнего вида, и программно проверять их поведение при отправке. --- -## Добавить изображение к полям кнопок +## Добавление изображения к полям кнопок Этот фрагмент кода объясняет, как добавить изображение в качестве внешнего вида к существующему полю кнопки в PDF‑форме. Операция улучшает визуальное представление PDF‑кнопки, заменяя её внешний вид по умолчанию пользовательским изображением. @@ -53,7 +53,7 @@ def add_image_appearance_to_button_fields(infile, outfile): pdf_form.save(outfile) ``` -## Получить флаги отправки +## Получение флагов отправки Библиотека Python помогает получить флаги отправки кнопки отправки в PDF‑форме, используя API Aspose.PDF Facades. Флаги отправки определяют поведение кнопки отправки, например, отправляет ли она всю форму, включает ли аннотации или отправляет данные в формате FDF, XFDF, PDF или HTML. diff --git a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md index 223f6e45d..1e94dd107 100644 --- a/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md +++ b/ru/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Добавить действия JavaScript к полям Abstract: В этой статье объясняется, как открыть PDF‑форму, назначить код JavaScript конкретному полю формы, добавить дополнительные действия скрипта и сохранить обновленный документ. В примере используется класс FormEditor из API Aspose.PDF Facades для программного управления поведением формы. --- -## Добавить действия JavaScript к полям PDF‑формы с помощью Python +## Добавление действия JavaScript к полям PDF‑формы с помощью Python Этот фрагмент кода позволяет добавить действия JavaScript к существующему полю PDF‑формы с использованием библиотеки Aspose.PDF for Python. Он открывает PDF‑документ, назначает действие JavaScript полю формы и добавляет скрипт, который выполняется при срабатывании поля. В конце обновлённый PDF сохраняется в новый файл. Используя [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) класс из [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) модуля, вы можете программно привязать JavaScript к существующим полям формы: diff --git a/ru/python-net/working-with-facades/pdffilesecurity/change-password/_index.md b/ru/python-net/working-with-facades/pdffilesecurity/change-password/_index.md index 001b85a01..091fbe344 100644 --- a/ru/python-net/working-with-facades/pdffilesecurity/change-password/_index.md +++ b/ru/python-net/working-with-facades/pdffilesecurity/change-password/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Обновить пароли PDF Abstract: Узнайте, как изменить как пользовательский, так и пароль владельца в защищённом PDF‑файле с помощью Aspose.PDF for Python via .NET. Этот пример демонстрирует, как безопасно обновить учётные данные доступа, сохраняя существующее шифрование и разрешения нетронутыми. --- -## Изменить пароль пользователя и владельца +## Изменение пароль пользователя и владельца Во многих случаях вам может потребоваться обновить пароли защищённого PDF без изменения текущих настроек безопасности. Это может быть полезно при смене учетных данных, передаче прав собственности или повышении безопасности документа. @@ -59,7 +59,7 @@ def change_user_and_owner_password(infile, outfile): file_security.save(outfile) ``` -## Изменить пароль и сбросить безопасность +## Изменение пароль и сбросить безопасность При работе с защищёнными PDF‑документами простая смена паролей может быть недостаточной. Возможно, также потребуется изменить разрешения, такие как печать, копирование или права на редактирование. diff --git a/ru/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md b/ru/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md index bd2860ffe..1a6481cff 100644 --- a/ru/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md +++ b/ru/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Управление разрешениями PDF и кон Abstract: Узнайте, как контролировать действия пользователей с PDF, устанавливая привилегии документа с помощью Aspose.PDF for Python via .NET. Это руководство охватывает применение разрешений с паролем или без него для ограничения таких действий, как печать, копирование или редактирование. --- -## Установить привилегии PDF без паролей +## Установка привилегии PDF без паролей Посмотрите, как применить привилегии к документу PDF без указания паролей пользователя или владельца, используя Aspose.PDF for Python via .NET. Этот фрагмент кода демонстрирует, как контролировать разрешённые действия, сохраняя документ доступным. @@ -56,7 +56,7 @@ def set_pdf_privileges_without_passwords(infile, outfile): file_security.save(outfile) ``` -## Установить привилегии PDF с паролями пользователя и владельца +## Установка привилегии PDF с паролями пользователя и владельца Для полной защиты PDF‑документа часто требуется как контроль доступа (пароли), так и ограничения использования (разрешения). Объединив их, вы можете гарантировать, что только уполномоченные пользователи смогут открыть документ и выполнить определённые действия. diff --git a/ru/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md b/ru/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md index d59f33db3..7076f22ed 100644 --- a/ru/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md +++ b/ru/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md @@ -75,7 +75,7 @@ def create_custom_signature_appearance(): return appearance ``` -## Подписать PDF с базовыми параметрами сертификата +## Подписание PDF с базовыми параметрами сертификата Этот подход настраивает сертификат напрямую на `PdfFileSignature` объект. Это полезно, когда вам нужен простой процесс подписи со стандартными метаданными подписи и без отдельного управления объектом подписи. @@ -102,7 +102,7 @@ def sign_pdf_with_basic_parameters(infile, outfile, certificate_path): pdf_signature.close() ``` -## Подписать PDF с объектом PKCS7 +## Подписание PDF с объектом PKCS7 Использовать `PKCS7` объект, когда вам нужно сначала подготовить подпись, а затем передать её в вызов подписи. Этот шаблон даёт вам больший контроль над настройками подписи и является хорошей основой для более сложных рабочих процессов. @@ -122,7 +122,7 @@ def sign_pdf_with_certificate_object(infile, outfile, certificate_path): pdf_signature.close() ``` -## Подписать PDF с именованной подписью +## Подписание PDF с именованной подписью Если ваш рабочий процесс с документом зависит от заранее определенного имени поля подписи, передайте это имя в `sign()`. Это упрощает последующее обращение к подписи для проверки, обработки или интеграции с процессом утверждения. diff --git a/ru/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md b/ru/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md index 19ccddd52..5844e27b2 100644 --- a/ru/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md +++ b/ru/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md @@ -22,7 +22,7 @@ Aspose.PDF for Python via .NET предоставляет [PdfFileSignature](htt 1. Получить общее количество ревизий в подписанном документе. 1. Прочитать разрешения доступа из сертифицированного PDF. -## Получить номер ревизии подписи +## Получение номер ревизии подписи Используйте этот подход, когда PDF уже содержит одну или несколько подписей, и вам необходимо определить ревизию, связанную с конкретной подписью. Пример получает имя первой доступной подписи и затем вызывает `get_revision()`. @@ -42,7 +42,7 @@ def get_signature_revision(infile): pdf_signature.close() ``` -## Получить общее количество ревизий документа +## Получение общее количество ревизий документа Использовать `get_total_revision()` когда вам нужно узнать, сколько ревизий хранится в подписанном PDF. Это полезно для проверки того, прошёл ли документ через несколько обновлений после применения оригинальной подписи. @@ -61,7 +61,7 @@ def get_total_document_revisions(infile): pdf_signature.close() ``` -## Получить разрешения доступа из сертифицированного PDF +## Получение разрешения доступа из сертифицированного PDF Сертифицированные документы могут определять, какие изменения разрешены после сертификации. Использовать `get_access_permissions()` проверить этот уровень разрешений и определить, разрешает ли документ отсутствие изменений, заполнение форм или другие контролируемые модификации. diff --git a/ru/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md b/ru/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md index 18e2f38f2..425c65d52 100644 --- a/ru/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md +++ b/ru/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md @@ -21,7 +21,7 @@ Aspose.PDF for Python via .NET предоставляет [PdfFileSignature](htt 1. Извлечь визуальное изображение, связанное с подписью. 1. Извлечь сертификат подписи из подписанного PDF. -## Извлечь изображение подписи +## Извлечение изображение подписи Используйте этот метод, когда PDF содержит видимую подпись и вы хотите экспортировать данные её изображения. В примере открывается подписанный документ, получается первое доступное имя подписи, извлекается поток изображения и записывается в файл. @@ -41,7 +41,7 @@ def extract_signature_image(infile, outfile): pdf_signature.close() ``` -## Извлечь сертификат подписи +## Извлечение сертификат подписи Используйте `extract_certificate()` когда вам нужны данные сертификата, прикреплённые к подписи. Это полезно для проверки, процессов валидации или отдельного хранения сертификата подписывающего от PDF‑документа. diff --git a/ru/python-net/working-with-facades/pdffilesignature/signature-information/_index.md b/ru/python-net/working-with-facades/pdffilesignature/signature-information/_index.md index 18bbb4224..8ad2dac29 100644 --- a/ru/python-net/working-with-facades/pdffilesignature/signature-information/_index.md +++ b/ru/python-net/working-with-facades/pdffilesignature/signature-information/_index.md @@ -23,7 +23,7 @@ Aspose.PDF for Python via .NET предоставляет [PdfFileSignature](htt 1. Получите дату и время подписи. 1. Прочитайте причину и место подписи. -## Получить имена подписей +## Получение имена подписей Используйте этот метод, когда PDF может содержать одну или несколько подписей, и вы хотите проверить, какие записи подписи доступны. Пример открывает документ и выводит список, возвращённый `get_sign_names()`. @@ -42,7 +42,7 @@ def get_signature_names(infile): pdf_signature.close() ``` -## Получить сведения о подписанте +## Получение сведения о подписанте Как только вы узнаете название подписи, вы можете получить метаданные, специфичные для подписанта. В этом примере читаются имя подписанта и контактная информация для первой доступной подписи в документе. @@ -66,7 +66,7 @@ def get_signer_details(infile): pdf_signature.close() ``` -## Получить дату и время подписи +## Получение дату и время подписи Используйте `get_date_time()` чтобы определить, когда была применена конкретная подпись. Это полезно для аудита и отображения истории подписей в рабочих процессах с документами. @@ -86,7 +86,7 @@ def get_signature_date_and_time(infile): pdf_signature.close() ``` -## Получить причину подписи и местоположение +## Получение причину подписи и местоположение Цифровые подписи также могут хранить описательные метаданные, такие как причина подписи и место её создания. В этом примере оба значения извлекаются для выбранной подписи и выводятся вместе. diff --git a/ru/python-net/working-with-facades/pdffilesignature/signature-management/_index.md b/ru/python-net/working-with-facades/pdffilesignature/signature-management/_index.md index 52e37b806..c176f66c4 100644 --- a/ru/python-net/working-with-facades/pdffilesignature/signature-management/_index.md +++ b/ru/python-net/working-with-facades/pdffilesignature/signature-management/_index.md @@ -21,7 +21,7 @@ Aspose.PDF for Python via .NET предоставляет [PdfFileSignature](htt 1. Удалить подпись из PDF‑документа. 1. Удалить подпись и очистить связанное поле подписи. -## Удалить подпись из PDF +## Удаление подпись из PDF Используйте `remove_signature()` когда вы хотите удалить выбранную подпись из документа, сохраняя при этом структуру поля подписи. В примере открывается подписанный PDF, определяется имя подписи, удаляется и сохраняется обновлённый выходной файл. @@ -41,7 +41,7 @@ def remove_signature_from_pdf(infile, outfile): pdf_signature.close() ``` -## Удалить подпись и очистить поле +## Удаление подпись и очистить поле Используйте перегрузку с дополнительным `True` флаг, когда вы хотите удалить подпись и также очистить связанное поле подписи. Это полезно, когда поле не должно оставаться в документе после удаления подписи. diff --git a/ru/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md b/ru/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md index 304ed2f73..158b5b017 100644 --- a/ru/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md +++ b/ru/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md @@ -41,7 +41,7 @@ def check_usage_rights(infile): pdf_signature.close() ``` -## Удалить права использования из PDF +## Удаление права использования из PDF Используйте `remove_usage_rights()` когда документ больше не должен сохранять свои текущие настройки прав использования. Пример проверяет начальное состояние, удаляет права и сохраняет обновлённый PDF в новый файл. diff --git a/ru/python-net/working-with-facades/pdffilestamp/add-footer/_index.md b/ru/python-net/working-with-facades/pdffilestamp/add-footer/_index.md index 9971a6b49..ea07ae3e0 100644 --- a/ru/python-net/working-with-facades/pdffilestamp/add-footer/_index.md +++ b/ru/python-net/working-with-facades/pdffilestamp/add-footer/_index.md @@ -13,7 +13,7 @@ Abstract: В этой статье объясняется, как добавит Aspose.PDF for Python via .NET предоставляет [PdfFileStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilestamp/) фасад для добавления повторяющегося контента на страницы PDF. Вы можете использовать его для размещения текста или изображений в нижнем колонтитуле внизу каждой страницы и настроить отступы нижнего колонтитула для управления размещением. -## Добавить текстовый нижний колонтитул +## Добавление текстового нижнего колонтитула Используйте `add_footer()` с `FormattedText` объект, когда вы хотите разместить одинаковый текстовый нижний колонтитул на каждой странице PDF. Второй аргумент задает отступ снизу, используемый для размещения нижнего колонтитула. @@ -37,7 +37,7 @@ def add_text_footer(infile: str, outfile: str) -> None: pdf_stamper.close() ``` -## Добавить изображение в нижний колонтитул +## Добавление изображения в нижний колонтитул Используйте `add_footer()` с потоковым изображением, когда нижний колонтитул должен отображать логотип или другое изображение вместо текста. В примере файл изображения открывается как бинарный поток и размещается внизу каждой страницы. diff --git a/ru/python-net/working-with-facades/pdffilestamp/add-header/_index.md b/ru/python-net/working-with-facades/pdffilestamp/add-header/_index.md index ab75067ec..25ea3766d 100644 --- a/ru/python-net/working-with-facades/pdffilestamp/add-header/_index.md +++ b/ru/python-net/working-with-facades/pdffilestamp/add-header/_index.md @@ -13,7 +13,7 @@ Abstract: В этой статье объясняется, как добавит Aspose.PDF for Python via .NET предоставляет [PdfFileStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilestamp/) фасад для добавления повторяющегося контента на страницы PDF. Вы можете использовать его для размещения текста заголовка или изображений в верхней части каждой страницы и настройки отступов заголовка для контроля позиционирования. -## Добавить текстовый заголовок +## Добавление текстового заголовка Используйте `add_header()` с `FormattedText` объект, когда вы хотите разместить один и тот же текст заголовка на каждой странице PDF. Второй аргумент определяет верхний отступ для заголовка. @@ -39,7 +39,7 @@ def add_text_header(infile: str, outfile: str) -> None: pdf_stamper.close() ``` -## Добавить заголовок с изображением +## Добавление заголовок с изображением Используйте `add_header()` с файлом изображения или потоком изображения, когда в заголовке должен отображаться логотип или другая графика. Это полезно для фирменных макетов документов. diff --git a/ru/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md b/ru/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md index 9b6377ea1..f524afa2f 100644 --- a/ru/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md +++ b/ru/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md @@ -13,7 +13,7 @@ Abstract: В этой статье объясняется, как добавит Aspose.PDF for Python via .NET предоставляет [PdfFileStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilestamp/) Facade для добавления повторяющегося контента на страницы PDF. Вы можете использовать её для вставки номеров страниц с размещением по умолчанию, позиционирования их в определённых координатах или управления их выравниванием и отступами. -## Добавить номера страниц с размещением по умолчанию +## Добавление номера страниц с размещением по умолчанию Используйте `add_page_number()` без дополнительных аргументов позиции, когда вы хотите, чтобы номера страниц добавлялись в месте по умолчанию. Это самый простой способ пронумеровать каждую страницу в документе. @@ -38,7 +38,7 @@ def add_page_numbers_default(infile: str, outfile: str) -> None: pdf_stamper.close() ``` -## Добавить номера страниц в пользовательских координатах +## Добавление номера страниц в пользовательских координатах Используйте перегрузку на основе координат, когда вам нужно, чтобы номера страниц отображались в конкретных позициях X и Y на каждой странице. Такой подход полезен, когда макет документа требует пользовательского размещения. @@ -95,7 +95,7 @@ def add_page_numbers_with_position_and_margins(infile: str, outfile: str) -> Non pdf_stamper.close() ``` -## Добавить нумерацию страниц в римском стиле +## Добавление нумерацию страниц в римском стиле Функция 'add_page_numbers_with_roman_style' демонстрирует, как улучшить PDF‑документ, добавив нумерацию страниц с использованием заглавных римских цифр. Она использует класс PdfFileStamp из Aspose.PDF для применения последовательной нумерации на всех страницах. diff --git a/ru/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md b/ru/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md index 85d3f6ee3..44f20f596 100644 --- a/ru/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md +++ b/ru/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md @@ -13,7 +13,7 @@ Abstract: В этой статье объясняется, как добавит Aspose.PDF for Python via .NET предоставляет [PdfFileStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilestamp/) Фасад для добавления повторяющегося контента на страницы PDF. Помимо заголовков, нижних колонтитулов и номеров страниц, его можно использовать для размещения текстовых штампов на каждой странице документа. -## Добавить штамп в PDF +## Добавление штамп в PDF После настройки штампа привяжите входной PDF к `PdfFileStamp`, добавить штамп, и сохранить выходной файл. Это применяет настроенный штамп по всему документу. diff --git a/ru/python-net/working-with-facades/stamp/_index.md b/ru/python-net/working-with-facades/stamp/_index.md index d66a1d27c..514515a7b 100644 --- a/ru/python-net/working-with-facades/stamp/_index.md +++ b/ru/python-net/working-with-facades/stamp/_index.md @@ -56,7 +56,7 @@ def _create_text_state() -> ap.text.TextState: return text_state ``` -## Добавить штамп изображения +## Добавление штамп изображения Используйте `bind_image()` когда штамп должен отображать изображение, такое как логотип, значок или иконка. После привязки изображения вы можете установить идентификатор штампа и его исходную точку перед добавлением его в документ. @@ -88,7 +88,7 @@ def add_image_stamp(infile: str, image_file: str, outfile: str) -> None: pdf_stamper.close() ``` -## Добавить страницу PDF в качестве штампа +## Добавление страницу PDF в качестве штампа Используйте `bind_pdf()` когда вы хотите использовать страницу из другого PDF‑файла в качестве содержимого штампа. Это полезно для наложений, таких как утверждения, шаблоны или заранее созданные визуальные элементы, хранящиеся в отдельном документе. @@ -120,7 +120,7 @@ def add_pdf_page_as_stamp(infile: str, stamp_pdf: str, outfile: str) -> None: pdf_stamper.close() ``` -## Добавить TextStamp с текстовым состоянием +## Добавление TextStamp с текстовым состоянием Используйте `bind_logo()` вместе с `bind_text_state()` когда вы хотите создать текстовую печать с пользовательским оформлением шрифта. Этот подход полезен для отметок одобрения, меток и аннотаций, специфичных для рабочего процесса. @@ -153,7 +153,7 @@ def add_text_stamp_with_text_state(infile: str, outfile: str) -> None: pdf_stamper.close() ``` -## Добавить штамп на определённые страницы +## Добавление штамп на определённые страницы Если штамп не должен отображаться на каждой странице, назначьте целевые номера страниц `pages` свойство. В этом примере добавляется штамп изображения только на первую страницу. @@ -186,7 +186,7 @@ def add_stamp_to_specific_pages(infile: str, image_file: str, outfile: str) -> N pdf_stamper.close() ``` -## Добавить фоновый ImageStamp +## Добавление фонового ImageStamp Используйте фоновый штамп, когда изображение должно располагаться позади содержимого страницы. Вы также можете управлять непрозрачностью штампа, его поворотом, качеством, размером и положением, чтобы создать эффекты в стиле водяного знака. From 500eb957797af805050d00f9e0ea2a6ee99d08fc Mon Sep 17 00:00:00 2001 From: Andriy Andruhovski Date: Thu, 14 May 2026 14:59:42 +0300 Subject: [PATCH 08/13] Update Russian documentation for consistency in headings and section titles across multiple files --- .../create-tagged-pdf-documents/_index.md | 2 +- .../setting-structure-elements-properties/_index.md | 2 +- .../security-annotations/_index.md | 4 ++-- .../annotations/import-export-annotations/_index.md | 2 +- .../attachments/extract-attachment/_index.md | 4 ++-- .../advanced-operations/attachments/portfolio/_index.md | 2 +- .../removing-attachment-from-an-existing-pdf/_index.md | 2 +- .../extract-signature-info/_index.md | 2 +- .../working-with-documents/create-pdf-document/_index.md | 4 ++-- .../manipulate-pdf-document/_index.md | 2 +- .../optimize-pdf-document/_index.md | 2 +- .../working-with-forms/acroforms/posting-form/_index.md | 2 +- .../working-with-graphs/line/_index.md | 2 +- .../working-with-pages/move-pages/_index.md | 4 ++-- ru/python-net/basic-operations/create/_index.md | 2 +- ru/python-net/parsing/_index.md | 9 ++++++++- ru/python-net/whatsnew/_index.md | 2 +- .../pdffilesignature/signature-verification/_index.md | 2 +- 18 files changed, 29 insertions(+), 22 deletions(-) diff --git a/ru/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/_index.md b/ru/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/_index.md index d96e06234..47eff9dc1 100644 --- a/ru/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/_index.md +++ b/ru/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/_index.md @@ -205,7 +205,7 @@ def illustrate_structure_elements(imagefile, outfile): document.save(outfile) ``` -## Проверить Tagged PDF +## Проверка Tagged PDF Aspose.PDF for Python via .NET предоставляет возможность проверять PDF/UA Tagged PDF Document. Метод ‘validate_tagged_pdf’ проверяет PDF‑документы в соответствии со стандартом PDF/UA-1, который является частью спецификации ISO 14289 для доступных PDF‑документов. Это гарантирует, что PDF‑файлы доступны пользователям с ограниченными возможностями и вспомогательными технологиями. diff --git a/ru/python-net/advanced-operations/accessibility-tagged-pdf/setting-structure-elements-properties/_index.md b/ru/python-net/advanced-operations/accessibility-tagged-pdf/setting-structure-elements-properties/_index.md index 3814ca285..a8919cca3 100644 --- a/ru/python-net/advanced-operations/accessibility-tagged-pdf/setting-structure-elements-properties/_index.md +++ b/ru/python-net/advanced-operations/accessibility-tagged-pdf/setting-structure-elements-properties/_index.md @@ -579,7 +579,7 @@ def set_note_element(outfile): document.save(outfile) ``` -## Как установить язык и заголовок +## Установка языка и заголовка Aspose.PDF for Python via .NET API также позволяет задать язык и заголовок для документа в соответствии со спецификацией PDF/UA. Язык может быть установлен как для всего документа, так и для его отдельных структурных элементов. Следующий фрагмент кода показывает, как et язык и заголовок в Tagged PDF Document: diff --git a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/security-annotations/_index.md b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/security-annotations/_index.md index 89dbbbf04..20db54dc9 100644 --- a/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/security-annotations/_index.md +++ b/ru/python-net/advanced-operations/annotations/add-delete-and-get-annotation/security-annotations/_index.md @@ -59,7 +59,7 @@ for text_fragment in text_fragment_absorber.text_fragments: page.annotations.add(redaction_annotation, True) ``` -### Сохранение помеченный PDF +### Сохранение помеченного PDF ```python document.save(outfile) @@ -118,7 +118,7 @@ for redaction_annotation in redaction_annotations: cast(ap.annotations.RedactionAnnotation, redaction_annotation).redact() ``` -### Сохранение отредактированный PDF +### Сохранение отредактированного PDF ```python document.save(outfile) diff --git a/ru/python-net/advanced-operations/annotations/import-export-annotations/_index.md b/ru/python-net/advanced-operations/annotations/import-export-annotations/_index.md index 9fc6266ae..2c35bad8e 100644 --- a/ru/python-net/advanced-operations/annotations/import-export-annotations/_index.md +++ b/ru/python-net/advanced-operations/annotations/import-export-annotations/_index.md @@ -26,7 +26,7 @@ Abstract: В этой статье объясняется, как копиров source_document = ap.Document(infile) ``` -## Создание целевой PDF +## Создание целевого PDF Затем создайте пустой PDF‑документ, который будет принимать импортированные аннотации. На данном этапе целевой документ не содержит страниц. diff --git a/ru/python-net/advanced-operations/attachments/extract-attachment/_index.md b/ru/python-net/advanced-operations/attachments/extract-attachment/_index.md index bde14dae9..8bf947e08 100644 --- a/ru/python-net/advanced-operations/attachments/extract-attachment/_index.md +++ b/ru/python-net/advanced-operations/attachments/extract-attachment/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: "Полное руководство по управлен Abstract: PDF‑вложения широко используются для хранения сопутствующих документов, отчетов, изображений и других ресурсов непосредственно внутри файла PDF. В этой статье представлено полное руководство по работе с PDF‑вложениями в Python с использованием Aspose.PDF. Описывается, как внедрять внешние файлы в существующие PDF, извлекать отдельные или все вложения, просматривать метаданные, такие как размер файла и метки времени, а также восстанавливать файлы, сохранённые как аннотации FileAttachment. Каждый пример демонстрирует практические методы автоматизации процессов работы с вложениями, повышения переносимости документов и упрощения управления файлами. Независимо от того, создаёте ли вы корпоративные системы документооборота или пользовательские скрипты автоматизации, разработчики могут использовать эти методы для эффективного управления вложенными файлами в PDF‑документах. --- -## Извлечение конкретное вложение из PDF +## Извлечение конкретного вложения из PDF Извлеките один встраиваемый файл из PDF‑документа с помощью Python и Aspose.PDF. Он ищет вложение по имени, извлекает его содержимое и сохраняет как отдельный файл. Это полезно для доступа к вложенным документам, таким как отчёты, журналы или вспомогательные файлы, хранящиеся внутри PDF. @@ -57,7 +57,7 @@ def _print_file_params(params): print(f"Size: {params.size}") ``` -## Извлечение и проверить все вложения PDF +## Извлечение и проверка всех вложений PDF Этот фрагмент кода демонстрирует, как извлекать все вложенные файлы из PDF‑документа с использованием Python и Aspose.PDF. Он не только сохраняет каждое вложение в указанную папку, но и выводит подробные метаданные, такие как имя файла, описание, тип MIME, контрольная сумма и метки времени. Это полезно для аудита, экспорта или обработки вложенного контента в PDF‑файлах. diff --git a/ru/python-net/advanced-operations/attachments/portfolio/_index.md b/ru/python-net/advanced-operations/attachments/portfolio/_index.md index 91c66b734..f6f308783 100644 --- a/ru/python-net/advanced-operations/attachments/portfolio/_index.md +++ b/ru/python-net/advanced-operations/attachments/portfolio/_index.md @@ -20,7 +20,7 @@ PDF‑портфель поможет продемонстрировать ва Используйте PDF‑портфель, когда хотите распределить набор связанных файлов вместе, сохранив каждый файл в его исходном формате внутри одного PDF‑контейнера. -## Как создать PDF‑портфель +## Создание PDF‑портфеля Aspose.PDF for Python via .NET позволяет создавать документы PDF‑портфеля, используя [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) class. Добавьте файл в объект document.collection после получения его с помощью [FileSpecification](https://reference.aspose.com/pdf/python-net/aspose.pdf/filespecification/) class. После добавления файлов используйте Document class' [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) метод для сохранения документа портфеля. diff --git a/ru/python-net/advanced-operations/attachments/removing-attachment-from-an-existing-pdf/_index.md b/ru/python-net/advanced-operations/attachments/removing-attachment-from-an-existing-pdf/_index.md index e965ba091..a9c5761b1 100644 --- a/ru/python-net/advanced-operations/attachments/removing-attachment-from-an-existing-pdf/_index.md +++ b/ru/python-net/advanced-operations/attachments/removing-attachment-from-an-existing-pdf/_index.md @@ -36,7 +36,7 @@ def remove_attachment(infile, outfile): document.save(outfile) ``` -## Удаление конкретное вложение по имени +## Удаление конкретного вложения по имени Если вам нужно удалить только одно вложение и оставить остальные, используйте [delete_by_key()](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/delete_by_key/) метод и передайте имя вложения. diff --git a/ru/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md b/ru/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md index 21e374dd9..12286291e 100644 --- a/ru/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md +++ b/ru/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md @@ -111,7 +111,7 @@ def extract_certificate_try_extract_certificate_method(infile: str) -> None: print("The certificate extraction succeeded") ``` -## Проверить внешние цифровые подписи +## Проверка внешних цифровых подписей Чтобы подтвердить, что документ не был изменён после подписания, проверьте каждую внешнюю подпись, используя `PdfFileSignature.verify_signature()`. Пример ниже вызывает исключение для любой подписи, которая не проходит проверку: diff --git a/ru/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md b/ru/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md index f6cc8af72..69fee52f2 100644 --- a/ru/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md +++ b/ru/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md @@ -18,7 +18,7 @@ Abstract: Aspose.PDF for Python via .NET — это универсальный A Используйте эти примеры, когда вам нужно создать новые PDF-файлы с нуля или преобразовать вывод OCR в поисковые PDF-документы на Python. -## Как создать простой PDF-файл +## Создание простого PDF-файла Чтобы создать PDF с помощью Python via .NET и Aspose.PDF, вы можете выполнить следующие шаги: @@ -40,7 +40,7 @@ def create_new_document(output_pdf): document.save(output_pdf) ``` -## Как создать поисковый PDF‑документ +## Создание поискового PDF‑документа Aspose.PDF for Python via .NET позволяет создавать и изменять существующие PDF‑документы. При добавлении текстовых элементов в PDF‑файл полученный PDF становится поисковым. Однако при преобразовании изображения, содержащего текст, в PDF‑файл содержимое получаемого PDF не является поисковым. В качестве обходного решения мы можем применить OCR к полученному файлу, чтобы он стал поисковым. diff --git a/ru/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md b/ru/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md index 5d80c5eed..7f089143e 100644 --- a/ru/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md +++ b/ru/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md @@ -139,7 +139,7 @@ def set_toc_levels(input_pdf, output_pdf): document.save(output_pdf) ``` -### Скрыть номера страниц в оглавлении +### Скрытие номеров страниц в оглавлении В случае, если вы не хотите отображать номера страниц вместе с заголовками в TOC, вы можете использовать [is_show_page_numbers](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/#properties) свойство [TocInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/) Class как false. Пожалуйста, проверьте следующий фрагмент кода, чтобы скрыть номера страниц в оглавлении: diff --git a/ru/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md b/ru/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md index ad279ea21..496bfe753 100644 --- a/ru/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md +++ b/ru/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md @@ -249,7 +249,7 @@ def unembed_fonts(infile, outfile): Оптимизационные ресурсы применяют эти методы к документу. Если любой из этих методов будет применён, размер документа, скорее всего, уменьшится. Если ни один из этих методов не будет применён, размер документа не изменится, что очевидно. -## Дополнительные способы уменьшить размер PDF‑документа +## Дополнительные способы уменьшения размера PDF‑документа ### Удаление или уплощение аннотаций diff --git a/ru/python-net/advanced-operations/working-with-forms/acroforms/posting-form/_index.md b/ru/python-net/advanced-operations/working-with-forms/acroforms/posting-form/_index.md index cbe05df2b..737c7f726 100644 --- a/ru/python-net/advanced-operations/working-with-forms/acroforms/posting-form/_index.md +++ b/ru/python-net/advanced-operations/working-with-forms/acroforms/posting-form/_index.md @@ -34,7 +34,7 @@ def add_submit_button(input_file_name, output_file_name): editor.save() ``` -## Добавление пользовательское действие отправки +## Добавление пользовательского действия отправки Следующий фрагмент кода объясняет, как создать пользовательскую кнопку отправки в PDF-форме с использованием Aspose.PDF for Python via .NET. Кнопка настроена на отправку данных формы по указанному URL при нажатии. diff --git a/ru/python-net/advanced-operations/working-with-graphs/line/_index.md b/ru/python-net/advanced-operations/working-with-graphs/line/_index.md index bb1f3c4f7..26359213f 100644 --- a/ru/python-net/advanced-operations/working-with-graphs/line/_index.md +++ b/ru/python-net/advanced-operations/working-with-graphs/line/_index.md @@ -48,7 +48,7 @@ def add_line(outfile: str): ![Добавить линию](add_line.png) -## Как добавить пунктирно‑штриховую линию в ваш PDF‑документ +## Добавление пунктирно‑штриховой линии в PDF‑документ ```python import aspose.pdf as ap diff --git a/ru/python-net/advanced-operations/working-with-pages/move-pages/_index.md b/ru/python-net/advanced-operations/working-with-pages/move-pages/_index.md index 3c6229eb9..7ee478a8e 100644 --- a/ru/python-net/advanced-operations/working-with-pages/move-pages/_index.md +++ b/ru/python-net/advanced-operations/working-with-pages/move-pages/_index.md @@ -14,7 +14,7 @@ AlternativeHeadline: Переместить страницы PDF между до Abstract: В этой статье объясняется, как перемещать страницы в PDF с помощью Aspose.PDF for Python via .NET. Узнайте, как переместить одну страницу или несколько страниц в другой документ, а также как изменить положение страницы в том же PDF, используя API Document и PageCollection. --- -## Переместить страницу из одного PDF‑документа в другой +## Перемещение страницы из одного PDF‑документа в другой Aspose.PDF for Python позволяет переместить страницу (а не только скопировать её) из одного PDF в другой. Она удаляет выбранную страницу из оригинального документа, а затем добавляет её в новый PDF‑файл. @@ -45,7 +45,7 @@ def move_page_from_one_document_to_another( another_document.save(output_file_name) ``` -## Переместить несколько страниц из одного PDF‑документа в другой +## Перемещение нескольких страниц из одного PDF‑документа в другой В отличие от копирования, эта операция перемещает выбранные страницы — удаляя их из исходного файла и сохраняя в новом PDF. diff --git a/ru/python-net/basic-operations/create/_index.md b/ru/python-net/basic-operations/create/_index.md index f33b4905c..222d0e146 100644 --- a/ru/python-net/basic-operations/create/_index.md +++ b/ru/python-net/basic-operations/create/_index.md @@ -13,7 +13,7 @@ Abstract: В разработке программного обеспечени Для разработчиков существует множество сценариев, когда становится необходимо программно генерировать PDF‑файлы. Вам может потребоваться программно создавать PDF‑отчёты и другие PDF‑файлы в вашем программном обеспечении. Писать собственный код и функции с нуля довольно долго и неэффективно. Чтобы создать PDF‑файл с помощью Python, существует лучшее решение — **Aspose.PDF for Python via .NET**. -## Как создать PDF‑файл с использованием Python +## Создание PDF‑файла с использованием Python Чтобы создать PDF‑файл с помощью Python, можно использовать следующие шаги. diff --git a/ru/python-net/parsing/_index.md b/ru/python-net/parsing/_index.md index 664b2d9f7..013c439b4 100644 --- a/ru/python-net/parsing/_index.md +++ b/ru/python-net/parsing/_index.md @@ -11,4 +11,11 @@ sitemap: priority: 0.7 --- -**Разбор PDF** документов - это термин, связанный с извлечением различной информации из PDF файла. Этот раздел охватывает, как: \ No newline at end of file +**Разбор PDF** документов - это термин, связанный с извлечением различной информации из PDF файла. Этот раздел охватывает, как: + +- [Извлечение текста из PDF](/ru/pdf/python-net/extract-text-from-pdf/). Разбор или извлечение текста — одна из самых популярных операций с готовыми PDF. Вы узнаете, как извлекать текст из всего документа, отдельной страницы или определённой области страницы. +- [Извлечение изображений из PDF](/ru/pdf/python-net/extract-images-from-the-pdf-file/). Извлечение изображений выполняет для изображений ту же задачу, что и операция выше для текста. +- [Извлечение шрифтов из PDF](/ru/pdf/python-net/extract-fonts-from-pdf/). Извлечение шрифтов — специализированная операция для работы со шрифтами в PDF. +- [Извлечение данных из формы](/ru/pdf/python-net/extract-data-from-acroform/). Если у вас много PDF-документов с формами, вероятно, вам нужно получать данные из этих форм. Эта статья поможет понять, как извлекать данные AcroForms с помощью Aspose.PDF for Python via .NET. +- [Извлечение данных из таблицы](/ru/pdf/python-net/extract-data-from-table-in-pdf/). Получение данных из таблицы в PDF-документе. +- [Извлечение векторных данных из PDF](/ru/pdf/python-net/extract-vector-data-from-pdf/). Вы можете извлекать векторные данные (path, polygon, polyline), такие как позиция, цвет, толщина линии и т. д. diff --git a/ru/python-net/whatsnew/_index.md b/ru/python-net/whatsnew/_index.md index a70c55279..bbf341073 100644 --- a/ru/python-net/whatsnew/_index.md +++ b/ru/python-net/whatsnew/_index.md @@ -439,7 +439,7 @@ def add_tagged_image_from_stream(self, image_file, outfile): 1. Изменить размер страниц PDF с масштабированием содержимого. 1. Применить пунктирные границы к таблицам. -### Создание помеченное оглавление (TOC) +### Создание помеченного оглавления (TOC) Автоматически генерировать доступные оглавления (TOC) в Tagged PDF. Создание полностью доступного оглавления (TOC) в PDF позволяет читателям эффективно перемещаться по документу и обеспечивает соответствие требованиям PDF/UA-1 по доступности. diff --git a/ru/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md b/ru/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md index 59661dbc0..4257ca93a 100644 --- a/ru/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md +++ b/ru/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md @@ -21,7 +21,7 @@ Aspose.PDF for Python via .NET предоставляет [PdfFileSignature](htt 1. Проверьте, действительна ли существующая подпись PDF. 1. Проверьте, содержит ли PDF какие-либо подписи. -## Проверить подпись PDF +## Проверка подписи PDF Используйте `verify_signature()` когда вам нужно проверить конкретную подпись в документе. Пример определяет первое доступное имя подписи и проверяет, действительна ли эта подпись. From fed093eeedee90676e90e7d05570b8b6334f1aad Mon Sep 17 00:00:00 2001 From: Andriy Andruhovski Date: Thu, 14 May 2026 15:01:51 +0300 Subject: [PATCH 09/13] Fix URLs in Russian documentation for PDF extraction methods to ensure correct navigation and consistency. --- ru/python-net/parsing/_index.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/ru/python-net/parsing/_index.md b/ru/python-net/parsing/_index.md index 013c439b4..7e45ee76c 100644 --- a/ru/python-net/parsing/_index.md +++ b/ru/python-net/parsing/_index.md @@ -13,9 +13,9 @@ sitemap: **Разбор PDF** документов - это термин, связанный с извлечением различной информации из PDF файла. Этот раздел охватывает, как: -- [Извлечение текста из PDF](/ru/pdf/python-net/extract-text-from-pdf/). Разбор или извлечение текста — одна из самых популярных операций с готовыми PDF. Вы узнаете, как извлекать текст из всего документа, отдельной страницы или определённой области страницы. -- [Извлечение изображений из PDF](/ru/pdf/python-net/extract-images-from-the-pdf-file/). Извлечение изображений выполняет для изображений ту же задачу, что и операция выше для текста. -- [Извлечение шрифтов из PDF](/ru/pdf/python-net/extract-fonts-from-pdf/). Извлечение шрифтов — специализированная операция для работы со шрифтами в PDF. -- [Извлечение данных из формы](/ru/pdf/python-net/extract-data-from-acroform/). Если у вас много PDF-документов с формами, вероятно, вам нужно получать данные из этих форм. Эта статья поможет понять, как извлекать данные AcroForms с помощью Aspose.PDF for Python via .NET. -- [Извлечение данных из таблицы](/ru/pdf/python-net/extract-data-from-table-in-pdf/). Получение данных из таблицы в PDF-документе. -- [Извлечение векторных данных из PDF](/ru/pdf/python-net/extract-vector-data-from-pdf/). Вы можете извлекать векторные данные (path, polygon, polyline), такие как позиция, цвет, толщина линии и т. д. +- [Извлечение текста из PDF](/pdf/ru/python-net/extract-text-from-pdf/). Разбор или извлечение текста — одна из самых популярных операций с готовыми PDF. Вы узнаете, как извлекать текст из всего документа, отдельной страницы или определённой области страницы. +- [Извлечение изображений из PDF](/pdf/ru/python-net/extract-images-from-the-pdf-file/). Извлечение изображений выполняет для изображений ту же задачу, что и операция выше для текста. +- [Извлечение шрифтов из PDF](/pdf/ru/python-net/extract-fonts-from-pdf/). Извлечение шрифтов — специализированная операция для работы со шрифтами в PDF. +- [Извлечение данных из формы](/pdf/ru/python-net/extract-data-from-acroform/). Если у вас много PDF-документов с формами, вероятно, вам нужно получать данные из этих форм. Эта статья поможет понять, как извлекать данные AcroForms с помощью Aspose.PDF for Python via .NET. +- [Извлечение данных из таблицы](/pdf/ru/python-net/extract-data-from-table-in-pdf/). Получение данных из таблицы в PDF-документе. +- [Извлечение векторных данных из PDF](/pdf/ru/python-net/extract-vector-data-from-pdf/). Вы можете извлекать векторные данные (path, polygon, polyline), такие как позиция, цвет, толщина линии и т. д. From a18c4c6249878b03f475532c8bfbfea0d0943f2f Mon Sep 17 00:00:00 2001 From: AnHolub <68945813+AnHolub@users.noreply.github.com> Date: Mon, 18 May 2026 13:43:23 +0300 Subject: [PATCH 10/13] Fix links (#583) * fixed links * added minor fixes --- .codex-temp.json | 12 -- .../basic-operations/merge-pdf/_index.md | 2 +- .../basic-operations/split-pdf/_index.md | 2 +- en/python-net/overview/_index.md | 2 +- .../pdfcontenteditor/annotations/_index.md | 2 +- .../pdfcontenteditor/attachments/_index.md | 2 +- .../links-and-navigation/_index.md | 2 +- .../delete-stamp-by-index/_index.md | 41 ++----- .../basic-operations/merge-pdf/_index.md | 2 +- .../basic-operations/split-pdf/_index.md | 2 +- .../pdfcontenteditor/annotations/_index.md | 2 +- .../pdfcontenteditor/attachments/_index.md | 2 +- .../links-and-navigation/_index.md | 2 +- ru/python-net/advanced-operations/_index.md | 102 ++++------------ .../basic-operations/merge-pdf/_index.md | 2 +- .../basic-operations/split-pdf/_index.md | 2 +- ru/python-net/get-started/_index.md | 59 ++++----- ru/python-net/overview/_index.md | 42 +++---- ru/python-net/overview/installation/_index.md | 38 +++--- ru/python-net/overview/key-features/_index.md | 112 ++++++++++-------- ru/python-net/overview/licensing/_index.md | 26 ++-- .../overview/supported-file-formats/_index.md | 45 +++---- .../overview/system-requirements/_index.md | 37 +++--- .../overview/technical-support/_index.md | 29 +++-- .../pdfcontenteditor/annotations/_index.md | 2 +- .../pdfcontenteditor/attachments/_index.md | 2 +- .../links-and-navigation/_index.md | 2 +- 27 files changed, 262 insertions(+), 313 deletions(-) delete mode 100644 .codex-temp.json diff --git a/.codex-temp.json b/.codex-temp.json deleted file mode 100644 index 501965719..000000000 --- a/.codex-temp.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "generatedAtUtc": "2026-05-14T08:25:54.6786942Z", - "inputRoot": "D:\\Work\\Hugo\\Deploy\\Aspose.PDF-Documentation\\en\\python-net\\working-with-facades\\pdfcontenteditor\\stamps-management", - "outputRoot": "D:\\Work\\Hugo\\Deploy\\Aspose.PDF-Documentation\\ru\\python-net\\pdfcontenteditor\\stamps-management", - "totalFiles": 11, - "translatedCount": 11, - "skippedCount": 0, - "failureCount": 0, - "validationWarningCount": 0, - "failures": [], - "validationWarnings": [] -} \ No newline at end of file diff --git a/en/python-net/basic-operations/merge-pdf/_index.md b/en/python-net/basic-operations/merge-pdf/_index.md index 8218c69a3..bd5afde71 100644 --- a/en/python-net/basic-operations/merge-pdf/_index.md +++ b/en/python-net/basic-operations/merge-pdf/_index.md @@ -3,7 +3,7 @@ title: Merge PDF Files in Python linktitle: Merge PDF files type: docs weight: 50 -url: /python-net/merge-pdf-documents/ +url: /python-net/merge-pdf/ description: Learn how to merge multiple PDF files into a single document in Python. lastmod: "2026-04-15" sitemap: diff --git a/en/python-net/basic-operations/split-pdf/_index.md b/en/python-net/basic-operations/split-pdf/_index.md index d5a4402c2..801ac1c35 100644 --- a/en/python-net/basic-operations/split-pdf/_index.md +++ b/en/python-net/basic-operations/split-pdf/_index.md @@ -3,7 +3,7 @@ title: Split PDF Files in Python linktitle: Split PDF files type: docs weight: 60 -url: /python-net/split-pdf-document/ +url: /python-net/split-pdf/ description: Learn how to split PDF pages into separate PDF files in Python. lastmod: "2026-04-15" sitemap: diff --git a/en/python-net/overview/_index.md b/en/python-net/overview/_index.md index c261f955a..b8c548e2c 100644 --- a/en/python-net/overview/_index.md +++ b/en/python-net/overview/_index.md @@ -29,7 +29,7 @@ The Aspose.PDF for Python supports a wide variety of functions such as: In addition, Aspose.PDF for Python via .NET can be applied to easily convert EPUB, Markdown, Text, XPS, PostScript, XML, LaTex to PDF and convert PDF to various document formats with excellent performance and good quality. -Try our [Free Online Apps](https://products.aspose.app/pdf/applications) demonstrating some of the most popular Aspose.PDF functionality. +Try our [Online Apps](https://products.aspose.app/pdf/applications) that demonstrate some of the most popular Aspose.PDF functionality. Learn more about: diff --git a/en/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md index 6980a8790..a7c27cb40 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md @@ -2,7 +2,7 @@ title: Annotations type: docs weight: 10 -url: /python-net/annotations/ +url: /python-net/annotations-facades/ description: lastmod: "2026-03-20" sitemap: diff --git a/en/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md index 7b00fc812..eee945534 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md @@ -2,7 +2,7 @@ title: Attachments type: docs weight: 20 -url: /python-net/attachments/ +url: /python-net/attachments-facades/ description: lastmod: "2026-03-20" sitemap: diff --git a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md index e57255180..169f0400f 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md @@ -2,7 +2,7 @@ title: Links and Navigation type: docs weight: 70 -url: /python-net/links-and-navigation/ +url: /python-net/links-and-navigation-facades/ description: lastmod: "2026-03-20" sitemap: diff --git a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md index faea38d3b..e49ab71cc 100644 --- a/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md +++ b/en/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md @@ -1,25 +1,25 @@ --- -title: Move Stamp By Index +title: Delete Stamp By Index type: docs weight: 50 -url: /python-net/move-stamp-by-index/ -description: This example creates two rubber stamps on page 2. After that, a stamp can be moved by specifying its index and new coordinates. +url: /python-net/delete-stamp-by-index/ +description: This example creates two rubber stamps on page 2. After that, a stamp can be deleted by specifying its index. lastmod: "2026-03-20" sitemap: changefreq: "weekly" priority: 0.7 TechArticle: true -AlternativeHeadline: Move a Rubber Stamp by Index in a PDF Using PdfContentEditor in Python -Abstract: This example demonstrates how to reposition a rubber stamp annotation in a PDF using its index with Aspose.PDF for Python via the Facades API. It shows how to add multiple stamps and then move one of them based on its order on the page. +AlternativeHeadline: Delete a Rubber Stamp by Index in a PDF Using PdfContentEditor in Python +Abstract: This example demonstrates how to delete a rubber stamp annotation in a PDF using its index with Aspose.PDF for Python via the Facades API. It shows how to add multiple stamps and then delete one of them based on its order on the page. --- -When multiple rubber stamps exist on a page, you can move a specific one using its index. The move_stamp() method allows repositioning annotations according to their sequence, which is useful when you don’t track stamp IDs but know their order. +When multiple rubber stamps exist on a page, you can delete a specific one using its index. The delete_stamp() method allows removing annotations according to their sequence, which is useful when you don’t track stamp IDs but know their order. 1. Create a [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) instance. 1. Bind the input PDF document. -1. Add two rubber stamp annotations on the same page. -1. Demonstrate how to move a stamp using its index. -1. Save the updated PDF document. +1. Bind the input PDF file to the PdfContentEditor instance using bind_pdf(infile). +1. Call 'delete_stamp(1, [2, 3])' to remove the stamp with index 1 from pages 2 and 3. +1. Save the modified PDF document to the output file using save(outfile). ```python import aspose.pdf.facades as pdf_facades @@ -33,31 +33,12 @@ sys.path.append(path.join(path.dirname(__file__), "..")) from config import set_license, initialize_data_dir -def move_stamp_by_index(infile, outfile): +def delete_stamp_by_index(infile, outfile): # Create PdfContentEditor object content_editor = pdf_facades.PdfContentEditor() # Bind document to PdfContentEditor content_editor.bind_pdf(infile) - - content_editor.create_rubber_stamp( - 2, - apd.Rectangle(200, 380, 180, 60), - "Draft", - "Draft stamp for ID-based operations", - apd.Color.orange, - ) - - content_editor.create_rubber_stamp( - 2, - apd.Rectangle(200, 480, 180, 60), - "Draft", - "Draft stamp for ID-based operations", - apd.Color.orange, - ) - content_editor.save(outfile) - - # Move first stamp on page 1 by index - # content_editor.move_stamp(1, 1, 10, 10) + content_editor.delete_stamp(1, [2, 3]) # Save updated document content_editor.save(outfile) ``` diff --git a/es/python-net/basic-operations/merge-pdf/_index.md b/es/python-net/basic-operations/merge-pdf/_index.md index cfb4befcc..c711f1118 100644 --- a/es/python-net/basic-operations/merge-pdf/_index.md +++ b/es/python-net/basic-operations/merge-pdf/_index.md @@ -3,7 +3,7 @@ title: Combinar archivos PDF en Python linktitle: Combinar archivos PDF type: docs weight: 50 -url: /es/python-net/merge-pdf-documents/ +url: /es/python-net/merge-pdf/ description: Aprenda cómo combinar varios archivos PDF en un solo documento en Python. lastmod: "2026-05-08" sitemap: diff --git a/es/python-net/basic-operations/split-pdf/_index.md b/es/python-net/basic-operations/split-pdf/_index.md index 7579df5ae..f92a1a30e 100644 --- a/es/python-net/basic-operations/split-pdf/_index.md +++ b/es/python-net/basic-operations/split-pdf/_index.md @@ -3,7 +3,7 @@ title: Dividir archivos PDF en Python linktitle: Dividir archivos PDF type: docs weight: 60 -url: /es/python-net/split-pdf-document/ +url: /es/python-net/split-pdf/ description: Aprenda cómo dividir páginas PDF en archivos PDF separados en Python. lastmod: "2026-04-15" sitemap: diff --git a/es/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md index 9796861ae..2faad6d69 100644 --- a/es/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md +++ b/es/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md @@ -3,7 +3,7 @@ title: Anotaciones linktitle: Anotaciones type: docs weight: 10 -url: /es/python-net/annotations/ +url: /es/python-net/annotations-facades/ description: lastmod: "2026-03-20" sitemap: diff --git a/es/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md index 57af42004..f3ea6b659 100644 --- a/es/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md +++ b/es/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md @@ -3,7 +3,7 @@ title: Adjuntos linktitle: Adjuntos type: docs weight: 20 -url: /es/python-net/attachments/ +url: /es/python-net/attachments-facades/ description: lastmod: "2026-03-20" sitemap: diff --git a/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md index 24365872b..1611fce23 100644 --- a/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md +++ b/es/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md @@ -3,7 +3,7 @@ title: Enlaces y navegación linktitle: Enlaces y navegación type: docs weight: 70 -url: /es/python-net/links-and-navigation/ +url: /es/python-net/links-and-navigation-facades/ description: lastmod: "2026-03-20" sitemap: diff --git a/ru/python-net/advanced-operations/_index.md b/ru/python-net/advanced-operations/_index.md index 72724cdca..a34440243 100644 --- a/ru/python-net/advanced-operations/_index.md +++ b/ru/python-net/advanced-operations/_index.md @@ -1,93 +1,35 @@ --- -title: Advanced operations -linktitle: Advanced operations +title: Расширенные операции +linktitle: Расширенные операции type: docs weight: 90 url: /ru/python-net/advanced-operations/ -description: Aspose.PDF for Python via .NET может выполнять простые и легкие задачи, а также справляться с более сложными целями. Ознакомьтесь со следующим разделом для продвинутых пользователей и разработчиков. -lastmod: "2023-04-17" +description: Aspose.PDF for Python via .NET может выполнять простые и лёгкие задачи и справляться с более сложными целями. Ознакомьтесь с следующим разделом для продвинутых пользователей и разработчиков. +lastmod: "2025-02-27" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Раздел «Расширенные операции» с Python +Abstract: Раздел «Расширенные операции» предоставляет всестороннее руководство по программной работе с существующими PDF‑файлами, независимо от их происхождения, с использованием различных инструментов и методов. Этот раздел расширяет базовые навыки, обсуждаемые в разделе «Basic Operations», исследуя расширенные функции. --- - - -**Расширенные операции** — это раздел о том, как программно работать с существующими PDF-файлами, будь то документы, созданные с помощью Aspose.PDF, как обсуждалось в [Основных операциях](/pdf/ru/python-net/basic-operations/), или PDF, созданные с помощью Adobe Acrobat, Google Docs, Microsoft Office, Open Office или любого другого средства создания PDF. +**Advanced Operations** — это раздел, посвящённый тому, как программно работать с существующими PDF‑файлами, будь то документы, созданные с помощью Aspose.PDF, как обсуждалось в [Базовые операции](/pdf/ru/python-net/basic-operations/), или PDF, созданные в Adobe Acrobat, Google Docs, Microsoft Office, Open Office или любом другом PDF‑производителе. Вы узнаете разные способы: -- [Работа с документами](/pdf/ru/python-net/working-with-documents/) - сжимать, разделять и объединять документы и выполнять другие операции с целым документом. -- [Работа с страницами](/pdf/ru/python-net/working-with-pages/) - добавлять, перемещать или удалять, обрезать страницы, добавлять водяные знаки, штампы и т.д. -- [Работа с изображениями](/pdf/ru/python-net/working-with-images/) - добавлять, извлекать или удалять изображения из PDF-документов. +- [Работа с документами](/pdf/ru/python-net/working-with-documents/) - сжимать, разбивать и объединять документы, а также выполнять другие операции с полным документом. +- [Работа со страницами](/pdf/ru/python-net/working-with-pages/) - добавлять, перемещать или удалять, обрезать страницы, добавлять водяные знаки, штампы и т.д. +- [Работа с изображениями](/pdf/ru/python-net/working-with-images/) - добавить, извлечь или удалить изображения из PDF‑документов. - [Вложения](/pdf/ru/python-net/attachments/) - вы узнаете, как программно добавлять и удалять вложения из PDF с помощью Python. -- [Навигация и взаимодействие](/pdf/ru/python-net/navigation-and-interaction/) - работать с действиями, закладками, навигацией по страницам. -- [Аннотации](/pdf/ru/python-net/annotations/) - аннотации позволяют пользователям добавлять пользовательский контент на страницы PDF. - Вы можете добавлять, удалять и изменять аннотации в PDF-документах. -- [Работа с таблицами](/pdf/ru/python-net/working-with-tables/) - вставка, оформление таблиц в PDF, извлечение табличных данных. -- [Работа с формами](/pdf/ru/python-net/working-with-forms/) - работа с интерактивными PDF-документами, добавление полей форм, извлечение данных. -- [Работа с текстом](/pdf/ru/python-net/working-with-text/) - добавление, форматирование, поиск и замена текста в PDF. \ No newline at end of file +- [Навигация и взаимодействие](/pdf/ru/python-net/navigation-and-interaction/) - работать с действиями, закладками, перемещаться по страницам. +- [Аннотации](/pdf/ru/python-net/annotations/) - аннотации позволяют пользователям добавлять пользовательский контент на страницы PDF. Вы можете добавлять, удалять и изменять аннотации в PDF‑документах. +- [Работа с таблицами](/pdf/ru/python-net/working-with-tables/) - вставлять, оформлять таблицы в PDF, извлекать табличные данные. +- [Работа с формами](/pdf/ru/python-net/working-with-forms/) - работать с интерактивными PDF‑документами, добавлять поля форм, извлекать данные. +- [Работа с текстом](/pdf/ru/python-net/working-with-text/) - добавлять, форматировать, искать и заменять текст в PDF. +- [Сравнение PDF документов](/pdf/ru/python-net/compare-pdf-documents/) - возможно сравнивать содержимое PDF документов. +- [Метаданные в PDFs](/pdf/ru/python-net/pdf-file-metadata/) - получать или задавать метаданные в документах, работать с данными XMP. +- [Работа с графиками](/pdf/ru/python-net/working-with-graphs/) - манипулировать формами на странице. +- [Работа с операторами](/pdf/ru/python-net/working-with-operators/) - выполнять низкоуровневые операции в PDF. +- [Артефакты](/pdf/ru/python-net/artifacts/) - работать с водяными знаками и другими специальными объектами в PDF. +- [Работа со слоями PDF](/python-net/work-with-pdf-layers/) - блокировать уровни, извлекать элементы, уплощать и объединять уровни PDF. diff --git a/ru/python-net/basic-operations/merge-pdf/_index.md b/ru/python-net/basic-operations/merge-pdf/_index.md index 8eb828036..98aeca962 100644 --- a/ru/python-net/basic-operations/merge-pdf/_index.md +++ b/ru/python-net/basic-operations/merge-pdf/_index.md @@ -3,7 +3,7 @@ title: Объединение PDF-файлов в Python linktitle: Объединение PDF-файлов type: docs weight: 50 -url: /ru/python-net/merge-pdf-documents/ +url: /ru/python-net/merge-pdf/ description: Узнайте, как объединить несколько PDF-файлов в один документ в Python. lastmod: "2026-04-15" sitemap: diff --git a/ru/python-net/basic-operations/split-pdf/_index.md b/ru/python-net/basic-operations/split-pdf/_index.md index cd27ee9d9..a8cea6d9c 100644 --- a/ru/python-net/basic-operations/split-pdf/_index.md +++ b/ru/python-net/basic-operations/split-pdf/_index.md @@ -3,7 +3,7 @@ title: Разделить PDF-файлы в Python linktitle: Разделить PDF-файлы type: docs weight: 60 -url: /ru/python-net/split-pdf-document/ +url: /ru/python-net/split-pdf/ description: Узнайте, как разделить страницы PDF на отдельные PDF-файлы в Python. lastmod: "2026-04-15" sitemap: diff --git a/ru/python-net/get-started/_index.md b/ru/python-net/get-started/_index.md index 29d7d5573..7a9d3ccfc 100644 --- a/ru/python-net/get-started/_index.md +++ b/ru/python-net/get-started/_index.md @@ -1,50 +1,51 @@ --- -title: Get Started -linktitle: Get Started +title: Начало работы +linktitle: Начало работы type: docs weight: 30 url: /ru/python-net/get-started/ -description: Этот раздел описывает основные принципы работы Aspose.PDF for Python via .NET. Библиотека Python поддерживает широкий спектр функций. +description: Узнайте, как начать работу с Aspose.PDF for Python via .NET для создания, редактирования, преобразования, проверки и извлечения содержимого из PDF‑документов. is_node: true -lastmod: "2022-12-20" +lastmod: "2026-04-14" sitemap: changefreq: "monthly" priority: 0.7 --- -## Что такое PDF файл? +## Что такое PDF‑файл? -PDF был создан Adobe в 1990-х годах для достижения двух целей. Первая заключается в том, что вы должны иметь возможность открывать документы на любом оборудовании или операционной системе, без необходимости иметь приложение, использованное для их создания — все, что вам нужно, это PDF-ридер, и в наши дни большинство веб-браузеров справляются с этой задачей. Вторая заключается в том, что где бы вы ни открыли PDF, макет документа должен выглядеть одинаково. +PDF был создан компанией Adobe в 1990‑х годах с целью достичь двух задач. Первая — вы должны быть в состоянии открыть документы на любом оборудовании или операционной системе, не требуя наличия приложения, использованного для их создания; всё, что нужно, — это PDF‑читалка, и в наши дни большинство веб‑браузеров подходят для этой задачи. Вторая — независимо от того, где вы открываете PDF, макет документа должен выглядеть одинаково. -Однако, недостаточно просто открыть ваш документ. Работая с PDF, вы столкнетесь с необходимостью создать такой документ заново, отредактировать его или преобразовать в нужный вам формат. +Aspose.PDF for Python via .NET помогает вам выйти за пределы простого открытия PDF‑файлов. Вы можете использовать библиотеку для создания PDF‑документов с нуля, редактирования существующих документов, извлечения содержимого, проверки соответствия стандартам и преобразования PDF‑файлов в другие форматы в приложениях Python. -## Почему использовать Aspose.PDF for Python via .NET? +## Зачем использовать Aspose.PDF for Python via .NET? -Использование Aspose.PDF for Python via .NET в вашем проекте дает вам следующие преимущества: +Использование Aspose.PDF for Python via .NET в вашем проекте дает следующие преимущества: -- широкий спектр функций -- на основе Aspose.PDF для .NET -- удобство и простота использования +- Широкий набор функций обработки PDF +- Доступ к проверенному движку Aspose.PDF for .NET из Python +- Практический API для общих задач создания, редактирования, анализа и конвертации документов -## Широкий спектр функций +## Общие задачи PDF, которые вы можете автоматизировать -- Поддерживает большинство устоявшихся стандартов PDF и спецификаций PDF. -- [Добавление, поиск, извлечение и замена текста в PDF-файлах](). -- [Добавление/удаление, извлечение и замена изображений](). -- [Вставка, удаление, разбиение страниц PDF](). -- [Установка и получение XMP метаданных](). -- [Валидация (PDF/A-1a, PDF/A-1b)](). -- Работа с [закладками](), [аннотациями](), [формами PDF](), [штампами](), [водяными знаками]() и многим другим. +- Поддержка широко используемых стандартов и спецификаций PDF +- [Добавлять, искать, извлекать и заменять текст в PDF‑файлах](/pdf/ru/python-net/working-with-text/) +- [Добавлять, удалять, извлекать и заменять изображения](/pdf/ru/python-net/working-with-images/) +- [Вставлять, удалять, извлекать и управлять страницами PDF](/pdf/ru/python-net/working-with-pages/) +- [Устанавливать и сохранять метаданные XMP](/pdf/ru/python-net/save-metadata-with-xmp/) +- [Проверять PDF‑документы на соответствие PDF/A‑1a и PDF/A‑1b](/pdf/ru/python-net/manipulate-pdf-document/) +- Работать с [закладки](/pdf/ru/python-net/bookmarks/), [аннотации](/pdf/ru/python-net/annotations/), [PDF-формы](/pdf/ru/python-net/working-with-forms/), [штампы](/pdf/ru/python-net/stamping/), и [водяные знаки](/pdf/ru/python-net/add-watermarks/) -## Функции конвертации +## Функции преобразования Document -- [Конвертация PDF в Word, Excel и PowerPoint](/pdf/ru/python-net/convert-pdf-to-word/). -- [Конвертация PDF в форматы изображений](/pdf/ru/python-net/convert-pdf-to-images-format/). -- [Конвертация PDF в формат HTML и обратно](/pdf/ru//python-net/convert-pdf-to-html/). -- [Конвертация PDF в EPUB, текст, XPS и др.](/pdf/ru/python-net/convert-pdf-to-other-files/). -- Конвертация EPUB, Markdown, текст, XPS, PostScript, XML, LaTex в PDF +- [Преобразовать PDF в Word, Excel и PowerPoint](/pdf/ru/python-net/convert-pdf-to-word/). +- [Преобразовать PDF в форматы изображений](/pdf/ru/python-net/convert-pdf-to-images-format/). +- [Преобразовать файлы PDF в HTML и преобразовать HTML в PDF](/pdf/ru/python-net/convert-pdf-to-html/). +- [Преобразовать PDF в EPUB, Text, XPS и т.д.](/pdf/ru/python-net/convert-pdf-to-other-files/). +- [Преобразовать EPUB, Markdown, Text, XPS, PostScript, XML, LaTex в PDF](/pdf/ru/python-net/convert-other-files-to-pdf/) -### Узнайте больше о: +## Начните с этих руководств + +- ["Hello, World" пример на Python](/pdf/ru/python-net/hello-world-example/) +- [Создайте сложный PDF‑документ](/pdf/ru/python-net/complex-pdf-example/) -- [Пример "Hello, World" на Python](/pdf/ru/python-net/hello-world-example/) -- [Сложный PDF](/pdf/ru/python-net/complex-pdf-example/) \ No newline at end of file diff --git a/ru/python-net/overview/_index.md b/ru/python-net/overview/_index.md index c52f3b7cc..f117c980f 100644 --- a/ru/python-net/overview/_index.md +++ b/ru/python-net/overview/_index.md @@ -1,39 +1,41 @@ --- -title: Overview -linktitle: Overview +title: Обзор +linktitle: Обзор type: docs weight: 20 url: /ru/python-net/overview/ -lastmod: "2022-12-20" +lastmod: "2025-02-20" description: Обзор ключевых функций и поддерживаемых форматов Aspose.PDF for Python via .NET, руководство по установке и лицензированию библиотеки. sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Обзор ключевых функций Aspose.PDF for Python +Abstract: Aspose.PDF for Python via .NET является комплексным API для обработки PDF, разработанным для разработчиков, позволяющим работать с PDF‑документами без необходимости использования Microsoft Office или автоматизации Adobe Acrobat. Библиотека поддерживает широкий спектр функций, включая соответствие установленным стандартам и спецификациям PDF, возможность чтения и экспорта PDF в различных графических форматах, таких как BMP, GIF, JPEG и PNG, а также возможность задавать базовую информацию о документе, например автора и создателя. Она также позволяет настраивать свойства страниц PDF, такие как ширина, высота, cropbox и bleedbox, а также функции, такие как нумерация страниц, уровни закладок и размеры страниц. Пользователи могут манипулировать текстом, абзацами, заголовками, гиперссылками, графиками и вложениями в PDF. Кроме того, Aspose.PDF for Python предоставляет эффективные возможности конвертации из форматов, таких как EPUB, Markdown, Text, XPS, PostScript, XML и LaTex в PDF и обратно, обеспечивая высокую производительность и качество. --- -_Эта страница представляет собой обзор функций Aspose.PDF для Python._ +_Эта страница представляет обзор функций Aspose.PDF for Python._ -**Aspose.PDF for Python via .NET**, API обработки PDF, который позволяет разработчикам работать с PDF-документами без необходимости в Microsoft Office® или Adobe Acrobat Automation. Ознакомьтесь с целевыми страницами [Aspose.PDF для Python](https://products.aspose.com/pdf/python-net/) для более детального описания функций и возможностей библиотеки. +**Aspose.PDF for Python via .NET**, API обработки PDF, позволяющий разработчикам работать с PDF‑документами без необходимости использовать Microsoft Office® или автоматизацию Adobe Acrobat. Посмотрите целевые страницы [Aspose.PDF for Python](https://products.aspose.com/pdf/python-net/) для более подробного описания функций и возможностей библиотеки. -Aspose.PDF для Python поддерживает широкий спектр функций, таких как: +Aspose.PDF for Python поддерживает широкий набор функций, таких как: -- Поддержка большинства установленных стандартов PDF и спецификаций PDF. -- Возможность чтения и экспорта PDF в нескольких форматах изображений, включая BMP, GIF, JPEG и PNG. -- Установка базовой информации (например. - author, creator) PDF документа. -- Настройка свойств страницы PDF (например, ширина, высота, cropbox, bleedbox и т.д.). -- Установка нумерации страниц, уровня закладок, размеров страниц и т.д. -- Возможность работы с текстом, абзацами, заголовками, гиперссылками, графиками, вложениями и т.д. +- Поддерживает большинство установленных стандартов PDF и спецификаций PDF. +- Возможность читать и экспортировать PDF в нескольких графических форматах, включая BMP, GIF, JPEG и PNG. +- Установить базовую информацию (например, автор, создатель) PDF‑документа. +- Настроить свойства страницы PDF (например, ширина, высота, cropbox, bleedbox и т.д.). +- Установить нумерацию страниц, уровень закладок, размеры страниц и т.п. +- Возможность работать с текстом, абзацами, заголовками, гиперссылками, графиками, вложениями и т.д. -Кроме того, Aspose.PDF for Python via .NET может быть использован для легкого преобразования EPUB, Markdown, Text, XPS, PostScript, XML, LaTex в PDF и конвертации PDF в различные форматы документов с отличной производительностью и хорошим качеством. +Кроме того, Aspose.PDF for Python via .NET можно использовать для простого преобразования EPUB, Markdown, Text, XPS, PostScript, XML, LaTex в PDF и конвертации PDF в различные форматы документов с отличной производительностью и хорошим качеством. -Попробуйте наши [Бесплатные Онлайн Приложения](https://products.aspose.app/pdf/applications), демонстрирующие некоторые из самых популярных функций Aspose.PDF. +Попробуйте наши [онлайн приложения](https://products.aspose.app/pdf/applications) которые демонстрируют некоторые из самых популярных функций Aspose.PDF. -Узнайте больше о: +Узнать больше о: -- [Поддерживаемые Форматы Файлов](/pdf/ru/python-net/supported-file-formats/) -- [Ключевые Особенности Aspose.PDF](/pdf/ru/python-net/key-features/) -- [Системные Требования](/pdf/ru/python-net/system-requirements/) +- [Поддерживаемые форматы файлов](/pdf/ru/python-net/supported-file-formats/) +- [Ключевые возможности Aspose.PDF](/pdf/ru/python-net/key-features/) +- [Системные требования](/pdf/ru/python-net/system-requirements/) - [Установка](/pdf/ru/python-net/installation/) - [Лицензирование](/pdf/ru/python-net/licensing/) -- [Техническая Поддержка](/pdf/ru/python-net/technical-support/) \ No newline at end of file +- [Техническая поддержка](/pdf/ru/python-net/technical-support/) diff --git a/ru/python-net/overview/installation/_index.md b/ru/python-net/overview/installation/_index.md index 8423e3d6b..6c5d3f4c2 100644 --- a/ru/python-net/overview/installation/_index.md +++ b/ru/python-net/overview/installation/_index.md @@ -1,45 +1,51 @@ --- -title: How to Install Aspose.PDF for Python -linktitle: Installation +title: Как установить Aspose.PDF для Python +linktitle: Установка type: docs weight: 40 url: /ru/python-net/installation/ -description: В этом разделе представлено описание продукта и инструкции по установке Aspose.PDF для Python. -lastmod: "2022-12-21" +description: Найдите пошаговые инструкции по установке Aspose.PDF для Python и .NET, чтобы начать работу с PDF‑документами. +lastmod: "2025-02-21" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Установка Aspose.PDF для Python +Abstract: Aspose.PDF for Python via .NET — это комплексная библиотека, предназначенная для интеграции возможностей обработки PDF в Python‑приложения, совместимая как с 32‑битными, так и с 64‑битными системами. Эта библиотека поддерживает широкий спектр задач обработки документов, включая манипуляцию текстом и страницами, обработку форм, работу с метаданными, а также управление аннотациями, закладками, водяными знаками и пользовательскими шрифтами. Она подходит для использования на различных операционных системах, где установлен Python версии 3.5 или новее. Библиотеку можно оценить, загрузив trial‑версию, которая переходит в лицензированное состояние после добавления соответствующего кода. Trial‑версия сохраняет полный функционал, но содержит оценочный водяной знак и ограничивает взаимодействие с элементами коллекций до четырёх. Пользователи могут запросить временную лицензию на 30 дней, чтобы обойти эти ограничения. Aspose.PDF for Python via .NET можно установить через pip, обеспечивая простой доступ к последним версиям. --- {{% alert color="primary" %}} -**Aspose.PDF for Python via .NET** — это библиотека, которая позволяет разработчикам добавлять возможности обработки PDF в свои приложения. API может использоваться для создания 32-битных и 64-битных приложений для генерации, чтения, преобразования и управления PDF-файлами без использования Adobe Acrobat. +**Aspose.PDF for Python via .NET** — это библиотека, позволяющая разработчикам добавлять возможности работы с PDF в свои приложения. API можно использовать для создания 32‑разрядных и 64‑разрядных приложений для генерации, чтения, конвертации и манипулирования PDF‑файлами без использования Adobe Acrobat. {{% /alert %}} ## Описание продукта -**Aspose.PDF for Python** позволяет выполнять ряд задач по обработке документов, таких как обработка форм, получение и установка метаданных, манипуляции с текстом и страницами, управление аннотациями, добавление или удаление закладок и водяных знаков, вложения, работа с пользовательскими шрифтами и многое другое. +**Aspose.PDF for Python** позволяет выполнять широкий спектр задач обработки документов, таких как обработка форм, получение и установка метаданных, манипуляции с текстом и страницами, управление аннотациями, добавление или удаление закладок и водяных знаков, вложения, работа с пользовательскими шрифтами и многое другое. - **Aspose.PDF для Python** можно использовать для разработки 32-битных и 64-битных приложений Python для различных операционных систем (таких как Windows и Linux), где установлена версия Python 3.5 или выше. +**Aspose.PDF for Python** может использоваться для разработки 32‑разрядных и 64‑разрядных Python‑приложений для различных операционных систем (например, Windows и Linux), где установлен Python версии 3.5 или более поздней. -# Установка +## Установка -## Оценка Aspose.PDF for Python via .NET +## Оцените Aspose.PDF for Python via .NET -Вы можете легко скачать Aspose.PDF для Python для оценки. Версия для оценки аналогична купленной версии. Версия для оценки становится лицензированной, когда вы добавляете несколько строк кода для применения лицензии. +Вы можете легко скачать Aspose.PDF for Python для оценки. Оценочная загрузка такая же, как и покупная загрузка. Оценочная версия просто становится лицензированной, когда вы добавляете несколько строк кода для применения лицензии. -Вы можете скачать [Aspose.PDF для Python](https://releases.aspose.com/pdf/pythonnet/) для оценки. Версия для оценки аналогична купленной версии. Версия для оценки становится лицензированной, когда вы добавляете несколько строк кода, чтобы [применить лицензию](/pdf/ru/python-net/licensing/). - -Версия для оценки Aspose.PDF (без указанной лицензии) предоставляет полную функциональность продукта, но имеет два ограничения: она вставляет водяной знак для оценки, и только четыре элемента любой коллекции могут быть просмотрены/отредактированы. +Вы можете скачать [Aspose.PDF for Python](https://releases.aspose.com/pdf/pythonnet/) для оценки. Оценочная загрузка такая же, как и покупная загрузка. Оценочная версия становится лицензированной, когда вы добавляете несколько строк кода, чтобы [применить лицензию](/pdf/ru/python-net/licensing/). +Оценочная версия Aspose.PDF (без указания лицензии) предоставляет полный функционал продукта, но имеет два ограничения: она вставляет оценочный водяной знак и только четыре элемента любой коллекции могут быть просмотрены/отредактированы. {{% alert color="primary" %}} -Если вы хотите протестировать Aspose.PDF для Python без ограничений версии для оценки, вы также можете запросить временную лицензию на 30 дней. Пожалуйста, обратитесь к [Как получить временную лицензию?](https://purchase.aspose.com/temporary-license) +Если вы хотите протестировать Aspose.PDF for Python без ограничений оценочной версии, вы также можете запросить 30‑дневную временную лицензию. Пожалуйста, обратитесь к [Как получить временную лицензию?](https://purchase.aspose.com/temporary-license) {{% /alert %}} -## Установка Aspose.PDF for Python via .NET +## Установка Aspose.PDF for Python через .NET + +Вы можете легко использовать aspose-pdf для Python по ссылке для прямой загрузки [pip](https://pypi.org/project/aspose-pdf/). +Выполните 'pip install aspose-pdf', чтобы загрузить пакет. Если у вас уже установлен Aspose.PDF for Python и вы хотите получить последнюю версию, пожалуйста, выполните 'pip install --upgrade aspose-pdf'. + + -Вы можете легко использовать aspose-pdf для Python, перейдя по ссылке для прямой загрузки [pip](https://pypi.org/project/aspose-pdf/). Запустите 'pip install aspose-pdf', чтобы загрузить пакет. Если у вас уже установлен Aspose.PDF для Python и вы хотите получить последнюю версию, пожалуйста, выполните 'pip install --upgrade aspose-pdf'. \ No newline at end of file diff --git a/ru/python-net/overview/key-features/_index.md b/ru/python-net/overview/key-features/_index.md index 36b83f6d1..223d645cc 100644 --- a/ru/python-net/overview/key-features/_index.md +++ b/ru/python-net/overview/key-features/_index.md @@ -1,53 +1,71 @@ --- -title: Основные функции Aspose.PDF для Python -linktitle: Основные функции +title: Основные возможности Aspose.PDF for Python +linktitle: Основные возможности type: docs weight: 20 url: /ru/python-net/key-features/ -description: Aspose.PDF for Python via .NET демонстрирует свои общие функции. Показывает поддерживаемые версии PDF и все манипуляции, которые мы можем делать с PDF. -lastmod: "2022-12-21" +description: Aspose.PDF for Python via .NET подчеркивает свои основные возможности, включая поддерживаемые версии PDF и доступные варианты манипулирования PDF. +lastmod: "2025-02-21" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Общие возможности Aspose.PDF for Python +Abstract: Aspose.PDF for Python via .NET — это мощная библиотека, предоставляющая обширные возможности для управления и манипулирования PDF‑документами. Она поддерживает установленные стандарты PDF и облегчает чтение и экспорт PDF в различные графические форматы, такие как BMP, GIF, JPEG и PNG. Пользователи могут настраивать свойства документа, атрибуты страниц и управлять текстом, абзацами, гиперссылками, графиками и вложениями. Библиотека превосходит в возможностях конвертации, позволяя без труда преобразовывать PDF в форматы Word, Excel, PowerPoint и HTML, среди прочих, а также конвертировать различные форматы обратно в PDF. --- -## Общие функции +## Общие возможности - Поддерживает большинство установленных стандартов PDF и спецификаций PDF. -- Возможность чтения и экспорта PDF в нескольких форматах изображений, включая BMP, GIF, JPEG и PNG. -- Установка основной информации (например, автор, создатель) документа PDF. -- Настройка свойств страницы PDF (например, ширина, высота, рамка обрезки, рамка вылетов и т. д.). -- Установка нумерации страниц, уровня закладок, размеров страниц и т. д. -- Возможность работы с текстом, абзацами, заголовками, гиперссылками, графиками, вложениями и т. д. +- Возможность читать и экспортировать PDF в нескольких графических форматах, включая BMP, GIF, JPEG и PNG. +- Установить базовую информацию (например, автор, создатель) PDF‑документа. +- Настроить свойства страницы PDF (например, ширина, высота, cropbox, bleedbox и т.д.). +- Установить нумерацию страниц, уровень закладок, размеры страниц и т.п. +- Возможность работать с текстом, абзацами, заголовками, гиперссылками, графиками, вложениями и т.д. -## Функции конверсии +## Поддерживаемые стандарты PDF -Библиотека Aspose.PDF for Python via .NET позволяет успешно, быстро и легко конвертировать ваши PDF-документы в наиболее популярные форматы и наоборот. +- ISO 32000-1 (PDF 1.2, PDF 1.3, PDF 1.4, PDF 1.5, PDF 1.6, PDF 1.7). +- ISO 32000-2 (PDF 2.0). +- ISO 19005 (PDF/A), ISO 15930 (PDF/X), ISO 24517 (PDF/E), ISO 14289 (PDF/UA). + +## Функции конвертации + +Библиотека Aspose.PDF for Python via .NET позволяет вам успешно, быстро и легко конвертировать ваши PDF‑документы в самые популярные форматы и обратно. - Конвертировать PDF в Word, Excel и PowerPoint. - Конвертировать PDF в форматы изображений. -- Конвертировать PDF файл в HTML формат и наоборот. -- Конвертировать PDF в EPUB, текст, XPS и т. д. -- Конвертировать EPUB, Markdown, текст, XPS, PostScript, XML, LaTex в PDF. +- Конвертировать PDF‑файл в формат HTML и обратно. +- Конвертировать PDF в EPUB, Text, XPS и т.д. +- Конвертировать EPUB, Markdown, Text, XPS, PostScript, XML, LaTex в PDF. ## Поддерживаемые версии PDF -Aspose.PDF для Python поддерживает версии PDF 1.2, 1.3, 1.4, 1.5, 1.6, 1.7 и 2.0. +Aspose.PDF for Python поддерживает версии PDF 1.2, 1.3, 1.4, 1.5, 1.6, 1.7 и 2.0. ## Текст - Извлечь текст со страниц. -- Искать текст на страницах. +- Поиск текста на страницах. - Заменить текст. - Добавить текст в PDF файл. +## Шрифты + +- 14 базовых шрифтов. +- Шрифты Type 1. +- Шрифты TrueType. +- Шрифты Type 3. +- Шрифты CJK. +- Поддержка Unicode. + ## Изображения -- Добавить изображение в PDF файл. +- Добавить изображение в файл PDF. - Удалить изображения. - Заменить изображения. - Извлечь изображения. -- Конвертация PDF в формат изображения. +- Преобразование формата PDF в изображение. ## Вложения @@ -59,39 +77,38 @@ Aspose.PDF для Python поддерживает версии PDF 1.2, 1.3, 1.4 - Вставить страницы PDF. - Удалить страницы PDF. - Разделить PDF на отдельные страницы. -- Перемещение набора страниц из одного PDF документа в другой -- Перемещение страницы в новое местоположение в текущем PDF документе +- Перемещение группы страниц из одного PDF‑документа в другой +- Перемещение страницы в новое место в текущем PDF‑документе - Изменить размер страницы PDF - Изменить ориентацию страницы - Получить свойства страницы - Получить количество страниц - Получить количество страниц -- Получить определенную страницу - -## Документ - -- Создать PDF файл -- Открыть существующий PDF документ из потока -- Открыть существующий PDF документ - -- Установка свойств диалогового окна печати -- Добавить оглавление в существующий PDF -- Добавить оглавление в существующий PDF -- Настроить нумерацию страниц при добавлении оглавления -- Установить срок действия PDF -- Упрощение заполняемого PDF -- Оптимизировать PDF-документ для Интернета +- Получить конкретную страницу + +## Document + +- Создать PDF-файл +- Открыть существующий PDF-документ из потока +- Открыть существующий PDF-документ +- Настройка предустановленных свойств диалогового окна печати +- Добавить TOC в существующий PDF +- Добавить TOC в существующий PDF +- Настроить номера страниц при добавлении TOC +- Установить дату истечения срока действия PDF +- Уплощение заполняемого PDF +- Оптимизировать PDF‑документ для веба - Уменьшить размер PDF -- Сжатие или уменьшение всех изображений +- Сжатие всех изображений - Удаление неиспользуемых объектов -- Удаление дублирующих потоков +- Связывание дублирующихся потоков - Удаление неиспользуемых потоков -- Отключение встраивания шрифтов -- Получить свойства просмотра документа. -- Установить свойства просмотра документа. -- Проверка (PDF/A-1a, PDF/A-1b). +- Удаление встроенных шрифтов +- Получить свойства просмотрщика документов. +- Установить свойства просмотрщика документов. +- Валидация (PDF/A-1a, PDF/A-1b). - Удаление полей формы -- Определение и установка метаданных документов +- Определить и установить метаданные документов ## Закладки @@ -116,15 +133,16 @@ Aspose.PDF для Python поддерживает версии PDF 1.2, 1.3, 1.4 - Изменить поля. - Заполнить поля. - Получить значения полей. +- Поддержка XFA (формы на основе XML) и AcroForms (стандартные формы). ## Штамп и водяной знак - Добавить текстовый штамп. - Добавить штамп изображения. -- Добавить штамп страницы PDF. +- Добавить штамп PDF‑страницы. -## Открытие зашифрованного документа +## Открыть зашифрованный PDF-документ -- Зашифровать PDF. -- Расшифровать PDF. +- Зашифровать PDF. +- Расшифровать PDF. - Изменить пароль. diff --git a/ru/python-net/overview/licensing/_index.md b/ru/python-net/overview/licensing/_index.md index 78734361d..267d2ccd2 100644 --- a/ru/python-net/overview/licensing/_index.md +++ b/ru/python-net/overview/licensing/_index.md @@ -1,34 +1,36 @@ --- -title: Aspose PDF License -linktitle: Licensing and limitations +title: Лицензия Aspose PDF +linktitle: Лицензирование и ограничения type: docs weight: 50 url: /ru/python-net/licensing/ -description: Aspose. PDF для Python приглашает своих клиентов получить классическую лицензию. Также используйте ограниченную лицензию для более детального изучения продукта. -lastmod: "2022-12-21" +description: Aspose.PDF for Python приглашает своих клиентов получить Classic лицензию. Также можно использовать ограниченную лицензию, чтобы лучше исследовать продукт. +lastmod: "2025-02-21" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Лицензирование Aspose.PDF for Python +Abstract: В статье рассматриваются ограничения и варианты лицензирования Aspose.PDF for Python. Отмечается, что оценочная версия позволяет полностью протестировать функциональность, но добавляет водяной знак к сгенерированным PDF‑файлам, отображающий надпись “Evaluation Only” вместе с информацией об авторских правах. Для пользователей, желающих тестировать без этих ограничений, доступна 30‑дневная временная лицензия. В статье также объясняется, как внедрить классическую лицензию, загрузив её из файла или потока, рекомендуется разместить файл лицензии в той же директории, что и файл Aspose.PDF.dll, и установить лицензию с помощью класса `Aspose.Pdf.License`. Приведены фрагменты кода, демонстрирующие процесс лицензирования. --- -## Ограничения пробной версии +## Ограничения оценочной версии -Мы хотим, чтобы наши клиенты тщательно протестировали наши компоненты перед покупкой, поэтому пробная версия позволяет использовать их, как обычно. +Мы хотим, чтобы наши клиенты тщательно тестировали наши компоненты перед покупкой, поэтому оценочная версия позволяет использовать её так, как вы обычно делаете. -- **PDF, созданный с водяным знаком пробной версии.** Пробная версия Aspose.PDF для Python предоставляет полную функциональность продукта, но все страницы в сгенерированных PDF-документах помечены водяным знаком "Только для оценки. Создано с помощью Aspose.PDF. Copyright 2002-2020 Aspose Pty Ltd" вверху. +- **PDF created with an evaluation watermark.** Оценочная версия Aspose.PDF for Python предоставляет полный функционал продукта, но все страницы в создаваемых PDF‑документах помечены водяным знаком "Evaluation Only. Created with Aspose.PDF. Copyright 2002-2020 Aspose Pty Ltd" в верхней части. ->Если вы хотите протестировать Aspose.PDF без ограничений пробной версии, вы также можете запросить временную лицензию на 30 дней. - Пожалуйста, обратитесь к [Как получить временную лицензию?](https://purchase.aspose.com/temporary-license) +>Если вы хотите протестировать Aspose.PDF без ограничений оценочной версии, вы также можете запросить 30‑дневную временную лицензию. Пожалуйста, обратитесь к [Как получить временную лицензию?](https://purchase.aspose.com/temporary-license) ## Классическая лицензия -Лицензию можно загрузить из файла или объекта потока. Самый простой способ установить лицензию — поместить файл лицензии в ту же папку, что и файл Aspose.PDF.dll, и указать имя файла без пути, как показано в примере ниже. +Лицензия может быть загружена из файла или объекта потока. Самый простой способ установить лицензию — поместить файл лицензии в ту же папку, что и файл Aspose.PDF.dll, и указать имя файла без пути, как показано в примере ниже. -Если вы используете любой другой компонент Aspose для Python вместе с Aspose.PDF для Python, пожалуйста, укажите пространство имен для License, как [класс Aspose.Pdf.License](). +Если вы используете любой другой компонент Aspose для Python вместе с Aspose.PDF for Python, пожалуйста, укажите пространство имён для License, как [Aspose.Pdf.License класс](). ```python license_file = LICENSE_FILE license = ap.License() license.set_license(license_file) -``` \ No newline at end of file +``` diff --git a/ru/python-net/overview/supported-file-formats/_index.md b/ru/python-net/overview/supported-file-formats/_index.md index 70807360e..2bd594d00 100644 --- a/ru/python-net/overview/supported-file-formats/_index.md +++ b/ru/python-net/overview/supported-file-formats/_index.md @@ -4,43 +4,48 @@ linktitle: Поддерживаемые форматы файлов type: docs weight: 10 url: /ru/python-net/supported-file-formats/ -description: Эта страница показывает, какие форматы файлов Aspose.PDF for Python via .NET может загружать и сохранять. -lastmod: "2022-12-22" +description: Эта страница показывает, какие форматы файлов может загружать и сохранять Aspose.PDF for Python via .NET. +lastmod: "2025-02-22" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Загрузка и сохранение форматов файлов с помощью Aspose.PDF for Python +Abstract: В этой статье представлена подробная таблица, описывающая форматы файлов, с которыми может работать Aspose.PDF for Python. В ней изложены возможности библиотеки по загрузке и сохранению различных типов документов, предоставляя представление о её гибкости в управлении различными форматами файлов. В таблице охвачены известные форматы, такие как PDF, EPUB, HTML и XML, все из которых могут как загружаться, так и сохраняться библиотекой. Также поддерживаются форматы изображений, такие как JPEG, PNG и TIFF, для обеих операций. Однако некоторые форматы, такие как CGM, MHT, PCL, PS, XSLFO и MD, доступны только для загрузки, тогда как другие, такие как XLS, XLSX, PPTX, DOC, DOCX и MobiXML, доступны исключительно для сохранения. Эта таблица служит практическим руководством для пользователей, желающих понять совместимость форматов Aspose.PDF for Python, подчеркивая как её сильные стороны, так и ограничения в поддержке форматов документов и изображений. --- -В следующей таблице указаны форматы файлов, которые Aspose.PDF для Python может загружать и сохранять. +В следующей таблице указаны форматы файлов, которые Aspose.PDF Python может загружать и сохранять. -|**Формат**|**Описание**|**Загрузка**|**Сохранение**|**Примечания**| +|**Формат**|**Описание**|**Загрузка**|**Сохранить**|**Примечания**| | :- | :- | :- | :- | :- | -|[PDF](https://docs.fileformat.com/pdf/)|Формат портативных документов|{{< emoticons/tick >}}|{{< emoticons/tick >}} | | -|[CGM](https://docs.fileformat.com/page-description-language/cgm/)|Метафайл компьютерной графики для 2D векторной графики|{{< emoticons/tick >}}| | | -|[EPUB](https://docs.fileformat.com/ebook/epub/)|Формат файлов электронной книги|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | +|[PDF](https://docs.fileformat.com/pdf/)|Переносимый формат документа|{{< emoticons/tick >}}|{{< emoticons/tick >}} | | +|[CGM](https://docs.fileformat.com/page-description-language/cgm/)|Computer Graphics Metafile для 2D векторной графики|{{< emoticons/tick >}}| | | +|[EPUB](https://docs.fileformat.com/ebook/epub/)|Формат файлов электронных книг|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | |[HTML](https://docs.fileformat.com/web/html/)|Формат HTML|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | - -|[TeX](https://docs.fileformat.com/page-description-language/tex/)|Формат файлов LaTex для набора текста|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | +|[TeX](https://docs.fileformat.com/page-description-language/tex/)|формат файла вёрстки LaTex|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | |[MHT](https://docs.fileformat.com/web/mhtml/)|Документ MHTML|{{< emoticons/tick >}}| | | -|[PCL](https://docs.fileformat.com/page-description-language/pcl/)|Файлы языка управления принтером|{{< emoticons/tick >}}| | | +|[PCL](https://docs.fileformat.com/page-description-language/pcl/)|Файлы Printer Control Language|{{< emoticons/tick >}}| | | |[PS](https://docs.fileformat.com/page-description-language/ps/)|Файлы Postscript|{{< emoticons/tick >}}| | | -|[SVG](https://docs.fileformat.com/page-description-language/svg/)|Масштабируемая векторная графика (векторный формат изображения на основе XML)|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | +|[SVG](https://docs.fileformat.com/page-description-language/svg/)|Scalable Vector Graphics (векторный графический формат на основе XML)|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | |[XML](https://docs.fileformat.com/web/xml/)|Формат XML|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | |[XPS](https://docs.fileformat.com/page-description-language/xps/)|Документы XPS|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | -|[XSLFO](https://docs.fileformat.com/page-description-language/xslfo/)|XSL-FO является частью файла XSL, который используется для преобразования и форматирования данных XML|{{< emoticons/tick >}}| | | - +|[XSLFO](https://docs.fileformat.com/page-description-language/xslfo/)|XSL-FO является частью файла XSL, который используется для преобразования и форматирования XML‑данных|{{< emoticons/tick >}}| | | |[MD](https://docs.fileformat.com/word-processing/md/)|Формат Markdown|{{< emoticons/tick >}}| | | -|[XLS](https://docs.fileformat.com/spreadsheet/xls/)|Сохраняет документ в формате Microsoft Excel SpreadSheet| |{{< emoticons/tick >}}| | +|[XLS](https://docs.fileformat.com/spreadsheet/xls/)|Сохраняет документ в электронную таблицу Microsoft Excel| |{{< emoticons/tick >}}| | |[XLSX](https://docs.fileformat.com/spreadsheet/xlsx/)|Сохраняет документ в формате Microsoft Excel 2007| |{{< emoticons/tick >}}| | -|[PPTX](https://docs.fileformat.com/presentation/pptx/)|Сохраняет документ в формате Microsoft PowerPoint Presentations| |{{< emoticons/tick >}}| | +|[PPTX](https://docs.fileformat.com/presentation/pptx/)|Сохраняет документ в формате Microsoft PowerPoint| |{{< emoticons/tick >}}| | +|[XLSM](https://docs.fileformat.com/spreadsheet/xlsm/)|Сохраняет документ в формате XLSM, который является типом файлов таблиц, поддерживающих макросы.||{{< emoticons/tick >}} | | |[DOC](https://docs.fileformat.com/word-processing/doc/)|Сохраняет документ в формате Microsoft Word| |{{< emoticons/tick >}}| | |[DOCX](https://docs.fileformat.com/word-processing/docx/)|Сохраняет документ в формате Microsoft Word| |{{< emoticons/tick >}}| | -|[MobiXML](https://docs.fileformat.com/ebook/mobi/)|Сохраняет документ в стандарте eBook MobiXML| |{{< emoticons/tick >}}| | +|[OFD](https://en.wikipedia.org/wiki/OFD)|Формат OFD относится к “Open Fixed-layout Document”, установлен как национальный стандарт Китая для электронного хранения файлов, используется как альтернатива популярному формату PDF.|{{< emoticons/tick >}}| | | +|[DJVU](https://docs.fileformat.com/image/djvu/)|DjVu — графический файловый формат, предназначенный для сканированных документов и книг, разработанный AT&T Labs.|{{< emoticons/tick >}}| | | +|[CDR](https://docs.fileformat.com/image/cdr/)|Файл CDR — это векторный графический файл, который нативно создаётся в CorelDRAW|{{< emoticons/tick >}}| | | +|[MobiXML](https://docs.fileformat.com/ebook/mobi/)|Сохраняет документ в формате eBook MobiXML Standard| |{{< emoticons/tick >}}| | |[JPEG](https://docs.fileformat.com/image/jpeg/)|Сохраняет документ в формате JPEG|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | - |[EMF](https://docs.fileformat.com/image/emf/)|Формат расширенного метафайла (EMF)|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | |[PNG](https://docs.fileformat.com/image/png/)|Сохраняет документ в формате PNG|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | |[BMP](https://docs.fileformat.com/image/bmp/)|Сохраняет документ в формате BMP|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | -|[GIF](https://docs.fileformat.com/image/gif/)|Формат обмена графикой| |{{< emoticons/tick >}}| | -|[TIFF](https://docs.fileformat.com/image/tiff/)|Сохраняет документ как одностраничное или многостраничное изображение TIFF|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | -|[Text](https://docs.fileformat.com/word-processing/txt/)|Сохраняет документ в текстовом формате|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | \ No newline at end of file +|[GIF](https://docs.fileformat.com/image/gif/)|Графический формат обмена| |{{< emoticons/tick >}}| | +|[TIFF](https://docs.fileformat.com/image/tiff/)|Сохраняет документ как одностраничное или многостраничное TIFF‑изображение|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | +|[Текст](https://docs.fileformat.com/word-processing/txt/)|Сохранить документ в текстовом формате|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | + diff --git a/ru/python-net/overview/system-requirements/_index.md b/ru/python-net/overview/system-requirements/_index.md index 62e531116..b5ea8d589 100644 --- a/ru/python-net/overview/system-requirements/_index.md +++ b/ru/python-net/overview/system-requirements/_index.md @@ -1,30 +1,33 @@ --- -title: System Requirements -linktitle: System Requirements +title: Системные требования +linktitle: Системные требования type: docs weight: 30 url: /ru/python-net/system-requirements/ -description: Этот раздел перечисляет поддерживаемые операционные системы, которые необходимы разработчику для успешной работы с Aspose.PDF для Python. -lastmod: "2022-12-22" +description: В этом разделе перечислены поддерживаемые операционные системы, необходимые разработчику для успешной работы с Aspose.PDF for Python. +lastmod: "2025-02-22" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Поддерживаемые операционные системы Aspose.PDF for Python через .NET +Abstract: Aspose.PDF for Python via .NET — это API для обработки PDF, разработанное для разработчиков, позволяющее управлять PDF‑документами без необходимости использования Microsoft Office или Adobe Acrobat Automation. Оно поддерживает создание 32‑битных и 64‑битных Python‑приложений на различных операционных системах, включая Windows и Linux, где установлен Python 3.5 или более новая версия. API совместим с несколькими версиями Windows, от Windows XP до Windows 11, а также с основными дистрибутивами Linux, такими как Ubuntu, OpenSUSE и CentOS. Для систем Linux требуются специфические компоненты: библиотеки среды выполнения GCC‑6, зависимости .NET Core Runtime (без необходимости установки самого runtime) и сборка Python с pymalloc для версий 3.5‑3.7. Кроме того, необходима общая библиотека libpython, для которой может потребоваться настройка параметров, чтобы правильно распознавался путь к библиотеке. --- -## Overview +## Обзор -Aspose.PDF for Python via .NET, API для обработки PDF, который позволяет разработчикам работать с PDF-документами без необходимости в Microsoft Office® или Adobe Acrobat Automation. Aspose.PDF для Python можно использовать для разработки 32-битных и 64-битных приложений на Python для различных операционных систем (таких как Windows и Linux), на которых установлена версия Python 3.5 или выше. +Aspose.PDF for Python via .NET, API обработки PDF, позволяющий разработчикам работать с PDF‑документами без необходимости использовать Microsoft Office® или автоматизацию Adobe Acrobat. Aspose.PDF for Python может использоваться для создания 32‑разрядных и 64‑разрядных Python‑приложений для различных операционных систем (например, Windows и Linux), где установлен Python версии 3.5 или новее. -## Supported Operating System +## Поддерживаемая операционная система ### Windows - Windows 2003 Server - Windows 2008 Server - Windows 2012 Server -- Windows 2012 R2 Server -- Windows 2016 Server -- Windows 2019 Server +- Windows 2012 R2 Сервер +- Windows 2016 Сервер +- Windows 2019 Сервер - Windows XP - Windows Vista - Windows 7 @@ -39,18 +42,14 @@ Aspose.PDF for Python via .NET, API для обработки PDF, которы - CentOS - и другие +## Системные требования для целевого Linux -## System Requirements for Target Linux +- Библиотеки выполнения GCC-6 (или более поздние). -- Библиотеки времени выполнения GCC-6 (или более поздние). +- Зависимости .NET Core Runtime. Установка самого .NET Core Runtime НЕ требуется. -- Зависимости среды выполнения .NET Core. Установка самой среды выполнения .NET Core НЕ требуется. +- Для Python 3.5-3.7: требуется сборка Python с pymalloc. Параметр сборки Python --with-pymalloc включён по умолчанию. Как правило, сборка Python с pymalloc отмечена суффиксом m в имени файла. -- Для Python 3.5-3.7: Необходим сборка pymalloc для Python. Опция сборки Python --with-pymalloc включена по умолчанию. Обычно сборка pymalloc для Python обозначается суффиксом m в названии файла. +- Разделяемая библиотека libpython. Параметр сборки Python --enable-shared отключён по умолчанию, некоторые дистрибутивы Python не включают разделяемую библиотеку libpython. На некоторых платформах Linux разделяемую библиотеку libpython можно установить с помощью менеджера пакетов, например: sudo apt-get install libpython3.7. Распространённая проблема заключается в том, что библиотека libpython устанавливается в другое место, отличающееся от стандартного системного расположения разделяемых библиотек. Проблему можно решить, используя параметры сборки Python для указания альтернативных путей к библиотекам при компиляции Python, либо создав символическую ссылку на файл библиотеки libpython в стандартном системном расположении разделяемых библиотек. Обычно имя файла разделяемой библиотеки libpython имеет вид libpythonX.Ym.so.1.0 для Python 3.5‑3.7, или libpythonX.Y.so.1.0 для Python 3.8 и новее (например: libpython3.7m.so.1.0, libpython3.9.so.1.0). -- Общая библиотека Python libpython. - The --enable-shared Python build option is disabled by default, some Python distributions do not contain the libpython shared library. For some linux platforms, the libpython shared library can be installed using the package manager, for example: sudo apt-get install libpython3.7. The common issue is that libpython library is installed in a different location than the standard system location for shared libraries. The issue can be fixed by using the Python build options to set alternate library paths when compiling Python, or fixed by creating a symbolic link to the libpython library file in the system standard location for shared libraries. Typically, the libpython shared library file name is libpythonX.Ym.so.1.0 for Python 3.5-3.7, or libpythonX.Y.so.1.0 for Python 3.8 or later (for example: libpython3.7m.so.1.0, libpython3.9.so.1.0). - - -Опция сборки Python --enable-shared отключена по умолчанию, некоторые дистрибутивы Python не содержат общую библиотеку libpython. Для некоторых платформ Linux общая библиотека libpython может быть установлена с помощью менеджера пакетов, например: sudo apt-get install libpython3.7. Распространенной проблемой является то, что библиотека libpython установлена в другом месте, чем стандартное системное расположение для общих библиотек. Проблема может быть решена с помощью параметров сборки Python для установки альтернативных путей к библиотекам при компиляции Python или решена путем создания символической ссылки на файл библиотеки libpython в стандартном системном расположении для общих библиотек. Как правило, имя файла общей библиотеки libpython — libpythonX.Ym.so.1.0 для Python 3.5-3.7, или libpythonX.Y.so.1.0 для Python 3.8 или более поздних версий (например: libpython3.7m.so.1.0, libpython3.9.so.1.0). \ No newline at end of file diff --git a/ru/python-net/overview/technical-support/_index.md b/ru/python-net/overview/technical-support/_index.md index 915b6a3f8..b8bc79461 100644 --- a/ru/python-net/overview/technical-support/_index.md +++ b/ru/python-net/overview/technical-support/_index.md @@ -1,30 +1,35 @@ --- -title: Aspose.PDF для поддержки Python +title: Поддержка Aspose.PDF for Python linktitle: Техническая поддержка type: docs weight: 60 url: /ru/python-net/technical-support/ -description: Эта страница дает рекомендации для быстрого и качественного решения ваших задач с использованием Aspose.PDF для Python. -lastmod: "2021-06-05" +description: Эта страница даёт рекомендации для быстрого и качественного выполнения ваших задач с использованием Aspose.PDF for Python. +lastmod: "2025-02-05" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Техническая поддержка Aspose.PDF for Python +Abstract: Aspose.PDF предоставляет бесплатную техническую поддержку через различные каналы, основной из которых — Aspose.Forums, в частности раздел форума Aspose.PDF, где пользователи могут задавать вопросы и получать быстрые ответы. Важно отметить, что Aspose не предоставляет техническую поддержку по телефону, а телефонные звонки ограничены запросами по продажам и покупке. Из‑за возможных различий во временных зонах время ответа может варьироваться. Чтобы обеспечить эффективное решение проблем, пользователям рекомендуется сначала убедиться, что они используют последнюю версию Aspose.PDF, проверив [Aspose.PDF for Python Downloads](https://pypi.org/project/aspose-pdf/). Кроме того, пользователи должны просмотреть существующие обсуждения форума, документацию и справочники API, чтобы узнать, решена ли их проблема уже. При размещении вопроса рекомендуется включить оригинальный документ и любые проблемные фрагменты кода, которые можно упаковать в zip‑архив для удобства. Все загруженные файлы доступны только пользователю и разработчикам Aspose, обеспечивая конфиденциальность и безопасность. --- -Aspose.PDF позволяет вам использовать бесплатную техническую поддержку для всех своих продуктов. Если у вас есть вопросы по Aspose.PDF, ознакомьтесь со следующей статьей: +Aspose.PDF позволяет использовать бесплатную техническую поддержку для всех своих продуктов. Если у вас есть вопросы по Aspose.PDF, ознакомьтесь со следующей статьёй: -- Самый популярный источник поддержки - это [Aspose.Forums](https://forum.aspose.com/). В разделе [Aspose.PDF forum](https://forum.aspose.com/c/pdf/10) вы можете задать свой вопрос и получить ответ как можно скорее. +- Самый популярный источник поддержки — это [Aspose.Forums](https://forum.aspose.com/). В [форум Aspose.PDF](https://forum.aspose.com/c/pdf/10) раздел, вы можете задать свой вопрос и получить ответ как можно быстрее. -- Вы должны знать, что Aspose не предоставляет техническую поддержку по телефону. Звонок возможен только для вопросов продаж и покупок. +- Вы должны знать, что Aspose не предоставляет техническую поддержку по телефону. Звонки доступны только для вопросов по продажам и покупкам. -- Пожалуйста, помните, что у нас есть разница в часовых поясах, это может повлиять на скорость ответов вам. +- Пожалуйста, помните, что у нас разница часовых поясов, это может сказаться на скорости ответов вам. -Если вам нужна помощь с проблемой в Aspose.PDF, следуйте следующим рекомендациям, чтобы убедиться, что она решена наиболее эффективным способом: +Если вам нужна помощь с проблемой Aspose.PDF, следуйте следующим рекомендациям, чтобы убедиться, что она решена максимально эффективно: -- Во-первых, убедитесь, что вы используете последнюю версию Aspose.PDF перед тем, как сообщить о проблеме, смотрите [Aspose.PDF для Python Загрузки](https://pypi.org/project/aspose-pdf/), чтобы узнать о последней версии. +- Во‑первых, проверьте, что вы используете последнюю версию Aspose.PDF перед тем как сообщать о проблеме, см. [Aspose.PDF for Python Downloads](https://pypi.org/project/aspose-pdf/) чтобы узнать о последней версии. -- Возможно, решение вашей проблемы уже обсуждалось и имеет решение, для этого изучите форум и документацию, проверьте API Reference перед тем, как сообщить о проблеме. +- Возможно, решение вашей проблемы уже обсуждалось и найдено; для этого изучите форум и документацию, проверьте справочник API перед тем как сообщать о проблеме. + +- Когда задаёте вопрос, пожалуйста, включайте исходный документ и, возможно, фрагмент кода, который вызывает проблему. Вы можете упаковать эти файлы в один документ, если их несколько. + +- Не беспокойтесь, доступ к «липким» файлам есть только у вас и разработчиков Aspose. -- Когда вы формируете свой вопрос, пожалуйста, включите оригинальный документ и, возможно, фрагмент вашего кода, который вызывает проблему. Вы можете заархивировать эти файлы в один документ, если их несколько. -- Не волнуйтесь, только вы и разработчики Aspose имеют доступ к прикрепленным файлам. diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md index c06f1cf11..f43aea0df 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md @@ -3,7 +3,7 @@ title: Аннотации linktitle: Аннотации type: docs weight: 10 -url: /ru/python-net/annotations/ +url: /ru/python-net/annotations-facades/ description: lastmod: "2026-03-20" sitemap: diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md index 643dc31d3..037809b9f 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md @@ -3,7 +3,7 @@ title: Вложения linktitle: Вложения type: docs weight: 20 -url: /ru/python-net/attachments/ +url: /ru/python-net/attachments-facades/ description: lastmod: "2026-03-20" sitemap: diff --git a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md index 5cf4de38c..b0665be25 100644 --- a/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md +++ b/ru/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md @@ -3,7 +3,7 @@ title: Ссылки и навигация linktitle: Ссылки и навигация type: docs weight: 70 -url: /ru/python-net/links-and-navigation/ +url: /ru/python-net/links-and-navigation-facades/ description: lastmod: "2026-03-20" sitemap: From 36efc40e2f0ca4fff1f58e31b573c2c6128b1cd9 Mon Sep 17 00:00:00 2001 From: Andriy Andruhovski Date: Mon, 18 May 2026 14:03:59 +0300 Subject: [PATCH 11/13] chore: minor fixes --- .../working-with-forms/xfaforms/extract-form/_index.md | 4 ++-- .../working-with-forms/xfaforms/fill-form/_index.md | 2 +- ru/python-net/overview/system-requirements/_index.md | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/en/php-java/advanced-operations/working-with-forms/xfaforms/extract-form/_index.md b/en/php-java/advanced-operations/working-with-forms/xfaforms/extract-form/_index.md index f0bad27b9..8c69a3125 100644 --- a/en/php-java/advanced-operations/working-with-forms/xfaforms/extract-form/_index.md +++ b/en/php-java/advanced-operations/working-with-forms/xfaforms/extract-form/_index.md @@ -3,11 +3,11 @@ title: Extract XFA Form linktitle: Extract XFA Form type: docs weight: 30 -url: /php-java/extract-form/ +url: /php-java/extract-xfa-form/ description: This section explains how to extract forms from your PDF document with Aspose.PDF for PHP via Java. lastmod: "2024-06-05" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 --- diff --git a/en/php-java/advanced-operations/working-with-forms/xfaforms/fill-form/_index.md b/en/php-java/advanced-operations/working-with-forms/xfaforms/fill-form/_index.md index 4bce854ce..5fbe01493 100644 --- a/en/php-java/advanced-operations/working-with-forms/xfaforms/fill-form/_index.md +++ b/en/php-java/advanced-operations/working-with-forms/xfaforms/fill-form/_index.md @@ -3,7 +3,7 @@ title: Fill AcroForms linktitle: Fill AcroForms type: docs weight: 20 -url: /php-java/fill-form/ +url: /php-java/fill-xfa-form/ description: This section explains how to fill form field in a PDF document with Aspose.PDF for PHP via Java. lastmod: "2024-06-05" sitemap: diff --git a/ru/python-net/overview/system-requirements/_index.md b/ru/python-net/overview/system-requirements/_index.md index b5ea8d589..1bc4fe3d1 100644 --- a/ru/python-net/overview/system-requirements/_index.md +++ b/ru/python-net/overview/system-requirements/_index.md @@ -11,7 +11,7 @@ sitemap: priority: 0.7 TechArticle: true AlternativeHeadline: Поддерживаемые операционные системы Aspose.PDF for Python через .NET -Abstract: Aspose.PDF for Python via .NET — это API для обработки PDF, разработанное для разработчиков, позволяющее управлять PDF‑документами без необходимости использования Microsoft Office или Adobe Acrobat Automation. Оно поддерживает создание 32‑битных и 64‑битных Python‑приложений на различных операционных системах, включая Windows и Linux, где установлен Python 3.5 или более новая версия. API совместим с несколькими версиями Windows, от Windows XP до Windows 11, а также с основными дистрибутивами Linux, такими как Ubuntu, OpenSUSE и CentOS. Для систем Linux требуются специфические компоненты: библиотеки среды выполнения GCC‑6, зависимости .NET Core Runtime (без необходимости установки самого runtime) и сборка Python с pymalloc для версий 3.5‑3.7. Кроме того, необходима общая библиотека libpython, для которой может потребоваться настройка параметров, чтобы правильно распознавался путь к библиотеке. +Abstract: > Aspose.PDF for Python via .NET — это API для обработки PDF, разработанное для разработчиков, позволяющее управлять PDF‑документами без необходимости использования Microsoft Office или Adobe Acrobat Automation. Оно поддерживает создание 32‑битных и 64‑битных Python‑приложений на различных операционных системах, включая Windows и Linux, где установлен Python 3.5 или более новая версия. API совместим с несколькими версиями Windows, от Windows XP до Windows 11, а также с основными дистрибутивами Linux, такими как Ubuntu, OpenSUSE и CentOS. Для систем Linux требуются специфические компоненты: библиотеки среды выполнения GCC‑6, зависимости .NET Core Runtime (без необходимости установки самого runtime) и сборка Python с pymalloc для версий 3.5‑3.7. Кроме того, необходима общая библиотека libpython, для которой может потребоваться настройка параметров, чтобы правильно распознавался путь к библиотеке. --- ## Обзор @@ -25,9 +25,9 @@ Aspose.PDF for Python via .NET, API обработки PDF, позволяющи - Windows 2003 Server - Windows 2008 Server - Windows 2012 Server -- Windows 2012 R2 Сервер -- Windows 2016 Сервер -- Windows 2019 Сервер +- Windows 2012 R2 Server +- Windows 2016 Server +- Windows 2019 Server - Windows XP - Windows Vista - Windows 7 From 773a9786a6ca04dc621983ee7dc455fc685a64c0 Mon Sep 17 00:00:00 2001 From: Andriy Andruhovski Date: Mon, 18 May 2026 14:28:25 +0300 Subject: [PATCH 12/13] Update last modified date and format abstract in system requirements documentation --- ru/python-net/overview/system-requirements/_index.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ru/python-net/overview/system-requirements/_index.md b/ru/python-net/overview/system-requirements/_index.md index 1bc4fe3d1..c17253d64 100644 --- a/ru/python-net/overview/system-requirements/_index.md +++ b/ru/python-net/overview/system-requirements/_index.md @@ -5,13 +5,14 @@ type: docs weight: 30 url: /ru/python-net/system-requirements/ description: В этом разделе перечислены поддерживаемые операционные системы, необходимые разработчику для успешной работы с Aspose.PDF for Python. -lastmod: "2025-02-22" +lastmod: "2026-05-15" sitemap: changefreq: "monthly" priority: 0.7 TechArticle: true AlternativeHeadline: Поддерживаемые операционные системы Aspose.PDF for Python через .NET -Abstract: > Aspose.PDF for Python via .NET — это API для обработки PDF, разработанное для разработчиков, позволяющее управлять PDF‑документами без необходимости использования Microsoft Office или Adobe Acrobat Automation. Оно поддерживает создание 32‑битных и 64‑битных Python‑приложений на различных операционных системах, включая Windows и Linux, где установлен Python 3.5 или более новая версия. API совместим с несколькими версиями Windows, от Windows XP до Windows 11, а также с основными дистрибутивами Linux, такими как Ubuntu, OpenSUSE и CentOS. Для систем Linux требуются специфические компоненты: библиотеки среды выполнения GCC‑6, зависимости .NET Core Runtime (без необходимости установки самого runtime) и сборка Python с pymalloc для версий 3.5‑3.7. Кроме того, необходима общая библиотека libpython, для которой может потребоваться настройка параметров, чтобы правильно распознавался путь к библиотеке. +Abstract: > + Aspose.PDF for Python via .NET — это API для обработки PDF, разработанное для разработчиков, позволяющее управлять PDF‑документами без необходимости использования Microsoft Office или Adobe Acrobat Automation. Оно поддерживает создание 32‑битных и 64‑битных Python‑приложений на различных операционных системах, включая Windows и Linux, где установлен Python 3.5 или более новая версия. API совместим с несколькими версиями Windows, от Windows XP до Windows 11, а также с основными дистрибутивами Linux, такими как Ubuntu, OpenSUSE и CentOS. Для систем Linux требуются специфические компоненты: библиотеки среды выполнения GCC‑6, зависимости .NET Core Runtime (без необходимости установки самого runtime) и сборка Python с pymalloc для версий 3.5‑3.7. Кроме того, необходима общая библиотека libpython, для которой может потребоваться настройка параметров, чтобы правильно распознавался путь к библиотеке. --- ## Обзор From 00216c2b4fddc2c4e1757aa9e92aa2ad2cfa943f Mon Sep 17 00:00:00 2001 From: Andriy Andruhovski Date: Mon, 18 May 2026 14:36:50 +0300 Subject: [PATCH 13/13] Update ru/python-net/overview/supported-file-formats/_index.md Co-authored-by: AnHolub <68945813+AnHolub@users.noreply.github.com> --- ru/python-net/overview/supported-file-formats/_index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru/python-net/overview/supported-file-formats/_index.md b/ru/python-net/overview/supported-file-formats/_index.md index 2bd594d00..0a78f4991 100644 --- a/ru/python-net/overview/supported-file-formats/_index.md +++ b/ru/python-net/overview/supported-file-formats/_index.md @@ -47,5 +47,5 @@ Abstract: В этой статье представлена подробная |[BMP](https://docs.fileformat.com/image/bmp/)|Сохраняет документ в формате BMP|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | |[GIF](https://docs.fileformat.com/image/gif/)|Графический формат обмена| |{{< emoticons/tick >}}| | |[TIFF](https://docs.fileformat.com/image/tiff/)|Сохраняет документ как одностраничное или многостраничное TIFF‑изображение|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | -|[Текст](https://docs.fileformat.com/word-processing/txt/)|Сохранить документ в текстовом формате|{{< emoticons/tick >}}|{{< emoticons/tick >}}| | +|[Text](https://docs.fileformat.com/word-processing/txt/)|Сохранить документ в текстовом формате|{{< emoticons/tick >}}|{{< emoticons/tick >}}| |