SelectPdf for .NET 10 - Pdf Page Objects - C# / .NET 10 Sample

This sample shows how to use SelectPdf Library for .NET to read and change what a page of an existing PDF document draws. Every text, image, path and group of the page is an object that can be moved, resized, recoloured, replaced or removed, and the layers of the document can be shown, hidden or flattened.

Without an uploaded PDF the sample builds a one page letter with a logo, a title, a few lines of text and a DRAFT mark, and changes that. Text is replaced in each text object that contains it; documents converted from HTML usually hold one text object per character, so search them with a single character.

PDF document (optional):

Page Number:


Password (for a protected PDF):


Find text:


Replace with:


Color the replaced text red

Move the images to the right by:
pt

Remove the images

Put the DRAFT text in a hidden layer
Flatten the layers

Sample code · C#
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SelectPdf.Universal;

namespace SelectPdf.Samples.Pages
{
    public class PdfPageObjectsModel : PageModel
    {
        public void OnGet()
        {
            TxtPage = "1";
            TxtFind = "SelectPdf";
            TxtReplace = "My Company";
            ChkRecolor = true;
            TxtMoveImagesX = "330";
            ChkDraftLayer = true;
        }

        // An uploaded PDF document, or nothing - the sample builds a small letter then.
        [BindProperty]
        public IFormFile FilePdf { get; set; }

        [BindProperty]
        public string TxtPassword { get; set; }

        [BindProperty]
        public string TxtPage { get; set; }

        [BindProperty]
        public string TxtFind { get; set; }

        [BindProperty]
        public string TxtReplace { get; set; }

        [BindProperty]
        public bool ChkRecolor { get; set; }

        [BindProperty]
        public string TxtMoveImagesX { get; set; }

        [BindProperty]
        public bool ChkRemoveImages { get; set; }

        [BindProperty]
        public bool ChkDraftLayer { get; set; }

        [BindProperty]
        public bool ChkFlattenLayers { get; set; }

        // The objects of the page, filled by the List handler.
        public List<string> ObjectList { get; private set; }

        public IActionResult OnPost()
        {
            PdfDocument document = LoadDocument();
            PdfPageObjectModel model = document.Pages[PageIndex(document)].ObjectModel;

            // replace a text in every text object that contains it
            if (!string.IsNullOrEmpty(TxtFind))
            {
                foreach (PdfTextObject text in model.GetTextObjects())
                {
                    if (text.Text.IndexOf(TxtFind, StringComparison.Ordinal) < 0)
                        continue;

                    text.ReplaceText(text.Text.Replace(TxtFind, TxtReplace ?? string.Empty));
                    if (ChkRecolor)
                        text.FillColor = new PdfColor(200, 30, 30);
                }
            }

            // move or remove the images of the page
            float moveX = Number(TxtMoveImagesX);
            foreach (PdfImageObject image in model.GetImageObjects())
            {
                if (ChkRemoveImages)
                    image.Remove();
                else if (moveX != 0)
                    image.Translate(moveX, 0);
            }

            // put the text that says DRAFT in a layer that is hidden when the document opens
            if (ChkDraftLayer)
            {
                PdfLayer draft = null;
                foreach (PdfTextObject text in model.GetTextObjects())
                {
                    if (text.Text.IndexOf("DRAFT", StringComparison.Ordinal) < 0)
                        continue;

                    if (draft == null)
                        draft = document.Layers.Add("Draft", false);
                    text.Layer = draft;
                }
            }

            // keep what the layers draw as plain, always visible page content
            if (ChkFlattenLayers)
                document.Layers.Flatten();

            // save pdf document
            byte[] pdf = document.Save();

            // close pdf document
            document.Close();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;
        }

        public IActionResult OnPostList()
        {
            PdfDocument document = LoadDocument();
            PdfPageObjectModel model = document.Pages[PageIndex(document)].ObjectModel;

            // every object of the page, in the order it is painted
            ObjectList = new List<string>();
            foreach (PdfPageObject pageObject in model.Objects)
            {
                string line = pageObject.Kind + " at " + Format(pageObject.Bounds);
                if (pageObject is PdfTextObject text)
                    line += ": \"" + text.Text + "\" (" + text.FontName + ", " +
                        text.FontSize.ToString("0.#", CultureInfo.InvariantCulture) + " pt)";
                else if (pageObject is PdfImageObject image)
                    line += ": " + image.PixelWidth + " x " + image.PixelHeight + " pixels";
                if (pageObject.Layer != null)
                    line += " - layer " + pageObject.Layer.Name;
                ObjectList.Add(line);
            }

            // close pdf document
            document.Close();
            return Page();
        }

        private PdfDocument LoadDocument()
        {
            // the document to change: the uploaded one, or a letter built by the sample
            byte[] source;
            if (FilePdf != null && FilePdf.Length > 0)
            {
                using (var uploaded = new MemoryStream())
                {
                    FilePdf.CopyTo(uploaded);
                    source = uploaded.ToArray();
                }
            }
            else
            {
                source = CreateLetter();
            }

            MemoryStream stream = new MemoryStream(source);
            if (string.IsNullOrEmpty(TxtPassword))
                return new PdfDocument(stream);
            return new PdfDocument(stream, TxtPassword);
        }

        // A one page letter with a logo, a title, a few lines of text and a DRAFT mark.
        private static byte[] CreateLetter()
        {
            PdfDocument doc = new PdfDocument();
            PdfPage page = doc.AddPage();

            PdfFont title = doc.Fonts.Add(PdfStandardFont.HelveticaBold);
            title.Size = 22;
            PdfFont body = doc.Fonts.Add(PdfStandardFont.Helvetica);
            body.Size = 12;
            PdfFont mark = doc.Fonts.Add(PdfStandardFont.HelveticaBold);
            mark.Size = 40;

            string logo = Path.Combine(Startup.ServerPath, "wwwroot", "images", "logo.png");
            page.Add(new PdfImageElement(0, 0, 150, logo));

            page.Add(new PdfTextElement(0, 80, "Quarterly Report - SelectPdf", title));
            string[] lines =
            {
                "Prepared by the SelectPdf team for our partners.",
                "Revenue grew 12% over the previous quarter.",
                "Questions about this report: contact SelectPdf support.",
            };
            float y = 130;
            foreach (string line in lines)
            {
                page.Add(new PdfTextElement(0, y, line, body));
                y += 22;
            }

            PdfTextElement draft = new PdfTextElement(0, 260, "DRAFT", mark);
            draft.ForeColor = new PdfColor(200, 200, 200);
            page.Add(draft);

            byte[] pdf = doc.Save();
            doc.Close();
            return pdf;
        }

        private int PageIndex(PdfDocument document)
        {
            int page = (int)Number(TxtPage);
            return Math.Min(Math.Max(page, 1), document.Pages.Count) - 1;
        }

        private static float Number(string text)
        {
            float value;
            if (float.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
                return value;
            return 0;
        }

        private static string Format(SelectPdf.Universal.Drawing.RectangleF r)
        {
            return string.Format(CultureInfo.InvariantCulture, "({0:0.#}, {1:0.#}) {2:0.#} x {3:0.#} pt",
                r.X, r.Y, r.Width, r.Height);
        }
    }
}