Creating PDF files from HTML using JavaScript in Docly
In today's digital age, the ability to generate PDF files programmatically has become increasingly important. JavaScript, a popular programming language known for its versatility and flexibility, can be utilized to create dynamic and interactive content on the web. When combined with powerful platforms like Docly, developers can efficiently generate PDF files with ease.
Generating a PDF with Docly
Let's look at how we can generate a simple PDF using Docly.
Step 1: Create a JS file in your API folder
The functions we will use here are only available from JS files placed in your API folder. Where JS files creating dynamic content must be placed.
The API folder must be place in your template / template folder (The # folder).
Read more about this here: https://developers.docly.net/Blog/2015/The-hash-folder
How to do this:
- Create a new folder and open it
- Publish this folder on one of your domains
- Create a sub folder called # and open it
- Create a sub folder called "API" and open it
- Create a "Code file" called "test.js"
This test.js endpoint will be available on your published url: https://yourdomain/foldername/API/test
Step 2: Define HTML code that we want in our PDF document
In the context of generating a PDF file, this HTML code can be used as the source content that will be converted into a PDF format. It's a common practice to store HTML content in a string variable like this when you're using tools or libraries that convert HTML into other formats.
let htmlcode =
`<html>
<head>
<title>Test PDF</title>
</head>
<body>
<h1>Hello World!</h1>
<p>This is a test PDF document.</p>
</body>
</html>`;
To generate a PDF file in landscape orientation, we can designate this particular configuration within the CSS as follows:
@page {
size: landscape;
}
Step 3: Define the name of the PDF we want to create
While it's not obligatory to assign the filename to a variable, doing so promotes cleaner and more procedural code, enhancing readability and maintainability.
let filename = 'test.pdf';
Step 4: Use the htmlToPdf() function in Docly to create the PDF document
The function accepts the two variables we've previously defined as its parameters and returns a PDF file represented in bytes. Optionally, a third parameter can be introduced to utilize print media while generating the PDF.
return docly.htmlToPdf(filename, htmlcode);
Conclusion
Generating PDF files in JavaScript does not have to be a complicated task. With tools like Docly, we can quickly and easily create dynamic PDF documents for our applications. Just remember that the content being generated should be valid HTML, as this is what Docly will use to generate the PDF document.
Happy coding! 😎