自訂 PDF 標頭,同時包含文字與圖形,是雲端報告解決方案的常見需求。 Aspose.PDF Cloud SDK for .NET 讓您能以 C# 透過簡單的 API 呼叫,程式化地將文字與圖像加入 PDF 標頭。在本教學中,您將看到完整的程式碼範例、cURL 替代方案,以及一步一步的說明。完成後,您將能在雲端環境中於所有 PDF 頁面嵌入品牌化的標頭。

在 C# 中向 PDF 標頭添加文字和圖像 - 完整程式碼示例

以下範例示範如何在 C# 中使用 Aspose.PDF Cloud SDK for .NET 為 PDF 標頭加入文字和圖像。

using System;
using System.Collections.Generic;
using System.IO;
using Aspose.Pdf.Cloud.Sdk.Api;
using Aspose.Pdf.Cloud.Sdk.Client;
using Aspose.Pdf.Cloud.Sdk.Model;

class Program
{
    static void Main()
    {
        // -------------------------------------------------
        // Configuration – replace with your actual App SID and API Key
        // -------------------------------------------------
        var config = new Configuration
        {
            ApiKey = new Dictionary<string, string> { { "api_key", "YOUR_API_KEY" } },
            Host = "https://api.aspose.cloud"
        };
        var pdfApi = new PdfApi(config);

// -------------------------------------------------
        // File names (local)
        // -------------------------------------------------
        string localPdfPath = "input.pdf";
        string localImagePath = "headerImage.png";
        string outputPdfPath = "output.pdf";

// -------------------------------------------------
        // Upload PDF to Aspose Cloud storage
        // -------------------------------------------------
        using (var pdfStream = File.OpenRead(localPdfPath))
        {
            pdfApi.UploadFile(Path.GetFileName(localPdfPath), pdfStream);
        }

// -------------------------------------------------
        // Upload image to Aspose Cloud storage
        // -------------------------------------------------
        using (var imgStream = File.OpenRead(localImagePath))
        {
            pdfApi.UploadFile(Path.GetFileName(localImagePath), imgStream);
        }

// -------------------------------------------------
        // Build HeaderFooter object with text and image
        // -------------------------------------------------
        var headerFooter = new HeaderFooter
        {
            // Text part
            TextState = new TextState
            {
                Value = "Confidential Document",
                FontSize = 14,
                Font = "Helvetica",
                FontStyle = FontStyles.Bold,
                ForegroundColor = new Color { A = 255, R = 255, G = 0, B = 0 } // Red color
            },
            // Image part
            Image = new Image
            {
                File = Path.GetFileName(localImagePath), // reference uploaded image
                Width = 100,
                Height = 30,
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin = new MarginInfo { Top = 5, Bottom = 5, Left = 5, Right = 5 }
            },
            // Header margin (optional)
            Margin = new MarginInfo { Top = 10, Bottom = 0, Left = 0, Right = 0 }
        };

// -------------------------------------------------
        // Apply header to all pages of the PDF
        // -------------------------------------------------
        pdfApi.PutHeaderFooter(Path.GetFileName(localPdfPath), headerFooter);

// -------------------------------------------------
        // Download the updated PDF
        // -------------------------------------------------
        using (var resultStream = pdfApi.GetDocument(Path.GetFileName(localPdfPath)))
        using (var fileStream = File.Create(outputPdfPath))
        {
            resultStream.CopyTo(fileStream);
        }

// -------------------------------------------------
        // Optional: clean up uploaded files from cloud storage
        // -------------------------------------------------
        pdfApi.DeleteFile(Path.GetFileName(localPdfPath));
        pdfApi.DeleteFile(Path.GetFileName(localImagePath));
    }
}

注意: 此程式碼範例展示了核心功能。在將其用於您的專案之前,請確保更新所有檔案路徑和設定值以符合實際環境,驗證所有必要的相依項已正確安裝,並在開發環境中徹底測試。如果您遇到任何問題,請參閱官方文件或聯繫支援團隊以獲得協助。

使用 cURL 在 PDF 標頭雲端插入文字和圖像

您可以使用 REST API 執行相同的操作。以下是必要的 cURL 命令。

# 1. Obtain an access token (replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET)
curl -X POST "https://api.aspose.cloud/connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
# 2. Upload the source PDF
curl -X PUT "https://api.aspose.cloud/v3.0/pdf/storage/file/input.pdf" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/pdf" \
  --data-binary "@input.pdf"
# 3. Upload the header image (PNG)
curl -X PUT "https://api.aspose.cloud/v3.0/pdf/storage/file/headerImage.png" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: image/png" \
  --data-binary "@headerImage.png"
# 4. Apply header with text and image
curl -X PUT "https://api.aspose.cloud/v3.0/pdf/input.pdf/headerfooter" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
        "TextState": {
            "Value": "Confidential Document",
            "FontSize": 14,
            "Font": "Helvetica",
            "FontStyle": "Bold",
            "ForegroundColor": { "A":255,"R":255,"G":0,"B":0 }
        },
        "Image": {
            "File": "headerImage.png",
            "Width": 100,
            "Height": 30,
            "HorizontalAlignment": "Center",
            "Margin": { "Top":5,"Bottom":5,"Left":5,"Right":5 }
        },
        "Margin": { "Top":10,"Bottom":0,"Left":0,"Right":0 }
      }'
