将 PDF 页面转换为 PNG 图像是当您想生成缩略图或在 Web 应用程序中显示文档时的常见需求。 GroupDocs.Viewer Cloud SDK for Python 提供了一个强大的库,可在云端完整处理此转换。在本指南中,您将学习如何在 Python 中将 PDF 页面转换为 PNG 图像,涵盖安装、单页和批量处理,以及用于 REST 集成的等效 cURL 调用。完成后,您将拥有可直接使用的代码,能够适配任何 Python 项目。

先决条件和设置

在开始之前,请确保您具备以下内容:

  • 在开发机器上安装了 Python 3.7 或更高版本。
  • 拥有包含 client_id 和 client_secret 值的 GroupDocs Cloud 帐户。
  • 访问存放 PDF 文件的 GroupDocs 存储。

使用 pip 安装 SDK:

pip install groupdocs-viewer-cloud

接下来,配置您的凭据。将占位符值替换为您在 GroupDocs Cloud 仪表板中的值。

from groupdocs_viewer_cloud import Configuration

config = Configuration()
config.client_id = "YOUR_CLIENT_ID"
config.client_secret = "YOUR_CLIENT_SECRET"

您还需要导入将在整个教程中使用的主要 API 类。请参阅完整的 API 参考文档,位于 GroupDocs Viewer API Reference。

安装了 SDK 并设置了凭据后,您已准备好开始将 PDF 转换为 PNG 图像。

如何在 Python 中将 PDF 页面转换为 PNG 图像:逐步演练

步骤 1:加载源文档

创建一个 ViewerApi 实例,并将其指向存储在 GroupDocs Cloud 中的 PDF 文件。

from groupdocs_viewer_cloud import ViewerApi, ApiClient

api_client = ApiClient(configuration=config)
viewer = ViewerApi(api_client)

此对象将用于所有转换调用。

步骤 2:配置转换选项

将所需的输出格式设置为 PNG,并指定保存图像的文件夹。

from groupdocs_viewer_cloud import models

options = models.PdfConvertOptions()
options.file_path = "sample.pdf"          # Path in GroupDocs Cloud storage
options.format = "PNG"                    # Output format
options.output_path = "output/all_pages"  # Destination folder

如果只需要特定页面,也可以在此处定义 pages 列表。

步骤 3:转换所有页面

调用 convert_document 方法而不提供 pages 列表,以转换每一页。

request = models.ConvertDocumentRequest(options)
result = viewer.convert_document(request)

for page in result.pages:
    print(f"Page {page.page_number} saved as {page.path}")

每页都保存为输出文件夹中的单独 PNG 文件。

第 4 步:转换选定页面

如果只需要特定的页面,请在选项中添加 pages 属性。

options.pages = [1, 3, 5]   # Convert pages 1, 3 and 5 only
request = models.ConvertDocumentRequest(options)
result = viewer.convert_document(request)

for page in result.pages:
    print(f"Selected page {page.page_number} saved as {page.path}")

这让您对渲染哪些页面拥有细粒度的控制。

步骤 5:批量转换多个 PDF

遍历 PDF 文件列表,并将每个文件转换为其各自的 PNG 文件夹。

pdf_files = ["sample.pdf", "another_document.pdf", "third_file.pdf"]
output_root = "output/batch"

for pdf_path in pdf_files:
    base_name = os.path.splitext(os.path.basename(pdf_path))[0]
    out_folder = os.path.join(output_root, base_name)

options.file_path = pdf_path
    options.output_path = out_folder

request = models.ConvertDocumentRequest(options)
    result = viewer.convert_document(request)

for page in result.pages:
        print(f"[{pdf_path}] Page {page.page_number} saved as {page.path}")

这种方法可以轻松扩展以处理大型文档集合。

完整代码示例:如何在 Python 中将 PDF 页面转换为 PNG 图像 - 完整实现

以下脚本将所有部分组合在一起。它演示了转换所有页面、选定页面以及批量处理多个 PDF。

# Install the SDK (run once):
# pip install groupdocs-viewer-cloud

import os
from groupdocs_viewer_cloud import ViewerApi, ApiClient, Configuration, models

# -------------------- Configuration --------------------
# Replace with your actual GroupDocs Cloud credentials
config = Configuration()
config.client_id = "YOUR_CLIENT_ID"
config.client_secret = "YOUR_CLIENT_SECRET"

api_client = ApiClient(configuration=config)
viewer = ViewerApi(api_client)

# -------------------- Helper Functions --------------------
def convert_pdf_to_png_all_pages(input_pdf: str, output_folder: str):
    """
    Convert every page of a PDF to separate PNG images.
    """
    # Ensure output folder exists
    os.makedirs(output_folder, exist_ok=True)

options = models.PdfConvertOptions()
    options.file_path = input_pdf          # Path in GroupDocs Cloud storage
    options.format = "PNG"                 # Desired output format
    options.output_path = output_folder    # Folder in storage where PNGs will be saved
    # No pages list -> all pages are converted

request = models.ConvertDocumentRequest(options)
    result = viewer.convert_document(request)

for page in result.pages:
        print(f"Page {page.page_number} saved as {page.path}")

def convert_pdf_to_png_selected_pages(input_pdf: str, output_folder: str, pages: list):
    """
    Convert only the specified pages of a PDF to PNG images.
    """
    os.makedirs(output_folder, exist_ok=True)

options = models.PdfConvertOptions()
    options.file_path = input_pdf
    options.format = "PNG"
    options.output_path = output_folder
    options.pages = pages                     # e.g., [1, 3, 5]

request = models.ConvertDocumentRequest(options)
    result = viewer.convert_document(request)

