Spire.Cloud.PDF provides the PdfImagesApi interface, allowing developers to handle images in PDF. This article shows you how to add an image to PDF and how to extract images from a particular page by using this API.
Example 1. Add an image to PDF
using System;
using System.IO;
using Spire.Cloud.Pdf.Sdk.Api;
using Spire.Cloud.Pdf.Sdk.Client;
namespace AddImage
{
class Program
{
static String appId = "App ID";
static String appKey = "App Key";
static String baseUrl = "https://api.cloudxdocs.com";
//Create a Configuration object based on App ID, App Key and base Url
static Configuration pdfConfiguration = new Configuration(appId, appKey, baseUrl);
//Create a PdfImagesApi object
static PdfImagesApi pdfImagesApi = new PdfImagesApi(pdfConfiguration);
static void Main(string[] args)
{
//Specify the source document name
string name = "sample.pdf";
//Specify the result document path
string outPath = "output/AddImage.pdf";
//Specify the index of the page to add image
int pageNumber = 1;
//Load the image file
using (System.IO.Stream file = new FileStream("C:/Users/Administrator/Desktop/logo.png", FileMode.Open))
{
//Specify the x and y coordinate where the image will be added
float x = 10;
float y = 10;
//Specify the width and height of image
float? width = null;
float? height = null;
//Specify the password, set to null if there is no password in the original document
string password = null;
//Specify the folder where the source document is stored
string folder = "input";
//Use the default storage, set to null
string storage = null;
//Call AddImage method to insert image to the spcified coodinate of the selected page
pdfImagesApi.AddImage(name, outPath, pageNumber, file, x, y, width, height, folder, storage, password);
}
}
}
}
Example 2. Extract images from a page
using System;
using Spire.Cloud.Pdf.Sdk.Api;
using Spire.Cloud.Pdf.Sdk.Client;
namespace ExtractImage
{
class Program
{
static String appId = "App ID";
static String appKey = "App Key";
static String baseUrl = "https://api.cloudxdocs.com";
//Create a Configuration object based on App ID, App Key and base Url
static Configuration pdfConfiguration = new Configuration(appId, appKey, baseUrl);
//Create a PdfImagesApi object
static PdfImagesApi pdfImagesApi = new PdfImagesApi(pdfConfiguration);
static void Main(string[] args)
{
//Specify the source document name
string name = "Images.pdf";
//Specify the output file path
string outPath = "output/";
//Specify the index of the page to extract image
int pageNumber = 1;
//Specify the password, set to null if there is no password in the original document
string password = null;
//Use the default storage, set to null
string storage = null;
//Specify the folder where the source document is stored
string folder = "input";
//Call ExtractImages to extract images from the specified page
pdfImagesApi.ExtractImages(name, outPath, pageNumber, folder, storage, password);
}
}
}