Konwersja SVG do PDF w C
IronPDF konwertuje grafiki SVG do dokumentów PDF, używając podejścia HTML do PDF - osadź swój SVG w tagu img z wyraźnie określonymi stylami szerokości/wysokości, aby zapewnić poprawne renderowanie.
IronPDF obsługuje renderowanie grafik SVG do dokumentów PDF poprzez metodę HTML do PDF. Pliki SVG (Scalable Vector Graphics) są szeroko stosowane do logotypów, ikon, ilustracji i wykresów z powodu ich skalowalności i ostrości renderowania w dowolnym rozmiarze. Konwersja SVG do PDF jest niezbędna do tworzenia dokumentów gotowych do druku, celów archiwalnych oraz zapewnienia spójnego wyświetlania na różnych platformach.
Uwaga: Ustaw atrybut stylu width i/lub height elementu img podczas osadzania SVG - w przeciwnym razie może zaniknąć do rozmiaru zero i nie pojawi się w renderowanym PDF.
Szybki start: Łatwa konwersja SVG do PDF
Konwertuj pliki SVG do PDF używając IronPDF w C#. Ten fragment demonstruje osadzanie SVG za pomocą tagu img HTML z określonymi wymiarami, co jest kluczowym krokiem do skutecznego renderowania. Postępuj wg tego przewodnika, aby szybko wdrożyć rozwiązanie, które zapewnia dokładne renderowanie i zapisywanie SVG jako PDF.
-
Install IronPDF with NuGet Package Manager
PM > Install-Package IronPdf -
Skopiuj i uruchom ten fragment kodu.
new IronPdf.ChromePdfRenderer { RenderingOptions = { WaitFor = IronPdf.Rendering.WaitFor.RenderDelay(1000) } } .RenderHtmlAsPdf("<img src='https://example.com/logo.svg' style='width:100px;height:100px;'>") .SaveAs("svgToPdf.pdf"); -
Wdrożenie do testowania w środowisku produkcyjnym
Rozpocznij używanie IronPDF w swoim projekcie już dziś z darmową wersją próbną
Minimalny proces (5 kroków)
- Zainstaluj bibliotekę IronPDF do konwersji SVG do PDF
- Użyj tagu
imgw HTML do importu obrazu SVG - Wykorzystaj różne metody renderowania w IronPDF do generowania PDF
- Zapisz plik PDF zawierający obraz SVG metodą
SaveAs - Sprawdź PDF w określonej lokalizacji
Jak renderować SVG do PDF z odpowiednimi rozmiarami?
Wiele przeglądarek toleruje SVG bez specyfikacji rozmiaru; jednak nasz silnik renderujący ich wymaga. Silnik renderujący Chrome używany przez IronPDF wymaga wyraźnych wymiarów, aby prawidłowo renderować elementy SVG. Bez określonych wymiarów SVG może nie pojawić się w końcowym PDF lub zostać zrenderowany z nieoczekiwanymi rozmiarami.
Pracując z SVG w IronPDF, masz kilka opcji zapewnienia poprawnego renderowania:
- Inline SVG z atrybutami stylów: Dodaj szerokość i wysokość bezpośrednio w atrybucie stylu
- Zewnętrzne pliki SVG: Odnośniki do plików SVG za pomocą URL lub lokalnej ścieżki pliku
- SVG zakodowane w Base64: Osadź SVG bezpośrednio w HTML jako ciągi Base64
Dla bardziej zaawansowanych opcji renderowania HTML zobacz nasz szczegółowy przewodnik na temat opcji renderowania.
:path=/static-assets/pdf/content-code-examples/how-to/SVGs-render.cs
using IronPdf;
string html = "<img src='https://ironsoftware.com/img/svgs/new-banner-svg.svg' style='width:100px'>";
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.WaitFor.RenderDelay(1000);
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("svgToPdf.pdf");
Imports IronPdf
Private html As String = "<img src='https://ironsoftware.com/img/svgs/new-banner-svg.svg' style='width:100px'>"
Private renderer As New ChromePdfRenderer()
renderer.RenderingOptions.WaitFor.RenderDelay(1000)
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("svgToPdf.pdf")
Jak wygląda wygenerowany plik PDF?
Dodatkowo, lub alternatywnie, węzeł SVG może mieć przypisane wyraźne atrybuty szerokości i wysokości. Zobacz także przykłady stylizacji SVG na CodePen.
Przykład renderowania SVG do PDF
Praca z lokalnymi plikami SVG
Przy konwersji lokalnych plików SVG do PDF użyj podejścia ze ścieżką pliku. Ta metoda dobrze działa z zasobami SVG przechowywanymi w Twoim projekcie:
using IronPdf;
using System.IO;
// Load SVG file content
string svgPath = @"C:\assets\company-logo.svg";
string svgContent = File.ReadAllText(svgPath);
// Create HTML with embedded SVG
string html = $@"
<html>
<head>
<style>
body {{ margin: 20px; }}
.logo {{ width: 200px; height: 100px; }}
</style>
</head>
<body>
<h1>Company Report</h1>
<img src='file:///{svgPath}' class='logo' />
<p>Annual financial summary with vector graphics.</p>
</body>
</html>";
// Configure renderer with custom settings
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.MarginTop = 10;
renderer.RenderingOptions.MarginBottom = 10;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
// Generate PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("report-with-svg.pdf");
using IronPdf;
using System.IO;
// Load SVG file content
string svgPath = @"C:\assets\company-logo.svg";
string svgContent = File.ReadAllText(svgPath);
// Create HTML with embedded SVG
string html = $@"
<html>
<head>
<style>
body {{ margin: 20px; }}
.logo {{ width: 200px; height: 100px; }}
</style>
</head>
<body>
<h1>Company Report</h1>
<img src='file:///{svgPath}' class='logo' />
<p>Annual financial summary with vector graphics.</p>
</body>
</html>";
// Configure renderer with custom settings
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.MarginTop = 10;
renderer.RenderingOptions.MarginBottom = 10;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
// Generate PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("report-with-svg.pdf");
Imports IronPdf
Imports System.IO
' Load SVG file content
Dim svgPath As String = "C:\assets\company-logo.svg"
Dim svgContent As String = File.ReadAllText(svgPath)
' Create HTML with embedded SVG
Dim html As String = $"
<html>
<head>
<style>
body {{ margin: 20px; }}
.logo {{ width: 200px; height: 100px; }}
</style>
</head>
<body>
<h1>Company Report</h1>
<img src='file:///{svgPath}' class='logo' />
<p>Annual financial summary with vector graphics.</p>
</body>
</html>"
' Configure renderer with custom settings
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.MarginTop = 10
renderer.RenderingOptions.MarginBottom = 10
renderer.RenderingOptions.PrintHtmlBackgrounds = True
' Generate PDF
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("report-with-svg.pdf")
Kodowanie Base64 dla osadzonych SVG
Dla scenariuszy wymagających bezpośredniego osadzania danych SVG w HTML bez odniesień do zewnętrznych plików, kodowanie Base64 zapewnia niezawodne rozwiązanie. To podejście jest szczegółowo wyjaśnione w naszym przewodniku osadzanie obrazów:
using IronPdf;
using System;
// SVG content as string
string svgContent = @"<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'>
<circle cx='50' cy='50' r='40' stroke='black' stroke-width='2' fill='red' />
</svg>";
// Convert to Base64
byte[] svgBytes = System.Text.Encoding.UTF8.GetBytes(svgContent);
string base64Svg = Convert.ToBase64String(svgBytes);
// Create HTML with Base64 embedded SVG
string html = $@"
<html>
<body>
<h2>Embedded SVG Example</h2>
<img src='data:image/svg+xml;base64,{base64Svg}' style='width:150px;height:150px;' />
</body>
</html>";
// Render to PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("embedded-svg.pdf");
using IronPdf;
using System;
// SVG content as string
string svgContent = @"<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'>
<circle cx='50' cy='50' r='40' stroke='black' stroke-width='2' fill='red' />
</svg>";
// Convert to Base64
byte[] svgBytes = System.Text.Encoding.UTF8.GetBytes(svgContent);
string base64Svg = Convert.ToBase64String(svgBytes);
// Create HTML with Base64 embedded SVG
string html = $@"
<html>
<body>
<h2>Embedded SVG Example</h2>
<img src='data:image/svg+xml;base64,{base64Svg}' style='width:150px;height:150px;' />
</body>
</html>";
// Render to PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("embedded-svg.pdf");
Imports IronPdf
Imports System
Imports System.Text
' SVG content as string
Dim svgContent As String = "<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'>
<circle cx='50' cy='50' r='40' stroke='black' stroke-width='2' fill='red' />
</svg>"
' Convert to Base64
Dim svgBytes As Byte() = Encoding.UTF8.GetBytes(svgContent)
Dim base64Svg As String = Convert.ToBase64String(svgBytes)
' Create HTML with Base64 embedded SVG
Dim html As String = $"
<html>
<body>
<h2>Embedded SVG Example</h2>
<img src='data:image/svg+xml;base64,{base64Svg}' style='width:150px;height:150px;' />
</body>
</html>"
' Render to PDF
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("embedded-svg.pdf")
Najlepsze praktyki konwersji SVG do PDF
1. Zawsze określ wymiary
Najczęstszym problemem przy konwersji SVG do PDF jest brak lub zerowe wymiary. Zawsze upewnij się, że Twoje elementy SVG mają określone wartości szerokości i wysokości. Dla responsywnych projektów rozważ użycie ustawień viewport do kontroli układu PDF.
2. Obsługuj złożone SVG z opóźnieniami renderowania
Złożone pliki SVG z animacjami lub JavaScriptem mogą wymagać dodatkowego czasu renderowania. Użyj opcji RenderDelay, aby zapewnić pełne renderowanie:
renderer.RenderingOptions.WaitFor.RenderDelay(2000); // Wait 2 seconds
renderer.RenderingOptions.WaitFor.RenderDelay(2000); // Wait 2 seconds
renderer.RenderingOptions.WaitFor.RenderDelay(2000) ' Wait 2 seconds
Dla zaawansowanej obsługi JavaScript, zapoznaj się z naszym przewodnikiem renderowania JavaScript.
3. Optymalizuj pliki SVG
Przed konwersją optymalizuj swoje pliki SVG poprzez:
- Usuwanie niepotrzebnych metadanych
- Upraszczanie ścieżek
- Konwersja tekstu na ścieżki dla spójnego renderowania
- Używanie odpowiedniej kompresji
4. Testuj kompatybilność międzyplatformową
Renderowanie SVG może się różnić w zależności od systemu operacyjnego. Testuj swoje konwersje na:
Rozwiązywanie typowych problemów z SVG
SVG nie pojawia się w PDF
Jeśli Twój SVG nie pojawia się w generowanym PDF:
- Zweryfikuj, czy wymiary są ustawione poprawnie
- Sprawdź, czy ścieżki plików lub URL można uzyskać
- Upewnij się, że właściwy typ MIME dla plików SVG
- Przejrzyj nasz przewodnik pixel-perfect rendering
Problemy ze skalowaniem i rozdzielczością
Dla wysokiej jakości renderowania SVG w różnych skalach:
// Set custom DPI for better quality
renderer.RenderingOptions.DPI = 300;
// Use CSS transforms for scaling
string html = @"
<img src='logo.svg' style='width:200px;height:200px;transform:scale(1.5);' />";
// Set custom DPI for better quality
renderer.RenderingOptions.DPI = 300;
// Use CSS transforms for scaling
string html = @"
<img src='logo.svg' style='width:200px;height:200px;transform:scale(1.5);' />";
' Set custom DPI for better quality
renderer.RenderingOptions.DPI = 300
' Use CSS transforms for scaling
Dim html As String = "
<img src='logo.svg' style='width:200px;height:200px;transform:scale(1.5);' />"
Renderowanie czcionek w SVG
Gdy SVG zawierają elementy tekstowe, upewnij się, że czcionki są prawidłowo osadzone. Dowiedz się więcej o zarządzaniu czcionkami i wsparciu web font.
Zaawansowane techniki konwersji SVG
Batch processing wielu SVG
Dla konwersji wielu plików SVG do jednego dokumentu PDF:
using IronPdf;
using System.Collections.Generic;
using System.Text;
List<string> svgFiles = new List<string>
{
"chart1.svg",
"chart2.svg",
"diagram.svg"
};
StringBuilder htmlBuilder = new StringBuilder();
htmlBuilder.Append("<html><body>");
foreach(string svgFile in svgFiles)
{
htmlBuilder.Append($@"
<div style='page-break-after:always;'>
<img src='{svgFile}' style='width:600px;height:400px;' />
</div>");
}
htmlBuilder.Append("</body></html>");
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlBuilder.ToString());
pdf.SaveAs("multiple-svgs.pdf");
using IronPdf;
using System.Collections.Generic;
using System.Text;
List<string> svgFiles = new List<string>
{
"chart1.svg",
"chart2.svg",
"diagram.svg"
};
StringBuilder htmlBuilder = new StringBuilder();
htmlBuilder.Append("<html><body>");
foreach(string svgFile in svgFiles)
{
htmlBuilder.Append($@"
<div style='page-break-after:always;'>
<img src='{svgFile}' style='width:600px;height:400px;' />
</div>");
}
htmlBuilder.Append("</body></html>");
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlBuilder.ToString());
pdf.SaveAs("multiple-svgs.pdf");
Imports IronPdf
Imports System.Collections.Generic
Imports System.Text
Dim svgFiles As New List(Of String) From {
"chart1.svg",
"chart2.svg",
"diagram.svg"
}
Dim htmlBuilder As New StringBuilder()
htmlBuilder.Append("<html><body>")
For Each svgFile As String In svgFiles
htmlBuilder.Append($"
<div style='page-break-after:always;'>
<img src='{svgFile}' style='width:600px;height:400px;' />
</div>")
Next
htmlBuilder.Append("</body></html>")
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlBuilder.ToString())
pdf.SaveAs("multiple-svgs.pdf")
Dla bardziej szczegółowych informacji o pracy z wieloma stronami, zobacz nasz przewodnik scalania i dzielenia PDF.
Gotowy, aby sprawdzić, co jeszcze możesz zrobić? Sprawdź nasze strony z samouczkami: Dodatkowe funkcje. Możesz również dowiedzieć się, jak dodać nagłówki i stopki do swoich PDF zawierających SVG lub poznać niestandardowe znaki wodne do brandingu dokumentów.
- Użyj
TextAnnotationiAddTextAnnotation
Często Zadawane Pytania
How do I convert SVG to PDF in C#?
IronPDF converts SVG to PDF using the HTML to PDF method. Simply embed your SVG in an HTML img tag with explicit width and height styles, then use IronPDF's ChromePdfRenderer to render the HTML as a PDF. The key is ensuring proper sizing attributes are set on the img element.
Why isn't my SVG appearing in the PDF?
SVGs may not appear in PDFs generated by IronPDF if they lack explicit width and height specifications. The Chrome rendering engine used by IronPDF requires dimensions to be set either through style attributes or width/height attributes on the img tag. Without these, the SVG may collapse to zero size.
What are the different methods to embed SVGs for PDF conversion?
IronPDF supports three main methods for embedding SVGs: 1) Inline SVG with style attributes for width and height, 2) External SVG files referenced via URL or local file path, and 3) Base64 encoded SVGs embedded directly in the HTML. All methods require proper sizing specifications.
Can I convert local SVG files to PDF?
Yes, IronPDF can convert local SVG files to PDF. Use the file path approach by referencing your SVG assets stored in your project through the img tag's src attribute. Remember to include width and height specifications for proper rendering.
What rendering options should I use for SVG to PDF conversion?
When converting SVG to PDF with IronPDF, use the ChromePdfRenderer with appropriate RenderingOptions. A common approach is to add a RenderDelay using WaitFor.RenderDelay(1000) to ensure SVGs load completely before conversion. This helps with complex SVGs or when loading external resources.
How do I save the converted SVG as a PDF file?
After rendering your SVG-containing HTML with IronPDF's ChromePdfRenderer, use the SaveAs method to save the PDF file. Simply call SaveAs("filename.pdf") on the rendered PDF object to save it to your specified location.