for page in result.pages:
        print(f"Selected page {page.page_number} saved as {page.path}")

def batch_convert_pdfs_to_png(pdf_files: list, output_root: str):
    """
    Convert multiple PDF documents to PNG images in a single batch operation.
    Each PDF gets its own sub‑folder under `output_root`.
    """
    os.makedirs(output_root, exist_ok=True)

for pdf_path in pdf_files:
        # Derive a folder name from the PDF file name (without extension)
        base_name = os.path.splitext(os.path.basename(pdf_path))[0]
        out_folder = os.path.join(output_root, base_name)

options = models.PdfConvertOptions()
        options.file_path = pdf_path
        options.format = "PNG"
        options.output_path = out_folder

request = models.ConvertDocumentRequest(options)
        result = viewer.convert_document(request)

for page in result.pages:
            print(f"[{pdf_path}] Page {page.page_number} saved as {page.path}")

# -------------------- Example Usage --------------------
if __name__ == "__main__":
    # Paths are relative to the root of your GroupDocs Cloud storage
    input_pdf = "sample.pdf"
    all_pages_output = "output/all_pages"
    selected_pages_output = "output/selected_pages"
    batch_output_root = "output/batch"

# 1. Convert all pages of a PDF to PNG
    convert_pdf_to_png_all_pages(input_pdf, all_pages_output)

# 2. Convert only pages 1, 3 and 5 of the same PDF to PNG
    convert_pdf_to_png_selected_pages(input_pdf, selected_pages_output, pages=[1, 3, 5])

# 3. Batch convert several PDFs
    pdf_list = ["sample.pdf", "another_document.pdf", "third_file.pdf"]
    batch_convert_pdfs_to_png(pdf_list, batch_output_root)

注意: 此代码示例演示了核心功能。在将其用于项目之前,请确保更新所有文件路径和配置值以匹配实际环境,验证已正确安装所有必需的依赖项,并在开发环境中彻底测试。如果遇到任何问题,请参阅官方文档或联系支持团队获取帮助。

使用 cURL 通过 REST API 将 PDF 转换为 PNG

相同的转换可以通过 GroupDocs Viewer 的 REST 端点执行。下面是您将要执行的典型 cURL 调用。

首先,使用您的客户端凭据获取访问令牌。

curl -X POST "https://api.groupdocs.cloud/v2.0/oauth2/token" \
     -H "Content-Type: application/json" \
     -d '{"client_id":"YOUR_CLIENT_ID","client_secret":"YOUR_CLIENT_SECRET"}'

假设响应中包含 "access_token":"YOUR_ACCESS_TOKEN",请在后续调用中使用该令牌。

将 PDF 文件上传到 GroupDocs 存储。

curl -X POST "https://api.groupdocs.cloud/v2.0/storage/file/upload?path=sample.pdf" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -F "file=@/path/to/local/sample.pdf"

请求将所有页面转换为 PNG。

curl -X POST "https://api.groupdocs.cloud/v2.0/viewer/pdf/convert?format=PNG&outputPath=output/all_pages" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{"filePath":"sample.pdf"}'

如果只需要特定页面,请添加 pages 查询参数(例如,pages=1,3,5)。

下载生成的 PNG 文件。

curl -X GET "https://api.groupdocs.cloud/v2.0/storage/file/download?path=output/all_pages/page1.png" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -o page1.png

有关请求参数的更多详细信息,请参阅 GroupDocs Viewer API Reference。

PDF 转 PNG 的转换选项:设置和微调

SDK 在 PdfConvertOptions 中公开了多个可调选项:

  • format - 必须设置为 "PNG" 以生成 PNG 图像。
  • output_path - 在 GroupDocs 存储中写入 PNG 文件的目标文件夹。
  • pages - 一个可选的页面 numbers 列表,用于转换(例如 [1, 3, 5])。

您还可以通过使用 API 参考中记录的其他属性来控制图像质量、DPI 和颜色模式。例如,要更改 DPI,您可以设置 options.dpi = 300(此属性未在基本代码示例中显示)。

结论

您现在已经了解如何在 Python 中使用 GroupDocs.Viewer Cloud SDK for Python 将 PDF 页面转换为 PNG 图像。该库能够以最少的代码处理单页、选择页和批量转换,等效的 cURL 命令则让您可以在任何能够发出 HTTP 请求的环境中集成相同的功能。请记得在产品页面查看授权选项;GroupDocs 提供基于订阅的定价,您还可以从 临时许可证页面 获取用于测试的临时许可证。立即开始在您的应用程序中集成 PDF 转 PNG 转换,享受无缝的文档渲染体验。

常见问题

  • 如何使用 Python 从 PDF 中提取 PNG 图像?
    使用 SDK 的 convert_pdf_to_png_all_pages 或 convert_pdf_to_png_selected_pages 方法。它们接受存储在 GroupDocs Cloud 中的 PDF,并为每页输出 PNG 文件。请参阅上面的完整示例。

  • 是否可以仅将 PDF 的某些页面转换为 PNG?
    是的。将 PdfConvertOptions 上的 pages 属性设置为您想要渲染的页面编号列表。API 参考提供了此属性的详细信息。

  • 我可以一次性批量将多个 PDF 转换为 PNG 吗?
    batch_convert_pdfs_to_png 辅助函数遍历 PDF 列表,为每个 PDF 创建单独的输出文件夹,使您能够使用单个脚本处理大量文档。

  • What are the licensing options for GroupDocs Viewer Cloud?
    GroupDocs 提供基于使用量的灵活订阅计划。用于评估时,您可以从临时许可证页面请求临时许可证。

阅读更多