Creating beautifully formatted PDFs using pdfmake in AngularJS

I have a HTML popup displaying data retrieved from the server, and I am attempting to download this data as a PDF using the pdfmake plugin. While I am able to generate the PDF file, the challenge lies in replicating the HTML page layout in the PDF. Here is a sample data from the HTML popup: https://i.sstatic.net/6CCBZ.jpg

Below is my JavaScript code:

$scope.download_pdf = function(questions,temptitle,extid,info){
        // Code logic here
    }

I am seeking to create a PDF file that mimics the design of the image provided. Any guidance on how to accomplish this would be greatly appreciated.

Thank you, Sankar.

Answer №1

Are you looking to capture a screenshot of a popup and convert it into a PDF format? Here is a sample code that has worked well for me:

1) Begin by importing the following scripts:

<!--html2canvas-->
<script type="text/javascript" src="~/Scripts/html2canvas.js"></script>

<!--PdfMAKER-->
<script type="text/javascript" src="~/Scripts/pdfmake.min.js"></script>
<script src="//kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>

2) Modify your HTML code to include the following structure:

<div id="exportthis">
       <!--INSERT YOUR POPUP'S HTML CODE HERE-->
    </div>

3) Update your JavaScript code with the following function:

function imprimir() {
    html2canvas(document.getElementById('exportthis'), {
        onrendered: function (canvas) {
            var data = canvas.toDataURL();
            var docDefinition = {
                content: [{
                    image: data,
                    width: 500,
                }]
            };
            pdfMake.createPdf(docDefinition).download("Titulo.pdf");
        }
    });
}

DESCRIPTION:

This code captures the content and style of the specified element, and then a button triggers the print() function to generate the PDF file.

Give it a try and let me know if it meets your requirements. If not, I can review the example to see if anything was missed.

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

Encountering an error when trying to access a property of an undefined MVC model in a

Embarked on a journey to learn web service development, only to encounter a roadblock. I'm struggling to figure out how to utilize ExpressJS Router() to pass POST data to the controller files. Upon inspecting the request redirected from product.route. ...

Is it possible to determine if the clipboard is accessible in Firefox?

In my upcoming JavaScript project, I am looking to determine the accessibility of the clipboard. Particularly in Firefox where specific permissions need to be granted for each site in order to use certain functions like execCommand with cut, copy or past ...

Instructions on how to modify a document's content by its unique identifier using Firebase Modular SDK (V9)

I am trying to figure out how to update an existing document for the same user ID in V9 Firebase whenever they log in, rather than creating a new one each time. Any suggestions on how to achieve this? Current Code setDoc( query(collectionRef), // ...

An error occurred while attempting to run the npm installation command

When trying to run the npm install command, I keep encountering this error: npm ERR! code 1 npm ERR! path /Users/alex/Documents/serviceName/node_modules/platform-tracer/node_modules/ls-trace npm ERR! command failed npm ERR! command sh -c node scripts/post_ ...

Tips for utilizing a switch statement

I'm a beginner in JavaScript and recently learned about the switch statement. I have an exercise where I need to convert numbers 1-10 into words like "one", "two", "three"... This is what I have tried so far: function sayNum(){ let numberArray = [ ...

Mirror the content of my div code onto a two-dimensional plane using an A-frame

Query I am currently developing a 3D scene using A-Frame () and I am in need of a solution to mirror an HTML div onto a plane within the A-Frame environment. For instance, imagine a scenario where there is a div at the bottom left corner of the screen fun ...

What is the significance of default parameters in a JavaScript IIFE within a TypeScript module?

If I were to create a basic TypeScript module called test, it would appear as follows: module test { export class MyTest { name = "hello"; } } The resulting JavaScript generates an IIFE structured like this: var test; (function (test) { ...

How can we sort an array based on the inner HTML values of its children elements in JavaScript?

Can you arrange a JavaScript array based on the innerText values of its HTML elements? I am generating a div element (class="inbox" id="inbox${var}") with a number as its innerText, then adding all these divs to an array (numArr). I wan ...

Error in Laravel 5.5 PusherBroadcaster.php at line 106

I am facing a frustrating issue with the BroadcastException in PusherBroadcaster.php (line 106) error while using Laravel 5.5 and Vue 2.0. Despite trying various solutions, I have been unable to resolve it. Desperately seeking assistance. Here's what ...

Utilizing Highcharts/Highstock for handling large volumes of data efficiently

Dealing with a growing amount of data daily (currently over 200k MySQL rows in one week), the chart loading speed has become quite slow. It seems like using async loading is the solution (http://www.highcharts.com/stock/demo/lazy-loading). I attempted to i ...

Discover every user receiving a database object instead of individual records with mLab

While using my express application with the mLab database, I encountered an issue. When trying to find only one record, everything works fine. However, when attempting to retrieve a list of users from the database, I receive the following response. Query ...

How can I delete a date value from a td if it matches the current date value?

I'm facing an issue with duplicate date values in my table rows and trying to find a solution using JavaScript or JQuery. The problem cannot be fixed within the SQL query itself, so I need to explore alternative approaches. I want to remove repeated d ...

Focus Google Map on Selected Option using AngularJS

I'm attempting to center the map based on a selection in a drop-down select option box. Despite trying various examples, I haven't been successful in getting the map to recenter to the new latitude and longitude coordinates. I'd like to ach ...

Learning to implement $first in an Angular ng-repeat to dynamically add a new table row

I am currently facing an issue with displaying a Google map for addresses in my Angular application. The problem seems to be related to the asynchronous nature of HTML and JS, but I am struggling to find a solution. The issue is that even though the map vi ...

Dealing with VueJS - Sharing an array of data from a child to a parent component using v-model

I am facing an issue in emitting data (array) from a child component to a parent component using v-model. However, when the parent component is created, my console.log does not work. I am hesitant to work with Vuex as I am still a beginner. Here is my chi ...

What is the functionality of the protection against AngularJS JSON vulnerability?

When working with JSONs in Angular, it is recommended to prefix them with )]}'\n for added protection against potential JSON vulnerability: A JSON vulnerability could allow a third-party website to transform your JSON resource URL into a JSONP ...

Deleting a specific row within a Material UI DataGrid in Reactjs: Tips and tricks

As I embark on this React project, things are progressing smoothly. However, a challenge has arisen. The functionality I aim for is as follows: When the checkbox in a row is clicked, I want that particular row to be deleted. For instance, selecting checkb ...

Trouble arises when jquery's "position().top" clashes with the CSS3 property "transform: scale()"

Currently, I am working on adding a font resizer feature to my editing tool. To implement this, I made some changes to the text elements where their origin is now set to the bottom left corner. The normal version of the tool works perfectly fine, but when ...

Managing absence of ID field in Prisma and retrieving data from API request

When fetching data from an API, my approach looks like this: async function getApiData() { const promises = []; for (let i = 0; i < PAGE_COUNT; i++) { const apiData = fetch(...); } const apiData = await Promise.all(promises); return apiDat ...

What is the best way to retrieve error messages from a transaction with ethers.js?

Incorporating a custom error in my Solidity contract: error Documents__AlreadyExist(string hash); The modifier I utilize is as follows: modifier alreadyExist(string memory hash) { if (s_documentsHashes[hash]) { revert Documents__AlreadyExi ...