Wednesday, March 7, 2018

HTML To PDF Generation in Java

HTML To PDF Generation in Java:- Below code snippet will help in generating the Pdf file from HTML Code. It will convert the HTML to PDF and save the file on your system. This code can be used according your requirement.

Maven Dependency:-
   <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.4.1</version>
    </dependency>

    <dependency>
        <groupId>com.itextpdf.tool</groupId>
        <artifactId>xmlworker</artifactId>
        <version>5.4.1</version>
    </dependency>

Java Class:-

package com.mettl.certification.systemAdmin.web.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

public class HTMLToPdfUtil {
   
    /**
     * This method accepts the
     * @param html code that will be written to PDF.
     */
    public static void createPDF(String html) {
        try {
            //Path to file system, where file will be saved.
            OutputStream file = new FileOutputStream(new File("/home/HTMLtoPDF.pdf"));
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, file);
            document.open();
            StringBuffer str = new StringBuffer();
            str.append("<html><head><title>PDF</title></head><body>");
            str.append(html).append("</body></html>");
            InputStream is = new ByteArrayInputStream(str.toString().getBytes());
           
            XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
            document.close();
            file.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
   
    public static void main(String args[]) {
        HTMLToPdfUtil.createPDF("Test Content");
    }
}

No comments:

Post a Comment