What is the best way to restore the original dimensions of images after they have been altered?

I have content displayed on a webpage with images, each image having a specific width or none specified. When a user clicks a button, the content is exported to a PDF file. To ensure the images fit correctly on the PDF page, I adjust their width and height. However, this adjustment also affects the images on the webpage itself. How can I prevent this from happening?

You can see a demonstration here: https://plnkr.co/edit/STVjUB1YMwbOrtYLxR8V?p=preview

In the demo above, when you click on the export button, the image dimensions are altered to ensure they fit properly in the PDF file. Unfortunately, these changes also impact the images displayed on the webpage. Is there a way to apply the modified dimensions only to the PDF file without affecting the webpage?

Here is an example of the HTML code:

<button ng-click="export()">export</button>
<div class="myDivClass"..>
 <img src="data:image/jpeg..">
 <img src="..." style="width:400px">
 ..
 //content
</div>

And here is the corresponding JavaScript code:

$scope.export = function() {
         var imagesToResize = document.getElementsByTagName("img");
         for(i=0;i<imagesToResize.length;i++){
            imagesToResize[i].style.width = "100px";
            imagesToResize[i].style.height = "100px";
        }

Any suggestions on how to address this issue would be greatly appreciated.

Answer №1

--- Update---------------------------------------------------------

Upon further investigation, I discovered that the issue stemmed from using document.getElementByTagName('img') and manipulating all images at once. This approach isn't suitable when you only need specific printable images to have custom height and width adjustments. Instead, it's better to move your printable content to a hidden div, perform the necessary manipulations there, and then use that div for printing. I created a GitHub repository where you can view the solution and determine if it resolves your problem. Find the repository here: https://github.com/sagarb3/jspdf-demo

In the GitHub link, I stored downloaded images as base64 to avoid cluttering the project. I also made modifications to some functions.

While my understanding of jspdf wasn't extensive, I managed to come up with a viable solution.

This is how my index.html appears now:

<!doctype html>
<html ng-app="app">

<head>
    <!-- Various script and stylesheet links -->
</head>

<body>
    <div ng-controller="listController">
        <button ng-click="export()">Export</button>
        <div id="content-div">
            <!-- Content structure -->
        </div>
    </div>
    <div id="pdf-content" style="display:none">
    </div>
</body>

</html>

And here is the JavaScript file containing the solution:

 var app = angular.module("app", []);

 app.controller("listController", ["$scope", '$timeout',
     function($scope, $timeout) {

         $scope.employees = [{ pageIndex: "div1", pageHeader: "This should be shown in page1" },
             { pageIndex: "div2", pageHeader: "This should be shown in page2" }
         ];


         $scope.export = function() {
             var pdf = new jsPDF('p', 'pt', 'A4');
             var pdfName = 'test.pdf';
             var vDom = $('#pdf-content').html($('#content-div').html());
             // Additional logic for exporting to PDF
         }
     }




 ])

Stay tuned for updates!

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

Pinia: Is it better to invoke '{myStore}' or 'return myStore' within the return statement?

I'm currently working on integrating a Pinia store into a component of my Vue app and I'm puzzled by the need to return the store in { } instead of just returning it as is. Can someone clarify the distinction between return {foo} and return foo f ...

The ng-cloak directive doesn't seem to be functioning properly

After writing some code to remove '#' tags from text input, I encountered an issue upon loading the page. The initial display showed '{{textWithHashes | textWithoutDashes}}', which is not appealing at all. I attempted to use ng-cloak to ...

Saving base64 encoded pdf on Safari

I am facing an issue with a POST call that returns a base64 PDF. The problem arises when trying to convert it to a Blob and download it using Safari browser. This method works perfectly in all other browsers. openPdf = () => { const sendObj = { ...

Retrieve an XML file using JavaScript and store it within a variable

I am currently developing a PhoneGap Application utilizing jQuery Mobile. One of the requirements is to access an xml file stored on a remote server (accessible through a web server like http://www.example.com/myXmlFile.xml). My goal is to extract the cont ...

Exploring yii2 with javascript to display image previews

I am looking to add a feature to my yii2 app similar to this: How to preview multiple images before upload?. I want to display up to five images but my current code is not working. When I select a file, nothing happens. <?php use yii\helpers\ ...

Using a jQuery plugin within an Angular 2 component: A step-by-step guide

Looking to implement an image slider plugin called Vegas only on the home page within my Angular 2 application. The Vegas jQuery plugin has been added via npm and is located under the /node_module directory. The following code snippet shows my home page c ...

Updating a Div with XML data through JQuery

Hey everyone, I have a simple question that I need help with... Currently, I am using jQuery to retrieve an XML document in the following format: $.ajax({ type: verb, url: url, dataType: datatype, success: callback }) } After receiving t ...

Updating state before and after making an API request

I have implemented an asynchronous function with prevState in my code. The purpose of using prevState is twofold: 1) updating a deeply nested object and 2) sending data to an API based on the current state. Asynchronous programming is utilized for the API ...

Excessive white space on WordPress pages is creating a less than ideal

On my WordPress page, I have set up a row with the main side at span10 and the right sidebar at span2. However, the layout leaves too much blank space, causing users to scroll to the right and see nothing. You can view the specific page here Below is the ...

What is the unit that you can deduct from a JavaScript / MongoDB Date object?

In relation to the query found at , I am seeking guidance on deducting N days from a Date object. Given that MongoDB utilizes JavaScript data types, my inquiry is this: When subtracting X from Date(), does X represent seconds? Minutes? Or microseconds? ...

Custom dropdown selection using solely JavaScript for hidden/unhidden options

I'm trying to simplify things here. I want to create a form that, when completed, will print the page. The form should have 3-4 drop-down lists with yes or no options. Some of the drop-downs will reveal the next hidden div on the form regardless of th ...

Can TypeScript support the implementation of versatile decorators that can be linked together based on their input and output types?

Within our integration processes, we have developed templated implementations in our codebase that align well with the "pipe and filter" pattern in my opinion. These "components" can be structured in the following formats: class Component1<In, Out, Xi ...

Replacing a div with another div can be achieved in a single swap

My goal is to swap one div with another div upon clicking using the provided code. It functions properly for a single instance. However, the issue arises when the class appears multiple times, causing all instances to change due to sharing the same class n ...

To initiate dragula on button click, simply add the dragula attribute

Currently, I am working with Angular (4.0) and ng2-dragula. I have turned a div into a dragula container to enable item movement within it using the following code: <div id="dragcontainer" [dragula]='"first-bag"'> Now, I want to add a fea ...

When clicked, the menu disappears successfully with the "show" functionality, but unfortunately, the "hide" feature is not working as intended

Within my menu, I have a section for portfolios that transforms into a dropdown on desktop hover and mobile click. The issue arises on mobile devices where the first click displays the menu correctly, but subsequent clicks do not trigger any change. I att ...

How can I ensure that images remain within the link elements in a flex container?

I'm currently assisting a colleague with his website. His main request is to have the two images positioned below the larger image at the beginning of the page align perfectly with the edge of the page, so that the right image lines up with the one ab ...

Turn off automatic vertical scrolling when refreshing thumbnails with scrollIntoView()

My Image Gallery Slider has a feature that uses ScrollIntoView() for its thumbnails, but whenever I scroll up or down the page and a new thumbnail is selected, it brings the entire page back to the location of that thumbnail. Is there a way to turn off t ...

Troubleshooting: Issue with Ajax communication to PHP backend script

I followed the solution on this Stack Overflow post but unfortunately it did not work as expected. When I open test.php, I see a box to input text and a submit button. However, when I try to submit the form, Firefox's developer console shows the follo ...

What is the best way to display HTML content from a stored object?

In my project using Next.js, I am faced with the challenge of rendering custom landing pages based on their unique URLs. While I have successfully retrieved all the necessary details from the database for each specific URL, there is a particular object con ...