C# 新增文字、圖片到PDF文件(基於Spire.Cloud.PDF.SDK)
阿新 • • 發佈:2020-04-24
Spire.Cloud.PDF.SDK提供了介面PdfTextApi及PdfImagesApi用於新增文字和圖片到PDF文件,新增文字時,可格式化文字樣式,包括文字字型型別、字號、字型樣式、文字顏色、字元間距、行距、首行縮排、文字對齊方式、文字環繞方式等;新增圖片時,可格式化圖片,包括圖片位置、高度、寬度等。本文將通過C#程式碼演示如何實現以上內容操作。
使用工具:
- Spire.Cloud.PDF.SDK
- Visual Studio
必要步驟:
步驟一:dll檔案獲取及匯入
方法1. 通過官網本地下載SDK檔案包。(須在e-iceblue中國官網線上編輯板塊中註冊賬號並登入)
下載後,解壓檔案,將Spire.Cloud.Pdf.Sdk.dll檔案及其他三個dll新增引用至VS程式;
方法2.在程式中通過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 { static String appId = "App ID"; static String appKey = "App Key"; static void Main(string[] args) { //配置賬號資訊 Configuration PdfConfiguration = newConfiguration(appId,appKey); PdfTextApi PdfTextApi = new PdfTextApi(PdfConfiguration); string name = "sample.pdf";//源文件 string outPath = "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;//文字環繞方式 //呼叫方法新增文字 PdfTextApi.AddText(name,outPath,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 { static String appId = "App ID"; static String appKey = "App Key"; static void Main(string[] args) { //配置賬號資訊 Configuration PdfConfiguration = new Configuration(appId,appKey); PdfImagesApi pdfImagesApi = new PdfImagesApi(PdfConfiguration); string name = "sample.pdf";//源文件 string outPath = "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; //呼叫方法新增圖片 pdfImagesApi.AddImage(name,file,x,y,width,height,password); } } }
圖片新增效果:
(本文完)