SaveAsSvg.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.Linq;
  8. using System.Drawing;
  9. using System.Collections.Generic;
  10. using GrapeCity.Documents.Pdf;
  11. using GrapeCity.Documents.Svg;
  12. using GrapeCity.Documents.Drawing;
  13. using GrapeCity.Documents.Text;
  14.  
  15. namespace DsPdfWeb.Demos.Basics
  16. {
  17. // This sample shows how to use the SaveAsSvg() method to save a PDF
  18. // page as SVG (scalable vector graphics) image, and how to load
  19. // and render that image on a new PDF page.
  20. // The PDF used as the source was generated by the SvgSpecArt sample,
  21. // but any valid PDF can be used instead.
  22. public class SaveAsSvg
  23. {
  24. public int CreatePDF(Stream stream)
  25. {
  26. var doc = new GcPdfDocument();
  27. var page = doc.NewPage();
  28.  
  29. var rc = Common.Util.AddNote(
  30. "We load an existing PDF into a temporary GcPdfDocument, " +
  31. "save its first page as an SVG image to a stream, and then " +
  32. "draw that image on the page of the resulting PDF.",
  33. page);
  34.  
  35. // Load a one page document into a temp PDF:
  36. using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "svg-spec-art.pdf"));
  37. var docSrc = new GcPdfDocument();
  38. docSrc.Load(fs);
  39.  
  40. // Save the first page of the loaded PDF as SVG:
  41. using var svgStream = new MemoryStream();
  42. docSrc.Pages[0].SaveAsSvg(svgStream, new SaveAsImageOptions() { BackColor = Color.Transparent });
  43. // PDF pages can also be saved as SVGZ (compressed SVG) using the ToSvgz() method:
  44. // docSrc.Pages[0].ToSvgz();
  45. svgStream.Position = 0;
  46. // Create a GcSvgDocument from the saved SVG so that we can draw it in the resulting PDF:
  47. using var svgDoc = GcSvgDocument.FromStream(svgStream);
  48.  
  49. // For illustration purposes we render the SVG with transparent background
  50. // on a rectangle with a custom fill and border:
  51. rc = new RectangleF(0, rc.Bottom, page.Size.Width, page.Size.Height - rc.Bottom);
  52. rc.Inflate(-4f, -4f);
  53. page.Graphics.DrawRectangle(rc, Color.DarkGoldenrod);
  54. page.Graphics.FillRectangle(rc, Color.PaleGoldenrod);
  55. page.Graphics.DrawSvg(svgDoc, rc);
  56.  
  57. // Done:
  58. doc.Save(stream);
  59. return doc.Pages.Count;
  60. }
  61. }
  62. }
  63.