PNG
JPG
BMP
TIFF
PDF
如何通过云 Python SDK 向 PDF 添加链接
要将链接添加到 PDF,我们将使用 Aspose.PDF Cloud Python SDK。这个云 SDK 帮助 Python 程序员使用 Python 编程语言通过 Aspose.PDF REST API 开发基于云的 PDF 创建、注释、编辑和转换应用程序。只需在 Aspose for Cloud 创建一个账户并获取您的应用信息。一旦您拥有了 App SID 和密钥,您就可以开始使用 Aspose.PDF Cloud Python SDK。如果 Python 包托管在 Github 上,您可以直接从 Github 安装:
从 Github 安装
pip install git+https://github.com/aspose-pdf-cloud/aspose-pdf-cloud-python.git
包管理器控制台命令
pip install asposepdfcloud
通过 Python SDK 向 PDF 添加链接的步骤
Aspose.PDF Cloud 开发人员可以轻松地在短短几行代码中加载和添加链接到 PDF。
- 安装 Python SDK
- 将 PDF 文档上传到 Aspose 云服务器
- 从 Aspose 云服务器下载处理后的 PDF 文档
- 将新的超链接注释附加到 PDF 文档的特定页面
使用 Python 向 PDF 添加链接
import shutil
import json
import logging
from pathlib import Path
from asposepdfcloud import ApiClient, PdfApi, LinkAnnotation, LinkActionType, LinkHighlightingMode, Color, Link, Rectangle
# Configure logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
class Config:
"""Configuration parameters."""
CREDENTIALS_FILE = Path(r"C:\\Projects\\ASPOSE\\Pdf.Cloud\\Credentials\\credentials.json")
LOCAL_FOLDER = Path(r"C:\Samples")
PDF_DOCUMENT_NAME = "sample.pdf"
LOCAL_RESULT_DOCUMENT_NAME = "output_sample.pdf"
NEW_LINK_ACTION = "https://reference.aspose.cloud/pdf/"
PAGE_NUMBER = 2
LINK_RECT = Rectangle(llx=244.914, lly=488.622, urx=284.776, ury=498.588)
class PdfLinks:
"""Class for managing PDF links using Aspose PDF Cloud API."""
def __init__(self, credentials_file: Path = Config.CREDENTIALS_FILE):
self.pdf_api = None
self._init_api(credentials_file)
def _init_api(self, credentials_file: Path):
"""Initialize the API client."""
try:
with credentials_file.open("r", encoding="utf-8") as file:
credentials = json.load(file)
api_key, app_id = credentials.get("key"), credentials.get("id")
if not api_key or not app_id:
raise ValueError("init_api(): Error: Missing API keys in the credentials file.")
self.pdf_api = PdfApi(ApiClient(api_key, app_id))
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
logging.error(f"init_api(): Failed to load credentials: {e}")
def upload_document(self):
"""Upload a PDF document to the Aspose Cloud server."""
if self.pdf_api:
file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
try:
self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path))
logging.info(f"upload_document(): File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
except Exception as e:
logging.error(f"upload_document(): Failed to upload file: {e}")
def download_result(self):
"""Download the processed PDF document from the Aspose Cloud server."""
if self.pdf_api:
try:
temp_file = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
shutil.move(temp_file, str(local_path))
logging.info(f"download_result(): File successfully downloaded: {local_path}")
except Exception as e:
logging.error(f"download_result(): Failed to download file: {e}")
def append_link(self):
"""Append a new hyperlink annotation to a specific page in the PDF document."""
if self.pdf_api:
link_annotation = LinkAnnotation(
links=[Link(href=Config.NEW_LINK_ACTION)],
action_type= LinkActionType.GOTOURIACTION,
action=Config.NEW_LINK_ACTION,
highlighting=LinkHighlightingMode.INVERT,
color=Color(a=255, r=0, g=255, b=0),
rect=Config.LINK_RECT,
)
try:
response = self.pdf_api.post_page_link_annotations(
Config.PDF_DOCUMENT_NAME, Config.PAGE_NUMBER, [link_annotation]
)
if response.code == 200:
logging.info(f"append_link(): Link '{Config.NEW_LINK_ACTION}' added to page #{Config.PAGE_NUMBER}.")
else:
logging.error(f"append_link(): Failed to add link to the page. Response code: {response.code}")
except Exception as e:
logging.error(f"append_link(): Error while adding link: {e}")
if __name__ == "__main__":
pdf_links = PdfLinks()
pdf_links.upload_document()
pdf_links.append_link()
pdf_links.download_result()
在 PDF 中处理链接
向 PDF 添加链接可以增强可用性、互动性和可访问性。无论是用于导航、营销还是交叉引用,超链接都可以提高文档的有效性,使用户更容易找到相关内容并采取行动。 使用 Aspose.PDF Cloud Python SDK 将链接添加到 PDF 文档中。
使用我们的 Python 库,您可以:
- 合并 PDF 文档。
- 拆分 PDF 文件。
- 将 PDF 转换为其他格式,反之亦然。
- 操作注释。
- 处理 PDF 中的图像等。
- 您可以尝试我们的免费应用在线测试功能。