Skip to content
Guides

Add Backgrounds in PDF

This sample shows how to add color and picture backgrounds and delete backgrounds:

C#
using ComPDFKit.PDFDocument;
using System; 
using System.IO; 
using ImageMagick;

namespace BackgroundTest
{
    internal class BackgroundTest
    {

        static private string parentPath = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory())));
        static private string outputPath = Path.Combine(parentPath, "Output", "CS");

        static void Main(string[] args)
        {
            Console.WriteLine("Running Watermark test sample…" + Environment.NewLine);
            SDKLicenseHelper.LicenseVerify();
            CPDFDocument document = CPDFDocument.InitWithFilePath("CommonFivePage.pdf");
            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }

            #region Sample 1: Add color background
            if (AddColorBackground(document))
            {
                Console.WriteLine("Add color background done.");
            } 
            document.Release();

            Console.WriteLine("--------------------");
            #endregion

            #region Sample 2: Add image background
            document = CPDFDocument.InitWithFilePath("CommonFivePage.pdf");
            if (AddImageBackground(document))
            {
                Console.WriteLine("Add image background done.");
            }
            document.Release();
            Console.WriteLine("--------------------");
            #endregion

            #region Sample 3: Remove background
            CPDFDocument colorBgDocument = CPDFDocument.InitWithFilePath("ColorBackground.pdf");
            CPDFDocument imageBgDocument = CPDFDocument.InitWithFilePath("ImageBackground.pdf");

            if (RemoveBackground(colorBgDocument, imageBgDocument))
            {
                Console.WriteLine("Remove background done.");
            }
            colorBgDocument.Release();
            imageBgDocument.Release();
            Console.WriteLine("--------------------");
            #endregion

            Console.WriteLine("Done!");
            Console.WriteLine("--------------------");
            Console.ReadLine();
        }

        /// <summary>
        /// Add color background                    
        /// </summary>
        /// <param name="document">Regular document</param> 
        static private bool AddColorBackground(CPDFDocument document)
        {
            CPDFBackground background = document.GetBackground();
            background.SetBackgroundType(C_Background_Type.BG_TYPE_COLOR);
            background.SetColor(new byte[] { 255, 0, 0 });
            background.SetOpacity(255);//0-255
            background.SetScale(1);//1 == 100%
            background.SetRotation(0);//Use radians
            background.SetHorizalign(C_Background_Horizalign.BG_HORIZALIGN_CENTER);
            background.SetVertalign(C_Background_Vertalign.BG_VERTALIGN_CENTER);
            background.SetXOffset(0);
            background.SetYOffset(0);
            background.SetPages("0-2");//Page numbering from 0
            background.Update();//Note: update after setup is complete
            string path = Path.Combine(outputPath, "AddColorBackgroundTest.pdf");
            if (!document.WriteToFilePath(path))
            {
                return false;
            }
            Console.WriteLine("Browse the changed file in " + path);

            return true;
        }

        /// <summary>
        /// Add image background.
        /// </summary>
        /// <param name="document">Regular document</param>
        static private bool AddImageBackground(CPDFDocument document)
        {
            CPDFBackground background = document.GetBackground();
            background.SetBackgroundType(C_Background_Type.BG_TYPE_IMAGE);
            
            using (var image = new MagickImage("ComPDFKit_Logo.ico"))
            {
                byte[] byteArray = image.ToByteArray(MagickFormat.Bgra);
                background.SetImage(byteArray, image.Width, image.Height, ComPDFKit.Import.C_Scale_Type.fitCenter);
            }
            background.SetOpacity(128);//0-255
            background.SetScale(1);//1 == 100%
            background.SetRotation(1f);//Use radians
            background.SetHorizalign(C_Background_Horizalign.BG_HORIZALIGN_CENTER);
            background.SetVertalign(C_Background_Vertalign.BG_VERTALIGN_CENTER);
            background.SetXOffset(0);
            background.SetYOffset(0);
            background.SetPages("0-2");//Page numbering from 0
            background.Update();//Note: update after setup is complete
            string path = Path.Combine(outputPath, "AddImageBackgroundTest.pdf");
            if (!document.WriteToFilePath(path))
            {
                return false;
            }
            Console.WriteLine("Browse the changed file in " + path);

            return true;
        }

        /// <summary>
        /// Check background type, and remove background. 
        /// </summary>
        /// <param name="colorBgDocument">Document with clolor background.</param>
        /// <param name="imageBgDocument">Document with image background.</param>  
        /// <returns></returns>
        static private bool RemoveBackground(CPDFDocument colorBgDocument, CPDFDocument imageBgDocument)
        {
            CPDFBackground colorBackground = colorBgDocument.GetBackground();
            if(colorBackground.GetBackgroundType() != C_Background_Type.BG_TYPE_COLOR)
            {
                return false;
            } 

            colorBackground.Clear();
            string path1 = Path.Combine(outputPath, "ClearColorBgTest.pdf");
            if (!colorBgDocument.WriteToFilePath(path1))
            {
                return false;
            }
            Console.WriteLine("Browse the changed file in " + path1);

            CPDFBackground imageBackground = imageBgDocument.GetBackground();

            imageBackground.Clear();
            string path2 = Path.Combine(outputPath, "ClearImageBgTest.pdf");
            if (!imageBgDocument.WriteToFilePath(path2))
            {
                return false;
            }
            Console.WriteLine("Browse the changed file in " + path2);

            return true;
        }
    }
}