Automatically tally up the pages and showcase the page numbers for seamless printing

I've been tackling a challenge in my Vue.js application, specifically with generating invoices and accurately numbering the pages. An issue arose when printing the invoice – each page was labeled "Page 1 of 20" irrespective of its actual position in the document. This inconsistency has left me perplexed, and I'm struggling to find a resolution. Any suggestions or troubleshooting insights would be greatly welcomed. Below is the problematic code snippet:

<template>
  <div style="background-color: lightgray" >
    <div style="background-color: white;margin: auto;width: 29.7cm" id="printable-content">
      <!-- Invoice content goes here -->
    </div>
  </div>

  <div class="invoice">
    <!-- Invoice content continues here -->

    <!-- Page number -->
    <span class="page-number"> <span class="page-counter"></span></span>
  </div>


</template>
<script>

export default {
  data() {
    return {
      pageNumber: 1, // Initial page number
      items: [
        {name: "Item 1", quantity: 2, price: 10, vat: 20, price_in: 1200, totalt: 2000},
        {name: "Item 2 with a long name that needs to be truncated", quantity: 1, price: 20},
        {name: "Item 3", quantity: 3, price: 15},
        <!-- More item objects -->
      ]
    };

    
  },
 
  methods: {
  limitNameLength(name) {
    const maxLength = 20;
    return name.length > maxLength ? name.substring(0, maxLength) + '...' : name;
  },
  updatePageCounter(totalPages) {
    const currentPage = this.pageNumber;
    this.$nextTick(() => {
      const pageCounterElement = document.querySelector('.page-counter');
      if (pageCounterElement) {
        document.querySelector('.page-counter').textContent = currentPage;
        pageCounterElement.textContent = `Page ${currentPage} of ${totalPages}`;
      }
    });
  },
},

mounted() {
    const totalPages = 20;
    this.updatePageCounter(totalPages);
  },


};

</script>

<style lang="scss">
thead td, tfoot td {
  padding: 20px;
}

tbody tr td {
  padding: 5px 20px;
}


.rejectBreak {
  page-break-after: always;
}

