C#/VB.NET 將SVG圖片新增到PDF、轉換為PDF
阿新 • • 發佈:2020-05-20
以下內容介紹在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; usingSpire.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 = newPdfDocument(); 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效果:
<完>