A guide on printing several PDF files at once with print.js in Angular 9

After successfully using the print.js library to print a single PDF, I encountered an issue when attempting to print multiple PDFs. An error message stating "ERROR Multiple Choices" was displayed. I also experimented with plain JS, but it resulted in multiple prompts for each document.

Below is the code snippet we implemented:

printJS({ 
         printable: ['dummy.pdf', 'dummy1.pdf'], 
         type:'pdf'
        });

Please see the attached image for reference: https://i.sstatic.net/ZHwKN.jpg

Any assistance on this matter would be greatly appreciated. Thank you!

Answer №1

After dedicating a full week to the task, I have successfully mastered the art of printing multiple PDF files using print.js in Angular 9. Here are the steps you need to follow to print multiple PDFs:

  1. Begin by installing the npm module: PDF-lib

    npm i pdf-lib

  2. Next, import the npm module into your Angular file and combine multiple PDFs into a single document using the following code (e.g., app.component.ts)

    import { PDFDocument } from 'pdf-lib'
    @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
    })
    
    export class AppComponent {
    title = 'print-multiple-pdfs';
    
    /* Convert the merged pdf array buffer to blob URL for printing or viewing in browser.*/
    downloadFile(data) {
     const blob = new Blob([data], { type: 'application/pdf' });
     const url= window.URL.createObjectURL(blob);
     //window.open(url);
     printJS({
       printable: url,
       type: 'pdf',
     })
    }
    
    async printPDFS() {
     /* Array of PDF URLs */
     let pdfsToMerge = ['https://cors-anywhere.herokuapp.com/https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf', 'https://cors-anywhere.herokuapp.com/http://africau.edu/images/default/sample.pdf', 'https://cors-anywhere.herokuapp.com/https://www.hq.nasa.gov/alsj/a17/A17_FlightPlan.pdf']
    
     const mergedPdf = await PDFDocument.create();
     for (const pdfCopyDoc of pdfsToMerge) {
     const pdfBytes = await fetch(pdfCopyDoc).then(res => res.arrayBuffer())
     //const pdfBytes = fs.readFileSync(pdfCopyDoc);
     const pdf = await PDFDocument.load(pdfBytes);
     const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());
     copiedPages.forEach((page) => {
       mergedPdf.addPage(page);
     });
    }
    const mergedPdfFile = await mergedPdf.save();
    this.downloadFile(mergedPdfFile);
     }
    }
    
  3. Lastly, call the function to print the PDFs (app.component.html)

    <button (click)="printPDFS()">Print PDFs</button>

For more information, visit: pdf-lib

Answer №2

If you find yourself needing to print multiple files with print.js, consider merging them into a single file first for a smoother user experience. This way, you only need to deal with one print preview.

Alternatively, you can utilize the onPrintDialogClose Event as a workaround:

printJS({
    printable: 'page01.pdf',
    type: 'pdf',
    onPrintDialogClose: function() {
        printJS('page02.pdf');
    }
})

Answer №3

As stated in the documentation

printable - Document source can be a pdf or image url, html element id, or json data object.

The implication is that only one printable can be processed at a time.

To handle this limitation, I recommend iterating through the basics of its usage by calling printJS() and passing in a PDF document URL:

var pdfs_list = ['dummy.pdf', 'dummy1.pdf'];
for (var i = 0; i < pdfs_list.length; i++) {
    printJS(pdfs_list[i]);
}

Alternatively, you could concatenate the files on the server-side as suggested by pbachman.

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

Implementing a dynamic like functionality using Ajax in Django

I've created a new structure for the like button, but it's not functioning correctly. Here are the files I'm working with: models.py class Comment(models.Model): title = models.CharField(max_length=50) author = models.ForeignKey(Pr ...

Customize your dropdown menu options with JQuery: A step-by-step guide

I am dealing with a situation where I have a dropdown menu labeled as Code. The options available in this dropdown are fetched from a database, populating the dropdown accordingly. Alongside the Code dropdown, there is a textbox named Name. Under certain c ...

When attempting to utilize POST commands in a React application, encountering the error "Cannot GET /"

I am encountering an issue with my react app - when I run node index.js, I receive a "Cannot GET /" error directly on my browser (even though I want to run it directly), despite requesting a POST command. Previously, the GET request was working fine. Curr ...

Retrieving JSON data in array by making an AngularJS resource call

Developed a factory that returns JSON data and calling it from the controller, but the data is returning empty. I'm not sure where I went wrong. There are no console errors and in the network tab, the JSON data is also loading. 'use strict&apos ...

