Display text on the screen with a customized design using JavaScript's CSS styles

I need help with printing a specific page that contains some information designed in print.css. I want to print this page, including an image, with the same style.

function printContent() {
    var divContents = document.getElementById("terms").innerHTML;
    var a = window.open('', '', 'height=1000, width=1000');
    a.document.write('<html>');
    a.document.write("<link rel=\"stylesheet\" href=\"print.css\" type=\"text/css\" media=\"print\"/>");
    a.document.write('<body >');
    a.document.write(divContents);
    a.document.write('</body></html>');
    a.document.close();
    a.focus();
    setTimeout(function () {
        a.print();
    }, 1000);
    a.print();
}
p {
    display: inline-block;
}

.container header .top {
    display: flex;
    align-items: center;
    gap: 30px;
    margin-top: 30px;
    padding-bottom: 20px;
    border-bottom: 2px solid #2c2a6b;
}

.container header .top h1 {
    color: white;
    background-color: #2c2a6b;
    padding: 10px 20px;
    width: fit-content;
    width: -moz-fit-content;
    border-top-left-radius: 20px;
}

.container header .top .print-header {
    display: flex;
    gap: 20px;
}

.container header .top .print-header h2{
    color: #2c2a6b;
    align-self: flex-end;
}

.container header .print-subheader {
    padding: 20px 0;
    color: #2c2a6b;
}

.container main .print-content .top {
    display: flex;
    align-items: flex-end;
    gap: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #2c2a6b;
}

.container main .print-content .top img {
    width: 50px;
}

.container main .print-content .top h3 {
    color: #2c2a6b;
}

.container main .print-content .content{
    margin-top: 20px;
}

.container main .print-content .content .inner-box{
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 10px;
}

.container main .print-content .content .inner-box p{
    color: #000;
    font-weight: 500;
    font-size: 16px;
}
<body>
    <div class="container" id="terms">
        <header>
            <div class="top">
                <h1>Tourism Sector</h1>
                <div class="print-header">
                    <img src="images/title-icon.png" alt="title">
                    <h2>Issuance of Tourist Accommodation License</h2>
                </div>
            </div>
            <div class="print-subheader">
                <h2>Obtaining an Investment License (Foreign Investor)</h2>
            </div>
        </header>
        <main>
            <div class="print-content">
                <div class="top">
                    <img src="images/terms.png" alt="terms">
                    <h3>General Terms</h3>
                </div>
                <div class="content">

                </div>
            </div>
        </main>
    </div>
    <input type="button" class="btn-print" onclick="printContent()" value="Print">
</body>

The issue I'm facing is that the image and style do not appear correctly after clicking the print button. Despite trying different solutions like putting a timeout and including the print.css file with media print, the problem persists. Any assistance would be greatly appreciated.

Answer №1

It appears that the solution provided may be overly complex for a simple requirement, but it's possible there are additional details not mentioned in the question.

Seems like you're dynamically including the CSS file for printing purposes, however, CSS already has a built-in feature for this. I suggest removing all JavaScript and instead utilizing a print media query within your CSS:

@media print {
    p {
        display: inline-block;
    }

    /* add any other necessary styles here */
}

Integrating these print styles into your existing CSS will allow the browser to handle them automatically when in print mode.

If using JavaScript is absolutely necessary, you'll need to ensure the stylesheet has finished loading before executing any code. This can be achieved by creating an element, attaching an event listener for the onload event, then appending it to the DOM.

Here's an example:

let styles = document.createElement('link');
styles.addEventListener('load', function(){
    window.print();
});
styles.setAttribute('rel', 'stylesheet');
styles.setAttribute('type', 'text/css');
styles.setAttribute('href', 'print.css');
document.head.appendChild(styles);

Answer №2

Maybe this can offer some assistance

HTML

<body>
    <div class="container" id="terms">
        <header>
            <div class="top">
                <h1>قطاع السياحة</h1>
                <div class="print-header">
                    <img src="images/title-icon.png" alt="title">
                    <h2> اصدار رخصة الإيواء السياحي</h2>
                </div>
            </div>
            <div class="print-subheader">
                <h2>الحصول على رخصة استثمار (المستثمر الاجنبي)</h2>
            </div>
        </header>
        <main>
            <div class="print-content">
                <div class="top">
                    <img src="images/terms.png" alt="terms">
                    <h3>الاشتراطات العامة</h3>
                </div>
                <div class="content">

                </div>
            </div>
        </main>
    </div>
  <button onclick="window.print();" class="noPrint">
Print Me
</button>
</body>

CSS

@media print {
  .noPrint{
    display:none;
  }
}
h1{
  color:#f6f6;
}

p {
    display: inline-block;
}

.container header .top {
    display: flex;
    align-items: center;
    gap: 30px;
    margin-top: 30px;
    padding-bottom: 20px;
    border-bottom: 2px solid #2c2a6b;
}

.container header .top h1 {
    color: white;
    background-color: #2c2a6b;
    padding: 10px 20px;
    width: fit-content;
    width: -moz-fit-content;
    border-top-left-radius: 20px;
}

.container header .top .print-header {
    display: flex;
    gap: 20px;
}

.container header .top .print-header h2{
    color: #2c2a6b;
    align-self: flex-end;
}

.container header .print-subheader {
    padding: 20px 0;
    color: #2c2a6b;
}

.container main .print-content .top {
    display: flex;
    align-items: flex-end;
    gap: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #2c2a6b;
}

.container main .print-content .top img {
    width: 50px;
}

.container main .print-content .top h3 {
    color: #2c2a6b;
}

.container main .print-content .content{
    margin-top: 20px;
}

.container main .print-content .content .inner-box{
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 10px;
}

.container main .print-content .content .inner-box p{
    color: #000;
    font-weight: 500;
    font-size: 16px;
}

