Link Search Menu Expand Document

Generate PDF Invoice From HTML Template - Java

PDF from HTML template (Mustache or HandleBars style) sample in Java demonstrating ‘Generate PDF Invoice From HTML Template’

invoice_data.json
{
    "number": "1234567",
    "date": "April 30, 2016",
    "from": "Acme Inc., City, Street 3rd , +1 888 123-456, support@example.com",
    "to": "Food Delivery Inc., New York, Some Street, 42",
    "lines": [{
        "title": "Setting up new web-site",
        "quantity": 3,
        "price": 50
    }, {
        "title": "Configuring mail server and mailboxes",
        "quantity": 5,
        "price": 50
    }]
}
invoice_template.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">

<head>
	<title>Invoice {{ number}}</title>

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
	<style type="text/css">
		.invoice-title h2,
		.invoice-title h3 {
			display: inline-block;
		}
		
		.table > tbody > tr > .no-line {
			border-top: none;
		}
		
		.table > thead > tr > .thick-line {
			border-bottom: 2px solid;
			border-bottom-color: #888888;
		}
		
		.table > tbody > tr > .thick-line {
			border-top: 2px solid;
			border-top-color: #888888;
		}
	</style>
	<script type="text/javascript">
		Handlebars.registerHelper('getTotal', function(quantity, price) {
			var total = quantity * price;
			return total;
		});
		Handlebars.registerHelper('getTotalLines', function(lines) {
			var total = 0;
			lines.forEach(function(line) {
				total += line.quantity * line.price;
			});
			return total;
		});

		Handlebars.registerHelper("formatDate", function(timestamp) {
			var date = new Date(timestamp);
			return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes();
		});
	</script>
</head>

<body>
	<div class="container">
		<div class="row">
			<div class="col-xs-12">
				<div class="invoice-title">
					<h2>Invoice #{{ number }}</h2>
				</div>
				<hr>

				<div class="row">
					<div class="col-xs-12">
						<address>
	    					<strong>Date:</strong> {{ formatDate date }}
	    				</address>
					</div>
				</div>

				<div class="row">
					<div class="col-xs-12">
						<address>
	        				<strong>From:</strong> {{ from }}
	    				</address>
					</div>
					<div class="col-xs-12">
						<address>
	        				<strong>To:</strong> {{ to }}
	    				</address>
					</div>
				</div>
			</div>
		</div>

		<div class="row">
			<div class="col-md-12">
				<div class="panel panel-default">
					<table class="table table-condensed">
						<thead>
							<tr class="active">
								<td class="thick-line"><strong>Service</strong></td>
								<td class="thick-line"><strong>Quantity</strong></td>
								<td class="text-center thick-line"><strong>Price</strong></td>
								<td class="text-right thick-line"><strong>Sub-Total</strong></td>
							</tr>
						</thead>
						<tbody>
							
							<!-- foreach ($order->lineItems as $line) or some such thing here -->
							{{#each lines}}
							<tr>
								<td>{{title}}</td>
								<td>{{quantity}}</td>
								<td class="text-center">${{price}}</td>
								<td class="text-right">{{ getTotal quantity price }}</td>
							</tr>
							{{/each}}

							<tr>
								<td class="thick-line"></td>
								<td colspan='3' class="thick-line text-right"><strong>Total Due: ${{ getTotalLines lines}}</strong></td>
							</tr>

						</tbody>
					</table>
				</div>

				<div class='text-left'>
					<strong>Terms:</strong> Due on receipt.
				</div>

				<p/>

				<div class='text-left'>
					Thank you for your business!
				</div>

			</div>
		</div>
	</div>
</body>

</html>

Main.java
package com.company;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import okhttp3.*;

import java.io.*;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main
{
    // The authentication key (API Key).
    // Get your own by registering at https://app.pdf.co
    final static String API_KEY = "***********************************";


    public static void main(String[] args) throws IOException
    {
        // HTML template
        final String template = new String(Files.readAllBytes(Paths.get(".\\invoice_template.html")));
        // Data to fill the template
        final String templateData = new String(Files.readAllBytes(Paths.get(".\\invoice_data.json")));
        // Destination PDF file name
        final Path destinationFile = Paths.get(".\\result.pdf");

        // Create HTTP client instance
        OkHttpClient webClient = new OkHttpClient();

        // Prepare URL for `HTML to PDF` API call
        String query = String.format(
                "https://api.pdf.co/v1/pdf/convert/from/html?name=%s",
                destinationFile.getFileName());

        // Make correctly escaped (encoded) URL
        URL url = null;
        try
        {
            url = new URI(null, query, null).toURL();
        }
        catch (URISyntaxException e)
        {
            e.printStackTrace();
        }

        // Prepare request body in JSON format
        JsonObject jsonBody = new JsonObject();
        jsonBody.add("html", new JsonPrimitive(template));
        jsonBody.add("templateData", new JsonPrimitive(templateData));

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonBody.toString());

        // Prepare request
        Request request = new Request.Builder()
                .url(url)
                .addHeader("x-api-key", API_KEY) // (!) Set API Key
                .addHeader("Content-Type", "application/json")
                .post(body)
                .build();
        // Execute request
        Response response = webClient.newCall(request).execute();

        if (response.code() == 200)
        {
            // Parse JSON response
            JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject();

            boolean error = json.get("error").getAsBoolean();
            if (!error)
            {
                // Get URL of generated PDF file
                String resultFileUrl = json.get("url").getAsString();

                // Download PDF file
                downloadFile(webClient, resultFileUrl, destinationFile.toFile());

                System.out.printf("Generated PDF file saved as \"%s\" file.", destinationFile.toString());
            }
            else
            {
                // Display service reported error
                System.out.println(json.get("message").getAsString());
            }
        }
        else
        {
            // Display request error
            System.out.println(response.code() + " " + response.message());
        }
    }

    public static void downloadFile(OkHttpClient webClient, String url, File destinationFile) throws IOException
    {
        // Prepare request
        Request request = new Request.Builder()
                .url(url)
                .build();
        // Execute request
        Response response = webClient.newCall(request).execute();

        byte[] fileBytes = response.body().bytes();

        // Save downloaded bytes to file
        OutputStream output = new FileOutputStream(destinationFile);
        output.write(fileBytes);
        output.flush();
        output.close();

        response.close();
    }
}

PDF.co Web API: the Web API with a set of tools for documents manipulation, data conversion, data extraction, splitting and merging of documents. Includes image recognition, built-in OCR, barcode generation and barcode decoders to decode bar codes from scans, pictures and pdf.

Get your PDF.co API key here!

Download Source Code (.zip)

return to the previous page explore PDF from HTML template (Mustache or HandleBars style) endpoint