Error code 405: The POST method is not compatible with submitting multiple forms using JavaScript code simultaneously

Having multiple forms on a single page that are all submitted using the same JavaScript code presents some challenges. <form class="form" id="cancelchallenge1" method="POST" action="{{action('ChallengeController@cancelChallenge')}}"> <i ...

The integration of Vue JS is not displaying properly in an Electron application

My electron app is loading Vue JS 2 from my local machine, but when I attach my el to an element, it completely empties the element and replaces its contents with a Vue JS comment. What could be causing this issue? index.html <!DOCTYPE html> <htm ...

How can I prevent an element from gaining focus after opening a NgbModal?

In the template, I am using a ngForm which is passed as an argument to open a NgbModal: <form #optionsForm="ngForm" noValidate (ngSubmit)="saveOptions()" id="optionsForm"> <div class="modal-body"> <div class="form-group"> < ...

Angularfire/Firebase utilizes the Authorization Code Grant flow for OAuth

I am trying to understand the authentication flow used by applications that depend on Firebase for single sign-on authentication. While I know that most SPA and client applications use the "implicit flow" due to everything happening in the browser without ...

Is there a way to speed up the processing time of parsing a 34Mb file using JSON.parse, which currently takes

Our app is currently in the development stage with a database containing approximately 4000 recipes. To save space, we have chosen to store the recipes in one locale during initial download. However, users have the option to switch locales within the app&a ...

Compilation failure due to Typescript initialization issue

Encountering a TypeScript error in my IntelliJ-Idea 2017.1.1 IDE I have enabled JavaScript, NodeJS, and TypeScript Compiler. I have exhausted all solutions but the issue persists, perhaps I am missing something. Error: Initialization error (typescript ...

What would be the most effective approach for creating a reactive setter for an object within an array in Vuex?

I am working with a Vuex object that contains an array of languages consisting of objects with guid, name, and level properties. I am trying to figure out how to write a method that will make it reactive. Currently, I have an input field with a value of " ...

Combining CSS and JS files for accordion list - experiencing issues when used separately

Recently, I've been trying to create an accordion list and stumbled upon some code (HTML, CSS, and JS) on www.w3schools.com. When I have the code all in one document and run it as a single .html file, everything works perfectly. However, when I split ...

Using Selenium to locate an element by CSS and submitting a form

I am new to using selenium and I have a few questions about my first script. driver.findElement({ css: '.input[name=login]' }).sendKeys('login'); //driver.sleep(0); driver.findElement({ css: '.input.passwd' }).sendKeys(' ...

What is the best way to convert similar JavaScript functions into a reusable function?

Looking to streamline my code by consolidating these 18 functions into one. I've attempted various approaches, but have been unsuccessful due to the nested loops involved. Below are examples of two out of the 18 functions to highlight the variations. ...

what is the best way to switch classes between 2 buttons using Angular8

Is there a way to create a toggle button effect that adds an 'active' class to BTN1 when it's clicked, and then removes the 'active' class from BTN1 and add it to BTN2 when BTN2 is clicked? Currently, my code only allows for addin ...

Having trouble with an unexpected value in your Angular2 Service? Don't forget to add

I encountered an error in my Angular2 app: Error: (SystemJS) Unexpected value 'ReleasesService' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation. Here is my AppModule code: import { NgModule } fr ...

Angular Group Formation Issue

I keep encountering the following error: formGroup expects a FormGroup instance. Please pass one in. This is how it looks in HTML: <mat-step [stepControl]="firstFormGroup"> <form [formGroup]="firstFormGroup"> And in my Typ ...

A guide on efficiently mapping all items from an object containing an unspecified number of items or item names within a reusable component

I am currently exploring the concept of building reusable components. In a personal project, I am in the process of mapping items retrieved from a database. My goal is to create a component that can dynamically map any number of unspecified types as table ...

Choosing the ID and class name through jQuery among numerous classes

I am looking to create a Modal Pop Up Box using CSS and JS, but I need help getting the id (mymodal , mybtn) and the Class (close) from the span Element in JavaScript. Please refer to the attached link for an explanation of the code. div class="head ...

Why would npm be unable to locate a file, potentially leading to an error? Could the lack of contents in my node_modules subfolder be the root cause of this issue?

I'm encountering an issue while attempting to execute npm install in the angular project directory obtained from ASP.NET Boilerplate. The error I'm facing is related to npm's inability to locate a specific file. D:\Dev\AspNetBoiler ...