以下内容介绍在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[].CreateTemplate();
template.Draw(pdf.Pages[].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().CreateTemplate
template.Draw(pdf.Pages().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效果:
<完>