Output Scalable Vector Graphics (SVG) content on a webpage

I need to include an SVG element in my Angular 2+ code.

My goal is to provide users with the option to print the SVG element as it appears on the screen.

<div class="floor-plan" id="printSectionId2"
   (drop)="onDrop($event)"
   (dragover)="onDragOverOrEnter($event)"
   (dragenter)="onDragOverOrEnter($event)">
<svg id="svgObject" [attr.width]="svgWidth + 'px'" [attr.height]="svgHeight + 'px'">
  <ng-container *ngIf="floorPlan && floorPlan.layout">
    <rect [attr.x]="floorPlan.x"
          [attr.y]="floorPlan.y"
          [attr.width]="floorPlan.width"
          [attr.height]="floorPlan.height"
          class="boundary">
    </rect>
    <ng-container *ngFor="let t of floorPlan.layout.tables; trackBy: trackByTables">
      <g class="dining-table"
         [attr.transform]="'translate(' + t.x + ' ' + t.y + ')'"
         [class.assigned]="t.isOccupied"
         [class.arrival]="t.isArrival"
         [class.hasSpecialInformation]="t.hasSpecialInformation"
         [class.hasOnlyBreakfast]="t.hasOnlyBreakfast">


        <rect *ngIf="t.shape === 'rectangle'"
              [attr.width]="t.width"
              [attr.height]="t.height"
              [attr.transform]="'rotate(' + t.rotation + ' ' + (t.width/2) + ' ' + (t.height/2) + ')'"
              [attr.data-tableId]="t.id">
          <title>Table {{t.number}}</title>
        </rect>

        <image *ngIf="t.isArrival" xlink:href="http://kommis.net/wp-content/uploads/2018/07/arrival-white.png" x="5" y="25" height="25px" width="25px" opacity="50"></image>

        <text *ngIf="t.shape === 'rectangle'"
              [attr.x]="t.width * 0.05"
              dominant-baseline="hanging"
              [attr.data-tableId]="t.id">
          <tspan x="5" class="table-number">{{t.number}}</tspan>
          <tspan x="5" dy="15" class="guest-info">{{t.guestInfo}}</tspan>
        </text>

        <ellipse *ngIf="t.shape === 'circle'"
                 [attr.rx]="t.width / 2"
                 [attr.ry]="t.height / 2"
                 [attr.data-tableId]="t.id">
          <title>Table {{t.number}}</title>
        </ellipse>

        <text *ngIf="t.shape === 'circle'"
              [attr.dy]="t.width / 2 * -0.5"
              text-anchor="middle"
              [attr.data-tableId]="t.id">
          <tspan x="0" class="table-number">{{t.number}}</tspan>
          <tspan x="0" dy="15" class="guest-info">{{t.guestInfo}}</tspan>
        </text>
      </g>
    </ng-container>
  </ng-container>
</svg>
</div>

Below is the CSS styling:

.floor-plan {
  background-color: #eaf3f3;
  border-radius: 2px;
}

.floor-plan svg {
  display: block;
}

.floor-plan .boundary {
  fill: transparent;
  stroke: #0A7A74;
  stroke-width: 2px;
}

.dining-table rect,
.dining-table ellipse {
  fill: transparent;
  stroke: #0A7A74;
  stroke-width: 2px;
}
/* Additional CSS styles... */

The rendered SVG graphic looks like this:

https://i.stack.imgur.com/PUDMT.png

I am seeking advice on the best approach for allowing users to print out this SVG image.

