Generate a series of printed pages corresponding to various scroll positions using JavaScript

I have created an HTML page through a program that generates evidence. Exporting this evidence to a PDF format would be beneficial in many situations.

This HTML document is divided into two columns, and I need to print multiple pages to PDF where each page displays the aligned content from both columns.

Instead of printing to a physical printer, I prefer utilizing the browser's capability to print directly to PDF. Although I attempted to use jsPDF, it does not handle <pre> tags effectively, which are crucial in my text.

The structure of the document consists of two <div>s placed next to each other with a scrollbar.

I have successfully written the code that aligns the columns as required and added a button to initiate the printing process using window.print(). The script looks something like this:

function align(loc) {
  $('#1').scrollTop($("#mark0"+loc).offset().top);
  $('#2').scrollTop($("#mark1"+loc).offset().top);
}

function print() {
  window.print();
}

// All locations are known in advance
function printAll() {
  for (i=1; i<=3; i++) {
    align(i);
    print();
  }
}
<div id=0 style='left:0; overflow:scroll; height:100%; width:50%'>
    A lot of text...
    <span id='mark01' />
    A lot of text...
    <span id='mark02' />
    A lot of text...
    <span id='mark03' />
    A lot of text...
</div>

<div id=1 style='right:0; overflow:scroll; height:100%; width:50%'>
    <pre>
        Some text.
        <b>
            A lot of text...
            <span id='mark11' />
            Some text.
        </b>
        Some text.
        <b>
            A lot of text...
        </b>
        <span id='mark12' />
        A lot of text...
        <span id='mark13' />
        <b>
            A lot of text...
        </b>
    </pre>
</div>

Currently, I have to manually align the columns, print to PDF, realign to a different position, print again, and repeat the process.

Is there a way to automate this process? I aim to develop a JavaScript script that will execute align(), followed by print() multiple times to generate a single PDF file.

Unfortunately, the example provided in printAll() does not produce the desired outcome.

Answer №1

If I were to tackle this task using JavaScript, my approach would involve creating a new section specifically designed for printing and then transferring the content into it.

The desired outcome is to generate a structured DOM layout similar to the following:

<div id="printarea">
    <div class="page">
        <div class="col"> col1 content1 </div>
        <div class="col"> col2 content1 </div>
    </div>
    <div class="page">
        <div class="col"> col1 content2 </div>
        <div class="col"> col2 content2 </div>
    </div>
    ....
</div>

While the initial step may be relatively straightforward, it becomes apparent that the original DOM structure may not be well-suited for the subsequent phase. It is likely necessary to manipulate the raw source in order to achieve the desired outcome.

An approach could involve:

// retrieve source
var col1Source = $('#0').innerHTML;
// use '<span id="marker##" />' as a separator -- VOILA!
var col1Sections = col1Source.split(/<span id='marker\d+'[^>]+>/);
// repeat process for col2

for(var i = 0,
    iMax = Math.max(col1Sections.length, col2Sections.length);
    i < iMax;
    i++
) {
    var newPage = $('<div class="page">');
    newPage.append('<div class="col">' + col1Sections[i] + '</div>');
    newPage.append('<div class="col">' + col2Sections[i] + '</div>');
    $('#printarea').append(newPage);
}

After completing the setup of the print area, you can utilize your developer tools to (1) remove the original #0 and #1 DOM elements, and (2) fine-tune the CSS styling until the printed layout meets your requirements.

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

Transferring dropdown Form data using PHP

I have encountered an issue with a form that I created. The form includes various input fields, one of which is a dropdown menu. When the form is submitted, all the information from the form is sent to a designated email address. However, I have noticed ...

Ways to adjust the color of table-striped for oversized rows (those with multiple lines)

Can the background color of table rows with rowspan= "x" be customized? The table has a large row with multiple small rows inside it using rowspan="x". Is there any way to change the background color for both the large row and small rows within it? View ...

Removing a data entry from a PHP-generated MySQL table

In the process of developing a system, I have encountered a need to display database records in an HTML table. The functionality for creating the HTML table and retrieving data is working as expected. However, I am facing an issue with adding a column cont ...

Sharing the state of a button group across different tabs using Bootstrap 5 and JQuery (or pure JavaScript): A complete guide!

