How to Convert Plain Text to PDF with JavaScript in NodeJS
This NodeJS example uses JavaScript to upload plain text to the pdfRest Convert to PDF API Tool. Structured options preserve existing lines, establish the PDF’s page design, and request tagged output as part of the multipart call.
Why Convert Plain Text to PDF with JavaScript in NodeJS?
Web services often assemble transcripts, notifications, and generated summaries as plain text because it is simple and interoperable. Once that information needs to leave the application, a raw .txt download may feel unfinished and can be difficult to include in a broader document workflow.
Consider a customer-support platform that exports a conversation transcript containing timestamps, agent names, and message boundaries. Its NodeJS backend can preserve those lines while converting the transcript into a PDF for escalation or customer delivery. The result opens consistently and can be retained with screenshots, forms, and other PDF case materials.
For automatically generated status narratives, the application can select reflow mode and allow the text to wrap as paragraphs instead. JavaScript code can therefore support both transcript fidelity and reader-friendly prose without implementing pagination or font layout itself.
JavaScript Code Example for Converting Plain Text to PDF
var axios = require("axios");
var fs = require("fs");
var FormData = require("form-data");
// By default, we use the US-based API service. This is the primary endpoint for global use.
var apiUrl = "https://api.pdfrest.com";
/* For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below.
* For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
*/
//var apiUrl = "https://eu-api.pdfrest.com";
// This sample converts plain text input to a tagged PDF through multipart /pdf.
// It demonstrates structured_text_options and the format-specific conversion options.
var inputPath = "/path/to/sample.txt";
var form = new FormData();
form.append("file", fs.createReadStream(inputPath));
form.append("structured_text_options", JSON.stringify({"title":"Structured Content Sample","language":"en-US","enable_tagging":true,"page_setup":{"size":"Letter","orientation":"portrait","margin":{"top":36,"right":42,"bottom":36,"left":42}},"style":{"font":"Arial","heading_font":"Arial","code_font":"Courier","text_size":11,"text_color_rgb":[34,34,34],"heading_scale":1.35,"table":{"column_width_weights":[2,3,2],"keep_header_with_first_row":true,"repeat_headers_on_overflow":true,"show_borders":true,"border_width":0.75,"border_color_rgb":[180,188,200],"header_fill_color_rgb":[33,64,98],"header_text_color_rgb":[255,255,255],"row_fill_color_rgb":[250,250,252],"alternate_row_fill_color_rgb":[235,240,246],"cell_padding":{"top":6,"right":8,"bottom":6,"left":8}}},"plain_text":{"line_handling":"preserve"}}));
form.append("output", "pdf_from_text");
axios.post(apiUrl + "/pdf", form, { headers: { "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", ...form.getHeaders() }, maxBodyLength: Infinity })
.then((response) => { console.log(JSON.stringify(response.data, null, 2)); })
.catch((error) => { console.error(error.response ? error.response.data : error.message); process.exitCode = 1; });
Source: View the sample on GitHub
Breaking Down the Code
The NodeJS Plain Text walkthrough uses axios, form-data, and Node’s file-system module. Outside the samples project, install its HTTP and multipart dependencies with npm install axios form-data.
var axios = require("axios");
var fs = require("fs");
var FormData = require("form-data");
This NodeJS excerpt keeps the regional endpoint visible for the Plain Text workflow:
// By default, we use the US-based API service. This is the primary endpoint for global use. var apiUrl = "https://api.pdfrest.com"; /* For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below. * For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work */ //var apiUrl = "https://eu-api.pdfrest.com";
JavaScript streams the .txt source into the form while preserving its filename. pdfRest infers Plain Text conversion from that extension, so structured_text_options does not need an input_format property.
// It demonstrates structured_text_options and the format-specific conversion options. var inputPath = "/path/to/sample.txt"; var form = new FormData();
The object passed through JSON.stringify is interpreted by pdfRest as structured_text_options. It sets PDF metadata, explicitly enables tagging, defines Letter portrait geometry and margins, and supplies the font and color choices used when laying out the Plain Text content.
{
"plain_text": {
"line_handling": "preserve"
}
}
preserve keeps every normalized source line and its spacing in a preformatted block. Windows and legacy carriage-return line endings are normalized consistently. The alternative reflow joins consecutive nonblank lines into paragraphs, using blank lines as paragraph boundaries; reflow is the default when the field is omitted. Only those two values are accepted. When horizontal alignment matters, select a monospaced body font because preserve mode retains characters and spacing but does not force a particular font.
The sample also carries style.table because the repository uses one broad structured-text profile. Plain Text does not create a table, so those table colors, borders, widths, and padding have no effect and may be omitted from a text-only integration.
NodeJS uses FormData to append the Plain Text file, stringified structured_text_options, and output name. The generated form headers provide the multipart boundary for those fields.
var inputPath = "/path/to/sample.txt";
var form = new FormData();
form.append("file", fs.createReadStream(inputPath));
form.append("structured_text_options", JSON.stringify({"title":"Structured Content Sample","language":"en-US","enable_tagging":true,"page_setup":{"size":"Letter","orientation":"portrait","margin":{"top":36,"right":42,"bottom":36,"left":42}},"style":{"font":"Arial","heading_font":"Arial","code_font":"Courier","text_size":11,"text_color_rgb":[34,34,34],"heading_scale":1.35,"table":{"column_width_weights":[2,3,2],"keep_header_with_first_row":true,"repeat_headers_on_overflow":true,"show_borders":true,"border_width":0.75,"border_color_rgb":[180,188,200],"header_fill_color_rgb":[33,64,98],"header_text_color_rgb":[255,255,255],"row_fill_color_rgb":[250,250,252],"alternate_row_fill_color_rgb":[235,240,246],"cell_padding":{"top":6,"right":8,"bottom":6,"left":8}}},"plain_text":{"line_handling":"preserve"}}));
form.append("output", "pdf_from_text");
axios.post(apiUrl + "/pdf", form, { headers: { "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", ...form.getHeaders() }, maxBodyLength: Infinity })
.then((response) => { console.log(JSON.stringify(response.data, null, 2)); })
.catch((error) => { console.error(error.response ? error.response.data : error.message); process.exitCode = 1; });
Axios sends the Plain Text request to /pdf with the form headers and Api-Key. Its success path prints resource JSON, while the rejection path exposes either the API response or the client-side error.
form.append("file", fs.createReadStream(inputPath));
form.append("structured_text_options", JSON.stringify({"title":"Structured Content Sample","language":"en-US","enable_tagging":true,"page_setup":{"size":"Letter","orientation":"portrait","margin":{"top":36,"right":42,"bottom":36,"left":42}},"style":{"font":"Arial","heading_font":"Arial","code_font":"Courier","text_size":11,"text_color_rgb":[34,34,34],"heading_scale":1.35,"table":{"column_width_weights":[2,3,2],"keep_header_with_first_row":true,"repeat_headers_on_overflow":true,"show_borders":true,"border_width":0.75,"border_color_rgb":[180,188,200],"header_fill_color_rgb":[33,64,98],"header_text_color_rgb":[255,255,255],"row_fill_color_rgb":[250,250,252],"alternate_row_fill_color_rgb":[235,240,246],"cell_padding":{"top":6,"right":8,"bottom":6,"left":8}}},"plain_text":{"line_handling":"preserve"}}));
form.append("output", "pdf_from_text");
axios.post(apiUrl + "/pdf", form, { headers: { "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", ...form.getHeaders() }, maxBodyLength: Infinity })
.then((response) => { console.log(JSON.stringify(response.data, null, 2)); })
.catch((error) => { console.error(error.response ? error.response.data : error.message); process.exitCode = 1; });
Beyond the Tutorial
NodeJS applications can turn support transcripts, application output, or dynamically assembled text into PDFs without introducing a separate document renderer. Logical tags can assist navigation and later processing, although they are not a PDF/UA or WCAG guarantee.
Remove optional style controls when the service only needs a simple text conversion. API Lab provides an interactive place to try the request, and the Convert to PDF documentation lists every accepted field.