C#/VB.NET 將SVG圖片添加到PDF、轉換為PDF

以下內容介紹在C# 程式中如何將SVG圖片添加到PDF文檔、以及如何將SVG圖片轉換為PDF文檔。

一、環境準備

先下載PDF類庫工具,Spire.PDF for .NET hotfix 6.5.6及以上版本(下載時,注意版本資訊)。下載後,解壓文件,將Bin文件夾下的Spire.Pdf.dll文件在VS中的「解決方案資源管理器」進行「添加引用」。另外,也可以通過Nuget下載。

dll引用效果如下:

 

 

 

用於測試的SVG圖片,如下圖:

二、程式碼示例

1. 添加SVG到PDF文檔

C#

using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;


namespace InsertSVGImage_PDF
{
    class Program
    {
        static void Main(string[] args)
        {
            //載入SVG圖片
            PdfDocument file1 = new PdfDocument();
            file1.LoadFromSvg("Image.svg");

            //創建一個PDF文檔,添加一頁
            PdfDocument pdf = new PdfDocument();
            pdf.AppendPage();

            //根據SVG圖片創建模板,並將模板繪製到PDF
            PdfTemplate template = file1.Pages[0].CreateTemplate();
            template.Draw(pdf.Pages[0].Canvas, new PointF());

            //保存PDF文檔
            pdf.SaveToFile("AddSVGtoPDF.pdf", FileFormat.PDF);
            System.Diagnostics.Process.Start("AddSVGtoPDF.pdf");
        }
    }
}

VB.NET

Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics

Namespace InsertSVGImage_PDF
    
    Class Program
        
        Private Shared Sub Main(ByVal args() As String)
            '載入SVG圖片
            Dim file1 As PdfDocument = New PdfDocument
            file1.LoadFromSvg("Image.svg")
            '創建一個PDF文檔,添加一頁
            Dim pdf As PdfDocument = New PdfDocument
            pdf.AppendPage
            '根據SVG圖片創建模板,並將模板繪製到PDF  
            Dim template As PdfTemplate = file1.Pages(0).CreateTemplate
            template.Draw(pdf.Pages(0).Canvas, New PointF)
            '保存PDF文檔
            pdf.SaveToFile("AddSVGtoPDF.pdf", FileFormat.PDF)
            System.Diagnostics.Process.Start("AddSVGtoPDF.pdf")
        End Sub
    End Class
End Namespace

SVG圖片添加效果:

 

2. 將SVG圖片轉換成PDF文檔

C#

using Spire.Pdf;


namespace SVGtoPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            //載入SVG圖片
            PdfDocument doc = new PdfDocument();
            doc.LoadFromSvg("Image.svg");

            //調用方法SaveToFile()保存為PDF格式
            doc.SaveToFile("ConvertSVGtoPDF.pdf", FileFormat.PDF);
            System.Diagnostics.Process.Start("ConvertSVGtoPDF.pdf");
        }
    }
}

VB.NET

Imports Spire.Pdf

Namespace SVGtoPDF
    
    Class Program
        
        Private Shared Sub Main(ByVal args() As String)
            '載入SVG圖片
            Dim doc As PdfDocument = New PdfDocument
            doc.LoadFromSvg("Image.svg")
            '調用方法SaveToFile()保存為PDF格式
            doc.SaveToFile("ConvertSVGtoPDF.pdf", FileFormat.PDF)
            System.Diagnostics.Process.Start("ConvertSVGtoPDF.pdf")
        End Sub
    End Class
End Namespace

SVG轉PDF效果:

 

<完>