# 5. Download the updated PDF
curl -X GET "https://api.aspose.cloud/v3.0/pdf/input.pdf" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -o output.pdf
<!--CODE_SNIPPET_END]-->

如需了解每個端點的詳細資訊,請參閱官方 API 文件。

## 分析在 C# 中向 PDF 標頭添加文字與圖片

了解程式碼如何在 C# 中向 PDF 標頭添加文字與圖片,可協助您在其他情境中進行調整。以下是一個簡明的步驟說明:

1. **設定組態** – `Configuration` 物件儲存您的 API 金鑰與主機 URL。  
   <!--CODE_SNIPPET_START-->
   ```csharp
   var [config](https://docs.fileformat.com/programming/config/) = new Configuration
   {
       ApiKey = new Dictionary<string, string> { { "api_key", "YOUR_API_KEY" } },
       Host = "https://api.aspose.cloud"
   };
  1. 上傳檔案UploadFile 將本機 PDF 與圖片上傳至 Aspose Cloud 儲存空間。

    pdfApi.UploadFile(Path.GetFileName(localPdfPath), pdfStream);
    pdfApi.UploadFile(Path.GetFileName(localImagePath), imgStream);
    
  2. 建立 HeaderFooterHeaderFooter 模型結合 TextState(文字)與 Image(圖片)物件。

    var headerFooter = new HeaderFooter
    {
        TextState = new TextState { Value = "Confidential Document", FontSize = 14, Font = "Helvetica", FontStyle = FontStyles.Bold, ForegroundColor = new Color { A = 255, R = 255, G = 0, B = 0 } },
        Image = new Image { File = Path.GetFileName(localImagePath), Width = 100, Height = 30, HorizontalAlignment = HorizontalAlignment.Center }
    };
    
  3. 套用標頭PutHeaderFooter 將標頭套用至指定 PDF 的每一頁。

    pdfApi.PutHeaderFooter(Path.GetFileName(localPdfPath), headerFooter);
    
  4. 下載與清理GetDocument 取得已修改的 PDF,DeleteFile 則從雲端儲存中刪除暫存檔案。

    var resultStream = pdfApi.GetDocument(Path.GetFileName(localPdfPath));
    pdfApi.DeleteFile(Path.GetFileName(localPdfPath));
    pdfApi.DeleteFile(Path.GetFileName(localImagePath));
    

如需更深入了解 HeaderFooter 類別,請參閱 API 參考文件。

安裝與設定 Aspose.PDF Cloud SDK for .NET

  1. 新增 NuGet 套件
   dotnet add package Aspose.PDF-Cloud
  1. 下載 SDK 二進位檔 - 您也可以從官方下載頁面取得最新發行版: Aspose.PDF Cloud SDK for .NET Download.

  2. 先決條件 - .NET 6.0 或更新版本、Aspose Cloud 帳戶,以及有效的客戶端憑證(App SID 與 API 金鑰)。

  3. 初始化客戶端 - 使用完整範例中顯示的相同組態程式碼連線至雲端服務。

安裝 SDK 並設定好憑證後,即可立即在 C# 中為 PDF 標頭加入文字與圖片。

結論

當您利用 Aspose.PDF Cloud SDK for .NET 的強大功能時,在 C# 中為 PDF 標頭加入文字與圖片變得相當簡單。此函式庫僅透過少量 API 呼叫即可處理檔案上傳、標頭建構與文件取得,非常適合雲端 PDF 處理流程。請務必保護您的 API 金鑰、遵守使用限制,並以不同頁面尺寸測試標頭佈局,以免發生溢位。 在正式環境部署時需要商業授權;授權費用資訊可於產品頁面查閱,亦可從臨時授權頁面取得評估用的臨時授權。立即開始整合品牌化標頭,為您的 PDF 賦予專業外觀。

常見問題

  • 如何在 C# 中使用雲端函式庫為 PDF 標頭加入文字與圖片?
    使用 HeaderFooter 模型定義 TextStateImage,然後呼叫 PutHeaderFooter。本文中的完整程式碼範例展示了具體步驟。

  • 我可以在不撰寫 C# 程式碼的情況下,於雲端為 PDF 標頭插入文字與圖片嗎?
    可以,您可以使用 REST 呼叫完成相同操作。cURL 範例提供了可直接使用的腳本,用於上傳檔案並套用標頭。

  • 標頭支援哪些圖片格式?
    API 支援常見格式,如 PNG 與 JPEG。請將圖片尺寸控制在合理範圍內(例如 100×30),以符合標頭邊距。

  • 在正式環境中執行此功能是否需要授權?
    正式環境使用需取得商業授權。請前往產品頁面了解價格,並可於臨時授權頁面先行評估 SDK 後再購買。

延伸閱讀