vladislavber
vladislavber

Reputation: 1

How to print svg string without file creation

I generated svg strings in my program c#. How can I print svg strings without file creation?

Upvotes: 0

Views: 673

Answers (2)

Jimi
Jimi

Reputation: 32233

A simple example using a WebBrowser class.
You can of course use a WebBorwser Control, if you also need to show the SVG on screen.
You can do the same with a WebView2 Control / CoreWebView2 object.

Using a bare-bone HTML5 document text, set the content of an IMG element to the SVG string converted to base64, setting the mime-type of the data to image/svg+xml.
The Width of the IMG element is set to 200 (~2 inches, ~50 millimeters).
Modify as required (considering the DPI, if necessary).

Then create a WebBrowser class, generate a new empty Document object and Write() to it the HTML content (using this method to have immediate rendering of the content).
After that, call the WebBrowser.Print() method to send the rendered SVG to the default Printer.

Assume svgContent is your SVG string:

string base64 = Convert.ToBase64String(svgContent);
int svgWidth = 200;

string html = $"<!DOCTYPE html><html><body>" +
    $"<img width={svgWidth} src=\"data:image/svg+xml;base64,{base64}\"/>" +
    "</body></html>";

var wb = new WebBrowser() {ScriptErrorsSuppressed = true };
try {
    wb.Navigate("");
    var doc = wb.Document.OpenNew(true);
    doc.Write(html);
    wb.Print();
}
finally {
    wb.Dispose();
}

Upvotes: 1

O. Jones
O. Jones

Reputation: 108706

You can place <svg>whatever</svg> tags directly inline into your html5 document as text. When a browser receives that document it renders the svg in whatever. This is a double-cool way to do it because your CSS applies to your svg elements.

Here's a decent introduction. Look for the section on how to use inline svg.

Upvotes: 0

Related Questions