Printing with Scalable Vector Graphics (SVG) Technology

I have a unique challenge with an SVG file of a flat displayed in my browser - I need to print it out at a specific scale. I've been using SVG.js to manipulate the content, but I'm struggling to find the right combination of viewport and viewbox settings to achieve my desired outcome.

What I do know is the size of the original SVG source file. Using x and y coordinates, I've calculated a distance to determine the correct "screen scale" that will match 1cm on the plan with a certain number of pixels.

For printing purposes, I must adhere to specific scales like 1/50. So, I attempted to determine the actual size of the flat by applying the screen scale and the SVG file size. Then I applied the 1/50 (0.02) scale to the total size. Finally, I tried to estimate the number of pixels based on a 72dpi resolution.

Below is the code I've been working with:

var svgNode = SVG(planNode);

var totalWidthCm = (svgNode.width().replace('px', '') * screenScale * printScaleVal);
var totalHeightCm = (svgNode.height().replace('px', '') * screenScale * printScaleVal);
var totalWidthPx = totalWidthCm * 0.393701 * 72;
var totalHeightPx = totalHeightCm * 0.393701 * 72;

svgNode.height(totalHeightPx + 'px');
svgNode.width(totalWidthPx  + 'px');

svgNode.viewbox('0', '0', '1000', '600');

The resulting SVG output:

<svg xmlns:cc="http://creativecommons.org/ns#" xmlns:svg="http://www.w3.org/2000/svg"
     xmlns="http://www.w3.org/2000/svg" version="1.1" width="495.79113386880005px" height="387.87611496479997px"
     preserveAspectRatio="xMinYMin slice" id="plan" xmlns:xlink="http://www.w3.org/1999/xlink"
     xmlns:svgjs="http://svgjs.dev/svgjs" viewBox="0 0 496 388">
     .....
</svg>

Unfortunately, I'm still unsure how to adjust the viewport and viewbox settings to display the scaled flat accurately for printing on A4 or A3 paper sizes.

To any SVG experts reading this, your help would be greatly appreciated! :D

Answer №1

It is not guaranteed that something displayed as X pixels on the screen will be the same size when printed. To accurately determine the scale for printing, you should print some samples of your SVG and measure them. Keep in mind that the scale may vary between different browsers and printers.

Start by setting your SVG to render at a 1:1 ratio on the screen. Set the width="496" and height="388" attributes to match the viewBox dimensions.

Print the SVG and measure a known dimension, such as a specific wall length.

For example, if a 2m wall on your plan measures 53mm when printed, the scale factor from real length to printed length would be:

2m = 53mm printed
worldToPrinterScaleFactor = 53 / 2000

To print a 1:1 scale replica of your room, adjust the SVG scale by multiplying it with 1 / worldToPrinterScaleFactor.

For a half-scale copy, multiply the SVG by 0.5 / worldToPrinterScaleFactor.

If you want to print at a scale of 1/50...

printScale = 1 / 50

You would then need to scale your SVG by:

printScale / worldToPrinterScaleFactor

Your JavaScript code could look something like this:

var printScale = 1 / 50;

var worldToPrinterScaleFactor = 53 / 2000;
var svgScale = printScale / worldToPrinterScaleFactor;

var svgNode = document.getElementById("plan");
var viewBox = svgNode.viewBox.baseVal;

svgNode.width.baseVal.value = svgScale * viewBox.width;
svgNode.height.baseVal.value = svgScale * viewBox.height;

Answer №2

To ensure accurate sizing for printing, it is important to set the width and height parameters in print size units such as millimeters. Additionally, defining the viewbox with the same width and height parameters will help achieve the exact desired size on the printed output.

For example, if you are working with a conversion rate of roughly 1/50 from pixels to centimeters:

<svg xmlns:cc="http://creativecommons.org/ns#" xmlns:svg="http://www.w3.org/2000/svg"
     xmlns="http://www.w3.org/2000/svg" version="1.1" width="100mm"   height="80mm"
     preserveAspectRatio="xMinYMin slice" id="plan" xmlns:xlink="http://www.w3.org/1999/xlink"
     xmlns:svgjs="http://svgjs.dev/svgjs" viewBox="0 0 100 80">
     .....
</svg>

By ensuring that the printer is set up for 100% scale (and not "Fit To Page") with the correct paper size, this setup will result in the desired printed output at scale. Scaling adjustments can be made as needed for various requirements, as explained by Paul.

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

The primary directory specified in the package.json file

Question: I have a pre-existing library that I want to turn into an NPM module. Currently, the library is being required through the local file system. How can I specify the main directory path for my module's files? If my structure looks like this: ...

Trouble with mobile compatibility for .json file content population in HTML elements script

Check out THIS amazing page where I have a series of placeholders for phone numbers in the format: 07xxxxxxxx. By simply clicking the green button "VEZI TELEFON", each placeholder in the green boxes gets replaced with a real phone number from a JSON file u ...