@media print {
  .page-footer {
    position: fixed;
    bottom: 0;
    right: 0;
    left: 0;
    padding: 10px;
    background-color: white;
    border-top: 1px solid lightgray;
    text-align: right;
  }

  tfoot {
    display: table-footer-group;
  }

  button {
    display: none;
  }

  body {
    margin: 0;
  }

  tfoot .tfootHolder {
    display: none;
  }
  .tfoot {
    display: block !important;
    padding: 20px;
    position: fixed;
    bottom: 0;
    width: 29.7cm;

  }
  .page-footer-space {
    height: 300px;
  }

  @page {
    size: A4;
  }

  <!-- Additional print styles -->

</style>

Despite extensive Vue.js coding, the page counting functionality remains faulty.

Answer №1

When working with Vue, it is recommended to use the ref attribute instead of document.querySelector for selecting elements (specifically in Vue 3):

<template>
<div ref="myDiv">lorem ipsum</div>
</template>

<script>
const myDiv = ref(null); // Start by initializing as null and ensure the variable name matches the ref attribute on the div.
</script>

In Vue 2, the approach would be:

<template>
<div ref="myDiv">lorem ipsum</div>
</template>

<script>
export default {
  mounted() {
    this.$refs.myDiv.innerHTML = 'Page number…';
  }
}
</script>

Additionally, there may be uncertainties around using $nextTick while in the print dialog.

One suggestion is to iterate through your invoices and adjust the height of each invoice <div> based on the paper size you are printing on:

<div class="page" v-for="(invoice, index) in invoices" :key="invoice">
  <span>Page {{ index + 1 }}</span>
</div>

<style>
@media print {
  .page {
    height: 793px; /* approximately 1 A4 page */
    break-after: always; /* enforce page break */
  }
}
</style>

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

Steps for Displaying Data from API Response in Vue.js

Immediately rendering the following template, without waiting for the API call to complete. I came up with a solution using v-if to prevent elements from rendering until the data is available. However, this seems to go against the DRY principle as I have ...

What strategies can be employed to mitigate the activation of the losing arm in a Promise.race?

My current task involves sending the same query to multiple identical endpoints (about five) across various Kubernetes clusters. The goal is to aggregate the results without any delays and report failures to the user while continuing with the process seaml ...

Guide on how to use JavaScript to swipe through loaded epub files in both lateral directions

Hello everyone, I have a question about implementing swipe functionality on a loaded epub using JavaScript. I successfully loaded the epub into a div and now I need to enable swipe left and right gestures on that div. I found a jQuery script that should a ...

Take the inputs, calculate the total by multiplying with the price, and then show

I'm in the process of developing a simple PHP form for an online t-shirt order system. Most aspects are running smoothly, but I'm facing issues with the final calculations. My goal is to combine the quantities based on sizes, multiply them by the ...

Exploring the scope in JavaScript functions

Looking at this small code snippet and the output it's producing, I can't help but wonder why it's printing in this unexpected order. How can I modify it to achieve the desired output? Cheers, The desired result: 0 1 2 0 1 2 The actual r ...

Modify an HTML table and record any modifications as POST requests using Javascript

As a beginner in JavaScript and HTML, I am open to corrections if I am not following the correct practices. Recently, I delved into editing an HTML form table. {%extends 'base.html'%} {%block content%} <html> <body> <h4> Search ...

Adjusting the height of content in Angular Material 2 md-tab

I've recently started working with angular material and I'm facing an issue while trying to implement md-tab into my application. The problem is that I can't seem to style my tab content to take up the remaining height of the screen. Could s ...

Can anyone help me with integrating a search functionality inside a select tag?

I am working on a select dropdown and want to add a search box to easily filter through the available options. I know this can be done using the chosen library, but I prefer to implement it using plain JavaScript or jQuery. Does anyone have suggestions on ...

Express server encounters a 404 error while processing a POST request

Recently, I encountered an issue while trying to post data to my express server using a function that is triggered by clicking a button. Here's the code snippet of the function: const fetchData = async () => { const response = await fetch(&apos ...

Webstorm encounters difficulties compiling Sass

While attempting to utilize Sass in the Webstorm IDE, I noticed that it is defaulting to Ruby 1.8 (OS Default) instead of my preferred RVM Ruby Version (1.9.x). To address this issue, I tried setting the path for Sass in the Watcher-Configuration: PATH=$ ...

What is the best way to tally a score after analyzing two spans in Javascript?

I have 3 spans where 2 contain an alphabet each. The third span is left blank for the result of comparing the first 2 spans. I need to display the result in the last span, showing a value of 1 if the two spans contain the same alphabet. Can anyone sugges ...

Switching the class or modifying the style of an element when it is clicked in Vue.js

The process of retrieving data can be quite intricate. I have an array called "tweets" where the data is stored, and each tweet is represented as a card. I am able to successfully change the style of a card when it's clicked using the markTweet functi ...

Collaborate and pass around SQL connections among different modules

One of my recently developed modules consists of three main functions: Establishing a SQL connection Executing a query Closing the connection This module is called in script.js along with other custom modules responsible for various operations that requi ...

What could be the reason my black overlay doesn't show up when the button is clicked?

Attempting to craft a pop-up window on my own, I encountered an issue. Upon pressing the button, instead of the anticipated pop-up appearing and darkening the background below it, the entire page freezes with no sign of the pop-up box. If I eliminate the ...

A guide on eliminating null or empty values within a React table's map

Is there a way to determine if the value of {row.storeId} is null or empty? If it is, I would like to display NA within the <TableCell>. {props.tableData.map(row => ( <TableRow key={row.storeId}> <TableCell>{row ...

What is the best way to iterate over my JSON data using JavaScript in order to dynamically generate cards on my HTML page?

var data = [ { "name":"john", "description":"im 22", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c7d7e7f0c2b212d2520622f">[email protected]</a>" }, { "name":"jessie", ...

What is the best way to handle constants in TypeScript?

I am facing an issue with a React component I have created: const myComponent = ({constant}: Iprops) => ( <div> {CONSTANTS[constant].property ? <showThis /> : null </div> ) The error message says 'element implicitly has ...

Can you please explain how to implement pagination using vue.js?

I have an HTML and JavaScript code that requests games (game1, 2, 3, 4, 5, 6) from a MongoDB database which contains a lot of games. I am interested in finding out how to implement pagination using Vue.js so that each page displays 4 games. const SEARCH = ...

EBUSY: Unable to access resource due to being busy or locked, unable to retrieve information from 'C:hiberfil.sys'

I am running into an issue while attempting to publish an npm package. The error message I keep receiving is causing me some trouble. Does anyone have any suggestions on how I can resolve this? Your help would be greatly appreciated! Thank you in advance ...

Get the large data file in sections

I ran a test script that looks like this: async function testDownload() { try{ var urls = ['https://localhost:54373/analyzer/test1','https://localhost:54373/analyzer/test2'] var fullFile = new Blob(); for (le ...