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. 添加SVGPDF文檔

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效果:

 

<完>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM