ReplaceText.cs
// 完毕:
using System;
using System.IO;
using System.Drawing;
using System.Text;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Text;
using GrapeCity.Documents.Pdf.AcroForms;

namespace DsPdfWeb.Demos
{
    // This example shows how to find and replace all occurrences of a text string in a PDF.
    public class ReplaceText
    {
        public int CreatePDF(Stream stream)
        {
            var doc = new GcPdfDocument();
            using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "LeaseAgreementDemo.pdf"));
            doc.Load(fs);

            // Replace:
            // "Jane Donahue" -> "John Doe"
            // "(123)098-7654" -> "(007)123-4567"
            // "janed@example.com" -> "johnd@example.com"
            doc.ReplaceText(new FindTextParams("Jane Donahue", false, true), "John Doe");
            doc.ReplaceText(new FindTextParams("(123)098-7654", false, true), "(007)123-4567");
            doc.ReplaceText(new FindTextParams("janed@example.com", false, true), "johnd@example.com");
            // "13-Dec-20 22:16:00" -> date now
            // "13-Dec-22 22:16:00" -> date now + 2 years
            var termStart = Common.Util.TimeNow();
            var termEnd = Common.Util.TimeNow() + TimeSpan.FromDays(365 * 2);
            doc.ReplaceText(new FindTextParams("13-Dec-20 22:16:00", false, true), termStart.ToString("yyyy-MM-dd") + " " + termStart.ToString("HH:mm"));
            doc.ReplaceText(new FindTextParams("13-Dec-22 22:16:00", false, true), termEnd.ToString("yyyy-MM-dd") + " " + termEnd.ToString("HH:mm"));

            // "condominium" -> "flat"
            var font = GrapeCity.Documents.Text.Font.FromFile(Path.Combine("Resources", "Fonts", "segoeuib.ttf"));
            doc.ReplaceText(new FindTextParams("condominium", true, false), "flat", null, font);

            // For reference, append the original PDF:
            Common.Util.AddNote("For reference, the following pages contain a copy of the original unmodified PDF.", doc.NewPage());
            var docOrig = new GcPdfDocument();
            docOrig.Load(fs);
            doc.MergeWithDocument(docOrig);

            // 完毕:
            doc.Save(stream);
            return doc.Pages.Count;
        }
    }
}