在Python SDK中压缩PDF

使用Cloud Python SDK优化PDF文档。

Get Started

如何通过Cloud Python SDK压缩PDF

为了压缩PDF,我们将使用 Aspose.PDF Cloud Python SDK。这个Cloud SDK帮助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。

  1. 安装Python SDK
  2. 定义配置类
  3. 初始化PDF API客户端
  4. 使用upload_document方法上传PDF文档
  5. 使用compress_pdf_document方法压缩PDF文档(在此示例中,我们压缩图像并降低其质量,您可以根据需要设置其他参数)。如果需要详细信息,请查看文档页面。
  6. 通过post_optimize_document()发送压缩请求。
  7. 下载结果PDF
 

使用Python压缩PDF


    import shutil
    import json
    import logging
    from pathlib import Path
    from asposepdfcloud import ApiClient, PdfApi, OptimizeOptions

    # Configure logging
    logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")


    class Config:
        """Configuration parameters."""
        CREDENTIALS_FILE = Path(r"Credentials/credentials.json")
        LOCAL_FOLDER = Path(r"C:\Samples")
        TEMP_FOLDER = 'TempPdfCloud'
        PDF_DOCUMENT_NAME = "sample.pdf"
        LOCAL_RESULT_DOCUMENT_NAME = "output_sample.pdf"

    class PdfCompress:
        """Class for compress 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
                stotage_path = Config.TEMP_FOLDER + '/' + Config.PDF_DOCUMENT_NAME
                try:
                    self.pdf_api.upload_file(stotage_path, 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.TEMP_FOLDER + '/' + 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 compress_pdf_document(self):
            """Compress the PDF document."""
            if self.pdf_api:
                optimize_options = OptimizeOptions(
                    allow_reuse_page_content=False,
                    compress_images=True,
                    image_quality=75,
                    link_duplcate_streams=False,
                    remove_unused_objects=False,
                    remove_unused_streams=False,            
                    unembed_fonts=False
                )        
            opts = {
                "options" : optimize_options,
                "folder" : Config.TEMP_FOLDER
            }
            try:
                response = self.pdf_api.post_optimize_document(Config.PDF_DOCUMENT_NAME, **opts)

                if response.code == 200:
                    logging.info(f"compress_pdf_document(): PDF document '{Config.PDF_DOCUMENT_NAME}' successfully compressed.")
                else:
                    logging.error(f"compress_pdf_document(): Failed to compress document. Response code: {response.code}")
            except Exception as e:
                logging.error(f"compress_pdf_document(): Error while compress document: {e}")


    if __name__ == "__main__":
        pdf_compress = PdfCompress()
        pdf_compress.upload_document()
        pdf_compress.compress_pdf_document()
        pdf_compress.download_result()
 

使用我们的Python库,您可以:

使用Aspose.PDF Cloud Python SDK压缩PDF文档。

  • 合并PDF文档。
  • 拆分PDF文件。
  • 将PDF转换为其他格式,反之亦然。
  • 操作注释。
  • 处理PDF中的图像等。
  • 您可以尝试我们的免费应用在线测试功能。