diff --git a/zh/python-net-translation-report.json b/zh/python-net-translation-report.json new file mode 100644 index 0000000000..451cf788da --- /dev/null +++ b/zh/python-net-translation-report.json @@ -0,0 +1,12 @@ +{ + "generatedAtUtc": "2026-06-08T15:43:37.2706993Z", + "inputRoot": "E:\\Github\\Aspose.PDF-Documentation\\en\\python-net", + "outputRoot": "E:\\Github\\Aspose.PDF-Documentation\\zh\\python-net", + "totalFiles": 334, + "translatedCount": 334, + "skippedCount": 0, + "failureCount": 0, + "validationWarningCount": 0, + "failures": [], + "validationWarnings": [] +} diff --git a/zh/python-net/_index.md b/zh/python-net/_index.md index d57a18a607..a45b378873 100644 --- a/zh/python-net/_index.md +++ b/zh/python-net/_index.md @@ -6,44 +6,46 @@ type: docs weight: 40 url: /zh/python-net/ is_root: true -lastmod: "2022-10-24" -description: 了解如何使用 Aspose.PDF Python via .NET 创建用于 PDF 文档处理的应用程序,适用于任何平台的 Python。浏览教程、示例代码等。 +lastmod: "2026-06-08" +description: 了解如何使用 Aspose.PDF for Python via .NET 在任何平台上使用 Python 创建 PDF 文档处理应用程序。浏览教程、示例代码等。 sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Aspose.PDF for Python via .NET 文档指南 +Abstract: Aspose.PDF for Python via .NET 是一个多功能组件,旨在帮助开发人员使用 Python 与 .NET 组合以编程方式创建和操作 PDF 文档。此工具支持广泛的功能,包括插入表格、图形、图像、超链接和自定义字体,以及 PDF 压缩。它还提供强大的安全功能以确保文档保护。值得注意的是,开发人员可以通过 API 或 XML 模板生成 PDF 文档。文档组织为多个章节,涵盖新功能、概览、入门指南、基本和高级操作、文档转换以及解析技术。其他资源包括功能亮点、发行说明、产品页面、下载链接、安装说明、API 参考指南,以及对支持论坛和帮助台的访问。 --- -![Aspose.PDF for Python via .NET logo image](aspose_pdf-for-python-net.png) +![Aspose.PDF for Python via .NET 标志图像](aspose_pdf-for-python-net.png) -

欢迎使用 Aspose.PDF for Python via .NET

+## 欢迎使用 Aspose.PDF for Python via .NET {{% 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 最显著的特点是它支持通过 API 和 XML 模板创建 PDF 文档。 +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 最显著的特点是,它支持通过 API 和 XML 模板两种方式创建 PDF 文档。 {{% /alert %}} -

章节

+## 章节 -- [最新动态](/pdf/zh/python-net/whatsnew/) -- [概览](/pdf/zh/python-net/overview/) -- [快速入门](/pdf/zh/python-net/get-started/) +- [有什么新内容](/pdf/zh/python-net/whatsnew/) +- [概述](/pdf/zh/python-net/overview/) +- [开始使用](/pdf/zh/python-net/get-started/) - [基本操作](/pdf/zh/python-net/basic-operations/) -- [文档转换](/pdf/zh/python-net/converting/) +- [转换文档](/pdf/zh/python-net/converting/) - [解析 PDF 文档](/pdf/zh/python-net/parsing/) - [高级操作](/pdf/zh/python-net/advanced-operations/) -- [展示案例](/pdf/zh/python-net/showcases/) -- [发行说明](https://releases.aspose.com/pdf/pythonnet/release-notes/) +- [发布说明](https://releases.aspose.com/pdf/pythonnet/release-notes/)

Aspose.PDF for Python via .NET 资源

-以下是一些您可能需要用来完成任务的有用资源链接。 -- [Aspose.PDF for Python via .NET 特性](/pdf/zh/python-net/key-features/) -- [Aspose.PDF for Python via .NET 发行说明](https://releases.aspose.com/pdf/pythonnet/release-notes/) +以下是您可能需要完成任务的一些有用资源链接。 + +- [Aspose.PDF for Python via .NET 功能](/pdf/zh/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 NuGet 包](https://www.nuget.org/packages/Aspose.PDF/) - [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 +- [Aspose.PDF for Python via .NET 付费支持帮助台](https://helpdesk.aspose.com/) diff --git a/zh/python-net/advanced-operations/_index.md b/zh/python-net/advanced-operations/_index.md index f89304faa7..42ffa80507 100644 --- a/zh/python-net/advanced-operations/_index.md +++ b/zh/python-net/advanced-operations/_index.md @@ -4,90 +4,32 @@ linktitle: 高级操作 type: docs weight: 90 url: /zh/python-net/advanced-operations/ -description: Aspose.PDF for Python via .NET 可以执行简单而轻松的任务,也可以应对更复杂的目标。请查看下一节内容,适用于高级用户和开发人员。 -lastmod: "2023-04-17" +description: Aspose.PDF for Python via .NET 可以执行简单易行的任务,并应对更复杂的目标。请查看下一节,针对高级用户和开发者。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 的高级操作章节 +Abstract: 高级操作章节提供了关于以编程方式处理现有 PDF 文件的全面指导,无论其来源如何,均可使用各种工具和技术。本章节通过探讨高级功能,扩展了“Basic Operations”中讨论的基础技能。 --- - +**Advanced Operations** 是一个关于如何以编程方式处理现有 PDF 文件的章节,无论这些文件是否为 Aspose.PDF 创建的,如前所述。 [基础操作](/pdf/zh/python-net/basic-operations/), 或使用 Adobe Acrobat、Google Docs、Microsoft Office、Open Office 或任何其他 PDF 生成器创建的 PDF。 -**高级操作**是关于如何以编程方式处理现有 PDF 文件的部分,无论是使用 Aspose.PDF 创建的文档(如[基本操作](/pdf/zh/python-net/basic-operations/)中所述),还是使用 Adobe Acrobat、Google Docs、Microsoft Office、Open Office 或任何其他 PDF 制作工具创建的 PDF。 - -您将学习不同的方法: +您将学习不同的方法来: - [处理文档](/pdf/zh/python-net/working-with-documents/) - 压缩、拆分和合并文档,并对整个文档进行其他操作。 -- [处理页面](/pdf/zh/python-net/working-with-pages/) - 添加、移动或删除、裁剪页面,添加水印、印章等。 -- [处理图像](/pdf/zh/python-net/working-with-images/) - 从 PDF 文档中添加、提取或删除图像。 -- [附件](/pdf/zh/python-net/attachments/) - 您将学习如何使用 Python 以编程方式添加和删除 PDF 附件。 -- [导航与交互](/pdf/zh/python-net/navigation-and-interaction/) - 处理动作、书签、导航页面。 -- [注释](/pdf/zh/python-net/annotations/) - 注释允许用户在 PDF 页面上添加自定义内容。 - 你可以添加、删除和修改PDF文档中的注释。 -- [处理表格](/pdf/zh/python-net/working-with-tables/) - 在PDF中插入、装饰表格,提取表格数据。 -- [处理表单](/pdf/zh/python-net/working-with-forms/) - 处理交互式PDF文档,添加表单字段,提取数据。 -- [处理文本](/pdf/zh/python-net/working-with-text/) - 在PDF中添加、格式化、搜索和替换文本。 \ No newline at end of file +- [页面操作](/pdf/zh/python-net/working-with-pages/) - 添加、移动或删除,裁剪页面,添加水印、印章等。 +- [处理图像](/pdf/zh/python-net/working-with-images/) - 在 PDF 文档中添加、提取或删除图像。 +- [附件](/pdf/zh/python-net/attachments/) - 您将学习如何使用 Python 以编程方式在 PDF 中添加和删除附件。 +- [导航和交互](/pdf/zh/python-net/navigation-and-interaction/) - 处理操作、书签、页面导航。 +- [注释](/pdf/zh/python-net/annotations/) - 注释允许用户在 PDF 页面上添加自定义内容。您可以添加、删除和修改 PDF 文档中的注释。 +- [处理表格](/pdf/zh/python-net/working-with-tables/) - 在 PDF 中插入、装饰表格,提取表格数据。 +- [处理表单](/pdf/zh/python-net/working-with-forms/) - 处理交互式 PDF 文档,添加表单字段,提取数据。 +- [处理文本](/pdf/zh/python-net/working-with-text/) - 在 PDF 中添加、格式化、搜索和替换文本。 +- [比较 PDF 文档](/pdf/zh/python-net/compare-pdf-documents/) - 可以比较 PDF 文档内容。 +- [PDF 中的元数据](/pdf/zh/python-net/pdf-file-metadata/) - 获取或设置文档的元数据,处理 XMP 数据。 +- [使用图形](/pdf/zh/python-net/working-with-graphs/) - 在页面上使用形状进行操作。 +- [使用操作符](/pdf/zh/python-net/working-with-operators/) - 在 PDF 中进行低层次操作。 +- [伪像](/pdf/zh/python-net/artifacts/) - 处理 PDF 中的水印和其他特殊对象。 +- [处理 PDF 层](/pdf/zh/python-net/work-with-pdf-layers/) - 锁定层、提取元素、扁平化以及合并 PDF 层。 diff --git a/zh/python-net/advanced-operations/accessibility-tagged-pdf/_index.md b/zh/python-net/advanced-operations/accessibility-tagged-pdf/_index.md new file mode 100644 index 0000000000..32008a61a7 --- /dev/null +++ b/zh/python-net/advanced-operations/accessibility-tagged-pdf/_index.md @@ -0,0 +1,27 @@ +--- +title: Python 中的可访问性和标记 PDF +linktitle: 可访问性。标记 PDF +type: docs +weight: 180 +url: /zh/python-net/accessibility-tagged-pdf/ +description: 了解如何使用 Aspose.PDF for Python via .NET 在 Python 中创建可访问的标记 PDF,包括 PDF/UA 结构、标记内容提取、结构属性以及表格。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +标记的 PDF 文档可以让残障人士更有效地访问。向 PDF 文件添加可访问性标签有助于屏幕阅读器和其他辅助技术正确解释标题、表格、超链接、书签、替代文本以及阅读顺序。 + +## 使用标记 PDF 可做的事情 + +当您需要构建或检查符合 PDF/UA 要求的可访问 PDF 文档时,请使用本节。这些文章覆盖了创建结构、读取语义内容、更新结构属性以及处理可访问表格的核心标记 PDF 工作流。 + +## Tagged PDF 主题 + +- [创建 Tagged PDF](/pdf/zh/python-net/create-tagged-pdf/) +- [从已标记的 PDF 中提取标记内容](/pdf/zh/python-net/extract-tagged-content-from-tagged-pdfs/) +- [设置 Structure Elements 属性](/pdf/zh/python-net/setting-structure-elements-properties/) +- [在标记 PDF 中处理表格](/pdf/zh/python-net/working-with-table-in-tagged-pdfs/) + +当您需要可访问的业务文档、合规报告或用于长期重用的语义结构化内容时,Tagged PDF 尤其有用。如果您从零开始,请先创建一个 Tagged PDF,然后在工作流程变得更高级时,继续进行结构检查和属性更新。 diff --git a/zh/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/_index.md b/zh/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/_index.md new file mode 100644 index 0000000000..a4fbd196be --- /dev/null +++ b/zh/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/_index.md @@ -0,0 +1,519 @@ +--- +title: 使用 Python 创建带标签的 PDF +linktitle: 创建带标签的 PDF +type: docs +weight: 10 +url: /zh/python-net/create-tagged-pdf/ +description: 学习如何通过 .NET 使用 Aspose.PDF for Python 在 Python 中创建带标签的 PDF 文档,包括 PDF/UA 结构元素、可访问表单、目录页和自动标记。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +创建带标签的 PDF 意味着在文档中添加(或创建)某些元素,使文档能够根据 PDF/UA 要求进行验证。这些元素通常被称为结构元素。 + +## 创建带标签的 PDF(简单场景) + +为了在带标签的 PDF 文档中创建结构元素,Aspose.PDF 提供了使用以下方法创建结构元素的方法 [ItaggedContent](https://reference.aspose.com/pdf/python-net/aspose.pdf.tagged/itaggedcontent/) 接口。此示例创建了带标签的 PDF 文档,即具有语义结构的 PDF,使其更易于访问且符合 PDF/UA 等标准。 +以下代码片段显示如何创建带标签的 PDF,其中包含 2 个元素:标题和段落。 + +```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) +``` + +## 创建带标签的 PDF(高级) + +```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) +``` + +创建后我们将获得以下文档: + +![带有 2 个元素的带标签的 PDF 文档-标题和段落](taggedpdf-01.png) + +## 设置文本结构样式 + +带标签的 PDF 是结构化文档,为内容提供可访问性功能和语义含义。 + +该示例使用带标签的内容结构创建具有无障碍功能的 PDF 文档。它演示了如何使用自定义样式和适当的文档元数据制作段落元素。 + +```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) +``` + +## 说明结构元素 + +带标签的 PDF 对于无障碍访问合规性至关重要,可提供可由屏幕阅读器和其他辅助技术正确解释的结构化内容。以下代码片段显示了如何使用嵌入式图像创建带标签的 PDF 文档: + +1. 使用图像创建带标签的 PDF。 +1. 配置文档。 +1. 创建和配置图。 +1. 设置定位。 +1. 保存文档。 + +```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) +``` + +## 验证带标签的 PDF + +通过 .NET for Python 的 Aspose.PDF 提供了验证带有 PDF/UA 标签的 PDF 文档的功能。“validate_tagged_pdf” 方法根据 PDF/UA-1 标准验证 PDF 文档,该标准是 ISO 14289 可访问的 PDF 文档规范的一部分。这可确保残障用户和辅助技术用户可以访问 PDF。 + +- 文件结构。正确的语义标记和逻辑结构。 +- 替代文本。图像和非文本元素的替代文本。 +- 阅读顺序。屏幕阅读器的逻辑顺序。 +- 颜色和对比度。足够的对比度。 +- 表格。可访问的表单字段和标签。 +- 导航。正确的书签和导航结构。 + +```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}") +``` + +## 调整文本结构的位置 + +以下代码片段显示了如何调整带标签的 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) +``` + +## 使用自动标记将 PDF 转换为 PDF/UA-1 + +此代码片段解释了如何使用适用于 Python 的 Aspose.PDF 通过.NET 将标准 PDF 转换为符合 PDF/UA-1(通用无障碍访问)的文件。 + +PDF/UA 确保残障用户可以访问文档,并与屏幕阅读器等辅助技术兼容。在转换过程中,该库可以自动生成逻辑结构树并使用内置的自动标记和标题识别应用语义标签。 + +通过配置 PDF 格式转换选项和启用 “自动标记设置”,您可以高效地将现有 PDF 转换为可访问的文档,而无需手动编辑结构。 + +1. 加载源文档。 +1. 创建 PDF/UA 转换选项。 +1. 启用自动标记。 +1. 配置航向识别。 +1. 将标记配置附加到转换选项。 +1. 运行转换过程。 +1. 保存可访问的 PDF。 + +```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) +``` + +## 使用可访问的签名表单字段创建带标签的 PDF + +1. 创建新的 PDF 文档。 +1. 访问带标签的内容。 +1. 创建签名表单字段。 +1. 将该字段添加到 AcroForm。 +1. 在标签结构中创建表单元素。 +1. 将 “结构” 元素链接到 “表单” 字段。 +1. 将表单元素追加到逻辑结构树中。 +1. 保存文档。 + +```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) +``` + +## 使用目录 (TOC) 页面创建带标签的 PDF + +此示例说明如何使用适用于 Python 的 Aspose.PDF 通过.NET 创建带有结构化目录 (TOC) 页面的带标签的 PDF 文档。 + +1. 创建新的 PDF 文档。 +1. 创建专用的目录页面。 +1. 在逻辑结构树中创建和注册 TOC 元素。 +1. 添加内容页面。 +1. 创建标题元素。 +1. 创建 /TOCI 元素。 +1. 将标题链接到目录。 +1. 保存文档。 + +```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) +``` + +## 使用分层目录 (TOC) 创建带有高级标签的 PDF + +通过.NET 使用 Python 版 Aspose.PDF,您可以创建具有结构化和分层目录表 (TOC) 的高级、带完整标签的 PDF 文档。 + +1. 创建文档并启用带标签的内容。 +1. 添加和配置 TOC 页面。 +1. 创建 /TOC 结构元素。 +1. 将 TOC 页面标题链接到标题元素。 +1. 添加主内容页面和第一个标题。 +1. 为标题创建 TOC 条目。 +1. 使用列表结构创建嵌套小节。 +1. 添加第二个顶级版块。 +1. 保存文档。 + +```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) +``` + +## 相关标签 PDF 主题 + +- [从带标签的 PDF 中提取带标签的内容](/pdf/zh/python-net/extract-tagged-content-from-tagged-pdfs/) 在创建后检查逻辑结构树。 +- [设置结构元素的属性](/pdf/zh/python-net/setting-structure-elements-properties/) 优化标题、语言、替代文本和扩展文本。 +- [在带标签的 PDF 中使用表格](/pdf/zh/python-net/working-with-table-in-tagged-pdfs/) 当您的可访问文档包含结构化表格时。 diff --git a/zh/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/taggedpdf-01.png b/zh/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/taggedpdf-01.png new file mode 100644 index 0000000000..6bb7280be1 Binary files /dev/null and b/zh/python-net/advanced-operations/accessibility-tagged-pdf/create-tagged-pdf-documents/taggedpdf-01.png differ diff --git a/zh/python-net/advanced-operations/accessibility-tagged-pdf/extract-tagged-content-from-tagged-pdfs/_index.md b/zh/python-net/advanced-operations/accessibility-tagged-pdf/extract-tagged-content-from-tagged-pdfs/_index.md new file mode 100644 index 0000000000..38887af655 --- /dev/null +++ b/zh/python-net/advanced-operations/accessibility-tagged-pdf/extract-tagged-content-from-tagged-pdfs/_index.md @@ -0,0 +1,152 @@ +--- +title: 在 Python 中从 PDF 中提取带标签的内容 +linktitle: 提取带标签的内容 +type: docs +weight: 20 +url: /zh/python-net/extract-tagged-content-from-tagged-pdfs/ +description: 学习如何通过 .NET 使用 Aspose.PDF for Python 在 Python 中提取带标签的 PDF 内容,包括访问带标签的内容、根结构和子结构元素。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +在本文中,您将学习如何使用 Python 从 PDF 文档中提取带标签的内容。 + +当您需要检查带标签的 PDF、阅读逻辑结构树或验证结构元素是否为无障碍工作流程正确创建时,请使用这些示例。 + +## 获取带标签的 PDF 内容 + +为了获取带有标签文本的 PDF 文档的内容,Aspose.PDF 提供 [已标记内容](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties) 的财产 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 班级。 + +使用结构化和分层的目录 (TOC) 创建高级、带完整标签的 PDF 文档: + +1. 创建新的 Document 对象。 +1. 访问 tagged_content 属性。 +1. 使用 “set_title ()” 设置文档标题。 +1. 使用 “set_language ()” 设置文档语言。 +1. 保存文档。 + +```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) +``` + +## 获取根结构 + +带标签的 PDF 包含定义文档语义结构的逻辑结构树。StructTreeRoot 代表该逻辑树的根,而 rootElement 则提供了与文档的顶级结构元素进行交互的接口。 + +以下代码片段显示了如何获取带标签的 PDF 文档的根结构: + +1. 创建新的带标签的 PDF 文档。 +1. 访问带标签的内容并设置元数据。 +1. 访问 StructTreeRoot 和 rootElement。 +1. 保存带标签的 PDF。 + +```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) +``` + +## 访问子元素 + +带标签的 PDF 包含逻辑结构树,用于定义文档的语义层次结构(标题、段落、表单、列表等)。访问和修改这些结构元素允许您: + +- 检查元数据,例如标题、语言、actual_text 和无障碍相关属性 +- 更新属性以改善可访问性或本地化 +- 以编程方式调整逻辑文档结构以符合 PDF/UA + + 以下代码片段显示了如何访问带标签的 PDF 文档的子元素: + +```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) +``` + +## 相关标签 PDF 主题 + +- [创建带标签的 PDF](/pdf/zh/python-net/create-tagged-pdf/) 在检查其结构之前构建可访问的带标签的文档。 +- [设置结构元素的属性](/pdf/zh/python-net/setting-structure-elements-properties/) 在提取结构元素后更新语义属性。 +- [在带标签的 PDF 中使用表格](/pdf/zh/python-net/working-with-table-in-tagged-pdfs/) 用于标记表的可访问性工作流程。 \ No newline at end of file diff --git a/zh/python-net/advanced-operations/accessibility-tagged-pdf/setting-structure-elements-properties/_index.md b/zh/python-net/advanced-operations/accessibility-tagged-pdf/setting-structure-elements-properties/_index.md new file mode 100644 index 0000000000..56c3ce1ab7 --- /dev/null +++ b/zh/python-net/advanced-operations/accessibility-tagged-pdf/setting-structure-elements-properties/_index.md @@ -0,0 +1,644 @@ +--- +title: 在 Python 中设置 Tagged PDF Structure Element 属性 +linktitle: 设置 Structure Elements 属性 +type: docs +weight: 30 +url: /zh/python-net/setting-structure-elements-properties/ +description: 了解如何在 Python 中使用 Aspose.PDF for Python via .NET 设置 Tagged PDF 结构元素属性,包括标题、语言、实际文本、替代文本和扩展文本。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +Structure elements 定义 PDF 文档的语义层次结构,例如章节、标题、段落或表格。通过设置 title、language、alternative_text、actual_text 和 expansion_text 等属性,您可以提升 PDF 对屏幕阅读器等辅助技术的可访问性和语义意义。 + +以下代码片段展示了如何设置标记 PDF 文档的结构元素属性: + +1. 创建一个新的标记 PDF 文档。 +1. 设置文档元数据。 +1. 创建结构元素。 +1. 设置可访问性属性。 +1. 保存 Tagged PDF。 + +```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) +``` + +## 设置文本结构元素 + +为了设置 Tagged PDF 文档的文本结构元素,Aspose.PDF 提供 [段落元素](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/paragraphelement/) 类。以下代码片段展示了如何设置 Tagged PDF 文档的文本结构元素: + +```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) + +``` + +## 设置文本块结构元素 + +此 Python 示例使用 Aspose.PDF 创建一个带有结构化层次标题和段落的 Tagged PDF,提升文档的语义和可访问性特性。 + +1. 创建一个新的标记 PDF 文档。 +1. 设置文档元数据。 +1. 访问根结构元素。 +1. 创建多级标题。 +1. 将标题追加到根结构。 +1. 创建一个段落元素。 +1. 将段落追加到根结构。 +1. 保存 Tagged PDF。 + +以下代码片段展示了如何设置 Tagged PDF 文档的文本块结构元素: + +```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) +``` + +## 设置内联结构元素 + +使用 Aspose.PDF for Python via .NET 在 Tagged PDF 的标题和段落中创建内联文本元素(/Span)。 + +以下代码片段展示了如何设置 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) +``` + +## 设置自定义标签名称 + +使用 Aspose.PDF for Python 为带标签的 PDF 设置结构和内联元素的自定义标签名称。 + +以下代码片段展示了如何设置自定义标签名称: + +1. 创建一个新的标记 PDF 文档。 +1. 设置文档元数据。 +1. 创建一个section元素。 +1. 创建带有自定义标签的段落元素。 +1. 创建带有自定义标签的内联 span 元素。 +1. 保存 Tagged PDF。 + +```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) +``` + +## 将结构元素添加到元素中 + +**此功能在 19.4 版或更高版本中受支持。** + +使用 Aspose.PDF for Python via .NET 在标记 PDF 中创建链接和图像元素。 + +下面的代码片段演示了如何在段落中使用 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) +``` + +## 设置链接结构元素 + +Aspose.PDF for Python via .NET API 还允许您添加链接结构元素。 + +下面的代码片段演示了如何向 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) +``` + +## 设置 Note 结构元素 + +Aspose.PDF for Python via .NET API 还允许您添加 [注释元素](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/noteelement/) 在标记的 PDF 文档中。下面的代码片段展示了如何在 Tagged PDF 文档中添加 note 元素: + +```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) +``` + +## 如何设置语言和标题 + +Aspose.PDF for Python via .NET API 还允许您根据 PDF/UA 规范为文档设置语言和标题。语言既可以为整个文档设置,也可以为其各个结构元素单独设置。以下代码片段展示了如何在 Tagged PDF Document 中设置语言和标题: + +1. 创建一个新的标记 PDF 文档。 +1. 设置文档标题和语言。 +1. 创建一个标题元素。 +1. 添加具有特定语言的段落。 +1. 保存 Tagged PDF。 + +```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) +``` + +## 相关 Tagged PDF 主题 + +- [创建 Tagged PDF](/pdf/zh/python-net/create-tagged-pdf/) 在更新属性之前生成结构元素。 +- [从已标记的 PDF 中提取标记内容](/pdf/zh/python-net/extract-tagged-content-from-tagged-pdfs/) 检查现有的结构节点和元数据。 +- [在标记 PDF 中处理表格](/pdf/zh/python-net/working-with-table-in-tagged-pdfs/) 如果您需要对表结构应用可访问属性。 diff --git a/zh/python-net/advanced-operations/accessibility-tagged-pdf/working-with-table-in-tagged-pdfs/_index.md b/zh/python-net/advanced-operations/accessibility-tagged-pdf/working-with-table-in-tagged-pdfs/_index.md new file mode 100644 index 0000000000..93f56aa4f7 --- /dev/null +++ b/zh/python-net/advanced-operations/accessibility-tagged-pdf/working-with-table-in-tagged-pdfs/_index.md @@ -0,0 +1,531 @@ +--- +title: 在 Python 中处理 Tagged PDF 表格 +linktitle: 在标记 PDF 中处理表格 +type: docs +weight: 40 +url: /zh/python-net/working-with-table-in-tagged-pdfs/ +description: 了解如何在 Python 中使用 Aspose.PDF for Python via .NET 处理 Tagged PDF 中的可访问表格,包括结构、跨列、对齐以及符合 PDF/UA 的表格标记。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +## 在 Tagged PDF 中创建表格 + +通过遵循上述步骤,您可以使用 Aspose.PDF for Python 在 PDF 文档中生成语义丰富、可访问的表格。生成的文件符合 PDF/UA-1 合规标准,确保与屏幕阅读器和辅助技术的兼容性。这非常适用于涉及法规遵从、可访问性审计和包容性内容发布的使用场景。 + +以下代码片段展示了如何在 Tagged PDF 文档中创建表格: + +1. 创建一个新的标记 PDF 文档。 +1. 设置文档元数据。 +1. 创建表结构。 +1. 创建表头行。 +1. 创建表体行及其单元格。 +1. 创建表格页脚行。 +1. 设置表格摘要属性。 +1. 保存已标记的 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) +``` + +## 样式表元素 + +1. 创建一个新的标记 PDF 文档。 +1. 设置文档标题和语言。 +1. 创建表结构元素。 +1. 配置重复的行和列。 +1. 添加页眉、正文和页脚。 +1. 保存 Tagged PDF 文档。 + +以下代码片段展示了如何在 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) +``` + +## 样式表行 + +Aspose.PDF for Python via .NET 允许在 Tagged PDF 文档中为表格行设置样式。为了为表格行设置样式,您可以使用以下属性 [TableTR 元素](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/) class. 以下是您可以用于为表格行设置样式的属性列表: + +- [背景颜色](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [边框](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [默认单元格边框](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [最小行高](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [固定行高](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [is_in_new_page](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [行是否损坏](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [默认单元格文本状态](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [默认单元格内边距](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). +- [vertical_alignment](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tabletrelement/#properties). + +以下代码片段展示了如何在 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) +``` + +## 表格单元格样式 + +Aspose.PDF for Python via .NET 允许在 Tagged PDF 文档中对表格单元格进行样式设置。为了对表格单元格进行样式设置,您可以使用属性 [表格单元格元素](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/) class. 以下是您可以用来设置表格单元格样式的属性列表: + +- [背景颜色](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [边框](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [is_no_border](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [边距](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [对齐](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [默认单元格文本状态](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [是否已换行](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [vertical_alignment](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [列跨度](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). +- [行跨度](https://reference.aspose.com/pdf/python-net/aspose.pdf.logicalstructure/tablecellelement/#properties). + +以下代码片段展示了如何在 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) +``` + +## 调整表格位置 + +使用 Aspose.PDF for Python via .NET 调整 Tagged PDF 中表格的位置,同时保持可访问性功能。 + +以下代码片段展示了如何在 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) +``` + +## 相关 Tagged PDF 主题 + +- [创建 Tagged PDF](/pdf/zh/python-net/create-tagged-pdf/) 构建围绕您的表格内容的整体可访问文档结构。 +- [从已标记的 PDF 中提取标记内容](/pdf/zh/python-net/extract-tagged-content-from-tagged-pdfs/) 在生成后检查与表相关的结构元素。 +- [设置 Structure Elements 属性](/pdf/zh/python-net/setting-structure-elements-properties/) 对表格单元格及其他结构元素的可访问元数据进行细化。 \ No newline at end of file diff --git a/zh/python-net/advanced-operations/annotations/_index.md b/zh/python-net/advanced-operations/annotations/_index.md index e32225d4a9..6c9443db6a 100644 --- a/zh/python-net/advanced-operations/annotations/_index.md +++ b/zh/python-net/advanced-operations/annotations/_index.md @@ -1,162 +1,43 @@ --- -title: PDF 注释 +title: Python 中的 PDF 注释 linktitle: PDF 注释 type: docs weight: 100 url: /zh/python-net/annotations/ -description: 本节介绍如何使用 Aspose.PDF 库对 PDF 文件添加各种注释。 -lastmod: "2023-02-17" +description: 了解如何使用 Aspose.PDF for Python via .NET 在 Python 中添加、修改、提取和管理 PDF 注释,包括文本、高亮、链接、图形等。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 向 PDF 添加注释 +Abstract: 本文讨论了在 PDF 中使用注释作为交互式元素,以增强文档的交互性和用户参与度。它突出展示了 Aspose.PDF for Python Library 在支持多种注释类型方面的能力,包括文本、高亮、图形和多媒体注释。注释具有多种用途,例如评论、审阅、标记文档以及提供反馈,从而促进协作、沟通,并加深对文档内容的理解。文章还提到有专门章节详细说明如何添加、删除和检索注释,为在 PDF 文档中有效管理这些元素提供指导。 --- - +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 for 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/zh/python-net/add-delete-and-get-annotation/) - 从此开始,了解主要的分组批注类别以及创建、检查和删除的核心工作流。 +- [导入和导出注释](/pdf/zh/python-net/import-export-annotations/) - 将注释从一个 PDF 文档复制到另一个 PDF 文件。 -You are able to do the following: +### 注释组 -您可以执行以下操作: +分组注释指南包括以下子主题: -- [Add, Delete and Get Annotation](/pdf/zh/python-net/add-delete-and-get-annotation/) - this section explains how to work with all types of allowed annotations. - -- [添加、删除和获取注释](/pdf/zh/python-net/add-delete-and-get-annotation/) - 本节解释如何处理所有类型的允许注释。 - - \ No newline at end of file +- [文本注释](/pdf/zh/python-net/text-based-Annotations/) - 使用自由文本、突出显示、下划线、波浪线和删除线注释。 +- [标记注释](/pdf/zh/python-net/markup-annotations/) - 添加或检查在评审场景中使用的备注、插入符号和替换注释。 +- [交互式注释](/pdf/zh/python-net/interactive-annotations/) - 创建链接注释、导航按钮和打印按钮。 +- [形状注释](/pdf/zh/python-net/shape-annotations/) - 使用线条、矩形、圆形、多边形和折线批注。 +- [媒体注释](/pdf/zh/python-net/media-annotations/) - 添加音频、屏幕、富媒体和3D批注。 +- [安全注释](/pdf/zh/python-net/security-annotations/) - 处理文件附件、编辑遮蔽以及相关的保护型批注。 +- [水印注释](/pdf/zh/python-net/watermark-annotations/) - 添加和管理基于批注的水印元素。 +批注在文档审阅、协作、内容标记和交互式导航方面尤其有用。当您想浏览支持的批注类型时,请从分组概览开始;如果已经了解所需的工作流,也可以直接跳转到特定主题。 diff --git a/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md index 8b4da6f4f8..46588c186d 100644 --- a/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md +++ b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/_index.md @@ -1,90 +1,34 @@ --- -title: 添加、删除和获取注释使用 Python +title: 在 Python 中添加、删除和获取 PDF 注释 linktitle: 添加、删除和获取注释 type: docs weight: 20 url: /zh/python-net/add-delete-and-get-annotation/ -description: 使用 Aspose.PDF for Python,您可以从 PDF 文件中添加、删除和获取注释。检查所有注释列表以解决您的任务。 -lastmod: "2023-02-17" +description: 使用 Aspose.PDF for Python,您可以在 PDF 文件中添加、删除和获取注释。检查所有注释列表以完成您的任务。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 操作 PDF 注释 +Abstract: PDF 文档中的注释通过允许添加诸如备注、文本高亮、形状和文件附件等各种元素来增强用户交互。这些功能提升了文档的浏览体验和交互性。Aspose.PDF for Python 库将注释划分为多个组——文本注释、突出显示注释、图形注释、粘性注释和额外注释,每个组都有不同的功能,以丰富文档的参与度和可用性。 --- - +PDF 文档中的注释是允许用户以特定方式在文档中分配内容的元素。注释可用于添加各种类型的备注、突出显示文本、绘制形状、附加文件以及执行其他操作,从而提升文档的浏览、交互和互动性。 -**什么是PDF文档中的注释?** +此页面将本部分文档中支持的主要批注类型进行分组,以便您可以快速跳转到所需的工作流。 -PDF文档中的注释是允许用户以某种方式在文档中分配内容的元素。注释可以用来添加不同类型的笔记、高亮文本、绘制形状、附加文件以及执行其他操作,以改善文档的查看、交互性和互动性。 +我们已将 Aspose.PDF for Python 库中可用的不同批注类型组合成组: -我们将Aspose.PDF for Python库中可用的不同种类的注释组合成组: +- [交互式注释](/pdf/zh/python-net/interactive-annotations/) +- [标记注释](/pdf/zh/python-net/markup-annotations/) +- [媒体注释](/pdf/zh/python-net/media-annotations/) +- [安全注释](/pdf/zh/python-net/security-annotations/) +- [形状注释](/pdf/zh/python-net/shape-annotations/) +- [文本注释](/pdf/zh/python-net/text-based-Annotations/) +- [水印注释](/pdf/zh/python-net/watermark-annotations/) -- [PDF文本注释](/pdf/zh/python-net/text-annotation/) -- [PDF高亮注释](/pdf/zh/python-net/highlights-annotation/) -- [PDF图形注释](/pdf/zh/python-net/figures-annotation/) -- [PDF便签注释](/pdf/zh/python-net/sticky-annotations/) -- [额外注释](/pdf/zh/python-net/extra-annotations/) \ No newline at end of file +## 相关批注主题 + +- [PDF 批注概览](/pdf/zh/python-net/annotations/) 用于父级章节和批注概念。 +- [导入和导出注释](/pdf/zh/python-net/import-export-annotations/) diff --git a/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/extra-annotations/_index.md b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/extra-annotations/_index.md deleted file mode 100644 index 7662243a38..0000000000 --- a/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/extra-annotations/_index.md +++ /dev/null @@ -1,345 +0,0 @@ ---- -title: 使用 Python 添加额外注释 -linktitle: 额外注释 -type: docs -weight: 60 -url: /zh/python-net/extra-annotations/ -description: 本节描述如何从您的 PDF 文档中添加、获取和删除额外类型的注释。 -lastmod: "2023-02-17" -sitemap: - changefreq: "weekly" - priority: 0.7 ---- - - - -## 如何通过 Python 将插入符号注释添加到现有 PDF 文件中 - -插入符号注释是指示文本编辑的符号。插入符号注释也是一种标记注释,因此 Caret 类继承自 Markup 类,并提供函数以获取或设置插入符号注释的属性并重置插入符号注释外观的流程。插入符号注释通常用于建议文本的更改、添加或修改。 - -创建插入符号注释的步骤: - -1. 加载 PDF 文件 - 新建 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)。 -2. 创建新的 [CaretAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/caretannotation/) 并设置插入符号参数(新建矩形、标题、主题、标志、颜色)。此注释用于指示文本的插入。 -3. 一旦我们能够将注释附加到页面。 - -以下代码片段显示了如何将插入符号注释添加到 PDF 文件: - -```python - - import aspose.pdf as ap - - # 打开文档 - document = ap.Document(input_file) - - caretAnnotation1 = ap.annotations.CaretAnnotation( - document.pages[1], ap.Rectangle(200, 700.664, 308.708, 740.769, True) - ) - caretAnnotation1.title = "Aspose 用户" - caretAnnotation1.subject = "插入文本 1" - caretAnnotation1.flags = ap.annotations.AnnotationFlags.PRINT - caretAnnotation1.color = ap.Color.blue - - document.pages[1].annotations.append(caretAnnotation1) - document.save(output_file) -``` - - -### 获取插入符号注释 - -请尝试使用以下代码片段在 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) -``` - -### 删除插入符号注释 - -以下代码片段展示了如何使用 Python 从 PDF 文件中删除插入符号注释。 - -```python - - import aspose.pdf as ap - - # 加载 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) -``` - -## 添加链接注释 - -[链接](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/linkannotation/) 是在点击时打开 URL 或移动到同一文档或外部文档中某些位置的注释。 - -一个链接注释是一个可以放置在页面任意位置的矩形区域。每个链接都有一个与之关联的相应 PDF 操作。当用户点击此链接的区域时,将执行此操作。 - -以下代码片段展示了如何使用电话号码示例向 PDF 文件添加链接注释: - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - # 创建 TextFragmentAbsorber 对象以查找电话号码 - textFragmentAbsorber = ap.text.TextFragmentAbsorber("file") - - # 仅接受第一页的吸收器 - document.pages[1].accept(textFragmentAbsorber) - - phoneNumberFragment = textFragmentAbsorber.text_fragments[1] - - # 创建链接注释并设置操作以拨打电话号码 - linkAnnotation = ap.annotations.LinkAnnotation(document.pages[1], phoneNumberFragment.rectangle) - linkAnnotation.action = ap.annotations.GoToURIAction("www.aspose.com") - - # 添加注释到页面 - document.pages[1].annotations.append(linkAnnotation) - document.save(output_file) -``` - - -### 获取链接注释 - -请尝试使用以下代码片段从 PDF 文档中获取 [LinkAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/linkannotation/)。 - -```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) -``` - -### 删除链接注释 - -以下代码片段显示了如何从 PDF 文件中删除链接注释。为此,我们需要找到并删除第一页上的所有链接注释。之后,我们将保存删除注释的文档。 - -```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) -``` - - -## 使用 Aspose.PDF for Python 对指定页面区域进行编辑注释 - -Aspose.PDF for Python via .NET 支持在现有 PDF 文件中添加和操作注释。PDF 文档中的编辑注释用于永久删除或隐藏文档中的机密信息。编辑信息的过程包括覆盖或遮盖特定内容,例如文本、图像或图形,以限制其他人对其的可见性和访问。这确保了敏感信息在文档中保持隐藏和保护。为了满足这一要求,提供了一个名为 [RedactionAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/redactionannotation/) 的类,可以用来编辑特定页面区域,或者可以用来操作现有的编辑注释并编辑它们(即展平注释并移除其下的文本)。 - -```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) -``` - - -### 获取涂黑注解 - -```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) -``` - -### 删除涂黑注解 - -```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/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/figures/_index.md b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/figures/_index.md deleted file mode 100644 index e866f9f4ac..0000000000 --- a/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/figures/_index.md +++ /dev/null @@ -1,436 +0,0 @@ ---- -title: 用Python添加图形注释 -linktitle: 图形注释 -type: docs -weight: 30 -url: /zh/python-net/figures-annotation/ -description: 本文描述了如何使用Aspose.PDF for Python通过.NET添加、获取和删除PDF文档中的图形注释 -lastmod: "2023-02-17" -sitemap: - changefreq: "weekly" - priority: 0.7 ---- - - - -## 添加方形和圆形注释 - -在 PDF 文档中,方形注释指的是一种特定类型的注释,它以方形形状表示。方形注释用于突出显示或引起文档中特定区域或部分的注意。 - -[方形](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/squareannotation/)和[圆形](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/circleannotation/)注释分别在页面上显示一个矩形或椭圆。 - -创建方形或圆形注释的步骤: - -1. 加载 PDF 文件 - 新建 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)。 -1. 创建新的 [SquareAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/squareannotation) 并设置参数(新的矩形、标题、颜色、内部颜色、不透明度)。 -1. 然后我们需要将方形注释添加到页面中。 - -以下代码片段展示了如何在 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 = "约翰·史密斯" - 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) -``` - -以下代码片段向您展示了如何在 PDF 页面中添加圆形注释。 - -```python - - import aspose.pdf as ap - - # 打开文档 - document = ap.Document(input_file) - - circleAnnotation = ap.annotations.CircleAnnotation( - document.pages[1], ap.Rectangle(270, 160, 483, 383, True) - ) - circleAnnotation.title = "约翰·史密斯" - 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) -``` - - -例如,我们将看到在 PDF 文档中添加方形和圆形注释的以下结果: - -![Circle and Square Annotation demo](circle_demo.png) - -### 获取圆形注释 - -请尝试使用以下代码片段从 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) -``` - -### 获取方形注释 - -请尝试使用以下代码片段从 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) -``` - -### 删除圆形注释 - -以下代码片段展示了如何从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) -``` - -### 删除方形注释 - -以下代码片段展示了如何从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) -``` - -## 添加多边形和折线注释 - -折线工具允许您在文档上创建具有任意边数的形状和轮廓。 - -[Polygon Annotations](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/polygonannotation/) 表示页面上的多边形。它们可以具有任意数量的由直线连接的顶点。 - -[Polyline Annotations](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/polylineannotation/) 也类似于多边形,唯一的区别是第一个和最后一个顶点没有隐式连接。 - -我们创建多边形注释的步骤: - -1. 加载 PDF 文件 - 新的 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)。 -1. 创建新的 [Polygon Annotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/polygonannotation) 并设置多边形参数(新的矩形、新的点、标题、颜色、内部颜色和不透明度)。 -1. 之后我们可以将注释添加到页面。 - -以下代码片段显示了如何向 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) -``` - - -以下代码片段显示了如何向 PDF 文件添加折线注释: - -1. 加载 PDF 文件 - 新建 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)。 -1. 创建新的 [Polyline Annotations](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/polylineannotation/) 并设置多边形参数(新建矩形、新建点、标题、颜色、内颜色和不透明度)。 -1. 之后我们可以将注释添加到页面。 - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - - 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) - ) - - document.pages[1].annotations.append(polylineAnnotation) - document.save(output_file) -``` - - -### 获取多边形和折线注释 - -请尝试使用以下代码片段在 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) -``` - -请尝试使用以下代码片段在 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) -``` - -### 删除多边形和折线注释 - -以下代码片段展示了如何从 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) -``` - - -以下代码片段展示了如何从 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/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/hightlights/_index.md b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/hightlights/_index.md deleted file mode 100644 index 60b1033224..0000000000 --- a/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/hightlights/_index.md +++ /dev/null @@ -1,330 +0,0 @@ ---- -title: PDF 高亮注释使用 Python -linktitle: 高亮注释 -type: docs -weight: 20 -url: /zh/python-net/highlights-annotation/ -description: 标记注释以高亮、下划线、删除线或锯齿下划线的形式呈现在文档的文本中。 -lastmod: "2023-02-17" -sitemap: - changefreq: "weekly" - priority: 0.7 ---- - - - -文本标记注释在PDF中用于突出显示、下划线、跳过或在文档中添加文本注释。这些注释旨在突出或引起对文本特定部分的注意。这样的注释允许用户以视觉方式标记或修改PDF文件的内容。 - -高亮注释用于用彩色背景(通常为黄色)标记文本,以指示其重要性或相关性。 - -下划线注释是在选定文本下方放置的一条线,以表示重要性、强调或建议的编辑。 - -删除线注释包括对特定文本的删除线或删除线,以表明它已被删除、替换或不再有效。 - -波浪线用于在文本下划线以指示不同类型的重音,例如拼写错误、潜在问题或建议的更改。 - -## 添加文本标记注释 - -为了向PDF文档添加文本标记注释,我们需要执行以下操作: - -1. 加载 PDF 文件 - 新的 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象。 -1. 创建注释: - - [HighlightAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/highlightannotation/) 并设置参数(标题,颜色)。 - - [StrikeOutAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/strikeoutannotation/) 并设置参数(标题,颜色)。 - - [SquigglyAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/squigglyannotation/) 并设置参数(标题,颜色)。 - - [UnderlineAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/underlineannotation/) 并设置参数(标题,颜色)。 -1. 然后我们应该将所有注释添加到页面中。 - -### 添加高亮注释 - -```python - - import aspose.pdf as ap - - # 打开文档 - document = ap.Document(input_file) - - # 创建圆形注释 - highlightAnnotation = ap.annotations.HighlightAnnotation( - document.pages[1], ap.Rectangle(300, 750, 320, 770, True) - ) - document.pages[1].annotations.append(highlightAnnotation) - document.save(output_file) -``` - - -### 添加删除线注释 - -```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 = "Aspose 用户" - strikeoutAnnotation.subject = "插入文本 1" - strikeoutAnnotation.flags = ap.annotations.AnnotationFlags.PRINT - strikeoutAnnotation.color = ap.Color.blue - - document.pages[1].annotations.append(strikeoutAnnotation) - document.save(output_file) -``` - -### 添加波浪线注释 - -```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) -``` - -### 添加下划线注释 - -```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 = "Aspose 用户" - underlineAnnotation.subject = "插入下划线 1" - underlineAnnotation.flags = ap.annotations.AnnotationFlags.PRINT - underlineAnnotation.color = ap.Color.blue - - document.pages[1].annotations.append(underlineAnnotation) - document.save(output_file) -``` - - -## 获取文本标注 - -请尝试使用以下代码片段从 PDF 文档中获取文本标注。 - -### 获取高亮标注 - -```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) -``` - -### 获取删除线标注 - -```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) -``` - -### 获取波浪线标注 - -```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) -``` - - -### 获取下划线注释 - -```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) -``` - -## 删除文本标记注释 - -以下代码片段演示了如何从PDF文件中删除文本标记注释。 - -### 删除高亮注释 - -```python - - import aspose.pdf as ap - - # 加载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) -``` - -### 删除删除线注释 - -```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) -``` - - -### 删除波浪线注释 - -```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) -``` - -### 删除下划线注释 - -```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/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/interactive-annotations/_index.md b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/interactive-annotations/_index.md new file mode 100644 index 0000000000..5b71de1b60 --- /dev/null +++ b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/interactive-annotations/_index.md @@ -0,0 +1,330 @@ +--- +title: 使用 Python 的交互式注释 +linktitle: 交互式注释 +type: docs +weight: 60 +url: /zh/python-net/interactive-annotations/ +description: 了解如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中添加、读取和删除链接注释,以及创建导航和打印按钮。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中处理交互式 PDF 注释和按钮。 +Abstract: 本文解释了如何使用 Aspose.PDF for Python via .NET 在 PDF 文件中处理交互式注释。它涵盖了添加链接注释、读取现有链接区域、删除链接注释、创建页面导航按钮以及向 PDF 文档添加打印按钮。 +--- + +本文展示了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中处理交互式批注。 + +示例脚本演示了几种常见的工作流程: + +- 在现有文本上添加链接注释 +- 获取页面中的链接注释矩形 +- 删除链接注释 +- 创建导航按钮 +- 创建一个打印按钮 + +## 链接注释 + +### 添加链接注释 + +此示例在第一页中搜索文本片段 `"file"` 并在匹配的文本区域上放置一个可点击的链接注释。当用户点击该注释时,PDF 将打开指定的网页地址。 + +#### 加载文档并查找目标文本 + +创建一个 `Document` 对象和使用 `TextFragmentAbsorber` 搜索将成为交互式的文本。 + +```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] +``` + +#### 创建链接注释 + +构建一个 `LinkAnnotation` 使用匹配文本片段的矩形并为其分配一个 URI 操作。 + +```python +link_annotation = ap.annotations.LinkAnnotation( + document.pages[1], phone_number_fragment.rectangle +) +link_annotation.action = ap.annotations.GoToURIAction("https://www.aspose.com") +``` + +#### 添加注释并保存 PDF + +将注释附加到页面并保存更新后的文件。 + +```python +document.pages[1].annotations.append(link_annotation) +document.save(outfile) +``` + +#### 完整示例 + +```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) +``` + +### 获取链接注释 + +要检查现有的交互式链接,请过滤第一页的注释集合,并仅保留其类型为的项目 `LINK`. 示例随后为每个匹配的注释打印矩形。 + +#### 加载 PDF 并收集链接注释 + +```python +document = ap.Document(infile) +link_annotations = [ + a + for a in document.pages[1].annotations + if (a.annotation_type == ap.annotations.AnnotationType.LINK) +] +``` + +#### 读取注释矩形 + +遍历过滤后的注释并打印每个链接区域的坐标。 + +```python +for link_annotation in link_annotations: + print(link_annotation.rect) +``` + +#### 完整示例 + +```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) +``` + +### 删除链接注释 + +此工作流会删除第一页中的所有链接注释,并将清理后的 PDF 保存为新文件。 + +#### 查找要删除的链接注释 + +```python +document = ap.Document(infile) +link_annotations = [ + a + for a in document.pages[1].annotations + if (a.annotation_type == ap.annotations.AnnotationType.LINK) +] +``` + +#### 删除每个链接注释 + +```python +for link_annotation in link_annotations: + document.pages[1].annotations.delete(link_annotation) +``` + +#### 保存已更新的文档 + +```python +document.save(outfile) +``` + +#### 完整示例 + +```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) +``` + +## 小部件注释 + +### 添加导航按钮 + +在多页 PDF 中,导航按钮非常有用,当您希望读者在页面之间切换而无需使用查看器界面时。本示例添加了 `Previous Page` 和 `Next Page` 按钮到每页。 + +#### 定义按钮设置 + +将按钮标题、位置和预定义操作存储在一个简单的配置列表中。 + +```python +button_config = [ + ("Previous Page", 120.0, ap.annotations.PredefinedAction.PREV_PAGE), + ("Next Page", 230.0, ap.annotations.PredefinedAction.NEXT_PAGE), +] +``` + +#### 加载 PDF 并确保存在多个页面 + +该示例打开源文档并添加一页,以便导航操作至少有两个页面可供使用。 + +```python +document = ap.Document(infile) +document.pages.add() +``` + +#### 在每页上创建按钮 + +为每页创建一个 `ButtonField`,设置其文本和颜色,分配预定义的导航操作,并将其添加到表单。 + +```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) +``` + +#### 保存结果 + +```python +document.save(outfile) +``` + +#### 完整示例 + +```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) +``` + +### 添加打印按钮 + +此示例创建一个新的一页 PDF,并在页面顶部附近放置一个打印按钮。单击该按钮将在兼容的 PDF 查看器中触发预定义的打印操作。 + +#### 创建一个新的 PDF 并添加页面 + +```python +document = ap.Document() +page = document.pages.add() +``` + +#### 创建并配置按钮 + +定义按钮矩形,创建 `ButtonField`,设置其标题,并附加打印操作。 + +```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 +) +``` + +#### 设置边框和背景样式 + +该示例定义了实线边框并使用自定义颜色,使按钮在文档中可见。 + +```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() +``` + +#### 添加按钮并保存 PDF + +```python +document.form.add(print_button) +document.save(outfile) +``` + +#### 完整示例 + +```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) +``` + +## 相关主题 + +- [导入和导出注释](/python-net/import-export-annotations/) +- [标记注释](/python-net/markup-annotations/) +- [媒体注释](/python-net/media-annotations/) +- [安全注释](/python-net/security-annotations/) +- [形状注释](/python-net/shape-annotations/) +- [基于文本的注释](/python-net/text-based-annotations/) +- [水印注释](/python-net/watermark-annotations/) diff --git a/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/markup-annotations/_index.md b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/markup-annotations/_index.md new file mode 100644 index 0000000000..93f03a3e29 --- /dev/null +++ b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/markup-annotations/_index.md @@ -0,0 +1,499 @@ +--- +title: 使用 Python 的标记注释 +linktitle: 标记注释 +type: docs +weight: 30 +url: /zh/python-net/markup-annotations/ +description: 了解如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中添加、读取和删除文本、插入符号以及替换批注。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 在 PDF 文件中处理标记注释。 +Abstract: 本文介绍了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中创建、检查和删除标记注释。它涵盖了文本注释、插入符号注释和替换注释,并将每个工作流程拆分为小步骤和代码示例。 +--- + +本文展示了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中处理标记注释。 + +示例脚本演示了三种常见的注释工作流: + +- 注释式评论的文本批注 +- 用于插入标记的插入符号注释 +- 替换用于文本替换标记的注释 + +## 文本注释 + +### 添加文本注释 + +本示例在第一页创建一个文本注释,并将其链接到弹出窗口。文本注释在审阅工作流中用于便签式评论,十分有用。 + +#### 打开源 PDF + +```python +document = ap.Document(infile) +``` + +#### 创建并配置文本注释 + +定义注释矩形并设置其标题、主题、内容、显示标志、颜色和图标。 + +```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 +``` + +#### 创建弹出注释 + +创建一个弹出窗口并将其连接到文本注释。 + +```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 +``` + +#### 添加注释并保存 PDF + +```python +document.pages[1].annotations.add(text_annotation, consider_rotation=False) +document.save(outfile) +``` + +#### 完整示例 + +```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) +``` + +### 获取文本批注 + +要检查现有的文本注释,请在第一页过滤注释集合,仅保留类型为 `TEXT`. + +#### 加载文档并收集文本批注 + +```python +document = ap.Document(infile) +text_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.TEXT +] +``` + +#### 打印注释矩形 + +```python +for annotation in text_annotations: + print(annotation.rect) +``` + +#### 完整示例 + +```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) +``` + +### 删除文本注释 + +此工作流会删除第一页上的所有文本注释并保存修改后的 PDF。 + +#### 查找要删除的文本注释 + +```python +document = ap.Document(infile) +text_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.TEXT +] +``` + +#### 删除注释并保存文件 + +```python +for annotation in text_annotations: + document.pages[1].annotations.delete(annotation) + +document.save(outfile) +``` + +#### 完整示例 + +```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) +``` + +## 插入符号批注 + +### 添加插入符号批注 + +Caret 注释用于在审阅场景中标记插入点。此示例添加了一个带有附加弹出注释的 caret 注释。 + +#### 打开文档并获取目标页面 + +```python +document = ap.Document(infile) +page = document.pages[1] +``` + +#### 创建并配置插入符号注释 + +```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 +``` + +#### 附加弹出窗口并保存文档 + +```python +caret_annotation.popup = ap.annotations.PopupAnnotation( + page, ap.Rectangle(310, 713, 410, 730, True) +) +page.annotations.append(caret_annotation) + +document.save(outfile) +``` + +#### 完整示例 + +```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) +``` + +### 获取 Caret 注释 + +要检查插入符号注释,请遍历页面注释并按以下进行过滤 `CARET` 注释类型。 + +#### 加载文档和页面 + +```python +document = ap.Document(infile) +page = document.pages[1] +``` + +#### 打印插入符号注释矩形 + +```python +for annot in page.annotations: + if annot.annotation_type == ap.annotations.AnnotationType.CARET: + print(annot.rect) +``` + +#### 完整示例 + +```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) +``` + +### 删除插入符注释 + +此工作流首先收集插入符号批注,逐个删除它们,然后保存更新后的文件。 + +#### 加载文档并收集插入符号注释 + +```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 +] +``` + +#### 删除注释并保存文档 + +```python +for annot in caret_annotations: + page.annotations.delete(annot) + +document.save(outfile) +``` + +#### 完整示例 + +```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) +``` + +## 替换注释 + +### 添加 替换 注释 + +Replace 注释将插入符号注释和分组删除线注释结合在一起。此模式标记应被替换的文本,并将替换备注链接到已划掉的内容。 + +#### 打开文档并获取页面 + +```python +document = ap.Document(infile) +page = document.pages[1] +``` + +#### 为替换文本创建插入符号注释 + +```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) +) +``` + +#### 创建分组删除线注释 + +定义删除线区域,分配四点坐标,并通过将其链接到插入符号注释 `in_reply_to` 和 `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 +``` + +#### 添加两个注释并保存 PDF + +```python +page.annotations.append(caret_annotation) +page.annotations.append(strikeout_annotation) + +document.save(outfile) +``` + +#### 完整示例 + +```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) +``` + +### 获取替换注释 + +要识别 replace 注释,需要查找被分组为对另一个注释的回复的 strikeout 注释。示例在检查其关系字段之前,会先对每个 strikeout 注释进行类型转换。 + +#### 加载文档并遍历注释 + +```python +document = ap.Document(infile) +page = document.pages[1] +``` + +#### 过滤分组的删除线批注 + +```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}") +``` + +#### 完整示例 + +```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}") +``` + +### 删除 替换 注释 + +此工作流收集用于替换标记的划线批注,将其从页面中移除,并保存输出的 PDF。 + +#### 加载文档并收集替换批注 + +```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 +] +``` + +#### 删除注释并保存文档 + +```python +for annot in replace_annotations: + page.annotations.delete(annot) + +document.save(outfile) +``` + +#### 完整示例 + +```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/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md new file mode 100644 index 0000000000..56ac7e821a --- /dev/null +++ b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/media-annotations/_index.md @@ -0,0 +1,499 @@ +--- +title: PDF 中的媒体注释 +linktitle: 媒体注释 +type: docs +weight: 40 +url: /zh/python-net/media-annotations/ +description: 了解如何向 PDF 文档添加声音、3D、屏幕和富媒体注释,以及如何使用 Aspose.PDF for Python via .NET 检查或删除多媒体注释。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.5 +TechArticle: true +AlternativeHeadline: 在 Python 中处理多媒体和富媒体 PDF 注释。 +Abstract: 本文解释了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中创建和管理媒体注释。它涵盖了声音注释、3D 注释、屏幕注释、富媒体注释,以及列出或删除 PDF 页面中多媒体注释的技术。 +--- + +本文展示了如何在 PDF 文档中使用 Aspose.PDF for Python via .NET 处理媒体注释。 + +示例脚本演示了多个多媒体工作流: + +- 添加声音注释 +- 从 U3D 模型创建 3D 注释 +- 从媒体文件添加屏幕注释 +- 添加和删除富媒体注释 +- 检查现有的多媒体注释 + +## 添加声音注释 + +此示例向现有 PDF 的第一页添加声音注释,并将其链接到存储在输入目录中的 WAV 媒体文件。 + +### 打开 PDF 并定义媒体文件 + +```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") +``` + +### 创建并配置声音注释 + +设置注释矩形、颜色、标题和主题。然后添加弹出注释,以在选中注释时提供额外的详细信息。 + +```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), +) +``` + +### 添加注释并保存 PDF + +```python +page.annotations.append(sound_annotation) +document.save(outfile) +``` + +### 完整示例 + +```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) +``` + +## 添加 3D 注释 + +此工作流创建一个新的 PDF 并嵌入来自 U3D 文件的 3D 模型。它还为 3D 内容定义了预设视图和渲染设置。 + +### 创建 PDF 文档和 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") +``` + +### 定义 3D 视图矩阵 + +这些矩阵描述了如何从不同视点显示 3D 模型。 + +```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, +) +``` + +### 向艺术作品添加命名视图 + +```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() + +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) +``` + +### 完整示例 + +```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) +``` + +## 添加屏幕注释 + +屏幕批注允许您将可播放的媒体附加到 PDF 页面。本例创建一个新 PDF,并基于 SWF 文件添加屏幕批注。 + +### 创建 PDF 和页面 + +```python +media_file = infile + +document = ap.Document() +page = document.pages.add() +``` + +### 创建屏幕注释 + +```python +screen_annotation = ann.ScreenAnnotation( + page, + ap.Rectangle(170, 190, 470, 380, True), + media_file, +) +``` + +### 添加注释并保存 PDF + +```python +page.annotations.append(screen_annotation) +document.save(outfile) +``` + +### 完整示例 + +```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) +``` + +## 富媒体注释 + +### 添加富媒体注释 + +富媒体注释可以嵌入高级交互内容,例如带有海报、皮肤和自定义播放设置的视频播放器。 + +### 准备媒体和播放器资源 + +示例从预定义的位置加载视频、海报图像和播放器皮肤文件。 + +```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" +``` + +### 创建富媒体注释 + +```python +rich_media_annotation = ann.RichMediaAnnotation( + page, + ap.Rectangle(100, 500, 300, 600, True), +) +``` + +### 附加自定义播放器、皮肤、海报和视频 + +```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) +``` + +### 设置播放行为并保存 PDF + +该注释被配置为视频内容,并在用户点击时激活。 + +```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) +``` + +### 完整示例 + +```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) +``` + +### 删除富媒体注释 + +此工作流会从现有 PDF 的首页中移除所有富媒体注释。 + +### 打开 PDF 并收集富媒体注释 + +```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 +] +``` + +### 删除注释并保存文档 + +```python +for annotation in to_delete: + page.annotations.delete(annotation) + +document.save(outfile) +``` + +### 完整示例 + +```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) +``` + +## 获取 Multimedia_annotations + +要检查已存储在 PDF 中的多媒体内容,请筛选注释集合中的 screen、sound 和 rich media 注释类型。 + +### 打开文档并定义目标注释类型 + +```python +document = ap.Document(infile) + +target_types = { + ann.AnnotationType.SCREEN, + ann.AnnotationType.SOUND, + ann.AnnotationType.RICH_MEDIA, +} +``` + +### 打印多媒体注释矩形 + +```python +for annotation in document.pages[1].annotations: + if annotation.annotation_type in target_types: + print(f"{annotation.annotation_type} [{annotation.rect}]") +``` + +### 完整示例 + +```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}]") +``` + +## 相关主题 + +- [导入和导出注释](/python-net/import-export-annotations/) +- [交互式注释](/python-net/interactive-annotations/) +- [标记注释](/python-net/markup-annotations/) +- [安全注释](/python-net/security-annotations/) +- [形状注释](/python-net/shape-annotations/) +- [基于文本的注释](/python-net/text-based-annotations/) +- [水印注释](/python-net/watermark-annotations/) diff --git a/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/security-annotations/_index.md b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/security-annotations/_index.md new file mode 100644 index 0000000000..c5682190b0 --- /dev/null +++ b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/security-annotations/_index.md @@ -0,0 +1,218 @@ +--- +title: 使用 Python 的安全注释 +linktitle: 安全注释 +type: docs +weight: 75 +url: /zh/python-net/security-annotations/ +description: 了解如何使用 Aspose.PDF for Python via .NET 标记要进行编辑的文本、应用编辑注释,以及在 PDF 文件中编辑图像区域。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中使用安全注释对敏感 PDF 内容进行脱敏处理。 +Abstract: 本文解释了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中处理安全注释。它涵盖了使用脱敏注释标记匹配的文本、永久应用脱敏以及基于检测到的图像放置矩形对选定的图像区域进行脱敏。 +--- + +本文展示了如何在 PDF 文档中使用 Aspose.PDF for Python via .NET 的安全注释。 + +示例脚本演示了三种常见的编辑工作流: + +- 使用编辑注释标记文本片段 +- 永久应用现有的遮蔽注释 +- 在页面上遮蔽检测到的图像区域 + +## 标记文本涂黑 + +此工作流在文档中搜索匹配的文本,并在每个匹配项上放置编辑注释。它不会立即删除内容;仅标记文本以供以后进行编辑。 + +### 打开 PDF 并搜索目标文本 + +创建一个 `TextFragmentAbsorber` 针对搜索词,在扫描所有页面之前启用常规文本搜索选项。 + +```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) +``` + +### 为每个匹配项创建涂黑注释 + +对于每个匹配的文本片段,创建一个 `RedactionAnnotation` 使用片段矩形并配置其视觉外观。 + +```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) +``` + +### 保存标记的 PDF + +```python +document.save(outfile) +``` + +### 完整示例 + +```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) +``` + + + +## 应用遮蔽 + +在添加了编辑遮盖注释后,此工作流会在第一页永久应用它们。应用后,原始内容将从文档输出中删除。 + +### 加载 PDF 并收集编辑注释 + +```python +document = ap.Document(infile) +redaction_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.REDACTION +] +``` + +### 应用每个编辑注释 + +该示例检查每个注释都可以被视为 a `RedactionAnnotation` 调用之前 `redact()`. + +```python +for redaction_annotation in redaction_annotations: + if is_assignable(redaction_annotation, ap.annotations.RedactionAnnotation): + cast(ap.annotations.RedactionAnnotation, redaction_annotation).redact() +``` + +### 保存已遮蔽的 PDF + +```python +document.save(outfile) +``` + +### 完整示例 + +```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) +``` + + + +## 编辑区域 + +此示例对检测到的图像区域进行遮蔽,而不是对文本进行遮蔽。它扫描页面中的图像放置位置,选择一个放置矩形,并在该区域上添加遮蔽注释。 + +### 打开 PDF 并检测图像放置 + +使用 `ImagePlacementAbsorber` 在首页查找图像位置。 + +```python +document = ap.Document(infile) + +image_placement_absorber = ap.ImagePlacementAbsorber() +page = document.pages[1] +page.accept(image_placement_absorber) +``` + +### 为所选图像区域创建遮蔽注释 + +该示例使用检测到的第三个图像放置,并应用与文本标记示例中相同的遮蔽样式。 + +```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 +``` + +### 添加注释并保存 PDF + +```python +page.annotations.add(redaction_annotation, True) +document.save(outfile) +``` + +### 完整示例 + +```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) +``` + +## 相关主题 + +- [导入和导出注释](/python-net/import-export-annotations/) +- [交互式注释](/python-net/interactive-annotations/) +- [标记注释](/python-net/markup-annotations/) +- [媒体注释](/python-net/media-annotations/) +- [形状注释](/python-net/shape-annotations/) +- [基于文本的注释](/python-net/text-based-annotations/) +- [水印注释](/python-net/watermark-annotations/) diff --git a/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md new file mode 100644 index 0000000000..faa9d998bb --- /dev/null +++ b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/shape-annotations/_index.md @@ -0,0 +1,720 @@ +--- +title: 通过 Python 的形状注释 +linktitle: 形状注释 +type: docs +weight: 20 +url: /zh/python-net/shape-annotations/ +description: 了解如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中添加、检查和删除直线、正方形、圆形、多边形和折线注释。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.5 +TechArticle: true +AlternativeHeadline: 在 Python 中处理几何 PDF 注释。 +Abstract: 本文说明如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中创建、读取和删除形状注释。它涵盖线、正方形、圆形、多边形和折线注释,并将每个工作流拆分为小步骤并提供完整的代码示例。 +--- + +本文介绍了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中处理形状注释。 + +示例脚本演示了几种基于几何的注释工作流: + +- 线注释 +- 方形批注 +- 圆形批注 +- 多边形注释 +- 折线注释 + +## 线注释 + +### 添加线注释 + +此示例向首页添加线注释,并配置箭头样式、线宽和弹出窗口。 + +#### 打开源 PDF + +```python +document = ap.Document(infile) +``` + +#### 创建并配置线注释 + +```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 +``` + +#### 附加弹出窗口并保存 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) +``` + +#### 完整示例 + +```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) +``` + +### 获取线注释 + +要检查线注释,请筛选第一页的注释集合,并将每个结果转换为 `LineAnnotation` 这样您可以读取它的起始点和结束点。 + +#### 加载 PDF 并收集线注释 + +```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 +] +``` + +#### 打印线坐标 + +```python +for annotation in line_annotation: + print( + f"[{annotation.starting.x},{annotation.starting.y}]" + f"-[{annotation.ending.x},{annotation.ending.y}]" + ) +``` + +#### 完整示例 + +```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}]" + ) +``` + +### 删除线注释 + +此工作流会删除第一页上的所有线注释并保存更新后的 PDF。 + +#### 查找要删除的线注释 + +```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 +] +``` + +#### 删除注释并保存 PDF + +```python +for annotation in line_annotations: + page.annotations.delete(annotation) + +document.save(outfile) +``` + +#### 完整示例 + +```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) +``` + + +## 方形和圆形批注 + +### 添加方形注释 + +方形批注对于在文档中标记矩形区域很有用。此示例创建了一个带有边框、填充和透明度设置的方形批注。 + +#### 打开 PDF 并创建方形注释 + +```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 +``` + +#### 添加注释并保存 PDF + +```python +document.pages[1].annotations.append(square_annotation) +document.save(outfile) +``` + +#### 完整示例 + +```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) +``` + +### 获取方形注释 + +要检查方形注释,请过滤第一页的注释: `SQUARE` 键入并打印每个矩形。 + +#### 加载文档并收集方形批注 + +```python +document = ap.Document(infile) +square_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.SQUARE +] +``` + +#### 打印注释矩形 + +```python +for annotation in square_annotations: + print(annotation.rect) +``` + +#### 完整示例 + +```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) +``` + +### 删除方形注释 + +此工作流会从第一页删除所有方形注释并保存文档。 + +#### 查找并删除方形批注 + +```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) +``` + +#### 完整示例 + +```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) +``` + +### 添加圆形注释 + +圆形批注标记 PDF 中的圆形区域。此示例添加了一个带有填充颜色、不透明度和弹出批注的圆形批注。 + +#### 打开 PDF 并创建圆形注释 + +```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 +``` + +#### 附加弹出窗口并保存 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) +``` + +#### 完整示例 + +```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) +``` + +### 获取圆形注释 + +要检查圆形注释,请按以下方式过滤页面注释 `CIRCLE` 键入并打印它们的矩形。 + +#### 加载文档并收集圆形注释 + +```python +document = ap.Document(infile) +circle_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.CIRCLE +] +``` + +#### 打印注释矩形 + +```python +for annotation in circle_annotations: + print(annotation.rect) +``` + +#### 完整示例 + +```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) +``` + +### 删除圆形注释 + +此工作流会从首页移除所有圆形批注,并保存输出的 PDF。 + +#### 查找并删除圆形注释 + +```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) +``` + +#### 完整示例 + +```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) +``` + + +## 多边形和折线注释 + +### 添加多边形批注 + +多边形注释定义了一个封闭的多点形状。此示例从矩形和点列表创建多边形注释。 + +#### 打开 PDF 并创建多边形注释 + +```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 +``` + +#### 添加注释并保存 PDF + +```python +document.pages[1].annotations.append(polygon_annotation) +document.save(outfile) +``` + +#### 完整示例 + +```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) +``` + +### 获取多边形注释 + +要检查多边形注释,请通过以下方式筛选第一页的注释 `POLYGON` 键入并打印每个注释矩形。 + +#### 加载文档并收集多边形注释 + +```python +document = ap.Document(infile) +polygon_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.POLYGON +] +``` + +#### 打印注释矩形 + +```python +for annotation in polygon_annotations: + print(annotation.rect) +``` + +#### 完整示例 + +```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) +``` + +### 删除多边形注释 + +此工作流会从第一页移除所有多边形批注并保存更新后的 PDF。 + +#### 查找并删除多边形注释 + +```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) +``` + +#### 完整示例 + +```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) +``` + +### 添加折线注释 + +折线批注通过多个点定义一条开放路径。此示例创建了一个带有弹出注释的折线批注。 + +#### 打开 PDF 并创建折线注释 + +```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 +``` + +#### 附加弹出窗口并保存 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) +``` + +#### 完整示例 + +```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) +``` + +### 获取折线注释 + +要检查折线注释,请通过以下方式过滤页面注释: `POLY_LINE` 键入并打印它们的矩形。 + +#### 加载文档并收集折线注释 + +```python +document = ap.Document(infile) +polyline_annotations = [ + annotation + for annotation in document.pages[1].annotations + if annotation.annotation_type == ap.annotations.AnnotationType.POLY_LINE +] +``` + +#### 打印注释矩形 + +```python +for annotation in polyline_annotations: + print(annotation.rect) +``` + +#### 完整示例 + +```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) +``` + +### 删除折线注释 + +此工作流从首页删除所有折线注释并保存输出 PDF。 + +#### 查找并删除折线批注 + +```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) +``` + +#### 完整示例 + +```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) +``` + +## 相关主题 + +- [导入和导出注释](/python-net/import-export-annotations/) +- [交互式注释](/python-net/interactive-annotations/) +- [标记注释](/python-net/markup-annotations/) +- [媒体注释](/python-net/media-annotations/) +- [安全注释](/python-net/security-annotations/) +- [基于文本的注释](/python-net/text-based-annotations/) +- [水印注释](/python-net/watermark-annotations/) diff --git a/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/sticks/_index.md b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/sticks/_index.md deleted file mode 100644 index fc50c2e8c6..0000000000 --- a/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/sticks/_index.md +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: PDF 粘性注释使用 Python -linktitle: 粘性注释 -type: docs -weight: 50 -url: /zh/python-net/sticky-annotations/ -description: 本主题关于粘性注释,作为示例,我们展示文本中的水印注释。 -lastmod: "2023-02-17" -sitemap: - changefreq: "weekly" - priority: 0.7 ---- - - - -## 添加水印注释 - -最明显且易于可视化和传递的是水印注释。这是将标志或任何其他确认其原创性的标志放置在 PDF 文档中的最佳方式。 - -水印注释应用于表示将在页面上以固定大小和位置打印的图形,而不考虑打印页面的尺寸。 - -您可以使用 [WatermarkAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/watermarkannotation/) 在 PDF 页面的特定位置添加水印文本。还可以使用 [opacity](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/watermarkannotation/#properties) 属性控制水印的透明度。 - -请查看以下代码片段以添加 WatermarkAnnotation。 - -```python - - import aspose.pdf as ap - - document = ap.Document(input_file) - # 创建注释 - # 加载 Page 对象以添加注释 - page = document.pages[1] - - # 创建注释 - wa = ap.annotations.WatermarkAnnotation(page, ap.Rectangle(100, 0, 400, 100, True)) - - # 将注释添加到页面的注释集合中 - page.annotations.append(wa) - - # 创建用于字体设置的 TextState - ts = ap.text.TextState() - ts.foreground_color = ap.Color.blue - ts.font_size = 25 - ts.font = ap.text.FontRepository.find_font("Arial"); - - # 设置注释文本的透明度级别 - wa.opacity = 0.5 - - # 在注释中添加文本 - wa.set_text_and_state([ "HELLO", "Line 1", "Line 2" ], ts) - - document.save(output_file) -``` - - -## 获取水印注释 - -```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) -``` - -## 删除水印注释 - -```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/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text-based-annotations/_index.md b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text-based-annotations/_index.md new file mode 100644 index 0000000000..ceac85c656 --- /dev/null +++ b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text-based-annotations/_index.md @@ -0,0 +1,749 @@ +--- +title: 使用 Python 的基于文本的注释 +linktitle: 文本注释 +type: docs +weight: 10 +url: /zh/python-net/text-based-annotations/ +description: 了解如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中添加、检查和删除自由文本、高亮、下划线、波浪线和删除线注释。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中处理文本和文本标记的 PDF 注释。 +Abstract: 本文说明了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中创建、读取和删除基于文本的注释。它涵盖了自由文本注释和文本标记注释,例如高亮、下划线、波浪线和删除线,并包括诸如扁平化、四点坐标和提取标记文本等高级下划线工作流。 +--- + +本文展示了如何在 PDF 文档中使用 Aspose.PDF for Python via .NET 处理基于文本的批注。 + +示例脚本演示了多个文本批注工作流: + +- 自由文本注释 +- 高亮注释 +- 下划线注释 +- 波浪线批注 +- 删除线批注 + +## 自由文本注释 + +### 添加自由文本批注 + +自由文本注释允许您直接在 PDF 页面上放置可见的文字评论。本示例向首页添加了一个简单的自由文本注释。 + +#### 打开源 PDF + +```python +document = ap.Document(infile) +``` + +#### 创建并配置自由文本注释 + +```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 +``` + +#### 添加注释并保存 PDF + +```python +document.pages[1].annotations.append(free_text_annotation) +document.save(outfile) +``` + +#### 完整示例 + +```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) +``` + +### 获取自由文本批注 + +要检查自由文本注释,请按以下方式过滤第一页注释 `FREE_TEXT` 键入并打印每个注释矩形。 + +#### 加载文档并收集自由文本批注 + +```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 +] +``` + +#### 打印注释矩形 + +```python +for annotation in free_text_annotations: + print(annotation.rect) +``` + +#### 完整示例 + +```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) +``` + +### 删除自由文本注释 + +此工作流从第一页中移除所有自由文本批注,并保存更新后的 PDF。 + +#### 查找并删除自由文本注释 + +```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) +``` + +#### 完整示例 + +```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) +``` + + +## 文本标记注释 + +### 高亮批注 + +#### 添加文本高亮 + +高亮注释在不更改底层内容的情况下强调文档的部分内容。此示例向首页添加了一个高亮注释。 + +```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) +``` + +#### 获取文本高亮 + +要检查高亮注释,请按以下方式过滤页面注释 `HIGHLIGHT` 键入并打印它们的矩形。 + +```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) +``` + +#### 删除文本高亮 + +此工作流会从第一页中移除所有高亮批注,并保存输出的 PDF。 + +```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) +``` + + +### 下划线注释 + +#### 添加文本下划线批注 + +下划线注释使用可见的下划线标记文本。此示例添加了一个基本的下划线注释,并设置了其元数据和颜色。 + +```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) +``` + +#### 添加文本下划线批注并展平 + +如果您希望下划线成为页面内容的一部分,而不是保持为交互式注释,您可以在添加后将其扁平化。 + +```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) +``` + +#### 使用四点添加文本下划线注释 + +四点坐标让您能够为下划线注释定义精确的标记区域。当您需要比简单矩形更精细的控制时,这非常有用。 + +```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) +``` + +#### 删除文本下划线注释 + +此工作流会删除首页上的所有下划线注释,并保存更新后的文档。 + +```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) +``` + +#### 按标题删除文本下划线注释 + +此工作流展示了在检查其标题后,如何有选择地删除下划线注释。 + +```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) +``` + +#### 获取文本下划线注释 + +要检查下划线注释,请按以下方式过滤第一页的注释 `UNDERLINE` 键入并打印每个矩形。 + +```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) +``` + +#### 获取带下划线注释标记的文本 + +此工作流将每个下划线批注转换为 `UnderlineAnnotation` 对象并提取标记的文本。 + +```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()}") +``` + +#### 获取已标记片段的文本下划线注释 + +如果您需要单独获取每个标记的片段,可以遍历返回的集合 `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}") +``` + + +### 波浪线注释 + +#### 添加波浪线批注 + +波浪线批注常用于标记文本中的拼写、语法或需要注意的区域。此示例在首页添加了波浪线批注。 + +```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) +``` + +#### 获取波浪线批注 + +要检查波浪线注释,请通过以下方式过滤页面注释 `SQUIGGLY` 键入并打印它们的矩形。 + +```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) +``` + +#### 删除波浪线批注 + +此工作流会从首页移除所有波浪线批注并保存结果。 + +```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) +``` + + +### 删除线注释 + +#### 添加文本删除线批注 + +删除线注释标记应视为已删除或划掉的文本。此示例添加了一个删除线注释,并设置其元数据和颜色。 + +```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) +``` + +#### 获取文本删除线批注 + +要检查删除线注释,请通过 `STRIKE_OUT` 键入并打印它们的矩形。 + +```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) +``` + +#### 删除文本删除线注释 + +此工作流会从首页删除所有删线批注并保存更新后的文档。 + +```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) +``` + +## 相关主题 + +- [导入和导出注释](/python-net/import-export-annotations/) +- [交互式注释](/python-net/interactive-annotations/) +- [标记注释](/python-net/markup-annotations/) +- [媒体注释](/python-net/media-annotations/) +- [安全注释](/python-net/security-annotations/) +- [形状注释](/python-net/shape-annotations/) +- [水印注释](/python-net/watermark-annotations/) diff --git a/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text/_index.md b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text/_index.md deleted file mode 100644 index df6430a911..0000000000 --- a/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/text/_index.md +++ /dev/null @@ -1,335 +0,0 @@ ---- -title: 使用文本注释处理PDF通过Python -linktitle: 文本注释 -type: docs -weight: 10 -url: /zh/python-net/text-annotation/ -description: Aspose.PDF for Python 允许您从PDF文档中添加、获取和删除文本注释。 -lastmod: "2023-02-17" -sitemap: - changefreq: "monthly" - priority: 0.5 ---- - - - -## 如何将文本注释添加到现有的 PDF 文件中 - -文本注释是附加在 PDF 文档特定位置的注释。关闭时,注释显示为图标;打开时,它应显示一个弹出窗口,其中包含读者选择的字体和大小的注释文本。 - -注释由特定页面的 [Annotations](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/annotationcollection/) 集合包含。此集合仅包含该单独页面的注释;每个页面都有其自己的注释集合。 - -要向特定页面添加注释,请使用 [add()](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/annotationcollection/#methods) 方法将其添加到该页面的注释集合中。 - -1. 首先,创建要添加到 PDF 的注释。 -1. 然后打开输入的 PDF。 - -1. 将注释添加到“页面”对象的[Annotations](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/annotationcollection/)集合中。 - -以下代码片段演示了如何在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 = "Aspose User" - textAnnotation.subject = "Inserted text 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) -``` - -## 从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) -``` - - -## 从 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) -``` - -## 如何添加(或创建)新的自由文本注释 - -自由文本注释直接在页面上显示文本。[FreeTextAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/freetextannotation/) 类允许创建此类型的注释。在以下代码片段中,我们在字符串首次出现的位置上方添加自由文本注释。 - -```python - - import aspose.pdf as ap - - # 加载 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) -``` - - -## 从 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) -``` - -## 从 PDF 文件删除自由文本注释 - -```python - - import aspose.pdf as ap - - # 加载 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) -``` - -### 使用 StrikeOutAnnotation 删除文字 - -Aspose.PDF for Python 允许您在 PDF 文档中添加、删除和更新注释。 - 一种类允许您划掉注释。当在 PDF 中应用 StrikeOutAnnotation 时,会在指定文本上画一条线,以指示该文本应被删除或忽略。 - -以下代码片段展示了如何向 PDF 添加 [StrikeOutAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/strikeoutannotation/)。 - -```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 = "Aspose 用户" - strikeoutAnnotation.subject = "插入的文本 1" - strikeoutAnnotation.flags = ap.annotations.AnnotationFlags.PRINT - strikeoutAnnotation.color = ap.Color.blue - - document.pages[1].annotations.append(strikeoutAnnotation) - document.save(output_file) -``` - - -## 从 PDF 获取 StrikeOutAnnotation - -```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) -``` - -## 从 PDF 中删除 StrikeOutAnnotation - -```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/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/watermark-annotations/_index.md b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/watermark-annotations/_index.md new file mode 100644 index 0000000000..a34ef19cd6 --- /dev/null +++ b/zh/python-net/advanced-operations/annotations/add-delete-and-get-annotation/watermark-annotations/_index.md @@ -0,0 +1,186 @@ +--- +title: 使用 Python 的水印注释 +linktitle: 水印注释 +type: docs +weight: 70 +url: /zh/python-net/watermark-annotations/ +description: 了解如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中添加、检查和删除水印注释。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 处理 PDF 文件中的水印批注。 +Abstract: 本文说明了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中创建、读取和删除水印批注。它涵盖了添加带自定义文字状态和不透明度的文字水印批注、检查已有的水印批注,以及从 PDF 页面删除水印批注。 +--- + +本文展示了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中处理水印批注。 + +示例脚本演示了三种常见的工作流程: + +- 添加水印注释 +- 获取水印注释矩形 +- 删除水印注释 + +## 添加水印注释 + +此示例在 PDF 文档的首页添加水印注释。水印使用文本状态来控制字体设置,并应用自定义不透明度以实现半透明外观。 + +### 打开 PDF 并获取目标页面 + +```python +document = ap.Document(infile) +page = document.pages[1] +``` + +### 创建水印注释 + +定义注释矩形并将其追加到页面注释集合中。 + +```python +watermark_annotation = ap.annotations.WatermarkAnnotation( + page, + ap.Rectangle(100, 100, 400, 200, True), +) + +page.annotations.append(watermark_annotation) +``` + +### 配置文本外观 + +创建一个 `TextState` 用于控制文本颜色、字体大小和字体族的对象。 + +```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") +``` + +### 设置不透明度和水印文本 + +示例使用 50% 不透明度,并将三行文本写入水印批注。 + +```python +watermark_annotation.opacity = 0.5 +watermark_annotation.set_text_and_state(["HELLO", "Line 1", "Line 2"], text_state) +``` + +### 保存 PDF + +```python +document.save(outfile) +``` + +### 完整示例 + +```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) +``` + +## 获取水印注释 + +要检查现有的水印注释,请通过以下方式过滤第一页的注释 `WATERMARK` 键入并打印它们的矩形。 + +### 加载文档并收集水印注释 + +```python +document = ap.Document(infile) +watermark_annotations = [ + a + for a in document.pages[1].annotations + if a.annotation_type == ap.annotations.AnnotationType.WATERMARK +] +``` + +### 打印注释矩形 + +```python +for watermark_annotation in watermark_annotations: + print(watermark_annotation.rect) +``` + +### 完整示例 + +```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) +``` + +## 删除水印批注 + +此工作流会从第一页删除所有水印注释并保存更新后的 PDF。 + +### 查找要删除的水印批注 + +```python +document = ap.Document(infile) +watermark_annotations = [ + a + for a in document.pages[1].annotations + if a.annotation_type == ap.annotations.AnnotationType.WATERMARK +] +``` + +### 删除注释并保存 PDF + +```python +for watermark_annotation in watermark_annotations: + document.pages[1].annotations.delete(watermark_annotation) + +document.save(outfile) +``` + +### 完整示例 + +```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) +``` + +## 相关主题 + +- [导入和导出注释](/python-net/import-export-annotations/) +- [交互式注释](/python-net/interactive-annotations/) +- [标记注释](/python-net/markup-annotations/) +- [媒体注释](/python-net/media-annotations/) +- [安全注释](/python-net/security-annotations/) +- [形状注释](/python-net/shape-annotations/) +- [基于文本的注释](/python-net/text-based-annotations/) diff --git a/zh/python-net/advanced-operations/annotations/import-export-annotations/_index.md b/zh/python-net/advanced-operations/annotations/import-export-annotations/_index.md new file mode 100644 index 0000000000..ba17e7a9ee --- /dev/null +++ b/zh/python-net/advanced-operations/annotations/import-export-annotations/_index.md @@ -0,0 +1,102 @@ +--- +title: 使用 Python 导入和导出批注 +linktitle: 导入和导出注释 +type: docs +weight: 80 +url: /zh/python-net/import-export-annotations/ +description: 了解如何使用 Aspose.PDF for Python via .NET 从一个 PDF 导入批注并将其导出到新 PDF 文档中。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中传输 PDF 注释。 +Abstract: 本文介绍了如何使用 Aspose.PDF for Python via .NET 将注释从源 PDF 复制并导出到新的 PDF 文档。该演练将过程拆分为多个小步骤,包括加载源文件、创建目标文档、添加页面、从第一页复制注释以及保存结果。 +--- + +本文展示了如何使用 Aspose.PDF for Python via .NET 从现有 PDF 导入批注并将其导出到新 PDF 文档。 + +此示例从源文件的第一页读取注释,创建一个新 PDF,添加一个空白页,并将每个注释复制到该新页。此方法在需要将评论、标记或审阅笔记移至单独的输出文档时非常有用。 + +## 加载源 PDF + +创建一个 `Document` 对象用于已经包含批注的输入文件。该对象提供对页面集合的访问以及每个页面上存储的批注。 + +```python +source_document = ap.Document(infile) +``` + +## 创建目标 PDF + +接下来,创建一个空的 PDF 文档,用于接收导入的批注。此时,目标文档不包含任何页面。 + +```python +destination_document = ap.Document() +``` + +## 添加一个用于导出注释的页面 + +因为注释必须属于页面,在复制任何内容之前,请向目标文档添加一个新页面。 + +```python +page = destination_document.pages.add() +``` + +## 复制源页面的注释 + +遍历源 PDF 第一页的注释集合,并将每个注释添加到目标文档的新页面中。 + +第二个参数在 `page.annotations.add(annot, True)` 告诉 Aspose.PDF 将批注复制到目标页面,而不是仅仅复用现有的对象引用。 + +```python +for annot in source_document.pages[1].annotations: + page.annotations.add(annot, True) +``` + +## 保存输出文档 + +在所有批注复制完成后,保存目标文档以生成最终的 PDF 文件。 + +```python +destination_document.save(outfile) +``` + +## 完整示例 + +以下代码将所有步骤合并为一个可重用的函数: + +```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) +``` + +## 相关主题 + +- [交互式注释](/python-net/interactive-annotations/) +- [标记注释](/python-net/markup-annotations/) +- [媒体注释](/python-net/media-annotations/) +- [安全注释](/python-net/security-annotations/) +- [形状注释](/python-net/shape-annotations/) +- [基于文本的注释](/python-net/text-based-annotations/) +- [水印注释](/python-net/watermark-annotations/) diff --git a/zh/python-net/advanced-operations/artifacts/_index.md b/zh/python-net/advanced-operations/artifacts/_index.md new file mode 100644 index 0000000000..8fadc778d4 --- /dev/null +++ b/zh/python-net/advanced-operations/artifacts/_index.md @@ -0,0 +1,67 @@ +--- +title: 在 Python 中使用 PDF 工件 +linktitle: 使用工件 +type: docs +weight: 170 +url: /zh/python-net/artifacts/ +description: 了解如何在 Python 中使用 PDF 工件来添加背景、浮水印和 Bates 编号,并使用 Aspose.PDF for Python via .NET 对工件类型进行计数。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中添加背景、浮水印和 Bates 编号工件 +Abstract: 本文阐述了如何在 Aspose.PDF for Python via .NET 中使用 PDF 工件。了解工件是什么、它们为何对可访问性和文档布局重要,以及如何在 PDF 文件中使用 Python 添加背景图像、应用浮水印、添加 Bates 编号并检查工件类型。 +--- + +PDF 中的工件是图形对象或其他不属于文档实际内容的元素。它们通常用于装饰、布局或背景目的。工件的例子包括页面页眉、页脚、分隔线或不传达任何意义的图像。 + +PDF 中的 artifact 旨在区分内容元素和非内容元素。这对可访问性很重要,因为屏幕阅读器和其他辅助技术可以忽略 artifact 并专注于相关内容。artifact 还可以提升 PDF 文档的性能和质量,因为它们可以在打印、搜索或复制时被省略。 + +当您需要在 Python 中创建或检查非内容 PDF 元素(如文档背景、页面水印和 Bates 编号标记)时,请使用本节。以下指南展示了 Aspose.PDF for Python via .NET 支持的主要 artifact 工作流。 + +要在 PDF 中将元素创建为 artifact,您需要使用 [Artifact](https://reference.aspose.com/pdf/python-net/aspose.pdf/artifact/) 类。 +它包含以下有用属性: + +- **custom_type** - 获取工件类型的名称。若工件类型为非标准类型,可使用此属性。 +- **custom_subtype** - 获取工件子类型的名称。若工件子类型不是标准子类型,可使用此属性。 +- **type** - 获取工件类型。 +- **subtype** - 获取工件子类型。如果工件拥有非标准子类型,可通过 CustomSubtype 读取子类型名称。 +- **contents** - 获取工件内部运算符的集合。 +- **form** - 获取工件的 XForm(如果使用了 XForm)。 +- **rectangle** - 获取工件的矩形。 +- **position** - 获取或设置工件的位置。如果指定了此属性,则会忽略边距和对齐方式。 +- **right_margin** - 工件的右边距。如果在 Position 属性中显式指定了位置,则此值将被忽略。 +- **left_margin** - 工件的左边距。如果在 Position 属性中显式指定了位置,则此值将被忽略。 +- **top_margin** - 工件的上边距。如果在 Position 属性中显式指定了位置,则此值将被忽略。 +- **bottom_margin** - 工件的下边距。如果在 Position 属性中显式指定了位置,则此值将被忽略。 +- **artifact_horizontal_alignment** - 构件的水平对齐方式。如果在 Position 属性中显式指定了位置,则此值被忽略。 +- **artifact_vertical_alignment** - 构件的垂直对齐方式。如果在 Position 属性中显式指定了位置,则此值被忽略。 +- **rotation** - 获取或设置构件的旋转角度。 +- **text** - 获取构件的文本。 +- **image** - 获取构件的图像(如果存在)。 +- **opacity** - 获取或设置构件的不透明度。可能的取值范围为 0..1。 +- **lines** - 多行文本工件的行。 +- **text_state** - 工件文本的文本状态。 +- **is_background** - 如果为 true,工件将放置在页面内容之后。 + +以下类在处理工件时可能也很有用: + +- [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/) +- [页脚工件](https://reference.aspose.com/pdf/python-net/aspose.pdf/footerartifact/) +- [水印工件](https://reference.aspose.com/pdf/python-net/aspose.pdf/watermarkartifact/) +- [BatesN工件](https://reference.aspose.com/pdf/python-net/aspose.pdf/batesnartifact/) + +## 本节涵盖的工件工作流 + +请查看文章的以下章节: + +- [添加背景](/pdf/zh/python-net/add-backgrounds/) - 使用 Python 向 PDF 文件添加背景图像。 +- [添加贝茨编号](/pdf/zh/python-net/add-bates-numbering/) - 为 PDF 添加贝茨编号。 +- [添加水印](/pdf/zh/python-net/add-watermarks/) - 如何使用 Python 为 PDF 添加水印。 +- [统计工件](/pdf/zh/python-net/counting-artifacts/) - 使用 Python 统计 PDF 中的伪影。 +- [管理 PDF 页眉和页脚](/pdf/zh/python-net/artifacts-header-footer/) - 管理 PDF 文档的页眉和页脚。 + +- 当您需要在不更改主文档内容流的情况下管理装饰性或结构性 PDF 元素时,这些教程非常有用。 diff --git a/zh/python-net/advanced-operations/artifacts/add-backgrounds/_index.md b/zh/python-net/advanced-operations/artifacts/add-backgrounds/_index.md new file mode 100644 index 0000000000..9bac96fe41 --- /dev/null +++ b/zh/python-net/advanced-operations/artifacts/add-backgrounds/_index.md @@ -0,0 +1,148 @@ +--- +title: 在 Python 中添加 PDF 背景 +linktitle: 添加背景 +type: docs +weight: 20 +url: /zh/python-net/add-backgrounds/ +description: 了解如何在 Python 中使用 Aspose.PDF for Python via .NET 的 BackgroundArtifact 类向 PDF 页面添加背景图像。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 为 PDF 添加背景 +Abstract: 本文讨论了在 PDF 文档中使用 Aspose.PDF for Python via .NET 添加背景图像的用法。它强调了通过利用 `BackgroundArtifact` 类,可向文档添加水印或细微设计的能力,该类允许将背景图像合并到各个页面对象中。文章提供了一个实用的代码示例,演示如何实现此功能。过程包括创建一个新的 PDF 文档、添加页面、创建 `BackgroundArtifact` 对象、设置背景图像,并将该背景工件追加到页面的 artifacts 集合中。最后,将修改后的文档保存为 PDF 文件。此技术可提升 PDF 文档的视觉呈现效果。 +--- + +## 向 PDF 添加背景图像 + +背景图像可用于在文档中添加水印或其他细微的设计。在 Aspose.PDF for Python via .NET 中,每个 PDF 文档都是页面的集合,每个页面包含一组工件。该 [BackgroundArtifact](https://reference.aspose.com/pdf/python-net/aspose.pdf/backgroundartifact/) 类可用于向页面对象添加背景图像。 + +当您需要在主 PDF 内容后面放置装饰性图像,而不将其转换为可搜索的文本文档时,此方法非常有用。 + +以下代码片段展示了如何使用 BackgroundArtifact 对象在 Python 中向 PDF 页面添加背景图像。 + +1. 加载 PDF 文档。 +1. 创建背景 artifact。 +1. 加载图像文件。 +1. 将工件附加到页面。 +1. 保存更新后的文档。 + +```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) +``` + +## 向 PDF 添加带透明度的背景图像 + +使用 Aspose.PDF for Python 向 PDF 页面添加半透明背景图像。 + +通过应用不透明度,背景图像会变得部分透明,使原始页面内容(文字、图像等)仍然清晰可见。这在以下情况下尤其有用: + +- 水印 +- 品牌覆盖层 +- 细微的设计增强 + +背景作为工件添加,确保它位于所有页面内容的后面。 + +1. 加载 PDF 文档。 +1. 创建背景 artifact。 +1. 加载图像文件。 +1. 设置不透明度级别。 +1. 将工件附加到页面。 +1. 保存更新后的文档。 + +```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) +``` + +## 为 PDF 添加背景颜色 + +使用 Aspose.PDF for Python 为 PDF 页面应用纯色背景。 + +1. 加载 PDF 文档。 +1. 创建背景 artifact。 +1. 设置背景颜色。 +1. 将工件附加到页面。 +1. 保存更新后的文档。 + +```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) +``` + +## 从 PDF 中移除背景 + +使用 Aspose.PDF for Python 从 PDF 页面中移除背景伪影。 +PDF 中的背景通常以伪影形式存储,此方法会选择性地识别并仅移除被分类为背景元素的伪影。 + +1. 加载 PDF 文档。 +1. 访问页面伪影。 +1. 过滤背景伪影。 +1. 收集背景元素。 +1. 删除背景伪影。 +1. 保存更新后的文档。 + +```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) +``` + +## 相关工件主题 + +- [在 Python 中使用 PDF 工件](/pdf/zh/python-net/artifacts/) +- [在 Python 中为 PDF 添加水印](/pdf/zh/python-net/add-watermarks/) +- [在 Python 中为 PDF 添加 Bates 编号](/pdf/zh/python-net/add-bates-numbering/) +- [统计 PDF 文件中的工件类型](/pdf/zh/python-net/counting-artifacts/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md b/zh/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md new file mode 100644 index 0000000000..9ef3b67408 --- /dev/null +++ b/zh/python-net/advanced-operations/artifacts/add-bates-numbering/_index.md @@ -0,0 +1,120 @@ +--- +title: 在 Python 中为 PDF 添加贝茨编号 +linktitle: 添加贝茨编号 +type: docs +weight: 10 +url: /zh/python-net/add-bates-numbering/ +description: 了解如何使用 Python 通过 Aspose.PDF for Python via .NET 在 PDF 文档中添加和删除贝茨编号。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 通过 Python 添加贝茨编号 +Abstract: Bates numbering 是法律、医疗和商业文档工作流中的关键功能,确保一组中的每页都获得唯一的、顺序的标识符,以便可靠引用。本文演示了 Aspose.PDF for Python via .NET 如何通过其灵活的 API 简化 Bates 编号的自动化。使用 BatesNArtifact 类,开发者可以配置编号行为——包括数字位数、前缀、后缀、对齐方式和页边距——并在整个文档中以编程方式应用。本文提供了多种方法,从直接应用工件到基于委托的配置,提供静态和动态两种控制方式。此外,API 支持通过一次方法调用即可完整移除 Bates 编号,实现分页工件的全生命周期管理。清晰的分步代码示例展示了如何添加、定制和删除 Bates 编号,使本指南成为希望简化文档处理工作流的开发者的实用资源。 +--- + +Bates 编号广泛用于法律、医疗和商务工作流中,为文档集中的页面分配唯一的、顺序的标识符。Aspose.PDF for Python via .NET 提供了简洁且灵活的 API 来自动化此过程,使您能够以编程方式在任何 PDF 上应用标准化的 Bates 编号。 + +使用 [`BatesNArtifact`](https://reference.aspose.com/pdf/python-net/aspose.pdf/batesnartifact/) 类,开发者可以完全自定义编号行为——包括起始号码、位数、前缀和后缀、对齐方式以及边距。配置完成后,artifact 可以应用于 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 通过 `add_bates_numbering` 方法 在 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 或作为列表的一部分添加 [`PaginationArtifact`](https://reference.aspose.com/pdf/python-net/aspose.pdf/paginationartifact/) objects. Aspose.PDF 也支持基于委托的配置风格,允许在运行时动态控制工件设置。 + +除了创建 Bates 编号之外,API 还提供了一种简便的方法来删除它们 `delete_bates_numbering`,在文档处理工作流中提供完全的灵活性。 + +本文展示了使用 Aspose.PDF for Python via .NET 在 PDF 中添加和删除 Bates 编号的多种方法,并提供了关于工件配置、应用和移除的清晰示例。 + +## 添加 Bates 编号工件 + +此示例演示如何使用 Aspose.PDF for Python via .NET 以编程方式向 PDF 文档添加 Bates 编号。通过配置一个 [`BatesNArtifact`](https://reference.aspose.com/pdf/python-net/aspose.pdf/batesnartifact/) 使用所需的设置并将其应用于文档的页面,您可以实现自动化,为每页添加标准化标识符的过程。 + +要向一个 Bates 编号工件添加 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/),调用 `AddBatesNumbering(BatesNArtifact)` 扩展方法 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/),传入一个 [`BatesNArtifact`](https://reference.aspose.com/pdf/python-net/aspose.pdf/batesnartifact/) 实例作为参数: + +```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) +``` + +## 使用分页工件添加贝茨编号 + +使用 Aspose.PDF for Python 中的分页工件集合为 PDF 添加贝茨编号: + +1. 加载 PDF 文档。 +1. 在应用页码之前,如有需要插入额外的页面。 +1. 创建一个 Bates 工件。 +1. 配置工件属性。 +1. 将该工件添加到分页集合中。 +1. 对页面应用分页。 +1. 保存更新后的文档。 + +```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) +``` + +## 删除 Bates 编号 + +要从 a 中删除 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/): + +```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) +``` + +## 相关工件主题 + +- [在 Python 中使用 PDF 工件](/pdf/zh/python-net/artifacts/) +- [在 Python 中为 PDF 添加水印](/pdf/zh/python-net/add-watermarks/) +- [在 Python 中添加 PDF 背景](/pdf/zh/python-net/add-backgrounds/) +- [统计 PDF 文件中的工件类型](/pdf/zh/python-net/counting-artifacts/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/artifacts/add-watermarks/_index.md b/zh/python-net/advanced-operations/artifacts/add-watermarks/_index.md new file mode 100644 index 0000000000..dc348a9f5d --- /dev/null +++ b/zh/python-net/advanced-operations/artifacts/add-watermarks/_index.md @@ -0,0 +1,120 @@ +--- +title: 在 Python 中为 PDF 添加水印 +linktitle: 添加水印 +type: docs +weight: 30 +url: /zh/python-net/add-watermarks/ +description: 了解如何使用 Aspose.PDF for Python via .NET 在 Python 中向 PDF 文件添加水印。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 向 PDF 添加水印 +Abstract: 本文讨论了使用 Aspose.PDF for Python via .NET 通过管理 artifacts 为 PDF 文档添加水印。它介绍了处理 artifacts 的关键类——`Artifact` 和 `ArtifactCollection`,并描述了如何通过 `Page` 类的 `Artifacts` 属性访问它们。本文详细说明了 `Artifact` 类的属性,包括 `contents`、`form`、`image`、`text`、`rectangle`、`rotation` 和 `opacity` 等属性,这些属性使得在 PDF 文件中对 artifacts 进行全面操作成为可能。此外,还提供了一个实用示例,演示如何使用 Python 编程方式向 PDF 的首页添加水印。代码片段展示了 `WatermarkArtifact` 的创建与配置,设置其文本、对齐方式、旋转角度和透明度,然后将其追加到 PDF 文档并保存更改。 +--- + +向 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 中提取水印 + +1. 加载 PDF 文档。 +1. 访问页面伪影。 +1. 过滤水印伪影。 +1. 收集水印元素。 +1. 提取水印属性。 +1. 输出水印信息。 + +```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}") +``` + +## 向 PDF 添加水印 + +使用 Aspose.PDF for Python 向 PDF 文档添加文本水印: + +1. 加载 PDF 文档。 +1. 创建文本状态。 +1. 创建水印工件。 +1. 设置水印文本和样式。 +1. 配置位置和旋转。 +1. 设置不透明度和背景行为。 +1. 将水印附加到页面。 +1. 保存更新后的文档。 + +```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) + +``` + +## 删除 PDF 页面上的水印伪影 + +使用 Aspose.PDF for Python API 从 PDF 文档的特定页面中删除水印伪影。该方法针对存储为页面伪影的水印元素(特别是被归类为分页水印子类型的元素),遍历它们并在保存更新后的文档之前将其删除。 + +1. 加载 PDF 文档。 +1. 访问页面伪影。 +1. 过滤水印伪影。 +1. 删除水印伪影。 +1. 保存更新后的文档。 + +```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) +``` + +## 相关工件主题 + +- [在 Python 中使用 PDF 工件](/pdf/zh/python-net/artifacts/) +- [在 Python 中添加 PDF 背景](/pdf/zh/python-net/add-backgrounds/) +- [在 Python 中为 PDF 添加 Bates 编号](/pdf/zh/python-net/add-bates-numbering/) +- [统计 PDF 文件中的工件类型](/pdf/zh/python-net/counting-artifacts/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md b/zh/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md new file mode 100644 index 0000000000..694a8f0a31 --- /dev/null +++ b/zh/python-net/advanced-operations/artifacts/artifacts-header-footer/_index.md @@ -0,0 +1,119 @@ +--- +title: 使用 Python 管理 PDF 页眉和页脚 +linktitle: 管理 PDF 页眉和页脚 +type: docs +weight: 70 +url: /zh/python-net/artifacts-header-footer/ +description: 了解如何使用 Python 和 Aspose.PDF 管理 PDF 文档中的页眉和页脚。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 添加、定制和删除 PDF 页眉和页脚 +Abstract: 在业务、出版和自动化工作流中处理 PDF 文档时,管理页眉和页脚是一项常见需求。本文演示如何使用 Aspose.PDF for Python 添加专业外观的页眉和页脚,并可自定义字体、大小、颜色和对齐方式等样式。它还展示了如何检测并删除 PDF 页面上已有的分页痕迹,如页眉和页脚。通过可复用的函数和清晰的示例,开发者可以快速将这些功能集成到文档处理系统中,用于品牌化、报告或文件清理。 +--- + +## 创建样式化文本痕迹 + +此实用函数说明了如何使用 Aspose.PDF for Python 为 PDF 页面创建可重用的文本工件。它旨在生成具有一致格式的样式化页眉或页脚,包括字体设置、颜色、大小和对齐方式。该函数对工件的创建进行抽象,以便在不同的页面级文本装饰中重复使用。 + +1. 实例化工件对象。 +1. 设置工件文本内容。 +1. 应用文本样式。 +1. 设置对齐。 +1. 返回已配置的工件。 + +```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 + +``` + +## 向 PDF 添加页眉 + +1. 打开输入的 PDF。 +1. 创建一个 HeaderArtifact,文本为 "Sample Header"。 +1. 将其追加到第一页。 +1. 保存更新后的 PDF。 + +```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) +``` + +## 向 PDF 添加页脚 + +1. 打开输入的 PDF。 +1. 创建一个 FooterArtifact,文本为 "Sample Footer"。 +1. 将其追加到第一页。 +1. 保存输出文件。 + +```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) +``` + +## 删除页眉或页脚工件 + +1. 打开 PDF。 +1. 查找标记为分页页眉或页脚的伪件。 +1. 将它们从首页中移除。 +1. 保存已清理的文档。 + +```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) +``` + +## 相关工件主题 + +- [在 Python 中使用 PDF 工件](/pdf/zh/python-net/artifacts/) +- [在 Python 中添加 PDF 背景](/pdf/zh/python-net/add-backgrounds/) +- [在 Python 中为 PDF 添加 Bates 编号](/pdf/zh/python-net/add-bates-numbering/) +- [统计 PDF 文件中的工件类型](/pdf/zh/python-net/counting-artifacts/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/artifacts/counting-artifacts/_index.md b/zh/python-net/advanced-operations/artifacts/counting-artifacts/_index.md new file mode 100644 index 0000000000..62cb18c56e --- /dev/null +++ b/zh/python-net/advanced-operations/artifacts/counting-artifacts/_index.md @@ -0,0 +1,58 @@ +--- +title: 在 Python 中统计 PDF 工件 +linktitle: 统计工件 +type: docs +weight: 40 +url: /zh/python-net/counting-artifacts/ +description: 了解如何使用 Python 通过 Aspose.PDF for Python via .NET 检查并统计 PDF 文档中的分页工件。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 统计 PDF 工件 +Abstract: 分页工件(如水印、背景、页眉和页脚)通常用于 PDF 文档,以提供结构、品牌和识别。本示例演示如何使用 Aspose.PDF for Python via .NET 以编程方式检查并统计这些工件。通过对页面上的工件进行过滤并按子类型分组,开发人员可以快速分析文档组成并验证特定元素的存在。提供的代码展示了如何打开 PDF、从第一页提取分页工件、统计每个子类型的数量并输出结果,提供了一种实用的文档审计和验证方法。 +--- + +## 统计特定类型的工件 + +检查并计数 PDF 中的分页工件 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 使用 Aspose.PDF for Python via .NET。分页工件包括水印、背景、页眉和页脚等元素,这些元素被应用于页面以进行布局和标识目的。通过过滤 [`Artifact`](https://reference.aspose.com/pdf/python-net/aspose.pdf/artifact/) 对象在 a [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 并按子类型分组(`Artifact.ArtifactSubtype`),开发人员可以快速分析文档的结构并验证特定元素的存在。 + +要计算特定类型工件的总数(例如,水印的总数),请使用以下代码。示例过滤页面的 [`Artifacts`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) 集合 (一个 [`ArtifactCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/artifactcollection/)) 通过 [`Artifact.ArtifactType`](https://reference.aspose.com/pdf/python-net/aspose.pdf/artifact/#properties) 然后计数子类型(`Artifact.ArtifactSubtype`). + +1. 打开 PDF 文档(参见 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)). +1. 使用页面的过滤分页伪像 [`Artifacts`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) 集合。 +1. 按子类型统计工件 (`Artifact.ArtifactSubtype`). +1. 打印结果。 + +```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)}") +``` + +## 相关工件主题 + +- [在 Python 中使用 PDF 工件](/pdf/zh/python-net/artifacts/) +- [在 Python 中为 PDF 添加水印](/pdf/zh/python-net/add-watermarks/) +- [在 Python 中添加 PDF 背景](/pdf/zh/python-net/add-backgrounds/) +- [在 Python 中为 PDF 添加 Bates 编号](/pdf/zh/python-net/add-bates-numbering/) diff --git a/zh/python-net/advanced-operations/artifacts/watermark.png b/zh/python-net/advanced-operations/artifacts/watermark.png new file mode 100644 index 0000000000..7e604310ae Binary files /dev/null and b/zh/python-net/advanced-operations/artifacts/watermark.png differ diff --git a/zh/python-net/advanced-operations/attachments/_index.md b/zh/python-net/advanced-operations/attachments/_index.md index 26214a4789..0e4862a0d5 100644 --- a/zh/python-net/advanced-operations/attachments/_index.md +++ b/zh/python-net/advanced-operations/attachments/_index.md @@ -1,84 +1,28 @@ --- -title: 使用 Python 处理 PDF 附件 -linktitle: 处理附件 +title: 在 Python 中使用 PDF 附件 +linktitle: 使用附件 type: docs weight: 130 url: /zh/python-net/attachments/ -description: 使用 Python PDF API 在应用程序中访问、添加和删除 PDF 文件中的附件。包含 Python 代码示例的完整指南。 -lastmod: "2023-02-17" +description: 了解如何在 Python 中使用 Aspose.PDF for Python via .NET 添加、提取、组织和删除 PDF 附件,包括嵌入文件和 PDF 组合文档。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中添加、删除和管理 PDF 附件及组合文档 +Abstract: 本文说明了如何在 Aspose.PDF for Python via .NET 中处理 PDF 附件。了解如何向 PDF 文档添加嵌入文件、以编程方式删除附件,以及创建或管理将多种文件类型捆绑到单个 PDF 容器中的 PDF 组合文档。 --- - +在本节中,我们将说明如何使用 Aspose.PDF for Python via .NET 处理 PDF 附件。 +附件是附加到父文档的额外文件,它可以是多种文件类型,例如 PDF、Word、图像或其他文件。 +您将学习如何使用 Python 向 PDF 添加附件、获取附件信息并保存到文件、以及以编程方式从 PDF 中删除附件。 -在本节中,我们将解释如何通过 Aspose.PDF for Python via .NET 处理 PDF 中的附件。附件是附加到主文档的附加文件,它可以是多种文件类型,例如 pdf、word、图像或其他文件。您将学习如何向 pdf 添加附件,获取附件的信息并将其保存到文件中,使用 Python 从 PDF 中以编程方式删除附件。 +在需要将支持文件嵌入 PDF、从现有文档中删除嵌入文件,或将相关材料打包为 PDF 作品集时,请使用这些文章。 -- [将附件添加到 PDF 文档](/pdf/zh/python-net/add-attachment-to-pdf-document/) +## 本节涵盖的附件工作流 + +- [向 PDF 文档添加附件](/pdf/zh/python-net/add-attachment-to-pdf-document/) - [从现有 PDF 中删除附件](/pdf/zh/python-net/removing-attachment-from-an-existing-pdf/) -- [组合文档](/pdf/zh/python-net/portfolio/) \ No newline at end of file +- [作品集](/pdf/zh/python-net/portfolio/) +- [提取附件](/pdf/zh/python-net/extract-attachment/) diff --git a/zh/python-net/advanced-operations/attachments/add-attachment-to-pdf-document/_index.md b/zh/python-net/advanced-operations/attachments/add-attachment-to-pdf-document/_index.md index 3a3a2e3279..8cef1c6f62 100644 --- a/zh/python-net/advanced-operations/attachments/add-attachment-to-pdf-document/_index.md +++ b/zh/python-net/advanced-operations/attachments/add-attachment-to-pdf-document/_index.md @@ -1,170 +1,45 @@ --- -title: 使用Python向PDF文档添加附件 -linktitle: 向PDF文档添加附件 +title: 在 Python 中向 PDF 添加附件 +linktitle: 向 PDF 文档添加附件 type: docs weight: 10 url: /zh/python-net/add-attachment-to-pdf-document/ -description: 本页面描述了如何通过Aspose.PDF for Python via .NET库向PDF文件添加附件。 -lastmod: "2023-02-17" +description: 了解如何在 Python 中使用 Aspose.PDF for Python via .NET 向 PDF 文档添加文件附件。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 向 PDF 添加附件的方法 +Abstract: 本文提供了使用 Python 和 Aspose.PDF 库向 PDF 文件添加附件的分步指南。它详细说明了建立新 Python 项目、导入必要的 Aspose.PDF 包以及创建 `Document` 对象的过程。文章解释了如何使用所需的文件和描述创建 `FileSpecification` 对象,以及如何使用 `add` 方法将该对象添加到 PDF 文档的 `EmbeddedFileCollection` 中。`EmbeddedFileCollection` 保存了 PDF 中的所有附件。文中还包含了一段代码示例,演示了打开文档、设置附件文件、将其追加到文档的附件集合以及保存更新后的 PDF 的过程。 --- - +附件可以包含各种信息,且可以是多种文件类型。本文解释了如何向 PDF 文件添加附件。 -附件可以包含多种信息,并且可以是多种文件类型。本文解释了如何向PDF文件添加附件。 +当需要将支持的源文件、电子表格、图像或相关文档与主 PDF 一起打包时,使用嵌入式 PDF 附件。 -1. 创建一个新的Python项目。 -2. 导入Aspose.PDF包。 -3. 创建一个[Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)对象。 -4. 使用您要添加的文件和文件描述创建一个[FileSpecification](https://reference.aspose.com/pdf/python-net/aspose.pdf/filespecification/)对象。 -5. 使用集合的[add](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/#methods)方法,将[FileSpecification](https://reference.aspose.com/pdf/python-net/aspose.pdf/filespecification/)对象添加到[Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)对象的[EmbeddedFileCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/)集合中。 +1. 创建一个新的 Python 项目。 +1. 导入 Aspose.PDF 包 +1. 创建一个 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象。 +1. 创建一个 [FileSpecification](https://reference.aspose.com/pdf/python-net/aspose.pdf/filespecification/) 包含您正在添加的文件及文件描述的对象。 +1. 添加 [FileSpecification](https://reference.aspose.com/pdf/python-net/aspose.pdf/filespecification/) 对象到 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象的 [EmbeddedFileCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/) 集合,带有集合的 [添加](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/#methods) 方法。 -[EmbeddedFileCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/)集合包含PDF文件中的所有附件。 - 以下代码片段向您展示如何在 PDF 文档中添加附件。 +这 [EmbeddedFileCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/) 集合包含 PDF 文件中的所有附件。以下代码片段向您展示如何在 PDF 文档中添加附件。 ```python +from os import path +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) +``` - import aspose.pdf as ap - - # 打开文档 - document = ap.Document(input_pdf) - - # 设置要作为附件添加的新文件 - fileSpecification = ap.FileSpecification(attachment_file, "示例文本文件") - - # 将附件添加到文档的附件集合中 - document.embedded_files.append(fileSpecification) +## 相关附件主题 - # 保存新的输出 - document.save(output_pdf) -``` +- [在 Python 中处理 PDF 附件](/pdf/zh/python-net/attachments/) +- [在 Python 中删除 PDF 附件](/pdf/zh/python-net/removing-attachment-from-an-existing-pdf/) +- [在 Python 中创建和管理 PDF 组合文件](/pdf/zh/python-net/portfolio/) - \ No newline at end of file diff --git a/zh/python-net/advanced-operations/attachments/extract-attachment/_index.md b/zh/python-net/advanced-operations/attachments/extract-attachment/_index.md new file mode 100644 index 0000000000..e749860c01 --- /dev/null +++ b/zh/python-net/advanced-operations/attachments/extract-attachment/_index.md @@ -0,0 +1,126 @@ +--- +title: 从 PDF 中提取附件 +linktitle: 提取附件 +type: docs +weight: 50 +url: /zh/python-net/extract-attachment/ +description: 了解如何使用 Python 和 Aspose.PDF 处理 PDF 附件。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: "Python 中管理 PDF 附件的完整指南:添加、提取和处理嵌入文件" +Abstract: PDF 附件被广泛用于将支持文档、报告、图像和其他资源直接存储在 PDF 文件内部。本文提供了使用 Python 通过 Aspose.PDF 处理 PDF 附件的完整概述。它解释了如何将外部文件嵌入现有 PDF、提取特定或全部附件、检查诸如文件大小和时间戳等元数据,以及恢复存储为 FileAttachment 注释的文件。每个示例演示了用于自动化附件工作流、提升文档可移植性和简化文件管理的实用技术。无论是构建企业文档系统还是自定义自动化脚本,开发者都可以使用这些方法高效地管理 PDF 文档中的嵌入文件。 +--- + +## 从 PDF 提取特定附件 + +使用 Python 和 Aspose.PDF 从 PDF 文档中提取单个嵌入文件。它通过名称搜索附件,获取其内容,并将其保存为独立的文件。这对于访问嵌入的文档(如报告、日志或存储在 PDF 中的支持文件)非常有用。 + +1. 定义函数 'extract_single_attachment()'。 +1. 打开 PDF 文档。 +1. 搜索附件。 +1. 提取附件内容。 + +```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") +``` + +## 显示文件附件的元数据 + +此辅助函数从文件规范对象中打印元数据信息。它通常在使用 Aspose.PDF 处理 PDF 中的嵌入式文件附件时使用,使开发人员能够检查诸如校验和、创建日期、修改日期和文件大小等细节。 + +```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}") +``` + +## 提取并检查所有 PDF 附件 + +此代码片段展示了如何使用 Python 和 Aspose.PDF 从 PDF 文档中提取所有嵌入文件。它不仅将每个附件保存到指定文件夹,还打印出文件名、描述、MIME 类型、校验和和时间戳等详细元数据。这对于审计、导出或处理 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()) +``` + +## 从 PDF 附件注释中提取文件 + +使用 Python 和 Aspose.PDF 从 PDF 中的 FileAttachment 注释提取嵌入式文件。它在首页搜索第一个附件注释,检索嵌入的文件,并将其保存到选定的输出目录。当 PDF 包含可点击的文件附件图标而不是标准的嵌入文件集合时,这非常有用。 + +```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/zh/python-net/advanced-operations/attachments/portfolio/_index.md b/zh/python-net/advanced-operations/attachments/portfolio/_index.md index 59b104879b..02466fd374 100644 --- a/zh/python-net/advanced-operations/attachments/portfolio/_index.md +++ b/zh/python-net/advanced-operations/attachments/portfolio/_index.md @@ -1,203 +1,85 @@ --- -title: 使用 Python 处理 PDF 中的作品集 +title: 在 Python 中创建 PDF 作品集 linktitle: 作品集 type: docs weight: 20 url: /zh/python-net/portfolio/ -description: 如何使用 Python 创建 PDF 作品集。您应该使用 Microsoft Excel 文件、Word 文档和图像文件来创建 PDF 作品集。 -lastmod: "2023-02-17" +description: 了解如何使用 Aspose.PDF for Python via .NET 在 Python 中创建和管理 PDF 作品集。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中构建和编辑包含嵌入文件的 PDF 作品集 +Abstract: 本文解释了如何使用 Aspose.PDF for Python via .NET 创建和管理 PDF 作品集。了解如何将多种文件类型打包到单个 PDF 作品集、将文件添加到文档集合,以及使用 Python 以编程方式删除作品集项目。 --- - - - -创建一个 PDF 组合文档可以将不同类型的文件合并和存档为一个一致的文档。这样的文档可以包括文本文件、图像、电子表格、演示文稿和其他材料,确保所有相关材料存储和组织在一个地方。 - -PDF 组合文档将有助于以高质量的方式展示您的演示,无论您在哪里使用它。一般来说,创建 PDF 组合文档是一个非常现代的任务。 - -## 如何创建 PDF 组合文档 - -Aspose.PDF for Python via .NET 允许使用 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类创建 PDF 组合文档。在通过 [FileSpecification](https://reference.aspose.com/pdf/python-net/aspose.pdf/filespecification/) 类获取后,将文件添加到 document.collection 对象中。当文件添加完成后,使用 Document 类的 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法保存组合文档。 - -以下示例使用 Microsoft Excel 文件、Word 文档和图像文件创建一个 PDF 组合文档。 - -以下代码生成了如下投资组合。 - -### 使用 Aspose.PDF for Python 创建的 PDF 投资组合 - -![使用 Aspose.PDF for Python 创建的 PDF 投资组合](working-with-pdf-portfolio_1.jpg) -```python +创建 PDF 作品集可以将不同类型的文件整合并归档到单个一致的文档中。此类文档可以包括文本文件、图像、电子表格、演示文稿以及其他材料,并确保所有相关资料都存储并组织在同一位置。 + +PDF 作品集将帮助您在任何使用场景中以高质量的方式展示您的演示文稿。总体而言,创建 PDF 作品集是一项非常前沿且现代的任务。 + +当您希望将一组相关文件一起分发,同时保持每个文件在一个 PDF 容器内保持原始格式时,请使用 PDF 作品集。 + +## 如何创建 PDF 作品集 + +Aspose.PDF for Python via .NET 允许使用 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) class. 在使用该类获取后,将文件添加到 a\u00A0document.collection\u00A0object 中 [FileSpecification](https://reference.aspose.com/pdf/python-net/aspose.pdf/filespecification/) class. 当文件已添加后,使用\u00A0Document\u00A0class\u0027 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 用于保存作品集文档的方法。 + +以下示例使用 Microsoft Excel 文件、Word 文档和图像文件来创建 PDF 作品集。 + +以下代码生成如下作品集。 - import aspose.pdf as ap +### 使用 Aspose.PDF for Python 创建的 PDF 作品集 - # 实例化 Document 对象 +![使用 Aspose.PDF for Python 创建的 PDF 作品集](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() - # 实例化文档 Collection 对象 + # Instantiate document Collection object document.collection = ap.Collection() - # 获取要添加到投资组合的文件 - 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]) - # 提供文件描述 - excel.description = "Excel 文件" - word.description = "Word 文件" - image.description = "图像文件" + # Provide description of the files + excel.description = "Excel File" + word.description = "Word File" + image.description = "Image File" - # 将文件添加到文档集合 + # Add files to document collection document.collection.append(excel) document.collection.append(word) document.collection.append(image) - # 保存投资组合文档 - document.save(output_pdf) + # Save Portfolio document + document.save(outfile) ``` -## 从 PDF 投资组合中移除文件 +## 从 PDF Portfolio 中删除文件 -为了从 PDF 投资组合中删除/移除文件,尝试使用以下代码行。 +要从 PDF 组合文档中删除/移除文件,请尝试使用以下代码行。 ```python +import aspose.pdf as ap - import aspose.pdf as ap - - # 打开文档 - document = ap.Document(input_pdf) +def remove_files_from_pdf_portfolio(infile, outfile): + # Open document + document = ap.Document(infile) document.collection.delete() - # 保存更新的文件 - document.save(output_pdf) + # Save updated file + document.save(outfile) ``` - \ No newline at end of file +## 相关附件主题 + +- [在 Python 中处理 PDF 附件](/pdf/zh/python-net/attachments/) +- [在 Python 中向 PDF 添加附件](/pdf/zh/python-net/add-attachment-to-pdf-document/) +- [在 Python 中删除 PDF 附件](/pdf/zh/python-net/removing-attachment-from-an-existing-pdf/) + diff --git a/zh/python-net/advanced-operations/attachments/portfolio/working-with-pdf-portfolio_1.jpg b/zh/python-net/advanced-operations/attachments/portfolio/working-with-pdf-portfolio_1.jpg new file mode 100644 index 0000000000..06de27133c Binary files /dev/null and b/zh/python-net/advanced-operations/attachments/portfolio/working-with-pdf-portfolio_1.jpg differ diff --git a/zh/python-net/advanced-operations/attachments/portfolio/working-with-pdf-portfolio_2.jpg b/zh/python-net/advanced-operations/attachments/portfolio/working-with-pdf-portfolio_2.jpg new file mode 100644 index 0000000000..06de27133c Binary files /dev/null and b/zh/python-net/advanced-operations/attachments/portfolio/working-with-pdf-portfolio_2.jpg differ diff --git a/zh/python-net/advanced-operations/attachments/removing-attachment-from-an-existing-pdf/_index.md b/zh/python-net/advanced-operations/attachments/removing-attachment-from-an-existing-pdf/_index.md index e35c9dab72..ed370b9ce1 100644 --- a/zh/python-net/advanced-operations/attachments/removing-attachment-from-an-existing-pdf/_index.md +++ b/zh/python-net/advanced-operations/attachments/removing-attachment-from-an-existing-pdf/_index.md @@ -1,166 +1,67 @@ --- -title: 从PDF中移除附件使用Python -linktitle: 从现有PDF中移除附件 +title: 在 Python 中删除 PDF 附件 +linktitle: 从现有 PDF 中删除附件 type: docs weight: 30 url: /zh/python-net/removing-attachment-from-an-existing-pdf/ -description: Aspose.PDF可以从您的PDF文档中移除附件。使用Python PDF API通过Aspose.PDF for Python via .NET库移除PDF文件中的附件。 -lastmod: "2023-02-17" +description: Aspose.PDF 可以从您的 PDF 文档中删除附件。使用 Python PDF API,通过 Aspose.PDF for Python via .NET 库来删除 PDF 文件中的附件。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 删除 PDF 附件 +Abstract: 本文讨论了如何使用 Aspose.PDF for Python 删除 PDF 文件中的附件。PDF 文档中的附件存储在 `Document` 对象的 `EmbeddedFiles` 集合中。要删除 PDF 中的所有附件,您可以对 `EmbeddedFiles` 集合调用 `delete()` 方法,然后使用 `Document` 对象的 `save()` 方法保存更新后的文档。文中提供了代码片段来演示此过程,展示了打开文档、删除附件并保存修改后文件的步骤。 --- - - - -Aspose.PDF for Python 可以从 PDF 文件中删除附件。PDF 文档的附件保存在 Document 对象的 [EmbeddedFiles](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/) 集合中。 + +Aspose.PDF for Python 可以删除 PDF 文件中的附件。PDF 文档的附件存放在 Document 对象的 [EmbeddedFiles](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/) 集合。 + +此工作流在您需要清理过时的嵌入文件、减小包大小或准备不附带源材料的 PDF 进行再分发时非常有用。 要删除与 PDF 文件关联的所有附件: -1. 调用 [EmbeddedFiles](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/) 集合的 [delete()](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/#methods) 方法。 -2. 使用 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象的 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法保存更新后的文件。 +1. 调用 [EmbeddedFiles](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/) collection 的 [delete()](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/#methods) 方法。 +1. 使用以下方式保存已更新的文件 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象的 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法。 -以下代码片段显示了如何从 PDF 文档中删除附件。 +下面的代码片段展示了如何从 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) +``` + +## 按名称删除特定附件 + +如果您只需删除一个附件并保留其他附件,请使用 [delete_by_key()](https://reference.aspose.com/pdf/python-net/aspose.pdf/embeddedfilecollection/delete_by_key/) 方法并传递附件名称。 - # 打开文档 - document = ap.Document(input_pdf) +删除特定附件: - # 删除所有附件 - document.embedded_files.delete() +1. 打开源 PDF 文件。 +1. 调用 `document.embedded_files.delete_by_key(attachment_name)`. +1. 保存更新后的 PDF 文件。 - # 保存更新后的文件 - document.save(output_pdf) +以下代码片段通过名称删除一个附件。 + +```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) ``` +## 相关附件主题 + +- [在 Python 中处理 PDF 附件](/pdf/zh/python-net/attachments/) +- [在 Python 中向 PDF 添加附件](/pdf/zh/python-net/add-attachment-to-pdf-document/) +- [在 Python 中创建和管理 PDF 组合文件](/pdf/zh/python-net/portfolio/) - \ No newline at end of file diff --git a/zh/python-net/advanced-operations/compare-pdf-documents/_index.md b/zh/python-net/advanced-operations/compare-pdf-documents/_index.md new file mode 100644 index 0000000000..097fe6e3e5 --- /dev/null +++ b/zh/python-net/advanced-operations/compare-pdf-documents/_index.md @@ -0,0 +1,189 @@ +--- +title: 在 Python 中比较 PDF 文档 +linktitle: 比较 PDF +type: docs +weight: 130 +url: /zh/python-net/compare-pdf-documents/ +description: 了解如何在 Python 中使用 Aspose.PDF for Python via .NET 通过并排和图形差异输出比较 PDF 文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中使用可视化差异输出比较 PDF 页面和完整文档 +Abstract: 本文介绍了如何在 Aspose.PDF for Python via .NET 中比较 PDF 文档。了解如何比较特定页面或整个 PDF 文件,并以并排方式输出,以及如何使用图形比较方法生成基于图像或基于 PDF 的差异报告。 +--- + +## 比较 PDF 文档的方法 + +在处理 PDF 文档时,有时需要比较两个文档的内容以识别差异。Aspose.PDF for Python via .NET 库为此提供了强大的工具集。在本文中,我们将通过几个简单的代码片段来探讨如何比较 PDF 文档。 + +当您希望得到一个在页面之间突出显示文本和布局更改的 PDF 输出时,请使用并排比较。当您需要基于图像的差异检测以用于可视化审查工作流、回归检查或 PDF 比较报告时,请使用图形比较。 + +Aspose.PDF 中的比较功能允许您逐页比较两个 PDF 文档。您可以选择比较特定页面或整个文档。生成的比较文档会突出显示差异,从而更容易识别两个文件之间的更改。 + +以下是使用 Aspose.PDF for Python via .NET 库比较 PDF 文档的可能方法列表: + +1. **比较特定页面** - 比较两个 PDF 文档的第一页。 +1. **比较整个文档** - 比较两个 PDF 文档的全部内容。 +1. **以图形方式比较 PDF 文档**: + +- 使用 'comparer.get_difference' 方法比较 PDF - 各个图像中标记了更改。 +- 使用 'comparer.compare_documents_to_pdf' 方法比较 PDF - PDF 文档中包含标记了更改的图像。 + +## 比较特定页面 + +第一个代码片段演示了如何使用 SideBySidePdfComparer 类比较两个 PDF 文档的首页。 + +1. 文档初始化。 +1. 创建一个函数来执行比较。 +1. 比较过程: + +- document1.pages[1] 和 document2.pages[1]: - 这些指定了每个文档用于比较的第一页。请注意,页面索引在 Aspose.PDF 中从 1 开始。 +- SideBySideComparisonOptions - 此类允许自定义比较行为。 +- additional_change_marks = True - 启用额外更改标记的显示,突出显示可能存在于其他页面的差异,即使这些差异不在当前比较的页面上。 +- comparison_mode = ComparisonMode.IgnoreSpaces - 将比较模式设置为忽略文本中的空格,只关注单词内部的更改。 + +1. 比较的结果保存为一个新的 PDF 文件,名为 ComparingSpecificPages_out.pdf,放置在指定的 data_dir 中。 + +```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 + ) +``` + +## 比较整个文档 + +第二段代码扩展了范围,以比较两个 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 + ) +``` + +提供的代码演示了使用 Aspose.PDF for Python via .NET 比较两个 PDF 文档。它利用 SideBySidePdfComparer 类逐页比较,生成一个显示差异并排的新 PDF。比较通过 SideBySideComparisonOptions 配置,其中 additional_change_marks 设置为 True,以便在当前页之外的其他页也突出显示更改,并且 comparison_mode 设置为 IgnoreSpaces,以通过忽略空白变化来关注有意义的内容差异。 + +## 使用 GraphicalPdfComparer 进行比较 + +在协作处理文档时,尤其是在专业环境中,你常常会得到同一文件的多个版本。 +提供的代码演示了如何使用 Aspose.PDF for Python via .NET 对两个 PDF 文档的特定页面进行可视化比较。通过使用的 `GraphicalPdfComparer` 类,它突出显示两个 PDF 的首页之间的差异,并生成相应的图像来表示这些差异。 + +您可以设置以下类属性: + +- Resolution - 输出图像的分辨率(以 DPI 为单位),以及比较过程中生成的图像的分辨率。 +- Color - 更改标记的颜色。 +- 阈值 - 以百分比更改阈值。默认值为零。将阈值设置为非零可以忽略对您而言不重要的图形更改。 + +使用 Aspose.PDF for Python via .NET,您可以比较文档和页面,并将比较结果输出为 PDF 文档或图像文件。 + +这 `GraphicalPdfComparer` 类有一个方法,允许您以适合进一步处理的形式获取页面图像差异: `get_difference(document1.pages[1], document2.pages[1])`. + +此方法返回一个对象的 `images_difference` type,其中包含正在比较的第一页的图像以及差异数组。 + +这 `images_difference` 对象允许您生成不同的图像,并通过对原始图像应用差异数组来获取第二页的对比图像。要实现此目的,请使用 `difference_to_image` 和 `get_destination_image` 方法。 + +### 使用 Get Difference 方法比较 PDF + +提供的代码定义了一个方法 `get_difference` 比较两个 PDF 文档并生成它们之间差异的可视化表示。 + +此方法比较两个 PDF 文件的第一页,并生成两张 PNG 图像: + +- 一张图像以红色突出显示页面之间的差异。 +- 另一张图像是目标(第二)PDF页面的可视化表示。 + +此过程可用于直观比较文档两个版本之间的更改或差异。 + +```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) +``` + +### 使用 CompareDocumentsToPdf 方法比较 PDF + +提供的代码片段使用了 `compare_documents_to_pdf` 方法,用于比较两个文档并生成比较结果的PDF报告。 + +```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) +``` + +此示例演示如何使用 Aspose.PDF for Python via .NET 对两个完整的 PDF 文档进行图形比较。通过利用 `GraphicalPdfComparer` 类,它会生成一个新的 PDF 文件,直观地突出显示文档之间的差异。 + +- 阈值属性设置为 3.0,这意味着在比较过程中,低于此百分比的细微差异将被忽略,关注更显著的变化。 +- 差异通过将 color 属性设置为 ap.Color.blue 标记为蓝色,从而实现清晰的视觉区分。 +- 通过设置分辨率属性,以 300 DPI 的分辨率执行比较,确保输出详尽清晰。 + +这 `compare_documents_to_pdf` 方法比较两个文档的所有页面,并将结果输出到一个新的 PDF 文件 compareDocumentsToPdf_out.pdf,差异以可视方式突出显示。 + +## 相关主题 + +- [Python中的高级PDF操作](/pdf/zh/python-net/advanced-operations/) +- [使用 Python 处理 PDF 文档](/pdf/zh/python-net/working-with-documents/) +- [在 Python 中处理 PDF 页面](/pdf/zh/python-net/working-with-pages/) +- [在Python中处理PDF文本](/pdf/zh/python-net/working-with-text/) diff --git a/zh/python-net/advanced-operations/navigation-and-interaction/_index.md b/zh/python-net/advanced-operations/navigation-and-interaction/_index.md index 309bc09b04..7c833d7ba8 100644 --- a/zh/python-net/advanced-operations/navigation-and-interaction/_index.md +++ b/zh/python-net/advanced-operations/navigation-and-interaction/_index.md @@ -1,144 +1,23 @@ --- -title: 使用 Python 在 PDF 中的导航和交互 -linktitle: 导航和交互 +title: Python 中的 PDF 导航与交互 +linktitle: 导航与交互 type: docs weight: 90 url: /zh/python-net/navigation-and-interaction/ -description: 本节介绍使用 Python 库进行链接、动作和书签的工作特性。 -lastmod: "2023-02-17" +description: 了解如何在 Python 中使用 PDF 链接、操作和书签来实现导航和交互式文档行为。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" - priority: 0.7 + changefreq: "monthly" + priority: 0.5 +TechArticle: true +AlternativeHeadline: 使用 Python 处理 PDF 文件中的链接、操作和书签 +Abstract: 本节说明如何使用 Python 管理 PDF 文档中的导航和交互功能。学习如何创建和更新链接、添加交互式操作以及使用书签,以提升 PDF 的导航性、可用性和文档工作流。 --- - +当您需要在 Python 中构建交互式 PDF 导航时,请使用本节,无论是创建书签、更新链接目标,还是将操作附加到文档事件、页面和表单元素。 -- [书签](/pdf/zh/python-net/bookmarks/)- 大型出版物通常包含一个书签框架,可以在书签窗格中轻松查看和选择,允许您点击书签跳转到它所代表的页面或章节。书签窗格是一个内容感知元素,只有在打开的 PDF 文档包含书签结构时,才会在侧边栏中可见。 +## 本节主题 - \ No newline at end of file +- [操作](/pdf/zh/python-net/actions/) - 在本文中,您将学习如何处理不同类型的操作。 +- [书签](/pdf/zh/python-net/bookmarks/)- 大型出版物通常包括一个书签框架,可在“书签窗格”中轻松查看和选择,允许您单击书签跳转到其代表的页面或章节。只有当打开的 PDF 文档包含书签结构时,书签窗格才作为内容感知元素显示在侧边栏中。 +- [链接](/pdf/zh/python-net/links/)- 使用 Python 库在 PDF 文档中处理链接。 diff --git a/zh/python-net/advanced-operations/navigation-and-interaction/actions/_index.md b/zh/python-net/advanced-operations/navigation-and-interaction/actions/_index.md new file mode 100644 index 0000000000..113a3ce980 --- /dev/null +++ b/zh/python-net/advanced-operations/navigation-and-interaction/actions/_index.md @@ -0,0 +1,360 @@ +--- +title: 在 Python 中使用 PDF 操作 +linktitle: 操作 +type: docs +weight: 20 +url: /zh/python-net/actions/ +description: 了解如何使用 Python 在 PDF 文件中添加、更新和删除文档、页面和表单操作。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.5 +TechArticle: true +AlternativeHeadline: 在 Python 中向 PDF 文件添加文档、页面和表单操作。 +Abstract: 本文探讨了如何使用 Aspose.PDF 库在 PDF 文档中处理动作,涵盖文档级、页面级和表单级的交互。PDF 动作是预定义或可自定义的触发器,响应用户事件,实现导航、JavaScript 执行、多媒体播放、表单提交等功能。指南演示了如何添加、定制和移除动作,例如在文档事件中打开 URL、创建特定页面的导航或缩放效果、添加用于打印和导航的交互按钮、动态隐藏表单元素以及将表单数据提交到 Web 端点。通过详细的 Python 代码示例,读者可以学习提升 PDF 的交互性、简化工作流,并将 PDF 与外部系统集成,同时了解查看器兼容性注意事项。 +--- + +PDF 中的操作是预定义的任务,当用户交互或文档事件触发时执行。它们可用于: + +- 导航到特定页面或外部文件 +- 打开网页链接 +- 播放多媒体内容 +- 运行 JavaScript +- 提交或重置表单 +- 显示/隐藏字段 +- 更改缩放级别或视图模式 + +几乎所有操作都使用内置参数,但有一些可以自定义。例如 - JavaScript 操作。 + +## 添加 PDF 启动操作 + +使用 Python 和 Aspose.PDF 向 PDF 文档添加基于 JavaScript 的启动操作。它将操作分配给关键文档事件,如打开、保存和打印,允许在受支持的 PDF 查看器中这些事件发生时自动启动 URL。 + +```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) +``` + +## 从 PDF 文档中删除操作 + +要清除(或移除)操作,只需将处理程序设置为 `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) +``` + +## 在 PDF 文档的页面中添加操作 + +类似的触发器已为页面提供: `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) +``` + +## AcroForms 中的操作 + +### 使用导航操作 + +PDF 标准提供了一组特定的命名操作。此类操作的含义由其名称决定。 +在下面的代码中,我们将使用动作进行导航。 + +```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) +``` + +此代码为 PDF 文档的每一页添加导航按钮,使用户更容易在页面之间移动。它首先使用辅助方法确定输入和输出文件的完整文件路径。button_config 列表定义了四种导航按钮——“首页”、“上一页”、“下一页”和“末页”——以及它们的水平位置、预定义的导航操作以及一个 lambda 函数,用于确定每个按钮在给定页面上是否应为只读(例如,“首页”和“上一页”按钮在第一页上为只读)。 + +代码随后加载 PDF 并遍历每一页。对于每一页,它会循环遍历按钮配置,为每个按钮创建一个矩形区域,并在该位置实例化一个 ButtonField。为每个按钮分配一个名称,其只读状态根据当前页设置,并将其点击操作指派给相应的导航操作。随后将该按钮添加到 PDF 表单字段中。 + +在所有按钮添加到所有页面后,修改后的文档被保存。如果在此过程中出现任何错误,它们会被捕获并打印出来。此方法确保每页都有一致的导航控件集合,提升了多页 PDF 的可用性。一个细节是使用 is_readonly_fn lambda 在按钮不合适时(例如在最后一页时禁用"Next Page"),这有助于防止用户产生困惑。 + +### 使用打印操作 + +在使用 PDF 表单时,通常需要打印此类 PDF 文档。此操作可以使用 PDF 阅读器来完成,但有时直接在文档中使用特殊按钮会更方便。 + +事实上,这又是一个如何使用命名动作的示例。我们将使用 `PredefinedAction.FILE_PRINT` (模拟使用 File->Print 菜单项),但您也可以使用 `PredefinedAction.PRINT` 或 `PredefinedAction.PRINT_DIALOG`,取决于您自己的目的。 + +```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) +``` + +此代码片段演示了如何向 PDF 文档的首页添加一个 “Print” 按钮。它首先从指定的输入文件路径加载 PDF,并选择首页 (document.pages[1])。 + +在页面上为按钮的位置和大小定义了一个矩形区域。随后在该位置创建了一个 ButtonField,命名为 "printButton",并将其显示值设置为 "Print"。该按钮被配置为在点击时(具体而言,在鼠标按钮释放时),触发预定义的 "Print File" 操作,促使 PDF 查看器打开打印对话框。 + +为了增强按钮的外观,创建了一个边框并分配给按钮,将其宽度设置为 1 个单位。然后将按钮添加到第一页的 PDF 表单字段中。最后,将修改后的文档保存到输出文件路径。此方法为用户提供了一种直接在 PDF 中打印文档的便捷方式。请注意,此功能的有效性取决于 PDF 查看器对交互式表单字段和预定义操作的支持。 + +### 使用隐藏操作 + +```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) +``` + +此代码片段在 PDF 的首页添加了一个按钮,单击后可隐藏文档中的所有复选框字段。它首先使用辅助方法解析完整的输入和输出文件路径。加载 PDF 后,通过筛选表单字段中该类型的实例来收集所有复选框字段。 `ap.CheckboxField`. + +在页面顶部附近定义了一个矩形区域,用于新按钮的位置。在此位置创建了一个 ButtonField,命名为 "HideButton,",并标记为 "Hide Checkboxes."。按钮被配置为在点击(鼠标按钮释放时)时触发 HideAction,隐藏所有已收集的复选框。 + +然后将按钮添加到第一页的表单字段中,并将修改后的 PDF 保存到输出文件。如果此过程出现任何错误,它们会被捕获并打印。此功能为用户提供了一种快速隐藏 PDF 中所有复选框的方法,这对于自定义文档的外观或工作流非常有用。 + +### 应用提交操作 + +```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) +``` + +此函数在 PDF 表单的首页添加一个“Submit”按钮,允许用户将表单数据提交到指定的网络端点。它首先构建输入和输出 PDF 文件的完整路径,然后使用 Aspose.PDF 库加载输入 PDF。 + +A `SubmitFormAction` 已创建以定义按钮被点击时的行为。操作的 URL 是使用 a 设置的 `FileSpecification` 指向 http://localhost:3000/submit, 这意味着表单数据将发送到此 URL。flags 属性组合 `EXPORT_FORMAT` 和 `SUBMIT_COORDINATES`,确保表单数据以标准格式导出,并且在提交中包含按钮点击的坐标。 + +在页面上为按钮的位置和大小定义了一个矩形区域。在第一页的该位置创建了一个 ButtonField,命名为 "SubmitButton",其显示值设置为 "Submit"。提交操作被分配给按钮的鼠标释放事件,因此当用户点击按钮时会触发该操作。 + +最后,将按钮添加到首页的表单字段中,并将修改后的 PDF 保存到输出文件。如果在此过程中出现任何错误,会被捕获并打印。此方法为 PDF 用户提供了一种友好的方式,可将表单数据直接提交到服务器端点。 + +## 相关导航主题 + +- [使用 Python 在 PDF 中进行导航和交互](/pdf/zh/python-net/navigation-and-interaction/) +- [使用 Python 在 PDF 中处理书签](/pdf/zh/python-net/bookmarks/) +- [使用 Python 处理 PDF 中的链接](/pdf/zh/python-net/links/) diff --git a/zh/python-net/advanced-operations/navigation-and-interaction/bookmarks/_index.md b/zh/python-net/advanced-operations/navigation-and-interaction/bookmarks/_index.md index 0a2bc81088..331c6e2769 100644 --- a/zh/python-net/advanced-operations/navigation-and-interaction/bookmarks/_index.md +++ b/zh/python-net/advanced-operations/navigation-and-interaction/bookmarks/_index.md @@ -1,86 +1,29 @@ --- -title: 使用 Python 在 PDF 中处理书签 +title: 在 Python 中使用 PDF 书签 linktitle: 书签 type: docs weight: 30 url: /zh/python-net/bookmarks/ -description: 本节解释如何使用 Aspose.PDF for Python via .NET 添加、删除和获取书签。 -lastmod: "2023-02-17" +description: 了解如何在 Python 中添加、删除、检索、更新和展开 PDF 书签。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 在 PDF 中操作书签 +Abstract: 本文讨论了书签在 PDF 文档中的重要性和实用性。书签通过实现高效的导航、组织和结构化 PDF 文件,提升用户体验,使文件更易获取。它们充当交互式链接,使用户能够快速跳转到特定章节或页面,类似于目录。本文提供了管理书签的指南,包括如何添加、删除、获取、更新以及展开书签,从而帮助用户有效地管理和查看 PDF 内容。 --- - +在 PDF 中使用书签是一项便利的功能。借助书签,您可以在文档中设置导航,组织和结构化 PDF 文件,使这些文件更易获取。它们在文档内充当交互式链接,使用户能够快速导航到特定章节或页面。 -在 PDF 中使用书签是一个非常有用的功能。通过它们,你可以在文档中设置导航,组织和结构化 PDF 文件,并使这些文件更易于访问。它们作为文档中的交互式链接,使用户能够快速导航到特定部分或页面。 +PDF 书签是阅读 PDF 文件的便捷且必不可少的工具。它们允许用户快速跳转到 PDF 文档的其他位置,浏览页面,并快速查看 PDF 的内容,就像目录一样。 -当阅读 PDF 文件时,PDF 书签是一个方便且必要的工具。它们允许用户快速跳转到 PDF 文档中的其他位置,浏览页面,并快速查看 PDF 的内容,就像目录一样。 -在本节中,你将学习如何: +在需要创建目录式导航体验或检查和更新 PDF 中现有书签树时,请使用以下书签指南。 + +## 涉及的书签任务 + +在本节中,您将学习如何: - [添加和删除书签](/pdf/zh/python-net/add-and-delete-bookmark/) -- [获取、更新和展开书签](/pdf/zh/python-net/get-update-and-expand-bookmark/) \ No newline at end of file +- [获取、更新并展开书签](/pdf/zh/python-net/get-update-and-expand-bookmark/) +- [导航和交互概述](/pdf/zh/python-net/navigation-and-interaction/) diff --git a/zh/python-net/advanced-operations/navigation-and-interaction/bookmarks/add-and-delete-bookmark/_index.md b/zh/python-net/advanced-operations/navigation-and-interaction/bookmarks/add-and-delete-bookmark/_index.md index ab3d123c45..329f31a846 100644 --- a/zh/python-net/advanced-operations/navigation-and-interaction/bookmarks/add-and-delete-bookmark/_index.md +++ b/zh/python-net/advanced-operations/navigation-and-interaction/bookmarks/add-and-delete-bookmark/_index.md @@ -1,205 +1,160 @@ --- -title: 使用 Python 添加和删除书签 +title: 在 Python 中添加和删除 PDF 书签 linktitle: 添加和删除书签 type: docs weight: 10 url: /zh/python-net/add-and-delete-bookmark/ -description: 你可以使用 Python 向 PDF 文档添加书签。可以从 PDF 文档中删除所有或特定书签。 -lastmod: "2023-02-17" +description: 了解如何使用 Python 在 PDF 文档中添加和删除书签。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 添加和删除书签 +Abstract: 本文提供了使用 Aspose.PDF library for Python 在 PDF 文档中管理书签的完整指南。它概述了在 PDF 中添加、修改和删除书签的流程。文章首先通过创建 `OutlineItemCollection` 对象并将其追加到文档的 `OutlineCollection` 来介绍如何添加书签。文中包含代码示例,演示了父书签和子书签的创建与添加,突出层级关系。此外,本文还介绍了删除所有书签或按标题删除特定书签的方法。每个章节都包含 Python 代码片段,以便读者能够轻松在其 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/) 集合中。 + +## 在 PDF 文档中添加书签 + +书签存放在 Document 对象的 [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) 集合本身在 [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) 集合。 要向 PDF 添加书签: -1. 使用 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象打开 PDF 文档。 +1. 使用打开 PDF 文档 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象。 1. 创建书签并定义其属性。 -1. 将 [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) 集合添加到大纲集合中。 +1. 添加 [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) 集合到 Outlines 集合。 -以下代码片段向您展示了如何在 PDF 文档中添加书签。 +下面的代码片段展示了如何在 PDF 文档中添加书签。 ```python +import aspose.pdf as ap +import sys +from os import path - import aspose.pdf as ap +def add_bookmark(infile, outfile): + # Open PDF document + document = ap.Document(infile) - # 打开文档 - document = ap.Document(input_pdf) + # Create a bookmark object + pdf_outline = ap.OutlineItemCollection(document.outlines) + pdf_outline.title = "Test Outline" + pdf_outline.italic = True + pdf_outline.bold = True - # 创建书签对象 - outline = ap.OutlineItemCollection(document.outlines) - outline.title = "测试书签" - outline.italic = True - outline.bold = True - # 设置目标页码 - outline.action = ap.annotations.GoToAction(document.pages[1]) - # 在文档的大纲集合中添加书签。 - document.outlines.append(outline) + # Set the destination page number + pdf_outline.action = ap.annotations.GoToAction(document.pages[1]) - # 保存输出 - document.save(output_pdf) -``` + # Add bookmark to the document's outline collection + outlines = document.outlines + outlines.append(pdf_outline) + # Save PDF document + document.save(outfile) +``` ## 向 PDF 文档添加子书签 -书签可以嵌套,表示与父书签和子书签的层次关系。本文解释了如何向 PDF 添加子书签,即二级书签。 +书签可以嵌套,表示父书签和子书签之间的层级关系。本文说明了如何向 PDF 添加子书签,即二级书签。 要向 PDF 文件添加子书签,首先添加父书签: 1. 打开文档。 -1. 向 [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) 添加书签,定义其属性。 -1. 将 OutlineItemCollection 添加到 Document 对象的 [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) 集合中。 +1. 将书签添加到 [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/),定义其属性。 +1. 将 OutlineItemCollection 添加到 Document 对象的 [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) 集合。 -子书签的创建方式与上述父书签相同,但被添加到父书签的 Outlines 集合中。 +子书签的创建方式与上文解释的父书签相同,但它被添加到父书签的 Outlines 集合中 以下代码片段展示了如何向 PDF 文档添加子书签。 ```python - - import aspose.pdf as ap - - # 打开文档 - document = ap.Document(input_pdf) - - # 创建一个父书签对象 - outline = ap.OutlineItemCollection(document.outlines) - outline.title = "Parent Outline" - outline.italic = True - outline.bold = True - - # 创建一个子书签对象 - childOutline = ap.OutlineItemCollection(document.outlines) - childOutline.title = "Child Outline" - childOutline.italic = True - childOutline.bold = True - - # 在父书签的集合中添加子书签 - outline.append(childOutline) - # 在文档的大纲集合中添加父书签。 - document.outlines.append(outline) - - # 保存输出 - document.save(output_pdf) +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) ``` +## 删除 PDF 文档中的所有书签 -## 从 PDF 文档中删除所有书签 - -PDF 中的所有书签都保存在 [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) 集合中。本文解释了如何从 PDF 文件中删除所有书签。 +PDF 中的所有书签都存储在 [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) 集合中。本篇文章解释如何从 PDF 文件中删除所有书签。 要从 PDF 文件中删除所有书签: -1. 调用 [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) 集合的 Delete 方法。 -1. 使用 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象的 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法保存修改后的文件。 +1. 调用 [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) collection 的 Delete 方法。 +1. 使用以下方式保存已修改的文件 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象的 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法。 以下代码片段展示了如何从 PDF 文档中删除所有书签。 ```python +import aspose.pdf as ap +import sys +from os import path - import aspose.pdf as ap - - # 打开文档 - document = ap.Document(input_pdf) +def delete_bookmarks(infile, outfile): + # Open PDF document + document = ap.Document(infile) - # 删除所有书签 + # Delete all bookmarks in the PDF document document.outlines.delete() - # 保存更新后的文件 - document.save(output_pdf) - + # Save PDF document + document.save(outfile) ``` -## 从 PDF 文档中删除特定书签 +## 删除 PDF 文档中的特定书签 -要从 PDF 文件中删除特定书签: +要从 PDF 文件中删除特定书签,请: -1. 将书签的标题作为参数传递给 [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) 集合的 Delete 方法。 +1. 将书签的标题作为参数传递给 [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) collection 的 Delete 方法。 1. 然后使用 Document 对象的 Save 方法保存更新后的文件。 -[Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类提供了 [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) 集合。[delete()](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/#methods) 方法删除传递给该方法的标题的任何书签。 +这 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) class’ 提供了 [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) 集合。The [delete()](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/#methods) method 删除传递给该方法的标题的任何书签。 -以下代码片段展示了如何从 PDF 文档中删除特定书签。 +以下代码片段展示了如何从 PDF 文档中删除特定的书签。 ```python +import aspose.pdf as ap +import sys +from os import path - import aspose.pdf as ap - - # 打开文档 - document = ap.Document(input_pdf) +def delete_bookmark(infile, outfile): + # Open PDF document + document = ap.Document(infile) - # 按标题删除特定大纲 + # 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") - # 保存更新后的文件 - document.save(output_pdf) \ No newline at end of file + # Save PDF document + document.save(outfile) +``` + +## 相关书签主题 + +- [在 Python 中使用 PDF 书签](/pdf/zh/python-net/bookmarks/) +- [在 Python 中获取、更新和展开 PDF 书签](/pdf/zh/python-net/get-update-and-expand-bookmark/) +- [使用 Python 在 PDF 中进行导航和交互](/pdf/zh/python-net/navigation-and-interaction/) + diff --git a/zh/python-net/advanced-operations/navigation-and-interaction/bookmarks/get-update-expand-bookmark/_index.md b/zh/python-net/advanced-operations/navigation-and-interaction/bookmarks/get-update-expand-bookmark/_index.md index be5a7fbe3e..94d8b92c9b 100644 --- a/zh/python-net/advanced-operations/navigation-and-interaction/bookmarks/get-update-expand-bookmark/_index.md +++ b/zh/python-net/advanced-operations/navigation-and-interaction/bookmarks/get-update-expand-bookmark/_index.md @@ -1,96 +1,32 @@ --- -title: 获取、更新和展开书签使用Python -linktitle: 获取、更新和展开书签 +title: 在 Python 中获取、更新和展开 PDF 书签 +linktitle: 获取、更新并展开书签 type: docs weight: 20 url: /zh/python-net/get-update-and-expand-bookmark/ -description: 本文描述了如何使用我们的Aspose.PDF for Python库在PDF文件中使用书签。 -lastmod: "2023-02-17" +description: 了解如何使用 Python 检索、更新和展开 PDF 文档中的书签。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 在 PDF 中使用书签 +Abstract: 本文提供了使用 Aspose.PDF 库在 Python 中管理 PDF 文档书签的完整指南。文章首先说明如何通过 `OutlineCollection` 检索 PDF 文件中的书签,该集合包含所有书签,并详细介绍通过 `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 文件中获取书签,以及如何获取特定书签所在的页面。 +这 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象的 [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) collection 包含 PDF 文件的所有书签。本篇文章解释了如何从 PDF 文件获取书签,以及如何获取特定书签所在的页面。 -要获取书签,遍历 [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) 集合,并在 OutlineItemCollection 中获取每个书签。[OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) 提供了对所有书签属性的访问。以下代码片段展示了如何从 PDF 文件中获取书签。 +要获取书签,遍历 [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) 集合,并在 OutlineItemCollection 中获取每个书签。 [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) 提供访问所有书签属性的功能。以下代码片段展示了如何从 PDF 文件中获取书签。 ```python +from os import path +import sys +import aspose.pdf as ap - import aspose.pdf as ap - - # 打开文档 +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 @@ sitemap: print(outline_item.color) ``` +## 获取书签的页面编号 -## 获取书签的页码 - -添加书签后,可以通过获取与书签对象关联的目标页码来找出它所在的页面。 +添加书签后,您可以通过获取与 Bookmark 对象关联的目标 PageNumber 来确定它所在的页码。 ```python - - import aspose.pdf as ap - - # 创建 PdfBookmarkEditor - bookmarkEditor = ap.facades.PdfBookmarkEditor() - # 打开 PDF 文件 - bookmarkEditor.bind_pdf(input_pdf) - # 提取书签 - 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, "标题:", bookmark.title) - print(str_level_seprator, "页码:", bookmark.page_number) - print(str_level_seprator, "页面操作:", 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) ``` ## 从 PDF 文档获取子书签 -书签可以组织成具有父子关系的层次结构。 - 要获取所有书签,请遍历 Document 对象的 Outlines 集合。然而,要同时获取子书签,还需要遍历在第一次循环中获得的每个 [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) 对象中的所有书签。以下代码片段展示了如何从 PDF 文档中获取子书签。 +书签可以以层次结构组织,拥有父级和子级。要获取所有书签,遍历 Document 对象的 Outlines 集合。然而,要同时获取子书签,还需遍历每个在第一次循环中获得的对象的所有书签。 [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) 在第一次循环中获取的对象。以下代码片段展示了如何从 PDF 文档中获取子书签。 ```python +from os import path +import sys +import aspose.pdf as ap - import aspose.pdf as ap - - # 打开文档 +def get_child_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) @@ -145,126 +80,65 @@ sitemap: print(outline_item.color) count = len(outline_item) if count > 0: - print("子书签") - # 有子书签则也遍历它们 + 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) ``` -## 更新 PDF 文档中的书签 +## 在 PDF 文档中更新书签 -要更新 PDF 文件中的书签,首先通过指定书签的索引,从 Document 对象的 OutlineColletion 集合中获取特定书签。一旦将书签检索到 [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) 对象中,就可以更新其属性,然后使用 Save 方法保存更新后的 PDF 文件。以下代码片段演示了如何在 PDF 文档中更新书签。 +要更新 PDF 文件中的书签,首先通过指定书签的索引,从 Document 对象的 OutlineColletion 集合中获取特定书签。检索到书签后,将其 [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) 对象后,您可以更新其属性,然后使用 Save 方法保存更新后的 PDF 文件。以下代码片段展示了如何在 PDF 文档中更新书签。 ```python +from os import path +import sys +import aspose.pdf as ap - import aspose.pdf as ap - - # 打开文档 +def update_bookmarks(input_pdf, output_pdf): + # Open document document = ap.Document(input_pdf) - # 获取书签对象 + # Get a bookmark object outline = document.outlines[1] - # 获取子书签对象 + # Get child bookmark object child_outline = outline[1] child_outline.title = "Updated Outline" child_outline.italic = True child_outline.bold = True - # 保存输出 + # Save output document.save(output_pdf) ``` -## 查看文档时展开书签 +## 在查看文档时展开书签 -书签保存在 Document 对象的 [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) 集合中,该集合本身在 [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) 集合中。 - 然而,我们可能需要在查看 PDF 文件时将所有书签展开。 +书签存放在 Document 对象的 [OutlineItemCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlineitemcollection/) 集合本身在 [OutlineCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/outlinecollection/) 集合。不过,我们可能需要在查看 PDF 文件时将所有书签展开。 -为了实现这一要求,我们可以将每个大纲/书签项的打开状态设置为打开。以下代码段向您展示如何在 PDF 文档中将每个书签的打开状态设置为展开。 +为了实现此需求,我们可以将每个大纲/书签项的打开状态设置为 Open。下面的代码片段展示了如何在 PDF 文档中将每个书签的打开状态设置为展开。 ```python +from os import path +import sys +import aspose.pdf as ap - import aspose.pdf as ap - - # 打开文档 +def expanded_bookmarks(input_pdf, output_pdf): document = ap.Document(input_pdf) - - # 设置页面查看模式,即显示缩略图,全屏,显示附件面板 document.page_mode = ap.PageMode.USE_OUTLINES - # 遍历 PDF 文件的大纲集合中的每个大纲项 for i in range(len(document.outlines)): item = document.outlines[i + 1] - # 设置大纲项的打开状态 item.open = True - - # 保存输出 document.save(output_pdf) ``` - \ No newline at end of file +## 相关书签主题 + +- [在 Python 中使用 PDF 书签](/pdf/zh/python-net/bookmarks/) +- [在 Python 中添加和删除 PDF 书签](/pdf/zh/python-net/add-and-delete-bookmark/) +- [使用 Python 在 PDF 中进行导航和交互](/pdf/zh/python-net/navigation-and-interaction/) + diff --git a/zh/python-net/advanced-operations/navigation-and-interaction/links/_index.md b/zh/python-net/advanced-operations/navigation-and-interaction/links/_index.md new file mode 100644 index 0000000000..0ce3a098a0 --- /dev/null +++ b/zh/python-net/advanced-operations/navigation-and-interaction/links/_index.md @@ -0,0 +1,23 @@ +--- +title: 在 Python 中使用 PDF 链接 +linktitle: 链接 +type: docs +weight: 10 +url: /zh/python-net/links/ +description: 了解如何使用 Python 在 PDF 文档中创建、提取和更新内部和外部链接。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中创建、提取和更新 PDF 链接 +Abstract: 《Aspose.PDF for Python via .NET》关于链接操作的指南提供了全面概述,帮助开发者使用 Python 以编程方式管理 PDF 文档中的超链接和导航元素。它涵盖了创建内部和外部链接、更新链接目标和外观以及提取现有链接等基本操作。 +--- + +当您需要创建可点击的链接、检查现有链接注释或更新 PDF 文件中链接的外观和目标时,请使用本节。 + +## 链接任务概述 + +- [创建链接](/pdf/zh/python-net/create-links/) - 学习一种简单的方法,使用 Python 在 PDF 文件中创建链接。 +- [更新链接](/pdf/zh/python-net/update-links/) - 尝试将目标设置为 PDF,尝试将链接目标设置为网页地址,尝试将链接目标设置为另一个 PDF 文件,更新链接文本颜色。 +- [提取链接](/pdf/zh/python-net/extract-links/) - 使用 Python 从 PDF 文件中提取链接。 diff --git a/zh/python-net/advanced-operations/navigation-and-interaction/links/create-links/_index.md b/zh/python-net/advanced-operations/navigation-and-interaction/links/create-links/_index.md new file mode 100644 index 0000000000..12b7047c55 --- /dev/null +++ b/zh/python-net/advanced-operations/navigation-and-interaction/links/create-links/_index.md @@ -0,0 +1,147 @@ +--- +title: 在 Python 中创建 PDF 链接 +linktitle: 创建链接 +type: docs +weight: 10 +url: /zh/python-net/create-links/ +description: 了解如何在 Python 中创建内部、外部和远程 PDF 链接。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何在 PDF 中创建链接 +Abstract: Aspose.PDF for Python via .NET 创建链接的指南为开发人员提供了使用 Python 向 PDF 文档添加交互式超链接的实用说明。它涵盖了如何创建各种类型的链接,包括启动外部应用程序、在同一文档内导航到特定页面或打开其他 PDF 文件的链接。文档解释了如何使用 LinkAnnotation 对象、使用 Rectangle 定义可点击区域,以及分配诸如 LaunchAction 或 GoToRemoteAction 等操作。通过清晰的代码示例和一步步的指导,该资源帮助开发人员在 Python 应用程序中提升 PDF 的导航和交互性。 +--- + +## PDF 文档中的链接 + +根据 PDF 1.7 规范(ISO 32000-1:2008),**链接注释**可以触发多种类型的动作,这些动作定义了注释激活时会发生什么。以下是支持的主要动作: + +1. **GoTo** – 导航到同一文档中的目标。 +1. **GoToR** – 跳转到另一个 PDF 文件中的目标(远程跳转)。 +1. **URI** – 打开统一资源标识符,通常是网页链接。 +1. **Launch** – 启动一个应用程序或打开一个文件(取决于平台,且通常出于安全原因受到限制)。 +1. **Named** – 执行预定义的操作,例如转到下一页或打印文档。 +1. **JavaScript** – 执行嵌入的 JavaScript 代码(因安全考虑需谨慎使用)。 +1. **SubmitForm** – 将表单数据提交到指定的 URL。 +1. **ResetForm** – 将表单字段重置为默认值。 +1. **ImportData** – 将数据从外部文件导入文档。 + +通过在文档中添加指向应用程序的链接,可以实现从文档链接到应用程序。这在例如希望读者在教程的特定位置执行某个操作,或创建功能丰富的文档时非常有用。 + +使用‘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) +``` + +## 在 PDF 文件中创建 PDF 文档链接 + +### 使用 GoToRemoteAction + +此代码片段演示了如何使用 Python PDF 库向 PDF 文档的特定页面添加链接注释。 + +1. 打开 PDF 文档 +1. 选择文档的第二页(索引 1) +1. 创建链接注释: +1. 位于坐标 (10, 580, 120, 600) 处 +1. 颜色为绿色 +1. 在第一页链接到 'sample.pdf' +1. 将链接注释添加到页面 +1. 将修改后的文档保存到输出文件路径 + +使用 'GoToRemoteAction' 创建 PDF 文档链接: + +```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) +``` + +### 使用 GoToAction + +此代码演示了如何使用 Aspose.PDF for Python 向 PDF 文档的特定页面添加链接注释。该链接显示为绿色、虚线边框的矩形,并允许用户在同一 PDF 中导航到另一页。要使用 'GoToAction' 创建 PDF 文档链接: + +```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) +``` + +### 应用 GoToURIAction + +下一个示例演示如何使用 Aspose.PDF for Python 向 PDF 文档添加链接批注。该链接在首页上显示为绿色可点击区域,点击后会通过 GoToURIAction 在网页浏览器中打开 Aspose.PDF for Python 文档。 + +此功能可用于在 PDF 中直接嵌入有用的外部参考、文档或支持链接。 + +1. 加载 PDF 文档。使用 ap.Document 打开现有的 PDF 文件。 +1. 访问第一页。使用 document.pages[1] 访问第一页(Aspose 使用基于 1 的索引)。 +1. 创建链接注释。创建一个 LinkAnnotation 对象,并使用 ap.Rectangle 指定可点击的矩形区域。 +1. 设置注释外观。使用 link.color = ap.Color.green 将注释的颜色设置为绿色。 +1. 分配一个 URI 操作。使用 GoToURIAction 将注释链接到外部 URL。 +1. 将注释添加到页面。将配置好的链接注释追加到第一页的注释集合中。 +1. 保存已修改的文档。将更新后的 PDF 文档保存到指定的输出路径。 + +```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) +``` + +## 相关链接主题 + +- [在 Python 中处理 PDF 链接](/pdf/zh/python-net/links/) +- [在 Python 中从 PDF 提取链接](/pdf/zh/python-net/extract-links/) +- [使用 Python 更新 PDF 中的链接](/pdf/zh/python-net/update-links/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md b/zh/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md new file mode 100644 index 0000000000..b6e5c8561c --- /dev/null +++ b/zh/python-net/advanced-operations/navigation-and-interaction/links/extract-links/_index.md @@ -0,0 +1,92 @@ +--- +title: 在 Python 中提取 PDF 链接 +linktitle: 提取链接 +type: docs +weight: 30 +url: /zh/python-net/extract-links/ +description: 了解如何在 Python 中从 PDF 文档中提取链接注释和超链接。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何从 PDF 中提取链接 +Abstract: Aspose.PDF for Python via .NET 关于提取链接的指南阐述了如何使用 Python 以编程方式从 PDF 文档中检索超链接注释。文档包含实用的代码示例,并强调此功能可用于链接审计、导航分析或构建交互式文档特性等任务。无论是处理单页 PDF 还是大批量文档,此指南都提供了清晰高效的超链接提取方法。 +--- + +## 从 PDF 文件中提取链接 + +此示例演示如何使用 Aspose.PDF for Python 遍历 PDF 首页上的所有链接注释。它会过滤注释以识别类型为 LinkAnnotation 的注释,安全地进行类型转换,然后打印它们的页面索引和在页面上的矩形位置。 + +这可用于调试、分析或对 PDF 中现有链接注释进行自动更新。 + +1. 加载 PDF 文档。使用 ap.Document(path_infile) 打开文件。 +1. 访问第一页的注释。使用 document.pages[1].annotations 检索所有注释。 +1. 仅过滤 LinkAnnotation 类型。检查每个 annotation 的 annotation_type。 +1. 对 LinkAnnotation 进行类型转换和处理。使用 is_assignable() 和 cast() 确保安全访问 LinkAnnotation 属性。 +1. 打印注释详情。输出每个链接的页面索引和矩形(位置)。 + +```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}") +``` + +## 从 PDF 文件中提取超链接 + +此代码演示了如何使用 Aspose.PDF for Python 从 PDF 文档的第一页提取所有 LinkAnnotation 对象,然后识别其中包含 GoToURIAction 的对象。对于每个此类链接,它会打印出页面索引和目标 URI。 + +这对于以下任务很有用: + +- 审计 PDF 中的外部链接 +- 提取文档或支持 URL +- 检测失效或过时的超链接 + +1. 加载 PDF 文档。使用 ap.Document 打开文件。 +1. 获取第一页中的所有链接注释。过滤注释,仅保留类型为 AnnotationType.LINK 的注释。 +1. 进行类型检查并转换为 LinkAnnotation。确保每个注释确实是 LinkAnnotation 后再访问其属性。 +1. 检查链接的动作类型。过滤出使用 GoToURIAction 的链接(即指向网页 URL 的链接)。 +1. 提取并打印 URI 和页面索引。使用 .uri 获取外部链接,使用 .page_index 获取上下文。 + +```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}") +``` + +## 相关链接主题 + +- [在 Python 中处理 PDF 链接](/pdf/zh/python-net/links/) +- [在 Python 中创建 PDF 链接](/pdf/zh/python-net/create-links/) +- [使用 Python 更新 PDF 中的链接](/pdf/zh/python-net/update-links/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/navigation-and-interaction/links/update-links/_index.md b/zh/python-net/advanced-operations/navigation-and-interaction/links/update-links/_index.md new file mode 100644 index 0000000000..56cd2c572a --- /dev/null +++ b/zh/python-net/advanced-operations/navigation-and-interaction/links/update-links/_index.md @@ -0,0 +1,114 @@ +--- +title: 在 Python 中更新 PDF 链接 +linktitle: 更新链接 +type: docs +weight: 20 +url: /zh/python-net/update-links/ +description: 了解如何在 Python 中更新 PDF 链接的外观和目标。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何在 PDF 中更新链接 +Abstract: Aspose.PDF for Python via .NET 的链接更新指南通过 Python 带领开发人员完成在 PDF 文档中修改超链接行为的过程。它说明了如何更改链接目标,以指向特定页面、外部网站或其他 PDF 文件。文档还涵盖了如何调整链接注释的外观,包括文本颜色,并为每种情况提供实用的代码示例。无论是纠正过时的 URL 还是提升导航体验,此资源都提供了一个清晰且高效的编程方式来管理链接。 +--- + +## 更新 LinkAnnotation 文本颜色 + +此示例演示如何使用 Aspose.PDF for Python 检测 PDF 第1页上的所有链接注释,然后通过将其字体颜色更改为红色来突出显示每个链接附近的文本。它使用 TextFragmentAbsorber,并在每个链接矩形周围稍微扩展的区域内查找并修改附近的文本。 + +此可用于: + +- 在文档中直观地标记链接 +- 通过强调链接内容来提升可访问性 +- 在审阅或导出之前对 PDF 文件进行预处理 + +对于这些链接注释,脚本检索其矩形边界并略微扩大该区域以包含附近的文本,从而实现更广泛的视觉识别。随后,它在此扩展区域上应用 TextFragmentAbsorber,以提取位于其中的任何文本片段。通过将这些捕获的片段的字体颜色更改为红色,对周围文本进行标记,以强调和审阅。应用所有这些更新后,修改后的文档保存到输出路径,保留已高亮的注释及其关联的文本。 + +```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) +``` + +## 更新边框 + +脚本聚焦于文档的第一页,并过滤掉所有注释,仅选择 LINK 类型的注释——这些通常代表交互元素,例如超链接或导航触发器。对于每个此类链接注释,代码将其强制转换为 LinkAnnotation 类型,并将其颜色属性更新为红色,以视觉上突出显示,使其在其他内容中脱颖而出。所有链接注释均被修改后,更新后的文档被保存到定义的输出位置,保留新的样式。 + +```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) +``` + +## 更新 Web 目标 + +一旦路径就绪,原始文档将使用 Aspose.PDF 库加载,使其内容可供修改。脚本随后聚焦于文档的首页,过滤掉所有注释,仅选择链接类型的注释,这类注释通常代表可点击的区域或超链接。为了避免类型错误并确保安全处理,脚本使用 is_assignable 检查每个注释,然后将其转换为相应的 LinkAnnotation 类型。如果该链接关联了 GoToURIAction,即指向网页地址,脚本会更新该 URI,以将用户重定向至 "https://www.aspose.com". 最后,在应用所有所需更改后,修改后的文档会保存到指定的输出路径。 + +```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) +``` + +## 相关链接主题 + +- [在 Python 中处理 PDF 链接](/pdf/zh/python-net/links/) +- [在 Python 中创建 PDF 链接](/pdf/zh/python-net/create-links/) +- [在 Python 中提取 PDF 链接](/pdf/zh/python-net/extract-links/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/pdf-file-metadata/_index.md b/zh/python-net/advanced-operations/pdf-file-metadata/_index.md new file mode 100644 index 0000000000..6e25c22a7f --- /dev/null +++ b/zh/python-net/advanced-operations/pdf-file-metadata/_index.md @@ -0,0 +1,147 @@ +--- +title: 在 Python 中处理 PDF 文件元数据 +linktitle: PDF 文件元数据 +type: docs +weight: 200 +url: /zh/python-net/pdf-file-metadata/ +description: 学习如何在 Python 中使用 Aspose.PDF 提取、更新和管理 PDF 文件元数据及 XMP 属性。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中获取和设置 PDF 文档信息及 XMP 元数据 +Abstract: 本文解释了如何在 Aspose.PDF for Python via .NET 中处理 PDF 元数据。了解如何读取文档信息,如作者、标题和关键字,更新文件属性,设置 XMP 元数据字段,以及在 Python 中为 PDF 文件注册自定义元数据前缀。 +--- + +当您需要检查文档属性、更新 PDF 文件信息以用于搜索或编目,或在 Python 中以编程方式管理 XMP 元数据时,请使用本指南。 + +## 获取 PDF 文件信息 + +此代码片段演示了如何使用 Aspose.PDF for Python via .NET 从 PDF 文档中提取元数据。通过访问 Document 对象的 info 属性,它检索关键信息,如作者、创建日期、关键字、修改日期、主题和标题。此功能对于需要文档编目、搜索优化或文档属性验证的应用程序至关重要。 + +1. 使用 Document 类打开 PDF 文件 +1. 通过 info 属性检索文档的元数据 +1. 显示元数据信息。打印所需的元数据字段 + +```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}") +``` + +## 设置 PDF 文件信息 + +Aspose.PDF for Python via .NET 允许您为 PDF 设置特定文件信息,例如作者、创建日期、主题和标题。要设置这些信息: + +1. 使用 Document 类打开 PDF 文件。 +1. 创建一个 [DocumentInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/documentinfo/) 对象并设置所需的元数据属性。 +1. 使用 save 方法将更改保存为一个新 PDF 文件。 + +下面的代码片段展示了如何设置 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) +``` + +## 在 PDF 文件中设置 XMP 元数据 + +此代码片段演示了如何使用 Aspose.PDF for Python via .NET 以编程方式设置或更新 PDF 文档中的 XMP 元数据。通过修改诸如 xmp:CreateDate、xmp:Nickname 和自定义字段等属性,您可以将标准化的元数据嵌入 PDF 文件中。此方法特别适用于提升文档组织、方便搜索以及将关键信息直接嵌入文件中。 + +Aspose.PDF 允许您在 PDF 文件中设置元数据。要设置元数据: + +1. 使用以下方式打开 PDF 文件 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类。 +1. 通过为特定键分配值来修改 XMP 元数据。 +1. 保存已更新的 PDF 文档。 + +以下代码片段展示了如何在 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) +``` + +## 插入带前缀的元数据 + +一些开发人员需要使用前缀创建新的元数据命名空间。下面的代码片段展示了如何插入带前缀的元数据。 + +```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) +``` + +## 相关主题 + +- [Python中的高级PDF操作](/pdf/zh/python-net/advanced-operations/) +- [使用 Python 处理 PDF 文档](/pdf/zh/python-net/working-with-documents/) +- [在 Python 中处理 PDF 附件](/pdf/zh/python-net/attachments/) +- [在 Python 中比较 PDF 文档](/pdf/zh/python-net/compare-pdf-documents/) diff --git a/zh/python-net/advanced-operations/securing-and-signing/_index.md b/zh/python-net/advanced-operations/securing-and-signing/_index.md new file mode 100644 index 0000000000..370e527b42 --- /dev/null +++ b/zh/python-net/advanced-operations/securing-and-signing/_index.md @@ -0,0 +1,41 @@ +--- +title: 在 Python 中保护和签署 PDF 文件 +linktitle: 在 PDF 中的保护和签署 +type: docs +weight: 210 +url: /zh/python-net/securing-and-signing/ +description: 了解如何在 Python 中签署、加密、解密和保护 PDF 文件,包括数字签名、智能卡和文档权限。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中签署、加密、解密和保护 PDF 文档 +Abstract: 本节解释如何使用 Aspose.PDF for Python via .NET 来保护和签署 PDF 文档。了解如何应用数字签名、使用智能卡和证书、提取签名信息,以及在 Python 中管理 PDF 加密、密码和访问权限。 +--- + +本节解释如何使用 Python 库安全地对 PDF 文档应用数字签名。虽然电子签名和数字签名有时被交替使用,但它们并不相同。数字签名是由 [证书颁发机构](https://en.wikipedia.org/wiki/Certificate_authority), 提供一个可信的印章,保护文档免受篡改。相比之下,电子签名通常用于表示个人签署文件的意图,但没有相同级别的安全验证。 + +当您需要保护 PDF 内容、控制文档权限、验证信任或在 Python 工作流中应用基于证书的签名时,请使用这些指南。 + +## 已涵盖的安全和签名任务 + +Aspose.PDF 支持数字签名: + +- PKCS1 与 RSA 签名算法和 SHA-1 摘要。 +- PKCS7 使用 RSA 签名算法和 SHA-1 摘要。 +- PKCS7 分离式使用 DSA、RSA 和 ECDSA 签名算法。支持的摘要算法取决于签名算法。 +- 时间戳签名。 + +PKCS7 分离式的摘要算法: + +- 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。 + +建议避免使用 SHA-1 摘要算法的数字签名,因为它不安全。 + +- [对 PDF 文件进行数字签名](/pdf/zh/python-net/digitally-sign-pdf-file/) +- [设置权限、加密和解密 PDF 文件](/pdf/zh/python-net/set-privileges-encrypt-and-decrypt-pdf-file/) +- [提取图像和签名信息](/pdf/zh/python-net/extract-image-and-signature-information/) +- [使用智能卡签署 PDF 文档](/pdf/zh/python-net/sign-pdf-document-from-smart-card/) diff --git a/zh/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md b/zh/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md new file mode 100644 index 0000000000..026382a542 --- /dev/null +++ b/zh/python-net/advanced-operations/securing-and-signing/digitally-sign-pdf-file/_index.md @@ -0,0 +1,232 @@ +--- +title: 在 Python 中添加数字签名或对 PDF 进行数字签名 +linktitle: 对 PDF 进行数字签名 +type: docs +weight: 10 +url: /zh/python-net/digitally-sign-pdf-file/ +description: 了解如何在 Python 中对 PDF 文档进行数字签名、添加时间戳以及验证签名。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 对 PDF 文件进行数字签名 +Abstract: 本指南说明了如何使用 Aspose.PDF for Python via .NET 对 PDF 文档进行数字签名。它详细介绍了应用标准和高级数字签名的过程,使用证书(PFX 和 PKCS#12),以及自定义签名外观和行为。文档包含代码示例,演示如何对现有 PDF 进行签名、添加时间戳以及验证签名有效性。这使开发人员能够在其 Python 应用程序中确保文档的真实性、完整性,并符合数字签名标准。 +--- + +## 使用数字签名签署 PDF + +```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) +``` + +一个 **PKCS#7 分离签名** 为文档添加数字签名,而不将内容嵌入签名块中。 + +当您需要对 PDF 文件使用基于证书的签名、验证签名有效性或向已签名文档添加可信时间戳时,请使用这些示例。 + +下面的示例使用 PKCS#7 分离数字签名对 PDF 文档进行签署,将签名应用于首页的指定矩形区域。 + +```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) +``` + +**验证 PDF 文档中的所有数字签名** + +1. 创建一个 PdfFileSignature 实例,使您能够在 PDF 中处理签名。 +1. 获取签名名称列表 `get_signature_names(True)`. +1. 检查列表中的第一个签名 `verify_signature` 以符合指定的证书。 + +```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") +``` + +**使用公钥证书文件验证签名** + +```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)) +``` + +**使用从文件中提取的证书验证签名** + +```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) +``` + +**验证已启用证书链验证的签名** + +```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}") +``` + +## 为数字签名添加时间戳 + +### 如何为 PDF 添加带时间戳的数字签名 + +Aspose.PDF for Python 支持使用时间戳服务器或 Web 服务对 PDF 进行数字签名。 + +为了完成此要求, [时间戳设置](https://reference.aspose.com/pdf/python-net/aspose.pdf/timestampsettings/) 类已添加到 Aspose.PDF 命名空间。请查看以下获取时间戳并将其添加到 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) +``` + +## 使用 ECDSA 对 PDF 文档进行签名 + +使用 ECDSA(椭圆曲线数字签名算法)对 PDF 文档进行签名涉及利用椭圆曲线密码学生成数字签名。 + +上面的代码片段演示了如何使用 Aspose.PDF for Python 对 PDF 文档应用 PKCS#7 分离数字签名。通过加载文档、配置签名外观和安全设置并保存结果,此示例展示了一个完整且可靠的 PDF 文件数字签署工作流。 + +此方法通过在首页嵌入安全且可验证的签名,确保文档的真实性和完整性。使用 SHA-256 作为摘要算法符合现代密码学标准,而能够控制签名位置则为可见的批准标记提供了灵活性。 + +```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) +``` + +**在 PDF 文档中验证 ECDSA 签名** + +```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") +``` + +## 相关安全主题 + +- [在 Python 中对 PDF 文件进行安全保护和签名](/pdf/zh/python-net/securing-and-signing/) +- [在 Python 中提取图像和签名信息](/pdf/zh/python-net/extract-image-and-signature-information/) +- [在 Python 中使用智能卡签署 PDF 文档](/pdf/zh/python-net/sign-pdf-document-from-smart-card/) +- [在 Python 中加密和解密 PDF 文件](/pdf/zh/python-net/set-privileges-encrypt-and-decrypt-pdf-file/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md b/zh/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md new file mode 100644 index 0000000000..97b1fb578c --- /dev/null +++ b/zh/python-net/advanced-operations/securing-and-signing/extract-signature-info/_index.md @@ -0,0 +1,170 @@ +--- +title: 在 Python 中从 PDF 提取签名信息 +linktitle: 从签名中提取详细信息 +type: docs +weight: 20 +url: /zh/python-net/extract-image-and-signature-information/ +description: 学习如何在 Python 中从 PDF 文件中提取签名图像、证书和数字签名详细信息。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中从 PDF 中提取签名图像和证书详细信息。 +Abstract: 本文介绍了如何使用 Aspose.PDF for Python 从 PDF 文档中提取图像和数字签名信息。了解如何检索签名图像、提取证书数据、检查签名算法以及检测已签名 PDF 文件中的受损签名。 +--- + +## 从签名字段提取图像 + +Aspose.PDF for Python via .NET 让您检索嵌入在 a 中的可视图像 [签名字段](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/signaturefield/). 当您需要显示或归档签名外观而无需渲染完整 PDF 时,这很有用。 + +下面的示例遍历所有表单字段,查找每一个 `SignatureField`, 并将其图像保存为 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) +``` + +## 读取签名算法详情 + +使用 `PdfFileSignature.get_signatures_info()` 读取文档中每个签名的加密元数据——包括摘要算法、算法类型、加密标准和签名名称: + +```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) +``` + +## 从签名字段中提取数字证书 + +使用 [提取证书](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/signaturefield/#methods) 方法在 a `SignatureField` 检索嵌入的证书为字节流并将其保存到磁盘以进行外部验证: + +```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 +``` + +## 使用 PdfFileSignature 外观提取证书 + +`PdfFileSignature.try_extract_certificate()` 提供了一种通过签名名称检索证书的替代方法。以下示例遍历所有签名名称,并尝试对每个进行提取: + +```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") +``` + +## 验证外部数字签名 + +要确认文档在签名后未被修改,请使用以下方式验证每个外部签名 `PdfFileSignature.verify_signature()`. 下面的示例会在任何验证失败的签名时抛出异常: + +```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") +``` + +## 检测受损的签名 + +`SignaturesCompromiseDetector` 检查文档中的任何数字签名是否因后续更改而失效。 在法律、金融或合规工作流中使用此功能,以确保文档完整性得到保证。 + +下面的示例检查受损的签名,并报告它们的名称以及文档的整体签名覆盖率: + +```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) +``` + +## 相关安全主题 + +- [在 Python 中对 PDF 文件进行安全保护和签名](/pdf/zh/python-net/securing-and-signing/) +- [在 Python 中对 PDF 文件进行数字签名](/pdf/zh/python-net/digitally-sign-pdf-file/) +- [在 Python 中使用智能卡签署 PDF 文档](/pdf/zh/python-net/sign-pdf-document-from-smart-card/) +- [在 Python 中加密和解密 PDF 文件](/pdf/zh/python-net/set-privileges-encrypt-and-decrypt-pdf-file/) diff --git a/zh/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md b/zh/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md new file mode 100644 index 0000000000..c784b8dc99 --- /dev/null +++ b/zh/python-net/advanced-operations/securing-and-signing/set-privileges/_index.md @@ -0,0 +1,228 @@ +--- +title: 在 Python 中加密和解密 PDF 文件 +linktitle: 加密和解密 PDF 文件 +type: docs +weight: 70 +url: /zh/python-net/set-privileges-encrypt-and-decrypt-pdf-file/ +description: 了解如何在 Python 中设置 PDF 权限、加密文件、解密受保护的 PDF,以及更改密码。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中设置 PDF 权限并管理加密。 +Abstract: 本文档页说明了如何使用 Aspose.PDF for Python 设置文档权限、应用加密以及解密 PDF 文件。它指导开发人员配置用户密码和所有者密码,定义访问限制(例如打印、复制或编辑)。代码示例展示了如何在 Python 应用程序中有效保护敏感内容并管理 PDF 安全,确保受控访问和数据机密性。 +--- + +管理文档安全在处理敏感或业务关键内容时至关重要。Aspose.PDF for Python via .NET 提供了一个强大的 API,用于以编程方式应用加密、通过权限控制访问以及解密受保护的 PDF 文件。 + +本文向 Python 开发者展示如何在 PDF 工作流中通过实际示例设置权限、应用和移除加密、更改密码以及检测保护状态。 + +Aspose.PDF for Python via .NET 为开发者提供了对 PDF 安全性的完全控制: + +**设置特权** - 使用权限进行细粒度访问控制。 +**Encrypt File** - 使用自定义密码应用 AES 或 RC4 加密。 +**解密文件** - 使用所有者密码移除安全保护。 +**更改密码** - 在不更改内容的情况下轮换或更新凭据。 +**检查安全性** - 检测加密状态或所需的密码类型。 + +当您需要使用密码保护 PDF 文档、限制打印或复制、旋转凭据,或检查文档是否已加密时,请使用此页面。 + +## 为现有 PDF 文件设置权限 + +您可以通过分配用户密码和所有者密码以及访问权限,限制或允许特定操作(例如,打印、复制、填写表单)。 + +```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) +``` + +## 使用不同的加密类型和算法加密 PDF 文件 + +对 PDF 加密可确保只有具有有效凭据的用户才能打开或修改文件。 + +>关键术语: + +- 用户密码。打开文档时需要。 + +- 所有者密码。更改权限或移除加密时需要。 + +- 密钥大小。 在现代工作流中使用 AE_SX128 以获得最大安全性。 + +下面的代码片段向您展示如何加密 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) +``` + +## 使用所有者密码解密 PDF 文件 + +要移除密码保护并恢复完全访问权限: + +1. 使用正确的密码加载加密的 PDF('password' 是用户密码或所有者密码)。 +1. 删除文档中的所有密码保护和加密设置。 +1. 将现在未受保护的 PDF 保存到指定的输出文件。 + +```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) +``` + +## 使用公钥证书对 PDF 进行加密和解密 + +```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")) +``` + +## 更改 PDF 文件的密码 + +更新 PDF 文档的安全凭证(用户密码和所有者密码),同时保持其内容和结构不变。 + +1. 使用现有的所有者密码('owner')打开 PDF,这提供了完全访问权限,包括更改安全设置的权限。 +1. 用新的用户密码('newuser')和新的所有者密码('newowner')替换旧密码。 +1. 使用更新的密码设置保存 PDF。 + +```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) +``` + +## 如何 - 确定源 PDF 是否受密码保护 + +### 从数组中确定正确的密码 + +在某些场景中,您可能需要从潜在候选密码列表中识别正确的密码,以访问受保护的 PDF。下面的代码片段演示了如何检查 PDF 文件是否受密码保护,然后使用 Aspose.PDF for Python via .NET 通过遍历预定义的密码列表尝试解锁它。 + +该过程包括: + +1. 使用 PdfFileInfo 检测 PDF 是否被加密。 +1. 尝试使用 ap.Document() 用每个密码打开 PDF。 +1. 如果成功,它会打印页数。 +1. 如果不是,它会捕获异常并报告密码错误。 + +```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") +``` + +## 相关安全主题 + +- [在 Python 中对 PDF 文件进行安全保护和签名](/pdf/zh/python-net/securing-and-signing/) +- [在 Python 中对 PDF 文件进行数字签名](/pdf/zh/python-net/digitally-sign-pdf-file/) +- [在 Python 中提取 PDF 的签名信息](/pdf/zh/python-net/extract-image-and-signature-information/) +- [在 Python 中使用智能卡签署 PDF 文档](/pdf/zh/python-net/sign-pdf-document-from-smart-card/) + diff --git a/zh/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md b/zh/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md new file mode 100644 index 0000000000..8584d71179 --- /dev/null +++ b/zh/python-net/advanced-operations/securing-and-signing/sign-pdf-document-from-smart-card/_index.md @@ -0,0 +1,131 @@ +--- +title: 在 Python 中使用智能卡签署 PDF 文档 +linktitle: 使用智能卡进行 PDF 签名 +type: docs +weight: 30 +url: /zh/python-net/sign-pdf-document-from-smart-card/ +description: 了解如何在 Python 中使用智能卡和外部证书签署 PDF 文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 从智能卡签署 PDF 文档 +Abstract: 本指南解释了如何使用 Aspose.PDF for Python via .NET 通过智能卡对 PDF 文档进行数字签名。它演示了如何通过 Windows 证书存储访问存储在硬件设备(如 USB 令牌或智能卡)中的证书,并将其用于签署 PDF 文件。文档包含代码示例,展示如何定位相应的证书、配置签名属性以及将数字签名嵌入 PDF 中。这实现了符合数字签名标准的安全硬件支持签名,适用于高信任的企业和法律工作流。 +--- + +Aspose.PDF 提供强大的功能,用于集成可视化和加密签名组件,确保数字签名 PDF 文档的真实性和专业呈现。 + +当您的签名过程依赖于存储在硬件支持设备(如智能卡、USB 令牌或受管理的证书存储)中的证书时,请使用此工作流。 + +## 使用签名字段进行智能卡签名 + +本示例演示如何使用 Aspose.PDF for Python 通过外部证书对 PDF 文档进行数字签名,并应用自定义签名外观图像: + +1. 打开 PDF 文档。 +1. 创建 PdfFileSignature 对象并将其绑定到文档。 +1. 使用自定义方法检索本地数字证书 `get_local_certificate()`. +1. 基于所选证书设置 ExternalSignature。 +1. 应用自定义签名外观图像(例如,公司徽标或手写签名)。 +1. 在文档的首页进行数字签名,并附加指定的元数据(原因、联系方式、位置)。 +1. 将已签名的文档保存到新的输出文件。 + +此方法非常适用于需要通过外部证书以编程方式进行签名的情况——例如硬件令牌、证书存储或受信任的提供者——并以个性化的视觉布局呈现。 + +以下是使用智能卡签署 PDF 文档的代码片段: + +```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) +``` + +## 验证数字签名 + +此代码片段演示了如何使用 Aspose.PDF for Python 验证 PDF 文档中的数字签名: + +1. 打开 PDF 文件。 +1. 创建一个 'PdfFileSignature object' 并将其绑定到文档。 +1. 使用 'get_signature_names()' 检索所有签名字段名称的列表。 +1. 通过 'verify_signature()' 遍历每个签名并验证其有效性。 +1. 如果任何签名验证失败,则抛出异常。 + +```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") +``` + +## 使用外部证书签名 + +此代码片段演示了如何使用 Aspose.PDF for Python 并结合外部证书,在 PDF 文档中添加并签署数字签名字段: + +1. 以二进制流打开 PDF 文件。 +1. 创建 SignatureField 并将其放置在文档的第一页的指定位置。 +1. 使用自定义方法检索本地数字证书 `get_local_certificate()`. +1. 设置 ExternalSignature,并提供权限、原因和联系信息等元数据。 +1. 为签名字段分配唯一的字段名称 (partial_name = "sig1"). +1. 在 PDF 的表单字段中添加签名字段。 +1. 使用外部证书对字段进行签名。 +1. 将已签名的文档保存到输出文件。 + +```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) +``` + +## 相关安全主题 + +- [在 Python 中对 PDF 文件进行安全保护和签名](/pdf/zh/python-net/securing-and-signing/) +- [在 Python 中对 PDF 文件进行数字签名](/pdf/zh/python-net/digitally-sign-pdf-file/) +- [在 Python 中提取 PDF 的签名信息](/pdf/zh/python-net/extract-image-and-signature-information/) +- [在 Python 中加密和解密 PDF 文件](/pdf/zh/python-net/set-privileges-encrypt-and-decrypt-pdf-file/) + diff --git a/zh/python-net/advanced-operations/working-with-documents/_index.md b/zh/python-net/advanced-operations/working-with-documents/_index.md index c671da640c..3e3d73e306 100644 --- a/zh/python-net/advanced-operations/working-with-documents/_index.md +++ b/zh/python-net/advanced-operations/working-with-documents/_index.md @@ -1,157 +1,33 @@ --- -title: 使用Python处理PDF文档 +title: 在 Python 中使用 PDF 文档 linktitle: 处理文档 type: docs weight: 10 url: /zh/python-net/working-with-documents/ -description: 本文向您描述了使用Aspose.PDF for Python via .NET库可以对文档进行哪些操作。 -lastmod: "2023-04-12" +description: 学习如何在 Python 中创建、格式化、操作、优化、合并、拆分和管理 PDF 文档。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中创建、格式化、合并、拆分和优化 PDF 文档 +Abstract: 本节介绍如何使用 Aspose.PDF for Python via .NET 处理 PDF 文档。学习如何创建 PDF 文件、格式化文档属性、操作内容结构、优化文件大小、合并和拆分 PDF,以及在 Python 工作流中管理可选内容层。 --- - +PDF 文件旨在安全且高质量地交换文档,无论使用哪种软件或操作系统查看。它们可以在许多设备和操作系统上打开和查看,包括电脑、平板和智能手机。如今,此类文档可能包含图像、表格、各种交互元素等。 -PDF 文件旨在安全、高质量地交换文档,无论使用何种软件或操作系统查看它们。它们可以在许多设备和操作系统上打开和查看,包括计算机、平板电脑和智能手机。如今,此类文档可能包含图像、表格、各种交互元素等。 +PDF 文档可以查看和打印,但并不总是容易编辑。然而,**Aspose.PDF for Python via .NET** 将帮助您应对处理 PDF 时最困难的任务。 -PDF 文档可以查看和打印,但不总是容易编辑。然而,**Aspose.PDF for Python Library** 将帮助您应对处理 PDF 时最困难的任务。 +当您需要在 Python 中处理整篇文档的 PDF 工作流时,请使用本节,例如创建文件、验证标准、优化大小、合并多个 PDF,或将大型文档拆分为更小的文件。 + +## 涉及的文档任务 您可以执行以下操作: - [创建 PDF 文档](/pdf/zh/python-net/create-pdf-document/) - 创建一个简单的 PDF 文档。 -- [格式化 PDF 文档](/pdf/zh/python-net/formatting-pdf-document/) - 创建文档,获取和设置文档属性,嵌入字体以及其他 PDF 文件操作。 - -- [操作 PDF 文档](/pdf/zh/python-net/manipulate-pdf-document/) - 验证 PDF 文档以符合 PDF A 标准,处理目录,设置 PDF 到期日期等。 -- [优化 PDF](/pdf/zh/python-net/optimize-pdf/) - 优化页面内容,优化文件大小,移除未使用的对象,压缩所有图像以成功优化文档。 -- [合并 PDF](/pdf/zh/python-net/merge-pdf-documents/) - 使用 Python 将多个 PDF 文件合并为一个 PDF 文档。 +- [格式化 PDF 文档](/pdf/zh/python-net/formatting-pdf-document/) - 创建文档、获取和设置文档属性、嵌入字体以及对 PDF 文件的其他操作。 +- [操作 PDF 文档](/pdf/zh/python-net/manipulate-pdf-document/) - 验证 PDF 文档是否符合 PDF A 标准,使用目录(TOC),设置 PDF 失效日期,等等。 +- [优化 PDF](/pdf/zh/python-net/optimize-pdf/) - 优化页面内容,优化文件大小,删除未使用的对象,压缩所有图像,以实现成功的文档优化。 +- [合并 PDF](/pdf/zh/python-net/merge-pdf-documents/) - 使用 Python 将多个 PDF 文件合并为单个 PDF 文档。 - [拆分 PDF](/pdf/zh/python-net/split-document/) - 在您的 Python 应用程序中将 PDF 页面拆分为单独的 PDF 文件。 -- [处理标题](/pdf/zh/python-net/working-with-headings/) - 您可以使用 Python 在 PDF 文档的标题中创建编号。 - - \ No newline at end of file +- [使用标题](/pdf/zh/python-net/working-with-headings/) - 您可以在 PDF 文档的标题中使用 Python 创建编号。 diff --git a/zh/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md b/zh/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md index 0f4f4e4867..323cea6784 100644 --- a/zh/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md +++ b/zh/python-net/advanced-operations/working-with-documents/create-pdf-document/_index.md @@ -1,103 +1,94 @@ --- -title: 如何使用 Python 创建 PDF +title: 在 Python 中创建 PDF 文件 linktitle: 创建 PDF 文档 type: docs weight: 10 url: /zh/python-net/create-pdf-document/ -description: 使用 Aspose.PDF for Python via .NET 创建和格式化 PDF 文档。 -lastmod: "2023-04-12" +description: 了解如何使用 Aspose.PDF for Python via .NET 在 Python 中创建 PDF 文件并构建可搜索的 PDF。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 创建 PDF 文件 +Abstract: Aspose.PDF for Python via .NET 是一个多功能 API,专为开发人员在针对 .NET 框架的 Python 应用程序中操作 PDF 文件而设计。它使用户能够轻松创建、加载、修改和转换 PDF 文档。本文提供了使用 Aspose.PDF 创建简单 PDF 文件的循序指导。该过程包括初始化一个 `Document` 对象、向文档添加 `Page`、在页面的段落中插入 `TextFragment`,并将文件保存为 PDF。文中附带的 Python 代码片段演示了这些步骤,创建了一个包含文本 “Hello World!” 的 PDF 文档。该 API 通过极少的代码简化了 PDF 处理,提高了在 .NET 环境下进行 PDF 开发的生产力。 --- - - - -**Aspose.PDF for Python via .NET** 是一个 PDF 操作 API,允许开发人员通过 .NET 应用程序使用 Python 直接创建、加载、修改和转换 PDF 文件,只需几行代码。 + +**Aspose.PDF for Python via .NET** 是一个 PDF 操作 API,允许开发人员仅用几行代码即可直接从 Python 为 .NET 应用程序创建、加载、修改和转换 PDF 文件。 + +当您需要从头生成新的 PDF 文件或将 OCR 输出转换为可搜索的 PDF 文档时,请使用这些示例。 ## 如何创建简单的 PDF 文件 -要使用 Aspose.PDF 通过 .NET 使用 Python 创建 PDF,可以按照以下步骤操作: +要使用 Python via .NET 与 Aspose.PDF 创建 PDF,您可以按照以下步骤操作: -1. 创建 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类的对象 -1. 向 Document 对象的 [pages](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties) 集合中添加一个 [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 对象 -1. 向页面的 [paragraphs](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) 集合中添加 [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/) +1. 创建一个对象 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类 +1. 添加一个 [页面](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 对象到 [页面](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties) Document 对象的集合 +1. 添加 [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/) 到 [段落](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) 页面集合 1. 保存生成的 PDF 文档 ```python +import sys +from os import path +import aspose.pdf as ap - import aspose.pdf as ap - - # 初始化文档对象 +def create_new_document(output_pdf): + """Create a simple PDF with a single “Hello World!” page.""" document = ap.Document() - # 添加页面 page = document.pages.add() - # 向新页面添加文本 page.paragraphs.add(ap.text.TextFragment("Hello World!")) - # 保存更新后的 PDF document.save(output_pdf) -``` \ No newline at end of file +``` + +## 如何创建可搜索的 PDF 文档 + +Aspose.PDF for Python via .NET 允许创建和操作现有的 PDF 文档。向 PDF 文件添加 Text 元素时,生成的 PDF 是可搜索的。然而,将包含文本的图像转换为 PDF 文件时,生成的 PDF 内容不可搜索。作为变通方法,我们可以对生成的文件应用 OCR,以使其可搜索。 + +以下是完成此需求的完整代码: + +1. 使用 'ap.Document' 加载 PDF。 +1. 配置渲染分辨率。 +1. 使用 'PngDevice.process' 将选定的 PDF 页面转换为图像。 +1. 对生成的图像运行 OCR。 +1. 从 OCR 输出创建一个新 PDF。 +1. 保存可搜索的 PDF。 + +```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) +``` + +## 相关文档主题 + +- [使用 Python 处理 PDF 文档](/pdf/zh/python-net/working-with-documents/) +- [在 Python 中格式化 PDF 文档](/pdf/zh/python-net/formatting-pdf-document/) +- [在 Python 中操作 PDF 文档](/pdf/zh/python-net/manipulate-pdf-document/) +- [在 Python 中优化 PDF 文件](/pdf/zh/python-net/optimize-pdf/) + diff --git a/zh/python-net/advanced-operations/working-with-documents/create-pdf-document/example.png b/zh/python-net/advanced-operations/working-with-documents/create-pdf-document/example.png new file mode 100644 index 0000000000..67f77f8bfa Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-documents/create-pdf-document/example.png differ diff --git a/zh/python-net/advanced-operations/working-with-documents/formatting-pdf-document/_index.md b/zh/python-net/advanced-operations/working-with-documents/formatting-pdf-document/_index.md index 3c68a2db71..d274fb264b 100644 --- a/zh/python-net/advanced-operations/working-with-documents/formatting-pdf-document/_index.md +++ b/zh/python-net/advanced-operations/working-with-documents/formatting-pdf-document/_index.md @@ -1,390 +1,256 @@ --- -title: 使用Python格式化PDF文档 -linktitle: 格式化PDF文档 +title: 在 Python 中格式化 PDF 文档 +linktitle: 格式化 PDF 文档 type: docs weight: 11 url: /zh/python-net/formatting-pdf-document/ -description: 使用Aspose.PDF for Python via .NET创建和格式化PDF文档。使用下面的代码片段来解决您的任务。 -lastmod: "2023-04-12" +description: 了解如何在 Python 中格式化 PDF 文档、嵌入字体、控制查看器设置以及调整显示选项。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 格式化 PDF 文档 +Abstract: 本文提供了使用 Aspose.PDF 库在 Python 中操作和格式化 PDF 文档的全面指南。它涵盖了 PDF 定制的各个方面,包括设置文档窗口和页面显示属性,如居中窗口、阅读方向以及隐藏 UI 元素。文章解释了如何使用 `Document` 类以编程方式获取和设置这些属性。此外,文章还涉及字体管理,详细说明了如何将 Standard Type 1 字体和其他字体嵌入 PDF,确保文档的可移植性和跨系统的视觉一致性。它还重点介绍了设置默认字体名称、从 PDF 中检索所有字体以及使用 `FontSubsetStrategy` 增强字体嵌入的技术。进一步地,本文阐述了使用 `GoToAction` 类调整 PDF 文档的缩放比例,以及配置打印对话框预设属性,包括双面打印选项。每个章节均附有代码片段,提供实现这些功能的实用示例。 --- - +当您需要在 Python 生成的文档中控制 PDF 查看器行为、字体嵌入、默认显示设置或打印首选项时,此指南很有用。 ## 格式化 PDF 文档 ### 获取文档窗口和页面显示属性 -本主题帮助您了解如何获取文档窗口、查看器应用程序的属性,以及页面如何显示。要设置这些属性: +本主题帮助您了解如何获取文档窗口、查看器应用程序的属性以及页面的显示方式。要设置这些属性: -使用 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类打开 PDF 文件。现在,您可以设置 Document 对象的属性,例如 +使用以下方式打开 PDF 文件 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类。现在,您可以设置 Document 对象的属性,例如 -- CenterWindow – 将文档窗口置于屏幕中央。默认值:false。 -- Direction – 阅读顺序。这决定了页面并排显示时的布局方式。默认值:从左到右。 +- CenterWindow – 将文档窗口居中显示在屏幕上。默认值:false。 +- 方向 – 阅读顺序。这决定了页面在并排显示时的布局方式。默认:从左到右。 - DisplayDocTitle – 在文档窗口标题栏中显示文档标题。默认值:false(显示标题)。 -- HideMenuBar – 隐藏或显示文档窗口的菜单栏。默认值:false(显示菜单栏)。 -- HideToolBar – 隐藏或显示文档窗口的工具栏。默认值:false(显示工具栏)。 -- HideWindowUI – 隐藏或显示文档窗口元素,如滚动条。 - 默认值:false(显示UI元素)。 -- NonFullScreenPageMode – 文档在非全屏模式下的显示方式。 +- HideMenuBar – 隐藏或显示文档窗口的菜单栏。默认:false(菜单栏已显示)。 +- HideToolBar – 隐藏或显示文档窗口的工具栏。默认:false(工具栏已显示)。 +- HideWindowUI – 隐藏或显示文档窗口元素,例如滚动条。默认:false(显示 UI 元素)。 +- NonFullScreenPageMode – 文档在非全页模式下的显示方式。 - PageLayout – 页面布局。 - PageMode – 文档首次打开时的显示方式。选项包括显示缩略图、全屏、显示附件面板。 -下面的代码片段展示了如何使用 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类获取属性。 +以下代码片段展示了如何使用获取属性 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类。 ```python +import aspose.pdf as ap - import aspose.pdf as ap - # 打开文档 +def get_document_window(input_pdf, output_pdf): + """Print document window metadata for inspection.""" document = ap.Document(input_pdf) - # 获取不同的文档属性 - # 文档窗口的位置 - 默认值:false - print("CenterWindow :", document.center_window) - - # 主要阅读顺序;决定页面的位置 - # 并排显示时 - 默认值:L2R - print("Direction :", document.direction) - - # 窗口的标题栏是否应显示文档标题 - # 如果为false,则标题栏显示PDF文件名 - 默认值:false - print("DisplayDocTitle :", document.display_doc_title) - - # 是否调整文档窗口的大小以适应 - # 首次显示的页面 - 默认值:false - print("FitWindow :", document.fit_window) - - # 是否隐藏查看器应用程序的菜单栏 - 默认值:false - print("HideMenuBar :", document.hide_menubar) - - # 是否隐藏查看器应用程序的工具栏 - 默认值:false - print("HideToolBar :", document.hide_tool_bar) - - # 是否隐藏UI元素,如滚动条 - # 仅显示页面内容 - 默认值:false - print("HideWindowUI :", document.hide_window_ui) - - # 文档的页面模式。退出全屏模式时如何显示文档。 - print("NonFullScreenPageMode :", document.non_full_screen_page_mode) - - # 页面布局,即单页,一列 - print("PageLayout :", document.page_layout) - - # 文档打开时的显示方式 - # 即显示缩略图、全屏、显示附件面板 - print("pageMode :", document.page_mode) - + 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) ``` ### 设置文档窗口和页面显示属性 本主题说明如何设置文档窗口、查看器应用程序和页面显示的属性。要设置这些不同的属性: -1. 使用 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类打开 PDF 文件。 +1. 使用以下方式打开 PDF 文件 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类。 1. 设置 Document 对象的属性。 -1. 使用保存方法保存更新的 PDF 文件。 +1. 使用 save 方法保存已更新的 PDF 文件。 可用的属性有: -- CenterWindow -- Direction -- DisplayDocTitle -- FitWindow -- HideMenuBar -- HideToolBar -- HideWindowUI -- NonFullScreenPageMode -- PageLayout -- PageMode +- 居中窗口 +- 方向 +- 显示文档标题 +- 适应窗口 +- 隐藏菜单栏 +- 隐藏工具栏 +- 隐藏窗口UI +- 非全屏页面模式 +- 页面布局 +- 页面模式 -每个属性的使用和描述如下代码所示。以下代码片段演示了如何使用 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类设置属性。 +每个都在下面的代码中使用并描述。以下 - 代码片段向您展示如何使用它设置属性。 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类。 ```python +import aspose.pdf as ap - import aspose.pdf as ap - # 打开文档 +def set_document_window(input_pdf, output_pdf): + """Set document window properties and save the result.""" document = ap.Document(input_pdf) - # 设置不同的文档属性 - # 指定将文档窗口居中显示 - 默认: false document.center_window = True - - # 主要阅读顺序; 确定页面的位置 - # 当并排显示时 - 默认: L2R document.direction = ap.Direction.R2L - - # 指定窗口的标题栏是否应显示文档标题 - # 如果为 false,标题栏显示 PDF 文件名 - 默认: false document.display_doc_title = True - - # 指定是否调整文档窗口的大小以适应 - # 首次显示的页面 - 默认: false document.fit_window = True - - # 指定是否隐藏查看器应用程序的菜单栏 - 默认: false document.hide_menubar = True - - # 指定是否隐藏查看器应用程序的工具栏 - 默认: false document.hide_tool_bar = True - - # 指定是否隐藏 UI 元素,如滚动条 - # 仅显示页面内容 - 默认: false document.hide_window_ui = True - - # 文档的页面模式。指定在退出全屏模式时如何显示文档。 document.non_full_screen_page_mode = ap.PageMode.USE_OC - - # 指定页面布局,即单页,一列 document.page_layout = ap.PageLayout.TWO_COLUMN_LEFT - - # 指定打开文档时的显示方式 - # 即显示缩略图,全屏,显示附件面板 document.page_mode = ap.PageMode.USE_THUMBS - # 保存更新的 PDF 文件 document.save(output_pdf) ``` +### 嵌入标准 Type 1 字体 -### 嵌入标准Type 1字体 - -一些PDF文档具有来自特殊Adobe字体集的字体。来自此集合的字体称为“标准Type 1字体”。此集合包括14种字体,嵌入这种类型的字体需要使用特殊的标志,即[embed_standard_fonts](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties)。以下是可以用于获取嵌入所有字体(包括标准Type 1字体)的文档的代码片段: +某些 PDF 文档使用来自特殊 Adobe 字体集的字体。该集合中的字体称为 “Standard Type 1 Fonts”。此集合包含 14 种字体,嵌入此类字体需要使用特殊标志,即 [嵌入标准字体](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties). 以下代码片段可用于获取一个将所有字体(包括标准 Type 1 字体)嵌入的文档: ```python +import aspose.pdf as ap - import aspose.pdf as ap - # 加载一个现有的PDF文档 +def embedded_fonts(input_pdf, output_pdf): + """Ensure fonts in an existing PDF are embedded.""" document = ap.Document(input_pdf) - # 设置文档的EmbedStandardFonts属性 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: - # 检查字体是否已经嵌入 if not page_font.is_embedded: page_font.is_embedded = True document.save(output_pdf) ``` +### 在创建 PDF 时嵌入字体 -### 在创建PDF时嵌入字体 +如果您需要使用除 Adobe Reader 支持的 14 种核心字体之外的任何字体,则必须在生成 PDF 文件时嵌入字体描述。如果未嵌入字体信息,Adobe Reader 将从操作系统中获取(前提是系统已安装该字体),否则将根据 PDF 中的字体描述符构建替代字体。 -如果您需要使用 Adobe Reader 支持的 14 种核心字体以外的任何字体,则必须在生成 PDF 文件时嵌入字体描述。如果字体信息没有嵌入,Adobe Reader 将从操作系统中获取(如果已经安装在系统上),或者根据 PDF 中的字体描述构建替代字体。 +>请注意,嵌入的字体必须安装在主机上,即在以下代码的情况下,‘Univers Condensed’ 字体已安装到系统中。 ->请注意,嵌入的字体必须安装在主机上,即在以下代码中,'Univers Condensed' 字体安装在系统上。 - -我们使用属性 'is_embedded' 将字体信息嵌入到 PDF 文件中。将此属性的值设置为 'True' 将把完整的字体文件嵌入到 PDF 中,虽然这会增加 PDF 文件的大小。以下是用于将字体信息嵌入 PDF 的代码片段。 +我们使用属性 'is_embedded' 将字体信息嵌入 PDF 文件。将此属性的值设为 'True' 将把完整的字体文件嵌入 PDF,尽管这会增加 PDF 文件的大小。以下是可用于将字体信息嵌入 PDF 的代码片段。 ```python +import aspose.pdf as ap - import aspose.pdf as ap - - # 通过调用其空构造函数实例化 Pdf 对象 - doc = ap.Document() - # 在 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(" 这是使用自定义字体的示例文本。") - 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) - # 保存 PDF 文档 - doc.save(output_pdf) + document.save(output_pdf) ``` +### 在保存 PDF 时设置默认字体名称 -### 保存 PDF 时设置默认字体名称 - -当 PDF 文档包含的字体在文档本身和设备上都不可用时,API 会将这些字体替换为默认字体。如果字体可用(安装在设备上或嵌入到文档中),输出的 PDF 应该具有相同的字体(不应被默认字体替换)。默认字体的值应包含字体的名称(而不是字体文件的路径)。我们实现了一个功能,可以在将文档保存为 PDF 时设置默认字体名称。以下代码片段可用于设置默认字体: +当 PDF 文档包含的字体在文档本身和设备上都不可用时,API 会将这些字体替换为默认字体。如果字体是可用的(已安装在设备上或已嵌入文档中),则输出的 PDF 应该保持相同的字体(不应被替换为默认字体)。默认字体的值应包含字体名称(而不是字体文件的路径)。我们已经实现了在将文档保存为 PDF 时设置默认字体名称的功能。以下代码片段可用于设置默认字体: ```python +import aspose.pdf as ap - import aspose.pdf as ap - # 加载一个现有的缺少字体的 PDF 文档 +def set_default_font(input_pdf, output_pdf): + """Assign a fallback font when saving a PDF.""" document = ap.Document(input_pdf) - pdfSaveOptions = ap.PdfSaveOptions() - # 指定默认字体名称 - 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) ``` -### 从 PDF 文档中获取所有字体 +### 获取 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 文档中获取所有字体: +如果您想获取 PDF 文档中的所有字体,您可以使用 [字体实用工具](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties) 提供的方法在 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类。请检查以下代码片段,以获取现有 PDF 文档中的所有字体: ```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) ``` ### 使用 FontSubsetStrategy 改进字体嵌入 -以下代码片段显示了如何设置使用 [font_utilities](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties) 属性的 [FontSubsetStrategy](https://reference.aspose.com/pdf/python-net/aspose.pdf/fontsubsetstrategy/): +以下代码片段展示了如何设置 [字体子集策略](https://reference.aspose.com/pdf/python-net/aspose.pdf/fontsubsetstrategy/) 已使用 [字体实用工具](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties) 属性: ```python +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) - import aspose.pdf as ap + 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) - # 在 SubsetAllFonts 的情况下,所有字体将作为子集嵌入到文档中。 - doc.font_utilities.subset_fonts(ap.FontSubsetStrategy.SUBSET_ALL_FONTS) - # 字体子集将嵌入完全嵌入的字体,但未嵌入到文档中的字体将不受影响。 - doc.font_utilities.subset_fonts(ap.FontSubsetStrategy.SUBSET_EMBEDDED_FONTS_ONLY) - doc.save(output_pdf) + document.save(output_pdf) ``` -### 获取和设置 PDF 文件的缩放因子 +### 获取/设置 PDF 文件的缩放因子 -有时,你可能想要确定 PDF 文档当前的缩放因子是多少。使用 Aspose.Pdf,你可以找出当前值并设置一个新的值。 +有时,您想确定 PDF 文档的当前缩放比例是多少。使用 Aspose.Pdf,您可以查找当前值,也可以设置它。 -[GoToAction](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/gotoaction/) 类的 Destination 属性允许你获取与 PDF 文件关联的缩放值。同样,它也可以用于设置文件的缩放因子。 +这 [转到动作](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/gotoaction/) 类 Destination 属性允许您获取与 PDF 文件关联的缩放值。同样,它可以用于设置文件的缩放因子。 #### 设置缩放因子 以下代码片段展示了如何设置 PDF 文件的缩放因子。 ```python +import aspose.pdf as ap - import aspose.pdf as ap - # 实例化新的 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 - # 保存文档 - 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) ``` #### 获取缩放因子 -以下代码片段展示了如何获取 PDF 文件的缩放因子。 +下面的代码片段展示了如何获取 PDF 文件的缩放因子。 ```python +import aspose.pdf as ap - import aspose.pdf as ap - # 实例化新的 Document 对象 - doc = ap.Document(input_pdf) - - # 创建 GoToAction 对象 - action = doc.open_action - - # 获取 PDF 文件的缩放因子 - print(action.destination.zoom) -``` - - -### 设置打印对话框预设属性 - -Aspose.PDF 允许设置 PDF 文档的 [DUPLEX_FLIP_LONG_EDGE](https://reference.aspose.com/pdf/python-net/aspose.pdf/printduplex/#members) 成员。它允许您更改 PDF 文档的 DuplexMode 属性,该属性默认设置为 simplex。这可以通过以下两种不同的方法实现。 - -```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") ``` -### 使用 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("该文件具有双面翻转短边") +## 相关文档主题 - ed.change_viewer_preference(ap.facades.ViewerPreference.DUPLEX_FLIP_SHORT_EDGE) - ed.save(output_pdf) -``` \ No newline at end of file +- [使用 Python 处理 PDF 文档](/pdf/zh/python-net/working-with-documents/) +- [在 Python 中创建 PDF 文件](/pdf/zh/python-net/create-pdf-document/) +- [在 Python 中操作 PDF 文档](/pdf/zh/python-net/manipulate-pdf-document/) +- [在 Python 中优化 PDF 文件](/pdf/zh/python-net/optimize-pdf/) diff --git a/zh/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md b/zh/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md index 6ca1a7c923..44961fffe9 100644 --- a/zh/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md +++ b/zh/python-net/advanced-operations/working-with-documents/manipulate-pdf-document/_index.md @@ -1,197 +1,118 @@ --- -title: 使用Python通过.NET操作PDF文档 -linktitle: 操作PDF文档 +title: 在 Python 中操作 PDF 文档 +linktitle: 操作 PDF 文档 type: docs weight: 20 url: /zh/python-net/manipulate-pdf-document/ -description: 本文包含有关如何使用Python验证PDF A标准的PDF文档,如何处理目录,如何设置PDF到期日期等信息。 -lastmod: "2023-04-13" +description: 学习如何在 Python 中验证、结构化和修改 PDF 文档,包括 TOC 管理和 PDF/A 检查。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 操作 PDF 文档的指南 +Abstract: 这篇文章提供了一个关于使用 Python 操作 PDF 文档的综合指南,特别是使用 Aspose.PDF 库。它涵盖了多项功能,包括使用 `Document` 类的 `validate` 方法对 PDF 文档进行 PDF/A-1a 和 PDF/A-1b 合规性验证。它还详细说明了如何在 PDF 文件中添加、定制和管理目录(TOC),例如设置不同的 TabLeaderTypes、隐藏页码以及使用前缀自定义页码。此外,文章解释了如何通过嵌入 JavaScript 实现访问限制来为 PDF 文档设置过期日期,以及如何将 PDF 中的可填写表单展平为不可编辑。每个章节均附有代码片段,演示如何在 Python 中使用 Aspose.PDF 实现这些功能。 --- - +当您需要验证 PDF 合规性、构建或自定义目录、设置文档过期行为,或在 Python 工作流中将可填写的 PDF 扁平化时,此页面非常有用。 ## 在 Python 中操作 PDF 文档 -## 验证 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 枚举:PDF_A_1A 或 PDF_A_1B。 +要验证 PDF 文档是否符合 PDF/A-1a 或 PDF/A-1b 兼容性,请使用 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类 [验证](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法。此方法允许您指定保存结果的文件名以及所需的验证类型 PdfFormat 枚举:PDF_A_1A 或 PDF_A_1B。 -以下代码片段向您展示如何验证 PDF 文档是否符合 PDF/A-1A。 +下面的代码片段向您展示如何验证 PDF 文档符合 PDF/A-1A。 ```python +import sys +from os import path +import aspose.pdf as ap - import aspose.pdf as ap - # 打开文档 +def validate_pdfa_standard_a1a(input_pdf, output_pdf): document = ap.Document(input_pdf) - - # 验证 PDF 是否符合 PDF/A-1a - document.validate(output_xml, ap.PdfFormat.PDF_A_1A) + document.validate(output_pdf, ap.PdfFormat.PDF_A_1A) ``` -以下代码片段向您展示如何验证 PDF 文档是否符合 PDF/A-1b。 +以下代码片段向您展示如何验证 PDF/A-1b 的 PDF 文档。 ```python +import sys +from os import path +import aspose.pdf as ap - import aspose.pdf as ap - # 打开文档 +def validate_pdfa_standard_a1b(input_pdf, output_pdf): document = ap.Document(input_pdf) - - # 验证 PDF 是否符合 PDF/A-1b - document.validate(output_xml, ap.PdfFormat.PDF_A_1B) + document.validate(output_pdf, ap.PdfFormat.PDF_A_1B) ``` +## 使用 TOC -## 使用目录 - -### 向现有 PDF 添加目录 +### 向现有 PDF 添加 TOC -PDF 中的目录(TOC)代表“目录”。它是一项功能,通过提供文档各个部分和标题的概览,允许用户快速浏览文档。 +PDF 中的 TOC 代表 “目录”。这是一个功能,允许用户通过提供文档章节和标题的概览,快速浏览文档。 -要向现有的 PDF 文件添加目录,请使用 [aspose.pdf](https://reference.aspose.com/pdf/python-net/aspose.pdf/) 命名空间中的 Heading 类。[aspose.pdf](https://reference.aspose.com/pdf/python-net/aspose.pdf/) 命名空间可以创建新 PDF 文件,也可以操作现有 PDF 文件。要向现有的 PDF 添加目录,请使用 Aspose.Pdf 命名空间。以下代码片段展示了如何使用 Python 通过 .NET 在现有 PDF 文件中创建目录。 +要向现有 PDF 文件添加 TOC,请使用 Heading 类 [aspose.pdf](https://reference.aspose.com/pdf/python-net/aspose.pdf/) 命名空间。该 [aspose.pdf](https://reference.aspose.com/pdf/python-net/aspose.pdf/) namespace 可以创建新的 PDF 文件,也可以操作已有的 PDF 文件。要向已有的 PDF 添加 TOC,请使用 Aspose.Pdf 命名空间。下面的代码片段展示了如何使用 Python via .NET 在已有的 PDF 文件中创建目录(table of contents)。 ```python +import sys +from os import path +import aspose.pdf as ap - import aspose.pdf as ap - - # 加载现有的 PDF 文件 - doc = ap.Document(input_pdf) - - # 访问 PDF 文件的第一页 - tocPage = doc.pages.insert(1) - # 创建对象以表示目录信息 - tocInfo = ap.TocInfo() - title = ap.text.TextFragment("目录") +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 - # 设置目录的标题 - tocInfo.title = title - tocPage.toc_info = tocInfo - - # 创建将用作目录元素的字符串对象 - titles = ["第一页", "第二页", "第三页", "第四页"] - for i in range(0, 2): - # 创建 Heading 对象 - heading2 = ap.Heading(1) - segment2 = ap.text.TextSegment() - heading2.toc_page = tocPage - heading2.segments.append(segment2) - - # 指定标题对象的目标页面 - heading2.destination_page = doc.pages[i + 2] - - # 目标页面 - heading2.top = doc.pages[i + 2].rect.height - - # 目标坐标 - segment2.text = titles[i] - - # 将标题添加到包含目录的页面 - tocPage.paragraphs.add(heading2) - - # 保存更新后的文档 - 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) ``` +### 为不同的 TOC 级别设置不同的 TabLeaderType -### 为不同的目录级别设置不同的TabLeaderType - -Aspose.PDF for Python还允许为不同的目录级别设置不同的TabLeaderType。您需要设置[TocInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/)的[line_dash](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/#properties)属性。 +Aspose.PDF for Python 还允许为不同的 TOC 级别设置不同的 TabLeaderType。您需要设置 [线段虚线](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/#properties) 的属性 [目录信息](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() - - # 设置LeaderType toc_info.line_dash = ap.text.TabLeaderType.SOLID - title = ap.text.TextFragment("目录") + title = ap.text.TextFragment("Table Of Contents") title.text_state.font_size = 30 toc_info.title = title - - # 将列表部分添加到Pdf文档的部分集合中 - tocPage.toc_info = toc_info - # 通过设置左边距和 - # 每个级别的文本格式设置来定义四级列表的格式 + 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 @@ -204,161 +125,146 @@ Aspose.PDF for Python还允许为不同的目录级别设置不同的TabLeaderTy toc_info.format_array[3].margin.right = 30 toc_info.format_array[3].text_state.font_style = ap.text.FontStyles.BOLD - # 在Pdf文档中创建一个部分 - page = doc.pages.add() - - # 在部分中添加四个标题 - 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 = "示例标题" + str(Level) - heading2.text_state.font = ap.text.FontRepository.find_font("Arial") - - # 将标题添加到目录中。 - heading2.is_in_list = True - page.paragraphs.add(heading2) - - # 保存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) ``` +### 在目录中隐藏页码 -### 隐藏目录中的页码 - -如果您不想在目录中显示页码,可以将[TocInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/)类的[is_show_page_numbers](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/#properties)属性设置为false。请查看以下代码片段以隐藏目录中的页码: +如果您不想在目录(TOC)的标题旁显示页码,您可以使用 [是否显示页码](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/#properties) 的属性 [目录信息](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/) Class 为 false。请检查以下代码片段以在目录中隐藏页码: ```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("目录") + 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 - # 将列表部分添加到PDF文档的部分集合中 + toc_info.is_show_page_numbers = False toc_page.toc_info = toc_info - # 通过设置左边距和各级文本格式设置来定义四级列表的格式 - 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() - # 在部分中添加四个标题 - 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 = "这是第 " + 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) ``` +### 在添加目录时自定义页码 -### 自定义页码同时添加目录 - -在 PDF 文档中添加目录时,自定义目录中的页码是很常见的。例如,我们可能需要在页码前添加一些前缀,如 P1、P2、P3 等。在这种情况下,Aspose.PDF for Python 提供了 [TocInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/) 类的 [page_numbers_prefix](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/#properties) 属性,可以用来自定义页码,如以下代码示例所示。 +在 PDF 文档中添加目录(TOC)时,通常会自定义目录中的页码。例如,我们可能需要在页码前添加前缀,如 P1、P2、P3 等。在这种情况下,Aspose.PDF for Python 提供 [页码前缀](https://reference.aspose.com/pdf/python-net/aspose.pdf/tocinfo/#properties) 的属性 [目录信息](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 - # 加载现有的 PDF 文件 - doc = ap.Document(input_pdf) - # 获取 PDF 文件的第一页 - toc_page = doc.pages.insert(1) - # 创建对象以表示目录信息 +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("Table Of Contents") title.text_state.font_size = 20 title.text_state.font_style = ap.text.FontStyles.BOLD - # 设置目录的标题 toc_info.title = title toc_info.page_numbers_prefix = "P" toc_page.toc_info = toc_info - for i in range(len(doc.pages)): - # 创建标题对象 - heading2 = ap.Heading(1) - segment2 = ap.text.TextSegment() - heading2.toc_page = toc_page - heading2.segments.append(segment2) - # 指定标题对象的目标页 - heading2.destination_page = doc.pages[i + 1] - # 目标页 - heading2.top = doc.pages[i + 1].rect.height - # 目标坐标 - segment2.text = "Page " + str(i) - # 将标题添加到包含目录的页面 - toc_page.paragraphs.add(heading2) - - # 保存更新后的文档 - 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) +``` -## 如何设置PDF到期日期 +## 如何设置 PDF 过期日期 -我们对PDF文件应用访问权限,以便某些用户组可以访问PDF文档的特定功能/对象。为了限制PDF文件的访问,我们通常应用加密,并且可能需要设置PDF文件的到期日期,以便访问/查看文档的用户可以获得有关PDF文件到期的有效提示。 +我们对 PDF 文件应用访问权限,以便特定用户组能够访问 PDF 文档的特定功能/对象。为了限制 PDF 文件的访问,我们通常使用加密,并且可能需要设置 PDF 文件的到期时间,以便访问/查看文档的用户能够收到有关 PDF 文件失效的有效提示。 ```python +import sys +from os import path +import aspose.pdf as ap - import aspose.pdf as ap - # 实例化Document对象 - doc = ap.Document() - # 向PDF文件的页面集合添加页面 - doc.pages.add() - # 向页面对象的段落集合中添加文本片段 - doc.pages[1].paragraphs.add(ap.text.TextFragment("Hello World...")) - # 创建JavaScript对象以设置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('The file is expired. You need a new one.');" + "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.');" ) - # 设置JavaScript为PDF打开动作 - doc.open_action = javaScript - - # 保存PDF文档 - doc.save(output_pdf) + document.open_action = script + document.save(output_pdf) ``` +## 在Python中展平可填写的PDF -## 在 Python 中将可填写的 PDF 扁平化 - -PDF 文档通常包含带有交互式可填写控件的表单,例如单选按钮、复选框、文本框、列表等。为了使其在各种应用程序中不可编辑,我们需要将 PDF 文件扁平化。 -Aspose.PDF 提供了在 Python 中只需几行代码即可扁平化 PDF 的功能: +PDF 文档通常包含具备交互式可填写部件的表单,如单选按钮、复选框、文本框、列表等。为满足各种应用需求,使其不可编辑,我们需要将 PDF 文件扁平化。 +Aspose.PDF 提供了在 Python 中仅需几行代码即可将 PDF 扁平化的功能: ```python +import sys +from os import path +import aspose.pdf as ap - import aspose.pdf as ap - # 加载源 PDF 表单 - doc = ap.Document(input_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) +``` - # 扁平化可填写的 PDF - if len(doc.form.fields) > 0: - for item in doc.form.fields: - item.flatten() +## 相关文档主题 - # 保存更新后的文档 - doc.save(output_pdf) \ No newline at end of file +- [使用 Python 处理 PDF 文档](/pdf/zh/python-net/working-with-documents/) +- [在 Python 中格式化 PDF 文档](/pdf/zh/python-net/formatting-pdf-document/) +- [在 Python 中创建 PDF 文件](/pdf/zh/python-net/create-pdf-document/) +- [在 Python 中优化 PDF 文件](/pdf/zh/python-net/optimize-pdf/) diff --git a/zh/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md b/zh/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md index 58e377afc6..7a9051a609 100644 --- a/zh/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md +++ b/zh/python-net/advanced-operations/working-with-documents/merge-pdf/_index.md @@ -1,186 +1,276 @@ --- -title: 如何使用 Python 合并 PDF +title: 在 Python 中合并 PDF 文件 linktitle: 合并 PDF 文件 type: docs weight: 50 url: /zh/python-net/merge-pdf-documents/ -description: 本页面说明如何使用 Python 将 PDF 文档合并为一个单一的 PDF 文件。 -lastmod: "2023-04-14" +description: 了解如何在 Python 中将多个 PDF 文件合并为单个文档。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 合并 PDF 页面 +Abstract: 本文讨论了将多个 PDF 文件合并为单个文档的常见需求,这一过程对于组织、优化存储和共享 PDF 内容非常有价值。文章探讨了使用 Aspose.PDF for Python via .NET 高效合并 PDF 文件,并指出在没有第三方库的情况下,Python 中合并 PDF 可能具有挑战性。本文提供了逐步指南来串联 PDF 文件——创建新文档、合并文件以及保存合并后的文档。代码片段演示了使用 Aspose.PDF 实现的方式,突出该库简化合并过程的能力。此外,文章还介绍了 Aspose.PDF Merger,这是一款用于合并 PDF 的在线工具,使用户能够在基于 Web 的环境中体验其功能。 --- - - - -## 合并或组合多个PDF为单个PDF在Python中 - -合并PDF文件是用户中非常流行的查询。当您有多个PDF文件想要作为一个文档共享或存储在一起时,这会很有用。 - -合并PDF文件可以帮助您整理文件,在您的电脑上腾出存储空间,并通过将多个PDF文件组合成一个文档来与他人分享。 - -在不使用第三方库的情况下,通过.NET在Python中合并PDF文件并不是一项简单的任务。 -本文展示了如何使用Aspose.PDF for Python via .NET将多个PDF文件合并为一个PDF文档。 - -## 使用Python和DOM合并PDF文件 - -要连接两个PDF文件: - -1. 创建两个[Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)对象,每个对象包含一个输入的PDF文件。 - -1. 然后为您想要添加其他 PDF 文件的 Document 对象调用 [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 集合的 [add()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) 方法。 -1. 将第二个 Document 对象的 PageCollection 集合传递给第一个 PageCollection 集合的 [add()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) 方法。 -1. 最后,使用 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法保存输出 PDF 文件。 - -以下代码片段展示了如何连接 PDF 文件。 -```python +## 在 Python 中将多个 PDF 合并或组合为单个 PDF + +合并 PDF 文件是用户非常常见的查询。这在您有多个 PDF 文件想要共享或一起存储为一个文档时非常有用。 + +合并 PDF 文件可以帮助您组织文档,为电脑腾出存储空间,并通过将多个 PDF 文件合并为一个文档与他人共享。 + +在 Python via .NET 中合并 PDF 并非一项直接的任务,除非使用第三方库。 +本文展示了如何使用 Aspose.PDF for Python via .NET 将多个 PDF 文件合并为一个 PDF 文档。 + +## 使用 Python 和 DOM 合并 PDF 文件 - import aspose.pdf as ap +合并两个 PDF 文件: - # 打开第一个文档 - document1 = ap.Document(input_pdf_1) - # 打开第二个文档 - document2 = ap.Document(input_pdf_2) +1. 创建一个新文档。 +1. 合并 PDF 文件 +1. 保存合并文档 - # 将第二个文档的页面添加到第一个文档 +将多个 PDF 文档合并为单个文件: + +```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) +``` + +## 将一个 PDF 的页面范围追加到另一个 PDF + +使用 Aspose.PDF for Python 将源 PDF 文档的特定页面范围复制并追加到目标 PDF 文档。 + +1. 使用 Document 类打开 PDF 文件。 +1. 检查源文档是否有页面。 +1. 验证页面范围。 +1. 如果起始页大于结束页,则跳过此操作。 +1. 遍历页面范围。 +1. 将页面追加到目标文档。 + +```python +import sys +import aspose.pdf as ap +from os import path + + +def _append_page_range(source_document, destination_document, start_page, end_page): + total_pages = len(source_document.pages) + if total_pages == 0: + return + + 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]) +``` + +## 合并多个 PDF 文档为一个 + +此代码片段说明了如何将多个 PDF 文件合并为一个文档: + +1. 创建一个空的输出文档。 +1. 遍历输入文件。 +1. 加载每个源文档。 +1. 确定页面范围。 +1. 将页面追加到输出文档。 +1. 对所有文档重复此操作。 +1. 保存合并后的 PDF。 + +```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) +``` + +## 合并多个 PDF 中选定的页面范围 + +1. 加载源 PDF 文档。 +1. 创建输出文档。 +1. 为每个文档定义页面范围。 +1. 从第一个文档追加页面。 +1. 将第二个文档的页面追加。 +1. 按所需顺序合并页面。 +1. 保存合并后的 PDF。 + +```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() + + _append_page_range(document1, output_document, 1, 2) + _append_page_range(document2, output_document, 2, 3) + + output_document.save(outfile) +``` + +## 在特定位置将一个 PDF 插入另一个 PDF + +1. 加载基文件并插入文档。 +1. 创建输出文档。 +1. 确定基础文档的总页数。 +1. 验证插入索引。 +1. 在插入点之前追加页面。 +1. 将插入文档的所有页面追加。 +1. 将基文档的剩余页面追加。 +1. 保存生成的 PDF。 + +```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) +``` + +## 交替页合并 PDF + +此示例演示了如何使用 Aspose.PDF for Python 通过交替页面合并两个 PDF 文档。 + +1. 加载输入 PDF 文档。 +1. 创建输出文档。 +1. 获取每个文档的页数。 +1. 计算最大页数。 +1. 遍历页码。 +1. 交替追加页面。 +1. 处理不等页数。 +1. 保存合并后的 PDF。 + +```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) - # 保存连接后的输出文件 - document1.save(output_pdf) + 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) ``` +## 合并带有章节分隔符和书签的 PDF + +使用 Aspose.PDF for Python 将多个 PDF 文档合并为单个文件,并包含结构化章节和导航书签。 + +1. 创建输出文档。 +1. 遍历输入文件。 +1. 加载源文档。 +1. 添加一个分隔页。 +1. 创建章节书签。 +1. 追加源文档页面。 +1. 跟踪第一页内容。 +1. 添加嵌套内容书签(可选)。 +1. 对所有文档重复此操作。 +1. 保存合并后的 PDF。 + +```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) +``` + +## 实时示例 + +[Aspose.PDF 合并器](https://products.aspose.app/pdf/merger) 是一个免费在线网络应用程序,允许您调查演示合并功能的工作原理。 + +[![Aspose.PDF 合并器](merger.png)](https://products.aspose.app/pdf/merger) + +## 相关文档主题 + +- [使用 Python 处理 PDF 文档](/pdf/zh/python-net/working-with-documents/) +- [在 Python 中拆分 PDF 文件](/pdf/zh/python-net/split-document/) +- [在 Python 中优化 PDF 文件](/pdf/zh/python-net/optimize-pdf/) +- [在 Python 中操作 PDF 文档](/pdf/zh/python-net/manipulate-pdf-document/) -## 实例演示 - -[Aspose.PDF 合并工具](https://products.aspose.app/pdf/merger) 是一个免费的在线网络应用程序,允许您研究演示合并功能的工作原理。 - -[![Aspose.PDF 合并工具](merger.png)](https://products.aspose.app/pdf/merger) - - \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-documents/merge-pdf/merger.png b/zh/python-net/advanced-operations/working-with-documents/merge-pdf/merger.png new file mode 100644 index 0000000000..c7977aa68d Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-documents/merge-pdf/merger.png differ diff --git a/zh/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md b/zh/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md index db834d2a56..76896e7c70 100644 --- a/zh/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md +++ b/zh/python-net/advanced-operations/working-with-documents/optimize-pdf-document/_index.md @@ -1,336 +1,359 @@ --- -title: 优化、压缩或减少 PDF 大小在 Python 中 +title: 在 Python 中优化 PDF 文件 linktitle: 优化 PDF type: docs weight: 30 url: /zh/python-net/optimize-pdf/ -description: 优化 PDF 文件,缩小所有图像,减少 PDF 大小,取消嵌入字体,使用 Python 删除未使用的对象。 -lastmod: "2023-04-17" +description: 了解如何在 Python 中使用 Aspose.PDF 优化、压缩和减小 PDF 文件大小。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 压缩 PDF 页面。 +Abstract: 本文提供了一份关于优化 PDF 文件以减小大小并提升在各种平台(如网页、电子邮件和存储系统)上的性能的全面指南。优化技术包括减小图像尺寸、移除未使用的资源以及解除嵌入字体。文中讨论了针对网络优化 PDF 以及整体减小文件大小的具体方法,使用 Aspose.PDF for Python 中的 `Optimize` 和 `OptimizeResources` 方法。通过 `OptimizationOptions` 可以自定义优化策略,针对性地执行压缩图像、移除未使用的对象和流、链接重复流以及解除嵌入字体等操作。其他策略还包括扁平化注释、移除表单字段以及将 PDF 文件从 RGB 转换为灰度,以进一步降低大小。文章还强调了使用 FlateDecode 压缩进行图像优化,确保在保持质量和功能的前提下有效管理 PDF 文件。 --- - - - -一个 PDF 文档有时可能包含额外的数据。减小 PDF 文件的大小将帮助您优化网络传输和存储。这在网页发布、社交网络分享、通过电子邮件发送或存储归档时尤其方便。我们可以使用几种技术来优化 PDF: + +PDF 文档有时可能包含额外的数据。缩小 PDF 文件的大小有助于优化网络传输和存储。这在网页发布、社交网络分享、通过电子邮件发送或存档存储时尤为便利。我们可以使用多种技术来优化 PDF: + +在需要减少 PDF 大小以用于网页传输、电子邮件共享、节省存储空间或打印友好输出且无需从头重新构建文档时,请使用此页面。 - 优化页面内容以便在线浏览 - 缩小或压缩所有图像 -- 启用页面内容重用 +- 启用页面内容复用 - 合并重复的流 -- 去除嵌入字体 +- 取消嵌入字体 - 删除未使用的对象 -- 移除平坦化表单字段 -- 移除或平坦化注释 +- 删除扁平化表单字段 +- 删除或展平注释 {{% alert color="primary" %}} -优化方法的详细解释可以在优化方法概述页面中找到。 + 详细的优化方法说明可在“优化方法概览”页面中找到。 {{% /alert %}} ## 为网络优化 PDF 文档 -Web 的优化或线性化是指使 PDF 文件适合使用网络浏览器在线浏览的过程。要优化文件以便网页展示: - -1. 在 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象中打开输入文档。 -1. 使用 [Optimize](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法。 -1. 使用 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法保存优化后的文档。 +优化(或称为 Web 线性化)是指将 PDF 文件处理成适合使用网页浏览器在线浏览的过程。要对文件进行 Web 显示优化: -以下代码片段展示了如何为网络优化 PDF 文档。 +1. 在一个中打开输入文档 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象。 +1. 使用 [优化](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法。 +1. 使用以下方式保存已优化的文档 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法。 -```python +以下代码片段展示了如何针对网页优化 PDF 文档。 - import aspose.pdf as ap +```python +import aspose.pdf as ap +from os import path, stat +import sys - # 打开文档 - document = ap.Document(input_pdf) - # 为网络优化 +def optimize_pdf(infile, outfile): + document = ap.Document(infile) document.optimize() - - # 保存输出文档 - 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 + ) + ) ``` -## 减小 PDF 大小 +## 压缩 PDF 大小 -[OptimizeResources()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法允许通过剔除不必要的信息来减少文档大小。默认情况下,该方法的工作方式如下: +这 [OptimizeResources()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 该方法通过剔除不必要的信息来减小文档大小。默认情况下,该方法的工作方式如下: -- 移除未在文档页面上使用的资源 -- 相同的资源合并为一个对象 +- 未在文档页面上使用的资源会被移除 +- 相等的资源被合并为一个对象 +- 未使用的对象已被删除 -- 删除未使用的对象 - -下面的代码片段是一个示例。但是,请注意这种方法不能保证文档缩小。 +下面的代码片段是一个示例。不过请注意,此方法不能保证文档的压缩。 ```python +import aspose.pdf as ap +from os import path, stat +import sys - import aspose.pdf as ap - # 打开文档 - document = ap.Document(input_pdf) - # 优化 PDF 文档。但是,请注意这种方法不能保证文档缩小 +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() - # 保存更新后的文档 - 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 + ) + ) ``` ## 优化策略管理 -我们还可以自定义优化策略。目前,[OptimizeResources()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法使用 5 种技术。这些技术可以通过使用 [OptimizationOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf.optimization/optimizationoptions/) 参数的 OptimizeResources() 方法来应用。 +我们也可以自定义优化策略。目前, [OptimizeResources()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法使用了5种技术。这些技术可以通过 OptimizeResources() 方法与 [优化选项](https://reference.aspose.com/pdf/python-net/aspose.pdf.optimization/optimizationoptions/) 参数。 ### 缩小或压缩所有图像 -我们有两种处理图像的方式:降低图像质量和/或改变其分辨率。 - 在任何情况下,都应应用 [ImageCompressionOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf.optimization/imagecompressionoptions/)。在下面的示例中,我们通过将 ImageQuality 降低到 50 来缩小图像。 +我们有两种处理图像的方法:降低图像质量和/或更改其分辨率。无论如何, [图像压缩选项](https://reference.aspose.com/pdf/python-net/aspose.pdf.optimization/imagecompressionoptions/) 应该应用。在以下示例中,我们通过将 ImageQuality 降至 50 来缩小图像。 ```python +import aspose.pdf as ap +from os import path, stat +import sys - import aspose.pdf as ap - # 打开文档 - document = ap.Document(input_pdf) - # 初始化 OptimizationOptions +def shrinking_or_compressing_all_images(infile, outfile): + # Open document + document = ap.Document(infile) + # Initialize OptimizationOptions optimizeOptions = ap.optimization.OptimizationOptions() - # 设置 CompressImages 选项 + # Set CompressImages option optimizeOptions.image_compression_options.compress_images = True - # 设置 ImageQuality 选项 + # Set ImageQuality option optimizeOptions.image_compression_options.image_quality = 50 - # 使用 OptimizationOptions 优化 PDF 文档 + # Optimize PDF document using OptimizationOptions document.optimize_resources(optimizeOptions) - # 保存更新后的文档 - 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 + ) + ) ``` -### 移除未使用的对象 +### 删除未使用的对象 -PDF 文档有时包含未被文档中任何其他对象引用的 PDF 对象。 这种情况可能发生在,例如,一个页面从文档页面树中移除,但页面对象本身并未被移除。移除这些对象不会使文档无效,而是缩小了它。 +PDF 文档有时会包含未被文档中任何其他对象引用的 PDF 对象。例如,当页面从文档页面树中被移除,但页面对象本身未被删除时,就可能出现这种情况。删除这些对象并不会使文档无效,而是会使文档体积变小。 ```python +import aspose.pdf as ap +from os import path, stat +import sys - import aspose.pdf as ap - # 打开文档 - document = ap.Document(input_pdf) - # 设置 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 - # 使用 OptimizationOptions 优化 PDF 文档 + # Optimize PDF document using OptimizationOptions document.optimize_resources(optimizeOptions) - # 保存更新后的文档 - 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 + ) + ) ``` -### 移除未使用的流 +### 删除未使用的流 -有时文档中包含未使用的资源流。 这些流不是“未使用的对象”,因为它们被引用自页面资源字典。因此,它们不会被“移除未使用的对象”方法移除。但是,这些流从未与页面内容一起使用。当图像被从页面上移除但没有从页面资源中移除时,可能会发生这种情况。此外,当从文档中提取页面且文档页面具有“公共”资源(即相同的Resources对象)时,这种情况经常发生。分析页面内容以确定资源流是否被使用。未使用的流将被移除。这有时会减少文档的大小。使用这种技术与前一步类似: +有时文档会包含未使用的资源流。这些流并不是“unused objects”,因为它们已在页面资源字典中被引用。因此,它们不会通过“remove unused objects”方法被移除。但这些流在页面内容中从未被使用。出现这种情况可能是因为图像已从页面中删除,但未从页面资源中删除。此外,当从文档中提取页面且文档页面具有“common”资源,也就是相同的 Resources 对象时,这种情况也经常出现。会分析页面内容,以确定资源流是否被使用。未使用的流会被删除。这有时会减小文档大小。使用此技术的方式类似于前一步: ```python +import aspose.pdf as ap +from os import path, stat +import sys - import aspose.pdf as ap - # 打开文档 - document = ap.Document(input_pdf) - # 设置 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 - # 使用 OptimizationOptions 优化 PDF 文档 + # Optimize PDF document using OptimizationOptions document.optimize_resources(optimizeOptions) - # 保存更新的文档 - 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 + ) + ) ``` ### 链接重复的流 -有些文档可能包含多个相同的资源流(例如,图像)。这种情况可能发生在文档与自身连接时。输出文档包含同一资源流的两个独立副本。我们分析所有资源流并进行比较。如果流是重复的,它们将被合并,也就是说,仅保留一个副本。引用会相应地更改,并且对象的副本会被删除。在某些情况下,这有助于减少文档的大小。 +某些文档可能包含多个相同的资源流(例如图像)。这可能会在文档与自身拼接时发生。输出文档包含同一资源流的两个独立副本。我们会分析所有资源流并进行比较。如果流被重复,则将其合并,即只保留一个副本。相应地更改引用,并删除对象的副本。在某些情况下,这有助于减小文档大小。 ```python +import aspose.pdf as ap +from os import path, stat +import sys - import aspose.pdf as ap - # 打开文档 - document = ap.Document(input_pdf) - # 设置 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 - # 使用 OptimizationOptions 优化 PDF 文档 + optimizeOptions.link_duplicate_streams = True + # Optimize PDF document using OptimizationOptions document.optimize_resources(optimizeOptions) - # 保存更新后的文档 - 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 + ) + ) ``` -### 移除嵌入字体 +### 取消嵌入字体 -如果文档使用嵌入字体,则意味着所有字体数据都存储在文档中。 - 文档的优点是,无论字体是否安装在用户的机器上都可以查看。但是嵌入字体会使文档变大。非嵌入字体的方法会移除所有嵌入的字体。因此,文档的大小会减小,但如果没有安装正确的字体,文档本身可能会变得不可读。 +如果文档使用嵌入式字体,这意味着所有字体数据都存储在文档中。好处是无论用户的机器上是否安装了该字体,文档都可以查看。但嵌入字体会使文档体积增大。取消嵌入字体的方法会移除所有嵌入的字体。于是,文档大小会减小,但如果没有安装正确的字体,文档本身可能会变得无法阅读。 ```python - - import aspose.pdf as ap - - # 打开文档 - document = ap.Document(input_pdf) - # 设置 UnembedFonts 选项 - optimizeOptions = ap.optimization.OptimizationOptions() - optimizeOptions.unembed_fonts = True - # 使用 OptimizationOptions 优化 PDF 文档 - document.optimize_resources(optimizeOptions) - # 保存更新后的文档 - 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( - "原始文件大小: {}. 减少后的文件大小: {}".format( + "Original file size: {}. Reduced file size: {}".format( file_stats_1.st_size, file_stats_2.st_size ) ) ``` -优化资源将这些方法应用于文档。 如果应用了这些方法,文档大小很可能会减少。如果没有应用这些方法,文档大小不会改变,这是显而易见的。 +优化资源将这些方法应用于文档。如果应用了其中任何一种方法,文档大小很可能会减少。如果没有应用这些方法,文档大小将保持不变,这是显而易见的。 -## 其他减少 PDF 文档大小的方法 +## 减少 PDF 文档大小的其他方法 ### 删除或扁平化注释 -当注释不必要时,可以删除它们。当它们需要但不需要额外编辑时,可以将它们扁平化。这两种技术都会减少文件大小。 +当注释不必要时,可以将其删除。当注释是必需的但不需要进一步编辑时,可以将其展平。这两种技术都能减小文件大小。 ```python +import aspose.pdf as ap +from os import path, stat +import sys - import aspose.pdf as ap - # 打开文档 - document = ap.Document(input_pdf) - # 扁平化注释 +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() - # 保存更新的文档 - document.save(output_pdf) + # Save updated document + document.save(outfile) ``` ### 删除表单字段 -如果 PDF 文档包含 AcroForms,我们可以尝试通过扁平化表单字段来减少文件大小。 +如果 PDF 文档包含 AcroForms,我们可以尝试通过扁平化表单字段来减小文件大小。 ```python +import aspose.pdf as ap +from os import path, stat +import sys - import aspose.pdf as ap - # 加载源 PDF 表单 - doc = ap.Document(input_pdf) +def flatten_forms(infile, outfile): + # Load source PDF form + doc = ap.Document(infile) - # 扁平化表单 + # Flatten Forms if len(doc.form.fields) > 0: for item in doc.form.fields: item.flatten() - # 保存更新的文档 - 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 + ) + ) ``` ### 将 PDF 从 RGB 颜色空间转换为灰度 -PDF 文件包含文本、图像、附件、注释、图表和其他对象。您可能会遇到将 PDF 从 RGB 颜色空间转换为灰度的需求,以便在打印这些 PDF 文件时速度更快。此外,当文件转换为灰度时,文档大小也会减少,但这也可能导致文档质量下降。此功能目前由 Adobe Acrobat 的预检功能支持,但在谈到办公自动化时,Aspose.PDF 是一个提供此类文档操作的终极解决方案。为了实现此需求,可以使用以下代码片段。 +PDF 文件由 Text、Image、Attachment、Annotations、Graphs 和其他对象组成。您可能会遇到将 PDF 从 RGB 颜色空间转换为灰度的需求,以便在打印这些 PDF 文件时更快。此外,当文件转换为灰度后,文档大小也会减小,但这同样可能导致文档质量下降。此功能目前已由 Adobe Acrobat 的 Pre-Flight 功能支持,但在谈到 Office 自动化时,Aspose.PDF 是提供此类文档操作的终极解决方案。为了实现此需求,可使用以下代码片段。 ```python +import aspose.pdf as ap +from os import path, stat +import sys - import aspose.pdf as ap - # 加载源 PDF 文件 - 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: - # 将 RGB 颜色空间图像转换为灰度颜色空间 + # Convert the RGB colorspace image to GrayScale colorspace strategy.convert(page) - # 保存结果文件 - document.save(output_pdf) + # Save resultant file + document.save(outfile) ``` - ### FlateDecode 压缩 -Aspose.PDF for Python via .NET 支持 PDF 优化功能的 FlateDecode 压缩。下面的代码片段展示了如何在优化中使用该选项以 **FlateDecode** 压缩存储图像: +Aspose.PDF for Python via .NET 提供对 PDF 优化功能的 FlateDecode 压缩的支持。下面的代码片段展示了如何在 Optimization 中使用该选项将图像存储为 **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): - # 打开文档 - doc = ap.Document(input_pdf) - # 初始化 OptimizationOptions + # Open Document + doc = ap.Document(infile) + # Initialize OptimizationOptions optimizationOptions = ap.optimization.OptimizationOptions() - # 为了使用 FlateDecode 压缩优化图像,设置优化选项为 Flate - optimizationOptions.image_compression_options.encoding = ap.optimization.ImageEncoding.FLATE - # 设置优化选项 + # 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) - # 保存文档 - doc.save(output_pdf) \ No newline at end of file + # Save Document + doc.save(outfile) +``` + +## 相关文档主题 + +- [使用 Python 处理 PDF 文档](/pdf/zh/python-net/working-with-documents/) +- [在 Python 中合并 PDF 文件](/pdf/zh/python-net/merge-pdf-documents/) +- [在 Python 中拆分 PDF 文件](/pdf/zh/python-net/split-document/) +- [在 Python 中操作 PDF 文档](/pdf/zh/python-net/manipulate-pdf-document/) + diff --git a/zh/python-net/advanced-operations/working-with-documents/split-pdf/_index.md b/zh/python-net/advanced-operations/working-with-documents/split-pdf/_index.md index af4b74233a..6d0921bb9e 100644 --- a/zh/python-net/advanced-operations/working-with-documents/split-pdf/_index.md +++ b/zh/python-net/advanced-operations/working-with-documents/split-pdf/_index.md @@ -1,34 +1,34 @@ --- -title: 在 Python 中拆分 PDF 文件 -linktitle: 拆分 PDF 文件 +title: 在Python中拆分PDF文件 +linktitle: 拆分PDF文件 type: docs weight: 60 url: /zh/python-net/split-pdf-document/ -description: 了解如何在 Python 中将 PDF 文件拆分为单页、等分、固定大小的组、自定义页范围,以及奇数页或偶数页。 -lastmod: "2026-04-15" +description: 了解如何在 Python 中将 PDF 文件拆分为单独页面、等分部分、固定大小的分组、自定义页面范围以及奇数或偶数页。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 TechArticle: true -AlternativeHeadline: 使用 Python 将 PDF 拆分为单页和页范围。 -Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 拆分 PDF 文件。它涵盖了将 PDF 拆分为单页、拆分为两等份、固定大小的页组、自定义页范围、命名页组、稳定的文件名以及奇数页或偶数页文件。 +AlternativeHeadline: 使用 Python 将 PDF 拆分为页面和页面范围 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 对 PDF 文件进行拆分。它涵盖了将 PDF 拆分为单独页面、两个相等部分、固定大小的页面组、自定义页面范围、具名页面组、稳定的文件名,以及奇数页或偶数页文件。 --- -此页面展示了如何使用 Aspose.PDF for Python via .NET 在 Python 中 **拆分 PDF 文件**。 +此页面展示了如何使用 Aspose.PDF for Python via .NET **在 Python 中拆分 PDF 文件**。 -在需要将大型 PDF 拆分为单页文件、等分部分、固定大小的组、自定义页码范围或奇偶页集合以进行分发、审阅或后续处理时,请使用这些示例。 +当您需要将大型PDF拆分为单页文件、等分部分、固定大小的组、自定义页范围,或奇偶页集合,以进行分发、审阅或下游处理时,请使用这些示例。 ## 在线拆分 PDF 示例 -[Aspose.PDF 拆分器](https://products.aspose.app/pdf/splitter) 是一个在线网页应用程序,让您测试 PDF 拆分功能。 +[Aspose.PDF 拆分器](https://products.aspose.app/pdf/splitter) 是一个在线网页应用程序,可让您测试 PDF 拆分功能。 [![Aspose 拆分 PDF](splitter.png)](https://products.aspose.app/pdf/splitter) -要在 Python 中将 PDF 页面拆分为单页 PDF 文件,请按以下步骤操作: +在 Python 中将 PDF 页面拆分为单页 PDF 文件,请按以下步骤操作: -1. 遍历 PDF 文档的页面 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象的 [页面集合](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 集合 -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) 方法 +1. 循环遍历 PDF 文档的页面 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象的 [页面集合](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 集合 +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) 方法 ## 在 Python 中将 PDF 拆分为多个文件 @@ -48,16 +48,16 @@ def split_documents(infile, outdir): new_document.save(path.join(outdir, f"Page_{page_num}.pdf")) ``` -## 将 PDF 拆分为两个相等的部分 +## 将 PDF 拆分为两个等分 1. 加载 PDF 文档。 1. 确定总页数。 1. 计算中点。 1. 创建第一个输出文档。 -1. 删除第一个文档的后半页。 +1. 从第一个文档中删除后半部分的页面。 1. 保存第一部分。 1. 创建第二个输出文档。 -1. 从第二个文档中删除前半部分的页面。 +1. 删除第二个文档的前半页。 1. 保存第二部分。 ```python @@ -84,19 +84,19 @@ def split_documents_into_two_parts(infile, outdir): second_document.save(path.join(outdir, "Part_2.pdf")) ``` -## 将 PDF 按每 N 页拆分为多个文件 +## 将 PDF 拆分为每 N 页的多个文件 -使用 Aspose.PDF for Python 将 PDF 文档拆分为多个较小的文件,依据固定的页数。 +使用 Aspose.PDF for Python 将 PDF 文档按固定页数拆分为多个较小的文件。 1. 加载 PDF 文档。 1. 确定总页数。 -1. 定义每个部分的页数。 -1. 以块的方式遍历文档。 -1. 计算每个部分的页码范围。 +1. 为每个部分定义页数。 +1. 逐块遍历文档。 +1. 计算每个部分的页面范围。 1. 为每个部分创建一个新文档。 1. 将页面复制到新文档中。 -1. 保存拆分的文档。 -1. 重复,直至所有页面处理完毕。 +1. 保存拆分文档。 +1. 重复执行,直到所有页面都处理完。 ```python import sys @@ -122,20 +122,20 @@ def split_documents_every_n_pages(infile, outdir, pages_per_part=3): part_index += 1 ``` -## 按自定义页码范围拆分 PDF +## 按自定义页面范围拆分 PDF -使用 Aspose.PDF for Python 将 PDF 文档按自定义页面范围拆分为多个文件。 +使用 Aspose.PDF for Python 将 PDF 文档根据自定义页面范围拆分为多个文件。 1. 加载 PDF 文档。 1. 确定总页数。 -1. 创建一个表示 (start_page, end_page) 范围的元组列表。 +1. 创建一个元组列表,表示 (start_page, end_page) 范围。 1. 遍历已定义的范围。 1. 验证起始页。 1. 调整结束页。 1. 验证有效范围。 1. 为每个范围创建一个新文档。 1. 将页面复制到新文档中。 -1. 保存每个拆分文档。 +1. 保存每个拆分的文档。 ```python import sys @@ -165,19 +165,19 @@ def split_documents_by_page_ranges(infile, outdir): ) ``` -## 将 PDF 拆分为首页和其余页面 +## 将 PDF 拆分为第一页和剩余页面 -使用 Aspose.PDF for Python 将 PDF 文档的首页与其余页面分离。 +使用 Aspose.PDF for Python 将 PDF 文档的第一页与其余页面分离。 1. 加载 PDF 文档。 1. 确定总页数。 1. 检查文档是否为空。 -1. 为首页创建文档。 +1. 为第一页创建文档。 1. 添加第一页。 1. 保存第一页文档。 -1. 检查是否有额外的页面。 +1. 检查是否有其他页面。 1. 为剩余页面创建文档。 -1. 复制剩余页面。 +1. 复制剩余的页面。 1. 保存剩余页面的文档。 ```python @@ -208,14 +208,14 @@ def split_documents_first_page_and_rest(infile, outdir): ## 将 PDF 拆分为最后一页和前面的页面 -使用 Aspose.PDF for Python 提取 PDF 文档的最后一页,并将其从其余页面中分离出来。 +使用 Aspose.PDF for Python 提取 PDF 文档的最后一页,并将其从其余页面中分离。 1. 加载 PDF 文档。 1. 确定总页数。 1. 检查文档是否为空。 1. 为最后一页创建文档。 1. 添加最后一页。 -1. 保存最后一页的文档。 +1. 保存最后一页文档。 1. 检查单页文档。 1. 从原始文档中删除最后一页。 1. 保存剩余的页面。 @@ -246,7 +246,7 @@ def split_documents_last_page_and_rest(infile, outdir): ## 将 PDF 拆分为三部分 -使用 Aspose.PDF for Python 将 PDF 文档拆分为三个独立的部分。 +使用 Aspose.PDF for Python 将 PDF 文档拆分为三个独立部分。 1. 加载 PDF 文档。 1. 确定总页数。 @@ -254,7 +254,7 @@ def split_documents_last_page_and_rest(infile, outdir): 1. 计算部件大小。 1. 遍历三个部分。 1. 确定每个部分的页码范围。 -1. 验证页码范围。 +1. 验证页面范围。 1. 为每个部分创建一个新文档。 1. 将页面复制到部件文档中。 1. 保存每个部分。 @@ -289,7 +289,7 @@ def split_documents_into_three_parts(infile, outdir): ## 自定义 PDF 页面拆分器 -使用 Aspose.PDF for Python 将 PDF 文档根据自定义页面组拆分为多个文件。 +使用 Aspose.PDF for Python 将 PDF 文档拆分为多个文件,依据自定义的页面分组。 ```python import sys @@ -338,7 +338,7 @@ def split_documents_with_stable_filenames(infile, outdir): ## 将 PDF 拆分为奇数页和偶数页 -使用 Aspose.PDF for Python 将 PDF 文档拆分为两个单独的文件,分别包含奇数页和偶数页。 +使用 Aspose.PDF for Python 将 PDF 文档拆分为两个独立的文件,分别包含奇数页和偶数页。 ```python import sys @@ -365,7 +365,8 @@ def split_documents_odd_even_pages(infile, outdir): ## 相关文档主题 -- [在 Python 中处理 PDF 文档](/pdf/zh/python-net/working-with-documents/) +- [使用 Python 处理 PDF 文档](/pdf/zh/python-net/working-with-documents/) - [在 Python 中合并 PDF 文件](/pdf/zh/python-net/merge-pdf-documents/) - [在 Python 中优化 PDF 文件](/pdf/zh/python-net/optimize-pdf/) -- [在Python中操作PDF文档](/pdf/zh/python-net/manipulate-pdf-document/) +- [在 Python 中操作 PDF 文档](/pdf/zh/python-net/manipulate-pdf-document/) + diff --git a/zh/python-net/advanced-operations/working-with-documents/split-pdf/splitter.png b/zh/python-net/advanced-operations/working-with-documents/split-pdf/splitter.png new file mode 100644 index 0000000000..ede55d9927 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-documents/split-pdf/splitter.png differ diff --git a/zh/python-net/advanced-operations/working-with-documents/working-with-headings/_index.md b/zh/python-net/advanced-operations/working-with-documents/working-with-headings/_index.md deleted file mode 100644 index 28ada50832..0000000000 --- a/zh/python-net/advanced-operations/working-with-documents/working-with-headings/_index.md +++ /dev/null @@ -1,218 +0,0 @@ ---- -title: 在 PDF 中处理标题 -type: docs -weight: 40 -url: /zh/python-net/working-with-headings/ -description: 使用 Python 在 PDF 文档的标题中创建编号。Aspose.PDF for Python via .NET 提供不同类型的编号样式。 -lastmod: "2023-04-17" -sitemap: - changefreq: "weekly" - priority: 0.7 ---- - - - -## 应用编号样式在标题中 - -标题是任何文档的重要部分。作者总是试图使标题对读者更显著和有意义。如果一个文档中有多个标题,作者有多种选择来组织这些标题。其中一种最常见的组织标题的方法是使用编号样式书写标题。 - -[Aspose.PDF for Python via .NET](/pdf/zh/python-net/) 提供了许多预定义的编号样式。这些预定义的编号样式存储在一个枚举中,[NumberingStyle](https://reference.aspose.com/pdf/python-net/aspose.pdf/numberingstyle/)。NumberingStyle 枚举的预定义值及其描述如下: - -|**标题类型**|**描述**| -| :- | :- | -|NumeralsArabic|阿拉伯类型,例如,1,1.1,...| -|NumeralsRomanUppercase|罗马大写类型,例如,I,I.II, ...| -|NumeralsRomanLowercase|罗马小写类型,例如,i,i.ii, ...| -|LettersUppercase|英文字母大写类型,例如,A,A.B, ...| - -|LettersLowercase|英文字母小写类型,例如,a,a.b, ...| -The [style](https://reference.aspose.com/pdf/python-net/aspose.pdf/heading/#properties) 属性是 [Heading](https://reference.aspose.com/pdf/python-net/aspose.pdf/heading/) 类用于设置标题的编号样式。 - -|**图:预定义编号样式**| -| :- | -获取上图所示输出的源代码如下示例所示。 - -```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 = "列表 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 = "列表 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 = "截至计划生效日期时,计划下分配的每个允许的财产的价值" - 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/zh/python-net/advanced-operations/working-with-forms/_index.md b/zh/python-net/advanced-operations/working-with-forms/_index.md index c3d42adc69..94ad7c8d41 100644 --- a/zh/python-net/advanced-operations/working-with-forms/_index.md +++ b/zh/python-net/advanced-operations/working-with-forms/_index.md @@ -1,84 +1,22 @@ --- -title: 使用Python处理表单 -linktitle: 使用表单 +title: 使用 Python 处理表单 +linktitle: 处理表单 type: docs weight: 60 url: /zh/python-net/working-with-forms/ -description: 本节介绍如何使用Aspose.PDF在PDF文档中处理AcroForms。适用于Python通过.NET。 -lastmod: "2023-02-17" +description: 本节描述了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中处理 AcroForm。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 处理表单 +Abstract: 本文概述了一种使用 Aspose.PDF for Python via .NET 库以编程方式完成 PDF 文档的简便方法。它重点说明了利用该库识别并映射已有 PDF 中使用 AcroForm 的字段的过程。AcroForm 是一种电子表单,能够让用户高效地填写、提交和存储信息,是数据收集的便利工具。此外,本文还提供了使用 Python 库创建表单、填写表单字段、提取数据以及在 PDF 中管理字段的相关技巧。 --- - +本节描述了一种快速简便的通过使用 Aspose.PDF for Python via .NET 库以编程方式完成 PDF 文档的方法。章节还讨论了如何使用 Aspose.PDF for Python 发现并映射已有包含 AcroForm 的 PDF 中可用字段的方式。 -该部分描述了一种通过使用Aspose.PDF for Python via .NET库以编程方式完成PDF文档的快速简单方法。该部分还讨论了如何使用Aspose.PDF for Python来发现和映射现有PDF中带有AcroForms的可用字段。 +AcroForms 允许用户以电子方式填写、提交和存储表单,使其成为收集信息的便捷且高效的方式。 -AcroForms允许用户填写、提交和存储表单,以电子方式进行,使其成为收集信息的一种方便高效的方式。 - -- [AcroForms](/pdf/zh/python-net/acroforms/) - 使用Python库创建表单、填写表单字段、从表单中提取数据、在PDF中添加和删除字段。 \ No newline at end of file +- [AcroForms](/pdf/zh/python-net/acroforms/) - 使用 Python 库在您的 PDF 中创建表单、填写表单字段、提取表单数据、添加和删除字段。 +- [XFA 表单](/pdf/zh/python-net/xfa-forms/) - 转换 XFA,使用 IgnoreNeedsRendering。 \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-forms/acroforms/_index.md b/zh/python-net/advanced-operations/working-with-forms/acroforms/_index.md index c1f05c7194..e2e5a7779c 100644 --- a/zh/python-net/advanced-operations/working-with-forms/acroforms/_index.md +++ b/zh/python-net/advanced-operations/working-with-forms/acroforms/_index.md @@ -4,155 +4,30 @@ linktitle: AcroForms type: docs weight: 10 url: /zh/python-net/acroforms/ -description: 使用 Aspose.PDF for Python,您可以从头创建表单、填写 PDF 文档中的表单字段、从表单中提取数据等。 -lastmod: "2023-02-17" +description: 了解如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中创建、填写、提取、导入、导出和管理 AcroForm 字段。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 处理 AcroForms 的指南 +Abstract: 本节介绍 AcroForms,并阐述如何使用 Aspose.PDF for Python via .NET 处理交互式 PDF 表单。它涵盖了创建表单、填写字段、提取数值、导入和导出表单数据以及修改或删除表单字段等核心工作流。这些教程帮助您构建实用的表单处理流水线,以应对文档自动化场景。 --- - +## AcroForms 基础 -## AcroForms 的基础知识 +AcroForms 是交互式、面向页面的 PDF 表单,由 Adobe 引入,并自 PDF 规范 1.2 版起包含在规范中。它们得到广泛支持,可用于跨平台工作流中的数据捕获、验证和交换。 -**AcroForms** - 来自 Adobe 的独特 PDF 表单技术。AcroForms 是一种面向页面的表单。它们首次出现于 1998 年。它们接受数据格式或 FDF 和 XML 表单数据格式或 xFDF 的输入。第三方供应商支持 AcroForms。当 Adobe 推出 AcroForms 时,他们称其为“PDF 表单,即 Adobe Acrobat Pro/Standard 的作者,而不是特殊类型的静态或动态 XFA 表单。AcroForms 是可移植的,并且可以在所有平台上工作。``` +在基于 AcroForm 的工作流中,表单数据可以以 FDF 和 XFDF 等格式进行交换。这使得 AcroForms 适用于需要从外部系统预填字段、提取提交值或在文档之间同步表单数据的场景。 -您可以使用 AcroForms 向 PDF 表单文档添加额外的页面。得益于模板的概念,您可以使用 AcroForms 来支持用多个数据库记录填充表单。 +Aspose.PDF for Python via .NET 提供 API,以编程方式创建和管理 AcroForms,包括填写字段、导出数据、修改表单结构以及添加提交操作。 -PDF 1.7 支持两种不同的方法来集成数据和 PDF 表单。 +有关实际示例,请参阅以下文章: -*AcroForms(也称为 Acrobat 表单)*,在 PDF 1.2 格式规范中引入和包含。 - -有关 Java 库功能的更详细学习,请参阅以下文章: - -- [创建 AcroForm](/pdf/zh/python-net/create-form) - 从头开始使用 Python 创建表单。 -- [填写 AcroForm](/pdf/zh/python-net/fill-form) - 填写 PDF 文档中的表单字段。 -- [提取 AcroForm](/pdf/zh/python-net/extract-form) - 从 PDF 文档的所有字段或单个字段获取值。 - - \ No newline at end of file +- [创建 AcroForm](/pdf/zh/python-net/create-form/) - 从头创建表单。 +- [填写 AcroForm](/pdf/zh/python-net/fill-form/) - 在 PDF 文档中填写表单字段。 +- [提取 AcroForm](/pdf/zh/python-net/extract-form/) 提取所有字段或特定字段的值。 +- [导入和导出表单数据](/pdf/zh/python-net/import-export-form-data/) 以常用格式导入和导出表单数据。 +- [修改 AcroForm](/pdf/zh/python-net/modifying-form/) 修改 AcroForm 字段属性。 +- [从 PDF 中删除表单](/pdf/zh/python-net/remove-form/) 从 PDF 文档中移除表单字段。 +- [发布表单](/pdf/zh/python-net/posting-form/) 为 PDF 表单添加提交功能。 diff --git a/zh/python-net/advanced-operations/working-with-forms/acroforms/create-form/_index.md b/zh/python-net/advanced-operations/working-with-forms/acroforms/create-form/_index.md index 25b7dfe223..fa7fb12d23 100644 --- a/zh/python-net/advanced-operations/working-with-forms/acroforms/create-form/_index.md +++ b/zh/python-net/advanced-operations/working-with-forms/acroforms/create-form/_index.md @@ -1,184 +1,255 @@ --- -title: 创建 AcroForm - 在 Python 中创建可填写的 PDF +title: 创建 AcroForm - 在 Python 中创建可填充 PDF linktitle: 创建 AcroForm type: docs weight: 10 url: /zh/python-net/create-form/ -description: 使用 Aspose.PDF for Python,您可以在 PDF 文件中从头开始创建表单 -lastmod: "2023-02-17" +description: 使用 Aspose.PDF for Python via .NET 从头创建 PDF 文档中的 AcroForm 字段。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 在 PDF 中创建 AcroForm +Abstract: 本文介绍了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中创建 AcroForm 字段。它涵盖了使用 TextBoxField 的基本字段创建、多部件文本框外观自定义,以及诸如单选按钮、组合框、复选框、列表框、签名字段和条形码字段等其他字段类型。这些示例帮助您构建交互式 PDF 表单,以进行数据收集和文档自动化工作流。 --- - - - -## 从头开始创建表单 + +## 从头创建表单 ### 在 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 文档中的表单字段。 +这 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类提供一个名为的集合 [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/form/) 它帮助您管理 PDF 文档中的表单字段。 要添加表单字段: 1. 创建您想要添加的表单字段。 -2. 调用 Form 集合的 [add](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/form/#methods) 方法。 +1. 调用 Form 集合的 [添加](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/form/#methods) 方法。 ### 添加 TextBoxField -下面的示例展示了如何添加 [TextBoxField](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/textboxfield/)。 +以下示例展示了如何添加一个 [文本框字段](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) +``` + +### PDF 中的多部件文本框字段 + +使用 Python 和 Aspose.PDF 在 PDF 中创建具有多个小部件外观的文本框表单字段。它在页面上放置多个文本输入区域,为每个小部件应用不同的字体和颜色,定制边框,并为交互式 PDF 表单设置背景样式。 + +1. 创建新 PDF 文档。 +1. 定义文本字段位置。 +1. 创建不同的默认外观。 +1. 创建文本框字段。 +1. 为每个小部件应用外观。 +1. 自定义边框样式。 +1. 向表单添加字段。 +1. 保存 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) +``` + +## 添加其他表单字段 + +下面的代码片段展示了如何添加各种字段类型,例如单选按钮、下拉框、复选框、列表框、签名字段和条形码字段。每个函数都会创建一个新的 PDF 文档,添加带有所选选项的目标字段,并保存更新后的文件。 + +1. 添加单选按钮字段 +1. 添加组合框字段 +1. 添加复选框字段 +1. 添加列表框字段 +1. 添加签名字段 +1. 添加条形码字段 + +### 添加单选按钮字段 + +```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) +``` + +### 添加组合框字段 + +```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) +``` + +### 添加复选框字段 ```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() - # 打开文档 - 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 - # 创建一个字段 - 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 +### 添加列表框字段 - 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) +``` - # 添加字段到文档 - pdfDocument.form.add(textBoxField, 1) +### 添加签名字段 - # 保存修改后的 PDF - 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) +``` + +### 添加条形码字段 + +```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) ``` +## 相关主题 - \ No newline at end of file +- [填写 AcroForm](/pdf/zh/python-net/fill-form/) +- [提取 AcroForm](/pdf/zh/python-net/extract-form/) +- [修改 AcroForm](/pdf/zh/python-net/modifying-form/) +- [导入和导出表单数据](/pdf/zh/python-net/import-export-form-data/) diff --git a/zh/python-net/advanced-operations/working-with-forms/acroforms/extract-form/_index.md b/zh/python-net/advanced-operations/working-with-forms/acroforms/extract-form/_index.md index e1ad2a8736..ca8e781566 100644 --- a/zh/python-net/advanced-operations/working-with-forms/acroforms/extract-form/_index.md +++ b/zh/python-net/advanced-operations/working-with-forms/acroforms/extract-form/_index.md @@ -1,99 +1,53 @@ --- -title: 提取 AcroForm - 在 Python 中从 PDF 提取表单数据 +title: 提取 AcroForm - 在 Python 中提取 PDF 表单数据 linktitle: 提取 AcroForm type: docs weight: 30 url: /zh/python-net/extract-form/ -description: 使用 Aspose.PDF for Python 库从您的 PDF 文档中提取表单。获取 PDF 文件中单个字段的值。 -lastmod: "2023-02-17" +description: 通过使用 Aspose.PDF for Python via .NET,从 PDF 文档的 AcroForm 字段中提取值。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 从 PDF 获取表单数据 +Abstract: 本文展示了如何通过使用 Aspose.PDF for Python via .NET,从 PDF 文档的 AcroForm 字段中提取数据。示例遍历表单字段名称,使用 Form 门面读取值,并返回一个字典以供后续处理。此工作流对于报告、验证以及与外部系统的集成非常有用。 --- - - -## 从表单中提取数据 +## 提取表单数据 ### 获取 PDF 文档中所有字段的值 -要从 PDF 文档中获取所有字段的值,需要遍历所有表单字段,然后使用 Value 属性获取值。从基础字段类型 [Field](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/field/) 的 Form 集合中获取每个字段,并访问其 [value](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/field/#properties) 属性。 +要读取 PDF 文档中所有字段的值,遍历表单字段名称并从中检索每个值 [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) 外观。 + +使用以下步骤: + +1. 将输入 PDF 绑定到 a `Form` 对象。 +1. 遍历 `field_names`. +1. 使用以下方式读取每个值 `get_field()`. +1. 将值存储在字典中。 +1. 返回或处理提取的值。 -以下 Python 代码片段展示了如何获取 PDF 文档中所有字段的值。 +下面的 Python 代码片段展示了此方法。 ```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 +``` - # 打开文档 - pdfDocument = ap.Document(input_file) +## 相关主题 - # 从所有字段获取值 - for formField in pdfDocument.form.fields: - # 如果需要,分析名称和值 - print("字段名称 : " + formField.partial_name) - print("值 : " + str(formField.value)) \ No newline at end of file +- [创建 AcroForm](/pdf/zh/python-net/create-form/) +- [填写 AcroForm](/pdf/zh/python-net/fill-form/) +- [导入和导出表单数据](/pdf/zh/python-net/import-export-form-data/) +- [修改 AcroForm](/pdf/zh/python-net/modifying-form/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-forms/acroforms/fill-form/_index.md b/zh/python-net/advanced-operations/working-with-forms/acroforms/fill-form/_index.md index 9fbbe706fa..8d9236a6ad 100644 --- a/zh/python-net/advanced-operations/working-with-forms/acroforms/fill-form/_index.md +++ b/zh/python-net/advanced-operations/working-with-forms/acroforms/fill-form/_index.md @@ -4,161 +4,50 @@ linktitle: 填写 AcroForm type: docs weight: 20 url: /zh/python-net/fill-form/ -description: 您可以使用 Aspose.PDF for Python 库在 PDF 文档中填写表单。 -lastmod: "2023-02-17" +description: 使用 Aspose.PDF for Python via .NET 在 PDF 文档中填写 AcroForm 字段。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 填写 PDF 表单字段 +Abstract: 本文解释了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中填写 AcroForm 字段。示例使用 Form 门面,将字段名称映射到字典中的新值,更新匹配的字段,并保存输出 PDF。此方法适用于自动化文档完成工作流和批量表单处理。 --- - +## 在 PDF 文档中填写 Form 字段 -## 在 PDF 文档中填写表单字段 +以下示例通过使用 the [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) 外观。 -要填写表单字段,从文档对象的 [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/form/) 集合中获取字段。然后使用字段的 [value](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/form/#properties) 属性设置字段值。 +使用以下步骤: -此示例选择一个 [TextBoxField](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/textboxfield/),并使用 Value 属性设置其值。 +1. 创建一个包含字段名称和值的字典。 +1. 将输入 PDF 绑定到 Form 对象。 +1. 遍历可用的表单字段。 +1. 填充字典中存在的字段。 +1. 保存更新后的 PDF。 ```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) - # 打开文档 - pdfDocument = ap.Document(input_file) - for formField in pdfDocument.form.fields: - if formField.partial_name == "Field 1": - # 修改字段值 - 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]) - # 保存更新后的文档 - pdfDocument.save(output_pdf) + form.save(output_file_name) ``` +## 相关主题 - \ No newline at end of file +- [创建 AcroForm](/pdf/zh/python-net/create-form/) +- [提取 AcroForm](/pdf/zh/python-net/extract-form/) +- [导入和导出表单数据](/pdf/zh/python-net/import-export-form-data/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-forms/acroforms/import-export-form-data/_index.md b/zh/python-net/advanced-operations/working-with-forms/acroforms/import-export-form-data/_index.md new file mode 100644 index 0000000000..c6332c4b8a --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-forms/acroforms/import-export-form-data/_index.md @@ -0,0 +1,226 @@ +--- +title: 导入和导出表单数据 +linktitle: 导入和导出表单数据 +type: docs +weight: 80 +url: /zh/python-net/import-export-form-data/ +description: 使用 Aspose.PDF for Python via .NET 导入和导出 AcroForm 字段数据,支持 XML、FDF、XFDF 和 JSON 格式。 +lastmod: "2026-06-08" +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python via .NET 的导入和导出技术。 +Abstract: 本汇编呈现了一套使用 Aspose.PDF for Python via .NET 的表单数据导入导出技术的完整方案。它涵盖了将 PDF 表单与包括 XML、FDF、XFDF 和 JSON 在内的外部数据格式集成的工作流。用户可以通过将结构化数据导入交互式字段来实现批量表单填充自动化,或提取字段值用于分析、备份或与其他系统的集成。示例展示了如何绑定 PDF 表单、在不同格式之间传输数据以及保存更新后的文档,从而在各种应用中实现可扩展且一致的文档处理。 +--- + +此页面展示了使用 Aspose.PDF for Python via .NET 导入和导出 AcroForm 数据的常见工作流。所有操作使用 [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) 外观。 + +## 从 XML 导入表单字段数据 + +使用此方法从外部 XML 数据填充 PDF 表单。 + +1. 创建一个 `Form` 对象。 +1. 绑定输入 PDF。 +1. 打开 XML 数据文件。 +1. 将 XML 数据导入表单。 +1. 保存更新后的 PDF。 + +```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) +``` + +## 将表单字段数据导出为 XML + +此方法将 PDF 文档中的 FormField 值导出为 XML。 + +1. 创建一个 `Form` 对象。 +1. 绑定输入 PDF。 +1. 打开 XML 输出文件。 +1. 将表单数据导出为 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) +``` + +## 从 FDF 导入表单字段数据 + +这 `import_data_from_fdf` 方法将表单字段数据从 FDF(Forms Data Format)文件导入到 PDF 表单中。 + +1. 创建一个 `Form` 对象。 +1. 绑定输入 PDF。 +1. 使用导入表单数据 `import_fdf()`. +1. 保存更新后的 PDF。 + +```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) +``` + +## 导出表单字段数据到 FDF + +此示例将 PDF 文档中的表单数据导出到 FDF 文件。 + +1. 创建一个 `Form` 对象。 +1. 绑定 PDF 文档。 +1. 导出表单数据使用 `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) +``` + +## 从XFDF导入表单字段数据 + +使用此方法将表单字段数据从 XFDF(XML 表单数据格式)文件导入到 PDF 表单中。 + +1. 创建一个 `Form` 对象。 +1. 绑定输入 PDF。 +1. 从 XFDF 文件导入表单数据。 +1. 保存更新后的 PDF。 + +```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) +``` + +## 导出表单字段数据到 XFDF + +此代码将 PDF 文档中的表单字段数据导出到 XFDF 文件。 + +1. 创建一个 `Form` 对象。 +1. 绑定输入 PDF。 +1. 将表单数据导出为 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) +``` + +## 从另一个 PDF 导入数据 + +此示例通过将 XFDF 导出到内存流并将其导入目标表单,将表单字段数据从源 PDF 传输到目标 PDF。 + +1. 创建源和目标 `Form` 对象。 +1. 绑定源 PDF 和目标 PDF。 +1. 从源 PDF 导出表单数据。 +1. 将表单数据导入目标 PDF。 +1. 保存已更新的目标 PDF。 + +```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) +``` + +## 提取表单字段为 JSON + +此方法通过使用将表单字段导出为JSON文件。 `export_json()`. + +1. 创建一个 `Form` 对象。 +1. 打开 JSON 输出文件。 +1. 通过使用导出表单字段 `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) +``` + +## 提取表单字段为 JSON 文档 + +此示例从表单字段名称和值创建自定义 JSON 文档。 + +1. 从输入文件创建 Form 对象。 +1. 初始化一个空字典以存储表单字段数据。 +1. 遍历所有表单字段并提取它们的值。 +1. 将表单数据字典序列化为带有 4 空格缩进的 JSON 字符串。 +1. 将 JSON 字符串以 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) +``` + +## 相关主题(外观方法) + +- [导入 XML 数据](/pdf/zh/python-net/import-xml-data/) +- [导入 FDF 数据](/pdf/zh/python-net/import-fdf-data/) +- [导入 XFDF 数据](/pdf/zh/python-net/import-xfdf-data/) +- [导入 JSON 数据](/pdf/zh/python-net/import-json-data/) +- [导出为 XML](/pdf/zh/python-net/export-to-xml/) +- [导出为 FDF](/pdf/zh/python-net/export-to-fdf/) +- [导出为 XFDF](/pdf/zh/python-net/export-to-xfdf/) +- [导出为 JSON](/pdf/zh/python-net/export-to-json/) diff --git a/zh/python-net/advanced-operations/working-with-forms/acroforms/modifying-form/_index.md b/zh/python-net/advanced-operations/working-with-forms/acroforms/modifying-form/_index.md new file mode 100644 index 0000000000..3d6bb0312f --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-forms/acroforms/modifying-form/_index.md @@ -0,0 +1,139 @@ +--- +title: 修改 AcroForm +linktitle: 修改 AcroForm +type: docs +weight: 45 +url: /zh/python-net/modifying-form/ +description: 使用 Aspose.PDF for Python via .NET 修改 PDF 文档中的 AcroForm 字段,包括清除文本、设置限制、设置字段样式以及删除字段。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 管理和自定义 PDF 表单字段 +Abstract: 本文提供了使用 Aspose.PDF for Python via .NET 修改 AcroForm 字段的实际示例。内容涵盖清除打字机表单内容中的文本、设置和读取文本字段的字符限制、应用自定义字体外观以及按名称删除字段。这些工作流支持在自动化 PDF 处理流水线中进行常见的表单维护任务。 +--- + +## 在表单中清除文本 + +此示例演示了如何使用 Aspose.PDF for Python via .NET 清除 PDF 中 Typewriter 表单字段的文本。它会扫描 PDF 的首页,识别 Typewriter 表单,删除其内容,并保存更新后的文档。此方法对于在重新分发 PDF 之前重置或清理表单字段非常有用。 + +1. 加载输入的 PDF 文档。 +1. 访问第一页上的表单。 +1. 遍历每个表单并检查它是否为 `Typewriter` 表单。 +1. 使用 TextFragmentAbsorber 在表单中查找文本片段。 +1. 清除每个片段的文本。 +1. 将修改后的 PDF 保存到输出文件。 + +```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) +``` + +## 设置字段限制 + +使用 `set_field_limit(field, limit)` 从 `FormEditor` 定义文本字段允许的最大字符数。 + +1. 创建一个 `FormEditor` 对象。 +1. 绑定输入 PDF。 +1. 为目标字段设置字段限制。 +1. 保存更新后的 PDF。 + +```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) +``` + +## 获取字段限制 + +您也可以从文本字段读取字符限制。 + +1. 加载 PDF 文档。 +1. 访问目标表单字段。 +1. 确保该字段是 `TextBoxField`. +1. 读取并打印 `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}") +``` + +## 为表单字段设置自定义字体 + +此示例为文本框字段设置自定义默认外观,包括字体、大小和颜色。 + +1. 加载 PDF 文档。 +1. 访问目标字段并验证其类型。 +1. 在...中查找字体 `FontRepository`. +1. 应用新的 `DefaultAppearance`. +1. 保存更新后的 PDF。 + +```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) +``` + +## 删除现有表单中的字段 + +此代码通过名称从 PDF 文档中删除特定的表单字段,并使用 Aspose.PDF for Python via .NET 保存更新后的文件。 + +1. 加载 PDF 文档。 +1. 按名称删除表单字段。 +1. 保存更新后的 PDF。 + +```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) +``` + +## 相关主题 + +- [创建 AcroForm](/pdf/zh/python-net/create-form/) +- [填写 AcroForm](/pdf/zh/python-net/fill-form/) +- [提取 AcroForm](/pdf/zh/python-net/extract-form/) +- [导入和导出表单数据](/pdf/zh/python-net/import-export-form-data/) diff --git a/zh/python-net/advanced-operations/working-with-forms/acroforms/posting-form/_index.md b/zh/python-net/advanced-operations/working-with-forms/acroforms/posting-form/_index.md new file mode 100644 index 0000000000..20f450befe --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-forms/acroforms/posting-form/_index.md @@ -0,0 +1,76 @@ +--- +title: 通过 Python 在 PDF 中发布表单 +linktitle: 发布表单 +type: docs +weight: 75 +url: /zh/python-net/posting-form/ +description: 使用 Aspose.PDF for Python via .NET 向 PDF AcroForms 添加提交按钮和提交操作。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 向 PDF 添加提交按钮和表单提交操作 +Abstract: 本文展示了两种通过 Aspose.PDF for Python via .NET 为 PDF 表单添加提交功能的方法。您可以通过 FormEditor 添加现成的提交按钮,或使用 SubmitFormAction 创建自定义按钮字段以实现高级控制。这些模式有助于将 PDF 表单与服务器端表单处理端点集成。 +--- + +## 使用 FormEditor 添加提交按钮 + +以下代码片段演示了如何使用 Aspose.PDF for Python via .NET 中的 FormEditor 类向 PDF 表单添加提交按钮。该按钮被配置为在点击时将表单数据提交到指定的 URL。 + +1. 创建一个 `FormEditor` 对象。 +1. 向目标页面添加提交按钮。 +1. 设置提交 URL 和按钮坐标。 +1. 保存更新后的 PDF。 + +```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() +``` + +## 添加自定义提交操作 + +以下代码片段说明了如何使用 Aspose.PDF for Python via .NET 在 PDF 表单中创建自定义提交按钮。该按钮被配置为在点击时将表单数据发送到指定的 URL。 + +1. 使用 ap.Document() 打开 PDF。 +1. 创建提交操作。 +1. 设置目标 URL 和提交标志。 +1. 创建按钮字段并绑定其点击操作。 +1. 将按钮添加到表单中。 +1. 保存更新后的 PDF。 + +```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) +``` + +## 相关主题 + +- [创建 AcroForm](/pdf/zh/python-net/create-form/) +- [填写 AcroForm](/pdf/zh/python-net/fill-form/) +- [修改 AcroForm](/pdf/zh/python-net/modifying-form/) +- [导入和导出表单数据](/pdf/zh/python-net/import-export-form-data/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-forms/acroforms/remove-form/_index.md b/zh/python-net/advanced-operations/working-with-forms/acroforms/remove-form/_index.md new file mode 100644 index 0000000000..b9e9db296c --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-forms/acroforms/remove-form/_index.md @@ -0,0 +1,65 @@ +--- +title: 在 Python 中删除 PDF 表单 +linktitle: 删除表单 +type: docs +weight: 70 +url: /zh/python-net/remove-form/ +description: 使用 Aspose.PDF for Python via .NET 从 PDF 页面中移除表单对象,包括完整清理和有针对性的删除。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python via .NET 从 PDF 中移除表单 +Abstract: 本文介绍了两种使用 Aspose.PDF for Python via .NET 从 PDF 文档中移除表单元素的方法。第一种方法清除选定页面上的所有表单对象,而第二种方法仅移除匹配的 Typewriter 表单资源。这些示例有助于表单清理、模板准备以及文档标准化工作流程。 +--- + +## 从页面中移除所有表单 + +此代码会从指定的页面中删除所有表单对象 `page_num` 并保存更新后的文档。 + +1. 加载 PDF 文档。 +1. 访问页面资源。 +1. 清除表单对象。 +1. 保存更新后的文档。 + +```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) +``` + +## 移除特定的表单类型 + +下面的示例遍历给定 PDF 页面上的表单对象,识别打字机表单注释,删除它们,然后使用 Aspose.PDF for Python via .NET 保存更新后的 PDF。 + +1. 加载 PDF 文档。 +1. 访问页面表单。 +1. 遍历表单。 +1. 检查是否有打字机表单。 +1. 删除匹配的表单。 +1. 保存更新后的文档。 + +```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) +``` + +## 相关主题 + +- [创建 AcroForm](/pdf/zh/python-net/create-form/) +- [填写 AcroForm](/pdf/zh/python-net/fill-form/) +- [修改 AcroForm](/pdf/zh/python-net/modifying-form/) +- [发布表单](/pdf/zh/python-net/posting-form/) diff --git a/zh/python-net/advanced-operations/working-with-forms/xfa-forms/_index.md b/zh/python-net/advanced-operations/working-with-forms/xfa-forms/_index.md new file mode 100644 index 0000000000..c0b90319fc --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-forms/xfa-forms/_index.md @@ -0,0 +1,61 @@ +--- +title: 使用 XFA 表单 +linktitle: XFA 表单 +type: docs +weight: 20 +url: /zh/python-net/xfa-forms/ +description: Aspose.PDF for Python via .NET API 让您能够在 PDF 文档中使用 XFA 和 XFA AcroForm 字段。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +## 将 XFA 转换为 AcroForm + +{{% alert color="primary" %}} + +在线试用 +您可以在此链接检查 Aspose.PDF 转换的质量并在线查看结果: [products.aspose.app/pdf/xfa/acroform](https://products.aspose.app/pdf/xfa/acroform) + +{{% /alert %}} + +下面的代码片段演示如何将动态 XFA(XML Forms Architecture)表单转换为标准 AcroForm。 + +**关键步骤包括:** + +1. 加载输入 PDF 文档。 +1. 将表单类型更改为 STANDARD。 +1. 将转换后的 PDF 保存到新文件。 + +此转换可在不同的 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) +``` + +## IgnoreNeedsRendering 的使用 + +本示例演示了如何使用 Aspose.PDF for Python 将动态 XFA 表单转换为标准 AcroForm。代码会检查输入的 PDF 是否包含 XFA 表单,并在必要时覆盖渲染。随后将表单类型设置为 STANDARD 并保存更新后的 PDF。 + +```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/zh/python-net/advanced-operations/working-with-graphs/_index.md b/zh/python-net/advanced-operations/working-with-graphs/_index.md new file mode 100644 index 0000000000..52b976b360 --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-graphs/_index.md @@ -0,0 +1,43 @@ +--- +title: 在 Python 中使用 PDF 图形 +linktitle: 使用图形 +type: docs +weight: 70 +url: /zh/python-net/working-with-graphs/ +description: 学习如何在 Python 中的 PDF 文件里绘制图形和形状,包括弧线、圆形、曲线、直线、矩形和椭圆。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 在 PDF 文件中绘制和自定义矢量图形形状 +Abstract: 本节介绍 Aspose.PDF for Python via .NET 中的 Graph 类,并解释如何在 PDF 文档中创建常见的矢量形状。学习如何添加和设置弧线、圆形、曲线、直线、矩形、椭圆的样式,并验证形状边界。 +--- + +## 什么是 Graph + +[Aspose.PDF for Python via .NET](/pdf/zh/python-net/) 提供 [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) 用于在 PDF 文档中绘制矢量图形的类。 + +`Graph` 是段落级别的元素,因此你通过页面将其添加到页面中。 `paragraphs` 集合。每个图表包含一个 `Shapes` 可以添加绘图对象(如直线、弧线、圆形、曲线、矩形和椭圆)的集合。 + +当您需要在 Python 中直接在 PDF 页面上绘制矢量图形时,请使用本节,无论是用于图表、图示、插图还是自定义页面注释。 + +## 已覆盖的 Graph Shapes + +以下形状类型受 [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) 类: + +- [弧](/pdf/zh/python-net/add-arc/) - 绘制部分圆形和弧形图表元素的弧段。 +- [圆形](/pdf/zh/python-net/add-circle/) - 为标记和视觉高亮创建圆形轮廓或实心圆。 +- [曲线](/pdf/zh/python-net/add-curve/) - 为自定义路径和光滑图形元素添加贝塞尔曲线。 +- [线](/pdf/zh/python-net/add-line/) - 绘制直线,包括样式化和虚线。 +- [矩形](/pdf/zh/python-net/add-rectangle/) - 创建带轮廓、填充、渐变或透明的矩形形状。 +- [Ellipse](/pdf/zh/python-net/add-ellipse/) - 绘制椭圆形状,并在需要时在其中添加文本。 + +您还可以通过边界检查来验证形状放置: + +- [使用 Python 检查 PDF 图形中的形状边界](/pdf/zh/python-net/aspose-pdf-drawing-graph-shapes-bounds-check/) + +本节的示例在下图中说明: + +![图表中的图形](graphs.png) + diff --git a/zh/python-net/advanced-operations/working-with-graphs/arc/_index.md b/zh/python-net/advanced-operations/working-with-graphs/arc/_index.md new file mode 100644 index 0000000000..5d53fcf745 --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-graphs/arc/_index.md @@ -0,0 +1,95 @@ +--- +title: 在 Python 中向 PDF 添加弧形 +linktitle: 添加弧形 +type: docs +weight: 10 +url: /zh/python-net/add-arc/ +description: 了解如何在 Python 中绘制和填充 PDF 文件中的弧形。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 在 PDF 文件中绘制弧形 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 向 PDF 文档添加弧形。它涵盖了创建描边弧形、绘制填充的弧段以及将它们添加到 Graph 容器中。 +--- + +## 添加 Arc 对象 + +Aspose.PDF for Python via .NET 允许您添加 [弧](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/arc/) 形状到 PDF 页面,使用 [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) 类。您可以绘制带轮廓的弧形和填充的弧形段,用于图表和技术插图。 + +请按照以下步骤: + +1. 创建 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 实例。 +1. 创建 [Graph 对象](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/) 具有特定尺寸。 +1. 设置 [边框](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/#properties) 针对 Graph 对象。 +1. 创建对应的弧对象。 +1. 将此对象添加到图形对象的 Shapes 集合中。 +1. 添加 [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) 对象添加到页面的 paragraphs 集合。 +1. 保存我们的 PDF 文件。 + +以下代码片段展示了如何添加 a。 [弧](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/arc/) 对象。 + +```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) +``` + +## 创建填充弧形对象 + +此示例演示如何添加带颜色填充的弧段。 + +```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) +``` + +添加填充弧形的结果: + +![填充弧形](filled_arc.png) + +## 相关图形主题 + +- [在 Python 中使用 PDF 图形](/pdf/zh/python-net/working-with-graphs/) +- [在 Python 中向 PDF 添加圆形](/pdf/zh/python-net/add-circle/) +- [在 Python 中向 PDF 添加曲线形状](/pdf/zh/python-net/add-curve/) +- [在 Python 中向 PDF 添加直线形状](/pdf/zh/python-net/add-line/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-graphs/arc/filled_arc.png b/zh/python-net/advanced-operations/working-with-graphs/arc/filled_arc.png new file mode 100644 index 0000000000..4b8fb92761 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-graphs/arc/filled_arc.png differ diff --git a/zh/python-net/advanced-operations/working-with-graphs/checking-shape-bounds/_index.md b/zh/python-net/advanced-operations/working-with-graphs/checking-shape-bounds/_index.md new file mode 100644 index 0000000000..e63067c677 --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-graphs/checking-shape-bounds/_index.md @@ -0,0 +1,72 @@ +--- +title: 使用 Python 检查 PDF 图形中的形状边界 +linktitle: 检查形状边界 +type: docs +weight: 70 +url: /zh/python-net/aspose-pdf-drawing-graph-shapes-bounds-check/ +description: 了解如何在 Python 中验证 PDF 图形集合中的形状边界。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 验证 PDF 文件中图形形状的边界 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 验证图形集合中的形状边界。它涵盖了配置 BoundsCheckMode、检测超出范围的形状以及安全处理边界异常。 +--- + +## 检查图形中的形状边界 + +当您向 a 添加形状时 [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/),您可以启用边界验证,以确保每个形状都适合图形区域。 + +使用 [BoundsCheckMode](https://reference.aspose.com/pdf/python-net/aspose.pdf/boundscheckmode/) 定义形状超出范围时的行为。在本例中, `THROW_EXCEPTION_IF_DOES_NOT_FIT` 用于引发异常。 + +请按照以下步骤: + +1. 创建一个新的 PDF [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 添加一个 [页面](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +1. 创建一个 [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) 并将其添加到页面。 +1. 创建一个 [矩形](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/rectangle/) 其超出图形边界。 +1. 将边界检查模式设置为 `THROW_EXCEPTION_IF_DOES_NOT_FIT`. +1. 添加矩形并处理异常。 +1. 保存文档。 + +```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) +``` + +## 备注 + +- 使用 `THROW_EXCEPTION_IF_DOES_NOT_FIT` 当需要严格的布局验证时。 +- 若要宽松的行为,请选择其他 `BoundsCheckMode` 基于您的布局需求的选项。 + +## 相关图形主题 + +- [在 Python 中使用 PDF 图形](/pdf/zh/python-net/working-with-graphs/) +- [在 Python 中向 PDF 添加矩形形状](/pdf/zh/python-net/add-rectangle/) +- [在 Python 中向 PDF 添加直线形状](/pdf/zh/python-net/add-line/) +- [在 Python 中向 PDF 添加椭圆形状](/pdf/zh/python-net/add-ellipse/) diff --git a/zh/python-net/advanced-operations/working-with-graphs/circle/_index.md b/zh/python-net/advanced-operations/working-with-graphs/circle/_index.md new file mode 100644 index 0000000000..976005fb2e --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-graphs/circle/_index.md @@ -0,0 +1,84 @@ +--- +title: 在 Python 中向 PDF 添加圆形形状 +linktitle: 添加圆形 +type: docs +weight: 20 +url: /zh/python-net/add-circle/ +description: 了解如何在 Python 中绘制和填充 PDF 文件中的圆形形状。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 在 PDF 文件中绘制圆形形状 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 向 PDF 文档添加圆形形状。内容包括创建轮廓圆、用颜色填充圆以及在圆对象内部放置文本。 +--- + +## 添加圆形对象 + +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/) 类。使用圆形用于图表、批注和简单的可视元素。 + +请按照以下步骤: + +1. 创建 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 实例。 +1. 创建 [Graph 对象](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/) 具有特定尺寸。 +1. 设置 [边框](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/#properties) 针对 Graph 对象。 +1. 添加 [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) 对象添加到页面的 paragraphs 集合。 +1. 保存我们的 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) +``` + +我们绘制的圆将会是这样的: + +![绘制圆形](drawing_circle.png) + +## 创建填充圆对象 + +此示例演示了如何添加圆形并填充颜色。 + +```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) +``` + +添加填充圆的结果: + +![已填充圆形](filled_circle.png) + +## 相关图形主题 + +- [在 Python 中使用 PDF 图形](/pdf/zh/python-net/working-with-graphs/) +- [在 Python 中向 PDF 添加弧形](/pdf/zh/python-net/add-arc/) +- [在 Python 中向 PDF 添加椭圆形状](/pdf/zh/python-net/add-ellipse/) +- [在 Python 中向 PDF 添加矩形形状](/pdf/zh/python-net/add-rectangle/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-graphs/circle/drawing_circle.png b/zh/python-net/advanced-operations/working-with-graphs/circle/drawing_circle.png new file mode 100644 index 0000000000..13109c6782 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-graphs/circle/drawing_circle.png differ diff --git a/zh/python-net/advanced-operations/working-with-graphs/circle/filled_circle.png b/zh/python-net/advanced-operations/working-with-graphs/circle/filled_circle.png new file mode 100644 index 0000000000..be6042befa Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-graphs/circle/filled_circle.png differ diff --git a/zh/python-net/advanced-operations/working-with-graphs/curve/_index.md b/zh/python-net/advanced-operations/working-with-graphs/curve/_index.md new file mode 100644 index 0000000000..e2a6f6a6ac --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-graphs/curve/_index.md @@ -0,0 +1,85 @@ +--- +title: 在 Python 中向 PDF 添加曲线形状 +linktitle: 添加曲线 +type: docs +weight: 30 +url: /zh/python-net/add-curve/ +description: 了解如何在 Python 中绘制并填充 PDF 文件中的曲线形状。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 在 PDF 文件中绘制曲线形状 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 向 PDF 文档添加曲线形状。内容包括创建带轮廓的曲线、填充曲线对象以及在 Graph 容器中渲染自定义曲线路径。 +--- + +## 添加曲线对象 + +Aspose.PDF for Python via .NET 允许您添加 [曲线](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/curve/) 通过该方式将形状添加到 PDF 页面 [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) 类。 + +本文展示了如何创建带轮廓和填充的曲线。 + +请按照以下步骤: + +1. 创建 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 实例。 +1. 创建 [Graph 对象](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/) 具有特定尺寸。 +1. 设置 [边框](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/#properties) 针对 Graph 对象。 +1. 添加 [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) 对象添加到页面的 paragraphs 集合。 +1. 保存我们的 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) +``` + +下图显示了使用我们的代码片段执行的结果: + +![绘制曲线](drawing_curve.png) + +## 创建填充曲线对象 + +本示例展示了如何添加一个填充颜色的 Curve 对象。 + +```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) +``` + +添加填充曲线的结果: + +![填充曲线](filled_curve.png) + +## 相关图形主题 + +- [在 Python 中使用 PDF 图形](/pdf/zh/python-net/working-with-graphs/) +- [在 Python 中向 PDF 添加弧形](/pdf/zh/python-net/add-arc/) +- [在 Python 中向 PDF 添加直线形状](/pdf/zh/python-net/add-line/) +- [在 Python 中向 PDF 添加椭圆形状](/pdf/zh/python-net/add-ellipse/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-graphs/curve/drawing_curve.png b/zh/python-net/advanced-operations/working-with-graphs/curve/drawing_curve.png new file mode 100644 index 0000000000..be9f2e5ceb Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-graphs/curve/drawing_curve.png differ diff --git a/zh/python-net/advanced-operations/working-with-graphs/curve/filled_curve.png b/zh/python-net/advanced-operations/working-with-graphs/curve/filled_curve.png new file mode 100644 index 0000000000..c1422bb267 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-graphs/curve/filled_curve.png differ diff --git a/zh/python-net/advanced-operations/working-with-graphs/ellipse/_index.md b/zh/python-net/advanced-operations/working-with-graphs/ellipse/_index.md new file mode 100644 index 0000000000..7b665fd44e --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-graphs/ellipse/_index.md @@ -0,0 +1,113 @@ +--- +title: 在 Python 中向 PDF 添加椭圆形状 +linktitle: 添加椭圆 +type: docs +weight: 60 +url: /zh/python-net/add-ellipse/ +description: 了解如何在 Python 中绘制、填充并标记 PDF 文件中的椭圆形状。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 在 PDF 文件中绘制椭圆形状 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 向 PDF 文档添加椭圆形状。它涵盖了描边椭圆、填充椭圆以及在椭圆对象内部添加文本。 +--- + +## 添加 Ellipse 对象 + +Aspose.PDF for Python via .NET 允许您添加 [Ellipse](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/ellipse/) 使用 the 将形状添加到 PDF 页面 [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) 类。您可以绘制椭圆轮廓、设置填充颜色,并在椭圆对象内部放置文本。 + +```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) +``` + +![添加椭圆](ellipse.png) + +## 创建填充椭圆对象 + +以下代码片段展示了如何添加 a。 [Ellipse](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/ellipse/) 被颜色填充的对象。 + +```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) +``` + +![已填充椭圆](fill_ellipse.png) + +## 在椭圆内添加文本 + +Aspose.PDF for Python via .NET 还允许您在形状对象内放置文本。下面的示例向椭圆形状添加文本。 + +```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) +``` + +![椭圆内的文本](text_ellipse.png) + +## 相关图形主题 + +- [在 Python 中使用 PDF 图形](/pdf/zh/python-net/working-with-graphs/) +- [在 Python 中向 PDF 添加圆形](/pdf/zh/python-net/add-circle/) +- [在 Python 中向 PDF 添加曲线形状](/pdf/zh/python-net/add-curve/) +- [在 Python 中向 PDF 添加矩形形状](/pdf/zh/python-net/add-rectangle/) diff --git a/zh/python-net/advanced-operations/working-with-graphs/ellipse/ellipse.png b/zh/python-net/advanced-operations/working-with-graphs/ellipse/ellipse.png new file mode 100644 index 0000000000..0322050025 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-graphs/ellipse/ellipse.png differ diff --git a/zh/python-net/advanced-operations/working-with-graphs/ellipse/fill_ellipse.png b/zh/python-net/advanced-operations/working-with-graphs/ellipse/fill_ellipse.png new file mode 100644 index 0000000000..ef85eef54a Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-graphs/ellipse/fill_ellipse.png differ diff --git a/zh/python-net/advanced-operations/working-with-graphs/ellipse/text_ellipse.png b/zh/python-net/advanced-operations/working-with-graphs/ellipse/text_ellipse.png new file mode 100644 index 0000000000..20468c71f2 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-graphs/ellipse/text_ellipse.png differ diff --git a/zh/python-net/advanced-operations/working-with-graphs/graphs.png b/zh/python-net/advanced-operations/working-with-graphs/graphs.png new file mode 100644 index 0000000000..b9574829a8 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-graphs/graphs.png differ diff --git a/zh/python-net/advanced-operations/working-with-graphs/line/_index.md b/zh/python-net/advanced-operations/working-with-graphs/line/_index.md new file mode 100644 index 0000000000..3395071473 --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-graphs/line/_index.md @@ -0,0 +1,109 @@ +--- +title: 在 Python 中向 PDF 添加线形状 +linktitle: 添加线条 +type: docs +weight: 40 +url: /zh/python-net/add-line/ +description: 学习如何在 Python 中的 PDF 文件中绘制线形状和样式化线条。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 在 PDF 文件中绘制线形状 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 向 PDF 文档添加线形状。它涵盖了创建基本线条、配置虚线样式以及在页面上绘制线条。 +--- + +## 添加线对象 + +Aspose.PDF for Python via .NET 允许您添加 [线](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/line/) 形状到 PDF 页面,使用 [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) 类。您可以控制线的颜色、虚线模式和位置。 + +请按照以下步骤: + +1. 创建 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 实例。 +1. 创建图形对象 +1. 添加 [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) 对象添加到页面的 paragraphs 集合。 +1. 创建并配置线条 +1. 添加 [线](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/line/) 到图形 +1. 保存我们的 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) +``` + +![添加线条](add_line.png) + +## 如何在 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) +``` + +添加点划线后的结果: + +![虚线](dash_line.png) + +## 在页面上绘制线条 + +您也可以在页面上绘制线条以形成十字交叉。 + +```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) +``` + +![绘制线条](draw_line.png) + +## 相关图形主题 + +- [在 Python 中使用 PDF 图形](/pdf/zh/python-net/working-with-graphs/) +- [在 Python 中向 PDF 添加曲线形状](/pdf/zh/python-net/add-curve/) +- [在 Python 中向 PDF 添加矩形形状](/pdf/zh/python-net/add-rectangle/) +- [使用 Python 检查 PDF 图形中的形状边界](/pdf/zh/python-net/aspose-pdf-drawing-graph-shapes-bounds-check/) diff --git a/zh/python-net/advanced-operations/working-with-graphs/line/add_line.png b/zh/python-net/advanced-operations/working-with-graphs/line/add_line.png new file mode 100644 index 0000000000..4cb1631d6f Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-graphs/line/add_line.png differ diff --git a/zh/python-net/advanced-operations/working-with-graphs/line/dash_line.png b/zh/python-net/advanced-operations/working-with-graphs/line/dash_line.png new file mode 100644 index 0000000000..2021f2d82a Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-graphs/line/dash_line.png differ diff --git a/zh/python-net/advanced-operations/working-with-graphs/line/draw_line.png b/zh/python-net/advanced-operations/working-with-graphs/line/draw_line.png new file mode 100644 index 0000000000..07e95f957a Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-graphs/line/draw_line.png differ diff --git a/zh/python-net/advanced-operations/working-with-graphs/rectangle/_index.md b/zh/python-net/advanced-operations/working-with-graphs/rectangle/_index.md new file mode 100644 index 0000000000..0c5600e759 --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-graphs/rectangle/_index.md @@ -0,0 +1,195 @@ +--- +title: 在 Python 中向 PDF 添加矩形形状 +linktitle: 添加矩形 +type: docs +weight: 50 +url: /zh/python-net/add-rectangle/ +description: 学习如何在 Python 中绘制和填充 PDF 文件中的矩形形状。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 在 PDF 文件中绘制矩形形状 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 向 PDF 文档添加矩形形状。它涵盖了带轮廓的矩形、实色和渐变填充、Alpha 透明度以及 Z-order 控制。 +--- + +## 添加 Rectangle 对象 + +Aspose.PDF for Python via .NET 允许您添加 [矩形](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/rectangle/) 通过该方式将形状添加到 PDF 页面 [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) 类。您可以绘制带轮廓的矩形并应用实色、渐变或透明填充。 + +请按照以下步骤: + +1. 创建一个新的 PDF [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 添加 [页面](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 到 PDF 文件的 pages 集合。 +1. 添加 [文本片段](https://reference.aspose.com/pdf/python-net/aspose.pdf/textfragment/) 到页面实例的段落集合。 +1. 创建 [Graph](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/graph/) 实例。 +1. 设置边框 [Graph 对象](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/). +1. 添加 [矩形](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/rectangle/) 对象到 Graph 对象的形状集合。 +1. 将图形对象添加到页面实例的段落集合中。 +1. 添加 [文本片段](https://reference.aspose.com/pdf/python-net/aspose.pdf/textfragment/) 到页面实例的段落集合。 +1. 并保存您的 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) +``` + +![创建矩形](create_rectangle.png) + +## 创建填充矩形对象 + +Aspose.PDF for Python via .NET 还提供了用特定颜色填充矩形对象的功能。 + +以下代码片段展示了如何添加 a。 [矩形](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/rectangle/) 被颜色填充的对象。 + +```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) +``` + +填充纯色的矩形的结果: + +![已填充的矩形](fill_rectangle.png) + +## 添加带渐变填充的绘图 + +Aspose.PDF for Python via .NET 支持向 PDF 文档添加图形对象的功能,有时需要用渐变颜色填充图形对象。 + +以下代码片段展示了如何添加 a。 [矩形](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/rectangle/) 填充了渐变颜色的对象。 + +```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) +``` + +![渐变矩形](gradient.png) + +## 创建带 Alpha 颜色通道的矩形 + +Aspose.PDF for Python via .NET 也支持通过 Alpha 颜色通道实现透明度。 + +以下代码片段展示了如何添加 a。 [矩形](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/rectangle/) 带有 Alpha 值的对象。 + +```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) +``` + +![矩形 Alpha 通道颜色](rectangle_color.png) + +## 控制形状的 Z-Order + +Aspose.PDF for .NET 支持向 PDF 文档添加图形对象(例如图形、线条、矩形等)的功能。向 PDF 文件中添加同一对象的多个实例时,我们可以通过指定 Z-Order 来控制它们的渲染。Z-Order 还用于需要将对象相互叠加渲染的情况。 + +以下代码片段展示了渲染的步骤 [矩形](https://reference.aspose.com/pdf/python-net/aspose.pdf.drawing/rectangle/) 相互叠加的对象。 + +```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) +``` + +![控制 Z 顺序](control.png) + +## 相关图形主题 + +- [在 Python 中使用 PDF 图形](/pdf/zh/python-net/working-with-graphs/) +- [使用 Python 检查 PDF 图形中的形状边界](/pdf/zh/python-net/aspose-pdf-drawing-graph-shapes-bounds-check/) +- [在 Python 中向 PDF 添加直线形状](/pdf/zh/python-net/add-line/) +- [在 Python 中向 PDF 添加椭圆形状](/pdf/zh/python-net/add-ellipse/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-graphs/rectangle/control.png b/zh/python-net/advanced-operations/working-with-graphs/rectangle/control.png new file mode 100644 index 0000000000..b7c0f8b35c Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-graphs/rectangle/control.png differ diff --git a/zh/python-net/advanced-operations/working-with-graphs/rectangle/create_rectangle.png b/zh/python-net/advanced-operations/working-with-graphs/rectangle/create_rectangle.png new file mode 100644 index 0000000000..f2748957f4 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-graphs/rectangle/create_rectangle.png differ diff --git a/zh/python-net/advanced-operations/working-with-graphs/rectangle/fill_rectangle.png b/zh/python-net/advanced-operations/working-with-graphs/rectangle/fill_rectangle.png new file mode 100644 index 0000000000..264a88da44 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-graphs/rectangle/fill_rectangle.png differ diff --git a/zh/python-net/advanced-operations/working-with-graphs/rectangle/gradient.png b/zh/python-net/advanced-operations/working-with-graphs/rectangle/gradient.png new file mode 100644 index 0000000000..854480c132 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-graphs/rectangle/gradient.png differ diff --git a/zh/python-net/advanced-operations/working-with-graphs/rectangle/rectangle_color.png b/zh/python-net/advanced-operations/working-with-graphs/rectangle/rectangle_color.png new file mode 100644 index 0000000000..e14ed9fef0 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-graphs/rectangle/rectangle_color.png differ diff --git a/zh/python-net/advanced-operations/working-with-images/_index.md b/zh/python-net/advanced-operations/working-with-images/_index.md index 6879a8645c..7ddb1337c6 100644 --- a/zh/python-net/advanced-operations/working-with-images/_index.md +++ b/zh/python-net/advanced-operations/working-with-images/_index.md @@ -4,85 +4,27 @@ linktitle: 处理图像 type: docs weight: 40 url: /zh/python-net/working-with-images/ -description: 本节介绍使用 Python 库在 PDF 文件中处理图像的功能。 -lastmod: "2023-04-17" +description: 了解如何使用 Python 添加、删除、提取、替换和检查 PDF 文档中的图像。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 管理 PDF 文件中的图像 +Abstract: 本节展示了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中处理图像。它涵盖了对现有 PDF 文件中图像的添加、删除、提取、替换和检查。 --- - +Aspose.PDF for Python via .NET 为现有 PDF 文档中的图像操作提供了一整套工具。 -有许多方法和工具可以编辑和操作PDF文档中的图像。 -除了通常的在PDF文件中添加和删除图像的功能外,Aspose.PDF for Python库还允许提取图像。 -**Aspose.PDF for Python** 是一个智能高效的工具,用于处理现有PDF中的图像。 +使用此部分在页面上插入新图像、删除或替换嵌入的图像、提取图像内容,并检查图像的放置细节。 -您可以执行以下操作: +## 涉及的图像任务 + +以下任务已覆盖: + +- [向现有 PDF 文件添加图像](/pdf/zh/python-net/add-image-to-existing-pdf-file/) - 将图像放置在固定坐标位置,并使用不同选项嵌入图像。 +- [从 PDF 文件中删除图像](/pdf/zh/python-net/delete-images-from-pdf-file/) - 从选定页面中删除单个图像资源或全部图像。 +- [从 PDF 文件提取图像](/pdf/zh/python-net/extract-images-from-pdf-file/) - 从 PDF 页面提取嵌入的图像。 +- [在现有 PDF 文件中替换图像](/pdf/zh/python-net/replace-image-in-existing-pdf-file/) - 按资源索引或位置替换嵌入的图像。 +- [搜索并获取 PDF 文档中的图像](/pdf/zh/python-net/search-and-get-images-from-pdf-document/) - 查找图像并检查文档中的图像位置。 -- [添加图像到现有PDF文件](/pdf/zh/python-net/add-image-to-existing-pdf-file/) - 在PDF文档中添加单个图像和引用,然后控制质量。 -- [从PDF文件中删除图像](/pdf/zh/python-net/delete-images-from-pdf-file/) - 查看删除PDF文件中图像的代码片段。 -- [从PDF文件中提取图像](/pdf/zh/python-net/extract-images-from-pdf-file/) - 下一篇文章展示如何使用Python库从PDF文件中提取图像。 \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-images/add-image-to-existing-pdf-file/_index.md b/zh/python-net/advanced-operations/working-with-images/add-image-to-existing-pdf-file/_index.md index 52a7e39011..de0a3f9325 100644 --- a/zh/python-net/advanced-operations/working-with-images/add-image-to-existing-pdf-file/_index.md +++ b/zh/python-net/advanced-operations/working-with-images/add-image-to-existing-pdf-file/_index.md @@ -4,22 +4,22 @@ linktitle: 向 PDF 添加图像 type: docs weight: 10 url: /zh/python-net/add-image-to-existing-pdf-file/ -description: 了解如何在 Python 中向现有 PDF 文件添加图像、将其放置在固定坐标、设置替代文本并使用图像压缩。 -lastmod: "2026-05-05" +description: 了解如何在 Python 中向现有 PDF 文件添加图像,放置在固定坐标位置,设置替代文本,并使用图像压缩。 +lastmod: "2026-06-08" TechArticle: true AlternativeHeadline: 使用 Python 向现有 PDF 文件添加图像 -Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 向 PDF 文档添加图像。内容包括在固定坐标处放置图像、使用低级 PDF 操作符绘制图像、为可访问性分配替代文本以及使用 Flate compression 嵌入图像。 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 向 PDF 文档添加图像。它涵盖了在固定坐标放置图像、使用低级 PDF 操作符绘制图像、为可访问性分配替代文本以及使用 Flate compression 嵌入图像。 --- ## 在 Python 中向现有 PDF 文件添加图像 -此示例展示了如何使用 Aspose.PDF for Python via .NET 在现有 PDF 页面上的固定位置放置图像。 +本示例展示了如何使用 Aspose.PDF for Python via .NET 在现有 PDF 页面上以固定位置放置图像。 -当您需要向现有 PDF 布局中添加徽标、照片、印章、图表或其他图形时,请使用这些示例。您可以使用页面坐标放置图像、使用操作符绘制图像、添加可访问性文本,或控制图像压缩。 +当您需要向现有 PDF 布局中添加徽标、照片、印章、图表或其他图形时,请使用这些示例。您可以使用页面坐标放置图像、通过操作符绘制图像、添加可访问性文本或控制图像压缩。 1. 加载现有的 PDF `ap.Document(infile)`. 1. 选择目标页面(`document.pages[1]` 针对第一页)。 -1. 呼叫 `page.add_image()` 使用: +1. 调用 `page.add_image()` 使用: - 图像文件路径。 - A `Rectangle` 定义放置坐标。 1. 保存更新后的 PDF。 @@ -37,12 +37,12 @@ def add_image(infile, image_file, outfile): ## 使用运算符向 PDF 添加图像 -此方法使用低级 PDF 运算符添加图像,而不是高级的 `add_image()` 帮助者。 +此方法使用低级 PDF 操作符添加图像,而不是高级的 `add_image()` 助手。 -1. 创建一个新 `Document` 并添加一页。 +1. 创建一个新 `Document` 并添加一个页面。 1. 将图像添加到页面资源(`page.resources.images`). -1. 创建转换运算符(`GSave`, `ConcatenateMatrix`, `Do`, `GRestore`). -1. 将操作符添加到页面内容。 +1. 创建转换运算符 (`GSave`, `ConcatenateMatrix`, `Do`, `GRestore`). +1. 向页面内容添加运算符。 1. 保存生成的 PDF。 ```python @@ -83,12 +83,12 @@ def add_image_using_operators(image_file, outfile): ## 向 PDF 添加带替代文本的图像 -此示例添加了一张图像并为可访问性分配替代文本。 +此示例添加图像并为可访问性分配替代文本。 -1. 创建一个新 `Document` 并添加一页。 -1. 将图像添加到页面,使用 `page.add_image()`. -1. 获取图像资源来源 `page.resources.images`. -1. 使用设置替代文本 `try_set_alternative_text()`. +1. 创建一个新 `Document` 并添加一个页面。 +1. 将图像添加到页面 `page.add_image()`. +1. 获取图像资源 `page.resources.images`. +1. 使用设置 alt 文本 `try_set_alternative_text()`. 1. 保存生成的 PDF。 ```python @@ -115,9 +115,9 @@ def add_image_set_alternative_text(image_file, outfile): 此示例使用嵌入图像 `ImageFilterType.FLATE` 压缩。 -1. 创建一个新 `Document` 并添加一页。 +1. 创建一个新 `Document` 并添加一个页面。 1. 将图像以 Flate 压缩方式添加到页面资源中。 -1. 使用矩阵运算符放置并绘制图像。 +1. 使用矩阵运算符来放置和绘制图像。 1. 保存文档。 ```python @@ -153,7 +153,7 @@ def add_image_to_pdf_with_flate_compression(image_file, outfile): ## 相关图像主题 -- [使用 Python 在 PDF 中处理图像](/pdf/zh/python-net/working-with-images/) -- [替换已有 PDF 文件中的图像](/pdf/zh/python-net/replace-image-in-existing-pdf-file/) +- [使用 Python 处理 PDF 中的图像](/pdf/zh/python-net/working-with-images/) +- [替换现有 PDF 文件中的图像](/pdf/zh/python-net/replace-image-in-existing-pdf-file/) - [从 PDF 文件中删除图像](/pdf/zh/python-net/delete-images-from-pdf-file/) - [从 PDF 文件中提取图像](/pdf/zh/python-net/extract-images-from-pdf-file/) diff --git a/zh/python-net/advanced-operations/working-with-images/delete-images-from-pdf-file/_index.md b/zh/python-net/advanced-operations/working-with-images/delete-images-from-pdf-file/_index.md index 85fd7971b5..c8c0bc694e 100644 --- a/zh/python-net/advanced-operations/working-with-images/delete-images-from-pdf-file/_index.md +++ b/zh/python-net/advanced-operations/working-with-images/delete-images-from-pdf-file/_index.md @@ -1,193 +1,58 @@ --- -title: 从 PDF 文件中删除图像使用 Python +title: 使用 Python 删除 PDF 文件中的图像 linktitle: 删除图像 type: docs weight: 20 url: /zh/python-net/delete-images-from-pdf-file/ -description: 本节解释如何使用 Aspose.PDF for Python via .NET 从 PDF 文件中删除图像。 -lastmod: "2023-04-17" +description: 了解如何在 Python 中从 PDF 文件中删除特定图像或全部图像。 +lastmod: "2026-06-08" +TechArticle: true +AlternativeHeadline: 使用 Python 删除 PDF 文件中的图像 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 从 PDF 文档中删除图像。它涵盖了删除特定图像资源以及从选定页面删除所有图像的操作。 --- - - - -有很多理由需要从 PDF 中删除所有或特定的图像。 - -有时,PDF 文件可能包含需要删除的重要图像,以保护隐私或防止未经授权访问某些信息。 - -删除不需要或冗余的图像可以帮助减少文件大小,从而更容易共享或存储 PDF。 - -如有必要,您可以通过删除文档中的所有图像来减少页数。此外,从文档中删除图像将有助于为 PDF 的压缩或提取文本信息做准备。 - -**Aspose.PDF for Python via .NET** 将帮助您完成此任务。 -## 从 PDF 文件中删除图像 +当您需要删除不必要的图形、减小 PDF 大小或清除文档中敏感的视觉内容时,请使用此页面。 -要从 PDF 文件中删除图像: +## 从 PDF 文件中删除图像 -1. 打开现有的 PDF 文档。 -2. 删除特定的图像。 -3. 保存更新后的 PDF 文件。 +使用以下步骤从页面中删除单个图像: -以下代码片段展示了如何从 PDF 文件中删除图像。 +1. 使用加载源 PDF `ap.Document(infile)`. +1. 选择页面和图像资源索引。 +1. 删除图像 `resources.images.delete(index)`. +1. 保存更新后的 PDF。 ```python +import aspose.pdf as ap - import aspose.pdf as ap - - # 打开文档 - document = ap.Document(input_file) - - # 删除特定图像 - document.pages[2].resources.images.delete(1) - # 保存更新后的 PDF 文件 - document.save(output_pdf) +def delete_image(infile, outfile): + document = ap.Document(infile) + document.pages[1].resources.images.delete(1) + document.save(outfile) ``` +## 删除页面上的所有图像 -## 从输入 PDF 中删除所有图像 +使用此示例从特定页面中删除所有图像。 ```python +import aspose.pdf as ap - import aspose.pdf as ap - # 打开文档 - document = ap.Document(input_file) +def delete_all_images_from_page(infile, outfile, page_number): + document = ap.Document(infile) + page = document.pages[page_number] - # 删除所有页面上的所有图像 - 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) - # 保存更新后的 PDF 文件 - document.save(output_file) + document.save(outfile) ``` +## 相关图像主题 - \ No newline at end of file +- [使用 Python 处理 PDF 中的图像](/pdf/zh/python-net/working-with-images/) +- [替换现有 PDF 文件中的图像](/pdf/zh/python-net/replace-image-in-existing-pdf-file/) +- [从 PDF 文件中提取图像](/pdf/zh/python-net/extract-images-from-pdf-file/) +- [向现有 PDF 文件添加图像](/pdf/zh/python-net/add-image-to-existing-pdf-file/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-images/extract-images-from-pdf-file/_index.md b/zh/python-net/advanced-operations/working-with-images/extract-images-from-pdf-file/_index.md index 60ef70ae64..a5208670ca 100644 --- a/zh/python-net/advanced-operations/working-with-images/extract-images-from-pdf-file/_index.md +++ b/zh/python-net/advanced-operations/working-with-images/extract-images-from-pdf-file/_index.md @@ -1,162 +1,69 @@ --- -title: 从 PDF 文件中提取图像使用 Python +title: 使用 Python 从 PDF 文件中提取图像 linktitle: 提取图像 type: docs weight: 30 url: /zh/python-net/extract-images-from-pdf-file/ -description: 本节展示如何使用 Python 库从 PDF 文件中提取图像。 -lastmod: "2023-02-17" +description: 了解如何在 Python 中从 PDF 文件中提取嵌入的图像。 +lastmod: "2026-06-08" +TechArticle: true +AlternativeHeadline: 使用 Python 从 PDF 文件中提取图像 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 从 PDF 文档中提取图像。内容涵盖提取单个嵌入图像以及导出页面上特定矩形区域内找到的图像。 --- - +当您需要复用嵌入的图形、归档图像资源或在 PDF 之外处理图像内容时,请使用此页面。 -你是否需要从PDF文件中分离图像?为了简化管理、存档、分析或分享文档中的图像,可以使用**Aspose.PDF for Python**从PDF文件中提取图像。 +1. 使用加载源 PDF `ap.Document(infile)`. +1. 选择目标页面和图像资源索引。 +1. 将图像对象保存到输出流。 -图像保存在每个页面的[资源](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties)集合的[XImage](https://reference.aspose.com/pdf/python-net/aspose.pdf/ximagecollection/)集合中。要提取特定页面的图像,可以使用图像的特定索引从Images集合中获取图像。 +```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) +``` + +## 从 PDF 的特定区域提取图像 + +此示例提取位于 PDF 页面上指定矩形区域内的图像,并将它们另存为单独的文件。 -图像的索引返回一个[XImage](https://reference.aspose.com/pdf/python-net/aspose.pdf/ximage/)对象。该对象提供一个[save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods)方法,可以用来保存提取的图像。以下代码片段展示了如何从PDF文件中提取图像。 +1. 加载源 PDF。 +1. 创建 `ImagePlacementAbsorber` 并在目标页面上接受它。 +1. 定义目标矩形。 +1. 遍历图像放置项,并检查每个图像的边界是否适合该区域。 +1. 将匹配的图像保存到输出文件。 ```python +import aspose.pdf as ap +from io import FileIO - import aspose.pdf as ap - # 打开文档 - 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) - # 提取特定图像 - 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) - # 保存输出图像 - 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 ``` +## 相关图像主题 - \ No newline at end of file +- [使用 Python 处理 PDF 中的图像](/pdf/zh/python-net/working-with-images/) +- [替换现有 PDF 文件中的图像](/pdf/zh/python-net/replace-image-in-existing-pdf-file/) +- [从 PDF 文件中删除图像](/pdf/zh/python-net/delete-images-from-pdf-file/) +- [向现有 PDF 文件添加图像](/pdf/zh/python-net/add-image-to-existing-pdf-file/) diff --git a/zh/python-net/advanced-operations/working-with-images/replace-image-in-existing-pdf-file/_index.md b/zh/python-net/advanced-operations/working-with-images/replace-image-in-existing-pdf-file/_index.md new file mode 100644 index 0000000000..a9bf46aad4 --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-images/replace-image-in-existing-pdf-file/_index.md @@ -0,0 +1,70 @@ +--- +title: 使用 Python 在已有 PDF 文件中替换图像 +linktitle: 替换图像 +type: docs +weight: 70 +url: /zh/python-net/replace-image-in-existing-pdf-file/ +description: 了解如何在 Python 中替换已有 PDF 文件中的嵌入图像。 +lastmod: "2026-06-08" +TechArticle: true +AlternativeHeadline: 使用 Python 替换已有 PDF 文件中的图像 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中替换图像。它涵盖了通过资源索引替换图像以及使用 ImagePlacementAbsorber 替换特定找到的图像。 +--- + +## 在 PDF 中替换图像 + +当您需要在 PDF 中更新徽标、图表或其他嵌入式图形且无需重新构建文档布局时,请使用此页面。 + +1. 使用加载源 PDF `ap.Document(infile)`. +1. 将替换图像以二进制流的形式打开。 +1. 按索引在页面上替换图像资源。 +1. 保存更新后的 PDF。 + +```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) +``` + +## 替换特定图像 + +此示例替换由...找到的特定图像放置 `ImagePlacementAbsorber`. + +1. 加载源 PDF。 +1. 创建 `ImagePlacementAbsorber` 并收集页面上的图像放置位置。 +1. 检查页面上是否存在任何图像位置。 +1. 用新的图像流替换所选位置。 +1. 保存更新后的 PDF。 + +```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) +``` + +## 相关图像主题 + +- [使用 Python 处理 PDF 中的图像](/pdf/zh/python-net/working-with-images/) +- [从 PDF 文件中删除图像](/pdf/zh/python-net/delete-images-from-pdf-file/) +- [从 PDF 文件中提取图像](/pdf/zh/python-net/extract-images-from-pdf-file/) +- [向现有 PDF 文件添加图像](/pdf/zh/python-net/add-image-to-existing-pdf-file/) diff --git a/zh/python-net/advanced-operations/working-with-images/search-and-get-images-from-pdf-document/_index.md b/zh/python-net/advanced-operations/working-with-images/search-and-get-images-from-pdf-document/_index.md new file mode 100644 index 0000000000..6df44007b0 --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-images/search-and-get-images-from-pdf-document/_index.md @@ -0,0 +1,236 @@ +--- +title: 获取并搜索 PDF 中的图像 +linktitle: 获取并搜索图像 +type: docs +weight: 40 +url: /zh/python-net/search-and-get-images-from-pdf-document/ +description: 了解如何在 Python 中搜索和检查 PDF 文档中的图像。 +lastmod: "2026-06-08" +TechArticle: true +AlternativeHeadline: 使用 Python 搜索并检查 PDF 文件中的图像 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中搜索和检查图像。它涵盖了使用 ImagePlacementAbsorber 来分析图像的放置位置、大小、分辨率和替代文本。 +--- + +## 检查 PDF 页面中的图像放置属性 + +本示例演示了如何使用 Aspose.PDF for Python via .NET 分析并显示特定 PDF 页面上所有图像的属性。 + +当您需要审计图像放置、检查图像分辨率或识别跨 PDF 页面嵌入的图像对象时,请使用此页面。 + +1. 创建一个 'ImagePlacementAbsorber' 来收集页面上的所有图像。 +1. 调用 'document.pages[1].accept(absorber)' 来分析第一页上的图像布局。 +1. 遍历 'absorber.image_placements' 并显示每个图像的关键属性: + - 宽度和高度(点)。 + - 左下 X (LLX) 和 左下 Y (LLY) 坐标。 + - 水平 (X) 和 垂直 (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)) +``` + +## 提取并统计 PDF 中的图像类型 + +此函数分析 PDF 首页的所有图像,并统计其中的灰度图像和 RGB 图像数量。 + +1. 创建一个 'ImagePlacementAbsorber' 来收集页面上的所有图像。 +1. 初始化灰度和 RGB 图像的计数器。 +1. 调用 'document.pages[1].accept(absorber)' 来分析图像放置位置。 +1. 打印找到的图像总数。 +1. 遍历 'absorber.image_placements' 中的每个图像: + - 使用 `image_placement.image.get_color_type()` 获取图像颜色类型。 + - 增加相应的计数器(灰度或 rgb)。 + - 为每个图像打印一条消息,指示它是灰度还是 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)) +``` + +## 从 PDF 中提取详细的图像信息 + +此函数分析 PDF 第一页上的所有图像,并根据页面的图形变换计算它们的缩放尺寸和有效分辨率。 + +1. 加载 PDF 并初始化变量 +1. 收集图像资源 +1. 处理页面内容操作符: + - 'GSave' - 将当前 CTM 推入堆栈。 + - 'GRestore' - 从堆栈中弹出最后一个 CTM。 + - 'ConcatenateMatrix' - 通过与运算符的矩阵相乘来更新当前 CTM。 +1. 打印图像名称、缩放后的尺寸和计算得到的分辨率。 + +```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()) +``` + +## 从 PDF 中提取图像的替代文本 + +此函数从 PDF 第一页的所有图像中检索替代文本(alt text),对可访问性和 PDF/UA 合规性检查很有用。 + +1. 使用 'ap.Document()' 加载 PDF 文档。 +1. 创建一个 'ImagePlacementAbsorber' 来收集页面上的所有图像。 +1. 在第一页接受吸收器(page.accept(absorber))。 +1. 遍历 'absorber.image_placements' 中的每个图像: + - 打印页面资源集合中图像的名称 (get_name_in_collection()). + - 使用 'get_alternative_text(page)' 检索替代文本。 + - 打印 alt 文本的第一行。 + +```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]) +``` + +## 相关图像主题 + +- [使用 Python 处理 PDF 中的图像](/pdf/zh/python-net/working-with-images/) +- [从 PDF 文件中提取图像](/pdf/zh/python-net/extract-images-from-pdf-file/) +- [替换现有 PDF 文件中的图像](/pdf/zh/python-net/replace-image-in-existing-pdf-file/) +- [向现有 PDF 文件添加图像](/pdf/zh/python-net/add-image-to-existing-pdf-file/) diff --git a/zh/python-net/advanced-operations/working-with-layers/_index.md b/zh/python-net/advanced-operations/working-with-layers/_index.md new file mode 100644 index 0000000000..651f062d2d --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-layers/_index.md @@ -0,0 +1,220 @@ +--- +title: 使用 Python 处理 PDF 图层 +linktitle: 处理 PDF 图层 +type: docs +weight: 50 +url: /zh/python-net/working-with-pdf-layers/ +description: 了解如何在 Python 中添加、锁定、提取、扁平化和合并 PDF 图层。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 管理 PDF 图层。 +Abstract: 本文介绍了如何使用 Aspose.PDF for Python via .NET 操作 PDF 图层(可选内容组)。了解如何添加图层、锁定图层可见性、提取图层内容、扁平化图层内容以及将多个图层合并为一个。 +--- + +PDF 层,也称为可选内容组(OCG),允许您将内容组织成可在兼容的 PDF 查看器中显示或隐藏的独立视觉组。在 Aspose.PDF 中,层操作基于 [`Layer`](https://reference.aspose.com/pdf/python-net/aspose.pdf/layer/) API。 + +使用 Aspose.PDF for Python via .NET,您可以: + +- 在页面上添加多个图层。 +- 锁定和解锁图层以控制可见性行为。 +- 将图层提取为单独的文件或流。 +- 将分层内容展平到页面。 +- 将多个图层合并为一个图层。 + +## 向 PDF 添加图层 + +此示例创建一个具有三个图层的 PDF。它使用一个 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/),添加 一个 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/),并追加 [`Layer`](https://reference.aspose.com/pdf/python-net/aspose.pdf/layer/) 对象到该页面。 + +1. 创建一个新 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 并添加一个 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +1. 创建并添加红色图层。 +1. 创建并添加绿色图层。 +1. 创建并添加蓝色层。 +1. 保存 PDF 文档。 + +生成的 PDF 将包含三个独立的图层:一条红线、一条绿线和一条蓝线。每个图层都可以在支持分层内容的 PDF 阅读器中打开或关闭。 + +```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}") +``` + +## 锁定 PDF 图层 + +此示例打开一个 PDF,在第一页锁定特定图层,并保存更新后的文件。 + +锁定图层可防止用户在支持的 PDF 查看器中更改该图层的可见性状态。图层从页面访问,并通过页面的图层集合进行管理。 + +可用的方法和属性: + +- [`Layer.lock()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/layer/#methods) 锁定该图层。 +- [`Layer.unlock()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/layer/#methods) 解锁该层。 +- [`Layer.locked`](https://reference.aspose.com/pdf/python-net/aspose.pdf/layer/#properties) 返回当前锁定状态。 + +1. 打开 PDF 文档。 +1. 访问 PDF 的第一页。 +1. 检查页面是否有图层。 +1. 获取第一层并锁定它。 +1. 保存更新后的 PDF。 + +如果 PDF 包含图层,第一层将被锁定,确保用户无法更改其可见性状态。如果未找到图层,则会打印一条消息。 + +```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.") +``` + +## 提取 PDF 图层元素 + +本示例使用 Aspose.PDF for Python via .NET 库,从 PDF 文档的首页提取各个图层,并通过使用将每个图层保存为单独的 PDF 文件 [`Layer.save()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/layer/#methods). + +要从图层创建新的 PDF,您可以使用以下代码片段: + +1. 加载 PDF [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 访问第1页的图层 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +1. 检查是否存在图层。 +1. 遍历图层并保存每个图层。 + +```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 +``` + +可以提取 PDF 图层元素并将其保存到新的 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}") +``` + +## 扁平化分层 PDF + +此脚本使用 Aspose.PDF for Python via .NET 将 PDF 文档的首页的所有图层进行扁平化。扁平化将每个图层的可视内容合并为一个统一的图层,使得打印、共享或归档更为简便,同时不失去视觉保真度或图层特定的数据。该操作使用 [`Layer.flatten()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/layer/#methods). + +1. 加载 PDF 文档。 +1. 访问第1页的图层。 +1. 检查是否存在图层。 +1. 使用以下方式扁平化每个图层 `layer.flatten(True)`. +1. 保存修改后的文档。 + +```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}") +``` + +## 将PDF中的所有图层合并为一个 + +此代码片段使用 Aspose.PDF 将 PDF 第一页的所有图层合并为一个具有自定义名称的统一图层,方法是使用 [`Page.merge_layers()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods). + +1. 加载 PDF 文档。 +1. 访问第1页并检索其图层。 +1. 检查是否存在图层。 +1. 定义一个新图层名称。 +1. 将图层合并为一个。 +1. 保存文档。 + +```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}") +``` + +## 相关图层主题 + +- [在 Python 中处理 PDF 页面](/pdf/zh/python-net/working-with-pages/) +- [使用 Python 在 PDF 中处理表格](/pdf/zh/python-net/working-with-tables/) +- [在 Python 中添加 PDF 页面](/pdf/zh/python-net/add-pages/) diff --git a/zh/python-net/advanced-operations/working-with-operators/_index.md b/zh/python-net/advanced-operations/working-with-operators/_index.md new file mode 100644 index 0000000000..d73f538cd9 --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-operators/_index.md @@ -0,0 +1,185 @@ +--- +title: 在 Python 中使用 PDF 操作符 +linktitle: 使用操作符 +type: docs +weight: 90 +url: /zh/python-net/working-with-operators/ +description: 了解如何在 Python 中使用低层 PDF 操作符,以实现精确的内容流处理和图形控制。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中使用低层 PDF 操作符进行内容流控制 +Abstract: 本文解释了如何在 Aspose.PDF for Python via .NET 中使用低级 PDF 操作符。了解如何直接操作内容流,使用操作符类精确定位图形,以及在 Python 工作流中从 PDF 页面中删除绘制的对象。 +--- + +## PDF 操作符及其用法简介 + +操作符是指定应执行的某种操作的 PDF 关键字,例如在页面上绘制图形形状。操作符关键字与具名对象的区别在于其前面没有斜线字符(2Fh)。操作符仅在内容流内部才有意义。 + +内容流是一个 PDF 流对象,其数据由描述在页面上绘制的图形元素的指令组成。关于 PDF 操作符的更多详细信息可在 [PDF 规范](https://opensource.adobe.com/dc-acrobat-sdk-docs/). + +当您需要在 Python 中直接控制 PDF 内容流时,请使用此页面,例如在精确坐标处放置图形、包装图形状态更改,或从页面中删除特定的绘图操作符。 + +## 使用运算符类添加图像 + +当您需要在 PDF 页面流中非常精确地放置图像内容且不依赖于更高级别的布局抽象时,请使用低层运算符类。 + +此方法通过直接使用低级图形操作符操控内容流,实现对 PDF 中图像放置的细粒度控制。当需要对图像进行精确定位和变换时,它特别有用,例如: + +- 在特定位置添加水印或徽标。 +- 将图像覆盖到已有内容上并实现精确对齐。 +- 实现不能通过更高级抽象实现的自定义布局。 + +通过使用 GSave、ConcatenateMatrix、Do 和 GRestore 等运算符,开发人员可以确保图像准确渲染,并且不会对其他页面内容产生意外的副作用。 + +- 这 [GSave](https://reference.aspose.com/pdf/python-net/aspose.pdf.operators/gsave/) 运算符保存 PDF 当前的图形状态。 +- 这 [ConcatenateMatrix](https://reference.aspose.com/pdf/python-net/aspose.pdf.operators/concatenatematrix/) (concatenate matrix)运算符用于定义图像应如何放置在 PDF 页面上。 +- 这 [Do](https://reference.aspose.com/pdf/python-net/aspose.pdf.operators/do/) 运算符在页面上绘制图像。 +- 这 [GRestore](https://reference.aspose.com/pdf/python-net/aspose.pdf.operators/grestore/) 操作符恢复图形状态。 + +将图像添加到 PDF 文件中: + +1. 打开 PDF 文档 +1. 定义图像放置坐标 +1. 访问目标页面 +1. 将图像加载到流中 +1. 保存当前图形状态 +1. 创建矩形和变换矩阵 +1. 应用变换矩阵 +1. 绘制图像 +1. 恢复先前的图形状态 +1. 保存已修改的 PDF 文档 + +以下代码片段展示了如何使用 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) +``` + +## 使用运算符在页面上绘制 XForm + +本示例利用 XForms 及图形运算符的强大功能,在 PDF 中高效地复用图形内容。通过将图像封装在 XForm 中,可以多次绘制而无需复制图像数据,从而减小文件大小并提升性能。此方法尤其在以下情况中受益: + +- 同一图像或图形需要在文档中出现多次。 + +- 需要对图形的放置和变换进行精确控制。 + +- 优化 PDF 的性能和大小是首要任务。 + +通过使用 GSave 和 GRestore 管理图形状态,并使用 ConcatenateMatrix 进行变换矩阵操作,此技术确保每个图形都能正确且独立地渲染。 + +```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) +``` + +## 使用运算符类删除图形对象 + +下面的代码片段展示了如何删除图形。请注意,如果 PDF 文件包含图形的文本标签,使用此方法它们可能仍然保留在 PDF 文件中。因此,请搜索图形操作符,以寻找删除此类图像的备用方法。 + +```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) +``` + +## 相关主题 + +- [Python中的高级PDF操作](/pdf/zh/python-net/advanced-operations/) +- [在 Python 中处理 PDF 页面](/pdf/zh/python-net/working-with-pages/) +- [使用 Python 处理 PDF 中的图像](/pdf/zh/python-net/working-with-images/) +- [在 Python 中使用 PDF 图形](/pdf/zh/python-net/working-with-graphs/) diff --git a/zh/python-net/advanced-operations/working-with-pages/_index.md b/zh/python-net/advanced-operations/working-with-pages/_index.md index c7916afa32..e8d7c1379f 100644 --- a/zh/python-net/advanced-operations/working-with-pages/_index.md +++ b/zh/python-net/advanced-operations/working-with-pages/_index.md @@ -1,167 +1,34 @@ --- title: 在 Python 中处理 PDF 页面 -linktitle: 处理页面 +linktitle: 页面操作 type: docs weight: 20 url: /zh/python-net/working-with-pages/ -description: 如何添加页面、添加页眉和页脚、添加水印,您可以在本节中了解。Aspose.PDF for Python via .NET 向您解释此主题的所有细节。 -lastmod: "2023-04-19" +description: 了解如何在 Python 中添加、移动、旋转、裁剪、提取、加盖印章以及管理 PDF 页面。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中管理 PDF 页面 +Abstract: 本节展示了如何使用 Aspose.PDF for Python via .NET 处理 PDF 页面。内容包括添加、删除、移动、提取、旋转、调整大小、裁剪和加盖印章的页面,以及页面属性、页眉、页脚和页码的管理。 --- - +当需要在 Python 中执行页面级 PDF 操作时,请使用本节。 -**Aspose.PDF for Python via .NET** 允许您在文件中的任何位置插入页面到 PDF 文档中,还可以在 PDF 文件的末尾添加页面。本节展示了如何在没有 Acrobat Reader 的情况下向 PDF 添加页面。 -您可以在 PDF 文件的页眉和页脚中添加文本或图像,并使用 Aspose 的 Python 库在文档中选择不同的页眉。 -另外,尝试使用 Python 以编程方式裁剪 PDF 文档中的页面。 +使用 **Aspose.PDF for Python via .NET**,您可以插入、删除、移动、提取、旋转、调整大小和裁剪页面,然后应用页眉、页脚、页码、水印和印章,以满足布局和审阅工作流的需求。 -本节教您如何使用 Artifact 类在 PDF 文件中添加水印。您将查看此任务的编程示例。 -使用 [PageNumberStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagenumberstamp/) 类添加页码。要在文档中添加印章,请使用 [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) 和 [TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/) 类。使用添加水印来创建 PDF 文件中的背景图像,使用 **Aspose.PDF for Python via .NET**。 +## 涉及的页面任务 +以下任务已覆盖: -您可以执行以下操作: - -- [添加页面](/pdf/zh/python-net/add-pages/) - 在所需位置或 PDF 文件末尾添加页面,并从您的文档中删除页面。 -- [移动页面](/pdf/zh/python-net/move-pages/) - 将页面从一个文档移动到另一个文档。 -- [删除页面](/pdf/zh/python-net/delete-pages/) - 使用 PageCollection 集合从您的 PDF 文件中删除页面。 -- [更改页面大小](/pdf/zh/python-net/change-page-size/) - 您可以使用 Aspose.PDF 库通过代码片段更改 PDF 页面大小。 -- [旋转页面](/pdf/zh/python-net/rotate-pages/) - 您可以更改现有 PDF 文件中页面的方向。 -- [拆分页面](/pdf/zh/python-net/split-document/) - 您可以将 PDF 文件拆分为一个或多个 PDF。 -- [添加页眉和/或页脚](/pdf/zh/python-net/add-headers-and-footers-of-pdf-file/) - 在您的 PDF 文件的页眉和页脚中添加文本或图像。 -- [裁剪页面](/pdf/zh/python-net/crop-pages/) - 您可以通过不同的页面属性以编程方式裁剪 PDF 文档中的页面。 - -- [添加水印](/pdf/zh/python-net/add-watermarks/) - 使用 Artifact 类在您的 PDF 文件中添加水印。 -- [在 PDF 文件中添加页码](/pdf/zh/python-net/add-page-number/) - PageNumberStamp 类将帮助您在 PDF 文件中添加页码。 -- [添加背景](/pdf/zh/python-net/add-backgrounds/) - 背景图像可用于添加水印。 -- [添加印章](/pdf/zh/python-net/stamping/) - 您可以使用 ImageStamp 类向 PDF 文件添加图像印章,使用 TextStamp 类添加文本。 -- [获取和设置页面属性](/pdf/zh/python-net/get-and-set-page-properties/) - 本节介绍如何获取 PDF 文件中的页数,获取有关 PDF 页面属性的信息,如颜色,并设置页面属性。 - - \ No newline at end of file +- [添加页面](/pdf/zh/python-net/add-pages/) - 在特定位置插入页面或将页面追加到文档末尾。 +- [移动页面](/pdf/zh/python-net/move-pages/) - 在文档内部或文档之间移动页面。 +- [删除页面](/pdf/zh/python-net/delete-pages/) - 从 PDF 文档中删除页面。 +- [提取页面](/pdf/zh/python-net/extract-pages/) - 将选定页面提取为新的 PDF 文件。 +- [旋转页面](/pdf/zh/python-net/rotate-pages/) - 更改现有 PDF 文件的页面方向。 +- [更改页面大小](/pdf/zh/python-net/change-page-size/) - 调整 PDF 文档的页面尺寸。 +- [添加页眉和页脚](/pdf/zh/python-net/add-headers-and-footers-of-pdf-file/) - 添加重复的文本、图像或结构化的页眉/页脚内容。 +- [裁剪 PDF 页面](/pdf/zh/python-net/crop-pages/) - 使用页面几何设置裁剪页面内容。 +- [获取和设置页面属性](/pdf/zh/python-net/get-and-set-page-properties/) - 访问并修改 PDF 页面各种属性,例如尺寸、旋转和颜色属性。 +- [盖章](/pdf/zh/python-net/stamping/) - 将文本、图像、页面和页码戳印应用于 PDF 页面。 diff --git a/zh/python-net/advanced-operations/working-with-pages/add-backgrounds/_index.md b/zh/python-net/advanced-operations/working-with-pages/add-backgrounds/_index.md deleted file mode 100644 index 4eaf806495..0000000000 --- a/zh/python-net/advanced-operations/working-with-pages/add-backgrounds/_index.md +++ /dev/null @@ -1,170 +0,0 @@ ---- -title: 使用 Python 添加背景到 PDF -linktitle: 添加背景 -type: docs -weight: 20 -url: /zh/python-net/add-backgrounds/ -description: 使用 Python 向您的 PDF 文件添加背景图像。使用 BackgroundArtifact 类。 -lastmod: "2023-04-17" -sitemap: - changefreq: "weekly" - priority: 0.7 ---- - - - -背景图像可以用于为文档添加水印或其他细微设计。在通过 .NET 的 Aspose.PDF for Python 中,每个 PDF 文档是一个页面集合,每个页面包含一个工件集合。[BackgroundArtifact](https://reference.aspose.com/pdf/python-net/aspose.pdf/backgroundartifact/) 类可以用于向页面对象添加背景图像。 - -以下代码片段展示了如何使用 BackgroundArtifact 对象通过 Python 向 PDF 页面添加背景图像。 - -```python - - import aspose.pdf as ap - - # 创建一个新的 Document 对象 - document = ap.Document() - - # 向 document 对象添加新页面 - page = document.pages.add() - - # 创建 Background Artifact 对象 - background = ap.BackgroundArtifact() - - # 为 backgroundartifact 对象指定图像 - background.background_image = io.FileIO(input_image_file) - - # 将 backgroundartifact 添加到页面的工件集合中 - page.artifacts.append(background) - - # 保存文档 - document.save(output_pdf) -``` - - - \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-pages/add-page-number/_index.md b/zh/python-net/advanced-operations/working-with-pages/add-page-number/_index.md deleted file mode 100644 index 522a20a7d2..0000000000 --- a/zh/python-net/advanced-operations/working-with-pages/add-page-number/_index.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -title: 使用 Python 为 PDF 添加页码 -linktitle: 添加页码 -type: docs -weight: 30 -url: /zh/python-net/add-page-number/ -description: Aspose.PDF for Python via .NET 允许您使用 PageNumber Stamp 类为 PDF 文件添加页码。 -lastmod: "2023-04-17" -sitemap: - changefreq: "weekly" - priority: 0.7 ---- - - - -所有文档必须包含页码。页码使读者更容易找到文档的不同部分。 -**Aspose.PDF for Python via .NET** 允许您使用 [PageNumberStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagenumberstamp/) 添加页码。 - -您可以使用 [PageNumberStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagenumberstamp/) 类在 PDF 文件中添加页码印章。 - [PageNumberStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagenumberstamp/) 类提供了创建基于页码的图章所需的属性,如格式、边距、对齐方式、起始号码等。为了添加页码图章,您需要创建一个 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象和一个使用所需属性的 [PageNumberStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagenumberstamp/) 对象。之后,您可以调用 [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 的 [add_stamp()](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods) 方法在 PDF 中添加图章。您还可以设置页码图章的字体属性。以下代码片段向您展示如何在 PDF 文件中添加页码。 - -```python - - import aspose.pdf as ap - - # 打开文档 - document = ap.Document(input_pdf) - - # 创建页码图章 - page_number_stamp = ap.PageNumberStamp() - # 图章是否为背景 - 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 - # 设置文本属性 - 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.font_style = ap.text.FontStyles.ITALIC - page_number_stamp.text_state.foreground_color = ap.Color.aqua - - # 将图章添加到特定页面 - document.pages[1].add_stamp(page_number_stamp) - - # 保存输出文档 - document.save(output_pdf) -``` - -## 实时示例 - -[添加 PDF 页码](https://products.aspose.app/pdf/page-number) 是一个免费的在线网络应用程序,让您了解添加页码功能的工作方式。 - -[![如何在 PDF 中使用 Python 添加页码](page_number.png)](https://products.aspose.app/pdf/page-number) - - \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-pages/add-pages/_index.md b/zh/python-net/advanced-operations/working-with-pages/add-pages/_index.md index c1088789ee..c18cb5d21b 100644 --- a/zh/python-net/advanced-operations/working-with-pages/add-pages/_index.md +++ b/zh/python-net/advanced-operations/working-with-pages/add-pages/_index.md @@ -1,200 +1,96 @@ --- -title: 在 PDF 中添加页面与 Python +title: 在 Python 中添加 PDF 页面 linktitle: 添加页面 type: docs weight: 10 url: /zh/python-net/add-pages/ -description: 本文介绍如何在 PDF 文件的所需位置插入(添加)页面。了解如何使用 C# 移动、删除(删除)PDF 文件中的页面。 -lastmod: "2022-02-17" +description: 了解如何在 Python 中向 PDF 文档添加或插入页面。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 添加或插入 PDF 页面 +Abstract: 本文解释了如何使用 Aspose.PDF for Python via .NET 向 PDF 文件添加页面。了解如何在特定位置插入空白页、在文档末尾追加页面,以及使用 Document 和 PageCollection API 从另一个 PDF 导入页面。 --- - - - -Aspose.PDF for Python via .NET API 提供了使用 Python 操作 PDF 文档页面的完全灵活性。它将 PDF 文档的所有页面保存在 [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 中,可以用于处理 PDF 页面。 -Aspose.PDF for Python via .NET 允许您在文件中的任何位置插入页面到 PDF 文档中,也可以在 PDF 文件的末尾添加页面。 -本节展示了如何使用 Python 向 PDF 添加页面。 -## 在 PDF 文件中添加或插入页面 +Aspose.PDF for Python via .NET 为 PDF 文档提供灵活的页面级操作。您可以通过 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 并向 a 添加页面 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 在特定位置或文件末尾。 + +在生成工作流中需要向现有 PDF 插入新的空白页或在文档末尾追加页面时,请使用此页面。 -Aspose.PDF for Python via .NET 允许您在文件中的任何位置插入页面到 PDF 文档中,也可以在 PDF 文件的末尾添加页面。 +## 在 PDF 文件中添加或插入页面 -### 在 PDF 文件的指定位置插入空白页面 +Aspose.PDF for Python via .NET 支持在特定索引处插入页面以及在 PDF 末尾追加页面。 -要在 PDF 文件中插入空白页面: +### 在 PDF 文件中插入空白页 -1. 使用输入 PDF 文件创建一个 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类对象。 +在 PDF 文件中插入空白页: -1. 使用指定索引调用[PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/)集合的[insert](https://reference.aspose.com/pdf/net/aspose.pdf/pagecollection/methods/insert)方法。 -1. 使用[save](https://reference.aspose.com/pdf/net/aspose.pdf.document/save/methods/4)方法保存输出PDF。 +1. 打开现有的 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 使用适当的方法。 +1. 使用该在特定索引处插入新的空白页 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) `insert()` 方法。 +1. 保存已修改的 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 到所需的输出路径。 -以下代码片段向您展示了如何在PDF文件中插入页面。 +在指定位置向现有 PDF 文件插入一个空白页: ```python +import aspose.pdf as ap - import aspose.pdf as ap - - # 打开文档 - document = ap.Document(input_pdf) - # 在PDF中插入一个空页面 +def insert_empty_page(input_file_name: str, output_file_name: str) -> None: + document = ap.Document(input_file_name) document.pages.insert(2) - # 保存输出文件 - document.save(output_pdf) + document.save(output_file_name) ``` -### 在PDF文件末尾添加一个空页面 +### 在 PDF 文件末尾添加空白页 -有时,您希望确保文档以空页面结尾。本主题解释了如何在PDF文档末尾插入一个空页面。 +有时,您希望确保文档以空白页结束。本主题说明如何在 PDF 文档的末尾插入空白页。 -要在PDF文件末尾插入一个空页面: +要在 PDF 文件的末尾插入一个空白页: -1. 使用输入PDF文件创建一个[Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)类对象。 +1. 打开现有的 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 使用适当的方法。 +1. 使用以下方式在文档末尾添加一个新空白页 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) `add()` 方法。 +1. 保存已更新的 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). -1. 调用 [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 集合的 [add()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) 方法,不带任何参数。 -1. 使用 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法保存输出 PDF。 - -以下代码片段向您展示如何在 PDF 文件的末尾插入一个空页面。 +以下代码片段向您展示如何在 PDF 文件的末尾插入一个空白页。 ```python +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) +``` - import aspose.pdf as ap +### 从另一个 PDF 文档添加页面 - # 打开文档 - document = ap.Document(input_pdf) +使用 Aspose.PDF for Python via .NET,您可以创建一个新的 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/),添加一个初始页面,然后将另一个 PDF 的页面导入其中。 - # 在 PDF 文件的末尾插入一个空页面 - document.pages.add() +1. 创建一个新 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 添加一个新的空白 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 并使用它在其上写入一些文本 [`TextFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/textfragment/). +1. 打开另一个现有的 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 复制一个 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 从该文档。 +1. 使用 将复制的页面粘贴到您的主文档中 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. 保存合并后的文件。 + +```python +import aspose.pdf as ap - # 保存输出文件 - document.save(output_pdf) +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) ``` - \ No newline at end of file +## 相关页面主题 + +- [在 Python 中处理 PDF 页面](/pdf/zh/python-net/working-with-pages/) +- [在 Python 中移动 PDF 页面](/pdf/zh/python-net/move-pages/) +- [在 Python 中删除 PDF 页面](/pdf/zh/python-net/delete-pages/) +- [在 Python 中提取 PDF 页面](/pdf/zh/python-net/extract-pages/) diff --git a/zh/python-net/advanced-operations/working-with-pages/add-watermarks/_index.md b/zh/python-net/advanced-operations/working-with-pages/add-watermarks/_index.md deleted file mode 100644 index 35bd409462..0000000000 --- a/zh/python-net/advanced-operations/working-with-pages/add-watermarks/_index.md +++ /dev/null @@ -1,188 +0,0 @@ ---- -title: 使用 Python 向 PDF 添加水印 -linktitle: 添加水印 -type: docs -weight: 40 -url: /zh/python-net/add-watermarks/ -description: 本文解释了如何使用 Python 程序处理 PDF 中的工件和获取水印的功能。 -lastmod: "2023-04-17" -sitemap: - changefreq: "monthly" - priority: 0.7 ---- - - - -**Aspose.PDF for Python via .NET** 允许使用Artifacts向您的PDF文档添加水印。请查看本文以解决您的任务。 - -为了处理artifacts,Aspose.PDF有两个类:[Artifact](https://reference.aspose.com/pdf/python-net/aspose.pdf/artifact/) 和 [ArtifactCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/artifactcollection/)。 - -为了获取特定页面上的所有artifacts,[Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 类有一个Artifacts属性。本主题解释了如何在PDF文件中处理artifact。 - -## 处理Artifacts - -[Artifact](https://reference.aspose.com/pdf/python-net/aspose.pdf/artifact/) 类包含以下属性: - -**contents** – 获取artifact内部操作符的集合。其支持的类型是System.Collections.ICollection。 -**form** – 获取artifact的XForm(如果使用了XForm)。水印、页眉和页脚的artifact包含显示所有artifact内容的XForm。 - -**image** – 获取artifact的图像(如果有图像,否则为null)。 -**text** – 获取一个工件的文本。 -**rectangle** – 获取一个工件在页面上的位置。 -**rotation** – 获取一个工件的旋转(以度为单位,正值表示逆时针旋转)。 -**opacity** – 获取一个工件的不透明度。可能的值在0到1的范围内,其中1是完全不透明的。 - -## 编程示例:如何在PDF文件上添加水印 - -以下代码片段展示了如何使用Python获取PDF文件第一页上的每个水印。 - -```python - - import aspose.pdf as ap - - document = ap.Document(input_pdf) - artifact = ap.WatermarkArtifact() - - ts = ap.text.TextState() - ts.font_size = 72 - ts.foreground_color = ap.Color.blue - ts.font = ap.text.FontRepository.find_font("Courier") - - artifact.set_text_and_state("WATERMARK", ts) - artifact.artifact_horizontal_alignment = ap.HorizontalAlignment.CENTER - artifact.artifact_vertical_alignment = ap.VerticalAlignment.CENTER - artifact.rotation = 45 - artifact.opacity = 0.5 - artifact.is_background = True - document.pages[1].artifacts.append(artifact) - document.save(output_pdf) -``` - - - \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-pages/adding-headers-and-footers-of-pdf-file/_index.md b/zh/python-net/advanced-operations/working-with-pages/adding-headers-and-footers-of-pdf-file/_index.md index 4a558e55ea..5964cb4c2a 100644 --- a/zh/python-net/advanced-operations/working-with-pages/adding-headers-and-footers-of-pdf-file/_index.md +++ b/zh/python-net/advanced-operations/working-with-pages/adding-headers-and-footers-of-pdf-file/_index.md @@ -1,308 +1,343 @@ --- -title: 向 PDF 添加页眉和页脚使用 Python +title: 在 Python 中添加 PDF 页眉和页脚 linktitle: 向 PDF 添加页眉和页脚 type: docs weight: 50 url: /zh/python-net/add-headers-and-footers-of-pdf-file/ -description: Aspose.PDF for Python via .NET 允许您使用 TextStamp 类向 PDF 文件添加页眉和页脚。 -lastmod: "2023-04-17" +description: 了解如何在 Python 中使用文本、图像和结构化内容向 PDF 文件添加页眉和页脚。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 为 PDF 文件添加页眉和页脚。 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 为 PDF 文档添加页眉和页脚。它涵盖了文本、页码、HTML、图像、表格以及基于 LaTeX 的页眉和页脚内容。 --- - - - -**Aspose.PDF for Python via .NET** 允许您在现有的 PDF 文件中添加页眉和页脚。您可以向 PDF 文档添加图像或文本。此外,还可以尝试在一个 PDF 文件中使用 Python 添加不同的页眉。 - -## 在 PDF 文件的页眉中添加文本 - -您可以使用 [TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/) 类在 PDF 文件的页眉中添加文本。TextStamp 类提供了创建基于文本的印章所需的属性,例如字体大小、字体样式和字体颜色等。为了在页眉中添加文本,您需要使用所需属性创建一个 Document 对象和一个 TextStamp 对象。之后,您可以调用 Page 的 'add_stamp' 方法将文本添加到 PDF 的页眉中。 - -您需要设置 [top_margin](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/#properties) 属性,以便调整 PDF 页眉区域中的文本。您还需要将 'horizontal_alignment' 设置为 Center 并将 'vertical_alignment' 设置为 Top。 - -以下代码片段向您展示了如何使用 Python 在 PDF 文件的页眉中添加文本: -```python +使用此页面在 PDF 页面上添加一致的页眉和页脚内容,使用 **Aspose.PDF for Python via .NET**。 + +您可以使用来构建页眉和页脚 [`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/),和 [`Table`](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/) 对象,然后通过它们进行应用 [`HeaderFooter`](https://reference.aspose.com/pdf/python-net/aspose.pdf/headerfooter/) 在每页上。 + +## 将页眉和页脚添加为文本片段 - import aspose.pdf as ap +为 PDF 的所有页面添加简易的文本页眉和页脚。它创建 [`HeaderFooter`](https://reference.aspose.com/pdf/python-net/aspose.pdf/headerfooter/) 对象,插入 [`TextFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/textfragment/) 将元素放入它们,设置 [`MarginInfo`](https://reference.aspose.com/pdf/python-net/aspose.pdf/margininfo/) 用于正确定位,并将它们附加到文档的每一页。结果是一个 PDF,所有页面都显示一致的页眉和页脚文本。 - # 打开文档 - document = ap.Document(input_pdf) +以下代码片段演示了如何使用 Python 在 PDF 中添加作为文本片段的页眉和页脚: - # 创建页眉 - textStamp = ap.TextStamp("Header Text") - # 设置印章的属性 - textStamp.top_margin = 10 - textStamp.horizontal_alignment = ap.HorizontalAlignment.CENTER - textStamp.vertical_alignment = ap.VerticalAlignment.TOP - # 在所有页面上添加页眉 - for page in document.pages: - page.add_stamp(textStamp) +1. 为页眉和页脚创建文本片段。 +1. 创建 HeaderFooter 对象并将文本片段添加到它们中。 +1. 定义边距设置以控制页眉和页脚的放置。 +1. 从输入文件加载 PDF 文档。 +1. 遍历文档中的所有页面。 +1. 为每页分配页眉和页脚。 +1. 将修改后的 PDF 保存到输出文件。 - # 保存更新的文档 - 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) ``` -## 在 PDF 文件的页脚中添加文本 +此方法对于在每页的顶部和底部添加统一的标题、页码指示或法律免责声明非常有用。您还可以将其扩展以包括图像或动态内容,例如页码。 -您可以使用 [TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/) 类在 PDF 文件的页脚中添加文本。 - TextStamp 类提供了创建基于文本的印章所需的属性,如字体大小、字体样式和字体颜色等。为了在页脚中添加文本,您需要使用所需属性创建一个 Document 对象和一个 TextStamp 对象。之后,您可以调用 Page 的 'add_stamp' 方法在 PDF 的页脚中添加文本。 +## 为页码添加页眉和页脚 -以下代码片段展示了如何使用 Python 在 PDF 文件的页脚中添加文本: +使用 Aspose.PDF for Python 为 PDF 文档的页眉和页脚添加自动页码。使用内置变量 $p(当前页码)和 $P(总页数),脚本在每页动态插入页码。页眉显示格式‘Page X from Y’,而页脚显示‘Page X / Y’。该 [`MarginInfo`](https://reference.aspose.com/pdf/python-net/aspose.pdf/margininfo/) 确保在每页上正确放置。 -```python +1. 使用“Page $p from $P”在页眉中创建一个 TextFragment,以显示当前页码和总页数。 +1. 创建一个 HeaderFooter 对象并将页眉文本添加到其中。 +1. 使用“Page $p / $P”创建一个用于页脚的 TextFragment,以实现替代编号样式。 +1. 创建一个 Footer 对象并添加页脚文本。 +1. 定义边距设置(左 = 50,上 = 20),并将其应用于页眉和页脚。 +1. 打开输入文件中的 PDF 文档。 +1. 遍历所有页面并为每个页面分配页眉和页脚。 +1. 将更新后的 PDF 保存到输出路径。 - import aspose.pdf as ap - - # 打开文档 - document = ap.Document(input_pdf) - # 创建页脚 - textStamp = ap.TextStamp("Footer Text") - # 设置印章的属性 - textStamp.bottom_margin = 10 - textStamp.horizontal_alignment = ap.HorizontalAlignment.CENTER - textStamp.vertical_alignment = ap.VerticalAlignment.BOTTOM - # 在所有页面上添加页脚 - for page in document.pages: - page.add_stamp(textStamp) - - # 保存更新的 PDF 文件 - 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) ``` -## 在 PDF 文件的页眉中添加图像 +## 将页眉和页脚添加为 HTML 片段 + +使用 Aspose.PDF for Python 为 PDF 文档的每一页应用 HTML 格式的页眉和页脚。通过使用 [`HtmlFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/htmlfragment/),脚本允许富文本样式——如粗体和斜体——出现在页眉和页脚中。 [`MarginInfo`](https://reference.aspose.com/pdf/python-net/aspose.pdf/margininfo/) 用于正确放置,并且相同的格式化元素附加到文档中的每一页。 -您可以使用 [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) 类在 PDF 文件的页眉中添加图像。 Image Stamp 类提供了创建基于图像的印章所需的属性,如字体大小、字体样式和字体颜色等。为了在页眉中添加图像,您需要创建一个 Document 对象和一个使用所需属性的 Image Stamp 对象。之后,您可以调用 Page 的 'add_stamp' 方法在 PDF 的页眉中添加图像。 +以下代码片段演示了如何使用 Python 将页眉和页脚作为 HTML 片段添加到 PDF 中: -下面的代码片段展示了如何使用 Python 在 PDF 文件的页眉中添加图像: +1. 使用 HtmlFragment 创建 HTML 标题片段——包括诸如 ' 的样式化文本' 用于加粗。 +1. 创建一个 HeaderFooter 对象并将 HTML 标头添加到它。 +1. 创建一个使用 ' 的HTML页脚片段' 用于斜体样式。 +1. 创建一个 Footer 对象并将页脚 HTML 添加到其中。 +1. 配置页边距(左 = 50,顶部 = 20),并将其分配给页眉和页脚。 +1. 使用 'ap.Document()' 加载 PDF 文档。 +1. 遍历所有页面并为每个页面分配页眉和页脚。 +1. 将修改后的 PDF 保存到指定的输出路径。 ```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) +``` + +使用 HtmlFragment 可以通过内联样式或 HTML 标记实现丰富的格式化,使您相较于纯文本拥有更大的设计灵活性。 - import aspose.pdf as ap +## 将页眉和页脚添加为图像 - # 打开文档 - document = ap.Document(input_pdf) +使用 Aspose.PDF for Python 为 PDF 文档的每一页添加基于图像的页眉和页脚。每页的页眉和页脚均使用相同的图像文件。 [`MarginInfo`](https://reference.aspose.com/pdf/python-net/aspose.pdf/margininfo/) 定位图像,图像会自动调整以适应页眉/页脚区域。 - # 创建页眉 - image_stamp = ap.ImageStamp(input_image) - # 设置印章的属性 - image_stamp.top_margin = 10 - image_stamp.horizontal_alignment = ap.HorizontalAlignment.CENTER - image_stamp.vertical_alignment = ap.VerticalAlignment.TOP - # 在所有页面上添加页眉 - for page in document.pages: - page.add_stamp(image_stamp) +以下代码片段演示了如何使用 Python 向 PDF 添加作为图像的页眉和页脚: - # 保存更新后的文档 - document.save(output_pdf) +1. 将图像加载到 'ap.Image' 对象中,并准备将其用作标题。 +1. 创建一个 HeaderFooter 对象并将页眉图像附加到它上。 +1. 再次加载相同的图像以用作页脚。 +1. 创建一个 Footer 对象,并将页脚图像添加到它。 +1. 使用 'ap.Document()' 加载输入 PDF 文档。 +1. 遍历文档的所有页面。 +1. 应用边距(左 = 50)以定位页眉和页脚。 +1. 为 PDF 的每一页分配页眉和页脚。 +1. 将更新后的 PDF 保存到指定的输出文件。 + +此技术非常适合在页眉/页脚区域使用徽标或水印对文档进行品牌化。 + +```python +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) ``` -## 在 PDF 文件底部添加图像 +## 将标题和页脚添加为表格 -您可以使用 [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) 类在 PDF 文件的页脚中添加图像。 [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) 类提供了创建基于图像的图章所需的属性,比如字体大小、字体样式和字体颜色等。为了在页脚中添加图像,你需要使用所需的属性创建一个 Document 对象和一个 Image Stamp 对象。之后,你可以调用 Page 的 'add_stamp' 方法在 PDF 的页脚中添加图像。 +使用 Aspose.PDF for Python 为 PDF 文档的所有页面添加结构化、基于表格的页眉和页脚。 [`Table`](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/) 对象提供了更好的布局控制、对齐以及对复杂页眉和页脚的一致格式。页眉文本居中,页脚文本左对齐,均使用 Arial 12pt 字体。列宽根据页面尺寸动态计算,以确保正确放置。 -以下代码片段向你展示了如何使用 Python 在 PDF 文件的页脚中添加图像: +此代码片段使用 Aspose.PDF for Python via .NET 为 PDF 文档的每一页添加页眉和页脚(使用表格)。 -```python +1. 使用定义文本样式 [`TextState`](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstate/) 用于页眉和页脚(字体、大小、对齐)。 +1. 创建 [`HeaderFooter`](https://reference.aspose.com/pdf/python-net/aspose.pdf/headerfooter/) 用于页眉和页脚的对象。 +1. 构建页眉 [`Table`](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/) 带有单行且单元格包含标题文本。 +1. 构建页脚 [`Table`](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/) 包含页脚文本的单行单元格。 +1. 将表格添加到相应的 [`HeaderFooter`](https://reference.aspose.com/pdf/python-net/aspose.pdf/headerfooter/) 对象。 +1. 设置页脚 [`MarginInfo`](https://reference.aspose.com/pdf/python-net/aspose.pdf/margininfo/) 用于正确的水平定位。 +1. 打开 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 使用适当的方法。 +1. 遍历所有页面并将基于表格的页眉和页脚分配给每个页面。 +1. 保存已修改的 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 到输出文件。 - import aspose.pdf as ap - - # 打开文档 - document = ap.Document(input_pdf) - # 创建页脚 - image_stamp = ap.ImageStamp(input_image) - # 设置图章的属性 - image_stamp.bottom_margin = 10 - image_stamp.horizontal_alignment = ap.HorizontalAlignment.CENTER - image_stamp.vertical_alignment = ap.VerticalAlignment.BOTTOM - # 在所有页面添加页脚 - for page in document.pages: - page.add_stamp(image_stamp) - - # 保存更新后的 PDF 文件 - document.save(output_pdf) +```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) ``` -## 在一个 PDF 文件中添加不同的页眉 +## 在 LaTeX 中添加页眉和页脚 -我们知道可以通过使用 [top_margin](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/#properties) 或 [bottom_margin](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/#properties) 属性在文档的页眉/页脚部分添加 TextStamp,但有时我们可能需要在单个 PDF 文档中添加多个页眉/页脚。**通过 .NET 的 Aspose.PDF for Python** 解释了如何做到这一点。 +使用 Aspose.PDF for Python 为 PDF 文档的所有页面添加包含 LaTeX 格式内容的页眉和页脚。LaTeX 可渲染数学符号、日期、版权标记以及其他高级格式。页眉包括动态日期,而页脚显示版权符号以及当前页码和总页数。 -为了实现此要求,我们将创建单独的 TextStamp 对象(对象的数量取决于所需的页眉/页脚数量),并将它们添加到 PDF 文档中。 - 我们还可以为单个图章对象指定不同的格式信息。在以下示例中,我们创建了 Document 对象和三个 TextStamp 对象,然后使用 Page 的 'add_stamp' 方法在 PDF 的页眉部分添加文本。以下代码片段向您展示如何使用 Aspose.PDF for Python 在 PDF 文件的页脚中添加图像: +以下代码片段展示了如何使用 [`TeXFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/texfragment/) 在 PDF 的页眉和页脚中使用 Aspose.PDF for Python via .NET。 -```python +1. 打开 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 使用适当的方法。 +1. 确定用于动态页脚的总页数。 +1. 遍历文档的所有页面。 +1. 创建一个 [`HeaderFooter`](https://reference.aspose.com/pdf/python-net/aspose.pdf/headerfooter/) 用于页眉的对象。 +1. 创建一个 [`TeXFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/texfragment/) 对于包含 LaTeX 命令的标题文本(例如, `\\today\\`). +1. 创建一个 [`HeaderFooter`](https://reference.aspose.com/pdf/python-net/aspose.pdf/headerfooter/) 页脚的对象。 +1. 创建一个 [`TeXFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/texfragment/) 用于包含 LaTeX 符号和页码的页脚文本。 +1. 添加 [`TeXFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/texfragment/) 到相应的页眉/页脚对象。 +1. 将页眉和页脚绑定到当前页面。 +1. 保存已修改的 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 到输出文件。 - import aspose.pdf as ap - - # 创建三个图章 - stamp1 = ap.TextStamp("Header 1") - stamp2 = ap.TextStamp("Header 2") - stamp3 = ap.TextStamp("Header 3") - - # 设置图章对齐方式(将图章放在页面顶部,水平居中) - stamp1.vertical_alignment = ap.VerticalAlignment.TOP - stamp1.horizontal_alignment = ap.HorizontalAlignment.CENTER - # 指定字体样式为粗体 - stamp1.text_state.font_style = ap.text.FontStyles.BOLD - # 设置文本前景色信息为红色 - stamp1.text_state.foreground_color = ap.Color.red - # 指定字体大小为14 - stamp1.text_state.font_size = 14 - - # 现在我们需要将第二个图章对象的垂直对齐方式设置为顶部 - stamp2.vertical_alignment = ap.VerticalAlignment.TOP - # 设置图章的水平对齐信息为居中对齐 - stamp2.horizontal_alignment = ap.HorizontalAlignment.CENTER - # 设置图章对象的缩放因子 - stamp2.zoom = 10 - - # 设置第三个图章对象的格式 - # 指定图章对象的垂直对齐信息为顶部 - stamp3.vertical_alignment = ap.VerticalAlignment.TOP - # 设置图章对象的水平对齐信息为居中对齐 - stamp3.horizontal_alignment = ap.HorizontalAlignment.CENTER - # 设置图章对象的旋转角度 - stamp3.rotate_angle = 35 - # 设置图章的背景颜色为粉色 - stamp3.text_state.background_color = ap.Color.pink - # 将图章的字体信息更改为 Verdana - stamp3.text_state.font = ap.text.FontRepository.find_font("Verdana") - # 第一个图章添加在第一页; - document.pages[1].add_stamp(stamp1) - # 第二个图章添加在第二页; - document.pages[2].add_stamp(stamp2) - # 第三个图章添加在第三页。 - document.pages[3].add_stamp(stamp3) - - # 保存更新的文档 - document.save(output_pdf) +```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 +## 相关页面主题 + +- [在 Python 中处理 PDF 页面](/pdf/zh/python-net/working-with-pages/) +- [在 Python 中为 PDF 添加页码](/pdf/zh/python-net/add-page-number/) +- [在 Python 中对 PDF 页面加盖印章](/pdf/zh/python-net/stamping/) +- [在 Python 中格式化 PDF 文档](/pdf/zh/python-net/formatting-pdf-document/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-pages/change-page-size/_index.md b/zh/python-net/advanced-operations/working-with-pages/change-page-size/_index.md index bf41fb3a47..fbce352160 100644 --- a/zh/python-net/advanced-operations/working-with-pages/change-page-size/_index.md +++ b/zh/python-net/advanced-operations/working-with-pages/change-page-size/_index.md @@ -1,172 +1,120 @@ --- -title: 使用 Python 更改 PDF 页面大小 -linktitle: 更改 PDF 页面大小 +title: 在 Python 中更改 PDF 页面大小 +linktitle: 更改页面大小 type: docs -weight: 60 +weight: 40 url: /zh/python-net/change-page-size/ -description: 使用 Aspose.PDF for Python via .NET 库更改 PDF 文档的页面大小。 -lastmod: "2023-04-17" +description: 了解如何在 Python 中读取和更改 PDF 页面的尺寸。 +lastmod: "2026-06-08" sitemap: changefreq: "weekly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 更改页面大小 +Abstract: 本文展示了如何使用 Aspose.PDF 读取和修改 PDF 页面尺寸。Get Page Size 示例检索特定 PDF 页面的宽度和高度,使用户能够检查页面布局、验证格式或分析文档结构。Set Page Size 示例说明如何更改页面的尺寸——例如将首页转换为 A4 大小——同时在修改前后显示框属性(CropBox、TrimBox、ArtBox、BleedBox、MediaBox)。 --- - - - -## 更改 PDF 页面大小 - -通过 .NET 的 Aspose.PDF for Python 允许您在 Python 应用程序中使用简单的代码行更改 PDF 页面大小。本主题解释如何更新/更改现有 PDF 文件的页面尺寸(大小)。 - -[Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 类包含 [set_page_size()](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods) 方法,允许您设置页面大小。下面的代码片段通过几个简单的步骤更新页面尺寸: - -1. 加载源 PDF 文件。 -1. 将页面获取到 [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 对象中。 -1. 获取指定页面。 -1. 调用 set_page_size() 方法更新其尺寸。 -1. 调用 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类的 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法以生成更新页面尺寸的 PDF 文件。 -```python +Aspose.PDF for Python via .NET 让您只需几行代码即可更改 PDF 页面尺寸。本主题展示了如何使用 the [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 和 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) API。 + +当您需要在 Python 中调整现有 PDF 页面大小、统一文档尺寸或检查页面框设置时,请使用本指南。 + +{{% alert color="primary" %}} + +请注意,高度和宽度属性使用点(points)作为基本单位,其中 1 英寸 = 72 点,1 厘米 = 1/2.54 英寸 = 0.3937 英寸 = 28.3 点。 + +{{% /alert %}} + +## 将 PDF 页面 的页面大小设置为 A4 + +此示例将 PDF 文档中第一页的尺寸更新为标准的 A4 大小。它还在调整大小前后打印页面的盒子尺寸(CropBox、TrimBox、ArtBox、BleedBox、MediaBox),以便您验证更改。 - import aspose.pdf as ap +以下代码片段展示了如何将 PDF 页面尺寸更改为 A4 大小: - document = ap.Document(input_pdf) +1. 访问第一个 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 的 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 在修改之前显示页面的框大小(CropBox、TrimBox、ArtBox、BleedBox、MediaBox)。 +1. 使用页面 API 应用 A4 尺寸(597.6 × 842.4 点)。 +1. 显示已更新的页面框尺寸。 +1. 保存已修改的 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 到指定的输出路径。 - # 获取特定页面 +```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] - # 设置页面大小为 A4 (11.7 x 8.3 英寸),在 Aspose.Pdf 中,1 英寸 = 72 点 - # 因此 A4 尺寸为 (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) +``` + +## 获取 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/) 并将其大小打印到控制台。这对于检查页面布局、验证格式或为进一步处理准备文档非常有用。 - # 保存更新的文档 - document.save(output_pdf) +1. 将 PDF 加载为 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 访问第一个 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +1. 使用检索页面的边界矩形 `get_page_rect()`. +1. 提取宽度和高度值。 +1. 打印页面尺寸。 + +```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}") +``` + +### 获取 PDF 页面大小(旋转前后) + +检索 PDF 页面在应用 90° 旋转前后的尺寸。这演示了旋转如何影响宽度和高度以及如何使用 `get_page_rect()` 考虑或不考虑旋转。 + +1. 将 PDF 打开为 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 访问第一个 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +1. 使用 90° 旋转 `page.rotate = ap.Rotation.ON90` (请参见 [`Rotation`](https://reference.aspose.com/pdf/python-net/aspose.pdf/rotation/) 枚举). +1. 在不旋转的情况下检索页面矩形 `get_page_rect(False)` 并打印其宽度和高度。 +1. 检索考虑旋转的页面矩形 `get_page_rect(True)` 并打印其宽度和高度。 +1. 比较由于旋转导致的尺寸变化。 + +```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}") ``` +## 相关页面主题 - \ No newline at end of file +- [在 Python 中处理 PDF 页面](/pdf/zh/python-net/working-with-pages/) +- [在 Python 中裁剪 PDF 页面](/pdf/zh/python-net/crop-pages/) +- [在 Python 中获取和设置 PDF 页面属性](/pdf/zh/python-net/get-and-set-page-properties/) +- [在 Python 中旋转 PDF 页面](/pdf/zh/python-net/rotate-pages/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-pages/crop-pages/_index.md b/zh/python-net/advanced-operations/working-with-pages/crop-pages/_index.md index dd4ed3b78f..7e5c0e7ab8 100644 --- a/zh/python-net/advanced-operations/working-with-pages/crop-pages/_index.md +++ b/zh/python-net/advanced-operations/working-with-pages/crop-pages/_index.md @@ -1,177 +1,94 @@ --- -title: 使用 Python 编程裁剪 PDF 页面 -linktitle: 裁剪页面 +title: 在 Python 中裁剪 PDF 页面 +linktitle: 裁剪 PDF 页面 type: docs weight: 70 url: /zh/python-net/crop-pages/ -description: 您可以通过 Aspose.PDF for Python via .NET 获取页面属性,例如宽度、高度、出血框、裁剪框和修剪框。 -lastmod: "2023-04-17" +description: 了解如何在 Python 中裁剪 PDF 页面并调整裁剪框、修剪框、出血框和媒体框。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 访问和修改 PDF 页面属性 +Abstract: 本文概述了如何使用 Aspose.PDF for Python 访问和修改 PDF 文档中的页面属性。它描述了多种页面属性,包括 media box、bleed box、trim box、art box 和 crop box,并解释了它们在定义 PDF 页面用于打印和显示的尺寸和边界方面的作用。media box 表示最大的页面尺寸,而 bleed box 确保在页面边缘之外的墨水覆盖,以便裁剪。trim box 标记裁剪后最终文档的尺寸,art box 包含实际的页面内容。crop box 定义了在 Adobe Acrobat 中可见的区域。文章还包含了一个 Python 代码片段,演示如何为 PDF 文档中的特定页面设置新的 crop box 以及其他盒子。视觉示例展示了应用裁剪前后页面的外观,展示了修改这些属性的实际应用。 --- - - ## 获取页面属性 -PDF 文件中的每个页面都有许多属性,例如宽度、高度、出血框、裁剪框和裁切框。Aspose.PDF for Python 允许您访问这些属性。 +PDF 文件中的每页都有多个属性,例如宽度、高度、bleed、crop 和 trimbox。Aspose.PDF for Python 允许您访问这些属性。 -- **media_box**: 媒体框是最大的页面框。它对应于打印到 PostScript 或 PDF 时选择的页面大小(例如 A4、A5、US Letter 等)。换句话说,媒体框决定了显示或打印 PDF 文档的介质的物理大小。 -- **bleed_box**: 如果文档有出血,PDF 也会有一个出血框。出血是超出页面边缘的颜色(或艺术品)的量。它用于确保当文档打印并裁切到尺寸(“裁切”)时,墨水会一直延伸到页面边缘。即使页面被错剪 - 稍微偏离裁切标记 - 页面上也不会出现白边。 -- **trim_box**: 裁切框指示文档在打印和裁切后的最终尺寸。 -- **art_box**: 艺术框是在文档中绘制在页面实际内容周围的框。 - 此页面框用于在其他应用程序中导入PDF文档。 -- **crop_box**: 裁剪框是您的PDF文档在Adobe Acrobat中显示的“页面”大小。在正常视图中,Adobe Acrobat中只显示裁剪框的内容。有关这些属性的详细描述,请阅读Adobe.Pdf规格,特别是10.10.1页面边界。 +当您需要缩小可见页面区域、为印刷工作流准备文件或检查 PDF 文档中的页面框几何形状时,请使用此页面。 -下面的代码片段展示了如何裁剪页面: +- **media_box**:媒体框是最大的页面框。它对应于文档打印成 PostScript 或 PDF 时所选的页面尺寸(例如 A4、A5、US Letter 等)。换句话说,媒体框决定了呈现或打印 PDF 文档的介质的物理尺寸。 +- **bleed_box**:如果文档有出血,PDF 也会包含出血框。出血是指超出页面边缘的颜色(或艺术作品)的范围。它用于确保在文档打印并裁剪至尺寸("trimmed")时,墨水能够延伸至页面的边缘。即使页面裁剪不准确——略微偏离裁剪标记——页面上也不会出现白边。 +- **trim_box**:修整框指示文档在打印和裁剪后的最终尺寸。 +- **art_box**:艺术框是围绕文档页面实际内容绘制的框。在将 PDF 文档导入其他应用程序时会使用此页面框。 +- **crop_box**:裁剪框是 Adobe Acrobat 中显示 PDF 文档的 “页” 大小。在普通视图中,Adobe Acrobat 只显示裁剪框的内容。有关这些属性的详细说明,请阅读 Adobe.Pdf 规范,特别是 10.10.1 页面边界。 -```python +裁剪第一个 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 使用 Aspose.PDF for Python 将 PDF 的内容定位到特定的矩形区域。该函数调整多个页面框—`crop_box`, `trim_box`, `art_box`,和 `bleed_box`—以确保视觉效果一致。裁剪对于去除不需要的边距或聚焦于页面的特定区域非常有用。 - import aspose.pdf as ap +1. 将 PDF 加载为 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) (使用 `ap.Document()`). +1. 使用以下方式定义裁剪矩形 [`Rectangle`](https://reference.aspose.com/pdf/python-net/aspose.pdf/rectangle/) 使用所需的坐标(单位为点)。 +1. 设置 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/)的 `crop_box`, `trim_box`, `art_box`,和 `bleed_box` 到定义的矩形。 +1. 保存已修改的 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 到一个新的输出文件。 + +```python +import sys +import aspose.pdf as ap +from os import path - document = ap.Document(input_pdf) +def crop_page(input_file_name, output_file_name): + document = ap.Document(input_file_name) - # 创建新的Box矩形 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) ``` -在此示例中,我们使用了一个示例文件[这里](crop_page.pdf)。最初,我们的页面看起来如图1所示。 -![图1. 裁剪后的页面](crop_page.png) - -更改后,页面将如图2所示。 -![图2. 裁剪页面](crop_page2.png) - - \ No newline at end of file +在此示例中我们使用了一个示例文件 [这里](crop_page.pdf). 最初我们的页面如图 1 所示。 +![图 1. 裁剪页面](crop_page.png) + +更改后,页面将如图 2 所示。 +![图 2. 裁剪页面](crop_page2.png) + +## 基于首个图像内容裁剪 PDF 页面 + +裁剪第一个 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 动态地基于页面上找到的第一个图像的边界。通过使用 [`ImagePlacementAbsorber`](https://reference.aspose.com/pdf/python-net/aspose.pdf/imageplacementabsorber/),脚本识别第一张图像并调整页面的 `crop_box` 以匹配图像的尺寸。当您想专注于特定的视觉内容而不是预先定义的坐标时,这种方法很有用。 + +1. 将 PDF 加载为 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 使用以下方法定位第一页上的图像 [`ImagePlacementAbsorber`](https://reference.aspose.com/pdf/python-net/aspose.pdf/imageplacementabsorber/). +1. 检查是否存在图像: + - 如果找到,设置 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) `crop_box` 匹配第一张图像的 [`Rectangle`](https://reference.aspose.com/pdf/python-net/aspose.pdf/rectangle/). + - 如果不是,保持页面不变并通知用户。 +1. 保存已修改的 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 到指定的输出文件。 + +```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) +``` + +## 相关页面主题 + +- [在 Python 中处理 PDF 页面](/pdf/zh/python-net/working-with-pages/) +- [在 Python 中更改 PDF 页面大小](/pdf/zh/python-net/change-page-size/) +- [在 Python 中获取和设置 PDF 页面属性](/pdf/zh/python-net/get-and-set-page-properties/) +- [在 Python 中旋转 PDF 页面](/pdf/zh/python-net/rotate-pages/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-pages/crop-pages/crop_page.pdf b/zh/python-net/advanced-operations/working-with-pages/crop-pages/crop_page.pdf new file mode 100644 index 0000000000..2bc27a2ac8 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-pages/crop-pages/crop_page.pdf differ diff --git a/zh/python-net/advanced-operations/working-with-pages/crop-pages/crop_page.png b/zh/python-net/advanced-operations/working-with-pages/crop-pages/crop_page.png new file mode 100644 index 0000000000..d61426415a Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-pages/crop-pages/crop_page.png differ diff --git a/zh/python-net/advanced-operations/working-with-pages/crop-pages/crop_page2.png b/zh/python-net/advanced-operations/working-with-pages/crop-pages/crop_page2.png new file mode 100644 index 0000000000..04ebc7427e Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-pages/crop-pages/crop_page2.png differ diff --git a/zh/python-net/advanced-operations/working-with-pages/delete-pages/_index.md b/zh/python-net/advanced-operations/working-with-pages/delete-pages/_index.md index a31f346e7b..0100a92f07 100644 --- a/zh/python-net/advanced-operations/working-with-pages/delete-pages/_index.md +++ b/zh/python-net/advanced-operations/working-with-pages/delete-pages/_index.md @@ -1,99 +1,64 @@ --- -title: 使用Python编程删除PDF页面 -linktitle: 删除PDF页面 +title: 在 Python 中删除 PDF 页面 +linktitle: 删除 PDF 页面 type: docs weight: 80 url: /zh/python-net/delete-pages/ -description: 您可以使用Aspose.PDF for Python通过.NET库从PDF文件中删除页面。 -lastmod: "2023-04-17" +description: 了解如何在 Python 中删除 PDF 文件的页面。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中删除一个或多个 PDF 页面 +Abstract: 本文解释了如何使用 Aspose.PDF for Python via .NET 从 PDF 文件中删除页面。了解如何通过使用 PageCollection API 删除文档中的单个页面或多个页面,然后保存更新后的 PDF。 --- - +您可以使用 Aspose.PDF for Python via .NET 删除 PDF 文件中的页面。要删除特定页面,请使用 the [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 的一个 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). -您可以使用 Aspose.PDF for Python via .NET 从 PDF 文件中删除页面。要从 [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 集合中删除特定页面。 +在需要在共享、归档或合并文档之前删除 PDF 中不需要的页面时,请使用此工作流。 -## 从 PDF 文件中删除页面 +## 从 PDF 文件删除页面 -1. 调用 [delete()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) 方法并指定页面的索引 -2. 调用 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法以保存更新的 PDF 文件 -下面的代码片段展示了如何使用 Python 从 PDF 文件中删除特定页面。 +Aspose.PDF for Python via .NET 从输入 PDF 中删除第 2 页,并将更新后的文档保存为新文件。此功能有助于在不更改文档其余部分的情况下删除不需要或敏感的页面。 -```python +1. 将输入 PDF 加载为一个 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 使用该方法删除页面 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. 调用 [`Document.save()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 用于保存已更新的 PDF 文件的方法。 - import aspose.pdf as ap +以下代码片段展示了如何使用 Python 删除 PDF 文件中的特定页面。 - # 打开文档 - document = ap.Document(input_pdf) +```python +import aspose.pdf as ap - # 删除特定页面 +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) +``` + +## 从 PDF 文档中删除多个页面 + +删除多个页面可让您一次性移除一组指定的页面,这比逐页删除更高效。生成的 PDF 将保存为新文件,保留原始文档。 + +1. 将输入 PDF 加载为一个 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 使用 pages 数组中列出的页面进行删除 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. 保存已更新的 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 保存到新文件。 + +```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) +``` + +## 相关页面主题 - # 保存更新后的 PDF - document.save(output_pdf) \ No newline at end of file +- [在 Python 中处理 PDF 页面](/pdf/zh/python-net/working-with-pages/) +- [在 Python 中添加 PDF 页面](/pdf/zh/python-net/add-pages/) +- [在 Python 中移动 PDF 页面](/pdf/zh/python-net/move-pages/) +- [在 Python 中提取 PDF 页面](/pdf/zh/python-net/extract-pages/) diff --git a/zh/python-net/advanced-operations/working-with-pages/extract-pages/_index.md b/zh/python-net/advanced-operations/working-with-pages/extract-pages/_index.md new file mode 100644 index 0000000000..1e184b6cff --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-pages/extract-pages/_index.md @@ -0,0 +1,64 @@ +--- +title: 在 Python 中提取 PDF 页面 +linktitle: 提取 PDF 页面 +type: docs +weight: 80 +url: /zh/python-net/extract-pages/ +description: 了解如何在 Python 中将单个或多个 PDF 页面提取到新文件中。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 提取 PDF 页面 +Abstract: 本文解释了如何使用 Aspose.PDF for Python via .NET 从 PDF 文件中提取页面。了解如何通过使用基于 1 的页面索引和 PageCollection API 将单个页面或多个页面复制到新文档中。 +--- + +## 从 PDF 中提取单个页面 + +从 PDF 文档中提取特定页面并将其保存为新文件。使用 Aspose.PDF 库,脚本将所需页面复制到一个新的 PDF 中,保持原始文档不变。这对于拆分 PDF 或提取重要页面进行分发非常有用。 + +1. 使用以下方式加载源 PDF [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) API (`ap.Document()`). +1. 创建一个新 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 用于保存提取的页面。 +1. 添加所需的 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 从源文档到新 PDF,使用目标文档的 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) (`dst_document.pages.add(...)`). + - 在此示例中,提取第 2 页(基于 1 的索引)。 +1. 保存新的 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 将提取的页面保存到指定的输出文件中。 + +```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) +``` + +## 提取 PDF 的多个页面 + +从 PDF 文档中提取多个特定页面并将其保存到新文件中。使用 Aspose.PDF 库,所选页面会被复制到新的 PDF 中,同时保持原始文档不变。这对于创建仅包含较大文档中相关部分的更小 PDF 非常有用。 + +1. 使用以下方式加载源 PDF [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) API (`ap.Document()`). +1. 创建一个新 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 用于保存提取的页面。 +1. 选择要提取的页面(在本例中,使用基于1的索引选择第2页和第3页)。 +1. 添加每个已选择的 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 从源文档到新PDF,使用其 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. 保存新的 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 将提取的页面写入指定的输出文件。 + +```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) +``` + +## 相关页面主题 + +- [在 Python 中处理 PDF 页面](/pdf/zh/python-net/working-with-pages/) +- [在 Python 中删除 PDF 页面](/pdf/zh/python-net/delete-pages/) +- [在 Python 中移动 PDF 页面](/pdf/zh/python-net/move-pages/) +- [在 Python 中拆分 PDF 文件](/pdf/zh/python-net/split-document/) diff --git a/zh/python-net/advanced-operations/working-with-pages/get-and-set-page-properties/_index.md b/zh/python-net/advanced-operations/working-with-pages/get-and-set-page-properties/_index.md index 4a5c35690e..3d5266d1b3 100644 --- a/zh/python-net/advanced-operations/working-with-pages/get-and-set-page-properties/_index.md +++ b/zh/python-net/advanced-operations/working-with-pages/get-and-set-page-properties/_index.md @@ -1,348 +1,158 @@ --- -title: 使用 Python 获取和设置页面属性 +title: 在 Python 中获取和设置 PDF 页面属性 linktitle: 获取和设置页面属性 type: docs weight: 90 url: /zh/python-net/get-and-set-page-properties/ -description: 本节展示如何获取 PDF 文件中的页数,获取有关 PDF 页面属性(如颜色)的信息,并设置页面属性。 -lastmod: "2023-04-17" +description: 学习如何在 Python 中检查和更新 PDF 页面属性,如尺寸、页数和颜色信息。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 获取和设置页面属性的方法 +Abstract: 本文讨论了 Aspose.PDF for Python via .NET 的功能,重点是使用 Python 读取和设置 PDF 文件的页面属性。文章涵盖了多种功能,包括确定 PDF 的页数、访问和修改页面属性以及处理颜色信息。要获取页数,使用 `Document` 类和 `PageCollection` 集合,并提供代码片段演示如何检索页数,即使不保存文档。文章解释了不同的页面属性,如 MediaBox、BleedBox、TrimBox、ArtBox 和 CropBox,并提供了访问这些属性的代码示例。此外,还介绍了从 PDF 中获取特定页面并将其另存为单独文档,以及确定每页的颜色类型。全文示例均使用 Python 实现,展示了这些功能的实际应用。 --- - - - -Aspose.PDF for Python via .NET 允许您在 Python 应用程序中读取和设置 PDF 文件中页面的属性。本节展示了如何获取 PDF 文件的页数,获取有关 PDF 页面属性(例如颜色)的信息,并设置页面属性。给出的示例是用 Python 编写的。 - -## 获取 PDF 文件中的页数 - -在处理文档时,您通常想知道它们包含多少页。使用 Aspose.PDF,这不需要超过两行代码。 - -要获取 PDF 文件中的页数: - -1. 使用 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类打开 PDF 文件。 -1. 然后使用 [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 集合的 Count 属性(来自 Document 对象)来获取文档中的总页数。 + +Aspose.PDF for Python via .NET 让您在 Python 应用程序中读取和设置 PDF 文件中页面的属性。本节展示如何获取 PDF 文件的页数,获取 PDF 页面属性(例如颜色)信息并设置页面属性。示例使用 the [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 和 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) APIs 并使用 Python 编写。 + +当您需要检查页面元数据、确定页面计数或更新页面级特征,以进行文档分析或标准化任务时,请使用本指南。 + +## 获取 PDF 文件的页数 + +在处理文档时,您通常想知道它们包含多少页。使用 Aspose.PDF,这只需不到两行代码。 + +获取 PDF 文件页数的方法如下: + +1. 使用以下方式打开 PDF 文件 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类。 +1. 然后使用 [页面集合](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 集合的 Count 属性(来自 Document 对象)来获取文档的总页数。 以下代码片段展示了如何获取 PDF 文件的页数。 ```python +import sys +import aspose.pdf as ap +from os import path - import aspose.pdf as ap - - # 打开文档 - document = ap.Document(input_pdf) +def get_page_count(input_file_name): + # Open document + document = ap.Document(input_file_name) - # 获取页数 - print("页数:", str(len(document.pages))) + # Get page count + print("Page Count:", str(len(document.pages))) ``` +### 获取页面计数而不保存文档 -### 获取页面数量而不保存文档 - -有时我们会动态生成PDF文件,在创建PDF文件时,可能会遇到获取PDF文件页面数量的需求(例如创建目录等),而不在系统或流上保存文件。为了满足这一需求,Document类中引入了一个方法[process_paragraphs()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods)。请看下面的代码片段,展示了在不保存文档的情况下获取页面数量的步骤。 +有时我们实时生成 PDF 文件,在 PDF 文件创建过程中,可能会遇到需求(例如创建目录等)需要在不将文件保存到系统或流中的情况下获取 PDF 文件的页面计数。为满足此需求,在 Document 类中引入了一个方法 [process_paragraphs()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 已在 Document 类中引入。请查看以下代码片段,展示了在不保存文档的情况下获取页面计数的步骤。 ```python +import sys +import aspose.pdf as ap +from os import path - import aspose.pdf as ap - - # 实例化Document实例 +def get_page_count_without_saving(input_file_name): + # Instantiate Document instance document = ap.Document() - # 向PDF文件的页面集合中添加页面 + # Add page to pages collection of PDF file page = document.pages.add() - # 创建循环实例 - for i in range(0, 300): - # 向页面对象的段落集合中添加TextFragment - page.paragraphs.add(ap.text.TextFragment("页面数量测试")) - # 处理PDF文件中的段落以获取准确的页面数量 + # 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() - # 打印文档中的页面数量 - print("文档中的页面数量 =", str(len(document.pages))) + # Print number of pages in document + print("Number of pages in document =", str(len(document.pages))) ``` - ## 获取页面属性 -PDF 文件中的每个页面都有许多属性,例如宽度、高度、出血框、裁剪框和切割框。Aspose.PDF 允许您访问这些属性。 +PDF 文件中的每一页都有多个属性,例如宽度、高度、bleed-、crop- 和 trimbox。Aspose.PDF 允许您访问这些属性。 -### **理解页面属性:Artbox、BleedBox、CropBox、MediaBox、TrimBox 和 Rect 属性之间的区别** +### 了解页面属性:Artbox、BleedBox、CropBox、MediaBox、TrimBox 和 Rect 属性之间的区别 -- **媒体框**:媒体框是最大的页面框。它对应于打印为 PostScript 或 PDF 时选择的页面大小(例如 A4、A5、美国信纸等)。换句话说,媒体框确定了显示或打印 PDF 文档的媒介的物理大小。 -- **出血框**:如果文档有出血,PDF 也会有一个出血框。 - 出血是指超出页面边缘的颜色(或艺术作品)的量。它用于确保当文档被打印和裁剪到尺寸(“修边”)时,油墨将一直延伸到页面的边缘。即使页面被误裁——稍微偏离修边标记切割——页面上也不会出现白色边缘。 -- **修边框**: 修边框表示文档在打印和修边后的最终尺寸。 -- **艺术框**: 艺术框是在文档页面的实际内容周围绘制的框。当在其他应用程序中导入PDF文档时,使用此页面框。 -- **裁剪框**: 裁剪框是您的PDF文档在Adobe Acrobat中显示的“页面”尺寸。在正常视图中,Adobe Acrobat中仅显示裁剪框的内容。 - 有关这些属性的详细描述,请阅读Adobe.Pdf规范,特别是10.10.1页面边界。 -- **Page.Rect**: MediaBox和DropBox的交集(通常为可见矩形)。 下图说明了这些属性。 +- **Media box**: 媒体框是最大的页面框。它对应于文档在打印为 PostScript 或 PDF 时所选的页面尺寸(例如 A4、A5、US Letter 等)。换句话说,媒体框决定了显示或打印 PDF 文档的介质的实际尺寸。 +- **Bleed box**: 如果文档有出血,PDF 也会有出血框。出血是指超出页面边缘的颜色(或艺术作品)的量。它用于确保在文档打印并裁剪到尺寸(“trimmed”)时,墨水能够一直覆盖到页面的边缘。即使页面裁剪不准确——稍微偏离裁切标记——也不会在页面出现白边。 +- **Trim box**: 裁剪框表示文档打印并裁切后最终的尺寸。 +- **Art box**: 艺术框是围绕文档页面实际内容绘制的框。该页面框在将 PDF 文档导入其他应用程序时使用。 +- **Crop box**:Crop box 是在 Adobe Acrobat 中显示 PDF 文档时的“页面”尺寸。在普通视图中,只有 Crop box 的内容会在 Adobe Acrobat 中显示。 + 有关这些属性的详细描述,请阅读 Adobe.Pdf 规范,特别是 10.10.1 Page Boundaries。 +-- **Page.Rect**:MediaBox 和 DropBox 的交集(通常可见的矩形)(`Page.rect`)。 查看 [`Rectangle`](https://reference.aspose.com/pdf/python-net/aspose.pdf/rectangle/) 矩形属性的类型。下图说明了这些属性。 -有关更多详细信息,请访问[此页面](http://www.enfocus.com/manuals/ReferenceGuide/PP/10/enUS/en-us/concept/c_aa1095731.html)。 +如需进一步了解,请访问 [此页面](http://www.enfocus.com/manuals/ReferenceGuide/PP/10/enUS/en-us/concept/c_aa1095731.html). -### **访问页面属性** +### 访问页面属性 -[Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/)类提供了与特定PDF页面相关的所有属性。PDF文件的所有页面都包含在[Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)对象的[PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/)集合中。 +这 [页面](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 类提供与特定 PDF 页面相关的所有属性。PDF 文件的所有页面都包含在的 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象的 [页面集合](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 集合。 -从那里,可以使用它们的索引访问单个Page对象,或者使用foreach循环遍历集合以获取所有页面。一旦访问了单个页面,我们就可以获取其属性。以下代码片段展示了如何获取页面属性。 +从那里,可以访问单个 `Page` 使用索引访问对象,或遍历集合以获取所有页面。访问单个页面后,我们可以获取其属性。以下代码片段展示了如何获取页面属性( `Page` API). ```python - - import aspose.pdf as ap - - # 打开文件 - document = ap.Document(input_pdf) - # 获取特定页面 +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] - # 获取页面属性 - print( - "ArtBox : 高度={},宽度={},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 : 高度={},宽度={},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 : 高度={},宽度={},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 : 高度={},宽度={},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 : 高度={},宽度={},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 : 高度={},宽度={},LLX={},LLY={},URX={},URY={}".format( - page.rect.height, - page.rect.width, - page.rect.llx, - page.rect.lly, - page.rect.urx, - page.rect.ury, - ) - ) - print("页面编号 :", page.number) - print("旋转 :", page.rotate) -``` - -## 获取 PDF 文件的特定页面 - -Aspose.PDF for Python 允许您[将 PDF 拆分为单独的页面](/pdf/zh/python-net/split-pdf-document/)并将其另存为 PDF 文件。在 PDF 文件中获取指定页面并将其另存为新的 PDF 是一个非常类似的操作:打开源文档,访问页面,创建一个新文档并将页面添加到该文档中。 - -[Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document) 对象的 [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection) 包含 PDF 文件中的页面。要从此集合中获取特定页面: - -1. 使用 Pages 属性指定页面索引。 -2. 创建一个新的 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象。 -3. 将 [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 对象添加到新的 Document 对象中。 -4. 使用 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法保存输出。 - -以下代码片段演示了如何从 PDF 文件中获取特定页面并将其另存为新文件。 - -```python - - import aspose.pdf as ap - # 打开文档 - 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, + } - # 获取特定页面 - 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}" + ) - # 将页面保存为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}") ``` ## 确定页面颜色 -[Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 类提供了与PDF文档中特定页面相关的属性,包括页面使用的颜色类型 - RGB、黑白、灰度或未定义。 +这 [页面](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 类提供与 PDF 文档中特定页面相关的属性,包括页面使用的颜色类型——RGB、黑白、灰度或未定义。 -PDF文件的所有页面都包含在 [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 集合中。 - The [color_type](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) 属性指定页面元素的颜色。要获取或确定特定 PDF 页面的颜色信息,请使用 [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 对象的 [color_type](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) 属性。 +所有 PDF 文件的页面都包含在 [页面集合](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 集合。The [color_type](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) property 指定页面上元素的颜色。要获取或确定特定 PDF 页面 的颜色信息,请使用 the [页面](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 对象的 [color_type](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) property. 以下代码片段展示了如何遍历 PDF 文件的各个页面以获取颜色信息。 ```python - - import aspose.pdf as ap - - # 打开源 PDF 文件 - document = ap.Document(input_pdf) - # 遍历 PDF 文件的所有页面 - for page_n in range(0, len(document.pages)): - page_number = page_n + 1 - # 获取特定 PDF 页面的颜色类型信息 +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("Page # " + str(page_number) + " is Black and white.") - - if page_color_type == ap.ColorType.GRAYSCALE: - print("Page # " + str(page_number) + " is Gray Scale.") - - if page_color_type == ap.ColorType.RGB: - print("Page # " + str(page_number) + " is RGB.") - - if page_color_type == ap.ColorType.UNDEFINED: - print("Page # " + str(page_number) + " Color is undefined.") + 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 +## 相关页面主题 + +- [在 Python 中处理 PDF 页面](/pdf/zh/python-net/working-with-pages/) +- [在 Python 中更改 PDF 页面大小](/pdf/zh/python-net/change-page-size/) +- [在 Python 中裁剪 PDF 页面](/pdf/zh/python-net/crop-pages/) +- [在 Python 中旋转 PDF 页面](/pdf/zh/python-net/rotate-pages/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-pages/move-pages/_index.md b/zh/python-net/advanced-operations/working-with-pages/move-pages/_index.md index 9a9ae78e21..ed7ba57de7 100644 --- a/zh/python-net/advanced-operations/working-with-pages/move-pages/_index.md +++ b/zh/python-net/advanced-operations/working-with-pages/move-pages/_index.md @@ -1,161 +1,110 @@ --- -title: 使用Python编程移动PDF页面 -linktitle: 移动PDF页面 +title: 在 Python 中移动 PDF 页面 +linktitle: 移动 PDF 页面 type: docs weight: 100 url: /zh/python-net/move-pages/ -description: 尝试使用Aspose.PDF for Python via .NET在PDF文件中将页面移动到所需位置或文件末尾。 -lastmod: "2023-04-17" +description: 了解如何在 Python 中在文档内部或在文档之间移动 PDF 页面。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中在文档之间移动 PDF 页面 +Abstract: 本文介绍了如何使用 Aspose.PDF for Python via .NET 在 PDF 中移动页面。了解如何将单个页面或多个页面移动到另一个文档,以及如何使用 Document 和 PageCollection API 在同一 PDF 中重新定位页面。 --- - - ## 将页面从一个 PDF 文档移动到另一个 -本主题解释了如何使用 Python 将页面从一个 PDF 文档移动到另一个文档的末尾。 -要移动页面,我们应该: +Aspose.PDF for Python 允许您将页面(而不仅仅是复制)从一个 PDF 移动到另一个。它会从原始文档中删除所选页面,然后将其添加到新的 PDF 文件中。 -1. 使用源 PDF 文件创建一个 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类对象。 -1. 使用目标 PDF 文件创建一个 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类对象。 -1. 从 [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 集合中获取页面。 -1. 将页面 [add()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) 到目标文档。 -1. 使用 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法保存输出 PDF。 -1. 在源文档中 [delete()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) 页面。 +可以把它想象成把一本书中的页面剪下来粘到另一本书上——移动后该页面在原文件中不再存在。 -1. 使用[save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods)方法保存源PDF。 +1. 使用 ... 打开源 PDF 文档 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类。 +1. 选择要移动的特定页面(在本例中,第 2 页)— 这指的是 a [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +1. 创建新的 PDF 文档(实例化另一个 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)). +1. 使用目标文档的 将选定的页面添加到新 PDF 文档中 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) (例如, `another_document.pages.add(page)`). +1. 通过其从原始文档中删除页面 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) (例如, `document.pages.delete(index)`). +1. 保存两个文档。 -以下代码片段展示了如何移动一页。 +以下代码片段向您展示如何移动一页。 ```python - - import aspose.pdf as ap - - srcDocument = ap.Document(src_file_name) - dstDocument = ap.Document(dst_File_name) - page = srcDocument.pages[2] - dstDocument.pages.add(page) - # 保存输出文件 - dstDocument.save(dst_File_name_new) - srcDocument.pages.delete(2) - srcDocument.save(src_file_name_new) +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) ``` -## 从一个PDF文档移动一组页面到另一个 +## 将多个页面从一个 PDF 文档移动到另一个 PDF 文档 -1. 使用源PDF文件创建一个[Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)类对象。 -1. 使用目标PDF文件创建一个[Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)类对象。 -1. 定义一个数组,包含要移动的页面编号。 -1. 循环遍历数组: +与复制不同,此操作会转移所选页面——将它们从源文件中移除并保存到一个新的 PDF 中。 -1. 从 [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 集合中获取页面。 -1. 将页面[添加](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods)到目标文档。 -1. 使用 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法保存输出 PDF。 -1. 使用数组在源文档中[删除](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods)页面。 -1. 使用 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法保存源 PDF。 +1. 创建一个新的、空的目标文档 ("`Document`). +1. 从源文档中选择多个页面(在本例中为第 1 页和第 3 页) [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. 遍历所选页面并将每个页面添加到目标文档中 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. 保存包含已移动页面的目标文档。 +1. 使用其从源文档中删除已移动的页面。 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. 使用新文件名保存已修改的源文档,以保留两个版本。 -以下代码片段展示了如何在 PDF 文件的末尾插入一个空白页面。 +下面的代码片段展示了如何移动多个页面。 ```python - - import aspose.pdf as ap - - srcDocument = ap.Document(input_pdf) - dstDocument = ap.Document() - pages = [1, 3] +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) - # 保存输出文件 - 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")) ``` +## 在同一 PDF 文档中将页面移动到新位置 -## 在当前 PDF 文档中移动页面到新位置 +它展示了如何在同一文档中将特定页面移动到不同位置——在重新组织或编辑 PDF 布局时的常见需求。 -1. 使用源 PDF 文件创建一个 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类对象。 -1. 从 [PageCollection](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 集合中获取页面。 -1. 将页面 [add()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) 到新位置(例如末尾)。 -1. 在先前位置 [delete()](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/#methods) 页面。 -1. 使用 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法保存输出 PDF。 +1. 使用以下方法加载输入 PDF 文档 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类。 +1. 选择要移动的页面(第 2 页)——这是一 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +1. 使用文档的…将其添加到文档末尾 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. 通过以下方式从其先前位置删除原始页面 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/). +1. 将修改后的文档另存为新文件。 ```python +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) - import aspose.pdf as ap + page = src_document.pages[2] + src_document.pages.add(page) + src_document.pages.delete(2) - srcDocument = ap.Document(input_pdf) + # Save output file + src_document.save(output_file_name) +``` - page = srcDocument.pages[2] - srcDocument.pages.add(page) - srcDocument.pages.delete(2) +## 相关页面主题 - # 保存输出文件 - srcDocument.save(output_pdf) \ No newline at end of file +- [在 Python 中处理 PDF 页面](/pdf/zh/python-net/working-with-pages/) +- [在 Python 中添加 PDF 页面](/pdf/zh/python-net/add-pages/) +- [在 Python 中删除 PDF 页面](/pdf/zh/python-net/delete-pages/) +- [在 Python 中提取 PDF 页面](/pdf/zh/python-net/extract-pages/) diff --git a/zh/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md b/zh/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md index 8000f964b8..cb457a38ce 100644 --- a/zh/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md +++ b/zh/python-net/advanced-operations/working-with-pages/rotate-pages/_index.md @@ -1,174 +1,44 @@ --- -title: 使用 Python 旋转 PDF 页面 +title: 在 Python 中旋转 PDF 页面 linktitle: 旋转 PDF 页面 type: docs weight: 110 url: /zh/python-net/rotate-pages/ -description: 本主题描述如何使用 Python 编程旋转现有 PDF 文件中的页面方向。 -lastmod: "2023-04-17" +description: 学习如何在 Python 中旋转 PDF 页面并更改页面方向。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 旋转 PDF 页面 +Abstract: 这篇文章提供了一个指南,介绍如何使用 Python 以编程方式更新或更改现有 PDF 文件中页面的页面方向。利用 Aspose.PDF for Python via .NET,用户可以通过调整页面的 MediaBox 属性轻松在横向和纵向之间切换。文章包含一个 Python 代码片段,演示如何遍历 PDF 文档中的页面,修改它们的 MediaBox 尺寸和位置,并在必要时调整 CropBox。此外,还解释了如何使用 “rotate” 方法设置页面的旋转角度以实现所需的方向。该过程以保存更新后的 PDF 文件结束。 --- - +本主题描述了如何使用 Python 以编程方式更新或更改现有 PDF 文件中页面的页面方向。 -这个主题描述了如何使用Python以编程方式更新或更改现有PDF文件中的页面方向。 +当您需要在纵向和横向之间切换页面方向或对现有 PDF 内容应用旋转角度时,请使用此页面。 ## 更改页面方向 -通过 .NET 的Aspose.PDF for Python支持出色的功能,比如将页面方向从横向更改为纵向,反之亦然。要更改页面方向,请使用以下代码片段设置页面的MediaBox。您还可以通过使用“rotate”方法设置旋转角度来更改页面方向。 +此函数会旋转 PDF 的每一页 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 使用 Aspose.PDF for Python 顺时针旋转 90 度。 +它对于纠正页面方向问题非常有用,例如扫描的文档被横向放置。原始 PDF 保持不变,旋转后的版本保存为新文件。 ```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 - # 为了补偿页面大小的变化,我们必须将页面向上移动 - # (页面的下边缘是0,0,信息通常从页面顶部放置。这就是为什么我们在 - # 新旧高度之间的差异上移动下边缘向上。 - newLLY = r.lly + (r.height - newHeight) - page.media_box = ap.Rectangle(newLLX, newLLY, newLLX + newWidth, newLLY + newHeight, True) - # 有时我们还需要设置CropBox(如果它在原始文件中设置) - page.crop_box = ap.Rectangle(newLLX, newLLY, newLLX + newWidth, newLLY + newHeight, True) - - # 设置页面旋转角度 +def rotate_page(infile, outfile): + document = ap.Document(infile) + for page in document.pages: page.rotate = ap.Rotation.ON90 - # 保存输出文件 - doc.save(output_pdf) + document.save(outfile) ``` +## 相关页面主题 - \ No newline at end of file +- [在 Python 中处理 PDF 页面](/pdf/zh/python-net/working-with-pages/) +- [在 Python 中更改 PDF 页面大小](/pdf/zh/python-net/change-page-size/) +- [在 Python 中裁剪 PDF 页面](/pdf/zh/python-net/crop-pages/) +- [在 Python 中获取和设置 PDF 页面属性](/pdf/zh/python-net/get-and-set-page-properties/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-pages/stamping/_index.md b/zh/python-net/advanced-operations/working-with-pages/stamping/_index.md index c41bc9b395..6abd5bf5d8 100644 --- a/zh/python-net/advanced-operations/working-with-pages/stamping/_index.md +++ b/zh/python-net/advanced-operations/working-with-pages/stamping/_index.md @@ -1,86 +1,29 @@ --- -title: 使用 Python 和 Aspose.PDF 进行盖章 +title: 在 Python 中为 PDF 页面加盖印章 linktitle: 盖章 type: docs weight: 120 url: /zh/python-net/stamping/ -description: 本节介绍如何通过 Python 向 PDF 页面添加图像印章和文本印章。 -lastmod: "2023-04-17" +description: 了解如何在 Python 中向 PDF 页面添加页码、页面印章、图像印章和文字印章。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 为 PDF 添加印章 +Abstract: 本文讨论了 PDF 文档中印章的概念和应用,印章类似于纸质文档上的橡皮章,可提供附加信息并增强文档安全性。文章重点介绍了使用 **Aspose.PDF for Python via .NET** 在 PDF 中添加图像印章或文字印章。内容包括添加图像印章、控制图像质量以及将图像印章用作背景的指导,同时还提供了添加文字印章、设置对齐方式和在 PDF 中填充描边文字的说明。读者可以查看两个章节获取详细步骤——\u0022Add Image stamps in PDF page\u0022 和 \u0022Add Text stamps in the PDF File\u0022。 --- - +PDF 文档中的印章类似于在纸质文档上使用橡皮章。 +PDF文件中的印章提供了额外的信息,例如保护PDF文件免受他人使用,并确认PDF文件内容的安全性。**Aspose.PDF for Python via .NET** 允许在您的 PDF 文档中添加图像或文本印章。 -在 PDF 文档中,印章类似于在纸质文档上应用橡皮印章。 -PDF 文件中的印章提供了 PDF 文件的附加信息,例如保护 PDF 文件不被他人使用以及确认 PDF 文件内容的安全性。**Aspose.PDF for Python via .NET** 允许在您的 PDF 文档中添加图像或文字印章。 +当您需要向现有 PDF 页面添加页码、水印、徽标或文本标记等覆盖层时,请使用本节。 + +查看以下章节,了解如何使用 Python 添加印章: + +- [在 PDF 页面中添加图像印章](/pdf/zh/python-net/image-stamps-in-pdf-page/) - 添加图像印章,控制图像质量,将图像印章设为 PDF 文件的背景。 +- [在 PDF 文件中添加文本印章](/pdf/zh/python-net/text-stamps-in-the-pdf-file/) - 添加文本印章,为 TextStamp 对象定义对齐方式,以描边文本作为 PDF 文件中的印章。 +- [在 PDF 文件中添加页面印章](/pdf/zh/python-net/page-stamps-in-the-pdf-file/) - 添加页面印章以覆盖整页或章节,适用于水印、文档版本控制或为 PDF 文件添加自定义背景。 +- [在 PDF 文件中添加页码印章](/pdf/zh/python-net/add-page-number/) - 为您的 PDF 文档添加页码,自定义其外观,并控制其位置。 -查看以下部分以了解如何使用 Python 添加印章: -- [在 PDF 页面中添加图像印章](/pdf/zh/python-net/image-stamps-in-pdf-page/) - 添加图像印章,控制图像质量,将图像印章作为 PDF 文件的背景。 -- [在 PDF 文件中添加文字印章](/pdf/zh/python-net/text-stamps-in-the-pdf-file/) - 添加文字印章,为 TextStamp 对象定义对齐方式,在 PDF 文件中填充描边文字作为印章。 \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-pages/stamping/add-page-number/_index.md b/zh/python-net/advanced-operations/working-with-pages/stamping/add-page-number/_index.md new file mode 100644 index 0000000000..41dcee84f1 --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-pages/stamping/add-page-number/_index.md @@ -0,0 +1,118 @@ +--- +title: 在 Python 中为 PDF 添加页码 +linktitle: 添加页码 +type: docs +weight: 30 +url: /zh/python-net/add-page-number/ +description: 了解如何在 Python 中向 PDF 文档添加页码戳。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 为 PDF 添加页码 +Abstract: 本文讨论了在文档中添加页码以便更轻松导航的重要性,并介绍了 Aspose.PDF for Python via .NET 库,作为在 PDF 文件中实现此功能的工具。该库使用 PageNumberStamp 类,提供了自定义页码戳的属性,包括格式、边距、对齐方式和起始编号。该过程包括创建 Document 对象和 PageNumberStamp 对象,配置所需属性,并使用 add_stamp() 方法将戳应用于 PDF 页面。文章提供了一个 Python 代码示例,演示如何设置和应用带有可自定义字体属性的页码戳。 +--- + +所有文档都必须包含页码。页码使读者更容易定位文档的不同部分。 + +**Aspose.PDF for Python via .NET** 允许您添加页码 [PageNumberStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagenumberstamp/). + +## 向 PDF 添加页码印章 + +向 PDF 添加动态页码印章 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 使用 Aspose.PDF for Python。 [`PageNumberStamp`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagenumberstamp/) 对象允许您自动显示当前页码以及总页数。示例展示了如何使用创建页码印章,定制其外观(字体、大小、样式、颜色、对齐方式和边距) [`TextState`](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstate/),并将其应用于特定的 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 在 PDF 中通过 [`Page.add_stamp()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods) 方法。对齐值来自于 [`HorizontalAlignment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/horizontalalignment/) 枚举,颜色/字体/样式可通过 [`Color`](https://reference.aspose.com/pdf/python-net/aspose.pdf/color/) 和 [`FontStyles`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/fontstyles/) (通过发现的字体 [`FontRepository.find_font()`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/fontrepository/#methods)). 此功能对于生成专业的、带编号的文档以及在 PDF 工作流中自动化分页非常有用。 + +1. 打开 PDF 文档。 +1. 创建页码印章。 +1. 设置印章属性。 +1. 自定义文本样式。 +1. 将印章应用于页面。 +1. 保存修改后的 PDF。 + +```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) +``` + +## 向 PDF 添加罗马数字页码 + +在 PDF 文档的所有页面上添加罗马数字格式的页码。页码通过使用 [`PageNumberStamp`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagenumberstamp/),具有可自定义的字体、大小、样式、颜色和对齐方式。使用的 [`NumberingStyle`](https://reference.aspose.com/pdf/python-net/aspose.pdf/numberingstyle/) 枚举来选择罗马数字或其他编号方案。编号也可以从任意指定的值开始。 + +1. 打开 PDF 文档。 +1. 创建页码印章。 +1. 配置印章属性。 +1. 设置文本外观。 +1. 将印章应用于所有页面。 +1. 保存修改后的 PDF。 + +```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) +``` + +## 实时示例 + +[添加 PDF 页码](https://products.aspose.app/pdf/page-number) 是一个在线免费网页应用程序,允许您研究添加页码功能的工作方式。 + +[![如何使用 Python 在 PDF 中添加页码](page_number.png)](https://products.aspose.app/pdf/page-number) + +## 相关的盖章主题 + +- [在 Python 中对 PDF 页面加盖印章](/pdf/zh/python-net/stamping/) +- [使用 Python 向 PDF 添加页面印章](/pdf/zh/python-net/page-stamps-in-the-pdf-file/) +- [使用 Python 向 PDF 添加图像印章](/pdf/zh/python-net/image-stamps-in-pdf-page/) +- [在 Python 中向 PDF 添加文本印章](/pdf/zh/python-net/text-stamps-in-the-pdf-file/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-pages/stamping/add-page-number/page_number.png b/zh/python-net/advanced-operations/working-with-pages/stamping/add-page-number/page_number.png new file mode 100644 index 0000000000..d718abd250 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-pages/stamping/add-page-number/page_number.png differ diff --git a/zh/python-net/advanced-operations/working-with-pages/stamping/add-page-stamp/_index.md b/zh/python-net/advanced-operations/working-with-pages/stamping/add-page-stamp/_index.md new file mode 100644 index 0000000000..d312254128 --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-pages/stamping/add-page-stamp/_index.md @@ -0,0 +1,48 @@ +--- +title: 在 Python 中向 PDF 添加页面印章 +linktitle: 添加页面印章 +type: docs +weight: 30 +url: /zh/python-net/page-stamps-in-the-pdf-file/ +description: 了解如何在 Python 中将 PDF 页面印章作为叠加层或背景添加。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 向 PDF 添加页面印章 +Abstract: 本文介绍如何使用 Aspose.PDF for Python 向 PDF 文档添加页面印章。页面印章允许您在 PDF 的特定页面上覆盖或底层放置内容——如徽标、水印或批注。示例展示了如何打开现有 PDF,从另一个 PDF 页面创建 PdfPageStamp 对象,将其配置为背景印章,并将其应用于指定页面。随后将带印章的 PDF 保存为新文档。此技术在自动化 PDF 工作流中用于品牌化、水印或强调页面级内容。 +--- + +Aspose.PDF for Python via .NET 展示了如何将页面印章(水印或叠加层)应用于 PDF 的特定页面 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). 页面印章可以是作为背景或前景层使用的已有 PDF 页面(参见 [`PdfPageStamp`](https://reference.aspose.com/pdf/python-net/aspose.pdf.pdfpagestamp/))。这对于添加徽标、水印或其他重复的页面内容非常有用。 + +1. 使用以下方法打开 PDF 文档 `ap.Document()` (见 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)). +1. 创建一个 `PdfPageStamp` 使用 PDF 页面或文件作为印章的对象(参见 [`PdfPageStamp`](https://reference.aspose.com/pdf/python-net/aspose.pdf.pdfpagestamp/)). +1. 设置印章属性,例如, `background = True` 将其放置在内容后面。 +1. 使用以下方法将印章添加到特定页面 `document.pages[page_number].add_stamp(page_stamp)` (见 [`Page.add_stamp()`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods) 和 [`PageCollection`](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/)). +1. 使用以下方式将修改后的 PDF 保存到指定的输出文件 [`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) +``` + +## 相关的盖章主题 + +- [在 Python 中对 PDF 页面加盖印章](/pdf/zh/python-net/stamping/) +- [在 Python 中为 PDF 添加页码](/pdf/zh/python-net/add-page-number/) +- [使用 Python 向 PDF 添加图像印章](/pdf/zh/python-net/image-stamps-in-pdf-page/) +- [在 Python 中向 PDF 添加文本印章](/pdf/zh/python-net/text-stamps-in-the-pdf-file/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-pages/stamping/image-stamps-in-pdf-page/_index.md b/zh/python-net/advanced-operations/working-with-pages/stamping/image-stamps-in-pdf-page/_index.md index d1cc3258a8..a1f94313aa 100644 --- a/zh/python-net/advanced-operations/working-with-pages/stamping/image-stamps-in-pdf-page/_index.md +++ b/zh/python-net/advanced-operations/working-with-pages/stamping/image-stamps-in-pdf-page/_index.md @@ -1,101 +1,38 @@ --- -title: 使用 Python 在 PDF 中添加图像印章 +title: 在 Python 中向 PDF 添加图像印章 linktitle: PDF 文件中的图像印章 type: docs weight: 10 url: /zh/python-net/image-stamps-in-pdf-page/ -description: 使用 Aspose.PDF for Python 库的 ImageStamp 类在 PDF 文档中添加图像印章。 -lastmod: "2023-04-17" +description: 了解如何在 Python 中向 PDF 页面添加图像印章。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 在 PDF 中添加图像印章 +Abstract: 本文提供了使用 Aspose.PDF library for Python 向 PDF 文件添加图像印章的全面指南。文中详细说明了 `ImageStamp` 类的使用,该类允许自定义基于图像的印章,包括高度、宽度、不透明度和旋转等属性。过程包括创建一个 `Document` 对象和一个具有所需属性的 `ImageStamp` 对象,然后使用 `add_stamp()` 方法将印章添加到 PDF 的特定页面。文章包含了 Python 代码片段,演示如何将图像印章应用于 PDF 并使用 `quality` 属性控制其质量,该属性以百分比形式调整图像质量。此外,文章还解释了如何使用 `FloatingBox` 类将图像印章作为浮动框的背景,并提供了另一个代码示例来展示实现方式。本指南是希望使用 Aspose.PDF 为 PDF 增强图像印章的开发者的有用资源。 --- - - ## 在 PDF 文件中添加图像印章 -您可以使用 [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) 类向 PDF 文件添加图像印章。[ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) 类提供了创建基于图像的印章所需的属性,如高度、宽度、不透明度等。 - -要添加图像印章: - -1. 使用所需属性创建一个 Document 对象和一个 ImageStamp 对象。 -1. 调用 [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 类的 [add_stamp()](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods) 方法将印章添加到 PDF 中。 +您可以使用 [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) 类来向 PDF 文件添加图像印章。The [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) 类提供创建基于图像的印章所需的属性,如高度、宽度、不透明度等。该印章可以定位、调整大小、旋转,并可部分透明,从而实现水印、品牌或注释。 以下代码片段展示了如何在 PDF 文件中添加图像印章。 -```python - - import aspose.pdf as ap +1. 使用 'ap.Document()' 加载 PDF。 +1. 使用 'ImageStamp()' 创建图像印章。 +1. 配置印章属性。 +1. 将印章添加到目标页面。 +1. 保存修改后的 PDF。 - # 打开文档 - document = ap.Document(input_pdf) +```python +import sys +import aspose.pdf as ap +from os import path - # 创建图像印章 +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 @@ sitemap: image_stamp.width = 300 image_stamp.rotate = ap.Rotation.ON270 image_stamp.opacity = 0.5 - # 将印章添加到特定页面 - document.pages[1].add_stamp(image_stamp) - # 保存输出文档 - document.save(output_pdf) + document.pages[1].add_stamp(image_stamp) + document.save(outfile) ``` +## 添加印章时控制图像质量 -## 控制添加图章时的图像质量 +在将图像添加为印章对象时,您可以控制图像的质量。该 [质量](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/#properties) 属性的 [ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) 类用于此目的。它以百分比表示图像的质量(有效值为 0..100)。 +通过设置 quality 属性,您可以降低图像分辨率以优化 PDF 大小,或保持更高的保真度以获得更清晰的效果。 -在将图像作为图章对象添加时,您可以控制图像的质量。[ImageStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/) 类的 [quality](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/#properties) 属性用于此目的。它表示图像的质量百分比(有效值为 0..100)。 +1. 打开 PDF 文档。 +1. 创建图像印章。 +1. 设置图像质量。 +1. 将印章添加到目标页面。 +1. 保存修改后的 PDF。 ```python +import sys +import aspose.pdf as ap +from os import path - import aspose.pdf as ap +def add_image_stamp_with_quality_control(infile, input_image_file, outfile): + document = ap.Document(infile) - # 打开文档 - document = ap.Document(input_pdf) - - # 创建图像图章 - image_stamp = ap.ImageStamp(input_jpg) + image_stamp = ap.ImageStamp(input_image_file) image_stamp.quality = 10 - # 将图章添加到特定页面 - document.pages[1].add_stamp(image_stamp) - # 保存输出文档 - document.save(output_pdf) + document.pages[1].add_stamp(image_stamp) + document.save(outfile) ``` -## 浮动框中的背景图像图章 +## 图像印章作为浮动框的背景 -Aspose.PDF for Python API 允许您在浮动框中添加图像图章作为背景。 - [FloatingBox](https://reference.aspose.com/pdf/python-net/aspose.pdf/floatingbox/) 类的 [background](https://reference.aspose.com/pdf/python-net/aspose.pdf/imagestamp/#properties) 属性可以用于为浮动框设置背景图像印章,如以下代码示例所示。 +创建一个 [FloatingBox](https://reference.aspose.com/pdf/python-net/aspose.pdf/floatingbox/) 在 PDF 中应用图像作为其背景。它还展示了如何添加文本、设置边框、背景颜色,以及在页面上精确定位该框。此功能对于创建视觉丰富的 PDF 内容非常有用,例如带有图像上文字的标注、横幅或高亮区域。 -```python - - import aspose.pdf as ap +1. 打开或创建 PDF 文档。 +1. 创建一个 'FloatingBox' 对象。 +1. 向框中添加文本内容。 +1. 设置框的边框和背景颜色。 +1. 添加背景图像。 +1. 将 FloatingBox 添加到页面。 +1. 保存 PDF 文档。 - # 实例化 Document 对象 - document = ap.Document() - # 向 PDF 文档添加页面 - page = document.pages.add() - # 创建 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) - # 设置 FloatingBox 的左侧位置 + # Set left position for FloatingBox box.left = 40 - # 设置 FloatingBox 的顶部位置 + # Set Top position for FloatingBox box.top = 80 - # 设置 FloatingBox 的水平对齐方式 + # Set the Horizontal alignment for FloatingBox box.horizontal_alignment = ap.HorizontalAlignment.CENTER - # 向 FloatingBox 的段落集合中添加文本片段 - box.paragraphs.add(ap.text.TextFragment("main text")) - # 设置 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 - # 添加背景图像 + # Add background image box.background_image = img - # 设置 FloatingBox 的背景颜色 + # Set background color for FloatingBox box.background_color = ap.Color.yellow - # 将 FloatingBox 添加到页面对象的段落集合中 + # Add FloatingBox to paragraphs collection of page object page.paragraphs.add(box) - # 保存 PDF 文档 - document.save(output_pdf) + # Save the PDF document + document.save(outfile) ``` - \ No newline at end of file +## 相关的盖章主题 + +- [在 Python 中对 PDF 页面加盖印章](/pdf/zh/python-net/stamping/) +- [使用 Python 向 PDF 添加页面印章](/pdf/zh/python-net/page-stamps-in-the-pdf-file/) +- [在 Python 中向 PDF 添加文本印章](/pdf/zh/python-net/text-stamps-in-the-pdf-file/) +- [在 Python 中为 PDF 添加页码](/pdf/zh/python-net/add-page-number/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-pages/stamping/text-stamps-in-pdf-file/_index.md b/zh/python-net/advanced-operations/working-with-pages/stamping/text-stamps-in-pdf-file/_index.md index b33013feab..12c4588262 100644 --- a/zh/python-net/advanced-operations/working-with-pages/stamping/text-stamps-in-pdf-file/_index.md +++ b/zh/python-net/advanced-operations/working-with-pages/stamping/text-stamps-in-pdf-file/_index.md @@ -1,259 +1,65 @@ --- -title: 在 PDF 中添加文字印章通过 Python -linktitle: PDF 文件中的文字印章 +title: 在 Python 中向 PDF 添加文本印章 +linktitle: PDF 文件中的文本印章 type: docs weight: 20 url: /zh/python-net/text-stamps-in-the-pdf-file/ -description: 使用 Aspose.PDF for Python 库的 TextStamp 类向 PDF 文档添加文字印章。 -lastmod: "2023-04-17" +description: 学习如何在 Python 中向 PDF 文档添加文本印章。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 在 PDF 中添加文本印章 +Abstract: 本文提供了使用 Aspose.PDF for Python 库向 PDF 文件添加文本印章的完整指南。它概述了使用 `TextStamp` 类创建可自定义的文本印章,具备字体大小、样式、颜色和对齐等属性。文章包含代码示例,演示如何添加简单的文本印章、配置文本对齐以及应用诸如填充描边文本等高级渲染模式。第一部分说明了创建 `Document` 和 `TextStamp` 对象、设置文本属性并将印章添加到特定页面的过程。第二部分介绍了 `text_alignment` 属性,用于水平和垂直对齐文本,并提供了在 PDF 页面上居中文本的代码示例。最后一部分讨论了渲染模式,演示如何使用 `TextState` 对象设置描边颜色和渲染模式后,再将其绑定到印章,从而实现填充描边文本。每个部分均配有实用示例,以帮助读者理解并实现相关功能。 --- - +## 使用 Python 添加文本印章 -## 使用 Python 添加文字印章 +您可以使用 [TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/) 类用于在 PDF 文件中添加文本印章。 [TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/) 类提供创建基于文本的印章所需的属性,如字体大小、字体样式和字体颜色等。为了添加文本印章,您需要使用所需属性创建一个 Document 对象和一个 TextStamp 对象。之后,您可以调用 [add_stamp()](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods) Page 的方法,以在 PDF 中添加印章。以下代码片段展示了如何在 PDF 文件中添加文本印章。这对于向 PDF 页面添加注释、水印或标签非常有用。 -您可以使用 [TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/) 类在 PDF 文件中添加文字印章。[TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/) 类提供了创建基于文本的印章所需的属性,例如字体大小、字体样式和字体颜色等。为了添加文字印章,您需要使用所需的属性创建一个 Document 对象和一个 TextStamp 对象。之后,您可以调用 Page 的 [add_stamp()](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#methods) 方法在 PDF 中添加印章。以下代码片段向您展示了如何在 PDF 文件中添加文字印章。 +1. 打开 PDF 文档。 +1. 创建一个 TextStamp 对象。 +1. 设置印章背景行为。 +1. 在页面上定位印章。 +1. 如有需要,旋转印章。 +1. 设置文本属性。 +1. 将印章添加到页面。 +1. 保存修改后的 PDF 文档。 ```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) - # 打开文档 - document = ap.Document(input_pdf) - - # 创建文字印章 + # Create text stamp text_stamp = ap.TextStamp("Sample Stamp") - # 设置印章是否为背景 + # Set whether stamp is background text_stamp.background = True - # 设置起始位置 + # Set origin text_stamp.x_indent = 100 text_stamp.y_indent = 100 - # 旋转印章 + # Rotate stamp text_stamp.rotate = ap.Rotation.ON90 - # 设置文本属性 + # 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 - # 将印章添加到特定页面 - document.pages[1].add_stamp(text_stamp) - - # 保存输出文档 - document.save(output_pdf) -``` - - -## 为 TextStamp 对象定义对齐方式 - -在 PDF 文档中添加水印是经常需要的功能之一,Aspose.PDF for Python 完全能够添加图像和文本水印。我们有一个名为 [TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/) 的类,它提供了在 PDF 文件上添加文本印章的功能。最近有一个需求是支持在使用 TextStamp 对象时指定文本对齐方式的功能。因此,为了满足这一需求,我们在 [TextStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/) 类中引入了 [text_alignment](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/#properties) 属性。使用此属性,我们可以指定 [horizontal_alignment](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstamp/#properties) 文本对齐方式。 - -以下代码片段展示了如何加载现有 PDF 文档并在其上添加 TextStamp 的示例。 - -```python - - import aspose.pdf as ap - - # 用输入文件实例化 Document 对象 - doc = ap.Document(input_pdf) - # 用示例字符串实例化 FormattedText 对象 - text = ap.facades.FormattedText("This") - # 向 FormattedText 添加新文本行 - text.add_new_line_text("is sample") - text.add_new_line_text("Center Aligned") - text.add_new_line_text("TextStamp") - text.add_new_line_text("Object") - # 使用 FormattedText 创建 TextStamp 对象 - stamp = ap.TextStamp(text) - # 指定文本印章的水平对齐方式为居中对齐 - stamp.horizontal_alignment = ap.HorizontalAlignment.CENTER - # 指定文本印章的垂直对齐方式为居中对齐 - stamp.vertical_alignment = ap.VerticalAlignment.CENTER - # 指定 TextStamp 的文本水平对齐方式为居中对齐 - stamp.text_alignment = ap.HorizontalAlignment.CENTER - # 设置印章对象的上边距 - stamp.top_margin = 20 - # 在文档的第一页上添加印章对象 - doc.pages[1].add_stamp(stamp) - - # 保存更新后的文档 - doc.save(output_pdf) -``` - - -## 在 PDF 文件中填充描边文本作为印章 - -我们已经实现了在文本添加和编辑场景中设置渲染模式。要渲染描边文本,请创建 TextState 对象以传递高级属性。为描边设置颜色。之后,设置文本渲染模式,下一步是绑定 TextState,并添加印章。 - -以下代码片段演示了如何添加填充描边文本: - -```python - - import aspose.pdf as ap - - # 创建 TextState 对象以传递高级属性 - ts = ap.text.TextState() - # 为描边设置颜色 - ts.stroking_color = ap.Color.gray - # 设置文本渲染模式 - ts.rendering_mode = ap.text.TextRenderingMode.STROKE_TEXT - # 加载输入 PDF 文档 - file_stamp = ap.facades.PdfFileStamp(ap.Document(input_pdf)) - - stamp = ap.facades.Stamp() - stamp.bind_logo( - ap.facades.FormattedText( - "PAID IN FULL", - 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) - # 绑定 TextState - stamp.bind_text_state(ts) - # 设置 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 - # 添加印章 - file_stamp.add_stamp(stamp) - file_stamp.save(output_pdf) - file_stamp.close() + document.save(output_file_name) ``` +## 相关的盖章主题 - \ No newline at end of file +- [在 Python 中对 PDF 页面加盖印章](/pdf/zh/python-net/stamping/) +- [使用 Python 向 PDF 添加页面印章](/pdf/zh/python-net/page-stamps-in-the-pdf-file/) +- [使用 Python 向 PDF 添加图像印章](/pdf/zh/python-net/image-stamps-in-pdf-page/) +- [在 Python 中为 PDF 添加页码](/pdf/zh/python-net/add-page-number/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-tables/_index.md b/zh/python-net/advanced-operations/working-with-tables/_index.md index bb570dfb87..616089375e 100644 --- a/zh/python-net/advanced-operations/working-with-tables/_index.md +++ b/zh/python-net/advanced-operations/working-with-tables/_index.md @@ -1,152 +1,29 @@ --- -title: 使用 Python 处理 PDF 中的表格 +title: 在 PDF 中使用 Python 处理表格 linktitle: 处理表格 type: docs weight: 50 url: /zh/python-net/working-with-tables/ -description: 本节描述如何添加和提取表格,如何使用 Python 库操作和处理表格。 -lastmod: "2023-09-17" +description: 了解如何使用 Python 在 PDF 文档中添加、提取、集成、操作和删除表格。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中添加、提取、集成和管理 PDF 表格 +Abstract: 本节说明如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中处理表格。了解如何创建和插入表格、提取表格数据、将表格与数据源集成、修改表格内容以及在 Python 工作流中从现有 PDF 文件中删除表格。 --- - +**Aspose.PDF for Python via .NET** 提供完整的工具,用于在 PDF 文件中处理表格。您可以创建并添加表格、控制表格布局和页面流、提取表格数据、更新现有表格,以及从现有 PDF 中删除一个或多个表格。 -**Aspose.PDF for Python via .NET** 允许您在 PDF 文件中高级处理表格。这个完美的工具通过提取表格帮助解决 PDF 的简单性问题。使用 Python 库资源,您可以轻松地在现有 PDF 文档中创建或添加表格,确定表格是否会在当前页面中断,提取表格,以及从现有 PDF 中删除表格。 +当您需要使用 Python 构建基于表格的报告、从 PDF 中提取结构化数据,或在现有文档中更新表格内容时,请使用本节。 -您可以执行以下操作: - -- [在现有 PDF 文档中创建或添加表格](/pdf/zh/python-net/add-table-in-existing-pdf-document/) - 在 PDF 文件中创建表格时合并列或行,并考虑边框、边距和填充。 -- [从现有 PDF 文档中提取表格](/pdf/zh/python-net/extract-table-from-existing-pdf-document/) - 您可以从 PDF 文件中提取表格。 -- [在现有 PDF 中操作表格](/pdf/zh/python-net/manipulate-tables-in-existing-pdf/) - 使用 TableAbsorber 操作 PDF 中的表格。 +## 覆盖的表格任务 -- [从现有 PDF 中删除表格](/pdf/zh/python-net/remove-tables-from-existing-pdf/) - 从 PDF 文档中删除一个或多个表格。 +您可以执行以下操作: - \ No newline at end of file +- [添加表格](/pdf/zh/python-net/adding-tables/) - 在 PDF 文件中创建表格,包括合并的行/列、边框、页边距和填充。 +- [提取表格](/pdf/zh/python-net/extracting-table/) - 从现有 PDF 文件中提取表格数据。 +- [将表格与数据源集成](/pdf/zh/python-net/integrate-table/) - 从数据库和 pandas DataFrame 数据在 Python 中构建表格。 +- [操作表格](/pdf/zh/python-net/manipulating-tables/) - 检查并更新 PDF 文档中的现有表格。 +- [删除表格](/pdf/zh/python-net/removing-tables/) - 从 PDF 文档中删除一个或多个表格。 diff --git a/zh/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/_index.md b/zh/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/_index.md index 2f4a301551..5a78ac87e6 100644 --- a/zh/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/_index.md +++ b/zh/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/_index.md @@ -1,545 +1,841 @@ --- -title: 在 PDF 中创建或添加表格使用 Python -linktitle: 创建或添加表格 +title: 在 Python 中向 PDF 添加表格 +linktitle: 添加表格 type: docs weight: 10 -url: /zh/python-net/add-table-in-existing-pdf-document/ -description: Aspose.PDF for Python via .NET 是一个用于创建、读取和编辑 PDF 表格的库。在此主题中查看其他高级功能。 -lastmod: "2023-02-17" +url: /zh/python-net/adding-tables/ +description: 了解如何在 Python 中向现有 PDF 文档添加和配置表格。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 在 PDF 文档中添加和格式化表格。 +Abstract: 本文解释了如何在 PDF 文档中使用 Aspose.PDF for Python via .NET 添加和配置表格。它涵盖了表格创建、边框、页边距、内边距、行和列跨距、AutoFit 行为、表格宽度处理、单元格中的图像插入以及跨页渲染控制。 --- - - - -## 使用 Python 创建表格 - -在处理 PDF 文档时,表格非常重要。它们为系统化显示信息提供了极好的功能。Aspose.PDF 命名空间包含名为 [Table](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/)、[Cell](https://reference.aspose.com/pdf/python-net/aspose.pdf/cell/) 和 [Row](https://reference.aspose.com/pdf/python-net/aspose.pdf/row/) 的类,这些类提供了从头创建 PDF 文档时创建表格的功能。 - -可以通过创建 Table 类的对象来创建表格。 -```python +在现有 PDF 文档中添加表格是数据展示、结构化内容和报告的常见需求。**Aspose.PDF for Python via .NET** 提供了一个实用的 API,用于在现有 PDF 中插入和格式化表格。 + +本指南提供了表格创建、列大小设置、边框、行和单元格以及保存修改后文档的分步示例。它还涵盖了高级选项,如单元格边框、外边距、内边距以及用于动态表格大小的 AutoFit 设置。 + +当您需要在已有 PDF 中添加新表格并在 Python 中控制其布局行为时,请使用此页面。 + +## 创建基本表格 + +### 创建表格 + +本示例演示如何在 PDF 文档中创建带有边框和多行的表格。 +1. 创建一个新的 PDF 文档。 +1. 在文档中添加一个空白页。 +1. 初始化表格。 +1. 设置整体表格边框。 +1. 设置单个单元格的边框。 +1. 添加行和单元格。 +1. 将表格插入页面中。 +1. 将 PDF 保存到指定路径。 + +```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) -### 在现有 PDF 文档中添加表格 + # Save updated document containing table object + document.save(outfile) +``` -要通过 .NET 使用 Aspose.PDF for Python 将表格添加到现有的 PDF 文件,请执行以下步骤: +### 将图像添加到表格单元格 -1. 加载源文件。 -1. 初始化表格并设置其列和行。 -1. 设置表格设置(我们已设置边框)。 -1. 填充表格。 -1. 将表格添加到页面。 -1. 保存文件。 +此代码片段展示了如何在 PDF 文档的 Table 单元格中插入图像。 -以下代码片段显示了如何在现有 PDF 文件中添加文本。 +1. 创建一个新的 PDF 文档。 +1. 初始化表格。 +1. 以点为单位设置列宽。 +1. 已将文本片段添加到第一个单元格。 +1. 一个 'ap.Image()' 实例被添加到第二个单元格。 +1. 将图像文件的路径设置为 'img.file'。 +1. ‘img.fix_width’ 和 ‘img.fix_height’ 控制单元格内图像的大小。 +1. 将表格插入 PDF 页面。 +1. 保存 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) +``` + +您可以将 SVG 图像添加到 PDF 文档的表格单元格中: - # 加载源PDF文档 - doc = ap.Document(input_file) - # 初始化一个新的表实例 +```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() - # 将表格边框颜色设置为浅灰色 - table.border = ap.BorderInfo(ap.BorderSide.ALL, 5, ap.Color.from_rgb(apd.Color.light_gray)) - # 设置表格单元格的边框 - table.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, 5, ap.Color.from_rgb(apd.Color.light_gray)) - # 创建一个循环以添加10行 - for row_count in range(0, 10): - # 向表中添加行 + # 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() - # 添加表格单元格 - row.cells.add("列 (" + str(row_count) + ", 1)") - row.cells.add("列 (" + str(row_count) + ", 2)") - row.cells.add("列 (" + str(row_count) + ", 3)") - # 将表对象添加到输入文档的第一页 - doc.pages[1].paragraphs.add(table) - # 保存包含表对象的更新文档 - 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和RowSpan +### 表格中的列跨度和行跨度 -Aspose.PDF for Python via .NET 提供了 [col_span](https://reference.aspose.com/pdf/python-net/aspose.pdf/cell/#properties) 属性用于合并表中的列,以及 [row_span](https://reference.aspose.com/pdf/python-net/aspose.pdf/cell/#properties) 属性用于合并行。 +此示例展示了如何垂直和水平合并表格单元格以创建复杂的表格布局。 - -我们在创建表格单元格的 `Cell` 对象上使用 `col_span` 或 `row_span` 属性。应用所需属性后,创建的单元格可以添加到表格中。 +1. 设置整体表格边框。 +1. 设置默认单元格边框。 +1. 将两个单元格水平合并为一个。 +1. 将单元格垂直合并跨越两行。 +1. 第5行通过跳过合并的列来处理跨行(rowspan)。 +1. 将表格插入页面中。 +1. 保存 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() - # 通过调用空构造函数初始化 Document 对象 - pdf_document = ap.Document() - pdf_document.pages.add() - # 初始化一个新的 Table 实例 + # Initializes a new instance of the Table table = ap.Table() - # 设置表格边框颜色为浅灰色 + # Set the table border color as LightGray table.border = ap.BorderInfo(ap.BorderSide.ALL, 0.5, ap.Color.black) - # 设置表格单元格的边框 + # Set the border for table cells table.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, 0.5, ap.Color.black) - # 向表格添加第一行 + # Add 1st row to table row1 = table.rows.add() - for cellCount in range(1, 5): - # 添加表格单元格 - row1.cells.add("测试 1" + str(cellCount)) + for cell_count in range(1, 5): + # Add table cells + row1.cells.add("Test 1" + str(cell_count)) - # 向表格添加第二行 + # Add 2nd row to table row2 = table.rows.add() - row2.cells.add("测试 2 1") - cell = row2.cells.add("测试 2 2") + row2.cells.add("Test 2 1") + cell = row2.cells.add("Test 2 2") cell.col_span = 2 - row2.cells.add("测试 2 4") + row2.cells.add("Test 2 4") - # 向表格添加第三行 + # Add 3rd row to table row3 = table.rows.add() - row3.cells.add("测试 3 1") - row3.cells.add("测试 3 2") - row3.cells.add("测试 3 3") - row3.cells.add("测试 3 4") + row3.cells.add("Test 3 1") + row3.cells.add("Test 3 2") + row3.cells.add("Test 3 3") + row3.cells.add("Test 3 4") - # 向表格添加第四行 + # Add 4th row to table row4 = table.rows.add() - row4.cells.add("测试 4 1") - cell = row4.cells.add("测试 4 2") + row4.cells.add("Test 4 1") + cell = row4.cells.add("Test 4 2") cell.row_span = 2 - row4.cells.add("测试 4 3") - row4.cells.add("测试 4 4") + row4.cells.add("Test 4 3") + row4.cells.add("Test 4 4") - # 向表格添加第五行 + # Add 5th row to table row5 = table.rows.add() - row5.cells.add("测试 5 1") - row5.cells.add("测试 5 3") - row5.cells.add("测试 5 4") - - # 将表格对象添加到输入文档的第一页 - pdf_document.pages[1].paragraphs.add(table) - # 保存更新后的包含表格对象的文档 - pdf_document.save(output_file) -``` - + row5.cells.add("Test 5 1") + row5.cells.add("Test 5 3") + row5.cells.add("Test 5 4") -执行代码的结果如下图所示的表格: + # Add table object to first page of input document + page.paragraphs.add(table) + # Save updated document containing table object + document.save(outfile) +``` ![ColSpan 和 RowSpan 演示](colspan_rowspan.png) -## 处理边框、边距和填充 +### 为表格和单元格应用边框 -请注意,它还支持为表格设置边框样式、边距和单元格填充的功能。在深入技术细节之前,理解下面示意图中展示的边框、边距和填充的概念非常重要: +此示例演示如何设置单元格内边距、表格边距,并控制表格单元格中文本的自动换行。 -![边框、边距和填充](set-border-style-margins-and-padding-of-table_1.png) - -在上图中,您可以看到表格、行和单元格的边框重叠。使用 Aspose.PDF,表格可以有边距,单元格可以有填充。要设置单元格边距,我们必须设置单元格填充。 - -### 边框 - -要设置 [Table](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/)、[Row](https://reference.aspose.com/pdf/python-net/aspose.pdf/row/) 和 [Cell](https://reference.aspose.com/pdf/python-net/aspose.pdf/cell/) 对象的边框,请使用 Table.border、Row.border 和 Cell.border 属性。 - 单元格边框也可以使用 [Table](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/) 或 Row 类的 [default_cell_border](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/#properties) 属性来设置。上面讨论的所有与边框相关的属性都被分配给 Row 类的一个实例,该实例是通过调用其构造函数创建的。Row 类有许多重载,可以接受几乎所有定制边框所需的参数。 - -### 边距或填充 - -可以使用 Table 类的 [default_cell_padding](https://reference.aspose.com/pdf/python-net/aspose.pdf/row/#properties) 属性来管理单元格填充。所有与填充相关的属性都被分配给 [MarginInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/margininfo/) 类的一个实例,该类接受关于 `left`、`right`、`top` 和 `bottom` 参数的信息来创建自定义边距。 -在以下示例中,单元格边框的宽度设置为0.1点,表格边框的宽度设置为1点,单元格内边距设置为5点。 - -![PDF表格中的边距和边框](margin-border.png) +1. 设置列的宽度。 +1. 定义表格和单元格边框。 +1. 设置单元格内部填充以实现一致的间距。 +1. 默认情况下将填充应用于所有单元格。 +1. 添加文本并控制换行。 +1. 添加行和单元格。 +1. 保存 PDF。 ```python - - import aspose.pdf as ap - - # 通过调用其空构造函数实例化Document对象 - doc = ap.Document() - page = doc.pages.add() - # 实例化一个表对象 +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() - # 在所需部分的段落集合中添加表格 + # Add the table in paragraphs collection of the desired section page.paragraphs.add(tab1) - # 设置表格的列宽 + # Set with column widths of the table tab1.column_widths = "50 50 50" - # 使用BorderInfo对象设置默认单元格边框 + # Set default cell border using BorderInfo object tab1.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, 0.1) - # 使用另一个自定义的BorderInfo对象设置表格边框 + # Set table border using another customized BorderInfo object tab1.border = ap.BorderInfo(ap.BorderSide.ALL, 1) - # 创建MarginInfo对象并设置其左、下、右和上边距 + # 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 - # 将默认单元格内边距设置为MarginInfo对象 + # Set the default cell padding to the MarginInfo object tab1.default_cell_padding = margin - # 创建表格中的行,然后在行中创建单元格 + # 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 with large text string") - # Row1.Cells.Add("col3 with large text string to be placed inside cell") - 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") - # 保存Pdf - doc.save(output_file) + # Save updated document containing table object + document.save(outfile) ``` +![PDF 表格中的边距和边框](margin-border.png) -要创建圆角表格,请使用 [BorderInfo 类](https://reference.aspose.com/pdf/python-net/aspose.pdf/borderinfo/) [rounded_border_radius](https://reference.aspose.com/pdf/python-net/aspose.pdf/borderinfo/#properties) 值,并将表格角样式设置为圆形。 - -```python +## 表格布局和尺寸 - import aspose.pdf as ap - - tab1 = ap.Table() - graph = ap.GraphInfo() - graph.color = ap.Color.red - # 创建一个空白的 BorderInfo 对象 - b_info = ap.BorderInfo(ap.BorderSide.ALL, graph) - # 设置圆角边框,圆角半径为 15 - b_info.rounded_border_radius = 15 - # 将表格角样式设置为圆形 - tab1.corner_style = ap.BorderCornerStyle.ROUND - # 设置表格边框信息 - tab1.border = b_info -``` +### 自动调整列和行 -## 应用不同的自动调整设置到表格 +此代码片段展示了如何自动调整表格列宽以适应页面。 +请注意,在参数 table.column_widths = "50 50 50" 中,它的单位是点。但您也可以指定厘米(cm)、英寸或 %。 -在使用像 Microsoft Word 这样的可视化工具设计表格时,您通常会使用自动调整功能之一来方便地将表格调整到所需的宽度。 - 例如,您可以使用 "AUTO_FIT_TO_WINDOW" 选项将表格的宽度与页面匹配,或使用 AUTO_FIT_TO_CONTENT。默认情况下,使用 Aspose.Pdf 创建新表格时,它使用 [column_adjustment](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/#properties) 的 "Customized" 值。在以下代码片段中,我们在表格中设置对象参数 [MarginInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/margininfo/) 和 [BorderInfo](https://reference.aspose.com/pdf/python-net/aspose.pdf/borderinfo/) 对象。测试示例并评估结果。 +1. 设置初始列宽。 +1. 自动调整列以适应页面宽度。 +1. 定义单元格和表格边框。 +1. 'table.default_cell_padding' 使用 'MarginInfo()' 来在单元格内部实现一致的间距。 +1. 使用 'table.rows.add()' 添加行,使用 'row.cells.add()' 添加单元格。 +1. 保存 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) - # 通过调用空构造函数实例化 Pdf 对象 - doc = ap.Document() - # 在 Pdf 对象中创建章节 - sec1 = doc.pages.add() - # 实例化一个表格对象 - tab1 = ap.Table() - # 在所需章节的段落集合中添加表格 - sec1.paragraphs.add(tab1) - # 设置表格的列宽 - tab1.column_widths = "50 50 50" - tab1.column_adjustment = ap.ColumnAdjustment.AUTO_FIT_TO_WINDOW - # 使用 BorderInfo 对象设置默认单元格边框 - tab1.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, 0.1) - # 使用另一个自定义 BorderInfo 对象设置表格边框 - tab1.border = ap.BorderInfo(ap.BorderSide.ALL, 1) - # 创建 MarginInfo 对象并设置其左、下、右和上边距 margin = ap.MarginInfo() margin.top = 5 margin.left = 5 margin.right = 5 margin.bottom = 5 - # 将默认单元格填充设置为 MarginInfo 对象 - tab1.default_cell_padding = margin - # 在表格中创建行,然后在行中创建单元格 - 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") - # 保存更新后的包含表格对象的文档 - doc.save(output_file) + + document.save(outfile) ``` -### 获取表格宽度 +### 创建具有合并单元格和重复列的复杂 PDF 表格 -有时需要动态获取表格宽度。Aspose.PDF.Table 类有一个方法 [get_width()](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/#methods) 用于此目的。例如,您没有明确设置表格列宽并将 [column_adjustment](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/#properties) 设置为 'AUTO_FIT_TO_CONTENT'。在这种情况下,您可以按如下方式获取表格宽度。 +使用 Python 和 Aspose.PDF 在 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_table_hide_borders(outfile: str) -> None: + # Create PDF document + document = ap.Document() + page = document.pages.add() - # 创建一个新文档 - doc = ap.Document() - # 在文档中添加页面 - page = doc.pages.add() - # 初始化新表格 + # 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 - # 在表格中添加行 + 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() - # 在表格中添加单元格 - cell = row.cells.add("单元格 1 文本") - cell = row.cells.add("单元格 2 文本") - # 获取表格宽度 - 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) ``` -## 向表格单元格添加 SVG 图像 +![边框、外边距和内边距](set-border-style-margins-and-padding-of-table_1.png) -Aspose.PDF for Python via .NET 提供了将表格单元格插入 PDF 文件的功能。 - 在构建表格时,您可以在这些单元格中包含文本和图像。此外,API 提供了将 SVG 文件转换为 PDF 格式的功能。通过将这些功能结合使用,您可以加载 SVG 图像并将其放置在表格单元格内。 +### 表格角落样式 -以下代码摘录演示了创建表对象并在其一个单元格内嵌入 SVG 图像的过程。 +Aspose.PDF for Python via .NET 展示了如何为表格应用圆角并自定义边框半径。 + +1. 创建一个新的表实例。 +1. 为所有侧面初始化边框。 +1. 设置圆角半径。 +1. 应用圆角样式。 +1. 添加行和单元格。 +1. 使用 'page.paragraphs.add(table)' 将表格插入 PDF 页面。 +1. 保存 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() - # 实例化 Document 对象 - doc = ap.Document() - # 创建图像实例 - img = ap.Image() - # 将图像类型设置为 SVG - img.file_type = ap.ImageFileType.SVG - # 源文件路径 - img.file = DIR_INPUT_TABLE + "SVGToPDF.svg" - # 设置图像实例的宽度 - img.fix_width = 50 - # 设置图像实例的高度 - img.fix_height = 50 - # 创建表实例 + # Create a table table = ap.Table() - # 设置表格单元格的宽度 - table.column_widths = "100 100" - # 创建行对象并将其添加到表实例中 - row = table.rows.add() - # 创建单元格对象并将其添加到行实例中 - cell = row.cells.add() - # 向单元格对象的段落集合中添加文本片段 - cell.paragraphs.add(ap.text.TextFragment("First cell")) - # 向行对象中添加另一个单元格 - cell = row.cells.add() - # 向最近添加的单元格实例的段落集合中添加 SVG 图像 - cell.paragraphs.add(img) - # 创建页面对象并将其添加到文档实例的页面集合中 - page = doc.pages.add() - # 将表格添加到页面对象的段落集合中 + + # 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) - # 保存 PDF 文件 - doc.save(output_file) + # Save updated document containing table object + document.save(outfile) ``` -## 在表格行之间插入分页符 +## 向表格添加内容 -默认情况下,当您在 PDF 文件中创建表格时,如果表格超出其底部边距,表格将跨多个页面显示。然而,有时我们需要在表格中添加特定数量的行后强制进行分页。以下代码片段描述了在表格中包含 10 行时插入分页符的过程。 +### 在单元格中使用 HtmlFragment + +此示例展示了如何将 HTML 格式的内容插入表格单元格。 + +1. 定义表格和单元格边框。 +1. 添加 HTML 内容。 +1. 添加行。循环在每个单元格中添加包含 HTML 格式内容的多行。 +1. 使用 'page.paragraphs.add(table)' 将表格插入 PDF 页面。 +1. 保存 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) +``` + +### 在单元格中使用 LaTeX 片段 + +本示例演示如何将 LaTeX 格式的内容插入表格单元格,以用于数学或样式化的表达式。 + +1. 定义表格和单元格边框。 +1. 添加 LaTeX 内容。 +1. 添加行。循环在每个单元格中添加多行包含 LaTeX 格式内容的行。 +1. 使用 'page.paragraphs.add(table)' 将表格插入 PDF 页面。 +1. 保存 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) +``` + +## 高级表格功能 + +### 在 PDF 表格中插入自动换页 + +使用 Python 和 Aspose.PDF 在 PDF 中创建大表格,并在达到特定行数后自动分页。它构建多行表格,应用边框,并强制选定的行在新页面开始,以获得更好的布局控制。 ```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 - - # 实例化 Document 对象 - doc = ap.Document() - # 向 PDF 文件的页面集合中添加页面 - doc.pages.add() - # 创建表格实例 - tab = ap.Table() - # 设置表格的边框样式 - tab.border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.red) - # 设置表格的默认边框样式,边框颜色为红色 - tab.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, ap.Color.red) - # 指定表格列宽 - tab.column_widths = "100 100" - # 创建循环以添加 200 行到表格 - 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) - # 当添加 10 行时,将新行渲染到新页面中 + + # When 10 rows are added, render new row in new page if counter % 10 == 0 and counter != 0: row.is_in_new_page = True - # 将表格添加到 PDF 文件的段落集合中 - doc.pages[1].paragraphs.add(tab) - # 保存 PDF 文档 - doc.save(output_file) -``` + # Add table to paragraphs collection of PDF file + page.paragraphs.add(table) -## 在新页面上渲染表格 + # Save PDF document + document.save(outfile) +``` -默认情况下,段落被添加到页面对象的段落集合中。然而,可以在新页面上渲染表格,而不是直接在页面上添加之前的段落级对象之后。 +### 在多个页面上重复标题行 -### 示例:如何使用 Python 在新页面上渲染表格 +此示例展示了如何创建跨多页的表格,同时在每页上保持标题行可见。 -要在新页面上渲染表格,请使用 [BaseParagraph](https://reference.aspose.com/pdf/python-net/aspose.pdf/baseparagraph/) 类中的 [is_in_new_page](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/#properties) 属性。以下代码片段展示了如何实现。 +1. 初始化表格。 +1. 重复标题行,包括字体、大小和颜色。 +1. 设置列宽并为表格应用边框。 +1. 添加标题行。 +1. 添加许多数据行以强制表格跨越多页。 +1. 使用 'page.paragraphs.add(table)' 将表格插入 PDF 页面。 +1. 保存 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) +``` + +### 重复列 + +函数 'add_repeating_columns' 创建一个带有重复列的表格的 PDF 文档。它设置了带边框的表格,添加标题,填充数据行,并将生成的 PDF 文件保存到指定位置。设置此属性将导致表格按列方式在下一页断开,并在下一页的起始处重复给定的列数。 + +1. 初始化一个新的 PDF 文档。 +1. 添加一个具有自定义尺寸的页面。 +1. 设置表格边框样式。 +1. 初始化表格。 +1. 在 PDF 页面上添加表格。 +1. 添加标题行。 +1. 添加数据行。 +1. 保存 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" - # 添加页面。 - 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("内容 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 - # 我想把表格 1 保持在下一页... - 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) +``` + +### 创建一个带有旋转文本单元格的 PDF 表格 + +使用 Python 和 Aspose.PDF 在 PDF 中创建表格,并在每个单元格内将文本旋转不同角度。这对于垂直标题、创意布局、紧凑表格以及自定义报告格式非常有用。 + +```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) ``` +## 相关表格主题 - \ No newline at end of file +- [使用 Python 在 PDF 中处理表格](/pdf/zh/python-net/working-with-tables/) +- [从 PDF 文档中提取表格](/pdf/zh/python-net/extracting-table/) +- [将 PDF 表格与数据源集成](/pdf/zh/python-net/integrate-table/) +- [在现有 PDF 中操作表格](/pdf/zh/python-net/manipulating-tables/) diff --git a/zh/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/colspan_rowspan.png b/zh/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/colspan_rowspan.png new file mode 100644 index 0000000000..d8bc203285 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/colspan_rowspan.png differ diff --git a/zh/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/margin-border.png b/zh/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/margin-border.png new file mode 100644 index 0000000000..70b66bc129 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/margin-border.png differ diff --git a/zh/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/set-border-style-margins-and-padding-of-table_1.png b/zh/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/set-border-style-margins-and-padding-of-table_1.png new file mode 100644 index 0000000000..08b2a1af1c Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-tables/add-table-in-existing-pdf-document/set-border-style-margins-and-padding-of-table_1.png differ diff --git a/zh/python-net/advanced-operations/working-with-tables/extract-table-from-existing-pdf-document/_index.md b/zh/python-net/advanced-operations/working-with-tables/extract-table-from-existing-pdf-document/_index.md index cd8c37f6b6..388b073e1f 100644 --- a/zh/python-net/advanced-operations/working-with-tables/extract-table-from-existing-pdf-document/_index.md +++ b/zh/python-net/advanced-operations/working-with-tables/extract-table-from-existing-pdf-document/_index.md @@ -1,167 +1,64 @@ --- -title: 从 PDF 文档中提取表格 +title: 在 Python 中从 PDF 提取表格 linktitle: 提取表格 type: docs weight: 20 -url: /zh/python-net/extract-table-from-existing-pdf-document/ -description: Aspose.PDF for Python via .NET 可以对您的 PDF 文档中包含的表格进行各种操作。 -lastmod: "2023-02-17" +url: /zh/python-net/extracting-table/ +description: 了解如何在 Python 中从现有的 PDF 文档中提取表格数据。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 从 PDF 文件中提取表格数据 +Abstract: 本文介绍如何使用 Aspose.PDF for Python via .NET 从 PDF 文档中提取表格。它展示了如何使用 `TableAbsorber` 按页检测表格,遍历行和单元格,并检索单元格文本以进行分析和下游数据处理。 --- - - ## 从 PDF 中提取表格 -使用 Python 从 PDF 中提取表格对于数据提取和分析非常有用。通过 Aspose.PDF for Python via .NET Library,您可以高效地处理嵌入在 PDF 文档中的表格,以完成各种与数据相关的任务。 +从 PDF 中提取表格对于报告、数据迁移和分析工作流非常有用。使用 Aspose.PDF for Python via .NET,您可以高效地检测并读取现有 PDF 文档中的表格内容。 -```python +此代码片段打开一个现有的 PDF 文件,扫描每一页的表格,并提取单元格文本内容。它使用 `TableAbsorber` 检测表格,然后遍历行和单元格以打印提取的文本。 - import aspose.pdf as ap +1. 将 PDF 加载到 ap.Document 对象中。 +1. 遍历页面。 +1. 创建一个 TableAbsorber 对象。 +1. 遍历表格。 +1. 遍历行和单元格。 +1. 提取并打印单元格中的文本。 - # 加载源 PDF 文档 - pdf_document = ap.Document(input_file) - for page in pdf_document.pages: +此示例读取 PDF,查找所有表格,并逐行打印单元格内容。 + +```python +import aspose.pdf as ap +from os import path +import sys + +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 +## 相关表格主题 + +- [使用 Python 在 PDF 中处理表格](/pdf/zh/python-net/working-with-tables/) +- [使用 Python 向 PDF 添加表格](/pdf/zh/python-net/adding-tables/) +- [将 PDF 表格与数据源集成](/pdf/zh/python-net/integrate-table/) +- [从现有 PDF 中删除表格](/pdf/zh/python-net/removing-tables/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-tables/integrate-table-in-existing-pdf-document/_index.md b/zh/python-net/advanced-operations/working-with-tables/integrate-table-in-existing-pdf-document/_index.md new file mode 100644 index 0000000000..0bcbd96556 --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-tables/integrate-table-in-existing-pdf-document/_index.md @@ -0,0 +1,103 @@ +--- +title: 在 Python 中将 PDF 表格与数据源集成 +linktitle: 集成表格 +type: docs +weight: 30 +url: /zh/python-net/integrate-table/ +description: 了解如何在 Python 中将 PDF 表格与数据库和 pandas DataFrame 等数据源集成。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 将 PDF 表格与数据库和 DataFrame 集成 +Abstract: 本文阐述了如何使用 Aspose.PDF for Python via .NET 将 PDF 表格与外部数据源集成。了解如何从 pandas DataFrame 和其他结构化来源构建 PDF 表格,将其插入文档,并在 Python 中跨 PDF 页面渲染时控制表格流动。 +--- + +## 从 DataFrame 创建 PDF + +这 `create_pdf_from_dataframe` 函数构建一个新的 PDF 并插入一个由 pandas DataFrame 生成的表格。这种方法对于数据已经以表格形式存在的报告工作流非常有用。 + +该函数执行以下步骤: + +1. 使用创建一个空的 PDF 文档 `ap.Document()`. +1. 向文档添加一个页面。 +1. 通过调用将 DataFrame 转换为 Aspose.PDF 表格 `create_table_from_dataframe(df, max_rows)`. +1. 使用将表格添加到页面 `page.paragraphs.add(table)`. +1. 将 PDF 保存到输出路径。 + +```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) +``` + +## 从 DataFrame 创建表 + +这 `create_table_from_dataframe` 函数将 DataFrame 转换为 Aspose.PDF `Table` 可以添加到任何页面的对象。 + +它执行以下操作: + +1. 创建一个空的 `ap.Table()` 实例。 +1. 设置表格和单元格边框,以实现一致的格式。 +1. 使用 DataFrame 列名添加标题行。 +1. 从...添加数据行 `df.head(max_rows)`. +1. 返回填充好的表格对象。 + +```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 +``` + +## 相关表格主题 + +- [使用 Python 在 PDF 中处理表格](/pdf/zh/python-net/working-with-tables/) +- [使用 Python 向 PDF 添加表格](/pdf/zh/python-net/adding-tables/) +- [从 PDF 文档中提取表格](/pdf/zh/python-net/extracting-table/) +- [在现有 PDF 中操作表格](/pdf/zh/python-net/manipulating-tables/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-tables/manipulate-tables-in-existing-pdf/_index.md b/zh/python-net/advanced-operations/working-with-tables/manipulate-tables-in-existing-pdf/_index.md index 95f9b32eaf..5a9ef8007a 100644 --- a/zh/python-net/advanced-operations/working-with-tables/manipulate-tables-in-existing-pdf/_index.md +++ b/zh/python-net/advanced-operations/working-with-tables/manipulate-tables-in-existing-pdf/_index.md @@ -1,322 +1,114 @@ --- -title: 操作现有PDF中的表格 +title: 操作现有 PDF 文档中的表格 linktitle: 操作表格 type: docs weight: 40 -url: /zh/python-net/manipulate-tables-in-existing-pdf/ -lastmod: "2023-02-17" +url: /zh/python-net/manipulating-tables/ +description: 学习如何使用 Python 检查和修改现有 PDF 文档中的表格。 +lastmod: "2026-06-08" sitemap: changefreq: "weekly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 检查并修改现有 PDF 表格 +Abstract: 本文解释了如何使用 Aspose.PDF for Python via .NET 操作 PDF 文档中已存在的表格。了解如何使用 TableAbsorber 定位表格、访问特定的行和单元格、更新表格文本内容,并在 Python 中保存修改后的 PDF。 --- - - ## 操作现有 PDF 中的表格 -Aspose.PDF for Python via .NET 支持的最早功能之一是其处理表格的能力,并且它为从头生成或已有的 PDF 文件中添加表格提供了极大的支持。在这个新版本中,我们实现了搜索和解析已经存在于 PDF 文档页面上的简单表格的新功能。一个名为 [TableAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/) 的新类提供了这些能力。TableAbsorber 的用法与现有的 [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber/) 类非常相似。以下代码片段展示了更新特定表格单元格内容的步骤。 - -```python +Aspose.PDF for Python via .NET 让您能够更新 PDF 文档中已存在的表格。您可以使用 [TableAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/) 类来查找页面上的表格,访问行和单元格,修改文本内容,并保存更新后的文件。 - import aspose.pdf as ap - - # 加载现有 PDF 文件 - pdf_document = ap.Document(input_file) - # 创建 TableAbsorber 对象以查找表格 - absorber = ap.text.TableAbsorber() - # 使用吸收器访问第一页 - absorber.visit(pdf_document.pages[1]) - # 获取页面上第一个表格的访问权限,第一个单元格及其中的文本片段 - fragment = absorber.table_list[0].row_list[0].cell_list[0].text_fragments[1] - # 更改单元格中第一个文本片段的文本 - fragment.text = "hi world" - pdf_document.save(output_file) -``` +当您需要在不重新创建整个文档布局的情况下更新 PDF 中已有的表格内容时,请使用此页面。 +## 在 PDF 表格单元格中查找并替换文本 -## 在 PDF 文档中用新表替换旧表 +此示例在第 1 页找到第一个表格,访问第一个单元格,替换其文本,并保存输出的 PDF。 -如果您需要查找特定表并用所需表替换它,可以使用 [TableAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/) 类的 [replace()](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/#methods) 方法来实现。以下示例演示了在 PDF 文档中替换表的功能: +1. 打开输入的 PDF。 +1. 创建一个 TableAbsorber 并访问第 1 页。 +1. 确保检测到至少一个表格。 +1. 访问第一个表格的第一行中的第一个单元格。 +1. 确保单元格包含文本片段,然后更新第一个片段。 +1. 保存修改后的 PDF。 ```python +import aspose.pdf as ap - import aspose.pdf as ap +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) - # 加载现有的 PDF 文档 - pdf_document = ap.Document(input_file) - # 创建 TableAbsorber 对象以查找表 + # Create TableAbsorber object to find tables absorber = ap.text.TableAbsorber() - # 使用吸收器访问第一页 - absorber.visit(pdf_document.pages[1]) - # 获取页面上的第一个表 - table = absorber.table_list[0] - # 创建新表 - new_table = ap.Table() - new_table.column_widths = "100 100 100" - new_table.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, 1) - row = new_table.rows.add() - row.cells.add("列 1") - row.cells.add("列 2") - row.cells.add("列 3") + # Visit first page with absorber + absorber.visit(document.pages[1]) + + if len(absorber.table_list) == 0: + raise ValueError("No tables were found on page 1.") - # 用新表替换表 - absorber.replace(pdf_document.pages[1], table, new_table) - # 保存文档 - pdf_document.save(output_file) + 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.") + + # Change text of the first text fragment in the cell + first_cell.text_fragments[0].text = "New Value" + + # Save PDF document + document.save(outfile) ``` +## 用新表替换现有表 -## 如何确定表格是否会在当前页面中断 +您还可以用新创建的表替换检测到的表。当结构和内容都必须更改时,这种方法非常有用。 -此代码生成一个包含表格的PDF文档,计算页面上的可用空间,并检查向表格添加更多行是否会因空间限制而导致分页符。结果将保存到输出文件中。 +以下代码打开一个 PDF,查找第 1 页的第一张表格,创建一个替换表格,用新表格替换旧表格,并保存结果。 ```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) - # 实例化一个PDF类对象 - pdf = ap.Document() - # 添加一个部分到PDF文档的部分集合中 - page = pdf.pages.add() - # 实例化一个表格对象 - table1 = ap.Table() - table1.margin.top = 300 - # 在所需部分的段落集合中添加表格 - page.paragraphs.add(table1) - # 设置表格的列宽 - table1.column_widths = "100 100 100" - # 使用BorderInfo对象设置默认单元格边框 - table1.default_cell_border = ap.BorderInfo(ap.BorderSide.ALL, 0.1) - # 使用另一个自定义的BorderInfo对象设置表格边框 - table1.border = ap.BorderInfo(ap.BorderSide.ALL, 1) - # 创建MarginInfo对象并设置其左、下、右和上边距 - margin = ap.MarginInfo() - margin.top = 5 - margin.left = 5 - margin.right = 5 - margin.bottom = 5 - # 将默认单元格内边距设置为MarginInfo对象 - table1.default_cell_padding = margin - # 如果将计数器增加到17,表格将会中断 - # 因为它不能再容纳于这个页面上 - for row_counter in range(0, 17): - # 在表格中创建行,然后在行中创建单元格 - 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") - # 获取页面高度信息 - page_height = pdf.page_info.height - # 获取页面顶部和底部边距、表格顶部边距和表格高度的总高度信息 - total_objects_height = page.page_info.margin.top + page.page_info.margin.bottom + table1.margin.top + \ - table1.get_height(None) - # 显示页面高度、表格高度、表格顶部边距以及页面顶部和底部边距信息 - print("PDF文档高度 = " + str(pdf.page_info.height) + "\n顶部边距信息 = " + str(page.page_info.margin.top) - + "\n底部边距信息 = " + str(page.page_info.margin.bottom) + "\n\n表格顶部边距信息 = " - + str(table1.margin.top) + "\n平均行高 = " + str(table1.rows[0].min_row_height) + " \n表格高度 " - + str(table1.get_height(None)) + "\n ----------------------------------------" + "\n总页面高度 =" - + str(page_height) + "\n包括表格的累计高度 =" + str(total_objects_height)) - # 检查我们是否从页面高度中扣除页面顶部边距+页面底部边距 - # + 表格顶部边距和表格高度,且小于10(平均行高可以大于10) - if (page_height - total_objects_height) <= 10: - # 如果值小于10,则显示消息。 - # 这表明不能再放置另一行,如果我们添加新行,表格将会中断。 - # 这取决于行高值。 - print("页面高度 - 对象高度 < 10,因此表格将会中断") - # 保存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]) -## 在表中添加重复列 + if len(absorber.table_list) == 0: + raise ValueError("No tables were found on page 1.") -在 [Aspose.Pdf.Table](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/) 类中,你可以设置 [repeating_rows_count](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/#properties),如果表格在垂直方向上太长而溢出到下一页,它将重复行。然而,在某些情况下,表格太宽而无法适应单个页面,需要在下一页继续。为了实现这个目的,我们在 [Aspose.Pdf.Table](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/) 类中实现了 [repeating_columns_count](https://reference.aspose.com/pdf/python-net/aspose.pdf/table/#properties) 属性。设置此属性将导致表格按列方式分隔至下一页,并在下一页的开头重复给定的列数。以下代码片段展示了 [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) - # 创建一个新文档 - doc = ap.Document() - page = doc.pages.add() - # 实例化一个占据整个页面的外部表 - outer_table = ap.Table() - outer_table.column_widths = "100%" - outer_table.horizontal_alignment = ap.HorizontalAlignment.LEFT - # 实例化一个将嵌套在 outerTable 内的表对象,该对象将在同一页面内拆分 - my_table = ap.Table() - my_table.broken = ap.TableBroken.VERTICAL_IN_SAME_PAGE - my_table.column_adjustment = ap.ColumnAdjustment.AUTO_FIT_TO_CONTENT - # 将 outerTable 添加到页面段落 - # 将我的表格添加到 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) - # 添加标题行 - row = my_table.rows.add() - row.cells.add("header 1") - row.cells.add("header 2") - row.cells.add("header 3") - row.cells.add("header 4") - row.cells.add("header 5") - row.cells.add("header 6") - row.cells.add("header 7") - row.cells.add("header 11") - 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") - for row_counter in range(0, 6): - # 在表中创建行,然后在行中创建单元格 - 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) ``` +## 相关表格主题 - \ No newline at end of file +- [使用 Python 在 PDF 中处理表格](/pdf/zh/python-net/working-with-tables/) +- [使用 Python 向 PDF 添加表格](/pdf/zh/python-net/adding-tables/) +- [从 PDF 文档中提取表格](/pdf/zh/python-net/extracting-table/) +- [从现有 PDF 中删除表格](/pdf/zh/python-net/removing-tables/) diff --git a/zh/python-net/advanced-operations/working-with-tables/remove-tables-from-existing-pdf/_index.md b/zh/python-net/advanced-operations/working-with-tables/remove-tables-from-existing-pdf/_index.md index aa8bad3832..dc46f7efa5 100644 --- a/zh/python-net/advanced-operations/working-with-tables/remove-tables-from-existing-pdf/_index.md +++ b/zh/python-net/advanced-operations/working-with-tables/remove-tables-from-existing-pdf/_index.md @@ -1,195 +1,75 @@ --- -title: 从现有 PDF 中移除表格 -linktitle: 移除表格 +title: 从现有 PDF 文档中删除表格 +linktitle: 删除表格 +description: 了解如何在 Python 中从现有 PDF 文档中删除一个或多个表格。 +lastmod: "2026-06-08" type: docs weight: 50 -url: /zh/python-net/remove-tables-from-existing-pdf/ -lastmod: "2023-02-17" +url: /zh/python-net/removing-tables/ sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 删除 PDF 文件中的一个或多个表格 +Abstract: 本文说明了如何使用 Aspose.PDF for Python via .NET 从现有 PDF 文档中删除表格。它介绍了 `TableAbsorber` 用于定位表格,并演示了如何删除单个表格或从页面中删除所有检测到的表格。 --- - +## 从 PDF 文档中删除表格 -{{% alert color="primary" %}} +Aspose.PDF for Python 允许您从 PDF 中移除表格。它打开现有的 PDF,检测首页上的第一个表格,用 `TableAbsorber`,使用删除该表 `remove()`,并将更新后的 PDF 保存到一个新文件。 -Aspose.PDF for Python via .NET 提供在生成 PDF 文档时插入/创建表格的功能,您也可以在任何现有的 PDF 文档中添加表格对象。然而,您可能需要[操作现有 PDF 中的表格](https://docs.aspose.com/pdf/python-net/manipulate-tables-in-existing-pdf/),在这里您可以更新现有表格单元格中的内容。然而,您可能会遇到需要从现有 PDF 文档中移除表格对象的需求。 - -{{% /alert %}} - -为了移除表格,我们需要使用 [TableAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/) 类来获取现有 PDF 中的表格,然后调用 [remove()](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/#methods)。 - -## 从 PDF 文档中移除表格 - -我们添加了新功能,即。 - [remove()](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/#methods) 到现有的 [TableAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/) 类,以便从 PDF 文档中删除表格。一旦吸收器成功地在页面上找到表格,它就能够删除它们。请查看以下代码片段,了解如何从 PDF 文档中删除表格: +当您需要清理大量表格的 PDF、删除过时的表格内容,或在重新分发前简化文档时,请使用此页面。 ```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) - # 加载现有的 PDF 文档 - pdf_document = ap.Document(input_file) - # 创建 TableAbsorber 对象以查找表格 + # Create TableAbsorber object to find tables absorber = ap.text.TableAbsorber() - # 用吸收器访问第一页 - absorber.visit(pdf_document.pages[1]) - # 获取页面上的第一个表格 + # Visit first page with absorber + absorber.visit(document.pages[1]) + # Get first table on the page table = absorber.table_list[0] - # 删除表格 + # Remove the table absorber.remove(table) - # 保存 PDF - pdf_document.save(output_file) + # Save PDF + document.save(outfile) ``` -## 从 PDF 文档中删除多个表格 +## 从 PDF 文档中移除所有表格 -有时,PDF 文档可能包含多个表格,您可能需要从中删除多个表格。 为了从PDF文档中删除多个表格,请使用以下代码片段: +使用我们的库,您可以从 PDF 的特定页面中移除所有表格。代码打开现有的 PDF,使用 TableAbsorber 检测第二页上的所有表格,遍历检测到的表格,逐一移除,然后将修改后的 PDF 保存为新文件。当您需要批量移除页面上的表格而保留 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) - # 加载现有的PDF文档 - pdf_document = ap.Document(input_file) - # 创建TableAbsorber对象以查找表格 + # Create TableAbsorber object to find tables absorber = ap.text.TableAbsorber() - # 使用吸收器访问第二页 - absorber.visit(pdf_document.pages[1]) - # 获取表格集合的副本 - tables = absorber.table_list - # 遍历集合的副本并删除表格 + # 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) - # 保存文档 - pdf_document.save(output_file) + + # Save document + document.save(outfile) ``` - \ No newline at end of file +## 相关表格主题 + +- [使用 Python 在 PDF 中处理表格](/pdf/zh/python-net/working-with-tables/) +- [使用 Python 向 PDF 添加表格](/pdf/zh/python-net/adding-tables/) +- [从 PDF 文档中提取表格](/pdf/zh/python-net/extracting-table/) +- [在现有 PDF 中操作表格](/pdf/zh/python-net/manipulating-tables/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-text/_index.md b/zh/python-net/advanced-operations/working-with-text/_index.md index 6db201e906..6d6df4273f 100644 --- a/zh/python-net/advanced-operations/working-with-text/_index.md +++ b/zh/python-net/advanced-operations/working-with-text/_index.md @@ -1,91 +1,31 @@ --- -title: 在 PDF 中使用 Python 处理文本 +title: 使用 Python 处理 PDF 文本 linktitle: 处理文本 type: docs weight: 30 url: /zh/python-net/working-with-text/ -description: 本节解释了各种文本处理技术。了解如何使用 Aspose.PDF for Python 添加、替换、旋转、搜索文本。 -lastmod: "2024-01-17" +description: 了解如何在 PDF 文档中使用 Python 添加、搜索、格式化、替换、旋转和检查文本。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中添加、格式化、搜索、替换和旋转 PDF 文本 +Abstract: 本节阐述如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中处理文本。了解如何添加和格式化文本、创建工具提示和悬浮文本布局、搜索并提取文本、替换已有文本以及在 Python 工作流中旋转文本元素。 --- - + 我们有时需要向 PDF 文件添加文本。例如,您可能想在主文本下方放置译文、在图像旁添加标题,或填写申请表。当所有文本元素都能以您偏好的样式进行格式化时,也会很有帮助。常见的文本操作包括在文档中添加文本、格式化文本、替换文本和旋转文本。**Aspose.PDF for Python via .NET** 提供了处理 PDF 文本内容所需的一切。 -我们有时需要在 PDF 文件中添加文本。例如,当您想在主文本下添加翻译,在图像旁边放置标题,或只是填写申请表。 如果所有文本元素都能以您自己想要的样式进行格式化,这也会很有帮助。 在您的 PDF 文件中最常见的文本操作是:向 PDF 添加文本,格式化 PDF 文件中的文本,替换和旋转文档中的文本。**Aspose.PDF for Python via .NET** 是最佳解决方案,具备与 PDF 内容交互所需的一切。 +当您需要在 Python 应用程序中直接在 PDF 页面内生成、格式化、检查或修改文本时,请使用本节。 -您可以执行以下操作: +## 涉及的文本任务 -- [向 PDF 文件添加文本](/pdf/zh/python-net/add-text-to-pdf-file/) - 将文本添加到您的 PDF 中,使用流和文件中的字体,添加 HTML 字符串,添加超链接等。 -- [PDF 工具提示](/pdf/zh/python-net/pdf-tooltip/) - 您可以通过使用 Python 添加不可见按钮来为搜索文本添加工具提示。 -- [PDF 内部的文本格式](/pdf/zh/python-net/text-formatting-inside-pdf/) - 在格式化文本时,您可以为文档添加许多功能。 - 增加行缩进,添加文本边框,添加下划线文本,使用 Aspose.PDF 库添加换行符。 -- [替换 PDF 中的文本](/pdf/zh/python-net/replace-text-in-pdf/) - 替换 PDF 文档所有页面中的文本。您首先需要使用 TextFragmentAbsorber。 -- [旋转 PDF 内部文本](/pdf/zh/python-net/rotate-text-inside-pdf/) - 使用 TextFragment 类的旋转属性旋转 PDF 内的文本。 -- [搜索并从 PDF 文档的页面中获取文本](/pdf/zh/python-net/search-and-get-text-from-pdf/) - 您可以使用 TextFragmentAbsorber 类来搜索和获取页面中的文本。 -- [确定换行](/pdf/zh/python-net/determine-line-break/) - 本主题解释如何跟踪多行文本片段的换行。 \ No newline at end of file + 您可以执行以下操作: + +- [向 PDF 文件添加文本](/pdf/zh/python-net/add-text-to-pdf-file/) - 向 PDF 添加文本,使用来自流和文件的字体,添加 HTML 字符串,添加超链接等。 +- [PDF 工具提示](/pdf/zh/python-net/pdf-tooltip/) - 您可以通过使用 Python 添加不可见按钮,为搜索到的文本添加工具提示。 +- [使用 FloatingBox](/pdf/zh/python-net/floating-box/) - 将样式化文本和其他内容放置在浮动容器中。 +- [替换 PDF 中的文本](/pdf/zh/python-net/replace-text-in-pdf/) - 替换或删除 PDF 文件中的现有文本。 +- [旋转 PDF 内的文本](/pdf/zh/python-net/rotate-text-inside-pdf/) - 旋转 PDF 中的文字片段和段落。 +- [搜索并获取 PDF 文本](/pdf/zh/python-net/search-and-get-text-from-pdf/) - 搜索文本并检查页面上提取的文本详细信息。 +- [PDF 中的文本格式化](/pdf/zh/python-net/text-formatting-inside-pdf/) - 控制行间距、边框、缩进和文本样式。 diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-a-pdf-file/_index.md b/zh/python-net/advanced-operations/working-with-text/add-text-to-a-pdf-file/_index.md deleted file mode 100644 index c22509e13a..0000000000 --- a/zh/python-net/advanced-operations/working-with-text/add-text-to-a-pdf-file/_index.md +++ /dev/null @@ -1,843 +0,0 @@ ---- -title: 使用 Python 向 PDF 添加文本 -linktitle: 向 PDF 添加文本 -type: docs -weight: 10 -url: /zh/python-net/add-text-to-pdf-file/ -description: 本文描述了在 Aspose.PDF 中处理文本的各个方面。了解如何向 PDF 添加文本、添加 HTML 片段或使用自定义 OTF 字体。 -lastmod: "2024-02-17" -sitemap: - changefreq: "monthly" - priority: 0.7 ---- - - - -## 添加文本 - -1. 使用 Aspose.PDF 打开输入的 PDF 文档。 -1. 选择要添加文本的特定页面。 -1. 创建一个 TextFragment 对象。文本片段是用内容 'main text' 创建的。该片段定位在页面的坐标 (100, 600)。 -1. 设置文本属性。设置文本的各种属性,如字体大小、字体类型(Times New Roman)、背景颜色(浅灰色)和前景颜色(红色)。 -1. 创建 TextBuilder 对象。用所选页面实例化一个 TextBuilder 对象。 -1. 附加文本片段。使用 TextBuilder 对象将先前创建的文本片段附加到 PDF 页面。 -1. 调用 [document.save](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法并保存输出的 PDF 文件。 - -以下代码片段展示了如何在现有 PDF 文件中添加文本: - -```python - - import aspose.pdf as ap - - # 打开文档 - document = ap.Document(input_pdf) - - # 获取特定页面 - page = document.pages[1] - - # 创建文本片段 - text_fragment = ap.text.TextFragment("main text") - text_fragment.position = ap.text.Position(100, 600) - - # 设置文本属性 - 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 - - # 创建 TextBuilder 对象 - builder = ap.text.TextBuilder(page) - - # 将文本片段附加到 PDF 页面 - builder.append_text(text_fragment) - - # 保存生成的 PDF 文档。 - document.save(output_pdf) -``` - - -## 从流加载字体 - -以下代码片段显示了如何在向 PDF 文档添加文本时从流对象加载字体。 - -```python - - import aspose.pdf as ap - - # 加载输入 PDF 文件 - document = ap.Document() - document.pages.add() - # 为文档的第一页创建文本构建器对象 - text_builder = ap.text.TextBuilder(document.pages[1]) - # 创建带示例字符串的文本片段 - text_fragment = ap.text.TextFragment("Hello world") - - if input_ttf != "": - # 将 TrueType 字体加载到流对象中 - font_stream = open(input_ttf, "rb") - # 设置文本字符串的字体名称 - text_fragment.text_state.font = ap.text.FontRepository.open_font( - font_stream, ap.text.FontTypes.TTF - ) - # 指定文本片段的位置 - text_fragment.position = ap.text.Position(10, 10) - # 将文本添加到 TextBuilder,以便可以将其放置在 PDF 文件上 - text_builder.append_text(text_fragment) - # 保存生成的 PDF 文档。 - document.save(output_pdf) -``` - - -## 使用 TextParagraph 添加文本 - -以下代码片段演示了如何使用 [TextParagraph](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textparagraph/) 类在 PDF 文档中添加文本。 - -```python - - import aspose.pdf as ap - - # 打开文档 - document = ap.Document() - # 向文档对象的页面集合中添加页面 - page = document.pages.add() - builder = ap.text.TextBuilder(page) - # 创建文本段落 - paragraph = ap.text.TextParagraph() - # 设置后续行缩进 - paragraph.subsequent_lines_indent = 20 - # 指定添加 TextParagraph 的位置 - paragraph.rectangle = ap.Rectangle(100, 300, 200, 700, False) - # 指定自动换行模式 - paragraph.formatting_options.wrap_mode = ( - ap.text.TextFormattingOptions.WordWrapMode.BY_WORDS - ) - # 创建文本片段 - 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 - # 将片段添加到段落 - paragraph.append_line(fragment1) - # 添加段落 - builder.append_paragraph(paragraph) - - # 保存生成的 PDF 文档。 - document.save(output_pdf) -``` - - -## 向 TextSegment 添加超链接 - -此代码演示了如何在 PDF 文档中创建动态和交互式内容,包括指向外部资源的超链接。 - -PDF 页面可能由一个或多个 TextFragment 对象组成,其中每个 TextFragment 对象可以包含一个或多个 [TextSegment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textsegment/) 实例。 - -请尝试使用以下代码片段来完成此需求: - -```python - - import aspose.pdf as ap - - # 创建文档实例 - document = ap.Document() - # 向 PDF 文件的页面集合中添加页面 - page1 = document.pages.add() - # 创建 TextFragment 实例 - tf = ap.text.TextFragment("Sample Text Fragment") - # 设置 TextFragment 的水平对齐方式 - tf.horizontal_alignment = ap.HorizontalAlignment.RIGHT - # 使用示例文本创建一个 textsegment - segment = ap.text.TextSegment(" ... Text Segment 1...") - # 将 segment 添加到 TextFragment 的 segments 集合中 - tf.segments.append(segment) - # 创建一个新的 TextSegment - segment = ap.text.TextSegment("Link to Google") - # 将 segment 添加到 TextFragment 的 segments 集合中 - tf.segments.append(segment) - # 为 TextSegment 设置超链接 - segment.hyperlink = ap.WebHyperlink("www.google.com") - # 设置文本段的前景色 - segment.text_state.foreground_color = ap.Color.blue - # 将文本格式设置为斜体 - segment.text_state.font_style = ap.text.FontStyles.ITALIC - # 创建另一个 TextSegment 对象 - segment = ap.text.TextSegment("TextSegment without hyperlink") - # 将 segment 添加到 TextFragment 的 segments 集合中 - tf.segments.append(segment) - # 将 TextFragment 添加到页面对象的段落集合中 - page1.paragraphs.add(tf) - # 保存生成的 PDF 文档。 - document.save(output_pdf) -``` - - -## 使用 OTF 字体 - -Aspose.PDF for Python via .NET 提供了在创建/操作 PDF 文件内容时使用自定义/TrueType 字体的功能,以便文件内容可以使用非默认系统字体显示。 - -```python - - import aspose.pdf as ap - - # 创建新的文档实例 - document = ap.Document() - # 向 PDF 文件的页面集合添加页面 - page = document.pages.add() - # 使用示例文本创建 TextFragment 实例 - fragment = ap.text.TextFragment("OTF 字体中的示例文本") - # 您甚至可以在系统目录中指定 OTF 字体的路径 - fragment.text_state.font = ap.text.FontRepository.open_font(input_otf) - # 指定在 PDF 文件中嵌入字体,以便其正确显示, - # 即使目标计算机上未安装/存在特定字体 - fragment.text_state.font.is_embedded = True - # 将 TextFragment 添加到 Page 实例的段落集合 - page.paragraphs.add(fragment) - # 保存生成的 PDF 文档。 - document.save(output_pdf) -``` - - -## 使用 DOM 添加 HTML 字符串 - -下面的 Python 代码利用 Aspose.PDF 库创建一个包含 HTML 片段的 PDF 文档。 - -1. 实例化 Document。创建 Document 类的一个实例,代表 PDF 文档。 -2. 向 PDF 文档添加页面。 -3. 用 HTML 内容实例化一个 HtmlFragment 对象。 -4. 设置 HTML 片段的边距。在本例中,底部边距设置为 10 点,顶部边距设置为 200 点。 -5. 将 HTML 片段添加到页面。 -6. 保存 PDF 文件。 - -```python - - import aspose.pdf as ap - - # 实例化 Document 对象 - doc = ap.Document() - # 向 PDF 文件的页面集合中添加页面 - page = doc.pages.add() - # 用 HTML 内容实例化 HtmlFragment - title = ap.HtmlFragment("Table") - # 设置底部边距信息 - title.margin.bottom = 10 - # 设置顶部边距信息 - title.margin.top = 200 - # 将 HTML 片段添加到页面的段落集合 - page.paragraphs.add(title) - # 保存 PDF 文件 - doc.save(output_pdf) -``` - - -### FootNote的自定义线样式 - -以下示例演示了如何将脚注添加到Pdf页面的底部并定义自定义线样式。 - -```python - - import aspose.pdf as ap - - # 创建Document实例 - doc = ap.Document() - # 向PDF的pages集合添加页面 - page = doc.pages.add() - # 创建GraphInfo对象 - graph = ap.GraphInfo() - # 设置线宽为2 - graph.line_width = 2 - # 设置graph对象的颜色 - graph.color = ap.Color.red - # 设置虚线数组值为3 - graph.dash_array = [3] - # 设置虚线相位值为1 - graph.dash_phase = 1 - # 为页面设置脚注线样式为graph - page.note_line_style = graph - # 创建TextFragment实例 - text = ap.text.TextFragment("Hello World") - # 为TextFragment设置FootNote值 - text.foot_note = ap.Note("测试文本1的脚注") - # 将TextFragment添加到文档第一页的段落集合中 - page.paragraphs.add(text) - # 创建第二个TextFragment - text = ap.text.TextFragment("Aspose.Pdf for .NET") - # 为第二个文本片段设置FootNote - text.foot_note = ap.Note("测试文本2的脚注") - # 将第二个文本片段添加到PDF文件的段落集合中 - page.paragraphs.add(text) - # 保存生成的PDF文档。 - doc.save(output_pdf) -``` - - -### 自定义脚注标签 - -下面的代码片段展示了如何创建一个包含脚注的文本片段的 PDF 文档。 - -默认情况下,脚注编号从 1 开始递增。然而,我们可能需要设置一个自定义的脚注标签。为了实现这一需求,请尝试使用以下代码片段 - -```python - - import aspose.pdf as ap - - # 创建 Document 实例 - document = ap.Document() - # 向 PDF 的页面集合中添加页面 - page = document.pages.add() - # 创建 GraphInfo 对象 - graph = ap.GraphInfo() - # 设置线宽为 2 - graph.line_width = 2 - # 设置图形对象的颜色 - graph.color = ap.Color.red - # 设置虚线数组值为 3 - graph.dash_array = [3] - # 设置虚线相位值为 1 - graph.dash_phase = 1 - # 为页面设置脚注线样式为图形 - page.note_line_style = graph - # 创建 TextFragment 实例 - text = ap.text.TextFragment("Hello World") - # 为 TextFragment 设置脚注值 - text.foot_note = ap.Note("测试文本 1 的脚注") - # 指定脚注的自定义标签 - text.foot_note.text = " Aspose" - # 将 TextFragment 添加到文档第一页的段落集合中 - page.paragraphs.add(text) - # 保存生成的 PDF 文档 - document.save(output_pdf) -``` - - -## 添加图像和表格到脚注 - -此代码演示了如何使用 Aspose.PDF for Python 创建一个包含复杂脚注的 PDF 文档,该脚注包括图像、文本和表格。 - -```python - - import aspose.pdf as ap - - document = ap.Document() - page = document.pages.add() - text = ap.text.TextFragment("some text") - 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("footnote text") - 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("Row 1 Cell 1")) - text.foot_note.paragraphs.add(table) - - # 保存生成的 PDF 文档。 - document.save(output_pdf) -``` - -## 如何创建尾注 - -尾注是一个引用来源,指引读者到文章末尾的一个特定位置,在那里他们可以找到文章中引用或提到的信息或文字的来源。 - 当使用尾注时,你引用或改写的句子或总结的材料后面会跟着一个上标数字。 - -此代码演示了如何使用 Aspose.PDF for Python 将一个带有尾注的文本片段添加到 PDF 文档中: - -```python - - import aspose.pdf as ap - - # 创建 Document 实例 - document = ap.Document() - # 添加页面到 PDF 的页面集合中 - page = document.pages.add() - # 创建 TextFragment 实例 - text = ap.text.TextFragment("Hello World") - # 为 TextFragment 设置尾注值 - text.end_note = ap.Note("sample End note") - # 为 FootNote 指定自定义标签 - text.end_note.text = " Aspose" - # 将 TextFragment 添加到文档第一页的段落集合中 - page.paragraphs.add(text) - # 保存生成的 PDF 文档。 - document.save(output_pdf) -``` - -## 文本和图像作为行内段落 - -PDF 文件的默认布局是流式布局(从左上到右下)。 因此,每个新元素添加到 PDF 文件时,都是添加到右下方的流程中。然而,我们可能需要在同一水平线(一个接一个)显示各种页面元素,即图像和文本。一种方法是创建一个表格实例,并将两个元素添加到单独的单元格对象中。然而,另一种方法可以是使用内联段落。通过将图像和文本的 IsInLineParagraph 属性设置为 true,这些段落会显示为其他页面元素的内联段落。 - -以下代码片段展示了如何在 PDF 文件中将文本和图像作为内联段落添加。 - -```python - - import aspose.pdf as ap - - # 实例化 Document 实例 - document = ap.Document() - # 向 Document 实例的 pages 集合中添加页面 - page = document.pages.add() - # 创建 TextFragment - text = ap.text.TextFragment("Hello World.. ") - # 将文本片段添加到 Page 对象的段落集合中 - page.paragraphs.add(text) - # 创建一个图像实例 - image = ap.Image() - # 设置图像为内联段落,使其显示在 - # 上一个段落对象(TextFragment)之后 - image.is_in_line_paragraph = True - # 指定图像文件路径 - image.file = input_jpg - # 设置图像高度(可选) - image.fix_height = 30 - # 设置图像宽度(可选) - image.fix_width = 100 - # 将图像添加到 page 对象的段落集合中 - page.paragraphs.add(image) - # 使用不同的内容重新初始化 TextFragment 对象 - text = ap.text.TextFragment(" Hello Again..") - # 设置 TextFragment 为内联段落 - text.is_in_line_paragraph = True - # 将新创建的 TextFragment 添加到页面的段落集合中 - page.paragraphs.add(text) - # 保存生成的 PDF 文档 - document.save(output_pdf) -``` - -## 指定添加文本时的字符间距 - -下面的代码片段展示了如何生成一个包含增加字符间距的文本片段的 PDF 文档。 - -可以使用 TextFragment 实例在 PDF 文件的段落集合中添加文本,也可以使用 TextParagraph 对象,甚至可以使用 TextStamp 类在 PDF 内盖上文本。 - -### 使用 TextBuilder 和 TextFragment - -```python - - import aspose.pdf as ap - - # 创建 Document 实例 - document = ap.Document() - # 向 Document 的页面集合添加页面 - document.pages.add() - # 创建 TextBuilder 实例 - builder = ap.text.TextBuilder(document.pages[1]) - # 创建包含示例内容的文本片段实例 - wide_fragment = ap.text.TextFragment("Text with increased character spacing") - wide_fragment.text_state.apply_changes_from(ap.text.TextState("Arial", 12)) - # 为 TextFragment 指定字符间距 - wide_fragment.text_state.character_spacing = 2.0 - # 指定 TextFragment 的位置 - wide_fragment.position = ap.text.Position(100, 650) - # 将 TextFragment 附加到 TextBuilder 实例 - builder.append_text(wide_fragment) - # 保存生成的 PDF 文档。 - document.save(output_pdf) -``` - - -### 使用 TextParagraph - -```python - - import aspose.pdf as ap - - # 创建 Document 实例 - document = ap.Document() - # 将页面添加到 Document 的页面集合中 - document.pages.add() - # 创建 TextBuilder 实例 - builder = ap.text.TextBuilder(document.pages[1]) - # 实例化 TextParagraph 实例 - paragraph = ap.text.TextParagraph() - # 创建 TextState 实例以指定字体名称和大小 - state = ap.text.TextState(12.0) - state.font = ap.text.FontRepository.find_font("Arial") - # 指定字符间距 - state.character_spacing = 1.5 - # 将文本追加到 TextParagraph 对象 - tt = "这是具有字符间距的段落" - paragraph.append_line(tt, state) - # 指定 TextParagraph 的位置 - paragraph.position = ap.text.Position(100, 550) - # 将 TextParagraph 追加到 TextBuilder 实例 - builder.append_paragraph(paragraph) - # 保存生成的 PDF 文档。 - document.save(output_pdf) -``` - -### 使用 TextStamp - -```python - - import aspose.pdf as ap - - # 创建 Document 实例 - document = ap.Document() - # 将页面添加到 Document 的页面集合中 - page = document.pages.add() - # 使用示例文本实例化 TextStamp 实例 - stamp = ap.TextStamp("这是具有字符间距的文本印章") - # 为 Stamp 对象指定字体名称 - stamp.text_state.font = ap.text.FontRepository.find_font("Arial") - # 指定 TextStamp 的字体大小 - stamp.text_state.font_size = 12 - # 将字符间距指定为 1 - stamp.text_state.character_spacing = 1 - # 设置印章的 x_indent - stamp.x_indent = 100 - # 设置印章的 y_indent - stamp.y_indent = 500 - # 将文本印章添加到页面实例 - stamp.put(page) - # 保存生成的 PDF 文档。 - document.save(output_pdf) -``` - - -## 创建多列 PDF 文档 - -[Aspose.PDF for Python via .NET](https://docs.aspose.com/pdf/python-net/) 也提供了在 PDF 文档页面内创建多列的功能。为了创建多列 PDF 文件,我们可以使用 FloatingBox 类,因为它提供了 column_info 属性来指定 FloatingBox 内的列数,并且我们还可以使用 column_spacing 和 width 属性分别指定列间距和列宽。 - -列间距是指列之间的空隙,默认列间距为 1.25 厘米。如果未指定列宽,[Aspose.PDF for Python via .NET](https://docs.aspose.com/pdf/python-net/) 会根据页面大小和列间距自动计算每列的宽度。 - -下面给出了一个示例,以演示如何创建包含图形对象(Line)的两列,并将它们添加到 FloatingBox 的段落集合中,然后将其添加到 Page 实例的段落集合中。 - -```python - - import aspose.pdf as ap - - document = ap.Document() - # 指定PDF文件的左边距信息 - document.page_info.margin.left = 40 - # 指定PDF文件的右边距信息 - document.page_info.margin.right = 40 - page = document.pages.add() - - graph1 = ap.drawing.Graph(500, 2) - # 将线添加到段落集合的部分对象中 - page.paragraphs.add(graph1) - - # 指定线的坐标 - pos1 = [1.0, 2.0, 500.0, 2.0] - l1 = ap.drawing.Line(pos1) - graph1.shapes.append(l1) - # 创建包含HTML标签的文本字符串变量 - s = ( - '' - + " 如何避免金钱骗局 " - + "" - ) - # 创建包含HTML文本的文本段落 - heading_text = ap.HtmlFragment(s) - page.paragraphs.add(heading_text) - - box = ap.FloatingBox() - # 在部分中添加四列 - box.column_info.column_count = 2 - # 设置列之间的间距 - box.column_info.column_spacing = "5" - - box.column_info.column_widths = "105 105" - text1 = ap.text.TextFragment("作者:一位谷歌员工(谷歌官方博客)") - 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 - # 创建一个图形对象来绘制一条线 - graph2 = ap.drawing.Graph(50, 10) - # 指定线的坐标 - pos2 = [1.0, 10.0, 100.0, 10.0] - l2 = ap.drawing.Line(pos2) - graph2.shapes.append(l2) - - # 将线添加到段落集合的部分对象中 - 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) - # 保存PDF文件 - document.save(output_pdf) -``` - - -## 使用自定义制表位 - -这个Python代码片段展示了如何创建一个PDF文档,其中包含使用制表位排列的文本片段,以模拟表格结构。 - -以下是设置自定义制表位的示例。 - -```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( - "这是一个使用制表位形成表格的示例", 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) -``` - - -## 如何在 PDF 中添加透明文本 - -PDF 文件包含图像、文本、图形、附件、注释对象,在创建 TextFragment 时,您可以设置前景色、背景色信息以及文本格式。Aspose.PDF for Python via .NET 支持添加带有 Alpha 颜色通道的文本功能。 - -以下代码片段展示了如何添加带有透明颜色的文本。 - -```python - - import aspose.pdf as ap - - # 创建 Document 实例 - document = ap.Document() - # 创建页面并添加到 PDF 文件的页面集合 - page = document.pages.add() - - # 使用示例值创建 TextFragment 实例 - text = ap.text.TextFragment( - "transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text transparent text " - ) - # 从 Alpha 通道创建颜色对象 - color = ap.Color.from_argb(30, 0, 255, 0) - # 为文本实例设置颜色信息 - text.text_state.foreground_color = color - # 将文本添加到页面实例的段落集合 - page.paragraphs.add(text) - - document.save(output_pdf) -``` - - -## 为字体指定行间距 - -每种字体都有一个抽象的方块,其高度是相同字号的行之间的预期距离。这个方块称为 em 方块,它是定义字形轮廓的设计网格。许多输入字体的字母的某些点放置在字体的 em 方块边界之外,因此为了正确显示字体,需要使用特殊设置。 - -下面的代码片段加载一个 PDF,使用 TrueType 字体添加具有特定行间距的文本片段,并保存修改后的 PDF 文档: - -```python - - import aspose.pdf as ap - - # 加载输入 PDF 文件 - document = ap.Document() - # 创建包含 LineSpacingMode.FULL_SIZE 的 TextFormattingOptions - options = ap.text.TextFormattingOptions() - options.line_spacing = ap.text.TextFormattingOptions.LineSpacingMode.FULL_SIZE - - # 创建带有示例字符串的文本片段 - text_fragment = ap.text.TextFragment("Hello world") - - # 将 TrueType 字体加载到流对象中 - font_stream = open(input_ttf, "rb") - # 设置文本字符串的字体名称 - text_fragment.text_state.font = ap.text.FontRepository.open_font( - font_stream, ap.text.FontTypes.TTF - ) - # 指定文本片段的位置 - text_fragment.position = ap.text.Position(100, 600) - # 将当前片段的 TextFormattingOptions 设置为预定义的(指向 LineSpacingMode.FULL_SIZE) - text_fragment.text_state.formatting_options = options - page = document.pages.add() - page.paragraphs.add(text_fragment) - - # 保存生成的 PDF 文档 - document.save(output_pdf) -``` - - -## 动态获取文本宽度 - -此Python代码片段在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("意外的字体字符串测量!") - - if mt.fabs(ts.measure_string("z") - 7.0) > 0.001: - print("意外的字体字符串测量!") - - 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("字体和状态字符串测量不匹配!") - - c_code += 1 -``` - - \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/_index.md b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/_index.md new file mode 100644 index 0000000000..48642fc5a5 --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/_index.md @@ -0,0 +1,938 @@ +--- +title: 在 Python 中向 PDF 添加文本 +linktitle: 向 PDF 添加文本 +type: docs +weight: 10 +url: /zh/python-net/add-text-to-pdf-file/ +description: 了解如何在 Python 中向 PDF 文档添加文本、HTML 片段、列表、链接和自定义字体。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 向 PDF 文件添加文本、链接、HTML 和字体 +Abstract: 本文说明了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中添加和格式化文本。它涵盖了核心技术,如定位文本、应用字体和样式设置、插入链接和列表,以及在 Python 工作流中使用 HTML、LaTeX 和自定义字体。 +--- + +本指南介绍如何使用 Aspose.PDF for Python via .NET 向 PDF 文档添加文本内容。您将学习核心的文本插入技术——从在特定位置放置简单的文本片段,到对其进行样式设置(字体、大小、颜色、样式),处理从右到左 (RTL) 语言,嵌入超链接,以及使用段落布局、列表和透明度效果。文章还涵盖了高级场景,例如使用 HTML 或 LaTeX 片段、自定义字体以及行间距和字符间距等文本格式化选项。 + +无论您是构建简单的注释还是丰富的排版布局,本资源为您提供使用 Aspose.PDF 在 PDF 中处理文本的基本构建块。 + +## 基本文本插入 + +Aspose.PDF for Python via .NET 提供了强大且灵活的 API,用于处理 PDF 文件中的文本。 +无论您需要简单的静态标签、丰富格式的内容、多语言文本,还是交互式超链接,该工具包都能通过简洁的 Python 代码实现所有这些功能。 + +### 添加文本 简单案例 + +Aspose.PDF for Python via .NET 显示如何在页面的特定位置添加一个简单的文本片段。您将学习如何创建一个新的 PDF 文档,添加页面,在给定坐标插入文本,并保存生成的文件。 + +1. 创建一个新 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象。 +1. 使用 `document.pages.add()` 创建一个新的空白 [页面](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +1. 创建一个 [`TextFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/) 带有文本内容。 +1. 使用该方式设置文本位置 [`Position`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/position/) 类。如果您指定 `Position`,文本将在您的文档中从左到右定位并向下偏移。 +1. 自定义文本外观。您可以设置字体大小、颜色、字体样式等,通过 [`TextState`](https://reference.aspose.com/pdf/python-net/aspose.pdf/textstate/). +1. 追加 `TextFragment` 将页面的段落集合与 `page.paragraphs.add(text_fragment)`. +1. 保存文档。 + +以下代码片段展示了如何在现有 PDF 文件中添加文本: + +```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) +``` + +此代码示例使用 TextFragment。您也可以使用 TextParagraph 向 PDF 页面添加文本。 +该 **[TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/)** 是单个文本块。它代表一个可以独立放置、样式化和定位的文本字符串。当您需要添加小而简单的文本内容时,它是理想的选择。 + +该 **[文本段落](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textparagraph/)** 是一组 TextFragments。它可以添加多行文本。TextParagraph 是一个容器或集合,包含一个或多个 TextFragment 对象。当您需要对多个片段进行分组时,它非常理想——例如,创建一个包含多行、单词或格式化元素的文本块。 +TextParagraph 还管理文本对齐、行间距以及页面上的自动布局。仅在 TextParagraph 中才能使用红线。 + +有关文本处理的更多信息,请参阅 [PDF 中的文本格式化](/pdf/zh/python-net/text-formatting-inside-pdf/) 和 [搜索并获取 PDF 文本](/pdf/zh/python-net/search-and-get-text-from-pdf/). + +### 使用 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/) 带有换行选项。 + +1. 创建一个新 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 以及空白 [页面](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 使用 `document.pages.add()`. +1. 从文件读取文本或使用默认文本。 +1. 创建一个 [`TextBuilder`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textbuilder/) 添加具有布局和换行控制的段落级内容。 +1. 创建一个 [`TextParagraph`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textparagraph/) 并设置换行模式(示例使用 `DISCRETIONARY_HYPHENATION`). +1. 创建一个 [`TextFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/), 应用样式,并将片段追加到段落。 +1. 使用 the 将段落追加到页面 `TextBuilder`. +1. 保存文档。 + +```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) +``` + +![使用 TextParagraph 添加文本](text_paragraph.png) + +### 在 PDF 中添加带缩进的段落 + +以下代码片段展示了如何创建一个新的 PDF 文档并添加两段具有不同缩进样式的文本: + +- 第一段演示了首行缩进(仅首行缩进)。 + +- 第二段演示了后续行缩进(首行之后的所有行都缩进)。 + +它使用 Aspose.PDF 中的 'TextParagraph'、'TextBuilder' 和 'TextFragment' 类来精确控制布局和格式。 + +```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) +``` + +### 在 PDF 中添加新行文本 + +Aspose.PDF for Python via .NET 允许您使用 TextFragment、TextParagraph 和 TextBuilder 类向 PDF 文档插入多行文本。 + +1. 创建一个新文档。 +1. 定义一个包含换行符的 TextFragment。 +1. 设置文本样式。 +1. 将片段添加到段落中。 +1. 定位段落。 +1. 在页面上渲染段落。 +1. 保存文档。 + +```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) +``` + +### 确定 PDF 中的换行符并记录通知 + +它展示了如何创建包含多个文本片段的 PDF 文档,并启用 Aspose.PDF 通知日志,以在渲染期间监控布局事件——例如换行和文字换行——。 + +1. 创建一个新的 PDF 文档。 +1. 启用通知日志记录。 +1. 使用 document.pages.add() 来创建第一页。 +1. 添加多个文本片段。 +1. 使用 page.paragraphs.add(text) 来渲染每个文本片段。 +1. 保存文档。 + +```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) +``` + +### 在 PDF 中动态测量文本宽度 + +使用 Aspose.PDF for Python via .NET 动态测量特定字体中字符和字符串的宽度。它使用 'Font.measure_string()' 和 'TextState.measure_string()' 方法来验证测得的字符串宽度是否一致且准确。 + +1. 使用 'FontRepository.find_font()' 从仓库检索 Arial 字体对象。 +1. 创建一个 TextState 对象来管理字体属性。 +1. 测量单个字符。 +1. 比较两种方法在所有字符从 'A' 到 'z' 之间的结果。 +1. 确保两种测量方法得到相同的结果。 + +```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 +``` + +### 添加带超链接的文本 + +使用 Aspose.PDF for Python via .NET 在 PDF 中添加可点击的超链接。我们的库演示了如何在单个 TextFragment 中添加多个文本段落,并为特定段落应用超链接,以及对文本段落进行单独样式设置(例如颜色、斜体字体)。 + +1. 使用 'Document()' 创建新文档和页面,并使用 'document.pages.add()' 添加空白页。 +1. 创建一个 TextFragment。 +1. 添加多个 TextSegment 对象。每个段落都可以拥有自己的内容和样式。例如,普通文本或超链接文本。 +1. 将超链接应用于一个段落。创建一个具有所需 URL 的 WebHyperlink 对象。 +1. 为段落设置样式。使用 text_state 自定义颜色、字体样式、大小等。 +1. 使用 'page.paragraphs.add()' 将片段添加到页面。 +1. 保存 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) +``` + +![在 PDF 中显示的文本片段展示了混合内容,包含 Sample Text Fragment,随后是 Text Segment 1,然后是一个蓝色超链接文本,内容为 Link to Aspose(链接到 https://products.aspose.com/pdf),并以普通黑色文本格式的 TextSegment 结尾且不带超链接](hyperlink_text.png) + +### 向 PDF 文档添加从右到左 (RTL) 文本 + +RTL(从右到左)是一种属性,指示文本书写的方向,即文本从右侧向左侧书写。 +Aspose.PDF for Python via .NET. 演示如何向 PDF 文档添加从右到左 (RTL) 文本,例如阿拉伯语或希伯来语。 + +1. 使用 'Document()' 创建新文档和页面,并使用 'document.pages.add()' 添加空白页。 +1. 创建一个包含 RTL 内容的 TextFragment。将您的阿拉伯语、希伯来语或其他 RTL 语言文本作为片段内容插入。 +设置字体和样式。选择支持 RTL 脚本的字体(例如,Tahoma,Arial Unicode MS)。根据需要设置 font_size 和 foreground_color。 +1. 使用 'text_fragment.horizontal_alignment' 将水平对齐设置为右对齐。 +1. 将 TextFragment 添加到页面。 +1. 保存 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) +``` + +![从右到左文本](rtl_text.png) + +## 文本样式 + +### 添加带字体样式的文本 + +这是一个更高级的示例,展示了文本样式、字体自定义以及混合格式文本(使用下标文本段)。Aspose.PDF 解释了如何将字体属性(如字体系列、大小、颜色、粗体、斜体和下划线)应用于文本片段。 +此外,此代码片段展示了如何在单个片段中使用多个文本段来创建复杂的文本表达式——例如,包含下标或上标字符,这在公式或科学表示中常常需要。 + +1. 使用 'Document()' 创建新文档和页面,并使用 'document.pages.add()' 添加空白页。 +1. 创建一个用于简单样式文本的 TextFragment。 +1. 定义文本内容。 +1. 使用 Position(x, y) 坐标设置位置。 +1. 通过 'text_state property' 应用样式 - font、font_size、foreground_color、underline。 +1. 使用多个 TextSegment 对象创建复杂表达式。每个 TextSegment 表示文本的一部分,可以拥有各自的样式。这使您能够构建表达式,例如数学或化学公式。 +1. 定义多个 TextState 对象。一个用于主要文本(text_state_letters)。另一个用于下标或上标文本(text_state_index)。 +1. 合并文本段。使用 'segments.append()' 将每个段追加到 'TextFragment'。 +1. 将两个文本对象都添加到页面。使用 'page.paragraphs.add()' 将它们放置在文档中。 +1. 保存最终文档。 + +```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) +``` + +![文本片段使用蓝色斜体 Arial 字体显示,内容为 Hello, Aspose!,随后是一个数学公式,显示 S = a₂ₙ + a₂ₙ₊₁ + a₂ₙ₊₂,主文本为蓝色,下标为红色格式。](styled_text.png) + +## 添加文本透明 + +使用 Aspose.PDF for Python 向 PDF 文档添加半透明形状和文本。 +它创建了一个带有部分不透明度的彩色矩形,并在其上覆盖一个具有透明前景色的 TextFragment。 + +1. 初始化一个 Document 对象并添加一个空白页用于绘制内容。 +1. 使用 'ap.drawing.Graph' 创建一个画布,以便您可以绘制形状。 +1. 添加一个具有半透明填充的矩形。 +1. 防止画布位置偏移。 +1. 将画布添加到页面。将图形形状插入页面段落集合。 +1. 创建一个透明的文本片段。 +1. 将文本片段插入页面段落集合。 +1. 保存 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) +``` + +### 向 PDF 添加不可见文本 + +本示例演示如何创建一个包含可见文本和不可见文本的 PDF 文档。不可见文本仍然是文档结构的一部分,但在视觉上被隐藏,这使其可用于嵌入元数据、可访问性标签或可搜索内容,而不会影响布局。 + +1. 创建 PDF 文档和页面。 +1. 创建一个包含重复可见内容的文本片段。 +1. 添加第二个文本片段并将其标记为不可见。 +1. 保存文档。 + +```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) +``` + +### 在 PDF 中添加带边框样式的文本 + +Aspose.PDF 库展示了如何创建包含带可见边框的样式化文本片段的 PDF 文档。该方法为文本矩形应用背景色和前景色、字体设置以及描边(边框),以增强视觉强调。 + +1. 创建一个 PDF 文档和一个页面。 +1. 创建并定位文本片段。添加一个带有消息的文本片段并设置其位置。 +1. 应用文本样式。将字体设置为 Times New Roman,大小 12。应用浅灰色背景和红色前景(文本)颜色。 +1. 配置边框样式。 +1. 将文本添加到页面。使用 TextBuilder 将样式化的文本追加到页面。 +1. 保存文档。 + +```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) +``` + +### 在 PDF 中添加删除线文字 + +在 PDF 文档中的文本片段添加删除线(划掉)格式。删除线文本对于在注释文档中指示删除、修订或强调非常有用。 + +1. 使用 'Document()' 创建新文档和页面,并使用 'document.pages.add()' 添加空白页。 +1. 创建并样式化文本片段。 +1. 应用颜色和删除线格式。将背景设为浅灰色,文字颜色设为红色,并启用删除线。 +1. 定位文本。 +1. 使用 'TextBuilder' 将样式化文本附加到页面。 +1. 保存文档。 + +```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) +``` + +## 高级颜色效果 + +### 在 PDF 中对文本应用轴向渐变 + +Aspose.PDF for Python via .NET 演示了如何在 PDF 文档中的文本上应用线性渐变效果。轴向渐变在文本中平滑地从红色过渡到蓝色,形成视觉上令人印象深刻的标题。此技术非常适用于样式化标题、品牌标识或 PDF 文档布局中的装饰元素。 + +1. 初始化一个新文档并添加一个空白页。 +1. 创建并样式化文本片段。添加标题,设置位置、字体和大小。 +1. 使用 'GradientAxialShading' 应用轴向渐变遮罩。使用 GradientAxialShading 将前景颜色设置为从红色到蓝色。 +1. 添加下划线样式。 +1. 将样式化的文本片段插入页面。 +1. 保存文档。 + +```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) +``` + +### 在 PDF 中对文本应用径向渐变 + +径向渐变在文本中心向外辐射,形成圆形的颜色过渡,为标题、页眉或装饰元素提供一种视觉上动态的样式选项。 + +1. 初始化一个新文档并添加一个空白页。 +1. 创建并样式化文本片段。添加标题,设置位置、字体和大小。 +1. 使用 'GradientRadialShading' 应用径向渐变。使用 GradientRadialShading 将前景颜色设置为从红色到蓝色。 +1. 添加下划线样式。 +1. 将样式化的文本片段插入页面。 +1. 保存文档。 + +```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) +``` + +![应用径向渐变着色](gradient_radial_shading.png) + +## HTML 和 LaTeX 片段 + +### 在 PDF 文档中添加 HTML 文本 + +Aspose.PDF for Python via .NET 库允许您使用 HtmlFragment 类将 HTML 格式的内容插入 PDF 文档。通过使用 HTML 标记,您可以直接在 PDF 中呈现带样式、结构化或类似公式的文本。 + +1. 使用 'Document()' 创建新文档和页面,并使用 'document.pages.add()' 添加空白页。 +1. 创建 HtmlFragment 类的实例,并将您的 HTML 字符串作为参数传入。 +1. 使用 'page.paragraphs.add()' 将片段添加到页面,以插入 HTML 内容。 +1. 保存 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)
+```
+
+![向 PDF 文档添加 HTML 文本](html_fragment.png)
+
+### 向 PDF 文档添加带有各种格式的样式化 HTML 片段
+
+我们可以定义一个 HTML 片段,并直接使用 HTML 标签设置文本样式。将带样式的 HTML 内容嵌入 PDF 文档中。此代码片段创建一个新的 PDF 文件,添加一个页面,插入包含各种格式元素(标题、段落、链接和内联样式)的 HTML 片段,并将结果保存到指定路径。
+
+1. 初始化一个新的 Document 对象来表示 PDF。
+1. 在文档中追加一个空白页,HTML 内容将放置在该页上。
+1. 准备 HTML 内容。HTML 字符串包含一个 h1 标题,一个绿色段落,其中包含粗体、斜体和下划线文本,以及一个字体增大的指向网站的超链接。
+1. 创建 HTML 片段。将 HTML 字符串包装在 HtmlFragment 对象中。
+1. 将 HTML 插入页面。将 HTML 片段添加到页面的段落集合中,将 HTML 渲染为原生 PDF 内容。
+1. 保存文档。
+
+```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) +``` + +![向 PDF 文档添加 HTML 内容](html_content.png) + +### 添加带有覆盖文本状态的 HTML Fragment + +正如我们在前面的示例中看到的,可以直接在HTML代码中设置样式。这有其优势,但也有一些缺点。假设我们正在处理客户的HTML,并希望统一我们输出的外观。 +在这种情况下,我们可以通过使用自己的 TextState 来覆盖客户的样式,如下例所示。 + +1. 使用 'Document()' 创建新文档和页面,并使用 'document.pages.add()' 添加空白页。 +1. 准备 HTML 内容。HTML 字符串包含一个使用 Verdana 字体的 h1 标题,一个绿色段落,其中包含加粗、斜体和下划线文本,以及一个字体更大的指向网站的超链接。 +1. 创建 HTML 片段。将 HTML 字符串包装在 HtmlFragment 对象中。 +1. 覆盖文本格式。创建一个 TextState 对象并设置 Font、Font Size 和 Text Color。 +1. 将 HTML 片段添加到页面的段落集合中。 +1. 保存文档。 + +```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) +``` + +![添加 HTML 片段覆盖文本状态](html_override.png) + +### 向 PDF 文档添加 LaTeX 文本 + +使用 Aspose.PDF for Python via .NET 中的 TeXFragment 类向 PDF 文档添加 LaTeX 格式的数学表达式。 +LaTeX 是一个功能强大的排版系统,广泛用于创建科学和数学文档。通过使用 TeXFragment,您可以直接在 PDF 页面中渲染 LaTeX 数学记号和符号。 + +1. 使用 'Document()' 创建新文档和页面,并使用 'document.pages.add()' 添加空白页。 +1. 使用 TeXFragment 类直接渲染 LaTeX 语法。 +1. 使用 'page.paragraphs.add()' 将 LaTeX 内容添加到 PDF 布局中。 +1. 保存 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) +``` + +![复杂的数学表达式显示在 PDF 中,展示了 LaTeX 公式,对 (a+b)⁶ 使用了 overbrace(上括号)标记,对整个表达式 (a+b)⁶ · (c+d)⁷ 使用了 underbrace(下括号)标记,标记为文本示例,并等于 42。该公式展示了高级数学排版,具备 LaTeX 渲染的适当间距和括号样式。](latex_fragment.png) + +## 自定义字体 + +### 使用文件中的自定义字体 + +此示例演示如何使用 Aspose.PDF for Python via .NET 中的自定义 OpenType 字体向 PDF 文件添加文本。它展示了如何创建新 PDF 文档、在页面上精确定位文本以及应用自定义格式,如字体类型、大小、颜色和斜体样式。 + +1. 创建一个新的 PDF 文档并添加一个页面。 +1. 定义您想要添加到 PDF 的文本内容。 +1. 设置文本的位置。 +1. 将 TextFragment 添加到页面。 +1. 保存 PDF 文档。 + +此函数不仅适用于 OTF,还适用于 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) +``` + +![在 PDF 文档中显示的文本片段,展示 Hello, Aspose! 使用蓝色斜体 BriosoPro 字体渲染,演示了自定义 OpenType 字体集成和 PDF 文本格式化中的样式功能。](custom_font.png) + +### 使用来自流的自定义 Font + +此代码片段演示了如何使用 Aspose.PDF for Python via .NET,通过自定义嵌入的 OpenType (OTF) 字体向 PDF 文档添加文本。它展示了如何将字体文件以流的形式打开,将其嵌入 PDF,以确保在不同系统中字体可用,并应用诸如字体大小、颜色和斜体样式等文本格式。此方法非常适合创建视觉一致的 PDF,即使在未安装该字体的设备上共享或查看时,也能保持排版效果。 + +1. 将字体文件加载为二进制流。 +1. 使用 'FontRepository.open_font' 打开并嵌入字体。 +1. 创建一个新的 PDF 文档并添加一个页面。 +1. 添加带样式的文本片段: + - 嵌入的自定义字体。 + - 斜体样式和蓝色。 + - 特定的字体大小和位置。 +1. 将最终文档保存到指定的输出路径。 + +```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) +``` + +嵌入字体可确保跨平台的一致渲染,使此方法非常适合品牌塑造、设计保真度以及多语言支持。 + +## 相关文本主题 + +- [使用 Python 在 PDF 中处理文本](/pdf/zh/python-net/working-with-text/) +- [在 Python 中格式化 PDF 文本](/pdf/zh/python-net/text-formatting-inside-pdf/) +- [通过 Python 替换 PDF 中的文本](/pdf/zh/python-net/replace-text-in-pdf/) +- [在 Python 中搜索并提取 PDF 文本](/pdf/zh/python-net/search-and-get-text-from-pdf/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/bullet_list_html.png b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/bullet_list_html.png new file mode 100644 index 0000000000..701c621614 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/bullet_list_html.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/bullet_list_latex.png b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/bullet_list_latex.png new file mode 100644 index 0000000000..c42c33a539 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/bullet_list_latex.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/character_spacing_simple.png b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/character_spacing_simple.png new file mode 100644 index 0000000000..3d1ac22841 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/character_spacing_simple.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/custom_font.png b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/custom_font.png new file mode 100644 index 0000000000..6415c929f0 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/custom_font.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/gradient_radial_shading.png b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/gradient_radial_shading.png new file mode 100644 index 0000000000..c6eeb2c416 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/gradient_radial_shading.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/html_content.png b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/html_content.png new file mode 100644 index 0000000000..742222d41e Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/html_content.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/html_fragment.png b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/html_fragment.png new file mode 100644 index 0000000000..569d530709 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/html_fragment.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/html_override.png b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/html_override.png new file mode 100644 index 0000000000..d10cdc2593 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/html_override.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/hyperlink_text.png b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/hyperlink_text.png new file mode 100644 index 0000000000..137c29629b Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/hyperlink_text.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/latex_fragment.png b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/latex_fragment.png new file mode 100644 index 0000000000..bc246cfc0f Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/latex_fragment.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/line_spacing.png b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/line_spacing.png new file mode 100644 index 0000000000..eb284e2afa Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/line_spacing.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/numbered_list_html.png b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/numbered_list_html.png new file mode 100644 index 0000000000..f04bb77a7d Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/numbered_list_html.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/numbered_list_latex.png b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/numbered_list_latex.png new file mode 100644 index 0000000000..9fdb376e24 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/numbered_list_latex.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/rtl_text.png b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/rtl_text.png new file mode 100644 index 0000000000..439ac9dbe3 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/rtl_text.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/styled_text.png b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/styled_text.png new file mode 100644 index 0000000000..dff4a6b1a9 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/styled_text.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/text_paragraph.png b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/text_paragraph.png new file mode 100644 index 0000000000..10cf9ea243 Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/add-text-to-pdf-file/text_paragraph.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/add-tooltip-to-text/_index.md b/zh/python-net/advanced-operations/working-with-text/add-tooltip-to-text/_index.md index 1d3d573f1a..4adf1a9370 100644 --- a/zh/python-net/advanced-operations/working-with-text/add-tooltip-to-text/_index.md +++ b/zh/python-net/advanced-operations/working-with-text/add-tooltip-to-text/_index.md @@ -1,295 +1,187 @@ --- -title: PDF 工具提示使用 Python +title: 在 Python 中为 PDF 文本添加工具提示 linktitle: PDF 工具提示 type: docs weight: 20 url: /zh/python-net/pdf-tooltip/ -description: 学习如何使用 Python 和 Aspose.PDF 向 PDF 中的文本片段添加工具提示 -lastmod: "2024-02-17" +description: 了解如何在 Python 中向 PDF 文档的文本片段添加工具提示。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 为 PDF 文本片段添加交互式工具提示 +Abstract: 本文提供了两个使用 Aspose.PDF for Python via .NET 为 PDF 文本添加交互式帮助的 Python 示例。第一个示例通过放置不可见的 `ButtonField` 元素并设置 `alternate_name` 来为匹配的文本片段添加工具提示。第二个示例创建一个隐藏的 `TextBoxField`,通过将 `HideAction` 事件绑定到不可见的 `ButtonField` 实现悬停时显示。 --- - +## 在 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`. -此代码演示了如何使用 Aspose.PDF 为 PDF 文档中的特定文本片段添加工具提示。当鼠标光标悬停在相应文本上时,将显示工具提示。 +当您需要通过添加悬停帮助、内联解释或上下文注释来使 PDF 文本更具交互性时,请使用此页面。 -以下代码片段将向您展示如何实现此功能: +1. 创建一个新 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 保存初始文档。 +1. 重新打开 PDF 文档。 +1. 使用搜索目标文本 [`TextFragmentAbsorber`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber/). +1. 添加一个不可见的 [`ButtonField`](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/buttonfield/) 带有简短的工具提示。 +1. 搜索第二个目标文本。 +1. 添加一个不可见的 [`ButtonField`](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/buttonfield/) 在匹配的片段上显示长工具提示。 +1. 保存最终文档。 ```python - - import aspose.pdf as ap - - document = ap.Document() - document.pages.add().paragraphs.add( - ap.text.TextFragment("将鼠标光标移到这里以显示工具提示") - ) - document.pages[1].paragraphs.add( - ap.text.TextFragment( - "将鼠标光标移到这里以显示一个非常长的工具提示" +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) - - # 打开带有文本的文档 - document = ap.Document(output_pdf) - # 创建 TextAbsorber 对象以查找所有匹配正则表达式的短语 - absorber = ap.text.TextFragmentAbsorber( - "将鼠标光标移到这里以显示工具提示" - ) - # 接受文档页面的吸收器 - document.pages.accept(absorber) - # 获取提取的文本片段 - text_fragments = absorber.text_fragments - - # 循环遍历片段 - for fragment in text_fragments: - # 在文本片段位置创建不可见按钮 - field = ap.forms.ButtonField(fragment.page, fragment.rectangle) - # alternate_name 值将在查看器应用程序中显示为工具提示 - field.alternate_name = "文本的工具提示。" - # 将按钮字段添加到文档 - document.form.add(field) - - # 接下来是非常长的工具提示的示例 - absorber = ap.text.TextFragmentAbsorber( - "将鼠标光标移到这里以显示一个非常长的工具提示" - ) - document.pages.accept(absorber) - text_fragments = absorber.text_fragments - - for fragment in text_fragments: - field = ap.forms.ButtonField(fragment.page, fragment.rectangle) - # 设置非常长的文本 - 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) - # 保存文档 - 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) ``` +## 在 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/) 当用户将鼠标悬停在其上时。此技术非常适合上下文帮助、批注或动态内容呈现。 -这个Python代码片段展示了如何在PDF文档中添加浮动文本,当鼠标光标悬停在特定区域时显示。 - -首先,创建一个新的PDF文档,并向其中添加包含文本“将鼠标光标移到这里以显示浮动文本”的段落。然后保存文档。 - -接下来,重新打开保存的文档,并创建一个TextAbsorber对象来查找之前添加的文本片段。然后使用这个文本片段来定义浮动文本字段的位置和特征。 - -创建一个TextBoxField对象来表示浮动文本字段,并相应地设置其属性,如位置、值、只读状态和可见性。此外,为字段分配唯一名称和外观特征。 - -将浮动文本字段添加到文档的表单中,并在原始文本片段的位置创建一个不可见的按钮字段。 - HideAction 事件被分配给按钮字段,指定当鼠标光标进入其附近时,浮动文本字段应出现,并在光标退出时消失。 - -最后,将按钮字段添加到文档的表单中,并保存修改后的文档。 - -此代码片段提供了一种使用 Aspose.PDF for Python 在 PDF 文档中创建交互式浮动文本元素的方法。 +1. 创建一个新的 PDF 文档。 +1. 保存 PDF,以便以后重新打开进行交互设置。 +1. 重新打开 PDF 文档。 +1. 使用定位目标文本 [`TextFragmentAbsorber`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber/). +1. 创建隐藏的 [`TextBoxField`](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/textboxfield/). +1. 将隐藏字段添加到文档的 [`Form`](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/form/) 集合。 +1. 创建一个不可见的 [`ButtonField`](https://reference.aspose.com/pdf/python-net/aspose.pdf.forms/buttonfield/). +1. 分配鼠标操作(`on_enter`, `on_exit`) 使用 [`HideAction`](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/hideaction/) 显示/隐藏隐藏字段。 +1. 保存最终文档。 ```python - - import aspose.pdf as ap - - document = ap.Document() - document.pages.add().paragraphs.add( - ap.text.TextFragment("将鼠标光标移动到此处以显示浮动文本") - ) - document.save(output_pdf) - - # 打开带有文本的文档 - document = ap.Document(output_pdf) - # 创建 TextAbsorber 对象以查找与正则表达式匹配的所有短语 - absorber = ap.text.TextFragmentAbsorber( - "将鼠标光标移动到此处以显示浮动文本" - ) - # 接受文档页面的吸收器 - document.pages.accept(absorber) - # 获取第一个提取的文本片段 - text_fragments = absorber.text_fragments - fragment = text_fragments[1] - - # 在页面的指定矩形中为浮动文本创建隐藏文本字段 - floating_field = ap.forms.TextBoxField( - fragment.page, ap.Rectangle(100.0, 700.0, 220.0, 740.0, False) - ) - # 设置要显示的文本作为字段值 - floating_field.value = '这是“浮动文本字段”。' - # 我们建议在此方案中将字段设置为“只读” - floating_field.read_only = True - # 设置“隐藏”标志以使字段在文档打开时不可见 - floating_field.flags |= ap.annotations.AnnotationFlags.HIDDEN - - # 设置唯一字段名称不是必须的,但允许 - floating_field.partial_name = "FloatingField_1" - - # 设置字段外观特征不是必须的,但会更好 - 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 - - # 将文本字段添加到文档中 - document.form.add(floating_field) - # 在文本片段位置创建不可见按钮 - button_field = ap.forms.ButtonField(fragment.page, fragment.rectangle) - # 为指定字段(注释)和不可见性标志创建新的隐藏动作。 - # (如果之前指定了名称,您也可以通过名称引用浮动字段。) - # 在不可见按钮字段上添加鼠标进入/退出动作 - - 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 - ) - - # 将按钮字段添加到文档中 - document.form.add(button_field) - - # 保存文档 - 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 +## 相关文本主题 + +- [使用 Python 在 PDF 中处理文本](/pdf/zh/python-net/working-with-text/) +- [在 Python 中使用 FloatingBox 进行 PDF 文本布局](/pdf/zh/python-net/floating-box/) +- [在 Python 中搜索并提取 PDF 文本](/pdf/zh/python-net/search-and-get-text-from-pdf/) +- [向 PDF 添加文本](/pdf/zh/python-net/add-text-to-pdf-file/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-text/determine-line-break/_index.md b/zh/python-net/advanced-operations/working-with-text/determine-line-break/_index.md deleted file mode 100644 index fd658008ee..0000000000 --- a/zh/python-net/advanced-operations/working-with-text/determine-line-break/_index.md +++ /dev/null @@ -1,185 +0,0 @@ ---- -title: 确定换行符 -linktitle: 确定换行符 -type: docs -weight: 70 -url: /zh/python-net/determine-line-break/ -description: 了解更多关于如何使用Python确定多行TextFragment的换行符 -lastmod: "2024-02-17" -sitemap: - changefreq: "weekly" - priority: 0.7 ---- - - - -## 跟踪多行文本片段的换行 - -下面的代码片段展示了如何跟踪PDF文档中多行文本片段的换行行为。 - -定义了 track_line_breaking() 函数来演示此功能。它首先指定生成的PDF文档和对应的文本文件的输出文件路径,该文本文件将包含有关换行的信息。 - -在函数内部,创建了一个新的PDF文档对象,并向其中添加了一个新页面。随后,使用循环生成了四个 TextFragment 实例,其中在字符串中插入了换行符("\r\n")以模拟多行文本。 - -每个 TextFragment 被配置为 20 点的字体大小,然后被添加到页面的段落中。 - -在所有 TextFragment 被添加后,文档被保存。 - -然后,函数继续使用 get_notifications() 方法从生成的PDF文档的第二页提取有关换行的通知。 - 这些通知被写入之前指定的文本文件中。 - -此代码片段演示了如何创建包含多行文本的PDF文档,然后提取有关换行行为的信息,以提供有关文本在文档中布局的见解。 - -```python - - import aspose.pdf as ap - - def track_line_breaking(): - """跟踪多行文本片段的换行""" - output_pdf = DIR_OUTPUT_TEXTS + "track_line_breaking.pdf" - output_txt = DIR_OUTPUT_TEXTS + "track_line_breaking.txt" - - # 创建新的文档对象 - 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/zh/python-net/advanced-operations/working-with-text/floating-box/_index.md b/zh/python-net/advanced-operations/working-with-text/floating-box/_index.md new file mode 100644 index 0000000000..af63dfced1 --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-text/floating-box/_index.md @@ -0,0 +1,304 @@ +--- +title: 在 Python 中使用 FloatingBox 进行 PDF 布局 +linktitle: 使用 FloatingBox +type: docs +weight: 30 +url: /zh/python-net/floating-box/ +description: 学习如何在 PDF 文档中使用 FloatingBox 进行文本布局、多列内容和精确定位(使用 Python)。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.5 +TechArticle: true +AlternativeHeadline: 使用 Python 在 PDF 中创建并定位样式化的 FloatingBox 容器。 +Abstract: 本文介绍了如何在 Aspose.PDF for Python via .NET 中使用 FloatingBox。了解如何将文本和其他内容放置在样式化的浮动容器中,控制布局、边框、对齐和裁剪,并在 Python 中构建更结构化的 PDF 页面设计。 +--- + +## 基本 FloatingBox 用法 + +这 [`FloatingBox`](https://reference.aspose.com/pdf/python-net/aspose.pdf/floatingbox/) 类是用于在 PDF 页面上放置文本和其他内容的容器。它比普通文本段落提供了更强的布局、边框和样式控制。如果内容超出框的大小,裁剪行为由框设置控制。 + +当您需要在 PDF 文档中使用结构化文本容器、多列布局和精确定位,并使用 Aspose.PDF for Python via .NET 时,请使用此页面。 + +1. 创建一个新 [`Document`](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 添加一个 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 到文档。 +1. 创建一个 [`FloatingBox`](https://reference.aspose.com/pdf/python-net/aspose.pdf/floatingbox/). +1. 使用设置框的边框 [`BorderInfo`](https://reference.aspose.com/pdf/python-net/aspose.pdf/borderinfo/) 和 [`BorderSide`](https://reference.aspose.com/pdf/python-net/aspose.pdf/borderside/). +1. 使用控制框进行重复 [`is_need_repeating`](https://reference.aspose.com/pdf/python-net/aspose.pdf/floatingbox/#properties) property. +1. 使用添加文本内容 [`TextFragment`](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/). +1. 添加 `FloatingBox` 到 [`Page`](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/). +1. 使用保存最终 PDF 文档 [`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) +``` + +在上面的示例中, `FloatingBox` 已创建,宽度为 400 pt,高度为 30 pt。 +该文本故意超出了可用高度,因此部分被裁剪。 + +![图像 1](image01.png) + +这 [`is_need_repeating`](https://reference.aspose.com/pdf/python-net/aspose.pdf/floatingbox/#properties) 属性的值为 `False` 将文本渲染限制为单页。 + +如果您将此属性设置为 `True`, 文本在相同位置重新流向后续页面。 + +![图片 2](image02.png) + +## 高级浮动框功能 + +### 多列支持 + +#### 多列布局(简单情况) + +`FloatingBox` 支持多列布局。要创建此布局,您必须定义以下值 [`ColumnInfo`](https://reference.aspose.com/pdf/python-net/aspose.pdf/columninfo/) 属性。 + +* `column_widths` 是一个字符串,用于定义每列的宽度(以点为单位)。 +* `column_spacing` 是一个定义列之间间隙宽度的字符串。 +* `column_count` 是列的数量。 + +```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) +``` + +此示例生成示例段落并将其放置在三列中。内容会继续到额外的页面,直到所有段落渲染完成。 + +#### 带强制列起始的多列布局 + +此示例使用相同的多列布局,但强制每个新增段落在新列中开始。为此,请设置 `is_first_paragraph_in_column = True` 在每个 `TextFragment` 在将其添加到 `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) +``` + +### 后台支持 + +将背景颜色应用于 `FloatingBox` 在 PDF 文档中使用 Aspose.PDF for Python via .NET。 +通过分配一个 [`Color`](https://reference.aspose.com/pdf/python-net/aspose.pdf/color/) 到 `background_color`, 您可以突出显示标题、提示或样式化的部分。 + +此代码片段展示了如何创建一个带有示例内容的浅绿色文本框。 + +```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) +``` + +### 定位支持 + +a 的位置 `FloatingBox` 页面上由...控制 `positioning_mode`, `left`,和 `top`. +何时 `positioning_mode` 是: + +* [`ParagraphPositioningMode.DEFAULT`](https://reference.aspose.com/pdf/python-net/aspose.pdf/paragraphpositioningmode/) (默认) + +位置取决于先前添加的元素。 添加新段落会影响后续元素的流动。 如果 [`left`](https://reference.aspose.com/pdf/python-net/aspose.pdf/floatingbox/#properties) 或 [`top`](https://reference.aspose.com/pdf/python-net/aspose.pdf/floatingbox/#properties) 为非零时,它们也会被应用。 + +* [`ParagraphPositioningMode.ABSOLUTE`](https://reference.aspose.com/pdf/python-net/aspose.pdf/paragraphpositioningmode/) + +位置已固定 `left` 和 `top`;它不依赖于先前的元素,也不影响后续元素的流程。 + +```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) +``` + +### 在 PDF 中对浮动框进行垂直和水平对齐 + +对齐 `FloatingBox` 使用 PDF 页面上的元素 [`VerticalAlignment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/verticalalignment/) 和 [`HorizontalAlignment`](https://reference.aspose.com/pdf/python-net/aspose.pdf/horizontalalignment/) 在 Aspose.PDF for Python via .NET 中。这可以帮助您在页面布局、页眉/页脚块或侧注中,将浮动容器放置在顶部、居中或底部位置。 + +1. 创建一个新的 PDF 文档。 +1. 向文档添加一个页面。 +1. 添加第一个 `FloatingBox` 右下对齐。 +1. 添加第二个 `FloatingBox` 居中右对齐。 +1. 添加第三个 `FloatingBox` 右上对齐。 +1. 保存文档。 + +```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) +``` + +## 相关文本主题 + +* [使用 Python 在 PDF 中处理文本](/pdf/zh/python-net/working-with-text/) +* [向 PDF 添加文本](/pdf/zh/python-net/add-text-to-pdf-file/) +* [在 Python 中格式化 PDF 文本](/pdf/zh/python-net/text-formatting-inside-pdf/) +* [在 Python 中为 PDF 文本添加工具提示](/pdf/zh/python-net/pdf-tooltip/) diff --git a/zh/python-net/advanced-operations/working-with-text/floating-box/image01.png b/zh/python-net/advanced-operations/working-with-text/floating-box/image01.png new file mode 100644 index 0000000000..362771c51d Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/floating-box/image01.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/floating-box/image02.png b/zh/python-net/advanced-operations/working-with-text/floating-box/image02.png new file mode 100644 index 0000000000..c179e185fb Binary files /dev/null and b/zh/python-net/advanced-operations/working-with-text/floating-box/image02.png differ diff --git a/zh/python-net/advanced-operations/working-with-text/replace-text-an-a-pdf/_index.md b/zh/python-net/advanced-operations/working-with-text/replace-text-an-a-pdf/_index.md index 3043d4990b..893c8a1372 100644 --- a/zh/python-net/advanced-operations/working-with-text/replace-text-an-a-pdf/_index.md +++ b/zh/python-net/advanced-operations/working-with-text/replace-text-an-a-pdf/_index.md @@ -4,43 +4,43 @@ linktitle: 替换 PDF 中的文本 type: docs weight: 40 url: /zh/python-net/replace-text-in-pdf/ -description: 学习如何使用 Python 替换 PDF 文件中的文本,包括跨页替换文本、将更改限制在页面区域内、使用正则表达式以及删除文本。 -lastmod: "2026-05-05" +description: 了解如何使用 Python 替换 PDF 文件中的文字,包括跨页替换文字、将更改限制在页面区域、使用正则表达式以及删除文字。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 aliases: - /python-net/replace-text-in-a-pdf-document/ TechArticle: true -AlternativeHeadline: 使用 Python 替换和删除 PDF 文件中的文本 -Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 替换 PDF 文档中的文本。它涵盖了跨所有页面的文本替换、页面区域替换、正则表达式匹配、字体替换、文本布局调整以及删除可见或隐藏的文本。 +AlternativeHeadline: 使用 Python 替换和删除 PDF 文件中的文字 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中替换文本。它涵盖了跨所有页面的文本替换、页面区域替换、正则表达式匹配、字体替换、文本布局调整以及删除可见或隐藏的文本。 --- -此页面展示了如何 **使用 Python 替换 PDF 中的文本**,借助 Aspose.PDF for Python via .NET。 +此页面展示了如何使用 Aspose.PDF for Python via .NET **使用 Python 替换 PDF 中的文本**。 当您需要更新文本值、删除不需要的内容、在特定页面区域替换文本,或在多个 PDF 页面上应用文本替换规则时,请使用这些示例。 ## 使用 Python 替换 PDF 中的文本 -### 在 PDF 文档的所有页面中替换文本 +### 在 PDF 文档的所有页面上替换文本 {{% alert color="primary" %}} -您可以尝试使用 Aspose.PDF 在线进行文本搜索和替换 [脱敏应用](https://products.aspose.app/pdf/redaction). +您可以尝试使用 Aspose.PDF 在线进行文本搜索和替换 [编辑隐藏应用](https://products.aspose.app/pdf/redaction). {{% /alert %}} -文本替换是在更新或纠正现有 PDF 文档内容时的常见需求——例如,更改产品名称、修正错别字,或在多个页面中更新术语。 +文本替换是在更新或纠正现有 PDF 文档内容时的常见需求——例如,修改产品名称、修正拼写错误,或在多个页面中更新术语。 Aspose.PDF for Python via .NET 提供了一种强大且高效的方法,可通过编程方式搜索和替换文本 [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber/) 类。 -本示例演示如何在整个 PDF 文档中查找特定短语(在本例中为 "Black cat")的所有出现位置,并将其替换为新的短语("White dog")。 +本例演示了如何在整个 PDF 文档中查找特定短语的所有出现位置(在本例中为“Black cat”),并将其替换为新短语(“White dog”)。 -1. 指定搜索和替换短语。设置您要查找的文本以及要替换为的文本。 +1. 指定搜索和替换短语。设置您想要查找的文本以及要替换的文本。 1. 加载 PDF 文档。 -1. 创建一个 Text Absorber。TextFragmentAbsorber 使用搜索短语进行初始化。它会扫描文档中所有给定短语的实例。 -1. 将 Absorber 应用于所有页面。这会遍历所有页面并收集匹配该短语的文本片段。 -1. 替换每个找到的片段。每个 “Black cat” 实例都应更改为 “White dog”。 +1. 创建 Text Absorber。TextFragmentAbsorber 使用搜索短语进行初始化。它扫描文档中所有给定短语的实例。 +1. 将吸收器应用于所有页面。这将在所有页面上遍历并收集与该短语匹配的文本片段。 +1. 替换每个找到的片段。每个出现的“Black cat”都应更改为“White dog”。 1. 保存已更新的 PDF。 ```python @@ -64,18 +64,18 @@ def replace_text_on_all_pages(infile, outfile): ### 在特定页面区域替换文本 -有时,您可能需要仅在 PDF 页面的特定区域内替换文本,而不是搜索整个文档——例如,更新已知位置中的页眉、页脚或表格单元格。 +有时,您可能只需要在 PDF 页面中的特定区域内替换文本,而不是搜索整个文档——例如,更新已知位置的页眉、页脚或表格单元格。 -Aspose.PDF for Python via .NET 库通过利用该功能来实现 [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber/) 与基于区域的文本搜索相结合。 +Aspose.PDF for Python via .NET 库通过利用实现此功能 [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber/) 与基于区域的文本搜索相结合。 -本示例演示了如何在特定页面的已定义矩形区域内查找并替换目标短语的所有出现。 +本示例演示了如何在特定页面的指定矩形区域内查找并替换目标短语的所有出现。 1. 指定搜索和替换短语。 1. 加载 PDF 文档。 -1. 创建 Text Absorber 以进行搜索。初始化 TextFragmentAbsorber 来查找所需的文本。 +1. 创建一个 Text Absorber 用于搜索。初始化一个 TextFragmentAbsorber 来查找所需的文本。 1. 限制搜索区域。矩形指定页面上的 x 和 y 坐标限制。 -1. 将 Absorber 应用于特定页面。此操作在指定区域内执行搜索并收集匹配的文本片段。 -1. 替换已找到的文本。定义区域内的每个 'doc' 出现都变成 'DOC'。 +1. 将 Absorber 应用于特定页面。这将在指定区域执行搜索并收集匹配的文本片段。 +1. 替换已找到的文本。 在定义的区域内,所有出现的 'doc' 都将变为 'DOC'。 1. 保存已更新的 PDF。 ```python @@ -102,13 +102,13 @@ def replace_text_in_particular_page_region(infile, outfile): ### 在不更改字体大小的情况下调整和移动文本 在 PDF 中替换文本时,有时您希望在不修改字体大小的情况下,将新文本适配或重新定位到特定区域内。 -Aspose.PDF for Python via .NET 提供了调整文本布局和间距的选项,同时保持原始字体大小不变。 +Aspose.PDF for Python via .NET 提供了在保持原始字体大小不变的情况下调整文本布局和间距的选项。 1. 加载 PDF 文档。 1. 使用 'TextFragmentAbsorber' 收集页面上的所有文本片段。 1. 选择要修改的片段。 -1. 移动并调整文本矩形的大小。 -1. 调整文字间距。启用间距调整以使文字适应修改后的矩形。 +1. 平移并调整文本矩形的大小。 +1. 调整文字间距。启用间距调整以使文本适应修改后的矩形。 1. 替换片段文本。 1. 保存已更新的 PDF。 @@ -136,12 +136,12 @@ def replace_text_and_resize_and_shift_without_changing_font_size(infile, outfile ### 在 PDF 中调整段落大小并移动 -在处理 PDF 时,有时需要替换或扩展段落,同时保持其在页面布局中的视觉对齐。Aspose.PDF 允许您调整段落的边界矩形大小并调节间距以适应新文本,且无需更改字体大小。 +在处理 PDF 时,有时需要替换或扩展段落,同时保持其在页面布局中的视觉对齐。Aspose.PDF 允许您调整段落的边界矩形大小并调整间距以适应新文本,且无需更改字体大小。 1. 加载 PDF 文档。 -1. 使用 'TextFragmentAbsorber' 在页面上收集所有文本片段。 +1. 使用 'TextFragmentAbsorber' 收集页面上的所有文本片段。 1. 选择要修改的片段。 -1. 调整并移动段落。使用页面的媒体框来确定边界并调整矩形。 +1. 调整段落的大小和位置。使用页面的媒体框来确定边界并调整矩形。 1. 调整间距。此操作修改单词/字母之间的间距,而不是更改字体大小。 1. 替换片段文本。 1. 保存已修改的 PDF。 @@ -171,7 +171,7 @@ def replace_text_and_resize_and_shift_paragraph(infile, outfile): ### 替换文本并自动扩展字体以填满目标区域 -在 PDF 中替换文本,同时自动调整大小并扩展字体以填满特定矩形区域。使用 Aspose.PDF for Python via .NET 库,代码会动态调整字体大小和间距,使新文本内容完美适配定义的边界框 — 无需手动计算字体。 +在 PDF 中替换文本,同时自动调整大小并扩展字体以填满特定的矩形区域。使用 Aspose.PDF for Python via .NET 库,代码会动态调整字体大小和间距,使新文本内容恰好适配定义的边界框 —​— 无需手动计算字体。 1. 加载 PDF。 1. 捕获文本片段。 @@ -205,15 +205,15 @@ def replace_text_and_resize_and_expand_font(infile, outfile): ### 替换文本并将其适配到矩形中 -在 PDF 文档中替换文本,同时确保新内容适配原始文本的矩形区域,必要时自动减小字体大小。 +在 PDF 文档中替换文本,同时通过在需要时自动减小字体大小,确保新内容适应原始文本的矩形区域。 -使用 Aspose.PDF for Python via .NET 库,此功能动态调整文本布局和字体大小,同时保持文档结构并防止溢出。 +使用 Aspose.PDF for Python via .NET 库,此函数动态调整文本布局和字体大小,保留文档结构并防止溢出。 -1. 创建一个 TextFragmentAbsorber 对象以提取第一页的所有文本片段。 +1. 创建一个 TextFragmentAbsorber 对象以提取第一页中的所有文本片段。 1. 访问特定文本片段。 1. 设置替换区域。 1. 配置文本调整选项。设置两个关键的替换选项: - - 字体大小调整 - 'SHRINK_TO_FIT' 在新文本过长时会自动缩小字体大小。 + - 字体大小调整 - 'SHRINK_TO_FIT' 如果新文本太长,将自动减少字体大小。 - 间距调整 - 'ADJUST_SPACE_WIDTH' 保持间距比例。 1. 替换文本。 1. 保存已修改的 PDF。 @@ -242,14 +242,14 @@ def replace_text_and_fit_text_into_rectangle(infile, outfile): ### 自动替换占位符文本并重新排列 PDF 布局 -将 PDF(例如模板或表单)中的占位符文本替换为实际数据,如姓名或公司信息。 +将 PDF(例如模板或表单)中的占位符文本替换为实际数据,例如姓名或公司信息。 它会自动调整页面布局以适应新文本,同时应用自定义格式(字体、颜色、大小)。 1. 导入并加载 PDF。 1. 为占位符创建 Text Absorber。 -1. 将 Absorber 应用于所有页面。 -1. 循环遍历找到的文本片段。 -1. 应用自定义文本格式。 +1. 将吸收器应用于所有页面。 +1. 遍历已找到的 TextFragment。 +1. 应用自定义文本格式化。 1. 保存已更新的文档。 ```python @@ -274,20 +274,20 @@ def automatically_rearrange_page_contents(input_file, output_file): document.save(output_file) ``` -### 根据正则表达式替换文本 +### 基于正则表达式替换文本 -在处理 PDF 文档时,您可能需要替换符合特定模式的文本,而不是特定短语——例如,电话号码、代码或类似日期的格式。 +在处理 PDF 文档时,您可能需要替换符合特定模式的文本,而不是特定的短语——例如,电话号码、代码或类似日期的格式。 -Aspose.PDF for Python via .NET 允许您使用 TextFragmentAbsorber 类结合正则表达式(regex)进行此类替换。 +Aspose.PDF for Python via .NET 允许您使用 TextFragmentAbsorber 类结合正则表达式(regex)执行此类替换。 -此示例演示如何查找文本模式(在本例中,任何匹配格式 ####-#### 的文本,例如 1234-5678),并将其替换为格式化字符串 'ABC1-2XZY'。它还展示了如何自定义替换后文本的字体、颜色和大小。 +本示例演示了如何查找文本模式(在本例中,匹配格式 ####-#### 的任意文本,例如 1234-5678),并将其替换为格式化字符串 'ABC1-2XZY'。它还展示了如何自定义替换后文本的字体、颜色和大小。 -以下代码片段展示了如何基于正则表达式替换文本。 +以下代码片段向您展示如何基于正则表达式替换文本。 1. 加载 PDF 文档。 1. 创建一个基于正则表达式的 Text Absorber。使用正则表达式模式初始化 TextFragmentAbsorber。 -1. 启用正则表达式模式。'True' 参数会激活正则表达式搜索模式。 -1. 将 Absorber 应用于页面。这将在页面上扫描所有与定义的正则表达式模式匹配的文本片段。 +1. 启用正则表达式模式。'True' 参数激活正则表达式搜索模式。 +1. 将 Absorber 应用于页面。此操作会扫描页面中所有匹配定义的正则表达式模式的文本片段。 1. 将每个匹配项替换为新文本并应用自定义样式。 1. 保存已修改的文档。 @@ -312,20 +312,20 @@ def replace_text_based_on_regex(infile, outfile): document.save(outfile) ``` -## 替换字体或删除未使用的字体 +## 替换字体或移除未使用的字体 ### 替换现有 PDF 文件中的字体 -有时,您需要在 PDF 中统一或更新字体——例如,用更易获取的字体替换过时或专有的字体。Aspose.PDF for Python via .NET 库允许您以编程方式检测并替换字体,确保排版一致性和文档兼容性。 +有时,您需要在 PDF 中统一或更新字体——例如,将过时或专有的字体替换为更易获取的字体。Aspose.PDF for Python via .NET 库允许您以编程方式检测和替换字体,确保排版一致性和文档兼容性。 -本示例演示如何在整个 PDF 文档中将特定字体的所有实例(例如 'Arial-BoldMT')替换为另一种字体(例如 'Verdana')。 +此示例演示如何在 PDF 文档中将所有特定字体(例如 'Arial-BoldMT')替换为另一种字体(例如 'Verdana')。 -以下代码片段展示了如何在 PDF 文档中替换 Font: +以下代码片段展示了如何替换 PDF 文档中的字体: 1. 打开 PDF 文档。 1. 初始化 TextFragmentAbsorber。 1. 使用 Absorber 从文档的每一页中提取文本片段。 -1. 识别并替换字体。脚本检查片段的当前字体是否为 'Arial-BoldMT'。如果是,则使用 FontRepository.find_font() 方法将其替换为 'Verdana' 字体。 +1. 识别并替换字体。脚本检查片段的当前字体是否为 'Arial-BoldMT'。如果为真,它使用 FontRepository.find_font() 方法将其替换为 'Verdana' 字体。 1. 保存已修改的文档。 ```python @@ -347,23 +347,23 @@ def replace_fonts(infile, outfile): ### 删除未使用的字体 -随着时间的推移,PDF 文档可能会积累未使用或嵌入的字体,这会增加文件大小并降低处理速度。这些未使用的字体即使在进行文本编辑或替换后仍常常保留,尤其是在处理大型或复杂的 PDF 时。 +随着时间的推移,PDF 文档可能会累积未使用或已嵌入的字体,这会增加文件大小并减慢处理速度。这些未使用的字体即使在文本编辑或替换后仍然存在,尤其是在处理大型或复杂的 PDF 时。 -Aspose.PDF for Python via .NET 库提供了一种使用 TextEditOptions 类删除此类冗余字体的高效方法。这不仅优化了您的文档,还确保仅使用实际应用于可见文本的字体。 +Aspose.PDF for Python via .NET 库提供了一种高效的方法,可使用 TextEditOptions 类删除此类冗余字体。这不仅优化了您的文档,还确保仅使用实际应用于可见文本的字体。 -‘remove_unused_fonts()’ 方法是一种简单但强大的方式,通过删除冗余字体数据来优化 PDF 文件。 +‘remove_unused_fonts()’ 方法是一种简单而强大的方式,通过移除冗余的字体数据来优化 PDF 文件。 本示例演示如何: -- 扫描 PDF 以查找未使用的字体。 -- 安全地将它们移除。 +- 扫描 PDF 中未使用的字体。 +- 安全地删除它们。 - 将活动文本片段重新分配为一致的字体(例如,Times New Roman)。 1. 打开 PDF 文档。 -1. 配置文本编辑选项。这指示引擎删除任何当前未在可见文本中使用的嵌入字体。 -1. 创建一个带有选项的 Text Absorber。TextFragmentAbsorber 从文档中提取文本片段以进行编辑。 -1. 重新分配标准字体。一旦吸收器收集了所有片段,遍历它们并应用一致的字体。 -1. 保存已清理的 PDF。 +1. 配置文本编辑选项。这指示引擎删除当前在可见文本中未使用的任何嵌入字体。 +1. 创建带有选项的 Text Absorber。TextFragmentAbsorber 用于从文档中提取文本片段以进行编辑。 +1. 重新分配标准字体。一旦吸收器收集了所有片段,遍历它们并应用统一的字体。 +1. 保存清理后的 PDF。 ```python import sys @@ -395,14 +395,14 @@ def remove_unused_fonts(input_file, output_file): ## 删除所有文本 -### 从 PDF 中删除文本 +### 从 PDF 中移除文本 -从 PDF 文件中删除所有文本内容,同时保留图像、形状和布局结构完整。 -通过使用 TextFragmentAbsorber,代码能够高效地扫描整个文档并删除每页上找到的所有文本片段。 +从 PDF 文件中删除所有文本内容,同时保持图像、形状和布局结构完整。 +通过使用 TextFragmentAbsorber,代码高效地扫描整个文档,并删除每页上找到的所有文本片段。 1. 加载 PDF 文档。 -1. 创建一个 TextFragmentAbsorber 对象以检测并处理 PDF 中的文本片段。 -1. 删除所有文本内容。方法 ‘absorber.remove_all_text()’ 会从已加载的文档中移除所有文本元素,保持非文本组件不受影响。 +1. 创建了一个 TextFragmentAbsorber 对象,用于检测和处理 PDF 中的文本片段。 +1. 移除所有文本内容。方法 'absorber.remove_all_text()' 从已加载的文档中删除每个文本元素,保留非文本组件不变。 1. 保存已更新的文档。 ```python @@ -420,11 +420,11 @@ def remove_all_text_using_absorber1(infile, outfile): ### 删除特定页面上的所有文本 使用 Aspose.PDF 中的 TextFragmentAbsorber 类从 PDF 文档的单页中删除所有文本。 -与全文删除不同,此方法执行页面级文本清理,仅删除所选页面的文本,而保持其他所有页面不受影响。 +与完整文档的删除不同,此方法执行页面级文本清理,仅从所选页面删除文本,其他页面保持不变。 1. 加载 PDF 文件。 1. 创建一个 TextFragmentAbsorber 实例。 -1. 删除第一页的所有文本。 +1. 从第一页删除所有文本。 1. 保存已修改的 PDF。 ```python @@ -439,10 +439,10 @@ def remove_all_text_using_absorber2(infile, outfile): document.save(outfile) ``` -### 从 PDF 页面中的特定区域删除所有文本 +### 从 PDF 页面上的特定区域删除所有文本 使用 Aspose.PDF 的 TextFragmentAbsorber 从页面的特定矩形区域中删除所有文本。 -此方法不是清除整页,而是执行针对性的文本删除,允许精确控制受影响的页面部分。 +此方法并非清除整页,而是执行针对性的文本删除,能够精确控制受影响的页面部分。 1. 加载 PDF 文档。 1. 创建一个 TextFragmentAbsorber。 @@ -465,10 +465,10 @@ def remove_all_text_using_absorber3(infile, outfile): document.save(outfile) ``` -### 从 PDF 文档中移除所有隐藏的 Text +### 从 PDF 文档中删除所有隐藏的文本 使用 Aspose.PDF 的 TextFragmentAbsorber 从页面的特定矩形区域中删除所有文本。 -此方法不是清除整页,而是执行针对性的文本删除,允许精确控制受影响的页面部分。 +此方法并非清除整页,而是执行针对性的文本删除,能够精确控制受影响的页面部分。 1. 加载 PDF 文档。 1. 创建一个 TextFragmentAbsorber。 diff --git a/zh/python-net/advanced-operations/working-with-text/rotate-text-inside-pdf/_index.md b/zh/python-net/advanced-operations/working-with-text/rotate-text-inside-pdf/_index.md index 8ed7e4f636..7a3a698aee 100644 --- a/zh/python-net/advanced-operations/working-with-text/rotate-text-inside-pdf/_index.md +++ b/zh/python-net/advanced-operations/working-with-text/rotate-text-inside-pdf/_index.md @@ -1,315 +1,288 @@ --- -title: 在 PDF 中旋转文本使用 Python -linktitle: 在 PDF 中旋转文本 +title: 在 Python 中旋转 PDF 文本 +linktitle: 旋转 PDF 内的文本 type: docs weight: 50 url: /zh/python-net/rotate-text-inside-pdf/ -description: 学习不同的方法在 PDF 中旋转文本。Aspose.PDF 允许您旋转文本到任何角度,旋转文本片段或整个段落。 -lastmod: "2024-02-17" +description: 了解如何在 Python 中旋转 PDF 文档内的文本片段和段落。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 旋转 PDF 文档中的文本片段和段落 +Abstract: 本文解释了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中旋转文本。它展示了如何在 `TextFragment` 上设置 `rotation` 属性,使用 `TextBuilder` 和 `TextParagraph` 构建旋转内容,并将旋转文本直接添加到页面段落中以适应不同的布局场景。 --- - - - -## 使用旋转属性在PDF中旋转文本 - -通过使用[TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment)类的旋转属性,您可以在不同的角度旋转文本。在文档生成的不同场景中可以使用文本旋转。您可以指定旋转角度以根据您的需求旋转文本。请查看以下不同的场景,您可以在其中实现文本旋转。 - -## 使用TextFragment和TextBuilder实现旋转 - -```csharp -// 有关完整的示例和数据文件,请访问https://github.com/aspose-pdf/Aspose.PDF-for-.NET -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -// 初始化文档对象 -Document pdfDocument = new Document(); -// 获取特定页面 -Page pdfPage = (Page)pdfDocument.Pages.Add(); -// 创建文本片段 -TextFragment textFragment1 = new TextFragment("main text"); -textFragment1.Position = new Position(100, 600); -// 设置文本属性 -textFragment1.TextState.FontSize = 12; -textFragment1.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -// 创建旋转的文本片段 -TextFragment textFragment2 = new TextFragment("rotated text"); -textFragment2.Position = new Position(200, 600); -// 设置文本属性 -textFragment2.TextState.FontSize = 12; -textFragment2.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -textFragment2.TextState.Rotation = 45; -// 创建旋转的文本片段 -TextFragment textFragment3 = new TextFragment("rotated text"); -textFragment3.Position = new Position(300, 600); -// 设置文本属性 -textFragment3.TextState.FontSize = 12; -textFragment3.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -textFragment3.TextState.Rotation = 90; -// 创建TextBuilder对象 -TextBuilder textBuilder = new TextBuilder(pdfPage); -// 将文本片段附加到PDF页面 -textBuilder.AppendText(textFragment1); -textBuilder.AppendText(textFragment2); -textBuilder.AppendText(textFragment3); -// 保存文档 -pdfDocument.Save(dataDir + "TextFragmentTests_Rotated1_out.pdf"); + +使用 Aspose.PDF for Python via .NET 在 PDF 文档中旋转文本片段。本页展示了如何通过使用来控制文本的位置和旋转。 `TextFragment`, `TextState`,和 `TextBuilder`. 通过调整旋转角度,您可以创建诸如对角线标题、垂直标签和旋转注释等布局。 + +## 使用 TextBuilder 在 PDF 中旋转文本片段 + +创建一个名为…的 PDF 文件 `rotated_fragments.pdf` 包含三个水平对齐的文本片段: + +- 第一段文本未旋转 +- 第二段已旋转45° +- 第三段已旋转90° + +1. 创建一个新的 PDF 文档。 +1. 插入一个新页面来容纳旋转的文本。 +1. 创建第一个文本片段(无旋转)。 +1. 创建第二个文本片段(旋转 45°)。 +1. 创建第三个文本片段(旋转 90°)。 +1. 使用添加文本片段 `TextBuilder`. +1. 保存文档。 + +```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) ``` +## 在 PDF 中旋转段落内的单个文本片段 + +在段落中旋转单个文本片段。它展示了如何构建包含多个片段(TextParagraph)的多行段落(TextFragment),每个片段都有自己的旋转角度。此技术可用于创建视觉丰富的文档,结合水平和对角线方向的文本——例如,样式化标题、图表或带注释的标签。 + +创建一个名为的 PDF `rotated_paragraph_fragments.pdf` 包含一个段落,其中有三行文本,每行的旋转角度不同: + +- 第一行旋转45° +- 第二行保持水平 (0°) +- 第三行旋转-45° + +1. 创建一个新的 PDF 文档。 +1. 在旋转文本出现的地方添加一个空白页。 +1. 创建一个 `TextParagraph`. +1. 创建并配置第一个文本片段(+45° 旋转)。 +1. 创建第二个文本片段(无旋转)。 +1. 创建第三个文本片段(-45° 旋转)。 +1. 将文本片段附加到段落。 +1. 使用以下方法将段落添加到页面 `TextBuilder`. +1. 保存文档。 + +```python +import aspose.pdf as ap -## 使用 TextParagraph 和 TextBuilder 实现旋转(旋转的片段) - -```csharp -// 有关完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -// 初始化文档对象 -Document pdfDocument = new Document(); -// 获取特定页面 -Page pdfPage = (Page)pdfDocument.Pages.Add(); -TextParagraph paragraph = new TextParagraph(); -paragraph.Position = new Position(200, 600); -// 创建文本片段 -TextFragment textFragment1 = new TextFragment("rotated text"); -// 设置文本属性 -textFragment1.TextState.FontSize = 12; -textFragment1.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -// 设置旋转 -textFragment1.TextState.Rotation = 45; -// 创建文本片段 -TextFragment textFragment2 = new TextFragment("main text"); -// 设置文本属性 -textFragment2.TextState.FontSize = 12; -textFragment2.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -// 创建文本片段 -TextFragment textFragment3 = new TextFragment("another rotated text"); -// 设置文本属性 -textFragment3.TextState.FontSize = 12; -textFragment3.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -// 设置旋转 -textFragment3.TextState.Rotation = -45; -// 将文本片段添加到段落中 -paragraph.AppendLine(textFragment1); -paragraph.AppendLine(textFragment2); -paragraph.AppendLine(textFragment3); -// 创建 TextBuilder 对象 -TextBuilder textBuilder = new TextBuilder(pdfPage); -// 将文本段落添加到 PDF 页面 -textBuilder.AppendParagraph(paragraph); -// 保存文档 -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) ``` +## 在 PDF 中使用页面段落旋转文本 + +本节演示了一种使用 Aspose.PDF for Python via .NET 在 PDF 中旋转文本的简化方法。 +不同于采用低层次方法的 `TextBuilder` 或 `TextParagraph`,此方法直接将旋转的文本片段添加到页面的段落集合中(`page.paragraphs`). 当您需要基本文本旋转而不需要精确定位或段落结构时,它是理想的。 + +生成一个名为 `simple_rotated_text.pdf` 包含: + +- 一个主要的水平文本片段,旋转角度为 0° +- 315° 旋转片段 +- 270° 旋转片段 + +1. 初始化一个新的 PDF 文档。 +1. 创建一个页面以放置旋转的文本。 +1. 创建第一个文本片段(无旋转)。 +1. 创建第二个文本片段(315° 旋转)。 +1. 创建第三个文本片段(270° 旋转)。 +1. 直接将文本片段添加到页面段落。 +1. 保存 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) -## 实现使用 TextFragment 和 Page.Paragraphs 的旋转 - -```csharp -// 有关完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -// 初始化文档对象 -Document pdfDocument = new Document(); -// 获取特定页面 -Page pdfPage = (Page)pdfDocument.Pages.Add(); -// 创建文本片段 -TextFragment textFragment1 = new TextFragment("main text"); -// 设置文本属性 -textFragment1.TextState.FontSize = 12; -textFragment1.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -// 创建文本片段 -TextFragment textFragment2 = new TextFragment("rotated text"); -// 设置文本属性 -textFragment2.TextState.FontSize = 12; -textFragment2.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -// 设置旋转 -textFragment2.TextState.Rotation = 315; -// 创建文本片段 -TextFragment textFragment3 = new TextFragment("rotated text"); -// 设置文本属性 -textFragment3.TextState.FontSize = 12; -textFragment3.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -// 设置旋转 -textFragment3.TextState.Rotation = 270; -pdfPage.Paragraphs.Add(textFragment1); -pdfPage.Paragraphs.Add(textFragment2); -pdfPage.Paragraphs.Add(textFragment3); -// 保存文档 -pdfDocument.Save(dataDir + "TextFragmentTests_Rotated3_out.pdf"); + # Save the document + document.save(outfile) ``` +## 在 PDF 中旋转整个段落 + +此示例演示了在 PDF 中的高级段落级文本旋转。不同于片段级旋转(每个文本片段单独旋转),此方法将整个段落作为统一块以不同角度进行旋转。 +每个段落包含多个样式化的文本片段,整个段落会以特定角度旋转——从而实现复杂且一致的布局转换。 +这非常适用于艺术布局、水印或设计密集的 PDF,在这些情况下,需要将整段文本以不同方向进行排版。 + +创建 `rotated_paragraphs.pdf`,包含四个完整样式和旋转的段落: + +- 每个都以唯一的角度旋转(45°、135°、225°和315°) +- 每段包含三行文字,具有彩色背景、下划线和一致的样式 + +1. 创建一个新的 PDF 文档。 +1. 添加一个空白页以容纳旋转的段落。 +1. 迭代以创建多个段落。 +1. 创建并定位段落。 +1. 创建具有格式的文本片段。 +1. 应用文本格式化。 +1. 向段落添加文本片段。 +1. 使用将段落追加到页面 `TextBuilder`. +1. 对所有四个旋转重复此操作。 +1. 保存 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) -## 使用 TextParagraph 和 TextBuilder 实现旋转(整段旋转) - -```csharp -// 有关完整示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -// 初始化文档对象 -Document pdfDocument = new Document(); -// 获取特定页面 -Page pdfPage = (Page)pdfDocument.Pages.Add(); -for (int i = 0; i < 4; i++) -{ - TextParagraph paragraph = new TextParagraph(); - paragraph.Position = new Position(200, 600); - // 指定旋转 - paragraph.Rotation = i * 90 + 45; - // 创建文本片段 - TextFragment textFragment1 = new TextFragment("段落文本"); - // 创建文本片段 - textFragment1.TextState.FontSize = 12; - textFragment1.TextState.Font = FontRepository.FindFont("TimesNewRoman"); - textFragment1.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray; - textFragment1.TextState.ForegroundColor = Aspose.Pdf.Color.Blue; - // 创建文本片段 - TextFragment textFragment2 = new TextFragment("第二行文本"); - // 设置文本属性 - textFragment2.TextState.FontSize = 12; - textFragment2.TextState.Font = FontRepository.FindFont("TimesNewRoman"); - textFragment2.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray; - textFragment2.TextState.ForegroundColor = Aspose.Pdf.Color.Blue; - // 创建文本片段 - TextFragment textFragment3 = new TextFragment("还有更多文本..."); - // 设置文本属性 - 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); - // 创建 TextBuilder 对象 - TextBuilder textBuilder = new TextBuilder(pdfPage); - // 将文本片段附加到 PDF 页面 - textBuilder.AppendParagraph(paragraph); -} -// 保存文档 -pdfDocument.Save(dataDir + "TextFragmentTests_Rotated4_out.pdf"); + # Save the document + document.save(outfile) ``` +## 相关文本主题 - \ No newline at end of file +- [使用 Python 在 PDF 中处理文本](/pdf/zh/python-net/working-with-text/) +- [向 PDF 添加文本](/pdf/zh/python-net/add-text-to-pdf-file/) +- [在 Python 中格式化 PDF 文本](/pdf/zh/python-net/text-formatting-inside-pdf/) +- [使用 Python 替换 PDF 中的文本](/pdf/zh/python-net/replace-text-in-pdf/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-text/seach-and-get-text-from-pdf/_index.md b/zh/python-net/advanced-operations/working-with-text/seach-and-get-text-from-pdf/_index.md index 24c2b5ae92..ff5adc1993 100644 --- a/zh/python-net/advanced-operations/working-with-text/seach-and-get-text-from-pdf/_index.md +++ b/zh/python-net/advanced-operations/working-with-text/seach-and-get-text-from-pdf/_index.md @@ -1,556 +1,430 @@ --- -title: 从PDF页面中搜索并获取文本 +title: 在 Python 中搜索并提取 PDF 文本 linktitle: 搜索并获取文本 type: docs weight: 60 url: /zh/python-net/search-and-get-text-from-pdf/ -description: 本文解释了如何使用各种工具从Aspose.PDF for .NET中搜索和获取文本。 -lastmod: "2024-02-17" +description: 了解如何在 Python 中搜索、检查和提取 PDF 文档中的文本。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中搜索 PDF 文本并检查提取的片段 +Abstract: 本文说明了如何使用 Aspose.PDF for Python via .NET 对 PDF 文档进行搜索和提取文本。它涵盖了 `TextAbsorber` 和 `TextFragmentAbsorber`,包括基于区域的提取、特定页面的搜索、短语匹配,以及对文本位置和字体属性的检查。 --- - - - -## 从 PDF 文档的所有页面搜索并获取文本 - -[TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber) 类允许您从 PDF 文档的所有页面中查找与特定短语匹配的文本。为了从整个文档中搜索文本,您需要调用 Pages 集合的 Accept 方法。 [Accept](https://reference.aspose.com/pdf/python-net/aspose.pdf.page/accept/methods/3) 方法接受 TextFragmentAbsorber 对象作为参数,该对象返回 TextFragment 对象的集合。您可以遍历所有的片段并获取它们的属性,如文本、位置(XIndent、YIndent)、字体名称、字体大小、是否可访问、是否嵌入、是否子集、前景色等。 - -以下代码片段向您展示如何从所有页面搜索文本。 - -```csharp -// 有关完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// 文档目录的路径。 -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); - -// 打开文档 -Document pdfDocument = new Document(dataDir + "SearchAndGetTextFromAll.pdf"); - -// 创建 TextAbsorber 对象以查找输入搜索短语的所有实例 -TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("text"); - -// 接受所有页面的吸收器 -pdfDocument.Pages.Accept(textFragmentAbsorber); - -// 获取提取的文本片段 -TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; - -// 遍历片段 -foreach (TextFragment textFragment in textFragmentCollection) -{ - - Console.WriteLine("Text : {0} ", textFragment.Text); - Console.WriteLine("Position : {0} ", textFragment.Position); - Console.WriteLine("XIndent : {0} ", textFragment.Position.XIndent); - Console.WriteLine("YIndent : {0} ", textFragment.Position.YIndent); - Console.WriteLine("Font - Name : {0}", textFragment.TextState.Font.FontName); - Console.WriteLine("Font - IsAccessible : {0} ", textFragment.TextState.Font.IsAccessible); - Console.WriteLine("Font - IsEmbedded : {0} ", textFragment.TextState.Font.IsEmbedded); - Console.WriteLine("Font - IsSubset : {0} ", textFragment.TextState.Font.IsSubset); - Console.WriteLine("Font Size : {0} ", textFragment.TextState.FontSize); - Console.WriteLine("Foreground Color : {0} ", textFragment.TextState.ForegroundColor); -} -``` +## 从 PDF 中搜索文本 -如果您需要在特定 PDF 页面内搜索文本,请从 Document 实例的页面集合中指定页面编号,并对该页面调用 Accept 方法(如下面的代码行所示)。 +使用 … 在 PDF 文档中搜索并提取定义的矩形区域的文本 `TextAbsorber` 类。它使用纯文本格式模式,以获得干净、未格式化的输出,这对于从结构化区域(如页眉、页脚或表格区域)提取内容非常有用。通过组合 `TextExtractionOptions` 和 `TextSearchOptions` 使用矩形约束,您可以控制文本的提取位置和方式。 -```csharp -// 如需完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// 对特定页面应用吸收器 -pdfDocument.Pages[2].Accept(textFragmentAbsorber); -``` +当您需要审计 PDF 文本内容、提取用于分析的文本,或检查匹配文本片段的位置和格式时,请使用此页面。 -## 从 PDF 文档的所有页面搜索并获取文本片段 - -为了从所有页面搜索文本片段,您首先需要从文档中获取 TextFragment 对象。 - TextFragmentAbsorber 允许您从 PDF 文档的所有页面中查找匹配特定短语的文本。为了从整个文档中搜索文本,您需要调用 Pages 集合的 Accept 方法。Accept 方法将 TextFragmentAbsorber 对象作为参数,该对象返回一个 TextFragment 对象的集合。一旦从文档中获取了 TextFragmentCollection,您需要遍历这个集合并获取每个 TextFragment 对象的 TextSegmentCollection。之后,您可以获取每个 TextSegment 对象的所有属性。以下代码片段向您展示了如何从所有页面中搜索文本片段。 - -```csharp -// 有关完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// 文档目录的路径。 -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); - -// 打开文档 -Document pdfDocument = new Document(dataDir + "SearchAndGetTextPage.pdf"); - -// 创建 TextAbsorber 对象以查找输入搜索短语的所有实例 -TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("Figure"); -// 对所有页面接受吸收器 -pdfDocument.Pages.Accept(textFragmentAbsorber); -// 获取提取的文本片段 -TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; -// 遍历片段 -foreach (TextFragment textFragment in textFragmentCollection) -{ - foreach (TextSegment textSegment in textFragment.Segments) - { - Console.WriteLine("Text : {0} ", textSegment.Text); - Console.WriteLine("Position : {0} ", textSegment.Position); - Console.WriteLine("XIndent : {0} ", textSegment.Position.XIndent); - Console.WriteLine("YIndent : {0} ", textSegment.Position.YIndent); - Console.WriteLine("Font - Name : {0}", textSegment.TextState.Font.FontName); - Console.WriteLine("Font - IsAccessible : {0} ", textSegment.TextState.Font.IsAccessible); - Console.WriteLine("Font - IsEmbedded : {0} ", textSegment.TextState.Font.IsEmbedded); - Console.WriteLine("Font - IsSubset : {0} ", textSegment.TextState.Font.IsSubset); - Console.WriteLine("Font Size : {0} ", textSegment.TextState.FontSize); - Console.WriteLine("Foreground Color : {0} ", textSegment.TextState.ForegroundColor); - } -} -``` +1. 使用 'ap.Document' 加载 PDF 文件。 +1. 配置文本提取选项。 +1. 使用矩形约束定义搜索区域。 +1. 创建并配置 TextAbsorber。 +1. 处理文档中的所有页面。 +1. 检索并显示提取的文本。 + +```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)) -为了从 PDF 的特定页面搜索和获取 TextSegments,您需要在调用 Accept(..) 方法时指定特定的页面索引。请查看以下代码行。 + absorber = ap.text.TextAbsorber(text_extraction_options, text_search_options) -```csharp -// 有关完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// 接受所有页面的吸收器 -pdfDocument.Pages[2].Accept(textFragmentAbsorber); + # Process all pages + document.pages.accept(absorber) + + print(f"Text fragments found: {absorber.text}") ``` -## 使用正则表达式搜索并从所有页面获取文本 +## 从特定 PDF 页面搜索文本 -TextFragmentAbsorber 帮助您基于正则表达式搜索和检索所有页面的文本。 - 首先,你需要将正则表达式作为短语传递给 TextFragmentAbsorber 构造函数。之后,你需要设置 TextFragmentAbsorber 对象的 TextSearchOptions 属性。该属性需要 TextSearchOptions 对象,并且在创建新对象时需要将 true 作为参数传递给其构造函数。由于你想从所有页面中检索匹配的文本,因此需要调用 Pages 集合的 Accept 方法。TextFragmentAbsorber 返回一个 TextFragmentCollection,其中包含所有符合正则表达式指定的条件的片段。以下代码片段展示了如何基于正则表达式搜索并获取所有页面的文本。 +使用 Aspose.PDF 的 TextAbsorber 在 PDF 中搜索并提取特定页面和区域的文本。它针对文档的第 2 页,只提取在定义的矩形区域内找到的文本。 +通过结合 TextExtractionOptions(用于格式控制)和 TextSearchOptions(用于区域限制),您可以高效地执行精确的、针对特定页面的文本提取。 -```csharp -// 有关完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// 文档目录的路径。 -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); +1. 加载 PDF 文档。 +1. 设置文本提取选项。 +1. 将文本提取限制在页面的特定矩形区域。 +1. 创建并配置 TextAbsorber。 +1. 处理特定页面。 +1. 检索并显示提取的文本。 -// 打开文档 -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 -// 创建 TextAbsorber 对象以查找所有与正则表达式匹配的短语 -TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("\\d{4}-\\d{4}"); // 如 1999-2000 +def text_absorber_search_page(input_file_path): + document = ap.Document(input_file_path) -// 设置文本搜索选项以指定正则表达式使用 -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) -// 接受所有页面的吸收器 -pdfDocument.Pages.Accept(textFragmentAbsorber); + # Only page 2 + document.pages[2].accept(absorber) -// 获取提取的文本片段 -TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; + print(f"Text fragments found: {absorber.text}") +``` -// 遍历片段 -foreach (TextFragment textFragment in textFragmentCollection) -{ - Console.WriteLine("Text : {0} ", textFragment.Text); - Console.WriteLine("Position : {0} ", textFragment.Position); - Console.WriteLine("XIndent : {0} ", textFragment.Position.XIndent); - Console.WriteLine("YIndent : {0} ", textFragment.Position.YIndent); - Console.WriteLine("Font - Name : {0}", textFragment.TextState.Font.FontName); - Console.WriteLine("Font - IsAccessible : {0} ", textFragment.TextState.Font.IsAccessible); - Console.WriteLine("Font - IsEmbedded : {0} ", textFragment.TextState.Font.IsEmbedded); - Console.WriteLine("Font - IsSubset : {0} ", textFragment.TextState.Font.IsSubset); - Console.WriteLine("Font Size : {0} ", textFragment.TextState.FontSize); - Console.WriteLine("Foreground Color : {0} ", textFragment.TextState.ForegroundColor); -} +## 分析并提取 PDF 中的详细文本片段属性 + +与提取原始文本的 TextAbsorber 不同,TextFragmentAbsorber 提供关于每个文本片段的详细低层信息——例如其位置、字体属性、颜色以及嵌入细节。 + +1. 加载 PDF 文档。 +1. 初始化 TextFragmentAbsorber。 +1. 处理文档中的所有页面。 +1. 遍历提取的文本片段。 +1. 打印基本文本信息。 +1. 打印字体和格式详情。 + +```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 -// 有关完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -TextFragmentAbsorber textFragmentAbsorber; -// 为了精确匹配一个单词,您可以考虑使用正则表达式。 -textFragmentAbsorber = new TextFragmentAbsorber(@"\bWord\b", new TextSearchOptions(true)); +## 在单个 PDF 页面上搜索特定文本短语 + +使用 TextFragmentAbsorber 在 PDF 文档的单页中搜索特定文本短语。不同于搜索整个文档,这种方法仅限制在单页内进行搜索,从而更高效地确认文本在诸如页眉、页脚或特定内容区域等目标区域中的存在和位置。 -// 为了在大写或小写中搜索字符串,您可以考虑使用正则表达式。 -textFragmentAbsorber = new TextFragmentAbsorber("(?i)Line", new TextSearchOptions(true)); +1. 加载 PDF 文档。 +1. 使用搜索短语初始化 TextFragmentAbsorber。 +1. 将 Absorber 应用于特定页面。 +1. 遍历找到的片段。 -// 为了在 PDF 文档中搜索所有字符串(解析所有字符串),请尝试使用以下正则表达式。 -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 -// 查找搜索字符串的匹配项,并获取字符串之后直到换行符的任何内容。 -textFragmentAbsorber = new TextFragmentAbsorber(@"(?i)the ((.)*)"); +def text_fragment_absorber_search_page(input_file_path): + document = ap.Document(input_file_path) -// 请使用以下正则表达式查找正则表达式匹配后的文本。 -textFragmentAbsorber = new TextFragmentAbsorber(@"(?<=word).*"); + absorber = ap.text.TextFragmentAbsorber("whale") + document.pages[2].accept(absorber) -// 为了在 PDF 文档中搜索超链接/URL,请尝试使用以下正则表达式。 -textFragmentAbsorber = new TextFragmentAbsorber(@"(http|ftp|https):\/\/([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?"); + for fragment in absorber.text_fragments: + print("Text:", fragment.text) + print("Position:", fragment.position) ``` +## 逐页顺序文本搜索及累计结果 -## 基于正则表达式搜索文本并添加超链接 - -如果您想根据正则表达式在文本短语上添加超链接,首先使用 TextFragmentAbsorber 找到与该特定正则表达式匹配的所有短语,并在这些短语上添加超链接。 - -要找到短语并在其上添加超链接: - -1. 将正则表达式作为参数传递给 TextFragmentAbsorber 构造函数。 -2. 创建一个 TextSearchOptions 对象,以指定是否使用正则表达式。 -3. 将匹配的短语获取到 TextFragments 中。 -4. 循环遍历匹配项以获取其矩形尺寸,将前景色更改为蓝色(可选 - 使其看起来像超链接,并使用 PdfContentEditor 类的 CreateWebLink(..) 方法创建链接)。 -5. 使用 Document 对象的 Save 方法保存更新的 PDF。 -以下代码片段展示了如何使用正则表达式搜索 PDF 文件中的文本并在匹配项上添加超链接。 - -```csharp -// 有关完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// 文档目录的路径。 -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -// 创建吸收器对象以查找输入搜索短语的所有实例 -TextFragmentAbsorber absorber = new TextFragmentAbsorber("\\d{4}-\\d{4}"); -// 启用正则表达式搜索 -absorber.TextSearchOptions = new TextSearchOptions(true); -// 打开文档 -PdfContentEditor editor = new PdfContentEditor(); -// 绑定源 PDF 文件 -editor.BindPdf(dataDir + "SearchRegularExpressionPage.pdf"); -// 接受页面的吸收器 -editor.Document.Pages[1].Accept(absorber); - -int[] dashArray = { }; -String[] LEArray = { }; -System.Drawing.Color blue = System.Drawing.Color.Blue; - -// 循环遍历片段 -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(); -``` +使用 Aspose.PDF 的 TextFragmentAbsorber 在 PDF 文档的多页中逐步搜索文本。 +不同于单页或全文件搜索,这种方法允许您按顺序处理页面,逐步收集结果,并在页面特定的上下文中分析文本片段。此方法非常适合大型文档或渐进式处理工作流。 + +1. 加载 PDF 文档。 +1. 初始化 TextFragmentAbsorber 并设置搜索短语。 +1. 处理首页。仅搜索第 1 页。打印文本、页码和位置。提供单独的页面特定结果以确保清晰。 +1. 顺序处理下一页。转到第2页,并可选择继续处理文档的其余部分。\u0027absorber.visit()\u0027 确保累积所有已访问页面的结果。打印累计的搜索结果,显示文本和位置。 +```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_sequential_search(input_file_path): + document = ap.Document(input_file_path) -Aspose.PDF for .NET 支持搜索并获取每个字符或文本片段的坐标的功能。因此,为了确保返回每个字符的坐标,我们可以考虑在每个字符周围突出显示(添加矩形)。 + absorber = ap.text.TextFragmentAbsorber() + absorber.phrase = "whale" -对于文本段落,您可以考虑使用正则表达式来确定段落分隔符并在其周围绘制矩形。请查看以下代码片段。以下代码片段获取每个字符的坐标并在每个字符周围创建一个矩形。 + # 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 -// 有关完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// 文档目录的路径。 -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); + print("--") -// 打开文档 -Document document = new Document(dataDir + "SearchAndGetTextFromAll.pdf"); + # Continue to next page + document.pages[2].accept(absorber) + absorber.visit(document) -// 创建 TextAbsorber 对象以查找所有匹配正则表达式的短语 + for fragment in absorber.text_fragments: + print("Text:", fragment.text) + print("Page:", fragment.page.number) + print("Position:", fragment.position) +``` + +## 在矩形区域内的目标短语搜索 -TextFragmentAbsorber textAbsorber = new TextFragmentAbsorber(@"[\S]+"); +在 PDF 中搜索特定短语,同时将搜索限制在单页的特定矩形区域内。 +通过将短语搜索与空间约束相结合,您可以在指定区域精确定位内容,而无需扫描整页或整份文档。这对于表单、页眉、页脚或内容出现在可预测位置的结构化报告尤为有用。 -TextSearchOptions textSearchOptions = new TextSearchOptions(true); +1. 加载 PDF 文档。 +1. 使用 Phrase 和 Rectangular Constraints 初始化 TextFragmentAbsorber +1. 将吸收器应用于第2页。将处理限制在第2页,以减少不必要的计算。确保搜索针对特定页面。 +1. 遍历找到的片段并打印 -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) ``` +## 使用正则表达式在 PDF 中进行文本模式搜索 -## 在 PDF 文档中突出显示每个字符 - -{{% alert color="primary" %}} - -您可以尝试使用 Aspose.PDF 在文档中搜索文本,并在此[链接](https://products.aspose.app/pdf/search)在线获取结果 - -{{% /alert %}} - -Aspose.PDF for .NET 支持搜索并获取每个字符或文本片段坐标的功能。因此,为了确保返回每个字符的坐标,我们可以考虑在每个字符周围添加矩形进行突出显示。以下代码片段获取每个字符的坐标并在每个字符周围创建一个矩形。 - -```csharp -// 有关完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// 文档目录的路径。 -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]; -// 创建 TextAbsorber 对象以查找所有单词 -TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(@"[\S]+"); -textFragmentAbsorber.TextSearchOptions.IsRegularExpressionUsed = true; -page.Accept(textFragmentAbsorber); -// 获取提取的文本片段 -TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; -// 遍历片段 -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); -} -``` +使用正则表达式在 PDF 中搜索文本模式。通过在 TextFragmentAbsorber 中启用正则模式,您可以定位诸如数字、日期、价格、坐标或自定义文本格式等复杂模式。该函数将搜索限制在特定页面上,使针对结构化数据的提取更高效。 +1. 加载 PDF 文档。 +1. 使用正则表达式模式初始化 TextFragmentAbsorber。 +1. 将吸收器应用于第2页。为提高效率和精确度,将搜索限制在第2页。仅分析此页上的文本。 +1. 遍历已找到的片段。打印匹配的文本片段及其坐标。为提取的模式提供精确的位置信息。 -## 添加和搜索隐藏文本 +```python +import io +import sys +import shutil +import aspose.pdf as ap +import aspose.pydrawing as drawing +from os import path -有时候,我们想在 PDF 文档中添加隐藏文本,然后搜索隐藏文本并使用其位置进行后处理。为了方便您,Aspose.PDF for .NET 提供了这些功能。您可以在文档生成期间添加隐藏文本。此外,您可以使用 TextFragmentAbsorber 查找隐藏文本。要添加隐藏文本,请为添加的文本设置 TextState.Invisible 为“true”。TextFragmentAbsorber 会找到所有匹配模式的文本(如果指定)。这是无法更改的默认行为。为了验证找到的文本是否实际上是不可见的,可以使用 TextState.Invisible 属性。下面的代码片段展示了如何使用此功能。 +def text_fragment_absorber_search_regex(input_file_path): + document = ap.Document(input_file_path) -```csharp -// 有关完整示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// 文档目录的路径。 -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); + absorber = ap.text.TextFragmentAbsorber( + r"\d+\.\d+", ap.text.TextSearchOptions(is_regular_expression_used=True) + ) -//创建包含隐藏文本的文档 -Aspose.Pdf.Document doc = new Aspose.Pdf.Document(); -Page page = doc.Pages.Add(); -TextFragment frag1 = new TextFragment("This is common text."); -TextFragment frag2 = new TextFragment("This is invisible text."); + document.pages[2].accept(absorber) -//设置文本属性 - 不可见 -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(); +## 使用 TextFragmentAbsorber 将文本匹配转换为 PDF 超链接 -//搜索文档中的文本 -doc = new Aspose.Pdf.Document(dataDir + "39400_out.pdf"); -TextFragmentAbsorber absorber = new TextFragmentAbsorber(); -absorber.Visit(doc.Pages[1]); +在 PDF 中搜索特定的文本短语并将其转换为可点击的超链接。使用带有正则表达式模式的 TextFragmentAbsorber,它定位目标词并应用视觉样式(颜色和下划线)以及交互式链接。 -foreach (TextFragment fragment in absorber.TextFragments) -{ - //对片段进行处理 - Console.WriteLine("Text '{0}' on pos {1} invisibility: {2} ", - fragment.Text, fragment.Position.ToString(), fragment.TextState.Invisible); -} -doc.Dispose(); -``` +1. 加载 PDF 文档。 +1. 使用正则表达式模式初始化 TextFragmentAbsorber。 +1. 将 Absorber 应用于第 1 页。 +1. 为匹配项设置样式并添加超链接。 +1. 保存已修改的 PDF。 +```python +import io +import sys +import shutil +import aspose.pdf as ap +import aspose.pydrawing as drawing +from os import path -## 使用 .NET Regex 搜索文本 +def text_fragment_absorber_search_and_add_hyperlink(input_file_path): + document = ap.Document(input_file_path) -Aspose.PDF for .NET 提供了使用标准 .NET Regex 选项搜索文档的功能。可以使用 TextFragmentAbsorber 来实现这一目的,如下面的代码示例所示。 + absorber = ap.text.TextFragmentAbsorber("whale|elephant") + absorber.text_search_options = ap.text.TextSearchOptions(True) -```csharp -// 有关完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); + absorber.visit(document.pages[1]) -// 创建 Regex 对象以查找所有单词 -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}" + ) -// 打开文档 -Aspose.Pdf.Document document = new Aspose.Pdf.Document(dataDir + "SearchTextRegex.pdf"); + output = input_file_path.replace("in.pdf", "out.pdf") + document.save(output) +``` -// 获取特定页面 -Page page = document.Pages[1]; +## 使用 TextFragmentAbsorber 在 PDF 中搜索和识别样式化文本 -// 创建 TextAbsorber 对象以查找输入正则表达式的所有实例 -TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(regex); -textFragmentAbsorber.TextSearchOptions.IsRegularExpressionUsed = true; +在 PDF 中基于格式属性而不是内容搜索文本片段。使用 TextFragmentAbsorber,它可以识别具有特定样式的文本,例如粗体文本。 -// 接受页面的吸收器 -page.Accept(textFragmentAbsorber); +1. 加载 PDF 文档。 +1. 初始化 TextFragmentAbsorber。 +1. 将 Absorber 应用于第 1 页。 +1. 根据格式检查文本片段。检查字体样式是否为粗体。 -// 获取提取的文本片段 -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}") +``` -// 遍历文本片段 -foreach (TextFragment textFragment in textFragmentCollection) -{ - Console.WriteLine(textFragment.Text); -} +## PDF 页面中的可视文本高亮 + +此功能将文本识别与渲染合并为单一工作流程。它不仅提取文本,还通过在每页的 PNG 图像上用彩色矩形高亮显示片段、段落和字符来可视化它们。 + +我们的示例通过以下方式对 PDF 执行高级文本可视化: + +- 使用正则表达式搜索所有可见的文本片段 +- 将每个 PDF 页面渲染为高分辨率 PNG 图像 +- 在文本片段、文本段以及单个字符周围绘制彩色矩形 + +1. 设置输出图像分辨率。每个 PDF 页面均转换为 150 DPI 的 PNG 图像。 +1. 打开 PDF 并初始化 Text Absorber。 +1. 处理每一页。将吸收器应用于每一页。收集所有检测到的文本片段及其几何位置。 +1. 将页面转换为 PNG 流。 +1. 为绘图准备图形对象。 +1. 应用坐标变换。将 PDF 坐标转换为图像像素。 +1. 为文本元素绘制矩形。 +1. 保存结果。 + +```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, + ) ``` +## 相关文本主题 - \ No newline at end of file +- [使用 Python 在 PDF 中处理文本](/pdf/zh/python-net/working-with-text/) +- [通过 Python 替换 PDF 中的文本](/pdf/zh/python-net/replace-text-in-pdf/) +- [在 Python 中为 PDF 文本添加工具提示](/pdf/zh/python-net/pdf-tooltip/) +- [向 PDF 添加文本](/pdf/zh/python-net/add-text-to-pdf-file/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-text/text-formatting-inside-pdf/_index.md b/zh/python-net/advanced-operations/working-with-text/text-formatting-inside-pdf/_index.md index c5e5e3c1a8..75dbe1b5b8 100644 --- a/zh/python-net/advanced-operations/working-with-text/text-formatting-inside-pdf/_index.md +++ b/zh/python-net/advanced-operations/working-with-text/text-formatting-inside-pdf/_index.md @@ -1,427 +1,995 @@ --- -title: 使用 Python 在 PDF 中格式化文本 -linktitle: 在 PDF 中格式化文本 +title: 用 Python 格式化 PDF 文本 +linktitle: PDF 中的文本格式 type: docs -weight: 30 +weight: 70 url: /zh/python-net/text-formatting-inside-pdf/ -description: 本页面解释了如何在 PDF 文件中格式化文本。包括添加行缩进、添加文本边框、添加下划线文本等。 -lastmod: "2024-02-17" +description: 学习如何在 Python 中使用间距、边框、缩进和样式选项对 PDF 文档中的文本进行格式化。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 格式化 PDF 文件中的文本并设置其样式 +Abstract: 本文介绍如何通过.NET 使用适用于 Python 的 Aspose.PDF 格式化 PDF 文档中的文本。学习如何在 Python 中控制间距、缩进、边框、下划线、删除线效果和其他文本样式选项。 --- - - - -## 如何向 PDF 添加行缩进 - -Aspose.PDF for .NET 提供的 [TextFormattingOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textformattingoptions) 类中的 SubsequentLinesIndent 属性。可以在使用 TextFragment 和 Paragraphs 集合的 PDF 生成场景中指定行缩进。 - -请使用以下代码片段来使用该属性: - -```csharp -// 有关完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// 文档目录的路径。 -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -// 创建新的文档对象 -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); - -// 初始化文本片段的 TextFormattingOptions 并指定 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"); + +## 行间距和字符间距 + +### 使用行距 + +#### 如何在 Python 中使用自定义行距设置文本格式-简单案例 + +Aspose.PDF for Python 提供了一种通过行距调整来控制文本布局和可读性的简单方法。 + +我们的代码片段显示了如何控制 PDF 文档中的行距。它读取文件中的文本(或使用备用消息),应用自定义字体大小和行间距,并将格式化文本添加到 PDF 中的新页面。 + +1. 创建新的 PDF 文档。 +1. 加载源文本。 +1. 初始化一个 TextFragment 对象并将加载的文本分配给它。 +1. 设置文本的字体和间距属性。这些值决定了文本行显示的紧密程度或松散程度: + -字体大小:12 点 + -行距:16 点 +1. 将格式化文本片段插入页面的段落集合中。 +1. 保存文档。 + +```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) ``` +#### 如何在 Python 中使用自定义行距设置文本格式-特定案例 + +让我们来看看如何使用自定义 TrueType 字体 (TTF) 在 PDF 文档中应用不同的行距模式。 +它从文件加载文本,嵌入特定的字体,并在 PDF 页面上呈现两次相同的文本,每次都使用不同的行距模式: + +- 字体大小模式:行距等于字体大小。 +- FULL_SIZE 模式:行间距占字体的全部高度,包括上升和下降线。 + +该示例显示了行间距行为如何因所选模式而异。 + +1. 创建新的 PDF 文档。 +1. 指定自定义字体文件和文本源文件的路径。 +1. 加载文本内容。 +1. 打开自定义字体。 +1. 创建和配置第一个 TextFragment(字体大小模式)。将 line_spacing 设置为 “textFormattingOptions.linespacingMode.font_size”,这意味着行间距等于字体大小。 +1. 创建和配置第二个 TextFragment(FULL_SIZE 模式)。将 line_spacing 设置为 “textFormattingOptions.linespacingMode.full_size”,它使用字体的全高。 +1. 将两个文本片段附加到同一 PDF 页面。 +1. 将完成的文档保存到指定的输出位置。 + +```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) +``` + +![PDF 文档使用自定义行距显示文本,显示行间距 16 点,以提高可读性和文本布局格式](line_spacing.png) + +### 使用字符间距 + +#### 如何使用 TextFragment 类控制 PDF 文本中的字符间距 + +字符间距决定一行文本中各个字符之间的距离,这对于微调文本外观或实现特定的排版效果很有用。 + +1. 初始化一个新的 Document 对象并添加一个用于放置文本的空白页面。 +1. 定义片段生成器。实现辅助函数 make_fragment(间距): + -使用示例文本创建 TextFragment。 + -设置字体。 +1. 添加具有不同间距值的文本片段。 +1. 保存文档。 + +```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)) -## 如何添加文本边框 - -以下代码片段演示了如何使用 TextBuilder 并设置 TextState 的 DrawTextRectangleBorder 属性来为文本添加边框: - -```csharp -// 有关完整示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// 文档目录的路径。 -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -// 创建新的文档对象 -Document pdfDocument = new Document(); -// 获取特定页面 -Page pdfPage = (Page)pdfDocument.Pages.Add(); -// 创建文本片段 -TextFragment textFragment = new TextFragment("main text"); -textFragment.Position = new Position(100, 600); -// 设置文本属性 -textFragment.TextState.FontSize = 12; -textFragment.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray; -textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Red; -// 设置 StrokingColor 属性以在文本矩形周围绘制边框(描边) -textFragment.TextState.StrokingColor = Aspose.Pdf.Color.DarkRed; -// 将 DrawTextRectangleBorder 属性值设置为 true -textFragment.TextState.DrawTextRectangleBorder = true; -TextBuilder tb = new TextBuilder(pdfPage); -tb.AppendText(textFragment); -// 保存文档 -pdfDocument.Save(dataDir + "PDFWithTextBorder_out.pdf"); + document.save(outfile) ``` +![显示三行相同文本的 PDF 文档带有字符间距的示例文本显示自上而下的字符间距逐渐缩小,第一行字母之间的间距更宽,中行的间距适中,底行的字符间距最近,说明了 PDF 文本格式中不同字符间距值的视觉效果](character_spacing_simple.png) + +#### 如何使用文本段落和文本生成器控制 PDF 文本中的字符间距 + +Aspose.PDF 允许在使用文本段落和文本生成器向 PDF 文档添加文本时应用自定义字符间距。 +它定义页面上的特定区域,配置文本换行,并使用调整后的字符间距呈现文本片段。 + +当您需要精确控制文本放置和布局时,例如在构建结构化或多列文本块时,使用 TextProagragh 是理想的选择。 + +1. 创建新的 PDF 文档。 +1. 为该页面初始化一个 TextBuilder 实例。 +1. 创建和配置文本段落。 + -将自动换行模式设置为 “textFormattingOptions.Wordwrapmode.by_Words”。 +1. 创建具有自定义字符间距的 TextFragment。 + -创建一个新的 TextFragment 并设置其文本(例如,“带字符间距的示例文本”)。 + -指定字体属性,例如 Arial 和字体大小 14 pt。 + -应用字符间距 = 2.0,这会增加字符之间的间距。 +1. 将 TextFragment 添加到文本段落中。 +1. 将文本段落添加到页面。 +1. 保存 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) +``` + +## 创建清单 + +处理 PDF 文件时,您可能需要显示结构化信息,例如列表,无论它们是项目符号的、编号的,还是使用 HTML 或 LaTeX 格式化的。 +通过.NET for Python 的 Aspose.PDF 提供了几种灵活的方法来直接在 PDF 文档中创建和格式化列表,使您可以完全控制布局、字体和样式。 + +本文演示了在 PDF 中创建列表的多种方法,从纯文本格式到高级 HTML 和 LaTeX 呈现。每种方法都有特定的用例——无论你喜欢精确的编程控制还是基于标记的便捷样式。 + +在本文结束时,您将知道如何: + +- 使用文本段落和文本生成器创建自定义项目符号和编号列表。 + +- 使用 HTML 片段 (HtmlFragment) 可以轻松地在 PDF 中呈现 ul 和 ol 列表。 + +- 利用 LaTeX 片段 (TexFragment) 进行数学或科学列表格式。 + +- 控制页面内的文本包装、字体样式和布局定位。 + +- 了解手动列表构造和标记驱动方法之间的区别。 -## 如何添加下划线文本 - -以下代码片段展示了如何在创建新的 PDF 文件时添加下划线文本。 - -```csharp -// 有关完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// 文档目录的路径。 -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); - -// 创建文档对象 -Document pdfDocument = new Document(); -// 向 PDF 文档添加页面 -pdfDocument.Pages.Add(); -// 为第一页创建 TextBuilder -TextBuilder tb = new TextBuilder(pdfDocument.Pages[1]); -// 带有示例文本的 TextFragment -TextFragment fragment = new TextFragment("Test message"); -// 为 TextFragment 设置字体 -fragment.TextState.Font = FontRepository.FindFont("Arial"); -fragment.TextState.FontSize = 10; -// 将文本格式设置为下划线 -fragment.TextState.Underline = true; -// 指定 TextFragment 需要放置的位置 -fragment.Position = new Position(10, 800); -// 将 TextFragment 附加到 PDF 文件 -tb.AppendText(fragment); - -dataDir = dataDir + "AddUnderlineText_out.pdf"; - -// 保存生成的 PDF 文档。 -pdfDocument.Save(dataDir); +### 创建编号列表 + +```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) ``` +### 创建项目符号清单 + +```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) +``` -## 如何在添加的文本周围添加边框 +### 创建编号列表 HTML 版本 + +使用 HTML 片段在 PDF 文档中创建带编号(有序)的列表。它将 Python 字符串列表转换为 HTML 元素,并将其作为 HTMLFragment 插入 PDF 页面。 + +使用 HTML 片段可以将基于 HTML 的格式化功能,例如编号列表、粗体、斜体等,直接整合到 PDF 中。 + +1. 创建新的 PDF 文档并添加页面。 +1. 准备清单项目。 +1. 将列表转换为 HTML 有序列表。 + -使用 ol 标签获取编号列表。 + -使用列表推导将每个项目包含 “li” 标签。 +1. 将 HTML 字符串转换为可以添加到 PDF 页面的 HTMLFragment 对象。 +1. 将 HTMLFragment 插入到页面的段落集合中。 +1. 保存 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) +``` -您可以控制添加文本的外观。下面的示例显示了如何通过在添加的文本周围绘制一个矩形来添加边框。了解有关 [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor) 类的更多信息。 +![在 PDF 文档中显示的编号列表显示了四个自动编号的项目:1.列表中的第一项,2。第二项包含更多用于演示包装行为的文本,3。第三项,以及 4.第四项。该列表演示了在 PDF 结构中使用 HTML 格式的有序列表呈现,并采用了正确的数字顺序、缩进和项目间距](numbered_list_html.png) + +### 创建项目符号列表 HTML 版本 + +我们的库展示了如何使用 HTML 片段在 PDF 文档中创建项目符号(无序)列表。它将 Python 字符串列表转换为 HTML ul 元素,并将其作为 HTMLFragment 插入 PDF 页面。使用 HTML 片段可以直接在 PDF 中利用 HTML 格式化功能(如列表、粗体、斜体)。 + +1. 创建新的 PDF 文档并添加页面。 +1. 准备清单项目。 +1. 将该列表转换为 HTML 无序列表。 + -使用 ul 标签获取无序(项目符号)列表。 + -使用列表推导将每个项目包含 “li” 标签。 +1. 创建一个 HTMLFragment。将 HTML 字符串转换为可以添加到 PDF 页面的 HTMLFragment 对象。 +1. 将 HTMLFragment 插入到页面的段落集合中。 +1. 保存 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) +``` -```csharp -// 有关完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// 文档目录的路径。 -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); +![项目符号列表显示在 PDF 文档中,显示四个项目:列表中的第一项、包含更多用于演示包装行为的第二项、第三项和第四项。每个项目前面都有一个标准项目符号,并演示了在 PDF 结构中以适当的缩进和间距呈现 HTML 格式的列表](bullet_list_html.png) + +### 创建项目符号清单 LaTeX 版本 + +使用 LaTeX 片段 (TexFragment) 在 PDF 中创建项目符号(无序)列表。它将 Python 字符串列表转换为 LaTeX 逐项列出环境并将其插入到 PDF 页面中。当你想呈现具有精确格式的数学公式、符号或结构化列表时,使用 LaTeX 片段是理想的选择。 + +1. 创建新的 PDF 文档并添加页面。 +1. 定义一个 Python 字符串列表,这些字符串将成为 LaTeX 逐项列出环境中的要点。 +1. 将列表转换为 LaTeX 逐项列出环境: + -用\ begin {itemize} 和\ end {itemize} 包装商品。 + -使用列表推导,每个项目都以\ item 作为前缀。 +1. 将 LaTeX 字符串转换为可以在 PDF 中呈现的 TexFragment 对象。 +1. 将 LaTeX 片段添加到页面。 +1. 保存 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) +``` -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), ""); +![在 PDF 中显示的项目符号列表显示了 LaTex 渲染的格式和文本列表很容易创建:其次是四个带有项目符号的项目:第一项、第二项(包含更多用于演示包装行为的文本)、第三项和第四项。该清单演示了专业的 LaTeX 排版,在简洁的 PDF 文档布局中具有正确的项目符号格式、一致的间距和文本包装功能](bullet_list_latex.png) + +### 创建编号列表 LaTeX 版本 + +使用 LaTeX 片段 (TexFragment) 在 PDF 中创建带编号(有序)的列表。它将 Python 字符串列表转换为 LaTeX 枚举环境并将其插入到 PDF 页面中。当你想在 PDF 中进行精确的格式、结构化列表或数学表示法时,使用 LaTeX 片段是理想的选择。 + +1. 创建新的 PDF 文档并添加页面。 +1. 定义一个 Python 字符串列表,这些字符串将在 LaTeX 枚举环境中成为编号项目。 +1. 将列表转换为 LaTeX 枚举环境。 +1. 将 LaTeX 字符串转换为可以在 PDF 中呈现的 TexFragment 对象。 +1. 将 LaTeX 片段添加到页面。 +1. 保存 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) +``` -dataDir = dataDir + "AddingBorderAroundAddedText_out.pdf"; +![PDF 中显示的编号列表显示了 LaTeX 渲染的格式,其中包含第 1 项。第一项,2。第二项包含更多用于演示包装行为的文本,3。第三项,以及 4.第四项,前面是文本列表,易于创建](numbered_list_latex.png) -// 保存生成的 PDF 文档。 -editor.Save(dataDir); +## 脚注和尾注 + +### 添加脚注 + +脚注用于通过在相关文本旁边放置连续的上标数字来引用文档正文中的注释。这些数字对应于详细注释,这些注释通常缩进并位于同一页面的底部,提供额外的背景信息、引文或评论。 + +通过.NET 使用适用于 Python 的 Aspose.PDF 为 PDF 文档中的文本片段添加脚注。脚注可用于在不混乱主要内容的情况下提供补充信息、引文或澄清。这种方法可确保脚注在视觉和结构上集成到 PDF 布局中。 + +1. 创建新文档。 +1. 使用主要内容创建一个 TextFragment。 +1. 添加行内文本。创建另一个 TextFragment,该文本片段继续出现在同一段落中。 +1. 保存文档。 + +```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) +``` + +### 在 PDF 中添加带有自定义样式的脚注 + +1. 初始化新的 PDF 文档并添加空白页面。 +1. 创建正文片段。 +1. 创建脚注并设置其样式(字体、大小、颜色、样式)。 +1. 将带有脚注的样式文本片段插入页面。 +1. 添加另一个不带脚注的文本片段。 +1. 保存文档。 + +```python +import aspose.pdf as ap +import sys +from os import path + +def add_footnote_custom_text_style(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 + + 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 + + page.paragraphs.add(text_fragment) + + 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) + + document.save(outfile) ``` -## 如何添加换行符 +### 在 PDF 中添加带有自定义符号的脚注 + +使用适用于 Python 的 Aspose.PDF 通过.NET 向 PDF 文档中的文本片段添加脚注,并能够自定义脚注标记符号。 -TextFragment不支持文本中的换行符。然而,为了添加带有换行符的文本,请使用带有TextParagraph的TextFragment: +1. 创建 PDF 文档和页面。 +1. 添加第一个带有自定义脚注符号的文本片段。 +1. 添加另一个不带脚注的文本片段,继续执行该段落。 +1. 添加第二个带有默认脚注的文本片段。 +1. 保存文档。 -- 在TextFragment中使用"\r\n"或Environment.NewLine代替单个"\n"; -- 创建TextParagraph对象。它将添加分行的文本; -- 使用TextParagraph.AppendLine添加TextFragment; -- 使用TextBuilder.AppendParagraph添加TextParagraph。 -请使用下面的代码片段。 +```python +import aspose.pdf as ap +import sys +from os import path -```csharp -// 有关完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// 文档目录的路径。 -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -Aspose.Pdf.Document pdfApplicationDoc = new Aspose.Pdf.Document(); -Aspose.Pdf.Page applicationFirstPage = (Aspose.Pdf.Page)pdfApplicationDoc.Pages.Add(); +def add_footnote_custom_text(outfile): + document = ap.Document() + page = document.pages.add() -// 使用包含所需换行符的文本初始化新的TextFragment -Aspose.Pdf.Text.TextFragment textFragment = new Aspose.Pdf.Text.TextFragment("Applicant Name: " + Environment.NewLine + " Joe Smoe"); + 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 -// 如果需要,设置文本片段属性 -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; + note = ap.Note("This is the footnote content with custom text style.") + note.text = "*" + text_fragment.foot_note = note + page.paragraphs.add(text_fragment) -// 创建TextParagraph对象 -TextParagraph par = new TextParagraph(); + 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) -// 向段落添加新的TextFragment -par.AppendLine(textFragment); + 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) -// 设置段落位置 -par.Position = new Aspose.Pdf.Text.Position(100, 600); + document.save(outfile) +``` + +### 在 PDF 中添加带有自定义线条样式的脚注 + +使用 Python 库自定义 PDF 文档中脚注行的视觉外观。自定义脚注行可增强视觉清晰度,并使报告、学术论文和带注释的出版物等文档的风格保持一致。 + +1. 创建新的 PDF 文档并添加页面。 +1. 为脚注连接器定义自定义线条样式(颜色、宽度和短划线图案)。 +1. 添加多个带脚注的文本片段。 +1. 保存最终文档。 + +```python +import aspose.pdf as ap +import sys +from os import path -// 创建TextBuilder对象 -TextBuilder textBuilder = new TextBuilder(applicationFirstPage); -// 使用TextBuilder添加TextParagraph -textBuilder.AppendParagraph(par); +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 -// 保存生成的PDF文档。 -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) ``` +### 在 PDF 中添加带有图像和表格的脚注 + +如何通过.NET 使用 Aspose.PDF for Python 嵌入图像、样式化文本和表格来丰富 PDF 文档中的脚注? -## 如何添加删除线文本 +1. 创建新的 PDF 文档并添加页面。 +1. 添加带有附加脚注的文本片段。 +1. 在脚注中嵌入图像、样式文本和表格。 +1. 保存文档。 -TextState 类提供了设置 PDF 文档中 TextFragments 格式的功能。您可以使用此类将文本格式设置为粗体、斜体、下划线,并且从此版本开始,API 已提供将文本格式标记为删除线的功能。请尝试使用以下代码片段添加带有删除线格式的 TextFragment。 +```python +import aspose.pdf as ap +import sys +from os import path -请使用完整的代码片段: +def add_footnote_with_image_and_table(outfile): + document = ap.Document() + page = document.pages.add() -```csharp -// 有关完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// 文档目录的路径。 -string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); -// 打开文档 -Document pdfDocument = new Document(); -// 获取特定页面 -Page pdfPage = (Page)pdfDocument.Pages.Add(); + text = ap.text.TextFragment("This is a sample text with a footnote.") + page.paragraphs.add(text) -// 创建文本片段 -TextFragment textFragment = new TextFragment("main text"); -textFragment.Position = new Position(100, 600); + note = ap.Note() -// 设置文本属性 -textFragment.TextState.FontSize = 12; -textFragment.TextState.Font = FontRepository.FindFont("TimesNewRoman"); -textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray; -textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Red; -// 设置删除线属性 -textFragment.TextState.StrikeOut = true; -// 将文本标记为粗体 -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) -// 创建 TextBuilder 对象 -TextBuilder textBuilder = new TextBuilder(pdfPage); -// 将文本片段附加到 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) -// 保存生成的 PDF 文档。 -pdfDocument.Save(dataDir); + text.foot_note = note + + document.save(outfile) ``` +### 向 PDF 文档添加尾注 + +Endnote是一种引文,它引导读者进入文档末尾的指定部分,在那里他们可以找到引文、释义想法或摘要内容的完整参考资料。使用尾注时,在参考材料之后立即放置一个上标编号,引导读者阅读论文末尾的相应注释。 -## 应用渐变阴影到文本 +此代码片段演示了如何向 PDF 文档中的文本片段添加尾注。与脚注不同,脚注出现在引用文本附近,而尾注通常位于文档或章节的末尾。此方法还模拟了较长的文档,以说明尾注在扩展内容中的表现。 -在文本编辑场景的 API 中,文本格式化得到了进一步增强,现在您可以在 PDF 文档中添加带有图案颜色空间的文本。Aspose.Pdf.Color 类通过引入新的 PatternColorSpace 属性得到了进一步增强,该属性可用于指定文本的阴影颜色。这个新属性为文本添加了不同的渐变阴影,例如:轴向阴影、径向(类型 3)阴影,如以下代码片段所示: +1. 创建 PDF 文档和页面。 +1. 使用 Endnote 添加文本片段。 +1. 加载外部文本内容。 +1. 模拟长文档。多次添加加载的文本以模拟更长的文档。 +1. 保存文档。 -```csharp -// 有关完整示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// 文档目录的路径。 -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) - // 创建带有图案颜色空间的新颜色 - 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) +``` + +### 在 PDF 中添加带有自定义标记文本的尾注 + +在 PDF 文档的文本片段中添加尾注,并使用自定义标记符号(例如 “***”)。尾注通常放在文档或章节的末尾,可用于提供其他上下文、引文或评论。 + +1. 创建 PDF 文档和页面。 +1. 添加带有尾注的样式文本片段。 +1. 自定义尾注标记文本。 +1. 从 .txt 文件加载外部内容。 +1. 模拟长篇内容以说明尾注的位置。 +1. 保存 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) ``` +## 布局和页面控制 + +### 强制表格从 PDF 中的新页面开始 + +通过.NET 使用适用于 Python 的 Aspose.PDF 在 PDF 文档的新页面上添加特定内容。 +通过设置属性 “is_in_new_page”,您可以精确控制页面布局和结构,确保特定部分(例如表格、报告或摘要)始终从新页面开始,非常适合文档格式、打印就绪报告或有组织的输出生成。 ->要应用径向渐变,可以在上面的代码片段中将“PatternColorSpace”属性设置为‘Aspose.Pdf.Drawing.GradientRadialShading(startingColor, endingColor)’ +1. 创建和配置表。 +1. 向表中添加数据。 +1. 强制表格换一个新页面。这样可以确保表格从新页面的顶部开始,即使当前页面上有现有内容也是如此。 +1. 将表格添加到页面。使用 “page.parage.paraghs.add ()” 将表格包含在 PDF 布局中。 +1. 保存文档。 -## 如何将文本对齐到浮动内容 +```python +import aspose.pdf as ap +import sys +from os import path -Aspose.PDF 支持为 Floating Box 元素中的内容设置文本对齐。可以使用 Aspose.Pdf.FloatingBox 实例的对齐属性来实现,如以下代码示例所示。 +def force_new_page(output_file_name): + # Create new PDF document + document = ap.Document() + page = document.pages.add() -```csharp -// 有关完整的示例和数据文件,请访问 https://github.com/aspose-pdf/Aspose.PDF-for-.NET -// 文档目录的路径。 -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) +``` + +### 在 PDF 中使用行内段落属性 + +我们的库允许您使用 “is_in_line_paragraph” 属性来控制 PDF 中文本和图像之间的内联流动。 +通常,当您添加新元素(例如文本片段或图像)时,每个元素都从新行或新段落开始。 +通过设置 “is_in_line_paragraparage = True”,您可以使元素出现在同一行或同一段落中,从而创建流畅的行内布局——非常适合内联组合文本和图像,例如在句子中添加徽标、图标或符号。 + +第一个文本片段、图像和第二个文本片段出现在同一行上,形成一个连续的行内段落。 +第三个文本片段开始了一个新段落,演示了默认的换行行为。 + +1. 创建新的 PDF 文档。 +1. 添加第一个文本片段。 +1. 插入行内图片。 +1. 添加更多行内文本。 +1. 添加新段落。 +1. 保存 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) +``` + +### 创建多列 PDF + +通过 .NET 使用 Aspose.PDF for Python 在 PDF 中创建多栏报纸样式布局。 +它展示了如何在 FloatingBox 中组合文本、HTML 格式和图形,从而实现类似于多栏杂志或时事通讯设计的高级版面控制。 + +1. 初始化 PDF 文档。 +1. 在顶部添加一条水平分隔线。 +1. 添加样式化的 HTML 标题。 +1. 为布局控制创建 FloatingBox。 +1. 配置多列布局。 +1. 添加作者信息。 +1. 画另一条内部水平线。 +1. 添加文章文本。 +1. 保存最终的 PDF。 + +```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"); +### 在 PDF 中使用自定义制表位来对齐文本 + +使用自定义制表位在 PDF 中创建类似表格的文本布局,无需依赖表格结构。 +通过定义制表位位置、对齐方式和引线样式,您可以精确地在各列之间对齐文本。这对于发票、报告或结构化文本数据很有用。 + +1. 创建新的 PDF 文档。 +1. 定义自定义制表位。 +1. 在文本中使用 #$TAB占位符。 +1. 向 PDF 添加文本。 +1. 保存 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) ``` +### 相关文字主题 - \ No newline at end of file +- [使用 Python 处理 PDF 中的文本](/pdf/zh/python-net/working-with-text/) +- [向 PDF 添加文本](/pdf/zh/python-net/add-text-to-pdf-file/) +- [使用 Python 旋转 PDF 中的文本](/pdf/zh/python-net/rotate-text-inside-pdf/) +- [通过 Python 替换 PDF 中的文本](/pdf/zh/python-net/replace-text-in-pdf/) \ No newline at end of file diff --git a/zh/python-net/advanced-operations/working-with-vector-graphics/_index.md b/zh/python-net/advanced-operations/working-with-vector-graphics/_index.md new file mode 100644 index 0000000000..00430ee151 --- /dev/null +++ b/zh/python-net/advanced-operations/working-with-vector-graphics/_index.md @@ -0,0 +1,214 @@ +--- +title: 在 Python 中使用矢量图形 +linktitle: 使用矢量图形 +type: docs +weight: 100 +url: /zh/python-net/working-with-vector-graphics/ +description: 学习如何使用 Python 中的 GraphicsAbsorber 在 PDF 页面之间提取、移动、删除和复制矢量图形。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中使用 GraphicsAbsorber 检查和操作 PDF 矢量图形。 +Abstract: 本文解释了如何在 Aspose.PDF for Python via .NET 中使用 GraphicsAbsorber 类处理矢量图形。了解如何从 PDF 页面中提取矢量元素,移动或删除它们,以及在 Python 工作流中以低层控制在页面之间复制图形。 +--- + +[Aspose.PDF for Python via .NET](/pdf/zh/python-net/) 提供 [GraphicsAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/graphicsabsorber/) 用于访问和操作已存在于 PDF 页面中的矢量图形的类。调用它的 `visit` 在任何页面上使用方法提取路径、形状和其他图形操作符,然后根据需要移动、删除或复制这些元素。 + +当您需要检查或修改嵌入在现有 PDF 中的矢量绘图元素,而不是从零开始绘制新形状时,请使用此页面。 + +## 提取图形 + +提取是所有矢量图形任务的起点。 `GraphicsAbsorber` 读取页面的内容流,并公开每个图形元素及其页面引用、位置和原始操作符。 + +1. 打开 PDF 文档。 +1. 创建一个 [GraphicsAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/graphicsabsorber/) 实例。 +1. 调用 `visit` 在目标页面上填充 `elements`. +1. 遍历 `elements` 检查位置和运算符计数。 + +```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` 是...的一部分 `aspose.pdf.vector` 命名空间,专门用于与 PDF 内容流中的矢量图形交互。 + +## 动态图形 + +提取后,设置一个新的 `position` 对每个元素进行操作以将其重新定位到同一页面。将更新包装在 `suppress_update` / `resume_update` 调用将内容流写入批处理为单个操作,并避免冗余的重新绘制。 + +1. 打开 PDF 文档。 +1. 创建一个 `GraphicsAbsorber` 并调用 `visit` 在目标页面上。 +1. 调用 `suppress_update` 暂停内容流写入。 +1. 更新 `position` 每个元素的 +1. 调用 `resume_update` 一次性提交所有更改。 +1. 保存修改后的文档。 + +```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) +``` + +## 删除图形 + +要从页面中删除特定的矢量元素,请按位置或边界矩形过滤,然后将其删除。Aspose.PDF for Python 提供了两种方法,取决于您是想内联删除元素还是先收集它们。 + +### 方法1:使用矩形边界删除内联 + +此方法检查每个元素相对于矩形的位置并调用 `element.remove()` 直接在循环内部使用。当你想要简洁的代码且不需要在之后检查已删除的集合时使用它。 + +1. 打开 PDF 文档。 +1. 创建一个 `GraphicsAbsorber` 并调用 `visit` 在目标页面上。 +1. 定义目标 [矩形](https://reference.aspose.com/pdf/python-net/aspose.pdf/rectangle/). +1. 调用 `suppress_update` 暂停内容流写入。 +1. 迭代 `elements`,调用 `remove()` 对每个位置位于矩形内的元素。 +1. 调用 `resume_update` 提交删除。 +1. 保存修改后的文档。 + +```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) +``` + +### 方法二:先收集元素,然后删除 + +此方法将匹配的元素收集到一个 [图形元素集合](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/graphicelementcollection/) 并将集合传递给 `page.delete_graphics`. 在提交删除之前,如果您需要审查或记录将要删除的内容,请使用它。 + +1. 打开 PDF 文档。 +1. 创建一个 `GraphicsAbsorber` 并调用 `visit` 在目标页面上。 +1. 定义目标矩形。 +1. 迭代 `elements` 并将匹配的元素添加到 a `GraphicElementCollection`. +1. 调用 `page.contents.suppress_update` 暂停内容流写入。 +1. 调用 `page.delete_graphics` 与集合一起。 +1. 调用 `page.contents.resume_update` 提交删除。 +1. 保存修改后的文档。 + +```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) +``` + +## 在另一页上添加图形 + +从一个页面提取的矢量元素可以放置在同一文档的任何其他页面上。有两种方法可用:逐个添加元素,或在一次调用中传递整个集合。 + +### 方法 1:逐个添加元素 + +当您需要对每个元素进行控制时,例如在将它们放置到目标页面之前对单个元素进行过滤或转换,请使用此方法。 + +1. 打开 PDF 文档。 +1. 创建一个 `GraphicsAbsorber` 并调用 `visit` 在源页面上。 +1. 向文档添加一个新的目标页面。 +1. 调用 `page_2.contents.suppress_update` 暂停内容流写入。 +1. 调用 `element.add_on_page(page_2)` 对每个元素。 +1. 调用 `page_2.contents.resume_update` 提交所有添加。 +1. 保存修改后的文档。 + +```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) +``` + +### 方法 2:一次性添加整个集合 + +当您想一次性将所有提取的元素复制到页面,而无需手动遍历时,请使用此方法。 + +1. 打开 PDF 文档。 +1. 创建一个 `GraphicsAbsorber` 并调用 `visit` 在源页面上。 +1. 向文档添加一个新的目标页面。 +1. 调用 `page_2.contents.suppress_update` 暂停内容流写入。 +1. 调用 `page_2.add_graphics` 完整的 `elements` 集合。 +1. 调用 `page_2.contents.resume_update` 提交所有添加。 +1. 保存修改后的文档。 + +```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) +``` + +## 相关主题 + +- [Python中的高级PDF操作](/pdf/zh/python-net/advanced-operations/) +- [在 Python 中使用 PDF 图形](/pdf/zh/python-net/working-with-graphs/) +- [在 Python 中使用 PDF 操作符](/pdf/zh/python-net/working-with-operators/) +- [在 Python 中处理 PDF 页面](/pdf/zh/python-net/working-with-pages/) diff --git a/zh/python-net/advanced-operations/zugferd/_index.md b/zh/python-net/advanced-operations/zugferd/_index.md index d1f3784f7b..e5a1d9c3b7 100644 --- a/zh/python-net/advanced-operations/zugferd/_index.md +++ b/zh/python-net/advanced-operations/zugferd/_index.md @@ -1,36 +1,37 @@ --- - title: 使用 ZUGFeRD linktitle: 使用 ZUGFeRD type: docs weight: 90 url: /zh/python-net/working-with-zugferd/ -description: 学习如何使用 Aspose.PDF for Java 创建符合 ZUGFeRD 标准的 PDF 发票 -lastmod: "2024-01-17" +description: 了解如何在 Python 中使用 Aspose.PDF 处理 ZUGFeRD 发票,以管理和生成电子发票。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 - +TechArticle: true +AlternativeHeadline: 在 Python 中使用 Aspose.PDF 处理 ZUGFeRD 发票 +Abstract: ZUGFeRD 是一种电子发票标准,主要在德国和其他欧盟国家使用,旨在通过完全数字化的方式简化 B2B 发票流程。它促进了电子发票的高效创建、传输和处理,从而实现成本节约和运营效率提升。ZUGFeRD 格式独特地将可供人类阅读的 PDF 与机器可读取的 XML 结合在一起,确保不同软件平台之间的互操作性。该标准满足归档和税务合规的法律要求,并与欧盟标准 EN 16931 保持一致。最新版本 ZUGFeRD 2.0 提供多种配置文件,以满足多样化的业务需求,带来更快的处理速度、错误率降低、现金流改善以及降低环境影响等优势。文章还提供了在 Python、Java 和 .NET 中实现符合 ZUGFeRD 标准的 PDF 的资源。 --- ## 什么是 ZUGFeRD -电子发票是创建、发送、接收和处理电子发票文件的过程。它从头到尾都是完全数字化的,有助于企业在 B2B 环境中节省资金并提高效率。买卖双方都可以从电子发票中受益。 +电子发票是创建、发送、接收和处理电子发票文档的过程。它从头到尾完全数字化,帮助企业节省成本并在 B2B 环境中提高效率。买卖双方都可以受益于电子发票。 -随着技术的进步,数百万家公司正在采用电子发票以享受其优势。然而,他们需要标准以确保电子发票可以被任何软件轻松读取和理解,无论它们是如何生成的。 +随着技术的进步,数以百万计的公司正采用电子发票以享受其优势。然而,它们需要标准来确保电子发票能够被任何软件轻松读取和理解,无论它们是如何生成的。 -在众多电子发票数据格式中,ZUGFeRD 标准在德语区和欧盟国家中变得越来越普及。 +在众多电子发票数据格式中,ZUGFeRD 标准在德语地区及欧盟国家日益得到确立。 -ZUGFeRD 是德国电子发票的标准。 - 它代表“Zentraler User Guide des Forums elektronische Rechnung Deutschland”,即德国电子发票论坛的中央用户指南。 +ZUGFeRD 是德国的电子发票标准。它的全称是 "Zentraler User Guide des Forums elektronische Rechnung Deutschland",即德国电子发票论坛的中心用户指南。 -该格式是结合了人类可读的PDF文档和机器可读的XML数据文件的混合体。它允许企业和公共机构之间的发票信息交换统一且具有互操作性。 +该格式是一种混合体,结合了人类可阅读的 PDF 文档和机器可读取的 XML 数据文件。它实现了企业与公共部门之间统一且可互操作的发票信息交换。 -它还符合长期存档和税务合规的法律要求。ZUGFeRD有不同的版本和配置文件,以满足不同的需求和场景。最新版本是ZUGFeRD 2.0,与欧洲电子发票标准EN 16931兼容。 -ZUGFeRD为用户提供了许多好处和成本节约,例如更快的处理速度、减少错误、改善现金流和降低环境影响。 +它还符合长期存档和税务合规的法律要求。ZUGFeRD 有不同的版本和配置文件,适用于不同的需求和场景。最新版本是 ZUGFeRD 2.0,兼容欧洲电子发票标准 EN 16931。 +ZUGFeRD 为用户提供许多好处和成本节约,例如更快的处理速度、错误减少、现金流改善以及降低环境影响。 -* [在 Python 中创建符合 PDF/3-A 的 PDF 并附加 ZUGFeRD 发票](/pdf/zh/python-net/attach-zugferd/) +* [在 Python 中创建符合 PDF/3-A 标准的 PDF 并附加 ZUGFeRD 发票](/pdf/zh/python-net/attach-zugferd/) -另请参阅: +另见: -* [在 Java 中创建符合 PDF/3-A 的 PDF 并附加 ZUGFeRD 发票](/pdf/zh/java/attach-zugferd/) * [创建符合PDF/3-A的PDF并在.NET中附加ZUGFeRD发票](/pdf/zh/net/attach-zugferd/) \ No newline at end of file +* [在 Java 中创建符合 PDF/3-A 标准的 PDF 并附加 ZUGFeRD 发票](/pdf/zh/java/attach-zugferd/) +* [在 .NET 中创建符合 PDF/3-A 标准的 PDF 并附加 ZUGFeRD 发票](/pdf/zh/net/attach-zugferd/) diff --git a/zh/python-net/advanced-operations/zugferd/attach-zugferd/_index.md b/zh/python-net/advanced-operations/zugferd/attach-zugferd/_index.md index 086b6771eb..30683eedcf 100644 --- a/zh/python-net/advanced-operations/zugferd/attach-zugferd/_index.md +++ b/zh/python-net/advanced-operations/zugferd/attach-zugferd/_index.md @@ -1,58 +1,54 @@ --- -title: 创建符合PDF/3-A标准的PDF并在Python中附加ZUGFeRD发票 -linktitle: 将ZUGFeRD附加到PDF +title: 在 Python 中创建符合 PDF/3-A 标准的 PDF 并附加 ZUGFeRD 发票 +linktitle: 将 ZUGFeRD 附加到 PDF type: docs weight: 10 url: /zh/python-net/attach-zugferd/ -description: 了解如何通过Aspose.PDF for Python via .NET生成带有ZUGFeRD的PDF文档 -lastmod: "2024-01-18" +description: 了解如何在 Aspose.PDF for Python via .NET 中使用 ZUGFeRD 生成 PDF 文档 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何将 ZUGFeRD 附加到 PDF 文档 +Abstract: 本文提供了一个分步指南,说明如何使用 Aspose.PDF 库将 ZUGFeRD(电子发票格式)附加到 PDF 文档。该过程从导入必要的库并设置输入和输出文件的目录路径开始。它涉及将目标 PDF 文件加载到 Document 对象中,并为 XML 发票元数据文件创建一个 FileSpecification 对象。关键属性如 `mime_type` 和 `af_relationship` 被设置,以确保元数据的正确集成。随后将 XML 文件添加到 PDF 的嵌入文件集合中,从而将其作为元数据附加。接下来,PDF 文档被转换为 PDF/A-3A 格式,适用于归档电子文档,然后将包含嵌入 ZUGFeRD 的最终 PDF 保存。文章最后提供了一个 Python 代码片段,演示了这些步骤的实现,展示了 ZUGFeRD 与 PDF 的集成以提升文档管理。 --- -## 将ZUGFeRD附加到PDF +## 将 ZUGFeRD 附加到 PDF -我们建议按照以下步骤将ZUGFeRD附加到PDF: +我们建议遵循以下步骤将 ZUGFeRD 附加到 PDF: -1. 导入Aspose.PDF库,并为方便起见给它一个别名ap。 -1. 定义输入和输出PDF文件所在目录的路径。 -1. 定义将被处理的PDF文件的路径。 -1. 从路径变量加载PDF文件并创建一个Document对象。 -1. 为包含发票元数据的XML文件创建一个FileSpecification对象。使用路径变量和描述字符串来创建FileSpecification对象。 - -1. 将 FileSpecification 对象的 `mime_type` 和 `af_relationship` 属性分别设置为 `text/xml` 和 `ALTERNATIVE`。 -1. 将 fileSpecification 对象添加到文档对象的嵌入文件集合中。这会将 XML 文件作为发票元数据文件附加到 PDF 文档中。 -1. 将 PDF 文档转换为 PDF/A-3A 格式。使用日志文件的路径、`PdfFormat.PDF_A_3A` 枚举和 `ConvertErrorAction.DELETE` 枚举来转换文档对象。 -1. 保存附加了 ZUGFeRD 的 PDF 文档。 +1. 导入 Aspose.PDF 库,并为方便起见给它一个别名 ap。 +1. 定义输入和输出 PDF 文件所在目录的路径。 +1. 定义将要处理的 PDF 文件的路径。 +1. 从 path 变量加载 PDF 文件并创建一个 Document 对象。 +1. 为包含发票元数据的 XML 文件创建一个 FileSpecification 对象。使用 path 变量和描述字符串来创建该 FileSpecification 对象。 +1. 设置 `mime_type` 和 `af_relationship` FileSpecification 对象的属性 `text/xml` 和 `ALTERNATIVE`,分别。 +1. 将 fileSpecification 对象添加到 document 对象的嵌入文件集合中。这会将 XML 文件作为发票元数据文件附加到 PDF 文档。 +1. 将 PDF 文档转换为 PDF/A-3A 格式。使用日志文件的路径, `PdfFormat.PDF_A_3A` 枚举,以及 `ConvertErrorAction.DELETE` 用于转换文档对象的枚举。 +1. 将带有附加 ZUGFeRD 的 PDF 文档保存。 ```python +import sys +import os import aspose.pdf as ap -# 定义输入和输出 PDF 文件所在目录的路径 -_dataDir = "./" - -# 加载将被处理的 PDF 文件 -path = _dataDir + "ZUGFeRD/ZUGFeRD-test.pdf" -document = ap.Document(path) - -# 为包含发票元数据的 XML 文件创建一个 FileSpecification 对象 -description = "符合 ZUGFeRD 标准的发票元数据" -path = _dataDir + "ZUGFeRD/factur-x.xml" -fileSpecification = ap.FileSpecification(path, description) +def attach_invoice_zugferd_format(infile, invoice, outfile): + document = ap.Document(infile) -# 设置嵌入文件的 MIME 类型和 AFRelationship 属性 -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) -# 将嵌入的文件添加到 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 -# 将 PDF 文档转换为 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) -# 保存附加了 ZUGFeRD 的 PDF 文档 -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/zh/python-net/aspose_pdf-for-python-net.png b/zh/python-net/aspose_pdf-for-python-net.png new file mode 100644 index 0000000000..0a1f34628e Binary files /dev/null and b/zh/python-net/aspose_pdf-for-python-net.png differ diff --git a/zh/python-net/aspose_pdf-for-python-net.svg b/zh/python-net/aspose_pdf-for-python-net.svg new file mode 100644 index 0000000000..92b7ff53e8 --- /dev/null +++ b/zh/python-net/aspose_pdf-for-python-net.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/zh/python-net/basic-operations/_index.md b/zh/python-net/basic-operations/_index.md index 8398a84e94..f015685a07 100644 --- a/zh/python-net/basic-operations/_index.md +++ b/zh/python-net/basic-operations/_index.md @@ -1,18 +1,24 @@ --- -title: PDF文档的基本操作 +title: PDF 文档的基本操作 linktitle: 基本操作 type: docs weight: 60 url: /zh/python-net/basic-operations/ -lastmod: "2022-12-22" -description: 基本操作部分描述了使用Aspose.PDF for Python via .NET打开和保存PDF文档的可能性。 +lastmod: "2026-06-08" +description: 基本操作章节描述了使用 Aspose.PDF for Python via .NET 打开和保存 PDF 文档的可能性。 sitemap: changefreq: "monthly" priority: 0.5 +TechArticle: true +AlternativeHeadline: 使用 Python 对 PDF 进行基本操作概述 +Abstract: 本文概述了使用 Aspose.PDF for Python 处理 PDF 文档的基本操作。它涵盖了三个基本任务——在 Python 环境中创建、打开和保存 PDF 文件。“Create PDF Document” 部分详细说明了使用 Python 生成 PDF 文件的过程。“Open PDF Document” 部分探讨了在 Python 应用中访问 PDF 文档的多种方法。最后,“Save PDF Document” 部分解释了保存 PDF 文档的各种技术。每个部分都链接到更详细的文章,指导用户完成这些关键的 PDF 操作。 --- -**基本操作**部分描述了在Aspose.PDF for Python中进行PDF文档的第一个和最简单的操作: +**Basic operations** 部分描述了 Aspose.PDF for Python 中对 PDF 文档的第一种也是最简单的操作: -- [创建PDF文档](/pdf/zh/python-net/create-document/) - 本文描述了如何使用Python创建PDF文件。 -- [打开PDF文档](/pdf/zh/python-net/open-pdf-document/) - 本文描述了在Python应用程序中打开PDF文档的各种方法。 -- [保存PDF文档](/pdf/zh/python-net/save-pdf-document/) - 本文描述了保存PDF文档的各种方法。 \ No newline at end of file +- [创建 PDF 文档](/pdf/zh/python-net/create-document/) - 本文描述了如何使用 Python 创建 PDF 文件。 +- [打开 PDF 文档](/pdf/zh/python-net/open-pdf-document/) - 本文描述了在 Python 应用程序中打开 PDF 文档的各种方法。 +- [保存 PDF 文档](/pdf/zh/python-net/save-pdf-document/) - 本文描述了保存 PDF 文档的各种方法。 +- [合并 PDF](/pdf/zh/python-net/merge-pdf/) - 使用 Python 将多个 PDF 文件合并为单个 PDF 文档。 +- [拆分 PDF](/pdf/zh/python-net/split-pdf/) - 在您的 Python 应用程序中将 PDF 页面拆分为单独的 PDF 文件。 +- [保护 PDF 文件](/pdf/zh/python-net/protect-pdf-file/) - 使用 Aspose.PDF for .NET 保护您的 PDF 文件 diff --git a/zh/python-net/basic-operations/create/_index.md b/zh/python-net/basic-operations/create/_index.md index 5f4f5c029d..990ef7bb9f 100644 --- a/zh/python-net/basic-operations/create/_index.md +++ b/zh/python-net/basic-operations/create/_index.md @@ -1,36 +1,39 @@ --- -title: 程序化创建PDF文档 -linktitle: 创建PDF +title: 以编程方式创建 PDF 文档 +linktitle: 创建 PDF type: docs weight: 10 url: /zh/python-net/create-document/ -description: 本页描述如何使用Aspose.PDF for Python via .NET库从头开始创建PDF文档。 +description: 本页描述了如何使用 Aspose.PDF for Python via .NET 库从头开始创建 PDF 文档。 +lastmod: "2026-06-08" +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python 生成 PDF 文件 +Abstract: 在软件开发中,以编程方式生成 PDF 文件是一个常见需求,尤其是用于创建报告和其他文档。为此任务编写自定义代码可能效率低下且耗时。相反,开发者可以使用 **Aspose.PDF for Python via .NET**,这是一种使用 Python 创建 PDF 文件的强大解决方案。该过程包括创建一个 `Document` 对象,将 `Page` 对象添加到文档的 `Pages` 集合中,将 `TextFragment` 插入到页面的 `paragraphs` 集合中,然后保存文档。示例 Python 代码片段演示了这些步骤,展示了使用 Aspose.PDF 生成 PDF 文件的简便性。 --- -对于开发人员来说,在许多情况下需要程序化地生成PDF文件。您可能需要在软件中程序化地生成PDF报告和其他PDF文件。从头编写自己的代码和函数既漫长又低效。要使用Python创建PDF文件,有一个更好的解决方案 - **Aspose.PDF for Python via .NET**。 +对于开发者来说,有许多情景需要以编程方式生成 PDF 文件。您可能需要在软件中以编程方式生成 PDF 报告和其他 PDF 文件。自行从头编写代码和函数既冗长又低效。要使用 Python 创建 PDF 文件,有一个更好的解决方案——**Aspose.PDF for Python via .NET**。 -## 如何使用Python创建PDF文件 +## 如何使用 Python 创建 PDF 文件 -要使用Python创建PDF文件,可以使用以下步骤。 +使用 Python 创建 PDF 文件,可按照以下步骤进行。 -1. 创建一个[Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)类的对象 - -1. 将 [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 对象添加到 Document 对象的 [Pages](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties) 集合中 -1. 将 [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/) 添加到页面的 [paragraphs](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) 集合中 +1. 创建一个对象 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类 +1. 添加一个 [页面](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 对象到 [页面](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#properties) Document 对象的集合 +1. 添加 [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/) 到 [段落](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties) 页面集合 1. 保存生成的 PDF 文档 ```python - - import aspose.pdf as ap - - # 初始化文档对象 - document = ap.Document() - # 添加页面 - page = document.pages.add() - # 初始化 textfragment 对象 - text_fragment = ap.text.TextFragment("Hello,world!") - # 将文本片段添加到新页面 - page.paragraphs.add(text_fragment) - # 保存更新后的 PDF - document.save("output.pdf") -``` \ No newline at end of file +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/zh/python-net/basic-operations/merge-pdf/_index.md b/zh/python-net/basic-operations/merge-pdf/_index.md new file mode 100644 index 0000000000..74d855bdbc --- /dev/null +++ b/zh/python-net/basic-operations/merge-pdf/_index.md @@ -0,0 +1,44 @@ +--- +title: 在 Python 中合并 PDF 文件 +linktitle: 合并 PDF 文件 +type: docs +weight: 50 +url: /zh/python-net/merge-pdf/ +description: 了解如何在 Python 中将多个 PDF 文件合并为单个文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 合并 PDF 页面 +Abstract: 本文讨论了将多个 PDF 文件合并为单个文档的常见需求,这一过程对于组织、优化存储和共享 PDF 内容非常有价值。文章探讨了使用 Aspose.PDF for Python via .NET 高效合并 PDF 文件,并指出在没有第三方库的情况下,Python 中合并 PDF 可能具有挑战性。本文提供了逐步指南来串联 PDF 文件——创建新文档、合并文件以及保存合并后的文档。代码片段演示了使用 Aspose.PDF 实现的方式,突出该库简化合并过程的能力。此外,文章还介绍了 Aspose.PDF Merger,这是一款用于合并 PDF 的在线工具,使用户能够在基于 Web 的环境中体验其功能。 +--- + +## 使用 Python 和 DOM 合并 PDF 文件 + +合并两个 PDF 文件: + +1. 创建一个新文档。 +1. 合并 PDF 文件 +1. 保存合并文档 + +将多个 PDF 文档合并为单个文件: + +```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) +``` + +## 实时示例 + +[Aspose.PDF 合并器](https://products.aspose.app/pdf/merger) 是一个免费在线网络应用程序,允许您调查演示合并功能的工作原理。 + +[![Aspose.PDF 合并器](merger.png)](https://products.aspose.app/pdf/merger) + diff --git a/zh/python-net/basic-operations/merge-pdf/merger.png b/zh/python-net/basic-operations/merge-pdf/merger.png new file mode 100644 index 0000000000..c7977aa68d Binary files /dev/null and b/zh/python-net/basic-operations/merge-pdf/merger.png differ diff --git a/zh/python-net/basic-operations/opening/_index.md b/zh/python-net/basic-operations/opening/_index.md index 4e15137f7e..178dcb981d 100644 --- a/zh/python-net/basic-operations/opening/_index.md +++ b/zh/python-net/basic-operations/opening/_index.md @@ -1,49 +1,54 @@ --- -title: 以编程方式打开PDF文档 -linktitle: 打开PDF +title: 以编程方式打开 PDF 文档 +linktitle: 打开 PDF type: docs weight: 20 url: /zh/python-net/open-pdf-document/ -description: 了解如何在Python Aspose.PDF for Python via .NET库中打开PDF文件。您可以打开现有的PDF、从流中打开文档以及加密的PDF文档。 -lastmod: "2022-12-22" +description: 了解如何使用 Python Aspose.PDF for Python via .NET 库打开 PDF 文件。您可以打开现有的 PDF、来自流的文档以及加密的 PDF 文档。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF 库在 Python 中打开 PDF 文档 +Abstract: 本文提供了使用 Aspose.PDF 库在 Python 中打开现有 PDF 文档的指南。它概述了三种实现方法——通过指定文件名打开 PDF、从流中打开 PDF,以及通过提供密码打开受密码保护的 PDF。每种方法都包含代码片段,演示如何利用 Aspose.PDF 库访问 PDF 并打印其页数。这些示例展示了 Aspose.PDF 在处理不同 PDF 文件访问场景时的灵活性和功能性。 --- -## 打开现有的PDF文档 +## 打开现有 PDF 文档 -有几种方法可以打开文档。最简单的是指定文件名。 +打开文档有多种方式。最简单的是指定文件名。 ```python +import aspose.pdf as ap - import aspose.pdf as ap +def open_document_from_file(infile): - # 打开文档 - document = ap.Document(input_pdf) + # Open document + document = ap.Document(infile) print("Pages: " + str(len(document.pages))) ``` -## 从流中打开现有的PDF文档 +## 从流打开现有 PDF 文档 ```python - - import aspose.pdf as ap - - input_pdf = DIR_INPUT + "sample.pdf" - stream = io.FileIO(input_pdf, 'r') - # 打开文档 - document = ap.Document(stream) - print("Pages: " + str(len(document.pages))) +import aspose.pdf as ap +import io + +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))) ``` -## 打开加密的PDF文档 +## 打开加密的 PDF 文档 ```python +import aspose.pdf as ap - import aspose.pdf as ap - - # 打开文档 - document = ap.Document(input_pdf, password) +def open_document_encrypted(infile): + password = "P@ssw0rd" + # Open document + document = ap.Document(infile, password) print("Pages: " + str(len(document.pages))) -``` \ No newline at end of file +``` diff --git a/zh/python-net/basic-operations/protect/_index.md b/zh/python-net/basic-operations/protect/_index.md new file mode 100644 index 0000000000..b75e81581b --- /dev/null +++ b/zh/python-net/basic-operations/protect/_index.md @@ -0,0 +1,219 @@ +--- +title: 在 Python 中保护 PDF 文件 +linktitle: 加密和解密 PDF 文件 +type: docs +weight: 70 +url: /zh/python-net/protect-pdf-file/ +description: 了解如何在 Python 中加密文件、解密受保护的 PDF 并更改密码。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中设置 PDF 权限并管理加密。 +Abstract: 本页介绍了如何使用 Aspose.PDF for Python via .NET 设置文档权限、应用加密、解密 PDF 文件以及更改密码。它涵盖了配置用户密码和所有者密码、定义访问限制(例如打印、复制和编辑),以及在 Python 应用程序中管理 PDF 安全。 +--- + +## 使用密码和权限加密 PDF + +使用 Aspose.PDF for Python via .NET 对 PDF 文档进行基于密码的加密并限制权限。 + +1. 加载 PDF 文档。 +1. 创建一个 `DocumentPrivilege` 权限对象。 +1. 启用所需的权限。 +1. 设置用户密码和所有者密码。 +1. 选择加密算法。 +1. 对文档应用加密。 +1. 保存加密后的 PDF。 + +```python +import aspose.pdf as ap + +def encrypt_password(infile, outfile): + """ + Encrypt PDF with password and permissions. + + Args: + infile (str): Input PDF filename + outfile (str): Output PDF filename + + Returns: + None + + Example: + encrypt_password("sample.pdf", "sample_protected.pdf") + + Note: + Uses AES 128-bit encryption. Allows screen readers, forbids all other operations. + User password: "userpassword", Owner password: "ownerpassword". + """ + document = ap.Document(infile) + document_privilege = ap.facades.DocumentPrivilege.forbid_all + document_privilege.allow_screen_readers = True + + document.encrypt( + "userpassword", + "ownerpassword", + document_privilege, + ap.CryptoAlgorithm.AESx128, + False, + ) + document.save(outfile) +``` + +## 使用完整权限加密 PDF + +使用 Aspose.PDF for Python via .NET 对 PDF 文档进行加密,同时允许完整的访问权限。此示例使用 RC4 128 位加密,以兼容较旧的 PDF 查看器。 + +1. 加载 PDF 文档。 +1. 定义用户密码和所有者密码。 +1. 设置完整访问权限。 +1. 选择加密算法。 +1. 调用 `encrypt()` 带有密码、权限和算法。 +1. 保存加密后的 PDF。 + +```python +import aspose.pdf as ap + +def encrypt_pdf_file(infile, outfile): + """ + Encrypt PDF with full permissions. + + Args: + infile (str): Input PDF filename + outfile (str): Output PDF filename + + Returns: + None + + Example: + encrypt_pdf_file("sample.pdf", "sample_protected.pdf") + + Note: + Uses RC4 128-bit encryption with allow_all privileges. + """ + document = ap.Document(infile) + document.encrypt( + "userpassword", + "ownerpassword", + ap.facades.DocumentPrivilege.allow_all, + ap.CryptoAlgorithm.RC4x128, + False, + ) + document.save(outfile) +``` + +## 使用所有者密码解密 PDF 文件 + +要移除密码保护并恢复完全访问权限: + +1. 使用正确的密码(用户或拥有者)加载加密的 PDF。 +1. 从文档中移除所有密码保护和加密设置。 +1. 将现在未受保护的 PDF 保存到指定的输出文件。 + +```python +import aspose.pdf as ap + +def decrypt_pdf_file(infile, outfile): + """ + Decrypt password-protected PDF. + + Args: + infile (str): Input encrypted PDF filename + outfile (str): Output decrypted PDF filename + + Returns: + None + + Example: + decrypt_pdf_file("sample_protected.pdf", "sample_unprotected.pdf") + + Note: + Requires user password to open document. + """ + document = ap.Document(infile, "userpassword") + document.decrypt() + document.save(outfile) +``` + +## 更改 PDF 文件的密码 + +在保留 PDF 文档内容和结构的同时,更新其安全凭证(用户密码和所有者密码)。 + +1. 使用现有的拥有者密码打开 PDF,该密码提供对安全设置的完全访问权限。 +1. 将旧密码替换为新的用户密码和新的拥有者密码。 +1. 使用更新的密码设置保存 PDF。 + +```python +import aspose.pdf as ap + +def change_password(infile, outfile): + """ + Change user and owner passwords. + + Args: + infile (str): Input PDF filename + outfile (str): Output PDF filename + + Returns: + None + + Example: + change_password("sample_protected.pdf", "sample_changepassword.pdf") + + Note: + Changes from ownerpassword to newuser/newowner. + """ + document = ap.Document(infile, "ownerpassword") + document.change_passwords("ownerpassword", "newuser", "newowner") + document.save(outfile) + +``` + +## 从数组中确定正确的密码 + +在某些情况下,您可能需要从可能的候选密码列表中识别出正确的密码以访问受保护的 PDF。下面的代码片段检查 PDF 文件是否已加密,然后通过遍历预定义的密码列表尝试打开它。 + +该过程包括: + +1. 使用 `PdfFileInfo` 检测 PDF 是否被加密。 +1. 使用每个密码打开 PDF `ap.Document()`. +1. 如果成功,它会打印页数。 +1. 如果不是,它会捕获异常并报告密码错误。 + +```python +import aspose.pdf as ap + +def determine_correct_password_from_list(infile): + """ + Test multiple passwords to find correct one. + + Args: + infile (str): Input encrypted PDF filename + + Returns: + None + + Example: + determine_correct_password_from_list("sample_protected.pdf") + + Note: + Tries passwords: test, test1, test2, test3, userpassword. + Prints page count if password is correct. + """ + info = ap.facades.PdfFileInfo(infile) + print(f"File is password protected {info.is_encrypted}") + + passwords = "test", "test1", "test2", "test3", "userpassword" + + for password in passwords: + try: + document = ap.Document(infile, password) + count = len(document.pages) + if count > 0: + print(f"Number of Page in document are = {count}") + except RuntimeError as ex: + template = "An exception of type {0} occurred. Arguments:\n{1!r}" + message = template.format(type(ex).__name__, ex.args) + print(message) +``` diff --git a/zh/python-net/basic-operations/saving/_index.md b/zh/python-net/basic-operations/saving/_index.md index 3d9c88150d..f926ae7749 100644 --- a/zh/python-net/basic-operations/saving/_index.md +++ b/zh/python-net/basic-operations/saving/_index.md @@ -1,59 +1,68 @@ --- -title: 程序化地保存 PDF 文档 +title: 以编程方式保存 PDF 文档 linktitle: 保存 PDF type: docs weight: 30 url: /zh/python-net/save-pdf-document/ -description: 学习如何在 Python Aspose.PDF for Python via .NET 库中保存 PDF 文件。将 PDF 文档保存到文件系统、流和 Web 应用程序中。 -lastmod: "2022-12-22" +description: 了解如何在 Python 中使用 Aspose.PDF for Python via .NET 库保存 PDF 文件。将 PDF 文档保存到文件系统、流以及 Web 应用程序中。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF 库在 Python 中保存 PDF 文档 +Abstract: 本文提供了使用 Aspose.PDF 库在 Python 中保存 PDF 文档的指南。它概述了保存 PDF 的三种主要方法——保存到文件系统、保存到流以及保存为特定格式,如 PDF/A 或 PDF/X。`save()` 方法是 `Document` 类的核心操作。要将 PDF 保存到文件系统,可以创建或操作文档,例如添加新页面,然后直接保存到路径。对于保存到流,`Save` 方法的重载允许将文档写入流对象。此外,本文解释了如何将文档保存为 PDF/A 或 PDF/X 格式,这些分别是长期归档和图形交换的标准。此过程需要在保存之前使用 `convert` 方法准备文档。提供的 Python 代码示例演示了每种方法,展示了这些方法的实际应用。 --- -## 将 PDF 文档保存到文件系统 +## 保存 PDF 文档到文件系统 -您可以使用 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类的 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法将创建或操作的 PDF 文档保存到文件系统。 +您可以使用 将创建或操作的 PDF 文档保存到文件系统 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类。 ```python +import aspose.pdf as ap - import aspose.pdf as ap - - document = ap.Document(input_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(output_pdf) + document.save(outfile) ``` ## 将 PDF 文档保存到流 -您也可以通过使用 `Save` 方法的重载将创建或操作的 PDF 文档保存到流。 +您还可以通过使用重载,将创建或处理后的 PDF 文档保存到流中 `Save` 方法。 ```python +import aspose.pdf as ap +import io - import aspose.pdf as ap - - document = ap.Document(input_pdf) - # 进行一些操作,例如添加新空白页 +def save_document_to_stream(infile, outfile): + document = ap.Document(infile) + # make some manipulation, e.g. add new empty page document.pages.add() - document.save(io.FileIO(output_pdf, 'w')) + with io.FileIO(outfile, 'w') as stream: + document.save(stream) ``` +## 保存 PDF/A 或 PDF/X 格式 -## 保存为 PDF/A 或 PDF/X 格式 +您可以轻松地将文档保存为特定的 PDF 版本,例如 PDF/A 或 PDF/X。在这种情况下,我们需要在保存文档之前调用 convert 方法。 -PDF/A 是一种 ISO 标准化的便携文档格式 (PDF) 版本,用于电子文档的归档和长期保存。 PDF/A 与 PDF 的不同之处在于,它禁止不适合长期归档的功能,例如字体链接(与字体嵌入相对)和加密。 ISO 对 PDF/A 查看器的要求包括颜色管理指南、嵌入字体支持以及用于读取嵌入注释的用户界面。 +PDF/A 是一种经 ISO 标准化的便携文档格式(PDF)版本,用于归档和长期保存电子文档。 +PDF/A 与 PDF 的区别在于它禁止不适合长期归档的功能,例如字体链接(相对于字体嵌入)和加密。ISO 对 PDF/A 查看器的要求包括颜色管理指南、嵌入字体支持以及用于读取嵌入注释的用户界面。 -PDF/X 是 PDF ISO 标准的一个子集。 PDF/X 的目的是促进图形交换,因此它具有一系列不适用于标准 PDF 文件的打印相关要求。 +PDF/X 是 PDF ISO 标准的子集。PDF/X 的目的是促进图形交换,因此它具有一系列不适用于标准 PDF 文件的印刷相关要求。 -在这两种情况下,使用 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法来存储文档,而文档必须使用 [convert](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法进行准备。 +在这两种情况下, [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 此方法用于存储文档,而文档必须使用 [转换](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法。 ```python +import aspose.pdf as ap +import io - import aspose.pdf as ap - document = ap.Document(input_pdf) +def save_document_as_standard(infile, outfile, logfile): + document = ap.Document(infile) document.pages.add() - document.convert(output_log, ap.PdfFormat.PDF_X_3, ap.ConvertErrorAction.DELETE) - document.save(output_pdf) -``` \ No newline at end of file + document.convert(logfile, ap.PdfFormat.PDF_X_3, ap.ConvertErrorAction.DELETE) + document.save(outfile) +``` diff --git a/zh/python-net/basic-operations/split-pdf/_index.md b/zh/python-net/basic-operations/split-pdf/_index.md new file mode 100644 index 0000000000..b8f1b89fb9 --- /dev/null +++ b/zh/python-net/basic-operations/split-pdf/_index.md @@ -0,0 +1,60 @@ +--- +title: 在Python中拆分PDF文件 +linktitle: 拆分PDF文件 +type: docs +weight: 60 +url: /zh/python-net/split-pdf/ +description: 了解如何在 Python 中将 PDF 页面拆分为单独的 PDF 文件。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 拆分 PDF 页面 +Abstract: 本文讨论了使用 Python 将 PDF 页面拆分为单个文件的过程,强调该功能在管理大型 PDF 文档时的实用性。文中提到了 Aspose.PDF Splitter,这是一个用于演示 PDF 拆分功能的在线工具。本文提供了在 Python 应用程序中实现此功能的详细方法,涉及通过 `Document` 对象的 `PageCollection` 迭代 PDF 文档的页面。对每一页,创建一个新的 `Document` 对象,将该页添加进去,并使用 `save()` 方法保存新的 PDF 文件。随附的 Python 代码片段展示了此过程,说明了通过遍历页面并将每页保存为单独的 PDF 来将 PDF 文档拆分为多个文件的步骤。 +--- + +拆分 PDF 页面对于希望将大型文件拆分为单独页面或页面组的用户来说是一个有用的功能。 + +当您需要将大型 PDF 拆分为单页文件或更小的文档集合以进行分发、审阅或后续处理时,请使用此工作流。 + +## 实时示例 + +[Aspose.PDF 拆分器](https://products.aspose.app/pdf/splitter) 是一个在线免费网络应用程序,允许您调查演示拆分功能的工作原理。 + +[![Aspose 拆分 PDF](splitter.png)](https://products.aspose.app/pdf/splitter) + +本主题展示了如何在您的 Python 应用程序中将 PDF 页面拆分为单独的 PDF 文件。要使用 Python 将 PDF 页面拆分为单页 PDF 文件,可按照以下步骤进行: + +1. 循环遍历 PDF 文档的页面 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象的 [页面集合](https://reference.aspose.com/pdf/python-net/aspose.pdf/pagecollection/) 集合 +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) 方法 + +## 在 Python 中将 PDF 拆分为多个文件或单独的 PDF + +以下 Python 代码片段展示了如何将 PDF 页面拆分为单独的 PDF 文件。 + +```python + + import aspose.pdf as ap + + # Open document + document = ap.Document(input_pdf) + + 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 +``` + +## 相关文档主题 + +- [使用 Python 处理 PDF 文档](/pdf/zh/python-net/working-with-documents/) +- [在 Python 中合并 PDF 文件](/pdf/zh/python-net/merge-pdf-documents/) +- [在 Python 中优化 PDF 文件](/pdf/zh/python-net/optimize-pdf/) +- [在 Python 中操作 PDF 文档](/pdf/zh/python-net/manipulate-pdf-document/) + diff --git a/zh/python-net/basic-operations/split-pdf/splitter.png b/zh/python-net/basic-operations/split-pdf/splitter.png new file mode 100644 index 0000000000..ede55d9927 Binary files /dev/null and b/zh/python-net/basic-operations/split-pdf/splitter.png differ diff --git a/zh/python-net/converting/_index.md b/zh/python-net/converting/_index.md index 023c8fa9e8..57c45cce9a 100644 --- a/zh/python-net/converting/_index.md +++ b/zh/python-net/converting/_index.md @@ -1,69 +1,76 @@ --- -title: 使用Python转换PDF文档 -linktitle: 转换PDF文档 +title: 在 Python 中转换 PDF 文档 +linktitle: 转换 PDF 文档 type: docs weight: 70 url: /zh/python-net/converting/ -lastmod: "2022-12-22" -description: 本节包含有关使用Python API将PDF文档转换为不同格式及相反方向的文章。 +lastmod: "2026-06-08" +description: 了解如何使用 Aspose.PDF for Python via .NET 在 Python 中将 PDF 文档转换为 Word、Excel、PowerPoint、HTML、图像、PDF/A 以及其他格式。 sitemap: changefreq: "monthly" priority: 0.8 +TechArticle: true +AlternativeHeadline: 如何使用 Python 转换 PDF 文档 +Abstract: 本文介绍了 **Aspose.PDF for Python**,这是一种使用 Python 将 PDF 文档转换为多种格式的强大解决方案。Python 作为一种多功能的面向对象编程语言,广泛用于开发软件原型和数据处理应用。文章强调了 Aspose.PDF 将 PDF 转换用于编辑的能力,涵盖了包括文本、图像、超链接等在内的各种文档。该库支持与流行格式之间的相互转换,如 Microsoft Word、Excel、PowerPoint,以及 HTML 和各种图像格式。它还支持转换为 EPUB、Markdown 和用于长期存档的 PDF/A 等专用格式。文章提供了链接,指向使用 Python 编程执行这些转换的详细指南,并附有代码片段以帮助说明。此外,用户还可以通过 Aspose PDF Apps 在线探索转换选项。此综合概述展示了 Aspose.PDF 在 Python 中处理文档转换任务的多样性和易用性。 --- -您想使用Python将PDF转换为其他格式吗?**Aspose.PDF for Python**是转换PDF文档的最佳解决方案。回想一下,Python是一种面向对象的编程语言,用于开发Web应用程序和数据处理的软件原型。现在让我们学习如何使用Python将PDF转换为文本。 +您想使用 Python 将 PDF 转换为其他格式吗?**Aspose.PDF for Python** 是转换 PDF 文档的最佳解决方案。请记住,Python 是一种面向对象的编程语言,可用于开发 Web 应用程序和数据处理的软件原型。现在让我们学习如何使用 Python 将 PDF 转换为文本。 -PDF文件不仅可以包含文本,还可以包含图像、可点击按钮、超链接、嵌入字体、签名、印章等。希望将PDF文件转换为其他格式的用户是为了能够编辑PDF内容。 - -**我们的Aspose.PDF for Python**库允许您成功、快速且轻松地将PDF文档转换为最流行的格式及相反方向。 +PDF 文件不仅可以包含文本,还可以包含图像、可点击按钮、超链接、嵌入字体、签名、印章等。将 PDF 文件转换为其他格式的用户希望这样做是为了能够编辑 PDF 内容。 +**Our Aspose.PDF for Python** 库让您能够成功、快速且轻松地将 PDF 文档转换为最流行的格式,反之亦然。 ## 如何使用 Aspose.PDF 进行转换 -下一节描述了转换 PDF 文档的最常见选项。 -学习代码示例后,您将了解 Aspose.PDF for Python via .NET 库提供了相当通用的解决方案,可以帮助您解决文档转换的任务。 -Aspose.PDF 支持加载和保存最多的流行文档格式。 +下一节介绍了转换 PDF 文档的最常用选项。 +学习完代码示例后,您将了解 Aspose.PDF for Python via .NET 库提供了相当通用的解决方案,帮助您解决文档转换任务。 +Aspose.PDF 支持最多的流行文档格式,可用于加载和保存。 -请注意,当前部分仅描述流行的转换。 -有关支持的格式的完整列表,请参阅部分 [Aspose.PDF 支持的文件格式](https://docs.aspose.com/pdf/python-net/supported-file-formats/)。 +请注意,本节仅描述流行的转换。 +有关受支持格式的完整列表,请参见本节 [Aspose.PDF 支持的文件格式](https://docs.aspose.com/pdf/python-net/supported-file-formats/). -Aspose.PDF for Python via .NET 允许将 PDF 文档转换为各种格式,也可以从其他格式转换为 PDF。此外,您可以使用 Aspose.PDF 转换器应用在线检查 Aspose.PDF 转换的质量并查看结果。通过代码片段学习文档转换的部分。 +Aspose.PDF for Python via .NET 允许将 PDF 文档转换为多种格式,也可以将其他格式转换为 PDF。同时,您可以使用 Aspose.PDF 转换器应用程序检查 Aspose.PDF 转换的质量并在线查看结果。了解使用代码片段进行文档转换的章节。 -Word 文档是最通用和可编辑的格式。 - 将 PDF 手动转换为 Word 是一项非常耗时的任务。在本文中,您将学习如何在 Python 中以编程方式将 PDF 转换为 Word。 +Word 文档是最通用且可编辑的文档。手动将 PDF 转换为 Word 是一项非常耗时的工作。在本文中,您将学习如何在 Python 中以编程方式将 PDF 转换为 Word。 - [将 PDF 转换为 Microsoft Word](/pdf/zh/python-net/convert-pdf-to-word/) - 您可以使用 Python 将 PDF 文档转换为 Word 格式 -数字格式不仅可以使表格中的数据更易于阅读,还可以使表格更易于使用。当然,如果您需要将此类数据从 PDF 文档转换为 Excel 格式,请使用我们的 Aspose.PDF 库。 +数字格式不仅可以使表格中的数据更易阅读,还能让表格更易使用。当然,如果您需要将此类数据从 PDF 文档转换为 Excel 格式,请使用我们的 Aspose.PDF 库。 + +- [将 PDF 转换为 Microsoft Excel](/pdf/zh/python-net/convert-pdf-to-excel/) - 本节描述了如何将 PDF 文档转换为 XLSX、ODS、CSV 和 SpreadSheetML + +PowerPoint 格式用于创建各种演示文稿。PPT 文件包含大量包含各种信息的幻灯片或页面。 + +- [将 PDF 转换为 Microsoft PowerPoint](/pdf/zh/python-net/convert-pdf-to-powerpoint/) - 在这里,我们讨论通过跟踪转换过程将 PDF 转换为 PowerPoint。 -- [将 PDF 转换为 Microsoft Excel](/pdf/zh/python-net/convert-pdf-to-excel/) - 本节介绍如何将 PDF 文档转换为 XLSX、ODS、CSV 和 SpreadSheetML +超文本标记语言是一种超文本文档描述语言,是创建网页的标准语言。使用 Aspose.PDF for Python,您可以轻松地将 HTML 文档相互转换。 -PowerPoint 格式用于创建各种演示文稿。PPT 文件包含大量幻灯片或页面,其中包含各种信息。 +- [将 HTML 格式转换为 PDF 文件](/pdf/zh/python-net/convert-html-to-pdf/) - 有关 HTML 转 PDF 转换的不同方面的文章。 +- [将 PDF 文件转换为 HTML 格式](/pdf/zh/python-net/convert-pdf-to-html/) - 将您的 PDF 文档转换为 HTML 文件,作为单独页面或单一页面。 -- [将 PDF 转换为 Microsoft PowerPoint](/pdf/zh/python-net/convert-pdf-to-powerpoint/) - 这里我们讨论通过跟踪转换过程将 PDF 转换为 PowerPoint +有许多图像格式需要根据不同用途转换为 PDF。Aspose.PDF 支持最流行的图像格式相互转换。 -超文本标记语言是一种超文本文档描述语言,是创建网页的标准语言。 使用 Aspose.PDF for Python,您可以轻松地转换 HTML 文档及其反向转换。 +- [将 PDF 转换为各种图像格式](/pdf/zh/python-net/convert-pdf-to-images-format/) - 将 PDF 页面转换为 JPEG、PNG 等格式的图像。 -- [将 HTML 格式转换为 PDF 文件](/pdf/zh/python-net/convert-html-to-pdf/) - 关于 HTML 到 PDF 转换的不同方面的文章 -- [将 PDF 文件转换为 HTML 格式](/pdf/zh/python-net/convert-pdf-to-html/) - 将您的 PDF 文档转换为 HTML 文件,可以是单独的页面或单个页面 +本节包括以下格式:EPUB、Markdown、PCL、XPS、LATex/TeX、Text 和 PostScript。 -有许多图像格式需要转换为 PDF 以满足不同的目的。Aspose.PDF 允许最流行的图像格式及其反向转换。 +- [将 PDF 文件转换为其他格式](/pdf/zh/python-net/convert-pdf-to-other-files/) - 本主题描述了将 PDF 文档转换为各种格式的方法。 -- [将 PDF 转换为各种图像格式](/pdf/zh/python-net/convert-pdf-to-images-format/) - 将 PDF 页面转换为 JPEG、PNG 和其他格式的图像 +PDF/A 是 PDF 的一个版本,旨在长期归档电子文档。 +说实话,从外部很难判断它是 PDF 还是 PDF/A。要检查此文件,需要使用验证器。请查看以下文章,以获取高质量的 PDF 与 PDF/A 相互转换。 -本节包括以下格式:EPUB、Markdown、PCL、XPS、LATex/TeX、文本和 PostScript。 +- [将图像格式转换为 PDF 文件](/pdf/zh/python-net/convert-images-format-to-pdf/) - Aspose.PDF 允许您将不同格式的图像转换为 PDF 文件。 -- [将 PDF 文件转换为其他格式](/pdf/zh/python-net/convert-pdf-to-other-files/) - 本主题描述了将 PDF 文档转换为各种格式的方法 +- [将其他文件格式转换为 PDF](/pdf/zh/python-net/convert-other-files-to-pdf/) - 本主题描述了使用 EPUB、XPS、Postscript、文本等各种格式的转换。 -PDF/A 是一种专为电子文档长期归档而设计的 PDF 版本。 -坦白说,从外部很难确定它是 PDF 还是 PDF/A。 要检查此文件,使用了验证器。请查看以下文章,以确保高质量地将 PDF 转换为 PDF/A 及其相反过程。 +- [将 PDF/x 转换为 PDF](/pdf/zh/python-net/convert-pdf_x-to-pdf/) - 本主题描述了将 PDF/UA 和 PDF/A 转换为 PDF。 -- [将 PDF 转换为 PDF/A 格式](/pdf/zh/python-net/convert-pdf-to-pdfa/) - Aspose.PDF 的 Python 库提供了简单的方法来将 PDF 转换为 PDF/A +- [将 PDF 转换为 PDF/x](/pdf/zh/python-net/convert-pdf-to-pdf_x/) - 本主题描述了将 PDF 转换为 PDF/A、PDF/E 和 PDF/X 格式。 ## 尝试在线转换 PDF 文件 {{% alert color="success" %}} -您可以使用我们的 Aspose PDF 应用程序尝试转换功能: +您可以通过使用我们的 Aspose PDF 应用程序来尝试转换功能: -[![Aspose PDF 应用](app.png)](https://products.aspose.app/pdf/conversion) -{{% /alert %}} \ No newline at end of file +[![Aspose PDF 应用程序](app.png)](https://products.aspose.app/pdf/conversion) +{{% /alert %}} diff --git a/zh/python-net/converting/app.png b/zh/python-net/converting/app.png new file mode 100644 index 0000000000..6135eb7bcd Binary files /dev/null and b/zh/python-net/converting/app.png differ diff --git a/zh/python-net/converting/convert-html-to-pdf/_index.md b/zh/python-net/converting/convert-html-to-pdf/_index.md index fd177407d0..40f24a72ff 100644 --- a/zh/python-net/converting/convert-html-to-pdf/_index.md +++ b/zh/python-net/converting/convert-html-to-pdf/_index.md @@ -1,54 +1,202 @@ --- -title: 将 HTML 转换为 PDF 在 Python 中 +title: 在 Python 中将 HTML 转换为 PDF linktitle: 将 HTML 转换为 PDF 文件 type: docs weight: 40 url: /zh/python-net/convert-html-to-pdf/ -lastmod: "2022-12-22" -description: 本主题向您展示如何使用 Aspose.PDF 将 HTML 转换为 PDF 和 MHTML 转换为 PDF 在 Python 中。 +lastmod: "2026-06-08" +description: 了解如何在 Python 中使用 Aspose.PDF for Python via .NET 将 HTML 和 MHTML 转换为 PDF,包括 CSS 媒体设置、嵌入式字体和标记 PDF 输出。 sitemap: changefreq: "monthly" priority: 0.8 +TechArticle: true +AlternativeHeadline: 如何在 Python 中使用 Aspose.PDF 将 HTML 转换为 PDF +Abstract: 本文解释了如何使用 Aspose.PDF for Python via .NET 将 HTML 和 MHTML 文件转换为 PDF。它涵盖了基本的 HTML 转 PDF 工作流,并展示了如何通过媒体类型、CSS 页面规则优先级、嵌入字体、单页输出以及逻辑结构生成来控制渲染,以创建可访问的标记 PDF。 --- -## 概述 +## Python HTML 转 PDF 转换 -Aspose.PDF for Python via .NET 是一个专业解决方案,可让您在应用程序中从网页和原始 HTML 代码创建 PDF 文件。 +**Aspose.PDF for Python via .NET** 允许您将现有的 HTML 文档转换为 PDF,并提供灵活的渲染选项。您可以微调输出的生成方式,以符合您的布局、样式、可访问性和归档要求。 -本文解释了如何 **使用 Python 将 HTML 转换为 PDF**。它涵盖以下主题。 +## 将HTML转换为PDF -_格式_:**HTML** -- [Python HTML 转换为 PDF](#python-html-to-pdf) -- [Python 转换 HTML 为 PDF](#python-html-to-pdf) -- [Python 如何将 HTML 转换为 PDF](#python-html-to-pdf) +以下 Python 示例展示了将 HTML 文档转换为 PDF 的基本工作流程。 -## Python HTML 转 PDF 转换 +1. 创建该实例 [HtmlLoadOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/htmlloadoptions/) 类。 +1. 初始化一个 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 包含源 HTML 文件的对象。 +1. 通过调用保存输出的 PDF 文档 `document.save()`. -**Aspose.PDF for Python** 是一个 PDF 操作 API,它可以让您无缝地将任何现有的 HTML 文档转换为 PDF。HTML 转换为 PDF 的过程可以灵活定制。 +```python +from os import path +import aspose.pdf as ap -## 将 HTML 转换为 PDF +path_infile = path.join(self.data_dir, infile) +path_outfile = path.join(self.data_dir, "python", outfile) -以下 Python 代码示例展示了如何将 HTML 文档转换为 PDF。 +load_options = ap.HtmlLoadOptions() +load_options.page_layout_option = ap.HtmlPageLayoutOption.SCALE_TO_PAGE_WIDTH +document = ap.Document(path_infile, load_options) +document.save(path_outfile) +print(infile + " converted into " + outfile) +``` -1. 创建一个 [HtmlLoadOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/htmlloadoptions/) 类的实例。 -2. 初始化 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象。 -3. 通过调用 **Document.Save()** 方法保存输出 PDF 文档。 +## 相关转换 + +- [将 PDF 转换为 HTML](/pdf/zh/python-net/convert-pdf-to-html/) 当您需要从现有 PDF 文件生成适用于 Web 的输出时。 +- [将其他文件格式转换为 PDF](/pdf/zh/python-net/convert-other-files-to-pdf/) 用于 EPUB、XPS、文本和 PostScript 的转换工作流。 +- [将图像转换为 PDF](/pdf/zh/python-net/convert-images-format-to-pdf/) 当您的源内容是基于图像而不是 HTML 标记时。 + +{{% alert color="success" %}} +**尝试在线将HTML转换为PDF** + +Aspose 推出在线应用程序 ["HTML 转 PDF"](https://products.aspose.app/html/en/conversion/html-to-pdf), 您可以在此测试转换质量和输出。 + +[![使用 App 将 HTML 转换为 PDF 的 Aspose.PDF](html.png)](https://products.aspose.app/html/en/conversion/html-to-pdf) +{{% /alert %}} + +## 使用媒体类型将HTML转换为PDF + +此示例展示了如何使用特定的渲染选项将 HTML 文件转换为 PDF。 + +1. 创建该实例 [HtmlLoadOptions()](https://reference.aspose.com/pdf/python-net/aspose.pdf/htmlloadoptions/) 类。 +1. 设置 `html_media_type` 应用针对屏幕或打印布局的 CSS 规则,例如 `HtmlMediaType.SCREEN` 或 `HtmlMediaType.PRINT`. +1. 将 HTML 加载到一个 `ap.Document` 使用加载选项。 +1. 将文档保存为 PDF。 ```python +from os import path +import aspose.pdf as ap - import aspose.pdf as ap +path_infile = path.join(self.data_dir, infile) +path_outfile = path.join(self.data_dir, "python", outfile) - input_pdf = DIR_INPUT + "little_html.html" - output_pdf = DIR_OUTPUT + "convert_html_to_pdf.pdf" - options = ap.HtmlLoadOptions() - document = ap.Document(input_pdf, options) - document.save(output_pdf) +load_options = ap.HtmlLoadOptions() +load_options.html_media_type = ap.HtmlMediaType.SCREEN +document = ap.Document(path_infile, load_options) +document.save(path_outfile) +print(infile + " converted into " + outfile) ``` -{{% alert color="success" %}} -**尝试在线将 HTML 转换为 PDF** +## 优先处理 CSS `@page` HTML 转 PDF 转换期间的规则 + +有些文档使用 [这个 `@page` 规则](https://developer.mozilla.org/en-US/docs/Web/CSS/@page) 用于页面布局。如果这些样式与其他设置冲突,您可以使用 `is_priority_css_page_rule`. + +1. 创建该实例 [HtmlLoadOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/htmlloadoptions/) 类。 +1. 设置 `is_priority_css_page_rule = False` 让其他样式获得更高的优先级 `@page` 规则。 +1. 将 HTML 加载到一个 `ap.Document` 使用已配置的选项。 +1. 将文档保存为 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.HtmlLoadOptions() +# load_options.is_priority_css_page_rule = False +document = ap.Document(path_infile, load_options) +document.save(path_outfile) +print(infile + " converted into " + outfile) +``` + +## 将 HTML 转换为带嵌入字体的 PDF + +本示例展示了如何在嵌入字体的同时将 HTML 文件转换为 PDF。如果您需要输出 PDF 保留原始排版,请设置 `is_embed_fonts` 到 `True`. + +1. 创建 `HtmlLoadOptions()` 配置 HTML 到 PDF 转换。 +1. 设置 `is_embed_fonts = True` 将HTML中使用的字体直接嵌入PDF。 +1. 将 HTML 加载到一个 `ap.Document` 使用这些选项。 +1. 将文档保存为 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) -Aspose 向您展示在线免费应用程序 ["HTML to PDF"](https://products.aspose.app/html/en/conversion/html-to-pdf),您可以在其中尝试研究其功能和工作质量。 +load_options = ap.HtmlLoadOptions() +load_options.is_embed_fonts = True +document = ap.Document(path_infile, load_options) +document.save(path_outfile) +print(infile + " converted into " + outfile) +``` + +## 在单个 PDF 页面上渲染 HTML 内容 + +本示例演示如何使用 Aspose.PDF for Python via .NET 将 HTML 文件转换为单页 PDF。使用 `is_render_to_single_page` 属性,当您希望将完整的 HTML 内容渲染到同一连续页面时。 + +1. 创建实例 `HtmlLoadOptions()` 配置转换过程。 +1. 启用 `is_render_to_single_page` 将在单页上渲染完整的HTML内容。 +1. 使用已配置的选项加载文档到一个 `ap.Document`. +1. 将结果保存为 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) + +options = ap.HtmlLoadOptions() +options.is_render_to_single_page = True + +doc = ap.Document(path_infile, options) +doc.save(path_outfile) +``` + +## 从 HTML 标记创建逻辑结构 + +逻辑结构,也称为 Tagged PDF,保留了原始 HTML 的语义层次结构,例如标题、段落和列表。这使得生成的 PDF 更具可访问性、可搜索性,并适用于结构化文档工作流。 + +通过在转换过程中启用逻辑结构,HTML DOM 被映射到 PDF 标记树中,而不是仅作为可视内容进行渲染。 -[![Aspose.PDF 转换 HTML 为 PDF 使用免费应用](html.png)](https://products.aspose.app/html/en/conversion/html-to-pdf) -{{% /alert %}} \ No newline at end of file +为了满足可访问性要求,PDF 应该包含定义阅读顺序的逻辑结构元素,提供屏幕阅读器的替代文本,并保留内容的层次结构。 + +> 输出 PDF 中逻辑结构的质量直接取决于原始 HTML 标记的质量。结构不良或无效的 HTML 可能导致转换后的 PDF 中标记不完整或不准确。 + +1. 创建一个 HtmlLoadOptions 实例,以控制 HTML 的转换方式。 +1. 激活语义标记,使 PDF 包含结构化元素。 +1. 使用配置的选项打开 HTML 文件。 +1. 保存结构化的 PDF。 + +```python +import aspose.pdf as ap + +# Path to the source HTML +input_html_path = "input.html" +# Path for the Logical Structure PDF +output_pdf_path = "output_logical_structure.pdf" +# Initialize HtmlLoadOptions +options = ap.HtmlLoadOptions() +# Convert HTML markup to PDF logical structure elements +options.create_logical_structure = True +# Open PDF document +with ap.Document(input_html_path, options) as document: + # Save PDF document + document.save(output_pdf_path) +``` + +## 将 MHTML 转换为 PDF + +此示例演示如何使用 Aspose.PDF for Python via .NET 将 MHT 或 MHTML 文件转换为具有特定页面尺寸的 PDF 文档。 + +1. 创建实例 `ap.MhtLoadOptions()` 配置 MHTML 文件处理。 +1. 设置各种参数,例如页面大小。 +1. 使用输入文件和配置的加载选项初始化文档。 +1. 将生成的文档保存为 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.MhtLoadOptions() +load_options.page_info.width = 842 +load_options.page_info.height = 1191 +document = ap.Document(path_infile, load_options) +document.save(path_outfile) +print(infile + " converted into " + outfile) +``` diff --git a/zh/python-net/converting/convert-html-to-pdf/html.png b/zh/python-net/converting/convert-html-to-pdf/html.png new file mode 100644 index 0000000000..68fa4a3696 Binary files /dev/null and b/zh/python-net/converting/convert-html-to-pdf/html.png differ diff --git a/zh/python-net/converting/convert-images-format-to-pdf/_index.md b/zh/python-net/converting/convert-images-format-to-pdf/_index.md new file mode 100644 index 0000000000..af31af1faf --- /dev/null +++ b/zh/python-net/converting/convert-images-format-to-pdf/_index.md @@ -0,0 +1,359 @@ +--- +title: 在 Python 中将图像格式转换为 PDF +linktitle: 将图像转换为 PDF +type: docs +weight: 60 +url: /zh/python-net/convert-images-format-to-pdf/ +lastmod: "2026-06-08" +description: 了解如何使用 Aspose.PDF for Python via .NET 在 Python 中将 BMP、CGM、DICOM、PNG、TIFF、EMF、SVG 等图像格式转换为 PDF。 +sitemap: + changefreq: "monthly" + priority: 0.5 +TechArticle: true +AlternativeHeadline: 如何在 Python 中将图像转换为 PDF +Abstract: 本文提供了一份关于使用 Python 将各种图像格式转换为 PDF 的综合指南,特别是利用 Aspose.PDF for Python via .NET 库。文章涵盖了 BMP、CGM、DICOM、EMF、GIF、PNG、SVG 和 TIFF 等多种图像格式。每个章节详细说明了执行转换所需的步骤,并提供代码片段以演示该过程。例如,将 BMP 转换为 PDF 包括创建一个新的 PDF 文档、定义图像位置、插入图像以及保存文档。类似地,对于 CGM、DICOM 等格式,文中列出了特定的加载选项和处理步骤。文章还强调了使用 Aspose.PDF 执行此类任务的优势,例如它对不同编码方式的支持以及能够处理单帧和多帧图像的能力。 +--- + +## 相关转换 + +- [将 PDF 转换为图像格式](/pdf/zh/python-net/convert-pdf-to-images-format/) 当您需要反向工作流时。 +- [将HTML转换为PDF](/pdf/zh/python-net/convert-html-to-pdf/) 用于网页内容和 MHTML 源。 +- [将其他文件格式转换为 PDF](/pdf/zh/python-net/convert-other-files-to-pdf/) 针对 EPUB、XPS、文本以及其他非图像输入。 + +## Python 图像转 PDF 转换 + +**Aspose.PDF for Python via .NET** 允许您将不同格式的图像转换为 PDF 文件。我们的库展示了将最流行的图像格式转换为 PDF 的代码片段,例如 - BMP、CGM、DICOM、EMF、JPG、PNG、SVG 和 TIFF 格式。 + +## 将 BMP 转换为 PDF + +使用 **Aspose.PDF for Python via .NET** 库将 BMP 文件转换为 PDF 文档。 + +BMP 图像是具有扩展名的文件。BMP 代表用于存储位图数字图像的位图图像文件。这些图像独立于图形适配器,也称为设备无关位图(DIB)文件格式。 + +您可以使用 Aspose.PDF for Python via .NET API 将 BMP 转换为 PDF 文件。因此,您可以按照以下步骤将 BMP 图像转换为 PDF: + +在 Python 中将 BMP 转换为 PDF 的步骤: + +1. 创建一个空的 PDF 文档。 +1. 创建您需要的页面,例如,我们创建了 A4,但您可以指定自己的格式。 +1. 将图像(来自 infile)放置在页面内,使用定义的矩形。 +1. 将文档保存为 PDF。 + +因此,下面的代码片段遵循这些步骤,并展示了如何使用 Python 将 BMP 转换为 PDF: + +```python +import aspose.pdf as ap +from os import path +import sys + +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) +``` + +{{% alert color="success" %}} +**尝试在线将 BMP 转换为 PDF** + +Aspose 为您呈现在线应用 ["BMP 转 PDF"](https://products.aspose.app/pdf/conversion/bmp-to-pdf/),在此您可以尝试调查其功能以及其工作质量。 + +[![Aspose.PDF 将 BMP 转换为 PDF 使用 App](bmp_to_pdf.png)](https://products.aspose.app/pdf/conversion/bmp-to-pdf/) +{{% /alert %}} + +## 将 CGM 转换为 PDF + +使用 Aspose.PDF for Python via .NET 将 CGM(Computer Graphics Metafile)转换为 PDF(或其他受支持的格式)。 + +计算机图形元文件 是计算机图形元文件(Computer Graphics Metafile)格式的文件扩展名,常用于 CAD(计算机辅助设计)和演示图形应用程序。CGM 是一种矢量图形格式,支持三种不同的编码方法:二进制(最适合程序读取速度)、基于字符的编码(产生最小的文件大小并允许更快的数据传输)或明文编码(允许用户使用文本编辑器读取和修改文件)。 + +检查下面的代码片段以将 CGM 文件转换为 PDF 格式。 + +在 Python 中将 CGM 转换为 PDF 的步骤: + +1. 定义文件路径 +1. 为 CGM 设置加载选项。 +1. 将 CGM 转换为 PDF +1. 打印转换消息 + +```python +import aspose.pdf as ap +from os import path +import sys + +def convert_CGM_to_PDF(infile, outfile): + options = ap.CgmLoadOptions() + document = ap.Document(infile, options) + document.save(outfile) + + print(infile + " converted into " + outfile) +``` + +## 将 DICOM 转换为 PDF + +DICOM 格式是医学行业用于创建、存储、传输和可视化受检患者数字医学图像和文件的标准。 + +**Aspose.PDF for Python** 允许您转换 DICOM 和 SVG 图像,但由于技术原因,要向 PDF 添加图像,需要指定要添加的文件类型。 + +以下代码片段展示了如何使用 Aspose.PDF 将 DICOM 文件转换为 PDF 格式。您应加载 DICOM 图像,将图像放置在 PDF 文件的页面上并将输出保存为 PDF。我们使用额外的 pydicom 库来设置此图像的尺寸。如果您想在页面上定位图像,可以跳过此代码片段。 + +1. 加载 DICOM 文件。 +1. 提取图像尺寸。 +1. 打印图像大小。 +1. 创建一个新的 PDF 文档。 +1. 准备 DICOM 图像以用于 PDF。 +1. 设置 PDF 页面大小和边距。 +1. 将图像添加到页面。 +1. 保存 PDF。 +1. 打印转换消息。 + +```python +import aspose.pdf as ap +from os import path +import sys + +def convert_DICOM_to_PDF(infile, outfile): + # Load the DICOM file + import pydicom + + dicom_file = pydicom.dcmread(infile) + + # Get the dimensions of the image + rows = dicom_file.Rows + columns = dicom_file.Columns + + # Print the dimensions + print(f"DICOM image size: {rows} x {columns} pixels") + + # Initialize new Document + document = ap.Document() + page = document.pages.add() + 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 + page.page_info.margin.top = 0 + page.page_info.margin.right = 0 + page.page_info.margin.left = 0 + page.paragraphs.add(image) + + document.save(outfile) + print(infile + " converted into " + outfile) +``` + +{{% alert color="success" %}} +**尝试在线将 DICOM 转换为 PDF** + +Aspose 为您呈现在线应用 ["DICOM 转 PDF"](https://products.aspose.app/pdf/conversion/dicom-to-pdf/),在此您可以尝试调查其功能以及其工作质量。 + +[![使用 App 将 DICOM 转换为 PDF 的 Aspose.PDF](dicom_to_pdf.png)](https://products.aspose.app/pdf/conversion/dicom-to-pdf/) +{{% /alert %}} + +## 将 EMF 转换为 PDF + +EMF 以设备无关的方式存储图形图像。EMF 元文件由按时间顺序排列的可变长度记录组成,这些记录在任何输出设备上解析后都能渲染存储的图像。 + +以下代码片段展示了如何使用 Python 将 EMF 转换为 PDF: + +```python + +import aspose.pdf as ap +from os import path +import sys + +def convert_EMF_to_PDF(infile, outfile): + document = ap.Document() + page = document.pages.add() + rectangle = ap.Rectangle(0, 0, 595, 842, True) # A4 size in points + # add image to new pdf page + page.add_image(infile, rectangle) + + # Save the file into PDF format + document.save(outfile) + print(infile + " converted into " + outfile) +``` + +{{% alert color="success" %}} +**尝试在线将 EMF 转换为 PDF** + +Aspose 为您呈现在线应用 ["EMF 转 PDF"](https://products.aspose.app/pdf/conversion/emf-to-pdf/),在此您可以尝试调查其功能以及其工作质量。 + +[![Aspose.PDF 使用 App 将 EMF 转换为 PDF](emf_to_pdf.png)](https://products.aspose.app/pdf/conversion/emf-to-pdf/) +{{% /alert %}} + +## 将 GIF 转换为 PDF + +使用 **Aspose.PDF for Python via .NET** 库将 GIF 文件转换为 PDF 文档。 + +GIF 能够在不超过256种颜色的格式中存储压缩数据且不损失质量。硬件无关的 GIF 格式于 1987 年(GIF87a)由 CompuServe 开发,用于在网络上传输位图图像。 + +因此,下面的代码片段遵循这些步骤,并展示了如何使用 Python 将 BMP 转换为 PDF: + +```python + +import aspose.pdf as ap +from os import path +import sys + +def convert_GIF_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) +``` + +{{% alert color="success" %}} +**尝试在线将 GIF 转换为 PDF** + +Aspose 为您呈现在线应用 ["GIF 转 PDF"](https://products.aspose.app/pdf/conversion/gif-to-pdf/),在此您可以尝试调查其功能以及其工作质量。 + +[![使用 App 将 GIF 转换为 PDF 的 Aspose.PDF](bmp_to_pdf.png)](https://products.aspose.app/pdf/conversion/gif-to-pdf/) +{{% /alert %}} + +## 将 PNG 转换为 PDF + +**Aspose.PDF for Python via .NET** 支持将 PNG 图像转换为 PDF 格式的功能。请查看下面的代码片段以实现您的任务。 + +PNG 指的是一种使用无损压缩的光栅图像文件格式,这使它在用户中很受欢迎。 + +您可以使用以下步骤将 PNG 转换为 PDF 图像: + +1. 创建一个新的 PDF 文档。 +1. 定义图像放置。 +1. 保存 PDF。 +1. 打印转换消息。 + +此外,下面的代码片段展示了如何使用 Python 将 PNG 转换为 PDF: + +```python +import aspose.pdf as ap +from os import path +import sys + +def convert_PNG_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) +``` + +{{% alert color="success" %}} +**尝试在线将 PNG 转换为 PDF** + +Aspose 为您呈现在线应用 ["PNG 转 PDF"](https://products.aspose.app/pdf/conversion/png-to-pdf/),在此您可以尝试调查其功能以及其工作质量。 + +[![使用 App 将 PNG 转换为 PDF 的 Aspose.PDF](png_to_pdf.png)](https://products.aspose.app/pdf/conversion/png-to-pdf/) +{{% /alert %}} + +## 将 SVG 转换为 PDF + +**Aspose.PDF for Python via .NET** 解释了如何将 SVG 图像转换为 PDF 格式,以及如何获取源 SVG 文件的尺寸。 + +可伸缩矢量图形(SVG)是一系列基于 XML 的文件格式规范,用于二维矢量图形,包括静态和动态图形(交互式或动画)。SVG 规范是一项开放标准,自 1999 年起由万维网联盟(W3C)进行开发。 + +可缩放矢量图形 图像及其行为在 XML 文本文件中定义。这意味着它们可以被搜索、索引、脚本化,并在需要时进行压缩。作为 XML 文件,SVG 图像可以使用任何文本编辑器创建和编辑,但通常使用诸如 Inkscape 等绘图程序来创建会更方便。 + +{{% alert color="success" %}} +**尝试在线将 SVG 格式转换为 PDF** + +Aspose.PDF for Python via .NET 为您呈现在线应用程序 ["SVG 转 PDF"](https://products.aspose.app/pdf/conversion/svg-to-pdf),在此您可以尝试调查其功能以及其工作质量。 + +[![使用 App 将 SVG 转换为 PDF(Aspose.PDF)](svg_to_pdf.png)](https://products.aspose.app/pdf/conversion/svg-to-pdf) +{{% /alert %}} + +以下代码片段展示了使用 Aspose.PDF for Python 将 SVG 文件转换为 PDF 格式的过程。 + +```python +import aspose.pdf as ap +from os import path +import sys + +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) +``` + +## 将 TIFF 转换为 PDF + +**Aspose.PDF** 文件格式受支持,无论是单帧还是多帧的 TIFF 图像。这意味着您可以将 TIFF 图像转换为 PDF。 + +TIFF 或 TIF,标记图像文件格式,表示用于在符合此文件格式标准的各种设备上使用的光栅图像。TIFF 图像可以包含多个不同图像的帧。也支持 Aspose.PDF 文件格式,无论是单帧还是多帧 TIFF 图像。 + +您可以使用与其余光栅文件格式图形相同的方式将 TIFF 转换为 PDF: + +```python +import aspose.pdf as ap +from os import path +import sys + +def convert_TIFF_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) +``` + +## 将 CDR 转换为 PDF + +下面的代码片段展示了如何使用 Aspose.PDF for Python via .NET 中的 'CdrLoadOptions' 加载 CorelDRAW (CDR) 文件并将其保存为 PDF。 + +1. 创建 'CdrLoadOptions()' 以配置 CDR 文件的加载方式。 +1. 使用 CDR 文件和加载选项初始化 Document 对象。 +1. 将文档保存为 PDF。 + +```python +import aspose.pdf as ap +from os import path +import sys + +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) +``` + +## 将 JPEG 转换为 PDF + +此示例展示了如何使用 Aspose.PDF for Python via .NET 将 JPEG 转换为 PDF 文件。 + +1. 创建一个新的 PDF 文档。 +1. 添加新页面。 +1. 定义放置矩形(A4尺寸:595x842 点)。 +1. 将图像插入页面。 +1. 保存 PDF。 + +```python +import aspose.pdf as ap +from os import path +import sys + +def convert_JPEG_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) +``` diff --git a/zh/python-net/converting/convert-images-format-to-pdf/bmp_to_pdf.png b/zh/python-net/converting/convert-images-format-to-pdf/bmp_to_pdf.png new file mode 100644 index 0000000000..42ad04ba2a Binary files /dev/null and b/zh/python-net/converting/convert-images-format-to-pdf/bmp_to_pdf.png differ diff --git a/zh/python-net/converting/convert-images-format-to-pdf/dicom_to_pdf.png b/zh/python-net/converting/convert-images-format-to-pdf/dicom_to_pdf.png new file mode 100644 index 0000000000..13c6a97e9c Binary files /dev/null and b/zh/python-net/converting/convert-images-format-to-pdf/dicom_to_pdf.png differ diff --git a/zh/python-net/converting/convert-images-format-to-pdf/emf_to_pdf.png b/zh/python-net/converting/convert-images-format-to-pdf/emf_to_pdf.png new file mode 100644 index 0000000000..0962ba838b Binary files /dev/null and b/zh/python-net/converting/convert-images-format-to-pdf/emf_to_pdf.png differ diff --git a/zh/python-net/converting/convert-images-format-to-pdf/png_to_pdf.png b/zh/python-net/converting/convert-images-format-to-pdf/png_to_pdf.png new file mode 100644 index 0000000000..3d8399d4d4 Binary files /dev/null and b/zh/python-net/converting/convert-images-format-to-pdf/png_to_pdf.png differ diff --git a/zh/python-net/converting/convert-images-format-to-pdf/svg_to_pdf.png b/zh/python-net/converting/convert-images-format-to-pdf/svg_to_pdf.png new file mode 100644 index 0000000000..748dc5e136 Binary files /dev/null and b/zh/python-net/converting/convert-images-format-to-pdf/svg_to_pdf.png differ diff --git a/zh/python-net/converting/convert-other-files-to-pdf/_index.md b/zh/python-net/converting/convert-other-files-to-pdf/_index.md new file mode 100644 index 0000000000..dbabb5cc4a --- /dev/null +++ b/zh/python-net/converting/convert-other-files-to-pdf/_index.md @@ -0,0 +1,339 @@ +--- +title: 在 Python 中将其他文件格式转换为 PDF +linktitle: 将其他文件格式转换为 PDF +type: docs +weight: 80 +url: /zh/python-net/convert-other-files-to-pdf/ +lastmod: "2026-06-08" +description: 了解如何使用 Aspose.PDF for Python via .NET 在 Python 中将 EPUB、Markdown、PCL、XPS、PostScript、XML 和 LaTeX 文件转换为 PDF。 +sitemap: + changefreq: "monthly" + priority: 0.5 +TechArticle: true +AlternativeHeadline: 如何在 Python 中将其他文件格式转换为 PDF +Abstract: 本文提供了一份使用 Python 将各种文件格式转换为 PDF 的综合指南,利用 Aspose.PDF for Python via .NET 的功能。文档概述了多个格式的转换过程,包括 EPUB、Markdown、PCL、Text、XPS、PostScript、XML、XSL-FO 和 LaTeX/TeX。每个章节提供了具体的代码片段和实现这些转换的说明。文章强调了 Aspose.PDF 的特性,例如针对每种文件类型定制的加载选项,以确保转换的准确性和高效性。此外,还突出在线转换应用的可用性,供用户亲自体验该功能。该指南是开发者在其 Python 应用中集成 PDF 转换能力的实用资源。 +--- + +本文解释了如何 **使用 Python 将各种其他文件格式转换为 PDF**。它涵盖以下主题。 + +## 将 OFD 转换为 PDF + +OFD 代表开放固定布局文档(也称为开放固定文档格式)。它是中国国家标准(GB/T 33190-2016),用于电子文档,被作为 PDF 的替代方案引入。 + +在 Python 中将 OFD 转换为 PDF 的步骤: + +1. 使用 OfdLoadOptions() 来设置 OFD 加载选项。 +1. 加载 OFD 文档。 +1. 另存为 PDF。 + +```python +from os import path, remove +import aspose.pdf as ap +import sys + +def convert_OFD_to_PDF(infile, outfile): + load_options = ap.OfdLoadOptions() + document = ap.Document(infile, load_options) + document.save(outfile) + + print(infile + " converted into " + outfile) +``` + +## 将 LaTeX/TeX 转换为 PDF + +LaTeX 文件格式是一种文本文件格式,使用 TeX 系列语言的 LaTeX 派生标记,并且 LaTeX 是 TeX 系统的派生格式。LaTeX(ˈleɪtɛk/lay-tek 或 lah-tek)是一种文档排版系统和文档标记语言。它被广泛用于许多领域的科学文献的交流和出版,包括数学、物理和计算机科学。它在包含复杂多语言材料的书籍和文章的编写和出版中也发挥关键作用,如韩文、日文、汉字和阿拉伯文,以及特刊。 + +LaTeX 使用 TeX 排版程序来格式化其输出,并且它本身是用 TeX 宏语言编写的。 + +{{% alert color="success" %}} +**尝试在线将 LaTeX/TeX 转换为 PDF** + +Aspose.PDF for Python via .NET 为您呈现在线应用程序 ["LaTex 转 PDF"](https://products.aspose.app/pdf/conversion/tex-to-pdf),在此您可以尝试调查其功能以及其工作质量。 + +[![Aspose.PDF 将 LaTeX/TeX 转换为 PDF(使用 App)](latex.png)](https://products.aspose.app/pdf/conversion/tex-to-pdf) +{{% /alert %}} + +步骤 将 TEX 转换为 PDF(在 Python 中): + +1. 使用 LatexLoadOptions() 设置 LaTeX 加载选项。 +1. 加载 LaTeX 文档。 +1. 另存为 PDF。 + +```python +from os import path, remove +import aspose.pdf as ap +import sys + +def convert_TEX_to_PDF(infile, outfile): + load_options = ap.LatexLoadOptions() + document = ap.Document(infile, load_options) + document.save(outfile) + + print(infile + " converted into " + outfile) +``` + +## 将 EPUB 转换为 PDF + +**Aspose.PDF for Python via .NET** 允许您轻松将 EPUB 文件转换为 PDF 格式。 + +EPUB(全称 electronic publication,电子出版物)是一种由国际数字出版论坛(IDPF)推出的免费且开放的电子书标准。文件的扩展名为 .epub。EPUB 旨在支持可重排内容,这意味着 EPUB 阅读器可以针对特定显示设备优化文本。 + +EPUB 也支持固定布局内容。该格式旨在作为出版商和转换公司内部使用的统一格式,也用于分发和销售。它取代了 Open eBook 标准。EPUB 3 版本也得到图书行业研究集团(BISG)的认可,BISG 是一个领先的图书行业协会,致力于标准化最佳实践、研究、信息和活动,用于内容包装。 + +{{% alert color="success" %}} +**尝试在线将 EPUB 转换为 PDF** + +Aspose.PDF for Python via .NET 为您呈现在线应用程序 ["EPUB 转 PDF"](https://products.aspose.app/pdf/conversion/epub-to-pdf),在此您可以尝试调查其功能以及其工作质量。 + +[![Aspose.PDF 将 EPUB 转换为 PDF(使用 App)](epub.png)](https://products.aspose.app/pdf/conversion/epub-to-pdf) +{{% /alert %}} + +在 Python 中将 EPUB 转换为 PDF 的步骤: + +1. 使用 EpubLoadOptions() 加载 EPUB 文档。 +1. 将 EPUB 转换为 PDF。 +1. 打印确认。 + +下面的代码片段向您展示如何使用Python将 EPUB 文件转换为 PDF 格式。 + +```python +from os import path, remove +import aspose.pdf as ap +import sys + +def convert_EPUB_to_PDF(infile, outfile): + load_options = ap.EpubLoadOptions() + document = ap.Document(infile, load_options) + + document.save(outfile) + print(infile + " converted into " + outfile) +``` + +## 将 Markdown 转换为 PDF + +**此功能在 19.6 版或更高版本中受支持。** + +{{% alert color="success" %}} +**尝试在线将 Markdown 转换为 PDF** + +Aspose.PDF for Python via .NET 为您呈现在线应用程序 ["Markdown 转 PDF"](https://products.aspose.app/pdf/conversion/md-to-pdf),在此您可以尝试调查其功能以及其工作质量。 + +[![Aspose.PDF 将 Markdown 转换为 PDF 的应用](markdown.png)](https://products.aspose.app/pdf/conversion/md-to-pdf) +{{% /alert %}} + +这段由 Aspose.PDF for Python via .NET 提供的代码片段可帮助将 Markdown 文件转换为 PDF,实现更好的文档共享、格式保留以及打印兼容性.o + +以下代码片段展示了如何使用 Aspose.PDF 库实现此功能: + +```python +from os import path, remove +import aspose.pdf as ap +import sys + +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) +``` + +## 将 PCL 转换为 PDF + +PCL (Printer Command Language)是一种惠普(Hewlett-Packard)开发的打印机语言,用于访问标准打印机功能。PCL 1 至 5e/5c 级别是基于命令的语言,使用控制序列,按接收顺序进行处理和解释。在消费者层面,PCL 数据流由打印驱动程序生成。自定义应用程序也可以轻松生成 PCL 输出。 + +{{% alert color="success" %}} +**尝试在线将 PCL 转换为 PDF** + +Aspose.PDF for .NET 为您呈现在线应用 ["PCL 转 PDF"](https://products.aspose.app/pdf/conversion/pcl-to-pdf),在此您可以尝试调查其功能以及其工作质量。 + +[![Aspose.PDF 将 PCL 转换为 PDF 的应用](pcl_to_pdf.png)](https://products.aspose.app/pdf/conversion/pcl-to-pdf) +{{% /alert %}} + +为了允许将 PCL 转换为 PDF,Aspose.PDF 拥有该类 [`PclLoadOptions`](https://reference.aspose.com/pdf/net/aspose.pdf/pclloadoptions) 它用于初始化 LoadOptions 对象。随后在 Document 对象初始化期间,该对象作为参数传入,帮助 PDF 渲染引擎确定源文档的输入格式。 + +以下代码片段展示了将 PCL 文件转换为 PDF 格式的过程。 + +在 Python 中将 PCL 转换为 PDF 的步骤: + +1. 使用 PclLoadOptions() 加载 PCL 的选项。 +1. 加载文档。 +1. 另存为 PDF。 + +```python +from os import path, remove +import aspose.pdf as ap +import sys + +def convert_PCL_to_PDF(infile, outfile): + load_options = ap.PclLoadOptions() + load_options.supress_errors = True + + document = ap.Document(infile, load_options) + document.save(outfile) + + print(infile + " converted into " + outfile) +``` + +## 将预格式化文本转换为 PDF + +**Aspose.PDF for Python via .NET** 支持将纯文本和预格式化文本文件转换为 PDF 格式的功能。 + +将文本转换为 PDF 意味着向 PDF 页面添加文本片段。对于文本文件,我们处理两种类型的文本:预格式化(例如,25 行,每行 80 个字符)和非格式化文本(纯文本)。根据我们的需求,我们可以自行控制此添加,或将其委托给库的算法。 + +{{% alert color="success" %}} +**尝试在线将 TEXT 转换为 PDF** + +Aspose.PDF for Python via .NET 为您呈现在线应用程序 ["文本转PDF"](https://products.aspose.app/pdf/conversion/txt-to-pdf),在此您可以尝试调查其功能以及其工作质量。 + +[![使用 App 将文本转换为 PDF 的 Aspose.PDF](text_to_pdf.png)](https://products.aspose.app/pdf/conversion/txt-to-pdf) +{{% /alert %}} + +在 Python 中将 TEXT 转换为 PDF 的步骤: + +1. 逐行读取输入文本文件。 +1. 设置等宽字体(Courier New),以实现一致的文本对齐。 +1. 创建一个新的 PDF 文档,并添加第一页,使用自定义的边距和字体设置。 +1. 遍历文本文件的行。为了模拟打字机,我们使用 'monospace_font' 字体,大小为 12。 +1. 将页面创建限制为4页。 +1. 将最终的 PDF 保存到指定路径。 + +```python +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) + + print(infile + " converted into " + outfile) +``` + +## 将 PostScript 转换为 PDF + +本示例演示如何使用 Aspose.PDF for Python via .NET 将 PostScript 文件转换为 PDF 文档。 + +1. 创建一个 'PsLoadOptions' 实例以正确解释 PS 文件。 +1. 使用加载选项将 'PostScript' 文件加载到 Document 对象中。 +1. 将文档以 PDF 格式保存到所需的输出路径。 + +```python +from os import path, remove +import aspose.pdf as ap +import sys + +def convert_PS_to_PDF(infile, outfile): + load_options = ap.PsLoadOptions() + + document = ap.Document(infile, load_options) + document.save(outfile) + + print(infile + " converted into " + outfile) +``` + +## 将 XPS 转换为 PDF + +**Aspose.PDF for Python via .NET** 支持功能转换 XPS 文件转换为 PDF 格式。查看本文以解决您的任务。 + +XPS 文件类型主要与微软公司的 XML Paper Specification 相关。XML Paper Specification(XPS),前身代号为 Metro,并包含下一代打印路径(NGPP)营销概念,是微软将文档创建和查看集成到其 Windows 操作系统中的倡议。 + +以下代码片段展示了使用 Python 将 XPS 文件转换为 PDF 格式的过程。 + +```python +from os import path, remove +import aspose.pdf as ap +import sys + +def convert_XPS_to_PDF(infile, outfile): + load_options = ap.XpsLoadOptions() + document = ap.Document(infile, load_options) + document.save(outfile) + + print(infile + " converted into " + outfile) +``` + +{{% alert color="success" %}} +**尝试在线将 XPS 格式转换为 PDF** + +Aspose.PDF for Python via .NET 为您呈现在线应用程序 ["XPS 转 PDF"](https://products.aspose.app/pdf/conversion/xps-to-pdf/),在此您可以尝试调查其功能以及其工作质量。 + +[![Aspose.PDF 将 XPS 转换为 PDF 的应用程序](xps_to_pdf.png)](https://products.aspose.app/pdf/conversion/xps-to-pdf/) +{{% /alert %}} + +## 将 XSL-FO 转换为 PDF + +以下代码片段可用于使用 Aspose.PDF for Python via .NET 将 XSLFO 转换为 PDF 格式: + +```python +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) + + print(xmlfile + " converted into " + outfile) +``` + +## 使用 XSLT 将 XML 转换为 PDF + +本示例演示了如何通过先使用 XSLT 模板将 XML 文件转换为 HTML,然后将 HTML 加载到 Aspose.PDF 中,从而将 XML 文件转换为 PDF。 + +1. 创建一个 'HtmlLoadOptions' 实例以配置 HTML 到 PDF 的转换。 +1. 将转换后的 HTML 文件加载到 Aspose.PDF Document 对象中。 +1. 将文档保存为 PDF 到指定的输出路径。 +1. 成功转换后删除临时 HTML 文件。 + +```python +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) + + print(xmlfile + " converted into " + outfile) +``` + +## 相关转换 + +- [将HTML转换为PDF](/pdf/zh/python-net/convert-html-to-pdf/) 用于 HTML 和 MHTML 转换场景。 +- [将图像格式转换为 PDF](/pdf/zh/python-net/convert-images-format-to-pdf/) 当您的输入是 PNG、JPEG、TIFF、SVG 或其他图像时。 +- [将 PDF 转换为其他格式](/pdf/zh/python-net/convert-pdf-to-other-files/) 如果您还需要反向转换,例如 PDF 到 EPUB、Markdown 或文本。 diff --git a/zh/python-net/converting/convert-other-files-to-pdf/epub.png b/zh/python-net/converting/convert-other-files-to-pdf/epub.png new file mode 100644 index 0000000000..2b139c0f8e Binary files /dev/null and b/zh/python-net/converting/convert-other-files-to-pdf/epub.png differ diff --git a/zh/python-net/converting/convert-other-files-to-pdf/latex.png b/zh/python-net/converting/convert-other-files-to-pdf/latex.png new file mode 100644 index 0000000000..50fa2fd227 Binary files /dev/null and b/zh/python-net/converting/convert-other-files-to-pdf/latex.png differ diff --git a/zh/python-net/converting/convert-other-files-to-pdf/markdown.png b/zh/python-net/converting/convert-other-files-to-pdf/markdown.png new file mode 100644 index 0000000000..422b7fbfa5 Binary files /dev/null and b/zh/python-net/converting/convert-other-files-to-pdf/markdown.png differ diff --git a/zh/python-net/converting/convert-other-files-to-pdf/pcl_to_pdf.png b/zh/python-net/converting/convert-other-files-to-pdf/pcl_to_pdf.png new file mode 100644 index 0000000000..0593c84c27 Binary files /dev/null and b/zh/python-net/converting/convert-other-files-to-pdf/pcl_to_pdf.png differ diff --git a/zh/python-net/converting/convert-other-files-to-pdf/text_to_pdf.png b/zh/python-net/converting/convert-other-files-to-pdf/text_to_pdf.png new file mode 100644 index 0000000000..2d22af834e Binary files /dev/null and b/zh/python-net/converting/convert-other-files-to-pdf/text_to_pdf.png differ diff --git a/zh/python-net/converting/convert-other-files-to-pdf/xml_to_pdf.png b/zh/python-net/converting/convert-other-files-to-pdf/xml_to_pdf.png new file mode 100644 index 0000000000..f872ef616f Binary files /dev/null and b/zh/python-net/converting/convert-other-files-to-pdf/xml_to_pdf.png differ diff --git a/zh/python-net/converting/convert-other-files-to-pdf/xps_to_pdf.png b/zh/python-net/converting/convert-other-files-to-pdf/xps_to_pdf.png new file mode 100644 index 0000000000..8e0a2d15c0 Binary files /dev/null and b/zh/python-net/converting/convert-other-files-to-pdf/xps_to_pdf.png differ diff --git a/zh/python-net/converting/convert-pdf-to-excel/_index.md b/zh/python-net/converting/convert-pdf-to-excel/_index.md index cffe8a2b75..89ce85243c 100644 --- a/zh/python-net/converting/convert-pdf-to-excel/_index.md +++ b/zh/python-net/converting/convert-pdf-to-excel/_index.md @@ -4,38 +4,38 @@ linktitle: 将 PDF 转换为 Excel type: docs weight: 20 url: /zh/python-net/convert-pdf-to-excel/ -lastmod: "2026-04-14" -description: 了解如何在 Python 中将 PDF 转换为 Excel,包括 XLS、XLSX、CSV、ODS,单工作表输出以及列处理,使用 Aspose.PDF。 +lastmod: "2026-06-08" +description: 了解如何在 Python 中使用 Aspose.PDF 将 PDF 转换为 Excel,包括 XLS、XLSX、CSV、ODS,单工作表输出以及列处理。 sitemap: changefreq: "monthly" priority: 0.7 TechArticle: true -AlternativeHeadline: 在 Python 中将 PDF 转换为 Excel、XLSX、CSV 和 ODS。 -Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 将 PDF 文件转换为电子表格格式。它涵盖了 XLS、XLSX、XLSM、CSV 和 ODS 的输出,并提供了控制空白列和减少生成工作表数量的选项。 +AlternativeHeadline: 在 Python 中将 PDF 转换为 Excel、XLSX、CSV 和 ODS +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 将 PDF 文件转换为电子表格格式。它涵盖了 XLS、XLSX、XLSM、CSV 和 ODS 输出,以及控制空列和减少生成工作表数量的选项。 --- ## 在 Python 中将 PDF 转换为 Excel -**Aspose.PDF for Python via .NET** 支持从 Python 代码将 PDF 文件转换为 Excel 及其他电子表格格式。 +**Aspose.PDF for Python via .NET** 支持从 Python 代码将 PDF 文件转换为 Excel 和其他电子表格格式。 -当您需要将 PDF 转换为 XLS、XLSX、CSV 或 ODS 以进行表格提取、报告复用、排序、过滤或后续分析时,请使用此页面。在 PDF 转 Excel 转换过程中,单个 PDF 页面可以渲染为 Excel 工作表。 +当您需要将 PDF 转换为 XLS、XLSX、CSV 或 ODS 进行表格提取、报告复用、排序、过滤或下游分析时,请使用此页面。在 PDF 转 Excel 转换过程中,单个 PDF 页面可以渲染为 Excel 工作表。 -第一个示例将 PDF 文件转换为 Spreadsheet 2003 XML 格式。后续章节展示 XLSX、XLSM、CSV、ODS 以及单工作表输出。 +第一个示例将 PDF 文件转换为 Spreadsheet 2003 XML 格式。后面的章节展示了 XLSX、XLSM、CSV、ODS,以及单工作表输出。 {{% alert color="success" %}} -**尝试将 PDF 在线转换为 Excel** +**尝试在线将 PDF 转换为 Excel** -Aspose.PDF 向您展示在线应用程序 ["PDF 转 XLSX"](https://products.aspose.app/pdf/conversion/pdf-to-xlsx),在此您可以尝试调查其功能和工作质量。 +Aspose.PDF 为您提供在线应用程序 ["PDF 转 XLSX"](https://products.aspose.app/pdf/conversion/pdf-to-xlsx),在此您可以尝试调查其功能以及其工作质量。 -[![使用 App 将 Aspose.PDF 转换 PDF 为 Excel](pdf_to_xlsx.png)](https://products.aspose.app/pdf/conversion/pdf-to-xlsx) +[![Aspose.PDF 将 PDF 转换为 Excel 的应用](pdf_to_xlsx.png)](https://products.aspose.app/pdf/conversion/pdf-to-xlsx) {{% /alert %}} 以下代码片段展示了使用 Aspose.PDF for Python via .NET 将 PDF 文件转换为 XLS 或 XLSX 格式的过程。 -步骤:将 PDF 文件转换为 Excel(XML Spreadsheet 2003)格式 +步骤:将 PDF 文件转换为 Excel(XML 电子表格 2003)格式 1. 加载 PDF 文档。 -1. 使用 设置 Excel 保存选项 [Excel 保存选项](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/). +1. 使用设置 Excel 保存选项 [Excel保存选项](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/). 1. 保存已转换的文件。 ```python @@ -57,7 +57,7 @@ def convert_pdf_to_excel_spread_sheet2003(infile, outfile): 步骤:将 PDF 文件转换为 XLSX 格式(Excel 2007+) 1. 加载 PDF 文档。 -1. 使用 设置 Excel 保存选项 [Excel 保存选项](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/). +1. 使用设置 Excel 保存选项 [Excel保存选项](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/). 1. 保存已转换的文件。 ```python @@ -74,9 +74,9 @@ def convert_pdf_to_excel_2007(infile, outfile): print(infile + " converted into " + outfile) ``` -## 将 PDF 转换为 XLSX 并控制列 +## 将 PDF 转换为 XLSX 并进行列控制 -在将 PDF 转换为 Excel 格式时,输出文件的第一列可以添加一个空白列。使用 `insert_blank_column_at_first` 选项的 `ExcelSaveOptions` 用于控制此行为的类。其默认值为 `true`. +在将 PDF 转换为 Excel 格式时,可以在输出文件的第一列添加一个空列。使用 `insert_blank_column_at_first` 选项的 `ExcelSaveOptions` 用于控制此行为的类。其默认值是 `true`. ```python from os import path @@ -95,13 +95,13 @@ def convert_pdf_to_excel_2007_control_column(infile, outfile): ## 将 PDF 转换为单个 Excel 工作表 -Aspose.PDF for Python via .NET 展示了如何将 PDF 转换为 Excel(.xlsx)文件,并启用了 “minimize_the_number_of_worksheets” 选项。 +Aspose.PDF for Python via .NET 展示了如何将 PDF 转换为 Excel (.xlsx) 文件,并启用了 'minimize_the_number_of_worksheets' 选项。 -步骤:在 Python 中将 PDF 转换为 XLS 或 XLSX 单工作表 +步骤:在 Python 中将 PDF 转换为单个工作表的 XLS 或 XLSX 1. 加载 PDF 文档。 -1. 使用 设置 Excel 保存选项 [Excel 保存选项](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/). -1. ‘minimize_the_number_of_worksheets’ 选项通过将 PDF 页面合并到更少的工作表中来减少 Excel 工作表的数量(例如,如果可能的话,将整个文档放在一个工作表中)。 +1. 使用设置 Excel 保存选项 [Excel保存选项](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/). +1. 'minimize_the_number_of_worksheets' 选项通过将 PDF 页面合并到更少的工作表中来减少 Excel 工作表的数量(例如,如果可能的话,整个文档使用一个工作表)。 1. 保存已转换的文件。 ```python @@ -141,13 +141,13 @@ def convert_pdf_to_excel_2007_macro(infile, outfile): ### 将 PDF 转换为 CSV -‘convert_pdf_to_excel_2007_csv’ 函数执行与之前相同的操作,但这次的目标格式是 CSV(逗号分隔值),而不是 XLSM。 +'convert_pdf_to_excel_2007_csv' 函数执行与之前相同的操作,但这次目标格式是 CSV(逗号分隔值),而不是 XLSM。 步骤:在 Python 中将 PDF 转换为 CSV -1. 创建一个实例 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 包含源 PDF 文档的对象。 -1. 创建一个实例 [Excel 保存选项](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/) 使用 **ExcelSaveOptions.ExcelFormat.CSV** -1. 通过调用将其保存为 **CSV** 格式 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods)* 方法并传递它 [Excel 保存选项](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/). +1. 创建实例 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 包含源 PDF 文档的对象。 +1. 创建实例 [Excel保存选项](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/) 使用 **ExcelSaveOptions.ExcelFormat.CSV** +1. 通过调用将其保存为 **CSV** 格式 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods)* 方法并传递它 [Excel保存选项](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/). ```python from os import path @@ -165,11 +165,11 @@ def convert_pdf_to_excel_2007_csv(infile, outfile): ### 将 PDF 转换为 ODS -步骤:在 Python 中将 PDF 转换为 ODS +步骤:在Python中将PDF转换为ODS -1. 创建一个实例 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 包含源 PDF 文档的对象。 -1. 创建一个实例 [Excel 保存选项](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/) 使用 **ExcelSaveOptions.ExcelFormat.ODS** -1. 通过调用将其保存为 **ODS** 格式 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法并传递它 [Excel 保存选项](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/). +1. 创建实例 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 包含源 PDF 文档的对象。 +1. 创建实例 [Excel保存选项](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/) 使用 **ExcelSaveOptions.ExcelFormat.ODS** +1. 通过调用将其保存为 **ODS** 格式 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法和传递它 [Excel保存选项](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/). 转换为 ODS 格式的方式与所有其他格式相同。 @@ -189,6 +189,6 @@ def convert_pdf_to_ods(infile, outfile): ## 相关转换 -- [将 PDF 转换为 Word](/pdf/zh/python-net/convert-pdf-to-word/) 如果你的优先考虑是可编辑的文本流而不是电子表格结构。 +- [转换 PDF 为 Word](/pdf/zh/python-net/convert-pdf-to-word/) 如果你的优先考虑是可编辑的文本流,而不是电子表格结构。 - [将 PDF 转换为 HTML](/pdf/zh/python-net/convert-pdf-to-html/) 当您需要浏览器友好的输出时。 -- [将 PDF 转换为其他格式](/pdf/zh/python-net/convert-pdf-to-other-files/) 针对 EPUB、Markdown、文本、XPS 以及相关的导出工作流。 +- [将 PDF 转换为其他格式](/pdf/zh/python-net/convert-pdf-to-other-files/) 用于 EPUB、Markdown、文本、XPS 以及相关的导出工作流。 diff --git a/zh/python-net/converting/convert-pdf-to-excel/pdf_to_xlsx.png b/zh/python-net/converting/convert-pdf-to-excel/pdf_to_xlsx.png new file mode 100644 index 0000000000..a73534eb61 Binary files /dev/null and b/zh/python-net/converting/convert-pdf-to-excel/pdf_to_xlsx.png differ diff --git a/zh/python-net/converting/convert-pdf-to-html/_index.md b/zh/python-net/converting/convert-pdf-to-html/_index.md index 303c1a8c86..78aa56e392 100644 --- a/zh/python-net/converting/convert-pdf-to-html/_index.md +++ b/zh/python-net/converting/convert-pdf-to-html/_index.md @@ -1,68 +1,248 @@ --- -title: 将 PDF 转换为 HTML 在 Python 中 +title: 在 Python 中将 PDF 转换为 HTML linktitle: 将 PDF 转换为 HTML 格式 type: docs weight: 50 url: /zh/python-net/convert-pdf-to-html/ -lastmod: "2021-11-01" -description: 本主题向您展示如何使用 Aspose.PDF for Python .NET 库将 PDF 文件转换为 HTML 格式。 +lastmod: "2026-06-08" +description: 了解如何在 Python 中使用 Aspose.PDF for Python via .NET 将 PDF 转换为 HTML,包括多页输出、外部图像、SVG 处理和分层 HTML 渲染。 sitemap: changefreq: "monthly" priority: 0.8 +TechArticle: true +AlternativeHeadline: 如何在 Python 中将 PDF 转换为 HTML +Abstract: 本文提供了使用 Python 将 PDF 文件转换为 HTML 的全面指南,特别是通过 Aspose.PDF for Python via .NET 库。它概述了以编程方式实现此转换的必要步骤,重点介绍了从源 PDF 创建 `Document` 对象以及使用 `HtmlSaveOptions` 将文档保存为 HTML 格式的过程。文章包括了一个简洁的 Python 代码片段,演示转换过程。此外,还介绍了在线工具 Aspose.PDF 的“PDF to HTML”应用,供用户探索转换功能和质量。本文结构覆盖了各种相关主题,确保对使用 Python 进行 PDF 转 HTML 转换有深入了解。 --- -## 概述 - -本文解释了如何**使用 Python 将 PDF 转换为 HTML**。它涵盖了这些主题。 - -_格式_:**HTML** -- [Python PDF 转换为 HTML](#python-pdf-to-html) -- [Python 将 PDF 转换为 HTML](#python-pdf-to-html) -- [Python 如何将 PDF 文件转换为 HTML](#python-pdf-to-html) - ## 将 PDF 转换为 HTML -**Aspose.PDF for Python via .NET** 提供了许多功能,用于将各种文件格式转换为 PDF 文档,并将 PDF 文件转换为各种输出格式。 - 这篇文章讨论了如何将PDF文件转换为HTML。你可以使用几行Python代码将PDF转换为HTML。如果你想创建一个网站或将内容添加到在线论坛,可能需要将PDF转换为HTML。将PDF转换为HTML的一种方法是使用Python编程。 +**Aspose.PDF for Python via .NET** 提供了许多将各种文件格式转换为 PDF 文档以及将 PDF 文件转换为各种输出格式的功能。本文讨论如何将 PDF 文件转换为 HTML。 您可以只使用几行 Python 代码来将 PDF 转换为 HTML。如果您想创建网站或向在线论坛添加内容,可能需要将 PDF 转换为 HTML。将 PDF 转换为 HTML 的一种方法是以编程方式使用 Python。 {{% alert color="success" %}} -**尝试在线将PDF转换为HTML** +**尝试在线将 PDF 转换为 HTML** -Aspose.PDF for Python为您提供了一个在线免费应用程序["PDF to HTML"](https://products.aspose.app/pdf/conversion/pdf-to-html),您可以尝试研究其功能和工作质量。 +Aspose.PDF for Python 为您呈现在线应用 ["PDF 转 HTML"](https://products.aspose.app/pdf/conversion/pdf-to-html),在此您可以尝试调查其功能以及其工作质量。 -[![Aspose.PDF Convertion PDF to HTML with Free App](pdf_to_html.png)](https://products.aspose.app/pdf/conversion/pdf-to-html) +[![Aspose.PDF 将 PDF 转换为 HTML 的应用](pdf_to_html.png)](https://products.aspose.app/pdf/conversion/pdf-to-html) {{% /alert %}} -步骤:在Python中将PDF转换为HTML +步骤:在 Python 中将 PDF 转换为 HTML -1. 创建一个[Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/)对象的实例,并使用源PDF文档。 -2. 通过调用 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法,将其保存为 [HtmlSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/htmlsaveoptions/)。 +1. 创建实例 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 包含源 PDF 文档的对象。 +1. 保存到 [HtmlSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/htmlsaveoptions/) 通过调用 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法。 ```python +import aspose.pdf as ap +from os import path +import sys + +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) +``` + +## 相关转换 + +- [将HTML转换为PDF](/pdf/zh/python-net/convert-html-to-pdf/) 当您需要反向的网页到文档工作流时。 +- [转换 PDF 为 Word](/pdf/zh/python-net/convert-pdf-to-word/) 如果可编辑文档输出比HTML更有用。 +- [将 PDF 转换为图像格式](/pdf/zh/python-net/convert-pdf-to-images-format/) 用于光栅导出场景。 + +### 将 PDF 转换为 HTML,并将图像保存到指定文件夹 - import aspose.pdf as ap +此函数使用 Aspose.PDF for Python via .NET 将 PDF 文件转换为 HTML 格式。所有提取的图像都会存储在指定文件夹中,而不是嵌入到 HTML 文件中。 - input_pdf = DIR_INPUT + "sample.pdf" - output_pdf = DIR_OUTPUT + "convert_pdf_to_html.html" - # 打开 PDF 文档 - document = ap.Document(input_pdf) +1. 配置 HTML 保存选项。 +1. 另存为带外部图像的HTML。 - # 以 HTML 格式保存文档 +```python +import aspose.pdf as ap +from os import path +import sys + +def convert_PDF_to_HTML_storing_images(infile, outfile): + document = ap.Document(infile) save_options = ap.HtmlSaveOptions() - document.save(output_pdf, save_options) + 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) ``` -## 另请参见 +### 将 PDF 转换为多页 HTML -本文还涵盖了以下主题。代码与上述相同。 +此函数将 PDF 文件转换为多页 HTML,其中每个 PDF 页面导出为单独的 HTML 文件。这使得输出更易于浏览,并减少大型 PDF 的加载时间。 -_格式_: **HTML** -- [Python PDF 转 HTML 代码](#python-pdf-to-html) -- [Python PDF 转 HTML API](#python-pdf-to-html) -- [Python PDF 转 HTML 编程](#python-pdf-to-html) -- [Python PDF 转 HTML 库](#python-pdf-to-html) -- [Python 将 PDF 保存为 HTML](#python-pdf-to-html) -- [Python 从 PDF 生成 HTML](#python-pdf-to-html) -- [Python 从 PDF 创建 HTML](#python-pdf-to-html) +1. 使用 'ap.Document' 加载源 PDF。 +1. 创建 'HtmlSaveOptions' 并设置 `split_into_pages`。 +1. 将文档保存为HTML,并将页面拆分为单独的文件。 +1. 打印确认消息。 + +```python +import aspose.pdf as ap +from os import path +import sys + +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) +``` + +### 将 PDF 转换为 HTML,并将 SVG 图像保存到指定文件夹 + +此函数将 PDF 转换为 HTML 格式,同时将所有图像存储为 SVG 文件在指定文件夹中,而不是直接嵌入到 HTML 中。 + +1. 使用 'ap.Document' 加载源 PDF。 +1. 创建 'HtmlSaveOptions' 并将 `special_folder_for_svg_images` 设置为目标文件夹。 +1. 将文档保存为带有外部 SVG 图像的 HTML。 +1. 打印确认消息。 + +```python +import aspose.pdf as ap +from os import path +import sys + +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) +``` + +### 将 PDF 转换为 HTML 并保存压缩的 SVG 图像 + +此代码片段将 PDF 转换为 HTML 格式,将所有图像存储为指定文件夹中的 SVG 文件,并对其进行压缩以减小文件大小。 + +1. 使用 'ap.Document' 加载 PDF 文档。 +1. 创建 'HtmlSaveOptions' 并: + - 将 'special_folder_for_svg_images' 设置为在外部存储 SVG 图像。 + - 启用 'compress_svg_graphics_if_any' 以压缩 SVG 图像。 +1. 将文档保存为 HTML,并使用压缩的外部 SVG 图像。 +1. 打印确认消息。 + +```python +import aspose.pdf as ap +from os import path +import sys + +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) +``` + +### 将 PDF 转换为 HTML,同时控制嵌入的光栅图像 + +此代码片段将 PDF 转换为 HTML 格式,并将光栅图像嵌入为 PNG 页面背景。此方法在 HTML 中保留了图像质量和页面布局。 + +1. 使用 'ap.Document' 加载 PDF 文档。 +1. 创建 'HtmlSaveOptions' 并将 'set raster_images_saving_mode' 设置为 'AS_EMBEDDED_PARTS_OF_PNG_PAGE_BACKGROUND'。 +1. 将文档另存为包含嵌入栅格图像的 HTML。 +1. 打印确认消息。 + +```python +import aspose.pdf as ap +from os import path +import sys + +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) +``` + +### 将 PDF 转换为仅正文内容的 HTML 页面 + +此函数将 PDF 转换为 HTML 格式,生成仅包含 'body-only' 内容而不包含额外的 'html' 或 'head' 标签,并将输出拆分为单独的页面。 + +1. 使用 'ap.Document' 加载 PDF 文档。 +1. 创建 'HtmlSaveOptions' 并配置: + - 'html_markup_generation_mode = WRITE_ONLY_BODY_CONTENT' 仅生成 'body' 内容。 + - 'split_into_pages' 用于为每个 PDF 页面创建单独的 HTML 文件。 +1. 将文档保存为 HTML,并使用指定的选项。 +1. 打印确认消息。 + +```python +import aspose.pdf as ap +from os import path +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) +``` + +### 将 PDF 转换为带透明文本渲染的 HTML + +此函数将 PDF 转换为 HTML 格式,将所有文本渲染为透明,包括带阴影的文本,从而在保持视觉保真度的同时,允许在输出的 HTML 中进行灵活的样式设置。 + +1. 使用 'ap.Document' 加载 PDF 文档。 +1. 创建 'HtmlSaveOptions' 并配置: + - 'save_transparent_texts' 将普通文本渲染为透明。 + - 'save_shadowed_texts_as_transparent_texts' 将阴影文本渲染为透明。 +1. 将文档保存为带有透明文本渲染的 HTML。 +1. 打印确认消息。 + +```python +import aspose.pdf as ap +from os import path +import sys + +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) +``` + +### 将 PDF 转换为 HTML,使用文档层渲染 + +此函数将 PDF 转换为 HTML 格式,通过将标记内容转换为输出 HTML 中的独立层来保留文档层。这样可以准确渲染分层元素(如注释、背景和叠加层)。 + +1. 使用 'ap.Document' 加载 PDF 文档。 +1. 创建 'HtmlSaveOptions' 并启用 'convert_marked_content_to_layers' 以保留图层。 +1. 将文档保存为带有分层内容的HTML。 +1. 打印确认消息。 + +```python +import aspose.pdf as ap +from os import path +import sys + +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) +``` -- [Python PDF 转 HTML 转换器](#python-pdf-to-html) \ No newline at end of file diff --git a/zh/python-net/converting/convert-pdf-to-html/pdf_to_html.png b/zh/python-net/converting/convert-pdf-to-html/pdf_to_html.png new file mode 100644 index 0000000000..e2543a9b65 Binary files /dev/null and b/zh/python-net/converting/convert-pdf-to-html/pdf_to_html.png differ diff --git a/zh/python-net/converting/convert-pdf-to-images-format/_index.md b/zh/python-net/converting/convert-pdf-to-images-format/_index.md index 11f7cfd8a0..a9625cec1a 100644 --- a/zh/python-net/converting/convert-pdf-to-images-format/_index.md +++ b/zh/python-net/converting/convert-pdf-to-images-format/_index.md @@ -1,335 +1,306 @@ --- -title: 将PDF转换为不同图像格式的Python方法 -linktitle: 将PDF转换为图像 +title: 在 Python 中将 PDF 转换为图像格式 +linktitle: 将 PDF 转换为图像 type: docs weight: 70 url: /zh/python-net/convert-pdf-to-images-format/ -lastmod: "2022-12-23" -description: 本主题向您展示如何使用Aspose.PDF for Python将PDF转换为多种图像格式,例如TIFF、BMP、EMF、JPEG、PNG、GIF、SVG,只需几行代码。 +lastmod: "2026-06-08" +description: 了解如何在 Python 中使用 Aspose.PDF for Python via .NET 将 PDF 页面渲染为 TIFF、BMP、EMF、JPEG、PNG、GIF 和 SVG 文件。 sitemap: changefreq: "monthly" priority: 0.5 +TechArticle: true +AlternativeHeadline: 在 Python 中将 PDF 页面转换为 TIFF、PNG、JPEG、GIF、BMP、EMF 和 SVG。 +Abstract: 本文介绍如何使用 Aspose.PDF for Python via .NET 将 PDF 文件转换为常见的图像格式。内容包括使用 `TiffDevice` 对整篇文档进行 TIFF 导出,使用 `ImageDevice` 子类(如 `BmpDevice`、`JpegDevice`、`PngDevice`、`GifDevice` 和 `EmfDevice`)对每页生成光栅图像,以及使用 `SvgSaveOptions` 将向量导出为 SVG。每个章节都提供了核心步骤和所需的 Python 示例,以将 PDF 内容保存为图像输出。 --- -## 概述 +## Python 将 PDF 转换为图像 -本文解释了如何使用Python将PDF转换为不同的图像格式。它涵盖以下主题。 +**Aspose.PDF for Python via .NET** 支持多种将 PDF 内容转换为图像的方法。在实际中,大多数工作流使用以下两种选项之一: -_图像格式_:**TIFF** -- [Python PDF 转 TIFF](#python-pdf-to-tiff) -- [Python 将 PDF 转换为 TIFF](#python-pdf-to-tiff) -- [Python 将单个或特定页面的 PDF 转换为 TIFF](#python-pdf-to-tiff-pages) +- 用于将 PDF 页面渲染为光栅图像格式的设备方法 +- 用于将 PDF 内容导出为 SVG 的 SaveOptions 方法 -_图像格式_:**BMP** -- [Python PDF 转 BMP](#python-pdf-to-bmp) -- [Python 将 PDF 转换为 BMP](#python-pdf-to-bmp) -- [Python PDF 转 BMP 转换器](#python-pdf-to-bmp) +本文展示如何将 PDF 文件转换为 TIFF、BMP、EMF、JPEG、PNG、GIF 和 SVG。 -_图像格式_:**EMF** -- [Python PDF 转 EMF](#python-pdf-to-emf) -- [Python 将 PDF 转换为 EMF](#python-pdf-to-emf) -- [Python PDF to EMF Converter](#python-pdf-to-emf) - -_图片格式_: **JPG** -- [Python PDF 转 JPG](#python-pdf-to-jpg) -- [Python 转换 PDF 到 JPG](#python-pdf-to-jpg) -- [Python PDF 到 JPG 转换器](#python-pdf-to-jpg) - -_图片格式_: **PNG** -- [Python PDF 转 PNG](#python-pdf-to-png) -- [Python 转换 PDF 到 PNG](#python-pdf-to-png) -- [Python PDF 到 PNG 转换器](#python-pdf-to-png) - -_图片格式_: **GIF** -- [Python PDF 转 GIF](#python-pdf-to-gif) -- [Python 转换 PDF 到 GIF](#python-pdf-to-gif) -- [Python PDF 到 GIF 转换器](#python-pdf-to-gif) - -_图片格式_: **SVG** -- [Python PDF 转 SVG](#python-pdf-to-svg) -- [Python 转换 PDF 到 SVG](#python-pdf-to-svg) -- [Python PDF 到 SVG 转换器](#python-pdf-to-svg) - -## Python 转换 PDF 到图像 - -**Aspose.PDF for Python** 使用几种方法将 PDF 转换为图像。 - 通常情况下,我们使用两种方法:使用设备方法进行转换和使用保存选项进行转换。本节将向您展示如何使用其中一种方法将PDF文档转换为图像格式,如BMP、JPEG、GIF、PNG、EMF、TIFF和SVG格式。 - -库中有几类允许您使用虚拟设备来转换图像。DocumentDevice用于转换整个文档,而ImageDevice用于特定页面。 +该库包含多个渲染类。 `DocumentDevice` 旨在进行全文件转换,而 `ImageDevice` 针对单个页面。 ## 使用 DocumentDevice 类转换 PDF -**Aspose.PDF for Python**可以将PDF页面转换为TIFF图像。 +使用 `DocumentDevice` 当您想将整个 PDF 渲染为单个多页 TIFF 文件时。 -[TiffDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/)(基于DocumentDevice)类允许您将PDF页面转换为TIFF图像。此类提供了一个名为[process](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/#methods)的方法,允许您将PDF文件中的所有页面转换为单个TIFF图像。 +这 [Tiff设备](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/) 类是基于 `DocumentDevice` 并提供 [处理](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/#methods) 将 PDF 文件中的所有页面转换为单个 TIFF 输出的方法。 {{% alert color="success" %}} +**尝试在线将 PDF 转换为 TIFF** -**尝试在线将PDF转换为TIFF** -Aspose.PDF for Python via .NET 为您提供在线免费应用程序 ["PDF to 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) +[![使用 App 将 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 图像。 -步骤:在 Python 中将 PDF 转换为 TIFF +步骤:在 Python 中将 PDF 转换为 TIFF -1. 创建一个 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类的对象。 -2. 创建 [TiffSettings](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffsettings/) 和 [TiffDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/) 对象。 - -3. 调用 [process](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/#methods) 方法将 PDF 文档转换为 TIFF。 -4. 要设置输出文件的属性,请使用 [TiffSettings](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffsettings/) 类。 +1. 使用以下方式加载源 PDF [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类。 +1. 创建 [Tiff设置](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffsettings/) 和 [Tiff设备](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/tiffdevice/) 对象。 +1. 配置 TIFF 选项,例如压缩、色彩深度和空白页处理。 +1. 调用 [处理](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 - import aspose.pdf as ap - - input_pdf = DIR_INPUT + "sample.pdf" - output_pdf = DIR_OUTPUT + "convert_pdf_to_tiff.tiff" - # 打开 PDF 文档 - document = ap.Document(input_pdf) +def convert_PDF_to_TIFF(infile, outfile): + document = ap.Document(infile) - # 创建分辨率对象 resolution = ap.devices.Resolution(300) - - # 创建 TiffSettings 对象 tiffSettings = ap.devices.TiffSettings() tiffSettings.compression = ap.devices.CompressionType.LZW tiffSettings.depth = ap.devices.ColorDepth.DEFAULT tiffSettings.skip_blank_pages = False - # 创建 TIFF 设备 tiffDevice = ap.devices.TiffDevice(resolution, tiffSettings) + tiffDevice.process(document, f"{outfile}.tiff") - # 转换特定页面并将图像保存到流 - tiffDevice.process(document, output_pdf) + print(infile + " converted into " + outfile) ``` - ## 使用 ImageDevice 类转换 PDF -`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 图像。 +`ImageDevice` 是...的基类 `BmpDevice`, `JpegDevice`, `GifDevice`, `PngDevice`,和 `EmfDevice`. -- [GifDevice](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/gifdevice/) 类允许您将 PDF 页面转换为 GIF 图像。 +- 这 [Bmp设备](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) 类允许您将 PDF 页面转换为 BMP 图像。 +- 这 [Emf设备](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/emfdevice/) 类允许您将 PDF 页面转换为 EMF 图像。 +- 这 [Jpeg设备](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 图像。 -让我们看看如何将 PDF 页面转换为图像。 +每种格式的工作流程相同:加载文档,创建相应的设备,然后处理所需的页面。 -[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 页面转换为图像,我们只需实例化所需的类。 +[Bmp设备](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) 公开了 [处理](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/#methods) 将特定页面渲染为 BMP 的方法。其他图像设备类遵循相同的模式,因此您可以通过更改设备类来切换格式。 -以下步骤和 Python 中的代码片段展示了这种可能性 +以下链接和代码示例展示了如何将 PDF 页面渲染为常见的图像格式: -- [将 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) +- [在 Python 中将 PDF 转换为 BMP](#convert-pdf-to-bmp) +- [在 Python 中将 PDF 转换为 EMF](#convert-pdf-to-emf) +- [在 Python 中将 PDF 转换为 JPEG](#convert-pdf-to-jpeg) +- [在 Python 中将 PDF 转换为 PNG](#convert-pdf-to-png) +- [在 Python 中将 PDF 转换为 GIF](#convert-pdf-to-gif) -步骤:PDF 转换为图像(BMP、EMF、JPG、PNG、GIF)在 Python 中 +步骤:在 Python 中将 PDF 转换为图像(BMP、EMF、JPG、PNG、GIF) -1. 使用 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类加载 PDF 文件。 -2. 创建 [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) -3. 调用 [ImageDevice.Process()](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/imagedevice/#methods) 方法执行 PDF 到图像的转换。 +1. 使用 ... 加载 PDF 文件 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类。 +1. 创建所需的实例 [图像设备](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/imagedevice/) 子类: + - [Bmp设备](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/bmpdevice/) (将 PDF 转换为 BMP) + - [Emf设备](https://reference.aspose.com/pdf/python-net/aspose.pdf.devices/emfdevice/) (将 PDF 转换为 EMF) + - [Jpeg设备](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 ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - import aspose.pdf as ap - - input_pdf = DIR_INPUT + "many_pages.pdf" - output_pdf = DIR_OUTPUT + "convert_pdf_to_bmp" - # 打开 PDF 文档 - document = ap.Document(input_pdf) - - # 创建分辨率对象 +def convert_PDF_to_BMP(infile, outfile): + document = ap.Document(infile) resolution = ap.devices.Resolution(300) device = ap.devices.BmpDevice(resolution) - - for i in range(0, len(document.pages)): - # 创建文件用于保存 - imageStream = io.FileIO( - output_pdf + "_page_" + str(i + 1) + "_out.bmp", 'x' - ) - # 转换特定页面并将图像保存到流中 - device.process(document.pages[i + 1], imageStream) - imageStream.close() + page_count = 1 + while page_count <= len(document.pages): + 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 + + print(infile + " converted into " + outfile) ``` - -### 将PDF转换为EMF +### 将 PDF 转换为 EMF ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - import aspose.pdf as ap - - input_pdf = DIR_INPUT + "sample.pdf" - output_pdf = DIR_OUTPUT + "convert_pdf_to_emf" - # 打开PDF文档 - document = ap.Document(input_pdf) - - # 创建Resolution对象 +def convert_PDF_to_EMF(infile, outfile): + document = ap.Document(infile) resolution = ap.devices.Resolution(300) device = ap.devices.EmfDevice(resolution) - - for i in range(0, len(document.pages)): - # 创建用于保存的文件 - imageStream = io.FileIO( - output_pdf + "_page_" + str(i + 1) + "_out.emf", 'x' - ) - # 转换特定页面并将图像保存到流 - device.process(document.pages[i + 1], imageStream) - imageStream.close() + page_count = 1 + while page_count <= len(document.pages): + 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 - import aspose.pdf as ap - - input_pdf = DIR_INPUT + "many_pages.pdf" - output_pdf = DIR_OUTPUT + "convert_pdf_to_jpeg" - # 打开PDF文档 - document = ap.Document(input_pdf) - - # 创建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 - for i in range(0, len(document.pages)): - # 创建用于保存的文件 - imageStream = io.FileIO( - output_pdf + "_page_" + str(i + 1) + "_out.jpeg", "x" - ) - # 转换特定页面并将图像保存到流 - device.process(document.pages[i + 1], imageStream) - imageStream.close() -``` + while page_count <= len(document.pages): + 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 + print(infile + " converted into " + outfile) +``` ### 将 PDF 转换为 PNG ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - import aspose.pdf as ap +def convert_PDF_to_PNG(infile, outfile): + document = ap.Document(infile) + resolution = ap.devices.Resolution(300) - input_pdf = DIR_INPUT + "sample.pdf" - output_pdf = DIR_OUTPUT + "convert_pdf_to_png" - # 打开 PDF 文档 - document = ap.Document(input_pdf) + device = ap.devices.PngDevice(resolution) + page_count = 1 + while page_count <= len(document.pages): + 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 +``` + +### 将 PDF 转换为 PNG,使用默认字体 + +```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - # 创建 Resolution 对象 +def convert_PDF_to_PNG_with_default_font(infile, outfile): + document = ap.Document(infile) resolution = ap.devices.Resolution(300) - device = ap.devices.PngDevice(resolution) - for i in range(0, len(document.pages)): - # 创建文件以保存 - imageStream = io.FileIO( - output_pdf + "_page_" + str(i + 1) + "_out.png", 'x' - ) - # 转换特定页面并将图像保存到流 - device.process(document.pages[i + 1], imageStream) - imageStream.close() + rendering_options = ap.RenderingOptions() + rendering_options.default_font_name = "Arial" + + device = ap.devices.PngDevice(resolution) + device.rendering_options = rendering_options + + page_count = 1 + while page_count <= len(document.pages): + 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 ``` ### 将 PDF 转换为 GIF ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - import aspose.pdf as ap - - input_pdf = DIR_INPUT + "many_pages.pdf" - output_pdf = DIR_OUTPUT + "convert_pdf_to_gif" - # 打开 PDF 文档 - document = ap.Document(input_pdf) - - # 创建 Resolution 对象 +def convert_PDF_to_GIF(infile, outfile): + document = ap.Document(infile) resolution = ap.devices.Resolution(300) - device = ap.devices.GifDevice(resolution) - - for i in range(0, len(document.pages)): - # 创建文件以保存 - imageStream = io.FileIO( - output_pdf + "_page_" + str(i + 1) + "_out.gif", 'x' - ) - # 转换特定页面并将图像保存到流 - device.process(document.pages[i + 1], imageStream) - # 关闭流 - imageStream.close() + page_count = 1 + while page_count <= len(document.pages): + 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 + + print(infile + " converted into " + outfile) ``` - {{% alert color="success" %}} **尝试在线将 PDF 转换为 PNG** -作为我们免费应用程序如何工作的一个例子,请查看下一个功能。 +作为我们的应用程序工作方式的示例,请查看下一个功能。 -Aspose.PDF for Python 为您提供在线免费应用程序 ["PDF to 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) +[![如何使用 App 将 PDF 转换为 PNG](pdf_to_png.png)](https://products.aspose.app/pdf/conversion/pdf-to-png) {{% /alert %}} ## 使用 SaveOptions 类转换 PDF -本文的这一部分向您展示了如何使用 Python 和 SaveOptions 类将 PDF 转换为 SVG。 +使用 `SaveOptions` 当您想要将 PDF 内容导出为 SVG 时。 {{% alert color="success" %}} **尝试在线将 PDF 转换为 SVG** -Aspose.PDF for Python via .NET 为您提供在线免费应用程序 ["PDF to 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),在此您可以尝试调查其功能以及其工作质量。 -[![Aspose.PDF 使用免费应用程序将 PDF 转换为 SVG](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 %}} -**可缩放矢量图形 (SVG)** 是一种基于 XML 的文件格式的规格家族,用于二维矢量图形,包括静态和动态(交互式或动画)。SVG 规范是一个开放标准,自 1999 年以来一直由万维网联盟 (W3C) 开发。 +**可缩放矢量图形 (SVG)** 是一种基于 XML 的二维矢量图形格式。由于 SVG 保持矢量特性,当您需要为网页、UI 或设计工作流提供可缩放的输出时,它非常有用。 -SVG 图像及其行为在 XML 文本文件中定义。这意味着它们可以被搜索、索引、编写脚本,并在需要时进行压缩。作为 XML 文件,SVG 图像可以用任何文本编辑器创建和编辑,但通常使用绘图程序(如 Inkscape)创建它们更为方便。 +SVG 文件是基于文本的、可搜索的,并且易于在其他工具中进行后处理。 -Aspose.PDF for Python 支持将 SVG 图像转换为 PDF 格式的功能,并且还提供将 PDF 文件转换为 SVG 格式的功能。 - 要实现此要求,[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) 方法。 -以下代码片段展示了使用 Python 将 PDF 文件转换为 SVG 格式的步骤。 +以下步骤展示如何使用 Python 将 PDF 文件转换为 SVG。 -步骤:在 Python 中将 PDF 转换为 SVG +步骤:在 Python 中将 PDF 转换为 SVG -1. 创建 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类的对象。 -2. 使用所需的设置创建 [SvgSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/svgsaveoptions/) 对象。 -3. 调用 [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 [文档](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) 带有 the 的方法 `SvgSaveOptions` 用于写入 SVG 输出的实例。 ### 将 PDF 转换为 SVG ```python +import aspose.pdf as ap +from io import FileIO +from os import path +import sys - import aspose.pdf as ap +def convert_PDF_to_SVG(infile, outfile): + document = ap.Document(infile) - input_pdf = DIR_INPUT + "sample.pdf" - output_pdf = DIR_OUTPUT + "convert_pdf_to_svg.svg" - # 打开 PDF 文档 - document = ap.Document(input_pdf) + save_options = ap.SvgSaveOptions() + save_options.compress_output_to_zip_archive = False + save_options.treat_target_file_name_as_directory = True - # 实例化一个 SvgSaveOptions 对象 - saveOptions = ap.SvgSaveOptions() + document.save(f"{outfile}.svg", save_options) +``` - # 不将 SVG 图像压缩到 Zip 压缩包 - saveOptions.compress_output_to_zip_archive = False - saveOptions.treat_target_file_name_as_directory = True +## 相关转换 - # 将输出保存为 SVG 文件 - document.save(output_pdf, saveOptions) -``` \ No newline at end of file +- [将图像格式转换为 PDF](/pdf/zh/python-net/convert-images-format-to-pdf/) 当您需要从 JPG、PNG、TIFF、SVG 或其他图像来源重建 PDF 时。 +- [将 PDF 转换为 HTML](/pdf/zh/python-net/convert-pdf-to-html/) 用于生成对浏览器友好的输出,而不是光栅图像。 +- [将 PDF 转换为其他格式](/pdf/zh/python-net/convert-pdf-to-other-files/) 用于 EPUB、Markdown、文本和 XPS 导出工作流。 diff --git a/zh/python-net/converting/convert-pdf-to-images-format/pdf_to_png.png b/zh/python-net/converting/convert-pdf-to-images-format/pdf_to_png.png new file mode 100644 index 0000000000..af4c1c146a Binary files /dev/null and b/zh/python-net/converting/convert-pdf-to-images-format/pdf_to_png.png differ diff --git a/zh/python-net/converting/convert-pdf-to-images-format/pdf_to_svg.png b/zh/python-net/converting/convert-pdf-to-images-format/pdf_to_svg.png new file mode 100644 index 0000000000..f9c2273788 Binary files /dev/null and b/zh/python-net/converting/convert-pdf-to-images-format/pdf_to_svg.png differ diff --git a/zh/python-net/converting/convert-pdf-to-images-format/pdf_to_tiff.png b/zh/python-net/converting/convert-pdf-to-images-format/pdf_to_tiff.png new file mode 100644 index 0000000000..b8b7ff0c2f Binary files /dev/null and b/zh/python-net/converting/convert-pdf-to-images-format/pdf_to_tiff.png differ diff --git a/zh/python-net/converting/convert-pdf-to-other-files/_index.md b/zh/python-net/converting/convert-pdf-to-other-files/_index.md index c13506bb59..3dd72f2dfb 100644 --- a/zh/python-net/converting/convert-pdf-to-other-files/_index.md +++ b/zh/python-net/converting/convert-pdf-to-other-files/_index.md @@ -1,14 +1,17 @@ --- -title: 将 PDF 转换为 EPUB、LaTeX、文本、XPS 在 Python 中 +title: 在 Python 中将 PDF 转换为 EPUB、文本、XPS 等 linktitle: 将 PDF 转换为其他格式 type: docs weight: 90 url: /zh/python-net/convert-pdf-to-other-files/ -lastmod: "2022-12-23" -description: 本主题向您展示如何使用 Python 将 PDF 文件转换为其他文件格式,如 EPUB、LaTeX、文本、XPS 等。 +lastmod: "2026-06-08" +description: 了解如何在 Python 中使用 Aspose.PDF for Python via .NET 将 PDF 文件转换为 EPUB、LaTeX、Markdown、文本、XPS 和 MobiXML。 sitemap: changefreq: "monthly" priority: 0.8 +TechArticle: true +AlternativeHeadline: 如何在 Python 中将 PDF 转换为其他格式 +Abstract: 本文提供了使用 Aspose.PDF for Python 将 PDF 文件转换为多种格式的全面指南。它涵盖了将 PDF 转换为 EPUB、LaTeX/TeX、Text、XPS 和 XML 格式。每个章节都以邀请尝试 Aspose 提供的在线应用程序将 PDF 转换为相应格式开始,强调这些工具的易用性和质量。 --- ## 将 PDF 转换为 EPUB @@ -16,162 +19,167 @@ sitemap: {{% alert color="success" %}} **尝试在线将 PDF 转换为 EPUB** -Aspose.PDF for Python 为您提供了一个在线免费应用程序 ["PDF to EPUB"](https://products.aspose.app/pdf/conversion/pdf-to-epub),您可以尝试研究其功能和工作质量。 +Aspose.PDF for Python 为您呈现在线应用 ["PDF 转 EPUB"](https://products.aspose.app/pdf/conversion/pdf-to-epub),在此您可以尝试调查其功能以及其工作质量。 -[![Aspose.PDF 转换 PDF 为 EPUB 通过免费应用程序](pdf_to_epub.png)](https://products.aspose.app/pdf/conversion/pdf-to-epub) +[![Aspose.PDF 转换 PDF 为 EPUB 的应用](pdf_to_epub.png)](https://products.aspose.app/pdf/conversion/pdf-to-epub) {{% /alert %}} -**EPUB** 是国际数字出版论坛 (IDPF) 的一个免费和开放的电子书标准。 - 文件扩展名为.epub。 -EPUB设计用于可重排内容,这意味着EPUB阅读器可以为特定显示设备优化文本。EPUB还支持固定布局内容。该格式旨在作为一种单一格式,供出版商和转换公司在内部使用,以及用于分发和销售。它取代了Open eBook标准。 +EPUB 是由国际数字出版论坛(IDPF)推出的免费且开放的电子书标准。文件的扩展名为 .epub。 +EPUB 旨在用于可重排内容,这意味着 EPUB 阅读器可以针对特定显示设备优化文本。EPUB 也支持固定布局内容。该格式旨在作为出版商和转换公司内部使用的单一格式,同时用于分发和销售。它取代了 Open eBook 标准。 -Aspose.PDF for Python还支持将PDF文档转换为EPUB格式的功能。Aspose.PDF for Python有一个名为'EpubSaveOptions'的类,可以用作[save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods)方法的第二个参数,以生成EPUB文件。 -请尝试使用以下代码片段来使用Python实现此要求。 +Aspose.PDF for Python 也支持将 PDF 文档转换为 EPUB 格式的功能。Aspose.PDF for Python 有一个名为 \u0027EpubSaveOptions\u0027 的类,可用作第二个参数 [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法,用于生成 EPUB 文件。 +请尝试使用以下代码片段来实现此需求,使用 Python。 ```python +import aspose.pdf as ap +from os import path +import sys - import aspose.pdf as ap - - input_pdf = DIR_INPUT + "sample.pdf" - output_pdf = DIR_OUTPUT + "convert_pdf_to_epub.epub" - # 打开PDF文档 - document = ap.Document(input_pdf) - - # 实例化Epub保存选项 +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) - # 保存ePUB文档 - document.save(output_pdf, save_options) + print(infile + " converted into " + outfile) ``` +## 相关转换 + +- [转换 PDF 为 Word](/pdf/zh/python-net/convert-pdf-to-word/) 用于可编辑的 Office 文档输出。 +- [将 PDF 转换为 HTML](/pdf/zh/python-net/convert-pdf-to-html/) 用于面向浏览器的输出。 +- [将 PDF 转换为 PDF/A、PDF/E 和 PDF/X](/pdf/zh/python-net/convert-pdf-to-pdf_x/) 用于归档和符合标准的转换工作流。 + ## 将 PDF 转换为 LaTeX/TeX -**Aspose.PDF for Python via .NET** 支持将 PDF 转换为 LaTeX/TeX。LaTeX 文件格式是一种带有特殊标记的文本文件格式,用于基于 TeX 的文档准备系统,以实现高质量的排版。 +**Aspose.PDF for Python via .NET** 支持将 PDF 转换为 LaTeX/TeX。 +LaTeX 文件格式是一种文本文件格式,具备特殊标记,用于基于 TeX 的文档排版系统,以实现高质量的排版。 {{% alert color="success" %}} **尝试在线将 PDF 转换为 LaTeX/TeX** -Aspose.PDF for Python 为您提供免费的在线应用程序 ["PDF to LaTeX"](https://products.aspose.app/pdf/conversion/pdf-to-tex),您可以尝试研究其功能和工作质量。 +Aspose.PDF for Python 为您呈现在线应用 ["PDF 转 LaTeX"](https://products.aspose.app/pdf/conversion/pdf-to-tex),在此您可以尝试调查其功能以及其工作质量。 -[![Aspose.PDF 转换 PDF 到 LaTeX/TeX 的免费应用程序](pdf_to_latex.png)](https://products.aspose.app/pdf/conversion/pdf-to-tex) +[![Aspose.PDF 使用应用将 PDF 转换为 LaTeX/TeX](pdf_to_latex.png)](https://products.aspose.app/pdf/conversion/pdf-to-tex) {{% /alert %}} -要将 PDF 文件转换为 TeX,Aspose.PDF 提供了 [LaTeXSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/latexsaveoptions/) 类,该类提供 OutDirectoryPath 属性用于在转换过程中保存临时图像。 +要将 PDF 文件转换为 TeX,Aspose.PDF 提供了一个类 [LaTeX 保存选项](https://reference.aspose.com/pdf/python-net/aspose.pdf/latexsaveoptions/) 它提供属性 OutDirectoryPath,用于在转换过程中保存临时图像。 以下代码片段展示了使用 Python 将 PDF 文件转换为 TEX 格式的过程。 ```python +import aspose.pdf as ap +from os import path +import sys - import aspose.pdf as ap +def convert_PDF_to_TeX(infile, outfile): + document = ap.Document(infile) + save_options = ap.LaTeXSaveOptions() + document.save(outfile, save_options) - input_pdf = DIR_INPUT + "sample.pdf" - output_pdf = DIR_OUTPUT + "convert_pdf_to_tex.tex" - # 打开 PDF 文档 - document = ap.Document(input_pdf) - # 实例化 LaTeXSaveOptions 对象 - saveOptions = ap.LaTeXSaveOptions() - document.save(output_pdf, saveOptions) + print(infile + " converted into " + outfile) ``` ## 将 PDF 转换为文本 -**Aspose.PDF for Python** 支持将整个 PDF 文档和单个页面转换为文本文件。 - -### 将 PDF 文档转换为文本文件 - -您可以使用 'TextDevice' 类将 PDF 文档转换为 TXT 文件。 - -以下代码片段说明了如何从所有页面中提取文本。 +**Aspose.PDF for Python** 支持将整个 PDF 文档和单页转换为文本文件。您可以使用 'TextDevice' 类将 PDF 文档转换为 TXT 文件。以下代码片段说明了如何从所有页面提取文本。 ```python +import aspose.pdf as ap +from os import path +import sys - import aspose.pdf as ap - - input_pdf = DIR_INPUT + "sample.pdf" - output_pdf = DIR_OUTPUT + "convert_pdf_to_txt.txt" - # 打开 PDF 文档 - document = ap.Document(input_pdf) +def convert_PDF_to_TXT(infile, outfile): + document = ap.Document(infile) + device = ap.devices.TextDevice() + device.process(document.pages[1], outfile) - # 创建文本设备 - textDevice = ap.devices.TextDevice() - - # 转换特定页面并保存 - textDevice.process(document.pages[1], output_pdf) + print(infile + " converted into " + outfile) ``` -**尝试在线转换 PDF 为文本** {{% alert color="success" %}} +**尝试将 PDF 转换为文本在线** + +Aspose.PDF for Python 为您呈现在线应用 ["PDF 转文本"](https://products.aspose.app/pdf/conversion/pdf-to-txt),在此您可以尝试调查其功能以及其工作质量。 -[![Aspose.PDF 转换 PDF 为文本的免费应用程序](pdf_to_text.png)](https://products.aspose.app/pdf/conversion/pdf-to-txt) +[![Aspose.PDF 将 PDF 转换为文本的应用](pdf_to_text.png)](https://products.aspose.app/pdf/conversion/pdf-to-txt) {{% /alert %}} ## 将 PDF 转换为 XPS -**Aspose.PDF for Python** 提供了将 PDF 文件转换为 XPS 格式的可能性。让我们尝试使用所提供的代码片段将 PDF 文件转换为 Python 中的 XPS 格式。 +**Aspose.PDF for Python** 提供了将 PDF 文件转换为 XPS 格式的可能性。让我们尝试使用示例代码片段在 Python 中将 PDF 文件转换为 XPS 格式。 {{% alert color="success" %}} -**尝试在线转换 PDF 为 XPS** +**尝试在线将 PDF 转换为 XPS** -Aspose.PDF for Python 为您提供了在线免费应用程序["PDF to XPS"](https://products.aspose.app/pdf/conversion/pdf-to-xps),您可以在其中尝试调查其功能和工作质量。 +Aspose.PDF for Python 为您呈现在线应用 ["PDF 转 XPS"](https://products.aspose.app/pdf/conversion/pdf-to-xps),在此您可以尝试调查其功能以及其工作质量。 -[![Aspose.PDF 转换 PDF 为 XPS 的免费应用程序](pdf_to_xps.png)](https://products.aspose.app/pdf/conversion/pdf-to-xps) +[![Aspose.PDF 使用应用程序将 PDF 转换为 XPS](pdf_to_xps.png)](https://products.aspose.app/pdf/conversion/pdf-to-xps) {{% /alert %}} -XPS 文件类型主要与 Microsoft Corporation 的 XML 纸张规范相关联。XML 纸张规范(XPS),以前代号为 Metro,并且包含下一代打印路径(NGPP)营销概念,是微软将文档创建和查看集成到 Windows 操作系统中的一项计划。 +XPS 文件类型主要与微软公司的 XML Paper Specification(XML 纸张规范)相关联。XML Paper Specification(XPS),此前代号为 Metro,并整合了下一代打印路径(NGPP)营销概念,是微软将文档创建和查看集成到 Windows 操作系统中的倡议。 -为了将 PDF 文件转换为 XPS,Aspose.PDF 提供了类 [XpsSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/xpssaveoptions/),用于作为 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法的第二个参数来生成 XPS 文件。 +要将 PDF 文件转换为 XPS,Aspose.PDF 提供了该类 [XpsSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/xpssaveoptions/) 被用作第二个参数 [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 生成 XPS 文件的方法。 以下代码片段展示了将 PDF 文件转换为 XPS 格式的过程。 ```python +import aspose.pdf as ap +from os import path +import sys - import aspose.pdf as ap - - input_pdf = DIR_INPUT + "sample.pdf" - output_pdf = DIR_OUTPUT + "convert_pdf_to_xps.xps" - # 打开 PDF 文档 - document = ap.Document(input_pdf) - - # 实例化 XPS 保存选项 +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) - # 保存 XPS 文档 - document.save(output_pdf, save_options) + print(infile + " converted into " + outfile) ``` -## 转换 PDF 为 XML - -{{% alert color="success" %}} -**尝试在线将 PDF 转换为 XML** - -Aspose.PDF for Python 为您提供了一个在线免费应用程序 ["PDF to XML"](https://products.aspose.app/pdf/conversion/pdf-to-xml),您可以尝试研究其功能和工作质量。 +## 将 PDF 转换为 MD -[![Aspose.PDF 使用免费应用程序将 PDF 转换为 XML](pdf_to_xml.png)](https://products.aspose.app/pdf/conversion/pdf-to-xml) -{{% /alert %}} +Aspose.PDF有类‘MarkdownSaveOptions()’,它可以将PDF文档转换为Markdown(MD)格式,同时保留图像和资源。 -XML 是一种用于存储、传输和重构任意数据的标记语言和文件格式。 - -Aspose.PDF for Python 还支持将 PDF 文档转换为 XML 格式的功能。Aspose.PDF for Python 有一个名为 'XmlSaveOptions' 的类,可以用作 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法的第二个参数,以生成 XML 文件。请尝试使用以下代码片段来完成此需求。 +1. 使用 'ap.Document' 加载源 PDF。 +1. 创建一个 'MarkdownSaveOptions' 的实例。 +1. 将 'resources_directory_name' 设置为 'images' – 提取的图像将存储在此文件夹中。 +1. 使用配置的选项保存转换后的 Markdown 文档。 +1. 在转换后打印确认消息。 ```python +import aspose.pdf as ap +from os import path +import sys + +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) +``` - import aspose.pdf as ap +一个 Markdown 文件,包含文本和链接的图片,存放在指定的 images 文件夹中。 - def convert_pdf_to_xml(self, infile, outfile): - path_infile = self.dataDir + infile - path_outfile = self.dataDir + outfile +## 将 PDF 转换为 MobiXML - # 打开 PDF 文档 +此方法将 PDF 文档转换为 MOBI(MobiXML)格式,该格式常用于 Kindle 设备上的电子书。 - document = ap.Document(path_infile) +1. 使用 'ap.Document' 加载源 PDF 文档。 +1. 使用格式 'ap.SaveFormat.MOBI_XML' 保存文档。 +1. 转换完成后打印确认消息。 - # 实例化 XML 保存选项 - save_options = ap.XmlSaveOptions() +```python +import aspose.pdf as ap +from os import path +import sys - # 保存 XML 文档 - document.save(path_outfile, save_options) - print(infile + " 已转换为 " + outfile) -``` \ No newline at end of file +def convert_PDF_to_MobiXML(infile, outfile): + document = ap.Document(infile) + document.save(outfile, ap.SaveFormat.MOBI_XML) + + print(infile + " converted into " + outfile) +``` diff --git a/zh/python-net/converting/convert-pdf-to-other-files/pdf_to_epub.png b/zh/python-net/converting/convert-pdf-to-other-files/pdf_to_epub.png new file mode 100644 index 0000000000..4ca5e0b59b Binary files /dev/null and b/zh/python-net/converting/convert-pdf-to-other-files/pdf_to_epub.png differ diff --git a/zh/python-net/converting/convert-pdf-to-other-files/pdf_to_latex.png b/zh/python-net/converting/convert-pdf-to-other-files/pdf_to_latex.png new file mode 100644 index 0000000000..75e9f892d9 Binary files /dev/null and b/zh/python-net/converting/convert-pdf-to-other-files/pdf_to_latex.png differ diff --git a/zh/python-net/converting/convert-pdf-to-other-files/pdf_to_text.png b/zh/python-net/converting/convert-pdf-to-other-files/pdf_to_text.png new file mode 100644 index 0000000000..3286e1906b Binary files /dev/null and b/zh/python-net/converting/convert-pdf-to-other-files/pdf_to_text.png differ diff --git a/zh/python-net/converting/convert-pdf-to-other-files/pdf_to_xps.png b/zh/python-net/converting/convert-pdf-to-other-files/pdf_to_xps.png new file mode 100644 index 0000000000..c715946a9d Binary files /dev/null and b/zh/python-net/converting/convert-pdf-to-other-files/pdf_to_xps.png differ diff --git a/zh/python-net/converting/convert-pdf-to-pdfa/_index.md b/zh/python-net/converting/convert-pdf-to-pdfa/_index.md deleted file mode 100644 index fcb0800815..0000000000 --- a/zh/python-net/converting/convert-pdf-to-pdfa/_index.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: 将PDF转换为PDF/A格式在Python中 -linktitle: 将PDF转换为PDF/A格式 -type: docs -weight: 100 -url: /zh/python-net/convert-pdf-to-pdfa/ -lastmod: "2022-12-23" -description: 本主题向您展示如何通过Python使用Aspose.PDF将PDF文件转换为符合PDF/A标准的PDF文件。 -sitemap: - changefreq: "monthly" - priority: 0.8 ---- - -**Aspose.PDF for Python** 允许您将PDF文件转换为符合PDF/A标准的PDF文件。在执行此操作之前,必须验证文件。本文将解释如何操作。 - -{{% alert color="primary" %}} - -请注意,我们遵循Adobe Preflight来验证PDF/A符合性。市场上的所有工具都有自己对PDF/A符合性的“表示”。请查看这篇关于PDF/A验证工具的文章以作参考。我们选择Adobe产品来验证Aspose.PDF如何生成PDF文件,因为Adobe是与PDF相关的一切的中心。 - -{{% /alert %}} - -使用Document类的Convert方法转换文件。 - 在将 PDF 转换为符合 PDF/A 的文件之前,请使用 Validate 方法验证 PDF。验证结果存储在一个 XML 文件中,然后此结果也传递给 Convert 方法。您还可以使用 ConvertErrorAction 枚举指定无法转换的元素的操作。 - -{{% alert color="success" %}} -**尝试在线将 PDF 转换为 PDF/A** - -Aspose.PDF for Python 为您提供免费的在线应用程序 ["PDF to PDF/A-1A"](https://products.aspose.app/pdf/conversion/pdf-to-pdfa1a),您可以尝试研究其功能和工作质量。 - -[![Aspose.PDF 使用免费应用程序将 PDF 转换为 PDF/A](pdf_to_pdfa.png)](https://products.aspose.app/pdf/conversion/pdf-to-pdfa1a) -{{% /alert %}} - -## 将 PDF 文件转换为 PDF/A-1b - -以下代码片段展示了如何将 PDF 文件转换为符合 PDF/A-1b 的 PDF。 - -```python - - import aspose.pdf as ap - - input_pdf = DIR_INPUT + "sample.pdf" - output_pdf = DIR_OUTPUT + "convert_pdf_to_pdfa.pdf" - output_log = DIR_OUTPUT + "convert_pdf_to_pdfa.log" - # 打开 PDF 文档 - document = ap.Document(input_pdf) - # 转换为符合 PDF/A 的文档 - document.convert(output_log, ap.PdfFormat.PDF_A_1B, ap.ConvertErrorAction.DELETE) - # 保存输出文档 - document.save(output_pdf) -``` \ No newline at end of file diff --git a/zh/python-net/converting/convert-pdf-to-pdfx/_index.md b/zh/python-net/converting/convert-pdf-to-pdfx/_index.md new file mode 100644 index 0000000000..642c067d23 --- /dev/null +++ b/zh/python-net/converting/convert-pdf-to-pdfx/_index.md @@ -0,0 +1,280 @@ +--- +title: 在 Python 中将 PDF 转换为 PDF/A、PDF/E 和 PDF/X +linktitle: 将 PDF 转换为 PDF/A、PDF/E 和 PDF/X +type: docs +weight: 120 +url: /zh/python-net/convert-pdf-to-pdf_x/ +lastmod: "2026-06-08" +description: 了解如何使用 Aspose.PDF for Python via .NET 在 Python 中将 PDF 文件转换为 PDF/A、PDF/E 和 PDF/X,以用于归档、可访问性和打印工作流。 +sitemap: + changefreq: "monthly" + priority: 0.8 +TechArticle: true +AlternativeHeadline: 如何将 PDF 转换为 PDF/x 格式 +Abstract: 本文提供了使用 Aspose.PDF for Python 将 PDF 转换为 PDF/A、PDF/E 和 PDF/X 格式的全面指南。 +--- + +**PDF 到 PDF/x 格式指的是将 PDF 转换为其他附加格式的能力,即 PDF/A、PDF/E 和 PDF/X。** + +## 将 PDF 转换为 PDF/A + +**Aspose.PDF for Python** 允许您将 PDF 文件转换为 PDF/A 符合规范的 PDF 文件。在此之前,必须验证该文件。本主题说明如何操作。 + +{{% alert color="primary" %}} + +请注意,我们使用 Adobe Preflight 来验证 PDF/A 合规性。市场上的所有工具都有各自对 PDF/A 合规性的“表示”。请参考此关于 PDF/A 验证工具的文章。我们选择 Adobe 产品来验证 Aspose.PDF 生成 PDF 文件的方式,因为 Adobe 是所有与 PDF 相关事物的核心。 + +{{% /alert %}} + +使用 Document 类的 Convert 方法转换文件。在将 PDF 转换为符合 PDF/A 标准的文件之前,使用 Validate 方法对 PDF 进行验证。验证结果存储在 XML 文件中,然后该结果也传递给 Convert 方法。您还可以使用 ConvertErrorAction 枚举指定对无法转换的元素的操作。 + +{{% alert color="success" %}} +**尝试在线将 PDF 转换为 PDF/A** + +Aspose.PDF for Python 为您呈现在线应用 [PDF 转 PDF/A-1A](https://products.aspose.app/pdf/conversion/pdf-to-pdfa1a),在此您可以尝试调查其功能以及其工作质量。 + +[![Aspose.PDF 将 PDF 转换为 PDF/A 的应用](pdf_to_pdfa.png)](https://products.aspose.app/pdf/conversion/pdf-to-pdfa1a) +{{% /alert %}} + +'document.validate()' 方法验证 PDF 文件是否符合 PDF/A-1B 标准(ISO 标准化的 PDF 版本,旨在长期存档)。验证结果保存到日志文件中。 + +### 将 PDF 转换为 PDF/A-1B + +以下代码片段展示了如何将 PDF 文件转换为 PDF/A-1B 格式: + +1. 使用 'ap.Document' 加载 PDF 文档。 +1. 使用以下参数调用 convert 方法: + - 日志文件路径 - 存储转换过程和合规检查的详细信息。 + - 目标格式 - 'ap.PdfFormat.PDF_A_1B'(存档标准)。 + - Error action - ‘ap.ConvertErrorAction.DELETE’ — 自动删除阻止合规性的元素。 +1. 将转换后的符合 PDF/A 标准的文件保存到输出路径。 + +```python +import aspose.pdf as ap +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) +``` + +### 将 PDF 转换为 PDF 2.0 和 PDF/A-4 + +此示例演示如何将 PDF 文档转换为更新的标准化格式:PDF 2.0 和 PDF/A-4。 +两种转换都有助于确保符合现代规范和归档要求。 + +1. 使用 ap.Document 加载输入文档。 +1. 通过调用 document.convert 执行首次转换为 PDF 2.0: + - 转换详情的日志文件路径。 + - 目标格式 - 'ap.PdfFormat.V_2_0'。 + - 错误操作 - 'ap.ConvertErrorAction.DELETE' 用于移除不合规的元素。 +1. 使用相同的方法进行第二次转换为 PDF/A-4,确保文件也符合归档标准。 +1. 将生成的文档保存到指定的输出路径。 + +```python +import aspose.pdf as ap +from os import path +import sys + +def convert_PDF_to_PDFA4(infile, outfile): + logfile = outfile.replace(".pdf", "_log.xml") + + 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) +``` + +### 将 PDF 转换为带嵌入文件的 PDF/A-3A + +下面的代码片段演示了如何将外部文件嵌入 PDF 中,然后将 PDF 转换为 PDF/A-3A 格式,该格式支持附件,适用于带有嵌入内容的长期归档。 + +1. 使用 'ap.Document' 加载输入 PDF。 +1. 创建一个指向要嵌入的文件(例如 "aspose-logo.jpg")的 'FileSpecification' 对象,并提供描述。 +1. 将文件规范添加到 PDF 的 'embedded_files' 集合中。 +1. 使用 'document.convert' 将文档转换为 PDF/A-3A,指定: + - 日志文件路径。 + - 目标格式 - 'ap.PdfFormat.PDF_A_3A'. + - 错误操作 - 'ap.ConvertErrorAction.DELETE' 用于移除不合规的元素。 +1. 将转换后的 PDF 保存到输出路径。 +1. 打印确认消息。 + +```python +import aspose.pdf as ap +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) +``` + +### 将 PDF 转换为 PDF/A-1B 并进行字体替换 + +此函数将 PDF 转换为 PDF/A-1B 格式,同时通过用可用的字体替换缺失的字体来处理。这样可确保转换后的 PDF 在视觉上保持一致,并符合归档标准。 + +1. 使用 'ap.Document' 加载 PDF。 +1. 使用 'document.convert' 将 PDF 转换为 PDF/A-1B,指定: + - 日志文件路径。 + - 目标格式 - 'ap.PdfFormat.PDF_A_1B'。 + - 错误操作 - 'ap.ConvertErrorAction.DELETE' 用于移除不合规的元素。 +1. 将转换后的 PDF 保存到输出路径。 +1. 打印确认消息。 + +```python +import aspose.pdf as ap +from os import path +import sys + +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) + + document = ap.Document(infile) + document.convert(logfile, ap.PdfFormat.PDF_A_1B, ap.ConvertErrorAction.DELETE) + document.save(outfile) +``` + +### 将 PDF 转换为 PDF/A-1B 并自动标记 + +此函数将 PDF 文档转换为 PDF/A-1B 格式,同时自动为内容添加标签,以实现可访问性和结构一致性。自动标记可提升文档在屏幕阅读器中的可用性,并确保正确的语义结构。 + +1. 使用 'ap.Document' 加载 PDF。 +1. 创建 'PdfFormatConversionOptions' 并指定: + - 日志文件路径。 + - 目标格式 - 'ap.PdfFormat.PDF_A_1B'。 + - 错误操作 - 'ap.ConvertErrorAction.DELETE' 用于移除不合规的元素。 +1. 配置 'AutoTaggingSettings': + - 启用 'enable_auto_tagging = True'。 + - 设置 'heading_recognition_strategy = AUTO' 以自动检测标题。 +1. 将自动标记设置分配给转换选项。 +1. 使用 'document.convert(options)' 将 PDF 转换。 +1. 将转换后的 PDF 保存到输出路径。 +1. 打印确认消息。 + +```python +import aspose.pdf as ap +from os import path +import sys + +def convert_PDF_to_PDFA_with_automatic_tagging(infile, outfile): + logfile = outfile.replace(".pdf", "-log.xml") + + 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.heading_recognition_strategy = ( + ap.HeadingRecognitionStrategy.AUTO + ) + + options.auto_tagging_settings = auto_tagging_settings + document.convert(options) + document.save(outfile) + print(infile + " converted into " + outfile) +``` + +## 将 PDF 转换为 PDF/E + +此代码片段演示了如何将 PDF 文档转换为 PDF/E-1 格式,该格式是专为工程和技术文档制定的 ISO 标准。该格式保留了工程工作流所需的精确布局、图形和元数据。 + +1. 使用 'ap.Document' 加载源 PDF。 +1. 创建 'PdfFormatConversionOptions' 并指定: + - 用于跟踪转换问题的日志文件路径。 + - 目标格式 - 'ap.PdfFormat.PDF_E_1'. + - 错误操作 - 'ap.ConvertErrorAction.DELETE' 用于移除不合规的元素。 +1. 使用 'document.convert(options)' 将 PDF 转换。 +1. 将转换后的 PDF 保存到指定的输出路径。 +1. 打印确认消息。 + +```python +import aspose.pdf as ap +from os import path +import sys + +def convert_PDF_to_PDF_E(infile, outfile): + logfile = outfile.replace(".pdf", "-log.xml") + + document = ap.Document(infile) + options = ap.PdfFormatConversionOptions( + logfile, ap.PdfFormat.PDF_E_1, ap.ConvertErrorAction.DELETE + ) + + document.convert(options) + + # Save PDF document + document.save(outfile) + print(infile + " converted into " + outfile) +``` + +## 将 PDF 转换为 PDF/X + +下面的代码片段将 PDF 文档转换为 PDF/X-4 格式,这是印刷和出版行业常用的 ISO 标准。PDF/X-4 确保颜色准确性,保持透明度,并嵌入 ICC 配置文件,以在不同设备之间实现一致的输出。 + +1. 使用 'ap.Document' 加载源 PDF。 +1. 创建 'PdfFormatConversionOptions' 并指定: + - 日志文件路径。 + - 目标格式 - 'ap.PdfFormat.PDF_X_4'. + - 错误操作 - 'ap.ConvertErrorAction.DELETE' 用于移除不合规的元素。 +1. 通过 'icc_profile_file_name' 提供用于颜色管理的 **ICC 配置文件**。 +1. 为打印要求指定带有条件标识符(例如 "FOGRA39")的 **OutputIntent**。 +1. 使用 'document.convert()' 将 PDF 转换。 +1. 将转换后的 PDF 保存到指定的输出路径。 +1. 打印确认消息。 + +```python +import aspose.pdf as ap +from os import path +import sys + +def convert_PDF_to_PDF_X(infile, outfile): + logfile = outfile.replace(".pdf", "-log.xml") + + 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( + 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) + + # Save PDF document + document.save(outfile) + print(infile + " converted into " + outfile) +``` + +## 相关转换 + +- [转换 PDF 为 Word](/pdf/zh/python-net/convert-pdf-to-word/) 用于标准验证后的可编辑内容工作流。 +- [将 PDF 转换为 HTML](/pdf/zh/python-net/convert-pdf-to-html/) 当您的目标输出是面向网页而不是基于标准的 PDF 时。 diff --git a/zh/python-net/converting/convert-pdf-to-pdfx/pdf_to_pdfa.png b/zh/python-net/converting/convert-pdf-to-pdfx/pdf_to_pdfa.png new file mode 100644 index 0000000000..d126570b19 Binary files /dev/null and b/zh/python-net/converting/convert-pdf-to-pdfx/pdf_to_pdfa.png differ diff --git a/zh/python-net/converting/convert-pdf-to-powerpoint/_index.md b/zh/python-net/converting/convert-pdf-to-powerpoint/_index.md index f1536f3833..ef997eea45 100644 --- a/zh/python-net/converting/convert-pdf-to-powerpoint/_index.md +++ b/zh/python-net/converting/convert-pdf-to-powerpoint/_index.md @@ -1,26 +1,26 @@ --- -title: 在 Python 中将 PDF 转换为 PowerPoint +title: 使用 Python 将 PDF 转换为 PowerPoint linktitle: 将 PDF 转换为 PowerPoint type: docs weight: 30 url: /zh/python-net/convert-pdf-to-powerpoint/ -description: 了解如何在 Python 中将 PDF 转换为 PowerPoint,包括使用 Aspose.PDF 将 PDF 转换为 PPTX、将幻灯片保存为图像以及自定义图像分辨率。 -lastmod: "2026-04-14" +description: 了解如何在 Python 中将 PDF 转换为 PowerPoint,包括 PDF 转换为 PPTX、将幻灯片保存为图像,以及使用 Aspose.PDF 自定义图像分辨率。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 TechArticle: true -AlternativeHeadline: 在 Python 中将 PDF 转换为 PPTX PowerPoint 幻灯片 -Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 将 PDF 文件转换为 PowerPoint 演示文稿。它涵盖了 PDF 转 PPTX 的转换、将幻灯片转换为图像以及为演示输出设置图像分辨率。 +AlternativeHeadline: 使用 Python 将 PDF 转换为 PPTX PowerPoint 幻灯片 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 将 PDF 文件转换为 PowerPoint 演示文稿。它涵盖了 PDF 转 PPTX 的转换、将幻灯片转换为图像,以及为演示输出设置图像分辨率。 --- -## 在 Python 中将 PDF 转换为 PowerPoint +## 使用 Python 将 PDF 转换为 PowerPoint -**Aspose.PDF for Python via .NET** 允许您从 Python 代码将 PDF 文件转换为 PowerPoint PPTX 演示文稿。 +**Aspose.PDF for Python via .NET** 让您可以从 Python 代码将 PDF 文件转换为 PowerPoint PPTX 演示文稿。 -当您需要将 PDF 报告、幻灯片、手册或讲义重新用于 PowerPoint 文件时,请使用此工作流。在转换过程中,单个 PDF 页面会转换为 PPTX 文件中的独立幻灯片。 +当您需要将 PDF 报告、幻灯片、手册或讲义重新用于 PowerPoint 文件时,请使用此工作流程。在转换过程中,单个 PDF 页面会被转换为 PPTX 文件中的单独幻灯片。 -在 PDF 转 PPTX 的转换过程中,文本可以渲染为可在 PowerPoint 中选择并编辑的文字。要将 PDF 文件转换为 PPTX 格式,Aspose.PDF 提供了 [PptxSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/) 类。传递一个 `PptxSaveOptions` 对象作为第二个参数传递给 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法。 +在 PDF 转 PPTX 的转换过程中,文本可以被渲染为可选择的文字,您可以在 PowerPoint 中进行更新。要将 PDF 文件转换为 PPTX 格式,Aspose.PDF 提供了 [PptxSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/) 类。传递 a `PptxSaveOptions` 对象作为第二个参数传递给 [save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法。 ## 在 Python 中将 PDF 转换为 PPTX @@ -28,8 +28,8 @@ Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 将 PDF 文 步骤:在 Python 中将 PDF 转换为 PowerPoint -1. 创建一个实例 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类。 -1. 创建一个实例 [PptxSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/) 类。 +1. 创建实例 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 类。 +1. 创建实例 [PptxSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/) 类。 1. 调用 [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 方法。 ```python @@ -48,13 +48,13 @@ def convert_PDF_to_PPTX(infile, outfile): {{% alert color="success" %}} **尝试在线将 PDF 转换为 PowerPoint** -Aspose.PDF 提供在线 ["PDF 转 PPTX"](https://products.aspose.app/pdf/conversion/pdf-to-pptx) 可以测试转换质量的应用程序。 +Aspose.PDF 提供在线 ["PDF 转 PPTX"](https://products.aspose.app/pdf/conversion/pdf-to-pptx) 您可以测试转换质量的应用程序。 -[![Aspose.PDF 转换 PDF 为 PPTX 的应用程序](pdf_to_pptx.png)](https://products.aspose.app/pdf/conversion/pdf-to-pptx) +[![Aspose.PDF 应用程序将 PDF 转换为 PPTX](pdf_to_pptx.png)](https://products.aspose.app/pdf/conversion/pdf-to-pptx) {{% /alert %}} -如果您需要将可搜索的 PDF 转换为图像形式的 PPTX,而不是可选择的文本,Aspose.PDF 提供了通过 [PptxSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/) 类。要实现此功能,请设置属性 [slides_as_images](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/#properties) 的 [PptxSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/) 如下面的代码示例所示,将 class 设置为 'true'。 +如果您需要将可搜索的 PDF 转换为图像形式的 PPTX,而不是可选择的文本,Aspose.PDF 提供了此功能 via [PptxSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/) 类。要实现此目的,设置属性 [slides_as_images](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/#properties) 的 [PptxSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/pptxsaveoptions/) 类为 'true',如以下代码示例所示。 ```python import aspose.pdf as ap @@ -70,13 +70,13 @@ def convert_PDF_to_PPTX_slides_as_images(infile, outfile): document.save(outfile, save_options) ``` -## 使用自定义图像分辨率将 PDF 转换为 PPTX +## 将 PDF 转换为 PPTX(自定义图像分辨率) -此方法将 PDF 文档转换为 PowerPoint(PPTX)文件,并设置自定义图像分辨率(300 DPI)以提升质量。 +此方法在设置自定义图像分辨率(300 DPI)以提升质量的同时,将 PDF 文档转换为 PowerPoint(PPTX)文件。 1. 将 PDF 加载到 'ap.Document' 对象中。 1. 创建一个 'PptxSaveOptions' 实例。 -1. 将 'image_resolution' 属性设置为 300 DPI,以实现高质量渲染。 +1. 将 'image_resolution' 属性设置为 300 DPI,以获得高质量渲染。 1. 使用已定义的保存选项将 PDF 保存为 PPTX 文件。 ```python @@ -94,6 +94,6 @@ def convert_PDF_to_PPTX_image_resolution(infile, outfile): ## 相关转换 -- [转换 PDF 为 Word](/pdf/zh/python-net/convert-pdf-to-word/) 用于可编辑的文档输出,而不是幻灯片。 -- [转换 PDF 为 Excel](/pdf/zh/python-net/convert-pdf-to-excel/) 当源 PDF 包含大量表格的业务数据时。 +- [转换 PDF 为 Word](/pdf/zh/python-net/convert-pdf-to-word/) 用于可编辑的文档输出而不是幻灯片。 +- [将 PDF 转换为 Excel](/pdf/zh/python-net/convert-pdf-to-excel/) 当源 PDF 包含大量表格的业务数据时。 - [将 PDF 转换为 HTML](/pdf/zh/python-net/convert-pdf-to-html/) 用于浏览器就绪的发布工作流。 diff --git a/zh/python-net/converting/convert-pdf-to-powerpoint/pdf_to_pptx.png b/zh/python-net/converting/convert-pdf-to-powerpoint/pdf_to_pptx.png new file mode 100644 index 0000000000..9a0932cef7 Binary files /dev/null and b/zh/python-net/converting/convert-pdf-to-powerpoint/pdf_to_pptx.png differ diff --git a/zh/python-net/converting/convert-pdf-to-word/_index.md b/zh/python-net/converting/convert-pdf-to-word/_index.md index fd81769a52..53dfce2e4f 100644 --- a/zh/python-net/converting/convert-pdf-to-word/_index.md +++ b/zh/python-net/converting/convert-pdf-to-word/_index.md @@ -1,36 +1,36 @@ --- title: 在 Python 中将 PDF 转换为 Word -linktitle: 将 PDF 转换为 Word +linktitle: 转换 PDF 为 Word type: docs weight: 10 url: /zh/python-net/convert-pdf-to-word/ -lastmod: "2026-04-14" +lastmod: "2026-06-08" description: 了解如何在 Python 中将 PDF 转换为 Word,包括 PDF 转 DOC、PDF 转 DOCX,以及使用 Aspose.PDF 的高级布局识别。 sitemap: changefreq: "monthly" priority: 0.7 TechArticle: true AlternativeHeadline: 在 Python 中将 PDF 转换为 DOC 和 DOCX -Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 将 PDF 文件转换为 Microsoft Word 格式。它涵盖了 PDF 转 DOC、PDF 转 DOCX 以及用于从 PDF 内容创建可编辑 Word 文档的高级布局识别选项。 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 将 PDF 文件转换为 Microsoft Word 格式。内容包括 PDF 转 DOC、PDF 转 DOCX,以及用于将 PDF 内容创建可编辑 Word 文档的高级布局识别选项。 --- -本页面展示了如何在 Python 中 **将 PDF 转换为 Word**。当您需要从 PDF 文件获得可编辑的 DOC 或 DOCX 输出,以用于修订、重用或办公文档工作流时,请使用这些示例。 +此页面展示了如何在 Python 中**将 PDF 转换为 Word**。当您需要从 PDF 文件获取可编辑的 DOC 或 DOCX 输出以进行修订、重用或办公文档工作流时,请使用这些示例。 ## 在 Python 中将 PDF 转换为 DOC -最受欢迎的功能之一是 PDF 转 Microsoft Word DOC 的转换,这使内容管理更加轻松。**Aspose.PDF for Python via .NET** 允许您将 PDF 文件不仅转换为 DOC,还可以轻松高效地转换为 DOCX 格式。 +最受欢迎的功能之一是 PDF 转换为 Microsoft Word DOC,这简化了内容管理。**Aspose.PDF for Python via .NET** 使您能够轻松高效地将 PDF 文件转换为 DOC 以及 DOCX 格式。 -当您需要修改文本、在办公工作流中重复使用内容,或将 PDF 内容转移为可编辑的 DOC 或 DOCX 文档时,请使用 Word 转换。 +当您需要修改文本、在办公工作流中重用内容或将 PDF 内容转移到可编辑的 DOC 或 DOCX 文档时,请使用 Word 转换。 -该 [DocSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/docsaveoptions/) class 提供了大量属性,以改进将 PDF 文件转换为 DOC 格式的过程。在这些属性中,Mode 使您能够指定 PDF 内容的识别模式。您可以为此属性指定来自 RecognitionMode 枚举的任意值。这些值各自具有特定的优势和限制: +这 [DocSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/docsaveoptions/) 类提供了众多属性,可提升将 PDF 文件转换为 DOC 格式的过程。在这些属性中,Mode 允许您指定 PDF 内容的识别模式。您可以为此属性指定 RecognitionMode 枚举中的任意值。每个值都有其特定的优势和限制: 步骤:在 Python 中将 PDF 转换为 DOC 1. 将 PDF 加载到 'ap.Document' 对象中。 -1. 创建 'DocSaveOptions' 实例。 +1. 创建一个 'DocSaveOptions' 实例。 1. 将 format 属性设置为 'DocFormat.DOC',以确保输出为 .doc 格式(旧版 Word 格式)。 1. 使用指定的保存选项将 PDF 保存为 Word 文档。 -1. 打印确认信息。 +1. 打印确认消息。 ```python from os import path @@ -49,24 +49,24 @@ def convert_PDF_to_DOC(infile, outfile): {{% alert color="success" %}} **尝试在线将 PDF 转换为 DOC** -Aspose.PDF for Python 为您提供在线应用程序 ["PDF 转 DOC"](https://products.aspose.app/pdf/conversion/pdf-to-doc),您可以尝试调查它的功能和质量。 +Aspose.PDF for Python 为您呈现在线应用 ["PDF 转换为 DOC"](https://products.aspose.app/pdf/conversion/pdf-to-doc),在此您可以尝试调查其功能以及其工作质量。 [![将 PDF 转换为 DOC](/pdf/zh/net/images/pdf_to_word.png)](https://products.aspose.app/pdf/conversion/pdf-to-doc) {{% /alert %}} ## 在 Python 中将 PDF 转换为 DOCX -Aspose.PDF for Python API 允许您使用通过 .NET 的 Python 读取和转换 PDF 文档为 DOCX。DOCX 是一种广为人知的 Microsoft Word 文档格式,其结构已从纯二进制更改为 XML 与二进制文件的组合。Docx 文件可以在 Word 2007 及后续版本中打开,但不能在较早版本的 Microsoft Word(仅支持 DOC 文件扩展名)中打开。 +Aspose.PDF for Python API 可让您使用基于 .NET 的 Python 读取并将 PDF 文档转换为 DOCX。DOCX 是一种广为人知的 Microsoft Word 文档格式,其结构已从纯二进制更改为 XML 与二进制文件的组合。Docx 文件可以在 Word 2007 及其后续版本中打开,但不能在早期支持 DOC 文件扩展名的 MS Word 版本中打开。 -以下 Python 代码片段展示了将 PDF 文件转换为 DOCX 格式的过程。 +下面的 Python 代码片段展示了将 PDF 文件转换为 DOCX 格式的过程。 步骤:在 Python 中将 PDF 转换为 DOCX 1. 使用 'ap.Document' 加载源 PDF。 -1. 创建 'DocSaveOptions' 的实例。 +1. 创建一个 'DocSaveOptions' 的实例。 1. 将 format 属性设置为 'DocFormat.DOC_X' 以生成 .docx 文件(现代 Word 格式)。 -1. 使用配置好的保存选项将 PDF 保存为 DOCX 文件。 -1. 转换后打印确认信息。 +1. 使用已配置的保存选项将 PDF 保存为 DOCX 文件。 +1. 在转换后打印确认消息。 ```python from os import path @@ -82,7 +82,7 @@ def convert_PDF_to_DOCX(infile, outfile): ## 使用高级布局识别将 PDF 转换为 DOCX -使用 Python 和 Aspose.PDF 将 PDF 文档转换为 DOCX(Word)文件,并使用高级识别设置。它使用增强的流模式来保留文档结构,使输出更易编辑且更接近原始布局。 +使用 Python 和 Aspose.PDF 将 PDF 文档转换为 DOCX(Word)文件,并使用高级识别设置。它采用增强的流模式来保留文档结构,使输出更易编辑且更接近原始布局。 ```python from os import path @@ -97,12 +97,12 @@ def convert_PDF_to_DOCX_advanced(infile, outfile): document.save(outfile, save_options) ``` -该 [DocSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/docsaveoptions/) 类具有名为 Format 的属性,提供指定结果文档格式的功能,即 DOC 或 DOCX。要将 PDF 文件转换为 DOCX 格式,请从 DocSaveOptions.DocFormat 枚举中传递 Docx 值。 +这 [DocSaveOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf/docsaveoptions/) 类具有名为 Format 的属性,可提供指定生成文档格式的功能,即 DOC 或 DOCX。为了将 PDF 文件转换为 DOCX 格式,请从 DocSaveOptions.DocFormat 枚举中传入 Docx 值。 {{% alert color="warning" %}} **尝试在线将 PDF 转换为 DOCX** -Aspose.PDF for Python 为您提供在线应用程序 ["PDF 转 Word"](https://products.aspose.app/pdf/conversion/pdf-to-docx),您可以尝试调查它的功能和质量。 +Aspose.PDF for Python 为您呈现在线应用 ["PDF 转 Word"](https://products.aspose.app/pdf/conversion/pdf-to-docx),在此您可以尝试调查其功能以及其工作质量。 [![Aspose.PDF 转换 PDF 到 Word 应用](/pdf/zh/net/images/pdf_to_word.png)](https://products.aspose.app/pdf/conversion/pdf-to-docx) @@ -111,5 +111,5 @@ Aspose.PDF for Python 为您提供在线应用程序 ["PDF 转 Word"](https://pr ## 相关转换 - [将 PDF 转换为 Excel](/pdf/zh/python-net/convert-pdf-to-excel/) 用于面向电子表格的导出。 -- [将 PDF 转换为 PowerPoint](/pdf/zh/python-net/convert-pdf-to-powerpoint/) 当您需要演示文稿幻灯片而不是文字处理输出时。 -- [将 PDF 转换为 HTML](/pdf/zh/python-net/convert-pdf-to-html/) 用于网页发布和基于浏览器的内容工作流。 +- [将 PDF 转换为 PowerPoint](/pdf/zh/python-net/convert-pdf-to-powerpoint/) 当您需要演示幻灯片而不是文字处理输出时。 +- [将 PDF 转换为 HTML](/pdf/zh/python-net/convert-pdf-to-html/) 用于网络出版和基于浏览器的内容工作流。 diff --git a/zh/python-net/converting/convert-pdfx-to-pdf/_index.md b/zh/python-net/converting/convert-pdfx-to-pdf/_index.md new file mode 100644 index 0000000000..120203ca71 --- /dev/null +++ b/zh/python-net/converting/convert-pdfx-to-pdf/_index.md @@ -0,0 +1,69 @@ +--- +title: 在 Python 中将 PDF/A 和 PDF/UA 转换为 PDF +linktitle: 将 PDF/A 和 PDF/UA 转换为 PDF +type: docs +weight: 120 +url: /zh/python-net/convert-pdf_x-to-pdf/ +lastmod: "2026-06-08" +description: 了解如何使用 Aspose.PDF for Python via .NET 在 Python 中移除 PDF 文件的 PDF/A 和 PDF/UA 合规性,并将其保存为标准 PDF 文档。 +sitemap: + changefreq: "monthly" + priority: 0.8 +TechArticle: true +AlternativeHeadline: 在 Python 中如何将 PDF/A 和 PDF/UA 转换为标准 PDF +Abstract: 本文解释了如何使用 Aspose.PDF for Python via .NET 从基于标准的 PDF 文档中移除 PDF/A 和 PDF/UA 合规性。它涵盖了您可能需要标准 PDF 而不是归档或受可访问性限制的文件的场景,并展示了在移除合规性元数据和限制后如何保存结果。 +--- + +当您需要将基于标准的 PDF(例如 PDF/A 或 PDF/UA)转换回普通 PDF 文档,以便进行下游编辑、处理或再分发时,请使用此页面。 + +符合标准的 PDF 对于归档、打印和可访问性工作流很有帮助,但在某些情况下,你可能需要在将文件集成到其他系统或管道之前移除这些合规性。Aspose.PDF for Python via .NET 让你可以以编程方式做到这一点,然后将结果保存为标准 PDF 文件。 + +## 将 PDF/A 转换为 PDF + +此示例从 PDF 中移除 PDF/A 合规性元数据和限制,使文档能够再次保存为普通 PDF 文件。 + +1. 使用 'ap.Document' 加载 PDF 文档。 +1. 调用 'remove_pdfa_compliance()' 来剥离所有与 PDF/A 相关的合规设置和元数据。 +1. 将生成的 PDF 保存到输出路径。 + +```python +import aspose.pdf as ap +from os import path +import sys + +def convert_PDFA_to_PDF(infile, outfile): + document = ap.Document(infile) + document.remove_pdfa_compliance() + document.save(outfile) +``` + +## 移除 PDF/UA 合规性 + +本示例演示如何移除与 PDF/UA 相关的合规性,使文档能够以标准 PDF 保存,用于非无障碍特定的工作流。 + +1. 使用 'ap.Document()' 加载 PDF 文档。 +1. 调用 'document.remove_pdfa_compliance()' 以移除任何 PDF/A 限制或合规性设置。 +1. 将修改后的 PDF 保存到 '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) +``` + +## 何时使用此工作流 + +- 在将文档发送到不需要 PDF/A 或 PDF/UA 限制的工具链之前,删除合规性设置。 +- 当不再需要归档或可访问性元数据时,简化下游文档处理。 +- 在将输入 PDF 导出为其他格式之前,标准化它们。 + +## 相关转换 + +- [将 PDF 转换为 PDF/A、PDF/E 和 PDF/X](/pdf/zh/python-net/convert-pdf-to-pdf_x/) 如果您需要相反的工作流并希望创建符合标准的 PDF。 +- [转换 PDF 为 Word](/pdf/zh/python-net/convert-pdf-to-word/) 用于在移除合规约束后生成可编辑的文档输出。 +- [将 PDF 转换为 HTML](/pdf/zh/python-net/convert-pdf-to-html/) 用于从标准 PDF 文件生成适合浏览器的输出。 diff --git a/zh/python-net/faq/_index.md b/zh/python-net/faq/_index.md new file mode 100644 index 0000000000..02976b8067 --- /dev/null +++ b/zh/python-net/faq/_index.md @@ -0,0 +1,16 @@ +--- +title: 常见问题 +linktitle: 常见问题 +type: docs +weight: 140 +url: /zh/python-net/faq/ +description: 在此您可以找到 Aspose.PDF for Python via .NET 库的常见问题解答。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: false +--- + +

Aspose.PDF for Python via .NET 支持哪些格式?

Aspose.PDF for Python via .NET 支持常见的文件格式,如 PDF、TXT、HTML、PCL、XML、XPS、EPUB、TEX 以及图像格式。更多详情,请访问页面 .

Aspose.PDF for Python via .NET 支持哪些 AI 功能?

是的,该库内置了 OpenAI 和 Llama API 客户端。它们允许您进行 API 请求并创建 AI 副驾驶。您可以在 页面。

我一次可以合并多少个文件为PDF?

您可以一次性将无限数量的文件合并为 PDF。

如何将图像插入 PDF?

要使用 Aspose.PDF for Python via .NET 将图像插入 PDF,您可以查找 .

如何编辑 PDF 中的文本?

要使用 Aspose.PDF for Python via .NET 编辑 PDF 中的文本,您可以查找 .

如何向 PDF 文件添加页码?

要在 PDF 中使用 Aspose.PDF for Python via .NET 添加页码,您可以找到 .

如何为 PDF 文档创建背景?

要使用 Aspose.PDF for Python via .NET 为 PDF 文档创建背景,您可以查找 .

如何保护 PDF 文档?

要使用 Aspose.PDF for Python via .NET 来保护 PDF 文档,您可以找到 .

如何在 PDF 页面上的高亮批注中添加粗体文本?

要在高亮注释中添加粗体文字,您可以找到 .

如何验证 Tagged PDF?

要验证标记的 PDF 文档,您可以找到 .

如何为 TextFragmentAbsorber 实现正则搜索?

要使用正则表达式与 `TextFragmentAbsorber` 在 Aspose.PDF for Python via .NET 中的类,您可以找到 .

如何在未提供缺失字体或其替代字体的情况下创建有效的 PDF/A 文档?

要创建有效的 PDF/A 文档,您可以找到 .

我在 PDF/A 转换日志中看到错误。这是否意味着文档未成功转换?

不,Aspose.PDF 会记录它遇到的所有问题,包括那些已自动修复的。如果日志中的所有条目都标记为 Convertable=True,则所有问题都已修复,文档已成功转换。只有标记为 Convertable=False 的条目表示转换失败。

如果转换日志包含 “Font not embedded” 错误,如何制作有效的 PDF/A 文档?

如果 PDF/A 转换日志中包含标记为 Convertable=False 的 “Font not embedded” 错误条目,则表示原始文档中包含的字体在文档本身和执行转换的机器上均未嵌入。检查 学习如何替换缺失的字体。

为什么 Aspose.PDF 在使用 ConvertErrorAction.None 选项时不将文档转换为 PDF/A?

ConvertErrorAction.None 选项可防止 Aspose.PDF 从文档中删除元素,即使这些元素被 PDF/A 标准禁止。结果是,使用 ConvertErrorAction.None 模式可能无法转换文档。当您不希望 Aspose.PDF 自动删除文档中被禁止的元素时,请使用此选项,尤其是当您计划审查转换日志并手动修复文档的issue时。另一种使用此选项的情形是当您的文档已经基本或完全符合 PDF/A 标准,并且您希望避免不必要的更改。更宽松的 PDF/A 版本(例如 PDF/A-2 或 PDF/A-3)在使用 ConvertErrorAction.None 选项时更有可能成功转换。然而,对于 PDF/A-1a 和 PDF/A-1b 标准,通常建议使用 ConvertErrorAction.Delete 选项。

Aspose.PDF for Python via .NET 是否支持 Linux?

是的,Aspose.PDF for Python via .NET 支持在 Linux 环境中运行。您可以使用 Python via .NET Core 版本或更高版本,它是跨平台的,可在 Windows、macOS 和 Linux 上使用。

您的 Python via .NET 示例在哪里?

您可以在此查看所有内容 .

+ diff --git a/zh/python-net/get-started/_index.md b/zh/python-net/get-started/_index.md index a74ce55133..3b812666ae 100644 --- a/zh/python-net/get-started/_index.md +++ b/zh/python-net/get-started/_index.md @@ -1,50 +1,51 @@ --- -title: Get Started -linktitle: Get Started +title: 开始使用 +linktitle: 开始使用 type: docs weight: 30 url: /zh/python-net/get-started/ -description: 本节介绍了通过 .NET 使用 Aspose.PDF for Python 的基本工作原理。Python 库支持多种功能。 +description: 了解如何使用 Aspose.PDF for Python via .NET 入门,以创建、编辑、转换、验证和提取 PDF 文档中的内容。 is_node: true -lastmod: "2022-12-20" +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 --- -## 什么是 PDF 文件? +## PDF 文件是什么? -PDF 是 Adobe 在 1990 年代创建的,目的是实现两件事。首先,你应该能够在任何硬件或操作系统上打开文档,而不需要拥有用于创建它们的应用程序——你所需要的只是一个 PDF 阅读器,如今大多数网络浏览器都可以胜任。其次,无论你在哪里打开 PDF,文档的布局都应该看起来一样。 +PDF 于 1990 年代由 Adobe 创建,旨在实现两个目标。其一是您应该能够在任何硬件或操作系统上打开文档,而无需拥有用于创建它们的应用程序——只需一个 PDF 阅读器,而如今大多数网页浏览器都满足此需求。其二是无论在何处打开 PDF,文档的布局都应保持一致。 -然而,仅仅打开文档是不够的。在使用 PDF 时,你将面临重新创建此类文档、编辑或将其转换为所需格式的需求。 +Aspose.PDF for Python via .NET 帮助您超越仅仅打开 PDF 文件的需求。您可以使用该库在 Python 应用程序中从零创建 PDF、编辑现有文档、提取内容、验证标准合规性,并将 PDF 转换为其他格式。 -## 为什么通过 .NET 使用 Aspose.PDF for Python? +## 为什么使用 Aspose.PDF for Python via .NET? -在项目中使用通过 .NET 的 Aspose.PDF for Python 可以为你带来以下好处: +在项目中使用 Aspose.PDF for Python via .NET 可为您带来以下优势: -- 多种功能 -- 基于 Aspose.PDF for .NET -- 方便易用 +- 广泛的 PDF 处理功能 +- 从 Python 访问经过验证的 Aspose.PDF for .NET 引擎 +- 一个实用的 API,用于常见的文档创建、编辑、解析和转换任务 -## 多种功能 +## 您可以自动化的常见 PDF 任务 -- 支持大多数已建立的 PDF 标准和 PDF 规范。 -- [在 PDF 文件中添加、搜索、提取和替换文本]()。 -- [添加/删除、提取和替换图像]()。 -- [插入、删除、拆分 PDF 页面]()。 -- [设置和获取 XMP 元数据]()。 -- 验证 (PDF/A-1a, PDF/A-1b)。 -- 使用[书签]()、[注释]()、[PDF 表单]()、[印章]()、[水印]()等。 +- 支持广泛使用的 PDF 标准和规范 +- [在 PDF 文件中添加、搜索、提取和替换文本](/pdf/zh/python-net/working-with-text/) +- [添加、删除、提取和替换图像](/pdf/zh/python-net/working-with-images/) +- [插入、删除、提取和管理 PDF 页面](/pdf/zh/python-net/working-with-pages/) +- [设置并保存 XMP 元数据](/pdf/zh/python-net/save-metadata-with-xmp/) +- [验证 PDF 文档是否符合 PDF/A-1a 和 PDF/A-1b 标准](/pdf/zh/python-net/manipulate-pdf-document/) +- 使用 [书签](/pdf/zh/python-net/bookmarks/), [批注](/pdf/zh/python-net/annotations/), [PDF 表单](/pdf/zh/python-net/working-with-forms/), [印章](/pdf/zh/python-net/stamping/),和 [水印](/pdf/zh/python-net/add-watermarks/) -## 转换功能 +## 文档转换功能 -- [将 PDF 转换为 Word、Excel 和 PowerPoint](/pdf/zh/python-net/convert-pdf-to-word/)。 -- [将 PDF 转换为图像格式](/pdf/zh/python-net/convert-pdf-to-images-format/)。 -- [将 PDF 文件转换为 HTML 格式,反之亦然](/pdf/zh//python-net/convert-pdf-to-html/)。 -- [将 PDF 转换为 EPUB、文本、XPS 等](/pdf/zh/python-net/convert-pdf-to-other-files/)。 -- 将 EPUB、Markdown、文本、XPS、PostScript、XML、LaTex 转换为 PDF +- [将 PDF 转换为 Word、Excel 和 PowerPoint](/pdf/zh/python-net/convert-pdf-to-word/). +- [将 PDF 转换为图像格式](/pdf/zh/python-net/convert-pdf-to-images-format/). +- [将 PDF 文件转换为 HTML 并将 HTML 转换为 PDF](/pdf/zh/python-net/convert-pdf-to-html/). +- [将 PDF 转换为 EPUB、文本、XPS 等](/pdf/zh/python-net/convert-pdf-to-other-files/). +- [将 EPUB、Markdown、文本、XPS、PostScript、XML、LaTex 转换为 PDF](/pdf/zh/python-net/convert-other-files-to-pdf/) -### 了解更多关于: +## 从这些教程开始 + +- [“Hello, World” Python 示例](/pdf/zh/python-net/hello-world-example/) +- [创建一个复杂的 PDF 文档](/pdf/zh/python-net/complex-pdf-example/) -- ["Hello, World" Python 示例](/pdf/zh/python-net/hello-world-example/) -- [复杂 PDF](/pdf/zh/python-net/complex-pdf-example/) \ No newline at end of file diff --git a/zh/python-net/get-started/complex-pdf/_index.md b/zh/python-net/get-started/complex-pdf/_index.md index 3bcacee3e3..0f53750322 100644 --- a/zh/python-net/get-started/complex-pdf/_index.md +++ b/zh/python-net/get-started/complex-pdf/_index.md @@ -1,64 +1,68 @@ --- - -title: 创建一个复杂的PDF -linktitle: 创建一个复杂的PDF -type: docs -weight: 30 -url: /zh/python-net/complex-pdf-example/ -description: Aspose.PDF for Python via .NET 允许您创建包含图像、文本片段和表格的更复杂的文档。 -lastmod: "2022-12-22" -sitemap: - changefreq: "weekly" - priority: 0.7 - +title: 创建复杂的 PDF +linktitle: 创建复杂的 PDF +type: docs +weight: 30 +url: /zh/python-net/complex-pdf-example/ +description: Aspose.PDF for Python via .NET 允许您创建包含图像、文本片段和表格的更复杂文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 创建复杂的 PDF +Abstract: 本文扩展了在 “Hello, World” 示例中演示的基本 PDF 创建过程,展示如何使用 Python 和 Aspose.PDF 创建更复杂的 PDF 文档。示例文档是为一家虚构的客运渡轮公司开发的,包含一幅图像、两个文本片段(标题和段落)以及一张表格。该过程包括多个步骤 - 实例化 `Document` 对象来创建空 PDF,添加 `Page`,然后在页面中插入 `Image`。使用 Arial 字体、24pt 大小并居中对齐来创建标题的 `TextFragment`,随后将其添加到页面的段落中。第二个 `TextFragment` 用于描述,采用 Times New Roman 字体、14pt 大小且左对齐。随后创建并格式化表格,包括特定的列宽、边框和内边距。表格包含带有高亮单元格的标题行以及通过迭代生成的多行数据。 --- -[Hello, World](/pdf/zh/python-net/hello-world-example/) 示例展示了使用 Python 和 Aspose.PDF 创建 PDF 文档的简单步骤。在本文中,我们将看看如何使用 Aspose.PDF for Python 创建一个更复杂的文档。作为一个例子,我们将从一家运营客运渡轮服务的虚构公司获取一份文档。我们的文档将包含一张图片、两个文本片段(标题和段落)和一个表格。 +这 [Hello, World](/pdf/zh/python-net/hello-world-example/) 示例展示了使用 Python 和 Aspose.PDF 创建 PDF 文档的简易步骤。在本文中,我们将探讨使用 Aspose.PDF for Python 创建更复杂的文档。比如,我们将使用一家虚构的客运渡轮公司文档作为案例。我们的文档将包含一张图像、两个文本片段(标题和段落)以及一个表格。 -如果我们从头开始创建一个文档,我们需要遵循一定的步骤: +如果我们从头创建文档,需要遵循以下步骤: -1. 实例化一个 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象。在这一步中,我们将创建一个包含一些元数据但没有页面的空PDF文档。 -1. 向文档对象添加一个 [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/)。现在我们的文档将有一页。 -1. 向页面添加一个 [Image](https://reference.aspose.com/pdf/python-net/aspose.pdf/image/)。 -1. 为页眉创建一个 [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf/texfragment/)。对于页眉,我们将使用Arial字体,字体大小为24pt,并居中对齐。 -1. 将页眉添加到页面的 [paragraphs](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties)。 -1. 为描述创建一个 [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf/texfragment/)。对于描述,我们将使用Arial字体,字体大小为24pt,并居中对齐。 -1. 将(描述)添加到页面段落。 -1. 创建一个表格,添加表格属性。 - -1. 添加 (表格) 到页面 [段落](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties)。 -1. 保存文档 "Complex.pdf"。 +1. 实例化一个 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象。在此步骤中,我们将创建一个没有页面但带有一些元数据的空 PDF 文档。 +1. 添加一个 [页面](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 添加到文档对象。因此,现在我们的文档将有一页。 +1. 添加一个 [图像](https://reference.aspose.com/pdf/python-net/aspose.pdf/image/) 到页面。 +1. 创建一个 [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf/texfragment/) 用于标题。我们将在标题中使用 Arial 字体,字号为 24pt,居中对齐。 +1. 将标题添加到页面 [段落](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties). +1. 创建一个 [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf/texfragment/) 用于描述。我们将在描述中使用 Arial 字体,字号为 24pt,居中对齐。 +1. 将描述添加到页面段落。 +1. 创建并设置表格样式。设置列宽、边框、内边距和字体。 +1. 在页面上添加表格 [段落](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/#properties). +1. 保存文档 \u0022Complex.pdf\u0022。 ```python +from datetime import timedelta +import aspose.pdf as ap + - import aspose.pdf as ap +def run_complex(self): - # 初始化文档对象 + # Initialize document object document = ap.Document() - # 添加页面 + # Add page page = document.pages.add() - # 添加图像 - 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)) - # 添加标题 - header = ap.text.TextFragment("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) - # 添加描述 - descriptionText = "游客必须在线购买门票,每天限量5000张。 \ - 渡轮服务正在半负荷运行,并且时间表减少。请预期排队。" + # 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) - # 添加表格 + # Add table table = ap.Table() table.column_widths = "200" @@ -69,13 +73,15 @@ sitemap: table.default_cell_text_state.font = ap.text.FontRepository.find_font("Helvetica") headerRow = table.rows.add() - headerRow.cells.add("出发城市") - headerRow.cells.add("出发岛屿") + 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) @@ -91,5 +97,5 @@ sitemap: page.paragraphs.add(table) - document.save(output_pdf) -``` \ No newline at end of file + document.save(self.data_dir + "Complex.pdf") +``` diff --git a/zh/python-net/get-started/hello-world-example/_index.md b/zh/python-net/get-started/hello-world-example/_index.md index 1aade3313d..73289a97eb 100644 --- a/zh/python-net/get-started/hello-world-example/_index.md +++ b/zh/python-net/get-started/hello-world-example/_index.md @@ -1,42 +1,59 @@ --- -title: Python 中 Hello World 的示例 +title: 使用 Python 的 Hello World 示例 linktitle: Hello World 示例 type: docs weight: 20 url: /zh/python-net/hello-world-example/ -description: 此示例演示如何使用 Aspose.PDF for Python via .NET 创建一个包含文本 Hello World 的简单 PDF 文档。 -lastmod: "2022-12-22" +description: 此示例演示如何使用 Aspose.PDF for Python via .NET 创建包含 Hello World 文本的简单 PDF 文档。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 通过 Python 的 Hello World 示例 +Abstract: 本文提供了一个使用 Aspose.PDF for Python via .NET 库创建 PDF 文档的 Hello World 示例。该示例演示了使用 Aspose.PDF API 的基本步骤,即生成包含文本 \"Hello World!\" 的 PDF。过程包括实例化 `Document` 对象、添加 `Page`、创建 `TextFragment` 对象、设置文本属性如字体大小和颜色,以及使用 `TextBuilder` 将文本添加到页面。生成的 PDF 随后保存为 \"HelloWorld_out.pdf\"。本文还包含完整的 Python 代码片段,展示这些步骤,作为库使用的入门指南。 --- -"Hello World" 示例展示了任何编程语言中最简单的语法和最简单的程序。开发人员通过学习如何在设备屏幕上打印 "Hello World",来了解基本的编程语言语法。因此,我们将传统地从它开始与我们的库的相识。 +\"Hello World\" 示例展示了任何给定编程语言中最简洁的语法和最基础的程序。开发者通过学习在设备屏幕上打印 \"Hello World\" 来了解基本的编程语言语法。因此,我们传统上会从它开始熟悉我们的库。 -在本文中,我们正在创建一个包含文本 "Hello World!" 的 PDF 文档。在您的环境中安装 **Aspose.PDF for Python via .NET** 后,您可以执行下面的代码示例以查看 Aspose.PDF API 的工作方式。 +在本文中,我们正在创建一个包含文本“Hello World!”的 PDF 文档。 在你的环境中安装 **Aspose.PDF for Python via .NET** 后,你可以执行下面的代码示例,看看 Aspose.PDF API 如何工作。 -下面的代码片段遵循这些步骤: +下面的代码片段遵循以下步骤: -1. 实例化一个 [Document](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象 -1. 向文档对象添加一个 [Page](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) +1. 实例化一个 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 对象 +1. 添加一个 [页面](https://reference.aspose.com/pdf/python-net/aspose.pdf/page/) 到文档对象 1. 创建一个 [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/) 对象 -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 文档 +1. 设置文本颜色 +1. 创建文本构建器 +1. 添加 [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment/) 到页面 +1. [document.save()](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/#methods) 生成的 PDF 文档 -以下代码片段是一个 "Hello World" 程序,用于展示 Aspose.PDF for Python via .NET API 的工作原理。 +以下代码片段是一个 "Hello World" 程序,用于展示 Aspose.PDF for Python via the .NET API 的功能。 ```python +from datetime import timedelta +import aspose.pdf as ap - import aspose.pdf as ap - # 初始化文档对象 +def run_simple(self): + # Initialize document object document = ap.Document() - # 添加页面 + # Add page page = document.pages.add() - # 初始化文本片段对象 - text_fragment = ap.text.TextFragment("Hello,world!") - # 将文本片段添加到新页面 - page.paragraphs.add(text_fragment) - # 保存更新后的 PDF - 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/zh/python-net/overview/_index.md b/zh/python-net/overview/_index.md index 05666ba4dd..043f1f648c 100644 --- a/zh/python-net/overview/_index.md +++ b/zh/python-net/overview/_index.md @@ -4,36 +4,38 @@ linktitle: 概述 type: docs weight: 20 url: /zh/python-net/overview/ -lastmod: "2022-12-20" -description: Aspose.PDF for Python via .NET 的关键特性和支持格式的概述,库的安装和许可手册。 +lastmod: "2026-06-08" +description: Aspose.PDF for Python via .NET 的关键功能和支持格式概述,库的安装和授权手册。 sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Aspose.PDF for Python 的关键功能概述 +Abstract: Aspose.PDF for Python via .NET 是一个全面的 PDF 处理 API,专为开发人员设计,可在不依赖 Microsoft Office 或 Adobe Acrobat 自动化的情况下处理 PDF 文档。该库支持广泛的功能,包括遵循既定的 PDF 标准和规范,能够以 BMP、GIF、JPEG 和 PNG 等多种图像格式读取和导出 PDF,并具备设置作者、创建者等基本文档信息的能力。它还允许配置 PDF 页面属性,如宽度、高度、cropbox 和 bleedbox,以及页面编号、书签层级和页面尺寸等功能。用户可以在 PDF 中操作文本、段落、标题、超链接、图表和附件。此外,Aspose.PDF for Python 提供高效的转换功能,可在 EPUB、Markdown、Text、XPS、PostScript、XML、LaTex 等格式与 PDF 之间相互转换,确保高性能和高质量。 --- -_本页是 Aspose.PDF for Python 功能的概述。_ +_此页面是 Aspose.PDF for Python 功能的概述._ -**Aspose.PDF for Python via .NET**,PDF 处理 API,允许开发人员在无需 Microsoft Office® 或 Adobe Acrobat Automation 的情况下处理 PDF 文档。查看 [Aspose.PDF for Python](https://products.aspose.com/pdf/python-net/) 的着陆页,以获取有关库功能和可能性的更详细描述。 +**Aspose.PDF for Python via .NET**,PDF 处理 API,允许开发人员在无需 Microsoft Office® 或 Adobe Acrobat 自动化的情况下处理 PDF 文档。查看以下着陆页 [Aspose.PDF for Python](https://products.aspose.com/pdf/python-net/) 获取该库功能和可能性的更详细描述。 Aspose.PDF for Python 支持多种功能,例如: - 支持大多数已建立的 PDF 标准和 PDF 规范。 -- 能够以多种图像格式读取和导出 PDF,包括 BMP、GIF、JPEG 和 PNG。 -- 设置基本信息(例如。 - 作者、创建者)的PDF文档。 -- 配置PDF页面属性(例如,宽度、高度、裁剪框、出血框等)。 -- 设置页码、书签级别、页面大小等。 -- 能够处理文本、段落、标题、超链接、图表、附件等。 +- 能够读取和导出 PDF 为多种图像格式,包括 BMP、GIF、JPEG 和 PNG。 +- 设置 PDF 文档的基本信息(例如作者、创建者)。 +- 配置 PDF 页面属性(例如宽度、高度、裁剪框、出血框等)。 +- 设置页码、书签层级、页面尺寸等。 +- 能够处理文本、段落、标题、超链接、图形、附件等。 -此外,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/zh/python-net/supported-file-formats/) - [Aspose.PDF 的关键功能](/pdf/zh/python-net/key-features/) -- [系统要求](/pdf/zh/python-net/system-requirements/) +- [系统需求](/pdf/zh/python-net/system-requirements/) - [安装](/pdf/zh/python-net/installation/) - [许可](/pdf/zh/python-net/licensing/) -- [技术支持](/pdf/zh/python-net/technical-support/) \ No newline at end of file +- [技术支持](/pdf/zh/python-net/technical-support/) diff --git a/zh/python-net/overview/installation/_index.md b/zh/python-net/overview/installation/_index.md index 0e9b014b19..d84426d044 100644 --- a/zh/python-net/overview/installation/_index.md +++ b/zh/python-net/overview/installation/_index.md @@ -4,41 +4,48 @@ linktitle: 安装 type: docs weight: 40 url: /zh/python-net/installation/ -description: 本节展示产品描述和 Aspose.PDF for Python 的安装说明。 -lastmod: "2022-12-21" +description: 查找分步说明,以安装 Aspose.PDF for Python 和 .NET 并开始处理 PDF 文档。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 安装 Aspose.PDF for Python +Abstract: Aspose.PDF for Python via .NET 是一个综合库,旨在将 PDF 处理功能集成到 Python 应用程序中,兼容 32 位和 64 位系统。该库支持广泛的文档处理任务,包括文本和页面操作、表单处理、元数据管理,以及注释、书签、水印和自定义字体的管理。它适用于已安装 Python 3.5 或更高版本的各种操作系统。通过下载试用版可以对该库进行评估,试用版在添加相应代码后可切换为授权状态。试用版保留全部功能,但会带有评估水印,并将集合元素的交互限制为四个。用户可申请 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 for Python** 可以用于开发适用于不同操作系统(如 Windows 和 Linux)的 32 位和 64 位 Python 应用程序,这些操作系统上安装了 Python 3.5 或更高版本。 +**Aspose.PDF for Python** 可用于开发适用于不同操作系统(如 Windows 和 Linux)的 32 位和 64 位 Python 应用程序,只要安装了 Python 3.5 或更高版本。 -# 安装 +## 安装 -## 评估通过 .NET 的 Aspose.PDF for Python +## 评估 Aspose.PDF for Python via .NET -您可以轻松下载用于评估的 Aspose.PDF for Python。评估下载与购买的下载相同。当您添加几行代码来应用许可证时,评估版本就会被授权。 +您可以轻松下载 Aspose.PDF for Python 进行评估。评估下载与购买下载相同。只需添加几行代码来应用许可证,评估版即可转换为已授权版。 -您可以下载 [Aspose.PDF for Python](https://releases.aspose.com/pdf/pythonnet/) 进行评估。评估下载与购买的下载相同。当您添加几行代码来[申请许可证](/pdf/zh/python-net/licensing/)时,评估版本就会被授权。 +您可以下载 [Aspose.PDF for Python](https://releases.aspose.com/pdf/pythonnet/) 用于评估。评估版下载与购买版下载相同。当您添加几行代码时,评估版将获得授权。 [申请许可证](/pdf/zh/python-net/licensing/). -Aspose.PDF 的评估版本(未指定许可证)提供完整的产品功能,但有两个限制:它插入一个评估水印,并且只能查看/编辑任何集合的四个元素。 +Aspose.PDF 的评估版(未指定许可证)提供完整的产品功能,但有两个限制:会插入评估水印,并且任何集合的元素只能查看/编辑四个。 {{% alert color="primary" %}} -如果您想在没有评估版限制的情况下测试 Aspose.PDF for Python,您还可以申请 30 天的临时许可证。请参阅 [如何获取临时许可证?](https://purchase.aspose.com/temporary-license) +如果您想在不受评估版限制的情况下测试 Aspose.PDF for Python,您也可以请求 30 天的临时许可证。请参阅 [如何获取临时许可证?](https://purchase.aspose.com/temporary-license) {{% /alert %}} -## 通过 .NET 为 Python 安装 Aspose.PDF +## 安装 Aspose.PDF for Python via .NET + +您可以轻松地通过链接直接下载 aspose-pdf for Python 并使用它 [pip](https://pypi.org/project/aspose-pdf/). +运行 'pip install aspose-pdf' 以获取该包。如果您已经拥有 Aspose.PDF for Python 并想获取最新版本,请运行 'pip install --upgrade aspose-pdf'。 + + -您可以从直接下载链接 [pip](https://pypi.org/project/aspose-pdf/) 轻松使用 aspose-pdf for Python。运行 'pip install aspose-pdf' 来获取软件包。如果您已经拥有 Aspose.PDF for Python 并想获取最新版本,请运行 'pip install --upgrade aspose-pdf'。 \ No newline at end of file diff --git a/zh/python-net/overview/key-features/_index.md b/zh/python-net/overview/key-features/_index.md index b759e70128..20f87d7003 100644 --- a/zh/python-net/overview/key-features/_index.md +++ b/zh/python-net/overview/key-features/_index.md @@ -1,28 +1,37 @@ --- -title: Aspose.PDF for Python 的关键功能 -linktitle: 关键功能 +title: Aspose.PDF for Python 的关键特性 +linktitle: 关键特性 type: docs weight: 20 url: /zh/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: "2026-06-08" sitemap: - changefreq: "weekly" + 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 规范。 -- 能够以多种图像格式(包括 BMP、GIF、JPEG 和 PNG)读取和导出 PDF。 +- 支持大多数已建立的 PDF 标准和 PDF 规范。 +- 能够读取和导出 PDF 为多种图像格式,包括 BMP、GIF、JPEG 和 PNG。 - 设置 PDF 文档的基本信息(例如作者、创建者)。 - 配置 PDF 页面属性(例如宽度、高度、裁剪框、出血框等)。 -- 设置页码、书签级别、页面大小等。 +- 设置页码、书签层级、页面尺寸等。 - 能够处理文本、段落、标题、超链接、图形、附件等。 +## 支持的 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 文档转换为最流行的格式,反之亦然。 +Aspose.PDF for Python via .NET 库可帮助您成功、快速、轻松地将 PDF 文档转换为最流行的格式,亦可实现相反的转换。 - 将 PDF 转换为 Word、Excel 和 PowerPoint。 - 将 PDF 转换为图像格式。 @@ -36,18 +45,27 @@ Aspose.PDF for Python 支持 PDF 版本 1.2、1.3、1.4、1.5、1.6、1.7 和 2. ## 文本 -- 从页面中提取文本。 -- 从页面中搜索文本。 +- 从页面提取文本。 +- 在页面中搜索文本。 - 替换文本。 - 在 PDF 文件中添加文本。 +## 字体 + +- 14 种核心字体。 +- Type 1 字体。 +- TrueType 字体。 +- Type 3 字体。 +- CJK 字体。 +- Unicode 支持。 + ## 图像 - 在 PDF 文件中添加图像。 - 删除图像。 - 替换图像。 - 提取图像。 -- PDF 转图像格式转换。 +- PDF 转换为图像格式。 ## 附件 @@ -58,10 +76,10 @@ Aspose.PDF for Python 支持 PDF 版本 1.2、1.3、1.4、1.5、1.6、1.7 和 2. - 插入 PDF 页面。 - 删除 PDF 页面。 -- 将 PDF 拆分为单个页面。 -- 从一个 PDF 文档移动一组页面到另一个文档 +- 将 PDF 拆分为单独页面。 +- 将一批页面从一个 PDF 文档移动到另一个 PDF 文档 - 在当前 PDF 文档中将页面移动到新位置 -- 更改 PDF 页面大小 +- 更改 PDF 页面尺寸 - 更改页面方向 - 获取页面属性 - 获取页面数量 @@ -71,26 +89,25 @@ Aspose.PDF for Python 支持 PDF 版本 1.2、1.3、1.4、1.5、1.6、1.7 和 2. ## 文档 - 创建 PDF 文件 -- 从流中打开现有 PDF 文档 +- 从流打开现有 PDF 文档 - 打开现有 PDF 文档 - - 设置打印对话框预设属性 -- 添加目录到现有PDF -- 添加目录到现有PDF -- 自定义页码时添加目录 -- 设置PDF到期日期 -- 扁平化可填写的PDF -- 优化PDF文档以适应网络 -- 减小PDF大小 +- 向现有 PDF 添加 TOC +- 向现有 PDF 添加 TOC +- 在添加目录时自定义页码 +- 设置 PDF 到期日期 +- 扁平化可填写的 PDF +- 为网络优化 PDF 文档 +- 压缩 PDF 大小 - 缩小或压缩所有图像 -- 移除未使用的对象 +- 删除未使用的对象 - 链接重复的流 -- 移除未使用的流 +- 删除未使用的流 - 取消嵌入字体 - 获取文档查看器属性。 - 设置文档查看器属性。 -- 验证(PDF/A-1a,PDF/A-1b)。 -- 移除表单字段 +- 验证 (PDF/A-1a, PDF/A-1b)。 +- 删除表单字段 - 确定并设置文档的元数据 ## 书签 @@ -101,13 +118,13 @@ Aspose.PDF for Python 支持 PDF 版本 1.2、1.3、1.4、1.5、1.6、1.7 和 2. - 获取书签。 - 获取子书签。 - 修改书签。 -- 查看文档时展开书签。 +- 在查看文档时展开书签。 ## 注释 -- 添加注释。 -- 获取注释。 -- 删除注释。 +- 添加批注。 +- 获取批注。 +- 删除批注。 ## 表单 @@ -116,1041 +133,16 @@ Aspose.PDF for Python 支持 PDF 版本 1.2、1.3、1.4、1.5、1.6、1.7 和 2. - 修改字段。 - 填写字段。 - 获取字段值。 +- 支持 XFA(基于 XML 的表单)和 AcroForms(标准表单)。 ## 印章和水印 - 添加文字印章。 -- 添加图片印章。 -- 添加PDF页面印章。 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +- 添加图像印章。 +- 添加 PDF 页面印章。 +## 打开加密的 PDF 文档 -打开加密的PDF文档 -- 加密PDF。 -- 解密PDF。 -- 修改密码。 \ No newline at end of file +- 加密 PDF。 +- 解密 PDF。 +- 修改密码。 diff --git a/zh/python-net/overview/licensing/_index.md b/zh/python-net/overview/licensing/_index.md index bb45ebb37e..1555af3ba0 100644 --- a/zh/python-net/overview/licensing/_index.md +++ b/zh/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: /zh/python-net/licensing/ -description: Aspose. PDF for Python 邀请客户获取 Classic 许可证。以及使用有限许可证来更好地探索产品。 -lastmod: "2022-12-21" +description: Aspose.PDF for Python 鼓励其客户获取 Classic 许可证。同时使用受限许可证以更好地探索产品。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Aspose.PDF for Python 的许可 +Abstract: 本文讨论了 Aspose.PDF for Python 的限制和许可选项。它强调,评估版允许完整功能测试,但会在生成的 PDF 中添加水印,显示 “Evaluation Only” 并附带版权信息。希望在无这些限制的情况下进行测试的用户,可使用为期 30 天的临时许可证。本文进一步说明了如何通过从文件或流加载来实现 Classic 许可证,建议将许可证文件放置在与 Aspose.PDF.dll 相同的目录下,并使用 `Aspose.Pdf.License` 类设置许可证。提供了代码片段以演示许可过程。 --- -## 评估版本的限制 +## 评估版的限制 -我们希望客户在购买前彻底测试我们的组件,因此评估版本允许您像正常使用一样使用它。 +我们希望客户在购买前彻底测试我们的组件,因此评估版允许您像平常一样使用它。 -- **带有评估水印的 PDF。** Aspose.PDF for Python 的评估版本提供完整的产品功能,但生成的 PDF 文档中的所有页面都在顶部带有“仅限评估。由 Aspose.PDF 创建。版权 2002-2020 Aspose Pty Ltd”的水印。 +- **PDF 创建了评估水印。** Aspose.PDF for Python 的评估版本提供完整的产品功能,但生成的 PDF 文档中的所有页面都会被加上 \u0022仅供评估。使用 Aspose.PDF 创建。版权所有 2002-2020 Aspose Pty Ltd\u0022 在顶部。 ->如果您希望测试 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 for Python 组件与 Aspose.PDF for Python 一起使用,请为许可证指定命名空间,例如 [Aspose.Pdf.License 类]()。 +如果您在使用 Aspose.PDF for Python 的同时使用其他 Aspose 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/zh/python-net/overview/supported-file-formats/_index.md b/zh/python-net/overview/supported-file-formats/_index.md index cab6e898e8..c09b24ccf7 100644 --- a/zh/python-net/overview/supported-file-formats/_index.md +++ b/zh/python-net/overview/supported-file-formats/_index.md @@ -4,43 +4,48 @@ linktitle: 支持的文件格式 type: docs weight: 10 url: /zh/python-net/supported-file-formats/ -description: 本页显示了Aspose.PDF for Python via .NET可以加载和保存的文件格式。 -lastmod: "2022-12-22" +description: 此页面展示了 Aspose.PDF for Python via .NET 能够加载和保存的文件格式。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + 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/)|用于二维矢量图形的计算机图形元文件|{{< emoticons/tick >}}| | | +|[PDF](https://docs.fileformat.com/pdf/)|可移植文档格式|{{< emoticons/tick >}}|{{< emoticons/tick >}} | | +|[计算机图形元文件](https://docs.fileformat.com/page-description-language/cgm/)|用于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 >}}| | +|[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 >}}| | |[MHT](https://docs.fileformat.com/web/mhtml/)|MHTML 文档|{{< emoticons/tick >}}| | | |[PCL](https://docs.fileformat.com/page-description-language/pcl/)|打印机控制语言文件|{{< 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 >}}| | +|[可缩放矢量图形](https://docs.fileformat.com/page-description-language/svg/)|可缩放矢量图形 (基于 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电子表格保存文档| |{{< emoticons/tick >}}| | -|[XLSX](https://docs.fileformat.com/spreadsheet/xlsx/)|以Microsoft Excel 2007格式保存文档| |{{< emoticons/tick >}}| | -|[PPTX](https://docs.fileformat.com/presentation/pptx/)|以Microsoft PowerPoint演示文稿格式保存文档| |{{< 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 >}}| | -|[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 >}}| | +|[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 演示文稿格式| |{{< 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 >}}| | +|[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 标准格式| |{{< 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 +|[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/zh/python-net/overview/system-requirements/_index.md b/zh/python-net/overview/system-requirements/_index.md index 5bad368e69..d3f1f89199 100644 --- a/zh/python-net/overview/system-requirements/_index.md +++ b/zh/python-net/overview/system-requirements/_index.md @@ -1,19 +1,22 @@ --- -title: 系统要求 -linktitle: 系统要求 +title: 系统需求 +linktitle: 系统需求 type: docs weight: 30 url: /zh/python-net/system-requirements/ -description: 本节列出了开发人员需要成功使用 Aspose.PDF for Python 的支持操作系统。 -lastmod: "2022-12-22" +description: 本节列出了开发人员成功使用 Aspose.PDF for Python 所需的受支持操作系统。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Aspose.PDF for Python via .NET 的受支持操作系统 +Abstract: Aspose.PDF for Python via .NET 是一个 PDF 处理 API,旨在帮助开发人员在无需 Microsoft Office 或 Adobe Acrobat Automation 的情况下管理 PDF 文档。它支持在包括 Windows 和 Linux 在内的各种操作系统上开发 32 位和 64 位的 Python 应用程序,前提是已安装 Python 3.5 或更高版本。该 API 与多个 Windows 版本兼容,范围从 Windows XP 到 Windows 11,并且兼容主要的 Linux 发行版,如 Ubuntu、OpenSUSE 和 CentOS。对于 Linux 系统,具体要求包括 GCC-6 运行时库、.NET Core Runtime 的依赖项(无需 runtime 本身)以及 Python 3.5-3.7 的 pymalloc 构建。此外,还需要共享的 libpython 库,可能需要进行配置调整以正确识别库路径。 --- ## 概述 -Aspose.PDF for Python via .NET 是一个 PDF 处理 API,允许开发人员在不需要 Microsoft Office® 或 Adobe Acrobat Automation 的情况下处理 PDF 文档。Aspose.PDF for Python 可用于开发适用于不同操作系统(如安装了 Python 3.5 或更高版本的 Windows 和 Linux)的 32 位和 64 位 Python 应用程序。 +Aspose.PDF for Python via .NET,PDF 处理 API,允许开发者在无需 Microsoft Office® 或 Adobe Acrobat 自动化的情况下处理 PDF 文档。Aspose.PDF for Python 可用于在不同操作系统(如 Windows 和 Linux)上开发 32 位和 64 位的 Python 应用程序,只要安装了 Python 3.5 或更高版本。 ## 支持的操作系统 @@ -22,13 +25,13 @@ Aspose.PDF for Python via .NET 是一个 PDF 处理 API,允许开发人员在 - 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 -- Windows 8, 8.1 +- Windows 8,8.1 - Windows 10 - Windows 11 @@ -43,9 +46,10 @@ Aspose.PDF for Python via .NET 是一个 PDF 处理 API,允许开发人员在 - GCC-6 运行时库(或更高版本)。 -- .NET Core 运行时的依赖项。不需要安装 .NET Core 运行时本身。 +- .NET Core Runtime 的依赖项。不需要安装 .NET Core Runtime 本身。 + +- 对于 Python 3.5-3.7:需要使用 pymalloc 构建的 Python。默认启用 --with-pymalloc Python 构建选项。通常,使用 pymalloc 构建的 Python 在文件名中会带有 m 后缀。 + +- libpython 共享 Python 库。默认情况下,--enable-shared Python 构建选项是关闭的,一些 Python 发行版不包含 libpython 共享库。对于某些 Linux 平台,可以使用软件包管理器安装 libpython 共享库,例如:`sudo apt-get install libpython3.7`。常见的问题是 libpython 库被安装在与系统共享库标准位置不同的目录下。可以通过在编译 Python 时使用 Python 构建选项设置替代库路径来解决此问题,或者通过在系统共享库标准位置创建指向 libpython 库文件的符号链接来解决。通常,libpython 共享库文件名为 Python 3.5-3.7 的 `libpythonX.Ym.so.1.0`,或 Python 3.8 及以后版本的 `libpythonX.Y.so.1.0`(例如:`libpython3.7m.so.1.0`、`libpython3.9.so.1.0`)。 -- 对于 Python 3.5-3.7:需要 Python 的 pymalloc 构建。--with-pymalloc Python 构建选项是默认启用的。通常,Python 的 pymalloc 构建在文件名中带有 m 后缀标记。 -- libpython 共享 Python 库。 - --enable-shared Python 构建选项默认是禁用的,一些 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/zh/python-net/overview/technical-support/_index.md b/zh/python-net/overview/technical-support/_index.md index 403671b106..90557b31cb 100644 --- a/zh/python-net/overview/technical-support/_index.md +++ b/zh/python-net/overview/technical-support/_index.md @@ -4,27 +4,32 @@ linktitle: 技术支持 type: docs weight: 60 url: /zh/python-net/technical-support/ -description: 本页面提供使用 Aspose.PDF for Python 快速高效解决任务的建议。 -lastmod: "2021-06-05" +description: 本页提供使用 Aspose.PDF for Python 快速且高质量完成任务的建议。 +lastmod: "2026-06-08" sitemap: - changefreq: "weekly" + changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: Aspose.PDF for Python 技术支持 +Abstract: Aspose.PDF 通过其多个渠道提供免费技术支持,主要渠道是 Aspose.Forums,特别是 Aspose.PDF 论坛版块,用户可以在此发布查询并获得及时回复。需要注意的是,Aspose 不提供电话技术支持,电话仅限于销售和采购咨询。由于时区差异,响应时间可能会有所不同。为确保高效解决问题,建议用户首先通过检查 [Aspose.PDF for Python Downloads](https://pypi.org/project/aspose-pdf/) 来确认自己使用的是最新版 Aspose.PDF。此外,用户还应查阅已有的论坛讨论、文档和 API 参考,以确定问题是否已经得到解决。提问时,建议附上原始文档和任何有问题的代码片段,可将其压缩为 zip 以便上传。所有上传的文件仅对用户和 Aspose 开发者可见,确保隐私和安全。 --- -Aspose.PDF 允许您对其所有产品使用免费技术支持。如果您对 Aspose.PDF 有疑问,请查看以下文章: +Aspose.PDF 让您可以免费获得其所有产品的技术支持。如果您对 Aspose.PDF 有疑问,请查看下一篇文章: -- 最受欢迎的支持来源是 [Aspose.Forums](https://forum.aspose.com/)。在 [Aspose.PDF 论坛](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 for Python 下载](https://pypi.org/project/aspose-pdf/) 以了解最新版本。 +- 首先,检查您在报告问题之前是否使用了最新的 Aspose.PDF 版本,参见 [Aspose.PDF for Python Downloads](https://pypi.org/project/aspose-pdf/) 以了解最新版本。 -- 您的问题可能已经被讨论过,并且有解决方案,为此,请在报告问题之前研究论坛和文档,检查 API 参考。 +- 也许您问题的解决方案已经在论坛或文档中讨论并有了解决办法,为此,请在报告问题前研究论坛和文档,检查 API Reference。 + +- 在提出问题时,请包括原始文档以及可能导致问题的代码片段。如果有多个文件,您可以将这些文件压缩成一个文档。 + +- 别担心,只有您和 Aspose 的开发者可以访问这些粘性文件。 -- 当您提出问题时,请附上原始文档以及可能导致问题的代码片段。如果有多个文件,您可以将这些文件压缩成一个文档。 -- 不用担心,只有您和 Aspose 的开发人员可以访问这些粘性文件。 \ No newline at end of file diff --git a/zh/python-net/parsing/_index.md b/zh/python-net/parsing/_index.md index a7223f7024..464b701aed 100644 --- a/zh/python-net/parsing/_index.md +++ b/zh/python-net/parsing/_index.md @@ -4,11 +4,22 @@ linktitle: 解析 PDF 文档 type: docs weight: 80 url: /zh/python-net/parsing/ -description: 您想解析 PDF 文档吗?通过 Aspose.PDF for Python via .NET 发现各种 PDF 数据提取方法。 -lastmod: "2021-06-05" +description: 您想解析 PDF 文档吗?了解使用 Aspose.PDF for Python via .NET 的各种 PDF 数据提取方法。 +lastmod: "2026-06-08" sitemap: changefreq: "monthly" priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python 解析 PDF 文件 +Abstract: 文章《Parse PDF》深入探讨了从 PDF 文件中提取不同类型信息的各种方法。它强调了若干关键操作并提供指南。 --- -**解析 PDF** 文档是指从 PDF 文件中提取各种信息的术语。本节介绍如何: \ No newline at end of file +**Parse PDF** 文档是指从 PDF 文件中提取各种信息的相关术语。本节涵盖如何: + +- [从 PDF 中提取文本](/pdf/zh/python-net/extract-text-from-pdf/). 文本解析或提取是最常见的操作,适用于已有的 PDF。您将学习如何从整个文档、特定页面或页面中的特定区域进行文本解析。 +- [从 PDF 中提取图像](/pdf/zh/python-net/extract-images-from-the-pdf-file/). Image Extraction 对图像执行的操作与上述对文本的操作相同。 +- [提取 PDF 中的字体](/pdf/zh/python-net/extract-fonts-from-pdf/). Font Extraction 是在 PDF 中对字体的特定操作。 +- [从表单提取数据](/pdf/zh/python-net/extract-data-from-acroform/). 如果您拥有一堆包含表单的 PDF 文档,可能需要从这些表单中获取数据。本文将帮助您了解如何使用 Aspose.PDF for Python via .NET 提取 AcroForms 数据。 +- [从表格提取数据](/pdf/zh/python-net/extract-data-from-table-in-pdf/). 从 PDF 文档中的表格获取数据。 +- [从 PDF 提取矢量数据](/pdf/zh/python-net/extract-vector-data-from-pdf/). 您可以获取向量数据(路径、多边形、折线),例如位置、颜色、线宽等。 + diff --git a/zh/python-net/parsing/extract-data-from-acroform/_index.md b/zh/python-net/parsing/extract-data-from-acroform/_index.md new file mode 100644 index 0000000000..7258e3dc57 --- /dev/null +++ b/zh/python-net/parsing/extract-data-from-acroform/_index.md @@ -0,0 +1,197 @@ +--- +title: 使用 Python 从 AcroForm 提取数据 +linktitle: 从 AcroForm 提取数据 +type: docs +weight: 50 +url: /zh/python-net/extract-data-from-acroform/ +description: Aspose.PDF 让从 PDF 文件中提取表单字段数据变得简单。了解如何从 AcroForms 提取数据并将其保存为 JSON、XML 或 FDF 格式。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何通过 Python 提取 AcroForm 数据 +Abstract: 本文提供了使用 Aspose.PDF for Python 管理 PDF 文档中表单字段的综合指南。它详细说明了从 PDF 中提取、操作和导出表单数据的各种方法。文章首先演示如何提取表单字段值并将其存入字典,随后以 JSON 格式输出数据。进一步展示了将表单数据直接导出为 JSON 文件,以增强数据序列化能力。此外,本文还涵盖了将表单数据导出为 XML、FDF(Forms Data Format)和 XFDF 等其他格式,这些格式有助于数据交换和结构化数据存储。每个章节都包含 Python 代码片段,以帮助理解和实现。总体而言,本文是希望在 Python 应用中集成 PDF 表单处理的开发者的实用资源。 +--- + +## 从 PDF 文档中提取表单字段 + +[Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form) 来自 `aspose.pdf.facades` namespace 提供了一种直接的方法来读取 AcroForm 字段数据,而无需打开完整的文档对象模型。遍历 `form.field_names` 要获取表单中出现的每个字段名称,然后调用 `form.get_field(name)` 检索其当前值。 + +1. 构建一个 `Form` 通过传递输入文件路径来创建对象。 +1. 遍历 `form.field_names` 枚举所有字段名称。 +1. 调用 `form.get_field(name)` 对每个名称,将结果存储在字典中。 + +```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) +``` + +## 通过标题获取表单字段值 + +当您知道 PDF 表单中定义的确切字段名称(title)时,您可以直接使用 `form.get_field(name)` 无需遍历整个字段集合。当仅需要特定字段时,这是最快的方法。 + +1. 构建一个 [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form) 包含输入文件路径的对象。 +1. 调用 `form.get_field("FieldName")` 使用 PDF 中出现的确切字段标题。 +1. 在您的应用程序中根据需要使用返回的字符串值。 + +```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) +``` + +## 从 PDF 文档中提取表单字段为 JSON + +有两种方法可以将 AcroForm 数据导出为 JSON。第一种使用内置的 `export_json` 方法 在 [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form), 将所有字段数据直接序列化到文件流中,一次调用完成。 + +1. 构建一个 `Form` 包含输入文件路径的对象。 +1. 使用二进制流打开输出文件 `FileIO`. +1. 调用 `form.export_json(stream, True)` 编写 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) +``` + +第二种方法从...构建一个 Python 字典 `field_names` 和 `get_field`,然后使用它进行序列化 `json.dumps`. 在需要在写入之前转换或过滤数据时使用它。 + +1. 遍历 `form.field_names` 并用字段值填充字典。 +1. 使用以下方式序列化字典 `json.dumps(form_data, indent=4)`. +1. 将结果 JSON 字符串写入输出文件。 + +```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) +``` + +## 从 PDF 文件提取数据到 XML + +XML 导出对于将 PDF 表单数据与使用结构化 XML 提要或模式的系统集成非常有用。该 [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form) 类提供 `export_xml` 一次完成转换。 + +1. 创建一个 `Form` 实例并将 PDF 与之绑定 `form.bind_pdf(path)`. +1. 以二进制流打开输出文件。 +1. 调用 `form.export_xml(stream)` 将所有字段数据写入 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) +``` + +## 从PDF文件导出数据到FDF + +FDF(表单数据格式)是 AcroForm 数据的标准交换格式,广泛得到 PDF 查看器和处理工具的支持。使用 `export_fdf` 在 [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form) 用于生成可独立的 FDF 文件的类,该文件可以导入回原始 PDF 或其他兼容的表单。 + +1. 创建一个 `Form` 实例并将源 PDF 绑定到 `form.bind_pdf(path)`. +1. 以二进制流打开输出文件。 +1. 调用 `form.export_fdf(stream)` 写入 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) +``` + +## 从 PDF 文件导出数据到 XFDF + +XFDF(XML Forms Data Format)是基于 XML 的 FDF 的后继者,更适合在 Web 服务和现代数据管道中使用。和 FDF 一样,XFDF 文件可以导入回兼容的 PDF 表单。使用 `export_xfdf` 在 [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form) 生成输出的类。 + +1. 创建一个 `Form` 实例并将源 PDF 绑定到 `form.bind_pdf(path)`. +1. 以二进制流打开输出文件。 +1. 调用 `form.export_xfdf(stream)` 编写 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/zh/python-net/parsing/extract-data-from-tables/_index.md b/zh/python-net/parsing/extract-data-from-tables/_index.md new file mode 100644 index 0000000000..e75747b438 --- /dev/null +++ b/zh/python-net/parsing/extract-data-from-tables/_index.md @@ -0,0 +1,139 @@ +--- +title: 使用 Python 从 PDF 中的表格提取数据 +linktitle: 从表格提取数据 +type: docs +weight: 40 +url: /zh/python-net/extract-data-from-table-in-pdf/ +description: 了解如何使用 Aspose.PDF for Python 从 PDF 文件中提取表格数据,并导出结果以进行进一步处理。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 从 PDF 中提取表格数据 +Abstract: 本文介绍了如何使用 Aspose.PDF for Python 从 PDF 文档中提取和处理表格数据。它展示了如何使用 TableAbsorber 扫描每一页,读取检测到的表格中的行和单元格,将提取限制在特定的注释区域,并将 PDF 内容导出为 CSV 格式,以便在电子表格工具和后续处理过程中使用。 +--- + +## 以编程方式从 PDF 提取表格 + +使用 [TableAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/) 检测每页的表格 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). 在访问页面后,遍历 `table_list`, 然后遍历每一行和每个单元格,以可读的文本格式重建表格内容。 + +1. 将 PDF 打开为 `Document`. +1. 遍历页面 `document.pages`. +1. 创建一个 `TableAbsorber` 对每页调用 `visit(page)`. +1. 遍历检测到的表格、行和单元格。 +1. 读取每个单元格中的文本片段并组装提取的行输出。 + +```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)) +``` + +## 在PDF页面的特定区域提取表格 + +如果您只需要提取位于标记区域内的表格,请结合 [TableAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/tableabsorber/) 与 [SquareAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/squareannotation/). 在本例中,注释矩形用作边界,仅处理完全位于该区域内的表格。 + +1. 将 PDF 打开为 `Document`. +1. 选择目标页面。 +1. 查找标记感兴趣区域的方形注释。 +1. 创建一个 `TableAbsorber` 并访问该页面。 +1. 将每个检测到的表格矩形与注释矩形进行比较。 +1. 仅处理完全位于标记区域内的表格。 + +```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)) +``` + +## 将 PDF 表格数据导出为 CSV + +当您需要以电子表格友好的格式提取数据时,使用以下方式保存 PDF [Excel保存选项](https://reference.aspose.com/pdf/python-net/aspose.pdf/excelsaveoptions/) 并将输出格式设置为 CSV。生成的文件可以在 Excel、Google Sheets 中打开,或导入到分析工作流中。 + +1. 打开源 PDF 作为 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 创建一个 `ExcelSaveOptions` 实例。 +1. 设置 `excel_save.format` 到 `ExcelSaveOptions.ExcelFormat.CSV`. +1. 将文档保存到目标 CSV 路径。 + +```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/zh/python-net/parsing/extract-fonts-from-pdf/_index.md b/zh/python-net/parsing/extract-fonts-from-pdf/_index.md new file mode 100644 index 0000000000..7b17c4a5da --- /dev/null +++ b/zh/python-net/parsing/extract-fonts-from-pdf/_index.md @@ -0,0 +1,37 @@ +--- +title: 通过 Python 提取 PDF 中的字体 +linktitle: 提取 PDF 中的字体 +type: docs +weight: 30 +url: /zh/python-net/extract-fonts-from-pdf/ +description: 使用 Aspose.PDF for Python 库从您的 PDF 文档中提取所有嵌入的字体。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何使用 Python 从 PDF 中提取字体 +Abstract: 本文说明了如何使用 Aspose.PDF for Python 检查 PDF 文档中使用的字体。它展示了如何使用 Document 类打开 PDF,调用 `font_utilities.get_all_fonts()` 来检索可用的字体对象,并遍历结果以读取字体名称,用于分析、审计或文档处理工作流。 +--- + +使用 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 打开 PDF 并调用 `font_utilities.get_all_fonts()` 检索所有可用的 [Font](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/font/) 文档引用的对象。这在审计嵌入字体、在转换前检查字体可用性或分析文档资源时非常有用。 + +1. 打开源 PDF 作为 `Document`. +1. 调用 `document.font_utilities.get_all_fonts()` 获取字体集合。 +1. 遍历返回的 `Font` 对象。 +1. 读取并打印每个 `font.font_name` 值。 + +```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/zh/python-net/parsing/extract-images-from-pdf/_index.md b/zh/python-net/parsing/extract-images-from-pdf/_index.md new file mode 100644 index 0000000000..15b4dea33d --- /dev/null +++ b/zh/python-net/parsing/extract-images-from-pdf/_index.md @@ -0,0 +1,37 @@ +--- +title: 使用 Python 提取 PDF 中的图像 +linktitle: 从 PDF 中提取图像 +type: docs +weight: 20 +url: /zh/python-net/extract-images-from-the-pdf-file/ +description: 了解如何使用 Aspose.PDF for Python 提取 PDF 文件中嵌入的图像。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 如何通过 Python 提取 PDF 中的图像 +Abstract: 本文阐述了如何使用 Aspose.PDF for Python 从 PDF 文档中提取嵌入的图像。内容包括使用 Document 类打开源 PDF、从页面资源集合中访问图像,以及将提取的 XImage 保存到外部文件,以便重新使用、检查或后续处理。 +--- + +使用 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/) 打开 PDF,然后访问页面资源以检索一个 [XImage](https://reference.aspose.com/pdf/python-net/aspose.pdf/ximage/) 对象并将其另存为单独的文件。此方法在需要重复使用图像、检查提取的资源或从 PDF 内容构建图像处理工作流时非常有用。 + +1. 将 PDF 打开为 `Document`. +1. 从目标页面访问图像资源。 +1. 检索所需的 `XImage` 来自页面图像集合。 +1. 将提取的图像保存到输出文件。 + +```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/zh/python-net/parsing/extract-text-from-pdf/_index.md b/zh/python-net/parsing/extract-text-from-pdf/_index.md new file mode 100644 index 0000000000..3992f64189 --- /dev/null +++ b/zh/python-net/parsing/extract-text-from-pdf/_index.md @@ -0,0 +1,19 @@ +--- +title: 使用 Python 从 PDF 中提取文本 +linktitle: 从 PDF 中提取文本 +type: docs +weight: 10 +url: /zh/python-net/extract-text-from-pdf/ +description: 本节包含使用 Aspose.PDF 在 Python 中对 PDF 文档进行文本提取的文章。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +## 本节的文章 + +- [基本文本提取](/pdf/zh/python-net/basic-text-extraction/) +- [基于区域的提取](/pdf/zh/python-net/region-based-extraction/) +- [多列 PDF 的文本提取](/pdf/zh/python-net/text-extraction-from-multi‑column-pdf/) +- [批注和特殊文本](/pdf/zh/python-net/annotations-and-special-text/) \ No newline at end of file diff --git a/zh/python-net/parsing/extract-text-from-pdf/annotations-and-special-text/_index.md b/zh/python-net/parsing/extract-text-from-pdf/annotations-and-special-text/_index.md new file mode 100644 index 0000000000..d978e887c7 --- /dev/null +++ b/zh/python-net/parsing/extract-text-from-pdf/annotations-and-special-text/_index.md @@ -0,0 +1,161 @@ +--- +title: 使用 Python 的批注和特殊文本 +linktitle: 批注和特殊文本 +type: docs +weight: 40 +url: /zh/python-net/annotation-and-special-text/ +description: 了解如何使用 Aspose.PDF for Python 从 PDF 文档中的印章批注、突出显示的文本以及上标/下标内容中提取文本。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +## 从印章批注中提取文本 + +使用 [TextAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textabsorber) 提取嵌入的文本 [StampAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/stampannotation) 外观流。当印章内容以表单 XObject 的形式渲染而不是以纯文本形式存储时,这非常有用。 + +1. 打开 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document). +1. 访问目标注释 `page.annotations`. +1. 验证它是一个 `StampAnnotation`,然后检索其正常外观 XForm。 +1. 将 XForm 传递给 `TextAbsorber.visit()` 提取嵌入的文本。 + +```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() +``` + +## 提取突出显示的文本 + +遍历页面的注释并使用 [HighlightAnnotation.get_marked_text()](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/highlightannotation) 读取每个突出显示所覆盖的文本跨度。页面注释集合是从 1 开始的。 + +1. 打开 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document) 并选择目标页面。 +1. 遍历 `page.annotations`. +1. 使用 `is_assignable` 用于筛选 [HighlightAnnotation](https://reference.aspose.com/pdf/python-net/aspose.pdf.annotations/highlightannotation) 实例。 +1. 将注释强制转换后调用 `get_marked_text()` 检索突出显示的内容。 + +```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()) +``` + +## 提取上标和下标文本 + +上标和下标在公式、数学表达式以及化学化合物名称中经常出现。Aspose.PDF for Python via .NET 支持提取这些内容。 [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber), 它检测字符级别的定位元数据。 + +1. 打开 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document). +1. 创建一个 `TextFragmentAbsorber` 实例。 +1. 调用 `document.pages[page_number].accept(absorber)` 扫描目标页面。 +1. 从中检索完整提取的文本 `absorber.text`. +1. 将结果写入文件并关闭文档。 + +```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() +``` + +## 遍历文本碎片以检测上标/下标 + +对于每个片段的检查,遍历 `absorber.text_fragments` 并阅读 `text_state.superscript` 和 `text_state.subscript` 每个的布尔标志 [TextFragment](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragment). + +1. 打开 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document) 并创建一个 [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber). +1. 接受目标页上的吸收器以进行填充 `absorber.text_fragments`. +1. 对于每个片段,读取 `fragment.text`, `fragment.text_state.superscript`,和 `fragment.text_state.subscript`. +1. 将结果写入输出文件并关闭文档。 + +```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/zh/python-net/parsing/extract-text-from-pdf/basic-text-extraction/_index.md b/zh/python-net/parsing/extract-text-from-pdf/basic-text-extraction/_index.md new file mode 100644 index 0000000000..ccb5b41acb --- /dev/null +++ b/zh/python-net/parsing/extract-text-from-pdf/basic-text-extraction/_index.md @@ -0,0 +1,78 @@ +--- +title: 使用 Python 的基本文本提取 +linktitle: 基本文本提取 +type: docs +weight: 10 +url: /zh/python-net/basic-text-extraction/ +description: 了解如何使用 Aspose.PDF for Python 提取 PDF 文档的文本 — 一次性从所有页面提取或从特定页面提取。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +## 提取 PDF 文档所有页面的文本 + +使用 [TextAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textabsorber) 捕获 PDF 文档每一页的全部文本并将其写入文本文件。此方法非常适合将 PDF 转换为可搜索的文本、进行内容分析,或为索引和后续处理准备文本。 + +1. 使用以下方法打开 PDF 文档 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document). +1. 创建一个 `TextAbsorber` 实例。 +1. 调用 `document.pages.accept(text_absorber)` 扫描所有页面。 +1. 检索提取的文本来自 `text_absorber.text`. +1. 将结果写入输出文本文件。 + +```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) +``` + +## 从特定页面提取文本 + +应用 [TextAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textabsorber) 对单个页面进行操作,以隔离并保存多页文档中该部分的文本。这在您只需要单页内容时非常有用——例如,发票、报告章节或表单摘要。 + +1. 使用以下方法打开 PDF 文档 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document). +1. 创建一个 `TextAbsorber` 实例。 +1. 调用 `accept` 在目标页面上: `document.pages[page_number].accept(text_absorber)`. +1. 检索提取的文本并将其写入文件。 + +```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/zh/python-net/parsing/extract-text-from-pdf/region-based-extraction/_index.md b/zh/python-net/parsing/extract-text-from-pdf/region-based-extraction/_index.md new file mode 100644 index 0000000000..c7ada73096 --- /dev/null +++ b/zh/python-net/parsing/extract-text-from-pdf/region-based-extraction/_index.md @@ -0,0 +1,140 @@ +--- +title: 使用 Python 的基于区域的提取 +linktitle: 基于区域的提取 +type: docs +weight: 20 +url: /zh/python-net/region-based-extraction/ +description: 了解如何使用 Aspose.PDF for Python 从 PDF 文档中的特定页面区域或段落结构提取文本。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +## 从页面的特定区域提取文本 + +使用 [TextAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textabsorber/) 与 a [矩形](https://reference.aspose.com/pdf/python-net/aspose.pdf/rectangle/) 将提取限制在页面的特定区域。此方法对于从页眉、页脚、表格单元格、表单字段、发票或其他已预先知晓文本位置的固定布局区域进行基于区块的提取非常有用。 + +1. 打开源 PDF 作为 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 创建一个 `TextAbsorber` 实例。 +1. 配置 `text_search_options` 将提取限制在矩形内。 +1. 在目标页面接受吸收器。 +1. 将提取的文本写入输出文件。 + +```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() +``` + +## 通过遍历它们来提取段落 + +使用 [ParagraphAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/paragraphabsorber/) 当您需要段落感知的提取而不是普通的页面文本时。不同于 [TextAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textabsorber/) 或 [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber/), 此 API 按页面、章节和段落组织输出,这对于文本分析、结构化导出以及布局敏感的处理非常有用。 + +1. 打开源 PDF 作为 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 创建一个 `ParagraphAbsorber` 实例。 +1. 调用 `absorber.visit(document)` 分析所有页面。 +1. 遍历 `page_markups`,然后遍历每个章节和段落。 +1. 从每个段落读取文本片段,并将结果写入文件。 + +```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() +``` + +## 提取段落并呈现其边界多边形 + +您也可以使用 [ParagraphAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/paragraphabsorber/) 以检查段落几何形状。除了提取文本之外,此方法还记录每个章节矩形和段落多边形,这对于布局映射、文档分析、可访问性工具或基于区域的后处理非常有用。 + +1. 打开源 PDF 作为 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 创建一个 `ParagraphAbsorber` 实例。 +1. 访问目标页面。 +1. 读取页面标记来自 `absorber.page_markups`. +1. 遍历章节和段落以捕获几何信息和文本。 +1. 将矩形、多边形和文本数据写入输出文件。 + +```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/zh/python-net/parsing/extract-text-from-pdf/text-extraction-from-multi-column-pdf/_index.md b/zh/python-net/parsing/extract-text-from-pdf/text-extraction-from-multi-column-pdf/_index.md new file mode 100644 index 0000000000..283dc3ea8e --- /dev/null +++ b/zh/python-net/parsing/extract-text-from-pdf/text-extraction-from-multi-column-pdf/_index.md @@ -0,0 +1,88 @@ +--- +title: 改进多列 PDF 的文本提取 +linktitle: 多列 PDF 的文本提取 +type: docs +weight: 30 +url: /zh/python-net/text-extraction-from-multi-column-pdf/ +description: 了解使用 Aspose.PDF for Python 改进多列 PDF 布局中文本提取的技术。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +--- + +## 手动减小字体大小后再提取 + +在某些多列布局中,提取前减小文本片段的字体大小可以改善阅读顺序并减少重叠问题。此技术有助于处理布局紧凑的文档,如杂志、研究论文、宣传册或包含密集文本列的报告。 + +1. 加载 PDF。 +1. 使用 [TextFragmentAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textfragmentabsorber/) 收集文本片段。 +1. 将每个片段的字体大小减小,然后保存并重新打开文档。 +1. 使用 [TextAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textabsorber/) 提取文本。 +1. 将提取的文本写入输出文件。 + +```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) +``` + +## 使用比例因子提取文本 + +多列提取的另一种选项是配置 [TextExtractionOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textextractionoptions/) 使用比例因子。调整比例因子可以改善对紧密排列片段的解释,并有助于在密集布局、表格或基于列的文档中保持更准确的阅读顺序。 + +1. 加载 PDF。 +1. 创建一个 [TextAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.text/textabsorber/). +1. 配置 `TextExtractionOptions.scale_factor`. +1. 将提取选项分配给 absorber。 +1. 提取页面文本并将结果写入输出文件。 + +```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/zh/python-net/parsing/extract-vector-data-from-pdf/_index.md b/zh/python-net/parsing/extract-vector-data-from-pdf/_index.md new file mode 100644 index 0000000000..badffae7e2 --- /dev/null +++ b/zh/python-net/parsing/extract-vector-data-from-pdf/_index.md @@ -0,0 +1,178 @@ +--- +title: 使用 Python 从 PDF 文件提取矢量数据 +linktitle: 从 PDF 提取矢量数据 +type: docs +weight: 80 +url: /zh/python-net/extract-vector-data-from-pdf/ +description: Aspose.PDF 使从 PDF 文件中提取矢量数据变得轻而易举。您可以获取矢量数据(路径、多个多边形、折线),例如位置、颜色、线宽等。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +## 访问 PDF 文档中的矢量数据 + +使用 [GraphicsAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/graphicsabsorber/) 检查页面上的矢量图形元素 [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). 在访问目标页面后,遍历提取的元素,以检查诸如矩形边界、位置和绘图操作符等属性。 + +1. 打开源 PDF 作为 `Document`. +1. 创建一个 `GraphicsAbsorber` 实例。 +1. 调用 `gr_absorber.visit(page)` 在目标页面上。 +1. 读取提取的项目来自 `gr_absorber.elements`. +1. 遍历这些元素并将它们的属性写入输出文件。 + +```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() +``` + +## 将页面中的矢量图形保存为 SVG 文件 + +将 PDF 页面中的矢量图形导出为 SVG,以在原始 PDF 之外保留可缩放的路径和形状。此方法对于在网页、设计或出版工作流中重复使用矢量艺术作品非常有用。 + +1. 加载 PDF 文档。 +1. 访问目标页面。 +1. 调用 `page.try_save_vector_graphics()` 将页面的矢量路径导出为 SVG。 +1. 关闭文档。 + +```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() +``` + +### 将每个子路径提取为单独的 SVG + +当页面包含多个独立的矢量路径时,使用 [SvgExtractionOptions](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/svgextractionoptions/) 与 [SvgExtractor](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/svgextractor/) 将每个子路径写入单独的 SVG 文件。 + +1. 加载 PDF。 +1. 创建 `SvgExtractionOptions` 并设置 `extract_every_subpath_to_svg`. +1. 访问文档的第一页。 +1. 实例化 `SvgExtractor` 带有选项。 +1. 调用 `extractor.extract()` 为每个矢量子路径编写单独的 SVG 文件。 +1. 关闭文档。 + +```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() +``` + +### 将元素列表提取为单个图像 + +从 PDF 页面提取多个矢量元素,并将它们保存为单个合并的 SVG 图像。当您希望保留分组形状、图表或绘图片段之间的视觉关系时,这非常有用。 + +1. 使用以下方式打开 PDF [文档](https://reference.aspose.com/pdf/python-net/aspose.pdf/document/). +1. 选择页面并准备矢量元素列表。 +1. 使用 [SvgExtractor](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/svgextractor/) 以将这些元素合并为一个 SVG。 +1. 保存输出文件。 + +```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() +``` + +### 提取单个元素 + +从 PDF 中提取单个特定的矢量元素并将其保存为独立的 SVG 文件。这对于从更复杂的矢量页面中分离徽标、图标或独立形状非常有用。 + +1. 创建一个 [GraphicsAbsorber](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/graphicsabsorber/) 捕获矢量数据。 +1. 访问特定页面以收集其矢量元素。 +1. 选择目标元素,例如一个 [XFormPlacement](https://reference.aspose.com/pdf/python-net/aspose.pdf.vector/xformplacement/). +1. 将该单个元素保存为 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/zh/python-net/whatsnew/_index.md b/zh/python-net/whatsnew/_index.md index 712fc00d80..013615104c 100644 --- a/zh/python-net/whatsnew/_index.md +++ b/zh/python-net/whatsnew/_index.md @@ -1,344 +1,1169 @@ --- -title: 有什么新功能 -linktitle: 有什么新功能 +title: 有什么新内容 +linktitle: 有什么新内容 type: docs weight: 10 url: /zh/python-net/whatsnew/ -description: 本页介绍了Aspose.PDF for Python via .NET在最近发布版本中引入的最受欢迎的新功能。 +description: 本页介绍了在最近发布的 Aspose.PDF for Python via .NET 中最受欢迎的新功能。 sitemap: changefreq: "monthly" priority: 0.8 -lastmod: "2021-12-24" +lastmod: "2026-06-08" +TechArticle: false --- -## Aspose.PDF 23.12中的新功能 +## Aspose.PDF 26.3 有哪些新功能 -从Aspose.PDF 23.12开始,新增了对以下转换功能的支持: +在 **Aspose.PDF for Python via .NET** 26.3 中,我们添加了: -- 实现PDF到Markdown的转换 +在 PDF 优化期间进行无损图像流重新压缩。OptimizationOptions.CompressAllContentStreams 属性现在也会使用 FlateDecode 对符合条件的图像 XObject 流进行压缩,从而在保持图像质量完整的同时减小文件大小。 ```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) +``` + +图像重新压缩现在在优化过程中匹配所选的 ImageCompressionOptions.Encoding 设置,确保在使用 Jpeg2000 或 Flate 时以及图像缩放、分辨率限制和质量控制方面获得更一致的结果。 + +```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) +``` + +在将 PDF 文档保存为图像或 HTML 时支持渲染批注,帮助在导出带注释的文档以在 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" +改进了 PDF-to-TIFF 的渲染性能,适用于高容量光栅化场景,尤其是在将页面导出为二值 TIFF 图像时。 - 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) ``` -- 实现OFD到PDF的转换 +## Aspose.PDF 26.2 有哪些新功能 + +Aspose.PDF 26.2 引入了对 RTF 转 PDF 转换的支持。此功能允许开发人员直接将富文本格式(RTF)文档转换为 PDF 文件。 + +RTF 是一种被广泛支持的跨平台文档格式,最初由微软开发。它旨在实现不同文字处理应用之间的文档交换,同时保留基本的格式,如字体、颜色、粗体和斜体文本以及嵌入的图像。 ```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) ``` +此代码片段展示了如何使用 Aspose.PDF for Python 在 PDF 页面上在现有内容后插入表格。 + +脚本打开一个已有的 PDF 文档,并计算第一页上当前内容的边界框。利用这些信息,它找出现有内容的结束位置,并在最后一个元素下方放置一个新表格,在表格开始前留出指定的边距。 -Python 3.6 的支持已被终止。 +然后创建一个表格,并使用循环填充多行多列。在设置好表格结构和内容后,将表格添加到页面的段落集合中。最后,将更新后的文档保存为新的 PDF 文件。 -## 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) +``` -从 23.11 版本开始,可以删除隐藏文本。可以使用以下代码片段: +使用 Aspose.PDF for Python 检测并删除 PDF 文档中的不可见文本: ```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 +## Aspose.PDF 26.1 有哪些新功能 - document = ap.Document(input_file) - text_absorber = ap.text.TextFragmentAbsorber() - # 此选项可用于防止在替换隐藏文本后其他文本片段移动。 - text_absorber.text_replace_options = ap.text.TextReplaceOptions(ap.text.TextReplaceOptions.ReplaceAdjustment.NONE) - document.pages.accept(text_absorber) +在 **Aspose.PDF for Python via .NET** 26.1 中,我们已添加: - for fragment in text_absorber.text_fragments: - if fragment.text_state.invisible: - fragment.text = '' +1. 性能改进 – 解决了向文档添加文本时的性能不佳以及整体性能问题。 +1. 增强的渲染精度 – 修复了 PDF 左侧缺失的竖排文字,并纠正了 PDF 转 PNG 转换过程中的中文字符渲染问题。 +1. 改进的 HTML 转换 – API 现在在 HTML 转 PDF 转换中尊重线条颜色,并修复了 XFA 转标准转换中的文本重叠问题。 +1. 针对文档结构的错误修复 – NumberingStyle 现在对 Heading 对象能够正确工作,且 PDF 转 HTML 现在保留高亮文本颜色。 - document.save(output_file) -``` +## Aspose.PDF 25.12 的新功能是什么 -## Aspose.PDF 23.8 中的新功能 +将HTML文档转换为PDF,同时保留逻辑结构信息。生成的PDF更适合用于可访问性、标签化以及依赖结构化文档内容的下游处理。 -从 23.8 版本开始支持添加增量更新检测。 +```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) +``` -已添加检测 PDF 文档中增量更新的功能。 - 此函数在文档以增量更新保存时返回'true';否则,返回'false'。 +分析数字签名的 PDF,以识别并报告未被签名覆盖的内容。使用它来验证文档完整性,审计已签名的 PDF,并检测签名后修改。 ```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 +## Aspose.PDF 25.11 有哪些新功能 - doc = ap.Document(file_path) - updated = doc.has_incremental_update() - print(updated) +此函数比较两个 PDF 文档中指定页面,并生成并排的视觉差异。通过自定义比较选项和颜色,它能够突出显示有意义的更改,同时忽略诸如空白等不重要的差异。 + +```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 + ) ``` -此外,23.8支持处理嵌套复选框字段的方法。许多可填写的PDF表单具有作为单选组的复选框字段: +在 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) +``` -- 创建多值复选框字段: +通过字体子集化和内容流压缩优化资源 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)) - # 设置第一个复选框组选项值 - checkbox.export_value = "option 1" - # 在现有选项下添加新选项 - checkbox.add_option("option 2") - # 在给定矩形位置添加新选项 - checkbox.add_option("option 3", ap.Rectangle(100, 100, 120, 120, True)) - document.form.add(checkbox) - # 选择添加的复选框 - checkbox.value = "option 2" - document.save(DIR_OUTPUT + "checkbox_group.pdf") +## Aspose.PDF 25.10 的新功能 + +增强的 PDF 图层可见性控制 – 本次发布引入了以编程方式定义 PDF 图层初始可见状态并将其锁定,以防止在 PDF 查看器中更改可见性的能力。 + +一个新的 'layer.default_state' 属性允许使用 DefaultState 属性将图层的默认可见性设置为可见或隐藏。这为管理复杂的分层 PDF 文档提供了细粒度的控制,使用户可见性行为可预测。 + +```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) ``` -- 获取和设置多值复选框的值: +## Aspose.PDF 25.9 有哪些新功能 + +25.9 版引入了改进的可访问性、增强的合规支持以及用于处理带标签图像和文档标准的新 API 功能。 + +1. 将 PDF 转换为 PDF/E-1 格式。 +1. 从内存流中添加已标记的图像。 + +### 将 PDF 转换为 PDF/E-1 格式 + +在 25.9 版本的 Aspose.PDF for Python 库中,提供了 PDF/E-1 格式转换。您可以在该格式的更多信息上 [文件格式文档](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]) - - # 允许的值可以从 AllowedStates 集合中检索 - # 使用 Value 属性设置复选框的值 - checkbox.value = checkbox.allowed_states[0] - checkbox_value = checkbox.value # 之前设置的值,例如 "option 1" - # 值应为 AllowedStates 的任何元素 - checkbox.value = "option 2" - checkbox_value = checkbox.value # option 2 - # 通过将 Value 设置为 "Off" 或将 Checked 设置为 false 来取消选中 - checkbox.value = "Off" - # 或者,替代方法: - # checkbox.checked = False - checkbox_value = checkbox.value # Off +### 从流中添加标记图像 + +在 PDF 中从流添加带标签的图像。25.9 版本支持通过从内存流添加图像并为其标记替代文本,提升 PDF 文档的可访问性。 + +```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) ``` -- 用户点击时更新复选框状态: +## Aspose.PDF 25.8 有哪些新功能 + +此更新在布局和文档安全管理方面提供了更大的灵活性。 + +1. 创建带标签的目录(TOC)。 +1. 调整 PDF 页面大小并对内容进行缩放。 +1. 为表格应用虚线边框。 + +### 创建标记的目录(TOC) + +自动在标记的 PDF 中生成可访问的目录(TOC)。在 PDF 中创建完整可访问的目录(TOC)可以让读者高效地导航文档,并确保符合 PDF/UA-1 的可访问性要求。 ```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) +``` + +### 调整页面大小并缩放内容 - 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) # 例如,鼠标点击的坐标 - # 选项 1:查看页面上的注释 - 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 - # 选项 2:查看 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 +在保持布局并按比例缩放内容的同时调整 PDF 页面大小。处理 PDF 时,您可能需要调整页面大小或缩放内容以适应新尺寸。 + +```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) ``` +### 为表格应用虚线边框 + +使用虚线为表格添加自定义边框样式。本示例演示如何在 PDF 文档中使用 Aspose.PDF for Python via .NET 将自定义边框样式(如虚线或点线)应用于表格。 + +```python +import aspose.pdf as ap + -## 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.""" -由于23.7版本支持添加形状提取: + 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) +``` + +## Aspose.PDF 25.7 有哪些新功能 + +25.7 版本侧重于更好的批注支持、文本适配和数字签名管理。 + +1. 将文本适配到形状内部。 +1. 使用公共证书加密 PDF。 +1. 添加云形和多边形注释。 + +### 使用公共证书加密 PDF + +使用基于公钥证书的加密来保护您的 PDF。公钥证书加密允许为特定收件人加密 PDF,确保只有相应私钥的持有者才能打开和阅读文档。 ```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) ``` -还支持在添加文本时检测溢出的功能: +### 将文本适配到矩形内 + +自动缩放文本以适应定义的矩形内部。当在 PDF 中更新或扩展文本时,它可能会超出原始段落的边界。 ```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) +``` + +### 添加云形多边形注释 + +通过云状或多边形样式的批注提升 PDF 审阅工作流。多边形批注允许您使用几何形状在 PDF 中突出显示或强调特定区域。 - 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) ``` +## Aspose.PDF 25.6 的新功能 + +此版本的主要功能: + +1. 图像替代文本支持。 +1. 许可证信息访问。 +1. 带样式的自由文本注释。 +1. 可定制的数字签名外观。 -## Aspose.PDF 23.6 的新功能 +### 图片 Alt 文本支持 -支持设置 HTML 和 Epub 页面标题的功能: +设置和检索图像的替代文本,以提升屏幕阅读器的可访问性。 ```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) +``` + +### 许可证信息访问 - import aspose.pdf as ap +通过 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 = "NEW PAGE & TITILE" # <-- 这是新增的 +```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) ``` -## Aspose.PDF 23.5 的新功能 +### 带样式的自由文本批注 -自 23.5 版本起,支持添加 RedactionAnnotation 字体大小选项。使用下面的代码片段来解决此任务: +使用 SetTextStyle 对注释文本应用粗体、斜体、下划线等样式,或清除现有的格式。 ```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) +``` + +### 可定制的数字签名外观 + +添加图像,更改字体,并在背景内容上叠加签名图形,以实现更好的品牌化或设计一致性。 - import aspose.pdf as ap - - doc = ap.Document(DIR_INPUT + "input.pdf") - # 为特定页面区域创建 RedactionAnnotation 实例 - 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 - # 要在修订注释上打印的文本 - annot.overlay_text = "(Unknown)" - annot.text_alignment = ap.HorizontalAlignment.CENTER - # 在修订注释上重复覆盖文本 - annot.repeat = False - # 这里是新的属性! - annot.font_size = 20 - # 将注释添加到第一页的注释集合中 - doc.pages[1].annotations.add(annot, False) - # 扁平化注释并修订页面内容(即删除修订注释下方的文本和图像) - 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) ``` +## Aspose.PDF 25.5 有哪些新功能 + +最新的 Aspose.PDF 更新引入了若干强大的增强功能,提升了文档的可访问性、兼容性和安全性。开发人员现在可以直接从已签名的 PDF 文件中提取数字证书,从而实现高级的验证和合规检查。 -对Python 3.5的支持已被终止。对Python 3.11的支持已被添加。 +1. 从 PDF 签名中提取证书。 +1. 在标记的 PDF 中创建结构化有序列表。 +1. 使用公钥证书验证签名。 +1. 将动态 XFA 表单转换为 AcroForm PDF。 +1. PDF 中的字体替换 - XPS 转换。 -## Aspose.PDF 23.3中的新功能 +### 从 PDF 签名中提取证书 -版本23.3引入了为图像添加分辨率的支持。可以使用两种方法来解决此问题: +使用 '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 +### 在标记的 PDF 中创建结构化有序列表 - 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) +在标记的文档中生成可访问的编号列表(包括嵌套项)。 - 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) ``` -图像将以缩放分辨率放置,或者您可以结合使用FixedWidth或FixedHeight属性与IsApplyResolution +### 使用公钥证书验证签名 -## Aspose.PDF 23.1中的新功能 +使用外部公钥证书验证数字签名。 -自23.1版本起支持创建PrinterMark注释。 +```python +import aspose.pdf as ap -打印标记是添加到页面的图形符号或文本,以帮助生产人员识别多板作业的组件并在生产过程中保持一致的输出。 - 常用于印刷行业的示例包括: -- 对齐版材的套准标记 -- 用于测量颜色和墨水密度的灰阶和颜色条 -- 显示输出介质修剪位置的切割标记 +def verify_with_public_key_certificate1(self, certificate, infile): + path_infile = self.data_dir + infile -我们将展示一个带有颜色条选项的示例,用于测量颜色和墨水密度。这里有一个基本的抽象类 PrinterMarkAnnotation,从它派生出了子类 ColorBarAnnotation - 它已经实现了这些条纹。让我们检查这个示例: + # 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 +### 将动态 XFA 表单转换为 AcroForm PDF + +使用 'ignore_needs_rendering' 标准化 XFA 表单。 - 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) ``` -还支持矢量图像提取。尝试使用以下代码来检测和提取矢量图形: + +### PDF 中的字体替换 - XPS 转换 + +用默认后备字体(例如“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) +``` + +## Aspose.PDF 25.4 有什么新功能 + +### PDF/A 转换期间的自动标记 - import aspose.pdf as ap +将PDF转换为PDF/A-1b,并自动创建逻辑结构,以改进可访问性。 - 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/zh/python-net/working-with-facades/_index.md b/zh/python-net/working-with-facades/_index.md new file mode 100644 index 0000000000..c3c1e49fdd --- /dev/null +++ b/zh/python-net/working-with-facades/_index.md @@ -0,0 +1,60 @@ +--- +title: 使用 PDF Facades +linktitle: 使用 PDF Facades +type: docs +weight: 100 +url: /zh/python-net/working-with-facades/ +description: 了解如何在 Python via .NET 中使用 Aspose.PDF Facades 来编辑 PDF 内容、管理表单和批注、应用安全性、对文件进行签名、为页面添加印章、打印文档以及检查 PDF 元数据。 +is_node: true +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python via .NET 中使用 PDF Facades 进行表单、签名、安全性、印章和文件处理。 +Abstract: 本节说明如何在 Python via .NET 中使用 Aspose.PDF Facades 通过简化的 API 处理常见的 PDF 工作流。了解如何合并和拆分文件、编辑内容、管理批注和表单、应用安全性、对文档签名、添加印章、打印 PDF,以及获取文件信息。 +--- + +Aspose.PDF Facades 是 Aspose.PDF for Python via .NET 中的一组辅助类,使您能够在不直接使用低层文档对象模型的情况下执行常见的 PDF 操作。 + +本节介绍了您可以在 Python 应用程序中使用的主要 facade 类,用于编辑 PDF 内容、管理表单、添加批注、应用安全性、对文件签名、使用印章、打印文档以及检索 PDF 文件信息。 + +如果您需要一个实用的 API 来处理日常的 PDF 任务,例如合并文档、填写表单、应用权限或签署文件,Facades API 提供了一种简化的方式来构建这些工作流。 + +## 为什么在 Aspose.PDF for Python via .NET 中使用 Facades + +PDF Facades 为常见的文档工作流提供了简化的 API 层。当您需要快速执行实用的 PDF 操作时,它们非常有用,例如合并文件、填写表单、为页面加盖印章或应用数字签名,而无需直接使用完整的文档对象模型。 + +在自动化场景中,它们尤其有用,因为您希望在 Python 中获得简洁、面向任务的 PDF 编辑、表单处理、批注更新、文档安全和输出工作流的 API。 + +## 主要的 PDF Facade 类 + +在本节中,您将学习如何使用这些 Facade 类: + +- [使用 **PdfFileEditor** 对 PDF 文件进行拆分、合并和处理](/pdf/zh/python-net/pdffileeditor-class/). +- [使用 **PdfContentEditor** 编辑 PDF 内容](/pdf/zh/python-net/pdfcontenteditor-class/). +- [使用 **PdfAnnotationEditor** 管理 PDF 注释和评论](/pdf/zh/python-net/pdfannotationeditor-class/). +- [使用 **PdfFileSignature** 通过证书对 PDF 文件进行签名](/pdf/zh/python-net/pdffilesignature-class/). +- [使用 **FormEditor** 添加、更新和删除表单字段](/pdf/zh/python-net/formeditor-class/). +- [使用 **PdfFileInfo** 访问 PDF 元数据和文件详细信息](/pdf/zh/python-net/pdffileinfo-class/). +- [使用 **PdfFileSecurity** 加密、解密并设置文档权限](/pdf/zh/python-net/pdffilesecurity-class/). +- [使用 **PdfFileStamp** 添加页面和图像印章](/pdf/zh/python-net/pdffilestamp-class/). +- [使用 **PdfViewer** 打印 PDF 文档](/pdf/zh/python-net/pdfviewer-class/). +- [使用 **Form** 处理 AcroForm 数据](/pdf/zh/python-net/form-class/). +- [使用 **Stamp** 将印章应用于 PDF 文档](/pdf/zh/python-net/stamp-class/). + +## 流行的 PDF 外观工作流 + +在需要使用 Python 自动化常见 PDF 任务时,请使用这些 facade APIs: + +- 合并、拆分并重新排序 PDF 文件,以用于文档处理工作流。 +- 填写交互式 PDF 表单,更新字段,并提取表单值。 +- 向现有 PDF 页面添加批注、评论和印章。 +- 对文档进行加密、权限设置和数字签名以确保安全。 +- 在归档、打印或交付之前检查 PDF 元数据和文件属性。 + +## 本节涵盖的常见 PDF 任务 + +使用本节中的文章来处理实际的 PDF 工作流,例如在 Python 中进行表单填写、字段管理、注释编辑、附件处理、文本替换、页面处理、PDF 安全性以及签名操作。 + +要探索具体的 API,请先从上述类链接开始,然后转到本节中的基于任务的文章,获取逐步示例。 diff --git a/zh/python-net/working-with-facades/form/_index.md b/zh/python-net/working-with-facades/form/_index.md new file mode 100644 index 0000000000..ada042ce17 --- /dev/null +++ b/zh/python-net/working-with-facades/form/_index.md @@ -0,0 +1,21 @@ +--- +title: Form 类 +type: docs +weight: 140 +url: /zh/python-net/form-class/ +description: 本节说明如何使用 Aspose.PDF Facades 通过 Form 类进行操作。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中使用 Form 类处理 PDF 表单数据和 AcroForm 字段 +Abstract: 本节说明如何在 Aspose.PDF for Python via .NET 中使用 Form facade 来处理交互式 PDF 表单。了解如何导出和导入表单数据、填写不同类型的字段、管理现有字段、处理按钮字段和图像,以及以编程方式读取表单值。 +--- + +- [导出表单数据](/pdf/zh/python-net/exporting-form-data/) +- [导入表单数据](/pdf/zh/python-net/importing-form-data/) +- [填写 Form 字段](/pdf/zh/python-net/filling-form-fields/) +- [按钮字段和图像](/pdf/zh/python-net/button-fields-and-images/) +- [管理 Form 字段](/pdf/zh/python-net/managing-form-fields/) +- [读取表单值](/pdf/zh/python-net/reading-form-values/) diff --git a/zh/python-net/working-with-facades/form/button-fields-and-images/_index.md b/zh/python-net/working-with-facades/form/button-fields-and-images/_index.md new file mode 100644 index 0000000000..3ccbbaa9c6 --- /dev/null +++ b/zh/python-net/working-with-facades/form/button-fields-and-images/_index.md @@ -0,0 +1,85 @@ +--- +title: 按钮字段和图像 +type: docs +weight: 40 +url: /zh/python-net/button-fields-and-images/ +description: 本示例演示如何使用 Aspose.PDF Facades API 在 PDF 表单中管理按钮字段。 +lastmod: "2026-06-08" +TechArticle: true +AlternativeHeadline: 向按钮字段添加图像外观并读取提交标志 +Abstract: PDF 表单通常包含交互式按钮,这些按钮要么触发 JavaScript 动作,要么提交表单数据。您可以通过添加图像作为外观来在视觉上增强按钮字段,并通过编程方式检查其提交行为。 +--- + +## 向按钮字段添加图像外观 + +此代码片段说明了如何在 PDF 表单中的现有按钮字段上添加图像外观。此操作通过将默认外观替换为自定义图像来提升 PDF 按钮的视觉呈现效果。 + +1. 创建一个 Form 对象。 +1. 将 PDF 文件绑定到 Form 对象。 +1. 向 Button Field 添加 Image。 + + - 确定与 PDF 关联的图像文件的路径 + - 以二进制模式打开图像,作为 image_stream。 + - 使用完整限定的 button field 名称调用 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 库帮助您使用 Aspose.PDF Facades API 检索 PDF 表单中提交按钮的提交标志。提交标志定义了提交按钮的行为,例如它是发送整个表单、包含注释,还是以 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/zh/python-net/working-with-facades/form/exporting-form-data/_index.md b/zh/python-net/working-with-facades/form/exporting-form-data/_index.md new file mode 100644 index 0000000000..027c5bf2f1 --- /dev/null +++ b/zh/python-net/working-with-facades/form/exporting-form-data/_index.md @@ -0,0 +1,14 @@ +--- +title: 导出表单数据 +type: docs +weight: 10 +url: /zh/python-net/exporting-form-data/ +description: 本文演示了如何使用 Aspose.PDF for Python via .NET 将 PDF 表单数据导出为多种结构化格式。它提供了从标准 AcroForms 和基于 XFA 的 PDF 中提取表单字段值的实用示例,并使用 Form 类的 Aspose.PDF Facades 将其保存为 XML、FMD、XFDF 和 JSON 文件。 +lastmod: "2026-06-08" +--- + +- [导出为 FDF](/pdf/zh/python-net/export-to-fdf/) +- [导出为 XFDF](/pdf/zh/python-net/export-to-xfdf/) +- [导出为 JSON](/pdf/zh/python-net/export-to-json/) +- [导出为 XML](/pdf/zh/python-net/export-to-xml/) +- [提取 XFA 数据](/pdf/zh/python-net/extract-xfa-data/) \ No newline at end of file diff --git a/zh/python-net/working-with-facades/form/exporting-form-data/export-to-fdf/_index.md b/zh/python-net/working-with-facades/form/exporting-form-data/export-to-fdf/_index.md new file mode 100644 index 0000000000..1ba4567215 --- /dev/null +++ b/zh/python-net/working-with-facades/form/exporting-form-data/export-to-fdf/_index.md @@ -0,0 +1,42 @@ +--- +title: 导出为 FDF +type: docs +weight: 10 +url: /zh/python-net/export-to-fdf/ +description: 本示例解释了如何使用 Aspose.PDF for Python via .NET 将 PDF 表单字段数据导出到 FDF(Forms Data Format)文件。它演示了如何通过 Form 门面访问交互式表单数据,绑定源 PDF 文档,并将提取的数值保存到 FDF 流中。 +lastmod: "2026-06-08" +--- + +FDF 是一种轻量级格式,专门用于存储和传输 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/) 模块中初始化的,允许开发者与 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/zh/python-net/working-with-facades/form/exporting-form-data/export-to-json/_index.md b/zh/python-net/working-with-facades/form/exporting-form-data/export-to-json/_index.md new file mode 100644 index 0000000000..247f7c1353 --- /dev/null +++ b/zh/python-net/working-with-facades/form/exporting-form-data/export-to-json/_index.md @@ -0,0 +1,42 @@ +--- +title: 导出为 JSON +type: docs +weight: 30 +url: /zh/python-net/export-to-json/ +description: 本示例演示如何使用 Aspose.PDF for Python via .NET 将 PDF 表单字段值导出到 JSON 文件。它解释了如何加载 PDF 表单,通过 Form 门面访问其字段,并将提取的数据保存为结构化的 JSON 格式。 +lastmod: "2026-06-08" +--- + +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/zh/python-net/working-with-facades/form/exporting-form-data/export-to-xfdf/_index.md b/zh/python-net/working-with-facades/form/exporting-form-data/export-to-xfdf/_index.md new file mode 100644 index 0000000000..d80930f73d --- /dev/null +++ b/zh/python-net/working-with-facades/form/exporting-form-data/export-to-xfdf/_index.md @@ -0,0 +1,42 @@ +--- +title: 导出为 XFDF +type: docs +weight: 20 +url: /zh/python-net/export-to-xfdf/ +description: 本示例展示了如何使用 Aspose.PDF for Python via .NET 将 PDF 表单字段数据导出为 XFDF(XML Forms Data Format)文件。它演示了如何加载 PDF 表单,通过 Form 外观访问其字段,并将提取的值保存到 XFDF 流中。 +lastmod: "2026-06-08" +--- + +XFDF 是 PDF 表单数据的 XML 表示形式,允许开发人员独立于原始文档传输表单字段值。在本示例中,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 并将其数据导出为结构化的 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/zh/python-net/working-with-facades/form/exporting-form-data/export-to-xml/_index.md b/zh/python-net/working-with-facades/form/exporting-form-data/export-to-xml/_index.md new file mode 100644 index 0000000000..ee361d81c2 --- /dev/null +++ b/zh/python-net/working-with-facades/form/exporting-form-data/export-to-xml/_index.md @@ -0,0 +1,42 @@ +--- +title: 导出为 XML +type: docs +weight: 40 +url: /zh/python-net/export-to-xml/ +description: 这个示例演示如何使用 Aspose.PDF for Python via .NET 将 PDF 表单数据导出为 XML 文件。它展示了如何加载 PDF 文档,通过 Form facade 访问其表单字段,并使用 Form Class 将提取的数据保存为结构化 XML。 +lastmod: "2026-06-08" +--- + +导出表单数据使开发者能够在无需手动复制字段值的情况下重复使用存储在 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/zh/python-net/working-with-facades/form/exporting-form-data/extract-xfa-data/_index.md b/zh/python-net/working-with-facades/form/exporting-form-data/extract-xfa-data/_index.md new file mode 100644 index 0000000000..7cadb124ee --- /dev/null +++ b/zh/python-net/working-with-facades/form/exporting-form-data/extract-xfa-data/_index.md @@ -0,0 +1,41 @@ +--- +title: 提取 XFA 数据 +type: docs +weight: 50 +url: /zh/python-net/extract-xfa-data/ +description: 本示例说明如何使用 Aspose.PDF for Python via .NET 从 PDF 文件中提取 XFA 表单数据。它演示了如何将基于 XFA 的 PDF 文档绑定到 Form 门面并将其内部数据结构导出到文件流中。 +lastmod: "2026-06-08" +--- + +XFA(XML Forms Architecture)表单不同于传统的 AcroForm,因为它们的数据存储在 PDF 内部的 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 并将其 XFA 数据直接提取到文件中。 + +1. 创建 pdf_facades.Form() 的实例以管理表单数据。 +1. 调用 'bind_pdf()' 以附加包含 XFA 表单的源 PDF。 +1. 使用 'FileIO()' 创建可写文件流。 +1. 调用 'extract_xfa_data()' 导出嵌入的 XFA 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 + + +# 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/zh/python-net/working-with-facades/form/filling-form-fields/_index.md b/zh/python-net/working-with-facades/form/filling-form-fields/_index.md new file mode 100644 index 0000000000..4ae1a69a06 --- /dev/null +++ b/zh/python-net/working-with-facades/form/filling-form-fields/_index.md @@ -0,0 +1,15 @@ +--- +title: 填写 Form 字段 +type: docs +weight: 30 +url: /zh/python-net/filling-form-fields/ +description: 本文演示了如何使用 Aspose.PDF for Python via .NET 以编程方式填写 PDF 表单字段。它涵盖了填充不同类型交互式表单元素的实用技术,包括文本字段、复选框、单选按钮、列表框、条形码字段以及动态映射的名称–值对。通过使用 Form 门面,开发人员可以绑定 PDF 文档,通过简单的 API 调用更新字段值,并自动保存修改后的文件。 +lastmod: "2026-06-08" +--- + +- [填写文本字段](/pdf/zh/python-net/fill-text-fields/) +- [填写复选框字段](/pdf/zh/python-net/fill-check-box-fields/) +- [填写单选按钮字段](/pdf/zh/python-net/fill-radio-button-fields/) +- [填写列表框](/pdf/zh/python-net/fill-list-box/) +- [填写条形码字段](/pdf/zh/python-net/fill-barcode-fields/) +- [按名称和值填写字段](/pdf/zh/python-net/fill-fields-by-name-and-value/) diff --git a/zh/python-net/working-with-facades/form/filling-form-fields/fill-barcode-fields/_index.md b/zh/python-net/working-with-facades/form/filling-form-fields/fill-barcode-fields/_index.md new file mode 100644 index 0000000000..19b32fb538 --- /dev/null +++ b/zh/python-net/working-with-facades/form/filling-form-fields/fill-barcode-fields/_index.md @@ -0,0 +1,43 @@ +--- +title: 填写条形码字段 +type: docs +weight: 50 +url: /zh/python-net/fill-barcode-fields/ +description: 本示例演示了如何使用 Aspose.PDF for Python via .NET 以编程方式填充 PDF 表单中的条形码字段。它展示了如何绑定 PDF 文档、为条形码字段分配值,并保存更新后的文件。 +lastmod: "2026-06-08" +--- + +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/zh/python-net/working-with-facades/form/filling-form-fields/fill-check-box-fields/_index.md b/zh/python-net/working-with-facades/form/filling-form-fields/fill-check-box-fields/_index.md new file mode 100644 index 0000000000..e1d2a960a2 --- /dev/null +++ b/zh/python-net/working-with-facades/form/filling-form-fields/fill-check-box-fields/_index.md @@ -0,0 +1,44 @@ +--- +title: 填写复选框字段 +type: docs +weight: 20 +url: /zh/python-net/fill-check-box-fields/ +description: 本示例演示了如何使用 Aspose.PDF for Python via .NET 以编程方式填写 PDF 表单中的复选框字段。它展示了如何绑定 PDF 文档、按字段名称更新复选框的值,并保存修改后的文件。 +lastmod: "2026-06-08" +--- + +复选框通常在 PDF 表单中用于表示二元选择,例如订阅或协议确认。在本示例中, [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) facade 来自 [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/zh/python-net/working-with-facades/form/filling-form-fields/fill-fields-by-name-and-value/_index.md b/zh/python-net/working-with-facades/form/filling-form-fields/fill-fields-by-name-and-value/_index.md new file mode 100644 index 0000000000..7fb9ee6d36 --- /dev/null +++ b/zh/python-net/working-with-facades/form/filling-form-fields/fill-fields-by-name-and-value/_index.md @@ -0,0 +1,50 @@ +--- +title: 按名称和值填写字段 +type: docs +weight: 60 +url: /zh/python-net/fill-fields-by-name-and-value/ +description: 本文演示了如何使用 Aspose.PDF for Python via .NET 通过名称和值动态填充多个 PDF 表单字段。它不是逐个设置字段,而是使用字典结构将字段名称映射到对应值,并在循环中批量填充。 +lastmod: "2026-06-08" +--- + +使用名称‑值集合填充表单字段可让开发者打造可伸缩且灵活的 PDF 表单自动化解决方案。在本示例中,the [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) facade 来自 [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) 用于绑定 PDF 文档并遍历字段数据字典。每个条目通过 ‘fill_field method’ 应用,实现对表单字段的高效批量更新。 + +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/zh/python-net/working-with-facades/form/filling-form-fields/fill-list-box/_index.md b/zh/python-net/working-with-facades/form/filling-form-fields/fill-list-box/_index.md new file mode 100644 index 0000000000..5d82fb2381 --- /dev/null +++ b/zh/python-net/working-with-facades/form/filling-form-fields/fill-list-box/_index.md @@ -0,0 +1,43 @@ +--- +title: 填写列表框 +type: docs +weight: 40 +url: /zh/python-net/fill-list-box/ +description: 本示例演示了如何使用 Aspose.PDF for Python via .NET 以编程方式填充 PDF 表单中的列表框和多选字段。它展示了如何绑定 PDF 文档、在基于列表的表单字段中选择值,并保存更新后的文件。 +lastmod: "2026-06-08" +--- + +列表框和多选字段允许用户从预定义的选项集合中选择一个或多个值。在本示例中, [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) facade 来自 [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) 用于访问 PDF 表单并将选定的值分配给 favorite_colors 字段。选择所需的选项后,更新的文档将被保存。 + +1. 初始化 'pdf_facades.Form()' 以管理和更新表单字段。 +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 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/zh/python-net/working-with-facades/form/filling-form-fields/fill-radio-button-fields/_index.md b/zh/python-net/working-with-facades/form/filling-form-fields/fill-radio-button-fields/_index.md new file mode 100644 index 0000000000..f73731de77 --- /dev/null +++ b/zh/python-net/working-with-facades/form/filling-form-fields/fill-radio-button-fields/_index.md @@ -0,0 +1,44 @@ +--- +title: 填写单选按钮字段 +type: docs +weight: 30 +url: /zh/python-net/fill-radio-button-fields/ +description: 本示例演示了如何使用 Aspose.PDF for Python via .NET 以编程方式填写 PDF 表单中的单选按钮字段。它展示了如何绑定 PDF 文档、按索引选择单选按钮选项,并保存更新后的文件。 +lastmod: "2026-06-08" +--- + +单选按钮允许用户从预定义的组中选择单个选项,例如性别或偏好字段。在本示例中, [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/zh/python-net/working-with-facades/form/filling-form-fields/fill-text-fields/_index.md b/zh/python-net/working-with-facades/form/filling-form-fields/fill-text-fields/_index.md new file mode 100644 index 0000000000..03176ed461 --- /dev/null +++ b/zh/python-net/working-with-facades/form/filling-form-fields/fill-text-fields/_index.md @@ -0,0 +1,45 @@ +--- +title: 填写文本字段 +type: docs +weight: 10 +url: /zh/python-net/fill-text-fields/ +description: 此示例演示如何使用 Aspose.PDF for Python via .NET 自动填充 PDF 表单中的文本字段。它展示了如何加载 PDF 文档、按名称填充特定的表单字段并保存更新后的文件。 +lastmod: "2026-06-08" +--- + +通过编程方式填充文本字段使应用程序能够重复使用 PDF 模板并插入动态内容,而无需手动编辑。在本示例中, [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) facade 来自 [aspose.pdf.facades](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/) 用于绑定 PDF 表单并更新多个字段,如姓名、地址和电子邮件。赋值后,修改后的 PDF 被保存为新文档。 + +1. 初始化 \u0027pdf_facades.Form()\u0027 以管理表单字段操作。 +1. 使用 \u0027bind_pdf()\u0027 附加包含文本字段的输入 PDF。 +1. 调用 'fill_field()' 将数据插入到诸如 name、address 和 email 等字段。 +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/zh/python-net/working-with-facades/form/importing-form-data/_index.md b/zh/python-net/working-with-facades/form/importing-form-data/_index.md new file mode 100644 index 0000000000..a4bd9e7dc4 --- /dev/null +++ b/zh/python-net/working-with-facades/form/importing-form-data/_index.md @@ -0,0 +1,14 @@ +--- +title: 导入表单数据 +type: docs +weight: 20 +url: /zh/python-net/importing-form-data/ +description: 本节演示如何使用 Aspose.PDF for Python via .NET 从多种外部格式导入和替换 PDF 表单数据。它涵盖了将 PDF 表单字段填充自 XML、FDF、XFDF 和 JSON 文件的实用示例,以及替换现有 XFA 数据集。通过使用 Form 门面,开发者可以绑定 PDF 文档,通过文件流加载结构化数据,并自动更新表单字段,无需手动编辑。 +lastmod: "2026-06-08" +--- + +- [导入 FDF 数据](/pdf/zh/python-net/import-fdf-data/) +- [导入 XFDF 数据](/pdf/zh/python-net/import-xfdf-data/) +- [导入 JSON 数据](/pdf/zh/python-net/import-json-data/) +- [导入 XML 数据](/pdf/zh/python-net/import-xml-data/) +- [替换 XFA 数据](/pdf/zh/python-net/replace-xfa-data/) diff --git a/zh/python-net/working-with-facades/form/importing-form-data/import-fdf-data/_index.md b/zh/python-net/working-with-facades/form/importing-form-data/import-fdf-data/_index.md new file mode 100644 index 0000000000..2e19f2a51f --- /dev/null +++ b/zh/python-net/working-with-facades/form/importing-form-data/import-fdf-data/_index.md @@ -0,0 +1,45 @@ +--- +title: 导入 FDF 数据 +type: docs +weight: 10 +url: /zh/python-net/import-fdf-data/ +description: 本示例演示如何使用 Aspose.PDF for Python via .NET 将表单数据从 FDF 文件导入 PDF 表单。它展示了如何绑定 PDF 文档、从 FDF 流读取表单字段值,并自动填充相应的字段。 +lastmod: "2026-06-08" +--- + +FDF(Forms Data Format)是一种轻量级格式,用于存储和传输 PDF 表单字段值,而不包含整个文档。在本示例中, [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) facade 来自 [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/zh/python-net/working-with-facades/form/importing-form-data/import-json-data/_index.md b/zh/python-net/working-with-facades/form/importing-form-data/import-json-data/_index.md new file mode 100644 index 0000000000..74ef3947d5 --- /dev/null +++ b/zh/python-net/working-with-facades/form/importing-form-data/import-json-data/_index.md @@ -0,0 +1,46 @@ +--- +title: 导入 JSON 数据 +type: docs +weight: 30 +url: /zh/python-net/import-json-data/ +description: 本例演示了如何使用 Aspose.PDF for Python via .NET 将表单字段数据从 JSON 文件导入 PDF 表单。它展示了如何绑定 PDF 文档、通过文件流读取结构化 JSON 数据,并自动填充匹配的表单字段。 +lastmod: "2026-06-08" +--- + +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. 使用 \u0027FileIO()\u0027 读取包含表单值的 JSON 文件。 +1. 调用 \u0027import_json()\u0027 使用 JSON 键–值对填充 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 + + +# 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/zh/python-net/working-with-facades/form/importing-form-data/import-xfdf-data/_index.md b/zh/python-net/working-with-facades/form/importing-form-data/import-xfdf-data/_index.md new file mode 100644 index 0000000000..ddec92cb23 --- /dev/null +++ b/zh/python-net/working-with-facades/form/importing-form-data/import-xfdf-data/_index.md @@ -0,0 +1,46 @@ +--- +title: 导入 XFDF 数据 +type: docs +weight: 20 +url: /zh/python-net/import-xfdf-data/ +description: 本示例演示如何使用 Aspose.PDF for Python via .NET 将 XFDF 文件中的表单数据导入到 PDF 表单中。它展示了如何绑定 PDF 文档,通过文件流读取基于 XML 的 XFDF 数据,并自动填充匹配的表单字段。导入 XFDF 数据可实现高效的表单数据交换,并支持依赖结构化 XML 格式的自动化文档工作流。 +lastmod: "2026-06-08" +--- + +XFDF(XML Forms Data Format)是 PDF 表单数据的 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 表单并从外部 XFDF 文件导入字段值。导入数据后,更新后的 PDF 被另存为新文档。 + +1. 初始化 pdf_facades.Form() 以操作 PDF 表单字段。 +1. 调用 ‘bind_pdf()’ 以附加 PDF 表单模板。 +1. 使用 'open()' 读取 XFDF 文件。 +1. 调用 'import_xfdf()' 以使用 XFDF 文件中的值填充 PDF 字段。 +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/zh/python-net/working-with-facades/form/importing-form-data/import-xml-data/_index.md b/zh/python-net/working-with-facades/form/importing-form-data/import-xml-data/_index.md new file mode 100644 index 0000000000..7348b0f46c --- /dev/null +++ b/zh/python-net/working-with-facades/form/importing-form-data/import-xml-data/_index.md @@ -0,0 +1,46 @@ +--- +title: 导入 XML 数据 +type: docs +weight: 40 +url: /zh/python-net/import-xml-data/ +description: 本示例演示如何使用 Aspose.PDF for Python via .NET 将 XML 文件中的表单数据导入到 PDF 表单字段。它展示了如何绑定 PDF 文档,通过文件流读取结构化的 XML 数据,并自动填充相应的表单字段。 +lastmod: "2026-06-08" +--- + +XML 通常用于存储结构化的表单数据,使其成为在系统之间传递值的实用格式。在本示例中,the [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) facade 来自 [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/zh/python-net/working-with-facades/form/importing-form-data/replace-xfa-data/_index.md b/zh/python-net/working-with-facades/form/importing-form-data/replace-xfa-data/_index.md new file mode 100644 index 0000000000..b58c24bf10 --- /dev/null +++ b/zh/python-net/working-with-facades/form/importing-form-data/replace-xfa-data/_index.md @@ -0,0 +1,46 @@ +--- +title: 替换 XFA 数据 +type: docs +weight: 50 +url: /zh/python-net/replace-xfa-data/ +description: 本例演示如何使用 Aspose.PDF for Python via .NET 在 PDF 中替换现有的 XFA 表单数据。它展示了如何绑定基于 XFA 的 PDF 文档、从外部 XFA 文件加载新数据,并以编程方式更新表单内容。 +lastmod: "2026-06-08" +--- + +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 并使用外部 XML 流替换其现有的 XFA 数据集。应用新数据后,更新后的 PDF 将另存为一个单独的文件。 + +1. 初始化 pdf_facades.Form() 以管理 XFA 表单数据。 +1. 调用 'bind_pdf()' 以附加包含 XFA 表单的 PDF。 +1. 使用 'FileIO()' 读取 XFA XML 文件。 +1. 调用 'set_xfa_data()' 以新 XFA 内容更新 PDF。 +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/zh/python-net/working-with-facades/form/managing-form-fields/_index.md b/zh/python-net/working-with-facades/form/managing-form-fields/_index.md new file mode 100644 index 0000000000..13eb1e9cdc --- /dev/null +++ b/zh/python-net/working-with-facades/form/managing-form-fields/_index.md @@ -0,0 +1,12 @@ +--- +title: 管理 Form 字段 +type: docs +weight: 50 +url: /zh/python-net/managing-form-fields/ +description: 本节演示如何使用 Aspose.PDF for Python via .NET 管理和修改 PDF 表单字段。它涵盖了对特定字段进行扁平化、对所有 form 字段进行扁平化以及以编程方式重命名现有字段的实用示例。通过使用 Form facade,开发人员可以绑定 PDF 文档,调整字段行为,并保存已应用永久更改的更新文件。 +lastmod: "2026-06-08" +--- + +- [扁平化特定字段](/pdf/zh/python-net/flatten-specific-fields/) +- [扁平化所有字段](/pdf/zh/python-net/flatten-all-fields/) +- [重命名表单字段](/pdf/zh/python-net/rename-form-fields/) \ No newline at end of file diff --git a/zh/python-net/working-with-facades/form/managing-form-fields/flatten-all-fields/_index.md b/zh/python-net/working-with-facades/form/managing-form-fields/flatten-all-fields/_index.md new file mode 100644 index 0000000000..5e0d0be22b --- /dev/null +++ b/zh/python-net/working-with-facades/form/managing-form-fields/flatten-all-fields/_index.md @@ -0,0 +1,43 @@ +--- +title: 扁平化所有字段 +type: docs +weight: 10 +url: /zh/python-net/flatten-all-fields/ +description: 本示例演示如何使用 Aspose.PDF for Python via .NET 将 PDF 中的所有表单字段扁平化。它展示了如何绑定 PDF 文档、将每个交互式表单元素转换为静态页面内容,并保存最终文件。 +lastmod: "2026-06-08" +--- + +扁平化通过将字段值直接合并到文档布局中,去除 PDF 表单的交互性。在本示例中, [Form](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/form/) facade 来自 [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/zh/python-net/working-with-facades/form/managing-form-fields/flatten-specific-fields/_index.md b/zh/python-net/working-with-facades/form/managing-form-fields/flatten-specific-fields/_index.md new file mode 100644 index 0000000000..5a1132aed1 --- /dev/null +++ b/zh/python-net/working-with-facades/form/managing-form-fields/flatten-specific-fields/_index.md @@ -0,0 +1,47 @@ +--- +title: 扁平化特定字段 +type: docs +weight: 20 +url: /zh/python-net/flatten-specific-fields/ +description: 本节演示了如何使用 Aspose.PDF for Python via .NET 管理和修改 PDF 表单字段。内容涵盖了扁平化特定字段、扁平化所有表单字段以及以编程方式重命名现有字段的实用示例。 +lastmod: "2026-06-08" +--- + +管理表单字段是 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/zh/python-net/working-with-facades/form/managing-form-fields/rename-form-fields/_index.md b/zh/python-net/working-with-facades/form/managing-form-fields/rename-form-fields/_index.md new file mode 100644 index 0000000000..ca3f3c5aad --- /dev/null +++ b/zh/python-net/working-with-facades/form/managing-form-fields/rename-form-fields/_index.md @@ -0,0 +1,46 @@ +--- +title: 重命名表单字段 +type: docs +weight: 30 +url: /zh/python-net/rename-form-fields/ +description: 本示例演示了如何使用 Aspose.PDF for Python via .NET 在 PDF 文档中重命名表单字段。它展示了如何绑定 PDF 表单、以编程方式更新现有字段名称并保存修改后的文件。重命名字段有助于统一表单结构、改进数据映射,并简化与自动化工作流或外部系统的集成。 +lastmod: "2026-06-08" +--- + +在将 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/zh/python-net/working-with-facades/form/reading-form-values/_index.md b/zh/python-net/working-with-facades/form/reading-form-values/_index.md new file mode 100644 index 0000000000..42ff615464 --- /dev/null +++ b/zh/python-net/working-with-facades/form/reading-form-values/_index.md @@ -0,0 +1,15 @@ +--- +title: 读取表单值 +type: docs +weight: 60 +url: /zh/python-net/reading-form-values/ +description: 本节解释了如何使用 Form 类通过 Aspose.PDF Facades 读取表单值。 +lastmod: "2026-06-08" +--- + +- [获取字段值](/pdf/zh/python-net/get-field-values/) +- [获取单选按钮选项](/pdf/zh/python-net/get-radio-button-options/) +- [获取必填字段名称](/pdf/zh/python-net/get-required-field-names/) +- [获取富文本值](/pdf/zh/python-net/get-rich-text-values/) +- [获取字段Facade](/pdf/zh/python-net/get-field-facades/) +- [解析完整字段名称](/pdf/zh/python-net/resolve-full-field-names/) \ No newline at end of file diff --git a/zh/python-net/working-with-facades/form/reading-form-values/get-field-facades/_index.md b/zh/python-net/working-with-facades/form/reading-form-values/get-field-facades/_index.md new file mode 100644 index 0000000000..f9a89a8618 --- /dev/null +++ b/zh/python-net/working-with-facades/form/reading-form-values/get-field-facades/_index.md @@ -0,0 +1,43 @@ +--- +title: 获取字段Facade +type: docs +weight: 10 +url: /zh/python-net/get-field-facades/ +description: 本示例演示如何使用 Aspose.PDF Facades API 从 PDF 文档中读取特定表单字段的值。 +lastmod: "2026-06-08" +--- + +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/zh/python-net/working-with-facades/form/reading-form-values/get-field-values/_index.md b/zh/python-net/working-with-facades/form/reading-form-values/get-field-values/_index.md new file mode 100644 index 0000000000..b46a1a07ed --- /dev/null +++ b/zh/python-net/working-with-facades/form/reading-form-values/get-field-values/_index.md @@ -0,0 +1,43 @@ +--- +title: 获取字段值 +type: docs +weight: 50 +url: /zh/python-net/get-field-values/ +description: 使用 Form 类的 Aspose.PDF Facades 从 PDF 表单检索字段值。 +lastmod: "2026-06-08" +--- + +此代码片段展示了如何使用 Aspose.PDF Facades API 从 PDF 文档中检索表单字段的当前值。The [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/zh/python-net/working-with-facades/form/reading-form-values/get-radio-button-options/_index.md b/zh/python-net/working-with-facades/form/reading-form-values/get-radio-button-options/_index.md new file mode 100644 index 0000000000..5f35769c74 --- /dev/null +++ b/zh/python-net/working-with-facades/form/reading-form-values/get-radio-button-options/_index.md @@ -0,0 +1,42 @@ +--- +title: 获取单选按钮选项 +type: docs +weight: 20 +url: /zh/python-net/get-radio-button-options/ +description: 本文演示如何使用 Aspose.PDF Facades API 检索 PDF 文档中单选按钮字段的当前选定值。 +lastmod: "2026-06-08" +--- + +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 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/zh/python-net/working-with-facades/form/reading-form-values/get-required-field-names/_index.md b/zh/python-net/working-with-facades/form/reading-form-values/get-required-field-names/_index.md new file mode 100644 index 0000000000..d34c196e41 --- /dev/null +++ b/zh/python-net/working-with-facades/form/reading-form-values/get-required-field-names/_index.md @@ -0,0 +1,41 @@ +--- +title: 获取必填字段名称 +type: docs +weight: 30 +url: /zh/python-net/get-required-field-names/ +description: 本示例演示如何使用 Aspose.PDF Facades API 在 PDF 文档中识别并检索必填表单字段的名称。 +lastmod: "2026-06-08" +--- + +PDF 表单可能包含用户在提交前必须填写的强制性字段。这些字段通常在表单属性中标记为必填。 + +1. 创建 Form 对象。 +1. 绑定 PDF 文档。 +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/zh/python-net/working-with-facades/form/reading-form-values/get-rich-text-values/_index.md b/zh/python-net/working-with-facades/form/reading-form-values/get-rich-text-values/_index.md new file mode 100644 index 0000000000..5d8696acfa --- /dev/null +++ b/zh/python-net/working-with-facades/form/reading-form-values/get-rich-text-values/_index.md @@ -0,0 +1,42 @@ +--- +title: 获取富文本值 +type: docs +weight: 40 +url: /zh/python-net/get-rich-text-values/ +description: 本节介绍如何使用 Aspose.PDF Facades API 检索 PDF 文档中表单字段的富文本内容。与普通文本字段不同,富文本字段可以包含诸如粗体文字、不同字体、颜色以及段落样式等格式化内容。 +lastmod: "2026-06-08" +--- + +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 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/zh/python-net/working-with-facades/form/reading-form-values/resolve-full-field-names/_index.md b/zh/python-net/working-with-facades/form/reading-form-values/resolve-full-field-names/_index.md new file mode 100644 index 0000000000..ae9606edd2 --- /dev/null +++ b/zh/python-net/working-with-facades/form/reading-form-values/resolve-full-field-names/_index.md @@ -0,0 +1,42 @@ +--- +title: 解析完整字段名称 +type: docs +weight: 60 +url: /zh/python-net/resolve-full-field-names/ +description: 本示例演示如何使用 Aspose.PDF Facades API 检索 PDF 文档中表单字段的完全限定名称。 +lastmod: "2026-06-08" +--- + +在 PDF 表单中,字段可以按层次结构组织,尤其是使用子表单时。每个字段都有一个短名称和一个完全限定名称。完全限定名称表示字段在表单层次结构中的完整路径,许多用于操作或读取表单数据的 API 方法都需要此名称。 + +1. 创建 Form 对象。 +1. 绑定 PDF 文档。 +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/zh/python-net/working-with-facades/formeditor/_index.md b/zh/python-net/working-with-facades/formeditor/_index.md new file mode 100644 index 0000000000..3cc46ef51e --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/_index.md @@ -0,0 +1,25 @@ +--- +title: FormEditor 类 +type: docs +weight: 100 +url: /zh/python-net/formeditor-class/ +description: 了解如何在 Aspose.PDF for Python via .NET 中使用 FormEditor 类来创建表单字段、修改现有字段、定制字段外观以及添加脚本或提交操作。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 FormEditor 类在 Python 中创建和编辑 PDF 表单字段 +Abstract: 本节说明如何在 Aspose.PDF for Python via .NET 中使用 FormEditor 外观来构建和更新交互式 PDF 表单。了解如何以编程方式创建表单字段、定制字段外观、修改现有字段以及添加脚本或提交操作。 +--- + +这 `FormEditor` Aspose.PDF Facades 中的类旨在创建和更新交互式 PDF 表单字段。它帮助您构建表单结构,调整字段属性,修改外观设置,并在 Python 应用程序中附加诸如脚本和提交操作等交互行为。 + +## 常见 FormEditor 任务 + +使用以下教程来使用主要功能 `FormEditor` 外观: + +- [添加脚本和提交操作](/pdf/zh/python-net/adding-scripts-and-submit-actions/) +- [自定义字段外观](/pdf/zh/python-net/customizing-field-appearance/) +- [修改 Form 字段](/pdf/zh/python-net/modifying-form-fields/) +- [创建表单字段](/pdf/zh/python-net/creating-form-field) diff --git a/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md b/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md new file mode 100644 index 0000000000..87d5512319 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/_index.md @@ -0,0 +1,21 @@ +--- +title: 添加脚本和提交操作 +type: docs +weight: 40 +url: /zh/python-net/adding-scripts-and-submit-actions/ +description: 使用 Aspose.PDF for Python,开发人员可以自动执行这些操作,而无需手动编辑 PDF。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中添加和管理 PDF 表单字段脚本和提交操作 +Abstract: 了解如何以编程方式为 PDF 表单字段添加、修改或删除 JavaScript 操作,并使用 Aspose.PDF for Python 配置提交 URL。本指南解释了如何将脚本附加到字段、更新现有脚本、删除字段操作以及设置表单提交的 URL,从而实现动态交互式 PDF 表单。 +--- + +- [添加字段脚本](/pdf/zh/python-net/add-field-script/) +- [设置字段脚本](/pdf/zh/python-net/set-field-script/) +- [删除字段操作](/pdf/zh/python-net/remove-field-action/) +- [设置提交 Url](/pdf/zh/python-net/set-submit-url/) +- [设置提交标志](/pdf/zh/python-net/set-submit-flag/) + diff --git a/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md b/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md new file mode 100644 index 0000000000..7140277840 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/add-field-script/_index.md @@ -0,0 +1,56 @@ +--- +title: 添加字段脚本 +type: docs +weight: 10 +url: /zh/python-net/add-field-script/ +description: 交互式 PDF 表单可以包含 JavaScript,以在用户与表单字段交互时自动执行操作。使用 Aspose.PDF for Python,开发者可以轻松地将脚本附加到表单元素,如按钮或文本字段。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 为 PDF 表单字段添加 JavaScript 操作 +Abstract: 本文说明了如何打开 PDF 表单、将 JavaScript 代码分配给特定表单字段、追加其他脚本操作并保存更新后的文档。示例使用来自 Aspose.PDF Facades API 的 FormEditor 类,以编程方式操作表单行为。 +--- + +## 使用 Python 为 PDF 表单字段添加 JavaScript 操作 + +此代码片段使您能够使用 Aspose.PDF for Python 库向现有 PDF 表单字段添加 JavaScript 操作。它打开一个 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/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md b/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md new file mode 100644 index 0000000000..bf6277a5fc --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/remove-field-action/_index.md @@ -0,0 +1,50 @@ +--- +title: 删除字段操作 +type: docs +weight: 20 +url: /zh/python-net/remove-field-action/ +description: 从表单字段中删除 JavaScript 在修改交互式 PDF 表单、禁用先前分配的操作或清理包含不必要脚本的文档时可能有用。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 删除 PDF 表单字段中的 JavaScript 操作 +Abstract: 使用 Aspose.PDF for Python,开发者可以以编程方式移除附加在表单字段上的 JavaScript 操作。本文说明了如何打开现有的 PDF 表单、使用 FormEditor 类删除特定字段关联的脚本、验证该操作并保存修改后的文档。 +--- + +PDF 表单通常包含在用户与按钮或输入字段等表单元素交互时执行的 JavaScript 操作。在某些情况下,需要移除这些脚本以简化表单行为、提升安全性或更新表单逻辑。使用 Aspose.PDF for Python 从 PDF 文档的表单字段中删除 JavaScript 操作。代码打开现有的 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/),您可以从现有的 PDF 表单中的特定字段删除 JavaScript 操作: + +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/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md b/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md new file mode 100644 index 0000000000..aadd3b726f --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-field-script/_index.md @@ -0,0 +1,59 @@ +--- +title: 设置字段脚本 +type: docs +weight: 30 +url: /zh/python-net/set-field-script/ +description: 此代码片段演示了如何使用 Aspose.PDF for Python 将 JavaScript 操作分配给 PDF 文档中的表单字段。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 为 PDF 表单字段设置 JavaScript 操作 +Abstract: 本文说明了如何打开 PDF 文档、将 JavaScript 代码分配给表单字段、使用 FormEditor 类更新脚本并保存修改后的文件。示例演示了如何覆盖已有脚本以修改表单字段的行为。 +--- + +交互式 PDF 表单通常依赖 JavaScript 来执行诸如显示警报、验证输入或触发动态表单行为等任务。使用 Aspose.PDF for Python,开发者可以以编程方式管理这些脚本。 + +示例首先向字段添加一个 JavaScript 操作,然后使用 \u0027set_field_script\u0027 方法将其替换为另一个脚本。此方法允许开发者控制或更新 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/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md b/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md new file mode 100644 index 0000000000..d635def17e --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-flag/_index.md @@ -0,0 +1,46 @@ +--- +title: 设置提交标志 +type: docs +weight: 50 +url: /zh/python-net/set-submit-flag/ +description: 了解如何使用 Aspose.PDF for Python 以编程方式为 PDF 表单按钮设置提交标志。这样当用户点击按钮时,可将表单数据以特定格式(例如 XFDF)提交。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python 为 PDF 表单按钮设置提交标志 +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/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md b/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md new file mode 100644 index 0000000000..3a4e1664b8 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/adding-scripts-and-submit-actions/set-submit-url/_index.md @@ -0,0 +1,56 @@ +--- +title: 设置提交 Url +type: docs +weight: 40 +url: /zh/python-net/set-submit-url/ +description: 此示例演示如何使用 Aspose.PDF for Python 在 PDF 表单中为按钮字段配置提交操作。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 为 PDF 表单按钮设置提交 Url +Abstract: 本文说明了如何打开现有的 PDF 表单,使用 FormEditor 类为按钮字段定义提交 Url,验证操作是否成功,并保存更新后的 PDF 文档。 +--- + +PDF 表单可以设计为在用户点击提交按钮时将数据提交到 Web 服务器。使用 Aspose.PDF for Python,开发人员可以以编程方式为表单字段配置提交操作。 +通过设置提交 Url,表单可以在按钮被点击时将用户输入的数据发送到服务器。此功能在 PDF 表单必须向 Web 应用程序、数据库或处理服务提交信息的工作流中非常有用。 + +使用 [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/) 模块中,开发者可以以编程方式为现有 PDF 表单中的按钮字段分配提交 URL。 + +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/zh/python-net/working-with-facades/formeditor/creating-form-field/_index.md b/zh/python-net/working-with-facades/formeditor/creating-form-field/_index.md new file mode 100644 index 0000000000..be433aac7e --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/creating-form-field/_index.md @@ -0,0 +1,21 @@ +--- +title: 创建表单字段 +type: docs +weight: 50 +url: /zh/python-net/creating-form-field/ +description: 本文演示了如何使用 Aspose.PDF for Python 在 PDF 文档中创建交互式表单字段。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中创建 PDF 表单字段 +Abstract: PDF 表单使用户能够直接在文档中输入或选择数据。使用 Aspose.PDF,开发者可以以编程方式创建各种表单字段——CheckBox 用于布尔选择,ComboBox 用于下拉列表,ListBox 用于多选列表,RadioButton 用于唯一选项,TextBox 用于文本输入,SubmitButton 用于发送表单数据。这种统一的方法简化了交互式 PDF 的创建,确保准确的定位、一致的样式,以及与自动化处理和用户输入处理的兼容性。 +--- + +- [创建复选框字段](/pdf/zh/python-net/create-checkbox-field/) +- [创建 ComboBox 字段](/pdf/zh/python-net/create-combobox-field/) +- [创建 ListBox 字段](/pdf/zh/python-net/create-listbox-field/) +- [创建单选按钮字段](/pdf/zh/python-net/create-radiobutton-field/) +- [创建提交按钮](/pdf/zh/python-net/create-submit-button/) +- [创建 TextBox 字段](/pdf/zh/python-net/create-textbox-field/) \ No newline at end of file diff --git a/zh/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md b/zh/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md new file mode 100644 index 0000000000..93e06c1384 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/creating-form-field/create-checkbox-field/_index.md @@ -0,0 +1,54 @@ +--- +title: 创建复选框字段 +type: docs +weight: 10 +url: /zh/python-net/create-checkbox-field/ +description: 了解如何使用 Aspose.PDF for Python 以编程方式向 PDF 文档添加复选框表单字段。本指南演示如何使用 FormEditor 类将交互式复选框插入现有 PDF 文件并保存更新后的文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python 在 PDF 中创建复选框字段 +Abstract: 交互式表单字段允许用户在 PDF 文档中进行数字化填写和交互。在本教程中,您将学习如何使用 Aspose.PDF Python API 向 PDF 添加复选框字段。示例展示了如何绑定现有 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/zh/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md b/zh/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md new file mode 100644 index 0000000000..f59231a365 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/creating-form-field/create-combobox-field/_index.md @@ -0,0 +1,49 @@ +--- +title: 创建 ComboBox 字段 +type: docs +weight: 20 +url: /zh/python-net/create-combobox-field/ +description: 了解如何使用 Aspose.PDF for Python 以编程方式向 PDF 文档添加 ComboBox(下拉列表)字段。本示例演示如何插入 ComboBox 表单字段、添加可选择项,并保存更新后的 PDF 文件。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python 在 PDF 中创建 ComboBox 字段 +Abstract: 交互式表单字段使 PDF 更加动态且用户友好。ComboBox 字段允许用户从预定义的下拉列表中选择一个选项。在本教程中,您将学习如何使用 Aspose.PDF for Python 中的 FormEditor 类在 PDF 中创建 ComboBox,填充选项,并保存修改后的文档。 +--- + +PDF 表单广泛用于在数字文档(如申请表、调查问卷和注册表)中收集结构化信息。ComboBox 字段提供了一种方便的方式,让用户从预定义值列表中选择,同时保持表单紧凑有序。 + +这 [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) 该类允许您创建和管理不同类型的字段,包括文本框、复选框、单选按钮和下拉列表。 + +1. 加载现有的 PDF 文档。 +1. 使用 'add_field()' 方法和 'FieldType.COMBO_BOX' 参数添加 ComboBox 字段。 +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/zh/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md b/zh/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md new file mode 100644 index 0000000000..70afbf2a53 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/creating-form-field/create-listbox-field/_index.md @@ -0,0 +1,49 @@ +--- +title: 创建 ListBox 字段 +type: docs +weight: 30 +url: /zh/python-net/create-listbox-field/ +description: 了解如何使用 Aspose.PDF for Python 以编程方式向 PDF 文档添加 ListBox 表单字段。本指南展示了如何插入 ListBox 字段、定义可选项,并保存更新后的 PDF 文件。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python 在 PDF 中创建 ListBox 字段 +Abstract: PDF 表单允许用户通过选择选项、输入数据以及数字方式提交信息来与文档交互。ListBox 字段让用户能够从可见的选项列表中选择一个或多个值。在本教程中,您将学习如何使用 Aspose.PDF for Python 的 FormEditor 类在 PDF 中创建 ListBox 字段,并使用预定义的项目进行填充。 +--- + +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/zh/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md b/zh/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md new file mode 100644 index 0000000000..bb91971497 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/creating-form-field/create-radiobutton-field/_index.md @@ -0,0 +1,49 @@ +--- +title: 创建单选按钮字段 +type: docs +weight: 40 +url: /zh/python-net/create-radiobutton-field/ +description: 了解如何使用 Aspose.PDF for Python 以编程方式向 PDF 文档添加单选按钮表单字段。此示例演示如何创建单选按钮组、定义可选项并保存更新后的 PDF 文件。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python 在 PDF 中创建单选按钮字段 +Abstract: 单选按钮通常用于 PDF 表单中,以便用户从预定义的选项组中选择一个选项。在本教程中,您将学习如何使用 Aspose.PDF for Python 中的 FormEditor 类在 PDF 中创建单选按钮字段。示例展示了如何定义单选按钮项、设置默认选择以及保存更新后的文档。 +--- + +交互式 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/zh/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md b/zh/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md new file mode 100644 index 0000000000..de0de6b43c --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/creating-form-field/create-submit-button/_index.md @@ -0,0 +1,54 @@ +--- +title: 创建提交按钮 +type: docs +weight: 50 +url: /zh/python-net/create-submit-button/ +description: 了解如何使用 Aspose.PDF for Python 以编程方式向 PDF 文档添加提交按钮。本教程演示如何创建一个将表单数据提交到指定 URL 并保存更新后 PDF 的按钮。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python 在 PDF 中创建提交按钮 +Abstract: PDF 表单中的提交按钮允许用户将表单数据直接发送到服务器或端点。在本指南中,您将学习如何使用 Aspose.PDF for Python 中的 FormEditor 类向 PDF 添加提交按钮字段。示例展示了如何配置按钮的名称、标签、目标 URL 和位置,随后保存更新后的 PDF 文档。 +--- + +交互式 PDF 表单通常需要用户提交其输入以进行处理,例如发送调查结果、申请表或反馈数据。提交按钮字段通过将按钮链接到网络端点来提供此功能。 + +这 [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) 类允许添加按钮、复选框、单选按钮、文本字段和其他表单控件。 + +1. 加载现有的 PDF 文档。 +1. 在特定页面添加一个提交按钮字段。 +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/zh/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md b/zh/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md new file mode 100644 index 0000000000..d52c01d7b0 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/creating-form-field/create-textbox-field/_index.md @@ -0,0 +1,50 @@ +--- +title: 创建 TextBox 字段 +type: docs +weight: 60 +url: /zh/python-net/create-textbox-field/ +description: 了解如何使用 Aspose.PDF for Python 以编程方式向 PDF 文档添加 TextBox 字段。本教程展示了如何插入多个文本字段、设置默认值以及保存更新后的 PDF 文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python 在 PDF 中创建 TextBox 字段 +Abstract: PDF 表单中的 TextBox 字段允许用户输入和编辑文本,使文档具备交互性且友好易用。在本教程中,您将学习如何使用 Aspose.PDF for Python 中的 FormEditor 类在 PDF 中创建 TextBox 表单字段。示例演示了添加多个字段、指定默认值以及保存已修改的 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/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md b/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md new file mode 100644 index 0000000000..41a657f9cf --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/_index.md @@ -0,0 +1,23 @@ +--- +title: 自定义字段外观 +type: docs +weight: 30 +url: /zh/python-net/customizing-field-appearance/ +description: 使用 Aspose.PDF for Python,开发人员可以通过编程方式完全自定义字段的外观和行为。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中自定义 PDF 表单字段外观 - 对齐、颜色、限制和属性 +Abstract: 了解如何使用 Aspose.PDF for Python 自定义 PDF 表单字段的外观和行为。本指南涵盖使用颜色和边框装饰字段、设置水平和垂直对齐、控制可见性、调整字段属性、设置组合数字和字符限制以及检索字段外观信息。这些技术帮助开发人员创建视觉上统一且用户友好的 PDF 表单。 +--- + +- [装饰字段](/pdf/zh/python-net/decorate-field/) +- [设置字段对齐](/pdf/zh/python-net/set-field-alignment/) +- [设置字段垂直对齐](/pdf/zh/python-net/set-field-alignment-vertical/) +- [设置字段外观](/pdf/zh/python-net/set-field-appearance/) +- [设置字段组合号码](/pdf/zh/python-net/set-field-comb-number/) +- [设置字段限制](/pdf/zh/python-net/set-field-limit/) +- [获取字段外观](/pdf/zh/python-net/get-field-appearance/) + diff --git a/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md b/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md new file mode 100644 index 0000000000..5f8cec44b8 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/decorate-field/_index.md @@ -0,0 +1,55 @@ +--- +title: 装饰字段 +type: docs +weight: 10 +url: /zh/python-net/decorate-field/ +description: 本例演示了如何使用 Aspose.PDF for Python 自定义 PDF 文档中表单字段的外观。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 为 PDF 表单字段装饰自定义颜色和对齐方式 +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/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md b/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md new file mode 100644 index 0000000000..20cb811969 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/get-field-appearance/_index.md @@ -0,0 +1,45 @@ +--- +title: 获取字段外观 +type: docs +weight: 20 +url: /zh/python-net/get-field-appearance/ +description: 这篇文章解释了如何打开 PDF,访问表单字段,检索其外观设置并显示它们。示例演示了检索名为 "Last Name" 的字段的外观。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 检索 PDF 表单字段外观 +Abstract: 该示例演示了如何使用 Aspose.PDF for Python 检索 PDF 文档中表单字段的可视外观属性。代码打开现有的 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/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md b/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md new file mode 100644 index 0000000000..e46abf5152 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment-vertical/_index.md @@ -0,0 +1,56 @@ +--- +title: 设置字段垂直对齐 +type: docs +weight: 40 +url: /zh/python-net/set-field-alignment-vertical/ +description: 本示例演示如何使用 Aspose.PDF for Python 在 PDF 文档中设置表单字段的垂直对齐方式。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 设置 PDF 表单字段的垂直对齐 +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/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md b/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md new file mode 100644 index 0000000000..c0c43398db --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-alignment/_index.md @@ -0,0 +1,55 @@ +--- +title: 设置字段对齐 +type: docs +weight: 30 +url: /zh/python-net/set-field-alignment/ +description: 本示例演示了如何使用 Aspose.PDF for Python 在 PDF 文档中设置表单字段的文本对齐方式。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 设置 PDF 表单字段的文本对齐 +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/) constants,允许开发者以编程方式修改现有表单字段的对齐方式。 + +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/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md b/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md new file mode 100644 index 0000000000..e91c2c03d0 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-appearance/_index.md @@ -0,0 +1,55 @@ +--- +title: 设置字段外观 +type: docs +weight: 50 +url: /zh/python-net/set-field-appearance/ +description: 本示例演示如何使用 Aspose.PDF for Python 更改 PDF 表单字段的视觉外观。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 设置 PDF 表单字段外观 +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/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md b/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md new file mode 100644 index 0000000000..1f696d230c --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-comb-number/_index.md @@ -0,0 +1,50 @@ +--- +title: 设置字段组合号码 +type: docs +weight: 70 +url: /zh/python-net/set-field-comb-number/ +description: 本示例演示如何使用 Aspose.PDF for Python 为 PDF 表单字段设置组合号码。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 为 PDF 表单字段设置组合号码 +Abstract: 使用 Aspose.PDF for Python,开发人员可以以编程方式设置表单字段的盒子数量(组合号码),以强制固定长度输入。本文演示了为名为 "PIN" 的字段设置组合号码。 +--- + +组合号码定义了字段内容如何被拆分为等间距的盒子,常用于 PIN 码、序列号或其他固定长度的输入字段。代码打开现有 PDF,为字段设置组合号码,并保存修改后的文档。 + +这 [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) 该类提供了 'set_field_comb_number' 方法,用于定义表单字段中盒子(字符)的数量。 + +1. 打开现有的 PDF 表单。 +1. 创建一个 FormEditor 对象。 +1. 将名为 "PIN" 的字段的 comb number 设置为 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/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md b/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md new file mode 100644 index 0000000000..596f6f87a7 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/customizing-field-appearance/set-field-limit/_index.md @@ -0,0 +1,53 @@ +--- +title: 设置字段限制 +type: docs +weight: 80 +url: /zh/python-net/set-field-limit/ +description: 本示例展示了如何使用 Aspose.PDF for Python 为 PDF 文档中的表单字段设置最大字符限制。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 为 PDF 表单字段设置最大字符限制 +Abstract: 本示例演示了为名为 "Last Name" 的字段设置 10 个字符的字符限制,确保用户不能输入超过指定的限制。 +--- + +PDF 文档中的表单字段可能需要输入限制以保持正确的格式。使用 Aspose.PDF for Python,开发者可以以编程方式为字段设置最大字符数。 + +这 [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) class 提供了 '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/zh/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md new file mode 100644 index 0000000000..26c3984041 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/_index.md @@ -0,0 +1,24 @@ +--- +title: 修改 Form 字段 +type: docs +weight: 20 +url: /zh/python-net/modifying-form-fields/ +description: 使用 Aspose.PDF for Python,您可以通过 FormEditor 类以编程方式高效地修改 Form 字段。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中修改 PDF Form 字段 - 添加、移动、复制、重命名和删除字段 +Abstract: 了解如何使用 Aspose.PDF for Python 修改现有 PDF Form 字段。本指南解释了如何通过添加或删除列表项、移动字段、删除或重命名字段、将单行字段转换为多行以及在文档内部或之间复制字段来管理 Form 元素。这些技术帮助开发人员动态更新 PDF Form,并在无需重新创建整个表单结构的情况下,适应不断变化的业务需求。 +--- + +- [添加列表项](/pdf/zh/python-net/add-list-item/) +- [删除列表项](/pdf/zh/python-net/del-list-item/) +- [移动字段](/pdf/zh/python-net/move-field/) +- [删除字段](/pdf/zh/python-net/remove-field/) +- [重命名字段](/pdf/zh/python-net/rename-field/) +- [单个 到 多个](/pdf/zh/python-net/single-to-multiple/) +- [复制内部字段](/pdf/zh/python-net/copy-inner-field/) +- [复制外部字段](/pdf/zh/python-net/copy-outer-field/) + diff --git a/zh/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md new file mode 100644 index 0000000000..215568f13c --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/add-list-item/_index.md @@ -0,0 +1,45 @@ +--- +title: 添加列表项 +type: docs +weight: 10 +url: /zh/python-net/add-list-item/ +description: 本示例演示了如何使用 Aspose.PDF for Python 在 PDF 文档中向列表框表单字段添加项目。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 向 PDF 列表框字段添加项目 +Abstract: 本文展示了如何打开 PDF 文档,向名为 "Country" 的列表框字段追加项目,并保存更新后的文档。 +--- + +PDF 中的列表框字段允许用户从预定义集合中选择一个或多个选项。使用 Aspose.PDF for Python,开发者可以以编程方式向这些字段添加新项目。The [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/zh/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md new file mode 100644 index 0000000000..62a1f96df4 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/copy-inner-field/_index.md @@ -0,0 +1,71 @@ +--- +title: 复制内部字段 +type: docs +weight: 20 +url: /zh/python-net/copy-inner-field/ +description: 使用 Python(通过 Aspose.PDF for Python)将 PDF 表单字段复制到新位置。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 将 PDF 表单字段复制到新位置 +Abstract: 本示例演示了如何使用 Aspose.PDF for Python 将 PDF 文档中现有的表单字段复制到新位置。代码打开 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’ 字段复制到第 2 页坐标为 (200, 600) 的新字段 ‘First Name Copy’。 +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/zh/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md new file mode 100644 index 0000000000..4a874066c9 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/copy-outer-field/_index.md @@ -0,0 +1,79 @@ +--- +title: 复制外部字段 +type: docs +weight: 30 +url: /zh/python-net/copy-outer-field/ +description: 此示例演示如何使用 Aspose.PDF for Python 将表单字段从一个 PDF 文档复制到另一个 PDF 文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 从另一个文档复制 PDF 表单字段 +Abstract: 本文解释了如何创建一个新的 PDF 文档,将源 PDF 中的 "First Name" 字段复制到第 1 页的坐标 (200, 600) 处,并保存更新后的目标文档。 +--- + +有时,PDF 表单需要在文档之间复用字段。使用 Aspose.PDF for Python,开发者可以通过编程方式将表单字段从源 PDF 复制到目标 PDF。 + +这 [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) 类提供了 \u0027copy_outer_field\u0027 方法,该方法将在指定页面和坐标处将字段从源文档复制到目标文档。 + +代码创建一个新的 PDF(目标),添加一个页面,然后将现有 PDF(源)中的字段复制到目标文档的指定坐标处。 + +1. 创建一个新的目标 PDF 文档。 +1. 至少向目标 PDF 添加一页。 +1. 保存空的目标文档。 +1. 创建一个 FormEditor 对象并将其绑定到目标 PDF。 +1. 将源 PDF 中的 'First Name' 字段复制到第 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/zh/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md new file mode 100644 index 0000000000..be4f38f8c0 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/del-list-item/_index.md @@ -0,0 +1,50 @@ +--- +title: 删除列表项 +type: docs +weight: 40 +url: /zh/python-net/del-list-item/ +description: +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 从 PDF 列表框字段中移除项目 +Abstract: 此示例演示如何使用 Aspose.PDF for Python 从 PDF 文档中的列表框表单字段中移除项目。代码打开现有 PDF,删除列表框字段中的特定项目,并保存更新后的文档。 +--- + +PDF 中的列表框字段允许用户选择一个或多个预定义选项。使用 Aspose.PDF for Python,开发人员可以以编程方式从这些字段中移除项目。 + +本文说明如何删除名为“Country”的列表框字段中的 ‘UK’ 项,确保该字段仅包含所需的选项。 + +这 [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/zh/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md new file mode 100644 index 0000000000..bdf818c7ad --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/move-field/_index.md @@ -0,0 +1,47 @@ +--- +title: 移动字段 +type: docs +weight: 50 +url: /zh/python-net/move-field/ +description: 将现有表单字段移动到 PDF 文档中的其他位置。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 将 PDF 表单字段移动到新位置 +Abstract: 此示例演示如何使用 Aspose.PDF for Python 将现有表单字段移动到 PDF 文档中的其他位置。代码打开现有的 PDF,将指定的表单字段重新定位到新的坐标,并保存更新后的文档。 +--- + +PDF 表单在创建后常常需要进行布局调整。使用 Aspose.PDF for Python,开发人员可以在不重新创建表单字段的情况下将其移动到新位置。 + +此示例展示了如何通过指定其在页面中的新坐标来重新定位 “Country” 字段。The [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/zh/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md new file mode 100644 index 0000000000..5039a8a4ad --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/remove-field/_index.md @@ -0,0 +1,47 @@ +--- +title: 删除字段 +type: docs +weight: 60 +url: /zh/python-net/remove-field/ +description: 此示例演示如何使用 'FormEditor' 类的 'remove_field' 方法从 PDF 表单中删除 'Country' 字段。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 从 PDF 文档中删除表单字段 +Abstract: 此示例演示如何使用 Aspose.PDF for Python 从 PDF 文档中删除现有的表单字段。代码加载 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/zh/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md new file mode 100644 index 0000000000..cf58be6db6 --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/rename-field/_index.md @@ -0,0 +1,48 @@ +--- +title: 重命名字段 +type: docs +weight: 70 +url: /zh/python-net/rename-field/ +description: 使用 Aspose.PDF for Python 重命名 PDF 文档中的现有表单字段。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 重命名 PDF 表单字段 +Abstract: 本示例演示了如何使用 Aspose.PDF for Python 重命名 PDF 文档中的现有表单字段。代码打开一个输入 PDF,使用 FormEditor 类更改指定表单字段的名称,并保存更新后的文档。 +--- + +PDF 表单通常依赖字段名称进行脚本编写、自动化和数据处理。使用 Aspose.PDF for Python,开发人员可以在不重新创建字段或更改表单布局的情况下重命名现有字段。 + +这 [FormEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/formeditor/) class 提供了 '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/zh/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md new file mode 100644 index 0000000000..3c12adaf5d --- /dev/null +++ b/zh/python-net/working-with-facades/formeditor/modifying-form-fields/single-to-multiple/_index.md @@ -0,0 +1,48 @@ +--- +title: 单行字段转换为多行字段 +type: docs +weight: 80 +url: /zh/python-net/single-to-multiple/ +description: 使用 Aspose.PDF for Python 将 PDF 文档中的单行文本字段转换为多行字段。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 将 PDF 中的单行文本字段转换为多行字段 +Abstract: 本示例演示如何使用 Aspose.PDF for Python 将 PDF 文档中的单行文本字段转换为多行字段。代码加载现有的 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/zh/python-net/working-with-facades/pdfannotationeditor/_index.md b/zh/python-net/working-with-facades/pdfannotationeditor/_index.md new file mode 100644 index 0000000000..a4ecbc4434 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfannotationeditor/_index.md @@ -0,0 +1,21 @@ +--- +title: PdfAnnotationEditor 类 +type: docs +weight: 40 +url: /zh/python-net/pdfannotationeditor-class/ +description: 了解如何在 Aspose.PDF for Python via .NET 中使用 PdfAnnotationEditor 类,以编程方式处理 PDF 注释、评论和标记。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfAnnotationEditor 在 Python 中编辑 PDF 注释和评论 +Abstract: 本节介绍了 Aspose.PDF for Python via .NET 中的 PdfAnnotationEditor 类,用于与注释相关的 PDF 工作流。使用此外观在 Python 应用程序中处理现有文档时,能够以编程方式管理 PDF 注释、评论和标记。 +--- + +这 `PdfAnnotationEditor` Aspose.PDF Facades 中的类旨在处理 PDF 注释和基于评论的标记,而无需手动编辑文档的低层结构。它在 Python via .NET 环境下提供了一种简化的方式来处理注释工作流,适用于需要检查或更新现有 PDF 文件的情况。 + +## PdfAnnotationEditor 的用途是什么 + +当您的 PDF 工作流涉及注释、审阅评论或其他需要以编程方式管理的标记元素时,请使用此外观。随着本节的扩展,它应该作为围绕该主题构建的注释相关教程的着陆页。 `PdfAnnotationEditor` 类。 + diff --git a/zh/python-net/working-with-facades/pdfcontenteditor/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/_index.md new file mode 100644 index 0000000000..9b75cf90a7 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/_index.md @@ -0,0 +1,31 @@ +--- +title: PdfContentEditor 类 +type: docs +weight: 30 +url: /zh/python-net/pdfcontenteditor-class/ +description: 了解如何在 Aspose.PDF for Python via .NET 中使用 PdfContentEditor 类来编辑 PDF 内容、管理注释和附件、处理链接、图像、文本、多媒体、印章以及查看器首选项。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中编辑 PDF 内容和交互元素 +Abstract: 本节说明如何在 Aspose.PDF for Python via .NET 中使用 PdfContentEditor 类进行内容级别的 PDF 工作流。了解如何以编程方式管理注释、附件、文档操作、绘图标记、图像、链接、多媒体、印章、文本替换以及查看器首选项。 +--- + +这 `PdfContentEditor` Aspose.PDF Facades 中的类旨在对现有 PDF 文档进行内容级编辑任务。它提供了简化的 API,用于更新交互式元素、替换文本、处理附件和链接,以及在 Python via .NET 应用程序中调整文档行为。 + +## 使用 PdfContentEditor 可以做什么 + +使用此部分来探索 PDF 内容编辑支持的主要领域 `PdfContentEditor` 外观: + +- [使用 PdfContentEditor 处理注释](/pdf/zh/python-net/annotations/) +- [使用 PdfContentEditor 管理 PDF 附件](/pdf/zh/python-net/attachments/) +- [使用 PdfContentEditor 配置文档操作](/pdf/zh/python-net/document-actions/) +- [使用 PdfContentEditor 添加绘图注释](/pdf/zh/python-net/drawing-annotations/) +- [使用 PdfContentEditor 执行图像操作](/pdf/zh/python-net/image-operations/) +- [使用 PdfContentEditor 处理链接和导航](/pdf/zh/python-net/links-and-navigation/) +- [使用 PdfContentEditor 添加或管理多媒体内容](/pdf/zh/python-net/multimedia/) +- [使用 PdfContentEditor 管理 PDF 印章](/pdf/zh/python-net/stamps-management/) +- [使用 PdfContentEditor 替换和更新文本](/pdf/zh/python-net/text-operations/) +- [使用 PdfContentEditor 更改查看器首选项](/pdf/zh/python-net/viewer-preferences/) diff --git a/zh/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md new file mode 100644 index 0000000000..e136f255ac --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/annotations/_index.md @@ -0,0 +1,17 @@ +--- +title: 注释 +type: docs +weight: 10 +url: /zh/python-net/annotations-facades/ +description: +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [添加文本注释](/pdf/zh/python-net/add-text-annotation/) +- [添加自由文本批注](/pdf/zh/python-net/add-free-text-annotation/) +- [添加标记注释](/pdf/zh/python-net/add-markup-annotation/) +- [添加弹出注释](/pdf/zh/python-net/add-popup-annotation/) +- [添加插入符号注释](/pdf/zh/python-net/add-caret-annotation/) diff --git a/zh/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md new file mode 100644 index 0000000000..a022ea3c7f --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/annotations/add-caret-annotation/_index.md @@ -0,0 +1,58 @@ +--- +title: 添加插入符号注释 +type: docs +weight: 10 +url: /zh/python-net/add-caret-annotation/ +description: 此示例加载现有的 PDF,在首页添加插入符号注释,并保存修改后的文档。该注释包含红色插入符号图案和描述性注释文字。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 向 PDF 添加插入符号注释 +Abstract: 此示例演示如何使用 Aspose.PDF for Python via the Facades API 向 PDF 文档添加插入符号注释。示例展示了如何绑定 PDF 文件、使用矩形定义注释位置、配置插入符号属性以及保存更新后的文档。 +--- + +插入符号注释通常用于指示文档中的文字插入或编辑性评论。使用 PdfContentEditor,您可以通过指定页码、注释边界、指示区、符号、备注文字和颜色,以编程方式添加插入符号注释。 + +1. 创建 [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) 对象。 +1. 绑定输入 PDF。 +1. 定义插入符号注释参数: + - 将添加注释的页码 + - 插入符号矩形(注释位置) + - 呼出矩形(文本区域) + - 符号(例如 "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/zh/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md new file mode 100644 index 0000000000..179fa05ff0 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/annotations/add-free-text-annotation/_index.md @@ -0,0 +1,47 @@ +--- +title: 添加自由文本批注 +type: docs +weight: 20 +url: /zh/python-net/add-free-text-annotation/ +description: 此示例加载现有的 PDF 文件,在指定位置向第一页添加自由文本批注,然后保存修改后的文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 向 PDF 添加自由文本批注 +Abstract: 此示例演示如何使用 Aspose.PDF for Python via the Facades API 在 PDF 文档中插入自由文本批注。它展示了如何绑定 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/zh/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md new file mode 100644 index 0000000000..17fb5dfdc1 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/annotations/add-markup-annotation/_index.md @@ -0,0 +1,72 @@ +--- +title: 添加标记注释 +type: docs +weight: 30 +url: /zh/python-net/add-markup-annotation/ +description: 此示例绑定一个输入 PDF,在首页添加四种不同的标记注释,并保存更新后的文档。每个注释展示了不同的标记样式和颜色。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 在 PDF 中添加高亮、下划线、删除线和波浪线标记注释 +Abstract: 此示例演示如何使用 Aspose.PDF for Python via the 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_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/zh/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md new file mode 100644 index 0000000000..e4a1ad03e0 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/annotations/add-popup-annotation/_index.md @@ -0,0 +1,50 @@ +--- +title: 添加弹出注释 +type: docs +weight: 40 +url: /zh/python-net/add-popup-annotation/ +description: 此示例加载 PDF,将弹出注释添加到首页,并保存修改后的文档。弹出注释默认设置为可见,并显示指定的评论文本。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 向 PDF 添加弹出注释 +Abstract: 此示例演示如何使用 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. 保存已更新的 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/zh/python-net/working-with-facades/pdfcontenteditor/annotations/add-text-annotation/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/annotations/add-text-annotation/_index.md new file mode 100644 index 0000000000..0650f6dced --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/annotations/add-text-annotation/_index.md @@ -0,0 +1,61 @@ +--- +title: 添加文本注释 +type: docs +weight: 50 +url: /zh/python-net/add-text-annotation/ +description: 使用 Aspose.PDF for Python via .NET 中的 PdfContentEditor 类向 PDF 文档添加文本批注。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中添加文本批注。 +Abstract: 了解如何使用 Aspose.PDF for Python via .NET 中的 PdfContentEditor 类向 PDF 文档添加文本批注。此示例展示了如何在特定位置放置文本批注,定义其标题和内容,并保存更新后的 PDF 文件。 +--- + +本文展示了如何使用 [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) Aspose.PDF 中的类。 + +文本批注允许您将评论、注释或额外信息附加到 PDF 页面上的特定位置。这些批注可以以图标形式出现,并在用户查看文档时展开。 + +在此示例中: + +- 将 PDF 文档加载到 PdfContentEditor 中。 +- 在页面的特定位置添加文本注释。 +- 该注释包括标题、内容、图标类型和可见性设置。 +- 修改后的文档保存为新文件。 + +1. 创建一个 PdfContentEditor 对象。 +1. 绑定输入 PDF 文档。 +1. 定义注释位置。 +1. 添加文本注释。 +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/zh/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md new file mode 100644 index 0000000000..98840d0aa6 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/attachments/_index.md @@ -0,0 +1,17 @@ +--- +title: 附件 +type: docs +weight: 20 +url: /zh/python-net/attachments-facades/ +description: +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [添加附件](/pdf/zh/python-net/add-attachment/) +- [从路径添加附件](/pdf/zh/python-net/add-attachment-from-path/) +- [添加文件附件注释](/pdf/zh/python-net/add-file-attachment-annotation/) +- [从流添加文件附件注释](/pdf/zh/python-net/add-file-attachment-annotation-from-stream/) +- [删除附件](/pdf/zh/python-net/remove-attachments/) diff --git a/zh/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment-from-path/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment-from-path/_index.md new file mode 100644 index 0000000000..69371a77ad --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment-from-path/_index.md @@ -0,0 +1,47 @@ +--- +title: 从路径添加附件 +type: docs +weight: 20 +url: /zh/python-net/add-attachment-from-path/ +description: 此示例绑定一个输入 PDF,使用文件路径附加外部文件,并将带有嵌入附件的修改后 PDF 保存。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中使用文件路径重载将文件附加到 PDF +Abstract: 此示例演示如何使用 Aspose.PDF for Python via the Facades API 中的 'add_document_attachment()' 的文件路径重载将外部文件附加到 PDF 文档。它简化了无需手动打开文件流即可添加附件的过程。 +--- + +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/zh/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment/_index.md new file mode 100644 index 0000000000..96471aa55b --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/attachments/add-attachment/_index.md @@ -0,0 +1,50 @@ +--- +title: 添加附件 +type: docs +weight: 10 +url: /zh/python-net/add-attachment/ +description: 此示例绑定一个输入 PDF,将外部文件附加到第一页,并将带有嵌入附件的修改后 PDF 保存。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 向 PDF 添加文件附件 +Abstract: 此示例演示如何使用 Aspose.PDF for Python via the Facades API 将外部文件附加到 PDF 文档。它展示了如何绑定 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/zh/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md new file mode 100644 index 0000000000..23d1c1aa4d --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/attachments/add-file-attachment-annotation/_index.md @@ -0,0 +1,51 @@ +--- +title: 添加文件附件注释 +type: docs +weight: 30 +url: /zh/python-net/add-file-attachment-annotation/ +description: 此示例绑定一个输入 PDF,使用文件路径在首页添加文件附件注释,并保存已更新的文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 向 PDF 添加文件附件注释 +Abstract: 此示例演示如何使用 Aspose.PDF for Python via the Facades API 通过文件路径在 PDF 中创建文件附件注释。它展示了如何定义注释位置、设置描述文本、选择图标类型以及保存修改后的文档。 +--- + +文件附件注释允许您将外部文件嵌入为 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/zh/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md new file mode 100644 index 0000000000..ec61347052 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/attachments/add_file-attachment-annotation-from-stream/_index.md @@ -0,0 +1,57 @@ +--- +title: 从流添加文件附件注释 +type: docs +weight: 40 +url: /zh/python-net/add-file-attachment-annotation-from-stream/ +description: 此示例加载 PDF,读取外部文件到内存流,在第一页添加文件附件注释,并保存修改后的文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中从流向 PDF 添加文件附件注释 +Abstract: 此示例演示如何使用文件流和 Aspose.PDF for Python via the Facades API 在 PDF 中创建文件附件注释。它展示了如何指定注释位置、设置描述、包含不透明度值,并保存修改后的文档。 +--- + +文件附件注释允许将文件嵌入为 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/zh/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md new file mode 100644 index 0000000000..eaf8361694 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/attachments/remove-attachments/_index.md @@ -0,0 +1,44 @@ +--- +title: 删除附件 +type: docs +weight: 50 +url: /zh/python-net/remove-attachments/ +description: 此示例绑定一个输入 PDF,删除所有附件,并将修改后的 PDF 保存为不包含任何嵌入文件的版本。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 删除 PDF 中的所有附件 +Abstract: 本示例演示了如何使用 Aspose.PDF for Python via the Facades API 从 PDF 文档中删除所有文件附件。它展示了如何绑定 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/zh/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md new file mode 100644 index 0000000000..ebffd6d1bf --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/document-actions/_index.md @@ -0,0 +1,15 @@ +--- +title: 文档操作 +type: docs +weight: 40 +url: /zh/python-net/document-actions/ +description: +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [添加书签操作](/pdf/zh/python-net/add-bookmark-action/) +- [添加文档操作](/pdf/zh/python-net/add-document-action/) +- [删除打开操作](/pdf/zh/python-net/remove-open-action/) \ No newline at end of file diff --git a/zh/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md new file mode 100644 index 0000000000..4c79fb0575 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/document-actions/add-bookmark-action/_index.md @@ -0,0 +1,52 @@ +--- +title: 添加书签操作 +type: docs +weight: 10 +url: /zh/python-net/add-bookmark-action/ +description: 此示例绑定一个输入 PDF,创建一个标签为 "PdfContentEditor Bookmark" 的书签,该书签导航至第 1 页,并保存更新后的文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 在 PDF 中创建带导航操作的书签 +Abstract: 此示例演示了如何使用 Aspose.PDF for Python via the Facades API 向 PDF 文档添加带有导航操作的书签。它展示了如何配置书签文本、外观以及将用户导向特定页面的操作。 +--- + +书签提供了在 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/zh/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md new file mode 100644 index 0000000000..b65271ff8d --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/document-actions/add-document-action/_index.md @@ -0,0 +1,46 @@ +--- +title: 添加文档操作 +type: docs +weight: 20 +url: /zh/python-net/add-document-action/ +description: 本示例添加了一个在打开 PDF 时出现的 JavaScript 警报。该脚本附加到文档打开事件,并在支持的 PDF 查看器中自动执行。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 向 PDF 添加文档打开 JavaScript 操作 +Abstract: 本示例演示了如何添加一个在打开 PDF 时触发的文档级 JavaScript 操作。使用 Aspose.PDF for Python via the Facades API,示例展示了如何绑定文档、分配打开事件操作并保存更新后的 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/zh/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md new file mode 100644 index 0000000000..6ada096ed6 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/document-actions/remove-open-action/_index.md @@ -0,0 +1,45 @@ +--- +title: 删除打开操作 +type: docs +weight: 30 +url: /zh/python-net/remove-open-action/ +description: 此示例加载现有 PDF,删除打开操作,并保存已清理的文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 从 PDF 中删除文档打开操作 +Abstract: 此示例演示如何使用 Aspose.PDF for Python 通过 Facades API 从 PDF 中删除文档打开操作。它展示了如何绑定 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/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md new file mode 100644 index 0000000000..01b2131d34 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/_index.md @@ -0,0 +1,18 @@ +--- +title: 绘图批注 +type: docs +weight: 50 +url: /zh/python-net/drawing-annotations/ +description: +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [添加线注释](/pdf/zh/python-net/add-line-annotation/) +- [添加方形注释](/pdf/zh/python-net/add-square-annotation/) +- [添加圆形注释](/pdf/zh/python-net/add-circle-annotation/) +- [添加多边形批注](/pdf/zh/python-net/add-polygon-annotation/) +- [添加折线注释](/pdf/zh/python-net/add-polyline-annotation/) +- [添加曲线注释](/pdf/zh/python-net/add-curve-annotation/) diff --git a/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md new file mode 100644 index 0000000000..06f8b02395 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-circle-annotation/_index.md @@ -0,0 +1,49 @@ +--- +title: 添加圆形注释 +type: docs +weight: 10 +url: /zh/python-net/add-circle-annotation/ +description: 此示例绑定输入 PDF,在首页创建一个圆形注释,并保存修改后的文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中向 PDF 添加圆形注释 +Abstract: 此示例演示如何使用 Aspose.PDF for Python via the Facades API 向 PDF 文档添加圆形注释。它展示了如何定义注释边界、设置内容文本、配置颜色和外观,并保存更新后的文档。 +--- + +圆形注释对于突出 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/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md new file mode 100644 index 0000000000..6028ee608a --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-curve-annotation/_index.md @@ -0,0 +1,55 @@ +--- +title: 添加曲线注释 +type: docs +weight: 20 +url: /zh/python-net/add-curve-annotation/ +description: 此示例绑定一个输入 PDF,在首页绘制虚线曲线,并保存修改后的文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中向 PDF 添加曲线注释 +Abstract: 此示例演示如何使用 Aspose.PDF for Python via the Facades API 向 PDF 文档添加曲线注释。它展示了如何定义曲线顶点、边框样式、注释边界、文本内容,并保存更新后的文档。 +--- + +曲线注释用于在 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/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md new file mode 100644 index 0000000000..85f61faa40 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-line-annotation/_index.md @@ -0,0 +1,62 @@ +--- +title: 添加线注释 +type: docs +weight: 30 +url: /zh/python-net/add-line-annotation/ +description: 此示例绑定输入 PDF,绘制带方形线端点的红色线注释,并保存修改后的 PDF。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中向 PDF 添加线注释 +Abstract: 此示例演示如何使用 Aspose.PDF for Python via the Facades API 向 PDF 文档添加线注释。它说明了如何定义线的起点和终点、矩形边界、外观属性,并保存更新后的文档。 +--- + +线注释对于强调文本、突出关系或吸引对 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/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md new file mode 100644 index 0000000000..5131368997 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polygon-annotation/_index.md @@ -0,0 +1,54 @@ +--- +title: 添加多边形批注 +type: docs +weight: 40 +url: /zh/python-net/add-polygon-annotation/ +description: 此示例绑定输入 PDF,在首页绘制实心多边形,并将带有注释的修改后文档保存。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中使用 PdfContentEditor 为 PDF 添加多边形注释 +Abstract: 此示例演示如何使用 Aspose.PDF for Python via the Facades API 向 PDF 文档添加多边形注释。它展示了如何定义多边形顶点、边框样式、注释边界、描述性文本,并保存更新后的文档。 +--- + +多边形注释用于突出显示 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_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/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md new file mode 100644 index 0000000000..fc8f201511 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-polyline-annotation/_index.md @@ -0,0 +1,54 @@ +--- +title: 添加折线注释 +type: docs +weight: 50 +url: /zh/python-net/add-polyline-annotation/ +description: 示例绑定一个输入 PDF,在第一页创建一个实心折线,并将带注释的修改后文档保存。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中向 PDF 添加折线注释 +Abstract: 本示例演示如何使用 Aspose.PDF for Python via the Facades API 向 PDF 文档添加折线注释。它展示了如何定义顶点序列、边框样式、注释矩形、文本,并保存更新后的文档。 +--- + +折线注释允许您在 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/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md new file mode 100644 index 0000000000..d25582e9ee --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/drawing-annotations/add-square-annotation/_index.md @@ -0,0 +1,49 @@ +--- +title: 添加方形注释 +type: docs +weight: 60 +url: /zh/python-net/add-square-annotation/ +description: 本示例绑定一个输入 PDF,在首页添加一个填充的蓝色方形批注,并保存修改后的文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中向 PDF 添加方形批注 +Abstract: 本示例演示如何使用 Aspose.PDF for Python via the Facades API 向 PDF 文档添加方形批注。它展示了如何定义批注矩形、文本内容、颜色、填充选项,并保存更新后的文档。 +--- + +方形批注通常用于突出显示感兴趣的区域、标记重要章节或在 PDF 文档中提供视觉提示。Using [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/zh/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md new file mode 100644 index 0000000000..44061285bf --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/image-operations/_index.md @@ -0,0 +1,15 @@ +--- +title: 图像操作 +type: docs +weight: 60 +url: /zh/python-net/image-operations/ +description: +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [在 PDF 中替换图像](/pdf/zh/python-net/replace-image/) +- [从 PDF 中删除图像](/pdf/zh/python-net/delete-images/) +- [从 PDF 中删除所有图像](/pdf/zh/python-net/delete-all-images/) \ No newline at end of file diff --git a/zh/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md new file mode 100644 index 0000000000..5d36af4ed0 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-all-images/_index.md @@ -0,0 +1,44 @@ +--- +title: 从 PDF 中删除所有图像 +type: docs +weight: 10 +url: /zh/python-net/delete-all-images/ +description: 使用 Aspose.PDF for Python 通过 Facades API 删除 PDF 文档中的所有图像。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中使用 PdfContentEditor 从 PDF 中删除所有图像 +Abstract: 本示例演示如何使用 Aspose.PDF for Python 通过 Facades API 删除 PDF 文档中的所有图像。它展示了如何绑定 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/zh/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md new file mode 100644 index 0000000000..06eb853fec --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/image-operations/delete-images/_index.md @@ -0,0 +1,44 @@ +--- +title: 从 PDF 中删除图像 +type: docs +weight: 20 +url: /zh/python-net/delete-images/ +description: +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中删除 PDF 页面上的特定图像 +Abstract: 本示例演示如何使用 Aspose.PDF for Python via the Facades API 从 PDF 文档中删除特定图像。它展示了如何针对特定页面上的图像并保存更新后的文档。 +--- + +有时,您可能只想从 PDF 中删除某些图像,而不是清除所有视觉元素。使用 With [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/zh/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md new file mode 100644 index 0000000000..79242bf3ec --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/image-operations/replace-image/_index.md @@ -0,0 +1,42 @@ +--- +title: 在 PDF 中替换图像 +type: docs +weight: 30 +url: /zh/python-net/replace-image/ +description: 此示例绑定一个输入 PDF,将第 1 页上的第一张图像替换为新图像,并保存修改后的文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中替换 PDF 中的图像 +Abstract: 此示例演示如何使用 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 文档。 + +```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/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md new file mode 100644 index 0000000000..3f870d105f --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/_index.md @@ -0,0 +1,19 @@ +--- +title: 链接和导航 +type: docs +weight: 70 +url: /zh/python-net/links-and-navigation-facades/ +description: +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [添加网页链接](/pdf/zh/python-net/add-web-link/) +- [添加本地链接](/pdf/zh/python-net/add-local-link/) +- [添加 PDF 文档链接](/pdf/zh/python-net/add-pdf-document-link/) +- [添加 JavaScript 链接](/pdf/zh/python-net/add-javascript-link/) +- [添加应用链接](/pdf/zh/python-net/add-application-link/) +- [添加自定义操作链接](/pdf/zh/python-net/add-custom-action-link/) +- [提取链接](/pdf/zh/python-net/extract-links/) diff --git a/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md new file mode 100644 index 0000000000..262946c533 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-application-link/_index.md @@ -0,0 +1,53 @@ +--- +title: 添加应用链接 +type: docs +weight: 10 +url: /zh/python-net/add-application-link/ +description: 此示例绑定输入 PDF,在第一页添加应用启动链接,并保存修改后的文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中为 PDF 添加应用启动链接 +Abstract: 此示例演示如何使用 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. 指定要启动的应用程序路径。 +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/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md new file mode 100644 index 0000000000..d9562ee319 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-custom-action-link/_index.md @@ -0,0 +1,54 @@ +--- +title: 添加自定义操作链接 +type: docs +weight: 20 +url: /zh/python-net/add-custom-action-link/ +description: 此示例绑定一个输入 PDF,在首页添加自定义操作链接,并保存修改后的文档。为简化起见,使用了空的操作列表,但实际实现可以包含实际的操作。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中向 PDF 添加自定义操作链接 +Abstract: 此示例演示如何使用 Aspose.PDF for Python via the Facades API 向 PDF 文档添加自定义操作链接。它展示了如何在页面上创建可点击区域,分配自定义操作,并保存更新后的文档。 +--- + +自定义操作链接允许您在 PDF 中定义交互区域,点击时可触发特定操作,例如执行脚本、导航页面或运行特定应用程序的命令。Using [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/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md new file mode 100644 index 0000000000..1326b93363 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-javascript-link/_index.md @@ -0,0 +1,53 @@ +--- +title: 添加 JavaScript 链接 +type: docs +weight: 30 +url: /zh/python-net/add-javascript-link/ +description: 此示例绑定一个输入 PDF,添加一个在点击时触发警报的 JavaScript 链接,并保存修改后的文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中向 PDF 添加 JavaScript 链接 +Abstract: 这个示例演示了如何使用 Aspose.PDF for Python via the Facades API 向 PDF 文档添加 JavaScript 链接。它展示了如何创建一个可点击区域,在点击时执行 JavaScript 代码,并保存更新后的 PDF。 +--- + +PDF 中的 JavaScript 链接允许交互功能,例如显示警报、执行计算或动态修改文档内容。使用 [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/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md new file mode 100644 index 0000000000..fa41d237db --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-local-link/_index.md @@ -0,0 +1,53 @@ +--- +title: 添加本地链接 +type: docs +weight: 40 +url: /zh/python-net/add-local-link/ +description: 此示例绑定一个输入 PDF,在第 1 页添加一个红色本地链接,指向第 1 页,并保存修改后的文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中为 PDF 添加本地链接 +Abstract: 本示例演示了如何使用 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. 指定源页面和目标页面。 +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/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md new file mode 100644 index 0000000000..03d5761150 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-pdf-document-link/_index.md @@ -0,0 +1,54 @@ +--- +title: 添加 PDF 文档链接 +type: docs +weight: 50 +url: /zh/python-net/add-pdf-document-link/ +description: 本示例绑定一个输入 PDF,向另一个 PDF 的页面添加一个绿色链接,并保存修改后的文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中添加 PDF 文档链接 +Abstract: 本示例演示如何使用 Aspose.PDF for Python via the Facades API 向另一个 PDF 文档添加链接。它展示了如何创建一个可点击的区域,以打开不同的 PDF 并保存更新后的文档。 +--- + +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/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md new file mode 100644 index 0000000000..fa71a52482 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/add-web-link/_index.md @@ -0,0 +1,52 @@ +--- +title: 添加网页链接 +type: docs +weight: 60 +url: /zh/python-net/add-web-link/ +description: 此示例绑定一个输入 PDF,在第 1 页添加一个指向 Aspose 的 Python PDF 产品页面的蓝色网页链接注释,并保存修改后的文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中使用 PdfContentEditor 向 PDF 添加网页链接 +Abstract: 此示例演示如何使用 Aspose.PDF for Python via the Facades API 向 PDF 文档添加网页链接。它展示了如何在页面上创建可点击区域,以在网页浏览器中打开指定的 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/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md new file mode 100644 index 0000000000..858a80de35 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/links-and-navigation/extract-links/_index.md @@ -0,0 +1,60 @@ +--- +title: 提取链接 +type: docs +weight: 70 +url: /zh/python-net/extract-links/ +description: 此示例绑定一个输入 PDF,提取所有链接,并打印其坐标和 URI(如果可用)。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中提取 PDF 链接 +Abstract: 此示例演示如何使用 Aspose.PDF for Python via the Facades API 提取 PDF 文档中的所有链接。它展示了如何识别并检索嵌入在 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/zh/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md new file mode 100644 index 0000000000..af074cca92 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/multimedia/_index.md @@ -0,0 +1,14 @@ +--- +title: 多媒体 +type: docs +weight: 80 +url: /zh/python-net/multimedia/ +description: +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [添加电影批注](/pdf/zh/python-net/add-movie-annotation/) +- [添加声音注释](/pdf/zh/python-net/add-sound-annotation/) diff --git a/zh/python-net/working-with-facades/pdfcontenteditor/multimedia/add-movie-annotation/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/multimedia/add-movie-annotation/_index.md new file mode 100644 index 0000000000..c7924cd98d --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/multimedia/add-movie-annotation/_index.md @@ -0,0 +1,45 @@ +--- +title: 添加电影批注 +type: docs +weight: 10 +url: /zh/python-net/add-movie-annotation/ +description: 此示例绑定一个输入 PDF,在第 1 页添加电影批注,并保存更新后的 PDF。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中使用 PdfContentEditor 向 PDF 添加电影批注 +Abstract: 此示例演示如何使用 Aspose.PDF for Python via the Facades API 将电影(视频)嵌入 PDF 文档。它展示了如何添加可点击的批注,以在 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/zh/python-net/working-with-facades/pdfcontenteditor/multimedia/add-sound-annotation/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/multimedia/add-sound-annotation/_index.md new file mode 100644 index 0000000000..290ad67f39 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/multimedia/add-sound-annotation/_index.md @@ -0,0 +1,46 @@ +--- +title: 添加声音注释 +type: docs +weight: 20 +url: /zh/python-net/add-sound-annotation/ +description: 此示例绑定一个输入 PDF,在第 1 页添加声音注释,并保存修改后的 PDF。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中向 PDF 添加声音注释 +Abstract: 此示例演示如何使用 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. 指定音频文件、注释名称、页码和采样率。 +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/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md new file mode 100644 index 0000000000..940a36c8b0 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/_index.md @@ -0,0 +1,22 @@ +--- +title: 印章管理 +type: docs +weight: 90 +url: /zh/python-net/stamps-management/ +description: +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [添加橡胶印章](/pdf/zh/python-net/add-rubber-stamp/) +- [按索引删除印章](/pdf/zh/python-net/delete-stamp-by-index/) +- [按 ID 管理印章](/pdf/zh/python-net/manage-stamp-by-id/) +- [按 ID 删除印章](/pdf/zh/python-net/delete-stamp-by-ids-examples/) +- [按索引移动印章](/pdf/zh/python-net/move-stamp-by-index/) +- [通过 ID 移动印章](/pdf/zh/python-net/move-stamp-by-id-example/) +- [使用外观文件创建橡皮图章](/pdf/zh/python-net/create-rubber-stamp-with-appearance-file/) +- [使用外观流创建橡皮图章](/pdf/zh/python-net/create-rubber-stamp-with-appearance-stream/) +- [全局删除印章](/pdf/zh/python-net/delete-stamps-globally/) +- [列出印章](/pdf/zh/python-net/list-stamps/) diff --git a/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md new file mode 100644 index 0000000000..34ca65c143 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/add-rubber-stamp/_index.md @@ -0,0 +1,52 @@ +--- +title: 添加橡胶印章 +type: docs +weight: 10 +url: /zh/python-net/add-rubber-stamp/ +description: 此示例绑定一个输入 PDF,在前四页添加一个绿色的“已批准”橡胶印章,并保存修改后的文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 中的 PdfContentEditor 向 PDF 添加橡胶印章注释 +Abstract: 此示例演示如何使用 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–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/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md new file mode 100644 index 0000000000..0d762cfbe9 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-file/_index.md @@ -0,0 +1,52 @@ +--- +title: 使用外观文件创建橡皮图章 +type: docs +weight: 20 +url: /zh/python-net/create-rubber-stamp-with-appearance-file/ +description: 此示例绑定输入 PDF,在第 1 页使用图像文件作为图章外观创建橡皮图章,并保存更新后的 PDF。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 PDF 中创建具有自定义外观的橡皮图章 +Abstract: 此示例演示如何使用 Aspose.PDF for Python via the Facades API 将具有自定义外观(图像)的橡皮图章注释添加到 PDF 文档中。自定义图章允许您将徽标、签名或品牌视觉元素作为图章的一部分。 +--- + +橡皮图章注释不仅可以使用文本进行自定义,还可以通过使用图像文件作为其外观进行定制。这种方法对于在 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/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md new file mode 100644 index 0000000000..7b49a80dbd --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/create-rubber-stamp-with-appearance-stream/_index.md @@ -0,0 +1,52 @@ +--- +title: 使用外观流创建橡皮图章 +type: docs +weight: 30 +url: /zh/python-net/create-rubber-stamp-with-appearance-stream/ +description: 此示例加载 PDF,在第 1 页使用图像文件作为外观创建橡皮图章,并保存修改后的文档。 ✨ +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中创建自定义图像外观的橡皮图章 +Abstract: 此示例展示了如何使用 Aspose.PDF for Python 通过 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/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md new file mode 100644 index 0000000000..a9ef3967f0 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-ids-examples/_index.md @@ -0,0 +1,68 @@ +--- +title: 按 ID 删除印章 +type: docs +weight: 85 +url: /zh/python-net/delete-stamp-by-ids-examples/ +description: +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 PDF 中按单个或多个 ID 删除橡胶印章 +Abstract: 本示例演示了如何使用 Aspose.PDF for Python 通过 Facades API,基于唯一 ID 从 PDF 中删除橡胶印章注释。它涵盖了单 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. 添加两个具有不同 ID 的橡皮图章。 +1. 使用单 ID 和多 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 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/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md new file mode 100644 index 0000000000..3e40d2d1c3 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamp-by-index/_index.md @@ -0,0 +1,44 @@ +--- +title: 按索引删除印章 +type: docs +weight: 50 +url: /zh/python-net/delete-stamp-by-index/ +description: 此示例在第2页创建两个橡皮图章。之后,可通过指定其索引来删除印章。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 中的 PdfContentEditor 按索引删除 PDF 中的橡皮图章 +Abstract: 此示例演示如何使用 Aspose.PDF for Python via the Facades API,通过索引删除 PDF 中的橡皮图章注释。它展示了如何添加多个印章,然后根据它们在页面上的顺序删除其中一个。 +--- + +当页面上存在多个橡皮图章时,您可以使用其索引删除特定的图章。delete_stamp() 方法允许按照顺序删除注释,这在您不跟踪印章 ID 但知道其顺序时非常有用。 + +1. 创建一个 [PdfContentEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfcontenteditor/) 实例。 +1. 绑定输入的 PDF 文档。 +1. 使用 bind_pdf(infile) 将输入 PDF 文件绑定到 PdfContentEditor 实例。 +1. 调用 'delete_stamp(1, [2, 3])' 来删除索引为 1 的印章,在第 2 页和第 3 页。 +1. 使用 save(outfile) 将修改后的 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_index(infile, outfile): + # Create PdfContentEditor object + content_editor = pdf_facades.PdfContentEditor() + # Bind document to PdfContentEditor + content_editor.bind_pdf(infile) + content_editor.delete_stamp(1, [2, 3]) + # Save updated document + content_editor.save(outfile) +``` diff --git a/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md new file mode 100644 index 0000000000..23070d9e10 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/delete-stamps-globally/_index.md @@ -0,0 +1,59 @@ +--- +title: 全局删除印章 +type: docs +weight: 60 +url: /zh/python-net/delete-stamps-globally/ +description: 本示例演示如何使用 Aspose.PDF for Python via the Facades API 在 PDF 的所有页面上全局删除橡胶印章注释。它展示了如何通过 ID 删除印章,而无需指定单独的页面。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中全局删除 PDF 的橡胶印章 +Abstract: 本示例演示如何使用 Aspose.PDF for Python via the Facades API 在 PDF 的所有页面上全局删除橡胶印章注释。它展示了如何通过 ID 删除印章,而无需指定单独的页面。 +--- + +在处理多页文档时,您可能需要在整个文档中删除某些印章。'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. 使用其 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 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/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md new file mode 100644 index 0000000000..bd8ce66bef --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/list-stamps/_index.md @@ -0,0 +1,52 @@ +--- +title: 列出印章 +type: docs +weight: 70 +url: /zh/python-net/list-stamps/ +description: 本示例加载 PDF,检索第 1 页的所有印章,打印它们,并在未找到印章时显示提示信息。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中列出 PDF 的橡胶印章注释 +Abstract: 本示例演示如何使用 Aspose.PDF for Python via the Facades API 检索并列出 PDF 文档中的橡胶印章注释。它展示了如何访问特定页面上的印章并显示其详细信息。 +--- + +在处理带有注释的 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/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md new file mode 100644 index 0000000000..d112b25677 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/manage-stamp-by-id/_index.md @@ -0,0 +1,70 @@ +--- +title: 按 ID 管理印章 +type: docs +weight: 95 +url: /zh/python-net/manage-stamp-by-id/ +description: 如何使用 Aspose.PDF for Python 按唯一 ID 操作 PDF 中的橡胶印章注释 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 中的 PdfContentEditor 按 ID 管理 PDF 中的橡胶印章 +Abstract: 本示例演示如何通过 Aspose.PDF for Python 的 Facades API 按唯一 ID 操作 PDF 中的橡胶印章注释。您可以在特定页面隐藏或显示特定印章,而不影响其他印章。 +--- + +在包含多个橡胶印章的 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. 添加具有特定 ID 的橡皮图章。 +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 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/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md new file mode 100644 index 0000000000..6ef5d6fa4c --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-id-example/_index.md @@ -0,0 +1,55 @@ +--- +title: 通过 ID 移动印章 +type: docs +weight: 80 +url: /zh/python-net/move-stamp-by-id-example/ +description: 在本例中,先在第 1 页添加了一个橡胶印章,然后使用其 ID 将其移动到新位置,最后保存更新后的文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中通过 ID 移动 PDF 中的橡胶印章 +Abstract: 本例演示了如何使用 Aspose.PDF for Python via the Facades API 在 PDF 中重新定位已有的橡胶印章注释。它展示了如何创建印章,然后通过其 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/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md new file mode 100644 index 0000000000..b2fa479be1 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/stamps-management/move-stamp-by-index/_index.md @@ -0,0 +1,70 @@ +--- +title: 按索引移动印章 +type: docs +weight: 90 +url: /zh/python-net/move-stamp-by-index/ +description: 如何使用 Aspose.PDF for Python 通过页面上的索引重新定位 PDF 中的橡胶印章注释 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用基于索引的定位在 PDF 中移动橡胶印章 +Abstract: 此示例演示如何使用 Aspose.PDF for Python 通过 Facades API,利用页面上印章的索引重新定位 PDF 中的橡胶印章注释。它重点展示了创建多个印章并为移动操作做好准备。 +--- + +在 PDF 编辑中,可能需要调整现有橡胶印章的位置。此代码片段展示了如何: + +- 在同一页面上添加多个印章 +- 使用它们的索引准备重新定位。 +- 可选地通过指定其页面、索引和新坐标来移动印章。 + +‘move_stamp(page_number, stamp_index, new_x, new_y)’ 方法可以精确地重新定位印章。 + +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 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/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md new file mode 100644 index 0000000000..e5163676b5 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/_index.md @@ -0,0 +1,17 @@ +--- +title: 文本操作 +type: docs +weight: 100 +url: /zh/python-net/text-operations/ +description: +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [简单替换文本](/pdf/zh/python-net/replace-text-simple/) +- [替换文本正则](/pdf/zh/python-net/replace-text-regex/) +- [在页面上替换文本](/pdf/zh/python-net/replace-text-on-page/) +- [使用状态替换文本](/pdf/zh/python-net/replace-text-with-state/) +- [在页面上使用状态替换文本](/pdf/zh/python-net/replace-text-on-page-with-state/) diff --git a/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md new file mode 100644 index 0000000000..5b97e8c8aa --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page-with-state/_index.md @@ -0,0 +1,53 @@ +--- +title: 在页面上使用状态替换文本 +type: docs +weight: 20 +url: /zh/python-net/replace-text-on-page-with-state/ +description: 在本示例中,页面 1 上所有出现的单词 “software” 都被替换为 “SOFTWARE PAGE 1”,使用红色文本,字体大小为 12。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中对特定页面进行自定义格式的文本替换 +Abstract: 本示例演示了如何在 PDF 的特定页面上进行文本替换,同时使用 Aspose.PDF for Python via the 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/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md new file mode 100644 index 0000000000..8015c41f77 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-on-page/_index.md @@ -0,0 +1,47 @@ +--- +title: 在页面上替换文本 +type: docs +weight: 10 +url: /zh/python-net/replace-text-on-page/ +description: 在本例中,单词 "PDF" 的第一次出现被替换为 "Page 1 Replaced Text",使用了指定的字体大小。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中替换特定页面上的文本 +Abstract: 本例演示了如何使用 Aspose.PDF for Python 通过 Facades API 在 PDF 文档中替换文本。它展示了如何替换页面上文本的第一次出现并保存更新后的文档。 +--- + +在更新 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/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md new file mode 100644 index 0000000000..ebfb61fbe5 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-regex/_index.md @@ -0,0 +1,48 @@ +--- +title: 替换文本正则 +type: docs +weight: 30 +url: /zh/python-net/replace-text-regex/ +description: 在本示例中,文档中的所有四位数字都被替换为占位符 "[NUMBER]"。这对于遮蔽敏感数据、规范化内容或匿名化文档非常有用。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中通过正则表达式替换文本 +Abstract: 本示例演示了如何使用 Aspose.PDF for Python 通过 Facades API 结合正则表达式替换 PDF 中的文本。它展示了如何搜索模式并在整个文档中替换所有匹配项。 +--- + +正则表达式允许基于模式而非固定字符串进行灵活的文本替换。通过在 'replace_text_strategy' 中启用正则支持,您可以匹配诸如数字、日期或格式化字符串等动态内容。 + +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_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/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md new file mode 100644 index 0000000000..d9c5613acc --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-simple/_index.md @@ -0,0 +1,47 @@ +--- +title: 简单替换文本 +type: docs +weight: 40 +url: /zh/python-net/replace-text-simple/ +description: 在此示例中,文档中所有出现的“23”均被替换为“XXXIII ”。这演示了不使用自定义格式或正则表达式的直接字符串替换。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfContentEditor 在 Python 中跨 PDF 替换文本 +Abstract: 此示例演示了如何使用 Aspose.PDF for Python via the Facades API 在整个 PDF 文档中替换文本。它会将指定字符串的所有出现替换为新文本。 +--- + +在文档中更新重复值时,简单的文本替换非常有用。使用 [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/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md new file mode 100644 index 0000000000..47bd59f379 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/text-operations/replace-text-with-state/_index.md @@ -0,0 +1,53 @@ +--- +title: 使用状态替换文本 +type: docs +weight: 50 +url: /zh/python-net/replace-text-with-state/ +description: 在此示例中,所有出现的 “software” 都被替换为 “SOFTWARE”,并使用蓝色、14号字体进行格式化。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 PDF 中使用 PdfContentEditor(Python)进行自定义格式的文本替换 +Abstract: 本示例演示了如何在 PDF 文档中替换文本,同时使用 Aspose.PDF for Python via the 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/zh/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md new file mode 100644 index 0000000000..6495333744 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/_index.md @@ -0,0 +1,15 @@ +--- +title: 查看器首选项 +type: docs +weight: 110 +url: /zh/python-net/viewer-preferences/ +description: +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + + +- [更改 PDF 查看器首选项](/pdf/zh/python-net/change-viewer-preferences/) +- [获取 PDF 查看器首选项](/pdf/zh/python-net/get-viewer-preferences/) diff --git a/zh/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md new file mode 100644 index 0000000000..522bcfdf73 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/change-viewer-preferences/_index.md @@ -0,0 +1,75 @@ +--- +title: 更改 PDF 查看器首选项 +type: docs +weight: 10 +url: /zh/python-net/change-viewer-preferences/ +description: 本模块演示如何使用 Aspose.PDF for Python 调整 PDF 文档的查看器设置。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 定制 PDF 查看器体验 +Abstract: 通过以编程方式修改查看器首选项来控制 PDF 文档打开时的呈现方式。此功能允许您定制用户界面和布局,确保一致的查看体验。 +--- + +PDF 文件内置了查看器首选项,可控制页面布局、工具栏可见性和窗口行为等方面。使用此脚本,您可以: + +- 检查 PDF 的当前查看器首选项。 +- 修改布局选项(例如,单页、单列、双列)。 +- 切换 UI 元素,例如工具栏、菜单栏或标题显示。 +- 保存 PDF 并使用更新的首选项,以实现受控的查看体验。 + +1. 定义 ViewerPreference 标志。 +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/zh/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md b/zh/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md new file mode 100644 index 0000000000..df30c9aac8 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfcontenteditor/viewer-preferences/get-viewer-preferences/_index.md @@ -0,0 +1,45 @@ +--- +title: 获取 PDF 查看器首选项 +type: docs +weight: 20 +url: /zh/python-net/get-viewer-preferences/ +description: 如何使用 Aspose.PDF for Python 以编程方式读取和修改 PDF 查看器首选项 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中使用 Aspose.PDF 管理 PDF 查看器首选项 +Abstract: 本指南演示了如何使用 Aspose.PDF for Python 以编程方式读取和修改 PDF 查看器首选项。查看器首选项控制 PDF 在 PDF 查看器中打开时的显示方式,例如以大纲打开、隐藏工具栏或使用单页布局。 +--- + +Aspose.PDF 提供了访问和更新 PDF 查看器首选项的工具。这些首选项定义了 PDF 文档在 PDF 阅读器中的初始布局和呈现行为。包括启用大纲视图、隐藏菜单栏或指定页面布局模式等选项。使用 PdfContentEditor,您可以检索现有的首选项、检查特定标志,并根据需要进行更新。 + +1. 定义 ViewerPreference 标志。 +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/zh/python-net/working-with-facades/pdffileeditor/_index.md b/zh/python-net/working-with-facades/pdffileeditor/_index.md new file mode 100644 index 0000000000..f3d340d70a --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/_index.md @@ -0,0 +1,30 @@ +--- +title: PdfFileEditor 类 +type: docs +weight: 10 +url: /zh/python-net/pdffileeditor-class/ +description: 了解如何使用 Aspose.PDF 在 Python 中的 PdfFileEditor 类编辑和操作 PDF 文件。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 中的 PdfFileEditor 编辑 PDF 页面、合并文件和拆分文档 +Abstract: 学习如何在 Aspose.PDF for Python via .NET 中使用 PdfFileEditor 类来操作 PDF 页面和文档结构。本节涵盖页面布局更改、页面管理、PDF 合并、文档拆分以及小册子或 N-Up 排版工作流。 +--- + +处理 PDF 文档包括各种功能。管理 PDF 文件的页面是这项工作的重要部分。'aspose.pdf.facades' 提供了 `PdfFileEditor` 用于此目的的类。 + +PdfFileEditor 类包含用于操作单个页面的方法;该类不编辑或操作页面的内容。您可以插入新页面、删除现有页面、拆分页面,或使用 PdfFileEditor 指定页面的排版方式。 + +## 使用 PdfFileEditor 可以做什么 + +该类提供的功能可以分为页面编辑、PDF 排版和文档拆分工作流。本系列文章展示了如何重新排列页面、合并多个 PDF、为打印准备文件以及在不手动编辑源文件的情况下从现有文档中提取章节。 + +## PdfFileEditor 教程 + +- [页面布局与边距](/pdf/zh/python-net/page-layout-and-margins/) +- [页面管理](/pdf/zh/python-net/page-management/) +- [连接或合并 PDF 文件](/pdf/zh/python-net/page-merging/) +- [拆分 PDF 文档](/pdf/zh/python-net/splitting-pdf-documents/) +- [小册子和 N-Up 布局](/pdf/zh/python-net/booklet-and-nup-layout/) diff --git a/zh/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md b/zh/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md new file mode 100644 index 0000000000..df3b16c107 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/_index.md @@ -0,0 +1,21 @@ +--- +title: 小册子和 N-Up 布局 +type: docs +weight: 10 +url: /zh/python-net/booklet-and-nup-layout/ +description: 准备 PDF 打印通常需要将页面重新排列为特定布局,例如小册子或 N-Up 网格。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中为 PDF 文档创建小册子和 N-Up 布局 +Abstract: 了解如何使用 Aspose.PDF for Python 转换 PDF 页面布局。本指南解释了如何生成小册子式文档以及创建将多个页面放置在单张纸上的 N-Up 布局。这些技术有助于优化文档的打印,减少纸张使用,并生成紧凑的 PDF 输出。 +--- + +小册子和 N-Up 功能有助于准备 PDF 文档的打印和紧凑页面展示。这些工作流会重新排列页面顺序或将多个源页面放置在单张纸上,适用于讲义、草稿以及可直接打印的小册子输出。 + +## 布局转换教程 + +- [创建 N-Up PDF 文档](/pdf/zh/python-net/create-n-up-pdf-document/) +- [创建 PDF 小册子](/pdf/zh/python-net/create-pdf-booklet/) diff --git a/zh/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md b/zh/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md new file mode 100644 index 0000000000..b4e694ea12 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-n-up-pdf-document/_index.md @@ -0,0 +1,84 @@ +--- +title: 创建 N-Up PDF 文档 +type: docs +weight: 10 +url: /zh/python-net/create-n-up-pdf-document/ +description: 了解如何使用 Aspose.PDF for Python 在安全处理潜在错误的同时创建 N-Up PDF 文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中创建 N-Up PDF 布局 +Abstract: 了解如何使用 Aspose.PDF for Python 生成 N-Up PDF 布局。本示例演示如何使用 PdfFileEditor 类的 'make_n_up' 或 'try_make_n_up' 方法将 PDF 文档的多页合并到单页上。 +--- + +N-Up 布局将 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 允许您使用 PdfFileEditor 类生成 N-Up 布局。'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/zh/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md b/zh/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md new file mode 100644 index 0000000000..8cfc940e9a --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/booklet-and-nup-layout/create-pdf-booklet/_index.md @@ -0,0 +1,81 @@ +--- +title: 创建 PDF 小册子 +type: docs +weight: 20 +url: /zh/python-net/create-pdf-booklet/ +description: 使用 Aspose.PDF for Python 从现有文档生成小册子式 PDF +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 从现有 PDF 创建 PDF 小册子 +Abstract: 了解如何使用 Aspose.PDF for Python 从现有文档生成小册子式 PDF。此示例演示如何使用 PdfFileEditor 类重新排列页面,以便它们可以打印并折叠成小册子。该方法会自动对页面进行排序,以生成正确的小册子布局。 +--- + +在准备 PDF 打印时,创建小册子式文档是常见需求。在小册子布局中,页面会重新排列,以便打印并折叠后呈现正确的顺序。 + +使用 Aspose.PDF for Python,开发者可以轻松地将标准 PDF 转换为小册子,使用 [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) class. '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/zh/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md b/zh/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md new file mode 100644 index 0000000000..d0f83e8918 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/_index.md @@ -0,0 +1,18 @@ +--- +title: 页面布局与边距 +type: docs +weight: 20 +url: /zh/python-net/page-layout-and-margins/ +description: 管理 PDF 页面布局是文档处理工作流中的重要环节。开发人员经常需要调整边距、重新设置页面内容的大小,或插入分页符,以确保文档符合格式要求或打印标准。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中编辑 PDF 页面布局 - 添加边距、调整内容大小并插入分页符 +Abstract: 学习如何使用 Aspose.PDF for Python 修改 PDF 页面布局。本指南说明了如何为特定页面添加边距、调整页面内容大小以及以编程方式插入分页符。这些功能帮助开发人员调整文档格式、提升可读性,并为打印或结构化布局准备 PDF。 +--- + +- [为 PDF 页面添加页边距](/pdf/zh/python-net/add-margins-to-pdf-pages/) +- [调整 PDF 页面内容](/pdf/zh/python-net/resize-pdf-page-contents/) +- [在 PDF 中添加分页符](/pdf/zh/python-net/add-page-breaks-in-pdf/) \ No newline at end of file diff --git a/zh/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md b/zh/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md new file mode 100644 index 0000000000..c41247a0ed --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-margins-to-pdf-pages/_index.md @@ -0,0 +1,51 @@ +--- +title: 为 PDF 页面添加页边距 +type: docs +weight: 10 +url: /zh/python-net/add-margins-to-pdf-pages/ +description: 使用 Aspose.PDF for Python 为 PDF 的选定页面添加自定义页边距。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中为特定 PDF 页面添加自定义页边距 +Abstract: 了解如何使用 Aspose.PDF for Python 为 PDF 的选定页面添加自定义页边距。本示例演示如何通过为各个页面指定顶部、底部、左侧和右侧页边距来扩展页面边界,使 PDF 更易打印或在视觉上保持一致。 +--- + +为 PDF 页面添加页边距可以提升可读性、为打印做好准备或为注释预留空间。使用 Aspose.PDF for Python,开发人员可以在不修改内容布局的情况下,以编程方式为 PDF 的特定页面添加页边距。 + +在此代码片段中, [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) class 用于在输入文档的第 1 页和第 3 页添加 0.5 英寸的边距。边距以点为单位定义(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/zh/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md b/zh/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md new file mode 100644 index 0000000000..5325399ae4 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/add-page-breaks-in-pdf/_index.md @@ -0,0 +1,47 @@ +--- +title: 在 PDF 中添加分页符 +type: docs +weight: 20 +url: /zh/python-net/add-page-breaks-in-pdf/ +description: 使用 Aspose.PDF for Python 向 PDF 文档插入分页符。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中以编程方式向 PDF 页面添加分页符 +Abstract: 了解如何使用 Aspose.PDF for Python 向 PDF 文档插入分页符。此示例演示如何在指定的垂直位置拆分页面,使开发人员能够重新组织内容并动态创建额外的页面。 +--- + +当您需要将长 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/zh/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md b/zh/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md new file mode 100644 index 0000000000..2bff21c80c --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/page-layout-and-margins/resize-pdf-page-contents/_index.md @@ -0,0 +1,50 @@ +--- +title: 调整 PDF 页面内容 +type: docs +weight: 30 +url: /zh/python-net/resize-pdf-page-contents/ +description: 使用 Aspose.PDF for Python 调整特定 PDF 页面内容的大小。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中以编程方式调整 PDF 页面内容 +Abstract: 了解如何使用 Aspose.PDF for Python 调整特定 PDF 页面内容的大小。本示例演示了如何在保持文档结构的同时调整页面内容的宽度和高度,从而更轻松地优化打印或查看的布局。 +--- + +在为打印准备文档、将内容适配到特定布局或在文档中统一页面格式时,通常需要调整 PDF 页面内容的大小。使用 Aspose.PDF for Python,开发者可以以编程方式调整所选页面的内容大小,而无需手动编辑文档。 + +本文展示了如何使用 \u0027resize_contents\u0027 方法 [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/zh/python-net/working-with-facades/pdffileeditor/page-managment/_index.md b/zh/python-net/working-with-facades/pdffileeditor/page-managment/_index.md new file mode 100644 index 0000000000..438b5b00d1 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/page-managment/_index.md @@ -0,0 +1,25 @@ +--- +title: 页面管理 +type: docs +weight: 30 +url: /zh/python-net/page-management/ +description: 以编程方式管理 PDF 页面使开发人员能够在无需手动编辑的情况下修改文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中以编程方式管理 PDF 页面 - 提取、删除、插入和追加 +Abstract: 了解如何使用 Aspose.PDF for Python 对 PDF 文档执行页面级操作。本指南演示了如何提取特定页面、删除不需要的页面、从另一个 PDF 插入页面以及向现有文档追加页面,从而实现高效且自动化的 PDF 页面管理。 +--- + +页面管理任务是许多 PDF 工作流的核心。使用 Aspose.PDF for Python,您可以重新组织文档结构,删除不必要的页面,并在保持原始页面内容完整的情况下合并多个 PDF 的内容。 + +## 常见页面管理操作 + +使用以下教程来处理最常见的页面级编辑任务 `PdfFileEditor`: + +- [从 PDF 中提取页面](/pdf/zh/python-net/extract-pages-from-pdf/) +- [从 PDF 中删除页面](/pdf/zh/python-net/delete-pages-from-pdf/) +- [向 PDF 插入页面](/pdf/zh/python-net/insert-pages-into-pdf/) +- [将页面追加到 PDF](/pdf/zh/python-net/append-pages-to-pdf/) diff --git a/zh/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md b/zh/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md new file mode 100644 index 0000000000..d4eb044d2e --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/page-managment/append-pages-to-pdf/_index.md @@ -0,0 +1,42 @@ +--- +title: 将页面追加到 PDF +type: docs +weight: 10 +url: /zh/python-net/append-pages-to-pdf/ +description: 使用 Aspose.PDF for Python 将一个 PDF 文档的页面追加到另一个 PDF 文档中。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中将页面从一个 PDF 追加到另一个 PDF +Abstract: 了解如何使用 Aspose.PDF for Python 将一个 PDF 文档的页面追加到另一个文档中。本示例演示如何使用 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/zh/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md b/zh/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md new file mode 100644 index 0000000000..7e39cd2b4c --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/page-managment/delete-pages-from-pdf/_index.md @@ -0,0 +1,46 @@ +--- +title: 从 PDF 中删除页面 +type: docs +weight: 20 +url: /zh/python-net/delete-pages-from-pdf/ +description: 使用 Aspose.PDF for Python 从 PDF 文档中删除选定的页面。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中从 PDF 文档中删除特定页面 +Abstract: 了解如何使用 Aspose.PDF for Python 从 PDF 文档中删除选定的页面。此示例演示如何以编程方式删除现有 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/zh/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md b/zh/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md new file mode 100644 index 0000000000..0dbddb3cb7 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/page-managment/extract-pages-from-pdf/_index.md @@ -0,0 +1,45 @@ +--- +title: 从 PDF 中提取页面 +type: docs +weight: 30 +url: /zh/python-net/extract-pages-from-pdf/ +description: 使用 Aspose.PDF for Python 从 PDF 文档中提取选定的页面。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中从 PDF 文档中提取特定页面 +Abstract: 了解如何使用 Aspose.PDF for Python 从 PDF 文档中提取选定的页面。此示例演示如何创建仅包含所需页面的新 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/zh/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md b/zh/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md new file mode 100644 index 0000000000..0cd1070260 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/page-managment/insert-pages-into-pdf/_index.md @@ -0,0 +1,44 @@ +--- +title: 向 PDF 插入页面 +type: docs +weight: 40 +url: /zh/python-net/insert-pages-into-pdf/ +description: 使用 Aspose.PDF for Python 将一个 PDF 的页面插入另一个 PDF。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中将另一个 PDF 的页面插入现有 PDF +Abstract: 了解如何使用 Aspose.PDF for Python 将一个 PDF 的页面插入另一个 PDF。本示例演示如何将次要 PDF 中选定的页面添加到原始文档的特定位置,从而创建一个页面放置精确的合并 PDF。 +--- + +在合并文档、添加内容或重新组织报告时,向现有 PDF 插入页面是常见需求。使用 Aspose.PDF for Python,开发者可以通过编程在指定位置将一个 PDF 的页面插入另一个 PDF。 + +本文展示了如何使用 insert 方法的 [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) class。通过指定要插入的页码和目标位置,您可以在保持原始格式和结构的同时合并不同 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/zh/python-net/working-with-facades/pdffileeditor/page-merging/_index.md b/zh/python-net/working-with-facades/pdffileeditor/page-merging/_index.md new file mode 100644 index 0000000000..f0d5ccc1ac --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/page-merging/_index.md @@ -0,0 +1,22 @@ +--- +title: 合并 PDF 文件 +type: docs +weight: 40 +url: /zh/python-net/page-merging/ +description: 在自动化工作流、报告生成和文档管理中,合并 PDF 文档是一项常见需求。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中合并 PDF 文件 - 使用 Aspose.PDF 合并两个或多个 PDF +Abstract: 学习如何使用 Aspose.PDF for Python 以编程方式连接 PDF 文件。本指南演示了合并两个或多个 PDF 的方法、处理大量文件、优化输出,以及通过唯一后缀连接 PDF 表单以避免命名冲突。 +--- + +- [合并两个 PDF 文件](/pdf/zh/python-net/concatenate-two-files/) +- [合并多个 PDF 文件](/pdf/zh/python-net/concatenate-pdf-files/) +- [尝试合并两个 PDF 文件](/pdf/zh/python-net/try-concatenate-two-files/) +- [尝试连接多个 PDF 文件](/pdf/zh/python-net/try-concatenate-pdf-files/) +- [合并大量 PDF 文件](/pdf/zh/python-net/concatenate-large-number-files/) +- [合并 PDF 文件并进行优化](/pdf/zh/python-net/concatenate-pdf-files-with-optimization/) +- [使用唯一后缀连接 PDF 表单](/pdf/zh/python-net/concatenate-pdf-forms/) \ No newline at end of file diff --git a/zh/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md b/zh/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md new file mode 100644 index 0000000000..a7e2e83dbb --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-large-number-files/_index.md @@ -0,0 +1,37 @@ +--- +title: 合并大量 PDF 文件 +type: docs +weight: 10 +url: /zh/python-net/concatenate-large-number-files/ +description: 使用 Aspose.PDF for Python 高效合并大量 PDF 文件。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中使用磁盘缓存合并大型 PDF 文件 +Abstract: 了解如何使用 Aspose.PDF for Python 高效合并大量 PDF 文件。本示例演示如何启用磁盘缓存,以在不耗尽系统内存的情况下处理大型 PDF,确保多个文件的顺畅合并。 +--- + +在处理大型 PDF 文件集合时,内存消耗可能成为合并过程的瓶颈。使用 Aspose.PDF for Python,您可以在 the [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/zh/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md b/zh/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md new file mode 100644 index 0000000000..4d5140ae1a --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files-with-optimization/_index.md @@ -0,0 +1,37 @@ +--- +title: 合并 PDF 文件并进行优化 +type: docs +weight: 30 +url: /zh/python-net/concatenate-pdf-files-with-optimization/ +description: 使用 Aspose.PDF for Python 将多个 PDF 文件合并为单个优化的 PDF。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中合并 PDF 文件并生成优化的输出 +Abstract: 了解如何使用 Aspose.PDF for Python 将多个 PDF 文件合并为单个优化的 PDF。本示例演示如何启用大小优化,以在保持内容和格式的同时减小输出文件的大小。 +--- + +在合并多个 PDF 时,生成的文件可能会变得很大,尤其是其中包含图像或复杂内容时。使用 Aspose.PDF for Python,开发者可以在合并过程中启用优化,以在不降低质量的前提下降小文件尺寸。类中的 optimize_size 属性在 the [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/zh/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md b/zh/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md new file mode 100644 index 0000000000..8f2569b64c --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-files/_index.md @@ -0,0 +1,36 @@ +--- +title: 合并多个 PDF 文件 +type: docs +weight: 20 +url: /zh/python-net/concatenate-pdf-files/ +description: 使用 Aspose.PDF for Python 将多个 PDF 文件合并为单个文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中将多个 PDF 文件合并为一个 PDF +Abstract: 了解如何使用 Aspose.PDF for Python 将多个 PDF 文件合并为单个文档。此示例演示如何使用 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/zh/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md b/zh/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md new file mode 100644 index 0000000000..2635e897a2 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-pdf-forms/_index.md @@ -0,0 +1,39 @@ +--- +title: 使用唯一后缀连接 PDF 表单 +type: docs +weight: 50 +url: /zh/python-net/concatenate-pdf-forms/ +description: 使用 Aspose.PDF for Python 连接多个 PDF 表单,同时确保表单字段名称唯一。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中合并 PDF 表单,避免字段名称冲突 +Abstract: 了解如何使用 Aspose.PDF for Python 连接多个 PDF 表单,同时确保表单字段名称唯一。此示例演示如何设置自定义后缀,以防止在合并包含交互式表单字段的 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/zh/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md b/zh/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md new file mode 100644 index 0000000000..2efe8f87f5 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/page-merging/concatenate-two-files/_index.md @@ -0,0 +1,36 @@ +--- +title: 合并两个 PDF 文件 +type: docs +weight: 60 +url: /zh/python-net/concatenate-two-files/ +description: 使用 Aspose.PDF for Python 将两个 PDF 文件合并为单个文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中将两个 PDF 文件合并为单个 PDF +Abstract: 了解如何使用 Aspose.PDF for Python 将两个 PDF 文件合并为单个文档。本示例演示了如何无缝合并两个 PDF,同时保留其原始内容和格式。 +--- + +在合并报告、合同或表单时,合并两个 PDF 文件是一项常见任务。使用 Aspose.PDF for Python,您可以通过编程方式使用该类的 concatenate 方法将两个 PDF 合并为单个文档 the [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/zh/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md b/zh/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md new file mode 100644 index 0000000000..62b4bdc45d --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-pdf-files/_index.md @@ -0,0 +1,37 @@ +--- +title: 尝试合并 PDF 文件 +type: docs +weight: 70 +url: /zh/python-net/try-concatenate-pdf-files/ +description: 使用 Aspose.PDF for Python 合并多个 PDF 文件。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中使用错误处理安全合并 PDF 文件 +Abstract: 了解如何使用 Aspose.PDF for Python 安全地连接多个 PDF 文件。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/zh/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md b/zh/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md new file mode 100644 index 0000000000..2fd5f42d66 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/page-merging/try-concatenate-two-files/_index.md @@ -0,0 +1,39 @@ +--- +title: 尝试合并两个 PDF 文件 +type: docs +weight: 90 +url: /zh/python-net/try-concatenate-two-files/ +description: 使用 Aspose.PDF for Python 合并两个 PDF 文件。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中安全合并两个 PDF 文件,无异常 +Abstract: 了解如何使用 Aspose.PDF for Python 安全地合并两个 PDF 文件。try_concatenate 方法在不抛出异常的情况下合并文件,即使操作失败也能实现优雅的错误处理。 +--- + +合并两个 PDF 文件有时可能因为文件损坏、不兼容的格式或其他问题而失败。使用 Aspose.PDF for Python,PdfFileEditor 类的 try_concatenate 方法允许您安全地尝试合并两个 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/zh/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md b/zh/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md new file mode 100644 index 0000000000..72a8d4cc85 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/_index.md @@ -0,0 +1,22 @@ +--- +title: 拆分 PDF 文档 +type: docs +weight: 50 +url: /zh/python-net/splitting-pdf-documents/ +description: 拆分 PDF 是文档管理、报告和自动化工作流的常见需求。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中拆分 PDF 文档 - 从开头、到结尾,或拆分为单个文件 +Abstract: 了解如何使用 Aspose.PDF for Python 以编程方式拆分 PDF 文档。本指南演示了从开头或结尾提取页面、将 PDF 分割为多个文档,或拆分为单页 PDF 的方法,以实现灵活的文档管理。 +--- + +拆分 PDF 文档在您需要提取选定章节、分发单独页面,或将大型文件拆分为更小的单元以便存储和处理时非常有用。Aspose.PDF for Python 提供了多种 `PdfFileEditor` 有效处理这些场景的方法。 + +## PDF 拆分教程 + +- [从开头拆分 PDF](/pdf/zh/python-net/split-pdf-from-beginning/) +- [拆分 PDF 到末页](/pdf/zh/python-net/split-pdf-to-end/) +- [将 PDF 拆分为单页](/pdf/zh/python-net/split-pdf-into-single-pages/) diff --git a/zh/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md b/zh/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md new file mode 100644 index 0000000000..7b4d2e00e8 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-from-beginning/_index.md @@ -0,0 +1,37 @@ +--- +title: 从开头拆分 PDF +type: docs +weight: 10 +url: /zh/python-net/split-pdf-from-beginning/ +description: 使用 Aspose.PDF for Python 从开头拆分 PDF 文档。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中使用 Aspose.PDF 从起始位置拆分 PDF +Abstract: 了解如何使用 Aspose.PDF for Python 从开头拆分 PDF 文档。此示例演示从第1页开始提取特定页数,以创建新的 PDF 文档。 +--- + +从开头拆分 PDF 在您需要将文档的前几页作为单独文件时非常有用。使用 Aspose.PDF for Python,类中的 split_from_first 方法 [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) 类允许您从第1页开始提取指定页数。此功能非常适合生成摘录、预览或更大 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/zh/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md b/zh/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md new file mode 100644 index 0000000000..c070f4ff20 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-into-single-pages/_index.md @@ -0,0 +1,37 @@ +--- +title: 将 PDF 拆分为单页 +type: docs +weight: 30 +url: /zh/python-net/split-pdf-into-single-pages/ +description: 使用 Aspose.PDF for Python 将 PDF 文档拆分为单页 PDF。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中将 PDF 拆分为单个页面 +Abstract: 了解如何使用 Aspose.PDF for Python 将 PDF 文档拆分为单页 PDF。此方法会从原始 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/zh/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md b/zh/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md new file mode 100644 index 0000000000..6ae8b84866 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileeditor/splitting-pdf-documents/split-pdf-to-end/_index.md @@ -0,0 +1,37 @@ +--- +title: 拆分 PDF 到末页 +type: docs +weight: 40 +url: /zh/python-net/split-pdf-to-end/ +description: 使用 Aspose.PDF for Python 将 PDF 文档从指定页面拆分至最后一页。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中将 PDF 从特定页拆分至末页 +Abstract: 了解如何使用 Aspose.PDF for Python 将 PDF 文档从指定页面拆分至最后一页。本示例演示了从指定页面开始提取所有页面,以创建新的 PDF 文件。 +--- + +将 PDF 从特定页面拆分至末页在需要将文档后半部分作为单独文件时非常有用。使用 Aspose.PDF for Python,split_to_end 方法属于该 class [PdfFileEditor](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffileeditor/) 该 class 允许您提取从任意页码开始直至文档最后一页的页面。这非常适合创建摘录、提取章节,或在无需手动编辑的情况下处理大型 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/zh/python-net/working-with-facades/pdffileinfo/_index.md b/zh/python-net/working-with-facades/pdffileinfo/_index.md new file mode 100644 index 0000000000..9eb9a4a2a8 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileinfo/_index.md @@ -0,0 +1,25 @@ +--- +title: PdfFileInfo 类 +type: docs +weight: 110 +url: /zh/python-net/pdffileinfo-class/ +description: 了解如何在 Aspose.PDF for Python via .NET 中使用 PdfFileInfo 类来检查 PDF 元数据、文档属性、权限、版本详细信息和页面信息。 +lastmod: "2026-06-08" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfFileInfo 在 Python 中检查 PDF 元数据、属性和页面信息 +Abstract: 本节解释如何在 Aspose.PDF for Python via .NET 中使用 PdfFileInfo 类以编程方式检查 PDF 文件详细信息。了解如何在 Python 应用程序中处理 PDF 元数据、文档属性、权限、版本信息以及页面级数据。 +--- + +这 `PdfFileInfo` Aspose.PDF Facades 中的 class 提供对文档级和页面级 PDF 信息的访问,而无需进行低层解析。它在需要检查元数据、检索文档属性、检查权限,或在自动化工作流中检查页面尺寸和偏移时非常有用。 + +## 使用 PdfFileInfo 可以做什么 + +使用本节中的文章来探索主要的文件检查功能 `PdfFileInfo` 外观: + +- [使用 PdfFileInfo 管理 PDF 元数据](/pdf/zh/python-net/pdf-metadata/) +- [使用 PdfFileInfo 检查文档属性](/pdf/zh/python-net/document-properties/) +- [使用 PdfFileInfo 检索页面信息](/pdf/zh/python-net/page-information/) diff --git a/zh/python-net/working-with-facades/pdffileinfo/document-properties/_index.md b/zh/python-net/working-with-facades/pdffileinfo/document-properties/_index.md new file mode 100644 index 0000000000..5b4fac3636 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileinfo/document-properties/_index.md @@ -0,0 +1,18 @@ +--- +title: 文档属性 +type: docs +weight: 10 +url: /zh/python-net/document-properties/ +description: 了解如何使用 Aspose.PDF for Python 以编程方式访问 PDF 元数据。本指南涵盖如何检索 PDF 版本并检查文档权限,包括打印、复制、修改和填写表单的权限。 +lastmod: "2026-06-08" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python 获取 PDF 版本和文档权限 +Abstract: 理解 PDF 的元数据对于处理、合规性和工作流自动化至关重要。PDF 版本号指示所支持的功能和兼容性,而文档权限则控制诸如打印、复制内容、修改批注或填写表单字段等操作。本教程演示了如何在 Aspose.PDF for Python 中使用 PdfFileInfo 类。 +--- + +- [获取 PDF 版本](/pdf/zh/python-net/get-pdf-version/) +- [获取文档权限](/pdf/zh/python-net/get-document-privileges/) \ No newline at end of file diff --git a/zh/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md b/zh/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md new file mode 100644 index 0000000000..8dae200603 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileinfo/document-properties/get-document-privileges/_index.md @@ -0,0 +1,59 @@ +--- +title: 获取文档权限 +type: docs +weight: 10 +url: /zh/python-net/get-document-privileges/ +description: 了解如何使用 Aspose.PDF for Python 以编程方式检查 PDF 文档的权限。本教程演示如何使用 PdfFileInfo 类读取文档的安全设置,例如打印、复制或修改权限。 +lastmod: "2026-06-08" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python 检索 PDF 文档权限 +Abstract: PDF 文档可能具有限制打印、复制、修改或填写表单等操作的安全限制。通过以编程方式访问这些权限,开发人员可以确定在 PDF 上允许的操作。此指南展示如何使用 PdfFileInfo 类检索 PDF 的文档权限并在 Python 中显示它们。 +--- + +PDF 权限控制用户对文档可以执行和不能执行的操作。常见的权限包括: + +- 打印文档 +- 复制内容 +- 修改批注或内容 +- 填写表单字段 +- 使用屏幕阅读器 +- 组装或合并文档 + +使用 Aspose.PDF for Python,您可以通过编程方式使用 the 检查这些设置 [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/zh/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md b/zh/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md new file mode 100644 index 0000000000..3fbd5ce7f0 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileinfo/document-properties/get-pdf-version/_index.md @@ -0,0 +1,43 @@ +--- +title: 获取 PDF 版本 +type: docs +weight: 20 +url: /zh/python-net/get-pdf-version/ +description: 了解如何使用 Aspose.PDF for Python 以编程方式确定 PDF 文档的版本。本教程演示如何使用 PdfFileInfo 类检查文件的 PDF 版本。 +lastmod: "2026-06-08" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python 检索 PDF 版本 +Abstract: PDF 文档具有指示其支持的功能和规范的版本号(例如 1.4、1.7、2.0)。了解 PDF 版本对于兼容性、功能支持和文档处理工作流非常重要。在本指南中,您将学习如何使用 Aspose.PDF for Python 中的 PdfFileInfo 类以编程方式检索 PDF 版本。 +--- + +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/zh/python-net/working-with-facades/pdffileinfo/page-information/_index.md b/zh/python-net/working-with-facades/pdffileinfo/page-information/_index.md new file mode 100644 index 0000000000..2ca8b28ff3 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileinfo/page-information/_index.md @@ -0,0 +1,18 @@ +--- +title: 页面信息 +type: docs +weight: 20 +url: /zh/python-net/page-information/ +description: 本文说明了如何使用 Aspose.PDF for Python 从 PDF 页面提取关键布局和定位细节。 +lastmod: "2026-06-08" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 检索 PDF 页面信息和偏移量 +Abstract: PDF 页面可能在尺寸、旋转和内部内容定位上有所不同。Get Page Information 和 Get Page Offset 功能为开发者提供每页布局的完整视图。Get Page Information 返回页面宽度、高度和旋转角度,而 Get Page Offset 检索以英寸为单位的 X 和 Y 偏移量。这些方法一起使用,可实现文本、图像、批注及其他内容的精确对齐,支持单页和多页的自动化工作流。 +--- + +- [获取页面信息](/pdf/zh/python-net/get-page-info/) +- [获取页面偏移](/pdf/zh/python-net/get-page-offset/) diff --git a/zh/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md b/zh/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md new file mode 100644 index 0000000000..d2c45131a0 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileinfo/page-information/get-page-info/_index.md @@ -0,0 +1,50 @@ +--- +title: 获取页面信息 +type: docs +weight: 10 +url: /zh/python-net/get-page-info/ +description: 了解如何使用 Aspose.PDF for Python 以编程方式访问 PDF 的页面级信息。本指南展示了如何检索 PDF 文档中特定页面的宽度、高度、旋转角度和偏移量。 +lastmod: "2026-06-08" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python 获取 PDF 页面信息 +Abstract: 该函数提取 PDF 页面 的宽度、高度、旋转角度以及水平方向 (X) 和垂直方向 (Y) 的偏移量。这些属性以点为单位返回,反映页面的实际尺寸和 PDF 中内容的位置。函数会打印检索到的数值,使开发者能够了解页面布局和方向,以便进行进一步的 PDF 操作。 +--- + +‘get_page_information’ 实用函数帮助开发者了解 PDF 页面 的结构和布局。每个 PDF 页面可能拥有不同的尺寸、旋转角度和内部偏移,这可能会影响内容放置或自动化任务。 + +它能够检索 PDF 文件中特定页面的关键元数据和布局信息。Aspose.PDF Facades API 提供诸如页面宽度、高度、旋转角度以及 X/Y 偏移等细节。这些信息对于页面布局分析、注释放置或自动化 PDF 处理等任务至关重要。 + +1. 创建一个 PDF facade 对象。 +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/zh/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md b/zh/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md new file mode 100644 index 0000000000..bc09110bc2 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileinfo/page-information/get-page-offset/_index.md @@ -0,0 +1,45 @@ +--- +title: 获取页面偏移 +type: docs +weight: 20 +url: /zh/python-net/get-page-offset/ +description: 此示例演示如何使用 PdfFileInfo 获取特定页面的 X 和 Y 偏移量,并将其转换为英寸,以进行精确的布局和定位分析。 +lastmod: "2026-06-08" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Python 获取 PDF 页面偏移 +Abstract: ‘get_page_offsets’ 函数提取 PDF 文件中每页的水平 (X) 和垂直 (Y) 偏移量。这些偏移量表示页面内容相对于 PDF 原点的位置。通过将点转换为英寸,该函数提供精确、可读性强的度量,可用于注释、图像或文本的准确放置。它支持多页 PDF,旨在为从事 PDF 布局、自动化或内容对齐任务的开发者提供帮助。 +--- + +‘get_page_offsets’ 函数为开发者提供 PDF 文件中页面的精确水平 (X) 和垂直 (Y) 偏移量。在 PDF 文档中,每页可能拥有不同于页面左上角的内部原点,这会影响文本、图像、注释或其他内容的定位。 + +通过使用 Aspose.PDF Facades,此函数提取这些以点为单位的偏移量并将其转换为英寸,以便于解释。它支持多页 PDF,使其适用于需要精确内容放置的自动化工作流。 + +1. 创建 PDF facade 对象。 +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/zh/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md b/zh/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md new file mode 100644 index 0000000000..1587142d03 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileinfo/pdf-metadata/_index.md @@ -0,0 +1,20 @@ +--- +title: PDF 元数据 +type: docs +weight: 30 +url: /zh/python-net/pdf-metadata/ +description: 本文介绍了如何使用 Aspose.PDF for Python 访问、修改和保存 PDF 文档中的元数据。 +lastmod: "2026-06-08" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中管理 PDF 元数据 +Abstract: PDF 元数据包含有关文档的信息,例如标题、作者、关键字和创建日期,这有助于对文档进行编目、搜索和维护完整性。使用 Aspose.PDF,开发者可以通过编程方式 Get PDF Metadata、Set PDF Metadata values、Clear PDF Metadata,并将更改保存为标准 PDF 元数据或 XMP 格式。这种综合方法能够对文档属性进行精确控制,并确保在工作流和应用程序之间保持一致的处理。 +--- + +- [获取 PDF 元数据](/pdf/zh/python-net/get-pdf-metadata/) +- [设置 PDF 元数据](/pdf/zh/python-net/set-pdf-metadata/) +- [清除 PDF 元数据](/pdf/zh/python-net/clear-pdf-metadata/) +- [使用 XMP 保存元数据](/pdf/zh/python-net/save-metadata-with-xmp/) diff --git a/zh/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md b/zh/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md new file mode 100644 index 0000000000..56ba0aa48b --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileinfo/pdf-metadata/clear-pdf-metadata/_index.md @@ -0,0 +1,46 @@ +--- +title: 清除 PDF 元数据 +type: docs +weight: 10 +url: /zh/python-net/clear-pdf-metadata/ +description: 使用 Aspose.PDF for Python via .NET 删除 PDF 文档中的所有元数据。 +lastmod: "2026-06-08" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python 清除 PDF 元数据 +Abstract: 本指南解释了如何使用 Aspose.PDF for Python via .NET 删除 PDF 文档中的所有元数据。您将学习清除标准和自定义元数据字段并保存已净化的 PDF。这对于隐私、安全或为公开发布准备 PDF 非常有用。 +--- + +PDF 通常包含元数据,如标题、作者、关键字、创建日期和自定义字段。在某些情况下,您可能想要删除 PDF 的所有元数据,例如在分发或存档之前。Aspose.PDF 提供了 clear_info() 方法,可轻松删除所有元数据。清除后,您可以使用 save() 方法保存 PDF。 + +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/zh/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md b/zh/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md new file mode 100644 index 0000000000..06f87d6504 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileinfo/pdf-metadata/get-pdf-metadata/_index.md @@ -0,0 +1,58 @@ +--- +title: 获取 PDF 元数据 +type: docs +weight: 20 +url: /zh/python-net/get-pdf-metadata/ +description: 使用 Aspose.PDF for Python 提取并显示 PDF 文档的元数据。 +lastmod: "2026-06-08" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python 检索 PDF 元数据。 +Abstract: 本指南演示了如何使用 Aspose.PDF for Python 提取并显示 PDF 文档的元数据。您将学习如何访问标准 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/zh/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md b/zh/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md new file mode 100644 index 0000000000..6413778e54 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileinfo/pdf-metadata/save-metadata-with-xmp/_index.md @@ -0,0 +1,49 @@ +--- +title: 使用 XMP 保存元数据 +type: docs +weight: 30 +url: /zh/python-net/save-metadata-with-xmp/ +description: 使用 Aspose.PDF for Python via .NET 通过 XMP 保存 PDF 元数据 +lastmod: "2026-06-08" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python 通过 XMP 保存 PDF 元数据 +Abstract: 本指南演示了如何使用 Aspose.PDF for Python via .NET 通过 XMP(可扩展元数据平台)保存 PDF 元数据。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/zh/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md b/zh/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md new file mode 100644 index 0000000000..f8b290eed4 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffileinfo/pdf-metadata/set-pdf-metadata/_index.md @@ -0,0 +1,55 @@ +--- +title: 设置 PDF 元数据 +type: docs +weight: 50 +url: /zh/python-net/set-pdf-metadata/ +description: 使用 Aspose.PDF for Python via .NET 修改并保存 PDF 文档中的元数据。 +lastmod: "2026-06-08" +draft: false +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 Aspose.PDF for Python 更新 PDF 元数据 +Abstract: 本指南说明了如何使用 Aspose.PDF for Python via .NET 修改并保存 PDF 文档中的元数据。它演示了如何更新标准 PDF 属性,如标题、主题、关键字和创建者,以及自定义元数据字段。完成后,您将能够以编程方式更新 PDF 元数据并保存更改。 +--- + +PDF 文档可以包含标准元数据(Title、Subject、Keywords、Creator、Author)和以 XMP 属性存储的自定义元数据。Aspose.PDF 提供了一个简洁的 API 用于在 Python 中修改这些属性。本指南涵盖了如何更新这些字段并使用 the [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/zh/python-net/working-with-facades/pdffilesecurity/_index.md b/zh/python-net/working-with-facades/pdffilesecurity/_index.md new file mode 100644 index 0000000000..7164097ee7 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilesecurity/_index.md @@ -0,0 +1,25 @@ +--- +title: PdfFileSecurity 类 +type: docs +weight: 125 +url: /zh/python-net/pdffilesecurity-class/ +description: 了解如何在 Aspose.PDF for Python via .NET 中使用 PdfFileSecurity 类来加密和解密 PDF、修改密码以及控制文档特权。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfFileSecurity 在 Python 中加密、解密并控制 PDF 权限 +Abstract: 本节说明如何在 Aspose.PDF for Python via .NET 中使用 PdfFileSecurity 类以编程方式保护 PDF 文档。了解如何在 Python 应用中加密和解密 PDF 文件、修改密码以及配置文档特权和权限。 +--- + +这 `PdfFileSecurity` Aspose.PDF Facades 中的 class 用于保护 PDF 文档并控制用户对其的交互方式。它支持常见的安全工作流,如基于密码的加密、解密、密码轮换以及打印、复制和编辑的权限管理。 + +## 使用 PdfFileSecurity 可以做什么 + +使用本节中的文章来探索该部分支持的主要 PDF 安全任务 `PdfFileSecurity` 外观: + +- [使用 PdfFileSecurity 加密 PDF 文件](/pdf/zh/python-net/encrypt-pdf-file/) +- [使用 PdfFileSecurity 解密 PDF 文件](/pdf/zh/python-net/decrypt-pdf-file/) +- [使用 PdfFileSecurity 更改 PDF 密码](/pdf/zh/python-net/change-password/) +- [使用 PdfFileSecurity 设置 PDF 权限](/pdf/zh/python-net/set-privileges/) diff --git a/zh/python-net/working-with-facades/pdffilesecurity/change-password/_index.md b/zh/python-net/working-with-facades/pdffilesecurity/change-password/_index.md new file mode 100644 index 0000000000..f8e3dadc8e --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilesecurity/change-password/_index.md @@ -0,0 +1,154 @@ +--- +title: 更改 PDF 文件的密码 +type: docs +weight: 10 +url: /zh/python-net/change-password/ +description: 使用 Aspose.PDF for Python via .NET 更改受保护 PDF 文档的用户密码和所有者密码。 +lastmod: "2026-06-08" +sitemap: + changefreq: "monthly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 更新 PDF 密码 +Abstract: 了解如何使用 Aspose.PDF for Python via .NET 更改受保护 PDF 文件的用户密码和所有者密码。本示例演示了在保持现有加密和权限不变的情况下,安全地更新访问凭证的方法。 +--- + +## 更改用户和所有者密码 + +在许多情况下,您可能需要在不更改现有安全设置的前提下更新受保护 PDF 的密码。这在轮换凭证、转移所有权或增强文档安全性时非常有用。 + +'change_password' 方法属于 [PdfFileSecurity](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesecurity/) class 让您: + +- 更新用户密码(打开文档所需) +- 更新所有者密码(用于控制权限) +- 保留当前的加密和权限设置 + +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 文档时,单纯更改密码可能不足。您可能还需要调整权限,例如打印、复制或编辑权利。 + +了解如何在使用 Aspose.PDF for Python via .NET 重置 PDF 安全设置的同时更新用户密码和所有者密码。本示例展示了如何重新定义文档权限和加密强度以及新的访问凭证。 + +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) +``` + +## 尝试更改密码而不抛出异常 + +在某些工作流中,特别是批处理或自动化系统中,避免可能中断执行的异常非常重要。与其抛出错误,您可能更倾向于使用一种报告成功或失败的安全操作。 + +的 \u0027try_change_password\u0027 方法 [PdfFileSecurity](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesecurity/) 类通过以下方式提供此功能: + +1. 创建一个 'PdfFileSecurity' 对象。 +1. 使用 \u0027bind_pdf()\u0027 方法加载 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/zh/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md b/zh/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md new file mode 100644 index 0000000000..5c428c3e06 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilesecurity/decrypt-pdf-file/_index.md @@ -0,0 +1,91 @@ +--- +title: 解密 PDF 文件 +type: docs +weight: 20 +url: /zh/python-net/decrypt-pdf-file/ +description: 本指南说明如何移除诸如打印、复制和编辑等限制,以获得对 PDF 文档的完全访问权限。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 移除 PDF 的密码保护 +Abstract: 本文演示如何使用所有者密码解密 PDF 文件。它涵盖了移除限制打印、编辑或复制内容等操作的安全限制的过程。通过应用正确的所有者密码,用户可以解锁文档并重新获得对其功能的全部控制。 +--- + +## 使用所有者密码解密 PDF + +使用 Aspose.PDF for Python via .NET 的所有者密码解密受密码保护的 PDF 文档。此操作会移除加密并允许对文档进行无限制访问。 + +1. 创建一个 'PdfFileSecurity' 对象。 +1. 使用 'bind_pdf()' 方法加载加密的 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 + + +# 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 文档通常受到密码保护以限制访问和使用。要完全访问或修改此类文档,您可能需要移除加密。使用 Aspose.PDF for Python via .NET,利用所有者密码解密受保护的 PDF 文档,以移除加密和访问限制。 + +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/zh/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md b/zh/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md new file mode 100644 index 0000000000..4d6c3ea2db --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilesecurity/encrypt-pdf-file/_index.md @@ -0,0 +1,151 @@ +--- +title: 加密 PDF 文件 +type: docs +weight: 30 +url: /zh/python-net/encrypt-pdf-file/ +description: 加密 PDF 文档并配置权限,以控制用户对文件的操作。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 加密 PDF 并控制用户操作 +Abstract: 了解如何使用 Aspose.PDF for Python via .NET 加密 PDF 并定义特定的用户权限。本指南展示了如何在保持文档安全的同时,允许或限制诸如打印和复制等操作。 +--- + +## 使用用户密码和所有者密码加密 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/zh/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md b/zh/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md new file mode 100644 index 0000000000..b41b524357 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilesecurity/set-privileges/_index.md @@ -0,0 +1,147 @@ +--- +title: 为现有 PDF 文件设置权限 +type: docs +weight: 40 +url: /zh/python-net/set-privileges/ +description: 设置和管理 PDF 文档权限,以控制用户的打印、复制和编辑等操作。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 管理 PDF 权限和访问控制 +Abstract: 了解如何通过使用 Aspose.PDF for Python via .NET 设置文档权限来控制用户对 PDF 的操作。本指南涵盖了在有密码或无密码的情况下应用权限,以限制打印、复制或编辑等操作。 +--- + +## 在无密码情况下设置 PDF 权限 + +了解如何在不指定用户或所有者密码的情况下,使用 Aspose.PDF for Python via .NET 为 PDF 应用文档权限。此代码片段演示了在保持文档可访问的同时,如何控制允许的操作。 + +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. 使用 \u0027bind_pdf()\u0027 方法加载源 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/zh/python-net/working-with-facades/pdffilesignature/_index.md b/zh/python-net/working-with-facades/pdffilesignature/_index.md new file mode 100644 index 0000000000..3489148eed --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilesignature/_index.md @@ -0,0 +1,82 @@ +--- +title: PdfFileSignature 类 +type: docs +weight: 60 +url: /zh/python-net/pdffilesignature-class/ +description: 探索如何在 Python 中使用 Aspose.PDF 的 PdfFileSignature 类来添加、验证和移除 PDF 文档的数字签名。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +- [PDF 签名](/pdf/zh/python-net/pdf-signing/) +- [PDF 认证](/pdf/zh/python-net/pdf-certification/) +- [签名管理](/pdf/zh/python-net/signature-management/) +- [签名验证](/pdf/zh/python-net/signature-verification/) +- [签名信息](/pdf/zh/python-net/signature-information/) +- [签名完整性检查](/pdf/zh/python-net/signature-integrity-checks/) +- [修订与权限](/pdf/zh/python-net/revision-permissions/) +- [签名提取](/pdf/zh/python-net/signature-extraction/) +- [使用权限管理](/pdf/zh/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/zh/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md b/zh/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md new file mode 100644 index 0000000000..d18d0a736f --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilesignature/pdf-certification/_index.md @@ -0,0 +1,85 @@ +--- +title: PDF 认证 +type: docs +weight: 30 +url: /zh/python-net/pdf-certification/ +description: 了解如何在 Python 中使用 PdfFileSignature 和 DocMDPSignature 通过不同的文档修改权限对 PDF 文档进行认证。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中使用 DocMDP 权限对 PDF 文档进行认证 +Abstract: 本文说明了如何使用 Aspose.PDF for Python via .NET 通过 PdfFileSignature 门面对 PDF 文档进行认证。它展示了如何创建 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 进行表单填写认证 + +当文档应保持已认证状态,但用户仍需完成交互式表单或继续对文件进行签名时,请使用此方法。该 `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/zh/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md b/zh/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md new file mode 100644 index 0000000000..f58d4249f2 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilesignature/pdf-signing/_index.md @@ -0,0 +1,182 @@ +--- +title: 签署 PDF 文档 +type: docs +weight: 10 +url: /zh/python-net/pdf-signing/ +description: 了解如何在 Python 中使用 PdfFileSignature 对 PDF 文档进行基于证书、具名和可见的数字签名。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中使用数字签名签署 PDF 文档 +Abstract: 本文展示了如何使用 Aspose.PDF for Python via .NET 通过 PdfFileSignature 门面对 PDF 文档进行签名。它涵盖了证书配置、使用基本参数进行签名、使用 PKCS7 对象进行签名、分配签名名称以及应用可见签名外观。 +--- + +Aspose.PDF for Python via .NET 提供了 [PdfFileSignature](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilesignature/) 用于对现有 PDF 文档应用数字签名的门面。使用证书文件,您可以以编程方式签署文档,将签名放置在页面上,分配签名元数据,并自定义签名的显示方式。 + +本文演示了几种常见的签名工作流: + +1. 创建并绑定一个 `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() +``` + +## 使用 PKCS7 对象签署 PDF + +使用一个 `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/zh/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md b/zh/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md new file mode 100644 index 0000000000..d84aee45ab --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilesignature/revision-permissions/_index.md @@ -0,0 +1,81 @@ +--- +title: 修订和权限 +type: docs +weight: 40 +url: /zh/python-net/revision-permissions/ +description: 了解如何使用 Python 中的 PdfFileSignature 检查 PDF 文件中的签名修订、文档修订和认证权限。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中读取 PDF 签名修订和访问权限数据 +Abstract: 本文阐述了如何使用 Aspose.PDF for Python via .NET 检查已签名或已认证 PDF 文件中的修订和权限信息。它展示了如何获取签名的修订号、统计文档的总修订次数,以及从认证的 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/zh/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md b/zh/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md new file mode 100644 index 0000000000..73efd7732a --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilesignature/signature-extraction/_index.md @@ -0,0 +1,62 @@ +--- +title: 签名提取 +type: docs +weight: 50 +url: /zh/python-net/signature-extraction/ +description: 了解如何使用 Python 中的 PdfFileSignature 从已签名的 PDF 中提取签名图像和签署证书。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中从 PDF 提取签名图像和证书 +Abstract: 本文说明了如何使用 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. 提取与签名关联的可视图像。 +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/zh/python-net/working-with-facades/pdffilesignature/signature-information/_index.md b/zh/python-net/working-with-facades/pdffilesignature/signature-information/_index.md new file mode 100644 index 0000000000..874ef59291 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilesignature/signature-information/_index.md @@ -0,0 +1,111 @@ +--- +title: 签名信息 +type: docs +weight: 60 +url: /zh/python-net/signature-information/ +description: 了解如何使用 Python 中的 PdfFileSignature 从已签名的 PDF 文件中读取签名名称、签署者详细信息、时间戳以及签名元数据。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中读取 PDF 文档的签名详细信息 +Abstract: 本文说明了如何使用 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. 获取签署日期和时间。 +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/zh/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md b/zh/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md new file mode 100644 index 0000000000..357c56c5e4 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilesignature/signature-integrity-checks/_index.md @@ -0,0 +1,62 @@ +--- +title: 签名完整性检查 +type: docs +weight: 70 +url: /zh/python-net/signature-integrity-checks/ +description: 了解如何使用 Python 中的 PdfFileSignature 检查 PDF 签名是否覆盖整个文档并验证已签署文档的完整性。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中验证 PDF 签名覆盖范围和完整性 +Abstract: 本文解释了如何使用 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. 验证已签名 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/zh/python-net/working-with-facades/pdffilesignature/signature-management/_index.md b/zh/python-net/working-with-facades/pdffilesignature/signature-management/_index.md new file mode 100644 index 0000000000..8d38674aa4 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilesignature/signature-management/_index.md @@ -0,0 +1,61 @@ +--- +title: 签名管理 +type: docs +weight: 80 +url: /zh/python-net/signature-management/ +description: 了解如何使用 Python 中的 PdfFileSignature 从 PDF 文档中删除数字签名,并可选地清理签名字段。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中删除 PDF 签名并清理签名字段 +Abstract: 本文阐述了如何使用 Aspose.PDF for Python via .NET 管理 PDF 文档中现有的数字签名。它展示了如何从 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/zh/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md b/zh/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md new file mode 100644 index 0000000000..210a21fcbe --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilesignature/signature-verification/_index.md @@ -0,0 +1,60 @@ +--- +title: 签名验证 +type: docs +weight: 90 +url: /zh/python-net/signature-verification/ +description: 了解如何使用 Python 中的 PdfFileSignature 验证数字签名并检查 PDF 是否包含签名。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中验证 PDF 签名 +Abstract: 本文解释了如何使用 Aspose.PDF for Python via .NET 验证 PDF 文档中的数字签名。它展示了如何验证现有签名以及如何检查 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/zh/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md b/zh/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md new file mode 100644 index 0000000000..1bdbe975c3 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilesignature/usage-rights-management/_index.md @@ -0,0 +1,62 @@ +--- +title: 使用权限管理 +type: docs +weight: 100 +url: /zh/python-net/usage-rights-management/ +description: 了解如何使用 PdfFileSignature 在 Python 中检测并移除 PDF 文档的使用权限。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 在 Python 中移除 PDF 使用权限 +Abstract: 本文解释了如何使用 Aspose.PDF for Python via .NET 检查并移除 PDF 文档的使用权限。它展示了如何检查 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/zh/python-net/working-with-facades/pdffilestamp/_index.md b/zh/python-net/working-with-facades/pdffilestamp/_index.md new file mode 100644 index 0000000000..963a07d025 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilestamp/_index.md @@ -0,0 +1,25 @@ +--- +title: PdfFileStamp 类 +type: docs +weight: 155 +url: /zh/python-net/pdffilestamp-class/ +description: 了解如何在 Aspose.PDF for Python via .NET 中使用 PdfFileStamp 类向 PDF 文档添加页眉、页脚、页码和水印。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfFileStamp 在 Python 中为 PDF 添加页眉、页脚、页码和水印 +Abstract: 本节说明如何在 Aspose.PDF for Python via .NET 中使用 PdfFileStamp 外观向 PDF 文档添加重复内容。了解如何在 Python 应用程序中以编程方式在 PDF 页面上放置页眉、页脚、页码和水印。 +--- + +这 `PdfFileStamp` Aspose.PDF Facades 中的 class 旨在向 PDF 页面添加重复的可视内容。当您需要在文档中应用页眉、页脚、页码或水印,而无需手动编辑每一页时,它非常有用。 + +## 使用 PdfFileStamp 可以做的事 + +使用本节中的文章来探索该支持的主要盖章任务 `PdfFileStamp` 外观: + +- [使用 PdfFileStamp 为 PDF 页面添加页脚](/pdf/zh/python-net/add-footer/) +- [使用 PdfFileStamp 为 PDF 页面添加页眉](/pdf/zh/python-net/add-header/) +- [使用 PdfFileStamp 为 PDF 文档添加页码](/pdf/zh/python-net/page-number/) +- [使用 PdfFileStamp 为 PDF 页面添加印章](/pdf/zh/python-net/add-stamp/) diff --git a/zh/python-net/working-with-facades/pdffilestamp/add-footer/_index.md b/zh/python-net/working-with-facades/pdffilestamp/add-footer/_index.md new file mode 100644 index 0000000000..7a87dd8ec6 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilestamp/add-footer/_index.md @@ -0,0 +1,84 @@ +--- +title: 向 PDF 添加页脚 +type: docs +weight: 10 +url: /zh/python-net/add-footer/ +description: 学习如何在 Python 中使用 PdfFileStamp 为 PDF 页面添加文本和图像页脚。 +lastmod: "2026-06-08" +TechArticle: true +AlternativeHeadline: 在 Python 中为 PDF 添加文本和图像页脚 +Abstract: 本文阐述了如何使用 Aspose.PDF for Python via .NET 通过 PdfFileStamp 外观向 PDF 文档添加页脚内容。它展示了如何添加文本页脚、放置图像页脚,以及在保存更新的 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/zh/python-net/working-with-facades/pdffilestamp/add-header/_index.md b/zh/python-net/working-with-facades/pdffilestamp/add-header/_index.md new file mode 100644 index 0000000000..e8d9fb181a --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilestamp/add-header/_index.md @@ -0,0 +1,97 @@ +--- +title: 向 PDF 添加页眉 +type: docs +weight: 20 +url: /zh/python-net/add-header/ +description: 了解如何使用 PdfFileStamp 在 Python 中为 PDF 页面添加文字和图像页眉。 +lastmod: "2026-06-08" +TechArticle: true +AlternativeHeadline: 在 Python 中为 PDF 添加文字和图像页眉 +Abstract: 本文解释了如何使用 Aspose.PDF for Python via .NET 通过 PdfFileStamp facade 向 PDF 文档添加页眉内容。它展示了如何添加文字页眉、放置图像页眉以及在保存更新的 PDF 之前应用自定义页眉边距。 +--- + +Aspose.PDF for Python via .NET 提供了 [PdfFileStamp](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdffilestamp/) 用于向 PDF 页面添加重复内容的 facade。您可以使用它在每页顶部放置文字或图像页眉,并调整页眉边距以控制位置。 + +## 添加文本标题 + +使用 `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/zh/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md b/zh/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md new file mode 100644 index 0000000000..5c98e39634 --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilestamp/add-page-number/_index.md @@ -0,0 +1,122 @@ +--- +title: 在 PDF 中添加页码 +type: docs +weight: 30 +url: /zh/python-net/page-number/ +description: 了解如何在 Python 中使用 PdfFileStamp 为 PDF 文档添加页码。 +lastmod: "2026-06-08" +TechArticle: true +AlternativeHeadline: 在 Python 中为 PDF 添加页码 +Abstract: 本文说明了如何使用 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_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 文档。它利用 Aspose.PDF 中的 PdfFileStamp 类在所有页面上应用一致的编号。 + +```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/zh/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md b/zh/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md new file mode 100644 index 0000000000..d5670f8fdd --- /dev/null +++ b/zh/python-net/working-with-facades/pdffilestamp/add-stamp/_index.md @@ -0,0 +1,46 @@ +--- +title: 将印章添加到 PDF +type: docs +weight: 40 +url: /zh/python-net/add-stamp/ +description: 学习如何在 Python 中使用 PdfFileStamp 向 PDF 页面添加印章。 +lastmod: "2026-06-08" +TechArticle: true +AlternativeHeadline: 在 Python 中向 PDF 添加文本印章 +Abstract: 本文说明了如何使用 Aspose.PDF for Python via .NET 通过 PdfFileStamp 外观向 PDF 文档添加印章内容。它展示了如何创建印章、在页面上定位、控制旋转和不透明度,并保存更新后的 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/zh/python-net/working-with-facades/pdfviewer/_index.md b/zh/python-net/working-with-facades/pdfviewer/_index.md new file mode 100644 index 0000000000..bc41d2cce7 --- /dev/null +++ b/zh/python-net/working-with-facades/pdfviewer/_index.md @@ -0,0 +1,115 @@ +--- +title: PdfViewer 类 +type: docs +weight: 135 +url: /zh/python-net/pdfviewer-class/ +description: 了解如何在 Aspose.PDF for Python via .NET 中使用 PdfViewer 类来解码所有 PDF 页面、解码特定页面,并检查与查看器相关的 PDF 元数据。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +TechArticle: true +AlternativeHeadline: 使用 PdfViewer 在 Python 中解码 PDF 页面并检查查看器数据 +Abstract: 本文说明了如何在 Aspose.PDF for Python via .NET 中使用 PdfViewer 门面进行页面解码和查看器相关的检查任务。了解如何解码所有 PDF 页面、呈现特定页面,以及检查诸如页面计数、坐标类型和分辨率等属性。 +--- + +Aspose.PDF for Python via .NET 提供了 [PdfViewer](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/pdfviewer/) 用于处理 PDF 查看和页面解码场景的外观。一个常见的用例是将 PDF 页面转换为图像对象,然后可以将其保存到磁盘。 + +## 创建可复用的 PdfViewer 辅助类 + +在解码页面或读取与查看器相关的属性之前,创建一个小的帮助程序来初始化并返回一个 `PdfViewer` 实例。这使下面的示例保持自包含,并清楚地说明在将查看器对象绑定到 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 +``` + +## 解码所有 PDF 页面 + +使用 `decode_all_pages()` 当您想将 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 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() +``` + +## 解码特定的 PDF 页面 + +使用 `decode_page()` 当您只需要文档中的单页时。这在生成预览、缩略图或特定页面的导出时非常有用。 + +```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() +``` + +## 检查 PDF 元数据 + +这 `inspect_pdf_metadata` 函数演示如何使用 Aspose.PDF 打开 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 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/zh/python-net/working-with-facades/stamp/_index.md b/zh/python-net/working-with-facades/stamp/_index.md new file mode 100644 index 0000000000..adda11e449 --- /dev/null +++ b/zh/python-net/working-with-facades/stamp/_index.md @@ -0,0 +1,228 @@ +--- +title: Stamp 类 +type: docs +weight: 150 +url: /zh/python-net/stamp-class/ +description: 了解如何使用 Stamp 类在 Python 中向 PDF 文档添加图像、PDF 和基于文本的印章。 +lastmod: "2026-06-08" +sitemap: + changefreq: "weekly" + priority: 0.7 +--- + +Aspose.PDF for Python via .NET 提供了 [印章](https://reference.aspose.com/pdf/python-net/aspose.pdf.facades/stamp/) 用于在 PDF 页面上放置可重复使用的可视内容的类。Stamp 可以基于文字、图像,甚至来自其他 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()` 当印章应显示图像(例如徽标、徽章或图标)时。绑定图像后,您可以在将其添加到文档之前设置印章 ID 和原点。 + +```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() +``` + +## 添加带文本状态的文字印章 + +使用 `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() +``` + +## 添加背景图像印章 + +当图像应显示在页面内容后面时,使用背景印章。您还可以控制印章的不透明度、旋转、质量、大小和位置,以创建水印样式的效果。 + +```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() +``` + +## 相关外观主题 + +- [在 Python 中使用 PDF Facade](/pdf/zh/python-net/working-with-facades/) +- [使用 PdfFileStamp 添加页眉、页脚和印章](/pdf/zh/python-net/pdffilestamp-class/) +- [在 Python 中为 PDF 文件添加页面印章](/pdf/zh/python-net/add-stamp/)