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

What is the best way to determine Prisma types across various projects?

My current project has the following structure: dashboard -- prisma-project-1 -- prisma-project-2 -- client-of-prisma-project-1-and-prisma-project-2 This dashboard is designed to merge data from two separate databases and display them in a meaningful w ...

How to Adjust the Padding of Tree Row in GWT?

Have you ever seen a GWT tree before? It sort of resembles the following structure: <div class="gwt-Tree"> <div style="padding-top: 3px; padding-right: 3px; padding-bottom: 3px; margin-left: 0px; padding-left: ...

When executing a Javascript POST request to a PHP script, it succeeds when running on

I have a simple code that works fine on my website when the PHP file is linked as "/phpcode.php", but it fails to retrieve data when I place the JavaScript request on another site and use the full link. I am currently using GoDaddy as my hosting provider. ...

Arranging cells within a table with numerous rowspan configurations

I need some help creating a table that will be divided using rowspans for a PDF rendering with BFOreports. I have included an example layout below (numbers are just for reference): https://i.stack.imgur.com/Wbe96.png However, the output I am currently ge ...

Is it possible to conceal the status bar in a web app designed for iOS 7?

Currently working on a project that involves creating an "add to home screen" game. I am looking for a way to hide the status bar completely, including the time and battery indicators. I know it is possible to change the color of the status bar, but can it ...

Autodesk Forge serves as a hub for hosting dependencies on a nearby server

Our company has implemented an Angular/TypeScript version of the Forge Viewer, currently loading dependencies from Autodesk's server. To ensure these files are always accessible to our customers, we want to host them on our own servers. However, attem ...

CSS media queries with precise inequality restrictions

Imagine the following scenario: @media only screen and (max-width: 600px) { nav { display: none; } } @media only screen and (min-width: 601px) { nav { display: block; } } This setup can lead to undefined behavior for a wid ...

Using angular.js variables in the script tag: A step-by-step guide

Currently, I am working on a project that involves displaying elements on a view using Angular.js and attempting to connect these DOM elements using jQuery connections. While the elements are being displayed correctly, I am encountering an issue when tryin ...

Unlimited Possibilities in Designing Shared React Components

Seeking the most effective strategies for empowering developers to customize elements within my React shared component. For example, I have a dropdown and want developers to choose from predefined themes that allow them to define highlight color, font siz ...

Accordion menu causing Javascript linking problem

After following a tutorial, I managed to create an accordion menu in JavaScript. In the current setup, each main li with the class "ToggleSubmenu" acts as a category that can hide/show the sub-lis. Now, my query is this: How can I retain the link functio ...

Establish and define the global variable "Protractor"

In order to pass a string value from the function editPage.CreateEntity();, you can use that value in multiple test cases by assigning it to the variable entityName. You are able to retrieve the value by setting up the test case as follows: fit('Te ...

My website using Dynamic Ajax technology is currently experiencing heavy traffic due to the number of getScript

I am facing an issue with my dynamic website where all links fetch new sections via ajax requests from other pages and replace the current section. The problem I encounter has two main aspects. When loading a new div from an Ajax get request, some sections ...

Dealing with AJAX errors consistently in jQuery

Is it possible to efficiently handle 401 errors in AJAX calls and redirect to login.html without repeating the same code over and over again? if (xhr.status === 401) { location.assign('/login.html'); } I am seeking a way to manage these erro ...

Storing the results of an Ajax call in a global variable

What is the best way to store and access the output of an ajax call within a global variable? let globalOutput = []; $.ajax({ type: "GET", url: uri, dataType : "json", contentType: "application/json", data: { input: filterVa ...

Having trouble with Webpack dynamic import not returning files in ReactJS? Here's how to fix it

Struggling with importing and using images in Reactjs? I've imported all images from a folder but it's not returning an array with links. Take a look. function importAll(r) { return r.keys().map(r); } const images = importAll(requi ...

Utilizing the :after pseudo-element for placing text in a specific location

Here's the code I'm working with: div#myImg{ background: url('myimage.png') left top no-repeat; } div#myImg:after{ content: 'TEXT UNDER IMAGE'; margin:0 auto; vertical-align:text-b ...

Is it possible for the UUIDs generated by the uuid package to be identical?

I am in need of creating unique UIDs for objects that will be stored in a database. To achieve this, I am utilizing the UUID npm package for generating unique identifiers. I have concerns regarding the possibility of duplicate IDs being generated by this p ...

Responsive breakpoints in TailwindCSS seem to have an issue with applying padding and margin styles properly

Currently, I am tackling a project that involves creating a responsive design with Tailwind CSS on nuxtjs. Has anyone encountered the issue of py-8 applying to both breakpoints? If so, please share your insights! Here is how I have structured the compone ...

What is the best way to search for an Enum based on its value?

One of my challenges involves an enum containing various API messages that I have already translated for display in the front-end: export enum API_MESSAGES { FAILED_TO_LOAD = 'Failed to load data', TOKEN_INVALID = 'Token seems to be inva ...

Can we implement attribute selectors in Material-UI while utilizing makeStyles?

Is it possible to extract all the div elements with specific Mui class names such as access-MuiPickersCalendarHeader-switchHeader, access-MuiPickersDay-day? My components are styled using StylesProvider which adds "access" as a prefix to the original Mater ...