Display content exclusively in PDF format

On my HTML page, I have two sections - one for inputting values and the other for viewing a PDF. To ensure that the PDF view is hidden until explicitly requested, I need it to remain invisible by default. It should only appear as a PDF when someone clicks on the 'Generate PDF' button.

<div class="col-12">
    <input [(ngModel)]="fName" name="fname" placeholder="First Name">
    <input [(ngModel)]="LName" name="lname" placeholder="Last Name">
</div>

<div #PDF>
    <p>My Name is</p> 
    <p>{{fName}} {{lName}}<p>
</div>

<button class-"btn btn-primary" type="submit" (click)="pdfMethod">PDF</button>

TS

import * as jsPDF from 'jspdf'; 
@ViewChild('PDF') PDF: ElementRef;

pdfMethod(){
    var pdf = new jsPDF('p', 'pt', 'letter');
    pdf.addHTML(this.PDF.nativeElement, () => {
        pdf.save(`sum.pdf`);
    });
}

I intend for the input fields to be initially visible, with the #PDF section in PDF format revealed only upon clicking the button. Although I attempted using *ngIf, the error message stating native element not defined appeared.

Answer №1

If you're wondering why the PDF div isn't showing up, it's because Angular needs time to create and populate its content during the change detection cycle. To solve this issue, consider using ChangeDetectorRef to manually trigger the component's change detection before rendering the PDF.

component.html

<div #PDF *ngIf="showPDF">
<p>My Name is</p> 
<p>{{fName}} {{lName}}<p>
</div>

<button class="btn btn-primary" type="submit" (click)="pdfMethod()">PDF</button>

component.ts

import { Component,ViewChild,ElementRef, ChangeDetectorRef } from '@angular/core';

constructor(private cdr: ChangeDetectorRef){}

showPDF = false;
@ViewChild('PDF') PDF: ElementRef;
//@ViewChild('PDF', {static: false) PDF: ElementRef;//for angular 9

pdfMethod()
{
    this.showPDF = true;
    this.cdr.detectChanges();
        var pdf = new jsPDF('p', 'pt', 'letter');
        pdf.addHTML(this.PDF.nativeElement, () => {
          pdf.save(`sum.pdf`);
        });
}

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

Increase the totalAmount by adding the product each time

Can someone help me understand why the totalAmount shows as 20 when I add a product? Also, why doesn't it increase when I try to increment it? Any insights would be appreciated. Thank you. ts.file productList = [ { id: 1, name: 'Louis ...

Modify the paragraph's class upon clicking the radio button

I have been struggling with changing the color of <p> based on the radio button selected using two classes, red and blue. However, for some reason, it's not working as expected. If anyone has any insights or suggestions on how to fix this issue ...

What is the best approach for testing the TypeScript code below?

Testing the following code has been requested, although I am not familiar with it. import AWS from 'aws-sdk'; import db from './db'; async function uploadUserInfo(userID: number) { const user = db.findByPk(userID); if(!user) throw ...

Is it acceptable to use Angular to poll data from Laravel?

I have created a platform where users can stay updated with notifications and messages without the need to constantly refresh the page. Instead of using third-party services like Pusher, I decided to utilize polling to achieve this functionality. Essentia ...

Searching through all values can be done by following these steps

Need help with implementing a search feature that can search all values in Angular2. Here's the current code snippet: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filter' }) export class FilterPipe implem ...

Encountering special symbols in the ID of a form element triggers an error message in jQuery validator, stating 'Unrecognized expression'

One of the challenges I am facing is that I have a form with elements that have ids containing special symbols. For example: The id="$FormData[1]$PersonData[1]$PhysicalPerson[1]$PersonName[1]$Affix[@type='qualification' and @position='prefi ...

Ways to switch the class of the nearest element

When an image within the .process class is clicked, I am using the following code to toggle the class of .process-info to .process--shown. The code successfully toggles the class; however, it affects all elements on the page with the class of .process-inf ...

What could be causing a compile error in my React and TypeScript application?

I recently downloaded an app (which works in the sandbox) from this link: https://codesandbox.io/s/wbkd-react-flow-forked-78hxw4 However, when I try to run it locally using: npm install followed by: npm start I encounter the following error message: T ...

Confused between Javascript and PHP? Here's what you should consider!

Looking for a solution to transfer a string from JavaScript, obtained from the content of a div, to PHP in order to create a text file with this information. What would be the most effective approach to accomplish this task? Edit[1]: Using the Post ...

What's the best method for securely handling user input containing iframes from a WYSIWYG editor?

I have implemented a feature using the TinyMCE WYSIWYG editor that allows users to input rich text content. Users have the ability to paste links to rich media in the editor, which automatically detects and creates an iframe display. This means that pastin ...

How can I preserve the file extension of an ejs file as .html?

I'm in the process of building an expressjs application using the ejs template engine. However, I'd like to retain the file extension as .html instead of using .ejs. The main reason for this is that I am using Visual Studio for my development wor ...

Determine the validity of an image URL using Vue.js

Is there a way to check if an image URL is valid or broken in Vue.js, similar to the process outlined in Angular 2 - Check if image url is valid or broken? ...

The practice of following the UpperCamelCase convention post object transformation

I encountered a situation where I have an object that returned the result from an RxJs subscribe method: result: any { message: null role: Object success: true } To better manage this object in TypeScript, I decided to convert it to a type ca ...

What is a more efficient way to search and substitute text in NodeJS?

I am currently working on a task that involves reading a file, passing its contents and multiple arrays to a function, using regex to see if there are any matches, replacing them, and finally updating the file. The code I have put together may not be the ...

Seeking a solution for inserting input values into a JSON file within a node.js environment

As I was developing my new project, a to-do list web application, Below is the code snippet from 'todo.html' : <html> <head> <title>My TODO List</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery ...

Does vuetify have a v-autocomplete callback for when there is no filtered data available?

Is there a method to detect when the v-autocomplete component in Vuetify.js displays "no data available" after filtering? I have searched the events documentation here https://vuetifyjs.com/en/api/v-autocomplete/#events Is there a workaround for this iss ...

Is it possible to utilize npm packages within a standard web page without any frameworks or libraries?

I am currently working on a basic website created using vanilla HTML, CSS, and JS files. My goal is to incorporate the import { moment } from "moment" syntax into my JS files. However, after adding npm to my project, installing moment with npm i ...

The $http.get request is successful only when the page is initially loaded for the first

Imagine this scenario: a user navigates to http://localhost:3000/all, and sees a list of all users displayed on the page. Everything looks good so far. However, upon refreshing the page, all content disappears and only raw JSON output from the server is sh ...

Ensuring Uniform Data Types Across Objects (Using Typescript)

After much trial and error, I have finally reached this point where everything seems to be working perfectly. function test<types extends Record<string,any>>(dict: dictionary<types>){} type dictionary<types extends Record<string, a ...

Leveraging dependency injection in Angular 2+ with pre-loaded models

I desire the ability to create an instance of a model using a constructor while also providing injected services to that model. To clarify, I envision something like this: var book = new Book({ id: 5 }); // creates instance, sets id = 5 book.makeHttpCa ...