How to Generate PDF from Email in JavaScript
The example converts an EML file with attachment inclusion and conversion enabled. Supported attachments become PDF pages; unsupported files remain embedded attachments. These settings do not preserve every attachment in its original format. Inspect both the output pages and the PDF’s attachment list. The example runs synchronously with async set to false.
Features of Generating PDF From Email Endpoint
Users can utilize the "PDF from Email" endpoint of PDF.co Web API to generate a PDF from an email file. This endpoint requires a URL link and accepts other optional parameters to produce a link to a PDF file, which includes the email attachments in various formats according to user preferences. Additionally, users have the option to download and store the generated PDF file on their local storage using different file management modules, such as "fs".
Endpoint Parameters
Following are the parameters of the PDF From Email endpoint:
url: Required parameter. A string that specifies the link to the source email file, which can have an "EML or MSG" extension. Users can also provide links to files hosted on online storage platforms like Google Drive, Dropbox, and PDF.co's own cloud storage. Additionally, there is the option to temporarily upload files before invoking this API endpoint. For more information on uploading and managing files, users are encouraged to consult the "File Upload" section of the PDF.co API Documentation.embedAttachments: A boolean. Set totrueto include email attachments, orfalseto convert only the email body.convertAttachments: When attachments are included,trueconverts supported formats to PDF pages and merges them into the output. Set tofalseto retain the original files as embedded attachments. Unsupported formats remain embedded files, which require a PDF reader with attachment support. Check the current supported attachment formats when configuring the request.async: Optional parameter. Allows users to set the task to run asynchronously by setting it to "true". It is recommended for processing large or heavy documents, as it enables the task to be executed in the background, allowing the user to continue with other tasks without waiting for the immediate completion of the document processing.margins: Set top, right, bottom and left margins separated by spaces, for example"2px 2px 2px 2px". A single value applies to all sides.paperSize: Specify a size such as"A4"or"Letter". For custom dimensions, separate width and height with a space, for example"100px 200px".orientation: Optional parameter. Allows users to specify the orientation of the pages in the output PDF file. They have the choice between "Portrait" and "Landscape" orientations. By default, the orientation is set to "Portrait."profiles: Optional parameter. Must be a string. Enables users to apply additional configurations and tuning options to further customize their PDF generation process. Read more about profiles and find examples in the API Documentation.expiration: Optional parameter. Determines the expiration time of the output file's link, expressed in minutes. By default, the link expires after 60 minutes, but users can adjust this duration according to their subscription plan. After the set period, the files are automatically deleted from the cloud. For those needing permanent storage, users can opt to save the files using PDF.co's built-in file storage feature, ensuring their documents remain accessible beyond the default expiration timeframe.
Query Parameter
Query parameters are the parameters of the API endpoint URLs that users need to append to customize their requests. For this particular endpoint, no query parameters are needed, meaning users can proceed without appending additional information to the endpoint URL.
Endpoint URL
Below is the endpoint URL to generate a PDF from an Email file:
URL: /v1/pdf/convert/from/emailGenerate PDF from Email using Javascript
The example converts an EML file with embedAttachments and convertAttachments set to true. Supported attachments become PDF pages and are merged into the output. Unsupported types remain embedded attachments. Set convertAttachments to false to keep attachments in their original format. This example runs synchronously because async is false. Inspect both the PDF pages and attachment list.
Upon execution, users can view details such as the size and URL of the output PDF file in the terminal. This URL allows them to access the resulting PDF file. Alternatively, users can employ file management modules like "fs" to download the content of the file and save it to their local storage, providing a convenient way to retain a copy of the converted file.
Sample Code in JavaScript
Below is the sample code to generate a PDF from an email file:
var request = require('request');
var API_KEY = "********************";
var fileUrl = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/email-to-pdf/sample.eml";
var options = {
'method': 'POST',
'url': 'https://api.pdf.co/v1/pdf/convert/from/email',
'headers': {
'x-api-key': API_KEY
},
formData: {
"url": fileUrl,
"embedAttachments": "true",
"convertAttachments": "true",
"name": "email-with-attachments",
"async": "false",
"encrypt": "false",
"expiration" : "12"
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});Step-by-Step Guide to Generate PDF from Email
To generate a PDF from email files using this guide, follow these steps:
- Install the Request Module: Use the command
npm install requestin your terminal to install the "request" module, which facilitates making HTTP calls in Node.js. - Configure
package.json: Ensure yourpackage.jsonfile is set up to run and test your JavaScript file. This may involve specifying the entry point of your application and any test scripts. - API Key Initialization:
- Declare and initialize the
API_KEYvariable with the API key obtained by signing up or logging into your PDF.co dashboard. This key will be used to authenticate your API requests. - For added security, consider storing your API key in an environment file (
.env). This approach keeps sensitive information out of your codebase.
- Declare and initialize the
- Source File URL: Initialize a variable named
fileUrlwith the URL of your source email file (EML or MSG format). This setup allows you to convert different email files by simply updating this variable without modifying the underlying code or API logic. - Setting API Options: Declare a variable called
optionsand assign it the configuration for your API request. This includes the HTTP method, API endpoint URL, headers (which should contain your API key), and the form data.- The form data is an object where you specify the values for the various API parameters, such as
async, which is set tofalsein this example. You can adjust these parameters based on your specific conversion requirements.
- The form data is an object where you specify the values for the various API parameters, such as
- Making the API Call: Use the
requestmethod you imported to make the API call with the options you've set. Handle the response by printing it to the terminal or processing it further, such as by streaming the resulting PDF file content for download.
Source File
Below is the screenshot of the source file:

Output File
Below are the screenshots of the output file obtained in the API response:



Related Tutorials

