Spire.Cloud.SDK for .NET提供了接口PdfTextApi及PdfImagesApi用於添加文本和圖片到PDF文檔,添加文本時,可格式化文本樣式,包括文本字體類型、字號、字體樣式、文本顏色、字符間距、行距、首行縮進、文本對齊方式、文本環繞方式等;添加圖片時,可格式化圖片,包括圖片位置、高度、寬度等。本文將通過C#代碼演示如何實現以上內容操作。
使用工具:
- Spire.Cloud.SDK for .NET
- Visual Studio
必要步驟:
步驟一:dll文件獲取及導入。在VS程序中通過Nuget搜索下載,直接導入所有dll。
導入效果如下如所示:
步驟二:App ID及Key獲取。在“我的應用”板塊中創建應用以獲得App ID及App Key。
步驟三:源文檔上傳。在“文檔管理”板塊,上傳源文檔。這里可以建文件夾,將文檔存放在文件夾下。不建文件夾時,源文檔及結果文檔直接保存在根目錄。本文示例中,建了兩個文件夾,分別用於存放源文檔及結果文檔。(雲平台提供免費1 萬次調用次數和 2G 文檔內存)
C# 代碼示例
1. 添加文本到PDF
using System; using Spire.Cloud.Pdf.Sdk.Client; using Spire.Cloud.Pdf.Sdk.Api; using Spire.Cloud.Pdf.Sdk.Model; namespace AddText_Cloud.PDF { class Program { //配置AppID和AppKey static string appId = "App ID"; static string appKey = "App Key"; static string basePath = "https://api.e-iceblue.cn"; static Configuration Configuration = new Configuration(appId, appKey, basePath); static PdfTextApi textApi = new PdfTextApi(Configuration); static void Main(string[] args) { string name = "sample.pdf";//源文檔 string destFilePath = "output/AddText.pdf";//結果文檔路徑 int pageNumber = 2;//指定文本內容所在頁數 string folder = "input";//源文檔所在文件夾 Spire.Cloud.Pdf.Sdk.Model.Text text = new Spire.Cloud.Pdf.Sdk.Model.Text("This is a test. This is a test. This is a test. This is a test. This is a test. This is a test.", new Font(Font.FontTypeEnum.TrueType, "Arial", 13, Font.FontStyleEnum.Regular), new RectangleF(50, 320, 500, 200));//實例化文本信息(文本內容、字體類型、字號、字體樣式、文本位置) text.BackgroundColor = new Color(255, 244, 164, 96);//設置文本背景色 text.ForegroundColor = new Color(255, 135, 206, 235);//設置文本前景色 text.CharSpacing = 5;//字符間距 text.FirstLineIndent = 100;//首行縮進 text.LineSpacing = 15;//行距 text.HorizontalAlignment = Spire.Cloud.Pdf.Sdk.Model.Text.HorizontalAlignmentEnum.Left;//文本水平對齊方式 text.VerticalAlignment = Spire.Cloud.Pdf.Sdk.Model.Text.VerticalAlignmentEnum.Middle;//文本垂直對齊方式 text.WordSpacing = 12;//單詞間距 text.WordWrap = Spire.Cloud.Pdf.Sdk.Model.Text.WordWrapEnum.Character;//文本環繞方式 //調用方法添加文本 textApi.AddText(name, destFilePath, pageNumber, text, folder, null); } } }
文本添加效果:
2. 添加圖片到PDF
using Spire.Cloud.Pdf.Sdk.Api; using Spire.Cloud.Pdf.Sdk.Client; using System; using System.IO; namespace AddImg_Cloud.PDF { class Program { //配置AppID和AppKey static string appId = "App ID"; static string appKey = "App Key"; static string basePath = "https://api.e-iceblue.cn"; static Configuration Configuration = new Configuration(appId, appKey, basePath); static PdfImagesApi imageApi = new PdfImagesApi(Configuration); static void Main(string[] args) { string name = "sample.pdf";//源文檔 string destFilePath = "output/AddImg.pdf";//結果文檔路徑 int pageNumber = 2;//指定圖片所在文檔頁數 string folder = "input";//源文檔所在文件夾 string password = null;//源文檔密碼 System.IO.Stream file = new FileStream("logo.png", FileMode.Open);//打開圖片 //指定圖片位置及大小 float x = 50; float y = 320; float width = 200; float height = 200; //調用方法添加圖片 imageApi.AddImage(name, destFilePath, pageNumber, file, x, y, width, height, folder, password); } } }
圖片添加效果:
(本文完)