Detailed control over which annotations to draw when saving PDF as image

PDF TIFF SVG JPG C# VB
AnnotationDrawFilter.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 GrapeCity.Documents.Pdf;
  9. using GrapeCity.Documents.Text;
  10. using GrapeCity.Documents.Pdf.Annotations;
  11. using GrapeCity.Documents.Pdf.Graphics;
  12. using GrapeCity.Documents.Svg;
  13. using GrapeCity.Documents.Drawing;
  14.  
  15. namespace DsPdfWeb.Demos
  16. {
  17. // Shows how to programmatically control which annotations to include when saving a PDF as images.
  18. // The sample loads a one-page PDF containing several annotations, and saves that page as SVG
  19. // using DrawAnnotationFilter to include only annotations which satisfy certain conditions
  20. // (free text annotations that are within the page bounds).
  21. // The SVG is then inserted as the first page of the resulting PDF.
  22. // The second page shows the original PDF for reference.
  23. // The PDF used by this sample was generated by AnnotationTypes.
  24. public class AnnotationDrawFilter
  25. {
  26. public int CreatePDF(Stream stream)
  27. {
  28. var doc = new GcPdfDocument();
  29. // Load a PDF with some annotations into the document:
  30. using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "AnnotationTypes.pdf"));
  31. doc.Load(fs);
  32. using var svgStream = new MemoryStream();
  33. // Draw the first page of the PDF into an SVG:
  34. doc.Pages[0].SaveAsSvg(svgStream,
  35. new SaveAsImageOptions()
  36. {
  37. BackColor = Color.Transparent,
  38. DrawAnnotationFilter = (GcPdfDocument d, Page p, AnnotationBase a, ref bool draw) =>
  39. {
  40. // Draw only free text annotations which also fit horizontally within the page bounds:
  41. draw = a is FreeTextAnnotation fta && fta.Rect.Left > 0 && fta.Rect.Right < p.Size.Width;
  42. }
  43. });
  44. svgStream.Position = 0;
  45. // Create a GcSvgDocument from the saved SVG so that we can draw it in the resulting PDF:
  46. using var svgDoc = GcSvgDocument.FromStream(svgStream);
  47. // Insert a page into the PDF and draw the SVG on it, compare to the original on the 2nd page:
  48. var page = doc.Pages.Insert(0);
  49. var g = page.Graphics;
  50. var rc = new RectangleF(36, 36, page.Size.Width - 72, page.Size.Height - 72);
  51. g.DrawRectangle(rc, Color.DarkGoldenrod);
  52. g.FillRectangle(rc, Color.PaleGoldenrod);
  53. g.DrawSvg(svgDoc, rc);
  54.  
  55. // Done:
  56. doc.Save(stream);
  57. return doc.Pages.Count;
  58. }
  59. }
  60. }
  61.