Transform HTML content into a PDF document with page breaks

Currently, I am developing a function that involves an HTML template.

The purpose of this function is to generate a dynamic template and convert it into a PDF.

So far, I have been able to achieve this using the following code:

var output = '';
async.each(input.contentInfo, function(component, next) {
    renderTemplate(component, function(err, result){ //compile input and template together
        output = output + result; //merge all component's HTML source code together
        next();
    });
}, function(err) {
    conversion({        //phantom-html-to-pdf function from npm module
        html: output,
        paperSize: {
            format: 'A8', 
            orientation: 'landscape',
            margin: 0,
            headerHeight: 0,
            footerHeight: 0
        }
    }, function(err, pdf) {
        var outputFile = fs.createWriteStream('output.pdf');
        pdf.stream.pipe(outputFile);
    });
});

Without error handling in this example, let's assume everything functions correctly here.

After running this function, the output variable contains content similar to this:

<div style="page-break-before: always;">
    <div style="position:absolute;left:100;top:100;>
        Page 1 Content
    </div>
</div>
<div style="page-break-before: always;">
    <div style="position:absolute;left:100;top:100;>
        Page 2 Content
    </div>
</div>

When converting this HTML to PDF, I expected it to result in a 2-page document due to the page-break CSS property. However, with the position: absolute CSS included, it does not generate multiple pages as intended. Removing the position: absolute CSS fixes the page creation issue but affects the UI layout negatively.

Is there a solution to meet both requirements in this scenario?

Any assistance on this matter would be greatly appreciated. Thank you for your help and apologies if my explanation was unclear.

Answer №1

Upon navigating the npm module documentation, I was led to this specific page. One interesting section on "Page Breaks" caught my attention:

Within CSS, there are styles such as page-break-before which can be utilized to designate HTML page breaks. This feature can also be applied with phantom-pdf in order to indicate page breaks within PDF files.

    <h1>Greetings from Page 1</h1>

    <div style='page-break-before: always;'></div>

    <h1>Greetings from Page 2</h1>

    <div style="page-break-before: always;"></div>

    <h1>Greetings from Page 3</h1>

In brief: consider experimenting with page-break-before: always;.

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

Expand Navigation Bar upon Hover

My goal is to recreate a Navigation Bar similar to the one found on this website: I want the Navigation Block to expand and show Menu Items when hovered over, just like the example on the website mentioned above. I've attempted to use Bootstrap and ...

Having trouble with the clip-path in d3.js liquid fill gauge

Attempting to integrate the d3.js liquid fill gauge into my angular2 webapp has been a challenge. The clippath functionality seems to be malfunctioning, resulting in no wave being generated at all. https://i.stack.imgur.com/3Bmga.png instead of https://i. ...

Checking CORS permissions with a pre-flight OPTIONS request

During development, I implement a middleware called cors using the following syntax: app.use(cors({origin: 'http://localhost:8100'})); However, I have noticed that for every route request, two requests are being made as shown in the image below ...

Looking to retrieve just your Twitter follower count using JavaScript and the Twitter API V1.1?

I am trying to retrieve my Twitter follower count using JavaScript/jQuery in the script.js file and then passing that value to the index.html file for display on a local HTML web page. I will not be hosting these files online. I have spent weeks searching ...

NestJS: Specify the data type for @Body()

Consider the code snippet below: @Post() public async createPet(@Body() petDetails: PostPetDto): Promise<any> { } In this scenario, the type of @Bod() petDetails defaults to plain/any instead of the declared type of PostPetDto. What is the recommen ...

Display the div only after all images have finished loading in response to the AJAX call

Prior to diving into this, I am determined to steer clear of utilizing Jquery for personal reasons that I won't delve into. So please refrain from suggesting it, as that is not the solution I seek. I am currently working on a web page that sends mult ...

I am experiencing difficulties in installing JavaScript libraries

PS D:\React> npm i -g expo-cli npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d48555d42004e41446d68c7b6d717268805a6369786964 ...

What is the best way to create a Laravel object for use in JavaScript in a Laravel Blade?

please add description hereI am looking to obtain an object with this particular style var zoz2= { "11-30--0001": "<a href=\"https:\/\/www.dooz.ps\/p\/107229\" >\u0625\u0637\u0644\u0627& ...

Submitting a form with AJAX and additional fields can be accomplished by including the extra fields in

Imagine a scenario where I am working with a basic form like the one below <%= form_for(@category) do |f| %> <% if @category.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@category.errors.count, "erro ...

Use jQuery Ajax to fetch an image and display it on the webpage

Currently, I am working on an application that is designed to browse through a large collection of images. The initial phase of the project involved sorting, filtering, and loading the correct images, as well as separating them into different pages for imp ...

Only output to the console if the data returned from an AJAX request has been

Here is a script that I created: <script type="text/javascript> $('.storage').html(""); setInterval(function(){ $.get('./playcommand.php', function(data) { if($('.storage').html() !== data){ ...

Switching between languages dynamically with Angular JS using $translateProvider and JSON files

I currently have a collection consisting of 6 different JSON files. en.json es.json fr.json it.json ja.json zh.json An illustration of the data present in each file is as follows (in this instance, considering en.json): { "SomeText": "Test in Englis ...

Create a mechanism for implementing a "connection retry" feature upon initialization, even in cases where Redis is currently inaccessible

node-redis offers excellent features for managing Redis disconnections once the system is operational. If the Redis server becomes unavailable, using an appropriate retry_strategy allows the client to continuously attempt to reconnect until Redis is access ...

Having Trouble Styling Radio Buttons with CSS

Hello, I'm facing an issue with hiding the radio button and replacing it with an image. I was successful in doing this for one set of radio buttons, but the second set in another row is not working properly. Additionally, when a radio button from the ...

npm encountered an error stating that in the start command, the path must be specified as a string for

Trying to understand why my start npm script on my Mac is showing this error: path.js:8 throw new TypeError('Path must be a string. Received ' + ^ TypeError: Path must be a string. Received undefined at assertPath (path.js:8:11) ...

Using jQuery to dynamically swap out <tr> tags and all the elements inside of them

In order to enhance user experience, I am looking to automatically fill in certain form elements within a table when a link is clicked. The intention is for the fields to populate with predefined values and then convert into HTML paragraph elements, preven ...

Encountering the "Can't set headers after they're sent" error while integrating Socket.io with EJS

Currently, I am working on developing an app using Node.js, Express, and Socket.io on IBM Bluemix. For the view engine, I have chosen EJS. The following snippet shows the key part of my code - const express = require('express'); const app = exp ...

Achieving Comprehensive Test Coverage for NodeJS Functional Automation

Can anyone recommend a tool that can assist me in evaluating the functional automation coverage specifically for Node.js (not unit tests)? I currently have numerous Selenium automations set up for my frontend Node.js application. However, I am interested ...

Steps to implement the selection of multiple items from a drop-down or list on a React.js website

Hi there, I am a newcomer to the world of React JS web development. I am looking for guidance on how to implement a feature where users can select multiple cities from a drop-down or list, similar to the examples shown in image1. Once the user has made th ...

Using JavaScript to dynamically alter the background image of an HTML document from a selection of filenames

Just starting out with JavaScript and working on a simple project. My goal is to have the background image of an HTML document change to a random picture from a directory named 'Background' every time the page is opened. function main() { // ...