Creating a tabbed web page using Bootstrap 5 nav-tabs for the front end and JQuery for the back end. I aim to have a single radio button group displayed on all tabs, with the state of the group persisting across tab changes. Currently, both tabs display t ...

Utilizing AJAX to send a Zend Form submission

Is there a way to submit a Zend form using an ajax request in jQuery without the page refreshing? I have already tried using ajaxLink with Zend, but I am unsure how to implement it with a form. ...

Initiate the Html.BeginForm process in an asynchronous manner

Within my ASP.NET MVC 3 application, I am attempting to upload a file using the Html.BeginForm helper, as shown below: <% using (Html.BeginForm("ImportFile", "Home", new { someId = Id }, FormMethod.Post, new { enctype="multipart/form-data" } )) %> ...

Tips for binding data to numerous dynamic controls

Implementing reactive forms in my Angular project allowed me to create a simple form for adding employee work hours and breaks. The challenge I encountered was the inability to bind data from break controls. In the .ts file export class AddAppointmentForm ...

What is the process of incorporating a Higher-Order-Component in React?

I've been working on setting up a Higher Order Component (HOC) in React to enable text selection detection for any Input component. However, I seem to be missing a key piece of the puzzle in putting it all together. Initially, I followed an article t ...

Smoothstate triggering a jQuery function to execute only once per browsing session

Whenever I visit my index.html page, a jQuery function runs to grab an article's supporting image and follow the mouse cursor within a defined area. However, after navigating to other pages and returning to index.html, this function fails to run unles ...

Struggling to display a function's output on a separate web page within a flask application

After spending close to 10 hours on this, I find myself stuck. My restaurant search app is functioning perfectly when I print the output to the terminal. However, I can't seem to figure out how to display it on a new page. Here's a snippet of my ...

Retrieve and showcase images in a slideshow format sourced directly from the Server's directory(folder)

In my application, which is built with .NET C#, I have a feature that allows users to upload images. When an image is uploaded, I dynamically create a folder to store it. For example: strFolder = Server.MapPath("./folder/folder_"+folid+"/") This means th ...

Are there limitations on column width and count in CSS3?

While exploring the URL http://www.w3.org/TR/css3-multicol/, I noticed that it only allows you to specify either 'column-width' or 'column-count', and sometimes both using 'columns'. However, it lacks options to set minimum wi ...

How can I effectively display a blank menu item for the SelectField component in Material-UI within a React application?

I am using the select-field component from the material-ui framework version 0.15.4 with React version 15.4.0. I am attempting to add a blank menu-item to the select-field in order to allow for deselecting a value in the dropdown field when clicked. Howeve ...

Issue with Jcrop not functioning properly in IE8

Having trouble with jCrop. It works fine in other browsers but not in IE8. Can't seem to figure out what the issue is. Wondering if it's related to image data or the size preventing the crop. Any assistance would be appreciated! <script typ ...

Axios displays a status code of 0 instead of the expected 403

Trying to monitor the responses of requests using axios response interceptors has been quite a challenge for me. In one specific request that necessitates authorization, everything goes smoothly when the token is valid, and data is returned without any is ...

Display and conceal the information with a hyperlink

I need to create a content DIV that includes a link to expand and collapse it. Within this content DIV, there is an unordered list. Initially, only two list items should be displayed with an expand link. If users want to see additional list items, they mu ...

Ways to enable automatic user logoff upon closing the tab

Currently, I am developing a DotNetNuke website and facing an issue where I need to automatically logout the user when they close the browser or tab. Can someone guide me on how to detect the browser close event and trigger the user logout successfully? ...

Navigating the world of Python HTML Scraping and managing XHR requests

I am struggling to extract the complete HTML content from a journal URL. I have tried various methods mentioned on this platform, but none of them are giving me the desired result with the .text or .json() functions of requests.get. My objective is to re ...

Experiencing Setbacks while Implementing AJAX in a PHP Object Orient

I'm currently attempting to create an object-oriented programming (OOP) login system using Ajax. However, I am encountering issues with starting the session or being redirected to the "Directivo.php" page. When I run the code, there is no output displ ...

Is there a way to convert a PDF file to a Javascript array using a

Is there a way to extract only words from a PDF document using JavaScript? I am not interested in images, digits, or tables - just the words so that I can manipulate them as JavaScript objects. ...