If you include the class="noPrint" you can eliminate elements from being printed! Let me know if this meets your needs

Check out this codepen.io link

Answer №3

Would you like to dynamically load the image using JavaScript?

Or is this the image in question?

terms.png

The image should be visible, but you also have the option to load it separately with JavaScript and customize it in print.css.

a.document.write('<link rel="stylesheet" type="text/css" href="./print.css">'); //imports the style

document.write('<img src="./images/terms.png"> //or 
document.write('<img src="./images/terms.png" style="custom style for the image">

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

Unforeseen issues arise when working with CSS selectors

Exploring CSS with a series of buttons and encountering some unusual behavior. Here's the code: https://codepen.io/buoyantair/pen/JNgqXG?editors=1100 Let me share the snippets for Pug Script and Sass file: Pug Script header.row .col ...

Perform an Ajax request upon clicking on the dropdown list item

I recently created a drop-down list using some JavaScript code. Here's how I did it: <script> $('.menu').dropit(); </script> <ul class="menu"> <li> <a href="#">Product_name</a> ...

Protractor functions perfectly on localhost, but encounters a Timeout error when used remotely - the asynchronous callback was not executed within the specified timeout period

Running protractor protractor.conf.js --baseUrl=http://localhost:4200/ executes successfully by filling data, validating elements, etc. However, when attempting to test the same website through a remote URL protractor protractor.conf.js --baseUrl=http://t ...

Tips for getting the setTimeout() function to behave like a for loop

Is there a way to achieve the setTimeout() function's behavior in a for-loop? Take a look at this code snippet: function hello() { for (let index = 0; index < 3; index++) { setTimeout(function () { console.log('What&bs ...

Ways to determine if a script is currently running within Node.js环境

In my Node.js script, I am importing a separate script that I want to be compatible with various JavaScript engines. Specifically, I only want the line exports.x = y; to run if the code is being executed in a Node.js environment. How can I determine this ...

Socket.io operates individually with each user

Showing a basic web-chat using socket.io. Node.js code: io.on('connection', function(socket) { // Sends 'hello world' message to all users socket.emit('send:message', { text: 'hello world' }); ...

A guide on parsing a nested JSON file with ExtJS 4

Here is the content of my JSON file named "jobInfo.json": { "job": { "id": 1, "name": "Job 1", "description": "bla bla bla", "locations": { "type": "FeatureCollection", "features": [{ "id": 1, "t ...

The issue of req.file being consistently undefined in Node.js multer

I am having issues trying to upload a file using multer because the req.file is always undefined and the destination folder remains empty: Server: var express = require('express'); var multer = require('multer') var app = express(); ...

Updating a field in Mongoose by referencing an item from another field that is an array

I have developed an innovative Expense Tracker Application, where users can conveniently manage their expenses through a User Collection containing fields such as Name, Amount, Expenses Array, Incomes Array, and more. The application's database is p ...

Transform uploaded image file into a blob format and store it in a VueJS database

I am facing an issue with my form that has multiple inputs, including one of type "file". My goal is to upload an image and then submit the form to the API for storage in the database. <input name="image" class="w-full border-2 border-gray-200 rounded-3 ...

Decoding JavaScript content with Python

Currently, I am dissecting this specific portion of HTML <script type="text/javascript"> var spConfig = new Product.Config({"attributes":{"150":{"id":"150","code":"size_shoe","label":"Schuhgr\u00f6\u00dfe","options":[{"id":"494","label ...

The functionality of ellipsis, which consists of three dots, allows the text to expand

I am trying to implement a feature where the extra text is represented by three dots (...) as an ellipsis, and upon clicking the dots, the text should expand and contract. However, the current code only contracts the text and does not expand it upon clicki ...

Modify variables in the child function to be utilized in the parent function

I need to create a scenario where a variable defined in a parent function is modified within a child function and then returned back to the parent as an updated variable. Here is the code I have attempted: let value = 20; console.log(value); // Output: ...

HTML file unable to connect with CSS stylesheet

I'm facing an issue where my CSS stylesheet and HTML files aren't linking properly. Here is the code snippet from my HTML file: <head> <title>Website Sample</title> <meta charset="UTF-8"> <meta http-equiv= ...

Issue with displaying personalized radio buttons

I added a custom radio button, but it's not showing up. It seems to work when arranged like this: <label> <input type="radio" name="gender" /> <span>Female</span> </label> Why isn't it working? Is there somethin ...

Fixing an erroneous value that has been dragged into the drop function with Jquery

I am encountering an issue with my codes and need some assistance in identifying the problem. The data is being dynamically loaded from the database, and I am using a foreach loop to display all items in a draggable div. The issue arises when I drag an it ...

JQuery Keyup event is not functioning as expected

For my blog navigation, I have set up an event where pressing the 'J' key takes me to the previous post and the 'K' key takes me to the next post. However, I am facing an issue where the event works initially but stops working after the ...

Despite being correctly linked in EJS and without any errors, the CSS is still not loading

Hey there, I'm facing an issue with linking a CSS file to an EJS file. I believe that I am connecting them correctly: <head> <title>Acres & Karats Calculator</title> <base href="/"> <link type="text/css" href="css/Acres ...

Display HTML components as JSON data using AngularJS

Recently, I started exploring angular js and faced a challenge in formatting json data with the help of angular js. Below is a snippet of my json data: [ {"field_add_link": "<a href=\"/drupal3/drupal3/\">Home</a>"}, {"field ...

Is there a way to customize the hover style of Material UI Select or Menu MenuItem using the theme?

The theme I designed import { createMuiTheme } from 'material-ui/styles'; export const MyTheme = createMuiTheme({ palette: { primary: { light: '#757ce8', main: '#3f50 ...