How can one transform personalized HTML into a PDF document?

I attempted to send a customized HTML (+CSS) as a PDF, but the resulting PDF sent is only in black and white. I would appreciate any assistance with this issue. Thank you :)

Below is the function that I used:

  function sendEmails() {

  var data = getBody("DATA");
  var emailData = rowsToObjects(data);

  emailData.forEach(function (rowObject) {

    //var emailSubj = 'Konfirmasi Tagihan TUNEECA tanggal '+rowObject['TANGGAL AWAL']+' - '+rowObject['TANGGAL AKHIR']

  const pdfhtml = HtmlService.createHtmlOutputFromFile('body-pdf').getContent();
  const data = renderHtml(rowObject);
  const htmlContent = pdfhtml.replace('hereismytabledata',data).replace('$CUSTNAME',rowObject['NAMA PARTNER']);

  const blob = Utilities.newBlob(htmlContent, MimeType.HTML);
  blob.setName('Rincian Tagihan.pdf');

    var emailSubjectTemplate = 'Konfirmasi Tagihan tanggal {{TANGGAL AWAL}} - {{TANGGAL AKHIR}} '; 
    var emailBodyTemplate = HtmlService.createHtmlOutputFromFile('body-email').getContent();

    var emailSubject = renderTemplate(emailSubjectTemplate, rowObject);
    var body = renderTemplate(emailBodyTemplate, rowObject);

    const recipientEmail = rowObject['EMAIL'];

    console.log(emailSubject,body,recipientEmail)

  MailApp.sendEmail({
    to: recipientEmail,
    subject: emailSubject,
    htmlBody: body,
    attachments: [blob.getAs(MimeType.PDF)],
  });


  });
}

Here is my HTML : https://i.sstatic.net/bPGry.png

and here is the result PDF sent by email: https://i.sstatic.net/Ldw9I.png

Note: I apologize for submitting HTML as a picture due to an error while trying to edit and add some codes.

Answer №1

To convert an HTML web page to a PDF on your Windows PC, simply launch Internet Explorer, Google Chrome, or Firefox. Next, locate and press the "Convert to PDF" option within the Adobe PDF toolbar to initiate the conversion process. Lastly, provide a name for your PDF file and select where you want to save it on your computer.

Answer №2

To customize your printing style in HTML, simply include the following line within your style tag:

@media print {body {-webkit-print-color-adjust: exact;}}

Below are the files I utilized to verify this customization for your convenience:

Code.gs

function convertHTMLtoPDF() {
  var pdfhtml = HtmlService.createHtmlOutputFromFile('body-pdf').getContent();

  var htmlBlob = Utilities.newBlob(pdfhtml, MimeType.HTML);
  htmlBlob.setName('Test.pdf');

  var pdfBlob = htmlBlob.getAs(MimeType.PDF);

  DriveApp.createFile(pdfBlob); //saves the PDF to the root of your My Drive to inspect it
}

body-pdf.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        @media print {body {-webkit-print-color-adjust: exact;}}
        
        #customers {
            font-family: Arial, Helvetica, sans-serif;
            border-collapse: collapse;
            width: 100%;
        }
        #customers td, #customers th {
            border: 1px solid #ddd;
            padding: 8px;
        }

        #customers tr:nth-child(even) {
            background-color: #f2f2f2;
        }
        #customers tr:hover {
            background-color: #ddd;
        }
        #customers th {
            padding-top: 12px;
            padding-bottom: 12px;
            text-align: left;
            background-color: #04AA6D;
            color: white;
        }
    </style>
</head>
<body>
    <h1>Fancy Table</h1>

    <table id="customers">
        <tr>
            <th>Company</th>
            <th>Contact</th>
            <th>Country</th>
        </tr>
        <tr>
            <td>Company1</td>
            <td>Contact1</td>
            <td>Country1</td>
        </tr>
        <tr>
            <td>Company2</td>
            <td>Contact2</td>
            <td>Country2</td>
        </tr>
        <tr>
            <td>Company3</td>
            <td>Contact3</td>
            <td>Country3</td>
        </tr>
    </table>
</body>
</html>

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

Is there a way to extract the HTMLElement[] type from the DOM?

