Creating PDFs with White Space Using Angular

When trying to generate a PDF format with multiple pages based on an ngFor loop in the HTML, I encountered an issue. After clicking a button that redirects to a route for printing the view into a PDF using a library, a blank space appears before the container I specified for printing.

https://i.sstatic.net/fpj67.png

Below is my Angular code snippet showing how I redirect to the route:

print(){
this.router.navigate(['control/pdf']);

And here is my PDF component:

export class PdfComponent implements OnInit, AfterViewInit {
  options;
  element;
  html: html2pdf;
  constructor(private router: Router) {
  }

  ngOnInit(): void {
     this.options = {
          margin: 0,
          filename: 'myfile.pdf',
          image: { type: 'jpg', quality: 0.98 },
          html2canvas: { scale: 3 },
          jsPDF: { format: 'A4' },
        };
        this.element = document.getElementById('element-to-print');
        this.html = html2pdf().set(this.options).from(this.element);
  }

  ngAfterViewInit(): void {
    setTimeout(() => {
      Swal.fire({
        title: 'Wait',
        html: 'The file is being generated',
        timer: 2000,
        onBeforeOpen: () => {
          Swal.showLoading()
        }
      }).then(
        ()=>{
          this.html.save();
          Swal.fire({
            title: "Success!",
            html: "The file has been downloaded successfully",
            icon: 'success',
          });
          this.router.navigate(['control'])});
    }, 4000);
  }
}

To address the spacing issue, I have added a setTimeout function to allow time for the view to load properly before generating and downloading the PDF file.

Answer №1

Consider implementing the y and scrollY parameters in the html2canvas setup for better results.

For instance:

 this.settings = {
      margin: 0,
      filename: 'output.pdf',
      image: { type: 'jpg', quality: 0.98 },
      html2canvas: { scale: 3, y: 0, scrollY: 0},
      jsPDF: { format: 'A4' },
    };

If the above approach doesn't yield desired outcomes, experiment with including removeContainer within the same html2canvas options as a troubleshooting measure.

Answer №2

If you suspect a race condition, one way to address it is by utilizing change detection to refresh the template:

constructor(private cdr: ChangeDetectorRef)....

 /// ...after data loaded
this.cdr.detectChanges();

Additionally, you may consider defining a boolean variable in your class and encapsulating the entire .html file within an

<ng-container *ngIf="myBoolean">...pdfStuff...</ng-container>

Subsequently, once the data is retrieved, you can set myBoolean = true;, ensuring that the page only loads after this point.

Hopefully, these solutions will help resolve the issue!

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

Issue with automatically importing Meteor packages as external libraries for .ts files

Trying to transition a Node project primarily written in TypeScript to Meteor 1.4 and encountering some difficulties. I have noticed that WebStorm is supposed to automatically import meteor when the option is selected, as explained on https://www.jetbrain ...

Resize event of an Angular2 application within an iframe has been triggered

My current project involves embedding an Angular2 application within a Liferay portlet using iframes. The Liferay tomcat server is hosted on a different domain than the Angular2 application, and I am facing challenges with dynamically resizing the iframe b ...

Tips for applying unique scss classes to a div based on a specific condition

Currently, I am developing a chat application where I want to showcase messages from one specific user on the right side of the screen while displaying messages from other users on the left side. <ion-item *ngFor="let message of messages | slice:0: ...

ElasticSearch - delayed indexing update underway

Utilizing the elasticsearch module in typescript, I've encountered an issue where changes made to indexes or newly inserted documents are not being detected by the code... Below is an example: try { await this._client.indices.de ...

The Select element in angular fails to choose the intended option when tested with Cypress

I am encountering a challenge in my automation testing project where I need to select an option from a select element. The project is built using Angular and I am using Cypress for automation testing. As a newcomer to Cypress, I followed the instructions ...

When incorporating Dragular into an Angular 2 application, an error may occur if the document object

Being new to Angular2, I encountered challenges while trying to integrate Dragula into my application. Upon running the app, an error occurred before loading the home page: Error: Node module call failed with message: Prerendering failed due to ReferenceE ...

Tips for handling missing environment variables during the build process in a Node.js project

My current setup involves using a .env file to store variables for my TypeScript Node project. I am able to check for missing environment variables during runtime and throw an error if any are not present. export const SOME_KEY = process.env.SOME_KEY || &q ...

Adding an image to text in DiscordJs: a step-by-step guide

I need my Discord bot to send a welcome message in the following format: Some text1 <img1> Some text2 <img2> Some text3 Currently, I am using this code (but it places all images at the end of the message): const user = await client.users.fetc ...

RxJs operators prevent the need for multiple subscriptions through the use of looping mechanisms

Currently working on developing a navigation component for an Angular application. The code snippet below shows my current progress. I am looking to avoid the common issue of having multiple subscriptions within each other, known as the multiple subscripti ...

Display the column every time the user types something into the search bar

Currently working on an Angular project and I'm trying to figure out how to make the middle column visible whenever the user enters text in the search bar. At the moment, I have a search bar for user input and three flex columns. The middle column is ...

Issues with endpoints not functioning after importing a NESTJS module

Could someone please explain why the appController is functioning correctly while the itemsController, imported from a module, is not? I have been learning NestJS and followed the documentation as instructed. The appController is working fine with its unc ...

Switch the orientation of the content flow in bootstrap columns from horizontal to vertical

I am currently working on a file explorer project and I have run into an issue with the layout. My goal is to create a layout similar to Windows file explorer, where files are displayed vertically. However, my current code is arranging them horizontally li ...

Why is the AngularJS 2 child @Component not being replaced in this scenario?

UPDATE: It seems that the issue lies in how I am structuring and serving the project rather than a coding problem. If I find a solution, I'll be sure to update this post. Thank you for your assistance. I'm currently developing an AngularJS 2 ap ...

The app.module encounters issues with selectors specified in its child module, feature.module, in Angular 5

When working with Angular, my app.component.html is kept simple: <app-child></app-child> The setup in App.module looks like this: import { ChildModule } from './child/child.module'; import { NgModule, Browser } from '@angular/ ...

Using Observables in Angular 2 to send polling requests

I have the following AngularJS 2 code snippet for polling using GET requests: makeHtpGetRequest(){ let url ="http://bento/supervisor/info"; return Observable.interval(2000) .map(res => res.json()) //Error here ...

Webpack and React.js: Additional loaders might be required to manage the output generated by these loaders

An error occurred while parsing the module in ./productFlow/index.tsx at line 3, column 12. The file was processed with the following loaders: * ./node_modules/awesome-typescript-loader/dist/entry.js. It seems like an additional loader may be needed to h ...

The positioning of CSS arrows using the "top" attribute is not relative to the top of the page when using absolute values

I am currently working on positioning the arrow in the screenshot using TypeScript calculations. However, I am facing an issue where the position is being determined based on the top of the black popup instead of the top of the screen. From the top of the ...

Eliminate item from nested array when the array is devoid of elements in Typescript

If the nested array is empty and I want to remove the object, how can I achieve this? For example, consider the following array: pokemonGroups = [ { name: 'Grass', pokemon: [ 'bulbasaur-0', 'Bulbasaur' ...

Angular 9 Singleton Service Issue: Not Functioning as Expected

I have implemented a singleton service to manage shared data in my Angular application. The code for the service can be seen below: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataS ...

Issue: The keyword in React/React-Native is returning a boolean value instead of the expected element object

I've recently delved into learning and coding with React, and I'm encountering a bug that I need help fixing. The issue lies within my application screen where I have two checkboxes that should function like radio buttons. This means that when on ...