Currently, I'm attempting a JavaScript method as shown below:

 printToCart2(svgObject: string) {
    let popupWinindow;
    let innerContents = document.getElementById(svgObject).innerHTML;
    console.log(innerContents);
    popupWinindow = window.open('', '_blank', 'width=1000,height=1000,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
    // More JS code...
  }

However, when using this function, I only get a black square:

https://i.stack.imgur.com/WbRDM.png


Update:

The solution provided by @KoshVery helps achieve the desired output:

https://i.stack.imgur.com/57jNz.png


Update:

To ensure the CSS styles are applied, they must be included within Popupwindow.document.write() like so:

/* Updated CSS styles here... */

This results in the final printed image looking as intended:

https://i.stack.imgur.com/BDxig.png

Answer №1

To obtain the outerHTML of your svg, follow these steps:

let innerContents = document.getElementById(svgObject).outerHTML;

OR
If you have the innerHTML, enclose it in <svg> as shown below:

popupWinindow.document.write('<html><head><style></style></head><body onload="window.print()"><svg>' + innerContents + '</svg></html>');

Update
You can streamline your printing process with this alternative method:

<div>
<svg onclick="window.print(this)" id="svgObject" width="100" height="100">
    <circle fill="pink" cx="50" cy="50" r="45"/>
</svg>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I encountered an error with no matching overload when attempting to make a call using the Tanstack query function

While I was successfully calling a single data in my database using the useEffect hook, now I am attempting to learn how to use tanstack@query. Unfortunately, I encountered an error when trying to call it. No overload matches this call. Overload 1 of 3, ...

Retrieving Data from Web using Python Selenium

I've been trying to extract information from a website (snippet provided below) The process involves entering data, moving to another page for more inputs, and eventually displaying a table. However, I'm encountering an issue at this stage: dri ...

Warning: When VueJs OnMount props is utilized, it might display a message stating, "Expected Object, received Undefined."

This is my current component setup: <template> <Grid :items="items" /> </template> <script setup> import { ref, onMounted } from 'vue' import Grid from '@/components/Grid.vue' import { getData ...

Positioning of header, main content, and footer elements

My webpage is structured into three sections: the header, the main, and the footer. The header at the top has a fixed height of 109px with a 6px border. The main section should extend across the entire page below the header and reach the bottom where the ...

Ways to ensure the image stays fixed even as the screen dimensions fluctuate. HTML/CSS

Struggling to create an HTML header with a title and image positioned on the right side, but facing issues with the image shifting over the title when screen size changes. How can I ensure the image stays in place? Have tried various solutions without succ ...

What is the process for transmitting information via a Link in Next.js?

In my upcoming 13.1.5 version, I am faced with a challenge of sending the value of contact.name through a Link in my component. I am looking for the most effective approach to achieve this. The initial code block for the Link represents my original code. ...

What is the best way to establish communication between methods in a React application?

In the SelectedTopicPage component, I currently have two methods: navigateNext and render. My goal is to pass the value of topicPageNo from the navigateNext method to the render method. What is the best way to achieve this in React? When I attempt to decla ...

Looking for a PHP add-on for fpdf converter that can handle ul li tags

I need assistance with using fpdf to convert dynamic site content to pdf. The issue is that fpdf does not support ul li tags. Is there an add-on available for fpdf that supports ul li and ol li tags in html? To provide more context: The content being con ...

Utilizing NLP stemming on web pages using JavaScript and PHP for enhanced browsing experience

I've been exploring how to incorporate and utilize stemming results with JavaScript and PHP pages on web browsers. After running node index.js in the VS Code terminal, I was able to retrieve the output word using the natural library: var natural = re ...

I'm struggling to understand why the background-color is affecting the margins as well

Check out this code snippet: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title></title> <style type="text/css"> * {border: 0px; padding: 0px;} ...

Implement pagination for an array in JavaScript

I am seeking a solution involving displaying a JavaScript object in a paged format. For instance, given the sample object below, I aim to present it as pages based on the value stored in the perPage variable. { "fruits":[ { "from":"Shanghai ...

Is the tooltip display for Typescript types in VSCode reliable? No need for unnecessary type assertions

Exploring the concept of const assertions in TypeScript Looking at the array allDeviceTypes depicted below, VSCode indicates it has a return type of string[] when hovering over the variable name. https://i.sstatic.net/gIYch.png However, upon using a con ...

Getting duplicate tokens for multiple users while utilizing Firebase messaging

When attempting to acquire a token from firebase, I employ the code snippet provided below: const messaging = firebase.messaging(); messaging.requestPermission() .then(() =>{ return firebase.messaging().getToken(); }).then(token => { s ...

Updating the Title of a Page in Node.js

Is it possible to dynamically update the title of each page using NodeJS? The index.html file (located inside the public folder) looks like this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel= ...

The A-frame inspector tool is not very useful within the Glitch platform

Just want to preface this by saying that I am completely new to both a-frame and Stack Overflow. Lately, I've been experimenting with A-frame templates similar to the one linked here: When I pull up the inspector for the example above (ctrl-alt-i), ...

Struggling to use the bind method for the loadScene callback function in cocosCreator or cocos2d-x?

When the loadScene() callback function is bound, the information retrieved from getScene() becomes inaccurate. Upon transitioning from the Entry Scene to the Lobby Scene, I perform post-processing tasks. The implementation was done in TypeScript. Entry. ...

What is the best way to use jQuery to position a <div> at the bottom of another <div>?

Is there a way to achieve something similar to this concept? The dimensions displayed are just for visualization purposes, but feel free to utilize them. I am interested in moving the smaller red <div> box and attaching it to the bottom of the larg ...

The class in my CSS is currently impacting all the menu bar items, but I specifically want it to only affect my photo gallery

<div class="gallery"> <a tabindex="1"><img src="images/smile.jpg"></a> <a tabindex="1"><img src="images/smile.jpg"></a> <a tabindex="1"><img src="images/smile.jpg"></a> ...

Guide to setting up a nested vuetify navigation drawer

I am facing a scenario where I have one fixed navigation drawer with icons and another dynamic navigation drawer that should open and close adjacent to the fixed one without overlapping. The current implementation is causing the dynamic drawer to overlap t ...

Setting up TypeScript in Jest without the need for webpack

Currently, I'm developing an NPM module using TypeScript without the use of Webpack for compiling scripts. I need some guidance on configuring Jest to properly run tests with TypeScript files. Any recommendations? // test.spec.ts import {calc} from ...