In my TypeScript project, I am trying to gather all the top-level elements of a page using the code snippet below: const getHTMLElement() : HTMLElement[] { const doc = document.body.children; const list : HTMLElement[] = []; for (let c of Array.f ...

Add a new function for inserting a div element into the submenu of a Genesis framework

I am trying to figure out how to insert a new div element with a specific class within a submenu in the genesis framework using either a genesis hook or a PHP function. For reference, here is an example of what I am working with: Original Code: <div ...

Creating a function that generates a random number of <div> elements and places them inside a <li> element is a great way to dynamically add

Hey there! I could really use your assistance with this. I am trying to dynamically generate a list of items, but instead of placing each item in a separate <li>, I would like to achieve the following structure: <ul> <li> <di ...

Unable to implement styling to an HTML element using Javascript

Having very limited experience with Javascript, I decided to incorporate a feature on my webpage where the navbar changes size as the user scrolls down. The only way to achieve this was through the use of Javascript. Including the .js file in my HTML docu ...

What distinguishes between using ul#test and #test ul in CSS?

Could someone help clarify the distinction between these two types of CSS declarations: ul#test { } #test ul { } Despite my searching, I am unable to pinpoint the difference, but they exhibit different behaviors when implemented on a test page. To me, i ...

When I click on something else, the dropdown doesn't automatically close

In my current setup, I have 3 dropdowns on the page. When I click outside of any dropdown, they are correctly closed. However, if one dropdown is already open and I click on another one, the previously opened dropdown remains open. I want all dropdowns to ...

Display a custom toast from a list using Bootstrap 5

I've been utilizing the toast feature from Bootstrap, and it works perfectly when displaying a single toast. However, I encountered an issue when trying to display a specific toast, like an error toast, from a list of predefined toasts. It ended up sh ...

The Facebook like button disappears after being used just once

I've encountered an odd issue that hopefully someone can help me understand. WEBSITE: ISSUE: Initially, the like button functions properly. However, upon refreshing the page or navigating away and returning to the homepage, the like button mysterio ...

What is the best way to transform my product category columns into 4 separate categories?

I am trying to modify the product category view to display 4 columns instead of 3. Currently, on www.tattiniboots.com, you can see that the Accessory box section is the only item in the second row. I would like all items to be displayed in one row with 4 ...

What is the best way to modify the CSS of a child element within the context of "$(this)"

On my search results page, each result has an icon to add it to a group. The groups are listed in a hidden UL element on the page with display:none. The issue I'm facing is that when I click on the icon for one result, the UL appears under every sing ...

Tips for customizing the appearance of buttons in a JavaScript bxSlider

Take a look at my landing page: In the upper section, you'll find three buttons that allow you to switch between different slides. These buttons are named: credi5, credi10, and credi15. Now, I want to replace those buttons with images... specificall ...

PHP Email Verification Script

Essentially, I need to set up email validation with specific criteria. For example, let's say my college has a student with the ID [email protected]. I want the validation process to require the student to input 'x' at the beginning of ...

Subdirectory picture styling

Let's take a look at how everything is structured: https://i.sstatic.net/gvyFH.png I am attempting to retrieve an image from a subfolder using a CSS file Although I have attempted several methods, none of them seem to work as expected background-i ...

Retrieve Chrome Tab Title from JSON

My Chrome extension loads a local .html file. (within the manifest.json configuration file) "default_popup": "popup.html", Within this HTML file, a frame is created to display content from www.website.com, allowing users to view it in a small popup gene ...

Deactivate the rest of the buttons by utilizing the e.target.id

I have ten expansion panels. When I click a button in one expansion panel, I want to disable other buttons in the remaining expansion panels. The issue is that when I try to target an id, it does not return e.target.id but instead returns as the value pass ...

Using AJAX to insert HTML into a dynamically generated div within the same script

After spending countless hours trying to troubleshoot my code with no success, I am reaching out for help. I have a JavaScript function that dynamically creates a new 'Window' along with all the corresponding DIV elements. Within this function, t ...

What is the best way to ensure that <input> and <textarea> placed within a <div> are aligned to the top of the container?

Here is the setup I currently have: <div> <input> <input> <textarea> </div> I am looking to align the tops of the inputs and the textarea within the div. However, it seems like the inputs are at the bottom and the t ...

Retrieve the highchart data from a PHP database table

Is there a way to display every row of data from my table in highcharts using PHP to JavaScript for each row? <script> series: [{ name: 'Instant Noodles', data: [<?php foreach ($query as $row){echo $row['noo ...

Trigger the proxy server to retrieve a fresh version of the webpage using HTML

Although I am aware that this question has been asked before, I have attempted the following: <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE"> <META HTTP-EQUIV="EXPIRES" CONTENT="-1"> <meta http-equiv="pragma" content="no-cache" /> ...

Issue with fixed positioning of a div within a scrollable container

I attempted to replicate the issue, but unfortunately I was unsuccessful. If you'd like to view my efforts, you can check out this FIDDLE. By the way, I have a full-page menu that can be scrolled vertically. Inside the menu, I have placed some imag ...