如何合并 SVG 文件 – C# 示例

Aspose.SVG for .NET API 提供了 Renderer 类来渲染和合并 SVG 文档。本文提供有关 Render() 方法的信息,该方法用于将 SVG 文档转换为另一种格式并将它们合并到单个文件中。您将学习如何将多个 SVG 文档合并为 PDF、XPS 或图像格式,并查找 SVG 合并的 C# 示例。

渲染 SVG 文档

SVG 文件的渲染是通过 API 从 2D 模型生成图像的过程。从 SVG 转换为其他格式可以通过使用 Renderer 类的 Render(IDevice, TDocument) 方法来执行。

如何转换 SVG 文件 部分中,我们考虑两种转换场景:使用 ConvertSVG() 方法和 RenderTo() 方法。本文考虑将 Render() 方法应用于将 SVG 转换为其他格式 – PDF、XPS、JPG、JPG、BMP、PNG、TIFF 和 GIF。

要将 SVG 转换为其他格式(例如 PNG),请使用以下代码片段:

1using Aspose.Svg;
2using System.IO;
3using Aspose.Svg.Rendering;
4using Aspose.Svg.Rendering.Image;
 1// Render SVG to PNG using C#
 2
 3// Initialize an SVG document from a file
 4using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "owl.svg")))
 5{
 6    // Create an instance of SvgRenderer
 7    using (SvgRenderer renderer = new SvgRenderer())
 8    {
 9        // Create an instance of ImageDevice
10        using (ImageDevice device = new ImageDevice(Path.Combine(OutputDir, "owl.png")))
11        {
12            // Render SVG to PNG
13            renderer.Render(device, document);
14        }
15    }
16}

合并 SVG 文档

Render() 方法使您能够一次将多个文档发送到输出渲染设备并合并它们。文档合并可以通过几行代码完成:

1using Aspose.Svg;
2using System.IO;
3using Aspose.Svg.Rendering;
4using Aspose.Svg.Rendering.Pdf;
 1// Merge SVGs to PDF using C#
 2
 3// Initialize SVG documents from files to merge later
 4using (SVGDocument document1 = new SVGDocument(Path.Combine(DataDir, "circle.svg")))
 5using (SVGDocument document2 = new SVGDocument(Path.Combine(DataDir, "flower.svg")))
 6using (SVGDocument document3 = new SVGDocument(Path.Combine(DataDir, "lineto.svg")))
 7{
 8    // Create an instance of SvgRenderer
 9    using (SvgRenderer renderer = new SvgRenderer())
10    {
11        // Create an instance of PdfDevice
12        using (PdfDevice device = new PdfDevice(Path.Combine(OutputDir, "result.pdf")))
13        {
14            // Merge all SVG documents to PDF
15            renderer.Render(device, document1, document2, document3);
16        }
17    }
18}

您可以将 SVG 文件合并为 PDF、XPS、JPEG、JPG、BMP、PNG、TIFF 和 GIF 格式。

您可以从 GitHub 下载完整的示例和数据文件。关于从 GitHub 下载并运行示例,您可以从 如何运行示例 部分找到。

您可以尝试使用我们的免费在线 图像合并 将 SVG 文件合并为各种其他图像格式。该应用程序允许您自由添加任何图像、旋转、缩放、添加背景、滤镜和移动每个元素。您可以使用一组直观的组合选项,使您能够灵活控制图像拼贴的创建并达到所需的结果。使用图像合并应用程序,您将在几分钟内轻松制作图像拼贴。立即免费尝试我们强大的应用程序!

文本“横幅 SVG 转换器”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.