ReplaceText.cs
  1. //
  2. // This code is part of Document Solutions for PDF demos.
  3. // Copyright (c) MESCIUS inc. All rights reserved.
  4. //
  5. using System;
  6. using System.IO;
  7. using System.Drawing;
  8. using System.Text;
  9. using GrapeCity.Documents.Pdf;
  10. using GrapeCity.Documents.Text;
  11. using GrapeCity.Documents.Pdf.AcroForms;
  12.  
  13. namespace DsPdfWeb.Demos
  14. {
  15. // This example shows how to find and replace all occurrences of a text string in a PDF.
  16. public class ReplaceText
  17. {
  18. public int CreatePDF(Stream stream)
  19. {
  20. var doc = new GcPdfDocument();
  21. using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "LeaseAgreementDemo.pdf"));
  22. doc.Load(fs);
  23.  
  24. // Replace:
  25. // "Jane Donahue" -> "John Doe"
  26. // "(123)098-7654" -> "(007)123-4567"
  27. // "janed@example.com" -> "johnd@example.com"
  28. doc.ReplaceText(new FindTextParams("Jane Donahue", false, true), "John Doe");
  29. doc.ReplaceText(new FindTextParams("(123)098-7654", false, true), "(007)123-4567");
  30. doc.ReplaceText(new FindTextParams("janed@example.com", false, true), "johnd@example.com");
  31. // "13-Dec-20 22:16:00" -> date now
  32. // "13-Dec-22 22:16:00" -> date now + 2 years
  33. var termStart = Common.Util.TimeNow();
  34. var termEnd = Common.Util.TimeNow() + TimeSpan.FromDays(365 * 2);
  35. doc.ReplaceText(new FindTextParams("13-Dec-20 22:16:00", false, true), termStart.ToString("yyyy-MM-dd") + " " + termStart.ToString("HH:mm"));
  36. doc.ReplaceText(new FindTextParams("13-Dec-22 22:16:00", false, true), termEnd.ToString("yyyy-MM-dd") + " " + termEnd.ToString("HH:mm"));
  37.  
  38. // "condominium" -> "flat"
  39. var font = GrapeCity.Documents.Text.Font.FromFile(Path.Combine("Resources", "Fonts", "segoeuib.ttf"));
  40. doc.ReplaceText(new FindTextParams("condominium", true, false), "flat", null, font);
  41.  
  42. // For reference, append the original PDF:
  43. Common.Util.AddNote("For reference, the following pages contain a copy of the original unmodified PDF.", doc.NewPage());
  44. var docOrig = new GcPdfDocument();
  45. docOrig.Load(fs);
  46. doc.MergeWithDocument(docOrig);
  47.  
  48. // Done:
  49. doc.Save(stream);
  50. return doc.Pages.Count;
  51. }
  52. }
  53. }
  54.