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

What is the best way to send an array of grouped data to a table

Here's how I organized the array: { "2023-10-01": [ { "emp_id": 1, "name": "Aruna", "code": "DO", "date": "2023-10-01" }, { &qu ...

What is the best way to retrieve data from Elastic Search using Node.js?

I currently work with NODE JS in conjunction with an elastic search DB. Within this setup, I am utilizing the following package: https://www.npmjs.com/package/@elastic/elasticsearch In my elastic search DB, I have a collection that looks like this: [ { ...

What is the best way to utilize a single component for validating two other components?

I am encountering an issue with my components setup. I have three components in total: GalleryAddComponent, which is used to add a new element, GalleryItemComponent, used to edit an element, and FieldsComponent, the form component utilized by both GalleryA ...

Placing a CSS image with absolute positioning on top of a responsive image

Is there a way to keep the balloon image position fixed in relation to the grid image when resizing it? The balloons Balloon1 and B2 are technically within grid 5 and 7, but if you resize the grid left or right, the balloons will go off-center. Do I requ ...

A guide on expanding an HTML table dynamically with MVC razor syntax

My goal is to dynamically add new rows to a table by following the advice given in this answer on Stack Overflow: Add table row in jQuery I have successfully implemented it for one of my table requirements as seen below: function onAddItem() { $( ...

Transfer an array via Ajax to a Python server script

I need to send the names, values, and labels of my form elements when a button is clicked. Since the submit button messes up the order, I decided to handle it with JavaScript: $('#mybutton').click(function() { m.modal('show'); ...

Achieving horizontal alignment for divs in CSS can be challenging

Struggling to align three circular divs on my webpage, here's the code: <div class="row"> <div class="large-9 push-2 columns"> <div class="green"></div> <a href="#">Donnez</a> </div> <div cl ...

Issue with Flask-Cors in Nuxt with Flask and JWT authentication implementation

I have exhausted all the available solutions to my issue, but I still can't seem to pinpoint the problem. Despite trying every solution out there, nothing seems to be of any help. Every time I make a request, the browser blocks it due to CORS Policy ...

Repeated instances in a loop are strictly prohibited

I am facing an issue with AngularJS where I am unable to display JSON data in my HTML. Below is the code I am using: $('.loading').show(); $scope.posts=[]; $http.get("https://api.basebear.com/json/tables/20a3fb1d-42c7-45cb-9440-2c6d5d10403d/r ...

What is the best way to ensure that my theme button changer has an impact on all pages throughout my website, not only on the

Looking for some help here - I've got a button that changes the theme/colour of my website, but it only seems to work on the homepage and not on any other pages. Anyone know how I can fix this issue? Here's the JavaScript code: $(document).ready ...

converting an entire HTML layout into a PDF using JavaScript

I am attempting to convert an HTML design to PDF using the following script: <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>. I have designed a table to my liking, here is how it looks in HTML: https://i. ...

Do we need to employ strict mode when utilizing specific ES6 functions in Node.js?

There has been a debate circulating at my workplace regarding whether or not it is necessary to include 'use strict' when using ES6 in Node.js without Babel. Some argue that certain ES6 methods may not function correctly without it, but I haven&a ...

Angularjs is struggling to connect data to the user interface

It seems that the array is not binding properly in the UI. In the HTML code, I am using dataTables. The variable $scope.successMessage is also not binding to the UI. I have tried multiple approaches but none seem to be working. Here is a snippet of th ...

What is the best way to upload a file to Firebase Storage using React?

I am facing difficulty uploading a file to Firebase in order to retrieve its getDownloadURL. This is the code snippet I currently have: import React, {useState, useEffect} from 'react' import { Container, Button, Row, Col, Form, Alert } from &ap ...

Active Admin: Maintaining the top menu navigation bar while adding a fresh custom page

I am currently managing an active admin panel which involves several models, including a custom one. I am looking to maintain the top navbar when redirecting to a new page within the admin panel. Main Page: https://i.stack.imgur.com/USov1.png Custom Page ...

executing the following event in Node.js

Is it feasible to execute only a portion of the code on each iteration of the event loop in an application where requests can take a second or two? Consider the following scenario: function foo() { ...critical code... ...start processing the next ...

What is the best way to display a loading image and temporarily disable a button for 3 seconds before initiating the process of sending post data from another page via

Is there a way to display a loading image and disable a button for 3 seconds before sending post data from another page using AJAX POST? Once the OK button is clicked, I would like the loading image to appear and the <input type="button" value="Check" ...

Ways to retrieve the content from a textfield

Is there a way to retrieve text from a textfield in material UI without using the onChange method? It just seems odd that I would need to constantly track the value with onChange in order to use it for any other purpose. I decided to search for solutions ...

Switch button for updating text, icon, and displaying search bar

Having trouble with a header and navigation bar setup. The goal is to have a search button that toggles between "Search" and "Close Search" when clicked, while also opening the search bar below the navigation. I've experimented with different methods ...

To determine the class of an element and reveal its parent if the class is present

Typically, the parent element remains hidden by default. However, upon clicking a specific element, its child might gain a class called "selected". How can I check for this class and then display the entire list if it is present? <ul style="display: ...