What is the process for converting and transferring the date in Google Apps Script to generate a new event in Google Calendar?

To create an event in GAS, follow this link: https://developers.google.com/apps-script/reference/calendar/calendar#createEvent(String,Date,Date,Object) var event = CalendarApp.getDefaultCalendar().createEvent('Apollo 11 Landing', new Date(& ...

What is the manual way to initiate the onclicksubmit event in jqgrid?

Is there a way to manually trigger the onclicksubmit event in jqgrid? If a certain condition is met, I need to programmatically call the submit event. See the code snippet below for reference. afterShowForm: function (formid) { if (condition) { ...

What is the significance of :: in AngularJS?

When reviewing certain Angular JS files, I often come across the following syntax. What is the significance of a double colon "::" in this context? <span>{{::x}}</span> <div>{{::y.z()}}</div> ...

Oops! Encounterred a TypeError stating "Unable to access properties of an undefined object" while working with react native

Within my React Native Quiz function, I have implemented a fetch GET request to load data. Upon checking if the data has loaded using the showQuestion variable, I encounter an error message: Cannot read properties of undefined (evaluating 'questObj[ ...

What order does JavaScript async code get executed in?

Take a look at the angular code below: // 1. var value = 0; // 2. value = 1; $http.get('some_url') .then(function() { // 3. value = 2; }) .catch(function(){}) // 4. value = 3 // 5. value = 4 // 6. $http.get('some_url') ...

What steps can be taken to resolve the error ERROR TypeError: undefined is not an object when evaluating 'userData.username'?

.I need help fixing this error ERROR TypeError: undefined is not an object (evaluating 'userData.username') Currently, I am working on a small application where users are required to allow permission for their location in order to save their cit ...

What is the procedure for defining the secret code for a private key in saml2-js?

I need to implement a key/cert with a passphrase in my project that's currently using saml2-js. I have already set up everything but encountering a bad decrypt error without the passphrase. Is there a way to incorporate this passphrase? Below are the ...

Determining the duration of a button long press in React in seconds

Is there a way to track and display the number of seconds a button is being held down for? For example: "click and hold, starts counting 1, 2, 3, 4, 5, then resets to 0 when released" I have made progress with this functionality, and it works correctly i ...

Erase the Japanese content from the input

Having trouble removing Japanese characters from a text input box using jQuery. Here is the code I am trying: $('#email').keyup(function () { this.value = $(this).val().replace(/[^a-zA-Z0-9!.@#$%^&*()_-]/g,''); }); // try &l ...

The distance calculation is not functioning properly within the for loop

I am currently working on developing a geolocation test app. After finding some useful code for calculating the distance between two points using latitude and longitude coordinates, I am attempting to create a loop using a for loop to calculate the distan ...

Tips for setting react-native image source dynamically in a flat list

As a beginner in react native, I'm attempting to populate a flat list with images that are stored within the app. My goal is to dynamically set the image source in each iteration. This is my current approach, but I'm in need of assistance. <F ...

"HTML and JavaScript: The search functionality fails when trying to search for a string that is sourced from an array

Could someone assist me with a comparison issue I'm encountering? I am trying to use the includes() method to compare a list in a table with a list of names stored in a string. Strangely, when I hardcode the string directly into the includes() method, ...

Developing a JavaScript Set within an Array constructor

Just a heads up: For those who are wondering, I am fully aware that adding methods to JavaScript built-in objects is generally considered to be a bad practice. However, I'm currently in the process of adding a new method to the array prototype for a ...

jQuery Button State Toggler - Disabling and Enabling Buttons

I am trying to utilize jQuery to disable and enable a submit button based on the completeness of the user's input. I have been successful in disabling it, but unfortunately, I can't seem to figure out how to enable it afterwards. $('#submit ...

Establishing the Default Volume within a script

I'm looking to adjust the default volume of music on my website. Currently, it plays too loudly on load, but I have a slider bar that allows users to change the volume. How can I set the default volume to be 25% of the slider? CHECK OUT MY WEBSITE! ...

Checking for date overlap between two textboxes in MVC5 when searching against a date field

Currently, I am exploring options to implement search filters for my model results. I have a field called RunDate and I intend to allow users to search between two dates using two textboxes. @Html.TextBox("StartDate", null, new { @class = "datefield form- ...

"An error occurred: Attempting to access properties of an undefined object (specifically 'foundTicket'). While the getTickets() function, which fetches data from MongoDB using Mongoose, is working fine, the getTicketById()

I recently started working with next.js and I'm following a project tutorial by a YouTuber. Here is the link to my code: https://github.com/Fanguiee/ticketing-app/tree/edit-existing-item or you can also read below. Thank you in advance :) Screenshot: ...

Creating a function generator using a string parameter in TypeScript

Is there a way to pass a string parameter to a function and retrieve an object with that key? function getFunction(name: string): { [name]: () => number } { return { [name]: () => { console.log(1); return 2; }, }; } const { m ...