Adding a PDF generated from an HTML div to an email using Java

I am looking for a solution to convert the contents of an HTML div tag into a PDF file while preserving its associated CSS. This is essential as I will be using Java on the back-end to send emails, and I need to attach the PDF with the CSS intact when sending the email.

If anyone has any advice or guidance on how I can achieve this, I would greatly appreciate it.

Answer №1

> This code sample serves as a helpful starting point to get an idea.     <?php
>     /*
>     mPDF: Creating PDFs from HTML/CSS (Full Code)
>     */
>     require_once( 'mpdf/mpdf.php'); // Including mdpf
>     $stylesheet = file_get_contents('assets/css/pdf.css'); // Retrieving css content
>     $html = '<div id="pdf-content">
>                   Insert your PDF Content here (Text/HTML)
>              </div>';
>     // Setting up the PDF
>     $mpdf = new mPDF('utf-8', 'A4-L'); // Creating new PDF object with encoding & page size
>     $mpdf->setAutoTopMargin = 'stretch'; // Setting pdf top margin to stretch to prevent content overlap
>     $mpdf->setAutoBottomMargin = 'stretch'; // Setting pdf bottom margin to stretch to prevent content overlap
>     // Adding PDF header content
>     $mpdf->SetHTMLHeader('<div class="pdf-header">
>                               <img class="left" src="assets/img/pdf_header.png"/>                      
>                           </div>'); 
>     // Adding PDF footer content                      
>     $mpdf->SetHTMLFooter('<div class="pdf-footer">
>                             <a href="http://www.lubus.in">www.lubus.in</a>
>                           </div>'); 
>      
>     $mpdf->WriteHTML($stylesheet,1); // Writing style to pdf
>     $mpdf->WriteHTML($html); // Writing html to pdf
>     // FOR EMAILING
>     $content = $mpdf->Output('', 'S'); // Saving pdf for email attachment 
>     $content = chunk_split(base64_encode($content));
>     // Email configuration
>     $mailto = $email;
>     $from_name = 'LUBUS PDF Test';
>     $from_mail = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d18101c14113d1912101c14...';
>     $replyto = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3d6ded2dadff3d7dcded2da...';
>     $uid = md5(uniqid(time())); 
>     $subject = 'mdpf email with PDF';
>     $message = 'Download the attached pdf';
>     $filename = 'lubus_mpdf_demo.pdf';
>     $header = "From: ".$from_name." <".$from_mail.">\r\n";
>     $header .= "Reply-To: ".$replyto."\r\n";
>     $header .= "MIME-Version: 1.0\r\n";
>     $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
>     $header .= "This is a multi-part message in MIME format.\r\n";
>     $header .= "--".$uid."\r\n";
>     $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
>     $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
>     $header .= $message."\r\n\r\n";
>     $header .= "--".$uid."\r\n";
>     $header .= "Content-Type: application/pdf; name=\"".$filename."\"\r\n";
>     $header .= "Content-Transfer-Encoding: base64\r\n";
>     $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
>     $header .= $content."\r\n\r\n";
>     $header .= "--".$uid."--";
>     $is_sent = @mail($mailto, $subject, "", $header);
>     //$mpdf->Output(); // For sending Output to browser
>     $mpdf->Output('lubus_mdpf_demo.pdf','D'); // For Download
>     exit;
>     ?>

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

Leverage IBM Worklight to initiate iOS native code execution upon plugin creation

Currently, I am working on integrating iOS Native code into my Worklight application. I have successfully developed a Cordova plug-in with the following code: HelloWorldPlugin.h #import <Foundation/Foundation.h> #import <Cordova/CDV.h; @interf ...

Issue Alert: Inconsistencies with Google Scripts spreadsheets

Objective I have been working on a script that will make consecutive calls to an API (with a JSON response) and input the data into a Spreadsheet. Issue: When I debug the script, everything runs smoothly without any major problems. However, when I try r ...

Adjust the appearance of self and other classes on hover using CSS

I'm looking for a way to use the :hover effect in CSS to change the font color of one class (.footer_status_tex) and the background color of another class (.footer_status_gear). Here's a simplified version of what I have in mind: CSS .footer_s ...

Utilizing the Twitter API variable within ExpressJS while incorporating AngularJS

Using the "twit" Twitter package from GitHub, I am able to call the Twitter API and retrieve data that is logged in the console. However, I am unsure of how to pass this data to AngularJS in order to display the tweets on the front-end. T.get('search ...

Moving a div with arrow keys using percentages: A step-by-step guide

I found this amazing script on Stack Overflow that allows me to move elements around the page using arrow keys. It works flawlessly, and I love how it enables diagonal movement by combining different arrow key inputs. Now, my query is whether it's fe ...

[Vue alert]: Issue in created function: "TypeError: Unable to assign value to undefined property"

I'm currently in the process of developing a VueJS application where I have implemented a child component called Child.vue that receives data from its parent. Child.vue export default{ props:['info'], data: function(){ ...

Which Browser (or version) is the Only One That Cannot Manipulate Flash Objects?

In my attempts to modify Flash Objects / Embeds using Javascript, I've found that it works in all browsers except for IE. This has led me to consider abandoning IE altogether for this application, unless there are other older or less used browsers tha ...

How can I pass a string value from C++ to JavaScript in a Windows environment using Visual Studio 2008?

In my current project, I have successfully implemented an IDL for passing a string value from JavaScript to C++. The JavaScript code effectively passes a string value to the C++/COM object. [id(1), helpstring("method DoSomething")] HRESULT DoSomething([in ...

Tips for creating a useState variable within the render() function in reactjs

I'm completely new to reactjs, and I've been trying to define useState variables within the render() method of a reactjs component. However, I keep running into an error: "Invalid hook call." class ProductDefinition extends Component { construc ...

tips for sending the chosen product to axios

How can I send the selected item from the dropdown menu to Axios in order to retrieve data? I need to pass the item itself, not just the ID, to the API. <label>City</label> <select @change="getArea()" v-model="key"> <option :valu ...

Loading React Components dynamically depending on user input

Looking to dynamically render different Components based on checkbox selections without unnecessary component imports. Using an Array with Component names (using numbers for example) to import each component based on the array values. Considered the foll ...

Currently, I'm attempting to retrieve a specific ID field from a MongoDB collection

I need to retrieve the _id from the most recently updated row with a matching "EmployeeName". DBCursor cursor = collection.find(EmployeeName).sort(new BasicDBObject("timeSliceStart", -1)).limit(1); while(cursor.hasNext()) { String result = cu ...

Create a single JSON object by searching through two collections in MongoDB

Is it possible for you to assist me in combining data from two collections into one JSON format? Users [ user_id, user_name, city_id ] [ { "name": "Anton", "user_id": 1, "city_id": 1 }, { "name": "Vasiliy", ...

Revamp the HTML table with JavaScript headers

I imported data from a CSV file into an HTML table and here is how it appears: <div id="myTable" style="-ms-overflow-x: auto;"> <table> <tbody> <tr class="rownum-0"> <td>Make</td> ...

Discover the art of highlighting errors with React-hook-form and MUI React

My code consists of the following component: const App = () => { const formProps = useForm({ mode: "onBlur", }); const { handleSubmit, formState, register, watch, reset } = formProps; return ( <FormProvider {...formProps}> & ...

Smooth transition of an arrow moving in a continuous loop using CSS animations

I am attempting to create a seamless loop of a single arrow within a div. My approach involves using two SVG arrows in such a way that when the top part of the first arrow is hidden, the corresponding section of the second arrow should be displayed. This ...

Is ReactJS known for its exceptional performance in rendering large matrices?

Although I have no prior experience with ReactJS, I've heard about a great feature it offers called virtual DOM. It reminds me of the concept of virtual elements in Silverlight where invisible elements are removed from the tree to enhance user-perceiv ...

Tips for accessing the parent method within a jQuery AJAX success function

Similar Question: javascript how to reference parent element Hello everyone! This is my first time posting here. I have a question - how can I trigger alerts from a successful AJAX call? var page = { alerts: function (json) { if (json ...

Using weasyprint to convert a single HTML page into a PDF

I have encountered a challenge while attempting to convert an HTML page with a single table (containing images or text in the td elements) to a PDF using the Python module weasyprint. The issue I am facing is that weasyprint is inserting page breaks withi ...

Using a CSS style to modify a class based on another class at the same level in the hierarchy

I am working with a jQuery carousel that is adding an 'active' class to images within a div. Within the same div, there is also a span with a 'fade' class that has a CSS style of opacity: 0. Is there a way to change the CSS style of the ...