Creating beautiful prints with images

I have been tasked with developing an MVC C# application where the contents of a div are dynamically created using an AJAX call to fetch data from a database. Upon successful retrieval, the content is then displayed as a success message in JavaScript. Here's a simple example of the generated string:

"<div style='background:yellow'>asdf<img src='myfile.jpg'></div>"

To print this content, the following function is used:

function printDivContents(contents) {
    var printContents = contents;
    var originalContents = document.body.innerHTML;
    document.body.innerHTML = "<div style='margin:10px'>" + printContents + "</div>";
    window.print();
    document.body.innerHTML = originalContents;
}

While everything prints correctly most of the time, there seems to be an issue with the image within the content only printing if it has been loaded before. I am looking for a solution to ensure that the image always prints, regardless of prior loading. I have experimented with preloading the script into the content string but have not had success thus far. It is important to note that I can only use pure JavaScript and inline CSS exclusively. What options do I have to address this issue? Should I halt execution to wait for the DOM to load, set the image as a hidden div background on the calling page, or pursue another approach?

Answer №1

When calling the initial AJAX request on a webpage, establish an invisible division like this:

<div style="display:none; background:url('newfile.jpg')"></div>

To reflect any modifications to the file dynamically, adjust the background of the division before displaying it.

Answer №2

For those looking to maintain the ability to modify images dynamically, I encountered a similar challenge and discovered that delaying actions until the image has fully loaded proved effective:

var img = new Image();
img.onload = function () {
    // display on screen or perform other tasks
};
img.src = "desiredImageSource";

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

Adjust the background hue of the Row in the Table

Is there a way to update the background color of a Table Row? I attempted using "BackgroundColor" but didn't see any changes Any suggestions on how to fix this issue? <TableRow style={{ backgroundColor: "#FF0000" }}> <TableCell& ...

Learn the process of dynamically populating an HTML table with data using JavaScript and JSON

I have developed a code snippet to dynamically add an HTML table without using jQuery. The code serves as an application from the server to the client, where the client receives a JSON object to parse into a string. Here is how you can add an HTML table ...

Toggle the row to expand or collapse upon clicking it

After extensive research, I have been unable to get the row expansion and collapse feature to work in my script. Here is my current script: <thead> <tr> <th width="5" class="cb"><input type="checkbox" id="cbcall" /& ...

What is the proper way to use Object.entries with my specific type?

On my form, I have three fields (sku, sku_variation, name) that I want to use for creating a new product. I thought of converting the parsedData to unknown first, but it seems like a bad practice. export type TProduct = { id: string, sku: number ...

Set up specific vue.config.js configurations for unique environments in Vue

I am working on a multi-page app where I want certain pages to only show up in my development environment. Here's how my vue.config.js looks: module.exports = { productionSourceMap: false, pages: { index: "src/main.js", admin: { ...

Asynchronous AJAX processing in Ruby helper functions

I need assistance with running an asynchronous ajax request in a Ruby on Rails helper method. Specifically, I am trying to use remote_function: remote_function :url => { :action => "draw_graph" }, :after => "do_something_after_ajax_is_done()" } ...

By implementing setInterval, but I aim to deactivate it upon detecting user input

Currently, I have a function being called using setInterval that loads my page via an ajax get request and displays the response in real-time like a live updates page. The issue arises when users are inputting data into the form because the page is refresh ...

How to eliminate duplicate items in an array using various criteria

I have an array arr that needs to be cleaned up by removing duplicate objects with the same e_display_id and e_type as P. In this scenario, only objects with status==='N' should be considered. Here is the input array arr: let arr = [ { e_type ...

How can I retrieve the URL of images listed in my CSS file using Python?

I need help extracting all image URLs used in a CSS file. Here is an example snippet from my CSS file: sitewrap { width: 890px; margin: 0 auto; background: #ffffff url(../images/bg_sitewrap.gif) repeat-y; } Can anyone advise on how to extract ...

I'm having trouble getting Jquery's insertAfter() function to function properly

After creating a parent div and using jQuery's insertAfter() method to insert additional divs, an unexpected issue arises. The first record goes to the bottom, while subsequent records are inserted above it. Below is the function in question: functi ...

Primary tag badge using Bootstrap design

I am currently following a React tutorial by Mosh, where he is using the badge badge-primary class in a span tag. import React, { Component } from "react"; class Counter extends Component { state = { count: 0, }; render() { return ...

What is the best way to enlarge a Material UI card?

Currently, I am utilizing Material UI version 4 on my website and integrating cards (for more details, click here). https://i.stack.imgur.com/dm2M2.png I am interested in enlarging the overall size of the card so that the image appears larger. As I am si ...

Trying out the Send feature of Gmail API using Postman

Attempting to use the Gmail API for sending emails. Utilizing Postman as a tool to test requests and obtain correct code for web application integration, encountering an error: { "error": { "errors": [ { "domain": "global", ...

Detecting Android devices

Issue: My website functions properly on desktop but has a problem with the carousel images skewing on iPhones. To address this, I created a separate CSS styling for iPhone devices and used a JavaScript function found online to detect iPhones and iPads. Un ...

Is there a way to filter an array of dates without using the map function when a click

After finally grasping how to pass and retrieve data in React, I encountered an issue. I have a click handler called this.SortASC, and when I click on the title, I want to sort the titles alphabetically. However, I'm having trouble getting this functi ...

Troubleshooting Cordova's ng-route functionality issue

I am currently working on an Angular application that includes the following code: // app.js var rippleApp = angular.module('rippleApp', ['ngRoute', 'ngAnimate', 'ngAria', 'ngMaterial']); // configure ou ...

Animate moving between two points over a set period using JavaScript

My attempt to smoothly move a box from one position to another using Linear Interpolation is not working as expected. The box just moves without any easing effect. I came across a post on Stack Overflow titled C# Lerping from position to position, but I ma ...

Validate HTML 5 using Jquery assistance for best results

I have a form that includes HTML 5 Validations. I am looking to display a loader only when there are no error messages from the HTML 5 validation process. I have experimented with using the onclick event of the submit button and also attempted to trigger i ...

Centering items in Bootstrap 4, while excluding the first element

.c-footer { background: #000; padding: 20px 0; color: #fff; } .c-footer__logo { display: inline; } .c-footer__link { color: inherit; } .c-footer__link a { color: inherit; } .c-footer__link a:hover { color: #fff; } ...

Getting a variable from an ajax call and using it in a Pug template

Currently, I am experimenting with Express and Pug to learn some new concepts. Upon making a request to a website, I received some dynamic information stored in an array. However, I am facing challenges when trying to iterate over this array using Pug. The ...